Let the USB host write, and serve a gadget's disk over NBD

The emulated PC only ever read a mass storage disk and then ejected it, so
the write path through a gadget went untested and the disk could not be
used from the machine running the emulator.

The default session now asks MODE SENSE(6) for the write-protect bit and,
on a writable disk whose read checked out, writes the last 8 sectors back
as read (WRITE(10), SYNCHRONIZE CACHE) and reads them again.

--usb-host nbd[:port] (or [usb] nbd_port, or the config window) locks the
medium and serves the disk on 127.0.0.1 with a small non-blocking NBD
server (t210/nbd.cpp: fixed newstyle handshake, READ/WRITE/FLUSH/DISC).
Requests become READ(10)/WRITE(10)s of up to 64 KiB, a quiet client gets
a TEST UNIT READY every second, a write-protected disk is exported
read-only, and when the client disconnects the host ejects the disk.

Serving Nyx exposed a controller model bug: a device transfer shorter than
the host's request was taken as a short packet, so bdk's 64 KiB READ(10),
sent as two 32 KiB transfers, lost the second half. Only a short or
zero-length packet (the USB2 controller's own ZLP unless the queue head
disables it) now ends the host's transfer.

tests/usb grows a write-protected scenario, WRITE(10), MODE SENSE and
SYNCHRONIZE CACHE on its RAM disk (reads sent in 32 KiB transfers, as bdk
does), and three NBD runs driven by a Python client. Checked with Nyx SD
UMS on Erista and Mariko: nbdinfo negotiates, qemu-img convert copies the
256 MiB disk byte for byte, and a qemu-io write lands in the SD image.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YYewwDPujjo5B2xRyC5Grb
This commit is contained in:
Claude committed 2026-09-26 11:09:57 +00:00
1 parent 0c7f12a83b
commit f84caeaacc
13 files changed
+1183 -67

No files matched your search

+4
View File
@@ -323,6 +323,10 @@ struct EmuState {
// 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<bool> usb_host{false};
// --usb-host nbd[:port]: instead of reading a mass storage disk back and
// ejecting it, the host serves it over NBD on 127.0.0.1:port until the
// client disconnects. 0: off.
std::atomic<uint16_t> usb_nbd_port{0};
// SD card identity (returned for SDMMC1 CMD2 ALL_SEND_CID).
// Hekate parses these out of the R2 response per bdk/storage/sdmmc.c