js, guest: let the data disk grow past its 4 GiB template: openDataDisk({ size }) (and the data disk spec's size) makes a new disk that large or relabels a smaller saved one to it, never shrinking, and the base's /init grows /data's ext4 to its device with kwbox growfs (EXT4_IOC_RESIZE_FS)

This commit is contained in:
Pooya Parsa
2026-11-22 22:56:21 +00:00
parent 14e18e531f
commit 6b74afbf34
7 changed files with 145 additions and 15 deletions

View File

@@ -127,9 +127,19 @@ kernel/guest.md (Distro images).
- The store `kwdisk:kwdata-v1` is keyed by the format version, not by the
template or an ETag. It is never cleared or reseeded implicitly, and a
new template does not touch saved disks. A layout change needs a new version, plus a migration or the user's
export/import. If the identity
(format, size) does not match, the page runs a fresh in-memory disk and
says why.
export/import. If the identity's format does not match, the page runs
a fresh in-memory disk and says why.
- Its size is in the identity. The template is 4 GiB; Settings' Disk size
(`?datasize=`, GiB) makes a new disk larger, or grows a saved one at the
next boot without a suspended session that has the data disk to resume
(its kernel knows the old size), clamped to the browser's quota for
the page (a larger disk would fail its writes with EIO once the quota
is used up): `openDataDisk({ size })` relabels the
identity, the new space reads as zeros, and a disk never shrinks. The
base's `/init` grows the file system to the device after mounting
`/data` (`kwbox growfs`, `EXT4_IOC_RESIZE_FS`; 4 to 16 GiB in 40 ms,
2026-11-22), so a CLI `--data` file made larger with `truncate` grows
too. An import takes an image of any size.
- On first use the template's blocks are copied into the store in one
transaction, which also marks the store initialized.
- The disk has a volatile write cache. Each guest flush saves every block

View File

@@ -531,7 +531,8 @@ builds alone, as `test/wasi-binfmt.ts` and `gl/bridge/build-guest.sh` do).
KB alone; 2026-11-22). Callers name it: `kwbox TOOL ARGS` with TOOL `tty`,
`9p`, `vsock`, `shm`, `wasi`, `cmd` or `vtest` (the GL forwarder, which
serves Mesa's vtest socket; `gl` would also name virtio-gpu's path, which
has no forwarder). The tool runs with argv[0] and the process name (comm)
has no forwarder), or `growfs DEV DIR` (in `kwbox.c`: grows the ext4 on
DEV mounted at DIR to DEV's size; the base's `/init` runs it on `/data`). The tool runs with argv[0] and the process name (comm)
its program's own (`kwtty`, `kw9p`, ..., `vtest-bridge`): ps shows
`{kwtty} /usr/bin/kwbox tty serve`, busybox `pidof kwtty` finds it
(Debian's procps `pidof` matches argv[0], so there only `pidof kwbox`),

View File

@@ -9,7 +9,8 @@
# /sbin/init.
#
# 1. devtmpfs, proc, sysfs and a tmpfs on /run;
# 2. /data: the data disk (ext4 labelled kwdata), if the host attached one;
# 2. /data: the data disk (ext4 labelled kwdata), if the host attached one,
# its file system grown to the device (kwbox growfs);
# 3. the distro: the block device labelled kwroot (erofs or ext4), mounted
# read-only at /kw/distro; /usr/lib/kw-distro names it. None, one that
# does not mount or boot, or kw.root=base: the base shell (busybox
@@ -102,6 +103,9 @@ if bylabel kwdata; then
if mount -t ext4 -o $o "$d" /data; then
data=1
[ "$(stat -c %u:%g /data)" = 0:0 ] || chown 0:0 /data
# A disk the host made larger (the page's Disk size): the file system fills it.
g=$(/usr/bin/kwbox growfs "$d" /data 2>&1)
[ -z "$g" ] || say "kw-data: $g"
sysctl -q -w vm.dirty_expire_centisecs=100 vm.dirty_writeback_centisecs=100
else
say "kw-data: cannot mount $d (LABEL=kwdata) on /data"

View File

@@ -19,6 +19,12 @@
* programs (/usr/lib/kw/rc registers this path,
* and the kernel passes it as argv[0]; it cannot
* pass a TOOL), a link to kwbox
* kwbox growfs DEV DIR grow the ext4 file system on DEV, mounted at DIR,
* to DEV's size (EXT4_IOC_RESIZE_FS, online); says
* so on stdout when it grew it, nothing when it
* already fills DEV. The base's /init runs it on
* /data, whose disk the host may have made larger
* (the page's Disk size setting)
* any other name kwcmd's host command of that name: the links
* /run/kw/bin/NAME -> /usr/bin/kwbox that
* `kwbox cmd sync` makes (kwcmd.c)
@@ -27,10 +33,20 @@
* (js/core/commands.ts checkCommandName(), kwcmd.c valid_name()), the
* tools' names included.
*/
#include <errno.h>
#include <fcntl.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <linux/fs.h>
#include <sys/ioctl.h>
#include <sys/prctl.h>
#ifndef EXT4_IOC_RESIZE_FS
#define EXT4_IOC_RESIZE_FS _IOW('f', 16, uint64_t)
#endif
typedef int tool_main(int argc, char **argv);
tool_main kwtty_main, kw9p_main, kwvsock_main, kwshm_main, kwwasi_main, kwcmd_main, vtest_bridge_main;
@@ -42,6 +58,50 @@ static const struct { const char *name, *prog; tool_main *main; } tools[] = {
{ "vtest", "vtest-bridge", vtest_bridge_main },
};
static uint32_t le32(const unsigned char *p)
{
return p[0] | p[1] << 8 | p[2] << 16 | (uint32_t)p[3] << 24;
}
/* kwbox growfs DEV DIR: the superblock (offset 1024 on DEV) gives the
* block size and count, BLKGETSIZE64 the device's size. */
static int growfs_main(int argc, char **argv)
{
unsigned char sb[1024];
uint64_t bytes, old, n;
uint32_t bs;
int dev, dir;
if (argc != 3) {
fprintf(stderr, "usage: kwbox growfs DEV DIR\n");
return 2;
}
dev = open(argv[1], O_RDONLY | O_CLOEXEC);
if (dev < 0 || ioctl(dev, BLKGETSIZE64, &bytes) < 0 || pread(dev, sb, sizeof(sb), 1024) != sizeof(sb)) {
fprintf(stderr, "growfs: %s: %s\n", argv[1], strerror(errno));
return 1;
}
close(dev);
if (sb[56] != 0x53 || sb[57] != 0xef || le32(sb + 24) > 6) {
fprintf(stderr, "growfs: %s: not an ext4 file system\n", argv[1]);
return 1;
}
bs = 1024u << le32(sb + 24);
old = le32(sb + 4) | (le32(sb + 96) & 0x80 /* INCOMPAT_64BIT */ ? (uint64_t)le32(sb + 0x150) << 32 : 0);
n = bytes / bs;
if (n <= old)
return 0;
dir = open(argv[2], O_RDONLY | O_DIRECTORY | O_CLOEXEC);
if (dir < 0 || ioctl(dir, EXT4_IOC_RESIZE_FS, &n) < 0) {
fprintf(stderr, "growfs: %s: %s\n", argv[2], strerror(errno));
return 1;
}
close(dir);
printf("grew %s from %llu MiB to %llu MiB\n", argv[2],
(unsigned long long)(old * bs >> 20), (unsigned long long)(n * bs >> 20));
return 0;
}
int main(int argc, char **argv)
{
const char *base = argc ? strrchr(argv[0], '/') : NULL;
@@ -59,6 +119,8 @@ int main(int argc, char **argv)
return tools[i].main(argc - 1, argv + 1);
}
}
fprintf(stderr, "usage: kwbox TOOL [ARG...], TOOL one of tty 9p vsock shm wasi cmd vtest\n");
if (argc >= 2 && !strcmp(argv[1], "growfs"))
return growfs_main(argc - 1, argv + 1);
fprintf(stderr, "usage: kwbox TOOL [ARG...], TOOL one of tty 9p vsock shm wasi cmd vtest growfs\n");
return 2;
}

View File

@@ -78,6 +78,8 @@ export interface DataDiskSpec extends SpecCommon {
name?: string;
version?: string;
snapshotLimit?: number;
/** The disk's size in bytes: a new or smaller saved disk is made or grown this large, never shrunk (openDataDisk()'s `size`). */
size?: number;
}
export type DiskSpec = FileDiskSpec | HttpDiskSpec | DataDiskSpec;

View File

@@ -30,7 +30,7 @@ export const webDevices: DeviceRegistry = extendDevices(coreDevices, {
async data(spec: DataDiskSpec, ctx: DeviceContext) {
const template = spec.template === "bundled" ? bundledBoot(ctx.module).datadisk : spec.template;
if (!template) throw new Error("no template (the kernel has no unkernel.datadisk section)");
const common = { template, name: spec.name, version: spec.version, log: ctx.log };
const common = { template, name: spec.name, version: spec.version, size: spec.size, log: ctx.log };
if (spec.mode === "snapshot") return openDataDisk({ ...common, mode: "snapshot", snapshotLimit: spec.snapshotLimit });
try {
return await openDataDisk({ ...common, onError: (e) => ctx.onDiskError(ctx.index, e) });

View File

@@ -241,6 +241,25 @@ export class IdbStore implements OverlayStore {
});
}
/** The stored identity, without reading the index (undefined: none, or a reset that was cut off). */
async identity(): Promise<string | undefined> {
return this.#run("meta", "readonly", async (tx) => {
const meta = tx.objectStore("meta");
const [id, reset] = await Promise.all([reqP(meta.get("identity")), reqP(meta.get("reset"))]);
return reset || id === undefined ? undefined : String(id);
});
}
/** Replace the identity `from` with `to` (one transaction; false if the stored identity is not `from`). The blocks stay. */
async relabel(from: string, to: string): Promise<boolean> {
return this.#run("meta", "readwrite", async (tx) => {
const meta = tx.objectStore("meta");
if (await reqP(meta.get("reset")) || await reqP(meta.get("identity")) !== from) return false;
meta.put(to, "identity");
return true;
});
}
async close(): Promise<void> {
const p = this.dbp;
this.dbp = null;
@@ -308,6 +327,12 @@ export async function openDistroDisk(url: string, { chunkSize, prefetch, log }:
// store on first use; after that the store alone holds the disk (over a
// ZeroBase), and is never reset implicitly: it is keyed by the format
// version, not by the template.
//
// Its size is in the store's identity. The template is 4 GiB; a larger
// disk (openDataDisk's `size`) is the template's blocks on a larger zero
// base, and the guest's /init grows the file system to the device at boot
// (`kwbox growfs`). A saved disk grows to a larger `size` (its identity is
// relabelled; the new space reads as zeros) and never shrinks.
export const DATA_DISK_NAME = "kwdata";
export const DATA_DISK_VERSION = "v1";
@@ -326,6 +351,12 @@ export function dataDiskStore(size: number, { name = DATA_DISK_NAME, version = D
return { store: new IdbStore(id, { log }), identity: `${id} size=${size} bs=${BLOCK}` };
}
/** The size in a data disk identity of this name and version (dataDiskStore()), else undefined. */
function identitySize(identity: string | undefined, name: string, version: string): number | undefined {
const m = identity?.match(/^(.*) size=(\d+) bs=(\d+)$/);
return m && m[1] === `${name}-${version}` && Number(m[3]) === BLOCK ? Number(m[2]) : undefined;
}
export interface OpenDataDiskOptions extends DataDiskNameOptions {
/** The template: a kwsparse image (gzipped or not), or a decoded one. */
template: Uint8Array | ArrayBuffer | KwsparseImage;
@@ -338,30 +369,42 @@ export interface OpenDataDiskOptions extends DataDiskNameOptions {
mode?: "persistent" | "snapshot";
/** Default 64 MiB. */
snapshotLimit?: number;
/**
* The disk's size in bytes (rounded down to 4 KiB, at least the
* template's): a new disk is made this large, a saved disk smaller than
* this grows to it, a larger one keeps its size (a disk never shrinks).
* The guest's /init grows the file system to the device. Default: the
* saved disk's size, or the template's for a new one. Snapshot mode never
* grows a saved disk.
*/
size?: number;
onError?: (err: unknown) => void;
}
/**
* Open the data disk. The result has .persistent, and .notice when it is
* not the persistent disk. Throws a DataDiskFormatError if the saved disk
* has another identity (size); nothing is cleared, the caller decides (the
* has another identity (format); nothing is cleared, the caller decides (the
* page runs a snapshot of the template and says why).
*/
export async function openDataDisk({ name = DATA_DISK_NAME, version = DATA_DISK_VERSION, template, mode = "persistent",
snapshotLimit = 64 * 1048576, log = (m) => console.warn(m), onError }: OpenDataDiskOptions): Promise<CowDisk> {
snapshotLimit = 64 * 1048576, size, log = (m) => console.warn(m), onError }: OpenDataDiskOptions): Promise<CowDisk> {
const tpl = "indices" in template ? template : decodeKwsparse(await gunzipIfNeeded(template));
if (tpl.blockSize !== BLOCK) throw new Error(`data disk template: block size ${tpl.blockSize}, need ${BLOCK}`);
const haveIdb = typeof indexedDB !== "undefined";
const { store, identity } = dataDiskStore(tpl.size, { name, version, log });
const want = size !== undefined && size > 0 ? Math.max(tpl.size, Math.floor(size / BLOCK) * BLOCK) : undefined;
const { store } = dataDiskStore(0, { name, version, log });
const idOf = (n: number) => dataDiskStore(n, { name, version }).identity;
if (mode !== "persistent" || !haveIdb) {
let base = SparseBase.fromKwsparse(tpl), from = "the template";
let base = new SparseBase(want ?? tpl.size, tpl.map()), from = "the template";
if (haveIdb) {
try {
const st = await store.open(identity, { onMismatch: "refuse", write: false });
if (st.initialized && st.mismatch === undefined) {
const saved = identitySize(await store.identity(), name, version);
const st = saved === undefined ? null : await store.open(idOf(saved), { onMismatch: "refuse", write: false });
if (saved !== undefined && st?.initialized && st.mismatch === undefined) {
if (snapshotLimit > 0 && st.keys.size * BLOCK <= snapshotLimit) {
base = new SparseBase(tpl.size, await store.readAll());
base = new SparseBase(saved, await store.readAll());
from = "a copy of the saved disk";
} else {
from = `the template (the saved disk, ${(st.keys.size * BLOCK / 1048576).toFixed(0)} MiB, is too large to copy)`;
@@ -379,6 +422,14 @@ export async function openDataDisk({ name = DATA_DISK_NAME, version = DATA_DISK_
}
await warnOtherVersions(name, version, log);
// The saved size (another format's identity: none, and the open below refuses it), grown to `want`.
const savedId = await store.identity();
let eff = identitySize(savedId, name, version) ?? want ?? tpl.size;
if (savedId !== undefined && want !== undefined && want > eff && await store.relabel(savedId, idOf(want))) {
log(`[host] data disk: grew from ${eff / 1073741824} GiB to ${want / 1073741824} GiB (the guest grows its file system at boot)`);
eff = want;
}
const identity = idOf(eff);
const st = await store.open(identity, { onMismatch: "refuse" });
if (st.mismatch !== undefined) {
await store.close();
@@ -386,7 +437,7 @@ export async function openDataDisk({ name = DATA_DISK_NAME, version = DATA_DISK_
e.name = "DataDiskFormatError";
throw e;
}
const d = new CowDisk(new ZeroBase(tpl.size), { store, log, onError });
const d = new CowDisk(new ZeroBase(eff), { store, log, onError });
if (!st.initialized) {
const uid = await store.seed(tpl.indices.map((b, i) => [b, tpl.block(i).slice()]), identity);
d.adoptStore({ keys: new Set(tpl.indices), initialized: true, gen: 0, uid }, identity);