mirror of
https://github.com/pithings/unkernel.git
synced 2026-12-06 19:07:37 +08:00
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.
This commit is contained in:
132
web/src/boot.ts
132
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<string | null> | 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<SessionMeta | null>): Promise<boolean> {
|
||||
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.
|
||||
|
||||
@@ -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 (
|
||||
<label className="flex cursor-pointer items-center gap-1.5 text-muted select-none hover:text-fg">
|
||||
<input id={id} name={name} type="radio" value={value} checked={checked} onChange={onField} className="peer sr-only" />
|
||||
<label className={`flex items-center gap-1.5 text-muted select-none ${disabled ? "cursor-not-allowed opacity-50" : "cursor-pointer hover:text-fg"}`}>
|
||||
<input id={id} name={name} type="radio" value={value} checked={checked} disabled={disabled} onChange={onField} className="peer sr-only" />
|
||||
<span aria-hidden="true" className="whitespace-pre peer-focus-visible:outline-2 peer-focus-visible:outline-accent">
|
||||
<span className="text-faint">(</span><span className={checked ? "text-ok" : ""}>{checked ? "•" : " "}</span><span className="text-faint">)</span>
|
||||
</span>
|
||||
@@ -103,6 +105,7 @@ function Slider({ id, name, label, value, stops }: { id: string; name: string; l
|
||||
}
|
||||
|
||||
const SIZES = [64, 128, 256, 512, 1024];
|
||||
const CPU_COUNTS = [1, 2, 4, 8];
|
||||
const FONTS = [11, 12, 13, 14, 15, 16, 18];
|
||||
|
||||
export function Options() {
|
||||
@@ -141,6 +144,12 @@ export function Options() {
|
||||
}));
|
||||
const fontValue = fontPref === String(autoPx) ? "auto" : fontPref;
|
||||
|
||||
// CPUs: 1, 2, 4, 8 up to the host's threads, the suggested count and a ?smp= that is none of them.
|
||||
const cpus = [...new Set([...CPU_COUNTS.filter((n) => n <= cfg.cpuMax), ...(cfg.cpuSuggested ? [cfg.cpuSuggested] : []), cfg.smpParam])].sort((a, b) => a - b);
|
||||
const cpuNote = cfg.smpBlocked ? `One CPU on this page: ${cfg.smpBlocked}.`
|
||||
: cfg.smpWhy ? `This boot runs on one CPU: ${cfg.smpWhy}.`
|
||||
: "Experimental. More than one boots the SMP kernel, each CPU in a Web Worker (as with Worker thread); no Suspend.";
|
||||
|
||||
// Enter in a text field reboots, like the button.
|
||||
const enter = (e: KeyboardEvent) => { if (e.key === "Enter") { e.preventDefault(); ui.reboot(); } };
|
||||
|
||||
@@ -153,7 +162,7 @@ export function Options() {
|
||||
<Check id="opt-sound" name="sound" on="on" off="off" value={o.sound} label="Sound" note="ALSA and /dev/dsp" />
|
||||
<Check id="opt-verbose" name="verbose" on="keep" off="clear" value={o.verbose} label="Verbose boot" note="show all kernel messages" />
|
||||
<Check id="opt-root" name="root" on="safe" off="overlay" value={o.root} label="Safe mode" note="boot without your changes" />
|
||||
<Check id="opt-worker" name="worker" on="on" off="off" value={o.worker} label="Worker thread" note="experimental" />
|
||||
<Check id="opt-worker" name="worker" on="on" off="off" value={o.worker} label="Worker thread" note={o.cpus !== "1" && !cfg.smpBlocked ? "experimental; on with several CPUs" : "experimental"} />
|
||||
<Check id="opt-fx" name="fx" on="on" off="off" value={o.fx} label="fx" note="start the coding agent at load" />
|
||||
</div>
|
||||
|
||||
@@ -170,6 +179,16 @@ export function Options() {
|
||||
value={o.wisp} onChange={onField} onKeyDown={enter} className="field h-8 px-2.5 text-[12.5px]" />
|
||||
</Field>
|
||||
|
||||
<fieldset className="col-span-full flex flex-col gap-1.5">
|
||||
<legend className="mb-1.5 text-[11.5px] text-faint">CPUs</legend>
|
||||
<div className="flex flex-wrap gap-x-5 gap-y-1" role="radiogroup" id="opt-cpus">
|
||||
{cpus.map((n) => (
|
||||
<Radio key={n} id={`opt-cpus-${n}`} name="cpus" value={String(n)} current={o.cpus} disabled={!!cfg.smpBlocked && n > 1}
|
||||
label={n === cfg.cpuSuggested && n > 1 ? `${n} (suggested)` : String(n)} />
|
||||
))}
|
||||
</div>
|
||||
<small id="opt-cpus-note" className="text-[11.5px] text-faint">{cpuNote}</small>
|
||||
</fieldset>
|
||||
<div className="col-span-full mt-3 grid grid-cols-[repeat(auto-fit,minmax(200px,1fr))] gap-x-12 gap-y-5">
|
||||
<Slider id="opt-mem" name="mem" label="Memory" value={memValue} stops={mem} />
|
||||
<Slider id="opt-font" name="font" label="Font size" value={fontValue} stops={fonts} />
|
||||
|
||||
@@ -86,8 +86,9 @@ export function Panel() {
|
||||
<K>esc</K> close <K>k i l e ?</K> tabs <K>c</K> copy <K>s</K> suspend <K>r</K> reboot
|
||||
</p>
|
||||
<button id="copy" type="button" className="btn btn-sm max-md:flex-1" onClick={() => ui.copyDiagnostics()}>Copy diagnostics</button>
|
||||
<button id="suspend" type="button" className="btn btn-sm max-md:flex-1" title="Save the running system in this browser and stop it; the next load offers to resume it"
|
||||
onClick={() => void ui.confirmSuspend()}>Suspend</button>
|
||||
{/* The SMP kernel cannot be saved (no parking): no Suspend with several CPUs. */}
|
||||
{KW.config.cpus < 2 && <button id="suspend" type="button" className="btn btn-sm max-md:flex-1" title="Save the running system in this browser and stop it; the next load offers to resume it"
|
||||
onClick={() => void ui.confirmSuspend()}>Suspend</button>}
|
||||
<button id="reboot" type="button" className="btn btn-sm btn-primary max-md:flex-1" onClick={() => ui.reboot()}>{changed ? "Reboot to apply" : "Reboot"}</button>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
@@ -49,6 +49,16 @@
|
||||
// on the page's thread.
|
||||
// ?shared=0 with ?worker=1: messages even where shared memory works
|
||||
// (to compare the two)
|
||||
// ?smp=N experimental: boot the SMP kernel on N CPUs (2 to 8, at most
|
||||
// navigator.hardwareConcurrency), each CPU in a Web Worker
|
||||
// of its own on one shared memory; implies ?worker=1 (CPU 0
|
||||
// blocks while it waits for another CPU, which a page's main
|
||||
// thread may not). Needs the page's SMP kernel (sdk.ts
|
||||
// kernelSmpUrl: a release bundle with an SMP patch) and
|
||||
// cross-origin isolation (https or localhost); otherwise, or
|
||||
// when the SMP kernel fails to load or start, the page boots
|
||||
// on one CPU as usual (smpBlocker(), boot.ts). No Suspend.
|
||||
// Default (and ?smp=1): one CPU, the UP kernel.
|
||||
// ?fx (or ?fx=1) start fx, the coding agent, in its side panel once the
|
||||
// page passes its preflight (fx.ts; the status line's fx
|
||||
// button does the same later). ?fx=0 is off, as is no ?fx.
|
||||
@@ -60,7 +70,7 @@
|
||||
// pre-installs them, step ids pick a subset (showcase.ts);
|
||||
// read in launcher.ts
|
||||
// ?simulate=nojspi,oom,lowmem fake a failure (for tests)
|
||||
import { DEFAULT_MEMORY_FALLBACK_MIB, autoMemoryMiB, kernelUrl } from "./sdk.ts";
|
||||
import { DEFAULT_MEMORY_FALLBACK_MIB, autoMemoryMiB, kernelSmpUrl, kernelUrl, webCpuBlocker } from "./sdk.ts";
|
||||
|
||||
/** The project's source, linked from About and the boot notes. */
|
||||
export const REPO = "https://github.com/pithings/unkernel";
|
||||
@@ -96,8 +106,24 @@ export interface Config {
|
||||
data: boolean;
|
||||
/** ?root=initramfs: safe mode (kw.root=initramfs) for this boot, else null. */
|
||||
root: "initramfs" | null;
|
||||
/** ?worker=1: the kernel runs in a Web Worker (with the data disk, network, display, input and sound). */
|
||||
/** The kernel runs in a Web Worker (with the data disk, network, display, input and sound): ?worker=1, or more than one CPU. */
|
||||
worker: boolean;
|
||||
/** ?worker=1 as given (the Worker thread option). */
|
||||
workerParam: boolean;
|
||||
/** The SMP kernel's URL (sdk.ts kernelSmpUrl), or null when the page has none. */
|
||||
kernelSmpUrl: string | null;
|
||||
/** ?smp= as given (1 to 8; 1 when absent): the CPUs option. */
|
||||
smpParam: number;
|
||||
/** CPUs this load boots with: smpParam where possible (capped at cpuMax), else 1. */
|
||||
cpus: number;
|
||||
/** Why this page cannot boot more than one CPU (smpBlocker()), or null. */
|
||||
smpBlocked: string | null;
|
||||
/** Why this load boots on one CPU although ?smp= asks for more, or null. */
|
||||
smpWhy: string | null;
|
||||
/** The most CPUs offered: navigator.hardwareConcurrency, at most 8 (the kernel's limit). */
|
||||
cpuMax: number;
|
||||
/** The count the CPUs option suggests, or 0 when this device has too few threads to suggest one. */
|
||||
cpuSuggested: number;
|
||||
/** Worker mode: shared memory for input and frames where it works (?shared=0: messages). */
|
||||
shared: boolean;
|
||||
/** ?fx: start fx (fx.ts) in its panel at load. */
|
||||
@@ -111,6 +137,36 @@ export interface Config {
|
||||
fontSize: number;
|
||||
}
|
||||
|
||||
/** The kernel's limit (NR_CPUS in kw_smp.config). */
|
||||
export const MAX_CPUS = 8;
|
||||
|
||||
/**
|
||||
* Why this page cannot boot the SMP kernel, or null: no SMP kernel in the
|
||||
* page's bundle, no cross-origin isolation (shared memory), no Web
|
||||
* Workers or no Atomics.waitAsync (webCpuBlocker()), or one CPU thread.
|
||||
* JSPI and nested workers in the kernel worker are checked there: a worker
|
||||
* that cannot start CPUs boots the SMP kernel on one CPU (boot.ts says so).
|
||||
*/
|
||||
export function smpBlocker(): string | null {
|
||||
if (!kernelSmpUrl) return "this page's kernel has no SMP build (its release bundle carries no SMP patch)";
|
||||
const why = webCpuBlocker({ worker: true });
|
||||
if (why) return why;
|
||||
if ((navigator.hardwareConcurrency || 1) < 2) return "this device reports a single CPU thread";
|
||||
return null;
|
||||
}
|
||||
|
||||
/** sessionStorage: boot this tab's next load on one CPU (boot.ts bootUpOnce()), with why. */
|
||||
export const UP_ONCE_KEY = "kw-up-once";
|
||||
function takeUpOnce(): string | null {
|
||||
try {
|
||||
const v = sessionStorage.getItem(UP_ONCE_KEY);
|
||||
sessionStorage.removeItem(UP_ONCE_KEY);
|
||||
return v;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function readConfig(search: string = location.search): Config {
|
||||
const params = new URLSearchParams(search);
|
||||
const coarse = typeof matchMedia === "function" && matchMedia("(pointer: coarse)").matches;
|
||||
@@ -123,6 +179,19 @@ export function readConfig(search: string = location.search): Config {
|
||||
const root = params.get("root") === "initramfs" ? "initramfs" : null;
|
||||
const wispParam = params.get("wisp");
|
||||
const wisp = wispParam && wispParam !== "0" ? wispParam.split(",").map((s) => s.trim()).filter(Boolean) : null;
|
||||
// CPUs: as many as asked where the page can, never more than the host's
|
||||
// threads. The suggestion leaves half of them to the host (the page, the
|
||||
// browser, other tabs): a guest CPU whose thread the host deschedules
|
||||
// stalls the others when they wait for it (.agents/status.md, SMP).
|
||||
const hc = navigator.hardwareConcurrency || 1;
|
||||
const cpuMax = Math.max(1, Math.min(MAX_CPUS, hc));
|
||||
const half = Math.min(4, Math.floor(hc / 2));
|
||||
const smpParam = Math.max(1, Math.min(MAX_CPUS, Math.floor(Number(params.get("smp"))) || 1));
|
||||
const smpBlocked = smpBlocker();
|
||||
const upOnce = smpParam > 1 ? takeUpOnce() : null;
|
||||
const smpWhy = smpParam < 2 ? null : smpBlocked ?? upOnce;
|
||||
const cpus = smpWhy ? 1 : Math.min(smpParam, cpuMax);
|
||||
const workerParam = params.get("worker") === "1";
|
||||
return {
|
||||
kernelUrl: kernelUrl.pathname,
|
||||
memMiB: fixed ? Number(memParam) : auto.mib,
|
||||
@@ -140,7 +209,15 @@ export function readConfig(search: string = location.search): Config {
|
||||
sound: params.get("sound") !== "0",
|
||||
data: params.get("data") !== "0",
|
||||
root,
|
||||
worker: params.get("worker") === "1",
|
||||
worker: workerParam || cpus > 1,
|
||||
workerParam,
|
||||
kernelSmpUrl: kernelSmpUrl?.pathname ?? null,
|
||||
smpParam,
|
||||
cpus,
|
||||
smpBlocked,
|
||||
smpWhy,
|
||||
cpuMax,
|
||||
cpuSuggested: half >= 2 ? Math.min(half, cpuMax) : 0,
|
||||
shared: params.get("shared") !== "0",
|
||||
fx: params.has("fx") && params.get("fx") !== "0",
|
||||
verbose: params.get("verbose") === "1",
|
||||
|
||||
@@ -46,11 +46,16 @@ async function preflight(): Promise<boolean> {
|
||||
ui.check("secure", "Secure context", isSecureContext ? "pass" : "info", isSecureContext ? "yes" : `no (${location.protocol}//${location.hostname})`,
|
||||
isSecureContext ? "" : "not required: plain http on a LAN address is fine; only the clipboard and device-memory APIs are hidden");
|
||||
ui.check("coi", "Cross-origin isolated", "info", crossOriginIsolated ? "yes" : "no",
|
||||
"not required; with ?worker=1 it lets input and frames cross through shared memory instead of messages");
|
||||
"not required; with ?worker=1 it lets input and frames cross through shared memory instead of messages, and several CPUs (?smp=) need it");
|
||||
const devMem = (navigator as Navigator & { deviceMemory?: number }).deviceMemory;
|
||||
ui.check("devmem", "Device memory", "info", devMem ? `${devMem} GB` : "unknown", devMem ? "" : isSecureContext ? "API not supported" : "hidden on insecure origins");
|
||||
ui.check("mem", "Kernel memory", "info", `${cfg.memMiB} MiB requested`, cfg.memWhy);
|
||||
ui.check("cpu", "CPU threads", "info", String(navigator.hardwareConcurrency || "unknown"));
|
||||
// Several guest CPUs (?smp=N, config.ts): what this load boots with, and why not more.
|
||||
ui.check("smp", "Guest CPUs", cfg.smpParam < 2 ? "info" : cfg.cpus > 1 ? "pass" : "warn",
|
||||
cfg.cpus > 1 ? `${cfg.cpus} (?smp=${cfg.smpParam})` : cfg.smpParam > 1 ? `1 (asked for ${cfg.smpParam})` : "1",
|
||||
cfg.smpWhy ?? (cfg.cpus > 1 ? "the SMP kernel, each CPU in a Web Worker on one shared memory (experimental)"
|
||||
: cfg.smpBlocked ? `several CPUs are unavailable: ${cfg.smpBlocked}` : "Options, CPUs, boots the SMP kernel on several"));
|
||||
ui.check("input", "Input", "info", (cfg.coarse ? "touch" : "mouse/keyboard") + (navigator.maxTouchPoints ? `, ${navigator.maxTouchPoints} touch points` : ""));
|
||||
ui.check("viewport", "Viewport", "info", `${innerWidth}×${innerHeight} @${devicePixelRatio || 1}x`);
|
||||
ui.check("clipboard", "Clipboard API", navigator.clipboard ? "pass" : "info", navigator.clipboard ? "yes" : "no", navigator.clipboard ? "" : "copy/paste use a manual fallback");
|
||||
|
||||
@@ -12,6 +12,7 @@ import { webPlatform } from "../../js/web/platform.ts";
|
||||
export * from "../../js/core/index.ts";
|
||||
export { DEFAULT_MEMORY_FALLBACK_MIB, autoMemoryMiB } from "../../js/web/memory.ts";
|
||||
export { DATA_DISK_NAME, importDataDisk, openDataDisk, resetDataDisk } from "../../js/web/disk.ts";
|
||||
export { webCpuBlocker } from "../../js/web/cpu.ts";
|
||||
|
||||
/**
|
||||
* The kernel with Alpine bundled (vmlinux32.wasm + the initramfs,
|
||||
@@ -22,8 +23,8 @@ export const kernelUrl: URL = new URL("../kernel/page/unkernel-alpine.wasm", imp
|
||||
|
||||
/**
|
||||
* The SMP kernel with the same Alpine, its own hashed asset, or null when
|
||||
* the release bundle has no SMP patch. Nothing uses it yet: the page has no
|
||||
* CPU threads (.agents/status.md, SMP).
|
||||
* the release bundle has no SMP patch. Fetched only when the page boots on
|
||||
* more than one CPU (?smp=N, config.ts; boot.ts).
|
||||
*/
|
||||
export { kernelSmpUrl } from "virtual:unkernel-smp-kernel";
|
||||
|
||||
@@ -32,7 +33,8 @@ const platform = webPlatform(kernelUrl);
|
||||
/**
|
||||
* js/web.ts's createKernel(), with the page's kernel as the default; with
|
||||
* `worker: true` (?worker=1) on a Web Worker (js/web/worker.ts, which Vite
|
||||
* bundles as a worker).
|
||||
* bundles as a worker), which starts an SMP kernel's other CPUs as nested
|
||||
* workers (js/web/cpu.ts) when `cpus` asks for them.
|
||||
*/
|
||||
export function createKernel(opts: CreateKernelOptions & { worker: true }): Promise<WorkerKernel>;
|
||||
export function createKernel(opts?: CreateKernelOptions & { worker?: false }): Promise<KernelInstance>;
|
||||
|
||||
@@ -112,6 +112,8 @@ export interface Options {
|
||||
data: "on" | "off";
|
||||
root: "overlay" | "safe";
|
||||
worker: "on" | "off";
|
||||
/** CPUs, "1" to "8" (?smp=). */
|
||||
cpus: string;
|
||||
fx: "on" | "off";
|
||||
}
|
||||
|
||||
|
||||
@@ -77,8 +77,10 @@ function hintFor(msg: string): string {
|
||||
return "The kernel could not be downloaded. Check the network and reload; a page from an older deploy may refer to a kernel that is gone.";
|
||||
if (/module|script/i.test(msg))
|
||||
return "A page script failed to load or parse: check the network and the server log. A browser too old for the syntax fails the same way; Chrome/Edge 137+ or Safari 27+ is required anyway.";
|
||||
if (/panic|trap|unreachable|RuntimeError/i.test(msg))
|
||||
return "The kernel stopped. The kernel log tab has the last console lines; Copy diagnostics and reboot.";
|
||||
const smp = (KW.config?.cpus ?? 1) > 1;
|
||||
if (/panic|trap|unreachable|RuntimeError/i.test(msg) || (smp && /\bCPU \d/.test(msg)))
|
||||
return "The kernel stopped. The kernel log tab has the last console lines; Copy diagnostics and reboot." +
|
||||
(smp ? " Several CPUs are experimental: set CPUs to 1 under Options to boot as usual." : "");
|
||||
return "";
|
||||
}
|
||||
|
||||
@@ -106,7 +108,8 @@ export function createUi(cfg: Config) {
|
||||
append: cfg.baseCmdline,
|
||||
data: cfg.data ? "on" : "off",
|
||||
root: cfg.root === "initramfs" ? "safe" : "overlay",
|
||||
worker: cfg.worker ? "on" : "off",
|
||||
worker: cfg.workerParam ? "on" : "off",
|
||||
cpus: String(cfg.smpParam),
|
||||
fx: cfg.fx ? "on" : "off",
|
||||
};
|
||||
const $ = initStore({
|
||||
@@ -248,6 +251,7 @@ export function createUi(cfg: Config) {
|
||||
},
|
||||
/** Suspend from a shortcut or the dialog: asks first (boot.ts does it: KW.suspend). */
|
||||
async confirmSuspend() {
|
||||
if (cfg.cpus > 1) { ui.toast("Suspend needs one CPU: the SMP kernel cannot be saved (Options, CPUs)"); return; }
|
||||
if (!KW.suspend || $.get().state !== "running") { ui.toast("Suspend works once the system runs"); return; }
|
||||
if (!await ui.ask({ title: "suspend", msg: "Save the running system in this browser and stop it? The next load offers to resume it. Terminal windows 1-9 and network connections do not survive.", ok: "Suspend" })) return;
|
||||
ui.closePanel();
|
||||
@@ -378,7 +382,7 @@ export function createUi(cfg: Config) {
|
||||
L.push(`unkernel diagnostics, ${new Date().toISOString()}`);
|
||||
L.push(`url: ${location.href}`);
|
||||
L.push(`state: ${s.state} (${s.label}) after ${fmtT(now())}`);
|
||||
L.push(`config: mem=${cfg.memMiB} MiB (${cfg.memWhy})${KW.memActualMiB ? ` allocated=${KW.memActualMiB} MiB` : ""} kernel=${cfg.kernelUrl} cmdline="${cfg.cmdline}"${cfg.worker ? " worker=1" : ""}`);
|
||||
L.push(`config: mem=${cfg.memMiB} MiB (${cfg.memWhy})${KW.memActualMiB ? ` allocated=${KW.memActualMiB} MiB` : ""} kernel=${cfg.cpus > 1 ? cfg.kernelSmpUrl : cfg.kernelUrl} cmdline="${cfg.cmdline}"${cfg.worker ? " worker=1" : ""}${cfg.smpParam > 1 ? ` cpus=${cfg.cpus}${cfg.smpWhy ? ` (asked ${cfg.smpParam}: ${cfg.smpWhy})` : ""}` : ""}`);
|
||||
L.push("", "== stages");
|
||||
for (const [id] of STAGES) {
|
||||
const st = stages[id]!;
|
||||
@@ -433,6 +437,7 @@ export function createUi(cfg: Config) {
|
||||
set("data", o.data === "off" ? "0" : null);
|
||||
set("root", o.root === "safe" ? "initramfs" : null);
|
||||
set("worker", o.worker === "on" ? "1" : null);
|
||||
set("smp", o.cpus === "1" ? null : o.cpus);
|
||||
if (o.fx === "off") set("fx", null);
|
||||
else if (!cfg.fx) set("fx", "1"); // an existing ?fx (any value but 0) stays as written
|
||||
// URLSearchParams writes a bare ?fx as fx=: keep it bare, so the URL stays as given.
|
||||
|
||||
@@ -183,19 +183,23 @@ const scenarios = {
|
||||
mem("64"); net("custom"); set("opt-wisp", "wss://a.example/, wss://b.example/", "input");
|
||||
check("opt-jit", false); check("opt-verbose", true); set("opt-append", "console=hvc0 rdinit=/bin/sh", "input");
|
||||
check("opt-data", false); check("opt-root", true); check("opt-worker", true); check("opt-fx", true);
|
||||
// CPUs: only where the page has the SMP kernel and may boot it (else the choices above 1 are disabled).
|
||||
const cpus = !!$("opt-cpus-2") && !$("opt-cpus-2").disabled;
|
||||
if (cpus) check("opt-cpus-2", true);
|
||||
await tick();
|
||||
const all = KW.ui.rebootUrl(), wispShown = !$("opt-wisp-row").hidden, label = $("reboot").textContent;
|
||||
net("off");
|
||||
const off = KW.ui.rebootUrl();
|
||||
mem("auto"); net("default"); check("opt-jit", true); check("opt-verbose", false); set("opt-append", "", "input");
|
||||
check("opt-data", true); check("opt-root", false); check("opt-worker", false); check("opt-fx", false);
|
||||
if (cpus) check("opt-cpus-1", true);
|
||||
await tick();
|
||||
return { before, all, wispShown, label, off, reset: KW.ui.rebootUrl(), wispHidden: $("opt-wisp-row").hidden };
|
||||
return { before, all, wispShown, label, off, reset: KW.ui.rebootUrl(), wispHidden: $("opt-wisp-row").hidden, cpus };
|
||||
})()`);
|
||||
const q = new URLSearchParams(opts.all.split("?")[1]);
|
||||
if (opts.before !== "/" || opts.reset !== "/" || !opts.wispShown || !opts.wispHidden || opts.label !== "Reboot to apply"
|
||||
|| q.get("mem") !== "64" || q.get("wisp") !== "wss://a.example/,wss://b.example/" || q.get("jit") !== "0" || q.get("verbose") !== "1"
|
||||
|| q.get("append") !== "console=hvc0 rdinit=/bin/sh" || q.get("data") !== "0" || q.get("root") !== "initramfs" || q.get("worker") !== "1" || q.get("fx") !== "1" || new URLSearchParams(opts.off.split("?")[1]).get("wisp") !== "0")
|
||||
|| q.get("append") !== "console=hvc0 rdinit=/bin/sh" || q.get("data") !== "0" || q.get("root") !== "initramfs" || q.get("worker") !== "1" || q.get("fx") !== "1" || q.get("smp") !== (opts.cpus ? "2" : null) || new URLSearchParams(opts.off.split("?")[1]).get("wisp") !== "0")
|
||||
throw new Error(`options do not map to the URL: ${JSON.stringify(opts)}`);
|
||||
console.log(` options -> ${decodeURIComponent(opts.all)}`);
|
||||
await page.click('.tabs [data-tab="log"]');
|
||||
|
||||
Reference in New Issue
Block a user