mirror of
https://github.com/pithings/unkernel.git
synced 2026-12-06 05:29:38 +08:00
1776 lines
66 KiB
TypeScript
1776 lines
66 KiB
TypeScript
// SPDX-License-Identifier: MIT
|
|
// Copyright (C) 2026 Pooya Parsa <pooya@pi0.io>
|
|
// USB devices for the guest: the host side of kwusb (a host controller in
|
|
// the kernel, drivers/usb/host/kwusb.c, whose URBs the host serves), behind
|
|
// a backend interface shaped like WebUSB's USBDevice, so the same model
|
|
// serves a real device (js/web/usb.ts: webUsbBackend(device)) and
|
|
// FakeUsbBackend (usb-fake.ts: a small loopback device for tests and the
|
|
// CLI's --usb).
|
|
//
|
|
// Two parts, on the kernel's thread (inline, and in the kernel's worker in
|
|
// worker mode):
|
|
// - UsbDevice, the kernel's end: the wasm_driver_usb_* imports (none
|
|
// suspends) and IRQ 13. It reads each URB's struct kwusb_xfer at submit
|
|
// (copying OUT data straight out of guest memory), keeps the port status
|
|
// words and the finished transfers, and at reap writes IN data, the
|
|
// actual lengths and the isochronous packet results straight into the
|
|
// URB's buffers. A cancelled transfer is forgotten at once: nothing is
|
|
// written for it afterwards, even if it had finished.
|
|
// - UsbHost, the devices' end and the API (`vm.usb`): backends in slots
|
|
// (the root hub's ports), and per slot the translation from the URBs of
|
|
// a guest that enumerates and configures the device itself to WebUSB,
|
|
// where the browser already has:
|
|
// * SET_ADDRESS is answered here; GET_DESCRIPTOR for the device and
|
|
// configuration descriptors is answered from the descriptors read at
|
|
// attach (configurations filtered, below); every other GET_DESCRIPTOR
|
|
// and every class or vendor request passes through
|
|
// (controlTransferIn/Out). GET_CONFIGURATION and GET_INTERFACE are
|
|
// answered from what the guest set; SET_SEL and SET_ISOCH_DELAY
|
|
// (SuperSpeed) are answered here.
|
|
// * SET_CONFIGURATION is selectConfiguration() and a claim of every
|
|
// interface of that configuration that is shown; SET_INTERFACE is
|
|
// selectAlternateInterface(); CLEAR_FEATURE(ENDPOINT_HALT) is
|
|
// clearHalt(). A port reset is answered at once until the guest has
|
|
// configured the device (its enumeration resets the port twice, and
|
|
// the browser has just enumerated it); after that it is reset().
|
|
// * Interfaces of WebUSB's protected classes (audio, HID, mass storage,
|
|
// hub, smart card, video, audio/video, wireless controller: claiming
|
|
// one is a SecurityError) are hidden: the configuration descriptors
|
|
// the guest reads leave them out, with their endpoints, class
|
|
// descriptors and association descriptors (interface numbers stay,
|
|
// bNumInterfaces counts what is left), so no driver binds to
|
|
// something no transfer could reach; a request addressed to one
|
|
// stalls. An interface the browser could not claim for another
|
|
// reason (the OS has a driver on it) stays shown and its transfers
|
|
// fail with -EPROTO.
|
|
// * Status: "stall" is -EPIPE, "babble" -EOVERFLOW, a rejected
|
|
// transfer -EPROTO; transfers of a device that went away -ESHUTDOWN.
|
|
// URB_ZERO_PACKET sends a zero-length transferOut after an OUT that
|
|
// fills its last packet; short reads complete short (usbcore applies
|
|
// URB_SHORT_NOT_OK).
|
|
// * WebUSB cannot cancel a transfer. A cancelled IN URB leaves its
|
|
// transferIn pending: the endpoint keeps it as a spare read, and
|
|
// what it brings is parked and goes to the next URBs on that
|
|
// endpoint in order (as a device keeps data a cancelled URB never
|
|
// took), so no byte is lost. A selectConfiguration(),
|
|
// selectAlternateInterface() or reset() ends pending transfers, and
|
|
// then what was parked is dropped too. A cancelled OUT URB may
|
|
// still reach the device.
|
|
// * WebUSB does not tell the speed: it is derived from the descriptors
|
|
// (bcdUSB, bMaxPacketSize0, the endpoints' sizes and intervals) or
|
|
// given (attach's `speed`); SuperSpeed devices go on the USB 3 root
|
|
// hub.
|
|
// * The device's "disconnect" (the backend's listen()) is a port
|
|
// disconnect: every transfer in flight ends with -ESHUTDOWN.
|
|
// Control requests run one at a time per device; bulk and interrupt
|
|
// URBs run concurrently, each endpoint's in order.
|
|
// In worker mode the API on the owner is UsbRemote (below), which forwards
|
|
// attach(), detach() and the state. A WebUSB device the worker can open
|
|
// itself (navigator.usb.getDevices() there, matched by its ids; js/web/
|
|
// usb.ts) is driven in the worker, next to the kernel, with no thread hop
|
|
// per transfer; any other backend (FakeUsbBackend, or a device the worker
|
|
// cannot tell apart from another) stays on the owner and is driven over
|
|
// messages (RemoteUsbBackend calls, UsbRemote answers).
|
|
//
|
|
// Snapshots keep no device: UsbDevice saves the port count and which slots
|
|
// had a device, and a restored guest sees them disconnected (the kernel's
|
|
// restore notifier gives back every URB with -ESHUTDOWN too).
|
|
|
|
/** IRQ bit for the controller (WASM_IRQ_USB). */
|
|
export const IRQ_USB = 13;
|
|
/** Ports the controller offers at most; and by default. */
|
|
export const USB_MAX_PORTS = 8;
|
|
export const USB_DEFAULT_PORTS = 4;
|
|
|
|
/** wasm_driver_usb_port() bits: levels, then events (cleared by the read). */
|
|
export const USB_PORT_CONNECTED = 1 << 0;
|
|
export const USB_PORT_SPEED_SHIFT = 1;
|
|
export const USB_PORT_EV_CHANGE = 1 << 8;
|
|
export const USB_PORT_EV_RESET = 1 << 9;
|
|
/** wasm_driver_usb_port_op() ops. */
|
|
export const USB_OP_RESET = 1;
|
|
/** struct kwusb_xfer flags. */
|
|
export const USB_X_ZERO_PACKET = 1 << 0;
|
|
export const USB_X_SHORT_NOT_OK = 1 << 1;
|
|
/** USB_ENDPOINT_XFER_* */
|
|
export const USB_XFER_CONTROL = 0;
|
|
export const USB_XFER_ISO = 1;
|
|
export const USB_XFER_BULK = 2;
|
|
export const USB_XFER_INT = 3;
|
|
|
|
/** Bytes of a struct kwusb_xfer before its segments, and of each segment and completion. */
|
|
export const USB_XFER_SIZE = 48;
|
|
export const USB_SEG_SIZE = 16;
|
|
export const USB_DONE_SIZE = 16;
|
|
|
|
const EPROTO = 71, EPIPE = 32, EOVERFLOW = 75, ENODEV = 19, ESHUTDOWN = 108, ENOSYS = 38, EINVAL = 22;
|
|
|
|
/** The kernel's enum usb_device_speed values the port status carries. */
|
|
export type UsbSpeed = "low" | "full" | "high" | "super";
|
|
const SPEED_CODE: Record<UsbSpeed, number> = { low: 1, full: 2, high: 3, super: 5 };
|
|
|
|
/**
|
|
* Interface classes WebUSB will not let a page claim (the spec's protected
|
|
* interface classes): hidden from the guest.
|
|
*/
|
|
export const USB_PROTECTED_CLASSES: readonly number[] = [0x01, 0x03, 0x08, 0x09, 0x0b, 0x0e, 0x10, 0xe0];
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// The backend: WebUSB's USBDevice, as far as the host uses it.
|
|
|
|
export type UsbTransferStatus = "ok" | "stall" | "babble";
|
|
export interface UsbControlSetup {
|
|
requestType: "standard" | "class" | "vendor";
|
|
recipient: "device" | "interface" | "endpoint" | "other";
|
|
request: number;
|
|
value: number;
|
|
index: number;
|
|
}
|
|
export interface UsbInResult {
|
|
status: UsbTransferStatus;
|
|
data?: Uint8Array;
|
|
}
|
|
export interface UsbOutResult {
|
|
status: UsbTransferStatus;
|
|
bytesWritten: number;
|
|
}
|
|
export interface UsbIsoInResult {
|
|
packets: Array<{ status: UsbTransferStatus; data?: Uint8Array }>;
|
|
}
|
|
export interface UsbIsoOutResult {
|
|
packets: Array<{ status: UsbTransferStatus; bytesWritten: number }>;
|
|
}
|
|
|
|
/** What a backend says about itself (WebUSB's USBDevice fields), plain data. */
|
|
export interface UsbBackendInfo {
|
|
vendorId?: number;
|
|
productId?: number;
|
|
serialNumber?: string;
|
|
manufacturerName?: string;
|
|
productName?: string;
|
|
/** A label to show ("USB 1209:0001 kwusb test device"). */
|
|
label?: string;
|
|
}
|
|
|
|
/**
|
|
* The ids by which the kernel's worker finds the same WebUSB device in its
|
|
* own navigator.usb.getDevices() (js/web/usb.ts), plain data.
|
|
*/
|
|
export interface UsbDeviceKey {
|
|
vendorId: number;
|
|
productId: number;
|
|
serialNumber?: string;
|
|
manufacturerName?: string;
|
|
productName?: string;
|
|
deviceVersion?: string;
|
|
}
|
|
|
|
/**
|
|
* One USB device as the host drives it, shaped like WebUSB's USBDevice
|
|
* (endpoint numbers without the direction bit, as WebUSB takes them). The
|
|
* host calls open() at attach and close() at detach; transfers on
|
|
* different endpoints may be pending at once, and several on one endpoint
|
|
* (they complete in order). A rejection is an Error with a `name`
|
|
* (WebUSB's DOMException names); a device that went away calls `lost`.
|
|
*/
|
|
export interface UsbBackend {
|
|
readonly info?: UsbBackendInfo;
|
|
open(): Promise<void>;
|
|
close(): Promise<void>;
|
|
/** Select configuration `value` (resolves at once when it is the current one). */
|
|
selectConfiguration(value: number): Promise<void>;
|
|
claimInterface(n: number): Promise<void>;
|
|
releaseInterface(n: number): Promise<void>;
|
|
selectAlternateInterface(n: number, alt: number): Promise<void>;
|
|
clearHalt(direction: "in" | "out", endpoint: number): Promise<void>;
|
|
controlTransferIn(setup: UsbControlSetup, length: number): Promise<UsbInResult>;
|
|
controlTransferOut(setup: UsbControlSetup, data?: Uint8Array): Promise<UsbOutResult>;
|
|
transferIn(endpoint: number, length: number): Promise<UsbInResult>;
|
|
transferOut(endpoint: number, data: Uint8Array): Promise<UsbOutResult>;
|
|
isochronousTransferIn?(endpoint: number, packetLengths: number[]): Promise<UsbIsoInResult>;
|
|
isochronousTransferOut?(endpoint: number, data: Uint8Array, packetLengths: number[]): Promise<UsbIsoOutResult>;
|
|
reset(): Promise<void>;
|
|
/** Call `lost` when the device goes away (unplugged); returns the unsubscribe. */
|
|
listen?(lost: () => void): () => void;
|
|
/**
|
|
* Worker mode: the ids by which the kernel's worker can open this very
|
|
* device itself, or undefined when it cannot (not WebUSB, or another
|
|
* granted device has the same ids). js/web/usb.ts.
|
|
*/
|
|
workerKey?(): Promise<UsbDeviceKey | undefined>;
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Descriptors.
|
|
|
|
const DT_DEVICE = 1, DT_CONFIG = 2, DT_INTERFACE = 4, DT_ENDPOINT = 5, DT_IAD = 11;
|
|
|
|
/** An endpoint of a configuration, as the descriptors say. */
|
|
export interface UsbEndpointInfo {
|
|
address: number;
|
|
type: number;
|
|
maxPacket: number;
|
|
interval: number;
|
|
iface: number;
|
|
alt: number;
|
|
}
|
|
|
|
/** A configuration descriptor's interfaces and endpoints. */
|
|
export interface UsbConfigInfo {
|
|
value: number;
|
|
interfaces: Array<{ number: number; alt: number; cls: number }>;
|
|
endpoints: UsbEndpointInfo[];
|
|
}
|
|
|
|
export function parseConfig(d: Uint8Array): UsbConfigInfo {
|
|
const info: UsbConfigInfo = { value: d[5] ?? 0, interfaces: [], endpoints: [] };
|
|
let iface = -1, alt = 0;
|
|
for (let i = 0; i + 2 <= d.length; ) {
|
|
const len = d[i]!, type = d[i + 1]!;
|
|
if (len < 2 || i + len > d.length) break;
|
|
if (type === DT_INTERFACE && len >= 9) {
|
|
iface = d[i + 2]!;
|
|
alt = d[i + 3]!;
|
|
info.interfaces.push({ number: iface, alt, cls: d[i + 5]! });
|
|
} else if (type === DT_ENDPOINT && len >= 7 && iface >= 0) {
|
|
info.endpoints.push({ address: d[i + 2]!, type: d[i + 3]! & 3, maxPacket: (d[i + 4]! | (d[i + 5]! << 8)) & 0x1fff, interval: d[i + 6]!, iface, alt });
|
|
}
|
|
i += len;
|
|
}
|
|
return info;
|
|
}
|
|
|
|
/**
|
|
* The configuration descriptor `d` without the interfaces whose class is
|
|
* in `hidden` (every alternate setting, with the descriptors that follow
|
|
* each up to the next interface or association descriptor) and without
|
|
* association descriptors that start at a hidden interface. wTotalLength
|
|
* and bNumInterfaces are rewritten; interface numbers stay. Returns the
|
|
* descriptor and the interface numbers left out.
|
|
*/
|
|
export function filterConfig(d: Uint8Array, hiddenClasses: readonly number[] = USB_PROTECTED_CLASSES): { config: Uint8Array; hidden: number[] } {
|
|
const info = parseConfig(d);
|
|
const hidden = [...new Set(info.interfaces.filter((i) => hiddenClasses.includes(i.cls)).map((i) => i.number))];
|
|
if (!hidden.length) return { config: d, hidden };
|
|
const out: number[] = [];
|
|
let skip = false;
|
|
for (let i = 0; i + 2 <= d.length; ) {
|
|
const len = d[i]!, type = d[i + 1]!;
|
|
if (len < 2 || i + len > d.length) break;
|
|
const part = d.subarray(i, i + len);
|
|
if (i === 0 && type === DT_CONFIG) {
|
|
out.push(...part);
|
|
} else if (type === DT_INTERFACE) {
|
|
skip = hidden.includes(d[i + 2]!);
|
|
if (!skip) out.push(...part);
|
|
} else if (type === DT_IAD) {
|
|
skip = hidden.includes(d[i + 2]!);
|
|
if (!skip) out.push(...part);
|
|
} else if (!skip) out.push(...part);
|
|
i += len;
|
|
}
|
|
const config = Uint8Array.from(out);
|
|
config[2] = config.length & 0xff;
|
|
config[3] = config.length >> 8;
|
|
config[4] = new Set(info.interfaces.filter((x) => !hidden.includes(x.number)).map((x) => x.number)).size;
|
|
return { config, hidden };
|
|
}
|
|
|
|
/**
|
|
* The speed a device runs at, from its descriptors (WebUSB does not say):
|
|
* SuperSpeed by bcdUSB 3.x with a 512-byte ep0 (bMaxPacketSize0 9); high
|
|
* speed by 512-byte bulk endpoints, interrupt endpoints over 64 bytes,
|
|
* isochronous ones over 1023, or extra transactions per microframe; full speed by 64-byte (or smaller)
|
|
* bulk endpoints, an interrupt interval over 16, or a USB 1.x bcdUSB; low
|
|
* speed by an 8-byte ep0 on USB 1.x with only small interrupt endpoints.
|
|
* A USB 2.0 device that says nothing either way (only small interrupt
|
|
* endpoints) counts as high speed.
|
|
*/
|
|
export function deriveSpeed(device: Uint8Array, configs: readonly Uint8Array[]): UsbSpeed {
|
|
const bcd = (device[2] ?? 0) | ((device[3] ?? 0) << 8);
|
|
const mp0 = device[7] ?? 64;
|
|
if (bcd >= 0x300 && mp0 === 9) return "super";
|
|
const eps = configs.flatMap((c) => parseConfig(c).endpoints);
|
|
const bulk = eps.filter((e) => e.type === USB_XFER_BULK);
|
|
const periodic = eps.filter((e) => e.type === USB_XFER_INT || e.type === USB_XFER_ISO);
|
|
const intr = eps.filter((e) => e.type === USB_XFER_INT), isoc = eps.filter((e) => e.type === USB_XFER_ISO);
|
|
if (bulk.some((e) => (e.maxPacket & 0x7ff) >= 512) || intr.some((e) => (e.maxPacket & 0x7ff) > 64) || isoc.some((e) => (e.maxPacket & 0x7ff) > 1023) || periodic.some((e) => e.maxPacket & 0x1800)) return "high";
|
|
if (bcd < 0x200) {
|
|
if (mp0 === 8 && !bulk.length && !eps.some((e) => e.type === USB_XFER_ISO) && eps.every((e) => (e.maxPacket & 0x7ff) <= 8)) return "low";
|
|
return "full";
|
|
}
|
|
if (mp0 !== 64) return "full";
|
|
if (bulk.length) return "full";
|
|
if (eps.some((e) => e.type === USB_XFER_INT && e.interval > 16)) return "full";
|
|
return "high";
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// The kernel's end.
|
|
|
|
/** A URB as the host gets it. */
|
|
export interface UsbXfer {
|
|
id: number;
|
|
slot: number;
|
|
/** Endpoint address: number | 0x80 for IN. */
|
|
ep: number;
|
|
type: number;
|
|
flags: number;
|
|
length: number;
|
|
maxpacket: number;
|
|
interval: number;
|
|
/** Control: the setup packet. */
|
|
setup?: Uint8Array;
|
|
/** OUT: the bytes, copied at submit. */
|
|
data?: Uint8Array;
|
|
/** Isochronous: each packet's length (and offset in the buffer). */
|
|
packets?: Array<{ offset: number; length: number }>;
|
|
}
|
|
|
|
/** A finished URB, for the kernel's next reap. */
|
|
export interface UsbCompletion {
|
|
id: number;
|
|
status: number;
|
|
actual: number;
|
|
/** IN: the bytes (at most the URB's length are written). */
|
|
data?: Uint8Array;
|
|
/** Isochronous: each packet's result (IN data at the packet's offset). */
|
|
packets?: Array<{ status: number; actual: number; data?: Uint8Array }>;
|
|
}
|
|
|
|
/** What UsbDevice asks of the devices' end. */
|
|
export interface UsbPortsEnd {
|
|
/** The kernel's driver started with this many ports. */
|
|
init(ports: number): void;
|
|
/** 0 when taken (it completes later through UsbDevice.complete()), or a negative errno. */
|
|
submit(x: UsbXfer): number;
|
|
/** Forget transfer `id` (its completion, if it comes, is dropped). */
|
|
cancel(id: number): void;
|
|
/** A port op (USB_OP_RESET): 1 done now, 0 later (UsbDevice.resetDone()), < 0 no device. */
|
|
portOp(slot: number, op: number): number;
|
|
}
|
|
|
|
/** What a machine snapshot keeps of the controller: the port count and the slots that had a device (they come back disconnected). */
|
|
export interface UsbSnapshot {
|
|
ports: number;
|
|
connected: number[];
|
|
}
|
|
|
|
export interface UsbDeviceStats {
|
|
submitted: number;
|
|
completed: number;
|
|
cancelled: number;
|
|
/** Bytes the guest sent (OUT) and received (IN). */
|
|
bytesOut: number;
|
|
bytesIn: number;
|
|
}
|
|
|
|
export interface UsbDeviceOptions {
|
|
/** Ports to offer (1..8); 0 or undefined: no controller (wasm_driver_usb_init returns -ENODEV). */
|
|
ports?: number;
|
|
memory: () => WebAssembly.Memory;
|
|
raise: () => void;
|
|
}
|
|
|
|
interface KSlot {
|
|
connected: boolean;
|
|
speed: number;
|
|
events: number;
|
|
}
|
|
|
|
interface KXfer {
|
|
slot: number;
|
|
length: number;
|
|
segs: Array<[number, number]>;
|
|
iso: number;
|
|
npackets: number;
|
|
}
|
|
|
|
/**
|
|
* The kernel's end of kwusb (the imports), on the kernel's thread. The
|
|
* devices' end (UsbHost) is `end`; it calls complete(), setPort() and
|
|
* resetDone().
|
|
*/
|
|
export class UsbDevice {
|
|
readonly enabled: boolean;
|
|
ports: number;
|
|
/** Did the kernel ask (wasm_driver_usb_init)? False for a kernel without kwusb. */
|
|
probed = false;
|
|
end: UsbPortsEnd | undefined;
|
|
stats: UsbDeviceStats = { submitted: 0, completed: 0, cancelled: 0, bytesOut: 0, bytesIn: 0 };
|
|
#slots: KSlot[] = [];
|
|
#changed = 0;
|
|
#xfers = new Map<number, KXfer>();
|
|
#done: UsbCompletion[] = [];
|
|
#memory: () => WebAssembly.Memory;
|
|
#raise: () => void;
|
|
|
|
constructor(opts: UsbDeviceOptions) {
|
|
const n = Math.max(0, Math.min(USB_MAX_PORTS, Math.floor(opts.ports ?? 0)));
|
|
this.enabled = n > 0;
|
|
this.ports = n;
|
|
this.#memory = opts.memory;
|
|
this.#raise = opts.raise;
|
|
for (let i = 0; i < USB_MAX_PORTS; i++) this.#slots.push({ connected: false, speed: 0, events: 0 });
|
|
}
|
|
|
|
/** Transfers the kernel has given and not yet reaped or cancelled. */
|
|
get inFlight(): number {
|
|
return this.#xfers.size;
|
|
}
|
|
|
|
/** The devices' end: a device came (with its speed) or went in `slot`. */
|
|
setPort(slot: number, connected: boolean, speed?: UsbSpeed): void {
|
|
const s = this.#slots[slot];
|
|
if (!s || slot >= this.ports) return;
|
|
s.connected = connected;
|
|
s.speed = connected && speed ? SPEED_CODE[speed] : 0;
|
|
s.events |= USB_PORT_EV_CHANGE;
|
|
this.#changed |= 1 << slot;
|
|
this.#raise();
|
|
}
|
|
|
|
/** The devices' end: a reset that portOp() answered 0 for has ended. */
|
|
resetDone(slot: number): void {
|
|
const s = this.#slots[slot];
|
|
if (!s || slot >= this.ports) return;
|
|
s.events |= USB_PORT_EV_RESET;
|
|
this.#changed |= 1 << slot;
|
|
this.#raise();
|
|
}
|
|
|
|
/** The devices' end: transfer `c.id` finished (dropped when the kernel cancelled it). */
|
|
complete(c: UsbCompletion): void {
|
|
if (!this.#xfers.has(c.id)) return;
|
|
if (this.#done.push(c) === 1) this.#raise();
|
|
}
|
|
|
|
#u8(): Uint8Array {
|
|
return new Uint8Array(this.#memory().buffer);
|
|
}
|
|
|
|
/** Copy `src` into the transfer's buffer at logical offset `at`, across its segments. */
|
|
#scatter(mem: Uint8Array, x: KXfer, at: number, src: Uint8Array): void {
|
|
let off = 0;
|
|
for (const [addr, len] of x.segs) {
|
|
if (at < off + len && src.length) {
|
|
const into = at - off;
|
|
const n = Math.min(len - into, src.length);
|
|
mem.set(src.subarray(0, n), addr + into);
|
|
src = src.subarray(n);
|
|
at += n;
|
|
}
|
|
off += len;
|
|
if (!src.length) return;
|
|
}
|
|
}
|
|
|
|
imports(): Record<string, unknown> {
|
|
return {
|
|
wasm_driver_usb_init: (): number => {
|
|
this.probed = true;
|
|
if (!this.enabled) return -ENODEV;
|
|
this.end?.init(this.ports);
|
|
return this.ports;
|
|
},
|
|
wasm_driver_usb_changed: (): number => {
|
|
const c = this.#changed;
|
|
this.#changed = 0;
|
|
return c;
|
|
},
|
|
wasm_driver_usb_port: (slot: number): number => {
|
|
const s = this.#slots[slot >>> 0];
|
|
if (!s || slot >>> 0 >= this.ports) return 0;
|
|
const st = (s.connected ? USB_PORT_CONNECTED | (s.speed << USB_PORT_SPEED_SHIFT) : 0) | s.events;
|
|
s.events = 0;
|
|
return st;
|
|
},
|
|
wasm_driver_usb_port_op: (slot: number, op: number): number => {
|
|
const s = this.#slots[slot >>> 0];
|
|
if (!s || slot >>> 0 >= this.ports || !s.connected) return -ENODEV;
|
|
return this.end?.portOp(slot >>> 0, op >>> 0) ?? -ENODEV;
|
|
},
|
|
wasm_driver_usb_submit: (ptr: number | bigint): number => {
|
|
const mem = this.#u8();
|
|
const at = Number(ptr);
|
|
const dv = new DataView(mem.buffer, at, USB_XFER_SIZE);
|
|
const id = dv.getUint32(0, true), slot = dv.getUint8(4);
|
|
const s = this.#slots[slot];
|
|
if (!s || slot >= this.ports || !s.connected || !this.end) return -ENODEV;
|
|
const ep = dv.getUint8(5), type = dv.getUint8(6), flags = dv.getUint8(7);
|
|
const length = dv.getUint32(8, true), nseg = dv.getUint32(12, true);
|
|
const segs: Array<[number, number]> = [];
|
|
let total = 0;
|
|
if (nseg > 0) {
|
|
const sv = new DataView(mem.buffer, at + USB_XFER_SIZE, nseg * USB_SEG_SIZE);
|
|
for (let i = 0; i < nseg; i++) {
|
|
const a = Number(sv.getBigUint64(i * USB_SEG_SIZE, true)), l = sv.getUint32(i * USB_SEG_SIZE + 8, true);
|
|
segs.push([a, l]);
|
|
total += l;
|
|
}
|
|
}
|
|
if (total < length) return -EINVAL;
|
|
const x: UsbXfer = { id, slot, ep, type, flags, length, maxpacket: dv.getUint32(16, true), interval: dv.getUint32(20, true) };
|
|
const npackets = type === USB_XFER_ISO ? dv.getUint32(24, true) : 0;
|
|
const iso = npackets ? Number(dv.getBigUint64(40, true)) : 0;
|
|
if (type === USB_XFER_CONTROL) {
|
|
const setup = Number(dv.getBigUint64(32, true));
|
|
if (!setup) return -EINVAL;
|
|
x.setup = mem.slice(setup, setup + 8);
|
|
}
|
|
if (npackets) {
|
|
const pv = new DataView(mem.buffer, iso, npackets * 16);
|
|
x.packets = [];
|
|
for (let i = 0; i < npackets; i++) x.packets.push({ offset: pv.getUint32(i * 16, true), length: pv.getUint32(i * 16 + 4, true) });
|
|
}
|
|
const out = type === USB_XFER_CONTROL ? !((x.setup![0] ?? 0) & 0x80) : !(ep & 0x80);
|
|
if (out && length) {
|
|
// Gather the bytes now: the host never reads guest memory later.
|
|
const data = new Uint8Array(length);
|
|
let n = 0;
|
|
for (const [a, l] of segs) {
|
|
const take = Math.min(l, length - n);
|
|
data.set(mem.subarray(a, a + take), n);
|
|
n += take;
|
|
if (n >= length) break;
|
|
}
|
|
x.data = data;
|
|
this.stats.bytesOut += length;
|
|
}
|
|
this.#xfers.set(id, { slot, length, segs, iso, npackets });
|
|
const r = this.end.submit(x);
|
|
if (r) {
|
|
this.#xfers.delete(id);
|
|
return r;
|
|
}
|
|
this.stats.submitted++;
|
|
return 0;
|
|
},
|
|
wasm_driver_usb_cancel: (id: number): void => {
|
|
id >>>= 0;
|
|
if (!this.#xfers.delete(id)) return;
|
|
this.stats.cancelled++;
|
|
const i = this.#done.findIndex((c) => c.id === id);
|
|
if (i >= 0) this.#done.splice(i, 1);
|
|
else this.end?.cancel(id);
|
|
},
|
|
wasm_driver_usb_reap: (ptr: number | bigint, max: number): number => {
|
|
if (!this.#done.length) return 0;
|
|
const mem = this.#u8();
|
|
const at = Number(ptr);
|
|
const n = Math.min(max >>> 0, this.#done.length);
|
|
const dv = new DataView(mem.buffer, at, n * USB_DONE_SIZE);
|
|
const batch = this.#done.splice(0, n);
|
|
for (let i = 0; i < batch.length; i++) {
|
|
const c = batch[i]!;
|
|
const x = this.#xfers.get(c.id)!;
|
|
this.#xfers.delete(c.id);
|
|
let actual = 0, errors = 0;
|
|
if (x.npackets && c.packets) {
|
|
const pv = new DataView(mem.buffer, x.iso, x.npackets * 16);
|
|
for (let p = 0; p < x.npackets; p++) {
|
|
const r = c.packets[p];
|
|
const offset = pv.getUint32(p * 16, true), want = pv.getUint32(p * 16 + 4, true);
|
|
let got = Math.min(r?.actual ?? 0, want);
|
|
if (r?.data && got) {
|
|
got = Math.min(got, r.data.length);
|
|
this.#scatter(mem, x, offset, r.data.subarray(0, got));
|
|
}
|
|
pv.setUint32(p * 16 + 8, got, true);
|
|
pv.setInt32(p * 16 + 12, r ? r.status : -EPROTO, true);
|
|
if (!r || r.status) errors++;
|
|
actual += got;
|
|
}
|
|
} else {
|
|
actual = Math.min(c.actual, x.length);
|
|
if (c.data && actual) {
|
|
actual = Math.min(actual, c.data.length);
|
|
this.#scatter(mem, x, 0, c.data.subarray(0, actual));
|
|
this.stats.bytesIn += actual;
|
|
}
|
|
}
|
|
dv.setUint32(i * USB_DONE_SIZE, c.id, true);
|
|
dv.setInt32(i * USB_DONE_SIZE + 4, c.status, true);
|
|
dv.setUint32(i * USB_DONE_SIZE + 8, actual, true);
|
|
dv.setUint32(i * USB_DONE_SIZE + 12, errors, true);
|
|
this.stats.completed++;
|
|
}
|
|
return n;
|
|
},
|
|
};
|
|
}
|
|
|
|
/** At the snapshot point: the port count and the slots with a device. */
|
|
saveState(): UsbSnapshot {
|
|
return { ports: this.ports, connected: this.#slots.slice(0, this.ports).map((s, i) => (s.connected ? i : -1)).filter((i) => i >= 0) };
|
|
}
|
|
|
|
/**
|
|
* A restored kernel (loadSnapshot, after the IRQ bits were cleared): it
|
|
* does not ask for init again. Every slot starts empty; the kernel's
|
|
* restore notifier disconnects its ports and gives its URBs back.
|
|
*/
|
|
restoreState(s: UsbSnapshot): void {
|
|
this.probed = true;
|
|
this.ports = Math.max(1, Math.min(USB_MAX_PORTS, s.ports | 0));
|
|
this.end?.init(this.ports);
|
|
for (const i of s.connected) {
|
|
const k = this.#slots[i];
|
|
if (k && i < this.ports) {
|
|
k.events |= USB_PORT_EV_CHANGE;
|
|
this.#changed |= 1 << i;
|
|
}
|
|
}
|
|
if (this.#changed) this.#raise();
|
|
}
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// The devices' end.
|
|
|
|
/** Where a slot is. */
|
|
export type UsbPhase = "empty" | "opening" | "connected";
|
|
|
|
/** A slot as Usb.state() and onChange() show it. */
|
|
export interface UsbPortState {
|
|
/** The root hub's port (0-based; the guest's port number is slot + 1). */
|
|
slot: number;
|
|
attached: boolean;
|
|
info: UsbBackendInfo | undefined;
|
|
phase: UsbPhase;
|
|
speed: UsbSpeed | undefined;
|
|
/** The configuration the guest selected (0: none). */
|
|
configuration: number;
|
|
/** Interfaces claimed for the guest. */
|
|
claimed: number[];
|
|
/** Interfaces hidden from the guest (protected classes). */
|
|
hidden: number[];
|
|
/** Where the backend runs in worker mode ("worker": opened in the kernel's worker, "owner": driven over messages), else "inline". */
|
|
runs: "inline" | "worker" | "owner";
|
|
/** The latest failure (attach, a claim, a transfer), if any. */
|
|
error: string | undefined;
|
|
/** Transfers completed, and their bytes in each direction. */
|
|
transfers: number;
|
|
bytesIn: number;
|
|
bytesOut: number;
|
|
/** Resets the device saw (port resets the host did not answer itself). */
|
|
resets: number;
|
|
}
|
|
|
|
export interface UsbStats {
|
|
/** Ports the kernel registered (0 before its driver started, or without one). */
|
|
ports: number;
|
|
probed: boolean;
|
|
attached: number;
|
|
transfers: number;
|
|
bytesIn: number;
|
|
bytesOut: number;
|
|
}
|
|
|
|
export interface UsbAttachOptions {
|
|
/** The slot (default: the first free one). */
|
|
slot?: number;
|
|
/** The device's speed, when the descriptors would say otherwise (deriveSpeed()). */
|
|
speed?: UsbSpeed;
|
|
}
|
|
|
|
/** The USB API on a VM (`vm.usb`): attach backends to the guest's root hub ports and watch them. */
|
|
export interface Usb {
|
|
/** Ports the guest's root hub has. */
|
|
readonly ports: number;
|
|
/** Whether the kernel has the driver (it asked for init). */
|
|
readonly probed: boolean;
|
|
/**
|
|
* Attach `backend`: open it, read its descriptors and connect it to a
|
|
* port; resolves with the slot once the guest can see it. Rejects when
|
|
* the slot is taken, no slot is free, the backend is attached already,
|
|
* or the device cannot be opened or read.
|
|
*/
|
|
attach(backend: UsbBackend, opts?: UsbAttachOptions): Promise<number>;
|
|
/** Disconnect the device in `slot` (its transfers end with -ESHUTDOWN) and close it. */
|
|
detach(slot: number): Promise<void>;
|
|
/** The slot `backend` is attached to, or -1. */
|
|
slotOf(backend: UsbBackend): number;
|
|
state(slot: number): UsbPortState;
|
|
readonly states: UsbPortState[];
|
|
/** Called (from a microtask) when a slot's state changes (not the counters alone); returns the unsubscribe. */
|
|
onChange(listener: (state: UsbPortState) => void): () => void;
|
|
readonly stats: UsbStats;
|
|
}
|
|
|
|
interface Res {
|
|
status: number;
|
|
data?: Uint8Array;
|
|
}
|
|
|
|
interface HX extends UsbXfer {
|
|
/** Cancelled: its result is dropped. */
|
|
gone?: boolean;
|
|
/** OUT and isochronous: finished, waiting for those before it. */
|
|
result?: UsbCompletion;
|
|
}
|
|
|
|
interface Ep {
|
|
address: number;
|
|
epoch: number;
|
|
/** IN: URBs waiting for data, in order. */
|
|
waiting: HX[];
|
|
/** IN: transferIn calls pending (those of cancelled URBs are spares). */
|
|
outstanding: number;
|
|
/** IN: results no URB was waiting for. */
|
|
parked: Res[];
|
|
/** OUT and isochronous: URBs in order, completed in order. */
|
|
queue: HX[];
|
|
}
|
|
|
|
type CtlOp = { k: "xfer"; x: HX } | { k: "reset" };
|
|
|
|
interface Slot {
|
|
backend: UsbBackend | undefined;
|
|
unlisten: (() => void) | undefined;
|
|
/** Counts attaches and detaches: results of an older device are dropped. */
|
|
gen: number;
|
|
phase: UsbPhase;
|
|
runs: UsbPortState["runs"];
|
|
speed: UsbSpeed | undefined;
|
|
device: Uint8Array | undefined;
|
|
/** The configurations as read and as the guest sees them. */
|
|
raw: Uint8Array[];
|
|
shown: Uint8Array[];
|
|
hidden: number[][];
|
|
infos: UsbConfigInfo[];
|
|
configuration: number;
|
|
claimed: Set<number>;
|
|
alts: Map<number, number>;
|
|
/** The guest selected a configuration since the device came or was last reset. */
|
|
configured: boolean;
|
|
ctl: CtlOp[];
|
|
ctlBusy: boolean;
|
|
eps: Map<number, Ep>;
|
|
xfers: Map<number, HX>;
|
|
error: string | undefined;
|
|
transfers: number;
|
|
bytesIn: number;
|
|
bytesOut: number;
|
|
resets: number;
|
|
warned: number;
|
|
}
|
|
|
|
function errText(e: unknown): string {
|
|
const name = (e as { name?: string })?.name;
|
|
const msg = (e as Error)?.message ?? String(e);
|
|
return name && name !== "Error" && !msg.includes(name) ? `${name}: ${msg}` : msg;
|
|
}
|
|
|
|
function statusOf(s: UsbTransferStatus | undefined): number {
|
|
return s === "stall" ? -EPIPE : s === "babble" ? -EOVERFLOW : 0;
|
|
}
|
|
|
|
const TYPES = ["standard", "class", "vendor"] as const;
|
|
const RECIPIENTS = ["device", "interface", "endpoint", "other"] as const;
|
|
|
|
export interface UsbHostOptions {
|
|
/** Ports the guest gets (1..8). */
|
|
ports: number;
|
|
/** The kernel's end (set later with `device`, for createKernel's order). */
|
|
device?: UsbDevice;
|
|
log?: (msg: string) => void;
|
|
/** Interface classes to hide (default USB_PROTECTED_CLASSES). */
|
|
hiddenClasses?: readonly number[];
|
|
}
|
|
|
|
/**
|
|
* The devices' end: backends in slots, the translation of each device's
|
|
* URBs to its backend, and the API (`vm.usb`). It is UsbDevice's `end`.
|
|
*/
|
|
export class UsbHost implements Usb, UsbPortsEnd {
|
|
readonly ports: number;
|
|
#device: UsbDevice | undefined;
|
|
#probed = false;
|
|
#kernelPorts = 0;
|
|
#log: (msg: string) => void;
|
|
#hiddenClasses: readonly number[];
|
|
#slots: Slot[] = [];
|
|
#bySlotOf = new Map<number, number>();
|
|
#listeners = new Set<(s: UsbPortState) => void>();
|
|
#changed = new Set<number>();
|
|
#closed = false;
|
|
|
|
constructor(opts: UsbHostOptions) {
|
|
this.ports = Math.max(1, Math.min(USB_MAX_PORTS, Math.floor(opts.ports)));
|
|
this.#log = opts.log ?? ((m) => console.error(m));
|
|
this.#hiddenClasses = opts.hiddenClasses ?? USB_PROTECTED_CLASSES;
|
|
for (let i = 0; i < this.ports; i++) this.#slots.push(this.#emptySlot());
|
|
if (opts.device) this.device = opts.device;
|
|
}
|
|
|
|
#emptySlot(): Slot {
|
|
return {
|
|
backend: undefined, unlisten: undefined, gen: 0, phase: "empty", runs: "inline", speed: undefined, device: undefined, raw: [], shown: [], hidden: [], infos: [],
|
|
configuration: 0, claimed: new Set(), alts: new Map(), configured: false, ctl: [], ctlBusy: false, eps: new Map(), xfers: new Map(),
|
|
error: undefined, transfers: 0, bytesIn: 0, bytesOut: 0, resets: 0, warned: 0,
|
|
};
|
|
}
|
|
|
|
set device(d: UsbDevice | undefined) {
|
|
this.#device = d;
|
|
if (d) d.end = this;
|
|
}
|
|
|
|
get device(): UsbDevice | undefined {
|
|
return this.#device;
|
|
}
|
|
|
|
get probed(): boolean {
|
|
return this.#probed;
|
|
}
|
|
|
|
get stats(): UsbStats {
|
|
const s = this.#slots;
|
|
return {
|
|
ports: this.#kernelPorts, probed: this.#probed, attached: s.filter((x) => x.backend).length,
|
|
transfers: s.reduce((n, x) => n + x.transfers, 0), bytesIn: s.reduce((n, x) => n + x.bytesIn, 0), bytesOut: s.reduce((n, x) => n + x.bytesOut, 0),
|
|
};
|
|
}
|
|
|
|
#emit(slot: number): void {
|
|
if (this.#changed.has(slot)) return;
|
|
this.#changed.add(slot);
|
|
if (this.#changed.size === 1) queueMicrotask(() => {
|
|
const slots = [...this.#changed];
|
|
this.#changed.clear();
|
|
for (const i of slots) {
|
|
const st = this.state(i);
|
|
for (const l of this.#listeners) try { l(st); } catch {}
|
|
}
|
|
});
|
|
}
|
|
|
|
onChange(listener: (state: UsbPortState) => void): () => void {
|
|
this.#listeners.add(listener);
|
|
return () => this.#listeners.delete(listener);
|
|
}
|
|
|
|
state(slot: number): UsbPortState {
|
|
const s = this.#slots[slot];
|
|
if (!s) throw new RangeError(`usb: no slot ${slot} (the guest has ${this.ports})`);
|
|
return {
|
|
slot, attached: !!s.backend, info: s.backend?.info, phase: s.phase, speed: s.speed, configuration: s.configuration,
|
|
claimed: [...s.claimed].sort((a, b) => a - b), hidden: [...new Set(s.hidden.flat())].sort((a, b) => a - b), runs: s.runs,
|
|
error: s.error, transfers: s.transfers, bytesIn: s.bytesIn, bytesOut: s.bytesOut, resets: s.resets,
|
|
};
|
|
}
|
|
|
|
get states(): UsbPortState[] {
|
|
return this.#slots.map((_, i) => this.state(i));
|
|
}
|
|
|
|
slotOf(backend: UsbBackend): number {
|
|
return this.#slots.findIndex((s) => s.backend === backend);
|
|
}
|
|
|
|
backend(slot: number): UsbBackend | undefined {
|
|
return this.#slots[slot]?.backend;
|
|
}
|
|
|
|
/** @internal Worker mode: where the slot's backend runs (UsbPortState.runs). */
|
|
setRuns(slot: number, runs: UsbPortState["runs"]): void {
|
|
const s = this.#slots[slot];
|
|
if (s) {
|
|
s.runs = runs;
|
|
this.#emit(slot);
|
|
}
|
|
}
|
|
|
|
async attach(backend: UsbBackend, opts: UsbAttachOptions = {}): Promise<number> {
|
|
if (this.#closed) throw new Error("usb: the machine has ended");
|
|
if (this.slotOf(backend) >= 0) throw new Error(`usb: this backend is attached to slot ${this.slotOf(backend)} already`);
|
|
const i = opts.slot ?? this.#slots.findIndex((s) => !s.backend);
|
|
const s = this.#slots[i];
|
|
if (i < 0 || !s) throw new Error(opts.slot === undefined ? `usb: every port is taken (the guest has ${this.ports})` : `usb: no slot ${opts.slot} (the guest has ${this.ports})`);
|
|
if (s.backend) throw new Error(`usb: slot ${i} has a device attached`);
|
|
const fresh = this.#emptySlot();
|
|
Object.assign(s, fresh, { backend, gen: s.gen + 1, phase: "opening", runs: s.runs });
|
|
const gen = s.gen;
|
|
this.#emit(i);
|
|
try {
|
|
await backend.open();
|
|
const device = await this.#descriptor(backend, DT_DEVICE, 0, 18);
|
|
if (device.length < 18 || device[1] !== DT_DEVICE) throw new Error(`the device descriptor is ${device.length} bytes`);
|
|
const raw: Uint8Array[] = [];
|
|
for (let c = 0; c < device[17]!; c++) {
|
|
const head = await this.#descriptor(backend, DT_CONFIG, c, 9);
|
|
if (head.length < 9 || head[1] !== DT_CONFIG) throw new Error(`configuration ${c}: a ${head.length}-byte header`);
|
|
const total = head[2]! | (head[3]! << 8);
|
|
raw.push(total > 9 ? await this.#descriptor(backend, DT_CONFIG, c, total) : head);
|
|
}
|
|
if (s.gen !== gen) throw new Error("detached while attaching");
|
|
s.device = device;
|
|
s.raw = raw;
|
|
for (const c of raw) {
|
|
const f = filterConfig(c, this.#hiddenClasses);
|
|
s.shown.push(f.config);
|
|
s.hidden.push(f.hidden);
|
|
s.infos.push(parseConfig(c));
|
|
}
|
|
s.speed = opts.speed ?? deriveSpeed(device, raw);
|
|
s.unlisten = backend.listen?.(() => this.#lost(i, gen));
|
|
s.phase = "connected";
|
|
const hid = [...new Set(s.hidden.flat())];
|
|
if (hid.length) this.#log(`[usb] slot ${i}: interface${hid.length > 1 ? "s" : ""} ${hid.join(", ")} hidden (a class WebUSB does not let a page claim)`);
|
|
this.#device?.setPort(i, true, s.speed);
|
|
this.#emit(i);
|
|
return i;
|
|
} catch (e) {
|
|
const msg = errText(e);
|
|
if (s.gen === gen) {
|
|
s.backend = undefined;
|
|
s.phase = "empty";
|
|
s.error = `attach: ${msg}`;
|
|
s.gen++;
|
|
this.#emit(i);
|
|
void backend.close().catch(() => {});
|
|
}
|
|
throw new Error(`usb: cannot attach the device: ${msg}`);
|
|
}
|
|
}
|
|
|
|
async #descriptor(b: UsbBackend, type: number, index: number, length: number): Promise<Uint8Array> {
|
|
const r = await b.controlTransferIn({ requestType: "standard", recipient: "device", request: 6, value: (type << 8) | index, index: 0 }, length);
|
|
if (r.status !== "ok" || !r.data) throw new Error(`GET_DESCRIPTOR ${type}/${index}: ${r.status}`);
|
|
return r.data.slice();
|
|
}
|
|
|
|
async detach(slot: number): Promise<void> {
|
|
const s = this.#slots[slot];
|
|
if (!s?.backend) return;
|
|
const b = s.backend;
|
|
this.#disconnect(slot);
|
|
await b.close().catch((e) => this.#log(`[usb] slot ${slot}: close: ${errText(e)}`));
|
|
}
|
|
|
|
#lost(slot: number, gen: number): void {
|
|
const s = this.#slots[slot];
|
|
if (!s || s.gen !== gen || !s.backend) return;
|
|
this.#log(`[usb] slot ${slot}: the device is gone`);
|
|
const b = s.backend;
|
|
s.error = "the device is gone";
|
|
this.#disconnect(slot);
|
|
void b.close().catch(() => {});
|
|
}
|
|
|
|
/** The device leaves the slot: transfers in flight end with -ESHUTDOWN, the port disconnects. */
|
|
#disconnect(slot: number): void {
|
|
const s = this.#slots[slot]!;
|
|
const xfers = [...s.xfers.values()].sort((a, b) => a.id - b.id);
|
|
s.unlisten?.();
|
|
const keep = { gen: s.gen + 1, runs: s.runs, error: s.error, transfers: s.transfers, bytesIn: s.bytesIn, bytesOut: s.bytesOut, resets: s.resets };
|
|
Object.assign(s, this.#emptySlot(), keep);
|
|
for (const x of xfers) this.#device?.complete({ id: x.id, status: -ESHUTDOWN, actual: 0 });
|
|
this.#device?.setPort(slot, false);
|
|
this.#emit(slot);
|
|
}
|
|
|
|
// UsbPortsEnd
|
|
|
|
init(ports: number): void {
|
|
this.#probed = true;
|
|
this.#kernelPorts = ports;
|
|
// The kernel's view starts from nothing: tell it what is connected.
|
|
this.#slots.forEach((s, i) => {
|
|
if (s.phase === "connected") this.#device?.setPort(i, true, s.speed);
|
|
});
|
|
}
|
|
|
|
submit(x: UsbXfer): number {
|
|
const s = this.#slots[x.slot];
|
|
if (!s || s.phase !== "connected" || !s.backend) return -ENODEV;
|
|
const hx = x as HX;
|
|
s.xfers.set(x.id, hx);
|
|
this.#bySlotOf.set(x.id, x.slot);
|
|
if (x.type === USB_XFER_CONTROL) {
|
|
s.ctl.push({ k: "xfer", x: hx });
|
|
this.#pumpCtl(x.slot);
|
|
} else if (x.type === USB_XFER_ISO) {
|
|
this.#iso(x.slot, hx);
|
|
} else if (x.ep & 0x80) {
|
|
this.#in(x.slot, hx);
|
|
} else {
|
|
this.#out(x.slot, hx);
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
cancel(id: number): void {
|
|
const slot = this.#bySlotOf.get(id);
|
|
this.#bySlotOf.delete(id);
|
|
if (slot === undefined) return;
|
|
const s = this.#slots[slot]!;
|
|
const x = s.xfers.get(id);
|
|
if (!x) return;
|
|
s.xfers.delete(id);
|
|
x.gone = true;
|
|
if (x.type === USB_XFER_CONTROL) {
|
|
const i = s.ctl.findIndex((o) => o.k === "xfer" && o.x === x);
|
|
if (i >= 0) s.ctl.splice(i, 1);
|
|
return;
|
|
}
|
|
const ep = s.eps.get(x.ep);
|
|
if (!ep) return;
|
|
const w = ep.waiting.indexOf(x);
|
|
// Its transferIn, if it has one, stays pending: a spare read whose data goes to the next URB.
|
|
if (w >= 0) ep.waiting.splice(w, 1);
|
|
// An OUT or isochronous transfer cannot be stopped either; those after it complete without it.
|
|
const q = ep.queue.indexOf(x);
|
|
if (q >= 0) ep.queue.splice(q, 1);
|
|
this.#flushQueue(s, ep);
|
|
}
|
|
|
|
portOp(slot: number, op: number): number {
|
|
const s = this.#slots[slot];
|
|
if (!s || s.phase !== "connected" || !s.backend) return -ENODEV;
|
|
if (op !== USB_OP_RESET) return 1;
|
|
// The guest's enumeration resets the port (twice); the browser has just enumerated the device.
|
|
if (!s.configured) return 1;
|
|
s.ctl.push({ k: "reset" });
|
|
this.#pumpCtl(slot);
|
|
return 0;
|
|
}
|
|
|
|
#done(s: Slot, x: HX, status: number, actual: number, data?: Uint8Array, packets?: UsbCompletion["packets"]): void {
|
|
if (x.gone || s.xfers.get(x.id) !== x) return;
|
|
s.xfers.delete(x.id);
|
|
this.#bySlotOf.delete(x.id);
|
|
s.transfers++;
|
|
if (x.ep & 0x80 || (x.setup && x.setup[0]! & 0x80)) s.bytesIn += actual;
|
|
else s.bytesOut += actual;
|
|
this.#device?.complete({ id: x.id, status, actual, data, packets });
|
|
}
|
|
|
|
#fail(slot: number, s: Slot, what: string, e: unknown): number {
|
|
const msg = `${what}: ${errText(e)}`;
|
|
s.error = msg;
|
|
if (s.warned++ < 20) this.#log(`[usb] slot ${slot}: ${msg}`);
|
|
this.#emit(slot);
|
|
return -EPROTO;
|
|
}
|
|
|
|
#ep(s: Slot, address: number): Ep {
|
|
let ep = s.eps.get(address);
|
|
if (!ep) s.eps.set(address, (ep = { address, epoch: 0, waiting: [], outstanding: 0, parked: [], queue: [] }));
|
|
return ep;
|
|
}
|
|
|
|
/** Pending transfers of these endpoints were ended (a configuration, alternate setting or reset): what they bring is dropped. */
|
|
#resetEps(s: Slot, addresses?: number[]): void {
|
|
for (const ep of s.eps.values()) {
|
|
if (addresses && !addresses.includes(ep.address)) continue;
|
|
ep.epoch++;
|
|
ep.outstanding = 0;
|
|
ep.parked = [];
|
|
}
|
|
}
|
|
|
|
// Bulk and interrupt IN.
|
|
|
|
#in(slot: number, x: HX): void {
|
|
const s = this.#slots[slot]!;
|
|
const ep = this.#ep(s, x.ep);
|
|
ep.waiting.push(x);
|
|
this.#serveParked(s, ep);
|
|
if (!ep.waiting.includes(x)) return;
|
|
if (ep.outstanding < ep.waiting.length) this.#read(slot, s, ep, x.length);
|
|
}
|
|
|
|
#read(slot: number, s: Slot, ep: Ep, length: number): void {
|
|
const b = s.backend!;
|
|
const gen = s.gen, epoch = ep.epoch;
|
|
ep.outstanding++;
|
|
b.transferIn(ep.address & 0x0f, length).then(
|
|
(r) => this.#result(slot, gen, ep, epoch, { status: statusOf(r.status), data: r.data }),
|
|
(e) => {
|
|
if (s.gen === gen && ep.epoch === epoch) this.#result(slot, gen, ep, epoch, { status: this.#fail(slot, s, `IN 0x${ep.address.toString(16)}`, e) });
|
|
},
|
|
);
|
|
}
|
|
|
|
#result(slot: number, gen: number, ep: Ep, epoch: number, r: Res): void {
|
|
const s = this.#slots[slot]!;
|
|
if (s.gen !== gen || ep.epoch !== epoch) return;
|
|
ep.outstanding = Math.max(0, ep.outstanding - 1);
|
|
ep.parked.push(r);
|
|
this.#serveParked(s, ep);
|
|
}
|
|
|
|
/** Results go to the waiting URBs in order; what a URB has no room for stays parked for the next. */
|
|
#serveParked(s: Slot, ep: Ep): void {
|
|
while (ep.waiting.length && ep.parked.length) {
|
|
const x = ep.waiting.shift()!;
|
|
const r = ep.parked[0]!;
|
|
const data = r.data ?? new Uint8Array(0);
|
|
if (data.length > x.length && !r.status) {
|
|
ep.parked[0] = { status: 0, data: data.subarray(x.length) };
|
|
this.#done(s, x, 0, x.length, data.subarray(0, x.length));
|
|
} else {
|
|
ep.parked.shift();
|
|
this.#done(s, x, r.status, Math.min(data.length, x.length), data);
|
|
}
|
|
}
|
|
}
|
|
|
|
// Bulk and interrupt OUT.
|
|
|
|
#out(slot: number, x: HX): void {
|
|
const s = this.#slots[slot]!;
|
|
const ep = this.#ep(s, x.ep);
|
|
const b = s.backend!, gen = s.gen;
|
|
ep.queue.push(x);
|
|
const data = x.data ?? new Uint8Array(0);
|
|
const zlp = !!(x.flags & USB_X_ZERO_PACKET) && data.length > 0 && x.maxpacket > 0 && data.length % x.maxpacket === 0;
|
|
const run = async (): Promise<UsbCompletion> => {
|
|
const r = await b.transferOut(x.ep & 0x0f, data);
|
|
if (r.status === "ok" && zlp) {
|
|
const z = await b.transferOut(x.ep & 0x0f, new Uint8Array(0));
|
|
if (z.status !== "ok") return { id: x.id, status: statusOf(z.status), actual: r.bytesWritten };
|
|
}
|
|
return { id: x.id, status: statusOf(r.status), actual: r.bytesWritten };
|
|
};
|
|
run().then(
|
|
(c) => {
|
|
if (s.gen === gen) this.#queued(s, ep, x, c);
|
|
},
|
|
(e) => {
|
|
if (s.gen === gen) this.#queued(s, ep, x, { id: x.id, status: this.#fail(slot, s, `OUT 0x${x.ep.toString(16)}`, e), actual: 0 });
|
|
},
|
|
);
|
|
}
|
|
|
|
#queued(s: Slot, ep: Ep, x: HX, c: UsbCompletion): void {
|
|
x.result = c;
|
|
this.#flushQueue(s, ep);
|
|
}
|
|
|
|
#flushQueue(s: Slot, ep: Ep): void {
|
|
while (ep.queue[0]?.result) {
|
|
const x = ep.queue.shift()!;
|
|
const c = x.result!;
|
|
this.#done(s, x, c.status, c.actual, c.data, c.packets);
|
|
}
|
|
}
|
|
|
|
// Isochronous.
|
|
|
|
#iso(slot: number, x: HX): void {
|
|
const s = this.#slots[slot]!;
|
|
const ep = this.#ep(s, x.ep);
|
|
const b = s.backend!, gen = s.gen;
|
|
const lengths = (x.packets ?? []).map((p) => p.length);
|
|
ep.queue.push(x);
|
|
const finish = (c: UsbCompletion) => {
|
|
if (s.gen === gen) this.#queued(s, ep, x, c);
|
|
};
|
|
if (x.ep & 0x80) {
|
|
if (!b.isochronousTransferIn) return finish({ id: x.id, status: -ENOSYS, actual: 0 });
|
|
b.isochronousTransferIn(x.ep & 0x0f, lengths).then(
|
|
(r) => {
|
|
const packets = lengths.map((len, i) => {
|
|
const p = r.packets[i];
|
|
const d = p?.data;
|
|
return { status: p ? statusOf(p.status) : -EPROTO, actual: Math.min(d?.length ?? 0, len), data: d };
|
|
});
|
|
finish({ id: x.id, status: 0, actual: packets.reduce((n, p) => n + p.actual, 0), packets });
|
|
},
|
|
(e) => finish({ id: x.id, status: this.#fail(slot, s, `iso IN 0x${x.ep.toString(16)}`, e), actual: 0 }),
|
|
);
|
|
} else {
|
|
if (!b.isochronousTransferOut) return finish({ id: x.id, status: -ENOSYS, actual: 0 });
|
|
// The packets' bytes, from each packet's offset.
|
|
const all = x.data ?? new Uint8Array(0);
|
|
const data = new Uint8Array(lengths.reduce((n, l) => n + l, 0));
|
|
let at = 0;
|
|
for (const p of x.packets ?? []) {
|
|
data.set(all.subarray(p.offset, p.offset + p.length), at);
|
|
at += p.length;
|
|
}
|
|
b.isochronousTransferOut(x.ep & 0x0f, data, lengths).then(
|
|
(r) => {
|
|
const packets = lengths.map((len, i) => {
|
|
const p = r.packets[i];
|
|
return { status: p ? statusOf(p.status) : -EPROTO, actual: Math.min(p?.bytesWritten ?? 0, len) };
|
|
});
|
|
finish({ id: x.id, status: 0, actual: packets.reduce((n, p) => n + p.actual, 0), packets });
|
|
},
|
|
(e) => finish({ id: x.id, status: this.#fail(slot, s, `iso OUT 0x${x.ep.toString(16)}`, e), actual: 0 }),
|
|
);
|
|
}
|
|
}
|
|
|
|
// Control requests and device operations, one at a time.
|
|
|
|
#pumpCtl(slot: number): void {
|
|
const s = this.#slots[slot]!;
|
|
if (s.ctlBusy) return;
|
|
s.ctlBusy = true;
|
|
const gen = s.gen;
|
|
void (async () => {
|
|
try {
|
|
while (s.gen === gen && s.ctl.length && !this.#closed) {
|
|
const op = s.ctl.shift()!;
|
|
if (op.k === "reset") await this.#reset(slot, s);
|
|
else {
|
|
let c: { status: number; actual: number; data?: Uint8Array };
|
|
try {
|
|
c = await this.#control(slot, s, op.x);
|
|
} catch (e) {
|
|
c = { status: this.#fail(slot, s, `control ${Array.from(op.x.setup!, (b) => b.toString(16).padStart(2, "0")).join("")}`, e), actual: 0 };
|
|
}
|
|
if (s.gen === gen) this.#done(s, op.x, c.status, c.actual, c.data);
|
|
}
|
|
}
|
|
} finally {
|
|
if (s.gen === gen) s.ctlBusy = false;
|
|
}
|
|
})();
|
|
}
|
|
|
|
async #reset(slot: number, s: Slot): Promise<void> {
|
|
const b = s.backend!, gen = s.gen;
|
|
s.resets++;
|
|
try {
|
|
await b.reset();
|
|
} catch (e) {
|
|
if (s.gen !== gen) return;
|
|
this.#log(`[usb] slot ${slot}: reset: ${errText(e)}`);
|
|
s.error = `reset: ${errText(e)}`;
|
|
this.#lost(slot, gen);
|
|
return;
|
|
}
|
|
if (s.gen !== gen) return;
|
|
this.#resetEps(s);
|
|
s.configured = false;
|
|
s.configuration = 0;
|
|
s.alts.clear();
|
|
this.#device?.resetDone(slot);
|
|
this.#emit(slot);
|
|
}
|
|
|
|
/** The interface an endpoint address belongs to in the current configuration, or -1. */
|
|
#ifaceOf(s: Slot, address: number): number {
|
|
const ci = s.infos.findIndex((c) => c.value === s.configuration);
|
|
const ep = ci >= 0 ? s.infos[ci]!.endpoints.find((e) => e.address === address) : undefined;
|
|
return ep ? ep.iface : -1;
|
|
}
|
|
|
|
#hiddenNow(s: Slot, iface: number): boolean {
|
|
const ci = s.infos.findIndex((c) => c.value === s.configuration);
|
|
return s.hidden[ci >= 0 ? ci : 0]?.includes(iface) ?? false;
|
|
}
|
|
|
|
async #control(slot: number, s: Slot, x: HX): Promise<{ status: number; actual: number; data?: Uint8Array }> {
|
|
const b = s.backend!;
|
|
const st = x.setup!;
|
|
const bm = st[0]!, req = st[1]!, value = st[2]! | (st[3]! << 8), index = st[4]! | (st[5]! << 8), wLength = st[6]! | (st[7]! << 8);
|
|
const dirIn = !!(bm & 0x80), type = (bm >> 5) & 3, rcpt = bm & 0x1f;
|
|
const ok = (data?: Uint8Array) => ({ status: 0, actual: data ? Math.min(data.length, wLength) : 0, data: data?.subarray(0, wLength) });
|
|
const stall = { status: -EPIPE, actual: 0 };
|
|
if (type === 3 || rcpt > 3) return stall;
|
|
if (type === 0) {
|
|
if (rcpt === 0 && req === 5) return ok(); // SET_ADDRESS: the device has its address already
|
|
if (rcpt === 0 && req === 6 && dirIn) {
|
|
const dt = value >> 8, di = value & 0xff;
|
|
if (dt === DT_DEVICE) return ok(s.device);
|
|
if (dt === DT_CONFIG) return di < s.shown.length ? ok(s.shown[di]) : stall;
|
|
}
|
|
if (rcpt === 0 && req === 8 && dirIn) return ok(Uint8Array.of(s.configuration));
|
|
if (rcpt === 0 && req === 9) return (await this.#setConfiguration(slot, s, value & 0xff)) ? ok() : stall;
|
|
if (rcpt === 0 && (req === 0x30 || req === 0x31)) return ok(); // SET_SEL, SET_ISOCH_DELAY
|
|
if (rcpt === 1 && (req === 10 || req === 11)) {
|
|
const n = index & 0xff;
|
|
const info = s.infos.find((c) => c.value === s.configuration);
|
|
if (!info || this.#hiddenNow(s, n) || !info.interfaces.some((i) => i.number === n)) return stall;
|
|
if (req === 10) return dirIn ? ok(Uint8Array.of(s.alts.get(n) ?? 0)) : stall;
|
|
if (!s.claimed.has(n)) return stall;
|
|
await b.selectAlternateInterface(n, value & 0xff);
|
|
s.alts.set(n, value & 0xff);
|
|
this.#resetEps(s, info.endpoints.filter((e) => e.iface === n).map((e) => e.address));
|
|
this.#emit(slot);
|
|
return ok();
|
|
}
|
|
if (rcpt === 2 && req === 1 && value === 0) {
|
|
// CLEAR_FEATURE(ENDPOINT_HALT)
|
|
const addr = index & 0xff;
|
|
const iface = this.#ifaceOf(s, addr);
|
|
if (iface < 0 || this.#hiddenNow(s, iface)) return stall;
|
|
await b.clearHalt(addr & 0x80 ? "in" : "out", addr & 0x0f);
|
|
// A stall that a spare read brought back is over; data stays.
|
|
const ep = s.eps.get(addr);
|
|
if (ep) ep.parked = ep.parked.filter((r) => !r.status);
|
|
return ok();
|
|
}
|
|
}
|
|
if (rcpt === 1 && this.#hiddenNow(s, index & 0xff)) return stall;
|
|
if (rcpt === 2) {
|
|
const iface = this.#ifaceOf(s, index & 0xff);
|
|
if (iface >= 0 && this.#hiddenNow(s, iface)) return stall;
|
|
}
|
|
const setup: UsbControlSetup = { requestType: TYPES[type]!, recipient: RECIPIENTS[rcpt]!, request: req, value, index };
|
|
if (dirIn) {
|
|
const r = await b.controlTransferIn(setup, wLength);
|
|
const d = r.data ?? new Uint8Array(0);
|
|
return { status: statusOf(r.status), actual: Math.min(d.length, wLength), data: d };
|
|
}
|
|
const r = await b.controlTransferOut(setup, x.data ?? new Uint8Array(0));
|
|
return { status: statusOf(r.status), actual: r.bytesWritten };
|
|
}
|
|
|
|
async #setConfiguration(slot: number, s: Slot, value: number): Promise<boolean> {
|
|
const b = s.backend!;
|
|
if (value === 0) {
|
|
for (const n of s.claimed) await b.releaseInterface(n).catch(() => {});
|
|
s.claimed.clear();
|
|
s.configuration = 0;
|
|
s.alts.clear();
|
|
this.#resetEps(s);
|
|
this.#emit(slot);
|
|
return true;
|
|
}
|
|
const ci = s.infos.findIndex((c) => c.value === value);
|
|
if (ci < 0) return false;
|
|
await b.selectConfiguration(value);
|
|
this.#resetEps(s);
|
|
s.configuration = value;
|
|
s.configured = true;
|
|
s.alts.clear();
|
|
s.claimed.clear();
|
|
for (const n of new Set(s.infos[ci]!.interfaces.map((i) => i.number))) {
|
|
if (s.hidden[ci]!.includes(n)) continue;
|
|
try {
|
|
await b.claimInterface(n);
|
|
s.claimed.add(n);
|
|
} catch (e) {
|
|
this.#fail(slot, s, `claim interface ${n}`, e);
|
|
}
|
|
}
|
|
this.#emit(slot);
|
|
return true;
|
|
}
|
|
|
|
/** The machine ended: close every device (the backends stay the caller's). */
|
|
shutdown(): void {
|
|
if (this.#closed) return;
|
|
this.#closed = true;
|
|
for (const s of this.#slots) {
|
|
s.unlisten?.();
|
|
s.gen++;
|
|
const b = s.backend;
|
|
s.backend = undefined;
|
|
s.phase = "empty";
|
|
if (b) void b.close().catch(() => {});
|
|
}
|
|
}
|
|
}
|
|
|
|
/** USB options of createKernel (CreateKernelOptions.usb). */
|
|
export interface UsbOption {
|
|
/** Ports the guest's root hub gets, 1 to 8. Default 4. */
|
|
ports?: number;
|
|
/** Backends to attach at boot (each to the next free slot). More attach and detach later through `vm.usb`. */
|
|
attach?: ReadonlyArray<UsbBackend>;
|
|
/** Interface classes to hide from the guest (default USB_PROTECTED_CLASSES). */
|
|
hiddenClasses?: readonly number[];
|
|
/** @internal Worker mode, in the worker: the owner's end of the bridge (worker-serve.ts). */
|
|
bridge?: UsbWorkerBridge;
|
|
}
|
|
|
|
/** The port count a `usb` option asks for (0: no controller). */
|
|
export function usbPorts(opt: boolean | number | UsbOption | undefined): number {
|
|
if (!opt) return 0;
|
|
const n = opt === true ? USB_DEFAULT_PORTS : typeof opt === "number" ? opt : opt.ports ?? USB_DEFAULT_PORTS;
|
|
return Math.max(1, Math.min(USB_MAX_PORTS, Math.floor(n) || USB_DEFAULT_PORTS));
|
|
}
|
|
|
|
/** The usb option's `attach`: each to the next free slot (one that cannot be attached is logged). */
|
|
export function attachUsbBackends(usb: Usb, list: UsbOption["attach"], log: (msg: string) => void): void {
|
|
for (const b of list ?? []) void usb.attach(b).catch((e) => log(`[usb] ${(e as Error).message}`));
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Worker mode: the API on the owner (UsbRemote), the devices in the worker.
|
|
|
|
/** Owner -> worker, in order. */
|
|
export type UsbToWorker =
|
|
| { op: "attach"; req: number; slot?: number; speed?: UsbSpeed; info?: UsbBackendInfo; key?: UsbDeviceKey; bid?: number }
|
|
| { op: "detach"; req: number; slot: number }
|
|
/** The answer to a RemoteUsbBackend call (data transferred). */
|
|
| { op: "reply"; call: number; ok: boolean; value?: unknown; error?: { name: string; message: string } }
|
|
/** A remote backend's device went away. */
|
|
| { op: "lost"; bid: number };
|
|
|
|
/** Worker -> owner, in order. */
|
|
export type UsbFromWorker =
|
|
/** `slot`, or why not; `retry` (after a key): the worker could not open the device itself, attach it from the owner. */
|
|
| { op: "result"; req: number; ok: boolean; slot?: number; error?: string; retry?: boolean }
|
|
/** A call for the owner's backend `bid` (data transferred). */
|
|
| { op: "call"; call: number; bid: number; method: string; args: unknown[] }
|
|
/** The owner may forget backend `bid` (detached). */
|
|
| { op: "forget"; bid: number }
|
|
| { op: "state"; states: UsbPortState[]; stats: UsbStats };
|
|
|
|
/** The ArrayBuffers in a message to transfer. */
|
|
export function usbTransfer(m: UsbToWorker | UsbFromWorker): ArrayBuffer[] {
|
|
const out: ArrayBuffer[] = [];
|
|
const add = (v: unknown) => {
|
|
if (v instanceof Uint8Array && v.buffer instanceof ArrayBuffer && !out.includes(v.buffer)) out.push(v.buffer);
|
|
else if (v && typeof v === "object") for (const x of Array.isArray(v) ? v : Object.values(v)) if (x instanceof Uint8Array || (x && typeof x === "object")) add(x);
|
|
};
|
|
if (m.op === "reply") add(m.value);
|
|
else if (m.op === "call") add(m.args);
|
|
return out;
|
|
}
|
|
|
|
type Calls = Map<number, { resolve: (v: unknown) => void; reject: (e: unknown) => void }>;
|
|
|
|
const REMOTE_METHODS = ["open", "close", "selectConfiguration", "claimInterface", "releaseInterface", "selectAlternateInterface", "clearHalt",
|
|
"controlTransferIn", "controlTransferOut", "transferIn", "transferOut", "isochronousTransferIn", "isochronousTransferOut", "reset"] as const;
|
|
|
|
/** The worker's side of the bridge (worker-serve.ts makes it). */
|
|
export interface UsbWorkerBridge {
|
|
post(m: UsbFromWorker): void;
|
|
/** Opens a WebUSB device of the worker's own navigator.usb by its ids (js/web/usb.ts); absent where there is none. */
|
|
openLocal?(key: UsbDeviceKey): Promise<UsbBackend | undefined>;
|
|
}
|
|
|
|
/**
|
|
* A backend on the owner, in the worker: each method is a "call" message,
|
|
* answered by a "reply". Its calls complete when the worker's event loop
|
|
* runs (the kernel suspended), as every other message does.
|
|
*/
|
|
export class RemoteUsbBackend implements UsbBackend {
|
|
readonly info: UsbBackendInfo | undefined;
|
|
readonly bid: number;
|
|
#calls: Calls;
|
|
#next: () => number;
|
|
#post: (m: UsbFromWorker) => void;
|
|
#lost = new Set<() => void>();
|
|
isochronousTransferIn?: UsbBackend["isochronousTransferIn"];
|
|
isochronousTransferOut?: UsbBackend["isochronousTransferOut"];
|
|
|
|
constructor(bid: number, info: UsbBackendInfo | undefined, calls: Calls, next: () => number, post: (m: UsbFromWorker) => void) {
|
|
this.bid = bid;
|
|
this.info = info;
|
|
this.#calls = calls;
|
|
this.#next = next;
|
|
this.#post = post;
|
|
this.isochronousTransferIn = (ep, lengths) => this.#call("isochronousTransferIn", [ep, lengths]) as Promise<UsbIsoInResult>;
|
|
this.isochronousTransferOut = (ep, data, lengths) => this.#call("isochronousTransferOut", [ep, data, lengths]) as Promise<UsbIsoOutResult>;
|
|
}
|
|
|
|
#call(method: string, args: unknown[]): Promise<unknown> {
|
|
const call = this.#next();
|
|
return new Promise((resolve, reject) => {
|
|
this.#calls.set(call, { resolve, reject });
|
|
this.#post({ op: "call", call, bid: this.bid, method, args });
|
|
});
|
|
}
|
|
|
|
/** The owner said the device went away. */
|
|
lost(): void {
|
|
for (const l of this.#lost) try { l(); } catch {}
|
|
}
|
|
|
|
open() { return this.#call("open", []) as Promise<void>; }
|
|
close() { return this.#call("close", []) as Promise<void>; }
|
|
selectConfiguration(v: number) { return this.#call("selectConfiguration", [v]) as Promise<void>; }
|
|
claimInterface(n: number) { return this.#call("claimInterface", [n]) as Promise<void>; }
|
|
releaseInterface(n: number) { return this.#call("releaseInterface", [n]) as Promise<void>; }
|
|
selectAlternateInterface(n: number, alt: number) { return this.#call("selectAlternateInterface", [n, alt]) as Promise<void>; }
|
|
clearHalt(dir: "in" | "out", ep: number) { return this.#call("clearHalt", [dir, ep]) as Promise<void>; }
|
|
controlTransferIn(setup: UsbControlSetup, length: number) { return this.#call("controlTransferIn", [setup, length]) as Promise<UsbInResult>; }
|
|
controlTransferOut(setup: UsbControlSetup, data?: Uint8Array) { return this.#call("controlTransferOut", [setup, data?.slice()]) as Promise<UsbOutResult>; }
|
|
transferIn(ep: number, length: number) { return this.#call("transferIn", [ep, length]) as Promise<UsbInResult>; }
|
|
transferOut(ep: number, data: Uint8Array) { return this.#call("transferOut", [ep, data.slice()]) as Promise<UsbOutResult>; }
|
|
reset() { return this.#call("reset", []) as Promise<void>; }
|
|
|
|
listen(lost: () => void): () => void {
|
|
this.#lost.add(lost);
|
|
return () => this.#lost.delete(lost);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* The worker's half: UsbHost (next to the kernel) driven by the owner's
|
|
* messages; backends opened here or RemoteUsbBackends.
|
|
*/
|
|
export class UsbWorkerSide {
|
|
readonly host: UsbHost;
|
|
#bridge: UsbWorkerBridge;
|
|
#calls: Calls = new Map();
|
|
#nextCall = 1;
|
|
#remotes = new Map<number, RemoteUsbBackend>();
|
|
#stateQueued = false;
|
|
|
|
constructor(host: UsbHost, bridge: UsbWorkerBridge) {
|
|
this.host = host;
|
|
this.#bridge = bridge;
|
|
host.onChange(() => this.#queueState());
|
|
this.#queueState();
|
|
}
|
|
|
|
#queueState(): void {
|
|
if (this.#stateQueued) return;
|
|
this.#stateQueued = true;
|
|
queueMicrotask(() => {
|
|
this.#stateQueued = false;
|
|
this.#bridge.post({ op: "state", states: this.host.states, stats: this.host.stats });
|
|
});
|
|
}
|
|
|
|
/** Also after a counter changed (the owner's stats()): post the state now. */
|
|
postState(): void {
|
|
this.#queueState();
|
|
}
|
|
|
|
receive(m: UsbToWorker): void {
|
|
switch (m.op) {
|
|
case "reply": {
|
|
const c = this.#calls.get(m.call);
|
|
if (!c) return;
|
|
this.#calls.delete(m.call);
|
|
if (m.ok) c.resolve(m.value);
|
|
else c.reject(Object.assign(new Error(m.error?.message ?? "failed"), { name: m.error?.name ?? "Error" }));
|
|
return;
|
|
}
|
|
case "lost":
|
|
this.#remotes.get(m.bid)?.lost();
|
|
return;
|
|
case "detach":
|
|
void this.host.detach(m.slot).then(() => this.#bridge.post({ op: "result", req: m.req, ok: true }));
|
|
return;
|
|
case "attach":
|
|
void this.#attach(m);
|
|
return;
|
|
}
|
|
}
|
|
|
|
async #attach(m: Extract<UsbToWorker, { op: "attach" }>): Promise<void> {
|
|
const opts = { slot: m.slot, speed: m.speed };
|
|
if (m.key) {
|
|
// A WebUSB device this worker can open itself: driven here, next to the kernel.
|
|
let b: UsbBackend | undefined;
|
|
try {
|
|
b = await this.#bridge.openLocal?.(m.key);
|
|
} catch {}
|
|
if (!b) return this.#bridge.post({ op: "result", req: m.req, ok: false, retry: true, error: "the worker cannot open it" });
|
|
try {
|
|
const slot = await this.host.attach(b, opts);
|
|
this.host.setRuns(slot, "worker");
|
|
this.#bridge.post({ op: "result", req: m.req, ok: true, slot });
|
|
} catch (e) {
|
|
this.#bridge.post({ op: "result", req: m.req, ok: false, retry: true, error: (e as Error).message });
|
|
}
|
|
return;
|
|
}
|
|
const bid = m.bid!;
|
|
const r = new RemoteUsbBackend(bid, m.info, this.#calls, () => this.#nextCall++, (x) => this.#bridge.post(x));
|
|
this.#remotes.set(bid, r);
|
|
try {
|
|
const slot = await this.host.attach(r, opts);
|
|
this.host.setRuns(slot, "owner");
|
|
const off = this.host.onChange((st) => {
|
|
if (st.slot === slot && this.host.backend(slot) !== r) {
|
|
off();
|
|
this.#remotes.delete(bid);
|
|
this.#bridge.post({ op: "forget", bid });
|
|
}
|
|
});
|
|
this.#bridge.post({ op: "result", req: m.req, ok: true, slot });
|
|
} catch (e) {
|
|
this.#remotes.delete(bid);
|
|
this.#bridge.post({ op: "forget", bid });
|
|
this.#bridge.post({ op: "result", req: m.req, ok: false, error: (e as Error).message });
|
|
}
|
|
}
|
|
|
|
shutdown(): void {
|
|
this.host.shutdown();
|
|
for (const c of this.#calls.values()) c.reject(Object.assign(new Error("the machine has ended"), { name: "AbortError" }));
|
|
this.#calls.clear();
|
|
}
|
|
}
|
|
|
|
const EMPTY_STATS: UsbStats = { ports: 0, probed: false, attached: 0, transfers: 0, bytesIn: 0, bytesOut: 0 };
|
|
|
|
/**
|
|
* The USB API on the owner in worker mode (WorkerKernel.usb): attach() and
|
|
* detach() go to the worker's UsbHost, state() is the worker's latest, and
|
|
* the backends that run here answer the worker's calls.
|
|
*/
|
|
export class UsbRemote implements Usb {
|
|
readonly ports: number;
|
|
#post: (m: UsbToWorker, transfer?: ArrayBuffer[]) => void;
|
|
#log: (msg: string) => void;
|
|
#states: UsbPortState[];
|
|
#stats: UsbStats = EMPTY_STATS;
|
|
#listeners = new Set<(s: UsbPortState) => void>();
|
|
#reqs = new Map<number, (m: Extract<UsbFromWorker, { op: "result" }>) => void>();
|
|
#nextReq = 1;
|
|
#nextBid = 1;
|
|
#backends = new Map<number, { b: UsbBackend; unlisten?: () => void }>();
|
|
/** Slot -> the backend attached there (as this side knows it). */
|
|
#bySlot = new Map<number, UsbBackend>();
|
|
#closed = false;
|
|
|
|
constructor(ports: number, post: (m: UsbToWorker, transfer?: ArrayBuffer[]) => void, log?: (msg: string) => void) {
|
|
this.ports = Math.max(1, Math.min(USB_MAX_PORTS, Math.floor(ports)));
|
|
this.#post = post;
|
|
this.#log = log ?? ((m) => console.error(m));
|
|
this.#states = Array.from({ length: this.ports }, (_, slot) => ({
|
|
slot, attached: false, info: undefined, phase: "empty", speed: undefined, configuration: 0, claimed: [], hidden: [], runs: "inline",
|
|
error: undefined, transfers: 0, bytesIn: 0, bytesOut: 0, resets: 0,
|
|
}));
|
|
}
|
|
|
|
get probed(): boolean {
|
|
return this.#stats.probed;
|
|
}
|
|
|
|
get stats(): UsbStats {
|
|
return { ...this.#stats };
|
|
}
|
|
|
|
state(slot: number): UsbPortState {
|
|
const s = this.#states[slot];
|
|
if (!s) throw new RangeError(`usb: no slot ${slot} (the guest has ${this.ports})`);
|
|
return { ...s, claimed: [...s.claimed], hidden: [...s.hidden] };
|
|
}
|
|
|
|
get states(): UsbPortState[] {
|
|
return this.#states.map((_, i) => this.state(i));
|
|
}
|
|
|
|
onChange(listener: (state: UsbPortState) => void): () => void {
|
|
this.#listeners.add(listener);
|
|
return () => this.#listeners.delete(listener);
|
|
}
|
|
|
|
slotOf(backend: UsbBackend): number {
|
|
for (const [slot, b] of this.#bySlot) if (b === backend) return slot;
|
|
return -1;
|
|
}
|
|
|
|
#request(m: Omit<Extract<UsbToWorker, { op: "attach" }>, "req"> | Omit<Extract<UsbToWorker, { op: "detach" }>, "req">): Promise<Extract<UsbFromWorker, { op: "result" }>> {
|
|
const req = this.#nextReq++;
|
|
return new Promise((resolve) => {
|
|
this.#reqs.set(req, resolve);
|
|
this.#post({ ...m, req } as UsbToWorker);
|
|
});
|
|
}
|
|
|
|
async attach(backend: UsbBackend, opts: UsbAttachOptions = {}): Promise<number> {
|
|
if (this.#closed) throw new Error("usb: the machine has ended");
|
|
if (this.slotOf(backend) >= 0 || [...this.#backends.values()].some((x) => x.b === backend)) throw new Error("usb: this backend is attached already");
|
|
const base = { op: "attach" as const, slot: opts.slot, speed: opts.speed, info: backend.info };
|
|
let key: UsbDeviceKey | undefined;
|
|
try {
|
|
key = await backend.workerKey?.();
|
|
} catch {}
|
|
if (key) {
|
|
const r = await this.#request({ ...base, key });
|
|
if (r.ok) {
|
|
this.#bySlot.set(r.slot!, backend);
|
|
return r.slot!;
|
|
}
|
|
if (!r.retry) throw new Error(r.error ?? "usb: attach failed");
|
|
this.#log(`[usb] the kernel's worker could not open ${backend.info?.label ?? "the device"} (${r.error}); it runs on this thread`);
|
|
}
|
|
const bid = this.#nextBid++;
|
|
const entry: { b: UsbBackend; unlisten?: () => void } = { b: backend };
|
|
this.#backends.set(bid, entry);
|
|
entry.unlisten = backend.listen?.(() => this.#post({ op: "lost", bid }));
|
|
const r = await this.#request({ ...base, bid });
|
|
if (!r.ok) {
|
|
this.#forget(bid);
|
|
throw new Error(r.error ?? "usb: attach failed");
|
|
}
|
|
this.#bySlot.set(r.slot!, backend);
|
|
return r.slot!;
|
|
}
|
|
|
|
async detach(slot: number): Promise<void> {
|
|
await this.#request({ op: "detach", slot });
|
|
this.#bySlot.delete(slot);
|
|
}
|
|
|
|
#forget(bid: number): void {
|
|
const e = this.#backends.get(bid);
|
|
if (!e) return;
|
|
e.unlisten?.();
|
|
this.#backends.delete(bid);
|
|
for (const [slot, b] of this.#bySlot) if (b === e.b) this.#bySlot.delete(slot);
|
|
}
|
|
|
|
/** A message from the worker's side. */
|
|
receive(m: UsbFromWorker): void {
|
|
switch (m.op) {
|
|
case "result": {
|
|
const r = this.#reqs.get(m.req);
|
|
this.#reqs.delete(m.req);
|
|
r?.(m);
|
|
return;
|
|
}
|
|
case "forget":
|
|
this.#forget(m.bid);
|
|
return;
|
|
case "state": {
|
|
this.#stats = m.stats;
|
|
const before = this.#states;
|
|
this.#states = m.states;
|
|
for (const st of m.states) {
|
|
const old = before[st.slot];
|
|
if (old && !old.attached && !st.attached) continue;
|
|
if (!st.attached) this.#bySlot.delete(st.slot);
|
|
if (old && JSON.stringify({ ...old, transfers: 0, bytesIn: 0, bytesOut: 0 }) === JSON.stringify({ ...st, transfers: 0, bytesIn: 0, bytesOut: 0 })) continue;
|
|
for (const l of this.#listeners) try { l(this.state(st.slot)); } catch {}
|
|
}
|
|
return;
|
|
}
|
|
case "call":
|
|
void this.#run(m);
|
|
return;
|
|
}
|
|
}
|
|
|
|
async #run(m: Extract<UsbFromWorker, { op: "call" }>): Promise<void> {
|
|
const e = this.#backends.get(m.bid);
|
|
const reply = (r: Omit<Extract<UsbToWorker, { op: "reply" }>, "op" | "call">) => {
|
|
const msg: UsbToWorker = { op: "reply", call: m.call, ...r };
|
|
this.#post(msg, usbTransfer(msg));
|
|
};
|
|
const fn = e && (REMOTE_METHODS as readonly string[]).includes(m.method) ? (e.b as unknown as Record<string, (...a: unknown[]) => Promise<unknown>>)[m.method] : undefined;
|
|
if (!fn) return reply({ ok: false, error: { name: "NotSupportedError", message: `${m.method} is not available` } });
|
|
try {
|
|
const value = await fn.apply(e!.b, m.args);
|
|
reply({ ok: true, value: copyResult(value) });
|
|
} catch (err) {
|
|
reply({ ok: false, error: { name: (err as { name?: string })?.name ?? "Error", message: (err as Error)?.message ?? String(err) } });
|
|
}
|
|
}
|
|
|
|
shutdown(): void {
|
|
this.#closed = true;
|
|
for (const bid of [...this.#backends.keys()]) this.#forget(bid);
|
|
for (const r of this.#reqs.values()) r({ op: "result", req: 0, ok: false, error: "usb: the machine has ended" });
|
|
this.#reqs.clear();
|
|
}
|
|
}
|
|
|
|
/** A backend's result with its bytes in buffers of their own (so they can be transferred). */
|
|
function copyResult(v: unknown): unknown {
|
|
if (!v || typeof v !== "object") return v;
|
|
const r = v as { data?: Uint8Array; packets?: Array<{ data?: Uint8Array }> };
|
|
const out: Record<string, unknown> = { ...(v as object) };
|
|
if (r.data) out.data = r.data.slice();
|
|
if (r.packets) out.packets = r.packets.map((p) => (p.data ? { ...p, data: p.data.slice() } : { ...p }));
|
|
return out;
|
|
}
|