Commit Graph

42 Commits

Author SHA1 Message Date
Pooya Parsa
49f03d0c61 kernel: poll the timer and pending interrupts in cond_resched(), so that direct reclaim lets the OOM victim run (#6) 2026-11-24 18:04:25 +00:00
Pooya Parsa
951bb8e5dd kernel: let kwsnd periods go down to 2 ms, in a buffer of 10 ms or more (#22)
The shortest period and tick drop from 5 ms to 2 ms for programs that
ask for low latency. A buffer is 10 ms or more as before (two 5 ms
periods), and a late tick still hands over up to 15 ms' worth when ticks
are shorter than 5 ms, so a short period tolerates the same host stall.
Programs that leave the period to alsa-lib, plain aplay, OSS without
SETFRAGMENT and requests of 256 frames or more negotiate what they did;
snd_pcm_set_params() with a latency under 20 ms now gets four periods of
2.5 to 3.75 ms (measured on Node, 2026-11-24).

Co-authored-by: Adam Meghji <566793+adammeghji@users.noreply.github.com>
2026-11-24 16:25:03 +00:00
Pooya Parsa
d5a2597183 Give user space a 48-bit address space (256 TiB), as arm64 with 48-bit VAs: four-level Sv48-format page tables in the kernel and kwemu, so Ladybird's 4 TiB GC cage fits; check it in kwtest
The user page tables gain a level: the PGD now holds PUD tables (P4D
folded), and kwemu's walker and the kernel's uaccess walk read four
levels. TASK_SIZE is 1 << 48, and kwemu faults addresses at or above it.
KW_ABI_VERSION stays 4: no release carries ABI 4 yet.
2026-11-23 23:29:55 +00:00
Pooya Parsa
7fc4e1ff6f kernel: support ptrace debuggers: arm64's register sets, single-step in software, kernel writes into user code flushed for kwemu, and core dumps (23.5 KB), so strace, gdb, gdbserver and ltrace work in the guest; check them in kwtest 2026-11-23 23:22:19 +00:00
Pooya Parsa
2c376d6d66 kernel: place CPU 0's word of pending interrupts inside the image: unplaced by the linker script, it lay past _end in the page allocator's memory, and its writes zeroed a word of the page cache (busybox's udhcpc died of SIGILL) 2026-11-23 22:23:03 +00:00
Pooya Parsa
5a4a324044 kernel: turn on UDMABUF (/dev/udmabuf, 4 KB), which Mesa's lavapipe needs to export its images as dma-bufs 2026-11-23 21:59:46 +00:00
Pooya Parsa
5bdd68882d Give user space the whole 39-bit address space (512 GiB), as arm64 with 39-bit VAs: .NET's 256 GiB GC regions reservation now fits
TASK_SIZE was 1 << 38, the lower half of Sv39 carried over from the
riscv64 guest, so the .NET runtime failed at startup ("GC: Reserving
274877906944 bytes (256 GiB) for the regions range failed"). The kernel
never maps its own memory in the user page tables, so user space can
have every address the three levels index. kwemu now faults addresses
at or above 1 << 39 instead of accepting a sign-extended upper half,
which would alias pgd slots 256-511. KW_ABI_VERSION is 4.
2026-11-23 21:58:05 +00:00
Pooya Parsa
0b65e72c36 Enable seccomp filters in the kernel (arm64 ABI, 12 KB), check them in kwtest, and drop the Alpine image's bwrap shim, which removed bwrap's --seccomp 2026-11-23 21:18:38 +00:00
Pooya Parsa
44ff5a8dd9 a64: poll the code epoch with a plain load, and give it and each CPU's pending word 128 bytes: JavaScriptCore runs an atomic load as a read-modify-write, so 4 CPUs ran user code at 0.35x of one in Safari 2026-11-23 09:01:43 +00:00
Pooya Parsa
74e8c88957 guest, kernel: let terminal sessions renice their audio threads, and have kwsnd report a period only when one ends
kwtty's sessions get RLIMIT_NICE 40, as pam_limits gives a desktop's audio users: SDL asks for nice -20 for its audio thread, which at nice 0 shares the emulated CPU with the game's busy threads and misses its periods (ALSA underruns, gaps in the sound). kwsnd called snd_pcm_period_elapsed() on every tick, and the core takes a report that falls short of the next period more than half a buffer after the pointer last moved (the first tick after a stall of the machine) for a missed buffer and stops the stream; it now reports when the pointer crosses a period boundary or reaches appl_ptr (the end of a drain, an underrun), and works from its own position between reports.
2026-11-22 22:13:39 +00:00
Pooya Parsa
2abdc598e2 guest, kernel: boot faster and carry less in the base: /init looks for the data disk and the distro image on kwblk's disks only (wd*) and the kernel has no RAM disks (CONFIG_BLK_DEV_RAM off: probing brd's 16 took about 130 ms a boot); /init and rc read files with the shell instead of head; DHCP runs in the background (net background, net wait: the console's shell starts before the lease, kwtty serve and Debian's services with start links wait for it); the bundle stores the initrd uncompressed; wlandr moves from the base to the Debian image (wland says so where there is none); the checkout's CLI turns on Node's compile cache before it loads the SDK 2026-11-22 14:46:21 +00:00
Pooya Parsa
178298148d kernel, js: sync and drop file caches before a snapshot that stops the machine (SnapshotOptions.dropCaches, IRQ 11), and encode and restore a snapshot from its used chunks instead of scanning the machine's whole memory 2026-11-22 11:03:31 +00:00
Pooya Parsa
9f90e86085 kernel: backport virtio-gpu's damage clips for rendered resources; guest: X draws its own pointer on the DRM device (SWcursor in kw-kms.conf), and the Debian README names kmscube and X with glamor 2026-11-21 23:29:44 +00:00
Pooya Parsa
31bff45e60 kernel: place the virtio-gpu capset wait with the generic patches 2026-11-21 22:58:24 +00:00
Pooya Parsa
84d70b9b83 gl: load the renderer on the guest's first GL use (the device advertises virgl's capsets from fixed sizes; gl.eager, ?glload=eager load before boot) and turn guest GL on by default for Debian in the page, with the virtio-gpu device (?gpu=0: the vtest link only); the kw layer ships /etc/X11/kw-kms.conf (modesetting with glamor on /dev/dri/card0) and sets the vtest variables only without the device; virtio-gpu waits up to 30 s, killably, for a capset; a suspend while a program uses the GPU is refused at once with a message 2026-11-21 22:57:45 +00:00
Pooya Parsa
4d20370925 Give the guest /dev/dri: kwvirtio, a virtio transport over host imports, with the stock virtio_gpu driver (createKernel({ gpu }), --gpu); the SDK's device model shows dumb-buffer scanouts on the host display and, with gl, runs virgl 3D on the page's renderer through virglrenderer's API (patch 13), presents a KMS scanout from the renderer's texture without readback and gives host code a resource's texture (vm.gl.gpu.texture); the kernel leaves out I2C, the HDMI infoframe library, the panel bridge and NET_DEVMEM (four generic switches) and backports the virtio-gpu damage-clip fix 2026-11-21 20:27:49 +00:00
Pooya Parsa
8282a0665c kwemu: a 128K-op tenured ring beside the 320K-op nursery (KW_CPU_SIZE 9 MiB, ABI 3), which holds the compiled code of one run of a Bun-based program so that the next run reuses it; record the 2026-11-20 profiling findings in the agent docs and drop what they contradict 2026-11-21 10:21:45 +00:00
Pooya Parsa
bcf1782092 Name the file and offset of each profile sample, so that the same code adds up across processes, and symbolize sites from a copy of the guest root (--profile-root, symbolizeProfile) 2026-11-20 18:02:53 +00:00
Pooya Parsa
ccf57e51a9 Add a guest pc sampling profiler driven from the host: time samples through a profile IRQ bit set by a sampler thread (SMP kernel) and instruction samples through the budget, per-CPU rings in the kernel, the tier and the block before each stop from kwemu, and --profile in the CLI 2026-11-20 16:38:47 +00:00
Pooya Parsa
a30598df0c Park, snapshot and resume the SMP kernel: a rendezvous of every CPU at the consistent point, a restore that starts the other CPUs again and restarts each idle task, the CPU count in the snapshot, and Suspend on the page with several CPUs 2026-11-20 08:27:54 +00:00
Pooya Parsa
6065c4397c kernel: allow 16 CPUs on the SMP kernel
kw_smp.config sets NR_CPUS to 16 (the wasm SMP patch). A boot on fewer CPUs costs only a few KiB of static per-CPU arrays: the possible CPUs are the ones the host offers. kwtest's spread check starts two threads per CPU up to 32, so it covers more than 8 CPUs.
2026-11-19 16:36:29 +00:00
Pooya Parsa
21ef47685a kernel: enable erofs with zstd for the distro images 2026-11-19 14:46:13 +00:00
Pooya Parsa
a1acf312e0 Remove the riscv64 CPU, reset the kwemu ABI to 2
The riscv64 interpreter, its JIT emitter, test guests and drivers are
gone; kwemu keeps the ISA-neutral core (MMU, TLBs, code marking, block
cache, JIT core) and the A64 CPU. The arm64 user ABI is one kernel
patch, the last of the series, and the contract between the kernel and
kwemu starts again at KW_ABI_VERSION 2.
2026-11-19 00:12:39 +00:00
Pooya Parsa
3414200e47 a64: translate AdvSIMD, AES, PMULL and SHA with wasm SIMD
With a host that compiles wasm SIMD (a JIT host capability; the scalar
form remains as the fallback), V registers live in v128 locals and the
integer AdvSIMD ops, AES rounds, PMULL and the SHA families are
translated inline. The image's libcrypto picks its code paths from
HWCAP again, and SHA512 is advertised by default.
2026-11-19 00:12:38 +00:00
Pooya Parsa
1153cea626 a64: LSE atomics, SHA-512 and SHA-3
FEAT_LSE, FEAT_SHA512 and FEAT_SHA3 in the interpreter and the tier,
with their HWCAP bits and ID register fields in the kernel and checks in
kwtest.
2026-11-19 00:12:38 +00:00
Pooya Parsa
e43aaddca2 a64: run user code through a decoded-op tier
The decoded-block cache is generic over an ISA's block hooks. A64 code
is decoded once into ops (one instruction, one op) that runOps executes,
with coherence on SMP through a shared code epoch. The tier is tested
against the reference interpreter.
2026-11-19 00:12:38 +00:00
Pooya Parsa
783c48c76e Switch the guest CPU to AArch64
User space is now unmodified aarch64 Linux ELF. kwemu gets an A64
interpreter (src/a64): integer, scalar and vector floating point,
AdvSIMD, exclusives and load-acquire/store-release, the EL0 system
registers, AES, PMULL, SHA1, SHA256 and CRC32. The kernel runs arm64
user space (signal frames, HWCAP, ptrace regsets, the arm64 syscall ABI),
and the guest image, the bundle, kwtest and the page's texts are built
for aarch64.
2026-11-19 00:12:38 +00:00
Pooya Parsa
2b5e5a94d0 kernel: add policy routing, veth and dummy links
IP_ADVANCED_ROUTER with IP_MULTIPLE_TABLES gives ip rule and more than one routing table, so tailscaled uses its table 52 instead of falling back to the main table. VETH links network namespaces, DUMMY gives a throwaway interface. Together +64 KB raw, +24 KB gzip and 20 KiB of RAM. kwtest tries all three in a network namespace of its own.
2026-11-17 17:59:04 +00:00
Pooya Parsa
6dbf712c11 kernel: clear a parked CPU 0's pending word before it waits (SMP)
A CPU 0 stopped by another CPU parks in wasm_idle(-1), but its host's
idle wait ends at once while CPU 0's word of pending interrupts is not
0. The stop bit stayed there (taken in cpu_relax(), or raised again by a
CPU whose session ended), so CPU 0 was resumed in a loop of microtasks
that starved its host's event loop, and the exit from the other CPU was
never taken. Inline SMP kernels hung that way in pnpm test:api on 2 CPUs
(3 of 13 runs) once exec started new images on the other CPU, where
poweroff then stopped CPU 0. kw_ipi_stop() now clears the word before
each wait (folded into "wasm: SMP"; the later patches change only in
their hashes).
2026-11-17 17:46:42 +00:00
Pooya Parsa
0e4b2ecb4d Move held tasks to a better CPU at exec and when they wake on a busy CPU (SMP) 2026-11-17 15:52:46 +00:00
Pooya Parsa
1662c969f3 Let TLB flushes skip a CPU that compiles JIT code or yields to its host
On SMP a CPU inside a JIT compile (kwemu's gathering and emitting, the
host's new Module and Instance, V8's first-call compile) or inside its
20 ms yield to the host took no interrupt for 0.1 ms to tens of ms, and
every TLB shootdown to it waited that long.

kwemu (ABI 8) marks a compile with jit_busy in struct kw_cpu and does a
flush another CPU asked for through flush_all when it ends, then looks
the block up again; a compile waits while an interrupt is pending. Every
module returns at once for cpu = 0, and the host calls it so inside
kw_host_jit_compile (new flags argument), so V8's lazy compile falls in
the window. The kernel (patch 0037) skips compiling and yielding CPUs as
it skips lazy ones, and yields after taking pending interrupts. The JIT
host no longer nudges the collector on a free.

kwipi churn on 2 CPUs: shootdown p99.9 130 to 13 us, max 20 to 3.9 ms,
calls over 1 ms 194 to 3; throughput and compile counts unchanged
(kwemu.md, Numbers, Compile stalls).
2026-11-17 15:51:42 +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
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
26d08730cc Initial commit 2026-11-15 23:27:04 +00:00