diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index a02faa4..b49ec72 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -45,14 +45,16 @@ jobs:
grep -q "RCM Payload Emulator" out.txt \
|| { echo "banner missing - binary did not start"; exit 1; }
- - name: CCPLEX, SE and display regression tests
+ - name: CCPLEX, SE, USB and display regression tests
# Small self-contained payloads. One boots CPU0 through bdk's
# ccplex_boot_cpu0() register sequence: an unpowered release must be
# refused, a powered one must run an AArch64 blob at EL3, and WFE must
# park the core. One runs the Security Engine's RSA, SHA-256, AES and
- # RNG against vectors computed in Python. The others drive the
- # display controller and VIC in six scenarios, and the frame the
- # emulator shows must match the picture drawn, pixel for pixel.
+ # RNG against vectors computed in Python. One brings up USB gadgets on
+ # both device controllers for the --usb-host PC to enumerate and read
+ # back. The others drive the display controller and VIC in six
+ # scenarios, and the frame the emulator shows must match the picture
+ # drawn, pixel for pixel.
run: make test
- name: hwtest end to end
@@ -71,6 +73,7 @@ jobs:
path: |
tests/ccplex/out.log
tests/se/out.log
+ tests/usb/out_*.log
tests/hwtest/out.log
if-no-files-found: ignore
diff --git a/.gitignore b/.gitignore
index 0c77899..2803d36 100644
--- a/.gitignore
+++ b/.gitignore
@@ -10,6 +10,7 @@ last_fb.rgba
last_fb.meta
last_fb*.png
out.log
+out_*.log
out*.txt
emu_run*.log
emu_capture*.txt
diff --git a/DESIGN.md b/DESIGN.md
index d3739b5..61fa119 100644
--- a/DESIGN.md
+++ b/DESIGN.md
@@ -28,6 +28,7 @@ flowchart TB
mmio --> dc["DC + VIC (inline)
window registers A-D
VIC compose, flip/transpose"]
mmio --> stubs["inline stubs
GPIO, PMC, TSEC, KFUSE,
PWM, CLK, TMR, FUSE, UART"]
mmio --> pcie["pcie
AFI, root ports, CYW4356
(CPU-complex master only)"]
+ mmio --> usb["usb
USB2 + XUSB device controllers
and the --usb-host PC"]
cfg -.->|writes atomics| state["EmuState
(emu_state.h)"]
con -.->|RX inject / TX log| state
@@ -529,6 +530,62 @@ All TX append / RX pop is single-threaded -- both the CPU emulation and ImGui
rendering run on the main thread between SDL polls -- so no locking is
needed. The 64 KB TX log trim happens in-place during the write hook.
+### USB device mode (`t210/usb.cpp`)
+
+bdk runs its gadgets - Nyx's USB mass storage for the SD card, eMMC and
+emuMMC, and its Joy-Con gamepad - on one of two device controllers, and both
+are modelled:
+
+- **Erista: the USB2 controller USB1** (0x7D000000, bdk `usbd.c`), an
+ EHCI-derived device controller. Each endpoint half has a 64-byte queue
+ head at `ENDPOINTLISTADDR` (bdk keeps them in the controller's own memory
+ at +0x1000) and a chain of transfer descriptors in DRAM. `ENDPTPRIME`
+ loads the first descriptor and sets its bit in `ENDPTSTATUS` until the
+ transfer retires; each descriptor it reaches is written back with the
+ bytes it did not move, and the endpoint's bit set in `ENDPTCOMPLETE`. A
+ SETUP lands in queue head 0 with `ENDPTSETUPSTAT` bit 0. `USBCMD.RESET`
+ resets the controller and clears itself; `PHY_CLK_VALID` follows the
+ UTMI PHY's enable and reset. bdk copies SETUP packets out with `memcpy()`,
+ so byte and halfword accesses are handled.
+- **Mariko: the XUSB device controller** (0x700D0000, bdk `xusbd.c`), the
+ device side of xHCI. Endpoints are device context indexes (0 control, 2
+ bulk OUT, 3 bulk IN), each with a context (the dequeue pointer and DCS in
+ word 2) and a ring of TRBs the driver fills and closes with a Link TRB,
+ ringing the doorbell. The controller posts events on a two-segment event
+ ring, flipping its cycle bit per pass and raising `ST.IP`: a Port Status
+ Change on a bus reset, a Setup event with a sequence number per SETUP, a
+ Transfer event with the residue and SUCCESS or SHORT_PKT per TRB.
+ `EP_HALT` halts an endpoint (`EP_STCHG` reports it), `EP_RELOAD` reloads a
+ context, and a `PORTSC` write with LWS and RxDetect arms the port.
+
+**The host.** `--usb-host` (or `[usb] host`, or the config window's USB
+device mode box) plugs in a PC; without it nothing is on the cable and a
+gadget waits for a connection until it gives up, as with no cable. The host
+sees whichever controller attaches, waits out the attach debounce, resets
+the bus at high speed and enumerates: device descriptor, `SET_ADDRESS` (with
+its 2 ms recovery), configuration, strings, `SET_CONFIGURATION`. It then gives
+the class driver 100 ms to bind, as a PC does - bdk's XUSB driver stalls a
+`GET_MAX_LUN` that arrives before the gadget asks for it - and runs the
+class:
+
+- *Mass storage (Bulk-Only Transport):* `GET_MAX_LUN`, INQUIRY, TEST UNIT
+ READY (answering the first unit attention with REQUEST SENSE), READ
+ CAPACITY, READ(10) of the first 64 and the last 8 blocks, each logged with
+ its CRC32 and checked against the SD image when the disk is its size; then
+ PREVENT ALLOW MEDIUM REMOVAL, an eject (START STOP UNIT, LoEj) and TEST
+ UNIT READY every 500 ms until the gadget detaches, as Linux does. It only
+ reads.
+- *HID:* the report descriptor, `SET_IDLE` with an idle rate of 0 (report on
+ change), then the interrupt IN endpoint is polled. Nyx's gamepad has
+ nothing to report without Joy-Cons.
+
+The host advances on every access to either controller - it runs as far as
+the device and the emulated clock allow - so it needs no thread or main-loop
+hook and runs repeat exactly. It logs `[usb-host]` lines; `RCM_USB_TRACE=1`
+also logs each transfer descriptor, TRB and doorbell. Nyx's SD card mass
+storage reads back identical to the image and reports "Disk ejected" on
+both SoCs.
+
### Other peripherals (mostly stubs)
- **CAR and MC.** Registers without behaviour of their own read back what
@@ -722,8 +779,11 @@ emulated second.
refusal, the EL3 entry, a core released with its clock stopped, the
mailbox, WFE parking and the reset;
`tests/se/`, which runs the SE's RSA, SHA-256, AES and RNG against vectors
-computed in Python (`gen_vectors.py` writes `vectors.h`); and
-`tests/display/`, one payload built per scenario that drives the display
+computed in Python (`gen_vectors.py` writes `vectors.h`); `tests/usb/`, a
+mass storage gadget over a RAM disk on each device controller and a HID
+gadget, which the `--usb-host` PC must enumerate, read back (the CRC32s it
+logs match the payload's) and see detach, plus a run with nothing on the
+cable; and `tests/display/`, one payload built per scenario that drives the display
controller and VIC the way bdk does (a pitch window; Nyx's VIC turn into
pitch and into block-linear surfaces; a block-linear VIC source; the DC's
own column scan with an address offset; a mirrored window with window D
@@ -747,6 +807,10 @@ don't repeat the diagnosis:
real console's value taken after a payload had brought the display up, so
`display_init()` found DISP1 already clocked at RCM entry. Fix: the bank
starts at the TRM reset value and follows the payload's writes.
+- **Every USB gadget failed to start.** The USB controllers were plain
+ register caches, so `USBCMD.RESET` never cleared and bdk's
+ `usb_device_init()` timed out; Nyx's USB tools could not even wait for a
+ cable. Fix: both device controllers are modelled, with a PC to plug in.
- **Minerva hung Nyx** (hekate 6.5.3 with the stock `bootloader/` folder
never reached its GUI). The emulator planted hekate's "watchdog fired"
cookie in IRAM so the IPL would skip Minerva; Nyx then trained the DRAM
diff --git a/Makefile b/Makefile
index f05f547..d5bae68 100644
--- a/Makefile
+++ b/Makefile
@@ -102,6 +102,12 @@ tests/se/payload.bin: tests/se/payload.c tests/se/vectors.h tests/se/link.ld
$(TEST_CC) $(TEST_CFLAGS) -T tests/se/link.ld -o tests/se/payload.elf $<
$(TEST_OBJCOPY) -O binary tests/se/payload.elf $@
+USB_PAYLOADS = tests/usb/payload_1.bin tests/usb/payload_2.bin tests/usb/payload_3.bin
+
+tests/usb/payload_%.bin: tests/usb/payload.c tests/usb/link.ld
+ $(TEST_CC) $(TEST_CFLAGS) -DSCENARIO=$* -T tests/usb/link.ld -o tests/usb/payload_$*.elf $<
+ $(TEST_OBJCOPY) -O binary tests/usb/payload_$*.elf $@
+
DISPLAY_SCENARIOS = 1 2 3 4 5 6
DISPLAY_PAYLOADS = $(DISPLAY_SCENARIOS:%=tests/display/payload_%.bin)
@@ -109,14 +115,16 @@ tests/display/payload_%.bin: tests/display/payload.c tests/display/link.ld
$(TEST_CC) $(TEST_CFLAGS) -DSCENARIO=$* -T tests/display/link.ld -o tests/display/payload_$*.elf $<
$(TEST_OBJCOPY) -O binary tests/display/payload_$*.elf $@
-test: $(OUTPUT) tests/ccplex/payload.bin tests/se/payload.bin $(DISPLAY_PAYLOADS)
+test: $(OUTPUT) tests/ccplex/payload.bin tests/se/payload.bin $(USB_PAYLOADS) $(DISPLAY_PAYLOADS)
sh tests/ccplex/run.sh ./$(OUTPUT) tests/ccplex/payload.bin
sh tests/se/run.sh ./$(OUTPUT) tests/se/payload.bin
+ sh tests/usb/run.sh ./$(OUTPUT) tests/usb
sh tests/display/run.sh ./$(OUTPUT) tests/display
clean:
rm -f $(OUTPUT) $(OBJS) $(OBJS:.o=.d) \
tests/ccplex/payload.elf tests/ccplex/payload.bin tests/ccplex/out.log \
tests/se/payload.elf tests/se/payload.bin tests/se/out.log \
+ tests/usb/payload_*.elf tests/usb/payload_*.bin tests/usb/out_*.log \
tests/display/payload_*.elf tests/display/payload_*.bin \
$(WIN_OUT) $(WIN_OBJS) $(WIN_OBJS:.o=.d)
diff --git a/README.md b/README.md
index 7f3a85d..c5fc673 100644
--- a/README.md
+++ b/README.md
@@ -30,8 +30,12 @@ slow or destructive.
`--auto-te-script`, so a payload flow can be exercised from a CI run or a
one-shot script. `--input-script` scripts buttons and touchscreen taps for
any payload.
+- Plug an emulated PC into the USB-C port (`--usb-host`): Nyx's USB mass
+ storage and gamepad gadgets enumerate on both the Erista (USB2) and Mariko
+ (XUSB) device controllers, and the PC reads a mass storage disk back,
+ checks it against the SD image and ejects it.
- Tweak emulated hardware live (battery, charger, thermal, USB-PD, PMIC,
- fuses, SD insertion) from a side window. See [Live hardware tweaks](#live-hardware-tweaks).
+ fuses, SD insertion, the USB host) from a side window. See [Live hardware tweaks](#live-hardware-tweaks).
- Inspect each Tegra UART port (TX history) and inject keystrokes into the
payload's RX FIFO from a separate console window. See [UART console](#uart-console).
- Read real eMMC (embedded MMC) dumps (`BOOT0`, multi-part `rawnand.bin.NN`)
@@ -177,15 +181,20 @@ real consoles. Details in [DESIGN.md](DESIGN.md#ccplex-cpu0).
## Tests
```bash
-make test # CCPLEX, SE + display regression payloads (arm-none-eabi-gcc, python3)
+make test # CCPLEX, SE, USB + display regression payloads (arm-none-eabi-gcc, python3)
tests/hwtest/build.sh build-hwtest # build hwtest-rcm (+ gcc-aarch64-linux-gnu)
tests/hwtest/run.sh ./rcm_emu build-hwtest/hwtest-rcm/build/hwtest.bin
```
-The first boots CPU0 from a small self-contained payload and checks the
-refusal of an unpowered release, the EL3 entry, the mailbox, WFE parking and
-the reset. The second runs hwtest-rcm's whole hardware sweep headless and
-checks that the CPU0-driven Wi-Fi probe enumerates the endpoint. CI runs both.
+`make test` runs small self-contained payloads: one boots CPU0 and checks the
+refusal of an unpowered release, the EL3 entry, the mailbox, a stopped clock,
+WFE parking and the reset; one checks the Security Engine's RSA, SHA-256, AES
+and RNG against vectors computed in Python; one brings up a USB mass storage
+gadget on each device controller (and a HID gadget) for the `--usb-host` PC to
+enumerate and read back; one drives the display controller and VIC and
+compares the frame pixel for pixel. The hwtest scripts run hwtest-rcm's whole
+hardware sweep headless and check that the CPU0-driven Wi-Fi probe enumerates
+the endpoint. CI runs both.
## Live hardware tweaks
@@ -279,6 +288,7 @@ needed.
| `--oem` | `erista` \| `mariko` | Switch SoC generation. Drives `APB_MISC_GP_HIDREV` so Hekate's `h_cfg.t210b01` matches and pkg1 identification skips the right OEM header. Default `erista`. |
| `--bt-radio` | `healthy` \| `faulty` \| `absent` | Broadcom CYW4356 behaviour on UART-D. `healthy` powers up on the `BT_REG_ON` edge, holds `BT_HOST_WAKE` high, asserts `RTS_N` and answers HCI; `faulty` reproduces the 2110-1118 console (module fitted, never leaves POR); `absent` additionally leaves `BT_UART_RXD` in a break condition. Overrides `[bluetooth] radio` in the ini. Default `healthy`. |
| `--wifi-radio` | `healthy` \| `faulty` \| `absent` | The WLAN half of the same CYW4356: a PCI Express endpoint on root port 1, reachable only from CPU0 (the BPMP reads all ones, as on silicon). `healthy` trains the link, enumerates as `14E4:43EC` and answers a ChipCommon ChipID read with `0x4356`; `faulty` still trains and enumerates but reads all ones on the backplane (live PCIe front-end, dead radio die); `absent` never leaves detect. The model also enforces the datasheet's power-up ordering, so a payload that releases PERST# too early gets a link that stays down and a `[pcie]` line naming the reason. Overrides `[wifi] radio` in the ini. Default `healthy`. |
+| `--usb-host` | (none) | A PC on the USB-C port. It enumerates whatever USB gadget the payload brings up; a mass storage disk is read back (checked against the SD image), then ejected, and HID reports are polled. Logged as `[usb-host]`; `RCM_USB_TRACE=1` traces every transfer. Overrides `[usb] host` in the ini. |
| `--input-script` | file or spec | Scripted input keyed to emulated time: ` P\|U\|D [hold_ms]` presses POWER / VOL+ / VOL-, ` TAP [hold_ms]` taps the touchscreen at (x, y) in the 1280x720 picture, `+N` times an event N ms after the previous one. Events are separated by `,`, `;` or newlines. |
| `--auto-pin-recovery` | (none) | Drive the Lockpick PIN-recovery menu without user input. |
| `--auto-te-script` | (none) | Drive `recover_pin.te` in TegraExplorer without input. |
@@ -291,13 +301,14 @@ flowchart LR
root --> top["main.cpp
emu_state.h
Makefile
Dockerfile
README.md / DESIGN.md"]
root --> t210["t210/
(SoC peripheral models)"]
root --> display["display/"]
- root --> tests["tests/
ccplex/, se/, display/, hwtest/"]
+ root --> tests["tests/
ccplex/, se/, usb/, display/, hwtest/"]
t210 --> mmio["mmio.{h,cpp}
memory_map.h
regcache.h, tegra_bl.h"]
t210 --> cpus["bpmp.{h,cpp} BPMP clock
ccplex.{h,cpp} CPU0 (A57)"]
t210 --> pcie["pcie.{h,cpp}
root complex + CYW4356"]
t210 --> se["se_engine.{h,cpp}
AES-128, SHA-256, RSA, RNG"]
t210 --> i2c["i2c3.{h,cpp}
STMFTS / FTS4 touch"]
+ t210 --> usb["usb.{h,cpp}
USB device controllers + host PC"]
display --> sdl["sdl_display.{h,cpp}
DC window scan-out
+ SDL2"]
```
@@ -321,6 +332,9 @@ For implementation details, see [DESIGN.md](DESIGN.md).
seed, so runs repeat.
- **Single-threaded.** Both cores run in batches on the main thread between
SDL event polls. That is also what keeps them deterministic.
+- **The USB host is scripted.** `--usb-host` runs a fixed session - enumerate,
+ read back, eject - rather than bridging the gadget to the machine running
+ the emulator, so the disk cannot be mounted on it.
## Acknowledgements
diff --git a/display/config_window.cpp b/display/config_window.cpp
index fc61d34..0b60b06 100644
--- a/display/config_window.cpp
+++ b/display/config_window.cpp
@@ -138,6 +138,7 @@ void reset_to_defaults(EmuState *s) {
X(usb_pd_inserted, "usb_pd", "inserted", 0) \
X(usb_pd_voltage_mv, "usb_pd", "voltage_mv", 0) \
X(usb_pd_amperage_ma, "usb_pd", "amperage_ma", 0) \
+ X(usb_host, "usb", "host", 0) \
/* SoC / PMIC */ \
X(pmic_otp, "soc", "pmic_otp", 0) \
X(is_mariko, "soc", "is_mariko", 0) \
@@ -645,6 +646,15 @@ void build_ui(EmuState *state) {
atomic_slider_int("PDO amperage (mA)", state->usb_pd_amperage_ma, 500, 3000, "%d mA");
}
+ if (ImGui::CollapsingHeader("USB device mode")) {
+ // The PC in t210/usb.cpp: it enumerates a gadget the payload brings up.
+ bool host = state->usb_host.load();
+ if (ImGui::Checkbox("PC on the USB-C port (--usb-host)", &host)) {
+ state->usb_host.store(host);
+ }
+ ImGui::TextDisabled("Mass storage is read back and ejected; HID is polled.");
+ }
+
if (ImGui::CollapsingHeader("Display")) {
int bl = (int)state->backlight;
if (ImGui::SliderInt("Backlight", &bl, 0, 255)) {
diff --git a/emu_state.h b/emu_state.h
index 14fba46..9a2c63d 100644
--- a/emu_state.h
+++ b/emu_state.h
@@ -320,6 +320,10 @@ struct EmuState {
// SD card insertion (GPIO Port Z bit 1 = 0 means inserted).
std::atomic sd_inserted{true};
+ // A PC on the USB-C port (--usb-host): it enumerates whatever gadget the
+ // payload brings up (t210/usb.cpp). Off, nothing is on the cable.
+ std::atomic usb_host{false};
+
// SD card identity (returned for SDMMC1 CMD2 ALL_SEND_CID).
// Hekate parses these out of the R2 response per bdk/storage/sdmmc.c
// _sd_storage_parse_cid; the I2C handler builds the 16-byte CID payload
diff --git a/main.cpp b/main.cpp
index c51f905..5fa8a7a 100644
--- a/main.cpp
+++ b/main.cpp
@@ -356,6 +356,11 @@ int main(int argc, char *argv[]) {
fprintf(stderr, "[emu] Unknown --bt-radio value '%s'; expected"
" 'healthy', 'faulty' or 'absent'\n", mode);
}
+ } else if (strcmp(argv[i], "--usb-host") == 0) {
+ // A PC on the USB-C port: it enumerates whatever gadget the
+ // payload brings up and, for mass storage, reads it back.
+ state.usb_host = true;
+ printf("[emu] USB host connected [overrides ini]\n");
} else if (strcmp(argv[i], "--wifi-radio") == 0 && i + 1 < argc) {
// WLAN half of the same package, on PCIe. 'faulty' means
// something different here from the Bluetooth side: the link
diff --git a/platform.h b/platform.h
index d80eb2e..4df407d 100644
--- a/platform.h
+++ b/platform.h
@@ -36,6 +36,26 @@ static inline int64_t file_size64(int fd) {
#endif
}
+// pread/pwrite are POSIX and MinGW does not have them. Seek-then-read is
+// equivalent here: the emulated storage is touched only from the CPU thread,
+// so the atomicity real pread() buys against a shared file offset is not in
+// play.
+#ifdef _WIN32
+#include
+static inline ssize_t pread(int fd, void *buf, size_t n, long long off) {
+ if (_lseeki64(fd, off, SEEK_SET) < 0)
+ return -1;
+ return _read(fd, buf, (unsigned int)n);
+}
+static inline ssize_t pwrite(int fd, const void *buf, size_t n, long long off) {
+ if (_lseeki64(fd, off, SEEK_SET) < 0)
+ return -1;
+ return _write(fd, buf, (unsigned int)n);
+}
+#else
+#include
+#endif
+
// Large zero-filled memory that only becomes resident where it is touched
// (platform.cpp). zeroed_reset() makes all of it zero again, at the same
// address, without touching it.
diff --git a/t210/memory_map.h b/t210/memory_map.h
index 3d12bab..927be60 100644
--- a/t210/memory_map.h
+++ b/t210/memory_map.h
@@ -193,6 +193,16 @@ constexpr uint64_t SE_SIZE = 0x2000;
constexpr uint64_t MSELECT_BASE = 0x50060000;
constexpr uint64_t MSELECT_SIZE = 0x1000;
+// USB2 controller USB1 ("OTG"): the device controller bdk's usbd.c drives on
+// Erista. Registers, the UTMI PHY at +0x400/+0x800, queue heads at +0x1000.
+constexpr uint64_t USB_OTG_BASE = 0x7D000000;
+constexpr uint64_t USB_OTG_SIZE = 0x4000;
+
+// XUSB device controller: bdk's xusbd.c on Mariko. XHCI registers, then its
+// PCI configuration space at +0x8000 and device registers at +0x9000.
+constexpr uint64_t XUSB_DEV_BASE = 0x700D0000;
+constexpr uint64_t XUSB_DEV_SIZE = 0xA000;
+
// XUSB pad controller. Owns the UPHY SERDES lanes shared by PCIe (pcie-0..4)
// and USB 3.0 SuperSpeed (pcie-5/6 on this board), plus UPHY PLL P0.
constexpr uint64_t XUSB_PADCTL_BASE = 0x7009F000;
diff --git a/t210/mmio.cpp b/t210/mmio.cpp
index d244bda..72c6d02 100644
--- a/t210/mmio.cpp
+++ b/t210/mmio.cpp
@@ -8,6 +8,7 @@
#include "bpmp.h"
#include "ccplex.h"
#include "pcie.h"
+#include "usb.h"
#include "regcache.h"
#include "se_engine.h"
#include "tegra_bl.h"
@@ -24,26 +25,6 @@
#include
#include
-// pread/pwrite are POSIX and MinGW does not have them, so the SD/eMMC image
-// access below would not compile for Windows. Seek-then-read is equivalent
-// here: the emulated storage is touched only from the CPU thread, so the
-// atomicity real pread() buys against a shared file offset is not in play.
-// Kept next to the includes rather than in a header because these four call
-// sites are the only users in the tree.
-#ifdef _WIN32
-#include
-static inline ssize_t pread(int fd, void *buf, size_t n, long long off) {
- if (_lseeki64(fd, off, SEEK_SET) < 0)
- return -1;
- return _read(fd, buf, (unsigned int)n);
-}
-static inline ssize_t pwrite(int fd, const void *buf, size_t n, long long off) {
- if (_lseeki64(fd, off, SEEK_SET) < 0)
- return -1;
- return _write(fd, buf, (unsigned int)n);
-}
-#endif
-
#define BIT(n) (1U << (n))
static RegCache mmio_regs;
@@ -4618,6 +4599,10 @@ uint32_t mmio_bus_read(EmuState *state, uint64_t address, unsigned size) {
if (address >= XUSB_PADCTL_BASE &&
address < XUSB_PADCTL_BASE + XUSB_PADCTL_SIZE)
return padctl_read(state, address);
+ if (address >= USB_OTG_BASE && address < USB_OTG_BASE + USB_OTG_SIZE)
+ return usb2d_read(state, address, size);
+ if (address >= XUSB_DEV_BASE && address < XUSB_DEV_BASE + XUSB_DEV_SIZE)
+ return xusbd_read(state, address, size);
if (address >= MSELECT_BASE && address < MSELECT_BASE + MSELECT_SIZE)
return mselect_read(state, address);
if (address >= VIC_BASE && address < VIC_BASE + VIC_SIZE)
@@ -4777,6 +4762,10 @@ void mmio_bus_write(EmuState *state, uint64_t address, unsigned size,
} else if (address >= XUSB_PADCTL_BASE &&
address < XUSB_PADCTL_BASE + XUSB_PADCTL_SIZE) {
padctl_write(state, address, val);
+ } else if (address >= USB_OTG_BASE && address < USB_OTG_BASE + USB_OTG_SIZE) {
+ usb2d_write(state, address, size, val);
+ } else if (address >= XUSB_DEV_BASE && address < XUSB_DEV_BASE + XUSB_DEV_SIZE) {
+ xusbd_write(state, address, size, val);
} else if (address >= MSELECT_BASE && address < MSELECT_BASE + MSELECT_SIZE) {
mselect_write(state, address, val);
} else if ((address >= SDMMC1_BASE && address < SDMMC1_BASE + 0x200) ||
@@ -4947,6 +4936,8 @@ const struct {
{SYSCTR0_BASE, SYSCTR0_SIZE},
{BPMP_CACHE_BASE, BPMP_CACHE_SIZE},
{XUSB_PADCTL_BASE, XUSB_PADCTL_SIZE},
+ {USB_OTG_BASE, USB_OTG_SIZE},
+ {XUSB_DEV_BASE, XUSB_DEV_SIZE},
{MSELECT_BASE, MSELECT_SIZE},
// PCIe. T210 puts the root complex at the BOTTOM of the address map,
// below every other peripheral.
@@ -5056,6 +5047,7 @@ void mmio_soft_reset(EmuState *state, bool power_cycle) {
pcie_reset(state);
se_engine_reset();
i2c3_reset(state);
+ usb_reset(state);
mmio_regs.clear();
for (auto &u : uart_ports)
diff --git a/t210/usb.cpp b/t210/usb.cpp
new file mode 100644
index 0000000..6a80d47
--- /dev/null
+++ b/t210/usb.cpp
@@ -0,0 +1,1464 @@
+// USB device mode, and the PC on the other end of the cable.
+//
+// bdk runs its gadgets (mass storage, HID) on one of two device controllers:
+// the USB2 controller USB1 ("OTG", 0x7D000000) on Erista - bdk usbd.c, an
+// EHCI-style device controller - and the XUSB device controller on Mariko
+// (xusbd.c). A controller model implements UsbDc, which is all the host sees
+// of it: attach, bus reset, SETUP packets, and data IN or OUT of an endpoint.
+//
+// The host plays the PC. It is plugged in with --usb-host (or [usb] host in
+// the ini); without it nothing is on the cable, and a gadget waits for a
+// connection the way it does on a console with no cable. Once the device
+// attaches, the host resets the bus, enumerates, sets the configuration and
+// runs the class:
+//
+// mass storage GET_MAX_LUN, then over Bulk-Only Transport INQUIRY, TEST
+// UNIT READY, READ CAPACITY and two READ(10)s (the first 64
+// sectors and the last 8), checked against the SD image when
+// the capacity matches it; then it allows medium removal,
+// ejects (START STOP UNIT, LoEj) and polls TEST UNIT READY
+// until the gadget lets go, as Linux does
+// HID the report descriptor, SET_IDLE, then interrupt IN reports
+//
+// Everything is logged as [usb-host]. The host only reads: nothing is ever
+// written to the storage a gadget exports.
+//
+// The host advances whenever the payload touches the controller - every
+// register access runs it as far as the device and the emulated clock allow
+// - so it needs no thread and no main-loop hook, and runs are reproducible.
+
+#include "usb.h"
+
+#include
+#include
+#include
+#include
+#include
+#include
+
+#include
+
+#include "../emu_state.h"
+#include "../platform.h"
+#include "memory_map.h"
+
+namespace {
+
+// ---- What the host sees of a device controller ------------------------------
+
+// Transfer results: bytes moved, or one of these.
+constexpr int XFER_NAK = -1; // endpoint not ready; try again later
+constexpr int XFER_STALL = -2; // endpoint halted
+
+struct UsbDc {
+ virtual ~UsbDc() = default;
+ virtual bool attached() = 0; // pull-up on, controller running
+ virtual void bus_reset() = 0; // reset, then high speed
+ virtual bool reset_taken() = 0; // the device handled the reset
+ virtual void setup(const uint8_t pkt[8]) = 0;
+ virtual bool setup_taken() = 0; // the device read the SETUP
+ // Data from IN endpoint `ep` into buf, at most max bytes. *short_pkt: the
+ // device sent less than max, which ends a data stage.
+ virtual int in(int ep, uint8_t *buf, int max, bool *short_pkt) = 0;
+ // Data to OUT endpoint `ep`. Returns what the device accepted.
+ virtual int out(int ep, const uint8_t *buf, int len) = 0;
+ virtual uint32_t address() = 0; // the USB address the device set
+ virtual void detach() = 0; // the host saw the device go
+};
+
+EmuState *g_state = nullptr;
+
+// RCM_USB_TRACE=1 logs every transfer, event and doorbell.
+bool trace_on() {
+ static int on = -1;
+ if (on < 0) {
+ const char *e = getenv("RCM_USB_TRACE");
+ on = e && *e && *e != '0';
+ }
+ return on;
+}
+#define UTRACE(...) \
+ do { \
+ if (trace_on()) \
+ printf("[usb-trace] " __VA_ARGS__); \
+ } while (0)
+
+uint64_t now_us() { return g_state ? g_state->emu_usec : 0; }
+
+bool mem_read(uint64_t addr, void *buf, size_t n) {
+ return g_state && g_state->uc &&
+ uc_mem_read(g_state->uc, addr, buf, n) == UC_ERR_OK;
+}
+
+bool mem_write(uint64_t addr, const void *buf, size_t n) {
+ return g_state && g_state->uc &&
+ uc_mem_write(g_state->uc, addr, buf, n) == UC_ERR_OK;
+}
+
+// ---- The host ---------------------------------------------------------------
+
+constexpr uint64_t kDebounceUs = 100000; // USB 2.0 7.1.7.3: attach debounce
+constexpr uint64_t kRecoveryUs = 10000; // reset recovery
+constexpr uint64_t kSetAddrUs = 2000; // USB 2.0 9.2.6.3: SET_ADDRESS recovery
+// Between SET_CONFIGURATION and the first class request a PC binds its
+// class driver; bdk's XUSB driver stalls GET_MAX_LUN until the gadget has
+// come back from enumeration and asked for it, so an instant one fails.
+constexpr uint64_t kBindUs = 100000;
+constexpr uint64_t kTimeoutUs = 5000000;
+constexpr uint64_t kEjectPollUs = 500000;
+
+struct Endpoint {
+ uint8_t addr = 0, attr = 0, interval = 0;
+ uint16_t max_packet = 0;
+};
+
+// One control transfer: SETUP, an optional data stage, the status stage.
+struct Control {
+ enum Stage { SETUP, DATA, STATUS, DONE } stage = DONE;
+ uint8_t pkt[8] = {};
+ bool dir_in = false;
+ uint16_t len = 0;
+ std::vector data; // IN: what came back; OUT: what to send
+ size_t moved = 0;
+ bool stalled = false;
+};
+
+// One Bulk-Only Transport command: CBW, an optional data phase, CSW.
+struct Bot {
+ enum Phase { CBW, DATA, CSW, DONE } phase = DONE;
+ uint8_t cbw[31] = {};
+ bool dir_in = true;
+ uint32_t len = 0;
+ std::vector data;
+ uint8_t csw[13] = {};
+ size_t moved = 0;
+ bool stalled = false;
+};
+
+enum class Step {
+ Unplugged, WaitAttach, Debounce, WaitReset, Recover,
+ GetDevice8, SetAddress, AddrRecovery, GetDevice, GetConfig9, GetConfig,
+ GetLangs, GetVendor, GetProduct, GetSerial, SetConfig, Bind,
+ MscMaxLun, MscInquiry, MscTur, MscSense, MscCapacity, MscReadFirst, MscReadLast,
+ MscAllow, MscEject, MscAfterEject, MscEjectWait,
+ HidReport, HidIdle, HidPoll,
+ Idle, Failed,
+};
+
+class Host {
+public:
+ // Both device controllers; the host talks to whichever one attaches.
+ void set_controllers(UsbDc *a, UsbDc *b) {
+ dcs_[0] = a;
+ dcs_[1] = b;
+ }
+
+ void run() {
+ if (!g_state || !dcs_[0])
+ return;
+ bool plugged = g_state->usb_host.load();
+ if (!plugged) {
+ if (step_ != Step::Unplugged) {
+ if (dc_)
+ dc_->detach();
+ step_ = Step::Unplugged;
+ printf("[usb-host] unplugged\n");
+ }
+ return;
+ }
+ if (step_ == Step::Unplugged)
+ step_ = Step::WaitAttach;
+ if (step_ == Step::WaitAttach) {
+ dc_ = nullptr;
+ for (UsbDc *dc : dcs_)
+ if (dc && dc->attached())
+ dc_ = dc;
+ if (!dc_)
+ return;
+ }
+ // A device that goes away (controller stopped or reset) ends the session;
+ // the next attach starts a new one.
+ if (step_ != Step::WaitAttach && !dc_->attached()) {
+ printf("[usb-host] device detached\n");
+ dc_->detach();
+ step_ = Step::WaitAttach;
+ ctl_.stage = Control::DONE;
+ bot_.phase = Bot::DONE;
+ }
+ // Several steps can complete in one call; stop once one has to wait.
+ for (int guard = 0; guard < 64; guard++) {
+ Step before = step_;
+ tick();
+ if (step_ == before && !progressed_)
+ break;
+ progressed_ = false;
+ }
+ }
+
+ void reset() {
+ step_ = Step::Unplugged;
+ ctl_ = Control();
+ bot_ = Bot();
+ }
+
+private:
+ UsbDc *dcs_[2] = {};
+ UsbDc *dc_ = nullptr;
+ Step step_ = Step::Unplugged;
+ bool progressed_ = false;
+ uint64_t wait_until_ = 0, deadline_ = 0;
+ Control ctl_;
+ Bot bot_;
+
+ // What enumeration found.
+ std::vector dev_, cfg_;
+ uint8_t ep0_max_ = 64, cfg_value_ = 1, iface_ = 0;
+ uint8_t iface_class_ = 0, iface_sub_ = 0, iface_proto_ = 0;
+ uint16_t hid_report_len_ = 0;
+ Endpoint bulk_in_, bulk_out_, intr_in_;
+ std::string vendor_, product_, serial_;
+
+ // Mass storage.
+ uint32_t tag_ = 0, blocks_ = 0, block_len_ = 0;
+ int tur_tries_ = 0;
+ uint64_t eject_deadline_ = 0;
+ int reports_ = 0;
+
+ void go(Step s) {
+ step_ = s;
+ progressed_ = true;
+ }
+
+ void fail(const char *what) {
+ printf("[usb-host] %s - giving up on this device\n", what);
+ go(Step::Failed);
+ }
+
+ // ---- Control transfers ----
+
+ void control(uint8_t bm, uint8_t req, uint16_t val, uint16_t idx,
+ uint16_t len, const std::vector &out = {}) {
+ ctl_ = Control();
+ ctl_.pkt[0] = bm;
+ ctl_.pkt[1] = req;
+ ctl_.pkt[2] = val & 0xFF;
+ ctl_.pkt[3] = val >> 8;
+ ctl_.pkt[4] = idx & 0xFF;
+ ctl_.pkt[5] = idx >> 8;
+ ctl_.pkt[6] = len & 0xFF;
+ ctl_.pkt[7] = len >> 8;
+ ctl_.dir_in = bm & 0x80;
+ ctl_.len = len;
+ ctl_.data = ctl_.dir_in ? std::vector(len) : out;
+ ctl_.stage = Control::SETUP;
+ deadline_ = now_us() + kTimeoutUs;
+ dc_->setup(ctl_.pkt);
+ }
+
+ // True once the transfer is over (done or stalled); false while waiting.
+ bool control_poll() {
+ Control &c = ctl_;
+ for (;;) {
+ switch (c.stage) {
+ case Control::SETUP:
+ if (!dc_->setup_taken())
+ return false;
+ c.stage = c.len ? Control::DATA : Control::STATUS;
+ break;
+ case Control::DATA: {
+ int n;
+ bool short_pkt = false;
+ if (c.dir_in)
+ n = dc_->in(0, c.data.data() + c.moved, (int)(c.len - c.moved),
+ &short_pkt);
+ else
+ n = dc_->out(0, c.data.data() + c.moved, (int)(c.len - c.moved));
+ if (n == XFER_STALL) {
+ c.stalled = true;
+ c.stage = Control::DONE;
+ return true;
+ }
+ if (n == XFER_NAK)
+ return false;
+ c.moved += n;
+ if (c.moved >= c.len || short_pkt) {
+ c.data.resize(c.moved);
+ c.stage = Control::STATUS;
+ }
+ break;
+ }
+ case Control::STATUS: {
+ // The status stage runs the other way: a zero-length OUT after an
+ // IN data stage, a zero-length IN otherwise.
+ int n;
+ bool short_pkt = false;
+ uint8_t none = 0;
+ if (c.dir_in && c.len)
+ n = dc_->out(0, nullptr, 0);
+ else
+ n = dc_->in(0, &none, 0, &short_pkt);
+ if (n == XFER_STALL)
+ c.stalled = true;
+ else if (n == XFER_NAK)
+ return false;
+ c.stage = Control::DONE;
+ return true;
+ }
+ case Control::DONE:
+ return true;
+ }
+ }
+ }
+
+ // ---- Bulk-Only Transport ----
+
+ void bot(const uint8_t *cdb, int cdb_len, bool dir_in, uint32_t len) {
+ bot_ = Bot();
+ uint8_t *w = bot_.cbw;
+ uint32_t tag = ++tag_;
+ memcpy(w, "USBC", 4);
+ memcpy(w + 4, &tag, 4);
+ memcpy(w + 8, &len, 4);
+ w[12] = dir_in ? 0x80 : 0x00;
+ w[13] = 0; // LUN 0
+ w[14] = (uint8_t)cdb_len;
+ memcpy(w + 15, cdb, cdb_len);
+ bot_.dir_in = dir_in;
+ bot_.len = len;
+ bot_.data.resize(len);
+ bot_.phase = Bot::CBW;
+ deadline_ = now_us() + kTimeoutUs;
+ }
+
+ // True once the command is over; false while waiting.
+ bool bot_poll() {
+ Bot &b = bot_;
+ int out_ep = bulk_out_.addr & 0xF, in_ep = bulk_in_.addr & 0xF;
+ for (;;) {
+ switch (b.phase) {
+ case Bot::CBW: {
+ int n = dc_->out(out_ep, b.cbw + b.moved, (int)(31 - b.moved));
+ if (n == XFER_STALL) {
+ b.stalled = true;
+ b.phase = Bot::DONE;
+ return true;
+ }
+ if (n == XFER_NAK)
+ return false;
+ b.moved += n;
+ if (b.moved == 31) {
+ b.moved = 0;
+ b.phase = b.len ? Bot::DATA : Bot::CSW;
+ }
+ break;
+ }
+ case Bot::DATA: {
+ bool short_pkt = false;
+ int n = b.dir_in
+ ? dc_->in(in_ep, b.data.data() + b.moved, (int)(b.len - b.moved),
+ &short_pkt)
+ : dc_->out(out_ep, b.data.data() + b.moved, (int)(b.len - b.moved));
+ if (n == XFER_STALL) {
+ // A halted data phase is still followed by the CSW.
+ b.stalled = true;
+ b.phase = Bot::CSW;
+ break;
+ }
+ if (n == XFER_NAK)
+ return false;
+ b.moved += n;
+ if (b.moved >= b.len || short_pkt) {
+ b.data.resize(b.moved);
+ b.moved = 0;
+ b.phase = Bot::CSW;
+ }
+ break;
+ }
+ case Bot::CSW: {
+ bool short_pkt = false;
+ int n = dc_->in(in_ep, b.csw + b.moved, (int)(13 - b.moved), &short_pkt);
+ if (n == 0 && b.moved == 0)
+ return false; // a zero-length packet ending the data
+ if (n == XFER_STALL) {
+ b.stalled = true;
+ b.phase = Bot::DONE;
+ return true;
+ }
+ if (n == XFER_NAK)
+ return false;
+ b.moved += n;
+ if (b.moved >= 13 || short_pkt) {
+ b.phase = Bot::DONE;
+ return true;
+ }
+ break;
+ }
+ case Bot::DONE:
+ return true;
+ }
+ }
+ }
+
+ // The CSW's status byte, or -1 if it is not a valid CSW for this command.
+ int bot_status() const {
+ uint32_t tag;
+ memcpy(&tag, bot_.csw + 4, 4);
+ if (memcmp(bot_.csw, "USBS", 4) != 0 || tag != tag_)
+ return -1;
+ return bot_.csw[12];
+ }
+
+ // ---- Descriptors ----
+
+ static std::string string_desc(const std::vector &d) {
+ std::string s;
+ for (size_t i = 2; i + 1 < d.size() && i < d[0]; i += 2)
+ s += (d[i] >= 0x20 && d[i] < 0x7F && !d[i + 1]) ? (char)d[i] : '?';
+ return s;
+ }
+
+ void parse_config() {
+ iface_class_ = iface_sub_ = iface_proto_ = 0;
+ bulk_in_ = bulk_out_ = intr_in_ = Endpoint();
+ hid_report_len_ = 0;
+ if (cfg_.size() >= 9)
+ cfg_value_ = cfg_[5];
+ bool first_iface = true;
+ for (size_t i = 0; i + 2 <= cfg_.size() && cfg_[i] >= 2;
+ i += cfg_[i]) {
+ const uint8_t *d = &cfg_[i];
+ size_t n = std::min(d[0], cfg_.size() - i);
+ if (d[1] == 4 && n >= 9) { // interface
+ if (!first_iface)
+ break; // the first interface is enough
+ first_iface = false;
+ iface_ = d[2];
+ iface_class_ = d[5];
+ iface_sub_ = d[6];
+ iface_proto_ = d[7];
+ } else if (d[1] == 0x21 && n >= 9) { // HID descriptor
+ hid_report_len_ = d[7] | d[8] << 8;
+ } else if (d[1] == 5 && n >= 7) { // endpoint
+ Endpoint e;
+ e.addr = d[2];
+ e.attr = d[3];
+ e.max_packet = d[4] | d[5] << 8;
+ e.interval = d[6];
+ int type = e.attr & 3;
+ if (type == 2 && (e.addr & 0x80))
+ bulk_in_ = e;
+ else if (type == 2)
+ bulk_out_ = e;
+ else if (type == 3 && (e.addr & 0x80))
+ intr_in_ = e;
+ }
+ }
+ }
+
+ const char *class_name() const {
+ if (iface_class_ == 0x08 && iface_proto_ == 0x50)
+ return "mass storage, bulk-only";
+ if (iface_class_ == 0x03)
+ return "HID";
+ return "a class this host does not drive";
+ }
+
+ // ---- Mass storage checks ----
+
+ // Compare what was read with the SD image, when the disk is the size of it.
+ const char *compare_sd(uint32_t lba, const std::vector &got) {
+ if (!g_state || g_state->sd_fd < 0)
+ return "no SD image to compare with";
+ int64_t size = file_size64(g_state->sd_fd);
+ if (size / 512 != (int64_t)blocks_ + 1)
+ return "not the SD image's size, not compared";
+ std::vector want(got.size());
+ if (pread(g_state->sd_fd, want.data(), want.size(),
+ (long long)lba * 512) != (ssize_t)want.size())
+ return "SD image unreadable";
+ return memcmp(want.data(), got.data(), got.size()) == 0
+ ? "matches the SD image"
+ : "DIFFERS from the SD image";
+ }
+
+ static uint32_t crc32(const std::vector &d) {
+ uint32_t c = 0xFFFFFFFF;
+ for (uint8_t b : d) {
+ c ^= b;
+ for (int k = 0; k < 8; k++)
+ c = (c >> 1) ^ (0xEDB88320u & (0u - (c & 1)));
+ }
+ return ~c;
+ }
+
+ static uint32_t be32(const uint8_t *p) {
+ return (uint32_t)p[0] << 24 | p[1] << 16 | p[2] << 8 | p[3];
+ }
+
+ void read10(uint32_t lba, uint16_t count) {
+ uint8_t cdb[10] = {0x28, 0, (uint8_t)(lba >> 24), (uint8_t)(lba >> 16),
+ (uint8_t)(lba >> 8), (uint8_t)lba, 0,
+ (uint8_t)(count >> 8), (uint8_t)count, 0};
+ bot(cdb, 10, true, (uint32_t)count * block_len_);
+ }
+
+ // A BOT command finished: false (and the session failed) if it did not end
+ // with a good CSW.
+ bool bot_ok(const char *what) {
+ int st = bot_status();
+ if (bot_.stalled || st != 0) {
+ printf("[usb-host] %s: %s\n", what,
+ st < 0 ? "no valid CSW" : bot_.stalled ? "stalled" : "failed");
+ fail("mass storage command failed");
+ return false;
+ }
+ return true;
+ }
+
+ // ---- The session ----
+
+ void tick() {
+ switch (step_) {
+ case Step::Unplugged:
+ case Step::Idle:
+ case Step::Failed:
+ return;
+
+ case Step::WaitAttach:
+ if (!dc_->attached())
+ return;
+ printf("[usb-host] device attached\n");
+ wait_until_ = now_us() + kDebounceUs;
+ go(Step::Debounce);
+ return;
+
+ case Step::Debounce:
+ if (now_us() < wait_until_)
+ return;
+ dc_->bus_reset();
+ deadline_ = now_us() + kTimeoutUs;
+ go(Step::WaitReset);
+ return;
+
+ case Step::WaitReset:
+ if (!dc_->reset_taken()) {
+ if (now_us() > deadline_)
+ fail("the device never took the bus reset");
+ return;
+ }
+ wait_until_ = now_us() + kRecoveryUs;
+ go(Step::Recover);
+ return;
+
+ case Step::Recover:
+ if (now_us() < wait_until_)
+ return;
+ control(0x80, 6, 0x0100, 0, 64); // GET_DESCRIPTOR device
+ go(Step::GetDevice8);
+ return;
+
+ case Step::AddrRecovery:
+ if (now_us() < wait_until_)
+ return;
+ control(0x80, 6, 0x0100, 0, 18);
+ go(Step::GetDevice);
+ return;
+
+ case Step::Bind:
+ if (now_us() < wait_until_)
+ return;
+ start_class();
+ return;
+
+ case Step::MscEjectWait: {
+ if (now_us() < wait_until_)
+ return;
+ if (now_us() > deadline_)
+ return fail("the device never let go after the eject");
+ uint8_t cdb[6] = {0x00, 0, 0, 0, 0, 0}; // TEST UNIT READY
+ bot(cdb, 6, false, 0);
+ go(Step::MscAfterEject);
+ return;
+ }
+
+ case Step::HidPoll:
+ finish(); // polls the endpoint itself
+ return;
+
+ default:
+ break;
+ }
+
+ // Everything else waits on a transfer: a BOT command in the mass storage
+ // steps, a control transfer otherwise.
+ bool is_bot = step_ >= Step::MscInquiry && step_ <= Step::MscAfterEject;
+ if (!(is_bot ? bot_poll() : control_poll())) {
+ if (now_us() > deadline_ && step_ != Step::MscAfterEject)
+ fail("transfer timed out");
+ return;
+ }
+ finish();
+ }
+
+ // The class driver binds: its first request.
+ void start_class() {
+ if (iface_class_ == 0x08 && iface_proto_ == 0x50 && bulk_in_.addr &&
+ bulk_out_.addr) {
+ control(0xA1, 0xFE, 0, iface_, 1); // GET_MAX_LUN
+ return go(Step::MscMaxLun);
+ }
+ if (iface_class_ == 0x03 && intr_in_.addr) {
+ control(0x81, 6, 0x2200, iface_, hid_report_len_ ? hid_report_len_ : 256);
+ return go(Step::HidReport);
+ }
+ printf("[usb-host] configured; nothing more to do\n");
+ go(Step::Idle);
+ }
+
+ // The transfer of the current step is over: act on it and start the next.
+ void finish() {
+ switch (step_) {
+ case Step::GetDevice8:
+ if (ctl_.stalled || ctl_.data.size() < 8)
+ return fail("GET_DESCRIPTOR(device) failed");
+ ep0_max_ = ctl_.data[7];
+ control(0x00, 5, 1, 0, 0); // SET_ADDRESS 1
+ return go(Step::SetAddress);
+
+ case Step::SetAddress:
+ if (ctl_.stalled)
+ return fail("SET_ADDRESS stalled");
+ wait_until_ = now_us() + kSetAddrUs;
+ return go(Step::AddrRecovery);
+
+ case Step::GetDevice:
+ if (ctl_.stalled || ctl_.data.size() < 18)
+ return fail("GET_DESCRIPTOR(device) failed");
+ dev_ = ctl_.data;
+ control(0x80, 6, 0x0200, 0, 9); // configuration header
+ return go(Step::GetConfig9);
+
+ case Step::GetConfig9: {
+ if (ctl_.stalled || ctl_.data.size() < 9)
+ return fail("GET_DESCRIPTOR(configuration) failed");
+ uint16_t total = ctl_.data[2] | ctl_.data[3] << 8;
+ control(0x80, 6, 0x0200, 0, total);
+ return go(Step::GetConfig);
+ }
+
+ case Step::GetConfig:
+ if (ctl_.stalled || ctl_.data.size() < 9)
+ return fail("GET_DESCRIPTOR(configuration) failed");
+ cfg_ = ctl_.data;
+ parse_config();
+ control(0x80, 6, 0x0300, 0, 255); // string 0: languages
+ return go(Step::GetLangs);
+
+ case Step::GetLangs:
+ vendor_ = product_ = serial_ = "";
+ if (dev_[14]) {
+ control(0x80, 6, 0x0300 | dev_[14], 0x0409, 255);
+ return go(Step::GetVendor);
+ }
+ [[fallthrough]];
+ case Step::GetVendor:
+ if (step_ == Step::GetVendor && !ctl_.stalled)
+ vendor_ = string_desc(ctl_.data);
+ if (dev_[15]) {
+ control(0x80, 6, 0x0300 | dev_[15], 0x0409, 255);
+ return go(Step::GetProduct);
+ }
+ [[fallthrough]];
+ case Step::GetProduct:
+ if (step_ == Step::GetProduct && !ctl_.stalled)
+ product_ = string_desc(ctl_.data);
+ if (dev_[16]) {
+ control(0x80, 6, 0x0300 | dev_[16], 0x0409, 255);
+ return go(Step::GetSerial);
+ }
+ [[fallthrough]];
+ case Step::GetSerial:
+ if (step_ == Step::GetSerial && !ctl_.stalled)
+ serial_ = string_desc(ctl_.data);
+ printf("[usb-host] high-speed device %04X:%04X \"%s\" \"%s\" serial "
+ "\"%s\", address %u\n",
+ dev_[8] | dev_[9] << 8, dev_[10] | dev_[11] << 8, vendor_.c_str(),
+ product_.c_str(), serial_.c_str(), dc_->address());
+ printf("[usb-host] configuration %u: %s", cfg_value_, class_name());
+ if (bulk_in_.addr)
+ printf(" (EP %02X IN, EP %02X OUT, %u-byte packets)", bulk_in_.addr,
+ bulk_out_.addr, bulk_in_.max_packet);
+ if (intr_in_.addr)
+ printf(" (EP %02X IN, interrupt every %u)", intr_in_.addr,
+ intr_in_.interval);
+ printf("\n");
+ control(0x00, 9, cfg_value_, 0, 0); // SET_CONFIGURATION
+ return go(Step::SetConfig);
+
+ case Step::SetConfig:
+ if (ctl_.stalled)
+ return fail("SET_CONFIGURATION stalled");
+ wait_until_ = now_us() + kBindUs;
+ return go(Step::Bind);
+
+ // ---- Mass storage ----
+
+ case Step::MscMaxLun: {
+ int luns = ctl_.stalled || ctl_.data.empty() ? 1 : ctl_.data[0] + 1;
+ printf("[usb-host] %d LUN%s\n", luns, luns == 1 ? "" : "s");
+ uint8_t cdb[6] = {0x12, 0, 0, 0, 36, 0}; // INQUIRY
+ bot(cdb, 6, true, 36);
+ return go(Step::MscInquiry);
+ }
+
+ case Step::MscInquiry: {
+ if (!bot_ok("INQUIRY"))
+ return;
+ std::string id;
+ for (size_t i = 8; i < 32 && i < bot_.data.size(); i++)
+ id += (bot_.data[i] >= 0x20 && bot_.data[i] < 0x7F) ? (char)bot_.data[i]
+ : ' ';
+ printf("[usb-host] LUN 0: \"%s\"%s\n", id.c_str(),
+ bot_.data.size() > 1 && (bot_.data[1] & 0x80) ? ", removable" : "");
+ uint8_t cdb[6] = {0x00, 0, 0, 0, 0, 0}; // TEST UNIT READY
+ bot(cdb, 6, false, 0);
+ tur_tries_ = 0;
+ return go(Step::MscTur);
+ }
+
+ case Step::MscTur: {
+ // A fresh device answers the first TEST UNIT READY with a unit
+ // attention; ask for the sense data and try again, as a PC does.
+ if (!bot_.stalled && bot_status() == 1 && ++tur_tries_ < 5) {
+ uint8_t cdb[6] = {0x03, 0, 0, 0, 18, 0}; // REQUEST SENSE
+ bot(cdb, 6, true, 18);
+ return go(Step::MscSense);
+ }
+ if (!bot_ok("TEST UNIT READY"))
+ return;
+ uint8_t cdb[10] = {0x25}; // READ CAPACITY(10)
+ bot(cdb, 10, true, 8);
+ return go(Step::MscCapacity);
+ }
+
+ case Step::MscSense: {
+ if (!bot_ok("REQUEST SENSE"))
+ return;
+ if (bot_.data.size() >= 14)
+ printf("[usb-host] TEST UNIT READY: sense key %X, ASC %02X/%02X\n",
+ bot_.data[2] & 0xF, bot_.data[12], bot_.data[13]);
+ uint8_t cdb[6] = {0x00, 0, 0, 0, 0, 0};
+ bot(cdb, 6, false, 0);
+ return go(Step::MscTur);
+ }
+
+ case Step::MscCapacity: {
+ if (!bot_ok("READ CAPACITY"))
+ return;
+ if (bot_.data.size() < 8)
+ return fail("short READ CAPACITY");
+ blocks_ = be32(&bot_.data[0]);
+ block_len_ = be32(&bot_.data[4]);
+ uint64_t bytes = ((uint64_t)blocks_ + 1) * block_len_;
+ printf("[usb-host] %u blocks of %u bytes (%llu MiB)\n", blocks_ + 1,
+ block_len_, (unsigned long long)(bytes >> 20));
+ if (block_len_ != 512 || blocks_ < 72)
+ return fail("unexpected capacity");
+ read10(0, 64);
+ return go(Step::MscReadFirst);
+ }
+
+ case Step::MscReadFirst:
+ if (!bot_ok("READ(10)"))
+ return;
+ printf("[usb-host] read blocks 0-63 (crc32 %08X): %s\n",
+ crc32(bot_.data), compare_sd(0, bot_.data));
+ read10(blocks_ - 7, 8);
+ return go(Step::MscReadLast);
+
+ case Step::MscReadLast: {
+ if (!bot_ok("READ(10)"))
+ return;
+ printf("[usb-host] read blocks %u-%u (crc32 %08X): %s\n", blocks_ - 7,
+ blocks_, crc32(bot_.data), compare_sd(blocks_ - 7, bot_.data));
+ uint8_t cdb[6] = {0x1E, 0, 0, 0, 0, 0}; // PREVENT ALLOW: allow
+ bot(cdb, 6, false, 0);
+ return go(Step::MscAllow);
+ }
+
+ case Step::MscAllow: {
+ if (!bot_ok("PREVENT ALLOW MEDIUM REMOVAL"))
+ return;
+ uint8_t cdb[6] = {0x1B, 0, 0, 0, 0x02, 0}; // START STOP UNIT: eject
+ bot(cdb, 6, false, 0);
+ return go(Step::MscEject);
+ }
+
+ case Step::MscEject: {
+ if (!bot_ok("START STOP UNIT"))
+ return;
+ printf("[usb-host] ejected; polling until the device lets go\n");
+ eject_deadline_ = now_us() + 60000000;
+ wait_until_ = now_us() + kEjectPollUs;
+ deadline_ = eject_deadline_;
+ return go(Step::MscEjectWait);
+ }
+
+ case Step::MscAfterEject:
+ // The gadget now reports the medium gone. Keep asking, as Linux does,
+ // until it detaches; the answer does not matter.
+ wait_until_ = now_us() + kEjectPollUs;
+ deadline_ = eject_deadline_;
+ return go(Step::MscEjectWait);
+
+ // ---- HID ----
+
+ case Step::HidReport:
+ printf("[usb-host] HID report descriptor: %zu bytes%s\n",
+ ctl_.data.size(), ctl_.stalled ? " (stalled)" : "");
+ control(0x21, 0x0A, 0, iface_, 0); // SET_IDLE
+ return go(Step::HidIdle);
+
+ case Step::HidIdle:
+ // Idle rate 0: the device reports only when its input changes.
+ printf("[usb-host] SET_IDLE %s; polling EP %02X for reports\n",
+ ctl_.stalled ? "stalled" : "done", intr_in_.addr);
+ reports_ = 0;
+ deadline_ = now_us() + kTimeoutUs;
+ return go(Step::HidPoll);
+
+ case Step::HidPoll: {
+ uint8_t buf[512];
+ bool short_pkt = false;
+ int n = dc_->in(intr_in_.addr & 0xF, buf,
+ std::min(intr_in_.max_packet, sizeof(buf)),
+ &short_pkt);
+ if (n == XFER_NAK || n == XFER_STALL)
+ return;
+ if (reports_ < 3) {
+ printf("[usb-host] HID report %d:", reports_ + 1);
+ for (int i = 0; i < n && i < 16; i++)
+ printf(" %02X", buf[i]);
+ printf("\n");
+ }
+ if (++reports_ == 3)
+ printf("[usb-host] HID reports arriving; polling on\n");
+ progressed_ = true;
+ return;
+ }
+
+ default:
+ return;
+ }
+ }
+};
+
+Host g_host;
+
+// ---- USB2 device controller (USB1 / OTG, 0x7D000000) ------------------------
+//
+// The EHCI-derived device controller bdk's usbd.c drives (register layout in
+// its usb_t210.h). Endpoint n has an OUT ("RX", bit n) and an IN ("TX", bit
+// 16 + n) half, each with a 64-byte queue head at ENDPOINTLISTADDR + (2n +
+// in) * 64 - bdk keeps them in the controller's own memory at +0x1000 - and
+// a chain of transfer descriptors (dTDs) in DRAM:
+//
+// dTD +0 next dTD (bit 0 terminates)
+// +4 token: bytes left (30:16), IOC (15), ACTIVE (7), HALTED (6)
+// +8 five buffer page pointers
+// dQH +0 capabilities +4 current dTD +8 next dTD +C token
+// +28 the last SETUP packet
+//
+// Priming an endpoint (ENDPTPRIME) loads the first dTD and sets its bit in
+// ENDPTSTATUS until the transfer retires; the host then moves the data
+// through the dTD buffers, writes back what was left in each token, and sets
+// the bit in ENDPTCOMPLETE. A SETUP lands in queue head 0 with ENDPTSETUPSTAT
+// bit 0 set. The rest of the block - the UTMI PHY's registers at 0x400 and
+// 0x800 - reads back what was written, bar PHY_CLK_VALID.
+
+constexpr uint32_t R_USBCMD = 0x130;
+constexpr uint32_t R_USBSTS = 0x134;
+constexpr uint32_t R_DEVICEADDR = 0x144; // PERIODICLISTBASE in device mode
+constexpr uint32_t R_EPLISTADDR = 0x148; // ASYNCLISTADDR in device mode
+constexpr uint32_t R_PORTSC1 = 0x174;
+constexpr uint32_t R_HOSTPC1_DEVLC = 0x1B4;
+constexpr uint32_t R_OTGSC = 0x1F4;
+constexpr uint32_t R_USBMODE = 0x1F8;
+constexpr uint32_t R_SETUPSTAT = 0x208;
+constexpr uint32_t R_PRIME = 0x20C;
+constexpr uint32_t R_FLUSH = 0x210;
+constexpr uint32_t R_STATUS = 0x214;
+constexpr uint32_t R_COMPLETE = 0x218;
+constexpr uint32_t R_EPCTRL0 = 0x21C;
+constexpr uint32_t R_SUSP_CTRL = 0x400;
+
+constexpr uint32_t USBCMD_RUN = 1u << 0, USBCMD_RESET = 1u << 1;
+constexpr uint32_t USBSTS_UI = 1u << 0, USBSTS_PCI = 1u << 2,
+ USBSTS_URI = 1u << 6;
+constexpr uint32_t PORTSC_CCS = 1u << 0, PORTSC_PE = 1u << 2,
+ PORTSC_HSP = 1u << 9;
+constexpr uint32_t DEVLC_PHCD = 1u << 22, DEVLC_PSPD_HS = 2u << 25;
+constexpr uint32_t EPCTRL_RX_STALL = 1u << 0, EPCTRL_RX_RESET = 1u << 6,
+ EPCTRL_RX_ENABLE = 1u << 7, EPCTRL_TX_STALL = 1u << 16,
+ EPCTRL_TX_RESET = 1u << 22, EPCTRL_TX_ENABLE = 1u << 23;
+constexpr uint32_t SUSP_PHY_CLK_VALID = 1u << 7, SUSP_UTMIP_RESET = 1u << 11,
+ SUSP_UTMIP_PHY_ENB = 1u << 12;
+constexpr uint32_t DTD_ACTIVE = 1u << 7, DTD_IOC = 1u << 15;
+
+class Usb2d : public UsbDc {
+public:
+ Usb2d() { reset_controller(); }
+
+ uint32_t read(uint32_t off) {
+ switch (off) {
+ case R_PORTSC1:
+ return connected_ ? (PORTSC_CCS | PORTSC_PE | PORTSC_HSP) : 0;
+ case R_HOSTPC1_DEVLC:
+ return (reg(off) & ~(3u << 25)) | (connected_ ? DEVLC_PSPD_HS : 0);
+ case R_SUSP_CTRL: {
+ uint32_t v = reg(off) & ~SUSP_PHY_CLK_VALID;
+ return phy_valid() ? v | SUSP_PHY_CLK_VALID : v;
+ }
+ default:
+ return reg(off);
+ }
+ }
+
+ void write(uint32_t off, uint32_t val) {
+ switch (off) {
+ case R_USBCMD:
+ if (val & USBCMD_RESET) {
+ reset_controller();
+ return;
+ }
+ reg(off) = val;
+ return;
+ case R_USBSTS:
+ case R_SETUPSTAT:
+ case R_COMPLETE:
+ reg(off) &= ~val; // write 1 to clear
+ return;
+ case R_OTGSC:
+ // Interrupt status (22:16) is write 1 to clear; the rest reads back.
+ reg(off) = (val & ~(0x7Fu << 16)) | (reg(off) & ~val & (0x7Fu << 16));
+ return;
+ case R_PRIME:
+ prime(val);
+ return;
+ case R_FLUSH:
+ reg(R_STATUS) &= ~val;
+ reg(R_PRIME) &= ~val;
+ return;
+ case R_STATUS:
+ case R_PORTSC1:
+ return; // read-only here
+ default:
+ break;
+ }
+ if (off >= R_EPCTRL0 && off < R_EPCTRL0 + 16 * 4) {
+ // The data-toggle resets are strobes; endpoint 0 is always enabled.
+ val &= ~(EPCTRL_RX_RESET | EPCTRL_TX_RESET);
+ if (off == R_EPCTRL0)
+ val |= EPCTRL_RX_ENABLE | EPCTRL_TX_ENABLE;
+ reg(off) = val;
+ return;
+ }
+ if (off < kSize)
+ reg(off) = val;
+ }
+
+ // USBCMD.RESET: the controller's registers (0x000-0x3FF) to their reset
+ // state; the PHY's and the queue head memory are not part of it.
+ void reset_controller() {
+ memset(regs_, 0, 0x400);
+ reg(R_EPCTRL0) = EPCTRL_RX_ENABLE | EPCTRL_TX_ENABLE;
+ connected_ = false;
+ }
+
+ void full_reset() {
+ memset(regs_, 0, sizeof(regs_));
+ reset_controller();
+ }
+
+ // ---- UsbDc ----
+
+ bool attached() override {
+ return (reg(R_USBMODE) & 3) == 2 && (reg(R_USBCMD) & USBCMD_RUN) &&
+ phy_valid() && !(reg(R_HOSTPC1_DEVLC) & DEVLC_PHCD);
+ }
+
+ void bus_reset() override {
+ connected_ = true;
+ reg(R_USBSTS) |= USBSTS_URI | USBSTS_PCI;
+ }
+
+ bool reset_taken() override { return !(reg(R_USBSTS) & USBSTS_URI); }
+
+ void setup(const uint8_t pkt[8]) override {
+ // A SETUP clears a stalled endpoint 0 and whatever was primed on it.
+ reg(R_EPCTRL0) &= ~(EPCTRL_RX_STALL | EPCTRL_TX_STALL);
+ reg(R_STATUS) &= ~(1u | 1u << 16);
+ uint64_t qh = qh_addr(0);
+ qh_write(qh + 0x28, pkt, 8);
+ reg(R_SETUPSTAT) |= 1;
+ reg(R_USBSTS) |= USBSTS_UI;
+ }
+
+ bool setup_taken() override { return !(reg(R_SETUPSTAT) & 1); }
+
+ int in(int ep, uint8_t *buf, int max, bool *short_pkt) override {
+ uint32_t bit = 1u << (16 + ep);
+ if (reg(R_EPCTRL0 + ep * 4) & EPCTRL_TX_STALL)
+ return XFER_STALL;
+ if (!(reg(R_STATUS) & bit))
+ return XFER_NAK;
+ int moved = transfer(2 * ep + 1, buf, max, true);
+ *short_pkt = moved < max;
+ return moved;
+ }
+
+ int out(int ep, const uint8_t *buf, int len) override {
+ uint32_t bit = 1u << ep;
+ if (reg(R_EPCTRL0 + ep * 4) & EPCTRL_RX_STALL)
+ return XFER_STALL;
+ if (!(reg(R_STATUS) & bit))
+ return XFER_NAK;
+ return transfer(2 * ep, const_cast(buf), len, false);
+ }
+
+ uint32_t address() override { return reg(R_DEVICEADDR) >> 25; }
+
+ void detach() override { connected_ = false; }
+
+private:
+ static constexpr uint32_t kSize = 0x4000;
+ uint32_t regs_[kSize / 4] = {};
+ bool connected_ = false;
+
+ uint32_t ®(uint32_t off) { return regs_[(off & (kSize - 1)) / 4]; }
+
+ bool phy_valid() {
+ uint32_t s = reg(R_SUSP_CTRL);
+ return (s & SUSP_UTMIP_PHY_ENB) && !(s & SUSP_UTMIP_RESET);
+ }
+
+ // Queue heads live wherever ENDPOINTLISTADDR points: bdk uses the
+ // controller's own memory, but DRAM works the same way.
+ uint64_t qh_addr(int index) { return (uint64_t)reg(R_EPLISTADDR) + index * 64; }
+
+ bool in_controller(uint64_t a) {
+ return a >= USB_OTG_BASE && a + 4 <= USB_OTG_BASE + kSize;
+ }
+
+ uint32_t qh_read32(uint64_t a) {
+ if (in_controller(a))
+ return reg((uint32_t)(a - USB_OTG_BASE));
+ uint32_t v = 0;
+ mem_read(a, &v, 4);
+ return v;
+ }
+
+ void qh_write32(uint64_t a, uint32_t v) {
+ if (in_controller(a))
+ reg((uint32_t)(a - USB_OTG_BASE)) = v;
+ else
+ mem_write(a, &v, 4);
+ }
+
+ void qh_write(uint64_t a, const uint8_t *p, int n) {
+ for (int i = 0; i < n; i += 4) {
+ uint32_t v = 0;
+ memcpy(&v, p + i, std::min(4, n - i));
+ qh_write32(a + i, v);
+ }
+ }
+
+ void prime(uint32_t mask) {
+ for (int bit = 0; bit < 32; bit++) {
+ if (!(mask & (1u << bit)))
+ continue;
+ int ep = bit & 15, in = bit >> 4;
+ uint64_t qh = qh_addr(2 * ep + in);
+ uint32_t next = qh_read32(qh + 8);
+ if (next & 1)
+ continue; // nothing queued
+ uint32_t dtd = next & ~0x1Fu;
+ uint32_t token = 0;
+ mem_read(dtd + 4, &token, 4);
+ qh_write32(qh + 4, dtd);
+ qh_write32(qh + 0xC, token);
+ reg(R_STATUS) |= 1u << bit;
+ }
+ reg(R_PRIME) = 0; // priming is instant
+ }
+
+ // Move data through the primed dTD chain of queue head `index`: into buf
+ // for an IN endpoint, out of it for OUT. Each dTD it reaches retires with
+ // what it did not move left in its token. The transfer completes on a
+ // short dTD or at the end of the chain; if the data runs out exactly at a
+ // dTD boundary with more dTDs queued, the endpoint stays primed on the
+ // next one. A zero-length transfer retires the first dTD.
+ int transfer(int index, uint8_t *buf, int len, bool to_host) {
+ uint64_t qh = qh_addr(index);
+ uint32_t dtd = qh_read32(qh + 4) & ~0x1Fu;
+ UTRACE("ep %d %s: dTD @%08X, host %s %d bytes\n", index / 2,
+ to_host ? "IN" : "OUT", dtd, to_host ? "takes up to" : "sends", len);
+ int moved = 0;
+ bool ioc = false, primed_on = false;
+ uint32_t last = dtd, last_token = qh_read32(qh + 0xC), next = 1;
+ for (int guard = 0; guard < 64; guard++) {
+ uint32_t d[7] = {};
+ if (!dtd || !mem_read(dtd, d, sizeof(d)) || !(d[1] & DTD_ACTIVE))
+ break;
+ uint32_t size = (d[1] >> 16) & 0x7FFF;
+ uint32_t n = std::min(size, (uint32_t)(len - moved));
+ // Page 0 carries the starting offset; pages 1-4 are 4 KiB frames.
+ uint32_t off0 = d[2] & 0xFFF;
+ for (uint32_t i = 0; i < n;) {
+ uint32_t pos = off0 + i;
+ if ((pos >> 12) > 4)
+ break;
+ uint32_t addr = (d[2 + (pos >> 12)] & ~0xFFFu) | (pos & 0xFFF);
+ uint32_t chunk = std::min(n - i, 0x1000 - (pos & 0xFFF));
+ if (to_host)
+ mem_read(addr, buf + moved + i, chunk);
+ else
+ mem_write(addr, buf + moved + i, chunk);
+ i += chunk;
+ }
+ moved += (int)n;
+ uint32_t token = (d[1] & ~(0x7FFFu << 16) & ~DTD_ACTIVE) |
+ ((size - n) & 0x7FFF) << 16;
+ mem_write(dtd + 4, &token, 4);
+ ioc |= (d[1] & DTD_IOC) != 0;
+ last = dtd;
+ last_token = token;
+ next = d[0];
+ if (n < size || (next & 1))
+ break; // short, or the chain ended
+ dtd = next & ~0x1Fu;
+ if (moved == len) {
+ primed_on = true; // more queued, nothing to give
+ break;
+ }
+ }
+ if (primed_on) {
+ uint32_t token = 0;
+ mem_read(dtd + 4, &token, 4);
+ qh_write32(qh + 4, dtd);
+ qh_write32(qh + 8, dtd);
+ qh_write32(qh + 0xC, token);
+ return moved;
+ }
+ qh_write32(qh + 4, last);
+ qh_write32(qh + 8, next);
+ qh_write32(qh + 0xC, last_token);
+ uint32_t bit = index & 1 ? 1u << (16 + index / 2) : 1u << (index / 2);
+ reg(R_STATUS) &= ~bit;
+ reg(R_COMPLETE) |= bit;
+ if (ioc)
+ reg(R_USBSTS) |= USBSTS_UI;
+ return moved;
+ }
+};
+
+Usb2d g_usb2d;
+
+// ---- XUSB device controller (0x700D0000) ------------------------------------
+//
+// The device side of an xHCI controller, as bdk's xusbd.c drives it on
+// Mariko (register layout in usb_t210.h, TRB and context layouts in xusbd.c).
+// Endpoints are numbered as device context indexes: 0 is the control
+// endpoint, 2 and 3 bulk OUT and IN. Each has a context (16 words at ECP +
+// 64 * index: word 2 holds its transfer ring's dequeue pointer and DCS) and a
+// ring of 16-byte TRBs the driver fills - Data and Status TRBs on the control
+// ring, Normal TRBs on the bulk ones, a Link TRB closing each ring - ringing
+// the doorbell (DB) after each. The controller answers on the event ring: two
+// segments (ERST0/ERST1, sizes in ERSTSZ) it fills at EREP, flipping its
+// cycle bit on each pass, raising ST.IP; the driver consumes up to ERDP. It
+// posts a Port Status Change event on a bus reset, a Setup event for each
+// SETUP (with a sequence number the driver echoes on the doorbell), and a
+// Transfer event, with the bytes left and SUCCESS or SHORT_PKT, for each TRB
+// the host completes. EP_HALT halts endpoints (EP_STCHG reports the change),
+// EP_RELOAD reloads a context. PORTSC's change bits are write 1 to clear, and
+// a write with LWS sets the link state: the driver arms the port by moving it
+// to RxDetect, which is when the host sees it attach.
+
+constexpr uint32_t X_DB = 0x04, X_ERSTSZ = 0x08, X_ERST0 = 0x10, X_ERST1 = 0x18,
+ X_ERDP = 0x20, X_EREP = 0x28, X_CTRL = 0x30, X_ST = 0x34,
+ X_PORTSC = 0x3C, X_ECP = 0x40, X_EP_HALT = 0x50,
+ X_EP_RELOAD = 0x58, X_EP_STCHG = 0x5C, X_EP_STOPPED = 0x78;
+constexpr uint32_t XCTRL_ENABLE = 1u << 31;
+constexpr uint32_t XST_RC = 1u << 0, XST_IP = 1u << 4;
+constexpr uint32_t XPS_CCS = 1u << 0, XPS_PED = 1u << 1, XPS_PR = 1u << 4,
+ XPS_PLS_SHIFT = 5, XPS_PLS_MASK = 0xFu << 5,
+ XPS_PS_HS = 3u << 10, XPS_LWS = 1u << 16,
+ XPS_CHANGE = (1u << 17) | (1u << 19) | (0xFu << 20) |
+ (1u << 23),
+ XPS_CSC = 1u << 17, XPS_PRC = 1u << 21;
+constexpr uint32_t PLS_U0 = 0, PLS_RXDETECT = 5;
+constexpr uint32_t TRB_NORMAL = 1, TRB_DATA = 3, TRB_STATUS = 4, TRB_LINK = 6,
+ TRB_TRANSFER_EV = 32, TRB_PORT_EV = 34, TRB_SETUP_EV = 63;
+constexpr uint32_t COMP_SUCCESS = 1, COMP_SHORT_PKT = 13;
+
+class Xusbd : public UsbDc {
+public:
+ Xusbd() { reset_all(); }
+
+ uint32_t read(uint32_t off) { return reg(off); }
+
+ void write(uint32_t off, uint32_t val) {
+ switch (off) {
+ case X_DB:
+ UTRACE("doorbell %08X\n", val);
+ return; // TRBs are picked up when due
+ case X_ST:
+ reg(off) &= ~(val & (XST_RC | XST_IP));
+ return;
+ case X_PORTSC: {
+ uint32_t v = reg(off) & ~(val & XPS_CHANGE); // write 1 to clear
+ if (val & XPS_LWS) {
+ v = (v & ~XPS_PLS_MASK) | (val & XPS_PLS_MASK);
+ armed_ = ((val & XPS_PLS_MASK) >> XPS_PLS_SHIFT) == PLS_RXDETECT;
+ }
+ reg(off) = v;
+ return;
+ }
+ case X_EP_HALT:
+ reg(X_EP_STCHG) |= reg(off) ^ val; // the halt state changed
+ reg(off) = val;
+ return;
+ case X_EP_STCHG:
+ case X_EP_STOPPED:
+ reg(off) &= ~val;
+ return;
+ case X_EP_RELOAD:
+ for (int i = 0; i < 4; i++)
+ if (val & (1u << i)) {
+ load_ring(i);
+ UTRACE("reload ep %d: ring %08X dcs %u\n", i, rings_[i].deq,
+ rings_[i].dcs);
+ }
+ return; // reads back 0: done
+ case X_ECP:
+ reg(off) = val;
+ load_ring(0); // the control endpoint's context
+ return;
+ case X_EREP:
+ reg(off) = val;
+ enq_ = val & ~0xFu;
+ ecs_ = val & 1;
+ return;
+ default:
+ if (off < kSize)
+ reg(off) = val;
+ return;
+ }
+ }
+
+ void reset_all() {
+ memset(regs_, 0, sizeof(regs_));
+ for (auto &r : rings_)
+ r = Ring();
+ armed_ = connected_ = false;
+ enq_ = 0;
+ ecs_ = 1;
+ seq_ = 0;
+ }
+
+ // ---- UsbDc ----
+
+ bool attached() override { return (reg(X_CTRL) & XCTRL_ENABLE) && armed_; }
+
+ void bus_reset() override {
+ connected_ = true;
+ uint32_t ps = reg(X_PORTSC) & ~(XPS_PLS_MASK | (0xFu << 10) | XPS_PR);
+ reg(X_PORTSC) = ps | XPS_CCS | XPS_PED | XPS_PS_HS |
+ (PLS_U0 << XPS_PLS_SHIFT) | XPS_CSC | XPS_PRC;
+ post_event(0, 0, COMP_SUCCESS << 24, TRB_PORT_EV << 10);
+ }
+
+ bool reset_taken() override {
+ return !(reg(X_PORTSC) & (XPS_CSC | XPS_PRC));
+ }
+
+ void setup(const uint8_t pkt[8]) override {
+ uint32_t lo, hi;
+ memcpy(&lo, pkt, 4);
+ memcpy(&hi, pkt + 4, 4);
+ reg(X_EP_HALT) &= ~1u; // a SETUP clears a stalled EP0
+ post_event(lo, hi, (seq_++ & 0xFFFF) | COMP_SUCCESS << 24,
+ TRB_SETUP_EV << 10);
+ }
+
+ // The Setup event is on the ring; the data and status stages wait on the
+ // TRBs the driver queues in answer.
+ bool setup_taken() override { return true; }
+
+ int in(int ep, uint8_t *buf, int max, bool *short_pkt) override {
+ int n = transfer(ep ? 3 : 0, true, buf, max);
+ if (n >= 0)
+ *short_pkt = n < max;
+ return n;
+ }
+
+ int out(int ep, const uint8_t *buf, int len) override {
+ return transfer(ep ? 2 : 0, false, const_cast(buf), len);
+ }
+
+ uint32_t address() override { return (reg(X_CTRL) >> 24) & 0x7F; }
+
+ void detach() override { connected_ = false; }
+
+private:
+ static constexpr uint32_t kSize = 0xA000; // XHCI regs, then PCI (+0x8000), DEV (+0x9000)
+ uint32_t regs_[kSize / 4] = {};
+ bool armed_ = false, connected_ = false;
+ uint32_t enq_ = 0, ecs_ = 1, seq_ = 0;
+
+ struct Ring {
+ uint32_t deq = 0;
+ uint32_t dcs = 0;
+ bool valid = false;
+ } rings_[4];
+
+ uint32_t ®(uint32_t off) { return regs_[(off % kSize) / 4]; }
+
+ uint32_t ctx_addr(int dci) { return (reg(X_ECP) & ~0xFu) + dci * 64; }
+
+ void load_ring(int dci) {
+ uint32_t w2 = 0;
+ if (!reg(X_ECP) || !mem_read(ctx_addr(dci) + 8, &w2, 4))
+ return;
+ rings_[dci].deq = w2 & ~0xFu;
+ rings_[dci].dcs = w2 & 1;
+ rings_[dci].valid = rings_[dci].deq != 0;
+ }
+
+ // Write an event at the enqueue pointer, with the producer cycle bit.
+ void post_event(uint32_t w0, uint32_t w1, uint32_t w2, uint32_t w3) {
+ if (!enq_)
+ return;
+ uint32_t trb[4] = {w0, w1, w2, (w3 & ~1u) | ecs_};
+ mem_write(enq_, trb, sizeof(trb));
+ uint32_t seg0 = reg(X_ERST0) & ~0xFu, seg1 = reg(X_ERST1) & ~0xFu;
+ uint32_t n0 = reg(X_ERSTSZ) & 0xFFFF, n1 = reg(X_ERSTSZ) >> 16;
+ enq_ += 16;
+ if (enq_ == seg0 + n0 * 16) {
+ enq_ = seg1;
+ } else if (enq_ == seg1 + n1 * 16) {
+ enq_ = seg0;
+ ecs_ ^= 1;
+ }
+ reg(X_EREP) = enq_ | ecs_;
+ reg(X_ST) |= XST_IP;
+ }
+
+ // Complete the TRB at ring `dci`'s dequeue pointer: move data into buf (to
+ // the host) or out of it, post its Transfer event, advance. The TRB has to
+ // match: on the control ring a Data or Status TRB of this direction, on a
+ // bulk ring a Normal TRB.
+ int transfer(int dci, bool to_host, uint8_t *buf, int len) {
+ if (reg(X_EP_HALT) & (1u << dci))
+ return XFER_STALL;
+ Ring &r = rings_[dci];
+ if (!r.valid)
+ return XFER_NAK;
+ uint32_t t[4] = {};
+ for (int guard = 0; guard < 4; guard++) {
+ if (!mem_read(r.deq, t, sizeof(t)) || (t[3] & 1) != r.dcs)
+ return XFER_NAK;
+ if (((t[3] >> 10) & 0x3F) != TRB_LINK)
+ break;
+ if (t[3] & 2) // toggle cycle
+ r.dcs ^= 1;
+ r.deq = t[0] & ~0xFu;
+ }
+ uint32_t type = (t[3] >> 10) & 0x3F;
+ bool dir_in = (t[3] >> 16) & 1;
+ UTRACE("ep %d %s: TRB @%08X type %u dir %u len %u\n", dci,
+ to_host ? "IN" : "OUT", r.deq, type, dir_in, t[2] & 0x1FFFF);
+ if (dci == 0 ? !((type == TRB_DATA || type == TRB_STATUS) && dir_in == to_host)
+ : type != TRB_NORMAL)
+ return XFER_NAK;
+ uint32_t size = type == TRB_STATUS ? 0 : t[2] & 0x1FFFF;
+ uint32_t n = std::min(size, (uint32_t)std::max(len, 0));
+ if (n) {
+ if (to_host)
+ mem_read(t[0], buf, n);
+ else
+ mem_write(t[0], buf, n);
+ }
+ uint32_t left = size - n;
+ post_event(r.deq, 0, left | (left ? COMP_SHORT_PKT : COMP_SUCCESS) << 24,
+ TRB_TRANSFER_EV << 10 | (uint32_t)dci << 16);
+ r.deq += 16;
+ // Keep the context's dequeue pointer current, as the controller does.
+ uint32_t w2 = r.deq | r.dcs;
+ mem_write(ctx_addr(dci) + 8, &w2, 4);
+ return (int)n;
+ }
+};
+
+Xusbd g_xusbd;
+
+} // namespace
+
+// ---- Bus interface ----------------------------------------------------------
+
+// bdk copies SETUP packets out of the queue heads with memcpy() and clears
+// them with memset(), so byte and halfword accesses are real: a narrow read
+// returns its lanes of the word, and a narrow write to the queue head memory
+// merges into it. Registers take a narrow write shifted into place.
+uint32_t usb2d_read(EmuState *state, uint64_t addr, unsigned size) {
+ g_state = state;
+ g_host.set_controllers(&g_usb2d, &g_xusbd);
+ g_host.run();
+ uint32_t off = (uint32_t)(addr - USB_OTG_BASE);
+ uint32_t v = g_usb2d.read(off & ~3u);
+ return size < 4 ? v >> ((off & 3) * 8) : v;
+}
+
+void usb2d_write(EmuState *state, uint64_t addr, unsigned size, uint32_t val) {
+ g_state = state;
+ g_host.set_controllers(&g_usb2d, &g_xusbd);
+ uint32_t off = (uint32_t)(addr - USB_OTG_BASE);
+ if (size < 4) {
+ uint32_t shift = (off & 3) * 8;
+ uint32_t mask = (size == 1 ? 0xFFu : 0xFFFFu) << shift;
+ val = (val << shift) & mask;
+ if (off >= 0x1000)
+ val |= g_usb2d.read(off & ~3u) & ~mask;
+ }
+ g_usb2d.write(off & ~3u, val);
+ g_host.run();
+}
+
+uint32_t xusbd_read(EmuState *state, uint64_t addr, unsigned size) {
+ g_state = state;
+ g_host.set_controllers(&g_usb2d, &g_xusbd);
+ g_host.run();
+ uint32_t off = (uint32_t)(addr - XUSB_DEV_BASE);
+ uint32_t v = g_xusbd.read(off & ~3u);
+ return size < 4 ? v >> ((off & 3) * 8) : v;
+}
+
+void xusbd_write(EmuState *state, uint64_t addr, unsigned size, uint32_t val) {
+ g_state = state;
+ g_host.set_controllers(&g_usb2d, &g_xusbd);
+ uint32_t off = (uint32_t)(addr - XUSB_DEV_BASE);
+ if (size < 4) {
+ uint32_t shift = (off & 3) * 8;
+ uint32_t mask = (size == 1 ? 0xFFu : 0xFFFFu) << shift;
+ val = ((val << shift) & mask) | (g_xusbd.read(off & ~3u) & ~mask);
+ }
+ g_xusbd.write(off & ~3u, val);
+ g_host.run();
+}
+
+void usb_reset(EmuState *state) {
+ g_state = state;
+ g_usb2d.full_reset();
+ g_xusbd.reset_all();
+ g_host.reset();
+}
diff --git a/t210/usb.h b/t210/usb.h
new file mode 100644
index 0000000..112a632
--- /dev/null
+++ b/t210/usb.h
@@ -0,0 +1,18 @@
+#pragma once
+
+#include
+
+struct EmuState;
+
+// USB device mode (see usb.cpp): the Erista USB2 device controller, and the
+// PC a --usb-host run plugs into it.
+uint32_t usb2d_read(EmuState *state, uint64_t addr, unsigned size);
+void usb2d_write(EmuState *state, uint64_t addr, unsigned size, uint32_t val);
+
+// The Mariko XUSB device controller (XHCI registers, PCI config at +0x8000,
+// the device block at +0x9000).
+uint32_t xusbd_read(EmuState *state, uint64_t addr, unsigned size);
+void xusbd_write(EmuState *state, uint64_t addr, unsigned size, uint32_t val);
+
+// SoC reset: the controller back to its reset state, the host unplugged.
+void usb_reset(EmuState *state);
diff --git a/tests/usb/link.ld b/tests/usb/link.ld
new file mode 100644
index 0000000..bdc1203
--- /dev/null
+++ b/tests/usb/link.ld
@@ -0,0 +1,10 @@
+/* Loaded and entered at 0x40010000, like any RCM payload. */
+ENTRY(_start)
+SECTIONS {
+ . = 0x40010000;
+ .text : { KEEP(*(.text.start)) *(.text*) }
+ .rodata : { *(.rodata*) }
+ .data : { *(.data*) }
+ .bss : { *(.bss*) *(COMMON) }
+ /DISCARD/ : { *(.comment) *(.note*) *(.ARM.attributes) *(.ARM.exidx*) }
+}
diff --git a/tests/usb/payload.c b/tests/usb/payload.c
new file mode 100644
index 0000000..bb7d42b
--- /dev/null
+++ b/tests/usb/payload.c
@@ -0,0 +1,613 @@
+/*
+ * USB device mode regression payload.
+ *
+ * A freestanding BPMP payload that brings up a small USB mass storage gadget
+ * - one LUN, a 128-block RAM disk - on one of the two device controllers,
+ * with the register sequences bdk's drivers use, and serves whatever the
+ * emulator's --usb-host PC asks. Built once per scenario with -DSCENARIO=n:
+ *
+ * 1 the USB2 controller USB1 (bdk usbd.c, Erista): queue heads in the
+ * controller at +0x1000, transfer descriptors in DRAM
+ * 2 the XUSB device controller (bdk xusbd.c, Mariko): event ring,
+ * transfer rings and endpoint contexts in IRAM
+ * 3 the USB2 controller again, as a HID gadget: after the report
+ * descriptor and SET_IDLE it sends three interrupt IN reports
+ *
+ * Either way the gadget answers the standard requests and GET_MAX_LUN, then
+ * the Bulk-Only Transport: INQUIRY, TEST UNIT READY, REQUEST SENSE, READ
+ * CAPACITY, READ(10), PREVENT ALLOW MEDIUM REMOVAL and START STOP UNIT. When
+ * the host ejects, it stops the controller and powers off. It prints the
+ * CRC32 of the disk ranges the host reads, which tests/usb/run.sh compares
+ * with what the host logs. Run without --usb-host, scenario 1 sees no bus
+ * reset and says so.
+ */
+
+#ifndef SCENARIO
+#define SCENARIO 1
+#endif
+
+typedef unsigned int u32;
+typedef unsigned short u16;
+typedef unsigned char u8;
+
+#define REG(a) (*(volatile u32 *)(a))
+#define B(a) (*(volatile u8 *)(a))
+
+#define TIMERUS 0x60005010u
+#define UARTB_THR 0x70006040u
+#define I2C5 0x7000D000u
+
+#define DISK 0xC0000000u /* 128 blocks of 512 bytes */
+#define DISK_LBAS 128u
+#define EP0BUF 0xC0110000u
+#define CMDBUF 0xC0111000u /* CBW / CSW / small replies */
+
+static void putc_(char c) { REG(UARTB_THR) = (u32)(unsigned char)c; }
+
+static void puts_(const char *s) {
+ while (*s)
+ putc_(*s++);
+}
+
+static void puthex(u32 v) {
+ for (int i = 28; i >= 0; i -= 4)
+ putc_("0123456789ABCDEF"[(v >> i) & 0xF]);
+}
+
+static void i2c5_write(u32 dev, u32 reg, u32 val) {
+ REG(I2C5 + 0x04) = dev << 1;
+ REG(I2C5 + 0x0C) = reg | (val << 8);
+ REG(I2C5 + 0x00) = (1u << 1) | (1u << 9);
+}
+
+static __attribute__((noreturn)) void finish(const char *msg) {
+ puts_(msg);
+ i2c5_write(0x3C, 0x41, 0x02); /* MAX77620 ONOFFCNFG1: PWR_OFF */
+ for (;;)
+ ;
+}
+
+static void copy(u32 dst, const u8 *src, u32 n) {
+ for (u32 i = 0; i < n; i++)
+ B(dst + i) = src[i];
+}
+
+#if SCENARIO != 3
+static void zero(u32 dst, u32 n) {
+ for (u32 i = 0; i < n; i += 4)
+ REG(dst + i) = 0;
+}
+#endif
+
+static u32 crc32(u32 addr, u32 n) {
+ u32 c = 0xFFFFFFFFu;
+ for (u32 i = 0; i < n; i++) {
+ c ^= B(addr + i);
+ for (int k = 0; k < 8; k++)
+ c = (c >> 1) ^ (0xEDB88320u & (0u - (c & 1)));
+ }
+ return ~c;
+}
+
+/* ---- Descriptors --------------------------------------------------------- */
+
+static const u8 dev_desc[18] = {
+ 18, 1, 0x00, 0x02, 0, 0, 0, 64,
+ 0x09, 0x12, 0x57, 0x7E, /* 1209:7E57 */
+ 0x00, 0x01, 1, 2, 3, 1,
+};
+
+#if SCENARIO == 3
+static const u8 hid_report[21] = {
+ 0x06, 0x00, 0xFF, 0x09, 0x01, 0xA1, 0x01, /* vendor page, application */
+ 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x08,
+ 0x09, 0x01, 0x81, 0x02, 0xC0, /* 8 bytes of input */
+};
+
+static const u8 cfg_desc[34] = {
+ 9, 2, 34, 0, 1, 1, 0, 0x80, 50,
+ 9, 4, 0, 0, 1, 0x03, 0x00, 0x00, 0, /* HID */
+ 9, 0x21, 0x11, 0x01, 0, 1, 0x22, 21, 0, /* HID descriptor */
+ 7, 5, 0x81, 3, 8, 0, 4, /* interrupt IN, 8 bytes */
+};
+#else
+static const u8 cfg_desc[32] = {
+ 9, 2, 32, 0, 1, 1, 0, 0x80, 50,
+ 9, 4, 0, 0, 2, 0x08, 0x06, 0x50, 0, /* mass storage, SCSI, BOT */
+ 7, 5, 0x81, 2, 0x00, 0x02, 0, /* bulk IN, 512 */
+ 7, 5, 0x01, 2, 0x00, 0x02, 0, /* bulk OUT, 512 */
+};
+#endif
+
+static const u8 str_lang[4] = {4, 3, 0x09, 0x04};
+static const char *const strs[3] = {"RCM-Emulator", "USB test disk", "0001"};
+
+#if SCENARIO != 3
+static const u8 inquiry[36] = {
+ 0x00, 0x80, 0x02, 0x02, 31, 0, 0, 0,
+ 'R', 'C', 'M', 'E', 'M', 'U', ' ', ' ',
+ 'T', 'e', 's', 't', ' ', 'd', 'i', 's', 'k', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
+ '1', '.', '0', '0',
+};
+#endif
+
+/* ---- Transport ------------------------------------------------------------ */
+/*
+ * What the gadget needs from a controller:
+ * poll_setup(pkt) a SETUP packet, if one came (1) or not (0)
+ * ep0_in(len) send EP0BUF[0..len), then the status stage
+ * ep0_status() a no-data request's status stage
+ * ep0_stall() reject the request
+ * set_address(a) after its status stage
+ * configure() bring up the bulk endpoints
+ * bulk(in, buf, len) one bulk transfer; returns bytes moved
+ * stop() detach
+ */
+
+#if SCENARIO != 2
+/* ---- USB2 controller USB1 (bdk usbd.c) ---- */
+
+#define USB 0x7D000000u
+#define U(o) REG(USB + (o))
+#define USBCMD 0x130
+#define USBSTS 0x134
+#define DEVADDR 0x144
+#define EPLIST 0x148
+#define USBMODE 0x1F8
+#define SETUPST 0x208
+#define PRIME 0x20C
+#define FLUSH 0x210
+#define STATUS 0x214
+#define COMPL 0x218
+#define EPCTRL(n) (0x21C + 4 * (n))
+#define SUSP 0x400
+#define QHB (USB + 0x1000)
+#define QH(i) (QHB + 64 * (i))
+#define DTD 0xC0100000u /* 4 dTDs per queue head, 32 bytes each */
+
+static void init(void) {
+ U(SUSP) |= (1u << 12) | (1u << 11); /* UTMIP_PHY_ENB, UTMIP_RESET */
+ U(SUSP) &= ~(1u << 11);
+ while (!(U(SUSP) & (1u << 7))) /* PHY_CLK_VALID */
+ ;
+ U(USBCMD) |= 1u << 1; /* RESET */
+ while (U(USBCMD) & (1u << 1))
+ ;
+ U(USBMODE) = 2; /* device */
+ for (u32 i = 0; i < 4; i++) {
+ for (u32 w = 0; w < 16; w++)
+ REG(QH(i) + 4 * w) = 0;
+ REG(QH(i) + 8) = 1; /* no dTD */
+ }
+ REG(QH(0)) = 64u << 16 | 1u << 15; /* EP0 OUT: 64, IOS */
+ REG(QH(1)) = 64u << 16;
+ U(EPLIST) = QHB;
+ U(USBCMD) |= 1; /* RUN: attach */
+}
+
+/* One transfer on queue head idx (2 * ep + in), in up to four 16 KiB dTDs as
+ * bdk builds them. Returns the bytes moved, or -1 if it never completed. */
+static int xfer(u32 idx, u32 buf, u32 len) {
+ u32 base = DTD + idx * 4 * 32, off = 0, n = 0;
+ do {
+ u32 d = base + n * 32, sz = len - off > 16384 ? 16384 : len - off;
+ REG(d) = 1;
+ REG(d + 4) = sz << 16 | 0x80; /* bytes, ACTIVE */
+ for (u32 p = 0; p < 5; p++)
+ REG(d + 8 + 4 * p) = buf ? buf + off + 4096 * p : 0;
+ if (n)
+ REG(base + (n - 1) * 32) = d;
+ off += sz;
+ n++;
+ } while (off < len && n < 4);
+ REG(QH(idx) + 8) = base;
+ REG(QH(idx) + 0xC) = 0;
+ u32 bit = idx & 1 ? 1u << (16 + idx / 2) : 1u << (idx / 2);
+ U(PRIME) = bit;
+ u32 start = REG(TIMERUS);
+ while ((U(PRIME) | U(STATUS)) & bit)
+ if (REG(TIMERUS) - start > 5000000)
+ return -1;
+ U(COMPL) = bit;
+ u32 left = 0;
+ for (u32 i = 0; i < n; i++)
+ left += (REG(base + i * 32 + 4) >> 16) & 0x7FFF;
+ return (int)(len - left);
+}
+
+static int poll_setup(u8 *pkt) {
+ u32 sts = U(USBSTS);
+ U(USBSTS) = sts;
+ if (sts & (1u << 6)) { /* bus reset */
+ U(DEVADDR) = 0;
+ U(SETUPST) = U(SETUPST);
+ U(COMPL) = U(COMPL);
+ U(FLUSH) = 0xFFFFFFFFu;
+ }
+ if (!(U(SETUPST) & 1))
+ return 0;
+ U(SETUPST) = 1;
+ u32 lo = REG(QH(0) + 0x28), hi = REG(QH(0) + 0x2C);
+ for (int i = 0; i < 4; i++) {
+ pkt[i] = lo >> (8 * i);
+ pkt[4 + i] = hi >> (8 * i);
+ }
+ return 1;
+}
+
+static void ep0_in(u32 len) {
+ xfer(1, EP0BUF, len);
+ xfer(0, 0, 0);
+}
+
+static void ep0_status(void) { xfer(1, 0, 0); }
+
+static void ep0_stall(void) { U(EPCTRL(0)) |= 1u | 1u << 16; }
+
+static void set_address(u32 a) { U(DEVADDR) = a << 25; }
+
+static void configure(void) {
+ for (u32 i = 2; i < 4; i++) {
+ for (u32 w = 0; w < 16; w++)
+ REG(QH(i) + 4 * w) = 0;
+ REG(QH(i)) = 512u << 16;
+ REG(QH(i) + 8) = 1;
+ }
+ U(EPCTRL(1)) = 2u << 2 | 1u << 7 | 2u << 18 | 1u << 23; /* bulk RX/TX on */
+}
+
+static int bulk(int in, u32 buf, u32 len) { return xfer(in ? 3 : 2, buf, len); }
+
+static void stop(void) {
+ U(USBCMD) &= ~1u;
+ (void)U(USBCMD); /* let the host see it go */
+}
+
+/* Without a host nothing resets the bus: say so after half a second. */
+static int bus_reset_seen(void) {
+ u32 start = REG(TIMERUS);
+ while (REG(TIMERUS) - start < 500000)
+ if (U(USBSTS) & (1u << 6))
+ return 1;
+ return 0;
+}
+
+#else
+/* ---- XUSB device controller (bdk xusbd.c) ---- */
+
+#define XU 0x700D0000u
+#define X(o) REG(XU + (o))
+#define X_DB 0x04
+#define X_ERSTSZ 0x08
+#define X_ERST0 0x10
+#define X_ERST1 0x18
+#define X_ERDP 0x20
+#define X_EREP 0x28
+#define X_CTRL 0x30
+#define X_ST 0x34
+#define X_IMOD 0x38
+#define X_PORTSC 0x3C
+#define X_ECP 0x40
+#define X_HALT 0x50
+#define X_RELOAD 0x58
+
+#define XMEM 0x40030000u
+#define SEG0 (XMEM)
+#define SEG1 (XMEM + 0x100)
+#define CTX (XMEM + 0x500) /* four 64-byte endpoint contexts */
+
+struct ring { u32 base, idx, pcs; };
+static struct ring rings[4]; /* by context index: 0 control, 2 OUT, 3 IN */
+static u32 evt_deq, ccs, seq;
+
+static void ring_init(u32 dci, u32 base) {
+ struct ring *r = &rings[dci];
+ r->base = base;
+ r->idx = 0;
+ r->pcs = 1;
+ zero(base, 16 * 16);
+ REG(base + 15 * 16) = base; /* Link TRB back to the start */
+ REG(base + 15 * 16 + 12) = 6u << 10 | 2; /* type LINK, toggle cycle */
+ u32 ctx = CTX + 64 * dci;
+ zero(ctx, 64);
+ REG(ctx) = 1; /* EP_RUNNING */
+ REG(ctx + 8) = base | 1; /* dequeue pointer, DCS */
+}
+
+static void queue(u32 dci, u32 w0, u32 w2, u32 w3) {
+ struct ring *r = &rings[dci];
+ u32 t = r->base + r->idx * 16;
+ REG(t) = w0;
+ REG(t + 4) = 0;
+ REG(t + 8) = w2;
+ REG(t + 12) = w3 | r->pcs;
+ if (++r->idx == 15) {
+ REG(r->base + 15 * 16 + 12) = 6u << 10 | 2 | r->pcs;
+ r->idx = 0;
+ r->pcs ^= 1;
+ }
+ X(X_DB) = dci << 8 | (dci ? 0 : seq << 16);
+}
+
+static void init(void) {
+ zero(XMEM, 0x600);
+ X(X_ERST0) = SEG0;
+ X(X_ERST1) = SEG1;
+ X(X_ERSTSZ) = 16u << 16 | 16;
+ X(X_EREP) = SEG0 | 1;
+ X(X_ERDP) = SEG0;
+ evt_deq = SEG0;
+ ccs = 1;
+ ring_init(0, XMEM + 0x200);
+ X(X_CTRL) |= 1u << 4 | 1u << 1; /* IE, LSE */
+ X(X_ECP) = CTX;
+ X(X_IMOD) = 0;
+ X(X_PORTSC) = (X(X_PORTSC) & ~(0xFu << 5)) | 1u << 16 | 5u << 5; /* RxDetect */
+ X(X_CTRL) |= 1u << 31; /* ENABLE */
+}
+
+/* The next event, if any. Polling ST lets the host run. */
+static int next_event(u32 *ev) {
+ (void)X(X_ST);
+ if ((REG(evt_deq + 12) & 1) != ccs)
+ return 0;
+ for (int i = 0; i < 4; i++)
+ ev[i] = REG(evt_deq + 4 * i);
+ if (evt_deq == SEG0 + 15 * 16)
+ evt_deq = SEG1;
+ else if (evt_deq == SEG1 + 15 * 16) {
+ evt_deq = SEG0;
+ ccs ^= 1;
+ } else
+ evt_deq += 16;
+ X(X_ERDP) = evt_deq;
+ X(X_ST) = 1u << 4; /* IP, write 1 to clear */
+ return 1;
+}
+
+static void port_change(void) {
+ u32 ps = X(X_PORTSC);
+ X(X_PORTSC) = ps; /* write the change bits back */
+}
+
+/* Wait for the Transfer event of endpoint dci; the bytes it left over. */
+static int wait_xfer(u32 dci) {
+ u32 ev[4], start = REG(TIMERUS);
+ for (;;) {
+ if (REG(TIMERUS) - start > 5000000)
+ return -1;
+ if (!next_event(ev))
+ continue;
+ u32 type = ev[3] >> 10 & 0x3F;
+ if (type == 34)
+ port_change();
+ else if (type == 32 && (ev[3] >> 16 & 0x1F) == dci)
+ return (int)(ev[2] & 0xFFFFFF);
+ }
+}
+
+static int poll_setup(u8 *pkt) {
+ u32 ev[4];
+ if (!next_event(ev))
+ return 0;
+ u32 type = ev[3] >> 10 & 0x3F;
+ if (type == 34) {
+ port_change();
+ return 0;
+ }
+ if (type != 63)
+ return 0;
+ for (int i = 0; i < 4; i++) {
+ pkt[i] = ev[0] >> (8 * i);
+ pkt[4 + i] = ev[1] >> (8 * i);
+ }
+ seq = ev[2] & 0xFFFF;
+ return 1;
+}
+
+static void ep0_in(u32 len) {
+ queue(0, EP0BUF, len, 3u << 10 | 1u << 16 | 1u << 5); /* Data IN, IOC */
+ wait_xfer(0);
+ queue(0, 0, 0, 4u << 10 | 1u << 5); /* Status OUT */
+ wait_xfer(0);
+}
+
+static void ep0_status(void) {
+ queue(0, 0, 0, 4u << 10 | 1u << 16 | 1u << 5); /* Status IN */
+ wait_xfer(0);
+}
+
+static void ep0_stall(void) { X(X_HALT) |= 1; }
+
+static void set_address(u32 a) { X(X_CTRL) = (X(X_CTRL) & 0x80FFFFFFu) | a << 24; }
+
+static void configure(void) {
+ ring_init(2, XMEM + 0x300);
+ ring_init(3, XMEM + 0x400);
+ X(X_RELOAD) = 0xC;
+ while (X(X_RELOAD) & 0xC)
+ ;
+ X(X_HALT) &= ~0xCu;
+ X(X_CTRL) |= 1; /* RUN */
+}
+
+static int bulk(int in, u32 buf, u32 len) {
+ u32 dci = in ? 3 : 2;
+ queue(dci, buf, len, 1u << 10 | 1u << 5 | 1u << 2); /* Normal, IOC, ISP */
+ int left = wait_xfer(dci);
+ return left < 0 ? -1 : (int)(len - left);
+}
+
+static void stop(void) {
+ X(X_CTRL) = 0;
+ (void)X(X_CTRL);
+}
+
+static int bus_reset_seen(void) { return 1; }
+
+#endif
+
+/* ---- The gadget ----------------------------------------------------------- */
+
+static int configured, lun_asked, report_asked, idle_set;
+
+static void control(const u8 *p) {
+ u32 bm = p[0], req = p[1], val = p[2] | p[3] << 8, len = p[6] | p[7] << 8;
+ u32 n = 0;
+ if (bm == 0x80 && req == 6) { /* GET_DESCRIPTOR */
+ u32 type = val >> 8, idx = val & 0xFF;
+ if (type == 1) {
+ copy(EP0BUF, dev_desc, n = 18);
+ } else if (type == 2) {
+ copy(EP0BUF, cfg_desc, n = sizeof(cfg_desc));
+ } else if (type == 3 && idx == 0) {
+ copy(EP0BUF, str_lang, n = 4);
+ } else if (type == 3 && idx <= 3) {
+ const char *s = strs[idx - 1];
+ n = 2;
+ while (*s) {
+ B(EP0BUF + n) = *s++;
+ B(EP0BUF + n + 1) = 0;
+ n += 2;
+ }
+ B(EP0BUF) = n;
+ B(EP0BUF + 1) = 3;
+ } else {
+ ep0_stall();
+ return;
+ }
+ ep0_in(n < len ? n : len);
+ } else if (bm == 0x00 && req == 5) { /* SET_ADDRESS */
+ ep0_status();
+ set_address(val & 0x7F);
+ } else if (bm == 0x00 && req == 9) { /* SET_CONFIGURATION */
+ configure();
+ ep0_status();
+ configured = 1;
+ puts_("usb test: configured\n");
+ } else if (bm == 0xA1 && req == 0xFE) { /* GET_MAX_LUN */
+ B(EP0BUF) = 0;
+ ep0_in(1);
+ lun_asked = 1;
+#if SCENARIO == 3
+ } else if (bm == 0x81 && req == 6 && (val >> 8) == 0x22) { /* HID report */
+ copy(EP0BUF, hid_report, n = sizeof(hid_report));
+ ep0_in(n < len ? n : len);
+ report_asked = 1;
+ } else if (bm == 0x21 && req == 0x0A) { /* SET_IDLE */
+ ep0_status();
+ idle_set = 1;
+#endif
+ } else {
+ ep0_stall();
+ }
+}
+
+#if SCENARIO != 3
+static void put_be32(u32 a, u32 v) {
+ B(a) = v >> 24;
+ B(a + 1) = v >> 16;
+ B(a + 2) = v >> 8;
+ B(a + 3) = v;
+}
+
+/* Serve Bulk-Only Transport commands until the host ejects the disk. */
+static void bot(void) {
+ u32 sense = 6, asc = 0x29; /* a unit attention first, like a real disk */
+ for (;;) {
+ int n = bulk(0, CMDBUF, 512);
+ if (n != 31 || REG(CMDBUF) != 0x43425355u) /* "USBC" */
+ finish("usb test: FAIL bad CBW\n");
+ u32 tag = REG(CMDBUF + 4), want = REG(CMDBUF + 8);
+ u8 op = B(CMDBUF + 15);
+ u32 cdb = CMDBUF + 15, status = 0, sent = 0, eject = 0;
+ switch (op) {
+ case 0x12: /* INQUIRY */
+ copy(CMDBUF + 0x100, inquiry, 36);
+ sent = bulk(1, CMDBUF + 0x100, want < 36 ? want : 36);
+ break;
+ case 0x00: /* TEST UNIT READY */
+ status = sense ? 1 : 0;
+ break;
+ case 0x03: /* REQUEST SENSE */
+ zero(CMDBUF + 0x100, 20);
+ B(CMDBUF + 0x100) = 0x70;
+ B(CMDBUF + 0x102) = sense;
+ B(CMDBUF + 0x107) = 10;
+ B(CMDBUF + 0x10C) = asc;
+ sense = asc = 0;
+ sent = bulk(1, CMDBUF + 0x100, want < 18 ? want : 18);
+ break;
+ case 0x25: /* READ CAPACITY(10) */
+ put_be32(CMDBUF + 0x100, DISK_LBAS - 1);
+ put_be32(CMDBUF + 0x104, 512);
+ sent = bulk(1, CMDBUF + 0x100, 8);
+ break;
+ case 0x28: { /* READ(10) */
+ u32 lba = (u32)B(cdb + 2) << 24 | B(cdb + 3) << 16 | B(cdb + 4) << 8 |
+ B(cdb + 5);
+ u32 cnt = B(cdb + 7) << 8 | B(cdb + 8);
+ if (lba + cnt > DISK_LBAS)
+ status = 1;
+ else
+ sent = bulk(1, DISK + lba * 512, cnt * 512);
+ break;
+ }
+ case 0x1E: /* PREVENT ALLOW MEDIUM REMOVAL */
+ break;
+ case 0x1B: /* START STOP UNIT */
+ eject = B(cdb + 4) & 2;
+ break;
+ default:
+ status = 1;
+ break;
+ }
+ REG(CMDBUF + 0x200) = 0x53425355u; /* "USBS" */
+ REG(CMDBUF + 0x204) = tag;
+ REG(CMDBUF + 0x208) = want - sent;
+ B(CMDBUF + 0x20C) = status;
+ bulk(1, CMDBUF + 0x200, 13);
+ if (eject)
+ return;
+ }
+}
+#endif
+
+__attribute__((section(".text.start"), noreturn))
+void _start(void) {
+ for (u32 i = 0; i < DISK_LBAS * 512; i++)
+ B(DISK + i) = (u8)((i * 7) ^ (i >> 9));
+ puts_("usb test: disk crc32 first ");
+ puthex(crc32(DISK, 64 * 512));
+ puts_(" last ");
+ puthex(crc32(DISK + (DISK_LBAS - 8) * 512, 8 * 512));
+ putc_('\n');
+
+ init();
+ if (!bus_reset_seen()) {
+ stop();
+ finish("usb test: no bus reset, nothing on the cable\n");
+ }
+ u8 pkt[8];
+ u32 start = REG(TIMERUS);
+ while (!(configured && (SCENARIO == 3 ? report_asked && idle_set : lun_asked))) {
+ if (poll_setup(pkt))
+ control(pkt);
+ if (REG(TIMERUS) - start > 10000000)
+ finish("usb test: FAIL enumeration timed out\n");
+ }
+#if SCENARIO == 3
+ for (u32 k = 1; k <= 3; k++) {
+ for (u32 i = 0; i < 8; i++)
+ B(CMDBUF + i) = (u8)(k * 0x10 + i);
+ if (bulk(1, CMDBUF, 8) != 8)
+ finish("usb test: FAIL report not taken\n");
+ }
+ puts_("usb test: hid reports sent\n");
+#else
+ bot();
+ puts_("usb test: ejected\n");
+#endif
+ stop();
+ finish("usb test: done\n");
+}
diff --git a/tests/usb/run.sh b/tests/usb/run.sh
new file mode 100755
index 0000000..48a1182
--- /dev/null
+++ b/tests/usb/run.sh
@@ -0,0 +1,72 @@
+#!/bin/sh
+# USB device mode regression test: tests/usb/payload.c brings up a mass
+# storage gadget on each device controller and the emulator's --usb-host PC
+# enumerates it, reads it back and ejects it; without a host the gadget must
+# see nothing on the cable. Usage: tests/usb/run.sh [rcm_emu] [payload dir]
+EMU=${1:-./rcm_emu}
+DIR=${2:-tests/usb}
+fail=0
+
+run() {
+ log=$DIR/out_$1.log
+ shift
+ SDL_VIDEODRIVER=dummy RCM_EMU_NO_AUDIO=1 timeout 60 "$EMU" "$@" > "$log" 2>&1
+ echo $?
+}
+
+expect() {
+ if grep -q -- "$2" "$1"; then
+ echo " ok $3"
+ else
+ echo " FAIL $3 (missing: $2)"
+ fail=1
+ fi
+}
+
+check_host() {
+ log=$1
+ name=$2
+ expect "$log" '\[usb-host\] device attached' "$name: the host sees the device attach"
+ expect "$log" 'high-speed device 1209:7E57 "RCM-Emulator" "USB test disk" serial "0001", address 1' \
+ "$name: enumerated, strings read, address set"
+ expect "$log" 'configuration 1: mass storage, bulk-only (EP 81 IN, EP 01 OUT, 512-byte packets)' \
+ "$name: configuration parsed"
+ expect "$log" 'LUN 0: "RCMEMU Test disk ", removable' "$name: INQUIRY"
+ expect "$log" 'TEST UNIT READY: sense key 6, ASC 29/00' "$name: unit attention, then REQUEST SENSE"
+ expect "$log" '128 blocks of 512 bytes' "$name: READ CAPACITY"
+ first=$(sed -n 's/.*disk crc32 first \([0-9A-F]*\) last.*/\1/p' "$log")
+ last=$(sed -n 's/.*disk crc32 first [0-9A-F]* last \([0-9A-F]*\).*/\1/p' "$log")
+ expect "$log" "read blocks 0-63 (crc32 $first)" "$name: READ(10) of blocks 0-63 returns the disk"
+ expect "$log" "read blocks 120-127 (crc32 $last)" "$name: READ(10) of the last 8 blocks returns the disk"
+ expect "$log" 'usb test: ejected' "$name: START STOP UNIT ejects"
+ expect "$log" '\[usb-host\] device detached' "$name: the host sees the device go"
+ expect "$log" 'usb test: done' "$name: the payload ran to its end"
+}
+
+echo "usb test:"
+st=$(run 1 "$DIR/payload_1.bin" --usb-host)
+check_host "$DIR/out_1.log" "USB2 controller"
+[ "$st" -eq 0 ] || { echo " FAIL USB2 controller: emulator exit $st"; fail=1; }
+
+st=$(run 2 "$DIR/payload_2.bin" --usb-host --oem mariko)
+check_host "$DIR/out_2.log" "XUSB controller"
+[ "$st" -eq 0 ] || { echo " FAIL XUSB controller: emulator exit $st"; fail=1; }
+
+st=$(run 3 "$DIR/payload_3.bin" --usb-host)
+log=$DIR/out_3.log
+expect "$log" 'configuration 1: HID (EP 81 IN, interrupt every 4)' "HID gadget: configuration parsed"
+expect "$log" 'HID report descriptor: 21 bytes' "HID gadget: report descriptor read"
+expect "$log" 'SET_IDLE done; polling EP 81 for reports' "HID gadget: SET_IDLE"
+expect "$log" 'HID report 1: 10 11 12 13 14 15 16 17' "HID gadget: first interrupt report"
+expect "$log" 'HID report 3: 30 31 32 33 34 35 36 37' "HID gadget: third interrupt report"
+expect "$log" '\[usb-host\] device detached' "HID gadget: the host sees the device go"
+[ "$st" -eq 0 ] || { echo " FAIL HID gadget: emulator exit $st"; fail=1; }
+
+st=$(run 0 "$DIR/payload_1.bin")
+expect "$DIR/out_0.log" 'usb test: no bus reset, nothing on the cable' "no host: the gadget waits on an empty cable"
+if grep -q '\[usb-host\]' "$DIR/out_0.log"; then
+ echo " FAIL no host: the host logged activity"
+ fail=1
+fi
+
+[ $fail -eq 0 ] && echo "usb test: PASS" || { echo "usb test: FAIL (logs: $DIR/out_*.log)"; exit 1; }