Files
unkernel/js/core/bluetooth.ts

705 lines
23 KiB
TypeScript

// SPDX-License-Identifier: MIT
// Copyright (C) 2026 Pooya Parsa <pooya@pi0.io>
// Bluetooth for the guest: the host side of kwbt (hci0 in the kernel, a
// plain HCI transport), behind a controller interface at the HCI level, so
// the same transport serves an emulated controller (bluetooth-le.ts:
// VirtualLeController, BLE over a GattCentral such as the browser's Web
// Bluetooth) and real controllers (H4StreamController below: raw H4 over a
// byte stream; later HCI over WebUSB or a raw HCI socket under Node).
//
// A controller is "H4 packets in, H4 packets out, detach": every packet is
// the H4 type byte (1 command, 2 ACL, 3 SCO, 4 event, 5 ISO) and the HCI
// packet after it. One controller is attached at a time; attaching another
// detaches the first, and the guest sees hci0 go and come back, as with a
// USB dongle replaced, so switching from browser BLE to a dedicated adapter
// needs nothing on the guest side.
//
// Two halves, joined by ordered messages (BtDown, BtUp), as serial.ts:
// - BluetoothDevice, the kernel's end, in Kernel (CPU 0's thread, where the
// kernel calls the wasm_driver_bt_* imports and IRQ 14 is raised). None
// of its imports suspends: it keeps the packets received for the kernel,
// the packets in flight to the controller, the attached controller's id
// and the event bits, and sends the rest down.
// - BluetoothHost, the controller's end and the API (`vm.bluetooth`), on
// the thread that owns the machine: attach() and detach(), and the
// controller's packets in both directions.
// Inline both are on one thread; in worker mode BluetoothDevice is in the
// worker and BluetoothHost on the owner, where `navigator.bluetooth` is and
// the controller's objects are (a BluetoothDevice of Web Bluetooth cannot be
// posted), and the messages cross as "bt" batches (worker-protocol.ts).
//
// The kernel's side: each attach gets an id (1..65535, never 0), which the
// status word carries (bits 16-31) and every import names; calls for an id
// that is no longer attached get -ENODEV, so nothing reaches the wrong
// controller. The event bits (cleared by the read): RX (packets waiting),
// TX (room again after -EAGAIN) and CHANGE (an attach or detach). The kernel
// registers hci0 while a controller is attached; hdev open and close (the
// guest's power on and off, and the kernel's own setup) reach the
// controller as open() and close().
//
// Flow: TX_WINDOW packets may be in flight from the kernel to the
// controller (sent, not yet handed to it); past that send answers -EAGAIN
// and the TX event follows once half is free. RX: the host hands the
// kernel's end RX_WINDOW packets at most before it waits for the kernel to
// take some, keeping the rest. HCI's own flow control (command credits,
// Number of Completed Packets) bounds both in practice.
//
// Snapshots keep no controller state: a restored kernel sees its hci0 go
// (the driver's restore notifier) and whatever the new machine attaches
// come, as a new id (BluetoothSnapshot keeps the last id handed out).
/** IRQ bit of kwbt (WASM_IRQ_BT). */
export const IRQ_BT = 14;
/** wasm_driver_bt_status event bits (cleared by the read); the attached id is bits 16-31. */
export const BT_EV_RX = 1 << 0;
export const BT_EV_TX = 1 << 1;
export const BT_EV_CHANGE = 1 << 2;
/** H4 packet types (the first byte of every packet). */
export const H4_COMMAND = 1;
export const H4_ACL = 2;
export const H4_SCO = 3;
export const H4_EVENT = 4;
export const H4_ISO = 5;
/** Packets from the kernel to the controller in flight at most (sent down, not yet handed over). */
export const BT_TX_WINDOW = 64;
/** Packets from the controller waiting for the kernel's read at most, before the host holds them. */
export const BT_RX_WINDOW = 256;
const ENODEV = 19;
const EAGAIN = 11;
/** The bus a controller reports to the kernel (hdev->bus; `btmgmt info`, sysfs). */
export type BluetoothBus = "virtual" | "usb" | "uart" | "sdio" | "virtio";
const BUS_CODE: Record<BluetoothBus, number> = { virtual: 0, usb: 1, uart: 3, sdio: 6, virtio: 10 };
/** Where a controller sends its packets for the guest, and says it is gone. */
export interface BluetoothSink {
/** An H4 packet for the guest: the type byte (4 event, 2 ACL, 3 SCO, 5 ISO), then the packet. */
packet(data: Uint8Array): void;
/** The controller is gone (unplugged, its stream ended, a fatal error): it is detached. */
lost(reason?: string): void;
}
/**
* A Bluetooth controller as the host drives it, at the HCI level. attach()
* starts it, with the sink its packets go to; send() takes the guest's H4
* packets (commands, ACL, SCO, ISO) in order; open() and close() follow the
* kernel's transport (hdev open and close: power on and off, or the
* kernel's setup); detach() ends it, after which it calls the sink no more.
* Every method but detach() returns at once; a controller that needs to
* wait does so on its own (it answers commands when it can).
*/
export interface BluetoothController {
/** The bus the kernel reports (hdev->bus). Default "virtual". */
readonly bus?: BluetoothBus;
/** A name to show (the page's Settings). */
readonly label?: string;
attach(sink: BluetoothSink): void;
/** An H4 packet from the guest (type byte first). */
send(packet: Uint8Array): void;
open?(): void;
close?(): void;
detach(): void | Promise<void>;
}
/** Kernel -> controller (BluetoothDevice to BluetoothHost), in order. `gen` names the host's attach. */
export type BtDown =
| { op: "init" }
| { op: "open"; gen: number }
| { op: "close"; gen: number }
| { op: "send"; gen: number; data: Uint8Array }
| { op: "consumed"; gen: number; n: number };
/** Controller -> kernel (BluetoothHost to BluetoothDevice), in order. */
export type BtUp =
| { op: "attach"; gen: number; bus: number }
| { op: "detach"; gen: number }
| { op: "rx"; gen: number; data: Uint8Array }
| { op: "sent"; gen: number; n: number };
/** The ArrayBuffers of a batch to transfer. */
export function btTransfer(ops: ReadonlyArray<BtDown | BtUp>): ArrayBuffer[] {
const out: ArrayBuffer[] = [];
for (const m of ops) if ((m.op === "send" || m.op === "rx") && m.data.buffer instanceof ArrayBuffer && !out.includes(m.data.buffer)) out.push(m.data.buffer);
return out;
}
/** What a machine snapshot keeps of the device: the last id handed out, so a new attach after the restore is a new id. */
export interface BluetoothSnapshot {
lastId: number;
}
export interface BluetoothDeviceStats {
/** Packets the kernel sent and received. */
txPackets: number;
rxPackets: number;
/** Sends refused with -EAGAIN (the window was full). */
refused: number;
}
export interface BluetoothDeviceOptions {
/** Offer the device (wasm_driver_bt_init answers 1); false: -ENODEV, and the kernel registers nothing. */
enabled?: boolean;
memory: () => WebAssembly.Memory;
raise: () => void;
/** Where the kernel's requests go (BluetoothHost.receive(), or a message to the owner). */
send?: (m: BtDown) => void;
}
/**
* The kernel's end of kwbt (the imports), on the kernel's thread. Up
* messages from BluetoothHost go to receive().
*/
export class BluetoothDevice {
readonly enabled: boolean;
/** Did the kernel ask (wasm_driver_bt_init)? False for a kernel without kwbt. */
probed = false;
send: (m: BtDown) => void;
stats: BluetoothDeviceStats = { txPackets: 0, rxPackets: 0, refused: 0 };
/** The kernel's id of the attached controller (0: none), and the host's gen it stands for. */
#id = 0;
#gen = 0;
#bus = 0;
#lastId = 0;
#rx: Uint8Array[] = [];
#txOut = 0;
#txShort = false;
#events = 0;
#memory: () => WebAssembly.Memory;
#raise: () => void;
constructor(opts: BluetoothDeviceOptions) {
this.enabled = !!opts.enabled;
this.#memory = opts.memory;
this.#raise = opts.raise;
this.send = opts.send ?? (() => {});
}
/** The attached controller's id as the kernel sees it (0: none). */
get id(): number {
return this.#id;
}
/** Packets waiting for the kernel's read. */
get rxPending(): number {
return this.#rx.length;
}
#nextId(): number {
this.#lastId = this.#lastId >= 0xffff ? 1 : this.#lastId + 1;
return this.#lastId;
}
#reset(): void {
this.#rx = [];
this.#txOut = 0;
this.#txShort = false;
}
/** An up message from the controller's end. */
receive(m: BtUp): void {
switch (m.op) {
case "attach":
if (m.gen === this.#gen && this.#id) break; // announced again (at init)
this.#gen = m.gen;
this.#id = this.#nextId();
this.#bus = m.bus;
this.#reset();
this.#events |= BT_EV_CHANGE;
this.#raise();
break;
case "detach":
if (m.gen !== this.#gen || !this.#id) break;
this.#id = 0;
this.#reset();
this.#events |= BT_EV_CHANGE;
this.#raise();
break;
case "rx":
if (m.gen !== this.#gen || !this.#id || m.data.length < 2) break;
this.#rx.push(m.data);
this.#events |= BT_EV_RX;
this.#raise();
break;
case "sent":
if (m.gen !== this.#gen || !this.#id) break;
this.#txOut = Math.max(0, this.#txOut - m.n);
if (this.#txShort && this.#txOut <= BT_TX_WINDOW / 2) {
this.#txShort = false;
this.#events |= BT_EV_TX;
this.#raise();
}
break;
}
}
imports(): Record<string, unknown> {
const u8 = () => new Uint8Array(this.#memory().buffer);
const current = (id: number) => this.#id !== 0 && (id >>> 0) === this.#id;
return {
wasm_driver_bt_init: (): number => {
this.probed = true;
if (!this.enabled) return -ENODEV;
this.send({ op: "init" });
return 1;
},
wasm_driver_bt_status: (): number => {
const s = ((this.#id & 0xffff) << 16) | this.#events;
this.#events = 0;
return s >>> 0;
},
wasm_driver_bt_info: (id: number): number => (current(id) ? this.#bus : -ENODEV),
wasm_driver_bt_open: (id: number): number => {
if (!current(id)) return -ENODEV;
this.send({ op: "open", gen: this.#gen });
return 0;
},
wasm_driver_bt_close: (id: number): void => {
if (!current(id)) return;
this.send({ op: "close", gen: this.#gen });
},
wasm_driver_bt_send: (id: number, buf: number | bigint, len: number): number => {
if (!current(id)) return -ENODEV;
const n = len >>> 0;
if (n < 2) return 0;
if (this.#txOut >= BT_TX_WINDOW) {
this.#txShort = true;
this.stats.refused++;
return -EAGAIN;
}
const at = Number(buf);
this.#txOut++;
this.stats.txPackets++;
this.send({ op: "send", gen: this.#gen, data: u8().slice(at, at + n) });
return 0;
},
wasm_driver_bt_rx_len: (id: number): number => (current(id) && this.#rx.length ? this.#rx[0]!.length : 0),
wasm_driver_bt_recv: (id: number, buf: number | bigint, max: number): number => {
if (!current(id) || !this.#rx.length) return 0;
const p = this.#rx.shift()!;
const room = max >>> 0;
if (room) u8().set(room >= p.length ? p : p.subarray(0, room), Number(buf));
this.stats.rxPackets++;
this.send({ op: "consumed", gen: this.#gen, n: 1 });
return p.length;
},
};
}
/** At the snapshot point. */
saveState(): BluetoothSnapshot {
return { lastId: this.#lastId };
}
/**
* A restored kernel (loadSnapshot): it does not ask for init again, and
* its driver drops the hci_dev it had (its restore notifier). Ids go on
* after the saved one, so the new machine's controller is a new id.
*/
restoreState(s: BluetoothSnapshot): void {
this.probed = true;
this.#lastId = Math.max(this.#lastId, s.lastId & 0xffff);
this.send({ op: "init" });
}
}
/** The guest's adapter as BluetoothHost.state shows it. */
export interface BluetoothState {
/** A controller is attached (the guest has hci0). */
attached: boolean;
/** The attached controller's label and bus. */
label: string | undefined;
bus: BluetoothBus | undefined;
/** The kernel has opened it (hdev open: the guest powered the adapter, or the kernel set it up). */
open: boolean;
/** Packets to and from the guest since the attach. */
packetsIn: number;
packetsOut: number;
/** Why the last controller went, if it was lost. */
error: string | undefined;
}
export interface BluetoothStats {
/** The kernel has kwbt (it asked for init). */
probed: boolean;
attached: boolean;
packetsIn: number;
packetsOut: number;
}
/** The Bluetooth API on a VM (`vm.bluetooth`): attach a controller to the guest and watch it. */
export interface Bluetooth {
/** Whether the kernel has the driver (it asked for init); false before that and for a kernel without one. */
readonly probed: boolean;
/** The attached controller, if any. */
readonly controller: BluetoothController | undefined;
/**
* Attach `controller` (the guest gets hci0). One that is attached already
* is detached first (the guest sees its hci0 go and a new one come).
*/
attach(controller: BluetoothController): Promise<void>;
/** Detach the controller: the guest's hci0 goes, with its connections. */
detach(): Promise<void>;
readonly state: BluetoothState;
/** Called (from a microtask) when the state changes (attach, detach, open, close; not the packet counts alone); returns the unsubscribe. */
onChange(listener: (state: BluetoothState) => void): () => void;
readonly stats: BluetoothStats;
}
export interface BluetoothHostOptions {
/** Where up messages go, a batch at a time in order (to BluetoothDevice.receive(), or a message to the worker). */
send: (ops: BtUp[]) => void;
log?: (msg: string) => void;
}
/**
* The controller's end: the attached controller and the API
* (`vm.bluetooth`). Down messages from BluetoothDevice go to receive().
*/
export class BluetoothHost implements Bluetooth {
#probed = false;
#send: (ops: BtUp[]) => void;
#log: (msg: string) => void;
#ctl: BluetoothController | undefined;
#gen = 0;
#open = false;
#inFlight = 0;
#held: Uint8Array[] = [];
#packetsIn = 0;
#packetsOut = 0;
#error: string | undefined;
#out: BtUp[] = [];
#listeners = new Set<(s: BluetoothState) => void>();
#emitting = false;
#closed = false;
constructor(opts: BluetoothHostOptions) {
this.#send = opts.send;
this.#log = opts.log ?? ((m) => console.error(m));
}
get probed(): boolean {
return this.#probed;
}
get controller(): BluetoothController | undefined {
return this.#ctl;
}
get state(): BluetoothState {
const c = this.#ctl;
return {
attached: !!c, label: c?.label, bus: c ? c.bus ?? "virtual" : undefined, open: !!c && this.#open,
packetsIn: this.#packetsIn, packetsOut: this.#packetsOut, error: this.#error,
};
}
get stats(): BluetoothStats {
return { probed: this.#probed, attached: !!this.#ctl, packetsIn: this.#packetsIn, packetsOut: this.#packetsOut };
}
onChange(listener: (state: BluetoothState) => void): () => void {
this.#listeners.add(listener);
return () => this.#listeners.delete(listener);
}
#emit(): void {
if (this.#emitting) return;
this.#emitting = true;
queueMicrotask(() => {
this.#emitting = false;
const st = this.state;
for (const l of this.#listeners) try { l(st); } catch {}
});
}
// Up messages go out in one batch per microtask, in order.
#up(m: BtUp): void {
if (this.#closed) return;
if (this.#out.push(m) === 1) queueMicrotask(() => this.#flush());
}
#flush(): void {
const ops = this.#out;
this.#out = [];
if (ops.length && !this.#closed) this.#send(ops);
}
async attach(controller: BluetoothController): Promise<void> {
if (this.#closed) throw new Error("bluetooth: the machine has ended");
if (this.#ctl === controller) return;
if (this.#ctl) await this.detach();
const gen = ++this.#gen;
this.#ctl = controller;
this.#open = false;
this.#inFlight = 0;
this.#held = [];
this.#packetsIn = this.#packetsOut = 0;
this.#error = undefined;
const sink: BluetoothSink = {
packet: (data) => this.#fromController(gen, data),
lost: (reason) => {
if (this.#gen !== gen || this.#ctl !== controller) return;
this.#error = reason ?? "the controller is gone";
this.#log(`[bluetooth] ${controller.label ?? "controller"}: ${this.#error}`);
void this.#drop(controller);
},
};
try {
controller.attach(sink);
} catch (e) {
this.#ctl = undefined;
this.#emit();
throw e;
}
this.#up({ op: "attach", gen, bus: BUS_CODE[controller.bus ?? "virtual"] ?? 0 });
this.#emit();
}
async detach(): Promise<void> {
const c = this.#ctl;
if (c) await this.#drop(c);
}
async #drop(c: BluetoothController): Promise<void> {
if (this.#ctl !== c) return;
const gen = this.#gen;
this.#ctl = undefined;
this.#open = false;
this.#held = [];
this.#up({ op: "detach", gen });
this.#gen++; // late packets of the old controller are not this one's
this.#emit();
try {
await c.detach();
} catch (e) {
this.#log(`[bluetooth] detach: ${(e as Error)?.message ?? e}`);
}
}
#fromController(gen: number, data: Uint8Array): void {
if (gen !== this.#gen || !this.#ctl || this.#closed || data.length < 2) return;
this.#packetsOut++;
if (this.#inFlight < BT_RX_WINDOW && !this.#held.length) {
this.#inFlight++;
this.#up({ op: "rx", gen, data });
} else {
this.#held.push(data);
}
}
/** A down message from the kernel's end. */
receive(m: BtDown): void {
if (this.#closed) return;
if (m.op === "init") {
this.#probed = true;
// The kernel's mirror starts from nothing: announce the controller again.
if (this.#ctl) this.#up({ op: "attach", gen: this.#gen, bus: BUS_CODE[this.#ctl.bus ?? "virtual"] ?? 0 });
this.#emit();
return;
}
const c = this.#ctl;
if (!c || m.gen !== this.#gen) return;
switch (m.op) {
case "open":
this.#open = true;
this.#emit();
try { c.open?.(); } catch (e) { this.#log(`[bluetooth] open: ${(e as Error)?.message ?? e}`); }
break;
case "close":
this.#open = false;
this.#emit();
try { c.close?.(); } catch (e) { this.#log(`[bluetooth] close: ${(e as Error)?.message ?? e}`); }
break;
case "send":
this.#packetsIn++;
try {
c.send(m.data);
} catch (e) {
this.#log(`[bluetooth] send: ${(e as Error)?.message ?? e}`);
}
this.#up({ op: "sent", gen: m.gen, n: 1 });
break;
case "consumed":
this.#inFlight = Math.max(0, this.#inFlight - m.n);
while (this.#held.length && this.#inFlight < BT_RX_WINDOW) {
this.#inFlight++;
this.#up({ op: "rx", gen: this.#gen, data: this.#held.shift()! });
}
break;
}
}
/** The machine ended: detach the controller. */
shutdown(): void {
if (this.#closed) return;
const c = this.#ctl;
this.#closed = true;
this.#ctl = undefined;
this.#held = [];
if (c) void Promise.resolve().then(() => c.detach()).catch(() => {});
}
}
export interface BluetoothOption {
/** A controller to attach at boot; more attach() and detach() later through `vm.bluetooth`. */
attach?: BluetoothController;
/** @internal Worker mode, in the worker: the kernel's requests go to the owner (which runs BluetoothHost). */
raw?: { send: (m: BtDown) => void };
}
/** The length of the H4 packet at the start of `buf` (header included), 0 if more bytes are needed, -1 for an unknown type. */
export function h4Length(buf: Uint8Array): number {
if (!buf.length) return 0;
const t = buf[0]!;
const hdr = t === H4_COMMAND ? 3 : t === H4_ACL ? 4 : t === H4_SCO ? 3 : t === H4_EVENT ? 2 : t === H4_ISO ? 4 : -1;
if (hdr < 0) return -1;
if (buf.length < 1 + hdr) return 0;
let len: number;
if (t === H4_COMMAND) len = buf[3]!;
else if (t === H4_ACL) len = buf[3]! | (buf[4]! << 8);
else if (t === H4_SCO) len = buf[3]!;
else if (t === H4_EVENT) len = buf[2]!;
else len = (buf[3]! | (buf[4]! << 8)) & 0x3fff;
return 1 + hdr + len;
}
/** Splits a byte stream into H4 packets. */
export class H4Framer {
#buf = new Uint8Array(0);
/** Feed bytes; returns the whole packets they complete. Throws on an unknown packet type (the stream is out of sync). */
push(bytes: Uint8Array): Uint8Array[] {
let b: Uint8Array;
if (this.#buf.length) {
b = new Uint8Array(this.#buf.length + bytes.length);
b.set(this.#buf);
b.set(bytes, this.#buf.length);
} else {
b = bytes;
}
const out: Uint8Array[] = [];
let at = 0;
for (;;) {
const n = h4Length(b.subarray(at));
if (n < 0) {
this.#buf = new Uint8Array(0);
throw new Error(`H4: unknown packet type 0x${b[at]!.toString(16)}`);
}
if (!n || at + n > b.length) break;
out.push(b.slice(at, at + n));
at += n;
}
this.#buf = b.slice(at);
return out;
}
}
/** A duplex byte stream, as Web Serial's SerialPort (`readable`, `writable`) or a Node stream adapter gives one. */
export interface ByteStream {
readonly readable: ReadableStream<Uint8Array>;
readonly writable: WritableStream<Uint8Array>;
}
export interface H4StreamControllerOptions {
/** Opens the stream at attach (a serial port's open at its rate, a WebUSB claim...). */
open: () => Promise<ByteStream>;
/** Closes it at detach. */
close?: () => Promise<void>;
bus?: BluetoothBus;
label?: string;
log?: (msg: string) => void;
}
/**
* A real controller's HCI over a byte stream with H4 framing (the type
* byte, then the packet): a UART controller on a serial port (115200 8N1
* with RTS/CTS for most), or anything that speaks H4. The stream is opened
* at attach and the packets are passed through as they are; vendor setup
* (firmware, baud changes) is not done here. Not tested on hardware: the
* tests run it over an in-memory stream against VirtualLeController.
*/
export class H4StreamController implements BluetoothController {
readonly bus: BluetoothBus;
readonly label: string | undefined;
#opts: H4StreamControllerOptions;
#sink: BluetoothSink | undefined;
#writer: WritableStreamDefaultWriter<Uint8Array> | undefined;
#reader: ReadableStreamDefaultReader<Uint8Array> | undefined;
#pending: Uint8Array[] = [];
#writing = false;
#ended = false;
constructor(opts: H4StreamControllerOptions) {
this.#opts = opts;
this.bus = opts.bus ?? "uart";
this.label = opts.label;
}
attach(sink: BluetoothSink): void {
this.#sink = sink;
this.#ended = false;
void this.#start();
}
async #start(): Promise<void> {
let stream: ByteStream;
try {
stream = await this.#opts.open();
} catch (e) {
this.#sink?.lost(`open: ${(e as Error)?.message ?? e}`);
return;
}
if (this.#ended) return;
this.#writer = stream.writable.getWriter();
this.#reader = stream.readable.getReader();
void this.#pump();
void this.#read(this.#reader);
}
async #read(reader: ReadableStreamDefaultReader<Uint8Array>): Promise<void> {
const framer = new H4Framer();
try {
for (;;) {
const { value, done } = await reader.read();
if (done || this.#ended) break;
for (const p of framer.push(value)) this.#sink?.packet(p);
}
if (!this.#ended) this.#sink?.lost("the stream ended");
} catch (e) {
if (!this.#ended) this.#sink?.lost(`read: ${(e as Error)?.message ?? e}`);
}
}
send(packet: Uint8Array): void {
if (this.#ended) return;
this.#pending.push(packet);
void this.#pump();
}
async #pump(): Promise<void> {
if (this.#writing || !this.#writer) return;
this.#writing = true;
try {
while (this.#pending.length && !this.#ended) {
const p = this.#pending.shift()!;
await this.#writer.write(p);
}
} catch (e) {
if (!this.#ended) this.#sink?.lost(`write: ${(e as Error)?.message ?? e}`);
} finally {
this.#writing = false;
}
}
async detach(): Promise<void> {
this.#ended = true;
this.#sink = undefined;
this.#pending = [];
try { await this.#reader?.cancel(); } catch {}
try { this.#reader?.releaseLock(); } catch {}
try { await this.#writer?.close(); } catch {}
this.#reader = this.#writer = undefined;
await this.#opts.close?.().catch(() => {});
}
}