/* gameplaySP
 *
 * Copyright (C) 2023 David Guillen Fandos <david@davidgf.net>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of
 * the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

/* MODIFIED 2026-10-25 by PlayAgain (not upstream gpSP):
 * ported from libretro/gpsp rfu.c + the RFU parts of serial.c to an mGBA
 * GBASIODriver (link-port peripheral). Changes against gpSP:
 *  - register access goes through mGBA's struct GBASIO (siocnt, io[]);
 *    gpSP's update_serial(cycles) is replaced by self-scheduled mTiming
 *    events (transfer completion + a poll while the adapter is master);
 *  - packet queues are ring buffers, depth runtime-settable up to
 *    RFU_QMAX (gpSP: fixed 4), with drop counters;
 *  - every network copy is length-checked (gpSP copies hdata>>24 bytes,
 *    up to 255, into a 16-byte buffer on CLIENT_SEND, reads 24 bytes of
 *    BROADCAST payload unchecked, and copies (plen-1) words into a 23-word
 *    TX buffer); CLIENT_SEND no longer falls through into CLIENT_ACK;
 *  - RNG is a local LCG seeded with mGBA's global cycle count XOR a
 *    per-home salt (two homes booting identically got the same device ID);
 *  - stats + optional debug log exported to the shim;
 *  - queue depth 64 and a 900-frame silent-client hold by default (gpSP's
 *    4 and 240 lose trades to an ordinary network stall);
 *  - rfu_peer_gone() drops every peer at once, as a DISCONNECT from each
 *    would, so a game shows its own error when the other home leaves.
 * The wire format ("RFU1" packets) is unchanged, so a gpSP peer should
 * interoperate (not tested). */

#include <mgba/internal/gba/gba.h>
#include <mgba/internal/gba/io.h>
#include <mgba/internal/gba/sio.h>
#include <mgba/core/timing.h>

#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>

typedef uint8_t u8;
typedef uint16_t u16;
typedef uint32_t u32;
typedef int32_t s32;

#ifndef MIN
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#endif

int rfu_debug = 0;
#define RFU_DEBUG_LOG(...) do { if (rfu_debug) printf(__VA_ARGS__); } while (0)

// Config knobs, update with care.
#define BCST_ANNOUNCE_VB               30   // Send broadcast twice per second.
#define MAX_RFU_PEERS                  32   // Do not allow more than 32 peers.

#define RFU_DEF_TIMEOUT              32   // Expressed as frames (~533ms)
#define RFU_DEF_RTXMAX                4   // Up to 4 transmissions per send

#define RFU_QMAX                     64   // Max queue depth (gpSP: 4)
int rfu_qdepth = RFU_QMAX;                // Runtime queue depth (<= RFU_QMAX)
int rfu_client_ttl_frames = 900;          // Host drops a silent client after this (gpSP: 240)
int rfu_resp_rfu_frames = 0;
int rfu_trim_k = 0;       // >0: experimental backlog trim: if a host queue stays above k, drop its oldest packet
int rfu_trim_every = 30;  //     at most once every this many frames
static int trim_cool[4];
u32 rfu_trimmed = 0;              // 0 = gpSP default (rtx_max), else override (RFU frames of 1/6 GBA frame)

/* ---- glue provided by the shim (home.c) */
void rfu_host_send(uint16_t client_id, const void *buf, size_t len);
void rfu_host_poll(void);
extern uint32_t rfu_salt;

static struct GBASIO* rfu_sio = NULL;

static inline u16 siocnt_read(void) { return rfu_sio->siocnt; }
static inline void siocnt_write(u16 v) { rfu_sio->siocnt = v; }
/* NB: mTimingGlobalTime() only advances when mGBA is built with ENABLE_DEBUGGERS (globalCycles is
 * debugger-only), so use masterCycles + relative cycles, with wrapping 32-bit deltas. */
static inline u32 cycles_now(void) { return (u32) mTimingCurrentTime(&rfu_sio->p->timing); }
static inline u32 cpu_ticks_now(void) { return cycles_now(); }

static u32 rng_state = 1;
static void rand_seed(u32 s) { rng_state = s ? s : 1; }
static u32 rand_gen(void) { rng_state = rng_state * 1103515245u + 12345u; return (rng_state >> 16) & 0x7FFF; }

static inline u32 netorder32(u32 v) {
  return ((v & 0xFF) << 24) | ((v & 0xFF00) << 8) | ((v >> 8) & 0xFF00) | (v >> 24);
}

/* ---- stats */
struct RFUStats {
  u32 txPkts[8], txBytes;
  u32 rxPkts[8], rxBytes;
  u32 dropHostQ, dropClientQ, malformed, badLen;
  u32 respData, respNoData, respTimeout, respDisc;
  u32 cmdCount[64];
  u32 unknownCmds;
  u32 maxQHost, maxQClient;
  u32 resets;
};
struct RFUStats rfu_stats;

// Unpacks big endian integers used for signaling
static inline u32 upack32(const u8 *ptr) {
  return ptr[3] | (ptr[2] << 8) | (ptr[1] << 16) | ((u32) ptr[0] << 24);
}

// Unpacks payload data, which is little-endian
static inline u32 leupack32(const u8 *ptr) {
  return ptr[0] | (ptr[1] << 8) | (ptr[2] << 16) | ((u32) ptr[3] << 24);
}

// The following commands, names and bit fields are not a 100% known.
// Most of them is guessed via reverse engineering the adapter and/or
// games that use it. Please take it with a grain of salt.
// You might wanna check:
// https://github.com/afska/gba-link-connection/
// https://blog.kuiper.dev/gba-wireless-adapter

#define RFU_CONN_INPROGRESS  0x01000000     // Connection ongoing
#define RFU_CONN_FAILED      0x02000000     // Connection failed

#define RFU_CONN_COMP_FAIL   0x01000000     // Failed to connect

#define RFU_CMD_INIT1        0x10   // Dummy after-init command
#define RFU_CMD_INIT2        0x3d   // Dummy after-init command
#define RFU_CMD_SYSCFG       0x17   // System configuration (comms. config)

#define RFU_CMD_LINKPWR      0x11   // Link/RF strength (0 to 0x16/0xFF)

#define RFU_CMD_SYSVER       0x12   // Return some 1 word with version info.
#define RFU_CMD_SYSSTAT      0x13   // System/Connection status.
#define RFU_CMD_SLOTSTAT     0x14   // Reads slot status information.
#define RFU_CMD_CFGSTAT      0x15   // Reads some sort of config state.

#define RFU_CMD_BCST_DATA    0x16   // Broadcast data setup

#define RFU_CMD_HOST_START   0x19   // Start broadcasting and accepting clients
#define RFU_CMD_HOST_ACCEPT  0x1a   // Poll for incoming connections
#define RFU_CMD_HOST_STOP    0x1b   // Stop accepting new connections

#define RFU_CMD_BCRD_START   0x1c   // Broadcast read session start
#define RFU_CMD_BCRD_FETCH   0x1d   // Broadcast read (actual data read)
#define RFU_CMD_BCRD_STOP    0x1e   // Broadcast read session end

#define RFU_CMD_CONNECT      0x1f   // Connect to host
#define RFU_CMD_ISCONNECTED  0x20   // Check for conection status
#define RFU_CMD_CONCOMPL     0x21   // Complete connection?

#define RFU_CMD_SEND_DATA    0x24   // Sends a data packet
#define RFU_CMD_SEND_DATAW   0x25   // Sends a data packet and waits
#define RFU_CMD_RECV_DATA    0x26   // Receive (poll) some data
#define RFU_CMD_WAIT         0x27   // Wait (for response or timeout)
#define RFU_CMD_RTX_WAIT     0x37   // Wait after some retransmit?

#define RFU_CMD_DISCONNECT   0x30   // Disconnects clients

// RFU commands for slave mode (~command responses)
#define RFU_CMD_RESP_TIMEO   0x27   // Timeout!
#define RFU_CMD_RESP_DATA    0x28   // There's data available
#define RFU_CMD_RESP_DISC    0x29   // Some clients disconnected

#define RFU_COMSTATE_RESET       0    // Just out of reset
#define RFU_COMSTATE_HANDSHAKE   1    // Performing initial nintendo handshake
#define RFU_COMSTATE_WAITCMD     2    // Idle, waiting for a command
#define RFU_COMSTATE_WAITDAT     3    // Waiting for follow up data
#define RFU_COMSTATE_RESPCMD     4    // RFU to device response (cmd)
#define RFU_COMSTATE_RESPDAT     5    // RFU to device response (N words)
#define RFU_COMSTATE_RESPERR     6    // Send back the error command
#define RFU_COMSTATE_RESPERR2    7    // Send back the error code
#define RFU_COMSTATE_WAITEVENT   8    // Waiting for event or timeout
#define RFU_COMSTATE_WAITRESP    9    // Responding a wait command

#define RFU_STATE_IDLE            0
#define RFU_STATE_HOST            1    // Hosting (with broadcast)
#define RFU_STATE_CONNECTING      2    // Trying to connect to a parent
#define RFU_STATE_CLIENT          3    // Client, connected to a host

static u32 rfu_prev_data;
u32 rfu_comstate, rfu_state;
static u32 rfu_cnt;
static u32 rfu_buf[256];
static u8 rfu_cmd, rfu_plen;
static u32 rfu_timeout_cycles, rfu_resp_timeout;
static u8 rfu_timeout, rfu_rtx_max;

static struct {
  u32 buf[23];
  u8 blen;
} rfu_tx_buf;

struct ClientPkt { u32 datalen; u8 data[16]; };
struct HostPkt { u16 hblen; u8 hdata[92]; };

static struct {
  u16 devid;         // Device ID assigned to the host
  u8 tx_ttl;         // Internal counter for broadcast transmission
  u32 bdata[6];      // Data to broadcast other devices
  struct {
    u16 client_id;   // transport client ID
    u16 devid;       // Host-assigned device ID
    u16 clttl;       // Client TTL (to check for disconnects)
    u16 qhead, qlen; // ring buffer of packets received from this client
    struct ClientPkt pkts[RFU_QMAX];
  } clients[4];      // Connected clients IDs (zero means empty slot).
} rfu_host;

static struct {
  u16 devid;         // Device ID assigned to the client (by the host?)
  u16 clnum;         // Client number (0 to 3)
  u16 host_id;       // Client ID for the host device.
  u16 qhead, qlen;
  struct HostPkt pkts[RFU_QMAX];
} rfu_client;

typedef struct {
  u8 valid;
  u8 ttl;            // When it reaches zero, entry is invalidated
  u16 device_id;     // Random ID generated by the RFU for each new session
  u32 data[6];       // Broadcast data (game+user data)
} t_client_broadcast;

static t_client_broadcast rfu_peer_bcst[MAX_RFU_PEERS];

#define NET_RFU_HEADER          0x52465531       // RFU1

#define NET_RFU_BROADCAST       0x00    // Host to everyone broadcast packet
#define NET_RFU_CONNECT_REQ     0x01    // Client connection request
#define NET_RFU_CONNECT_ACK     0x02    // Host connection response (accept)
#define NET_RFU_CONNECT_NACK    0x03    // Host connection response (reject)
#define NET_RFU_DISCONNECT      0x04    // Client/Host disconnect notice
#define NET_RFU_HOST_SEND       0x05    // Host to client data send
#define NET_RFU_CLIENT_SEND     0x06    // Client to host data send
#define NET_RFU_CLIENT_ACK      0x07    // Client ACKs host received data.

static void net_send(u16 to, u32 ptype, const void *buf, size_t len) {
  rfu_stats.txPkts[ptype & 7]++;
  rfu_stats.txBytes += len;
  rfu_host_send(to, buf, len);
}

static void rfu_net_send_cmd(int client_id, u32 ptype, u32 h) {
  u32 pkt[4] = { netorder32(NET_RFU_HEADER), netorder32(ptype), netorder32(h), 0 };
  net_send(client_id, ptype, pkt, 16);
}

static void rfu_net_send_bcast(u32 ptype, u32 h, const u32 *pload) {
  u32 i;
  u32 pkt[9] = { netorder32(NET_RFU_HEADER), netorder32(ptype), netorder32(h) };
  for (i = 0; i < 6; i++)
    pkt[i + 3] = netorder32(pload[i]);
  net_send(0xffff, ptype, pkt, sizeof(pkt));
}

static void rfu_net_send_data(int client_id, u32 ptype, u32 h, const u32 *pload, unsigned plen) {
  u32 i;
  struct { u32 header[3]; u8 data8[92]; } pkt = {
    { netorder32(NET_RFU_HEADER), netorder32(ptype), netorder32(h) },
  };
  if (plen > 92) plen = 92;
  for (i = 0; i < plen; i++)
    pkt.data8[i] = pload[i / 4] >> (8 * (i & 3));
  memset(&pkt.data8[plen], 0, 92 - plen);
  net_send(client_id, ptype, &pkt, 104);
}

static void rfu_reset_fsm(void) {
  rfu_prev_data = 0;
  rfu_cnt = 0;
  rfu_state = RFU_STATE_IDLE;
  rfu_comstate = RFU_COMSTATE_RESET;
  rfu_timeout_cycles = 0;
  rfu_resp_timeout = 0;
  rfu_timeout = RFU_DEF_TIMEOUT;
  rfu_rtx_max = RFU_DEF_RTXMAX;
  memset(&rfu_host, 0, sizeof(rfu_host));
  memset(&rfu_client, 0, sizeof(rfu_client));
  memset(&rfu_peer_bcst, 0, sizeof(rfu_peer_bcst));
}

// Called on the GPIO reset pulse (pin SD).
static void rfu_reset(void) {
  RFU_DEBUG_LOG("RFU reset!\n");
  rfu_stats.resets++;
  rfu_reset_fsm();
  rand_seed(cpu_ticks_now() ^ (rfu_salt * 0x9E3779B9u));
}

static u16 new_devid(void) {
  while (1) {
    u16 n = rand_gen() ^ (u16) cpu_ticks_now() ^ (u16) (rfu_salt * 0x45d9f3b);
    if (n)
      return n;
  }
}

static void host_q_push(int c, const u8 *data, u32 len) {
  if (rfu_host.clients[c].qlen >= (u32) rfu_qdepth) {
    rfu_stats.dropHostQ++;
    RFU_DEBUG_LOG("Host dropped a client packet\n");
    return;
  }
  u32 idx = (rfu_host.clients[c].qhead + rfu_host.clients[c].qlen) % RFU_QMAX;
  memcpy(rfu_host.clients[c].pkts[idx].data, data, len);
  rfu_host.clients[c].pkts[idx].datalen = len;
  rfu_host.clients[c].qlen++;
  if (rfu_host.clients[c].qlen > rfu_stats.maxQHost) rfu_stats.maxQHost = rfu_host.clients[c].qlen;
}

static void client_q_push(const u8 *data, u32 len) {
  if (rfu_client.qlen >= (u32) rfu_qdepth) {
    rfu_stats.dropClientQ++;
    RFU_DEBUG_LOG("Client dropped a host packet\n");
    return;
  }
  u32 idx = (rfu_client.qhead + rfu_client.qlen) % RFU_QMAX;
  memcpy(rfu_client.pkts[idx].hdata, data, len);
  rfu_client.pkts[idx].hblen = len;
  rfu_client.qlen++;
  if (rfu_client.qlen > rfu_stats.maxQClient) rfu_stats.maxQClient = rfu_client.qlen;
}

static s32 rfu_process_command(void) {
  u32 i, j, cnt = 0;
  RFU_DEBUG_LOG("Processing command 0x%x (len %d)\n", rfu_cmd, rfu_plen);
  rfu_stats.cmdCount[rfu_cmd & 63]++;

  switch (rfu_cmd) {
  case RFU_CMD_INIT1:
  case RFU_CMD_INIT2:
    return 0;

  case RFU_CMD_SYSCFG:
    rfu_timeout = rfu_buf[0];
    rfu_rtx_max = rfu_buf[0] >> 8;
    return 0;

  case RFU_CMD_SYSVER:
    rfu_buf[0] = 0x00830117;
    return 1;

  case RFU_CMD_SYSSTAT:
    if (rfu_state == RFU_STATE_HOST)
      rfu_buf[0] = (1 << 24) | rfu_host.devid;
    else if (rfu_state == RFU_STATE_CLIENT)
      rfu_buf[0] = (5 << 24) | ((1 << rfu_client.clnum) << 16) | rfu_client.devid;
    else
      rfu_buf[0] = 0;
    return 1;

  case RFU_CMD_SLOTSTAT:
    if (rfu_state == RFU_STATE_HOST) {
      u32 c = 0;
      rfu_buf[c++] = 0;
      for (i = 0; i < 4; i++)
        if (rfu_host.clients[i].devid) {
          rfu_buf[0]++;
          rfu_buf[c++] = rfu_host.clients[i].devid | (i << 16);
        }
      return c;
    }
    return 0;

  case RFU_CMD_LINKPWR:
    if (rfu_state == RFU_STATE_HOST)
      rfu_buf[0] = (rfu_host.clients[0].devid ? 0x000000ff : 0) |
                   (rfu_host.clients[1].devid ? 0x0000ff00 : 0) |
                   (rfu_host.clients[2].devid ? 0x00ff0000 : 0) |
                   (rfu_host.clients[3].devid ? 0xff000000 : 0);
    else if (rfu_state == RFU_STATE_CLIENT)
      rfu_buf[0] = 0xffffffff;
    else
      rfu_buf[0] = 0;
    return 1;

  case RFU_CMD_BCRD_START:
    return 0;

  case RFU_CMD_BCRD_STOP:
  case RFU_CMD_BCRD_FETCH:
    i = rand_gen() % MAX_RFU_PEERS;
    for (j = 0, cnt = 0; cnt < 4 * 7 && j < MAX_RFU_PEERS; j++) {
      u32 entry = (i + j) % MAX_RFU_PEERS;
      if (rfu_peer_bcst[entry].valid) {
        rfu_buf[cnt++] = rfu_peer_bcst[entry].device_id;
        memcpy(&rfu_buf[cnt], rfu_peer_bcst[entry].data, sizeof(rfu_peer_bcst[entry].data));
        cnt += 6;
      }
    }
    return cnt;

  case RFU_CMD_BCST_DATA:
    if (rfu_plen == 6)
      memcpy(rfu_host.bdata, rfu_buf, sizeof(rfu_host.bdata));
    return 0;

  case RFU_CMD_HOST_START:
    if (rfu_state == RFU_STATE_CLIENT) {
      RFU_DEBUG_LOG("RFU error: Cannot start host, we are a client already\n");
      return -1;
    }
    if (rfu_state == RFU_STATE_IDLE) {
      rfu_host.devid = new_devid();
      memset(rfu_host.clients, 0, sizeof(rfu_host.clients));
      rfu_state = RFU_STATE_HOST;
      RFU_DEBUG_LOG("Start hosting with device ID %02x\n", rfu_host.devid);
    }
    rfu_host.tx_ttl = 0xff;
    return 0;

  case RFU_CMD_HOST_STOP:
    if (rfu_state == RFU_STATE_IDLE)
      return -1;
    if (rfu_state == RFU_STATE_HOST) {
      for (i = 0; i < 4; i++)
        if (rfu_host.clients[i].devid)
          return 0;
      rfu_state = RFU_STATE_IDLE;
    }
    return 0;

  case RFU_CMD_HOST_ACCEPT:
    if (rfu_state == RFU_STATE_IDLE)
      return -1;
    for (i = 0; i < 4; i++)
      if (rfu_host.clients[i].devid)
        rfu_buf[cnt++] = rfu_host.clients[i].devid | (i << 16);
    return cnt;

  case RFU_CMD_CONNECT:
    if (rfu_state == RFU_STATE_HOST)
      return -1;
    {
      u16 reqid = rfu_buf[0] & 0xffff;
      for (i = 0, cnt = 0; i < MAX_RFU_PEERS; i++) {
        if (rfu_peer_bcst[i].valid && rfu_peer_bcst[i].device_id == reqid) {
          rfu_net_send_cmd(i, NET_RFU_CONNECT_REQ, reqid);
          rfu_state = RFU_STATE_CONNECTING;
          RFU_DEBUG_LOG("Requesting connection to client %d (%x)\n", i, reqid);
          return 0;
        }
      }
    }
    return 0;

  case RFU_CMD_ISCONNECTED:
    if (rfu_state == RFU_STATE_HOST)
      return -1;
    if (rfu_state == RFU_STATE_CONNECTING)
      rfu_buf[0] = RFU_CONN_INPROGRESS;
    else if (rfu_state == RFU_STATE_IDLE)
      rfu_buf[0] = RFU_CONN_FAILED;
    else
      rfu_buf[0] = rfu_client.devid | (rfu_client.clnum << 16);
    return 1;

  case RFU_CMD_CONCOMPL:
    if (rfu_state == RFU_STATE_HOST)
      return -1;
    if (rfu_state == RFU_STATE_CLIENT) {
      rfu_buf[0] = rfu_client.devid | (rfu_client.clnum << 16);
    } else {
      rfu_buf[0] = RFU_CONN_COMP_FAIL;
      rfu_state = RFU_STATE_IDLE;
    }
    return 1;

  case RFU_CMD_SEND_DATAW:
  case RFU_CMD_SEND_DATA:
    if (!rfu_plen)
      return 0;
    {
      u32 words = MIN((u32) rfu_plen - 1, 23u);   // bounded (gpSP: unbounded)
      if (rfu_state == RFU_STATE_HOST) {
        rfu_tx_buf.blen = rfu_buf[0] & 0x7F;
        memcpy(rfu_tx_buf.buf, &rfu_buf[1], words * sizeof(u32));
      } else if (rfu_state == RFU_STATE_CLIENT) {
        rfu_tx_buf.blen = (rfu_buf[0] >> (8 + rfu_client.clnum * 5)) & 0x1F;
        memcpy(rfu_tx_buf.buf, &rfu_buf[1], words * sizeof(u32));
      }
    }
    /* fallthrough */
  case RFU_CMD_RTX_WAIT:
    if (rfu_state == RFU_STATE_HOST) {
      RFU_DEBUG_LOG("Host sending %d bytes / %d words to clients\n", rfu_tx_buf.blen, rfu_plen - 1);
      if (rfu_tx_buf.blen <= 90) {
        for (i = 0; i < 4; i++)
          if (rfu_host.clients[i].devid)
            rfu_net_send_data(rfu_host.clients[i].client_id, NET_RFU_HOST_SEND, rfu_tx_buf.blen, rfu_tx_buf.buf, rfu_tx_buf.blen);
      }
    } else if (rfu_state == RFU_STATE_CLIENT) {
      RFU_DEBUG_LOG("Client sending %d bytes / %d words to host\n", rfu_tx_buf.blen, rfu_plen - 1);
      if (rfu_tx_buf.blen <= 16) {
        rfu_net_send_data(rfu_client.host_id, NET_RFU_CLIENT_SEND,
          (rfu_tx_buf.blen << 24) | (rfu_client.clnum << 16) | rfu_client.devid,
          rfu_tx_buf.buf, rfu_tx_buf.blen);
      }
    } else
      return -1;
    break;

  case RFU_CMD_RECV_DATA:
    if (rfu_state == RFU_STATE_HOST) {
      u32 c = 0, bufbytes = 0;
      u8 tmpbuf[16 * 4] = {0};
      rfu_buf[c++] = 0;
      for (i = 0; i < 4; i++) {
        if (rfu_host.clients[i].devid && rfu_host.clients[i].qlen) {
          struct ClientPkt *p = &rfu_host.clients[i].pkts[rfu_host.clients[i].qhead];
          u32 dlen = MIN(16u, p->datalen);
          memcpy(&tmpbuf[bufbytes], p->data, dlen);
          bufbytes += dlen;
          rfu_buf[0] |= dlen << (8 + i * 5);
          rfu_host.clients[i].qhead = (rfu_host.clients[i].qhead + 1) % RFU_QMAX;
          rfu_host.clients[i].qlen--;
        }
      }
      for (i = 0; i < (bufbytes + 3) / 4; i++)
        rfu_buf[c++] = leupack32(&tmpbuf[i * 4]);
      return c;
    } else if (rfu_state == RFU_STATE_CLIENT) {
      u32 c = 0, dlen = 0;
      if (rfu_client.qlen) {
        struct HostPkt *p = &rfu_client.pkts[rfu_client.qhead];
        u8 tmp[96] = {0};
        dlen = MIN(92u, p->hblen);
        memcpy(tmp, p->hdata, dlen);
        rfu_buf[c++] = dlen;
        for (j = 0; j < (dlen + 3) / 4; j++)
          rfu_buf[c++] = leupack32(&tmp[j * 4]);
        rfu_client.qhead = (rfu_client.qhead + 1) % RFU_QMAX;
        rfu_client.qlen--;
      } else {
        rfu_buf[c++] = 0;
      }
      return c;
    }
    break;

  case RFU_CMD_WAIT:
    return 0;

  case RFU_CMD_DISCONNECT:
    if (rfu_state == RFU_STATE_CLIENT) {
      rfu_net_send_cmd(rfu_client.host_id, NET_RFU_DISCONNECT, rfu_client.devid | (rfu_client.clnum << 16));
      rfu_state = RFU_STATE_IDLE;
    } else if (rfu_state == RFU_STATE_HOST) {
      for (i = 0; i < 4; i++)
        if (rfu_buf[0] & (1 << i)) {
          rfu_net_send_cmd(rfu_host.clients[i].client_id, NET_RFU_DISCONNECT, rfu_host.clients[i].devid | (i << 16));
          memset(&rfu_host.clients[i], 0, sizeof(rfu_host.clients[i]));
        }
    }
    return 0;

  default:
    rfu_stats.unknownCmds++;
    RFU_DEBUG_LOG("Unknown RFU command %02x\n", rfu_cmd);
  };

  return 0;
}

static bool rfu_data_avail(void) {
  if (rfu_state == RFU_STATE_CLIENT) {
    if (rfu_client.qlen)
      return true;
  } else if (rfu_state == RFU_STATE_HOST) {
    u32 i;
    for (i = 0; i < 4; i++)
      if (rfu_host.clients[i].devid && rfu_host.clients[i].qlen)
        return true;
  }
  return false;
}

static u32 rfu_transfer(u32 sent_value) {
  u32 retval = 0x80000000;

  switch (rfu_comstate) {
  case RFU_COMSTATE_RESET:
    retval = 0;
    if ((sent_value & 0xFFFF) == 0x494E)
      rfu_comstate = RFU_COMSTATE_HANDSHAKE;
    break;

  case RFU_COMSTATE_HANDSHAKE:
    if (sent_value == 0xB0BB8001)
      rfu_comstate = RFU_COMSTATE_WAITCMD;
    retval = (sent_value << 16) | ((~rfu_prev_data) & 0xFFFF);
    break;

  case RFU_COMSTATE_WAITCMD:
    if ((sent_value >> 16) == 0x9966) {
      rfu_plen = (u8)(sent_value >> 8);
      rfu_cmd  = (u8)(sent_value);
      rfu_cnt = 0;
      if (!rfu_plen) {
        s32 ret = rfu_process_command();
        if (ret < 0) {
          rfu_comstate = RFU_COMSTATE_RESPERR;
          rfu_cmd = (u32)(-ret);
          rfu_plen = 1;
        } else {
          rfu_comstate = RFU_COMSTATE_RESPCMD;
          rfu_plen = (u32)ret;
        }
      } else
        rfu_comstate = RFU_COMSTATE_WAITDAT;
    }
    break;

  case RFU_COMSTATE_WAITDAT:
    rfu_buf[rfu_cnt++ & 0xFF] = sent_value;
    if (rfu_cnt >= rfu_plen) {
      s32 ret = rfu_process_command();
      if (ret < 0) {
        rfu_comstate = RFU_COMSTATE_RESPERR;
        rfu_cmd = (u32)(-ret);
        rfu_plen = 1;
      } else {
        rfu_comstate = RFU_COMSTATE_RESPCMD;
        rfu_plen = (u32)ret;
      }
      rfu_cnt = 0;
    }
    break;

  case RFU_COMSTATE_RESPCMD:
    retval = 0x99660080 | rfu_cmd | (rfu_plen << 8);
    if (rfu_cmd == RFU_CMD_WAIT || rfu_cmd == RFU_CMD_RTX_WAIT || rfu_cmd == RFU_CMD_SEND_DATAW) {
      rfu_comstate = RFU_COMSTATE_WAITEVENT;
      rfu_timeout_cycles = rfu_timeout * (16777216 / 60);
      rfu_resp_timeout = (rfu_resp_rfu_frames ? (u32) rfu_resp_rfu_frames : rfu_rtx_max) * (16777216 / 60 / 6);
    } else {
      rfu_comstate = rfu_plen ? RFU_COMSTATE_RESPDAT : RFU_COMSTATE_WAITCMD;
    }
    break;

  case RFU_COMSTATE_RESPDAT:
    retval = rfu_buf[rfu_cnt++ & 0xFF];
    if (rfu_cnt >= rfu_plen)
      rfu_comstate = RFU_COMSTATE_WAITCMD;
    break;

  case RFU_COMSTATE_WAITEVENT:
  case RFU_COMSTATE_WAITRESP:
    break;

  case RFU_COMSTATE_RESPERR:
    retval = 0x996601ee;
    rfu_comstate = RFU_COMSTATE_RESPERR2;
    break;

  case RFU_COMSTATE_RESPERR2:
    retval = rfu_cmd;
    rfu_comstate = RFU_COMSTATE_WAITCMD;
    break;
  };

  rfu_prev_data = sent_value;
  return retval;
}

void rfu_frame_update(void) {
  if (rfu_comstate != RFU_COMSTATE_RESET) {
    u32 i;
    for (i = 0; i < MAX_RFU_PEERS; i++) {
      if (rfu_peer_bcst[i].valid) {
        if (--rfu_peer_bcst[i].ttl == 0)
          rfu_peer_bcst[i].valid = 0;
      }
    }
    if (rfu_state == RFU_STATE_HOST) {
      if (rfu_host.tx_ttl++ >= BCST_ANNOUNCE_VB) {
        rfu_host.tx_ttl = 0;
        rfu_net_send_bcast(NET_RFU_BROADCAST, rfu_host.devid, rfu_host.bdata);
      }
    }
    if (rfu_state == RFU_STATE_HOST && rfu_trim_k > 0) {
      for (i = 0; i < 4; i++) {
        if (trim_cool[i] > 0) trim_cool[i]--;
        if (rfu_host.clients[i].devid && rfu_host.clients[i].qlen > (u32) rfu_trim_k && !trim_cool[i]) {
          rfu_host.clients[i].qhead = (rfu_host.clients[i].qhead + 1) % RFU_QMAX;
          rfu_host.clients[i].qlen--;
          trim_cool[i] = rfu_trim_every;
          rfu_trimmed++;
        }
      }
    }
    if (rfu_state == RFU_STATE_HOST) {
      for (i = 0; i < 4; i++) {
        if (rfu_host.clients[i].devid) {
          if (++rfu_host.clients[i].clttl >= rfu_client_ttl_frames) {
            RFU_DEBUG_LOG("Disconnect client slot %d due to timeout\n", i);
            memset(&rfu_host.clients[i], 0, sizeof(rfu_host.clients[i]));
          }
        }
      }
    }
  }
}

void rfu_net_receive(const void* buf, size_t len, uint16_t client_id) {
  if (len >= 12 && upack32((const u8*)buf) == NET_RFU_HEADER) {
    u32 i;
    const u8 *buf8 = (const u8*)buf;
    const u8 *payl = &buf8[12];
    u32 ptype = upack32(&buf8[4]);
    u32 hdata = upack32(&buf8[8]);
    rfu_stats.rxPkts[ptype & 7]++;
    rfu_stats.rxBytes += len;

    switch (ptype) {
    case NET_RFU_BROADCAST:
      if (len < 12 + 24) { rfu_stats.badLen++; break; }
      if (client_id < MAX_RFU_PEERS) {
        u32 j;
        rfu_peer_bcst[client_id].device_id = hdata;
        rfu_peer_bcst[client_id].valid = 1;
        rfu_peer_bcst[client_id].ttl = 0xff;
        for (j = 0; j < 6; j++)
          rfu_peer_bcst[client_id].data[j] = upack32(&payl[j * 4]);
      }
      break;

    case NET_RFU_CONNECT_REQ:
      if (rfu_state == RFU_STATE_HOST) {
        for (i = 0; i < 4; i++)
          if (rfu_host.clients[i].devid && rfu_host.clients[i].client_id == client_id)
            return;
        for (i = 0; i < 4; i++)
          if (!rfu_host.clients[i].devid) {
            u16 newid = new_devid();
            memset(&rfu_host.clients[i], 0, sizeof(rfu_host.clients[i]));
            rfu_host.clients[i].devid = newid;
            rfu_host.clients[i].client_id = client_id;
            rfu_net_send_cmd(client_id, NET_RFU_CONNECT_ACK, newid | (i << 16));
            return;
          }
        rfu_net_send_cmd(client_id, NET_RFU_CONNECT_NACK, 0);
      } else {
        rfu_net_send_cmd(client_id, NET_RFU_CONNECT_NACK, 0);
      }
      break;

    case NET_RFU_CONNECT_ACK:
      if (rfu_state == RFU_STATE_CONNECTING) {
        memset(&rfu_client, 0, sizeof(rfu_client));
        rfu_client.devid = hdata & 0xffff;
        rfu_client.clnum = (hdata >> 16) & 3;
        rfu_client.host_id = client_id;
        rfu_state = RFU_STATE_CLIENT;
      }
      break;

    case NET_RFU_CONNECT_NACK:
      if (rfu_state == RFU_STATE_CONNECTING)
        rfu_state = RFU_STATE_IDLE;
      break;

    case NET_RFU_DISCONNECT:
      if (rfu_state == RFU_STATE_HOST) {
        u32 clnum = (hdata >> 16) & 0x3;
        u16 cldid = hdata & 0xffff;
        if (rfu_host.clients[clnum].devid == cldid)
          memset(&rfu_host.clients[clnum], 0, sizeof(rfu_host.clients[clnum]));
      } else if (rfu_state == RFU_STATE_CLIENT) {
        memset(&rfu_client, 0, sizeof(rfu_client));
        rfu_state = RFU_STATE_IDLE;
      }
      break;

    case NET_RFU_HOST_SEND:
      if (rfu_state == RFU_STATE_CLIENT) {
        u32 blen = hdata & 0x7f;
        if (blen > 92 || len < blen + 12) { rfu_stats.badLen++; break; }
        rfu_net_send_cmd(client_id, NET_RFU_CLIENT_ACK, rfu_client.devid | (rfu_client.clnum << 16));
        client_q_push(payl, blen);
      }
      break;

    case NET_RFU_CLIENT_SEND:
      if (rfu_state == RFU_STATE_HOST) {
        u16 cdevid = hdata & 0xffff;
        u32 clid = (hdata >> 16) & 0x3;
        u32 blen = hdata >> 24;
        if (blen > 16 || len < blen + 12) { rfu_stats.badLen++; break; }
        if (rfu_host.clients[clid].devid == cdevid) {
          rfu_host.clients[clid].clttl = 0;
          host_q_push(clid, payl, blen);
        }
      }
      break;   // gpSP falls through into CLIENT_ACK here

    case NET_RFU_CLIENT_ACK:
      if (rfu_state == RFU_STATE_HOST) {
        u32 devid = hdata & 0xffff;
        u32 clid = (hdata >> 16) & 0x3;
        if (rfu_host.clients[clid].devid == devid)
          rfu_host.clients[clid].clttl = 0;
      }
      break;
    };
  } else {
    rfu_stats.malformed++;
    RFU_DEBUG_LOG("Drop malformed packet\n");
  }
}

/* The other home left or the channel dropped: as a DISCONNECT from every peer. */
void rfu_peer_gone(void) {
  u32 i;
  if (rfu_state == RFU_STATE_HOST) {
    for (i = 0; i < 4; i++)
      memset(&rfu_host.clients[i], 0, sizeof(rfu_host.clients[i]));
  } else if (rfu_state == RFU_STATE_CLIENT || rfu_state == RFU_STATE_CONNECTING) {
    memset(&rfu_client, 0, sizeof(rfu_client));
    rfu_state = RFU_STATE_IDLE;
  }
  for (i = 0; i < MAX_RFU_PEERS; i++)
    rfu_peer_bcst[i].valid = 0;
}

int rfu_poll_mid_wait = 0;   // 1: call the transport's poll during waits (gpSP behaviour)

// Account for consumed cycles and return if a serial IRQ should be raised.
static bool rfu_update(unsigned cycles) {
  if (rfu_comstate == RFU_COMSTATE_WAITEVENT) {
    if (rfu_poll_mid_wait)
      rfu_host_poll();

    rfu_timeout_cycles -= MIN(cycles, rfu_timeout_cycles);
    rfu_resp_timeout   -= MIN(cycles, rfu_resp_timeout);

    if ((siocnt_read() & 0x1) == 0) {
      if (rfu_state == RFU_STATE_IDLE) {
        rfu_buf[0] = 0x99660000 | (1 << 8) | RFU_CMD_RESP_DISC;
        rfu_buf[1] = 0xF;
        rfu_buf[2] = 0x80000000;
        rfu_cnt = 0;
        rfu_plen = 3;
        rfu_comstate = RFU_COMSTATE_WAITRESP;
        rfu_stats.respDisc++;
      } else if (rfu_data_avail()) {
        rfu_buf[0] = 0x99660000 | RFU_CMD_RESP_DATA;
        rfu_buf[1] = 0x80000000;
        rfu_cnt = 0;
        rfu_plen = 2;
        rfu_comstate = RFU_COMSTATE_WAITRESP;
        rfu_stats.respData++;
      } else if (rfu_state == RFU_STATE_HOST && !rfu_resp_timeout) {
        rfu_buf[0] = 0x99660000 | RFU_CMD_RESP_DATA | (1 << 8);
        rfu_buf[1] = 0x00000F0F;
        rfu_buf[2] = 0x80000000;
        rfu_cnt = 0;
        rfu_plen = 3;
        rfu_comstate = RFU_COMSTATE_WAITRESP;
        rfu_stats.respNoData++;
      } else if (!rfu_timeout_cycles) {
        rfu_buf[0] = 0x99660000 | RFU_CMD_RESP_TIMEO;
        rfu_buf[1] = 0x80000000;
        rfu_cnt = 0;
        rfu_plen = 2;
        rfu_comstate = RFU_COMSTATE_WAITRESP;
        rfu_stats.respTimeout++;
      }
    }
  }

  if (rfu_comstate == RFU_COMSTATE_WAITRESP) {
    u16 cnt = siocnt_read();
    if ((cnt & 0xC) == 0 && (cnt & 0x80)) {
      u16* io = rfu_sio->p->memory.io;
      io[GBA_REG(SIODATA32_HI)] = rfu_buf[rfu_cnt] >> 16;
      io[GBA_REG(SIODATA32_LO)] = rfu_buf[rfu_cnt] & 0xffff;
      siocnt_write(cnt & ~0x80);
      rfu_cnt++;
      if (rfu_cnt >= rfu_plen)
        rfu_comstate = RFU_COMSTATE_WAITCMD;
      return siocnt_read() & 0x4000;
    }
  }
  return false;
}

/* ------------------------------------------------------------------------
 * mGBA GBASIODriver glue (replaces gpSP serial.c RFU paths)
 * ---------------------------------------------------------------------- */

#define CLOCK_CYC_256KHZ_8BIT        524
#define CLOCK_CYC_2MHZ_8BIT           67
#define RFU_POLL_CYCLES             1024

struct RFUDriver {
  struct GBASIODriver d;
  struct mTimingEvent xferEvent;
  struct mTimingEvent pollEvent;
  u32 xferResult;
  bool xferPending;
  u32 lastPoll;
};

static struct RFUDriver rfuDriver;
u32 rfu_stat_polls = 0, rfu_stat_xfers = 0;

static void _schedulePoll(int32_t when) {
  struct mTiming* timing = &rfu_sio->p->timing;
  if (!mTimingIsScheduled(timing, &rfuDriver.pollEvent)) {
    rfuDriver.lastPoll = cycles_now();
    mTimingSchedule(timing, &rfuDriver.pollEvent, when);
  }
}

static void _pollEvent(struct mTiming* timing, void* user, uint32_t cyclesLate) {
  UNUSED(user);
  u32 now = cycles_now();
  unsigned cycles = (unsigned) (u32) (now - rfuDriver.lastPoll);
  rfuDriver.lastPoll = now;
  rfu_stat_polls++;
  if (rfu_update(cycles)) {
    GBARaiseIRQ(rfu_sio->p, GBA_IRQ_SIO, cyclesLate);
  }
  if (rfu_comstate == RFU_COMSTATE_WAITEVENT || rfu_comstate == RFU_COMSTATE_WAITRESP) {
    mTimingSchedule(timing, &rfuDriver.pollEvent, RFU_POLL_CYCLES);
  }
}

static void _xferEvent(struct mTiming* timing, void* user, uint32_t cyclesLate) {
  UNUSED(timing);
  UNUSED(user);
  rfuDriver.xferPending = false;
  // Set SI busy (weird SO/SI handshake), then complete: clears start, writes
  // the word and raises the IRQ if enabled.
  rfu_sio->siocnt |= 0x0004;
  GBASIONormal32FinishTransfer(rfu_sio, rfuDriver.xferResult, cyclesLate);
  if (rfu_comstate == RFU_COMSTATE_WAITEVENT || rfu_comstate == RFU_COMSTATE_WAITRESP)
    _schedulePoll(RFU_POLL_CYCLES);
}

static bool _rfuInit(struct GBASIODriver* driver) {
  UNUSED(driver);
  rfuDriver.xferEvent.context = &rfuDriver;
  rfuDriver.xferEvent.name = "GBA SIO RFU transfer";
  rfuDriver.xferEvent.callback = _xferEvent;
  rfuDriver.xferEvent.priority = 0x80;
  rfuDriver.pollEvent.context = &rfuDriver;
  rfuDriver.pollEvent.name = "GBA SIO RFU poll";
  rfuDriver.pollEvent.callback = _pollEvent;
  rfuDriver.pollEvent.priority = 0x81;
  rfu_sio = driver->p;
  rfu_reset_fsm();
  return true;
}

static void _rfuDeinit(struct GBASIODriver* driver) {
  UNUSED(driver);
  if (rfu_sio) {
    mTimingDeschedule(&rfu_sio->p->timing, &rfuDriver.xferEvent);
    mTimingDeschedule(&rfu_sio->p->timing, &rfuDriver.pollEvent);
  }
}

static void _rfuReset(struct GBASIODriver* driver) {
  _rfuDeinit(driver);
  rfuDriver.xferPending = false;
  rfu_reset_fsm();
}

static bool _rfuHandlesMode(struct GBASIODriver* driver, enum GBASIOMode mode) {
  UNUSED(driver);
  return mode == GBA_SIO_NORMAL_32 || mode == GBA_SIO_NORMAL_8;
}

static int _rfuConnected(struct GBASIODriver* driver) {
  UNUSED(driver);
  return 1;
}

static uint16_t _rfuWriteRCNT(struct GBASIODriver* driver, uint16_t value) {
  struct GBASIO* sio = driver->p;
  uint16_t oldval = sio->rcnt;   // low 9 bits still old here
  if ((sio->rcnt & 0xC000) == 0x8000) {   // GPIO mode
    if ((value & 0x20) && !(oldval & 0x02))
      rfu_reset();
  }
  return value;
}

static uint16_t _rfuWriteSIOCNT(struct GBASIODriver* driver, uint16_t value) {
  struct GBASIO* sio = driver->p;
  uint16_t oldval = sio->siocnt;
  uint16_t newval = (value & 0x7F8B) | (oldval & 0x0004);

  if (sio->mode == GBA_SIO_NORMAL_32 || sio->mode == GBA_SIO_NORMAL_8) {
    if ((newval & 0x0080) && (newval & 0x1) && !rfuDriver.xferPending) {
      u32 sent = sio->p->memory.io[GBA_REG(SIODATA32_LO)] | ((u32) sio->p->memory.io[GBA_REG(SIODATA32_HI)] << 16);
      rfuDriver.xferResult = rfu_transfer(sent);
      rfuDriver.xferPending = true;
      rfu_stat_xfers++;
      int32_t cyc = (newval & 0x2) ? CLOCK_CYC_2MHZ_8BIT : CLOCK_CYC_256KHZ_8BIT;
      if (newval & 0x1000)
        cyc <<= 2;
      mTimingDeschedule(&sio->p->timing, &rfuDriver.xferEvent);
      mTimingSchedule(&sio->p->timing, &rfuDriver.xferEvent, cyc);
    }
    if (newval & 0x1) {
      if ((newval & 0x0008) && !(oldval & 0x0008))
        newval &= ~0x0004;
    } else {
      if ((newval & 0x0008) && !(oldval & 0x0008))
        newval |= 0x0004;
      if (!(newval & 0x0008) && (oldval & 0x0008))
        newval &= ~0x0004;
      // Slave mode with start armed while the adapter wants to push: make sure we poll.
      if ((newval & 0x80) && (rfu_comstate == RFU_COMSTATE_WAITEVENT || rfu_comstate == RFU_COMSTATE_WAITRESP))
        _schedulePoll(64);
    }
  }
  return newval;
}

static bool _rfuStart(struct GBASIODriver* driver) {
  UNUSED(driver);
  return false;   // transfers are completed by this driver
}

static uint32_t _rfuFinishNormal32(struct GBASIODriver* driver) {
  UNUSED(driver);
  return rfuDriver.xferResult;
}

struct GBASIODriver* rfu_driver_create(void) {
  memset(&rfuDriver, 0, sizeof(rfuDriver));
  rfuDriver.d.init = _rfuInit;
  rfuDriver.d.deinit = _rfuDeinit;
  rfuDriver.d.reset = _rfuReset;
  rfuDriver.d.handlesMode = _rfuHandlesMode;
  rfuDriver.d.connectedDevices = _rfuConnected;
  rfuDriver.d.writeRCNT = _rfuWriteRCNT;
  rfuDriver.d.writeSIOCNT = _rfuWriteSIOCNT;
  rfuDriver.d.start = _rfuStart;
  rfuDriver.d.finishNormal32 = _rfuFinishNormal32;
  return &rfuDriver.d;
}

/* debug accessors for the shim */
u32 rfu_get(int what) {
  switch (what) {
  case 0: return rfu_comstate;
  case 1: return rfu_state;
  case 2: return rfu_host.devid;
  case 3: return rfu_client.devid;
  case 4: return rfu_client.qlen;
  case 5: return rfu_host.clients[0].qlen;
  case 6: return rfu_host.clients[0].devid;
  case 7: return rfu_timeout | (rfu_rtx_max << 8);
  case 8: return rfu_stat_polls;
  case 9: return rfu_stat_xfers;
  case 10: return rfu_host.clients[0].clttl;
  case 11: return rfu_trimmed;
  }
  return 0;
}
