mirror of
https://github.com/pithings/unkernel.git
synced 2026-12-02 03:10:15 +08:00
1353 lines
46 KiB
TypeScript
1353 lines
46 KiB
TypeScript
// SPDX-License-Identifier: MIT
|
|
// Copyright (C) 2026 Pooya Parsa <pooya@pi0.io>
|
|
// Serial ports for the guest: the host side of kwserial (/dev/ttyACM0..3 on
|
|
// serial_core in the kernel), behind a small backend interface, so the same
|
|
// model serves a real port (js/web/serial.ts: Web Serial's SerialPort) and
|
|
// FakeSerialBackend (below: a loopback for tests and the CLI's --serial).
|
|
//
|
|
// Two halves, joined by ordered messages (SerialDown, SerialUp):
|
|
// - SerialDevice, the kernel's end, in Kernel (CPU 0's thread, where the
|
|
// kernel calls the wasm_driver_serial_* imports and IRQ 12 is raised).
|
|
// None of its imports suspends: it keeps what the kernel must be answered
|
|
// at once (whether a backend is attached, the RX bytes received, the TX
|
|
// bytes in flight, the input signal levels and the event bits) and sends
|
|
// the rest down.
|
|
// - SerialHost, the ports' end and the API (`vm.serial`), on the thread
|
|
// that owns the machine: attach and detach backends, and per port the
|
|
// physical open, config, signals, writes and the reader, each in order.
|
|
// Inline both are on one thread; in worker mode SerialDevice is in the
|
|
// worker and SerialHost on the owner, where `navigator.serial.requestPort()`
|
|
// is (a page's window) and the backends are (SerialPort objects cannot be
|
|
// posted), and the messages cross as "serial" batches (worker-protocol.ts).
|
|
//
|
|
// The kernel's side of a port:
|
|
// - open(port): -ENODEV without a backend; else a new session (`gen`), and
|
|
// SerialHost opens the port physically, later: the open waits
|
|
// OPEN_DEBOUNCE_MS after the latest config (OPEN_DEBOUNCE_MAX_MS after
|
|
// the open at most), so the open, config and signals of a tty open
|
|
// become one physical open with the guest's settings. A failure is the
|
|
// hangup event.
|
|
// - config(): Web Serial cannot change an open port's settings, so a
|
|
// different config while open is a close and a reopen, in order with the
|
|
// writes and signal changes around it (each waits for the one before);
|
|
// the same config does nothing. After a reopen the guest's last signal
|
|
// state is set again (the OS may have changed DTR and RTS).
|
|
// - set_signals(): every state, in order with the writes, never merged.
|
|
// - write(): TX_WINDOW bytes may be in flight (accepted, not yet written
|
|
// out); a short write sets the "TX room" event once half of it is free.
|
|
// "TX empty" (a level) is no bytes in flight.
|
|
// - RX: the reader takes what the port gives while fewer than RX_WINDOW
|
|
// bytes wait for the kernel, and stops reading meanwhile, so a fast
|
|
// sender is held by the OS (and RTS/CTS where enabled) rather than
|
|
// dropped here.
|
|
// - The input signals (CTS, DSR, DCD, RI) have no change event in Web
|
|
// Serial: polled every POLL_MS while the guest has the port open.
|
|
// - Hangup (the event): the device was lost, detached while open, or its
|
|
// open or reopen failed. The session's later writes are dropped, and it
|
|
// stays hung until the kernel closes the port.
|
|
// Read errors map to the event bits: BreakError, FramingError, ParityError,
|
|
// BufferOverrunError and BufferOverflowError (the reader goes on), and
|
|
// NetworkError (the device is gone: hangup, and the backend is detached).
|
|
//
|
|
// Snapshots keep no port state: SerialDevice saves which ports the guest
|
|
// had open, and a restored machine sees each of them hung up. A snapshot
|
|
// with the device restores without it too (the restored kernel's opens get
|
|
// ENODEV) and the reverse (its kernel never registered a port).
|
|
|
|
/** IRQ bit for every serial port (WASM_IRQ_SERIAL). */
|
|
export const IRQ_SERIAL = 12;
|
|
/** Ports the device offers at most, and by default. */
|
|
export const SERIAL_MAX_PORTS = 4;
|
|
|
|
/** Status bits (wasm_driver_serial_status): levels, not cleared by the read. */
|
|
export const SERIAL_CTS = 1 << 0;
|
|
export const SERIAL_DSR = 1 << 1;
|
|
export const SERIAL_DCD = 1 << 2;
|
|
export const SERIAL_RI = 1 << 3;
|
|
export const SERIAL_ATTACHED = 1 << 4;
|
|
export const SERIAL_TX_EMPTY = 1 << 5;
|
|
/** Event bits, cleared by the read. */
|
|
export const SERIAL_EV_RX = 1 << 8;
|
|
export const SERIAL_EV_TX_ROOM = 1 << 9;
|
|
export const SERIAL_EV_SIGNALS = 1 << 11;
|
|
export const SERIAL_EV_HANGUP = 1 << 12;
|
|
export const SERIAL_EV_BREAK = 1 << 16;
|
|
export const SERIAL_EV_FRAMING = 1 << 17;
|
|
export const SERIAL_EV_PARITY = 1 << 18;
|
|
export const SERIAL_EV_OVERRUN = 1 << 19;
|
|
/** wasm_driver_serial_set_signals bits. */
|
|
export const SERIAL_SIG_DTR = 1 << 0;
|
|
export const SERIAL_SIG_RTS = 1 << 1;
|
|
export const SERIAL_SIG_BREAK = 1 << 2;
|
|
|
|
/**
|
|
* Bytes accepted from the guest and not yet written out, at most (per
|
|
* port): kwserial's FIFO size, since tcdrain without CRTSCTS waits at most
|
|
* twice the time that many characters take at the port's rate.
|
|
*/
|
|
export const SERIAL_TX_WINDOW = 4096;
|
|
/** Bytes received and not yet taken by the kernel before the reader waits (per port). */
|
|
export const SERIAL_RX_WINDOW = 65536;
|
|
/** The physical open waits this long after the guest's latest config... */
|
|
export const OPEN_DEBOUNCE_MS = 30;
|
|
/** ...but no longer than this after the guest's open. */
|
|
export const OPEN_DEBOUNCE_MAX_MS = 250;
|
|
/** How often the input signals are read while the guest has a port open. */
|
|
export const SERIAL_POLL_MS = 75;
|
|
/** Consecutive writes are written out as one chunk of at most this many bytes. */
|
|
const WRITE_CHUNK = 16384;
|
|
|
|
const ENODEV = 19;
|
|
|
|
/** The read errors that are events (the reader goes on), by DOMException name. */
|
|
const READ_ERROR_BITS: Record<string, number> = {
|
|
BreakError: SERIAL_EV_BREAK,
|
|
FramingError: SERIAL_EV_FRAMING,
|
|
ParityError: SERIAL_EV_PARITY,
|
|
BufferOverrunError: SERIAL_EV_OVERRUN,
|
|
BufferOverflowError: SERIAL_EV_OVERRUN,
|
|
};
|
|
|
|
/** A port's line settings, as Web Serial's open() takes them. */
|
|
export interface SerialConfig {
|
|
baudRate: number;
|
|
/** 5 to 8 (Web Serial opens 7 or 8 only: js/web/serial.ts). */
|
|
dataBits: number;
|
|
stopBits: 1 | 2;
|
|
parity: "none" | "odd" | "even";
|
|
flowControl: "none" | "hardware";
|
|
}
|
|
|
|
/** The output signals the guest sets (Web Serial's SerialOutputSignals). */
|
|
export interface SerialOutputSignals {
|
|
dataTerminalReady: boolean;
|
|
requestToSend: boolean;
|
|
break: boolean;
|
|
}
|
|
|
|
/** The input signals (Web Serial's SerialInputSignals). */
|
|
export interface SerialInputSignals {
|
|
clearToSend: boolean;
|
|
dataSetReady: boolean;
|
|
dataCarrierDetect: boolean;
|
|
ringIndicator: boolean;
|
|
}
|
|
|
|
/** What a backend says about itself (Web Serial's getInfo(), and a label to show). */
|
|
export interface SerialBackendInfo {
|
|
usbVendorId?: number;
|
|
usbProductId?: number;
|
|
label?: string;
|
|
}
|
|
|
|
/**
|
|
* One serial device as the host drives it. Every method but read() is
|
|
* called in order, one at a time (each awaited before the next); read()
|
|
* runs alongside them while the port is open, and close() makes a pending
|
|
* read() resolve null. A read error is thrown with a `name` (the
|
|
* DOMException names of Web Serial: BreakError, FramingError, ParityError,
|
|
* BufferOverrunError, BufferOverflowError are events, and the next read()
|
|
* goes on; NetworkError means the device is gone; any other ends the
|
|
* session as a hangup). close() is called after a failed open too, and may
|
|
* come while a write() is pending (a session closed while the device holds
|
|
* its writes, e.g. with CTS low): it should make that write settle.
|
|
*/
|
|
export interface SerialBackend {
|
|
readonly info?: SerialBackendInfo;
|
|
open(config: SerialConfig): Promise<void>;
|
|
close(): Promise<void>;
|
|
/** The next bytes received, or null once closed. */
|
|
read(): Promise<Uint8Array | null>;
|
|
/** Resolves once `data` is written out (as far as the platform tells). */
|
|
write(data: Uint8Array): Promise<void>;
|
|
setSignals(signals: SerialOutputSignals): Promise<void>;
|
|
getSignals(): Promise<SerialInputSignals>;
|
|
/** Call `lost` when the device goes away (unplugged); returns the unsubscribe. */
|
|
listen?(lost: () => void): () => void;
|
|
}
|
|
|
|
/** wasm_driver_serial_config's (baud, cfg) as a SerialConfig; baud 0 (B0) keeps `prev`'s rate. */
|
|
export function decodeSerialConfig(baud: number, cfg: number, prev?: SerialConfig): SerialConfig {
|
|
const bits = cfg & 0xf;
|
|
const par = (cfg >> 5) & 3;
|
|
return {
|
|
baudRate: baud > 0 ? baud : prev?.baudRate ?? 9600,
|
|
dataBits: bits >= 5 && bits <= 8 ? bits : 8,
|
|
stopBits: cfg & 0x10 ? 2 : 1,
|
|
parity: par === 1 ? "odd" : par === 2 ? "even" : "none",
|
|
flowControl: cfg & 0x80 ? "hardware" : "none",
|
|
};
|
|
}
|
|
|
|
/** The cfg word for a SerialConfig (decodeSerialConfig's inverse). */
|
|
export function encodeSerialConfig(c: Omit<SerialConfig, "baudRate">): number {
|
|
return (c.dataBits & 0xf) | (c.stopBits === 2 ? 0x10 : 0) | ((c.parity === "odd" ? 1 : c.parity === "even" ? 2 : 0) << 5) | (c.flowControl === "hardware" ? 0x80 : 0);
|
|
}
|
|
|
|
function sameConfig(a: SerialConfig | undefined, b: SerialConfig): boolean {
|
|
return !!a && a.baudRate === b.baudRate && a.dataBits === b.dataBits && a.stopBits === b.stopBits && a.parity === b.parity && a.flowControl === b.flowControl;
|
|
}
|
|
|
|
function signalsOf(bits: number): SerialOutputSignals {
|
|
return { dataTerminalReady: !!(bits & SERIAL_SIG_DTR), requestToSend: !!(bits & SERIAL_SIG_RTS), break: !!(bits & SERIAL_SIG_BREAK) };
|
|
}
|
|
|
|
function levelBits(s: SerialInputSignals): number {
|
|
return (s.clearToSend ? SERIAL_CTS : 0) | (s.dataSetReady ? SERIAL_DSR : 0) | (s.dataCarrierDetect ? SERIAL_DCD : 0) | (s.ringIndicator ? SERIAL_RI : 0);
|
|
}
|
|
|
|
/** Kernel -> ports (SerialDevice to SerialHost), in order. */
|
|
export type SerialDown =
|
|
| { op: "init"; ports: number }
|
|
| { op: "open"; port: number; gen: number }
|
|
| { op: "close"; port: number }
|
|
| { op: "config"; port: number; baud: number; cfg: number }
|
|
| { op: "signals"; port: number; signals: number }
|
|
| { op: "write"; port: number; data: Uint8Array }
|
|
| { op: "consumed"; port: number; n: number }
|
|
/** The guest opened a port that has no backend (ENODEV); at most one a second for a port. */
|
|
| { op: "wanted"; port: number };
|
|
|
|
/** Ports -> kernel (SerialHost to SerialDevice), in order. `gen` names the session (stale ones are dropped). */
|
|
export type SerialUp =
|
|
| { op: "attached"; port: number; on: boolean }
|
|
| { op: "rx"; port: number; gen: number; data: Uint8Array }
|
|
| { op: "written"; port: number; gen: number; n: number }
|
|
| { op: "levels"; port: number; levels: number }
|
|
| { op: "event"; port: number; gen: number; bits: number };
|
|
|
|
/** The ArrayBuffers of a batch to transfer. */
|
|
export function serialTransfer(ops: ReadonlyArray<SerialDown | SerialUp>): ArrayBuffer[] {
|
|
const out: ArrayBuffer[] = [];
|
|
for (const m of ops) if ((m.op === "write" || 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: how many ports, and which the guest had open (they come back hung up). */
|
|
export interface SerialSnapshot {
|
|
ports: number;
|
|
open: number[];
|
|
}
|
|
|
|
export interface SerialDeviceStats {
|
|
/** Bytes the guest wrote (accepted) and read, over all ports. */
|
|
txBytes: number;
|
|
rxBytes: number;
|
|
/** Writes accepted only in part (the TX window was full). */
|
|
shortWrites: number;
|
|
}
|
|
|
|
export interface SerialDeviceOptions {
|
|
/** Ports to offer (1..4); 0 or undefined: no device (wasm_driver_serial_init returns -ENODEV). */
|
|
ports?: number;
|
|
memory: () => WebAssembly.Memory;
|
|
raise: () => void;
|
|
/** Where the kernel's requests go (SerialHost.receive(), or a message to the owner). */
|
|
send?: (m: SerialDown) => void;
|
|
}
|
|
|
|
interface KPort {
|
|
attached: boolean;
|
|
open: boolean;
|
|
gen: number;
|
|
/** This session hung up: writes are dropped until the close. */
|
|
hung: boolean;
|
|
rx: Uint8Array[];
|
|
rxOff: number;
|
|
txOut: number;
|
|
txShort: boolean;
|
|
levels: number;
|
|
events: number;
|
|
}
|
|
|
|
/**
|
|
* The kernel's end of kwserial (the imports), on the kernel's thread. Up
|
|
* messages from SerialHost go to receive().
|
|
*/
|
|
export class SerialDevice {
|
|
readonly enabled: boolean;
|
|
/** Ports offered (0 without the device; a restore takes the snapshot's). */
|
|
ports: number;
|
|
/** Did the kernel ask (wasm_driver_serial_init)? False for a kernel without kwserial. */
|
|
probed = false;
|
|
send: (m: SerialDown) => void;
|
|
stats: SerialDeviceStats = { txBytes: 0, rxBytes: 0, shortWrites: 0 };
|
|
#p: KPort[] = [];
|
|
#memory: () => WebAssembly.Memory;
|
|
#raise: () => void;
|
|
|
|
constructor(opts: SerialDeviceOptions) {
|
|
const n = Math.max(0, Math.min(SERIAL_MAX_PORTS, Math.floor(opts.ports ?? 0)));
|
|
this.enabled = n > 0;
|
|
this.ports = n;
|
|
this.#memory = opts.memory;
|
|
this.#raise = opts.raise;
|
|
this.send = opts.send ?? (() => {});
|
|
this.#grow(n);
|
|
}
|
|
|
|
#grow(n: number): void {
|
|
while (this.#p.length < n) this.#p.push({ attached: false, open: false, gen: 0, hung: false, rx: [], rxOff: 0, txOut: 0, txShort: false, levels: 0, events: 0 });
|
|
}
|
|
|
|
/** When each port last sent "wanted". */
|
|
#wanted: number[] = [];
|
|
|
|
#port(port: number): KPort | undefined {
|
|
return (port >>> 0) < this.ports ? this.#p[port >>> 0] : undefined;
|
|
}
|
|
|
|
/** Bytes waiting for the kernel's read on `port`. */
|
|
rxPending(port: number): number {
|
|
const p = this.#p[port];
|
|
if (!p) return 0;
|
|
return p.rx.reduce((n, c) => n + c.length, 0) - p.rxOff;
|
|
}
|
|
|
|
/** An up message from the ports' end. */
|
|
receive(m: SerialUp): void {
|
|
const p = this.#port(m.port);
|
|
if (!p) return;
|
|
switch (m.op) {
|
|
case "attached":
|
|
p.attached = m.on;
|
|
break;
|
|
case "levels": {
|
|
const changed = p.levels !== m.levels;
|
|
p.levels = m.levels;
|
|
if (changed && p.open && !p.hung) {
|
|
p.events |= SERIAL_EV_SIGNALS;
|
|
this.#raise();
|
|
}
|
|
break;
|
|
}
|
|
case "rx":
|
|
// Not for this session (the host resets its credit at each open and close).
|
|
if (m.gen !== p.gen || !p.open || p.hung || !m.data.length) break;
|
|
p.rx.push(m.data);
|
|
p.events |= SERIAL_EV_RX;
|
|
this.#raise();
|
|
break;
|
|
case "written":
|
|
if (m.gen !== p.gen || !p.open || p.hung) break;
|
|
p.txOut = Math.max(0, p.txOut - m.n);
|
|
if (p.txShort && p.txOut <= SERIAL_TX_WINDOW / 2) {
|
|
p.txShort = false;
|
|
p.events |= SERIAL_EV_TX_ROOM;
|
|
this.#raise();
|
|
}
|
|
break;
|
|
case "event":
|
|
if (m.gen !== p.gen || !p.open || p.hung) break;
|
|
if (m.bits & SERIAL_EV_HANGUP) this.#hangup(p);
|
|
p.events |= m.bits;
|
|
this.#raise();
|
|
break;
|
|
}
|
|
}
|
|
|
|
#hangup(p: KPort): void {
|
|
p.hung = true;
|
|
p.txOut = 0;
|
|
if (p.txShort) {
|
|
p.txShort = false;
|
|
p.events |= SERIAL_EV_TX_ROOM;
|
|
}
|
|
this.#dropRx(p);
|
|
}
|
|
|
|
#dropRx(p: KPort): void {
|
|
p.rx = [];
|
|
p.rxOff = 0;
|
|
}
|
|
|
|
imports(): Record<string, unknown> {
|
|
const u8 = () => new Uint8Array(this.#memory().buffer);
|
|
return {
|
|
wasm_driver_serial_init: (): number => {
|
|
this.probed = true;
|
|
if (!this.enabled) return -ENODEV;
|
|
this.send({ op: "init", ports: this.ports });
|
|
return this.ports;
|
|
},
|
|
wasm_driver_serial_open: (port: number): number => {
|
|
const p = this.#port(port);
|
|
if (p && !p.attached) {
|
|
// Tell the ports' end that a program wants a device here (a page offers to connect one).
|
|
const now = Date.now();
|
|
if (now - (this.#wanted[port] ?? 0) >= 1000) {
|
|
this.#wanted[port] = now;
|
|
this.send({ op: "wanted", port });
|
|
}
|
|
}
|
|
if (!p || !p.attached) return -ENODEV;
|
|
p.open = true;
|
|
p.gen++;
|
|
p.hung = false;
|
|
this.#dropRx(p);
|
|
p.txOut = 0;
|
|
p.txShort = false;
|
|
p.events = 0;
|
|
this.send({ op: "open", port: port >>> 0, gen: p.gen });
|
|
return 0;
|
|
},
|
|
wasm_driver_serial_close: (port: number): void => {
|
|
const p = this.#port(port);
|
|
if (!p) return;
|
|
const was = p.open;
|
|
p.open = false;
|
|
p.hung = false;
|
|
// Unread RX goes with the session; its credit with it (the host resets it at the close).
|
|
this.#dropRx(p);
|
|
p.txOut = 0;
|
|
p.txShort = false;
|
|
p.events = 0;
|
|
if (was) this.send({ op: "close", port: port >>> 0 });
|
|
},
|
|
wasm_driver_serial_config: (port: number, baud: number, cfg: number): void => {
|
|
if (!this.#port(port)) return;
|
|
this.send({ op: "config", port: port >>> 0, baud: baud >>> 0, cfg: cfg >>> 0 });
|
|
},
|
|
wasm_driver_serial_write: (port: number, buf: number | bigint, len: number): number => {
|
|
const p = this.#port(port);
|
|
const want = Math.max(0, len | 0);
|
|
if (!p || !want) return 0;
|
|
// Nowhere to go (hung up, or a write outside a session): taken and dropped, so the tty drains.
|
|
if (!p.open || p.hung) return want;
|
|
const n = Math.min(want, SERIAL_TX_WINDOW - p.txOut);
|
|
if (n < want) {
|
|
p.txShort = true;
|
|
this.stats.shortWrites++;
|
|
}
|
|
if (n <= 0) return 0;
|
|
const at = Number(buf);
|
|
const data = u8().slice(at, at + n);
|
|
p.txOut += n;
|
|
this.stats.txBytes += n;
|
|
this.send({ op: "write", port: port >>> 0, data });
|
|
return n;
|
|
},
|
|
wasm_driver_serial_read: (port: number, buf: number | bigint, max: number): number => {
|
|
const p = this.#port(port);
|
|
const room = Math.max(0, max | 0);
|
|
if (!p || !room || !p.rx.length) return 0;
|
|
const mem = u8();
|
|
let at = Number(buf), n = 0;
|
|
while (n < room && p.rx.length) {
|
|
const c = p.rx[0]!;
|
|
const take = Math.min(room - n, c.length - p.rxOff);
|
|
mem.set(c.subarray(p.rxOff, p.rxOff + take), at);
|
|
at += take;
|
|
n += take;
|
|
p.rxOff += take;
|
|
if (p.rxOff >= c.length) {
|
|
p.rx.shift();
|
|
p.rxOff = 0;
|
|
}
|
|
}
|
|
if (n) {
|
|
this.stats.rxBytes += n;
|
|
this.send({ op: "consumed", port: port >>> 0, n });
|
|
}
|
|
return n;
|
|
},
|
|
wasm_driver_serial_set_signals: (port: number, signals: number): void => {
|
|
if (!this.#port(port)) return;
|
|
this.send({ op: "signals", port: port >>> 0, signals: signals & 7 });
|
|
},
|
|
wasm_driver_serial_status: (port: number): number => {
|
|
const p = this.#port(port);
|
|
if (!p) return 0;
|
|
const empty = !p.open || p.hung || p.txOut === 0;
|
|
const s = p.levels | (p.attached ? SERIAL_ATTACHED : 0) | (empty ? SERIAL_TX_EMPTY : 0) | p.events;
|
|
p.events = 0;
|
|
return s;
|
|
},
|
|
};
|
|
}
|
|
|
|
/** At the snapshot point: the port count and the ports the guest has open. */
|
|
saveState(): SerialSnapshot {
|
|
return { ports: this.ports, open: this.#p.map((p, i) => (p.open ? i : -1)).filter((i) => i >= 0) };
|
|
}
|
|
|
|
/**
|
|
* A restored kernel (loadSnapshot, after the IRQ bits were cleared): it
|
|
* does not ask for init again. Ports the guest had open come back hung
|
|
* up (the event is raised); none is opened physically.
|
|
*/
|
|
restoreState(s: SerialSnapshot): void {
|
|
this.probed = true;
|
|
this.ports = Math.max(1, Math.min(SERIAL_MAX_PORTS, s.ports | 0));
|
|
this.#grow(this.ports);
|
|
this.send({ op: "init", ports: this.ports });
|
|
let raise = false;
|
|
for (const i of s.open) {
|
|
const p = this.#p[i];
|
|
if (!p) continue;
|
|
p.open = true;
|
|
p.gen++;
|
|
this.#hangup(p);
|
|
p.events |= SERIAL_EV_HANGUP;
|
|
raise = true;
|
|
}
|
|
if (raise) this.#raise();
|
|
}
|
|
}
|
|
|
|
/** Where a port's physical side is. */
|
|
export type SerialPhase = "closed" | "opening" | "open" | "closing";
|
|
|
|
/** A slot as SerialHost.state() and onChange() show it. */
|
|
export interface SerialPortState {
|
|
/** The slot: the guest's /dev/ttyACM<slot>. */
|
|
slot: number;
|
|
device: string;
|
|
attached: boolean;
|
|
info: SerialBackendInfo | undefined;
|
|
/** A guest program has the tty open (its session; hung up ones too). */
|
|
guestOpen: boolean;
|
|
/** The guest's session hung up (lost device, detach, failed open); it ends at the guest's close. */
|
|
hungUp: boolean;
|
|
/** The physical port. */
|
|
phase: SerialPhase;
|
|
/** The settings it is open with (or will open with). */
|
|
config: SerialConfig | undefined;
|
|
/** The output signals the guest set last. */
|
|
signals: SerialOutputSignals;
|
|
/** The input signals read last. */
|
|
inputs: SerialInputSignals;
|
|
/** The latest failure (open, reopen, read, write), if any. */
|
|
error: string | undefined;
|
|
bytesIn: number;
|
|
bytesOut: number;
|
|
/** Physical opens (a config change while open counts one more). */
|
|
opens: number;
|
|
}
|
|
|
|
export interface SerialStats {
|
|
/** Ports the kernel registered (0 before its driver started, or without one). */
|
|
ports: number;
|
|
probed: boolean;
|
|
attached: number;
|
|
bytesIn: number;
|
|
bytesOut: number;
|
|
}
|
|
|
|
/** The serial API on a VM (`vm.serial`): attach backends to the guest's ports and watch them. */
|
|
export interface Serial {
|
|
/** Ports the guest gets (/dev/ttyACM0 to ttyACM<ports - 1>). */
|
|
readonly ports: number;
|
|
/** Whether the kernel has the driver (it asked for init); false before that and for a kernel without one. */
|
|
readonly probed: boolean;
|
|
/**
|
|
* Attach `backend` to `slot` (default: the first free one) and return the
|
|
* slot. Throws when that slot is taken, the backend is attached already,
|
|
* or no slot is free. The guest's next open of the tty opens it.
|
|
*/
|
|
attach(backend: SerialBackend, slot?: number): number;
|
|
/** Detach the backend from `slot`: a guest session on it hangs up, and the port is closed. */
|
|
detach(slot: number): Promise<void>;
|
|
/** The slot `backend` is attached to, or -1. */
|
|
slotOf(backend: SerialBackend): number;
|
|
backend(slot: number): SerialBackend | undefined;
|
|
state(slot: number): SerialPortState;
|
|
readonly states: SerialPortState[];
|
|
/** Called (from a microtask) when a slot's state changes (attached, phase, config, signals, inputs, error; not the byte counts alone); returns the unsubscribe. */
|
|
onChange(listener: (state: SerialPortState) => void): () => void;
|
|
/** Called when a guest program opens a port that has no backend (it gets ENODEV), at most once a second for a slot; returns the unsubscribe. */
|
|
onWanted(listener: (slot: number) => void): () => void;
|
|
readonly stats: SerialStats;
|
|
}
|
|
|
|
type Op =
|
|
| { k: "open" }
|
|
| { k: "config"; config: SerialConfig; seq: number }
|
|
| { k: "signals"; bits: number }
|
|
| { k: "write"; data: Uint8Array; gen: number }
|
|
| { k: "close" }
|
|
| { k: "halt" };
|
|
|
|
interface Slot {
|
|
backend: SerialBackend | undefined;
|
|
/** The backend physically open (or opening), which the next close closes. */
|
|
phys: SerialBackend | undefined;
|
|
unlisten: (() => void) | undefined;
|
|
/** The guest's session (0: none). */
|
|
gen: number;
|
|
hung: boolean;
|
|
config: SerialConfig | undefined;
|
|
physConfig: SerialConfig | undefined;
|
|
/** Counts the guest's configs; physSeq: the latest one the physical open has (later ones reopen, in order). */
|
|
configSeq: number;
|
|
physSeq: number;
|
|
signals: number;
|
|
/** The signal state last set on the port (set again after a reopen). */
|
|
applied: number | undefined;
|
|
inputs: SerialInputSignals;
|
|
phase: SerialPhase;
|
|
ops: Op[];
|
|
pumping: boolean;
|
|
/** The op the pump is in, if any. */
|
|
current: Op | undefined;
|
|
openAt: number;
|
|
configAt: number;
|
|
reader: number;
|
|
rxInFlight: number;
|
|
rxWake: (() => void) | undefined;
|
|
poll: ReturnType<typeof setInterval> | undefined;
|
|
polling: boolean;
|
|
error: string | undefined;
|
|
bytesIn: number;
|
|
bytesOut: number;
|
|
opens: number;
|
|
/** Backend.close() already called for the current physical open (early, for a stuck write). */
|
|
closing: Promise<void> | undefined;
|
|
}
|
|
|
|
const NO_INPUTS: SerialInputSignals = { clearToSend: false, dataSetReady: false, dataCarrierDetect: false, ringIndicator: false };
|
|
const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
|
|
|
|
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;
|
|
}
|
|
|
|
export interface SerialHostOptions {
|
|
/** Ports the guest gets (1..4). */
|
|
ports: number;
|
|
/** Where up messages go, a batch at a time in order (to SerialDevice.receive(), or a message to the worker). */
|
|
send: (ops: SerialUp[]) => void;
|
|
log?: (msg: string) => void;
|
|
}
|
|
|
|
/**
|
|
* The ports' end: backends in slots, each port's physical side and the API
|
|
* (`vm.serial`). Down messages from SerialDevice go to receive().
|
|
*/
|
|
export class SerialHost implements Serial {
|
|
readonly ports: number;
|
|
#probed = false;
|
|
#kernelPorts = 0;
|
|
#send: (ops: SerialUp[]) => void;
|
|
#log: (msg: string) => void;
|
|
#slots: Slot[] = [];
|
|
#listeners = new Set<(s: SerialPortState) => void>();
|
|
#changed = new Set<number>();
|
|
#wantedListeners = new Set<(slot: number) => void>();
|
|
#out: SerialUp[] = [];
|
|
#closed = false;
|
|
|
|
constructor(opts: SerialHostOptions) {
|
|
this.ports = Math.max(1, Math.min(SERIAL_MAX_PORTS, Math.floor(opts.ports)));
|
|
this.#send = opts.send;
|
|
this.#log = opts.log ?? ((m) => console.error(m));
|
|
for (let i = 0; i < this.ports; i++) {
|
|
this.#slots.push({
|
|
backend: undefined, phys: undefined, unlisten: undefined, gen: 0, hung: false, config: undefined, physConfig: undefined, configSeq: 0, physSeq: 0,
|
|
signals: 0, applied: undefined, inputs: { ...NO_INPUTS }, phase: "closed", ops: [], pumping: false, current: undefined,
|
|
openAt: 0, configAt: 0, reader: 0, rxInFlight: 0, rxWake: undefined, poll: undefined, polling: false,
|
|
error: undefined, bytesIn: 0, bytesOut: 0, opens: 0, closing: undefined,
|
|
});
|
|
}
|
|
}
|
|
|
|
get probed(): boolean {
|
|
return this.#probed;
|
|
}
|
|
|
|
get stats(): SerialStats {
|
|
const s = this.#slots;
|
|
return {
|
|
ports: this.#kernelPorts, probed: this.#probed, attached: s.filter((x) => x.backend).length,
|
|
bytesIn: s.reduce((n, x) => n + x.bytesIn, 0), bytesOut: s.reduce((n, x) => n + x.bytesOut, 0),
|
|
};
|
|
}
|
|
|
|
// Up messages go out in one batch per microtask, in order.
|
|
#up(m: SerialUp): 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);
|
|
}
|
|
|
|
#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: SerialPortState) => void): () => void {
|
|
this.#listeners.add(listener);
|
|
return () => this.#listeners.delete(listener);
|
|
}
|
|
|
|
onWanted(listener: (slot: number) => void): () => void {
|
|
this.#wantedListeners.add(listener);
|
|
return () => this.#wantedListeners.delete(listener);
|
|
}
|
|
|
|
state(slot: number): SerialPortState {
|
|
const s = this.#slots[slot];
|
|
if (!s) throw new RangeError(`serial: no slot ${slot} (the guest has ${this.ports})`);
|
|
return {
|
|
slot, device: `/dev/ttyACM${slot}`, attached: !!s.backend, info: s.backend?.info, guestOpen: s.gen > 0, hungUp: s.gen > 0 && s.hung,
|
|
phase: s.phase, config: s.physConfig ?? s.config, signals: signalsOf(s.signals), inputs: { ...s.inputs }, error: s.error,
|
|
bytesIn: s.bytesIn, bytesOut: s.bytesOut, opens: s.opens,
|
|
};
|
|
}
|
|
|
|
get states(): SerialPortState[] {
|
|
return this.#slots.map((_, i) => this.state(i));
|
|
}
|
|
|
|
slotOf(backend: SerialBackend): number {
|
|
return this.#slots.findIndex((s) => s.backend === backend);
|
|
}
|
|
|
|
backend(slot: number): SerialBackend | undefined {
|
|
return this.#slots[slot]?.backend;
|
|
}
|
|
|
|
attach(backend: SerialBackend, slot?: number): number {
|
|
if (this.#closed) throw new Error("serial: the machine has ended");
|
|
if (this.slotOf(backend) >= 0) throw new Error(`serial: this backend is attached to /dev/ttyACM${this.slotOf(backend)} already`);
|
|
const i = slot ?? this.#slots.findIndex((s) => !s.backend);
|
|
const s = this.#slots[i];
|
|
if (i < 0 || !s) throw new Error(slot === undefined ? `serial: every port is taken (the guest has ${this.ports})` : `serial: no slot ${slot} (the guest has ${this.ports})`);
|
|
if (s.backend) throw new Error(`serial: /dev/ttyACM${i} has a backend attached`);
|
|
s.backend = backend;
|
|
s.error = undefined;
|
|
s.inputs = { ...NO_INPUTS };
|
|
s.bytesIn = s.bytesOut = 0;
|
|
s.unlisten = backend.listen?.(() => this.#lost(i, backend));
|
|
this.#up({ op: "attached", port: i, on: true });
|
|
this.#up({ op: "levels", port: i, levels: 0 });
|
|
this.#emit(i);
|
|
return i;
|
|
}
|
|
|
|
async detach(slot: number): Promise<void> {
|
|
const s = this.#slots[slot];
|
|
if (!s?.backend) return;
|
|
const b = s.backend;
|
|
this.#hangup(slot, "detached");
|
|
this.#unplug(slot);
|
|
// The port's physical close follows the ops in flight (the halt above).
|
|
await this.#idle(slot, b);
|
|
}
|
|
|
|
/** Wait until the pump of `slot` has nothing left for `backend`. */
|
|
async #idle(slot: number, b: SerialBackend): Promise<void> {
|
|
const s = this.#slots[slot]!;
|
|
for (let i = 0; i < 400 && (s.pumping || s.phase !== "closed") && (s.backend === b || s.backend === undefined); i++) await sleep(5);
|
|
}
|
|
|
|
#unplug(slot: number): void {
|
|
const s = this.#slots[slot]!;
|
|
s.unlisten?.();
|
|
s.unlisten = undefined;
|
|
s.backend = undefined;
|
|
this.#up({ op: "attached", port: slot, on: false });
|
|
this.#emit(slot);
|
|
}
|
|
|
|
/** The device went away. */
|
|
#lost(slot: number, b: SerialBackend): void {
|
|
const s = this.#slots[slot];
|
|
if (!s || s.backend !== b) return;
|
|
this.#log(`[serial] /dev/ttyACM${slot}: the device is gone`);
|
|
s.error = "the device is gone";
|
|
this.#hangup(slot, "lost");
|
|
this.#unplug(slot);
|
|
}
|
|
|
|
/**
|
|
* The guest's session ends from this side: the hangup event, its writes
|
|
* dropped, and the physical port closed next (before any other op).
|
|
*/
|
|
#hangup(slot: number, why: string): void {
|
|
const s = this.#slots[slot]!;
|
|
if (s.gen && !s.hung) {
|
|
s.hung = true;
|
|
this.#up({ op: "event", port: slot, gen: s.gen, bits: SERIAL_EV_HANGUP });
|
|
if (why !== "detached" && why !== "lost") this.#log(`[serial] /dev/ttyACM${slot}: hung up (${why})`);
|
|
}
|
|
this.#stopPoll(s);
|
|
s.ops = s.ops.filter((o) => o.k !== "write" && o.k !== "open" && o.k !== "config" && o.k !== "signals");
|
|
s.ops.unshift({ k: "halt" });
|
|
this.#breakStuckWrite(s);
|
|
this.#pump(slot);
|
|
this.#emit(slot);
|
|
}
|
|
|
|
/** A write the device holds (flow control) must not hold a close: close the backend now, which settles it. */
|
|
#breakStuckWrite(s: Slot): void {
|
|
if (s.current?.k === "write" && s.phys && !s.closing) {
|
|
s.reader++;
|
|
s.closing = s.phys.close().catch(() => {});
|
|
}
|
|
}
|
|
|
|
/** A down message from the kernel's end. */
|
|
receive(m: SerialDown): void {
|
|
if (this.#closed) return;
|
|
if (m.op === "init") {
|
|
this.#probed = true;
|
|
this.#kernelPorts = m.ports;
|
|
for (let i = 0; i < this.ports; i++) {
|
|
const s = this.#slots[i]!;
|
|
// The kernel's mirror starts from nothing: tell it what is attached.
|
|
this.#up({ op: "attached", port: i, on: !!s.backend });
|
|
this.#up({ op: "levels", port: i, levels: levelBits(s.inputs) });
|
|
}
|
|
return;
|
|
}
|
|
const slot = m.port;
|
|
const s = this.#slots[slot];
|
|
if (!s) return;
|
|
if (m.op === "wanted") {
|
|
if (!s.backend) for (const l of this.#wantedListeners) try { l(slot); } catch {}
|
|
return;
|
|
}
|
|
switch (m.op) {
|
|
case "open":
|
|
s.gen = m.gen;
|
|
s.hung = false;
|
|
s.rxInFlight = 0;
|
|
s.error = undefined;
|
|
s.openAt = s.configAt = performance.now();
|
|
if (!s.backend) {
|
|
s.hung = true;
|
|
this.#up({ op: "event", port: slot, gen: m.gen, bits: SERIAL_EV_HANGUP });
|
|
break;
|
|
}
|
|
s.ops.push({ k: "open" });
|
|
this.#pump(slot);
|
|
break;
|
|
case "close":
|
|
s.gen = 0;
|
|
s.hung = false;
|
|
s.rxInFlight = 0;
|
|
s.rxWake?.();
|
|
this.#stopPoll(s);
|
|
// Pending TX goes; signal changes before the close (a DTR drop) still apply.
|
|
s.ops = s.ops.filter((o) => o.k !== "write");
|
|
s.ops.push({ k: "close" });
|
|
this.#breakStuckWrite(s);
|
|
this.#pump(slot);
|
|
break;
|
|
case "config":
|
|
s.config = decodeSerialConfig(m.baud, m.cfg, s.config);
|
|
s.configAt = performance.now();
|
|
s.configSeq++;
|
|
if (s.gen && !s.hung) {
|
|
s.ops.push({ k: "config", config: s.config, seq: s.configSeq });
|
|
this.#pump(slot);
|
|
}
|
|
break;
|
|
case "signals":
|
|
s.signals = m.signals;
|
|
if ((s.gen && !s.hung) || s.phase === "open" || s.ops.length) {
|
|
s.ops.push({ k: "signals", bits: m.signals });
|
|
this.#pump(slot);
|
|
}
|
|
break;
|
|
case "write":
|
|
if (!s.gen || s.hung || !s.backend) {
|
|
this.#up({ op: "written", port: slot, gen: s.gen, n: m.data.length });
|
|
break;
|
|
}
|
|
s.ops.push({ k: "write", data: m.data, gen: s.gen });
|
|
this.#pump(slot);
|
|
break;
|
|
case "consumed":
|
|
s.rxInFlight = Math.max(0, s.rxInFlight - m.n);
|
|
if (s.rxInFlight < SERIAL_RX_WINDOW) {
|
|
const w = s.rxWake;
|
|
s.rxWake = undefined;
|
|
w?.();
|
|
}
|
|
break;
|
|
}
|
|
this.#emit(slot);
|
|
}
|
|
|
|
#pump(slot: number): void {
|
|
const s = this.#slots[slot]!;
|
|
if (s.pumping) return;
|
|
s.pumping = true;
|
|
void (async () => {
|
|
try {
|
|
while (s.ops.length && !this.#closed) {
|
|
const op = s.ops.shift()!;
|
|
s.current = op;
|
|
try {
|
|
await this.#run(slot, op);
|
|
} catch (e) {
|
|
this.#log(`[serial] /dev/ttyACM${slot}: ${op.k}: ${errText(e)}`);
|
|
}
|
|
s.current = undefined;
|
|
this.#emit(slot);
|
|
}
|
|
} finally {
|
|
s.pumping = false;
|
|
s.current = undefined;
|
|
}
|
|
})();
|
|
}
|
|
|
|
async #run(slot: number, op: Op): Promise<void> {
|
|
const s = this.#slots[slot]!;
|
|
const b = s.backend;
|
|
switch (op.k) {
|
|
case "open": {
|
|
const gen = s.gen;
|
|
// One physical open for the tty open's open + config + signals (and a
|
|
// program's tcsetattr right after its open).
|
|
for (;;) {
|
|
const now = performance.now();
|
|
const due = Math.min(s.configAt + OPEN_DEBOUNCE_MS, s.openAt + OPEN_DEBOUNCE_MAX_MS);
|
|
if (now >= due) break;
|
|
await sleep(due - now);
|
|
}
|
|
if (s.gen !== gen || s.hung || !b || s.backend !== b) return;
|
|
await this.#openPhysical(slot, b, gen);
|
|
return;
|
|
}
|
|
case "config":
|
|
// A config the open (or a reopen) took already, from its debounce: nothing to do.
|
|
if (op.seq <= s.physSeq) return;
|
|
if (!b || s.hung || !s.gen || s.phase !== "open" || sameConfig(s.physConfig, op.config)) {
|
|
s.physSeq = op.seq;
|
|
return;
|
|
}
|
|
// Web Serial cannot change an open port: close and open it again.
|
|
await this.#closePhysical(s);
|
|
if (s.gen && !s.hung && s.backend === b) await this.#openPhysical(slot, b, s.gen, op);
|
|
return;
|
|
case "signals":
|
|
if (!b || s.phase !== "open") return;
|
|
try {
|
|
await b.setSignals(signalsOf(op.bits));
|
|
s.applied = op.bits;
|
|
} catch (e) {
|
|
this.#failed(slot, b, "setSignals", e);
|
|
}
|
|
return;
|
|
case "write": {
|
|
// Consecutive writes of the session go out as one chunk.
|
|
let chunk = op.data, n = op.data.length;
|
|
if (s.ops[0]?.k === "write") {
|
|
const parts = [op.data];
|
|
while (s.ops[0]?.k === "write" && (s.ops[0] as { gen: number }).gen === op.gen && n + (s.ops[0] as { data: Uint8Array }).data.length <= WRITE_CHUNK) {
|
|
const w = s.ops.shift() as { data: Uint8Array };
|
|
parts.push(w.data);
|
|
n += w.data.length;
|
|
}
|
|
if (parts.length > 1) {
|
|
chunk = new Uint8Array(n);
|
|
let at = 0;
|
|
for (const p of parts) {
|
|
chunk.set(p, at);
|
|
at += p.length;
|
|
}
|
|
}
|
|
}
|
|
try {
|
|
if (b && s.phase === "open" && s.gen === op.gen && !s.hung) {
|
|
await b.write(chunk);
|
|
s.bytesOut += n;
|
|
}
|
|
} catch (e) {
|
|
if (s.gen === op.gen) this.#failed(slot, b!, "write", e);
|
|
} finally {
|
|
this.#up({ op: "written", port: slot, gen: op.gen, n });
|
|
}
|
|
return;
|
|
}
|
|
case "close":
|
|
case "halt":
|
|
await this.#closePhysical(s);
|
|
if (op.k === "close") s.applied = undefined;
|
|
return;
|
|
}
|
|
}
|
|
|
|
/** Open with the guest's latest config, or for a reopen with that config op's. */
|
|
async #openPhysical(slot: number, b: SerialBackend, gen: number, reopen?: { config: SerialConfig; seq: number }): Promise<void> {
|
|
const s = this.#slots[slot]!;
|
|
const config = reopen?.config ?? s.config ?? decodeSerialConfig(9600, 8);
|
|
s.physSeq = reopen?.seq ?? s.configSeq;
|
|
s.phase = "opening";
|
|
s.phys = b;
|
|
s.closing = undefined;
|
|
this.#emit(slot);
|
|
try {
|
|
s.opens++;
|
|
await b.open(config);
|
|
} catch (e) {
|
|
s.phase = "closed";
|
|
s.phys = undefined;
|
|
s.error = `open: ${errText(e)}`;
|
|
this.#log(`[serial] /dev/ttyACM${slot}: cannot open it (${errText(e)})`);
|
|
// A failed open may leave the port half open (a reader, a writer): close() sorts it.
|
|
try { await b.close(); } catch {}
|
|
if (s.gen === gen) this.#hangup(slot, "open failed");
|
|
return;
|
|
}
|
|
s.phase = "open";
|
|
s.physConfig = config;
|
|
if (s.gen !== gen || s.hung || s.backend !== b) return; // the close or halt is queued behind
|
|
if (reopen && s.applied !== undefined) {
|
|
try {
|
|
await b.setSignals(signalsOf(s.applied));
|
|
} catch (e) {
|
|
this.#failed(slot, b, "setSignals", e);
|
|
return;
|
|
}
|
|
}
|
|
this.#startReader(slot, b, gen);
|
|
this.#startPoll(slot, b);
|
|
}
|
|
|
|
async #closePhysical(s: Slot): Promise<void> {
|
|
this.#stopPoll(s);
|
|
s.reader++;
|
|
s.rxWake?.();
|
|
const b = s.phys;
|
|
if (!b) {
|
|
s.phase = "closed";
|
|
s.physConfig = undefined;
|
|
return;
|
|
}
|
|
s.phase = "closing";
|
|
try {
|
|
await (s.closing ?? b.close());
|
|
} catch (e) {
|
|
this.#log(`[serial] close: ${errText(e)}`);
|
|
}
|
|
s.closing = undefined;
|
|
s.phys = undefined;
|
|
s.phase = "closed";
|
|
s.physConfig = undefined;
|
|
}
|
|
|
|
/** A failed setSignals or write: a lost device (NetworkError) is gone; anything else ends the session. */
|
|
#failed(slot: number, b: SerialBackend, what: string, e: unknown): void {
|
|
const s = this.#slots[slot]!;
|
|
if (s.backend !== b) return;
|
|
s.error = `${what}: ${errText(e)}`;
|
|
if ((e as { name?: string })?.name === "NetworkError") this.#lost(slot, b);
|
|
else this.#hangup(slot, s.error);
|
|
}
|
|
|
|
#startReader(slot: number, b: SerialBackend, gen: number): void {
|
|
const s = this.#slots[slot]!;
|
|
const token = ++s.reader;
|
|
void (async () => {
|
|
let errors = 0;
|
|
while (token === s.reader && s.phase === "open" && s.gen === gen && !this.#closed) {
|
|
if (s.rxInFlight >= SERIAL_RX_WINDOW) {
|
|
await new Promise<void>((r) => (s.rxWake = r));
|
|
continue;
|
|
}
|
|
let data: Uint8Array | null;
|
|
try {
|
|
data = await b.read();
|
|
} catch (e) {
|
|
if (token !== s.reader || s.gen !== gen) return;
|
|
const name = (e as { name?: string })?.name ?? "";
|
|
const bits = READ_ERROR_BITS[name];
|
|
if (bits && ++errors < 1000) {
|
|
this.#up({ op: "event", port: slot, gen, bits });
|
|
continue;
|
|
}
|
|
s.error = `read: ${errText(e)}`;
|
|
if (name === "NetworkError") this.#lost(slot, b);
|
|
else this.#hangup(slot, s.error);
|
|
return;
|
|
}
|
|
if (token !== s.reader || s.gen !== gen) return;
|
|
if (data === null) return;
|
|
errors = 0;
|
|
if (!data.length) continue;
|
|
s.rxInFlight += data.length;
|
|
s.bytesIn += data.length; // read by state(); not a change of its own
|
|
this.#up({ op: "rx", port: slot, gen, data });
|
|
}
|
|
})();
|
|
}
|
|
|
|
#startPoll(slot: number, b: SerialBackend): void {
|
|
const s = this.#slots[slot]!;
|
|
this.#stopPoll(s);
|
|
const tick = () => {
|
|
if (s.polling || s.phase !== "open" || s.backend !== b || !s.gen || s.hung) return;
|
|
s.polling = true;
|
|
b.getSignals().then((sig) => {
|
|
s.polling = false;
|
|
if (s.backend !== b || s.phase !== "open") return;
|
|
const before = levelBits(s.inputs), now = levelBits(sig);
|
|
s.inputs = { clearToSend: !!sig.clearToSend, dataSetReady: !!sig.dataSetReady, dataCarrierDetect: !!sig.dataCarrierDetect, ringIndicator: !!sig.ringIndicator };
|
|
if (before !== now) {
|
|
this.#up({ op: "levels", port: slot, levels: now });
|
|
this.#emit(slot);
|
|
}
|
|
}, () => {
|
|
// Closed or reopening meanwhile: the next tick tries again.
|
|
s.polling = false;
|
|
});
|
|
};
|
|
s.poll = setInterval(tick, SERIAL_POLL_MS);
|
|
tick();
|
|
}
|
|
|
|
#stopPoll(s: Slot): void {
|
|
if (s.poll !== undefined) clearInterval(s.poll);
|
|
s.poll = undefined;
|
|
}
|
|
|
|
/** Whether the input signals are being polled on `slot` (for tests). */
|
|
polling(slot: number): boolean {
|
|
return this.#slots[slot]?.poll !== undefined;
|
|
}
|
|
|
|
/** The machine ended: close every port (the backends stay the caller's). */
|
|
shutdown(): void {
|
|
if (this.#closed) return;
|
|
this.#closed = true;
|
|
for (const s of this.#slots) {
|
|
this.#stopPoll(s);
|
|
s.reader++;
|
|
s.rxWake?.();
|
|
s.ops = [];
|
|
s.gen = 0;
|
|
s.unlisten?.();
|
|
s.unlisten = undefined;
|
|
if (s.phys) void s.phys.close().catch(() => {});
|
|
s.phys = undefined;
|
|
s.phase = "closed";
|
|
}
|
|
}
|
|
}
|
|
|
|
/** Serial options of createKernel (CreateKernelOptions.serial). */
|
|
export interface SerialOption {
|
|
/** Ports the guest gets (/dev/ttyACM0 to ttyACM<n - 1>), 1 to 4. Default 4. */
|
|
ports?: number;
|
|
/** Backends to attach at boot: slot i gets attach[i]. More attach and detach later through `vm.serial`. */
|
|
attach?: ReadonlyArray<SerialBackend | undefined>;
|
|
/** @internal Worker mode, in the worker: the kernel's requests go to the owner (which runs SerialHost). */
|
|
raw?: { send: (m: SerialDown) => void };
|
|
}
|
|
|
|
/** The port count a `serial` option asks for (0: no device). */
|
|
export function serialPorts(opt: boolean | number | SerialOption | undefined): number {
|
|
if (!opt) return 0;
|
|
const n = opt === true ? SERIAL_MAX_PORTS : typeof opt === "number" ? opt : opt.ports ?? SERIAL_MAX_PORTS;
|
|
return Math.max(1, Math.min(SERIAL_MAX_PORTS, Math.floor(n) || SERIAL_MAX_PORTS));
|
|
}
|
|
|
|
/** One entry of FakeSerialBackend.calls: what the host asked, when (performance.now()). */
|
|
export type FakeSerialCall =
|
|
| { at: number; op: "open"; config: SerialConfig }
|
|
| { at: number; op: "close" }
|
|
| { at: number; op: "setSignals"; signals: SerialOutputSignals }
|
|
| { at: number; op: "write"; data: Uint8Array };
|
|
|
|
export interface FakeSerialOptions {
|
|
/** Bytes written come back as received (default true). */
|
|
loopback?: boolean;
|
|
info?: SerialBackendInfo;
|
|
/** The input signals getSignals() reports (setInputs() changes them). */
|
|
inputs?: Partial<SerialInputSignals>;
|
|
}
|
|
|
|
class FakeError extends Error {
|
|
constructor(name: string, message = name) {
|
|
super(message);
|
|
this.name = name;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* An in-memory serial device: writes loop back to the reader (unless
|
|
* `loopback: false`), the input signals are set by the test, errors and
|
|
* loss are injected, and every open, close, setSignals and write is
|
|
* recorded in order with its time (`calls`), so a test can check the exact
|
|
* sequence the guest caused.
|
|
*/
|
|
export class FakeSerialBackend implements SerialBackend {
|
|
readonly info: SerialBackendInfo;
|
|
loopback: boolean;
|
|
readonly calls: FakeSerialCall[] = [];
|
|
/** getSignals() calls (polling). */
|
|
polls = 0;
|
|
isOpen = false;
|
|
config: SerialConfig | undefined;
|
|
signals: SerialOutputSignals = { dataTerminalReady: false, requestToSend: false, break: false };
|
|
inputs: SerialInputSignals;
|
|
#rx: Uint8Array[] = [];
|
|
#errors: string[] = [];
|
|
#reader: ((v: Uint8Array | null | Error) => void) | undefined;
|
|
#failOpen: string | undefined;
|
|
#held = false;
|
|
#heldWrites: Array<() => void> = [];
|
|
#lost = new Set<() => void>();
|
|
#gone = false;
|
|
|
|
constructor(opts: FakeSerialOptions = {}) {
|
|
this.loopback = opts.loopback ?? true;
|
|
this.info = opts.info ?? { label: "loopback" };
|
|
this.inputs = { ...NO_INPUTS, ...opts.inputs };
|
|
}
|
|
|
|
/** The calls of one kind (e.g. "setSignals"), in order. */
|
|
callsOf<K extends FakeSerialCall["op"]>(op: K): Extract<FakeSerialCall, { op: K }>[] {
|
|
return this.calls.filter((c) => c.op === op) as Extract<FakeSerialCall, { op: K }>[];
|
|
}
|
|
|
|
/** Everything written, joined. */
|
|
written(): Uint8Array {
|
|
const w = this.callsOf("write");
|
|
const out = new Uint8Array(w.reduce((n, c) => n + c.data.length, 0));
|
|
let at = 0;
|
|
for (const c of w) {
|
|
out.set(c.data, at);
|
|
at += c.data.length;
|
|
}
|
|
return out;
|
|
}
|
|
|
|
/** Bytes from the device (as if received). */
|
|
feed(data: Uint8Array | string): void {
|
|
const bytes = typeof data === "string" ? new TextEncoder().encode(data) : data.slice();
|
|
if (!this.isOpen || !bytes.length) return;
|
|
this.#rx.push(bytes);
|
|
this.#deliver();
|
|
}
|
|
|
|
/** The next read() throws an error of this name (BreakError, FramingError, ParityError, BufferOverrunError, NetworkError...). */
|
|
inject(name: string): void {
|
|
this.#errors.push(name);
|
|
this.#deliver();
|
|
}
|
|
|
|
/** The next open() rejects with an error of this name (e.g. "NetworkError": the port is busy). */
|
|
failNextOpen(name = "NetworkError"): void {
|
|
this.#failOpen = name;
|
|
}
|
|
|
|
/** Set the input signals getSignals() reports. */
|
|
setInputs(s: Partial<SerialInputSignals>): void {
|
|
this.inputs = { ...this.inputs, ...s };
|
|
}
|
|
|
|
/** Hold writes (as a device with CTS low would): write() resolves only after releaseWrites() or close(). */
|
|
holdWrites(): void {
|
|
this.#held = true;
|
|
}
|
|
|
|
releaseWrites(): void {
|
|
this.#held = false;
|
|
const w = this.#heldWrites;
|
|
this.#heldWrites = [];
|
|
for (const r of w) r();
|
|
}
|
|
|
|
/** The device is unplugged: listeners are told, a pending read rejects with NetworkError, and opens fail. */
|
|
unplug(): void {
|
|
this.#gone = true;
|
|
this.#errors.push("NetworkError");
|
|
this.#deliver();
|
|
for (const l of this.#lost) try { l(); } catch {}
|
|
}
|
|
|
|
listen(lost: () => void): () => void {
|
|
this.#lost.add(lost);
|
|
return () => this.#lost.delete(lost);
|
|
}
|
|
|
|
#deliver(): void {
|
|
const r = this.#reader;
|
|
if (!r) return;
|
|
if (this.#errors.length) {
|
|
this.#reader = undefined;
|
|
const name = this.#errors.shift()!;
|
|
r(new FakeError(name, `${name} (injected)`));
|
|
} else if (this.#rx.length) {
|
|
this.#reader = undefined;
|
|
r(this.#rx.shift()!);
|
|
}
|
|
}
|
|
|
|
async open(config: SerialConfig): Promise<void> {
|
|
this.calls.push({ at: performance.now(), op: "open", config: { ...config } });
|
|
if (this.#gone) throw new FakeError("NetworkError", "the device is gone");
|
|
if (this.isOpen) throw new FakeError("InvalidStateError", "the port is already open");
|
|
const fail = this.#failOpen;
|
|
this.#failOpen = undefined;
|
|
if (fail) throw new FakeError(fail, `${fail} (injected open failure)`);
|
|
this.isOpen = true;
|
|
this.config = { ...config };
|
|
this.#rx = [];
|
|
}
|
|
|
|
async close(): Promise<void> {
|
|
this.calls.push({ at: performance.now(), op: "close" });
|
|
this.isOpen = false;
|
|
this.#rx = [];
|
|
const r = this.#reader;
|
|
this.#reader = undefined;
|
|
r?.(null);
|
|
const w = this.#heldWrites;
|
|
this.#heldWrites = [];
|
|
for (const done of w) done();
|
|
}
|
|
|
|
read(): Promise<Uint8Array | null> {
|
|
if (!this.isOpen && !this.#errors.length) return Promise.resolve(null);
|
|
return new Promise<Uint8Array | null>((resolve, reject) => {
|
|
this.#reader = (v) => (v instanceof Error ? reject(v) : resolve(v));
|
|
this.#deliver();
|
|
});
|
|
}
|
|
|
|
async write(data: Uint8Array): Promise<void> {
|
|
if (!this.isOpen) throw new FakeError("InvalidStateError", "the port is not open");
|
|
const copy = data.slice();
|
|
this.calls.push({ at: performance.now(), op: "write", data: copy });
|
|
if (this.#held) await new Promise<void>((r) => this.#heldWrites.push(r));
|
|
if (this.loopback && this.isOpen) {
|
|
this.#rx.push(copy);
|
|
this.#deliver();
|
|
}
|
|
}
|
|
|
|
async setSignals(signals: SerialOutputSignals): Promise<void> {
|
|
if (!this.isOpen) throw new FakeError("InvalidStateError", "the port is not open");
|
|
this.calls.push({ at: performance.now(), op: "setSignals", signals: { ...signals } });
|
|
this.signals = { ...signals };
|
|
}
|
|
|
|
async getSignals(): Promise<SerialInputSignals> {
|
|
this.polls++;
|
|
if (!this.isOpen) throw new FakeError("InvalidStateError", "the port is not open");
|
|
return { ...this.inputs };
|
|
}
|
|
}
|