From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Pooya Parsa Date: Sun, 29 Nov 2026 14:24:31 +0000 Subject: [PATCH] wasm: kwusb, a USB host controller served by the JavaScript host Gives the guest the host's USB devices (in a browser, devices picked through the WebUSB API) on a host controller with an emulated root hub: a USB 2.0 hub for low, full and high speed devices and a USB 3 hub sharing it (HCD_SHARED) for SuperSpeed ones, up to eight ports, the same slot on either. There are no registers or schedules: every URB goes to the host whole, so nothing is copied in the kernel and nothing crosses per packet. Seven imports, none of which suspends: wasm_driver_usb_init() (the number of ports, 1..8; <= 0: no device, and then nothing is registered or allocated), _submit(xfer) (a struct kwusb_xfer in kernel memory: the id, the slot, the endpoint, the type, URB_ZERO_PACKET, the length, the buffer's segments, the setup packet and the isochronous packet table, which the host reads during the call, copying OUT data then), _reap(done, max) (completions: status, actual length and isochronous errors; the host writes IN data and the isochronous packet results into the URB's own buffers first), _cancel(id) (the host forgets the URB and writes nothing for it any more), _changed() and _port(slot) (connected, the speed, a connection change, a finished reset) and _port_op(slot, op) (a port reset: done at once, or reported by the host later). The host raises WASM_IRQ_USB (13), one bit for everything; the handler reaps in batches of 64 and updates the root hubs' port status. Scatter-gather lists of any shape are passed as segments (sg_tablesize ~0, no_sg_constraint), so usbfs submits a large bulk transfer as one URB. A dequeue cancels at the host and gives the URB back at once with the unlink status. Suspend, power and link state are kept in the root hub's model only. A restored snapshot runs on a new host, which knows none of the URBs or devices: the park restore notifier gives every URB back with -ESHUTDOWN, disconnects every port and reads the ports from the host again. On SMP the host's imports answer on CPU 0 alone, and its interrupt arrives there. A submit, a cancel or a port reset on another CPU, in any context, is queued and raises WASM_IRQ_USB on CPU 0, whose handler submits, cancels and resets in order; an endpoint's URBs keep their order across CPUs. --- drivers/usb/Makefile | 1 + drivers/usb/host/Kconfig | 11 + drivers/usb/host/Makefile | 1 + drivers/usb/host/kwusb.c | 1008 +++++++++++++++++++++++++++++++++++++ 4 files changed, 1021 insertions(+) create mode 100644 drivers/usb/host/kwusb.c diff --git a/drivers/usb/Makefile b/drivers/usb/Makefile --- a/drivers/usb/Makefile +++ b/drivers/usb/Makefile @@ -33,6 +33,7 @@ obj-$(CONFIG_USB_FSL_USB2) += host/ obj-$(CONFIG_USB_FOTG210_HCD) += host/ obj-$(CONFIG_USB_MAX3421_HCD) += host/ obj-$(CONFIG_USB_XEN_HCD) += host/ +obj-$(CONFIG_USB_KWUSB_HCD) += host/ obj-$(CONFIG_USB_C67X00_HCD) += c67x00/ diff --git a/drivers/usb/host/Kconfig b/drivers/usb/host/Kconfig --- a/drivers/usb/host/Kconfig +++ b/drivers/usb/host/Kconfig @@ -733,3 +733,14 @@ config USB_XEN_HCD by the Xen host (usually Dom0). Only needed if the kernel is running in a Xen guest and generic access to a USB device is needed. + +config USB_KWUSB_HCD + bool "unkernel host USB devices (kwusb)" + depends on USB && WASM + help + A host controller for the USB devices of the JavaScript host of a + unkernel instance (in a browser, devices picked through the WebUSB + API), on an emulated root hub with up to eight ports (USB 2.0, and + USB 3 for SuperSpeed devices). The host performs every transfer as + a whole and raises one interrupt for all ports. Without host ports + nothing is registered. diff --git a/drivers/usb/host/Makefile b/drivers/usb/host/Makefile --- a/drivers/usb/host/Makefile +++ b/drivers/usb/host/Makefile @@ -89,3 +89,4 @@ obj-$(CONFIG_USB_HCD_BCMA) += bcma-hcd.o obj-$(CONFIG_USB_HCD_SSB) += ssb-hcd.o obj-$(CONFIG_USB_MAX3421_HCD) += max3421-hcd.o obj-$(CONFIG_USB_XEN_HCD) += xen-hcd.o +obj-$(CONFIG_USB_KWUSB_HCD) += kwusb.o diff --git a/drivers/usb/host/kwusb.c b/drivers/usb/host/kwusb.c new file mode 100644 --- /dev/null +++ b/drivers/usb/host/kwusb.c @@ -0,0 +1,1008 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * kwusb: a USB host controller whose transfers the JavaScript host serves + * (unkernel). + * + * Copyright (C) 2026 Pooya Parsa + * + * The host offers up to eight ports (in a browser, devices picked through + * the WebUSB API; js/core/usb.ts in unkernel). Each is a port of an + * emulated root hub: a USB 2.0 hub for low, full and high speed devices + * and a USB 3 hub sharing it (HCD_SHARED) for SuperSpeed ones, the same + * slot on either. There are no registers and no schedules: every URB is + * handed to the host whole, as a struct kwusb_xfer in kernel memory (the + * endpoint, the type, the flags, the setup packet, the buffer's segments + * and the isochronous packet table), which the host reads during the + * submit call; it copies OUT data then and writes IN data, the actual + * lengths and the isochronous packet results into the URB's own buffers + * during a later reap call, so no data is copied in the kernel and no + * crossing is made per packet. Completions arrive with WASM_IRQ_USB (13), + * one bit for everything, and the handler reaps them in batches. + * + * A cancel (urb_dequeue) tells the host to forget the URB: from then on it + * writes nothing for it, so the URB is given back at once with the unlink + * status (the host keeps whatever a transfer it could not stop brings, + * for the next URB on that endpoint). + * + * Ports: the host's port status word (connected, the speed, a connection + * change, a finished reset) drives the root hub's port status. A port + * reset asks the host (the first ones after a connection are answered at + * once; later ones reset the device), and the port is enabled when the + * host says it is done. Suspend, power and link state are kept here only. + * + * Present only when the host offers ports: wasm_driver_usb_init() <= 0 + * means none, and then nothing is registered or allocated. No import here + * suspends; each is called with kwusb_lock held and interrupts off. + * + * A restored snapshot runs on a new host, which knows none of the URBs or + * devices: the park restore notifier gives every URB back with -ESHUTDOWN + * and disconnects every port, and the ports are read from the host again. + * + * SMP: the host's imports answer on CPU 0 alone, and its interrupt arrives + * there. A submit, cancel or port reset on another CPU (in any context) is + * queued and leaves the work to CPU 0: it raises WASM_IRQ_USB there, and + * the handler submits, cancels and resets in order. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define KWUSB_MAX_PORTS 8 +/* Completion records taken from the host per reap call. */ +#define KWUSB_REAP_BATCH 64 + +/* wasm_driver_usb_port(): levels. */ +#define KWU_PORT_CONNECTED BIT(0) +#define KWU_PORT_SPEED_SHIFT 1 /* enum usb_device_speed, 3 bits */ +#define KWU_PORT_SPEED_MASK 7 +/* Events, cleared by the read. */ +#define KWU_PORT_EV_CHANGE BIT(8) /* a device came or went (maybe both) */ +#define KWU_PORT_EV_RESET BIT(9) /* a reset the host ran has ended */ + +/* wasm_driver_usb_port_op() @op. */ +#define KWU_OP_RESET 1 + +/* struct kwusb_xfer @flags. */ +#define KWU_X_ZERO_PACKET BIT(0) /* URB_ZERO_PACKET */ +#define KWU_X_SHORT_NOT_OK BIT(1) /* URB_SHORT_NOT_OK (usbcore applies it) */ + +/* Host ABI: little endian, in kernel memory, read by the host during submit. */ +struct kwusb_seg { + u64 addr; + u32 len; + u32 pad; +}; + +struct kwusb_xfer { + u32 id; + u8 slot; /* the port, 0-based */ + u8 ep; /* endpoint address: number | USB_DIR_IN */ + u8 type; /* USB_ENDPOINT_XFER_* */ + u8 flags; /* KWU_X_* */ + u32 length; /* bytes to send, or room to receive */ + u32 nseg; /* entries in seg[] */ + u32 maxpacket; /* the endpoint's wMaxPacketSize, bits 0..10 */ + u32 interval; /* urb->interval */ + u32 npackets; /* isochronous: urb->number_of_packets */ + u32 pad; + u64 setup; /* control: the 8-byte setup packet */ + u64 iso; /* isochronous: struct usb_iso_packet_descriptor[npackets] */ + struct kwusb_seg seg[]; +}; + +/* Host ABI: a completion, written by the host during reap. */ +struct kwusb_done { + u32 id; + s32 status; /* 0 or a negative errno */ + u32 actual; /* bytes transferred */ + u32 errors; /* isochronous: packets that failed */ +}; + +/* Host imports, module "unkernel" (js/core/usb.ts). None of them suspends. */ +/* The number of ports the host offers (1..8); <= 0: no device. */ +int wasm_driver_usb_init(void) + __unkernel_import(wasm_driver_usb_init); +/* Bits of the ports whose status has events; the read clears them. */ +u32 wasm_driver_usb_changed(void) + __unkernel_import(wasm_driver_usb_changed); +/* @slot's status word (KWU_PORT_*); the read clears its events. */ +u32 wasm_driver_usb_port(u32 slot) + __unkernel_import(wasm_driver_usb_port); +/* + * Act on @slot's device (KWU_OP_RESET): 1 when done at once, 0 when the + * host reports the end later (KWU_PORT_EV_RESET), < 0 with no device. + */ +int wasm_driver_usb_port_op(u32 slot, u32 op) + __unkernel_import(wasm_driver_usb_port_op); +/* Take @x (the host copies what it needs, and OUT data): 0, or a negative errno. */ +int wasm_driver_usb_submit(const struct kwusb_xfer *x) + __unkernel_import(wasm_driver_usb_submit); +/* Forget transfer @id: the host writes nothing for it any more. */ +void wasm_driver_usb_cancel(u32 id) + __unkernel_import(wasm_driver_usb_cancel); +/* + * Up to @max completions into @done; the host writes each one's IN data + * and isochronous packet results into the URB's buffers first. Returns + * how many. + */ +int wasm_driver_usb_reap(struct kwusb_done *done, u32 max) + __unkernel_import(wasm_driver_usb_reap); + +enum kwusb_state { + KWUSB_PENDING, /* queued on another CPU, not yet given to the host */ + KWUSB_INFLIGHT, /* the host has it */ + KWUSB_CANCELLING, /* unlinked on another CPU, the cancel not yet sent */ +}; + +struct kwusb_urb { + struct list_head node; + struct urb *urb; + struct usb_hcd *hcd; + enum kwusb_state state; + int status; /* for the giveback */ + struct kwusb_xfer x; /* last: its segments follow */ +}; + +struct kwusb_slot { + /* Port status words (wPortStatus | wPortChange << 16) on each root hub. */ + u32 hs, ss; + u8 speed; /* the device's, as the host last said */ + bool present; /* the host has a device in the slot */ + bool on_ss; /* it is on the USB 3 root hub */ + bool live; /* enabled by a finished reset: URBs go to the host */ + bool resetting; /* waiting for the host's reset */ + bool reset_req; /* a reset asked on another CPU, for CPU 0 to send */ +}; + +static DEFINE_SPINLOCK(kwusb_lock); +static unsigned int kwusb_nports; +static struct kwusb_slot kwusb_slots[KWUSB_MAX_PORTS]; +static struct usb_hcd *kwusb_hs, *kwusb_ss; +static struct platform_device *kwusb_pdev; +static DEFINE_IDR(kwusb_ids); +static LIST_HEAD(kwusb_pending); +static LIST_HEAD(kwusb_inflight); +static LIST_HEAD(kwusb_cancelling); +static struct kwusb_done kwusb_done[KWUSB_REAP_BATCH]; +/* Reads every port again (after boot and after a restore), on CPU 0. */ +static struct work_struct kwusb_resync; + +#ifdef CONFIG_SMP +#define KWUSB_CPU 0 +#else +#define KWUSB_CPU WORK_CPU_UNBOUND +#endif + +#define KWUSB_C_MASK ((USB_PORT_STAT_C_CONNECTION | USB_PORT_STAT_C_ENABLE | \ + USB_PORT_STAT_C_SUSPEND | USB_PORT_STAT_C_OVERCURRENT | \ + USB_PORT_STAT_C_RESET | USB_PORT_STAT_C_BH_RESET | \ + USB_PORT_STAT_C_LINK_STATE | USB_PORT_STAT_C_CONFIG_ERROR) << 16) + +static bool kwusb_on_host_cpu(void) +{ + return !IS_ENABLED(CONFIG_SMP) || raw_smp_processor_id() == 0; +} + +/* Leave the work to WASM_IRQ_USB's handler on CPU 0 (another CPU, SMP). */ +static void kwusb_kick(void) +{ +#ifdef CONFIG_SMP + kw_irq_raise(0, BIT(WASM_IRQ_USB)); +#endif +} + +static bool kwusb_is_ss(struct usb_hcd *hcd) +{ + return hcd->speed >= HCD_USB3; +} + +/* The status word of @slot on @hcd's root hub. */ +static u32 *kwusb_word(struct usb_hcd *hcd, unsigned int slot) +{ + return kwusb_is_ss(hcd) ? &kwusb_slots[slot].ss : &kwusb_slots[slot].hs; +} + +/* The speed bits a USB 2.0 port shows for its device. */ +static u32 kwusb_hs_speed_bits(struct kwusb_slot *s) +{ + if (s->speed == USB_SPEED_LOW) + return USB_PORT_STAT_LOW_SPEED; + if (s->speed == USB_SPEED_HIGH) + return USB_PORT_STAT_HIGH_SPEED; + return 0; +} + +/* The callers below hold kwusb_lock. */ + +/* A reset of @slot ended (@ok: the device is there and enabled). */ +static void kwusb_reset_done(unsigned int slot, bool ok) +{ + struct kwusb_slot *s = &kwusb_slots[slot]; + u32 *w = s->on_ss ? &s->ss : &s->hs; + + s->resetting = false; + s->reset_req = false; + if (!(*w & USB_PORT_STAT_RESET)) + return; + *w &= ~USB_PORT_STAT_RESET; + *w |= USB_PORT_STAT_C_RESET << 16; + if (ok && s->present) { + *w |= USB_PORT_STAT_ENABLE; + if (!s->on_ss) + *w |= kwusb_hs_speed_bits(s); + s->live = true; + } +} + +/* Ask the host to reset @slot's device (on the host's CPU). */ +static void kwusb_send_reset(unsigned int slot) +{ + int r; + + kwusb_slots[slot].reset_req = false; + r = wasm_driver_usb_port_op(slot, KWU_OP_RESET); + if (r) + kwusb_reset_done(slot, r > 0); +} + +/* Take @slot's status from the host into the root hubs' port status. */ +static void kwusb_port_update(unsigned int slot, u32 st) +{ + struct kwusb_slot *s = &kwusb_slots[slot]; + bool conn = st & KWU_PORT_CONNECTED; + u8 speed = (st >> KWU_PORT_SPEED_SHIFT) & KWU_PORT_SPEED_MASK; + bool ss = speed >= USB_SPEED_SUPER; + u32 *w; + + if ((st & KWU_PORT_EV_CHANGE) || conn != s->present || (conn && ss != s->on_ss)) { + if (s->present) { + w = s->on_ss ? &s->ss : &s->hs; + *w &= ~(USB_PORT_STAT_CONNECTION | USB_PORT_STAT_ENABLE | + USB_PORT_STAT_SUSPEND | USB_PORT_STAT_RESET | + USB_PORT_STAT_LOW_SPEED | USB_PORT_STAT_HIGH_SPEED); + *w |= USB_PORT_STAT_C_CONNECTION << 16; + } + s->live = false; + s->resetting = false; + s->reset_req = false; + s->present = conn; + s->speed = speed; + s->on_ss = ss; + if (conn) { + w = ss ? &s->ss : &s->hs; + *w |= USB_PORT_STAT_CONNECTION | USB_PORT_STAT_C_CONNECTION << 16; + } + } + if ((st & KWU_PORT_EV_RESET) && s->resetting) + kwusb_reset_done(slot, true); +} + +/* Out of the lists and the id table, off its endpoint: ready for the giveback. */ +static void kwusb_finish(struct kwusb_urb *k, int status, struct list_head *done) +{ + idr_remove(&kwusb_ids, k->x.id); + usb_hcd_unlink_urb_from_ep(k->hcd, k->urb); + k->urb->hcpriv = NULL; + k->status = status; + list_move_tail(&k->node, done); +} + +/* Give back what kwusb_finish() collected; kwusb_lock is not held, interrupts are off. */ +static void kwusb_giveback(struct list_head *done) +{ + struct kwusb_urb *k, *t; + + list_for_each_entry_safe(k, t, done, node) { + struct urb *urb = k->urb; + struct usb_hcd *hcd = k->hcd; + int status = k->status; + + list_del(&k->node); + kfree(k); + usb_hcd_giveback_urb(hcd, urb, status); + } +} + +/* Hand @k to the host; on failure it goes to @done. */ +static void kwusb_submit(struct kwusb_urb *k, struct list_head *done) +{ + int r = wasm_driver_usb_submit(&k->x); + + if (r) { + kwusb_finish(k, r, done); + return; + } + k->state = KWUSB_INFLIGHT; + list_move_tail(&k->node, &kwusb_inflight); +} + +/* Hand the host what other CPUs queued, in order. */ +static void kwusb_flush_pending(struct list_head *done) +{ + struct kwusb_urb *k, *t; + + list_for_each_entry_safe(k, t, &kwusb_pending, node) + kwusb_submit(k, done); +} + +/* Everything CPU 0 does for the host: queued work, completions, ports. */ +static void kwusb_service(struct list_head *done, bool *poll_hs, bool *poll_ss) +{ + struct kwusb_urb *k, *t; + unsigned int i; + u32 changed; + int n; + + kwusb_flush_pending(done); + list_for_each_entry_safe(k, t, &kwusb_cancelling, node) { + wasm_driver_usb_cancel(k->x.id); + kwusb_finish(k, -ECONNRESET, done); /* usbcore gives the unlink status */ + } + for (i = 0; i < kwusb_nports; i++) + if (kwusb_slots[i].reset_req) { + kwusb_send_reset(i); + *(kwusb_slots[i].on_ss ? poll_ss : poll_hs) = true; + } + do { + n = wasm_driver_usb_reap(kwusb_done, KWUSB_REAP_BATCH); + n = clamp(n, 0, KWUSB_REAP_BATCH); + for (i = 0; i < n; i++) { + struct kwusb_done *d = &kwusb_done[i]; + struct urb *urb; + + k = idr_find(&kwusb_ids, d->id); + if (!k || k->state == KWUSB_PENDING) { + pr_warn_once("kwusb: the host completed unknown transfer %u\n", d->id); + continue; + } + urb = k->urb; + urb->actual_length = min(d->actual, urb->transfer_buffer_length); + if (usb_pipeisoc(urb->pipe)) + urb->error_count = d->errors; + kwusb_finish(k, d->status, done); + } + } while (n == KWUSB_REAP_BATCH); + + changed = wasm_driver_usb_changed(); + for (i = 0; i < kwusb_nports; i++) { + if (!(changed & BIT(i))) + continue; + kwusb_port_update(i, wasm_driver_usb_port(i)); + *poll_hs = *poll_ss = true; + } +} + +static void kwusb_poll(bool hs, bool ss) +{ + if (hs && kwusb_hs) + usb_hcd_poll_rh_status(kwusb_hs); + if (ss && kwusb_ss) + usb_hcd_poll_rh_status(kwusb_ss); +} + +static irqreturn_t kwusb_irq(int irq, void *dev_id) +{ + bool poll_hs = false, poll_ss = false; + LIST_HEAD(done); + + spin_lock(&kwusb_lock); + kwusb_service(&done, &poll_hs, &poll_ss); + spin_unlock(&kwusb_lock); + kwusb_giveback(&done); + kwusb_poll(poll_hs, poll_ss); + return IRQ_HANDLED; +} + +static void kwusb_resync_work(struct work_struct *work) +{ + unsigned long flags; + unsigned int i; + + spin_lock_irqsave(&kwusb_lock, flags); + for (i = 0; i < kwusb_nports; i++) + kwusb_port_update(i, wasm_driver_usb_port(i)); + spin_unlock_irqrestore(&kwusb_lock, flags); + kwusb_poll(true, true); +} + +/* hc_driver */ + +static int kwusb_urb_enqueue(struct usb_hcd *hcd, struct urb *urb, gfp_t mem_flags) +{ + struct usb_device *udev = urb->dev; + unsigned int slot = udev->portnum - 1; + unsigned int nseg, len = urb->transfer_buffer_length; + struct usb_endpoint_descriptor *desc = &urb->ep->desc; + struct kwusb_slot *s; + struct kwusb_urb *k; + unsigned long flags; + LIST_HEAD(done); + int ret, id; + + /* Only devices on the root hub's ports: no hub is passed through. */ + if (!udev->parent || udev->parent->parent || slot >= kwusb_nports) + return -ENODEV; + if (!urb->transfer_buffer && !urb->num_sgs && len) + return -EINVAL; + nseg = urb->num_sgs ? urb->num_sgs : !!len; + k = kzalloc(sizeof(*k) + nseg * sizeof(struct kwusb_seg), mem_flags); + if (!k) + return -ENOMEM; + k->urb = urb; + k->hcd = hcd; + k->x.slot = slot; + k->x.ep = usb_endpoint_num(desc) | (usb_urb_dir_in(urb) ? USB_DIR_IN : 0); + k->x.type = usb_endpoint_type(desc); + if (urb->transfer_flags & URB_ZERO_PACKET) + k->x.flags |= KWU_X_ZERO_PACKET; + if (urb->transfer_flags & URB_SHORT_NOT_OK) + k->x.flags |= KWU_X_SHORT_NOT_OK; + k->x.length = len; + k->x.maxpacket = usb_endpoint_maxp(desc); + k->x.interval = urb->interval; + k->x.setup = (uintptr_t)urb->setup_packet; + if (usb_pipeisoc(urb->pipe)) { + k->x.npackets = urb->number_of_packets; + k->x.iso = (uintptr_t)urb->iso_frame_desc; + urb->error_count = 0; + if (urb->transfer_flags & URB_ISO_ASAP) + urb->start_frame = hcd->driver->get_frame_number(hcd); + } + if (urb->num_sgs) { + struct scatterlist *sg; + unsigned int i, left = len; + + nseg = 0; + for_each_sg(urb->sg, sg, urb->num_sgs, i) { + unsigned int n = min(sg->length, left); + + if (!n) + break; + k->x.seg[nseg].addr = (uintptr_t)sg_virt(sg); + k->x.seg[nseg].len = n; + nseg++; + left -= n; + } + } else if (len) { + k->x.seg[0].addr = (uintptr_t)urb->transfer_buffer; + k->x.seg[0].len = len; + } + k->x.nseg = nseg; + + spin_lock_irqsave(&kwusb_lock, flags); + s = &kwusb_slots[slot]; + if (!s->live || s->on_ss != kwusb_is_ss(hcd)) { + ret = -ENODEV; + goto err; + } + ret = usb_hcd_link_urb_to_ep(hcd, urb); + if (ret) + goto err; + id = idr_alloc_cyclic(&kwusb_ids, k, 1, INT_MAX, GFP_ATOMIC); + if (id < 0) { + usb_hcd_unlink_urb_from_ep(hcd, urb); + ret = id; + goto err; + } + k->x.id = id; + urb->hcpriv = k; + INIT_LIST_HEAD(&k->node); + if (kwusb_on_host_cpu() && list_empty(&kwusb_pending)) { + ret = wasm_driver_usb_submit(&k->x); + if (ret) { + idr_remove(&kwusb_ids, id); + usb_hcd_unlink_urb_from_ep(hcd, urb); + urb->hcpriv = NULL; + goto err; + } + k->state = KWUSB_INFLIGHT; + list_add_tail(&k->node, &kwusb_inflight); + } else { + /* After the ones queued before it: an endpoint's URBs keep their order. */ + k->state = KWUSB_PENDING; + list_add_tail(&k->node, &kwusb_pending); + if (kwusb_on_host_cpu()) + kwusb_flush_pending(&done); + else + kwusb_kick(); + } + spin_unlock(&kwusb_lock); + kwusb_giveback(&done); + local_irq_restore(flags); + return 0; + +err: + spin_unlock_irqrestore(&kwusb_lock, flags); + kfree(k); + return ret; +} + +static int kwusb_urb_dequeue(struct usb_hcd *hcd, struct urb *urb, int status) +{ + struct kwusb_urb *k; + unsigned long flags; + LIST_HEAD(done); + int ret; + + spin_lock_irqsave(&kwusb_lock, flags); + ret = usb_hcd_check_unlink_urb(hcd, urb, status); + if (ret) + goto out; + k = urb->hcpriv; + if (!k) + goto out; + switch (k->state) { + case KWUSB_PENDING: + kwusb_finish(k, status, &done); + break; + case KWUSB_INFLIGHT: + if (kwusb_on_host_cpu()) { + wasm_driver_usb_cancel(k->x.id); + kwusb_finish(k, status, &done); + } else { + k->state = KWUSB_CANCELLING; + list_move_tail(&k->node, &kwusb_cancelling); + kwusb_kick(); + } + break; + case KWUSB_CANCELLING: + break; + } +out: + spin_unlock(&kwusb_lock); + kwusb_giveback(&done); + local_irq_restore(flags); + return ret; +} + +static int kwusb_get_frame_number(struct usb_hcd *hcd) +{ + return (ktime_get_ns() / NSEC_PER_MSEC) & 0x7ff; +} + +static int kwusb_hub_status(struct usb_hcd *hcd, char *buf) +{ + int len = DIV_ROUND_UP(kwusb_nports + 1, 8); + bool changed = false; + unsigned long flags; + unsigned int i; + + memset(buf, 0, len); + spin_lock_irqsave(&kwusb_lock, flags); + for (i = 0; i < kwusb_nports; i++) { + if (*kwusb_word(hcd, i) & KWUSB_C_MASK) { + buf[(i + 1) / 8] |= 1 << ((i + 1) % 8); + changed = true; + } + } + if (changed && hcd->state == HC_STATE_SUSPENDED) + usb_hcd_resume_root_hub(hcd); + spin_unlock_irqrestore(&kwusb_lock, flags); + return changed ? len : 0; +} + +/* The root hub of a SuperSpeed bus has a BOS descriptor. */ +static const struct { + struct usb_bos_descriptor bos; + struct usb_ss_cap_descriptor ss_cap; +} __packed kwusb_bos = { + .bos = { + .bLength = USB_DT_BOS_SIZE, + .bDescriptorType = USB_DT_BOS, + .wTotalLength = cpu_to_le16(sizeof(kwusb_bos)), + .bNumDeviceCaps = 1, + }, + .ss_cap = { + .bLength = USB_DT_USB_SS_CAP_SIZE, + .bDescriptorType = USB_DT_DEVICE_CAPABILITY, + .bDevCapabilityType = USB_SS_CAP_TYPE, + .wSpeedSupported = cpu_to_le16(USB_5GBPS_OPERATION), + .bFunctionalitySupport = ilog2(USB_5GBPS_OPERATION), + }, +}; + +static void kwusb_hub_descriptor(struct usb_hcd *hcd, struct usb_hub_descriptor *desc) +{ + int width; + + memset(desc, 0, sizeof(*desc)); + desc->wHubCharacteristics = cpu_to_le16(HUB_CHAR_INDV_PORT_LPSM | HUB_CHAR_COMMON_OCPM); + desc->bNbrPorts = kwusb_nports; + if (kwusb_is_ss(hcd)) { + desc->bDescriptorType = USB_DT_SS_HUB; + desc->bDescLength = USB_DT_SS_HUB_SIZE; + desc->u.ss.bHubHdrDecLat = 0x04; + desc->u.ss.DeviceRemovable = cpu_to_le16(0xffff); + return; + } + desc->bDescriptorType = USB_DT_HUB; + width = desc->bNbrPorts / 8 + 1; + desc->bDescLength = USB_DT_HUB_NONVAR_SIZE + 2 * width; + memset(&desc->u.hs.DeviceRemovable[0], 0, width); + memset(&desc->u.hs.DeviceRemovable[width], 0xff, width); +} + +/* SetPortFeature(PORT_RESET or BH_PORT_RESET), under kwusb_lock. */ +static void kwusb_port_reset(struct usb_hcd *hcd, unsigned int slot) +{ + struct kwusb_slot *s = &kwusb_slots[slot]; + bool here = s->present && s->on_ss == kwusb_is_ss(hcd); + u32 *w = kwusb_word(hcd, slot); + + if (kwusb_is_ss(hcd)) + *w = (*w & ~0xffff) | USB_SS_PORT_STAT_POWER | + (here ? USB_PORT_STAT_CONNECTION : 0) | USB_PORT_STAT_RESET; + else + *w = (*w & ~(USB_PORT_STAT_ENABLE | USB_PORT_STAT_SUSPEND | + USB_PORT_STAT_LOW_SPEED | USB_PORT_STAT_HIGH_SPEED)) | + USB_PORT_STAT_RESET; + if (!here) { + *w &= ~USB_PORT_STAT_RESET; + *w |= USB_PORT_STAT_C_RESET << 16; + return; + } + s->live = false; + s->resetting = true; + if (kwusb_on_host_cpu()) { + kwusb_send_reset(slot); + } else { + s->reset_req = true; + kwusb_kick(); + } +} + +static int kwusb_hub_control(struct usb_hcd *hcd, u16 typeReq, u16 wValue, + u16 wIndex, char *buf, u16 wLength) +{ + bool ss = kwusb_is_ss(hcd); + unsigned int port = wIndex & 0xff; + unsigned long flags; + int ret = 0; + u32 *w = NULL; + + if (!HCD_HW_ACCESSIBLE(hcd)) + return -ETIMEDOUT; + spin_lock_irqsave(&kwusb_lock, flags); + if (port >= 1 && port <= kwusb_nports) + w = kwusb_word(hcd, port - 1); + + switch (typeReq) { + case ClearHubFeature: + break; + case SetHubFeature: + ret = -EPIPE; + break; + case GetHubStatus: + *(__le32 *)buf = cpu_to_le32(0); + break; + case GetHubDescriptor: + if (ss && (wLength < USB_DT_SS_HUB_SIZE || wValue != (USB_DT_SS_HUB << 8))) { + ret = -EPIPE; + break; + } + kwusb_hub_descriptor(hcd, (struct usb_hub_descriptor *)buf); + break; + case DeviceRequest | USB_REQ_GET_DESCRIPTOR: + if (!ss || (wValue >> 8) != USB_DT_BOS) { + ret = -EPIPE; + break; + } + ret = min_t(int, wLength, sizeof(kwusb_bos)); + memcpy(buf, &kwusb_bos, ret); + break; + case GetPortErrorCount: + if (!ss || !w) { + ret = -EPIPE; + break; + } + *(__le32 *)buf = cpu_to_le32(0); + break; + case SetHubDepth: + if (!ss) + ret = -EPIPE; + break; + case GetPortStatus: + if (!w) { + ret = -EPIPE; + break; + } + ((__le16 *)buf)[0] = cpu_to_le16(*w); + ((__le16 *)buf)[1] = cpu_to_le16(*w >> 16); + break; + case ClearPortFeature: + if (!w) { + ret = -EPIPE; + break; + } + switch (wValue) { + case USB_PORT_FEAT_ENABLE: + *w &= ~USB_PORT_STAT_ENABLE; + if (kwusb_slots[port - 1].on_ss == ss) + kwusb_slots[port - 1].live = false; + break; + case USB_PORT_FEAT_SUSPEND: + if (ss) { + ret = -EPIPE; + break; + } + /* Resumed at once: nothing is suspended on the host's side. */ + if (*w & USB_PORT_STAT_SUSPEND) { + *w &= ~USB_PORT_STAT_SUSPEND; + *w |= USB_PORT_STAT_C_SUSPEND << 16; + } + break; + case USB_PORT_FEAT_POWER: + *w &= ~(ss ? USB_SS_PORT_STAT_POWER : USB_PORT_STAT_POWER); + break; + case USB_PORT_FEAT_C_CONNECTION: + case USB_PORT_FEAT_C_ENABLE: + case USB_PORT_FEAT_C_SUSPEND: + case USB_PORT_FEAT_C_OVER_CURRENT: + case USB_PORT_FEAT_C_RESET: + *w &= ~BIT(wValue); + break; + case USB_PORT_FEAT_C_BH_PORT_RESET: + *w &= ~(USB_PORT_STAT_C_BH_RESET << 16); + break; + case USB_PORT_FEAT_C_PORT_LINK_STATE: + *w &= ~(USB_PORT_STAT_C_LINK_STATE << 16); + break; + case USB_PORT_FEAT_C_PORT_CONFIG_ERROR: + *w &= ~(USB_PORT_STAT_C_CONFIG_ERROR << 16); + break; + default: + break; + } + break; + case SetPortFeature: + if (!w) { + ret = -EPIPE; + break; + } + switch (wValue) { + case USB_PORT_FEAT_POWER: + *w |= ss ? USB_SS_PORT_STAT_POWER : USB_PORT_STAT_POWER; + break; + case USB_PORT_FEAT_BH_PORT_RESET: + if (!ss) { + ret = -EPIPE; + break; + } + fallthrough; + case USB_PORT_FEAT_RESET: + kwusb_port_reset(hcd, port - 1); + break; + case USB_PORT_FEAT_SUSPEND: + if (ss) + ret = -EPIPE; + else if (*w & USB_PORT_STAT_ENABLE) + *w |= USB_PORT_STAT_SUSPEND; + break; + case USB_PORT_FEAT_LINK_STATE: + case USB_PORT_FEAT_U1_TIMEOUT: + case USB_PORT_FEAT_U2_TIMEOUT: + case USB_PORT_FEAT_REMOTE_WAKE_MASK: + case USB_PORT_FEAT_FORCE_LINKPM_ACCEPT: + /* No link to manage. */ + if (!ss) + ret = -EPIPE; + break; + case USB_PORT_FEAT_INDICATOR: + case USB_PORT_FEAT_TEST: + break; + default: + ret = -EPIPE; + break; + } + break; + default: + ret = -EPIPE; + break; + } + spin_unlock_irqrestore(&kwusb_lock, flags); + if (w && (READ_ONCE(*w) & KWUSB_C_MASK)) + usb_hcd_poll_rh_status(hcd); + return ret; +} + +static int kwusb_reset(struct usb_hcd *hcd) +{ + if (usb_hcd_is_primary_hcd(hcd)) { + hcd->speed = HCD_USB2; + hcd->self.root_hub->speed = USB_SPEED_HIGH; + } else { + hcd->speed = HCD_USB3; + hcd->self.root_hub->speed = USB_SPEED_SUPER; + } + /* Any list of segments: the host gathers and scatters them. */ + hcd->self.sg_tablesize = ~0; + hcd->self.no_sg_constraint = 1; + return 0; +} + +static int kwusb_start(struct usb_hcd *hcd) +{ + hcd->power_budget = 0; + hcd->uses_new_polling = 1; + hcd->state = HC_STATE_RUNNING; + return 0; +} + +static void kwusb_stop(struct usb_hcd *hcd) +{ +} + +#ifdef CONFIG_PM +static int kwusb_bus_suspend(struct usb_hcd *hcd) +{ + unsigned long flags; + + spin_lock_irqsave(&kwusb_lock, flags); + hcd->state = HC_STATE_SUSPENDED; + spin_unlock_irqrestore(&kwusb_lock, flags); + return 0; +} + +static int kwusb_bus_resume(struct usb_hcd *hcd) +{ + unsigned long flags; + + spin_lock_irqsave(&kwusb_lock, flags); + hcd->state = HC_STATE_RUNNING; + spin_unlock_irqrestore(&kwusb_lock, flags); + return 0; +} +#else +#define kwusb_bus_suspend NULL +#define kwusb_bus_resume NULL +#endif + +static const struct hc_driver kwusb_hc_driver = { + .description = "kwusb", + .product_desc = "unkernel host USB", + .flags = HCD_USB3 | HCD_SHARED, + .reset = kwusb_reset, + .start = kwusb_start, + .stop = kwusb_stop, + .urb_enqueue = kwusb_urb_enqueue, + .urb_dequeue = kwusb_urb_dequeue, + .get_frame_number = kwusb_get_frame_number, + .hub_status_data = kwusb_hub_status, + .hub_control = kwusb_hub_control, + .bus_suspend = kwusb_bus_suspend, + .bus_resume = kwusb_bus_resume, +}; + +/* + * A snapshot was restored: the new host has none of the URBs or devices. + * Every URB comes back with -ESHUTDOWN and every port is disconnected; + * the ports are read from the host again on CPU 0. Runs while every other + * task is parked. + */ +static int kwusb_restored(struct notifier_block *nb, unsigned long action, void *data) +{ + struct kwusb_urb *k, *t; + unsigned long flags; + unsigned int i; + LIST_HEAD(done); + + spin_lock_irqsave(&kwusb_lock, flags); + list_for_each_entry_safe(k, t, &kwusb_pending, node) + kwusb_finish(k, -ESHUTDOWN, &done); + list_for_each_entry_safe(k, t, &kwusb_inflight, node) + kwusb_finish(k, -ESHUTDOWN, &done); + list_for_each_entry_safe(k, t, &kwusb_cancelling, node) + kwusb_finish(k, -ESHUTDOWN, &done); + for (i = 0; i < kwusb_nports; i++) + kwusb_port_update(i, KWU_PORT_EV_CHANGE); + spin_unlock(&kwusb_lock); + kwusb_giveback(&done); + local_irq_restore(flags); + queue_work_on(KWUSB_CPU, system_percpu_wq, &kwusb_resync); + return NOTIFY_OK; +} + +static struct notifier_block kwusb_restore_nb = { + .notifier_call = kwusb_restored, +}; + +static int kwusb_probe(struct platform_device *pdev) +{ + struct usb_hcd *hs, *ss; + int err; + + hs = usb_create_hcd(&kwusb_hc_driver, &pdev->dev, dev_name(&pdev->dev)); + if (!hs) + return -ENOMEM; + hs->has_tt = 1; + err = usb_add_hcd(hs, 0, 0); + if (err) + goto err_put_hs; + ss = usb_create_shared_hcd(&kwusb_hc_driver, &pdev->dev, dev_name(&pdev->dev), hs); + if (!ss) { + err = -ENOMEM; + goto err_remove_hs; + } + err = usb_add_hcd(ss, 0, 0); + if (err) + goto err_put_ss; + kwusb_hs = hs; + kwusb_ss = ss; + err = request_irq(WASM_IRQ_USB, kwusb_irq, 0, "kwusb", kwusb_slots); + if (err) + goto err_remove_ss; + kw_park_register_restore_notifier(&kwusb_restore_nb); + /* Devices the host attached before the handler was there. */ + queue_work_on(KWUSB_CPU, system_percpu_wq, &kwusb_resync); + return 0; + +err_remove_ss: + kwusb_hs = kwusb_ss = NULL; + usb_remove_hcd(ss); +err_put_ss: + usb_put_hcd(ss); +err_remove_hs: + usb_remove_hcd(hs); +err_put_hs: + usb_put_hcd(hs); + return err; +} + +static struct platform_driver kwusb_platform_driver = { + .probe = kwusb_probe, + .driver = { + .name = "kwusb", + .suppress_bind_attrs = true, + }, +}; + +static int __init kwusb_init(void) +{ + int n, err; + + if (usb_disabled()) + return 0; + n = wasm_driver_usb_init(); + if (n <= 0) + return 0; + kwusb_nports = min(n, KWUSB_MAX_PORTS); + INIT_WORK(&kwusb_resync, kwusb_resync_work); + err = platform_driver_register(&kwusb_platform_driver); + if (err) + goto err_ports; + kwusb_pdev = platform_device_register_simple("kwusb", -1, NULL, 0); + if (IS_ERR(kwusb_pdev)) { + err = PTR_ERR(kwusb_pdev); + goto err_driver; + } + if (!kwusb_hs) { + err = -ENODEV; + goto err_pdev; + } + pr_info("kwusb: %u host USB port(s)\n", kwusb_nports); + return 0; + +err_pdev: + platform_device_unregister(kwusb_pdev); +err_driver: + platform_driver_unregister(&kwusb_platform_driver); +err_ports: + kwusb_nports = 0; + return err; +} +device_initcall(kwusb_init);