diff --git a/.agents/kernel/smp.md b/.agents/kernel/smp.md index 975ff6f..a44a3be 100644 --- a/.agents/kernel/smp.md +++ b/.agents/kernel/smp.md @@ -90,8 +90,10 @@ The CPU that holds a moved task's old stack learns it from a per-CPU list could switch to that task (or a new task at the same address) again, calls `wasm_stack_drop(task)`; its host unwinds the stack (its suspended import throws `STACK_DROPPED`, js/core/wasi.ts, as for an exited task's), which -frees it at once: left parked it would wait for a garbage collection, and -Firefox allows a thread about 2000 stacks ("too many continuation stacks"). +frees it at once: left parked it would stay until the kernel ends (the +host keeps its resumer, and V8 keeps a suspended stack as a +garbage-collection root anyway), and Firefox allows a thread about 2000 +stacks ("too many continuation stacks"). A full list only leaks that stack until the task next starts fresh on that CPU. A task picked again on its own CPU resumes its stack rather than starting fresh: preemptions are frequent and moves rare, and a fresh start diff --git a/README.md b/README.md index e7431e4..4c31c63 100644 --- a/README.md +++ b/README.md @@ -471,6 +471,18 @@ in a worker: `{ kind: "data", template: "bundled", backend: "opfs" }`); `BlockDevice` works too, and a disk of your own can be the root: `cmdline: "console=hvc0 root=/dev/wda rw"` with `initrd: null`. +`distro` takes an image of your own too: an erofs or ext4 file system +labelled `kwroot` with an aarch64 user space, a working `/bin/sh`, and an +executable `/usr/local/sbin/kw-init` or `/sbin/init` that runs +`/usr/lib/kw/rc` and keeps `/usr/bin/kwbox tty serve` running (for +`exec()`, `spawn()` and mounts; both come from the base, laid over the +image), plus `/usr/lib/kw-distro` (a name of `[a-z0-9]+`) for its changes +to be kept on a data disk, and optionally an account `user` with `sudo` +without a password (programs run as root without it). The build of the +released images (`guest/build.sh distro`, [guest/README.md](guest/README.md), +Adding a distro) is the reference; those also carry a header that tells +the SDK which part of the image a boot reads, to fetch it ahead over HTTP. + ### Console and lifecycle ```js @@ -496,7 +508,35 @@ exitCode, signal }`, also for a non-zero exit. Pass `encoding: "buffer"` for bytes, and `cwd` or `env` as you would to `child_process`. On the distro images programs run as the user `user` (uid 1000, in `/home/user`), who has `sudo` without a password; pass `user: "root"` (or -another name or uid) to run as someone else. The base shell is root's. +another name or uid) to run as someone else. The default is the account +`user` where the guest's `/etc/passwd` has one, and root otherwise: the +base shell is root's, and so is an image of your own without that account. + +A program gets a fixed environment, not a login shell's: the account's +`HOME`, `USER`, `LOGNAME` and `SHELL`, a `PATH` of `/run/kw/bin`, +`~/.local/bin`, the system's directories and `/usr/lib/kw/bin`, and `TERM` +on a pty; nothing comes from the image's `/etc/profile`, +`/etc/profile.d` or `/etc/environment`. `env` is applied over these and may +replace them; for the profile, run a login shell (`exec("sh", ["-lc", +"..."])`, or `spawn()` without a program). The working directory is the +account's home unless `cwd` says otherwise. A program that cannot start +rejects `exec()` and `spawn()` with a `PtyError` whose `code` is +`"EREMOTE"` and whose message is the guest's: `kwtty: exec NAME: No such +file or directory` (or `Permission denied`), `kwtty: chdir DIR: ...` for a +bad `cwd`, `kwtty: no user NAME`. A program that starts and fails is not an +error: `exec()` resolves with its `exitCode`. A guest that does not run +unkernel's terminal server rejects with `ETIMEDOUT` after `timeout` (30 s +by default). + +On every distro image, `node`, `npm`, `npx`, `bun`, `bunx`, `uv`, `uvx`, +`claude`, `opencode` and `fx` are shims at the end of `PATH` (a version the +image installs comes first). The first call downloads the current release +for the user (Node's newest LTS), puts it in `~/.local/bin` and runs it; +that takes a network and a while (`node --version` took 14 s on Debian, +2026-12-01), and without a data disk the install is in guest memory and +gone at the next boot; without a network the shim exits 127. +`KW_NODE_VERSION`, `KW_BUN_VERSION`, +`KW_UV_VERSION` and `KW_CLAUDE_VERSION` in `env` pick another version. ```js const sh = await vm.spawn(); // a login shell on its own pty @@ -508,7 +548,9 @@ console.log(await sh.ended); // { type: "exit", code: 0 } `spawn(file, args, { cols, rows })` runs a program on a pty, in the zigpty / node-pty shape, with `resize()`, `kill(signal)` and `close()` (a hangup). Run as many as you like. Keep reading `output`: the guest program -waits while nobody does. +waits while nobody does. With `detachable: true` the session survives a +snapshot and restore, to be taken over with `attach()`; sessions on pipes +and `exec()` cannot be detachable, and end at a restore. ```js const gz = await vm.spawn("gzip", ["-c"], { pty: false }); @@ -571,7 +613,12 @@ evaluated once per open), a `MemoryFs` you read and write from the host, `nodeFs(dir)`, or your own `Fs`: `getattr`, `readdir` and `open` by path, sync or async, plus whichever change methods you want. Mounts are served over 9p on vsock. Each guest write reaches the host as it happens, and a -host change shows in the guest within a second. +host change shows in the guest within a second: the guest mounts with +`cache=readahead,metatimeout=1000`, so it reuses the names and attributes +it has looked up for up to 1 s before it asks the host again, and until +then a file the host rewrote reads with its old size (and the old content, +if the guest had it cached). The options are fixed; there is no setting to +shorten the window. ### Talk over vsock @@ -845,9 +892,16 @@ the machine run on, `{ stop: true }` stops it, and `{ commit }` stops it only once the snapshot is stored, so a failed save never loses the machine. Disks are not copied: a restore needs the same disks, unwritten since, and the same devices and CPU count, or `createKernel()` rejects with the reason. -Host mounts and detachable sessions survive; other vsock sessions and TCP -connections are reset. The CLI's `--input '{save=FILE}'` and `--restore -FILE` use it, and the page suspends a session with it. +Host mounts (in worker mode only with `commit`) and detachable sessions +survive a restore, and only a session on a pty can be detachable; other +vsock sessions and TCP connections are reset. The encoded size grows with +`memoryMiB` even for an idle guest (the base shell: 22 MiB at 512 MiB, +76 MiB at 4 GiB, 2026-12-01), and `decodeSnapshot()` allocates the whole +guest memory (on Node only the saved chunks take RAM, but each buffer +counts in full in `process.memoryUsage().arrayBuffers`), so keep snapshots +encoded and decode one just before its restore. The CLI's `--input +'{save=FILE}'` and `--restore FILE` use it, and the page suspends a +session with it. ### Run it in a worker @@ -865,14 +919,25 @@ and the network are given as specs, which the worker builds: `{ kind: "file", path }` on Node, `{ kind: "http", url }` and `{ kind: "data", template: "bundled" }` in browsers. Input and frames go through shared memory when it is available (`vm.transport` says). This mode is -experimental. +experimental. An inline kernel runs on your thread, so a busy guest and +your code take turns; a kernel in a worker runs in parallel with them. On +Node (2026-12-01, Alpine), `createKernel()` resolved about 150 ms later +with `worker: true` (starting the worker), and from then on an `exec()` +round trip (about 2.5 ms) and guest code ran at the same speed in both +modes. In worker mode a snapshot taken while host file systems are mounted +needs `commit`. -An SMP kernel (a bundle with the SMP patch) boots on several CPUs with -`cpus: 4`, each CPU in a thread of its own on one shared memory. In -browsers that needs a cross-origin isolated page and `worker: true`, -because a CPU blocks while it waits for another, which a page's main -thread may not; `webCpuBlocker()` says why it cannot, and -`vm.stats().cpus` how many CPUs the kernel got. +An SMP kernel boots on several CPUs with `cpus: 4` (at most 16, the +kernel's limit), each CPU in a thread of its own on one shared memory. The +bundled kernel carries the SMP kernel as a patch, which `createKernel()` +applies when `cpus` is above 1, inline or in a worker. A kernel you pass as +a `WebAssembly.Module` is used as it is, so compile it with +`loadKernelModule(source, { smp: true })`; a kernel without SMP boots on one +CPU and says so only in `log`. In browsers several CPUs need a cross-origin +isolated page and `worker: true`, because a CPU blocks while it waits for +another, which a page's main thread may not (without them the kernel boots +on one CPU, again with a line in `log`); `webCpuBlocker()` says why it cannot, +and `vm.stats().cpus` how many CPUs the kernel got. On a server, `worker: true` keeps the event loop free at no cost in speed, and `cpus: 4` gets most of what more CPUs give (about 3x on parallel work; @@ -904,6 +969,18 @@ const router = new ConsoleRouter({ // kernel log lines apart from vm.onOutput((bytes) => router.write(bytes)); ``` +`memoryMiB` is the guest's memory: 2048 by default on Node, and in +browsers a size for the device (`autoMemoryMiB()`). The host process gets +a page of it only when the guest first touches it, but keeps it until the +kernel stops and is collected: there is no balloon, so what the guest frees +stays allocated on the host (a guest that wrote 700 MiB to `/tmp` and +deleted it kept the Node process at about 900 MiB until it stopped, +2026-12-01). Without a data disk the root file system's changes live in +guest memory, and `/tmp`, `/run` and `/dev/shm` are memory too, with or +without one: each is a tmpfs capped at half the guest's memory, and they +share it. For more scratch space, raise `memoryMiB`, or attach a data disk +and write outside `/tmp`. + The SDK has some limits, on top of the kernel's [known limits](#-known-limits). There is no guest agent beyond terminal sessions, so you drive the guest through a terminal or its console, or over vsock with your diff --git a/docs/1.sdk/13.snapshots.md b/docs/1.sdk/13.snapshots.md index 26db0d2..97463e6 100644 --- a/docs/1.sdk/13.snapshots.md +++ b/docs/1.sdk/13.snapshots.md @@ -23,6 +23,8 @@ await restored.exec("cat", ["/tmp/state"]); // "kept" The kernel parks every task where its whole state is in memory, so a snapshot is the guest's memory plus a few host values. Without a data disk, that memory also holds the root file system's changes. `encodeSnapshot()` leaves out free pages, and by default a snapshot that stops the machine first drops the guest's clean file cache, so the idle base shell in a 2 GiB guest saved to 46 MiB (2026-11-30). +The encoded size grows with `memoryMiB` even for an idle guest: the base shell saved to 22 MiB with 512 MiB and 76 MiB with 4 GiB (2026-12-01). A decoded snapshot is bigger: `decodeSnapshot()` allocates a buffer of the whole guest memory and writes the saved chunks into it. On Node only those chunks take RAM, but each buffer counts at its full size in `process.memoryUsage().arrayBuffers` (four decodes of a 1 GiB guest's 30 MiB snapshot: RSS +119 MiB, `arrayBuffers` +4 GiB). Keep snapshots encoded, decode one just before its restore, and drop it once `createKernel()` has resolved: the restored kernel has its own copy. + - `snapshot()` alone copies the machine and lets it run on. - `snapshot({ stop: true })` stops it right after the copy (exit kind `"stopped"`). - `snapshot({ commit })` stops it only once `commit` has stored the snapshot. If `commit` rejects or times out (`commitTimeoutMs`), the machine runs on and `snapshot()` rejects with a `SnapshotCommitError`, so a failed save never loses the machine. @@ -39,9 +41,9 @@ The kernel parks every task where its whole state is in memory, so a snapshot is ## What survives -Host [mounts](/sdk/mounts) survive: pass the same mount paths (read-only as before) and the guest's open files on them are opened again by path. [Host commands](/sdk/commands) are replaced by the ones you pass. vsock sessions (`spawn()`, `exec()`, `connect()`, `fetch()`, listeners) and the guest's TCP connections do not survive: the guest's ends are reset. Serial ports, Bluetooth and USB devices come back unplugged. +Host [mounts](/sdk/mounts) survive: pass the same mount paths (read-only as before) and the guest's open files on them are opened again by path. In worker mode a snapshot is refused while anything is mounted, unless it has `commit`. [Host commands](/sdk/commands) are replaced by the ones you pass. vsock sessions (`spawn()`, `exec()`, `connect()`, `fetch()`, listeners) and the guest's TCP connections do not survive: the guest's ends are reset. Serial ports, Bluetooth and USB devices come back unplugged. -Terminal sessions survive if they are detachable: +A snapshot the machine runs on from (without `stop`, or a `hold` that continues) leaves every session connected. Across a restore, terminal sessions survive if they are detachable, which only a session on a pty can be (`exec()` and `spawn()` with `pty: false` cannot): ```js const sh = await vm.spawn("sh", [], { detachable: true }); diff --git a/docs/1.sdk/14.worker.md b/docs/1.sdk/14.worker.md index e737d43..80beb07 100644 --- a/docs/1.sdk/14.worker.md +++ b/docs/1.sdk/14.worker.md @@ -21,10 +21,12 @@ The kernel runs in a worker thread or Web Worker, with the same API. Disks and t Worker mode is experimental. :: +An inline kernel runs on your thread, so a busy guest and your code (or other inline kernels) take turns; a kernel in a worker runs in parallel with them. On Node (2026-12-01, Alpine), `createKernel()` resolved about 150 ms later with `worker: true` (starting the worker), and from then on an `exec()` round trip (about 2.5 ms) and guest code ran at the same speed in both modes. In worker mode a [snapshot](/sdk/snapshots) taken while host file systems are mounted needs `commit`. + ## Several CPUs -An SMP kernel (a bundle with the SMP patch) boots on several CPUs with `cpus: 4`, each CPU in a thread of its own on one shared memory. +An SMP kernel boots on several CPUs with `cpus: 4` (at most 16, the kernel's limit), each CPU in a thread of its own on one shared memory. The bundled kernel carries the SMP kernel as a patch, which `createKernel()` applies when `cpus` is above 1, inline or in a worker. A kernel you pass as a `WebAssembly.Module` is used as it is, so compile it with `loadKernelModule(source, { smp: true })`. A kernel without SMP (such as a module compiled without that option) boots on one CPU and says so only in `log`. -In browsers that needs a cross-origin isolated page and `worker: true`, because a CPU blocks while it waits for another, which a page's main thread may not. `webCpuBlocker()` says why it cannot, and `vm.stats().cpus` how many CPUs the kernel got. +In browsers that needs a cross-origin isolated page and `worker: true`, because a CPU blocks while it waits for another, which a page's main thread may not; without them the kernel boots on one CPU, again with a line in `log`. `webCpuBlocker()` says why it cannot, and `vm.stats().cpus` how many CPUs the kernel got. On a server, `worker: true` keeps the event loop free at no cost in speed, and `cpus: 4` gets most of what more CPUs give (about 3x on parallel work; 8 or 16 add little, and each CPU adds to boot time and takes 9 MiB of guest memory). `node test/profile.ts` measures your host, and the page's `/profile.html` a browser. diff --git a/docs/1.sdk/15.options.md b/docs/1.sdk/15.options.md index a9b62cb..4ad4f25 100644 --- a/docs/1.sdk/15.options.md +++ b/docs/1.sdk/15.options.md @@ -35,6 +35,12 @@ Other options: `vm.distro` describes the distro image the guest booted, and `vm.stats()` has the counters of every device. +## Memory + +`memoryMiB` is the guest's memory: 2048 by default on Node, and in browsers a size for the device (`autoMemoryMiB()`). The host process gets a page of it only when the guest first touches it, but keeps it until the kernel stops and is collected: there is no balloon, so what the guest frees stays allocated on the host. A guest that wrote 700 MiB to `/tmp` and deleted it kept the Node process at about 900 MiB until it stopped (2026-12-01). + +Without a data disk the root file system's changes live in guest memory, and `/tmp`, `/run` and `/dev/shm` are memory too, with or without one: each is a tmpfs capped at half the guest's memory, and they share it. For more scratch space, raise `memoryMiB`, or attach a [data disk](/sdk/disks) and write outside `/tmp`. + ## Limits On top of the kernel's own limits: diff --git a/docs/1.sdk/2.programs.md b/docs/1.sdk/2.programs.md index 51a559b..3fe7534 100644 --- a/docs/1.sdk/2.programs.md +++ b/docs/1.sdk/2.programs.md @@ -15,7 +15,21 @@ const { stdout: sum } = await vm.exec("sha256sum", [], { input: "hello" }); `exec()` runs a program on pipes and resolves with `{ stdout, stderr, exitCode, signal }`, also for a non-zero exit. Pass `encoding: "buffer"` for bytes, and `cwd` or `env` as you would to `child_process`. -On the distro images programs run as the user `user` (uid 1000, in `/home/user`), who has `sudo` without a password. Pass `user: "root"` (or another name or uid) to run as someone else. The base shell is root's. +On the distro images programs run as the user `user` (uid 1000, in `/home/user`), who has `sudo` without a password. Pass `user: "root"` (or another name or uid) to run as someone else. The default is the account `user` where the guest's `/etc/passwd` has one, and root otherwise: the base shell is root's, and so is an image of your own without that account. + +A program gets a fixed environment, not a login shell's: the account's `HOME`, `USER`, `LOGNAME` and `SHELL`, `PATH=/run/kw/bin:$HOME/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/lib/kw/bin`, and `TERM` on a pty. Nothing is read from the image's `/etc/profile`, `/etc/profile.d` or `/etc/environment`. `env` is applied over these and may replace them; for the profile, run a login shell (`exec("sh", ["-lc", "..."])`, or `spawn()` without a program). The working directory is the account's home unless `cwd` says otherwise. + +A program that cannot start rejects `exec()` and `spawn()` with a `PtyError` whose `code` is `"EREMOTE"` and whose message is the guest's: + +| Cause | Message | +| --- | --- | +| no such program, or not executable | `kwtty: exec NAME: No such file or directory` (or `Permission denied`) | +| a bad `cwd` | `kwtty: chdir DIR: No such file or directory` (or `Not a directory`) | +| a `user` the guest does not have | `kwtty: no user NAME` | + +A program that starts and fails is not an error: `exec()` resolves with its `exitCode`. A guest that does not run unkernel's terminal server rejects with `ETIMEDOUT` after `timeout` (30 s by default). + +On every distro image, `node`, `npm`, `npx`, `bun`, `bunx`, `uv`, `uvx`, `claude`, `opencode` and `fx` are shims at the end of `PATH` (a version the image installs comes first). The first call downloads the current release for the user (Node's newest LTS), puts it in `~/.local/bin` and runs it; that takes a network and a while (`node --version` took 14 s on Debian, 2026-12-01), and without a data disk the install is in guest memory and gone at the next boot. Without a network the shim exits 127. `KW_NODE_VERSION` (`lts`, `latest`, a major such as `22`, or `X.Y.Z`), `KW_BUN_VERSION`, `KW_UV_VERSION` and `KW_CLAUDE_VERSION` in `env` pick another version. ## `spawn()` on a pty @@ -26,7 +40,7 @@ await sh.write("cat /etc/alpine-release; exit\n"); console.log(await sh.ended); // { type: "exit", code: 0 } ``` -`spawn(file, args, { cols, rows })` runs a program on a pty, in the zigpty / node-pty shape, with `resize()`, `kill(signal)` and `close()` (a hangup). Run as many as you like. +`spawn(file, args, { cols, rows })` runs a program on a pty, in the zigpty / node-pty shape, with `resize()`, `kill(signal)` and `close()` (a hangup). Run as many as you like. With `detachable: true` the session survives a [snapshot](/sdk/snapshots) and restore, to be taken over with `attach()`; sessions on pipes and `exec()` cannot be detachable, and end at a restore. ::warning Keep reading `output`: the guest program waits while nobody does. diff --git a/docs/1.sdk/6.disks.md b/docs/1.sdk/6.disks.md index 8bc5705..4390c0a 100644 --- a/docs/1.sdk/6.disks.md +++ b/docs/1.sdk/6.disks.md @@ -21,6 +21,17 @@ A disk labelled `kwdata` is the guest's persistent data disk: the root file syst `createImageFromKwsparse(file, template)` makes a new data disk from the template the kernel carries (`bundledBoot(module).datadisk`). +## Your own distro image + +`distro` takes any image that the kernel's base system can boot. The build of the released images (`guest/build.sh distro`, with `guest/lib/image.sh`; [`guest/README.md`](https://github.com/pithings/unkernel/blob/main/guest/README.md), Adding a distro) is the reference. An image needs: + +- An erofs or ext4 file system labelled `kwroot`, with an aarch64 Linux user space. With another label the SDK logs a warning and the guest boots the base shell. +- A working `/bin/sh`, and an executable `/usr/local/sbin/kw-init` or `/sbin/init`, which runs once `/dev`, `/proc`, `/sys`, `/run`, `/tmp` (and `/data`) are mounted. It runs `/usr/lib/kw/rc` and keeps `/usr/bin/kwbox tty serve` running, which `exec()`, `spawn()` and mounts need (Alpine's `/etc/inittab` is a short example). These come from the base, laid over the image: the image must not carry them. +- `/usr/lib/kw-distro`, a name of `[a-z0-9]+`, for its changes to be kept on a data disk (`/data/distros//`), and `/usr/lib/kw-image`, an id that changes with the image. +- Optionally an account `user` with `sudo` without a password: programs run as root without it. + +The released erofs images also start with a header, in the 1024 bytes before the superblock, that tells the SDK how much of the image a boot reads, and they are laid out so that those reads come first; over HTTP the SDK fetches that part ahead. An image without the header is read lazily. + ## In the browser - `openHttpDisk(url)` reads an image over http(s) with range requests and keeps your writes in IndexedDB. diff --git a/docs/1.sdk/7.mounts.md b/docs/1.sdk/7.mounts.md index f507444..c9bcc46 100644 --- a/docs/1.sdk/7.mounts.md +++ b/docs/1.sdk/7.mounts.md @@ -32,4 +32,4 @@ A file system is one of: - **`nodeFs(dir)`** (Node), a host directory. - **Your own `Fs`**: `getattr`, `readdir` and `open` by path, sync or async, plus whichever change methods you want. -Mounts are served over 9p on [vsock](/sdk/vsock). Each guest write reaches the host as it happens, and a host change shows in the guest within a second. +Mounts are served over 9p on [vsock](/sdk/vsock). Each guest write reaches the host as it happens, and a host change shows in the guest within a second: the guest mounts with `cache=readahead,metatimeout=1000`, so it reuses the names and attributes it has looked up for up to 1 s before it asks the host again. Until then it works from what it saw: a file the host rewrote reads with its old size (and the old content, if the guest had it cached), and a name the host created or deleted can still be missing or present (directory listings always come from the host). The options are fixed; there is no setting to shorten the window.