mirror of
https://github.com/Creased/RCM-Emulator.git
synced 2026-12-06 02:48:11 +01:00
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:
13 files changed
+1182
-66
No files matched your search
@@ -51,8 +51,9 @@ jobs:
|
||||
# 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. 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
|
||||
# both device controllers for the --usb-host PC to enumerate, read
|
||||
# back and write, and serves the disk over NBD (on a localhost port)
|
||||
# to a Python client. 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
|
||||
|
||||
@@ -570,21 +570,48 @@ 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.
|
||||
CAPACITY, MODE SENSE(6) for the write-protect bit (asking for just the
|
||||
4-byte header: bdk stalls bulk IN on a reply shorter than asked), 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. Unless the disk is
|
||||
write-protected or the read was wrong, the last 8 blocks are written back
|
||||
as read (WRITE(10), SYNCHRONIZE CACHE) and read again. 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.
|
||||
- *Mass storage over NBD* (`--usb-host nbd[:port]`, `[usb] nbd_port`): after
|
||||
MODE SENSE the host sends PREVENT MEDIUM REMOVAL and serves the disk on
|
||||
127.0.0.1 with `t210/nbd.cpp`, a one-client NBD server (fixed newstyle
|
||||
handshake: `EXPORT_NAME`, `LIST`, `INFO` and `GO`, with the export's size,
|
||||
flags and 512-byte minimum block size; simple replies; READ, WRITE, FLUSH,
|
||||
DISC). It is non-blocking and polled from the host every 100 us of
|
||||
emulated time. A READ or WRITE is split into READ(10)s or WRITE(10)s of up
|
||||
to 64 KiB, a FLUSH is a SYNCHRONIZE CACHE, and misaligned or out-of-range
|
||||
requests are refused with `EINVAL` (writes to a write-protected disk with
|
||||
`EPERM`, and the export is read-only). A quiet client gets a TEST UNIT
|
||||
READY every emulated second, as Windows sends. When the client
|
||||
disconnects the host allows removal and ejects as above.
|
||||
- *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.
|
||||
hook and runs repeat exactly (an NBD session aside: its requests come when
|
||||
the client sends them). It logs `[usb-host]` lines; `RCM_USB_TRACE=1` also
|
||||
logs each transfer descriptor, TRB and doorbell.
|
||||
|
||||
A device transfer that retires before the host has all it asked for ends the
|
||||
host's transfer only on a short packet: fewer bytes than a whole number of
|
||||
max-size packets (the queue head or endpoint context gives the size), or a
|
||||
zero-length packet, which the USB2 controller appends unless the queue head
|
||||
disables it (ZLT; bdk disables it on every endpoint) and the XUSB controller
|
||||
never adds. Otherwise the host carries on with the device's next transfer:
|
||||
bdk sends a READ(10) under 512 KiB as 32 KiB transfers.
|
||||
|
||||
Nyx's SD card mass storage reads back identical to the image, takes the
|
||||
write check and reports "Disk ejected" on both SoCs. Over NBD, `nbdinfo`
|
||||
negotiates, `qemu-img convert` copies the whole 256 MiB disk byte for byte,
|
||||
and a `qemu-io` write lands in the SD image.
|
||||
|
||||
### Other peripherals (mostly stubs)
|
||||
|
||||
@@ -780,10 +807,14 @@ 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`); `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
|
||||
mass storage gadget over a RAM disk on each device controller (writable, and
|
||||
write-protected in scenario 4) and a HID gadget, which the `--usb-host` PC
|
||||
must enumerate, read back (the CRC32s it logs match the payload's), write
|
||||
back unchanged unless write-protected and see detach, plus a run with
|
||||
nothing on the cable and three NBD runs where `nbd_check.py` negotiates,
|
||||
reads the disk, is refused a misaligned and an out-of-range read, writes
|
||||
(or is refused on the write-protected disk), pipelines two reads, flushes
|
||||
and disconnects, and the disk's CRC32 after the eject must be the client's; 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
|
||||
@@ -811,6 +842,13 @@ don't repeat the diagnosis:
|
||||
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.
|
||||
- **NBD reads of 64 KiB failed on Nyx.** The host took a device transfer
|
||||
that moved less than it asked for as a short packet, so when bdk sent a
|
||||
64 KiB READ(10) as two 32 KiB transfers the data phase ended after the
|
||||
first and the CSW read found data. Fix: only a transfer whose last packet
|
||||
is short (or zero-length, including the USB2 controller's own ZLP when the
|
||||
queue head allows it) ends the host's transfer; the test payload now sends
|
||||
reads in 32 KiB transfers too.
|
||||
- **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
|
||||
|
||||
@@ -102,7 +102,8 @@ 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
|
||||
USB_PAYLOADS = tests/usb/payload_1.bin tests/usb/payload_2.bin tests/usb/payload_3.bin \
|
||||
tests/usb/payload_4.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 $<
|
||||
|
||||
@@ -33,7 +33,9 @@ slow or destructive.
|
||||
- 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.
|
||||
checks it against the SD image, writes a few sectors back unchanged and
|
||||
ejects it. With `--usb-host nbd` the PC serves the disk over NBD instead,
|
||||
so it can be mounted on the machine running the emulator.
|
||||
- Tweak emulated hardware live (battery, charger, thermal, USB-PD, PMIC,
|
||||
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
|
||||
@@ -191,11 +193,39 @@ 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
|
||||
enumerate, read back and write, and serves it over NBD to a Python client;
|
||||
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.
|
||||
|
||||
## Mounting a gadget's disk
|
||||
|
||||
`--usb-host nbd` turns the emulated PC into a bridge: when a mass storage
|
||||
gadget attaches - Nyx's SD card, eMMC or emuMMC under USB tools - the PC
|
||||
locks the medium (PREVENT MEDIUM REMOVAL, so Nyx will not unload it from its
|
||||
side) and serves it with the NBD protocol on 127.0.0.1, port 10809 or the one
|
||||
given as `nbd:<port>`. Every NBD read, write and flush becomes SCSI
|
||||
commands to the gadget, so what reaches the SD image goes through bdk's UMS
|
||||
code as it would from a real PC. A write-protected disk (Nyx's eMMC in its
|
||||
default read-only mode) is exported read-only.
|
||||
|
||||
```sh
|
||||
./rcm_emu hekate.bin --sd sd.img --usb-host nbd
|
||||
# in Nyx: Tools > USB Tools > SD Card, then on the host:
|
||||
sudo modprobe nbd max_part=8
|
||||
sudo nbd-client 127.0.0.1 10809 /dev/nbd0 -b 512
|
||||
sudo mount /dev/nbd0p1 /mnt # ... use it ...
|
||||
sudo umount /mnt && sudo nbd-client -d /dev/nbd0 # the disk is ejected
|
||||
```
|
||||
|
||||
Without root, `qemu-img convert nbd://127.0.0.1:10809 copy.img` takes a
|
||||
copy, `qemu-io nbd://127.0.0.1:10809` reads and writes sectors, and
|
||||
`nbdfuse` exposes the disk as a file. The session ends when the client
|
||||
disconnects: the PC allows removal and ejects, and Nyx reports "Disk
|
||||
ejected". The port only listens while a disk is being served. In the config
|
||||
window, the USB device mode section has the same switch and port.
|
||||
|
||||
## Live hardware tweaks
|
||||
|
||||
Press `M` in the main window to open a second window that exposes the values
|
||||
@@ -288,7 +318,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. |
|
||||
| `--usb-host` | `nbd[:port]` (optional) | 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), its last 8 sectors are written back unchanged and read again unless it is write-protected, and it is ejected; HID reports are polled. With `nbd` the disk is served over NBD on 127.0.0.1 (port 10809 by default) until the client disconnects, then ejected - see [Mounting a gadget's disk](#mounting-a-gadgets-disk). Logged as `[usb-host]`; `RCM_USB_TRACE=1` traces every transfer. Overrides `[usb] host` and `[usb] nbd_port` in the ini. |
|
||||
| `--input-script` | file or spec | Scripted input keyed to emulated time: `<ms> P\|U\|D [hold_ms]` presses POWER / VOL+ / VOL-, `<ms> TAP <x> <y> [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. |
|
||||
@@ -332,9 +362,11 @@ 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.
|
||||
- **The USB host drives mass storage and HID only.** A gadget of another
|
||||
class is enumerated and left configured. Over NBD, one client has the disk
|
||||
per session: when it disconnects - `nbdinfo` and `qemu-img info` do so as
|
||||
soon as they have their answer - the disk is ejected, as a PC ejects a
|
||||
disk it has unmounted.
|
||||
|
||||
## Acknowledgements
|
||||
|
||||
|
||||
@@ -139,6 +139,7 @@ void reset_to_defaults(EmuState *s) {
|
||||
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) \
|
||||
X(usb_nbd_port, "usb", "nbd_port", 0) \
|
||||
/* SoC / PMIC */ \
|
||||
X(pmic_otp, "soc", "pmic_otp", 0) \
|
||||
X(is_mariko, "soc", "is_mariko", 0) \
|
||||
@@ -652,7 +653,18 @@ void build_ui(EmuState *state) {
|
||||
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.");
|
||||
// Mass storage served over NBD instead (--usb-host nbd[:port]);
|
||||
// takes effect when the next disk is attached.
|
||||
bool nbd = state->usb_nbd_port.load() != 0;
|
||||
if (ImGui::Checkbox("Serve mass storage over NBD", &nbd)) {
|
||||
state->usb_nbd_port.store(nbd ? 10809 : 0);
|
||||
}
|
||||
if (nbd) {
|
||||
atomic_slider_int<uint16_t>("NBD port", state->usb_nbd_port, 1024, 65535, "%d");
|
||||
ImGui::TextDisabled("127.0.0.1 only; the disk is ejected when the client disconnects.");
|
||||
} else {
|
||||
ImGui::TextDisabled("Mass storage is read back, written back unchanged and ejected;\nHID is polled.");
|
||||
}
|
||||
}
|
||||
|
||||
if (ImGui::CollapsingHeader("Display")) {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -358,9 +358,28 @@ int main(int argc, char *argv[]) {
|
||||
}
|
||||
} 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.
|
||||
// payload brings up and, for mass storage, reads it back - or,
|
||||
// given "nbd[:port]", serves the disk over NBD.
|
||||
state.usb_host = true;
|
||||
if (i + 1 < argc && strncmp(argv[i + 1], "nbd", 3) == 0 &&
|
||||
(argv[i + 1][3] == 0 || argv[i + 1][3] == ':')) {
|
||||
const char *arg = argv[++i];
|
||||
unsigned long port = 10809; // the NBD port
|
||||
char *end = nullptr;
|
||||
if (arg[3] == ':')
|
||||
port = strtoul(arg + 4, &end, 10);
|
||||
if (port == 0 || port > 65535 || (end && *end)) {
|
||||
fprintf(stderr, "[emu] Bad --usb-host value '%s'; expected"
|
||||
" nbd or nbd:<port>\n", arg);
|
||||
port = 10809;
|
||||
}
|
||||
state.usb_nbd_port = (uint16_t)port;
|
||||
printf("[emu] USB host connected, serving mass storage over"
|
||||
" NBD on port %lu [overrides ini]\n", port);
|
||||
} else {
|
||||
state.usb_nbd_port = 0;
|
||||
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
|
||||
|
||||
+397
@@ -0,0 +1,397 @@
|
||||
// A one-client NBD server for the emulated USB host (see nbd.h).
|
||||
//
|
||||
// The handshake is the fixed newstyle one every current client speaks
|
||||
// (nbd-client, qemu-nbd, nbdfuse, libnbd):
|
||||
//
|
||||
// server "NBDMAGIC" "IHAVEOPT" handshake flags
|
||||
// client its flags, then options: "IHAVEOPT", option, length, data
|
||||
// server answers each option; EXPORT_NAME or GO hands over the disk
|
||||
//
|
||||
// then requests (magic 0x25609513, flags, type, handle, offset, length,
|
||||
// and a WRITE's data) each answered by a simple reply (magic 0x67446698,
|
||||
// error, handle, and a READ's data). The export has one name - any name
|
||||
// the client asks for - and takes READ, WRITE, FLUSH and DISC; structured
|
||||
// replies and the other extensions are refused, which clients handle.
|
||||
|
||||
#include "nbd.h"
|
||||
|
||||
#ifdef _WIN32
|
||||
#include <winsock2.h>
|
||||
#include <ws2tcpip.h>
|
||||
#else
|
||||
#include <arpa/inet.h>
|
||||
#include <cerrno>
|
||||
#include <fcntl.h>
|
||||
#include <netinet/in.h>
|
||||
#include <netinet/tcp.h>
|
||||
#include <sys/select.h>
|
||||
#include <sys/socket.h>
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr uint64_t NBDMAGIC = 0x4E42444D41474943ull; // "NBDMAGIC"
|
||||
constexpr uint64_t IHAVEOPT = 0x49484156454F5054ull; // "IHAVEOPT"
|
||||
constexpr uint64_t REPLY_MAGIC = 0x0003E889045565A9ull; // option replies
|
||||
constexpr uint32_t REQUEST_MAGIC = 0x25609513;
|
||||
constexpr uint32_t SIMPLE_REPLY_MAGIC = 0x67446698;
|
||||
|
||||
constexpr uint16_t FLAG_FIXED_NEWSTYLE = 1 << 0, FLAG_NO_ZEROES = 1 << 1;
|
||||
constexpr uint16_t FLAG_HAS_FLAGS = 1 << 0, FLAG_READ_ONLY = 1 << 1,
|
||||
FLAG_SEND_FLUSH = 1 << 2;
|
||||
|
||||
constexpr uint32_t OPT_EXPORT_NAME = 1, OPT_ABORT = 2, OPT_LIST = 3,
|
||||
OPT_INFO = 6, OPT_GO = 7;
|
||||
constexpr uint32_t REP_ACK = 1, REP_SERVER = 2, REP_INFO = 3,
|
||||
REP_ERR_UNSUP = 0x80000001, REP_ERR_INVALID = 0x80000003;
|
||||
constexpr uint16_t INFO_EXPORT = 0, INFO_BLOCK_SIZE = 3;
|
||||
|
||||
#ifdef _WIN32
|
||||
using sock_t = SOCKET;
|
||||
const sock_t BAD_SOCK = INVALID_SOCKET;
|
||||
bool net_init() {
|
||||
static bool ok = [] {
|
||||
WSADATA d;
|
||||
return WSAStartup(MAKEWORD(2, 2), &d) == 0;
|
||||
}();
|
||||
return ok;
|
||||
}
|
||||
void close_sock(sock_t s) { closesocket(s); }
|
||||
bool would_block() { return WSAGetLastError() == WSAEWOULDBLOCK; }
|
||||
bool set_nonblocking(sock_t s) {
|
||||
u_long on = 1;
|
||||
return ioctlsocket(s, FIONBIO, &on) == 0;
|
||||
}
|
||||
const char *sock_error() {
|
||||
static char buf[32];
|
||||
snprintf(buf, sizeof(buf), "winsock error %d", WSAGetLastError());
|
||||
return buf;
|
||||
}
|
||||
#else
|
||||
using sock_t = int;
|
||||
const sock_t BAD_SOCK = -1;
|
||||
bool net_init() { return true; }
|
||||
void close_sock(sock_t s) { ::close(s); }
|
||||
bool would_block() {
|
||||
#if EWOULDBLOCK != EAGAIN
|
||||
if (errno == EWOULDBLOCK)
|
||||
return true;
|
||||
#endif
|
||||
return errno == EAGAIN || errno == EINTR;
|
||||
}
|
||||
bool set_nonblocking(sock_t s) {
|
||||
int fl = fcntl(s, F_GETFL, 0);
|
||||
return fl >= 0 && fcntl(s, F_SETFL, fl | O_NONBLOCK) == 0;
|
||||
}
|
||||
const char *sock_error() { return strerror(errno); }
|
||||
#endif
|
||||
|
||||
#ifdef MSG_NOSIGNAL
|
||||
constexpr int SEND_FLAGS = MSG_NOSIGNAL; // a gone client is an error, not SIGPIPE
|
||||
#else
|
||||
constexpr int SEND_FLAGS = 0;
|
||||
#endif
|
||||
|
||||
sock_t sock(intptr_t s) { return (sock_t)s; }
|
||||
|
||||
// Wait up to 10 s for room to send.
|
||||
bool wait_writable(sock_t s) {
|
||||
fd_set w;
|
||||
FD_ZERO(&w);
|
||||
FD_SET(s, &w);
|
||||
timeval tv = {10, 0};
|
||||
return select((int)s + 1, nullptr, &w, nullptr, &tv) > 0;
|
||||
}
|
||||
|
||||
// Everything on the wire is big-endian.
|
||||
void put16(uint8_t *p, uint16_t v) {
|
||||
p[0] = v >> 8;
|
||||
p[1] = (uint8_t)v;
|
||||
}
|
||||
void put32(uint8_t *p, uint32_t v) {
|
||||
put16(p, v >> 16);
|
||||
put16(p + 2, (uint16_t)v);
|
||||
}
|
||||
void put64(uint8_t *p, uint64_t v) {
|
||||
put32(p, v >> 32);
|
||||
put32(p + 4, (uint32_t)v);
|
||||
}
|
||||
uint16_t get16(const uint8_t *p) { return (uint16_t)(p[0] << 8 | p[1]); }
|
||||
uint32_t get32(const uint8_t *p) {
|
||||
return (uint32_t)get16(p) << 16 | get16(p + 2);
|
||||
}
|
||||
uint64_t get64(const uint8_t *p) {
|
||||
return (uint64_t)get32(p) << 32 | get32(p + 4);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool NbdServer::listen(uint16_t port, uint64_t size, bool read_only) {
|
||||
close();
|
||||
if (!net_init()) {
|
||||
printf("[usb-host] NBD: no sockets (%s)\n", sock_error());
|
||||
return false;
|
||||
}
|
||||
sock_t s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
|
||||
if (s == BAD_SOCK) {
|
||||
printf("[usb-host] NBD: no socket (%s)\n", sock_error());
|
||||
return false;
|
||||
}
|
||||
#ifndef _WIN32
|
||||
// Windows' SO_REUSEADDR lets another process take a bound port; the
|
||||
// POSIX one only skips TIME_WAIT, so a restarted run gets its port back.
|
||||
int one = 1;
|
||||
setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
|
||||
#endif
|
||||
sockaddr_in a;
|
||||
memset(&a, 0, sizeof(a));
|
||||
a.sin_family = AF_INET;
|
||||
a.sin_port = htons(port);
|
||||
a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
|
||||
if (bind(s, (sockaddr *)&a, sizeof(a)) != 0 || ::listen(s, 1) != 0 ||
|
||||
!set_nonblocking(s)) {
|
||||
printf("[usb-host] NBD: cannot listen on 127.0.0.1:%u (%s)\n", port,
|
||||
sock_error());
|
||||
close_sock(s);
|
||||
return false;
|
||||
}
|
||||
listen_ = (intptr_t)s;
|
||||
size_ = size;
|
||||
read_only_ = read_only;
|
||||
state_ = Listening;
|
||||
return true;
|
||||
}
|
||||
|
||||
void NbdServer::close() {
|
||||
drop_client();
|
||||
if (listen_ != -1)
|
||||
close_sock(sock(listen_));
|
||||
listen_ = -1;
|
||||
state_ = Idle;
|
||||
}
|
||||
|
||||
void NbdServer::drop_client() {
|
||||
if (client_ != -1)
|
||||
close_sock(sock(client_));
|
||||
client_ = -1;
|
||||
in_.clear();
|
||||
peer_closed_ = false;
|
||||
state_ = listen_ != -1 ? Listening : Idle;
|
||||
}
|
||||
|
||||
uint16_t NbdServer::transmission_flags() const {
|
||||
return FLAG_HAS_FLAGS | FLAG_SEND_FLUSH | (read_only_ ? FLAG_READ_ONLY : 0);
|
||||
}
|
||||
|
||||
// Read what the client has sent. False once it has closed its end.
|
||||
bool NbdServer::fill() {
|
||||
static uint8_t buf[65536];
|
||||
// Room for the largest WRITE; a client pipelining more waits in the socket.
|
||||
while (in_.size() < NBD_MAX_PAYLOAD + sizeof(buf)) {
|
||||
int n = recv(sock(client_), (char *)buf, sizeof(buf), 0);
|
||||
if (n > 0) {
|
||||
in_.insert(in_.end(), buf, buf + n);
|
||||
continue;
|
||||
}
|
||||
return n < 0 && would_block();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool NbdServer::send_all(const void *p, size_t n) {
|
||||
const char *c = (const char *)p;
|
||||
while (n) {
|
||||
int k = send(sock(client_), c, (int)std::min<size_t>(n, 1u << 20),
|
||||
SEND_FLAGS);
|
||||
if (k > 0) {
|
||||
c += k;
|
||||
n -= (size_t)k;
|
||||
} else if (k < 0 && would_block()) {
|
||||
if (!wait_writable(sock(client_)))
|
||||
return false;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool NbdServer::option_reply(uint32_t opt, uint32_t type,
|
||||
const std::vector<uint8_t> &data) {
|
||||
uint8_t h[20];
|
||||
put64(h, REPLY_MAGIC);
|
||||
put32(h + 8, opt);
|
||||
put32(h + 12, type);
|
||||
put32(h + 16, (uint32_t)data.size());
|
||||
return send_all(h, sizeof(h)) &&
|
||||
(data.empty() || send_all(data.data(), data.size()));
|
||||
}
|
||||
|
||||
// One handshake option. False drops the client.
|
||||
bool NbdServer::option(uint32_t opt, const std::vector<uint8_t> &d) {
|
||||
switch (opt) {
|
||||
case OPT_EXPORT_NAME: {
|
||||
// No reply header: the export's size and flags, then (unless the
|
||||
// client opted out) 124 zero bytes, and the disk is the client's.
|
||||
uint8_t r[10 + 124] = {};
|
||||
put64(r, size_);
|
||||
put16(r + 8, transmission_flags());
|
||||
if (!send_all(r, no_zeroes_ ? 10 : sizeof(r)))
|
||||
return false;
|
||||
state_ = Transmission;
|
||||
break;
|
||||
}
|
||||
case OPT_ABORT:
|
||||
option_reply(opt, REP_ACK);
|
||||
return false;
|
||||
case OPT_LIST: {
|
||||
if (!d.empty())
|
||||
return option_reply(opt, REP_ERR_INVALID);
|
||||
std::vector<uint8_t> unnamed(4, 0); // one export, the default name
|
||||
return option_reply(opt, REP_SERVER, unnamed) && option_reply(opt, REP_ACK);
|
||||
}
|
||||
case OPT_INFO:
|
||||
case OPT_GO: {
|
||||
// Export name length, the name, the count of info requests, the
|
||||
// requests. Whatever the client asks for, it gets the size and flags
|
||||
// and the block sizes: 512-byte sectors, 4 KiB preferred.
|
||||
if (d.size() < 6)
|
||||
return option_reply(opt, REP_ERR_INVALID);
|
||||
uint32_t name_len = get32(&d[0]);
|
||||
if (name_len > d.size() - 6 ||
|
||||
d.size() != 6 + name_len + 2 * (size_t)get16(&d[4 + name_len]))
|
||||
return option_reply(opt, REP_ERR_INVALID);
|
||||
std::vector<uint8_t> e(12), b(14);
|
||||
put16(&e[0], INFO_EXPORT);
|
||||
put64(&e[2], size_);
|
||||
put16(&e[10], transmission_flags());
|
||||
put16(&b[0], INFO_BLOCK_SIZE);
|
||||
put32(&b[2], 512);
|
||||
put32(&b[6], 4096);
|
||||
put32(&b[10], NBD_MAX_PAYLOAD);
|
||||
if (!option_reply(opt, REP_INFO, e) || !option_reply(opt, REP_INFO, b) ||
|
||||
!option_reply(opt, REP_ACK))
|
||||
return false;
|
||||
if (opt == OPT_GO)
|
||||
state_ = Transmission;
|
||||
break;
|
||||
}
|
||||
default:
|
||||
return option_reply(opt, REP_ERR_UNSUP);
|
||||
}
|
||||
if (state_ == Transmission)
|
||||
printf("[usb-host] NBD client has the disk\n");
|
||||
return true;
|
||||
}
|
||||
|
||||
NbdEvent NbdServer::poll(NbdRequest *req) {
|
||||
if (state_ == Idle)
|
||||
return NbdEvent::None;
|
||||
if (state_ == Listening) {
|
||||
sock_t c = accept(sock(listen_), nullptr, nullptr);
|
||||
if (c == BAD_SOCK)
|
||||
return NbdEvent::None;
|
||||
set_nonblocking(c);
|
||||
int one = 1;
|
||||
setsockopt(c, IPPROTO_TCP, TCP_NODELAY, (const char *)&one, sizeof(one));
|
||||
#ifdef SO_NOSIGPIPE
|
||||
setsockopt(c, SOL_SOCKET, SO_NOSIGPIPE, &one, sizeof(one));
|
||||
#endif
|
||||
client_ = (intptr_t)c;
|
||||
in_.clear();
|
||||
peer_closed_ = no_zeroes_ = false;
|
||||
uint8_t hello[18];
|
||||
put64(hello, NBDMAGIC);
|
||||
put64(hello + 8, IHAVEOPT);
|
||||
put16(hello + 16, FLAG_FIXED_NEWSTYLE | FLAG_NO_ZEROES);
|
||||
if (!send_all(hello, sizeof(hello))) {
|
||||
drop_client();
|
||||
return NbdEvent::None;
|
||||
}
|
||||
state_ = ClientFlags;
|
||||
}
|
||||
if (!fill())
|
||||
peer_closed_ = true;
|
||||
|
||||
for (;;) {
|
||||
size_t n = in_.size();
|
||||
if (state_ == ClientFlags) {
|
||||
if (n < 4)
|
||||
break;
|
||||
uint32_t f = get32(&in_[0]);
|
||||
in_.erase(in_.begin(), in_.begin() + 4);
|
||||
no_zeroes_ = (f & FLAG_FIXED_NEWSTYLE) && (f & FLAG_NO_ZEROES);
|
||||
state_ = Options;
|
||||
} else if (state_ == Options) {
|
||||
if (n < 16)
|
||||
break;
|
||||
uint32_t opt = get32(&in_[8]), len = get32(&in_[12]);
|
||||
if (get64(&in_[0]) != IHAVEOPT || len > 65536) {
|
||||
printf("[usb-host] NBD: not an NBD client; dropped\n");
|
||||
drop_client();
|
||||
return NbdEvent::None;
|
||||
}
|
||||
if (n < 16 + (size_t)len)
|
||||
break;
|
||||
std::vector<uint8_t> data(in_.begin() + 16, in_.begin() + 16 + len);
|
||||
in_.erase(in_.begin(), in_.begin() + 16 + len);
|
||||
if (!option(opt, data)) {
|
||||
drop_client();
|
||||
return NbdEvent::None;
|
||||
}
|
||||
} else {
|
||||
if (n < 28)
|
||||
break;
|
||||
uint16_t type = get16(&in_[6]);
|
||||
uint32_t len = get32(&in_[24]);
|
||||
if (get32(&in_[0]) != REQUEST_MAGIC ||
|
||||
(type == NBD_CMD_WRITE && len > NBD_MAX_PAYLOAD)) {
|
||||
printf("[usb-host] NBD: malformed request; client dropped\n");
|
||||
drop_client();
|
||||
return NbdEvent::Closed;
|
||||
}
|
||||
size_t need = 28 + (type == NBD_CMD_WRITE ? len : 0);
|
||||
if (n < need)
|
||||
break;
|
||||
req->flags = get16(&in_[4]);
|
||||
req->type = type;
|
||||
req->handle = get64(&in_[8]);
|
||||
req->offset = get64(&in_[16]);
|
||||
req->len = len;
|
||||
req->data.assign(in_.begin() + 28, in_.begin() + need);
|
||||
in_.erase(in_.begin(), in_.begin() + need);
|
||||
if (type == NBD_CMD_DISC) {
|
||||
printf("[usb-host] NBD client disconnected\n");
|
||||
drop_client();
|
||||
return NbdEvent::Closed;
|
||||
}
|
||||
return NbdEvent::Request;
|
||||
}
|
||||
}
|
||||
|
||||
if (peer_closed_) {
|
||||
bool had_disk = state_ == Transmission;
|
||||
printf("[usb-host] NBD client %s\n",
|
||||
had_disk ? "went away without disconnecting" : "left");
|
||||
drop_client();
|
||||
return had_disk ? NbdEvent::Closed : NbdEvent::None;
|
||||
}
|
||||
return NbdEvent::None;
|
||||
}
|
||||
|
||||
void NbdServer::reply(uint64_t handle, uint32_t error, const uint8_t *data,
|
||||
size_t len) {
|
||||
if (state_ != Transmission)
|
||||
return;
|
||||
uint8_t h[16];
|
||||
put32(h, SIMPLE_REPLY_MAGIC);
|
||||
put32(h + 4, error);
|
||||
put64(h + 8, handle);
|
||||
if (!send_all(h, sizeof(h)) || (!error && len && !send_all(data, len)))
|
||||
peer_closed_ = true; // the next poll reports it gone
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
|
||||
// A one-client NBD server - the network block device protocol, fixed
|
||||
// newstyle handshake - that the emulated USB host (usb.cpp) serves a mass
|
||||
// storage gadget's disk with, so the disk can be mounted on the machine the
|
||||
// emulator runs on. It listens on 127.0.0.1 only. Single-threaded and
|
||||
// non-blocking: poll() does whatever the socket allows and returns.
|
||||
|
||||
struct NbdRequest {
|
||||
uint16_t type = 0; // NBD_CMD_*
|
||||
uint16_t flags = 0;
|
||||
uint64_t handle = 0, offset = 0;
|
||||
uint32_t len = 0;
|
||||
std::vector<uint8_t> data; // what a WRITE carries
|
||||
};
|
||||
|
||||
constexpr uint16_t NBD_CMD_READ = 0, NBD_CMD_WRITE = 1, NBD_CMD_DISC = 2,
|
||||
NBD_CMD_FLUSH = 3;
|
||||
constexpr uint32_t NBD_EPERM = 1, NBD_EIO = 5, NBD_EINVAL = 22;
|
||||
|
||||
// The largest READ or WRITE a client may send (the protocol's default).
|
||||
constexpr uint32_t NBD_MAX_PAYLOAD = 32u << 20;
|
||||
|
||||
enum class NbdEvent {
|
||||
None, // nothing to do yet
|
||||
Request, // *req holds the next command
|
||||
Closed, // the client that was using the disk disconnected
|
||||
};
|
||||
|
||||
class NbdServer {
|
||||
public:
|
||||
~NbdServer() { close(); }
|
||||
|
||||
// Listen on 127.0.0.1:port for a client, exporting `size` bytes. False
|
||||
// (and logged) when the port cannot be had.
|
||||
bool listen(uint16_t port, uint64_t size, bool read_only);
|
||||
void close();
|
||||
bool active() const { return state_ != Idle; }
|
||||
|
||||
// Accept, run the handshake, read the next request. A client that goes
|
||||
// away before it has the disk (a listing, a failed negotiation) is not a
|
||||
// Closed event: the server just waits for the next one.
|
||||
NbdEvent poll(NbdRequest *req);
|
||||
|
||||
// Answer a request; a READ's data goes with a zero error.
|
||||
void reply(uint64_t handle, uint32_t error, const uint8_t *data = nullptr,
|
||||
size_t len = 0);
|
||||
|
||||
private:
|
||||
enum State { Idle, Listening, ClientFlags, Options, Transmission };
|
||||
State state_ = Idle;
|
||||
intptr_t listen_ = -1, client_ = -1; // sockets
|
||||
std::vector<uint8_t> in_;
|
||||
bool peer_closed_ = false, no_zeroes_ = false, read_only_ = false;
|
||||
uint64_t size_ = 0;
|
||||
|
||||
bool fill();
|
||||
bool send_all(const void *p, size_t n);
|
||||
bool option(uint32_t opt, const std::vector<uint8_t> &data);
|
||||
bool option_reply(uint32_t opt, uint32_t type,
|
||||
const std::vector<uint8_t> &data = {});
|
||||
void drop_client();
|
||||
uint16_t transmission_flags() const;
|
||||
};
|
||||
+279
-20
@@ -13,15 +13,25 @@
|
||||
// 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
|
||||
// UNIT READY, READ CAPACITY, MODE SENSE (write protection)
|
||||
// and two READ(10)s (the first 64 sectors and the last 8),
|
||||
// checked against the SD image when the capacity matches it.
|
||||
// Unless the disk is write-protected, the last 8 sectors are
|
||||
// then written back unchanged (WRITE(10), SYNCHRONIZE CACHE)
|
||||
// and read again. 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.
|
||||
// With --usb-host nbd[:port] (or [usb] nbd_port) the mass storage session
|
||||
// instead locks the medium (PREVENT MEDIUM REMOVAL) and serves the disk over
|
||||
// NBD on 127.0.0.1 (nbd.cpp), so it can be mounted on this machine: each
|
||||
// request becomes READ(10)s, WRITE(10)s or a SYNCHRONIZE CACHE, and a TEST
|
||||
// UNIT READY goes out every second the client is quiet, as Windows does.
|
||||
// When the client disconnects, the host ejects the disk as above.
|
||||
//
|
||||
// Everything is logged as [usb-host]. The only data the host writes on its
|
||||
// own is what it has just read from the same sectors.
|
||||
//
|
||||
// The host advances whenever the payload touches the controller - every
|
||||
// register access runs it as far as the device and the emulated clock allow
|
||||
@@ -41,6 +51,7 @@
|
||||
#include "../emu_state.h"
|
||||
#include "../platform.h"
|
||||
#include "memory_map.h"
|
||||
#include "nbd.h"
|
||||
|
||||
namespace {
|
||||
|
||||
@@ -106,6 +117,12 @@ constexpr uint64_t kSetAddrUs = 2000; // USB 2.0 9.2.6.3: SET_ADDRESS recover
|
||||
constexpr uint64_t kBindUs = 100000;
|
||||
constexpr uint64_t kTimeoutUs = 5000000;
|
||||
constexpr uint64_t kEjectPollUs = 500000;
|
||||
// Serving NBD: the socket is polled every 100 us of emulated time rather
|
||||
// than on every register access, a quiet client gets a TEST UNIT READY every
|
||||
// second, and requests go to the device 64 KiB at a time.
|
||||
constexpr uint64_t kNbdPollUs = 100;
|
||||
constexpr uint64_t kNbdIdleUs = 1000000;
|
||||
constexpr uint32_t kNbdChunkBlocks = 128;
|
||||
|
||||
struct Endpoint {
|
||||
uint8_t addr = 0, attr = 0, interval = 0;
|
||||
@@ -139,8 +156,10 @@ 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,
|
||||
MscMaxLun, MscInquiry, MscTur, MscSense, MscCapacity, MscModeSense,
|
||||
MscReadFirst, MscReadLast, MscWrite, MscSync, MscReadBack,
|
||||
NbdPrevent, NbdRead, NbdWrite, NbdFlush, NbdTur,
|
||||
MscAllow, MscEject, MscAfterEject, MscEjectWait, NbdServe,
|
||||
HidReport, HidIdle, HidPoll,
|
||||
Idle, Failed,
|
||||
};
|
||||
@@ -161,6 +180,7 @@ public:
|
||||
if (step_ != Step::Unplugged) {
|
||||
if (dc_)
|
||||
dc_->detach();
|
||||
nbd_.close();
|
||||
step_ = Step::Unplugged;
|
||||
printf("[usb-host] unplugged\n");
|
||||
}
|
||||
@@ -181,6 +201,7 @@ public:
|
||||
if (step_ != Step::WaitAttach && !dc_->attached()) {
|
||||
printf("[usb-host] device detached\n");
|
||||
dc_->detach();
|
||||
nbd_.close();
|
||||
step_ = Step::WaitAttach;
|
||||
ctl_.stage = Control::DONE;
|
||||
bot_.phase = Bot::DONE;
|
||||
@@ -199,6 +220,7 @@ public:
|
||||
step_ = Step::Unplugged;
|
||||
ctl_ = Control();
|
||||
bot_ = Bot();
|
||||
nbd_.close();
|
||||
}
|
||||
|
||||
private:
|
||||
@@ -222,8 +244,22 @@ private:
|
||||
uint32_t tag_ = 0, blocks_ = 0, block_len_ = 0;
|
||||
int tur_tries_ = 0;
|
||||
uint64_t eject_deadline_ = 0;
|
||||
bool wp_ = false; // MODE SENSE said write-protected
|
||||
std::vector<uint8_t> last_; // the last 8 sectors, as read
|
||||
int reports_ = 0;
|
||||
|
||||
// Serving NBD: the request in hand, how many of its blocks have been
|
||||
// moved, and what a READ has gathered.
|
||||
NbdServer nbd_;
|
||||
NbdRequest req_;
|
||||
uint32_t req_done_ = 0;
|
||||
std::vector<uint8_t> req_data_;
|
||||
uint64_t last_cmd_us_ = 0, last_poll_us_ = 0;
|
||||
uint64_t nbd_reads_ = 0, nbd_writes_ = 0, nbd_read_bytes_ = 0,
|
||||
nbd_write_bytes_ = 0;
|
||||
|
||||
static uint16_t nbd_port() { return g_state ? g_state->usb_nbd_port.load() : 0; }
|
||||
|
||||
void go(Step s) {
|
||||
step_ = s;
|
||||
progressed_ = true;
|
||||
@@ -231,6 +267,7 @@ private:
|
||||
|
||||
void fail(const char *what) {
|
||||
printf("[usb-host] %s - giving up on this device\n", what);
|
||||
nbd_.close();
|
||||
go(Step::Failed);
|
||||
}
|
||||
|
||||
@@ -465,6 +502,8 @@ private:
|
||||
|
||||
// ---- Mass storage checks ----
|
||||
|
||||
static constexpr const char *kDiffers = "DIFFERS from the SD image";
|
||||
|
||||
// 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<uint8_t> &got) {
|
||||
if (!g_state || g_state->sd_fd < 0)
|
||||
@@ -478,7 +517,7 @@ private:
|
||||
return "SD image unreadable";
|
||||
return memcmp(want.data(), got.data(), got.size()) == 0
|
||||
? "matches the SD image"
|
||||
: "DIFFERS from the SD image";
|
||||
: kDiffers;
|
||||
}
|
||||
|
||||
static uint32_t crc32(const std::vector<uint8_t> &d) {
|
||||
@@ -502,6 +541,28 @@ private:
|
||||
bot(cdb, 10, true, (uint32_t)count * block_len_);
|
||||
}
|
||||
|
||||
void write10(uint32_t lba, uint16_t count, const uint8_t *src) {
|
||||
uint8_t cdb[10] = {0x2A, 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, false, (uint32_t)count * block_len_);
|
||||
memcpy(bot_.data.data(), src, bot_.data.size());
|
||||
}
|
||||
|
||||
void synchronize_cache() {
|
||||
uint8_t cdb[10] = {0x35};
|
||||
bot(cdb, 10, false, 0);
|
||||
}
|
||||
|
||||
bool bot_good() const { return !bot_.stalled && bot_status() == 0; }
|
||||
|
||||
// Done with the disk: allow medium removal, then eject.
|
||||
void release_disk() {
|
||||
uint8_t cdb[6] = {0x1E, 0, 0, 0, 0, 0}; // PREVENT ALLOW: allow
|
||||
bot(cdb, 6, false, 0);
|
||||
go(Step::MscAllow);
|
||||
}
|
||||
|
||||
// A BOT command finished: false (and the session failed) if it did not end
|
||||
// with a good CSW.
|
||||
bool bot_ok(const char *what) {
|
||||
@@ -585,6 +646,10 @@ private:
|
||||
finish(); // polls the endpoint itself
|
||||
return;
|
||||
|
||||
case Step::NbdServe:
|
||||
serve();
|
||||
return;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
@@ -600,6 +665,72 @@ private:
|
||||
finish();
|
||||
}
|
||||
|
||||
// ---- Serving NBD ----
|
||||
|
||||
void serve_next() {
|
||||
last_cmd_us_ = now_us();
|
||||
last_poll_us_ = 0; // a pipelined request is next
|
||||
go(Step::NbdServe);
|
||||
}
|
||||
|
||||
// The next piece of an NBD READ or WRITE.
|
||||
void next_chunk() {
|
||||
uint32_t lba = (uint32_t)(req_.offset / block_len_) + req_done_;
|
||||
uint16_t count = (uint16_t)std::min<uint32_t>(
|
||||
req_.len / block_len_ - req_done_, kNbdChunkBlocks);
|
||||
if (req_.type == NBD_CMD_READ) {
|
||||
read10(lba, count);
|
||||
return go(Step::NbdRead);
|
||||
}
|
||||
write10(lba, count, req_.data.data() + (size_t)req_done_ * block_len_);
|
||||
go(Step::NbdWrite);
|
||||
}
|
||||
|
||||
void serve() {
|
||||
if (now_us() - last_poll_us_ < kNbdPollUs)
|
||||
return;
|
||||
last_poll_us_ = now_us();
|
||||
switch (nbd_.poll(&req_)) {
|
||||
case NbdEvent::None:
|
||||
if (now_us() - last_cmd_us_ >= kNbdIdleUs) {
|
||||
uint8_t cdb[6] = {0x00, 0, 0, 0, 0, 0}; // TEST UNIT READY
|
||||
bot(cdb, 6, false, 0);
|
||||
go(Step::NbdTur);
|
||||
}
|
||||
return;
|
||||
case NbdEvent::Closed:
|
||||
nbd_.close();
|
||||
printf("[usb-host] NBD: %llu reads (%llu KiB), %llu writes (%llu KiB); "
|
||||
"ejecting the disk\n",
|
||||
(unsigned long long)nbd_reads_,
|
||||
(unsigned long long)(nbd_read_bytes_ >> 10),
|
||||
(unsigned long long)nbd_writes_,
|
||||
(unsigned long long)(nbd_write_bytes_ >> 10));
|
||||
return release_disk();
|
||||
case NbdEvent::Request:
|
||||
break;
|
||||
}
|
||||
uint64_t size = ((uint64_t)blocks_ + 1) * block_len_;
|
||||
bool rw = req_.type == NBD_CMD_READ || req_.type == NBD_CMD_WRITE;
|
||||
uint32_t err = 0;
|
||||
if (req_.type == NBD_CMD_FLUSH) {
|
||||
synchronize_cache();
|
||||
return go(Step::NbdFlush);
|
||||
}
|
||||
if (!rw || req_.offset % block_len_ || req_.len % block_len_ ||
|
||||
req_.offset > size || req_.len > size - req_.offset)
|
||||
err = NBD_EINVAL; // whole sectors, on the disk
|
||||
else if (req_.type == NBD_CMD_WRITE && wp_)
|
||||
err = NBD_EPERM;
|
||||
if (err || !req_.len) {
|
||||
nbd_.reply(req_.handle, err);
|
||||
return serve_next();
|
||||
}
|
||||
req_done_ = 0;
|
||||
req_data_.clear();
|
||||
next_chunk();
|
||||
}
|
||||
|
||||
// The class driver binds: its first request.
|
||||
void start_class() {
|
||||
if (iface_class_ == 0x08 && iface_proto_ == 0x50 && bulk_in_.addr &&
|
||||
@@ -760,10 +891,32 @@ private:
|
||||
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));
|
||||
bool mib = bytes >= (1u << 20);
|
||||
printf("[usb-host] %u blocks of %u bytes (%llu %s)\n", blocks_ + 1,
|
||||
block_len_, (unsigned long long)(bytes >> (mib ? 20 : 10)),
|
||||
mib ? "MiB" : "KiB");
|
||||
if (block_len_ != 512 || blocks_ < 72)
|
||||
return fail("unexpected capacity");
|
||||
// Just the 4-byte header: bdk stalls bulk IN on a reply shorter than
|
||||
// the host asked for.
|
||||
uint8_t cdb[6] = {0x1A, 0, 0x3F, 0, 4, 0}; // MODE SENSE(6), all pages
|
||||
bot(cdb, 6, true, 4);
|
||||
return go(Step::MscModeSense);
|
||||
}
|
||||
|
||||
case Step::MscModeSense: {
|
||||
// Bit 7 of byte 2 of the header: write-protected. A device that
|
||||
// cannot say is taken to be.
|
||||
bool ok = bot_good() && bot_.data.size() >= 4;
|
||||
wp_ = !ok || (bot_.data[2] & 0x80);
|
||||
printf("[usb-host] %s\n", !ok ? "MODE SENSE failed; taking the disk as "
|
||||
"write-protected"
|
||||
: wp_ ? "write-protected" : "writable");
|
||||
if (nbd_port()) {
|
||||
uint8_t cdb[6] = {0x1E, 0, 0, 0, 1, 0}; // PREVENT ALLOW: prevent
|
||||
bot(cdb, 6, false, 0);
|
||||
return go(Step::NbdPrevent);
|
||||
}
|
||||
read10(0, 64);
|
||||
return go(Step::MscReadFirst);
|
||||
}
|
||||
@@ -779,12 +932,96 @@ private:
|
||||
case Step::MscReadLast: {
|
||||
if (!bot_ok("READ(10)"))
|
||||
return;
|
||||
const char *cmp = compare_sd(blocks_ - 7, bot_.data);
|
||||
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);
|
||||
blocks_, crc32(bot_.data), cmp);
|
||||
// The write check puts back exactly what was read, so only data that
|
||||
// is known good - or cannot be checked - is written.
|
||||
if (wp_ || cmp == kDiffers) {
|
||||
printf("[usb-host] write check skipped: %s\n",
|
||||
wp_ ? "the disk is write-protected" : "the read was wrong");
|
||||
return release_disk();
|
||||
}
|
||||
last_ = bot_.data;
|
||||
write10(blocks_ - 7, 8, last_.data());
|
||||
return go(Step::MscWrite);
|
||||
}
|
||||
|
||||
case Step::MscWrite:
|
||||
if (!bot_ok("WRITE(10)"))
|
||||
return;
|
||||
synchronize_cache();
|
||||
return go(Step::MscSync);
|
||||
|
||||
case Step::MscSync:
|
||||
if (!bot_ok("SYNCHRONIZE CACHE"))
|
||||
return;
|
||||
read10(blocks_ - 7, 8);
|
||||
return go(Step::MscReadBack);
|
||||
|
||||
case Step::MscReadBack:
|
||||
if (!bot_ok("READ(10)"))
|
||||
return;
|
||||
printf("[usb-host] wrote blocks %u-%u back unchanged; read back: %s, "
|
||||
"%s\n", blocks_ - 7, blocks_,
|
||||
bot_.data == last_ ? "the same data" : "DIFFERENT data",
|
||||
compare_sd(blocks_ - 7, bot_.data));
|
||||
return release_disk();
|
||||
|
||||
// ---- Serving NBD ----
|
||||
|
||||
case Step::NbdPrevent: {
|
||||
if (!bot_ok("PREVENT ALLOW MEDIUM REMOVAL"))
|
||||
return;
|
||||
uint16_t port = nbd_port();
|
||||
if (!nbd_.listen(port, ((uint64_t)blocks_ + 1) * block_len_, wp_)) {
|
||||
printf("[usb-host] not serving the disk\n");
|
||||
return release_disk();
|
||||
}
|
||||
printf("[usb-host] serving the disk over NBD at 127.0.0.1:%u%s (e.g. "
|
||||
"nbd-client 127.0.0.1 %u /dev/nbd0); it is ejected when the "
|
||||
"client disconnects\n",
|
||||
port, wp_ ? ", read-only" : "", port);
|
||||
fflush(stdout); // a script may be waiting on it
|
||||
nbd_reads_ = nbd_writes_ = nbd_read_bytes_ = nbd_write_bytes_ = 0;
|
||||
return serve_next();
|
||||
}
|
||||
|
||||
case Step::NbdRead:
|
||||
case Step::NbdWrite: {
|
||||
bool read = step_ == Step::NbdRead;
|
||||
uint32_t count = bot_.len / block_len_;
|
||||
if (!bot_good() || (read && bot_.data.size() != bot_.len)) {
|
||||
printf("[usb-host] NBD %s of blocks %llu-%llu failed\n",
|
||||
read ? "read" : "write",
|
||||
(unsigned long long)(req_.offset / block_len_ + req_done_),
|
||||
(unsigned long long)(req_.offset / block_len_ + req_done_ +
|
||||
count - 1));
|
||||
nbd_.reply(req_.handle, NBD_EIO);
|
||||
return serve_next();
|
||||
}
|
||||
if (read)
|
||||
req_data_.insert(req_data_.end(), bot_.data.begin(), bot_.data.end());
|
||||
req_done_ += count;
|
||||
if (req_done_ < req_.len / block_len_)
|
||||
return next_chunk();
|
||||
if (read) {
|
||||
nbd_reads_++;
|
||||
nbd_read_bytes_ += req_.len;
|
||||
} else {
|
||||
nbd_writes_++;
|
||||
nbd_write_bytes_ += req_.len;
|
||||
}
|
||||
nbd_.reply(req_.handle, 0, req_data_.data(), read ? req_data_.size() : 0);
|
||||
return serve_next();
|
||||
}
|
||||
|
||||
case Step::NbdFlush:
|
||||
nbd_.reply(req_.handle, bot_good() ? 0 : NBD_EIO);
|
||||
return serve_next();
|
||||
|
||||
case Step::NbdTur:
|
||||
return serve_next(); // only keeps the gadget company
|
||||
|
||||
case Step::MscAllow: {
|
||||
if (!bot_ok("PREVENT ALLOW MEDIUM REMOVAL"))
|
||||
@@ -904,6 +1141,7 @@ constexpr uint32_t EPCTRL_RX_STALL = 1u << 0, EPCTRL_RX_RESET = 1u << 6,
|
||||
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;
|
||||
constexpr uint32_t QH_MAX_PKT_SHIFT = 16, QH_ZLT_DISABLE = 1u << 29;
|
||||
|
||||
class Usb2d : public UsbDc {
|
||||
public:
|
||||
@@ -1013,7 +1251,7 @@ public:
|
||||
if (!(reg(R_STATUS) & bit))
|
||||
return XFER_NAK;
|
||||
int moved = transfer(2 * ep + 1, buf, max, true);
|
||||
*short_pkt = moved < max;
|
||||
*short_pkt = moved < max && ends_transfer(2 * ep + 1, moved);
|
||||
return moved;
|
||||
}
|
||||
|
||||
@@ -1042,6 +1280,18 @@ private:
|
||||
return (s & SUSP_UTMIP_PHY_ENB) && !(s & SUSP_UTMIP_RESET);
|
||||
}
|
||||
|
||||
// A device transfer of n bytes that retired before the host had all it
|
||||
// asked for ends the host's transfer too only if its last packet was
|
||||
// short, or zero-length - which the controller appends to a whole number
|
||||
// of packets unless the queue head disables it (ZLT, as bdk does on every
|
||||
// endpoint). Otherwise the host goes on to the device's next transfer:
|
||||
// bdk sends a 64 KiB READ(10) as two 32 KiB ones.
|
||||
bool ends_transfer(int index, int n) {
|
||||
uint32_t caps = qh_read32(qh_addr(index));
|
||||
uint32_t mps = (caps >> QH_MAX_PKT_SHIFT) & 0x7FF;
|
||||
return n == 0 || !mps || n % mps || !(caps & QH_ZLT_DISABLE);
|
||||
}
|
||||
|
||||
// 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; }
|
||||
@@ -1296,9 +1546,18 @@ public:
|
||||
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;
|
||||
int dci = ep ? 3 : 0;
|
||||
int n = transfer(dci, true, buf, max);
|
||||
if (n >= 0) {
|
||||
// As on the USB2 controller, a TRB that moved less than the host asked
|
||||
// for ends its transfer only on a short or zero-length packet; this
|
||||
// side appends no ZLP of its own. The max packet size is in word 1 of
|
||||
// the endpoint context.
|
||||
uint32_t w1 = 0;
|
||||
mem_read(ctx_addr(dci) + 4, &w1, 4);
|
||||
uint32_t mps = w1 >> 16;
|
||||
*short_pkt = n < max && (n == 0 || !mps || n % mps);
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
|
||||
@@ -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
@@ -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;
|
||||
else
|
||||
sent = bulk(1, DISK + lba * 512, cnt * 512);
|
||||
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;
|
||||
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
@@ -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; }
|
||||
Reference in new issue
Block a user