Microphone: kwsnd gains a capture substream fed by the host (SDK option
soundIn, the page's Microphone setting and ?mic=0, the CLI's
--sound-in-wav and --sound-in).
Camera: kwcam is a V4L2 capture device (/dev/video0) fed by the host: I420,
NV12 and YUYV at 320x240 to 1280x720, and H.264 encoded by the host's
WebCodecs encoder where it has one, with bitrate, GOP and key frame
controls (SDK option camera, the page's Camera setting and ?cam=0, the
CLI's --camera). The base's rc writes the udev database entry of
/dev/video*, so programs that list cameras through libudev find it.
kwva (protocol 5): an encode whose input surface is a camera buffer's
dma-buf names the frame to the host instead of sending its pixels, and
pixels an app writes into an exported surface reach the host (put).
On the SMP kernel a workqueue worker in the middle of an item could wait
for kernel threads that had already parked, never reach its own park
point, and end the cycle with -EBUSY naming it. A netns teardown's
cleanup_net() does that: it waits for grace periods, the expedited
grace-period worker and other work items. A cycle started right after an
`unshare -n` exit failed 13 times in 15 on 2 CPUs and 12 in 15 on 4; beside
a loop of netns teardowns 22 of 30 and 20 of 30 failed. Docker's
containers (#59) make such teardowns routine in Debian guests.
- The TREE_RCU grace-period kthread parks only while no grace period is
in progress or requested, so that a kernel thread in synchronize_rcu()
or rcu_barrier() can reach its park point (a fixup of the park points
patch).
- Between the user and the kernel-thread phases kwparkd waits, at most
HZ/2, until every workqueue worker is idle (in TASK_IDLE), while every
kernel thread still runs (kw_park_settle_work(), a fixup of the arch
patch).
With both, every cycle of those runs passed (120 on 2 and 4 CPUs). An idle
cycle's median went from 17.9 ms to 0.3 ms on 2 CPUs; a cycle that waits
for a teardown takes 60-230 ms. kwtest's park check is unchanged (2-5 ms
mean). parking.md describes the settle step and the grace-period rule.
Based on Martin Brook's patches on the android branch of
martinbrook/unkernel (cc78ca9, 4849ed9). His settle step also ran
rcu_barrier() and waited only for workers in an uninterruptible sleep:
here the barrier cost 40-50 ms in every cycle, and a worker between two
waits (runnable) ended the wait early, so 11 of 15 cycles still failed.
Co-authored-by: Pooya Parsa <pooya@pi0.io>
Co-authored-by: Martin Brook <martin.brook100@googlemail.com>
get_user() and put_user() of an aligned 1, 2, 4 or 8 bytes are now one
load or store through kw_user_addr() instead of a memcpy (memory.copy,
which the Wasm spec does not make single-copy atomic on a shared
memory), so a futex word read beside another CPU's stores cannot tear;
an unaligned access still goes through raw_copy_*_user().
kwfb's set_par checks the mappings, allocates and switches the buffer
under info->mm_lock, which fbdev's mmap holds (check_var reads the count
under it too): an mmap racing FBIOPUT_VSCREENINFO from another thread
could map the old buffer.
kwtest checks both (uaccess: FUTEX_WAIT and getcpu beside another CPU's
stores, fault-in, EFAULT and a put_user across a page; kwfb: 200 mmaps
beside a thread changing the mode), and `kwtest smp` runs the kwfb
checks. Ported from VOD-Studio/unkernel@25e90b3f.
Co-authored-by: Pooya Parsa <pooya@pi0.io>
Co-authored-by: xfy <i@rua.plus>
* Enable Docker IPv4 bridge networking in Debian guests
* kernel: leave out the netfilter and bridge defaults Docker does not use
NETFILTER_INGRESS and NETFILTER_EGRESS (hooks for nft's netdev family,
which is not built), NF_CT_PROTO_SCTP and BRIDGE_IGMP_SNOOPING come on
by default with the options the Docker bridge needs; turning them off
saves 78,289 bytes of vmlinux32.wasm (25,917 bytes gzip). Re-export the
series: 0049, 0052 and 0055 carried index lines for the old
kw_defconfig.
* kernel: fix the conntrack hash size at 1024 buckets
Built-in conntrack allocates its hash table and the NAT bysource table,
which takes the same size, at boot also without rules, sized from RAM:
512 KiB each above 1 GiB, as on the page's 2 GiB default. A new generic
patch adds NF_CONNTRACK_HASHSIZE; kw_defconfig sets it to 1024, 8 KiB
per table, with nf_conntrack_max 8192. A 2 GiB guest keeps about 940 KiB
more free after boot.
---------
Co-authored-by: Pooya Parsa <pooya@pi0.io>
Fold the 56 kernel patches into 32: one arch patch (which now includes
the riscv ISA patch, parking, atomics, SMP, blocking waits, unfair
spinlocks, the arm64 user ABI, pc sampling, ptrace, single-step and core
dumps), each driver with its SMP part, the generic changes one per piece
(the cond_resched() poll split out of the arch patch), and kw_defconfig
last. The messages describe the code as it is; every patch that was
kernel-wasm@localhost's is Pooya Parsa's. The tree is unchanged.
kernel/build.sh patches (kernel/tools/export-patches.sh) exports the
series without what changed in every later patch on each edit: no
numbers in the file names (the order is the new series file, which
build.sh applies), a zero commit hash, no git version signature and no
index lines, with the diff options fixed.
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>
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.
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.
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.
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.
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.
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.
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.
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.
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.
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).
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).
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`.
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.
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.
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.
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/).