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
+1183
-67
No files matched your search
+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,13 +932,97 @@ 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"))
|
||||
return;
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user