USB Devices
Real USB devices for the guest, through WebUSB, on a USB host controller of its own.
import { createKernel, webUsbBackend } from "unkernel";
const vm = await createKernel({ usb: true }); // a root hub with 4 ports, nothing attached
button.onclick = async () => {
const device = await navigator.usb.requestDevice({ filters: [] }); // WebUSB, from a click
const slot = await vm.usb.attach(webUsbBackend(device)); // the guest enumerates it
};
// in the guest: lsusb, adb devices, fastboot, dfu-util, openocd, rtl_test, /dev/ttyUSB0...The guest sees the device as if it were plugged into its own USB port: its kernel enumerates and configures it, binds a driver (the USB serial drivers for FTDI, CP210x, CH34x and PL2303 adapters make /dev/ttyUSB*), and programs reach the rest through usbfs (/dev/bus/usb), which is what libusb uses. Each transfer goes to the device whole, in order on its endpoint: control requests become controlTransferIn/Out, bulk and interrupt transfers transferIn/Out, isochronous ones isochronousTransferIn/Out. A stall is EPIPE in the guest, as on Linux.
WebUSB keeps some interfaces from pages: audio, HID (keyboards, mice, gamepads), mass storage, hubs, smart cards, video and wireless controllers. Those are hidden from the guest: it sees the device without them. A device made only of such interfaces (a USB stick, a webcam) shows no interface at all. An interface the browser's OS has claimed for its own driver cannot be used either; its transfers fail (EPROTO).
vm.usb.detach(slot) or unplugging the device is a disconnect in the guest: transfers in flight end with ESHUTDOWN. A guest program's reset (libusb_reset_device) resets the real device. vm.usb.state(slot) and onChange() say what is attached, its speed, the configuration the guest chose and which interfaces are claimed or hidden. usb: { ports: 2, attach: [backend] } offers fewer ports and attaches at boot.
webUsbBackend() needs WebUSB: Chromium-based browsers, in a secure context; webUsbBlocker() says why it is missing. In worker mode the kernel's worker opens the same device itself where the browser has WebUSB in dedicated workers, so transfers do not cross to your thread. Otherwise, and for a device it cannot tell apart from another granted one (two identical boards without serial numbers), the device is driven from your thread. Do not claim the device's interfaces yourself. Any object with WebUSB's USBDevice methods can be a backend; FakeUsbBackend is an in-memory test device (a bulk loopback, interrupt and isochronous endpoints, a HID interface to hide) that records every call.
Nothing of a device is in a snapshot (vm.snapshot()): after a restore the guest sees it unplugged.