Commit Graph

20 Commits

Author SHA1 Message Date
Pooya Parsa
21fc21c81a 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.
2026-11-17 11:26:48 +00:00
Pooya Parsa
f7fb9adef3 Retry user accesses while the fault succeeds, atomic futex ops (SMP)
kw_user_addr() gave up after three faults, so a system call could fail
with EFAULT on a valid address when other threads of the mm took the
page away again after each fault (MADV_DONTNEED, a fork's COW
write-protect under host load). It now walks again for as long as the
fault succeeds, ended by a fatal signal or a real fault error, with a
backstop of 10000 rounds. A kernel access whose fault returned
VM_FAULT_RETRY failed with any signal pending (user_mode() of a NULL
pt_regs); only a fatal signal ends it now, and its faults wait
killable. On SMP the futex ops on user words were not atomic against
user AMOs on other CPUs, and the page-table walk reads each level once.

kwtest gets `uaccess:` checks (a userfaultfd read with a signal pending,
FUTEX_WAKE_OP beside amoadd). The kernel changes are two fixup! patches
at the end of the series, for the arch patch and `wasm: SMP`.
2026-11-17 11:07:18 +00:00
Pooya Parsa
cc8fa76b43 Describe the kernel patch tools as they are used 2026-11-17 10:44:33 +00:00
Pooya Parsa
96598464f9 Build the CPU worker into the package and split the page's kernel
pnpm build inlines js/node/cpu-entry.ts where js/node/cpu.ts starts it,
in the Node entries and inside the inlined Node kernel worker (WORKERS
nested), so the package starts SMP CPUs without source files. The page
build serves web/kernel/page/: the bundle without its SMP patch section
(the same bytes when there is none) and, only with a patch, the SMP
bundle it makes as a second hashed asset (kernelSmpUrl, unused until the
page has CPU threads).
2026-11-17 10:44:16 +00:00
Pooya Parsa
869f8375fd Ship the SMP kernel as a patch in the UP bundle (packaging prototype)
kernel/tools/bundle.mjs --smp adds unkernel.kernel.smp.kwpatch: a
bsdiff-style patch (kwdiff.mjs) from the bundle's kernel to the SMP
build, after renumbering the base's function, global and type indices
and moving its data addresses to the target's (kwremap.mjs,
js/core/kremap.ts). With more than one CPU asked, loadKernelModule()
and the CLI derive the SMP kernel from it (js/core/kpatch.ts, hashes
checked); one CPU or a bundle without the section behaves as before.
test/kpatch.test.ts round-trips synthetic data and, given KPATCH_UP and
KPATCH_SMP, the real kernels.
2026-11-17 10:30:14 +00:00
Pooya Parsa
1a9eb7343c Take a free spinlock out of turn, kw_spin_unfair= (SMP step 7) 2026-11-17 09:50:28 +00:00
Pooya Parsa
e668cddedf Block instead of spinning for another CPU (SMP step 6)
A guest CPU waiting for another (a spinlock, a cross-CPU call's answer,
smp_cond_load_*()) spins 20 us and then blocks its thread until the
unlock or csd_unlock() kicks it, an IPI arrives or 100 us pass, and a
long spin takes its expired timer. On a busy host the spinning made
cross-CPU work 10-50x slower than the guest's lost share explains;
beside 24 spinning host processes a 4-CPU kwtest move ping-pong now
takes 0.58 s instead of 10 s, and a pipe ping-pong, fork and a
contended kernel spinlock are 15-50x faster. Idle-host numbers and the
UP build are unchanged.

Two new kernel patches: the csd wait hooks in kernel/smp.c, and the
arch's waits.
2026-11-16 23:32:57 +00:00
Pooya Parsa
9869855afd Run kwblk, kwshm, kwfb, kwinput and kwsnd on SMP kernels (SMP step 5)
The five host-device drivers that refused to start on an SMP kernel now
work there; every device import still runs on CPU 0, whose host has the
devices. kwblk: blk-mq calls ->queue_rq() on the submitting CPU in
atomic context, so another CPU's request waits in a list and raises the
block interrupt on CPU 0, which submits it before it reaps. kwshm, kwfb,
kwinput and kwsnd call their imports from process context through
kw_host_call() (at once on CPU 0, else a work item there while the
caller sleeps); kwsnd's timer is pinned to CPU 0, and a start or stop
triggered on another CPU is sent from a work item on CPU 0, in order.
The UP kernel compiles to the same code but for one WARN line number.

Host side: BlockHost.raise() sets IRQ 3 with Kernel.setIrqBits(), an
atomic OR on a shared memory; its plain read-modify-write could drop an
IPI bit another CPU set meanwhile.

Tests: UNKERNEL_TEST_CPUS=n runs test/api.test.ts on an SMP kernel
(snapshot tests skip), and glimmer-check passes --initrd and --smp to
the CLI. The docs describe the funnels, their cost and what snapshots
on SMP would need from them.
2026-11-16 21:04:18 +00:00
Pooya Parsa
3b94faa2c4 Run kwemu's JIT on every CPU of an SMP kernel (SMP step 4)
Each CPU's thread now has a JitHost of its own, bound to its instance's
function table, so each CPU's kwemu compiles what it finds hot into its
own table; nothing compiled on one CPU is reachable from another. The
host no longer turns the JIT off with more than one CPU. A secondary's
JIT host mirrors its counters into a SharedArrayBuffer: stats().jit is
the sum over CPUs, stats().jitCpus and kwemuCpus are per CPU, and the
CLI's --stats prints a line per CPU.

A secondary CPU's thread never reached its event loop, so V8 ran neither
FinalizationRegistry callbacks nor the last pass of its collections
there: the JIT host saw nothing collected, prompted collections with
ever larger allocations (one stalled a CPU for 0.58 s while a TLB
shootdown waited for it) and would have refused to compile after 2048
frees. Every CPU now yields to its host every 20 ms of user code (the
kernel side is folded into wasm: SMP), and a secondary's sched_yield
returns through its event loop.

kwemu: compiled code reads the interrupt word with i32.atomic.load when
the memory is shared (a plain load in a loop that stores nothing may be
hoisted, and an IPI would go unseen), and an interpreted self-loop that
an interrupt ends now counts its passes towards the compile threshold
(under a stream of IPIs hot loops were never compiled). A unit test
covers the latter.

kwtest gains jit: checks for SMP kernels: hot() and fphot() on every CPU
at once under signals, byte and halfword stores beside AMOs and LR/SC in
one cache line, a thread moved every 4 ms while in compiled loops, and
code that one CPU runs compiled while another rewrites it (with
__builtin___clear_cache), replaces it by mremap() or makes it
non-executable. The docs describe the guarantees (kwemu.md, JIT on
several harts) and the numbers.
2026-11-16 19:38:24 +00:00
Pooya Parsa
b1d9b47692 Flush only CPUs that use the mm, and keep a secondary's memory views (SMP)
A TLB flush no longer waits for a CPU in lazy TLB mode (idle or a
kthread with the mm still loaded): it marks the CPU stale, and the CPU
flushes when it switches back to that mm. A PTE that only gained access
(update_mmu_cache_range(), the spurious-fault flush) is flushed on this
CPU alone, since kwemu caches only translations that allowed the
access. The teardown of a whole mm clears PTEs with a plain read and
store. A secondary CPU's host makes its memory views once instead of a
DataView per clock read.

With a process moved to CPU 1 while CPU 0 idles, a page fault goes from
3,321 to 536 ns, fork+exit+wait from 118 to 80 us and clock_gettime
from 500 to 358 ns; exit costs 4.3 ns less per mapped page. The kernel
side is folded into the wasm: SMP patch. status.md lists the measured
changes that were not applied (vendor/smp-deferred/).
2026-11-16 18:22:14 +00:00
Pooya Parsa
bc9403d6be Move tasks between CPUs where their stack can be dropped (SMP step 3)
A user task may now move to another CPU at the reschedule on its way to
user mode, where its state is all in pt_regs, and starts there on a
fresh stack; switched in on its own CPU it resumes its stack as before.
The load balancer and affinity changes move tasks: sched_setaffinity()
records the mask at once and the task moves on its way to user mode,
instead of failing with EBUSY. A task asleep in a system call stays
until it returns. A workqueue rescuer that serves another CPU's per-CPU
pool moves there instead of running that CPU's work on its own.

The CPU that held a moved task's stack calls the new import
wasm_stack_drop(task), and its host forgets that stack. A secondary
CPU's host also raises the stop IPI on CPU 0 when the session ends there
(exit, trap, fatal error), which the kernel takes even while spinning
with interrupts off, so CPU 0 suspends and its host ends the session.

kwtest gains move checks (threads spreading from one CPU, register, FP
and TLS state across 300 self-moves, affinity changes of a busy and a
sleeping thread, queued signals and pipe and futex ping-pong across
moves) and `kwtest smp`, which runs only the SMP checks. The kernel side
is folded into the sched, kthread and workqueue, and wasm: SMP patches.
2026-11-16 17:41:34 +00:00
Pooya Parsa
55095f50bf Boot an SMP kernel on several CPUs in Node (SMP step 2)
A second kernel build (kw_smp.config) runs one instance of the module
per CPU, each in a worker thread on a shared memory. The host's Kernel
is CPU 0 with every device; wasm_cpu_start starts the others through
Platform.spawnCpu (js/node/cpu.ts), which run js/core/cpu.ts: their own
JSPI task switching, the clocks on CPU 0's time base, and console and
exit forwarded to CPU 0's host. The host sets IRQ bits atomically and
ends CPU 0's idle on Atomics.waitAsync of its word, which other CPUs'
IPIs notify. createKernel's cpus option and the CLI's --smp N (which
implies --worker) ask for CPUs; a UP kernel ignores them with a log
line, and more than one CPU runs the interpreter only.

kwemu built with -Dkwemu-atomics makes AMOs atomic, SC a
compare-and-swap against the value LR read, and FENCE a barrier (ABI
7). kwtest gains an smp check (threads on several CPUs counting
through AMOs, LR/SC and a mutex) and skips the park check on an SMP
kernel, which has no parking. The kernel side is in five new patches.
2026-11-16 16:07:40 +00:00
Pooya Parsa
9ec93c1104 Make atomic_read and atomic_set plain, skip a zero folio_ref_add, and document where the atomics cost is (SMP, WIP) 2026-11-16 14:58:54 +00:00
Pooya Parsa
2c3f3c10aa Document the shared-memory kernel build and its cost, export its kernel patch 2026-11-16 13:23:51 +00:00
Pooya Parsa
cabc62f8f2 web: scope the service worker to /vm/ and drop the offline copy
The worker now answers only /vm/<id>/<port>[/...], the guest preview's
relay. The page and its assets load from the network: a cache-first page
stayed old whenever caching a new build failed. Root-relative requests
from a preview are no longer relayed; guest pages use relative URLs.

sw.ts calls registration.update() on every load and after an hour
hidden, since register() with an unchanged URL never looks for a new
script. The old scope-/ registration gets the new script on its next
navigation, deletes the kw-app-* caches and tells old pages an update is
ready; the next load unregisters it. The update indicator, the Offline
copy row and /kw-assets.json go with the offline copy.
2026-11-16 12:29:32 +00:00
Pooya Parsa
e13e193bb8 guest: leave kwtest and kwbench out of release bundles
alpine.sh always writes alpine-test.cpio: the image followed by a second
cpio archive with kwtest and kwbench, which the kernel unpacks after the
first. alpine.cpio, which build.sh bundles, is the same, or with
KW_RELEASE=1 the image alone. The choice is in alpine.sh because build.sh
is part of the release workflow's cache keys.

The release workflow sets KW_RELEASE=1, so the GitHub release bundle, the
npm package and the deployed page have no test programs. Its kwtest steps
boot the release bundle's kernel with --initrd alpine-test. wasi-node.ts
uses alpine-test.cpio, and the headless lowmem scenario boots to the
shell instead of running kwtest, since the built page runs a release
kernel.
2026-11-16 12:24:42 +00:00
Pooya Parsa
eacd495a91 guest: use devtmpfs nodes in kwtest's vsock and kwfb checks
kwtest made /dev/vsock and /dev/fb0 in /tmp. The overlay root mounts /tmp
nodev, so from a shell there (the page with its data disk) every open of
those nodes failed with EACCES: the kwfb check failed, and the vsock check
took the no-device branch and failed on ECONNRESET. It now uses the node
in /dev when devtmpfs has it, and makes one in /tmp only otherwise (as
/init), removing one left over from a killed run first.
2026-11-16 12:24:42 +00:00
Pooya Parsa
447d26f29d guest: rebuild busybox, zlib, openssl and apk-tools for kwemu
kernel/guest/alpine-opt.sh builds them from Alpine's own source,
patches and configuration (the aports commits the image's packages came
from), with gcc 16 at -O2 for rv64gc + Zba/Zbb/Zbs/Zicond, linked with
lld, against a sysroot of Alpine's packages (the image's musl). alpine.sh
and alpine-disk.sh swap the six files into the images.

Measured in the guest: shell scripts about 20% faster, exec 24%, apk
with both indexes 11%, sha1/sha512/chacha20 22-30%
(.agents/guest-packages.md).

The release workflow installs the host tools and caches the build output
under its own key; no existing cache key, path or hashed file changes.
setup.sh checks the new tools.
2026-11-16 11:50:47 +00:00
Pooya Parsa
3fd7021dc9 web: add fx, the coding agent, in a side panel working on the VM
The status line's fx button (or Ctrl-A f, or ?fx at load) runs libfx's
wasm fx terminal in a panel docked right of the stage, over it on narrow
screens. Its shell tool runs each command in the guest through
vm.exec(). The sign-in, settings and history stay in module memory only.
vercel.com sends its OAuth discovery document without CORS headers, so
fx's fetch falls back to a copy of the fields it reads. The launcher's
fx demo (the x86_64 binary under qemu) is hidden.
2026-11-16 00:35:12 +00:00
Pooya Parsa
26d08730cc Initial commit 2026-11-15 23:27:04 +00:00