Files
unkernel/test/usb.test.ts

236 lines
9.9 KiB
TypeScript

// SPDX-License-Identifier: MIT
// Copyright (C) 2026 Pooya Parsa <pooya@pi0.io>
// kwusb end to end: the kernel's host controller
// (drivers/usb/host/kwusb.c) on the SDK's devices' end (js/core/usb.ts)
// with its test device (usb-fake.ts FakeUsbBackend). The guest program
// test/usb/usbtest.c (built here with zig cc, static aarch64 musl, from a
// host directory mounted over 9p) drives the device through usbfs, and at
// its steps this side acts (an unplug, a new device) or checks the
// backend's calls (a real reset, no SET_ADDRESS or SET_CONFIGURATION sent
// as requests, the hidden HID interface never claimed). On the UP kernel,
// and on the SMP kernel in worker mode with the program on CPU 1, where the
// driver hands its work to CPU 0 and the device runs on the owner's thread
// (a FakeUsbBackend is not WebUSB, so it is driven over messages). Also:
// a SuperSpeed and a full-speed device, no controller without the option,
// and a snapshot restored without the device (the guest's URB ends with
// ESHUTDOWN, the device is gone).
//
// node --test test/usb.test.ts
// UNKERNEL_TEST_KERNEL=path ... another bundle instead of vendor/build/bundle/unkernel.wasm
// ZIG=path ... zig for the guest program (default: zig on PATH)
import test, { after, before, describe } from "node:test";
import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { FakeUsbBackend, bundledKernelUrl, createKernel, loadKernelModule, nodeFs } from "../js/node.ts";
type Instance = Awaited<ReturnType<typeof createKernel>>;
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const testKernel = process.env.UNKERNEL_TEST_KERNEL ? path.resolve(process.env.UNKERNEL_TEST_KERNEL) : undefined;
const kernelFile = testKernel ?? fileURLToPath(bundledKernelUrl);
/** Kernel messages that must not appear. */
const KERNEL_TROUBLE = /WARNING|BUG|Oops|Call trace|INFO: rcu| stall|blocked for more|kwusb: the host/;
const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
const hasDriver = WebAssembly.Module.imports(await loadKernelModule(readFileSync(kernelFile))).some((i) => i.name === "wasm_driver_usb_init");
const hasSmp = WebAssembly.Module.imports(await loadKernelModule(readFileSync(kernelFile), { smp: true })).some((i) => i.name === "wasm_cpu_start");
const noDriver = !hasDriver && "the kernel has no kwusb";
const dir = mkdtempSync(path.join(tmpdir(), "kw-usb-test-"));
const mounts = { "/mnt/usb": { fs: nodeFs(dir), readOnly: true } };
const USBTEST = "/mnt/usb/usbtest";
before(() => {
const cc = spawnSync(process.env.ZIG ?? "zig", ["cc", "-target", "aarch64-linux-musl", "-mcpu=generic", "-static", "-O2", "-s", "-o", path.join(dir, "usbtest"), path.join(root, "test/usb/usbtest.c")], { encoding: "utf8" });
assert.equal(cc.status, 0, `building usbtest: ${cc.stderr}`);
});
after(() => rmSync(dir, { recursive: true, force: true }));
/** Lines of a stream as they come; next() waits for the next one (null at the end). */
function lines(stream: ReadableStream<Uint8Array>) {
const seen: (string | null)[] = [];
let buf = "";
let wake = () => {};
void (async () => {
const dec = new TextDecoder();
for await (const b of stream) {
buf += dec.decode(b, { stream: true });
let i;
while ((i = buf.indexOf("\n")) >= 0) {
seen.push(buf.slice(0, i));
buf = buf.slice(i + 1);
}
wake();
}
})()
.catch(() => {})
.finally(() => {
if (buf) seen.push(buf);
seen.push(null);
wake();
});
let at = 0;
return {
seen,
async next(ms = 180000): Promise<string | null> {
const end = Date.now() + ms;
while (at >= seen.length) {
if (Date.now() > end) throw new Error(`no line from the guest within ${ms} ms; so far:\n${seen.join("\n")}`);
await Promise.race([new Promise<void>((r) => (wake = r)), sleep(200)]);
}
return seen[at++]!;
},
};
}
async function until(cond: () => boolean, ms = 5000): Promise<boolean> {
for (const end = Date.now() + ms; !cond(); ) {
if (Date.now() > end) return false;
await sleep(20);
}
return true;
}
/** Kernel trouble in the guest's dmesg, if any. */
async function trouble(vm: Instance): Promise<string> {
const r = await vm.exec("dmesg", []);
return r.stdout.split("\n").filter((l) => KERNEL_TROUBLE.test(l)).join("\n");
}
/** Run `usbtest run [cpu]` and answer its steps; returns the problems seen on either side and the bulk rate. */
async function runSequence(vm: Instance, first: FakeUsbBackend, cpu?: number): Promise<{ problems: string[]; transcript: string; rates: number[] }> {
const problems: string[] = [];
const rates: number[] = [];
let fake = first;
const p = await vm.spawn(USBTEST, ["run", ...(cpu === undefined ? [] : [String(cpu)])], { pty: false });
void p.stderr.cancel();
const out = lines(p.stdout);
const stdin = p.stdin.getWriter();
const go = () => stdin.write("go\n");
for (;;) {
const l = await out.next();
if (l === null) {
problems.push("the guest program ended without its done line");
break;
}
let m: RegExpExecArray | null;
if (l.startsWith("FAIL")) problems.push(`guest: ${l}`);
else if ((m = /^rate ([\d.]+) MB\/s$/.exec(l))) rates.push(Number(m[1]));
else if (l === "step reset-done") {
if (fake.resets !== 1) problems.push(`${l}: the device was reset ${fake.resets} times, want 1 (USBDEVFS_RESET only; enumeration's resets are answered by the host)`);
for (const c of fake.callsOf("controlTransferOut")) {
const s = c.args[0] as { requestType: string; request: number };
if (s.requestType === "standard" && (s.request === 5 || s.request === 9)) problems.push(`${l}: a standard request ${s.request} reached the device`);
}
if (fake.callsOf("claimInterface").some((c) => c.args[0] === 1)) problems.push(`${l}: the hidden interface was claimed`);
await go();
} else if (l === "step unplug") {
fake.unplug();
await go();
} else if (l === "step reattach") {
if (vm.usb!.state(0).attached) problems.push(`${l}: slot 0 still attached after the unplug`);
fake = new FakeUsbBackend();
try {
await vm.usb!.attach(fake, { slot: 0 });
} catch (e) {
problems.push(`${l}: ${(e as Error).message}`);
}
await go();
} else if (/^done /.test(l)) break;
}
await stdin.close().catch(() => {});
const end = await p.ended;
if (end.type !== "exit" || end.code !== 0) problems.push(`usbtest ended ${JSON.stringify(end)}`);
return { problems, transcript: out.seen.filter((x) => x !== null).join("\n"), rates };
}
describe("kwusb", { skip: noDriver }, () => {
for (const c of [
{ name: "UP", opts: {}, cpu: undefined },
{ name: "SMP, 2 CPUs in a worker, the program on CPU 1", opts: { cpus: 2, worker: true }, cpu: 1, skip: !hasSmp && "the bundle has no SMP patch" },
]) {
test(`the test device through usbfs (${c.name})`, { skip: c.skip, timeout: 600000 }, async (t) => {
const fake = new FakeUsbBackend();
const vm = await createKernel({ kernel: testKernel, ...c.opts, usb: { attach: [fake] }, mounts, log: () => {} });
try {
const { problems, transcript, rates } = await runSequence(vm, fake, c.cpu);
t.diagnostic(transcript);
t.diagnostic(`bulk loopback ${rates.join(", ")} MB/s`);
assert.deepEqual(problems, [], transcript);
assert.equal(await trouble(vm), "");
if (c.opts.worker) assert.equal(vm.usb!.state(0).runs, "owner");
} finally {
vm.stop();
}
});
}
for (const [speed, sysfs] of [["super", "5000"], ["full", "12"]] as const) {
test(`a ${speed}-speed device`, { timeout: 300000 }, async () => {
const vm = await createKernel({ kernel: testKernel, usb: { attach: [new FakeUsbBackend({ speed })] }, mounts, log: () => {} });
try {
const r = await vm.exec(USBTEST, ["quick", sysfs]);
assert.match(r.stdout, /done 0 failure/, r.stdout);
assert.equal(await trouble(vm), "");
} finally {
vm.stop();
}
});
}
test("no controller without the usb option", { timeout: 300000 }, async () => {
const vm = await createKernel({ kernel: testKernel, mounts, log: () => {} });
try {
const r = await vm.exec("sh", ["-c", "ls /sys/bus/usb/devices 2>&1; dmesg | grep -c kwusb"]);
assert.doesNotMatch(r.stdout, /usb1/);
assert.match(r.stdout, /^0$/m);
} finally {
vm.stop();
}
const vm2 = await createKernel({ kernel: testKernel, usb: 2, mounts, log: () => {} });
try {
const r = await vm2.exec("sh", ["-c", "cat /sys/bus/usb/devices/usb1/maxchild /sys/bus/usb/devices/usb2/maxchild /sys/bus/usb/devices/usb1/speed /sys/bus/usb/devices/usb2/speed"]);
assert.equal(r.stdout, "2\n2\n480\n5000\n");
assert.equal(vm2.usb!.stats.ports, 2);
} finally {
vm2.stop();
}
});
test("a snapshot restored without the device: the pending URB ends, the device is gone", { timeout: 300000 }, async () => {
const fake = new FakeUsbBackend();
const vm = await createKernel({ kernel: testKernel, usb: { attach: [fake] }, mounts, log: () => {} });
let snap;
try {
await vm.exec("sh", ["-c", `setsid ${USBTEST} park /tmp/park.out > /tmp/park.log 2>&1 < /dev/null &`]);
let ready = false;
for (let i = 0; i < 100 && !ready; i++) {
ready = (await vm.exec("cat", ["/tmp/park.log"])).stdout === "ready\n";
if (!ready) await sleep(100);
}
assert.ok(ready, "usbtest park said ready");
assert.ok(await until(() => fake.pendingReads(0x81) === 1), "the IN is pending on the device");
snap = await vm.snapshot({ stop: true });
} finally {
vm.stop();
}
const vm2 = await createKernel({ kernel: testKernel, restore: snap, mounts, log: () => {} });
try {
let r;
for (let i = 0; i < 100; i++) {
r = await vm2.exec("cat", ["/tmp/park.out"]);
if (r.exitCode === 0) break;
await sleep(100);
}
assert.equal(r!.stdout, "urb -108\nnext -1 No such device\n");
assert.equal(await trouble(vm2), "");
} finally {
vm2.stop();
}
});
});