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

+153
View File
@@ -0,0 +1,153 @@
#!/usr/bin/env python3
"""NBD client for tests/usb/run.sh: talks to the disk the emulator's
--usb-host nbd serves and checks what comes back.
Usage: nbd_check.py <port> <log> rw|ro
Waits for the host to say it is serving, negotiates with NBD_OPT_GO, reads
the whole disk (tests/usb/payload.c fills it with a known pattern), checks
that bad requests are refused, then - on a writable disk - writes two
sectors, reads them back and flushes, or - on a write-protected one - checks
that the write is refused. Two reads go out back to back to check that
pipelined requests are answered in turn. Prints the CRC32 the disk should
have once the client is done, then disconnects.
"""
import socket
import struct
import sys
import time
import zlib
NBDMAGIC = 0x4E42444D41474943
IHAVEOPT = 0x49484156454F5054
REPLY_MAGIC = 0x0003E889045565A9
OPT_GO, OPT_LIST = 7, 3
REP_ACK, REP_SERVER, REP_INFO = 1, 2, 3
CMD_READ, CMD_WRITE, CMD_DISC, CMD_FLUSH = 0, 1, 2, 3
FLAG_READ_ONLY, FLAG_SEND_FLUSH = 1 << 1, 1 << 2
EPERM, EINVAL = 1, 22
LBAS = 384
failed = False
def check(ok, what):
global failed
print((" ok " if ok else " FAIL ") + what)
if not ok:
failed = True
def pattern():
return bytes(((i * 7) ^ (i >> 9)) & 0xFF for i in range(LBAS * 512))
def recv_all(s, n):
b = b""
while len(b) < n:
c = s.recv(n - len(b))
if not c:
raise EOFError("server closed the connection")
b += c
return b
def option(s, opt, data=b""):
s.sendall(struct.pack(">QII", IHAVEOPT, opt, len(data)) + data)
replies = []
while True:
magic, ropt, rtype, rlen = struct.unpack(">QIII", recv_all(s, 20))
if magic != REPLY_MAGIC or ropt != opt:
raise ValueError("bad option reply")
replies.append((rtype, recv_all(s, rlen)))
if rtype == REP_ACK or rtype & 0x80000000:
return replies
def request(s, cmd, handle, offset, length, data=b""):
s.sendall(struct.pack(">IHHQQI", 0x25609513, 0, cmd, handle, offset,
length) + data)
def reply(s, want_handle, length=0):
magic, err, handle = struct.unpack(">IIQ", recv_all(s, 16))
if magic != 0x67446698 or handle != want_handle:
raise ValueError("bad reply (magic %08X, handle %d)" % (magic, handle))
return err, (recv_all(s, length) if not err and length else b"")
def main():
port, log, mode = int(sys.argv[1]), sys.argv[2], sys.argv[3]
deadline = time.time() + 60
while "serving the disk over NBD" not in open(log, errors="replace").read():
if time.time() > deadline:
check(False, "the host serves the disk over NBD")
return 1
time.sleep(0.1)
s = socket.create_connection(("127.0.0.1", port), timeout=30)
magic, opt_magic, hflags = struct.unpack(">QQH", recv_all(s, 18))
check(magic == NBDMAGIC and opt_magic == IHAVEOPT and hflags & 1,
"NBD %s: fixed newstyle greeting" % mode)
s.sendall(struct.pack(">I", 3)) # fixed newstyle, no zeroes
listing = option(s, OPT_LIST)
check([r[0] for r in listing] == [REP_SERVER, REP_ACK],
"NBD %s: NBD_OPT_LIST names one export" % mode)
go = option(s, OPT_GO, struct.pack(">IH", 0, 0))
size = flags = None
for rtype, data in go:
if rtype == REP_INFO and struct.unpack(">H", data[:2])[0] == 0:
size, flags = struct.unpack(">QH", data[2:12])
check(go[-1][0] == REP_ACK and size == LBAS * 512,
"NBD %s: NBD_OPT_GO, export of %s bytes" % (mode, size))
check(bool(flags & FLAG_READ_ONLY) == (mode == "ro") and
bool(flags & FLAG_SEND_FLUSH),
"NBD %s: transmission flags %s" % (mode, flags and hex(flags)))
disk = bytearray(pattern())
request(s, CMD_READ, 1, 0, len(disk))
err, data = reply(s, 1, len(disk))
check(err == 0 and data == disk,
"NBD %s: reading the whole disk returns it" % mode)
request(s, CMD_READ, 2, 100, 512)
check(reply(s, 2)[0] == EINVAL, "NBD %s: an unaligned read is refused" % mode)
request(s, CMD_READ, 3, len(disk), 512)
check(reply(s, 3)[0] == EINVAL, "NBD %s: a read past the end is refused" % mode)
new = bytes((i * 13 + 5) & 0xFF for i in range(1024))
request(s, CMD_WRITE, 4, 10 * 512, len(new), new)
err = reply(s, 4)[0]
if mode == "rw":
check(err == 0, "NBD rw: writing blocks 10-11")
disk[10 * 512:12 * 512] = new
else:
check(err == EPERM, "NBD ro: a write is refused")
request(s, CMD_READ, 5, 8 * 512, 4 * 512)
request(s, CMD_READ, 6, (LBAS - 1) * 512, 512)
e5, d5 = reply(s, 5, 4 * 512)
e6, d6 = reply(s, 6, 512)
check(e5 == 0 and d5 == disk[8 * 512:12 * 512] and
e6 == 0 and d6 == disk[(LBAS - 1) * 512:],
"NBD %s: two pipelined reads%s" %
(mode, ", the first seeing the write" if mode == "rw" else ""))
request(s, CMD_FLUSH, 7, 0, 0)
check(reply(s, 7)[0] == 0, "NBD %s: flush" % mode)
request(s, CMD_DISC, 8, 0, 0)
s.close()
print("nbd check: disk crc32 %08X" % (zlib.crc32(disk) & 0xFFFFFFFF))
return 1 if failed else 0
if __name__ == "__main__":
try:
sys.exit(main())
except (OSError, EOFError, ValueError) as e:
print(" FAIL NBD client: %s" % e)
sys.exit(1)
+69 -14
View File
@@ -2,7 +2,7 @@
* 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,
* - one LUN, a 384-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:
*
@@ -12,14 +12,16 @@
* 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
* 4 scenario 1 with the disk write-protected
*
* 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.
* CAPACITY, MODE SENSE(6), READ(10), WRITE(10), SYNCHRONIZE CACHE, 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, and of the whole disk after the eject, which tests/usb/run.sh
* compares with what the host logs and what its NBD client wrote. Run without
* --usb-host, scenario 1 sees no bus reset and says so.
*/
#ifndef SCENARIO
@@ -37,10 +39,12 @@ typedef unsigned char u8;
#define UARTB_THR 0x70006040u
#define I2C5 0x7000D000u
#define DISK 0xC0000000u /* 128 blocks of 512 bytes */
#define DISK_LBAS 128u
#define DISK 0xC0000000u /* 384 blocks of 512 bytes */
#define DISK_LBAS 384u
#define EP0BUF 0xC0110000u
#define CMDBUF 0xC0111000u /* CBW / CSW / small replies */
#define SCRATCH 0xC0120000u /* a rejected WRITE's data */
#define READ_ONLY (SCENARIO == 4)
static void putc_(char c) { REG(UARTB_THR) = (u32)(unsigned char)c; }
@@ -54,6 +58,19 @@ static void puthex(u32 v) {
putc_("0123456789ABCDEF"[(v >> i) & 0xF]);
}
#if SCENARIO != 3
static void putdec(u32 v) {
char b[10];
int n = 0;
do {
b[n++] = (char)('0' + v % 10);
v /= 10;
} while (v);
while (n)
putc_(b[--n]);
}
#endif
static void i2c5_write(u32 dev, u32 reg, u32 val) {
REG(I2C5 + 0x04) = dev << 1;
REG(I2C5 + 0x0C) = reg | (val << 8);
@@ -250,7 +267,7 @@ 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)) = 512u << 16 | 1u << 29; /* 512, no ZLP, as bdk */
REG(QH(i) + 8) = 1;
}
U(EPCTRL(1)) = 2u << 2 | 1u << 7 | 2u << 18 | 1u << 23; /* bulk RX/TX on */
@@ -311,6 +328,7 @@ static void ring_init(u32 dci, u32 base) {
u32 ctx = CTX + 64 * dci;
zero(ctx, 64);
REG(ctx) = 1; /* EP_RUNNING */
REG(ctx + 4) = (dci ? 512u : 64u) << 16; /* max packet size */
REG(ctx + 8) = base | 1; /* dequeue pointer, DCS */
}
@@ -543,16 +561,49 @@ static void bot(void) {
put_be32(CMDBUF + 0x104, 512);
sent = bulk(1, CMDBUF + 0x100, 8);
break;
case 0x28: { /* READ(10) */
case 0x1A: /* MODE SENSE(6) */
zero(CMDBUF + 0x100, 4); /* the header, no pages */
B(CMDBUF + 0x100) = 3;
B(CMDBUF + 0x102) = READ_ONLY ? 0x80 : 0; /* WP */
sent = bulk(1, CMDBUF + 0x100, want < 4 ? want : 4);
break;
case 0x28: /* READ(10) */
case 0x2A: { /* WRITE(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)
int bad = lba + cnt > DISK_LBAS || cnt * 512 != want;
if (op == 0x28) {
/* In 32 KiB transfers, as bdk sends a read: the host has to
* go on to the next one after a full-sized packet. */
if (bad)
status = 1;
for (u32 off = 0; !bad && off < want; off += 32768) {
u32 n = want - off > 32768 ? 32768 : want - off;
if (bulk(1, DISK + lba * 512 + off, n) != (int)n)
break;
sent += n;
}
break;
}
/* The host sends the data whatever happens to it. */
if (bad || READ_ONLY) {
sent = bulk(0, SCRATCH, want);
status = 1;
else
sent = bulk(1, DISK + lba * 512, cnt * 512);
break;
}
sent = bulk(0, DISK + lba * 512, want);
status = sent != want;
puts_("usb test: WRITE(10) blocks ");
putdec(lba);
putc_('-');
putdec(lba + cnt - 1);
putc_('\n');
break;
}
case 0x35: /* SYNCHRONIZE CACHE(10) */
puts_("usb test: SYNCHRONIZE CACHE\n");
break;
case 0x1E: /* PREVENT ALLOW MEDIUM REMOVAL */
break;
case 0x1B: /* START STOP UNIT */
@@ -581,6 +632,8 @@ void _start(void) {
puthex(crc32(DISK, 64 * 512));
puts_(" last ");
puthex(crc32(DISK + (DISK_LBAS - 8) * 512, 8 * 512));
puts_(" all ");
puthex(crc32(DISK, DISK_LBAS * 512));
putc_('\n');
init();
@@ -606,7 +659,9 @@ void _start(void) {
puts_("usb test: hid reports sent\n");
#else
bot();
puts_("usb test: ejected\n");
puts_("usb test: ejected; disk crc32 ");
puthex(crc32(DISK, DISK_LBAS * 512));
putc_('\n');
#endif
stop();
finish("usb test: done\n");
+86 -8
View File
@@ -1,8 +1,11 @@
#!/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]
# enumerates it, reads it back, writes its last sectors back unchanged and
# ejects it; on a write-protected disk it leaves the write out. With
# --usb-host nbd the disk is served over NBD instead, and nbd_check.py reads
# and writes 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
@@ -23,7 +26,19 @@ expect() {
fi
}
check_host() {
expect_not() {
if grep -q -- "$2" "$1"; then
echo " FAIL $3 (found: $2)"
fail=1
else
echo " ok $3"
fi
}
crc() { sed -n "s/.*disk crc32 first [0-9A-F]* last [0-9A-F]* all \([0-9A-F]*\).*/\1/p" "$1"; }
# Enumeration and the reads, the same in every mass storage run.
check_disk() {
log=$1
name=$2
expect "$log" '\[usb-host\] device attached' "$name: the host sees the device attach"
@@ -33,14 +48,64 @@ check_host() {
"$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"
expect "$log" '384 blocks of 512 bytes (192 KiB)' "$name: READ CAPACITY"
}
check_end() {
log=$1
name=$2
want=$3
expect "$log" "usb test: ejected; disk crc32 $want" "$name: START STOP UNIT ejects, the disk as expected"
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"
}
check_host() {
log=$1
name=$2
check_disk "$log" "$name"
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"
expect "$log" "read blocks 376-383 (crc32 $last)" "$name: READ(10) of the last 8 blocks returns the disk"
if [ "$3" = ro ]; then
expect "$log" '\[usb-host\] write-protected' "$name: MODE SENSE reports write protection"
expect "$log" 'write check skipped: the disk is write-protected' "$name: no write to a write-protected disk"
expect_not "$log" 'usb test: WRITE(10)' "$name: the gadget sees no WRITE(10)"
else
expect "$log" '\[usb-host\] writable' "$name: MODE SENSE reports a writable disk"
expect "$log" 'usb test: WRITE(10) blocks 376-383' "$name: WRITE(10) of the last 8 blocks"
expect "$log" 'usb test: SYNCHRONIZE CACHE' "$name: SYNCHRONIZE CACHE"
expect "$log" 'wrote blocks 376-383 back unchanged; read back: the same data' \
"$name: the blocks read back as written"
fi
check_end "$log" "$name" "$(crc "$log")"
}
# --usb-host nbd: nbd_check.py reads, writes (or is refused) and disconnects.
check_nbd() {
n=$1
name=$2
mode=$3
shift 3
port=$((PORT_BASE + n))
log=$DIR/out_nbd$n.log
SDL_VIDEODRIVER=dummy RCM_EMU_NO_AUDIO=1 timeout 60 "$EMU" "$@" --usb-host nbd:$port > "$log" 2>&1 &
emu=$!
python3 "$DIR/nbd_check.py" $port "$log" $mode > "$DIR/out_nbd${n}_client.log" 2>&1
client=$?
wait $emu
st=$?
cat "$DIR/out_nbd${n}_client.log"
[ $client -eq 0 ] || { echo " FAIL $name: NBD client"; fail=1; }
check_disk "$log" "$name"
expect "$log" "serving the disk over NBD at 127.0.0.1:$port" "$name: serving over NBD"
expect "$log" 'NBD client has the disk' "$name: the client negotiated"
expect "$log" 'NBD client disconnected' "$name: the client disconnected"
expect "$log" 'ejecting the disk' "$name: the disk is ejected on disconnect"
want=$(sed -n 's/^nbd check: disk crc32 \([0-9A-F]*\)$/\1/p' "$DIR/out_nbd${n}_client.log")
check_end "$log" "$name" "${want:-none}"
[ "$st" -eq 0 ] || { echo " FAIL $name: emulator exit $st"; fail=1; }
}
echo "usb test:"
@@ -52,6 +117,10 @@ 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 4 "$DIR/payload_4.bin" --usb-host)
check_host "$DIR/out_4.log" "write-protected disk" ro
[ "$st" -eq 0 ] || { echo " FAIL write-protected disk: 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"
@@ -69,4 +138,13 @@ if grep -q '\[usb-host\]' "$DIR/out_0.log"; then
fail=1
fi
if command -v python3 > /dev/null; then
PORT_BASE=${USB_TEST_NBD_PORT:-$((20000 + $$ % 20000))}
check_nbd 1 "NBD, USB2 controller" rw "$DIR/payload_1.bin"
check_nbd 2 "NBD, XUSB controller" rw "$DIR/payload_2.bin" --oem mariko
check_nbd 4 "NBD, write-protected disk" ro "$DIR/payload_4.bin"
else
echo " skip NBD: no python3"
fi
[ $fail -eq 0 ] && echo "usb test: PASS" || { echo "usb test: FAIL (logs: $DIR/out_*.log)"; exit 1; }