duckstation

duckstation, but archived from the revision just before upstream changed it to a proprietary software project, this version is the libre one
git clone https://git.neptards.moe/u3shit/duckstation.git
Log | Files | Refs | README | LICENSE

pad.cpp (27126B)


      1 // SPDX-FileCopyrightText: 2019-2024 Connor McLaughlin <stenzek@gmail.com> and contributors.
      2 // SPDX-License-Identifier: (GPL-3.0 OR CC-BY-NC-ND-4.0)
      3 
      4 #include "pad.h"
      5 #include "controller.h"
      6 #include "host.h"
      7 #include "interrupt_controller.h"
      8 #include "memory_card.h"
      9 #include "multitap.h"
     10 #include "save_state_version.h"
     11 #include "system.h"
     12 #include "types.h"
     13 
     14 #include "util/imgui_manager.h"
     15 #include "util/state_wrapper.h"
     16 
     17 #include "common/bitfield.h"
     18 #include "common/bitutils.h"
     19 #include "common/fifo_queue.h"
     20 #include "common/log.h"
     21 
     22 #include "IconsFontAwesome5.h"
     23 
     24 #include <array>
     25 #include <memory>
     26 
     27 Log_SetChannel(Pad);
     28 
     29 namespace Pad {
     30 
     31 enum class State : u32
     32 {
     33   Idle,
     34   Transmitting,
     35   WaitingForACK
     36 };
     37 
     38 enum class ActiveDevice : u8
     39 {
     40   None,
     41   Controller,
     42   MemoryCard,
     43   Multitap
     44 };
     45 
     46 union JOY_CTRL
     47 {
     48   u16 bits;
     49 
     50   BitField<u16, bool, 0, 1> TXEN;
     51   BitField<u16, bool, 1, 1> SELECT;
     52   BitField<u16, bool, 2, 1> RXEN;
     53   BitField<u16, bool, 4, 1> ACK;
     54   BitField<u16, bool, 6, 1> RESET;
     55   BitField<u16, u8, 8, 2> RXIMODE;
     56   BitField<u16, bool, 10, 1> TXINTEN;
     57   BitField<u16, bool, 11, 1> RXINTEN;
     58   BitField<u16, bool, 12, 1> ACKINTEN;
     59   BitField<u16, u8, 13, 1> SLOT;
     60 };
     61 
     62 union JOY_STAT
     63 {
     64   u32 bits;
     65 
     66   BitField<u32, bool, 0, 1> TXRDY;
     67   BitField<u32, bool, 1, 1> RXFIFONEMPTY;
     68   BitField<u32, bool, 2, 1> TXDONE;
     69   BitField<u32, bool, 7, 1> ACKINPUT;
     70   BitField<u32, bool, 9, 1> INTR;
     71   BitField<u32, u32, 11, 21> TMR;
     72 };
     73 
     74 union JOY_MODE
     75 {
     76   u16 bits;
     77 
     78   BitField<u16, u8, 0, 2> reload_factor;
     79   BitField<u16, u8, 2, 2> character_length;
     80   BitField<u16, bool, 4, 1> parity_enable;
     81   BitField<u16, u8, 5, 1> parity_type;
     82   BitField<u16, u8, 8, 1> clk_polarity;
     83 };
     84 
     85 static bool CanTransfer();
     86 static bool ShouldAvoidSavingToState();
     87 static u32 GetMaximumRollbackFrames();
     88 
     89 static TickCount GetTransferTicks();
     90 
     91 // From @JaCzekanski
     92 // ACK lasts ~96 ticks or approximately 2.84us at master clock (not implemented).
     93 // ACK delay is between 6.8us-13.7us, or ~338 ticks at master clock for approximately 9.98us.
     94 // Memory card responds faster, approximately 5us or ~170 ticks.
     95 static constexpr TickCount GetACKTicks(bool memory_card)
     96 {
     97   return memory_card ? 170 : 450;
     98 }
     99 
    100 static void SoftReset();
    101 static void UpdateJoyStat();
    102 static void TransferEvent(void*, TickCount ticks, TickCount ticks_late);
    103 static void BeginTransfer();
    104 static void DoTransfer(TickCount ticks_late);
    105 static void DoACK();
    106 static void EndTransfer();
    107 static void ResetDeviceTransferState();
    108 
    109 static bool DoStateController(StateWrapper& sw, u32 i);
    110 static bool DoStateMemcard(StateWrapper& sw, u32 i, bool is_memory_state);
    111 static MemoryCard* GetDummyMemcard();
    112 static void BackupMemoryCardState();
    113 static void RestoreMemoryCardState();
    114 
    115 static std::array<std::unique_ptr<Controller>, NUM_CONTROLLER_AND_CARD_PORTS> s_controllers;
    116 static std::array<std::unique_ptr<MemoryCard>, NUM_CONTROLLER_AND_CARD_PORTS> s_memory_cards;
    117 
    118 static std::array<Multitap, NUM_MULTITAPS> s_multitaps;
    119 
    120 static TimingEvent s_transfer_event{"Pad Serial Transfer", 1, 1, &Pad::TransferEvent, nullptr};
    121 static State s_state = State::Idle;
    122 
    123 static JOY_CTRL s_JOY_CTRL = {};
    124 static JOY_STAT s_JOY_STAT = {};
    125 static JOY_MODE s_JOY_MODE = {};
    126 static u16 s_JOY_BAUD = 0;
    127 
    128 static ActiveDevice s_active_device = ActiveDevice::None;
    129 static u8 s_receive_buffer = 0;
    130 static u8 s_transmit_buffer = 0;
    131 static u8 s_transmit_value = 0;
    132 static bool s_receive_buffer_full = false;
    133 static bool s_transmit_buffer_full = false;
    134 
    135 static u32 s_last_memory_card_transfer_frame = 0;
    136 static DynamicHeapArray<u8> s_memory_card_backup;
    137 static std::unique_ptr<MemoryCard> s_dummy_card;
    138 
    139 } // namespace Pad
    140 
    141 void Pad::Initialize()
    142 {
    143   Reset();
    144 }
    145 
    146 void Pad::Shutdown()
    147 {
    148   s_memory_card_backup.deallocate();
    149 
    150   s_transfer_event.Deactivate();
    151 
    152   for (u32 i = 0; i < NUM_CONTROLLER_AND_CARD_PORTS; i++)
    153   {
    154     s_controllers[i].reset();
    155     s_memory_cards[i].reset();
    156   }
    157 }
    158 
    159 void Pad::Reset()
    160 {
    161   SoftReset();
    162 
    163   for (u32 i = 0; i < NUM_CONTROLLER_AND_CARD_PORTS; i++)
    164   {
    165     if (s_controllers[i])
    166       s_controllers[i]->Reset();
    167 
    168     if (s_memory_cards[i])
    169       s_memory_cards[i]->Reset();
    170   }
    171 
    172   for (u32 i = 0; i < NUM_MULTITAPS; i++)
    173     s_multitaps[i].Reset();
    174 }
    175 
    176 bool Pad::ShouldAvoidSavingToState()
    177 {
    178   // Currently only runahead, will also be used for netplay.
    179   return g_settings.IsRunaheadEnabled();
    180 }
    181 
    182 u32 Pad::GetMaximumRollbackFrames()
    183 {
    184   return g_settings.runahead_frames;
    185 }
    186 
    187 bool Pad::DoStateController(StateWrapper& sw, u32 i)
    188 {
    189   const ControllerType controller_type = s_controllers[i] ? s_controllers[i]->GetType() : ControllerType::None;
    190   ControllerType state_controller_type = controller_type;
    191 
    192   // Data type change...
    193   u32 state_controller_type_value = static_cast<u32>(state_controller_type);
    194   sw.Do(&state_controller_type_value);
    195   state_controller_type = static_cast<ControllerType>(state_controller_type_value);
    196 
    197   if (controller_type != state_controller_type)
    198   {
    199     const Controller::ControllerInfo* state_cinfo = Controller::GetControllerInfo(state_controller_type);
    200     Assert(sw.IsReading());
    201 
    202     // UI notification portion is separated from emulation portion (intentional condition check redundancy)
    203     if (g_settings.load_devices_from_save_states)
    204     {
    205       Host::AddOSDMessage(
    206         fmt::format(TRANSLATE_FS("OSDMessage",
    207                                  "Save state contains controller type {0} in port {1}, but {2} is used. Switching."),
    208                     state_cinfo ? state_cinfo->GetDisplayName() : "", i + 1u,
    209                     Controller::GetControllerInfo(controller_type)->GetDisplayName()),
    210         Host::OSD_WARNING_DURATION);
    211     }
    212     else
    213     {
    214       Host::AddOSDMessage(
    215         fmt::format(TRANSLATE_FS("OSDMessage", "Ignoring mismatched controller type {0} in port {1}."),
    216                     state_cinfo ? state_cinfo->GetDisplayName() : "", i + 1u, Host::OSD_WARNING_DURATION));
    217     }
    218 
    219     DEV_LOG("Controller type mismatch in slot {}: state={}({}) ui={}({}) load_from_state={}", i + 1u,
    220             state_cinfo ? state_cinfo->name : "", static_cast<unsigned>(state_controller_type),
    221             Controller::GetControllerInfo(controller_type)->name, static_cast<unsigned>(controller_type),
    222             g_settings.load_devices_from_save_states ? "yes" : "no");
    223 
    224     if (g_settings.load_devices_from_save_states)
    225     {
    226       s_controllers[i].reset();
    227       if (state_controller_type != ControllerType::None)
    228         s_controllers[i] = Controller::Create(state_controller_type, i);
    229     }
    230     else
    231     {
    232       // mismatched controller states prevents us from loading the state into the user's preferred controller.
    233       // just doing a reset here is a little dodgy. If there's an active xfer on the state-saved controller
    234       // then who knows what might happen as the rest of the packet streams in. (possibly the SIO xfer will
    235       // timeout and the controller will just correct itself on the next frame's read attempt -- after all on
    236       // physical HW removing a controller is allowed and could happen in the middle of SIO comms)
    237 
    238       if (s_controllers[i])
    239         s_controllers[i]->Reset();
    240     }
    241   }
    242 
    243   // we still need to read/write the save state controller state even if the controller does not exist.
    244   // the marker is only expected for valid controller types.
    245   if (state_controller_type == ControllerType::None)
    246     return true;
    247 
    248   if (!sw.DoMarker("Controller"))
    249     return false;
    250 
    251   if (auto& controller = s_controllers[i]; controller && controller->GetType() == state_controller_type)
    252     return controller->DoState(sw, g_settings.load_devices_from_save_states);
    253   else if (auto dummy = Controller::Create(state_controller_type, i); dummy)
    254     return dummy->DoState(sw, g_settings.load_devices_from_save_states);
    255 
    256   return true;
    257 }
    258 
    259 bool Pad::DoStateMemcard(StateWrapper& sw, u32 i, bool is_memory_state)
    260 {
    261   bool card_present_in_state = static_cast<bool>(s_memory_cards[i]);
    262 
    263   sw.Do(&card_present_in_state);
    264 
    265   if (card_present_in_state && !s_memory_cards[i] && g_settings.load_devices_from_save_states)
    266   {
    267     Host::AddIconOSDMessage(
    268       fmt::format("card_load_warning_{}", i), ICON_FA_SD_CARD,
    269       fmt::format(
    270         TRANSLATE_FS("OSDMessage", "Memory card {} present in save state but not in system. Creating temporary card."),
    271         i + 1u),
    272       Host::OSD_ERROR_DURATION);
    273     s_memory_cards[i] = MemoryCard::Create();
    274   }
    275 
    276   MemoryCard* card_ptr = s_memory_cards[i].get();
    277   if (card_present_in_state)
    278   {
    279     if (sw.IsReading() && !g_settings.load_devices_from_save_states)
    280     {
    281       // load memcard into a temporary: If the card datas match, take the one from the savestate
    282       // since it has other useful non-data state information. Otherwise take the user's card
    283       // and perform a re-plugging.
    284       card_ptr = GetDummyMemcard();
    285     }
    286 
    287     if (!sw.DoMarker("MemoryCard") || !card_ptr->DoState(sw))
    288       return false;
    289   }
    290 
    291   if (sw.IsWriting())
    292     return true; // all done as far as writes concerned.
    293 
    294   if (card_ptr != s_memory_cards[i].get())
    295   {
    296     if (s_memory_cards[i])
    297     {
    298       if (s_memory_cards[i]->GetData() == card_ptr->GetData())
    299       {
    300         DEV_LOG("Card {} data matches, copying state", i + 1u);
    301         s_memory_cards[i]->CopyState(card_ptr);
    302       }
    303       else
    304       {
    305         Host::AddIconOSDMessage(
    306           fmt::format("card_load_warning_{}", i), ICON_FA_SD_CARD,
    307           fmt::format(
    308             TRANSLATE_FS("OSDMessage",
    309                          "Memory card {} from save state does not match current card data. Simulating replugging."),
    310             i + 1u),
    311           Host::OSD_WARNING_DURATION);
    312 
    313         WARNING_LOG("Memory card {} data mismatch. Using current data via instant-replugging.", i + 1u);
    314         s_memory_cards[i]->Reset();
    315       }
    316     }
    317     else
    318     {
    319       Host::AddIconOSDMessage(
    320         fmt::format("card_load_warning_{}", i), ICON_FA_SD_CARD,
    321         fmt::format(
    322           TRANSLATE_FS("OSDMessage", "Memory card {} present in save state but not in system. Ignoring card."), i + 1u),
    323         Host::OSD_ERROR_DURATION);
    324     }
    325 
    326     return true;
    327   }
    328 
    329   if (!card_present_in_state && s_memory_cards[i])
    330   {
    331     if (g_settings.load_devices_from_save_states)
    332     {
    333       Host::AddIconOSDMessage(
    334         fmt::format("card_load_warning_{}", i), ICON_FA_SD_CARD,
    335         fmt::format(
    336           TRANSLATE_FS("OSDMessage", "Memory card {} present in system but not in save state. Removing card."), i + 1u),
    337         Host::OSD_ERROR_DURATION);
    338       s_memory_cards[i].reset();
    339     }
    340     else
    341     {
    342       Host::AddIconOSDMessage(
    343         fmt::format("card_load_warning_{}", i), ICON_FA_SD_CARD,
    344         fmt::format(
    345           TRANSLATE_FS("OSDMessage", "Memory card {} present in system but not in save state. Replugging card."),
    346           i + 1u),
    347         Host::OSD_WARNING_DURATION);
    348       s_memory_cards[i]->Reset();
    349     }
    350   }
    351 
    352   return true;
    353 }
    354 
    355 MemoryCard* Pad::GetDummyMemcard()
    356 {
    357   if (!s_dummy_card)
    358     s_dummy_card = MemoryCard::Create();
    359   return s_dummy_card.get();
    360 }
    361 
    362 void Pad::BackupMemoryCardState()
    363 {
    364   DEV_LOG("Backing up memory card state.");
    365 
    366   if (s_memory_card_backup.empty())
    367     s_memory_card_backup.resize(MemoryCard::STATE_SIZE * NUM_CONTROLLER_AND_CARD_PORTS);
    368 
    369   StateWrapper sw(s_memory_card_backup.span(), StateWrapper::Mode::Write, SAVE_STATE_VERSION);
    370   for (u32 i = 0; i < NUM_CONTROLLER_AND_CARD_PORTS; i++)
    371   {
    372     if (s_memory_cards[i])
    373       s_memory_cards[i]->DoState(sw);
    374   }
    375 }
    376 
    377 void Pad::RestoreMemoryCardState()
    378 {
    379   DebugAssert(!s_memory_card_backup.empty());
    380 
    381   VERBOSE_LOG("Restoring backed up memory card state.");
    382 
    383   StateWrapper sw(s_memory_card_backup.cspan(), StateWrapper::Mode::Read, SAVE_STATE_VERSION);
    384   for (u32 i = 0; i < NUM_CONTROLLER_AND_CARD_PORTS; i++)
    385   {
    386     if (s_memory_cards[i])
    387       s_memory_cards[i]->DoState(sw);
    388   }
    389 }
    390 
    391 bool Pad::DoState(StateWrapper& sw, bool is_memory_state)
    392 {
    393   if (is_memory_state && ShouldAvoidSavingToState())
    394   {
    395     // We do a bit of trickery for memory states here to avoid writing 128KB * num_cards to the state.
    396     // Profiling shows that the card write scan be up to 17% of overall CPU time, so it's definitely worth skipping.
    397     // However, we can't roll back past a transfer boundary, because that'll corrupt our cards. So, we have to be smart
    398     // about this.
    399     //
    400     // There's three main scenarios:
    401     //  (1) No transfers occurring before or after the rollback point.
    402     //  (2) A transfer was started before the rollback point.
    403     //  (3) A transfer was started after the rollback point.
    404     //
    405     // For (1), it's easy, we don't have to do anything. Just skip saving and continue on our merry way.
    406     //
    407     // For (2), we serialize the state whenever there's a transfer within the last N_ROLLBACK frames. Easy-ish.
    408     //
    409     // For (3), it gets messy. We didn't know that a transfer was going to start, and our rollback state doesn't
    410     // contain the state of the memory cards, because we were cheeky and skipped it. So, instead, we back up
    411     // the state of memory cards when any transfer begins, assuming it's not within the last N_ROLLBACK frames, in
    412     // DoTransfer(). That way, when we do have to roll back past this boundary, we can just restore the known good "pre
    413     // transfer" state. Any memory saves created after the transfer begun will go through the same path as (2), so we
    414     // don't risk corrupting that way.
    415     //
    416     // Hopefully that's everything.
    417     //
    418     bool process_memcard_state = true;
    419 
    420     const u32 frame_number = System::GetFrameNumber();
    421     const u32 frames_since_transfer = frame_number - s_last_memory_card_transfer_frame;
    422     const u32 prev_transfer_frame = s_last_memory_card_transfer_frame;
    423     bool state_has_memcards = false;
    424 
    425     sw.Do(&s_last_memory_card_transfer_frame);
    426 
    427     // If there's been a transfer within the last N_ROLLBACK frames, include the memory card state when saving.
    428     state_has_memcards = (frames_since_transfer <= GetMaximumRollbackFrames());
    429     sw.Do(&state_has_memcards);
    430 
    431     if (sw.IsReading())
    432     {
    433       // If no transfers have occurred, no need to reload state.
    434       if (s_last_memory_card_transfer_frame != frame_number && s_last_memory_card_transfer_frame == prev_transfer_frame)
    435       {
    436         process_memcard_state = false;
    437       }
    438       else if (!state_has_memcards)
    439       {
    440         // If the memory state doesn't have card data (i.e. rolling back past a transfer start), reload the backed up
    441         // state created when the transfer initially begun.
    442         RestoreMemoryCardState();
    443         process_memcard_state = false;
    444       }
    445     }
    446 
    447     // Still have to parse through the data if it's present.
    448     if (state_has_memcards)
    449     {
    450       MemoryCard* dummy_card = process_memcard_state ? nullptr : GetDummyMemcard();
    451       for (u32 i = 0; i < NUM_CONTROLLER_AND_CARD_PORTS; i++)
    452       {
    453         if (s_memory_cards[i])
    454         {
    455           MemoryCard* const mc = process_memcard_state ? s_memory_cards[i].get() : dummy_card;
    456           mc->DoState(sw);
    457         }
    458       }
    459     }
    460 
    461     // Always save controller state.
    462     for (u32 i = 0; i < NUM_CONTROLLER_AND_CARD_PORTS; i++)
    463     {
    464       if (s_controllers[i])
    465       {
    466         // Ignore input state, use the current. I think we want this?
    467         s_controllers[i]->DoState(sw, false);
    468       }
    469     }
    470   }
    471   else
    472   {
    473     for (u32 i = 0; i < NUM_CONTROLLER_AND_CARD_PORTS; i++)
    474     {
    475       if ((sw.GetVersion() < 50) && (i >= 2)) [[unlikely]]
    476       {
    477         // loading from old savestate which only had max 2 controllers.
    478         // honoring load_devices_from_save_states in this case seems debatable, but might as well...
    479         if (s_controllers[i])
    480         {
    481           if (g_settings.load_devices_from_save_states)
    482             s_controllers[i].reset();
    483           else
    484             s_controllers[i]->Reset();
    485         }
    486 
    487         if (s_memory_cards[i])
    488         {
    489           if (g_settings.load_devices_from_save_states)
    490             s_memory_cards[i].reset();
    491           else
    492             s_memory_cards[i]->Reset();
    493         }
    494 
    495         // and make sure to skip trying to read controller_type / card_present flags which don't exist in old states.
    496         continue;
    497       }
    498 
    499       if (!DoStateController(sw, i))
    500         return false;
    501 
    502       if (!DoStateMemcard(sw, i, is_memory_state))
    503         return false;
    504     }
    505   }
    506 
    507   if (sw.GetVersion() >= 50) [[unlikely]]
    508   {
    509     for (u32 i = 0; i < NUM_MULTITAPS; i++)
    510     {
    511       if (!s_multitaps[i].DoState(sw))
    512         return false;
    513     }
    514   }
    515 
    516   sw.Do(&s_state);
    517   sw.Do(&s_JOY_CTRL.bits);
    518   sw.Do(&s_JOY_STAT.bits);
    519   sw.Do(&s_JOY_MODE.bits);
    520   sw.Do(&s_JOY_BAUD);
    521   sw.Do(&s_receive_buffer);
    522   sw.Do(&s_transmit_buffer);
    523   sw.Do(&s_receive_buffer_full);
    524   sw.Do(&s_transmit_buffer_full);
    525 
    526   if (sw.IsReading() && IsTransmitting())
    527     s_transfer_event.Activate();
    528 
    529   return !sw.HasError();
    530 }
    531 
    532 Controller* Pad::GetController(u32 slot)
    533 {
    534   return s_controllers[slot].get();
    535 }
    536 
    537 void Pad::SetController(u32 slot, std::unique_ptr<Controller> dev)
    538 {
    539   s_controllers[slot] = std::move(dev);
    540 }
    541 
    542 MemoryCard* Pad::GetMemoryCard(u32 slot)
    543 {
    544   return s_memory_cards[slot].get();
    545 }
    546 
    547 void Pad::SetMemoryCard(u32 slot, std::unique_ptr<MemoryCard> dev)
    548 {
    549   INFO_LOG("Memory card slot {}: {}", slot,
    550            dev ? (dev->GetFilename().empty() ? "<no file configured>" : dev->GetFilename().c_str()) : "<unplugged>");
    551 
    552   s_memory_cards[slot] = std::move(dev);
    553 }
    554 
    555 std::unique_ptr<MemoryCard> Pad::RemoveMemoryCard(u32 slot)
    556 {
    557   std::unique_ptr<MemoryCard> ret = std::move(s_memory_cards[slot]);
    558   if (ret)
    559     ret->Reset();
    560   return ret;
    561 }
    562 
    563 Multitap* Pad::GetMultitap(u32 slot)
    564 {
    565   return &s_multitaps[slot];
    566 }
    567 
    568 u32 Pad::ReadRegister(u32 offset)
    569 {
    570   switch (offset)
    571   {
    572     case 0x00: // JOY_DATA
    573     {
    574       if (IsTransmitting())
    575         s_transfer_event.InvokeEarly();
    576 
    577       const u8 value = s_receive_buffer_full ? s_receive_buffer : 0xFF;
    578       DEBUG_LOG("JOY_DATA (R) -> 0x{:02X}{}", value, s_receive_buffer_full ? "" : "(EMPTY)");
    579       s_receive_buffer_full = false;
    580       UpdateJoyStat();
    581 
    582       return (ZeroExtend32(value) | (ZeroExtend32(value) << 8) | (ZeroExtend32(value) << 16) |
    583               (ZeroExtend32(value) << 24));
    584     }
    585 
    586     case 0x04: // JOY_STAT
    587     {
    588       if (IsTransmitting())
    589         s_transfer_event.InvokeEarly();
    590 
    591       const u32 bits = s_JOY_STAT.bits;
    592       s_JOY_STAT.ACKINPUT = false;
    593       return bits;
    594     }
    595 
    596     case 0x08: // JOY_MODE
    597       return ZeroExtend32(s_JOY_MODE.bits);
    598 
    599     case 0x0A: // JOY_CTRL
    600       return ZeroExtend32(s_JOY_CTRL.bits);
    601 
    602     case 0x0E: // JOY_BAUD
    603       return ZeroExtend32(s_JOY_BAUD);
    604 
    605     [[unlikely]] default:
    606       ERROR_LOG("Unknown register read: 0x{:X}", offset);
    607       return UINT32_C(0xFFFFFFFF);
    608   }
    609 }
    610 
    611 void Pad::WriteRegister(u32 offset, u32 value)
    612 {
    613   switch (offset)
    614   {
    615     case 0x00: // JOY_DATA
    616     {
    617       DEBUG_LOG("JOY_DATA (W) <- 0x{:02X}", value);
    618 
    619       if (s_transmit_buffer_full)
    620         WARNING_LOG("TX FIFO overrun");
    621 
    622       s_transmit_buffer = Truncate8(value);
    623       s_transmit_buffer_full = true;
    624 
    625       if (!IsTransmitting() && CanTransfer())
    626         BeginTransfer();
    627 
    628       return;
    629     }
    630 
    631     case 0x0A: // JOY_CTRL
    632     {
    633       DEBUG_LOG("JOY_CTRL <- 0x{:04X}", value);
    634 
    635       s_JOY_CTRL.bits = Truncate16(value);
    636       if (s_JOY_CTRL.RESET)
    637         SoftReset();
    638 
    639       if (s_JOY_CTRL.ACK)
    640       {
    641         // reset stat bits
    642         s_JOY_STAT.INTR = false;
    643         InterruptController::SetLineState(InterruptController::IRQ::PAD, false);
    644       }
    645 
    646       if (!s_JOY_CTRL.SELECT)
    647         ResetDeviceTransferState();
    648 
    649       if (!s_JOY_CTRL.SELECT || !s_JOY_CTRL.TXEN)
    650       {
    651         if (IsTransmitting())
    652           EndTransfer();
    653       }
    654       else
    655       {
    656         if (!IsTransmitting() && CanTransfer())
    657           BeginTransfer();
    658       }
    659 
    660       UpdateJoyStat();
    661       return;
    662     }
    663 
    664     case 0x08: // JOY_MODE
    665     {
    666       DEBUG_LOG("JOY_MODE <- 0x{:08X}", value);
    667       s_JOY_MODE.bits = Truncate16(value);
    668       return;
    669     }
    670 
    671     case 0x0E:
    672     {
    673       DEBUG_LOG("JOY_BAUD <- 0x{:08X}", value);
    674       s_JOY_BAUD = Truncate16(value);
    675       return;
    676     }
    677 
    678       [[unlikely]] default:
    679       {
    680         ERROR_LOG("Unknown register write: 0x{:X} <- 0x{:08X}", offset, value);
    681         return;
    682       }
    683   }
    684 }
    685 
    686 bool Pad::IsTransmitting()
    687 {
    688   return s_state != State::Idle;
    689 }
    690 
    691 bool Pad::CanTransfer()
    692 {
    693   return s_transmit_buffer_full && s_JOY_CTRL.SELECT && s_JOY_CTRL.TXEN;
    694 }
    695 
    696 TickCount Pad::GetTransferTicks()
    697 {
    698   return static_cast<TickCount>(ZeroExtend32(s_JOY_BAUD) * 8);
    699 }
    700 
    701 void Pad::SoftReset()
    702 {
    703   if (IsTransmitting())
    704     EndTransfer();
    705 
    706   s_JOY_CTRL.bits = 0;
    707   s_JOY_STAT.bits = 0;
    708   s_JOY_MODE.bits = 0;
    709   s_receive_buffer = 0;
    710   s_receive_buffer_full = false;
    711   s_transmit_buffer = 0;
    712   s_transmit_buffer_full = false;
    713   ResetDeviceTransferState();
    714   UpdateJoyStat();
    715 }
    716 
    717 void Pad::UpdateJoyStat()
    718 {
    719   s_JOY_STAT.RXFIFONEMPTY = s_receive_buffer_full;
    720   s_JOY_STAT.TXDONE = !s_transmit_buffer_full && s_state != State::Transmitting;
    721   s_JOY_STAT.TXRDY = !s_transmit_buffer_full;
    722 }
    723 
    724 void Pad::TransferEvent(void*, TickCount ticks, TickCount ticks_late)
    725 {
    726   if (s_state == State::Transmitting)
    727     DoTransfer(ticks_late);
    728   else
    729     DoACK();
    730 }
    731 
    732 void Pad::BeginTransfer()
    733 {
    734   DebugAssert(s_state == State::Idle && CanTransfer());
    735   DEBUG_LOG("Starting transfer");
    736 
    737   s_JOY_CTRL.RXEN = true;
    738   s_transmit_value = s_transmit_buffer;
    739   s_transmit_buffer_full = false;
    740 
    741   // The transfer or the interrupt must be delayed, otherwise the BIOS thinks there's no device detected.
    742   // It seems to do something resembling the following:
    743   //  1) Sets the control register up for transmitting, interrupt on ACK.
    744   //  2) Writes 0x01 to the TX FIFO.
    745   //  3) Delays for a bit.
    746   //  4) Writes ACK to the control register, clearing the interrupt flag.
    747   //  5) Clears IRQ7 in the interrupt controller.
    748   //  6) Waits until the RX FIFO is not empty, reads the first byte to $zero.
    749   //  7) Checks if the interrupt status register had IRQ7 set. If not, no device connected.
    750   //
    751   // Performing the transfer immediately will result in both the INTR bit and the bit in the interrupt
    752   // controller being discarded in (4)/(5), but this bit was set by the *new* transfer. Therefore, the
    753   // test in (7) will fail, and it won't send any more data. So, the transfer/interrupt must be delayed
    754   // until after (4) and (5) have been completed.
    755 
    756   s_state = State::Transmitting;
    757   s_transfer_event.SetPeriodAndSchedule(GetTransferTicks());
    758 }
    759 
    760 void Pad::DoTransfer(TickCount ticks_late)
    761 {
    762   DEBUG_LOG("Transferring slot {}", s_JOY_CTRL.SLOT.GetValue());
    763 
    764   const u8 device_index = s_multitaps[0].IsEnabled() ? 4u : s_JOY_CTRL.SLOT;
    765   Controller* const controller = s_controllers[device_index].get();
    766   MemoryCard* const memory_card = s_memory_cards[device_index].get();
    767 
    768   // set rx?
    769   s_JOY_CTRL.RXEN = true;
    770 
    771   const u8 data_out = s_transmit_value;
    772 
    773   u8 data_in = 0xFF;
    774   bool ack = false;
    775 
    776   switch (s_active_device)
    777   {
    778     case ActiveDevice::None:
    779     {
    780       if (s_multitaps[s_JOY_CTRL.SLOT].IsEnabled())
    781       {
    782         if ((ack = s_multitaps[s_JOY_CTRL.SLOT].Transfer(data_out, &data_in)) == true)
    783         {
    784           TRACE_LOG("Active device set to tap {}, sent 0x{:02X}, received 0x{:02X}", static_cast<int>(s_JOY_CTRL.SLOT),
    785                     data_out, data_in);
    786           s_active_device = ActiveDevice::Multitap;
    787         }
    788       }
    789       else
    790       {
    791         if (!controller || (ack = controller->Transfer(data_out, &data_in)) == false)
    792         {
    793           if (!memory_card || (ack = memory_card->Transfer(data_out, &data_in)) == false)
    794           {
    795             // nothing connected to this port
    796             TRACE_LOG("Nothing connected or ACK'ed");
    797           }
    798           else
    799           {
    800             // memory card responded, make it the active device until non-ack
    801             TRACE_LOG("Transfer to memory card, data_out=0x{:02X}, data_in=0x{:02X}", data_out, data_in);
    802             s_active_device = ActiveDevice::MemoryCard;
    803 
    804             // back up memory card state in case we roll back to before this transfer begun
    805             const u32 frame_number = System::GetFrameNumber();
    806 
    807             // consider u32 overflow case
    808             if (ShouldAvoidSavingToState() &&
    809                 (frame_number - s_last_memory_card_transfer_frame) > GetMaximumRollbackFrames())
    810               BackupMemoryCardState();
    811 
    812             s_last_memory_card_transfer_frame = frame_number;
    813           }
    814         }
    815         else
    816         {
    817           // controller responded, make it the active device until non-ack
    818           TRACE_LOG("Transfer to controller, data_out=0x{:02X}, data_in=0x{:02X}", data_out, data_in);
    819           s_active_device = ActiveDevice::Controller;
    820         }
    821       }
    822     }
    823     break;
    824 
    825     case ActiveDevice::Controller:
    826     {
    827       if (controller)
    828       {
    829         ack = controller->Transfer(data_out, &data_in);
    830         TRACE_LOG("Transfer to controller, data_out=0x{:02X}, data_in=0x{:02X}", data_out, data_in);
    831       }
    832     }
    833     break;
    834 
    835     case ActiveDevice::MemoryCard:
    836     {
    837       if (memory_card)
    838       {
    839         s_last_memory_card_transfer_frame = System::GetFrameNumber();
    840         ack = memory_card->Transfer(data_out, &data_in);
    841         TRACE_LOG("Transfer to memory card, data_out=0x{:02X}, data_in=0x{:02X}", data_out, data_in);
    842       }
    843     }
    844     break;
    845 
    846     case ActiveDevice::Multitap:
    847     {
    848       if (s_multitaps[s_JOY_CTRL.SLOT].IsEnabled())
    849       {
    850         ack = s_multitaps[s_JOY_CTRL.SLOT].Transfer(data_out, &data_in);
    851         TRACE_LOG("Transfer tap {}, sent 0x{:02X}, received 0x{:02X}, acked: {}", static_cast<int>(s_JOY_CTRL.SLOT),
    852                   data_out, data_in, ack ? "true" : "false");
    853       }
    854     }
    855     break;
    856   }
    857 
    858   s_receive_buffer = data_in;
    859   s_receive_buffer_full = true;
    860 
    861   // device no longer active?
    862   if (!ack)
    863   {
    864     s_active_device = ActiveDevice::None;
    865     EndTransfer();
    866   }
    867   else
    868   {
    869     const bool memcard_transfer =
    870       s_active_device == ActiveDevice::MemoryCard ||
    871       (s_active_device == ActiveDevice::Multitap && s_multitaps[s_JOY_CTRL.SLOT].IsReadingMemoryCard());
    872 
    873     const TickCount ack_timer = GetACKTicks(memcard_transfer);
    874     DEBUG_LOG("Delaying ACK for {} ticks", ack_timer);
    875     s_state = State::WaitingForACK;
    876     s_transfer_event.SetPeriodAndSchedule(ack_timer);
    877   }
    878 
    879   UpdateJoyStat();
    880 }
    881 
    882 void Pad::DoACK()
    883 {
    884   s_JOY_STAT.ACKINPUT = true;
    885 
    886   if (s_JOY_CTRL.ACKINTEN)
    887   {
    888     DEBUG_LOG("Triggering ACK interrupt");
    889     s_JOY_STAT.INTR = true;
    890     InterruptController::SetLineState(InterruptController::IRQ::PAD, true);
    891   }
    892 
    893   EndTransfer();
    894   UpdateJoyStat();
    895 
    896   if (CanTransfer())
    897     BeginTransfer();
    898 }
    899 
    900 void Pad::EndTransfer()
    901 {
    902   DebugAssert(s_state == State::Transmitting || s_state == State::WaitingForACK);
    903   DEBUG_LOG("Ending transfer");
    904 
    905   s_state = State::Idle;
    906   s_transfer_event.Deactivate();
    907 }
    908 
    909 void Pad::ResetDeviceTransferState()
    910 {
    911   for (u32 i = 0; i < NUM_CONTROLLER_AND_CARD_PORTS; i++)
    912   {
    913     if (s_controllers[i])
    914       s_controllers[i]->ResetTransferState();
    915     if (s_memory_cards[i])
    916       s_memory_cards[i]->ResetTransferState();
    917   }
    918 
    919   for (u32 i = 0; i < NUM_MULTITAPS; i++)
    920     s_multitaps[i].ResetTransferState();
    921 
    922   s_active_device = ActiveDevice::None;
    923 }