From 21fc21c81a495c037359b8bd91c9ffdbffe78a2a Mon Sep 17 00:00:00 2001 From: Pooya Parsa Date: Tue, 17 Nov 2026 11:26:09 +0000 Subject: [PATCH] web: boot on several CPUs with the CPUs option (?smp=N) Off by default: one CPU loads the UP bundle as before. With several the page loads the SMP bundle (only then) and boots it in worker mode. The choices are disabled with the reason where the page cannot (no SMP kernel in the bundle, no cross-origin isolation, no Atomics.waitAsync), and a failed SMP download or start reloads once on one CPU. Suspend is hidden with several CPUs; a suspended session is offered to resume on one CPU. --- .agents/status.md | 18 +++-- .agents/web.md | 78 ++++++++++++++++++- README.md | 11 ++- kernel/README.md | 7 +- web/src/boot.ts | 132 ++++++++++++++++++++++++++++----- web/src/components/Options.tsx | 31 ++++++-- web/src/components/Panel.tsx | 5 +- web/src/config.ts | 83 ++++++++++++++++++++- web/src/main.tsx | 7 +- web/src/sdk.ts | 8 +- web/src/store.ts | 2 + web/src/ui.ts | 13 +++- web/test/headless.mjs | 8 +- 13 files changed, 351 insertions(+), 52 deletions(-) diff --git a/.agents/status.md b/.agents/status.md index 1b6f496..8b933e9 100644 --- a/.agents/status.md +++ b/.agents/status.md @@ -374,16 +374,24 @@ qemu's TCG keeps writing new code, which kwemu interprets or recompiles. another CPU flips between 0 and ~0, 2 CPUs), and the futex paths retry on an unexpected value. Scalar `__get_user_fn` and `__put_user_fn` for aligned 1, 2, 4 and 8 bytes would make it so. - - Browsers: not tried. They need cross-origin isolation, a worker for - CPU 0 (the CLI implies `--worker`), a web `Platform.spawnCpu`, and - `Atomics.waitAsync` for CPU 0's idle (check each engine; a message - from the sender's host would do instead). + - Browsers (2026-11-17; js.md, CPU threads; web.md, Several CPUs): + `js/web/cpu.ts` starts each CPU as a Web Worker, nested in worker + mode's kernel worker (CPU 0 must be able to block, so not on a + page's main thread), and the page has a CPUs option (`?smp=N`, off + by default) that loads the SMP bundle only then and falls back to + one CPU. Run only in headless Chromium (2 and 4 CPUs: boot, a + terminal window, glimmer, the JIT on every CPU, parallel loops + scaling). Not tried: Firefox (whether it has `Atomics.waitAsync`; + the option is disabled where it is missing), Safari, phones, a + hidden tab (worker throttling), long sessions. The page offers it + only once a release bundle carries the SMP patch (Packaging, below). - Packaging: one bundle carries the UP kernel and a patch to the SMP one (`kernel/tools/bundle.mjs --smp`; js.md, CPU threads; web.md for the page's split; study and sizes in `vendor/smp-deferred/packaging/README.md`, 2026-11-17). Not done: `kernel/build.sh` has no SMP target and `bundle` no `--smp`, so the - release workflow (and with it npm and the page) still ships UP only; + release workflow (and with it npm and the page, whose CPUs option + stays disabled) still ships UP only; the README there has the proposal. - Deferred fork and wakeup changes, measured 2026-11-16 (kwfork, 9 alternating rounds; patches and a README with their base in diff --git a/.agents/web.md b/.agents/web.md index 55e257b..c310ef9 100644 --- a/.agents/web.md +++ b/.agents/web.md @@ -55,8 +55,8 @@ the dev server's own responses) and `__KW_BUILD__`. `web/kernel/page/unkernel-alpine-smp.wasm`, the SMP bundle the patch makes, which the `unkernel:kernel-smp` plugin emits as its own hashed asset and `src/sdk.ts` exports as `kernelSmpUrl` (null without it, - from `virtual:unkernel-smp-kernel`). Nothing uses it yet: the page has - no CPU threads. The dev server splits again when the file changes. Building or deploying the + from `virtual:unkernel-smp-kernel`). Only a load with several CPUs + fetches it (Several CPUs, below). The dev server splits again when the file changes. Building or deploying the page needs no kernel toolchain. - `pnpm dev` runs the file that is there, without a network check. `kernel/build.sh bundle` (and so `kernel`, `alpine`, `datadisk`, `all`) @@ -143,7 +143,7 @@ elsewhere) and Ctrl-Shift-O; Copy diagnostics is y after the prefix after `write()` returned and yields a task (a MessageChannel, which background tabs do not throttle) every 16 ms or 256 KiB. `KW.windows` is their API. Checked by hand only (no browser test yet). -- `?worker=1` (experimental) boots through the SDK's worker mode (js.md): +- `?worker=1` (experimental, and implied by `?smp=N`) boots through the SDK's worker mode (js.md): the page compiles the kernel and passes the `WebAssembly.Module`; disks and the network are specs built in the worker. The data disk in worker mode follows data-disk.md (Persistence in the browser). `KW.kernel` and @@ -203,9 +203,74 @@ elsewhere) and Ctrl-Shift-O; Copy diagnostics is y after the prefix `user-scalable=no`), and wterm's hidden textarea is 16 px, because iOS zooms on focusing a smaller field. +## Several CPUs + +The CPUs option (System tab, Options, `#opt-cpus-` radios; `?smp=N`, +config.ts) boots the SMP kernel on N CPUs (kernel.md, SMP; js.md, CPU +threads). Default 1: the UP kernel, exactly as without the option (the +same files and code paths; `#opt-cpus-1`). It applies on Reboot, like the +other options. + +- Choices: 1, 2, 4 and 8 up to `navigator.hardwareConcurrency` (the + kernel's limit is 8), plus the suggested count, min(4, + hardwareConcurrency / 2), marked "(suggested)" (none below 4 threads). + Half the host's threads stay free for the page, the browser and other + tabs: a guest CPU whose thread the host deschedules stalls the CPUs + that wait for it (status.md, SMP, under host load). A larger `?smp=` is + capped at the thread count. +- `smpBlocker()` (config.ts) disables the choices above 1, with the + reason under them (`#opt-cpus-note`) and in the Environment tab's + "Guest CPUs" row: no SMP kernel in the page's bundle (`kernelSmpUrl` + null, every release so far), no cross-origin isolation (a plain-http + LAN page), no Web Workers or no `Atomics.waitAsync` + (`webCpuBlocker({ worker: true })`), or one host thread. Such a load + with `?smp=N` boots on one CPU as usual and says why. +- With several CPUs, boot.ts loads `kernelSmpUrl` instead of `kernelUrl` + (streaming compile; the UP bundle is not fetched) and boots in worker + mode (`cfg.worker` is set, the Worker thread option is not), with + `cpus`; the kernel worker starts the other CPUs as nested Web Workers. + The download starts only after the suspended session was offered + (below), since the answer picks the kernel. The SMP bundle is a hashed + `/assets/` file like the UP one: the service worker (scope `/vm/`) never + sees it, and the HTTP cache keeps each file on its own. +- Falling back: a failed SMP download or compile, or a `createKernel()` + that rejects (the worker, its JSPI, the shared memory), calls + `bootUpOnce()`: it stores the reason in sessionStorage `kw-up-once` and + reloads; that load boots on one CPU the usual way (inline unless + `?worker=1`) and shows the reason (`cfg.smpWhy`: the Guest CPUs row, + the CPUs note, diagnostics). `?smp=` stays in the URL, so the next + Reboot tries again. If sessionStorage refuses, the failure is reported + instead (no reload loop). A kernel worker that cannot start CPU threads + (`webCpuBlocker()` there) runs the SMP kernel on one CPU: the Guest + CPUs row warns, from `stats().cpus`. A failure after the kernel started + (a CPU's trap or fatal error) ends the session like any other, with a + hint to set CPUs to 1. +- No Suspend: the SMP kernel cannot park. `KW.suspend` stays unset (so + the status line has no pause icon), the dialog footer has no + `#suspend`, and Ctrl-A s says why. A suspended session (always a UP + one) is offered before the download: "Resume on 1 CPU" reloads once on + one CPU (`bootUpOnce()` with `kw-resume`) and resumes it; "Boot on N + CPUs" boots SMP and, when the session has a data disk, deletes it (that + boot changes the disk), else keeps it. +- The boot summary says "on N CPUs, in Web Workers"; diagnostics' config + line has `cpus=`. +- Checked in headless Chromium (Playwright's build, the built page from + the l2 patch bundle, 2026-11-17, a scratch script, not in `web/test/`): + the default load fetched only the UP bundle and ran on one CPU; `?smp=2` + and `?smp=4` fetched only the SMP bundle, `nproc` gave 2 and 4, a + terminal window, glimmer's test pattern, key and sound through worker + mode worked, the JIT compiled on every CPU, and n parallel awk loops + took 1.14x (2 CPUs) and 1.20x (4) the time of one; a plain-http LAN + load disabled the option and booted on one CPU; a blocked SMP download + reloaded on one CPU; a UP session resumed from a `?smp=2` load ("Resume + on 1 CPU") and was deleted by "Boot on 2 CPUs"; a page from the newest + release (no patch) showed the option disabled and booted UP. Also the + Vite dev server (nested worker from source). Firefox, Safari and + phones: not tried. + ## Suspend and resume -Suspend (Ctrl-A s, `s` in the dialog, the dialog footer's `#suspend`, the +Not with several CPUs (above). Suspend (Ctrl-A s, `s` in the dialog, the dialog footer's `#suspend`, the status line's pause icon `#bar-suspend` while the system runs, or `KW.suspend()` without asking) saves the running machine with the SDK's `snapshot({ stop: true })` (js.md, Snapshots), inline or in worker mode, and @@ -509,6 +574,11 @@ script. ## Engines +- Several CPUs need, besides JSPI in every worker: cross-origin + isolation, nested dedicated workers (Chrome, Firefox, Safari 15.5+), + `Atomics.waitAsync` (Chrome 87+, Safari 16.4+; check Firefox) and + posting a `WebAssembly.Module` and a shared `WebAssembly.Memory` to a + worker. Only Chromium has run it (Several CPUs). - JSPI (`WebAssembly.Suspending`/`promising`) is required: Chrome/Edge 137+, Firefox 153+, Safari 27+ (every iOS browser uses the system WebKit). memory64 is not needed, because the page runs the lowered diff --git a/README.md b/README.md index 013e9f0..d5528b5 100644 --- a/README.md +++ b/README.md @@ -128,6 +128,7 @@ The page takes a few URL parameters: | `?jit=0` | Interpreter only | | `?data=0` | No persistent disk, a fresh system every time | | `?worker=1` | Run the kernel in a Web Worker (experimental) | +| `?smp=2` | Boot on several CPUs, each in a Web Worker (experimental; only where the page has the SMP kernel and is cross-origin isolated) | Browsers can't open raw TCP sockets, so the page reaches the internet through a Wisp proxy. The default one accepts only known origins, so if you @@ -228,7 +229,8 @@ faster than without it, which is still well behind native. ### 🚧 Known limits -- One CPU, no SMP. +- One CPU in the released kernel. Several CPUs (SMP) are experimental, + not in a release yet, and cannot be suspended. - No IPv6, no UDP beyond DHCP and DNS, no inbound network connections ([`vm.connect()`, `vm.fetch()`](#talk-over-vsock) and `--forward` reach guest servers over vsock instead). @@ -458,6 +460,13 @@ template: "bundled" }` in browsers. Input and frames go through shared memory when it is available (`vm.transport` says). This mode is experimental. +An SMP kernel (a bundle with the SMP patch) boots on several CPUs with +`cpus: 4`, each CPU in a thread of its own on one shared memory. In +browsers that needs a cross-origin isolated page and `worker: true`, +because a CPU blocks while it waits for another, which a page's main +thread may not; `webCpuBlocker()` says why it cannot, and +`vm.stats().cpus` how many CPUs the kernel got. + ### Boot options and helpers ```js diff --git a/kernel/README.md b/kernel/README.md index 8ef37d0..a7b1900 100644 --- a/kernel/README.md +++ b/kernel/README.md @@ -751,7 +751,9 @@ from source). Everything is self-hosted except the Wisp fallback. `?root=initramfs` (safe mode: `kw.root=initramfs`), `?verbose=1`, `?worker=1` (experimental: the kernel, the data disk, the network, the display, input and sound in a Web Worker; input and frames through shared memory when the page is - cross-origin isolated, `?shared=0` for messages), `?fx` (start the fx + cross-origin isolated, `?shared=0` for messages), `?smp=N` (experimental: the SMP + kernel on N CPUs, each in a Web Worker; offered only when the page's bundle carries + the SMP kernel and the page is cross-origin isolated, else one CPU; no Suspend), `?fx` (start the fx coding agent in its panel at load), and, for tests, `?simulate=nojspi|oom|lowmem` (documented in `web/src/config.ts`). * **Launcher:** ❯ at the left of the status line (or ⌘K on Apple devices, @@ -1036,7 +1038,8 @@ switching, no block or net device, no JIT). held in memory as a whole. * SMP is experimental: a second build (`arch/wasm/configs/kw_smp.config`, built by hand, `.agents/kernel.md`, SMP) runs one kernel instance per - CPU in worker threads on a shared memory (CLI `--smp N`; Node only), + CPU in worker threads on a shared memory (CLI `--smp N`; the page's + `?smp=N`, in Web Workers, once its bundle carries the SMP kernel), each CPU with its own JIT. It has every device, all served by CPU 0 (disk I/O from other CPUs is handed to it), but no snapshots yet. A task moves to another CPU only on its way back to user mode (the load balancer, `taskset`); one asleep in a system call diff --git a/web/src/boot.ts b/web/src/boot.ts index 213aa52..c607fb8 100644 --- a/web/src/boot.ts +++ b/web/src/boot.ts @@ -9,12 +9,15 @@ // a wterm terminal with a systemd-style boot transcript, the status // indicator and stages (ui.ts), and the kernel's console as window 0, with // more terminal windows over vsock (windows.ts), and the guest preview -// (preview.ts: guest web servers in an iframe). +// (preview.ts: guest web servers in an iframe). With several CPUs (?smp=N, +// config.ts) it loads the SMP kernel instead and boots it in worker mode, +// whose worker starts the other CPUs; whatever stops that before the +// kernel runs reloads once on one CPU (bootUpOnce()). import "@wterm/dom/src/terminal.css"; import { WTerm } from "@wterm/dom"; import { prefetchApkIndexes } from "./apk.ts"; import { createAudioOut } from "./audio.ts"; -import { REPO } from "./config.ts"; +import { REPO, UP_ONCE_KEY } from "./config.ts"; import { attachDataDisk, detachDataDisk, downloadKwsparse, exportDataDisk, fmtSize, importDataDisk, resetDataDisk, storageState, acquireDiskLock, type DataAttach } from "./data.ts"; import { createDisplayUi } from "./display.ts"; import { KW } from "./kw.ts"; @@ -108,6 +111,10 @@ export function start(): void { /** The kernel has exited (inline: the moment it does; a worker: once its exit message arrived). */ const ended = () => { const l = local(); return l ? !!l.kernel.result : vmExited; }; const send = (s: string | Uint8Array) => vm?.write(s); + /** This load boots the SMP kernel on several CPUs (config.ts; never resumed, never suspended). */ + const smp = cfg.cpus > 1; + /** The kernel this load runs: the UP bundle, or the SMP one (sdk.ts kernelSmpUrl). */ + const kernelUrl = smp ? cfg.kernelSmpUrl! : cfg.kernelUrl; // --- display and input (kwfb, kwinput; ?display=0 turns them off): display.ts -------------- const display = createDisplayUi({ @@ -408,7 +415,8 @@ export function start(): void { let replay = ""; // user-space output during the boot phase, redrawn below the summary // Each step already shows its own time: the summary is the total from page load. const summary = () => `${SGR.dim}Booted in${SGR.off} ${SGR.bold}${fmtS(Date.now() - KW.t0)}${SGR.off}` + - (cfg.worker ? ` ${SGR.dim}in a Web Worker (experimental, ?worker=1)${SGR.off}` : "") + "\r\n"; + (smp ? ` ${SGR.dim}on ${cfg.cpus} CPUs, in Web Workers (experimental, ?smp=${cfg.smpParam})${SGR.off}` + : cfg.worker ? ` ${SGR.dim}in a Web Worker (experimental, ?worker=1)${SGR.off}` : "") + "\r\n"; // Two lines under the summary of a fresh boot: the source (an OSC 8 link, // which wterm opens on Ctrl/⌘-click) and how to open the demo launcher. const link = (url: string, text: string) => `\x1b]8;;${url}\x1b\\${text}\x1b]8;;\x1b\\`; @@ -519,7 +527,7 @@ export function start(): void { const ms = performance.now() - t0Download; const rate = `${(d.loaded / 1048576 / Math.max(ms / 1000, 0.001)).toFixed(1)} MiB/s`; ui.stage("kernel", "done", `${d.url} · ${fmtMiB(d.loaded)} · ${rate}`); - ok(`Downloaded unkernel-alpine.wasm, ${fmtMiB(d.loaded)}`, ms); + ok(`Downloaded ${smp ? "unkernel-alpine-smp.wasm" : "unkernel-alpine.wasm"}, ${fmtMiB(d.loaded)}`, ms); // The kernel compiles while it downloads (compileStreaming); what is left shows as the compile step. ui.stage("compile", "active"); ui.setState("booting", "Compiling"); @@ -594,8 +602,13 @@ export function start(): void { } /** The Suspend in progress: settles with null once saved, or why it failed (the exit waits for it). */ let suspending: Promise | null = null; - /** Suspend: save the running machine in this browser and stop it (session.ts); the next load offers to resume it. */ - KW.suspend = async () => { + /** + * Suspend: save the running machine in this browser and stop it + * (session.ts); the next load offers to resume it. Not with several CPUs: + * the SMP kernel cannot park, so it has no snapshots (ui.confirmSuspend() + * says so, and KW.suspend stays unset). + */ + if (!smp) KW.suspend = async () => { if (!vm || ended() || !running) throw new Error("the system is not running"); if (suspending) throw new Error("a suspend is in progress"); if (typeof indexedDB === "undefined") throw new Error("this browser has no IndexedDB to keep the session in"); @@ -623,6 +636,59 @@ export function start(): void { } }; + // --- several CPUs: what falls back to one --------------------------------------- + /** + * Reload this tab once on one CPU (config.ts reads UP_ONCE_KEY; ?smp= stays + * in the URL, so the next Reboot tries again), optionally resuming the + * suspended session. False if sessionStorage refuses the note, which would + * make the reload try the same again: then the caller reports the failure. + */ + function bootUpOnce(reason: string, resume = false): boolean { + try { + sessionStorage.setItem(UP_ONCE_KEY, reason); + } catch { + return false; + } + ui.hostLog(`[host] booting on one CPU instead: ${reason}`); + KW.term?.notice(`[host] booting on one CPU instead: ${reason}`); + if (resume) ui.resume(); // sets kw-resume and reloads + else location.reload(); + return true; + } + /** + * Several CPUs and a suspended session (always saved on one CPU, the UP + * kernel): offer to resume it on one CPU this time. True: the page + * reloads to do that. Asked before the kernel downloads, since the answer + * picks which one. + */ + async function offerResumeUp(info: Promise): Promise { + let meta: SessionMeta | null; + try { + meta = await info; + } catch (e) { + ui.hostLog(`[host] suspended session: cannot read it: ${(e as Error)?.message ?? e}`); + return false; + } + if (!meta) return false; + const label = `saved ${ago(meta.saved)}, ${fmtMiB(meta.bytes)}`; + const why = sessionMismatch(meta, cfg.kernelUrl, sessionDevices()) ?? + (cfg.data && meta.devices.data && data?.lock && !data.lock.held ? "the data disk is open in another tab" : null); + if (why) { + ui.check("session", "Suspended session", "info", `${label}; not resumed`, why); + ui.hostLog(`[host] suspended session (${label}) not offered: ${why}`); + return false; + } + const n = cfg.cpus; + const dataNote = meta.devices.data ? ` Booting on ${n} CPUs discards it: that boot changes the data disk.` : ` Booting on ${n} CPUs keeps it for later.`; + if (!resumeRequested && !await ui.ask({ title: "resume", msg: `Resume the session suspended ${ago(meta.saved)} (${fmtMiB(meta.bytes)}, ${meta.memoryMiB} MiB of memory)? It resumes on one CPU, as it was saved.${dataNote}`, ok: "Resume on 1 CPU", cancel: `Boot on ${n} CPUs` })) { + ui.hostLog(`[host] suspended session (${label}): booting on ${n} CPUs instead`); + ui.check("session", "Suspended session", "info", `${label}; not resumed`, `booted on ${n} CPUs instead${meta.devices.data ? " (discarded: the data disk changes)" : ""}`); + if (meta.devices.data) await clearSession().catch(() => {}); + return false; + } + return bootUpOnce(`resuming the session suspended ${ago(meta.saved)}, which runs on one CPU`, true); + } + // --- boot -------------------------------------------------------------------- async function boot() { ui.setState("loading", "Downloading"); @@ -631,22 +697,37 @@ export function start(): void { // The kernel downloads and compiles on this thread in both modes (the engine compiles // off-thread while it streams), so it overlaps the terminal's start and, in worker // mode, the data disk lock; the worker then gets the compiled Module. - const loading = loadKernelModule(cfg.kernelUrl, { what: "kernel", onProgress: onDownload }).catch((e: unknown) => { - const compile = e instanceof BootError && e.stage === "compile"; - throw tag(e, compile ? "compile" : "fetch", compile ? "compile" : "kernel"); - }); - loading.catch(() => {}); // awaited below; a failure there is the one reported + const load = (url: string) => { + const p = loadKernelModule(url, { what: "kernel", onProgress: onDownload }).catch((e: unknown) => { + const compile = e instanceof BootError && e.stage === "compile"; + throw tag(e, compile ? "compile" : "fetch", compile ? "compile" : "kernel"); + }); + p.catch(() => {}); // awaited below; a failure there is the one reported + return p; + }; + // Several CPUs: the SMP kernel, once a suspended session was offered (below). + let loading = smp ? null : load(kernelUrl); const session = sessionInfo(); session.catch(() => {}); let dataDisks: BlockDevice[] | DiskSpec[] = []; if (cfg.worker) { // The worker builds the data disk and the network from specs. - ui.check("worker", "Worker mode", "warn", "experimental (?worker=1)", - "the kernel, the data disk, the network, the display, input and sound devices run in a Web Worker"); - ui.hostLog("[host] worker mode: the kernel runs in a Web Worker, with the data disk, the network, the display, input and sound"); + ui.check("worker", "Worker mode", "warn", cfg.workerParam ? "experimental (?worker=1)" : `for ${cfg.cpus} CPUs (?smp=${cfg.smpParam})`, + "the kernel, the data disk, the network, the display, input and sound devices run in a Web Worker" + (smp ? ", which starts the other CPUs as workers of its own" : "")); + ui.hostLog(`[host] worker mode: the kernel runs in a Web Worker, with the data disk, the network, the display, input and sound${smp ? `; ${cfg.cpus} CPUs` : ""}`); dataDisks = await dataSpec(); } - const module = await loading; + if (smp) { + if (await offerResumeUp(session)) return; // reloading to resume on one CPU + loading = load(kernelUrl); + } + let module: WebAssembly.Module; + try { + module = await loading!; + } catch (e) { + if (smp && bootUpOnce(`the SMP kernel did not load (${(e as Error)?.message ?? e})`)) return; + throw e; + } dropLegacyScope(); // an older build's offline copy (sw.ts) if (ui.stageState("compile") !== "active") ui.stage("compile", "active"); // no progress events (e.g. a cached module) ui.stage("compile", "done", `${WebAssembly.Module.imports(module).length} imports, ${WebAssembly.Module.exports(module).length} exports`); @@ -654,8 +735,8 @@ export function start(): void { ok("Compiled the kernel", ui.stageTime("compile")); ui.hostLog(`[host] kernel downloaded and compiled in ${fmtS(performance.now() - t0)}`); const b = bundledBoot(module).initrd; - if (!b) throw tag(new Error(`${cfg.kernelUrl} has no bundled root file system`), "compile", "kernel"); - ui.hostLog(`[host] root file system: bundled in ${cfg.kernelUrl} (${fmtMiB(b.length)} gzipped)`); + if (!b) throw tag(new Error(`${kernelUrl} has no bundled root file system`), "compile", "kernel"); + ui.hostLog(`[host] root file system: bundled in ${kernelUrl} (${fmtMiB(b.length)} gzipped)`); ok(`Found the bundled root fs (${fmtMiB(b.length)})`); if (!cfg.worker) dataDisks = await openData(module); @@ -712,7 +793,8 @@ export function start(): void { sound: cfg.sound ? createAudioOut({ log }) : false, // Web Audio, ?sound=0 (audio.ts) vsock: true, // the terminal windows (windows.ts: kwtty sessions) }; - const resume = await offerResume(session, dataDisks); + // Several CPUs: offered above (offerResumeUp), on one CPU only. + const resume = smp ? null : await offerResume(session, dataDisks); kernelStarting = true; try { const create = (restore?: KernelSnapshot) => { @@ -722,6 +804,7 @@ export function start(): void { // worker downloads (from the HTTP cache) and compiles it. const inWorker = (kernel: WebAssembly.Module | string) => createKernel({ ...common, worker: true, kernel, compileInWorker: typeof kernel === "string", + cpus: smp ? cfg.cpus : undefined, // the worker starts the other CPUs (js/web/cpu.ts) shared: cfg.shared ? undefined : false, // shared memory where the page is cross-origin isolated (?shared=0: never) disks: dataDisks as DiskSpec[], onDiskError: (_i, e) => saveError(e), net: browserNetSpec({ enabled: cfg.net, servers: cfg.wisp }), // Wisp, in the worker (net.ts) @@ -731,7 +814,7 @@ export function start(): void { ? inWorker(module).catch((e: unknown) => { if (!(e instanceof BootError && e.stage === "support" && /cannot send the kernel/.test(e.message))) throw e; ui.hostLog(`[host] ${e.message}; the worker loads the kernel itself`); - return inWorker(new URL(cfg.kernelUrl, location.href).href); + return inWorker(new URL(kernelUrl, location.href).href); }) : createKernel({ ...common, kernel: module, disks: dataDisks as BlockDevice[], restore, @@ -758,6 +841,8 @@ export function start(): void { } catch (e) { kernelStarting = false; clearTimeout(workerWatchdog); + // Several CPUs that did not start (the worker, its JSPI, the shared memory): one CPU. + if (smp && bootUpOnce(`booting on ${cfg.cpus} CPUs failed (${(e as Error)?.message ?? e})`)) return; const be = e instanceof BootError ? e : undefined; if (cfg.worker && be?.stage === "support") throw tag(e, "worker", "boot"); if (cfg.worker && be?.stage === "download") throw tag(e, "fetch", "kernel"); @@ -787,6 +872,15 @@ export function start(): void { : `${why}: they wait for the kernel's next yield, up to 20 ms while the guest is busy`); ui.hostLog(`[host] kernel worker: console and evdev input and frames by ${shared ? "shared memory" : "messages"} (${why})`); } + if (smp) { + // The worker gives the SMP kernel one CPU where it cannot start their threads (it logs why). + const got = vm.stats().cpus; + ui.check("smp", "Guest CPUs", got > 1 ? "pass" : "warn", got > 1 ? `${got} (?smp=${cfg.smpParam})` : `1 (asked for ${cfg.cpus})`, + got > 1 ? "the SMP kernel, each CPU in a Web Worker on one shared memory (experimental)" + : "the kernel worker could not start CPU threads (the Kernel log says why): the SMP kernel runs on one CPU"); + ui.hostLog(`[host] SMP kernel on ${got} CPU${got > 1 ? "s" : ""} (${cfg.cpus} asked)`); + if (got < cfg.cpus) ui.toast(`Running on ${got} CPU${got > 1 ? "s" : ""}: the worker could not start more`); + } const booted = vm; KW.jitStats = () => booted.stats().jit; // kwemu's JIT counters in the System tab (and Copy diagnostics), for devices without devtools. diff --git a/web/src/components/Options.tsx b/web/src/components/Options.tsx index 158dfba..bafb6be 100644 --- a/web/src/components/Options.tsx +++ b/web/src/components/Options.tsx @@ -3,8 +3,10 @@ // Options in the System tab: one control per URL parameter (config.ts) // except ?simulate. Reboot loads the page with them (ui.rebootUrl()); Font // size applies at once and is kept in localStorage. Terminal style: on/off -// options are [x] check boxes, Network is (•) radio choices, Memory and -// Font size are sliders over their sizes. +// options are [x] check boxes, Network and CPUs are (•) radio choices, +// Memory and Font size are sliders over their sizes. CPUs are disabled, +// with the reason, where the page cannot boot more than one (config.ts +// smpBlocker()). // // The fields are controlled by the store. Besides onChange, native listeners // on the form (capture phase, so non-bubbling events count too) read every @@ -57,11 +59,11 @@ function Check({ id, name, on, off, value, label, note }: { id: string; name: ke } /** (•) one of several. */ -function Radio({ id, name, value, current, label }: { id: string; name: keyof Opts; value: string; current: string; label: string }) { +function Radio({ id, name, value, current, label, disabled }: { id: string; name: keyof Opts; value: string; current: string; label: string; disabled?: boolean }) { const checked = value === current; return ( -