From 0e1cd96b775698f102dc4bbfe932b1b8539fc858 Mon Sep 17 00:00:00 2001 From: Pooya Parsa Date: Tue, 17 Nov 2026 13:23:55 +0000 Subject: [PATCH] Build the SMP kernel and the bundle's SMP patch with kernel/build.sh kernel/build.sh smp builds the SMP kernel (kw_defconfig + kw_smp.config, kwemu with atomics) from the same tree into vendor/build/kernel-smp; all builds both kernels, and every bundle refresh adds the UP-to-SMP patch when the SMP kernel is the same build of the tree (KW_SMP=1 requires it, KW_SMP=0 leaves it out). kernel stays the UP-only quick loop. The patch is cached in kernel-smp/up.kwpatch. Fixed build stamps (user, host, a build id hashed from the tree and kwemu sources, the tree's newest commit date) make kernels and patch reproducible while every other build keeps its own banner for snapshot matching. Configs are checked against their fragments after a reconfigure. KW_BUILD, KOUT_SMP, KWEMU_SMP and LINUX_REPO make the script runnable against another tree and output root. bundle.mjs --smp refuses two kernels that are not the UP and SMP builds of one tree (banner, KW_ABI_VERSION, wasm_cpu_start, memory type), with --smp-optional to warn instead and --smp-patch to reuse a cached patch. The release workflow builds both kernels, runs kwtest on 2 CPUs and the kernel patch tests (unexercised). --- .agents/js.md | 16 +- .agents/kernel.md | 65 +++++++- .agents/status.md | 14 +- .agents/testing.md | 34 ++-- .agents/web.md | 11 +- .github/workflows/release.yml | 42 ++++- AGENTS.md | 15 +- kernel/README.md | 47 ++++-- kernel/build.sh | 302 ++++++++++++++++++++++++++-------- kernel/guest/alpine-disk.sh | 2 +- kernel/guest/alpine.sh | 4 +- kernel/guest/ubuntu-disk.sh | 2 +- kernel/tools/bundle.mjs | 153 +++++++++++++++-- kernel/tools/env.sh | 4 + package.json | 1 + setup.sh | 7 +- test/kpatch.test.ts | 68 ++++++++ 17 files changed, 643 insertions(+), 144 deletions(-) diff --git a/.agents/js.md b/.agents/js.md index 6f81deb..d776fe2 100644 --- a/.agents/js.md +++ b/.agents/js.md @@ -440,7 +440,9 @@ parts that are easy to get wrong. `wasm_host_irqs` (`Kernel.watchIrqWord`), which another CPU's `memory.atomic.notify` (an IPI) ends; the wait's `done` runs once. - Both kernels in one bundle: a bundle made with `kernel/tools/bundle.mjs - --smp ` (same tree) carries + --smp ` (same tree; `kernel/build.sh` passes it once + the SMP kernel is built, and bundle.mjs refuses kernels of two different + builds: kernel.md, Two kernels) carries `unkernel.kernel.smp.kwpatch` last, a patch from its UP kernel to the SMP one (`kernel/tools/kwdiff.mjs --remap`: the base's function, global and type indices and data addresses renumbered to the target's by @@ -453,9 +455,15 @@ parts that are easy to get wrong. compiles the SMP kernel followed by the bundle's other `unkernel.*` sections, so `bundledBoot()` reads it as the bundle. Without the section, with one CPU, or with a compiled Module as `kernel`, nothing - changes. `withoutSmpPatch()` gives the bundle without the section (the - page's split, web.md). `test/kpatch.test.ts` (with `KPATCH_UP` and - `KPATCH_SMP` set, also on the real kernels). + changes. A patch that does not fit the bundle's kernel (another length, + another SHA-256, or a result whose SHA-256 is wrong) is an error, never a + wrong kernel: `loadKernelModule()` rejects with a `BootError` at the + `compile` stage ("Deriving the SMP kernel from the bundle failed: ..."), + and the CLI says it cannot load the kernel and exits 1. + `withoutSmpPatch()` gives the bundle without the section (the page's + split, web.md). `pnpm test:kpatch` (`test/kpatch.test.ts`; with + `KPATCH_UP` and `KPATCH_SMP` set, also on the real kernels and + bundle.mjs's checks). - Browsers (`js/web/cpu.ts`, `web-cpu-entry.ts`; `webPlatform` and the web kernel worker pass `spawnWebCpu` and `webCpuBlocker`): each CPU is a module Web Worker (`unkernel-cpu`) running the same `runCpu()`, diff --git a/.agents/kernel.md b/.agents/kernel.md index 895e4e6..a675fb9 100644 --- a/.agents/kernel.md +++ b/.agents/kernel.md @@ -569,9 +569,8 @@ third-party implementation. A second build of the same tree: `make kw_defconfig kw_smp.config` (SMP, `NR_CPUS` 8), which also links with `--shared-memory` (arch Makefile), with kwemu built by `zig build -Dkwemu-jit=true -Dkwemu-atomics=true`. -The build script has no target for it yet: run make by hand into a -`KOUT` of its own with the script's make variables and `KWEMU=` that -kwemu, then lower it as `lower` does. The UP build does not change +`kernel/build.sh smp` does that into `vendor/build/kernel-smp` (Two +kernels, below). The UP build does not change (every SMP piece is `#ifdef CONFIG_SMP` or compiles away). Status, numbers and open issues: status.md item 8. @@ -922,6 +921,66 @@ and the reference (`--kernel vendor/build/kernel/vmlinux`). `lower` is required: build.sh fetches Binaryen 133 if it finds no `wasm-opt` with `--table64-lowering`. +## Two kernels: UP and SMP + +One tree, two configs, two output directories: `kernel/build.sh kernel` +builds the UP kernel into `vendor/build/kernel` (`KOUT`), `smp` the SMP +kernel into `vendor/build/kernel-smp` (`KOUT_SMP`) with kwemu built with +atomics in `vendor/build/kwemu-smp` (`KWEMU_SMP=` takes a prebuilt one); +each is lowered, and `all` builds both (`KW_SMP=0`: UP only). `kernel` +stays the quick loop and never builds SMP. A step reconfigures when a +fragment (`kw_defconfig`, `kw_smp.config`) is newer than `.config` and +then checks that every option the fragments set is in `.config` as +written, failing with the list otherwise (Kconfig drops options whose +dependencies are not met silently; both configs pass as of 2026-11-17). + +- **The bundle** (`bundle_alpine`, `kernel/tools/bundle.mjs --smp`) + carries the UP kernel and a patch to the SMP kernel (js.md, CPU + threads). bundle.mjs refuses two kernels that are not the UP and SMP + builds of one tree: their banners must differ only in `SMP` (with the + stamps below that means the same tree, kwemu sources and toolchain), + kwemu's `kw_abi_version()` must return the same constant, only the SMP + one may import `wasm_cpu_start`, and both must have the same memory + index type. Every step that refreshes the bundle (`kernel`, `smp`, + `lower`, `alpine`, `datadisk`, `bundle`) adds the patch when the SMP + kernel exists and matches, and otherwise warns and leaves it out + (`--smp-optional`), so after a tree change `kernel` gives a bundle + without the patch until `smp` runs. `KW_SMP=1` (and `all`) makes a + missing or mismatched SMP kernel an error; `KW_SMP=0` leaves the patch + out. Making the patch takes about 15 s, so it is cached in + `vendor/build/kernel-smp/up.kwpatch` (`--smp-patch`: reused when its + header's SHA-256s are those of the two kernels, else made again). +- **Build stamps.** Kernels are reproducible: the same tree, kwemu + sources and toolchain give the same bytes, and so the same patch + (2026-11-17: two clean builds of each kernel into different output + roots, and the bundles made from them, were byte-identical; with the + stamps of a hand build the UP and SMP kernels were byte-identical to + it). `kernel_stamps` exports `KBUILD_BUILD_USER` and `_HOST` + (`unkernel`), `_VERSION` (the build id: 12 hex digits of a hash of the + kernel tree's HEAD tree, its uncommitted and untracked changes, the + repository's `src`, `include`, `build.zig*`, `kernel/patches/llvm` + and `kernel/tools/fake-llvm`, the zig version and the JIT and stats + options) and `_TIMESTAMP` (the newest author date on the tree, which a + fresh `git am` of the series reproduces), unless the environment sets + them. The banner then reads `Linux version 7.3.4+ (unkernel@unkernel) + (clang ..., LLD ...) # [SMP] `. The build id matters beyond + pairing: a snapshot is matched to its kernel by `linux_banner` + (Parking), so every build whose module may differ needs another + banner, and a fixed `#1` would let a snapshot restore into another + build of the same date. A different clang or wasm-ld changes the + banner through its compiler line. Libraries given as `KWEMU=` or + `KWEMU_SMP=` count as built from the checkout's sources. +- **Overrides**: `KSRC` (the tree), `KOUT`, `KOUT_SMP`, and `KW_BUILD` + (the output root, default `vendor/build`: kernels, kwemu-smp and + kwemu-stats, initramfs, disks, bundle; the toolchain's + `vendor/build/lld22` and alpine-opt.sh's package cache stay). The CLI, + `pnpm build` and the tests read `vendor/build`, so pass them paths. + `LINUX_REPO` names where a fresh tree fetches the base commit from. +- On a fresh clone `prepare_kernel_tree` applies the whole series (UP and + SMP patches alike) as `kw-riscv-user`; it warns when the checked-out + HEAD of `KSRC` has another number of commits than the series has + patches. + ## Kernel tests - kwtest (`kernel/guest/kwtest.c`, `/usr/bin/kwtest` in local builds and diff --git a/.agents/status.md b/.agents/status.md index f128f5f..e22d414 100644 --- a/.agents/status.md +++ b/.agents/status.md @@ -384,15 +384,11 @@ qemu's TCG keeps writing new code, which kwemu interprets or recompiles. by hand on a deployed build in desktop Chrome, Firefox and on iOS. Not tried: desktop Safari, Android, 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, whose CPUs option - stays disabled) still ships UP only; - the README there has the proposal. + only once a release bundle carries the SMP patch (the next release: + `kernel/build.sh` builds both kernels and the bundle with the patch, + kernel.md, Two kernels, and the release workflow runs it). That + workflow's SMP steps are unexercised (testing.md, Release workflow, + says what they still need). - Deferred fork and wakeup changes, measured 2026-11-16 (kwfork, 9 alternating rounds; patches and a README with their base in `vendor/smp-deferred/`, which is gitignored like all of vendor): diff --git a/.agents/testing.md b/.agents/testing.md index 3fe999c..77edef0 100644 --- a/.agents/testing.md +++ b/.agents/testing.md @@ -7,7 +7,8 @@ are run only when asked; the page is tested by hand with `pnpm dev`. | Change | Run | | --- | --- | | Emulator (`src/`, `guest/`, `include/`) | `zig build test`, then the kernel row | -| Kernel or `kw_emu.h` | `kernel/build.sh kernel`; `node js/cli.ts --append "console=hvc0 rdinit=/usr/bin/kwtest"`, the same with `--kernel vendor/build/kernel/vmlinux`, and both again with `--no-jit` (expect `kwtest: 0 failure(s)`, exit 0); `node test/wasi-node.ts` (`PASS`) | +| Kernel or `kw_emu.h` | `kernel/build.sh kernel` and `kernel/build.sh smp`; `node js/cli.ts --append "console=hvc0 rdinit=/usr/bin/kwtest"`, the same with `--kernel vendor/build/kernel/vmlinux`, and both again with `--no-jit` (expect `kwtest: 0 failure(s)`, exit 0); the SMP kernel as below the table; `node test/wasi-node.ts` (`PASS`) | +| Bundle, kernel patch, `build.sh` | `KPATCH_UP=vendor/build/kernel/vmlinux32.wasm KPATCH_SMP=vendor/build/kernel-smp/vmlinux32.wasm pnpm test:kpatch`; after a change to the stamps or the build, two clean builds into different `KW_BUILD` roots give the same `vmlinux32.wasm` files and bundle (`sha256sum`) | | JIT (`src/emu/jit.zig`, `js/core/jit.ts`) | the two rows above; `zig build test -Dkwemu-fp-fuzz=1000000` after FP changes; `zig build fuzz -- 20000` after control-flow changes; Alpine with real work under JIT and `--no-jit`, comparing outputs (`seq 30000 \| sort -rn \| md5sum`, `tar cf - /lib \| gzip \| md5sum`, `sha256sum`); `node --expose-gc --test test/api.test.ts` | | Anything a real userland sees | `node js/cli.ts --timeout 120 --input '{8}uname -a; apk --version\n{2}poweroff\n'` | | Block, ext4, disk script | `node js/cli.ts --disk vendor/build/disk/alpine.ext4 --snapshot --timeout 120 --input '{6}df -h /\n{2}poweroff\n'` (`/dev/root` mounted, `kw-shutdown: / is clean`) | @@ -27,10 +28,12 @@ dumped frame pixel for pixel, the injected input events and the recorded test signal sample for sample (`--no-sound`: without a sound card; `--worker`: the same through the CLI's `--worker`, with input and frames in shared memory; run it also with `--worker=messages` after a worker-mode change). -An SMP kernel (kernel.md, SMP) runs the same checks: kwtest with `--smp -2` and `--smp 4` (add `--display --shm` for its kwfb and kwshm checks), -`UNKERNEL_TEST_KERNEL= UNKERNEL_TEST_CPUS=2 node --test -test/api.test.ts` (the snapshot tests skip), and `node +The SMP kernel (kernel.md, SMP; `kernel/build.sh smp` puts it in the +bundle) runs the same checks: kwtest with `--smp 2`, `--smp 4` and +`--smp 2 --no-jit` (add `--display --shm` for its kwfb and kwshm checks) +and once on one CPU (`--kernel vendor/build/kernel-smp/vmlinux32.wasm +--initrd alpine-test`), `UNKERNEL_TEST_CPUS=2 pnpm test:api` (the +snapshot tests skip), and `node test/glimmer-check.mjs --run --kernel --initrd --smp 2`. Emulator guests print `name: N checks, 0 failures`. @@ -48,11 +51,15 @@ date, UTC), which it tags `v` once the build passes. Its other ref before building, and stamps the version into package.json before `pnpm build`. It builds everything from source with `KW_RELEASE=1`, so `alpine.sh` leaves kwtest and kwbench out of `alpine.cpio` and the bundle -(`kernel/build.sh toolchain kernel alpine datadisk`, clang 22 from -apt.llvm.org; kwemu with `zig build -Dcpu=baseline` handed over as -`KWEMU=`, so the zig cache survives runners with other CPU models), runs +(`kernel/build.sh toolchain kernel smp alpine datadisk`, the last two +with `KW_SMP=1`, so the bundle must carry the SMP patch; clang 22 from +apt.llvm.org; both kwemu libraries with `zig build -Dcpu=baseline` +handed over as `KWEMU=` and `KWEMU_SMP=`, so the zig cache survives +runners with other CPU models), runs kwtest with and without the JIT (the bundle's kernel with `--initrd -alpine-test`), `pnpm typecheck`, the tty, http and 9p +alpine-test`) and on 2 CPUs (the SMP kernel from the bundle; a hosted +runner has 4 vCPUs, so not more), `pnpm typecheck`, `pnpm test:kpatch` +on the two kernels, the tty, http and 9p tests, `pnpm build`, kwtest (the same way) and the api tests on the built package, then uploads `npm pack`'s tarball (`unkernel.tgz`) and the bundle. A release publishes the tarball to npm through trusted publishing (npmjs.com trusts @@ -61,4 +68,11 @@ publishes the tarball to npm through trusted publishing (npmjs.com trusts publishes a GitHub release with both files attached (a normal release, marked latest). CI runs Node 26; package.json's engines stay at >= 24. The workflow's header lists the caches. The kernel tree is restored only by an exact -patch-series key, and the kernel build only for that same tree. +patch-series key, and the kernel builds (UP and SMP, one cache) only for +that same tree. +The SMP steps are unexercised (not run in CI as of 2026-11-17; the YAML +parses, and the kernels, bundle and tests they make were checked +locally). Still to do there: a first run, its time (a second kernel build on a cache miss, about +as long as the first: 1.5 min each at `-j8` locally), whether kwtest's +timing checks (`move:`) hold on a 4-vCPU runner, kwtest without the JIT +on 2 CPUs, and the api tests with `UNKERNEL_TEST_CPUS=2`. diff --git a/.agents/web.md b/.agents/web.md index 3f64726..789bc72 100644 --- a/.agents/web.md +++ b/.agents/web.md @@ -51,7 +51,8 @@ the dev server's own responses) and `__KW_BUILD__`. (`web/scripts/kernel.ts`) makes it from `web/kernel/unkernel-alpine.wasm` (the file the rest of this list is about) without its SMP patch section (js.md, CPU threads), so it is byte for byte that file when there is - none, as in every release so far. When there is one, it also writes + none, as in every release so far (the release workflow builds bundles + with it from the next release on; testing.md). When there is one, it also writes `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, @@ -59,8 +60,12 @@ the dev server's own responses) and `__KW_BUILD__`. 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`) - copies its output there, so the dev server runs your latest local build. + `kernel/build.sh bundle` (and so `kernel`, `smp`, `alpine`, `datadisk`, + `all`) copies its output there, so the dev server runs your latest local + build, with the SMP bundle once `smp` has built the SMP kernel. + Checked 2026-11-17 with `KW_KERNEL=` a bundle from the build path: the + built page had both assets (UP 11.48 MB, SMP 11.88 MB); with the newest + release (no patch) it had only the UP asset, with the deployed name. Only when there is no file does it download one. - A page build (`pnpm build:web`, a deploy, the browser tests' build) always takes the `unkernel-alpine.wasm` attached to the newest non-draft release diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 1b1f79a..8fbe639 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -26,9 +26,9 @@ # toolchain the patched wasm-ld (~1 h to build on a 2-core runner); # key: LLVM commit, kernel/patches/llvm # linux-src the patched kernel tree; key: base commit, kernel/patches/linux -# kernel-out the kernel build directory, reused only with the same tree -# (same patches, clang and fake-llvm wrapper), so Kbuild -# rebuilds incrementally and never from a different source +# kernel-out the UP and SMP kernel build directories, reused only with +# the same tree (same patches, clang and fake-llvm wrapper), so +# Kbuild rebuilds incrementally and never from a different source # downloads Alpine minirootfs and Binaryen (checksums are verified anyway) # alpine-opt the rebuilt busybox, zlib, openssl and apk-tools (installed # files only, ~9 MB; ~4 min to rebuild); key: alpine-opt.sh, @@ -214,25 +214,34 @@ jobs: id: kernel-out uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: - path: vendor/build/kernel + path: | + vendor/build/kernel + vendor/build/kernel-smp key: kernel-out-${{ steps.keys.outputs.clang }}-${{ hashFiles('kernel/patches/linux/**', 'kernel/tools/fake-llvm/**') }}-${{ hashFiles('src/**', 'include/**', 'build.zig', 'build.zig.zon', 'kernel/build.sh') }} restore-keys: kernel-out-${{ steps.keys.outputs.clang }}-${{ hashFiles('kernel/patches/linux/**', 'kernel/tools/fake-llvm/**') }}- - name: Drop a kernel build that does not match the tree if: steps.linux-src.outputs.cache-hit != 'true' - run: rm -rf vendor/build/kernel + run: rm -rf vendor/build/kernel vendor/build/kernel-smp # build.sh would run `zig build` itself, whose native artifacts (unused # here) target the runner's CPU, and hosted runners vary in CPU model, # which invalidates that part of the zig cache. Build for a baseline # CPU instead and hand build.sh the library. - name: Build kwemu - run: zig build -Dkwemu-jit=true -Dcpu=baseline + run: | + zig build -Dkwemu-jit=true -Dcpu=baseline + zig build -Dkwemu-jit=true -Dkwemu-atomics=true -Dcpu=baseline --prefix vendor/build/kwemu-smp - - name: Build the kernel + # Both kernels of the one tree: the bundle carries the UP kernel and a + # patch to the SMP one (kernel/build.sh, bundle.mjs --smp). + - name: Build the kernels env: KWEMU: ${{ github.workspace }}/zig-out/lib/libkwemu.a - run: kernel/build.sh kernel + KWEMU_SMP: ${{ github.workspace }}/vendor/build/kwemu-smp/lib/libkwemu.a + run: | + kernel/build.sh kernel + kernel/build.sh smp - name: Save the kernel tree if: steps.linux-src.outputs.cache-hit != 'true' @@ -244,7 +253,9 @@ jobs: if: steps.kernel-out.outputs.cache-hit != 'true' uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: - path: vendor/build/kernel + path: | + vendor/build/kernel + vendor/build/kernel-smp key: ${{ steps.kernel-out.outputs.cache-primary-key }} # busybox, zlib, openssl and apk-tools rebuilt for kwemu @@ -264,6 +275,8 @@ jobs: vendor/downloads/alpine-opt/*/APKBUILD key: alpine-opt-${{ runner.os }}-${{ hashFiles('kernel/guest/alpine-opt.sh', 'kernel/tools/env.sh') }} - name: Build the Alpine initramfs, data disk template and bundle + env: + KW_SMP: "1" # the bundle must carry the SMP patch run: | kernel/build.sh alpine kernel/build.sh datadisk # refreshes the bundle with the template @@ -305,8 +318,19 @@ jobs: --append "console=hvc0 rdinit=/usr/bin/kwtest" --smp 2` (and once without `--smp`); `zig build test -Dkwemu-atomics=true` after a kwemu change | +| SMP (`CONFIG_SMP`, `js/core/cpu.ts`; kernel.md, SMP), or any kernel change that SMP code sees | `kernel/build.sh smp` (after `kernel`, so that the bundle carries the patch); kwtest with `--smp 2` (the SMP kernel from the bundle) and once with `--kernel vendor/build/kernel-smp/vmlinux32.wasm --initrd alpine-test` (one CPU); `zig build test -Dkwemu-atomics=true` after a kwemu change | +| Bundle and kernel patch (`bundle.mjs`, `kwdiff.mjs`, `kpatch.ts`, `kremap.ts`) | `KPATCH_UP=vendor/build/kernel/vmlinux32.wasm KPATCH_SMP=vendor/build/kernel-smp/vmlinux32.wasm pnpm test:kpatch` | | Page (`web/`) | `pnpm typecheck:web`; `pnpm build:web` | The optional checks boot the same bundle as `pnpm test:api`, which already diff --git a/kernel/README.md b/kernel/README.md index a7b1900..501678c 100644 --- a/kernel/README.md +++ b/kernel/README.md @@ -20,7 +20,10 @@ repository root. Commands are run from the repository root. and `kernel/build.sh all`. By hand: ```sh -kernel/build.sh all # wasm-ld 22, Binaryen, kernel + vmlinux32.wasm, Alpine initramfs + bundle, disk +kernel/build.sh all # wasm-ld 22, Binaryen, UP and SMP kernels + vmlinux32.wasm, Alpine initramfs + bundle, disk +kernel/build.sh kernel # the UP kernel only (the quick loop), then the bundle +kernel/build.sh smp # the SMP kernel (vendor/build/kernel-smp), then the bundle with the SMP patch +node js/cli.ts --smp 2 --append "console=hvc0 rdinit=/usr/bin/kwtest" # kwtest on the SMP kernel from the bundle, 2 CPUs node js/cli.ts # Alpine (the bundle), interactive; Ctrl-] quits node js/cli.ts --append "console=hvc0 rdinit=/usr/bin/kwtest" # kwtest smoke test as /init (the bundle) node js/cli.ts --kernel vendor/build/kernel/vmlinux --append "console=hvc0 rdinit=/usr/bin/kwtest" # same tests on the wasm64 build @@ -47,8 +50,8 @@ node test/overlay-node.mjs # the overlay root under Node: persistence, kw.root ``` `build.sh` steps, each also available on its own (`toolchain`, `binaryen`, -`kernel`, `lower`, `alpine`, `disk`, `datadisk`, `bundle`; `ubuntu` is -separate and not part of `all`): +`kernel`, `smp`, `lower`, `alpine`, `disk`, `datadisk`, `bundle`; `ubuntu` +and `stats` are separate and not part of `all`): * **toolchain**: sparse-clones `llvmorg-22.1.8` (commit checked), applies `patches/llvm/`, and builds `wasm-ld` only. The patches are Joel's GNU-ld linker-script support @@ -67,7 +70,17 @@ separate and not part of `all`): takes a prebuilt library as is); with `KWEMU=none` a stub is linked instead. `include/kw_emu.h` is copied over the kernel's `arch/wasm/include/asm/kw_emu.h` (with a warning) if the two differ. It - then runs `lower`. + then runs `lower`. After a reconfigure it checks that `.config` has + every option `kw_defconfig` sets. The banner has fixed stamps, so two + builds of the same tree are identical: `(unkernel@unkernel)`, a build + id (`#` and 12 hex digits, a hash of the tree, the kwemu sources and + the toolchain inputs) and the date of the newest commit on the tree + (`.agents/kernel.md`, Two kernels). +* **smp**: the SMP kernel from the same tree (`kw_defconfig` plus + `arch/wasm/configs/kw_smp.config`, kwemu built with + `-Dkwemu-atomics=true` in `vendor/build/kwemu-smp`) into + `vendor/build/kernel-smp`, lowered like the UP one. `all` builds it + (`KW_SMP=0`: not); `kernel` never does. * **binaryen**: downloads the Binaryen release `version_133` (pinned checksum) into `vendor/toolchain/binaryen`. `lower` does this if no suitable `wasm-opt` is found. @@ -82,12 +95,17 @@ separate and not part of `all`): with `alpine.cpio` (gzipped), its command line and, if it exists, the data disk template in custom sections (`tools/bundle.mjs`; `unkernel.initrd`, `unkernel.cmdline`, `unkernel.datadisk`). There is no wasm64 bundle. - `tools/bundle.mjs --smp ` also adds - `unkernel.kernel.smp.kwpatch`, a patch from this kernel to an SMP build - of the same tree (`tools/kwdiff.mjs`), which the runtime applies when it - is asked for more than one CPU; build.sh does not pass it yet. - `kernel`, `lower`, `alpine` and `datadisk` refresh it when both inputs - exist; without a template it warns and bundles none. + With an SMP kernel built from the same tree it also has + `unkernel.kernel.smp.kwpatch` (`tools/bundle.mjs --smp`), a patch from + the UP kernel to the SMP one (`tools/kwdiff.mjs`, 1.3 MiB), which the + runtime applies when it is asked for more than one CPU. bundle.mjs + refuses an SMP kernel of another build (banners that differ in more + than `SMP`, another `KW_ABI_VERSION`); build.sh then warns and bundles + without the patch, or fails with `KW_SMP=1` (as in `all`). The patch + is cached in `vendor/build/kernel-smp/up.kwpatch` while both kernels + stay the same. `kernel`, `smp`, `lower`, `alpine` and `datadisk` + refresh the bundle when both inputs exist; without a template it warns + and bundles none. * **datadisk**: `vendor/build/disk/kwdata.kwsparse.gz`, the template of the data disk (see Block devices): an empty ext4 file system labelled `kwdata`, 4 GiB, 4 KiB blocks, made with `mke2fs -t ext4 -b 4096 -L @@ -147,8 +165,11 @@ removes the device, `--net-mtu N` sets the MTU handed out by DHCP, and `--net-wisp URL` sends the guest's TCP through a Wisp server instead of host sockets. -`build.sh` also takes `KSRC=dir` (a kernel git worktree) and `KOUT=dir` (its -build output), so a branch can be built without touching the main tree. +`build.sh` also takes `KSRC=dir` (a kernel git worktree), `KOUT=dir` and +`KOUT_SMP=dir` (the two kernels' build outputs) and `KW_BUILD=dir` (the +root of every build output, default `vendor/build`), so a branch can be +built without touching the main tree or its outputs; the header of +`build.sh` lists the rest (`KW_SMP`, `KWEMU`, `KWEMU_SMP`, ...). Downloads are pinned: the kernel base commit and the LLVM tag/commit in `build.sh`; Binaryen, Alpine and Ubuntu Base by SHA-256 (`build.sh`, @@ -1037,7 +1058,7 @@ switching, no block or net device, no JIT). loses at most the unflushed tail. An export or import of the data disk is 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 + `kernel/build.sh smp`, `.agents/kernel.md`, SMP) runs one kernel instance per 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 diff --git a/kernel/build.sh b/kernel/build.sh index d94756a..e0c8d7b 100755 --- a/kernel/build.sh +++ b/kernel/build.sh @@ -1,58 +1,100 @@ #!/usr/bin/env bash # SPDX-License-Identifier: GPL-2.0-or-later # Copyright (C) 2026 Pooya Parsa -# Build the unkernel kernel (wasm64 vmlinux with emulated riscv64 user mode), -# its 32-bit-memory variant (the one the page and the bundle use), the -# Alpine initramfs and disk images, and the single-file bundle; `ubuntu` -# builds the Ubuntu Base disk image (not part of `all`). +# Build the unkernel kernels (wasm64 vmlinux with emulated riscv64 user mode) +# and their 32-bit-memory variants (the ones the page and the bundle use): +# the UP kernel and the SMP kernel (CONFIG_SMP, one wasm instance per CPU on +# a shared memory) from the same tree; the Alpine initramfs and disk +# images, and the single-file bundle (the UP kernel, Alpine and a patch +# from the UP to the SMP kernel); `ubuntu` builds the Ubuntu Base disk +# image (not part of `all`). # ./setup.sh at the repository root checks the prerequisites and runs `all`. # -# kernel/build.sh [toolchain|binaryen|kernel|lower|alpine|disk|datadisk|bundle|ubuntu|stats|all] (default: all) +# kernel/build.sh [toolchain|binaryen|kernel|smp|lower|alpine|disk|datadisk|bundle|ubuntu|stats|all] (default: all) # # `all` is idempotent: finished steps are skipped or rebuilt incrementally, and # an existing vendor/build/disk/alpine.ext4 is kept (it may hold your changes; -# `kernel/build.sh disk` rebuilds it). +# `kernel/build.sh disk` rebuilds it). It builds both kernels (KW_SMP=0: the +# UP kernel only). +# +# `kernel` builds the UP kernel only (the quick loop for kernel work), `smp` +# the SMP kernel only (vendor/build/kernel-smp, with kwemu built with atomics +# in vendor/build/kwemu-smp); each refreshes the bundle. The bundle carries +# the patch to the SMP kernel when that kernel was built from the same tree +# as the UP one (the kernels' banners, kernel/tools/bundle.mjs --smp), and +# otherwise leaves it out with a warning (run `smp` after `kernel`). # # `stats` builds a profiling variant next to the normal outputs, which it # leaves alone: kwemu with -Dkwemu-stats (exit counters, the kw_debug_stats -# export) in vendor/build/kwemu-stats, the kernel in vendor/build/kernel-stats -# (the first run is a full kernel build) and the bundle -# vendor/build/bundle/unkernel-alpine-stats.wasm. Boot it with -# `node js/cli.ts --kernel vendor/build/bundle/unkernel-alpine-stats.wasm --stats`. +# export) in vendor/build/kwemu-stats, the UP kernel in +# vendor/build/kernel-stats (the first run is a full kernel build) and the +# bundle vendor/build/bundle/unkernel-alpine-stats.wasm (no SMP patch). Boot +# it with `node js/cli.ts --kernel vendor/build/bundle/unkernel-alpine-stats.wasm --stats`. +# +# Kernels are reproducible: two builds of the same tree with the same +# toolchain are byte for byte the same (so is the bundle's SMP patch). The +# banner (linux_banner, `uname -v`) has fixed stamps instead of the user, +# host, build count and time: (unkernel@unkernel), the build id as the build +# "number" (#<12 hex digits>: a hash of the kernel tree with its uncommitted +# changes, the kwemu sources, the wasm-ld patches and the zig version, so +# every other build of the kernel module has another banner, which is what a +# snapshot is matched against), and the date of the newest commit (author +# date) on the kernel tree. KBUILD_BUILD_USER, _HOST, _VERSION and +# _TIMESTAMP in the environment take precedence. # # Everything large lives under vendor/ (gitignored): # vendor/src/llvm22 llvm-project llvmorg-22.1.8 (sparse: llvm, lld) # vendor/build/lld22 wasm-ld with kernel/patches/llvm applied # vendor/src/linux-wasm-kernel Linux at $LINUX_BASE (kernel.org) + kernel/patches/linux # (branch kw-riscv-user) -# vendor/build/kernel kernel build output (vmlinux = the wasm64 module, +# vendor/build/kernel UP kernel build output (vmlinux = the wasm64 module, # vmlinux32.wasm = the same lowered to a 32-bit memory/table, # the default for the browser page) +# vendor/build/kernel-smp SMP kernel build output (kw_defconfig + kw_smp.config), +# and up.kwpatch, the UP->SMP patch the last bundle used +# vendor/build/kwemu-smp kwemu built with atomics, for the SMP kernel # vendor/toolchain/binaryen Binaryen release (wasm-opt), fetched by `binaryen` # vendor/build/disk/alpine.ext4 Alpine root file system image for kwblk (`disk`) # vendor/build/disk/kwdata.kwsparse.gz empty ext4 "kwdata" data disk template (`datadisk`) # vendor/build/disk/ubuntu.ext4 Ubuntu Base 24.04 root file system image (`ubuntu`) # vendor/build/initramfs/ alpine.cpio (also holds /usr/bin/kwtest and kwbench) # vendor/build/bundle/ unkernel-alpine.wasm (vmlinux32.wasm + alpine.cpio + cmdline -# + the data disk template in custom sections); the default of -# the CLI (js/cli.ts) and the SDK, and copied to web/kernel/ -# for the page's dev server; unkernel-alpine-stats.wasm from `stats` +# + the data disk template + the SMP patch in custom sections); +# the default of the CLI (js/cli.ts) and the SDK, and copied to +# web/kernel/ for the page's dev server; +# unkernel-alpine-stats.wasm from `stats` # # Environment: -# KWEMU=path wasm64 kwemu static library (default: zig-out/lib/libkwemu.a, -# rebuilt with `zig build` on every run; set KWEMU=none for the stub) -# KWEMU_JIT=0 build that library without the JIT tier (default 1: -Dkwemu-jit=true, +# KW_BUILD=dir build output root instead of vendor/build (every output above but +# the toolchain's vendor/build/lld22; alpine-opt.sh's package rebuild +# also stays in vendor/build/alpine-opt, a cache that its stamp keys), +# e.g. with KSRC to build a branch without touching the main outputs. +# The CLI, the SDK build and the tests read vendor/build: give them +# paths (--kernel, --initrd, UNKERNEL_TEST_KERNEL, KW_KERNEL) +# KW_SMP=1|0 1: the bundle must carry the SMP patch (fail otherwise); 0: no SMP +# kernel in `all` and no patch in the bundle. Default: `all` builds +# both and requires it, every other step adds it when it matches +# KWEMU=path wasm64 kwemu static library for the UP kernel (default: +# zig-out/lib/libkwemu.a, rebuilt with `zig build` on every run; +# set KWEMU=none for the stub) +# KWEMU_SMP=path the same for the SMP kernel, built with -Dkwemu-atomics=true +# (default: vendor/build/kwemu-smp/lib/libkwemu.a, rebuilt on every run). +# Libraries given here count as built from this checkout with the +# default options (the build id hashes the sources, not the library) +# KWEMU_JIT=0 build those libraries without the JIT tier (default 1: -Dkwemu-jit=true, # the kernel then imports unkernel.kw_host_jit_*; ignored with KWEMU=) -# KWEMU_STATS=1 build that library with -Dkwemu-stats into vendor/build/kwemu-stats +# KWEMU_STATS=1 build the UP library with -Dkwemu-stats into vendor/build/kwemu-stats # (what `stats` sets; ignored with KWEMU=) # JOBS=n parallelism (default: nproc) # KSRC=dir kernel source tree, e.g. a git worktree (default: vendor/src/linux-wasm-kernel) -# KOUT=dir kernel build output (default: vendor/build/kernel) +# KOUT=dir UP kernel build output (default: vendor/build/kernel) +# KOUT_SMP=dir SMP kernel build output (default: vendor/build/kernel-smp) +# LINUX_REPO=url where a fresh kernel tree fetches $LINUX_BASE from (default: kernel.org) # WASM_OPT=path wasm-opt for the 32-bit lowering (default: vendor/toolchain/binaryen, -# then PATH); `lower` redoes only that step on an existing vmlinux +# then PATH); `lower` redoes only that step on existing vmlinux files set -euo pipefail -. "$(dirname "$0")/tools/env.sh" # root, vendor, zig, pins, real_bin, ... +. "$(dirname "$0")/tools/env.sh" # root, vendor, build, zig, pins, real_bin, ... jobs="${JOBS:-$(nproc)}" what="${1:-all}" use_real_host_tools @@ -60,7 +102,7 @@ use_real_host_tools # Kernel base: Linux v7.3.4 from kernel.org, fetched by exact commit (shallow). # arch/wasm is based on Joel Severin's linux-wasm (joelseverin/linux, branch # wasm-7.0); see .agents/kernel.md. -LINUX_REPO=https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git +LINUX_REPO="${LINUX_REPO:-https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git}" LINUX_BASE=7595a62d45ee1a2297eafa5f2ef5d0a45142d84d LLVM_REPO=https://github.com/llvm/llvm-project.git LLVM_TAG=llvmorg-22.1.8 @@ -70,7 +112,8 @@ BINARYEN_SHA256_x86_64=2dc9c7813f5375db93d96ead4b78222fcc3e2677bbb832297af479778 BINARYEN_SHA256_aarch64=89c07ea56faf38d0fbecf36ca8ec0721756716185f265b568e133d427f299bf8 ksrc="${KSRC:-$vendor/src/linux-wasm-kernel}" -kout="${KOUT:-$vendor/build/kernel}" +kout="${KOUT:-$build/kernel}" +kout_smp="${KOUT_SMP:-$build/kernel-smp}" toolchain="$vendor/toolchain/bin" need_clang() { @@ -141,13 +184,14 @@ prepare_kernel_tree() { git_am "$ksrc" "$root"/kernel/patches/linux/*.patch git -C "$ksrc" checkout -q -b kw-riscv-user fi - # An existing branch is never re-applied: say so when it no longer + # An existing branch is never re-applied: say so when what is checked + # out (kw-riscv-user, or the branch of a KSRC worktree) no longer # matches the series (an older series, or commits not yet exported). local npatch ncommit npatch=$(ls "$root"/kernel/patches/linux/*.patch | wc -l) - ncommit=$(git -C "$ksrc" rev-list --count "$LINUX_BASE..kw-riscv-user" 2>/dev/null || echo "?") + ncommit=$(git -C "$ksrc" rev-list --count "$LINUX_BASE..HEAD" 2>/dev/null || echo "?") if [ "$npatch" != "$ncommit" ]; then - echo "warning: kw-riscv-user has $ncommit commits, kernel/patches/linux has $npatch patches;" >&2 + echo "warning: $ksrc has $ncommit commits on $LINUX_BASE, kernel/patches/linux has $npatch patches;" >&2 echo " export your commits, or rename the branch (git -C $ksrc branch -m kw-riscv-user old) to re-apply the series" >&2 fi # The emulator contract (include/kw_emu.h) is the source of truth; the @@ -166,23 +210,29 @@ kwemu_jit_flag() { if [ "${KWEMU_JIT:-1}" = 0 ]; then echo -Dkwemu-jit=false; else echo -Dkwemu-jit=true; fi } +# kwemu_obj up|smp: the kwemu library to link into that kernel (empty for +# the stub). The SMP kernel's is built with atomics (kernel.md, SMP), into +# its own prefix, as a stats library is, so zig-out keeps the normal one. kwemu_obj() { - # A stats library goes to its own prefix, so zig-out keeps the normal one. - local prefix="$root/zig-out" stats=() - if [ "${KWEMU_STATS:-0}" = 1 ]; then - prefix="$vendor/build/kwemu-stats" - stats=(-Dkwemu-stats=true) + local prefix="$root/zig-out" flags=() k="${KWEMU:-}" + if [ "$1" = smp ]; then + prefix="$build/kwemu-smp" + flags=(-Dkwemu-atomics=true) + k="${KWEMU_SMP:-}" + elif [ "${KWEMU_STATS:-0}" = 1 ]; then + prefix="$build/kwemu-stats" + flags=(-Dkwemu-stats=true) fi - local k="${KWEMU:-$prefix/lib/libkwemu.a}" if [ "$k" = none ]; then echo "" return fi - if [ -z "${KWEMU:-}" ]; then + if [ -z "$k" ]; then # Always run it: zig build is incremental and keeps libkwemu.a current # (also after a `zig build` or `zig build test` without the JIT option). need_zig - (cd "$root" && "$zig" build "$(kwemu_jit_flag)" "${stats[@]}" --prefix "$prefix" >&2) || return 1 + (cd "$root" && "$zig" build "$(kwemu_jit_flag)" "${flags[@]}" --prefix "$prefix" >&2) || return 1 + k="$prefix/lib/libkwemu.a" fi if [ ! -f "$k" ]; then echo "no kwemu library at $k (KWEMU=none links a stub that cannot run user code)" >&2 @@ -191,23 +241,108 @@ kwemu_obj() { echo "$k" } +# digest_files DIR PATH...: sha256 lines of the files under PATH (tracked or +# untracked but not ignored, when DIR is a git checkout). +digest_files() { + local dir="$1" + shift + ( + cd "$dir" + if git rev-parse --is-inside-work-tree >/dev/null 2>&1; then + git --no-optional-locks ls-files -z -co --exclude-standard -- "$@" + else + find "$@" -type f ! -path '*/__pycache__/*' -print0 2>/dev/null | sort -z + fi | xargs -0r sha256sum 2>/dev/null || true + ) +} + +# kernel_stamps: export the fixed build stamps (KBUILD_BUILD_*; see the top +# of this file), unless the environment has them. Both kernels of a tree get +# the same ones, so their banners differ only in "SMP". +kernel_stamps() { + [ -z "${stamps_done:-}" ] || return 0 + stamps_done=1 + local id when + id="$( + { + echo "tree $(git -C "$ksrc" rev-parse 'HEAD^{tree}')" + git -C "$ksrc" --no-optional-locks diff --binary HEAD + (cd "$ksrc" && git --no-optional-locks ls-files -z -o --exclude-standard | xargs -0r sha256sum) + digest_files "$root" src include build.zig build.zig.zon kernel/patches/llvm kernel/tools/fake-llvm + echo "zig $("${zig:-zig}" version 2>/dev/null) jit ${KWEMU_JIT:-1} stats ${KWEMU_STATS:-0}" + } | sha256sum | cut -c1-12 + )" + when="$({ + git -C "$ksrc" log -1 --format=%at "$LINUX_BASE" + git -C "$ksrc" log --format=%at "$LINUX_BASE..HEAD" + } | sort -n | tail -1)" + export KBUILD_BUILD_USER="${KBUILD_BUILD_USER:-unkernel}" + export KBUILD_BUILD_HOST="${KBUILD_BUILD_HOST:-unkernel}" + export KBUILD_BUILD_VERSION="${KBUILD_BUILD_VERSION:-$id}" + export KBUILD_BUILD_TIMESTAMP="${KBUILD_BUILD_TIMESTAMP:-$(LC_ALL=C date -u -d "@$when")}" + echo "kernel stamps: #$KBUILD_BUILD_VERSION $KBUILD_BUILD_TIMESTAMP ($KBUILD_BUILD_USER@$KBUILD_BUILD_HOST)" +} + +# check_config OUT FRAGMENT...: every option the fragments set (a later one +# wins) must be in OUT/.config as written. Kconfig drops an option whose +# dependencies are not met without a word. +check_config() { + local out="$1" bad + shift + bad="$(cd "$ksrc/arch/wasm/configs" && awk -v cfg="$out/.config" ' + function key(l) { + if (l ~ /^CONFIG_[A-Za-z0-9_]+=/) { sub(/=.*/, "", l); return l } + if (l ~ /^# CONFIG_[A-Za-z0-9_]+ is not set$/) { l = substr(l, 3); sub(/ is not set$/, "", l); return l } + return "" + } + { k = key($0) } + k == "" { next } + FILENAME != cfg { want[k] = $0; next } + { have[k] = $0 } + END { + for (k in want) { + w = want[k]; h = (k in have) ? have[k] : "# " k " is not set" + if (w ~ /^#/ ? h !~ /^#/ : w != h) print " " w " (.config: " h ")" + } + }' "$@" "$out/.config")" + if [ -n "$bad" ]; then + echo "$out/.config lacks what $* set (dependencies not met?):" >&2 + echo "$bad" >&2 + return 1 + fi +} + +# build_kernel [up|smp]: the UP kernel (kw_defconfig) into KOUT, or the SMP +# kernel (kw_defconfig + kw_smp.config, kwemu with atomics) into KOUT_SMP, +# from the same tree, then lowered (vmlinux32.wasm). build_kernel() { + local variant="${1:-up}" out="$kout" frags=(kw_defconfig) f stale= kwemu + if [ "$variant" = smp ]; then + out="$kout_smp" + frags+=(kw_smp.config) + fi [ -x "$toolchain/wasm-ld" ] || build_toolchain prepare_kernel_tree - local kwemu - kwemu="$(kwemu_obj)" || exit 1 - local make_cmd=(make -C "$ksrc" O="$kout" ARCH=wasm + kernel_stamps + kwemu="$(kwemu_obj "$variant")" || exit 1 + local make_cmd=(make -C "$ksrc" O="$out" ARCH=wasm LLVM="$root/kernel/tools/fake-llvm/" REAL_LLVM="$toolchain/" CROSS_COMPILE=wasm64-unknown-unknown- HOSTCC=gcc KWEMU="$kwemu") # The wrapper (python3) and Kbuild find clang/wasm-ld through REAL_LLVM. - mkdir -p "$kout" - # (Re)configure when there is no .config or kw_defconfig changed since. - if [ ! -f "$kout/.config" ] || [ "$ksrc/arch/wasm/configs/kw_defconfig" -nt "$kout/.config" ]; then - "${make_cmd[@]}" kw_defconfig + mkdir -p "$out" + # (Re)configure when there is no .config or a fragment changed since, and + # then check the result. + [ -f "$out/.config" ] || stale=1 + for f in "${frags[@]}"; do + [ "$ksrc/arch/wasm/configs/$f" -nt "$out/.config" ] && stale=1 + done + if [ -n "$stale" ]; then + "${make_cmd[@]}" "${frags[@]}" + check_config "$out" "${frags[@]}" || exit 1 fi "${make_cmd[@]}" -j"$jobs" vmlinux - echo "kernel: $kout/vmlinux" - lower_kernel + echo "kernel ($variant): $out/vmlinux" + lower_kernel "$out" } # Binaryen release binaries (wasm-opt) into vendor/toolchain/binaryen. @@ -247,16 +382,17 @@ find_wasm_opt() { # every load/store, memory and table op wraps its address to i32, which is # exact because guest RAM is < 4 GiB. The import/export signatures (and with # them JSPI) are unchanged. Fetches the pinned Binaryen if there is no wasm-opt. +# $1: the kernel build output (default KOUT). lower_kernel() { - local wasm_opt + local k="${1:-$kout}" wasm_opt wasm_opt="$(find_wasm_opt)" [ -n "$wasm_opt" ] || { fetch_binaryen && wasm_opt="$(find_wasm_opt)"; } || true if [ -z "$wasm_opt" ]; then echo "lower: no wasm-opt with --table64-lowering (run '$0 binaryen' or set WASM_OPT);" >&2 echo " the browser page and the bundle need vmlinux32.wasm" >&2 - if [ -f "$kout/vmlinux32.wasm" ] && [ "$kout/vmlinux" -nt "$kout/vmlinux32.wasm" ]; then - rm -f "$kout/vmlinux32.wasm" - echo " removed the stale $kout/vmlinux32.wasm (older than vmlinux)" >&2 + if [ -f "$k/vmlinux32.wasm" ] && [ "$k/vmlinux" -nt "$k/vmlinux32.wasm" ]; then + rm -f "$k/vmlinux32.wasm" + echo " removed the stale $k/vmlinux32.wasm (older than vmlinux)" >&2 fi return 1 fi @@ -264,29 +400,52 @@ lower_kernel() { # In current Binaryen --table64-lowering is an alias of --memory64-lowering # (which lowers both); giving both is harmless (identical output) and also # covers releases where they were separate passes. - "$wasm_opt" "$kout/vmlinux" -g --memory64-lowering --table64-lowering -o "$kout/vmlinux32.wasm.tmp" - mv "$kout/vmlinux32.wasm.tmp" "$kout/vmlinux32.wasm" - echo "kernel (32-bit memory): $kout/vmlinux32.wasm ($("$wasm_opt" --version))" + "$wasm_opt" "$k/vmlinux" -g --memory64-lowering --table64-lowering -o "$k/vmlinux32.wasm.tmp" + mv "$k/vmlinux32.wasm.tmp" "$k/vmlinux32.wasm" + echo "kernel (32-bit memory): $k/vmlinux32.wasm ($("$wasm_opt" --version))" } -# A single-file kernel (the 32-bit-memory build) with Alpine (gzipped) and its -# command line bundled in custom sections; the runtime boots it when given no -# initrd of its own. -# $1: the bundle's file name (default unkernel-alpine.wasm). +# The bundle's SMP options (bundle.mjs): the SMP kernel and the file that +# caches the patch to it (reused while both kernels are the same). Unless +# KW_SMP=1 a kernel that does not match the UP one (another build of the +# tree) is left out with a warning (--smp-optional). +smp_bundle_args() { + [ "${KW_SMP:-}" != 0 ] || return 0 + if [ -f "$kout_smp/vmlinux32.wasm" ]; then + printf '%s\n' --smp "$kout_smp/vmlinux32.wasm" --smp-patch "$kout_smp/up.kwpatch" + [ "${KW_SMP:-}" = 1 ] || echo --smp-optional + elif [ "${KW_SMP:-}" = 1 ]; then + echo "bundle: no SMP kernel $kout_smp/vmlinux32.wasm (run '$0 smp'; KW_SMP=1)" >&2 + return 1 + else + echo "bundle: no SMP kernel ($kout_smp; '$0 smp' builds it), so no SMP patch" >&2 + fi +} + +# A single-file kernel (the 32-bit-memory build) with Alpine (gzipped), its +# command line, the data disk template and the patch to the SMP kernel +# bundled in custom sections; the runtime boots it when given no initrd of +# its own. +# $1: the bundle's file name (default unkernel-alpine.wasm; another name, +# the stats bundle, gets no SMP patch). bundle_alpine() { - local out="$vendor/build/bundle" cpio="$vendor/build/initramfs/alpine.cpio" name="${1:-unkernel-alpine.wasm}" + local out="$build/bundle" cpio="$build/initramfs/alpine.cpio" name="${1:-unkernel-alpine.wasm}" [ -f "$cpio" ] || { echo "bundle: no $cpio (run '$0 alpine')" >&2; return 1; } [ -f "$kout/vmlinux32.wasm" ] || { echo "bundle: no $kout/vmlinux32.wasm (run '$0 lower')" >&2; return 1; } mkdir -p "$out" rm -f "$out/unkernel-alpine32.wasm" # earlier name of this bundle - local dd=() tpl="$vendor/build/disk/kwdata.kwsparse.gz" + local dd=() smp=() args tpl="$build/disk/kwdata.kwsparse.gz" if [ -f "$tpl" ]; then dd=(--datadisk "$tpl") else echo "warning: no $tpl ('$0 datadisk' needs mke2fs); the bundle has no data disk template" >&2 fi + if [ "$name" = unkernel-alpine.wasm ]; then + args="$(smp_bundle_args)" || return 1 + [ -z "$args" ] || mapfile -t smp <<< "$args" + fi node "$root/kernel/tools/bundle.mjs" "$kout/vmlinux32.wasm" "$cpio" -o "$out/$name" \ - --cmdline "console=hvc0 rdinit=/init" "${dd[@]}" + --cmdline "console=hvc0 rdinit=/init" "${dd[@]}" "${smp[@]}" # The page's dev server runs web/kernel/'s copy (web/scripts/kernel.ts); # a page build replaces it with the newest release's. if [ "$name" = unkernel-alpine.wasm ]; then @@ -310,7 +469,7 @@ DATADISK_UUID=6b776461-7461-4000-8000-000000000001 DATADISK_HASH_SEED=6b776461-7461-4000-8000-000000000002 DATADISK_EPOCH=1767225600 # 2026-01-01T00:00:00Z build_datadisk() { - local out="$vendor/build/disk" mke2fs e2fsck + local out="$build/disk" mke2fs e2fsck mke2fs="$(PATH="$PATH:/usr/sbin:/sbin" command -v mke2fs || true)" e2fsck="$(PATH="$PATH:/usr/sbin:/sbin" command -v e2fsck || true)" if [ -z "$mke2fs" ]; then @@ -344,13 +503,13 @@ build_datadisk() { # After a kernel or Alpine rebuild: keep the bundle (the default of the CLI, # the SDK and the page) in step, when both inputs exist. refresh_bundle() { - [ -f "$vendor/build/initramfs/alpine.cpio" ] && [ -f "$kout/vmlinux32.wasm" ] || return 0 + [ -f "$build/initramfs/alpine.cpio" ] && [ -f "$kout/vmlinux32.wasm" ] || return 0 bundle_alpine } # The disk image is kept if it is newer than everything it is built from. disk_is_current() { - local img="$vendor/build/disk/alpine.ext4" f + local img="$build/disk/alpine.ext4" f [ -f "$img" ] || return 1 for f in "$root/kernel/guest/alpine-disk.sh" "$root/kernel/guest/alpine.sh" \ "$root/kernel/guest/curl-shim.sh" "$root/kernel/guest/kw-data.sh" "$root/kernel/tools/ext4-owners.py" \ @@ -362,8 +521,13 @@ disk_is_current() { case "$what" in toolchain) build_toolchain ;; binaryen) fetch_binaryen ;; -kernel) build_kernel; refresh_bundle ;; -lower) lower_kernel; refresh_bundle ;; +kernel) build_kernel up; refresh_bundle ;; +smp) build_kernel smp; refresh_bundle ;; +lower) + lower_kernel "$kout" + if [ -f "$kout_smp/vmlinux" ]; then lower_kernel "$kout_smp"; fi + refresh_bundle + ;; alpine) "$root/kernel/guest/alpine.sh"; refresh_bundle ;; disk) "$root/kernel/guest/alpine-disk.sh" ;; datadisk) build_datadisk; refresh_bundle ;; @@ -371,22 +535,26 @@ bundle) bundle_alpine ;; ubuntu) "$root/kernel/guest/ubuntu-disk.sh" ;; stats) KWEMU_STATS=1 - kout="${KOUT:-$vendor/build/kernel-stats}" - build_kernel + kout="${KOUT:-$build/kernel-stats}" + build_kernel up bundle_alpine unkernel-alpine-stats.wasm ;; all) - build_kernel + build_kernel up + if [ "${KW_SMP:-}" != 0 ]; then + build_kernel smp + KW_SMP=1 # so the bundle must carry the patch + fi "$root/kernel/guest/alpine.sh" build_datadisk || true # without mke2fs: a bundle without the data disk bundle_alpine if disk_is_current; then - echo "disk: keeping $vendor/build/disk/alpine.ext4 (kernel/build.sh disk rebuilds it)" + echo "disk: keeping $build/disk/alpine.ext4 (kernel/build.sh disk rebuilds it)" elif PATH="$PATH:/usr/sbin:/sbin" command -v mke2fs >/dev/null; then "$root/kernel/guest/alpine-disk.sh" else echo "warning: no mke2fs (e2fsprogs); skipping the disk image" >&2 fi ;; -*) echo "usage: $0 [toolchain|binaryen|kernel|lower|alpine|disk|datadisk|bundle|ubuntu|stats|all]" >&2; exit 2 ;; +*) echo "usage: $0 [toolchain|binaryen|kernel|smp|lower|alpine|disk|datadisk|bundle|ubuntu|stats|all]" >&2; exit 2 ;; esac diff --git a/kernel/guest/alpine-disk.sh b/kernel/guest/alpine-disk.sh index 057e1fe..5d06fa7 100755 --- a/kernel/guest/alpine-disk.sh +++ b/kernel/guest/alpine-disk.sh @@ -12,7 +12,7 @@ set -euo pipefail . "$(dirname "$0")/../tools/env.sh" # root, ALPINE_*, fetch_verified -out="$root/vendor/build/disk" +out="$build/disk" dl="$root/vendor/downloads" size="${DISK_SIZE:-512M}" mkdir -p "$out" "$dl" diff --git a/kernel/guest/alpine.sh b/kernel/guest/alpine.sh index 8ea4acd..7e5751b 100755 --- a/kernel/guest/alpine.sh +++ b/kernel/guest/alpine.sh @@ -27,11 +27,11 @@ set -euo pipefail . "$(dirname "$0")/../tools/env.sh" # root, zig, ALPINE_*, fetch_verified, need_zig need_zig -out="$root/vendor/build/initramfs" +out="$build/initramfs" dl="$root/vendor/downloads" mkdir -p "$out" "$dl" # Images of the test and busybox root fs variants, which no longer exist. -rm -rf "$out"/{test,busybox}{.cpio,-root} "$root/vendor/build/busybox-riscv64" +rm -rf "$out"/{test,busybox}{.cpio,-root} "$build/busybox-riscv64" # ALPINE_TARBALL=file overrides the pinned release (tools/env.sh). if [ -z "${ALPINE_TARBALL:-}" ]; then diff --git a/kernel/guest/ubuntu-disk.sh b/kernel/guest/ubuntu-disk.sh index 61c0041..18cbe7c 100755 --- a/kernel/guest/ubuntu-disk.sh +++ b/kernel/guest/ubuntu-disk.sh @@ -22,7 +22,7 @@ set -euo pipefail . "$(dirname "$0")/../tools/env.sh" # root, UBUNTU_*, fetch_verified -out="$root/vendor/build/disk" +out="$build/disk" dl="$root/vendor/downloads" size="${DISK_SIZE:-2G}" mkdir -p "$out" "$dl" diff --git a/kernel/tools/bundle.mjs b/kernel/tools/bundle.mjs index 66e6ad5..8b38083 100644 --- a/kernel/tools/bundle.mjs +++ b/kernel/tools/bundle.mjs @@ -5,7 +5,7 @@ // // node kernel/tools/bundle.mjs -o // [--cmdline "console=hvc0 rdinit=/init"] [--datadisk kwdata.kwsparse.gz] [--no-gzip] -// [--smp ] +// [--smp [--smp-patch ] [--smp-optional]] // // The initramfs goes into a custom section "unkernel.initrd", the command // line into "unkernel.cmdline", and the data disk template (a gzipped @@ -14,6 +14,14 @@ // this kernel into the given SMP build of the same tree // ("unkernel.kernel.smp.kwpatch", kwdiff.mjs --remap, last), which the // loader applies when asked for more than one CPU (js/core/kpatch.ts). +// It refuses two kernels that are not the UP and SMP builds of one tree +// (smpPairError: their banners must differ only in "SMP", which with +// kernel/build.sh's build stamps means the same tree and kwemu sources; +// the same KW_ABI_VERSION in their kwemu; only the SMP one importing +// wasm_cpu_start; the same memory index type); with --smp-optional it +// warns and leaves the patch out instead. --smp-patch caches the patch +// (making it takes about 15 s): a patch in that file made from these two +// kernels (its header's SHA-256s) is reused, else a new one is written there. // Custom sections are ignored by the engine, so // the module is otherwise unchanged (same code, imports and memory type), and // the kernel needs no rebuild. The host runtime (js/core/kernel.ts, see @@ -23,9 +31,11 @@ // // The cpio is gzipped (CONFIG_RD_GZIP) unless it already is or --no-gzip is // given. Existing unkernel.* sections are replaced, so re-bundling works. -import { readFileSync, writeFileSync, renameSync } from "node:fs"; +import { readFileSync, writeFileSync, renameSync, existsSync } from "node:fs"; +import { createHash } from "node:crypto"; import { gzipSync } from "node:zlib"; import { makePatch } from "./kwdiff.mjs"; +import { kernelPatchInfo } from "../../js/core/kpatch.ts"; export const INITRD_SECTION = "unkernel.initrd"; export const CMDLINE_SECTION = "unkernel.cmdline"; @@ -75,7 +85,93 @@ function sections(wasm) { return out; } -export function bundle(wasm, initrd, { cmdline, datadisk, gzip = true, smp } = {}) { +/** + * What identifies a kernel build: { banner, smp, abi, cpuStart, memory64 }. + * banner is linux_banner without its newline and smp whether its version + * part ("# SMP