28. Density and the devices you refuse

Density: time to the sentinel against guests started at once, and the memory of one guest Median time to the sentinel on straylight, 2026-10-04, for guests started at once, N from 1 to 128 on a log scale. wick boot: N=1 308.3 ms, N=2 235 ms, N=4 227.1 ms, N=8 244.8 ms, N=16 246.2 ms, N=32 349.2 ms, N=64 607.9 ms, N=128 1166.1 ms; the median first reaches twice N=1's at N=128. wick restore, the time for the load call to return: N=1 48.7 ms, N=2 47.8 ms, N=4 46.7 ms, N=8 47 ms, N=16 54.3 ms, N=32 80.2 ms, N=64 149.6 ms; the median first reaches twice N=1's at N=64. Firecracker boot: N=1 435.1 ms, N=2 435.9 ms, N=4 438.1 ms, N=8 444.3 ms, N=16 447.8 ms, N=32 551.9 ms, N=64 693.5 ms, N=128 897.1 ms; the median first reaches twice N=1's at N=128. Below, the memory of one guest at its sentinel in KiB. Boot: guest RAM touched 25312, VMM heap and stacks 284, binary 2060. Restore: guest RAM 131072, VMM heap and stacks 396, binary 2060. guests started at once: median time to the sentinel 0 200 400 600 800 1000 1200 1400 ms 1 2 4 8 16 32 64 128 guests started at once (log scale); restore is the load call wick boot: ring at N=128 wick restore (load call returns): ring at N=64 Firecracker boot: ring at N=128 memory of one booted guest at its sentinel (process RSS) VmHWM 27,656 KiB guest RAM touched: 25,312 KiB VMM heap and stacks: 284 KiB file-backed (binary, libraries): 2,060 KiB a restore holds all 131,072 KiB of RAM (VmHWM 133,528 KiB) straylight, Linux 6.18.51, 2026-10-04 UTC; load average 1.83 at the start. Medians of 20 runs; whiskers are min and max; rings mark the first N at twice N=1.

Why a claim about speed needs a host

A microVM makes three claims: many on one host, fast to start, small in memory. Firecracker, the VMM wick is modelled on, writes them down. Its SPECIFICATION.md at v1.15.1 says that a microVM of one CPU and 128 MiB, with “the Firecracker-tuned kernel”, costs the VMM’s threads “a memory overhead <= 5 MiB” and that it “takes <= 125 ms to go from receiving the Firecracker InstanceStart API call to the start of the Linux guest user-space /sbin/init process”, measured “using a VM with the serial console disabled and a minimal kernel and root file system” (SPECIFICATION.md:24-42). The page says where: “On an M5D.metal instance (with hyperthreading disabled) and an M6G.metal instance” (lines 8 to 10). Those are Firecracker’s numbers on its hardware, with its kernel and its console switched off; they are not a claim about any other machine, and they say nothing about this book’s guest.

A claim about speed needs a number, and a number needs a host, a date, a command and a spread. This chapter measures wick with a script (labs/ch28/measure.sh) on one machine, straylight (AMD RYZEN AI MAX+ 395 w/ Radeon 8060S, 32 threads, Linux 6.18.51), on 2026-10-04 (UTC), and puts every figure it prints into a committed file, labs/ch28/measured-straylight.txt. Each figure is the median of 20 runs, with the smallest and the largest beside it, and the chapter quotes the median and says where the spread is wide. The same guest, kernel and initramfs of chapter 24, run under Firecracker v1.15.1 on the same host by the same script, gives the comparison that Firecracker’s own page cannot: a second VMM, under the same conditions. It is not Firecracker at its best: the page’s kernel is a tuned one and its console is off, and the guest here has neither.

And the other half of the title. A device that wick does not have is a device whose code the guest cannot reach, whose state a snapshot does not carry and whose host privileges the VMM never asked for. Firecracker’s paper says the same of its own deletions: “Lower-level features, such as additional devices (USB, PCI, sound, video, etc), BIOS, and CPU instruction emulation are simply not implemented because they are not needed by typical serverless container and function workloads” (Agache et al., Firecracker: Lightweight Virtualization for Serverless Applications, NSDI 2020, section 1). The chapter’s second half goes through seven things wick could have and does not, says what each would cost it, and says why hearth, the type-1 hypervisor this book ends with, does not want it either; and then, at the length the reader asked for, the one refusal that is not a device: vcpu_count: 2.

Mechanism

What bounds density

Density is how many guests a host runs at once, and four things bound it: the memory each one holds that no other holds, the CPU each one takes to start, the host objects each one needs, and the scheduler’s share of the machine. Each is measured here for one guest and for many.

Memory. A guest’s RAM is one mapping in the wick process, made by vm-memory:

// vm-memory 0.18.0, src/mmap/unix.rs:239-244
    pub fn new(size: usize) -> Result<Self> {
        MmapRegionBuilder::new_with_bitmap(size, B::with_len(size))
            .with_mmap_prot(libc::PROT_READ | libc::PROT_WRITE)
            .with_mmap_flags(libc::MAP_ANONYMOUS | libc::MAP_NORESERVE | libc::MAP_PRIVATE)
            .build()
    }

(GuestMemoryMmap::from_ranges, which Vm::new calls, reaches it through GuestRegionMmap::from_range, mmap/mod.rs:103-115; the doc comment above the function says “shared”, the flags say MAP_PRIVATE.) An anonymous private mapping is zero-filled on demand: a page that no one touches costs no memory, and MAP_NORESERVE keeps the kernel from counting the whole mapping against the host’s commit limit at creation. So a guest with 128 MiB costs what it touches. On straylight, a held wick at the guest’s sentinel has 25,312 KiB of that mapping resident (min 25,288, max 25,328; labs/ch28/measure.sh, section “boot, chapter 24’s arguments”, /proc/PID/smaps, the one mapping whose Size is 131072 kB): about a fifth of the 131,072 KiB. The process as a whole peaks at 27,656 KiB (VmHWM of /proc/PID/status) and its cgroup’s memory.peak reads 27,208 KiB. memory.peak is the smaller of the two, because the two count different things: the process’s resident set includes the 2,060 KiB (about 2 MiB; it depends on the build) of file-backed pages of the wick binary and its libraries, which an earlier run’s cgroup already had charged (the rule is in the cgroup documentation), while the scope was charged for kernel memory on the process’s behalf that no resident set shows.

// linux v7.2.8, Documentation/admin-guide/cgroup-v2.rst:1966-1969
A memory area is charged to the cgroup which instantiated it and stays
charged to the cgroup until the area is released.  Migrating a process
to a different cgroup doesn't move the memory usages that it
instantiated while in the previous cgroup to the new cgroup.

The kernel image and the initramfs are read by wick before the guest starts, but in a warm run they are already in the page cache, instantiated by an earlier run’s cgroup, so memory.peak of a fresh scope does not include them: the figure is a lower bound on what a guest costs the machine, and the runs here are warm.

What is shared between two wick processes and what is not is in smaps_rollup. With two held guests, the first one’s (the file’s section “sharing”): Rss 27,660 KiB, of which 2,052 KiB are Shared_Clean, pages of the wick binary that the other process maps too, and 25,608 KiB are Private_Dirty, the guest’s RAM and the heap. Pss, the proportional share, which divides a shared page among the processes that map it, is 26,632 KiB, 1,028 KiB less than Rss: that difference, about one process’s share of the binary, is the whole of what a second guest saves, and it is the program text, not the guest. Each guest’s memory is its own, and a thousand of them hold a thousand copies of the same kernel pages. Linux has a facility for that, kernel samepage merging:

// linux v7.2.8, Documentation/admin-guide/mm/ksm.rst:17-28
The KSM daemon ksmd periodically scans those areas of user memory
which have been registered with it, looking for pages of identical
content which can be replaced by a single write-protected page (which
is automatically copied if a process later wants to update its
content). The amount of pages that KSM daemon scans in a single pass
and the time between the passes are configured using :ref:`sysfs
interface <ksm_sysfs>`

KSM only merges anonymous (private) pages, never pagecache (file) pages.
KSM's merged pages were originally locked into kernel memory, but can now
be swapped out just like other user pages (but sharing is broken when they
are swapped back in: ksmd must rediscover their identity and merge again).

and it “only operates on those areas of address space which an application has advised to be likely candidates for merging, by using the madvise(2) system call”, with MADV_MERGEABLE (the same file, lines 33 to 35). wick never calls madvise (grep -rn madvise wick/src finds nothing), ksm_run reads 0 on straylight, and so merging does not happen. The guest’s pages that are identical across guests, the kernel’s text and read-only data and the initramfs, sit in every guest’s own RAM: 25,312 KiB for each guest, so a hundred guests hold 2,472 MiB between them, each its own copy of the same kernel image and initramfs (the same files, the same sizes; the chapter did not measure how many of the touched pages are identical). A VMM that wants those pages shared has to arrange it: map one file MAP_PRIVATE into every guest, which is what a restore from a memory file can do (below), or advise the pages mergeable and pay for the scan.

Host objects. The same held wick has 13 open file descriptors and 4 threads (open_fds and threads of the same section). Five are eventfds, one is an epoll instance, two are the KVM objects for the VM and the vCPU, and the rest are /dev/kvm, the API socket, /dev/null and the two files the harness gave wick for its output and its log. The threads are wick’s main thread, which is the VMM thread, wick_api, wick_vcpu0, and one the kernel makes for the VM, kvm-nx-lpage-re (the section “sharing” lists the four by name); that last one is the recovery worker of the kernel’s NX-huge-page mitigation, for huge pages KVM split in its own mapping of the guest’s memory, made by the kernel as a vhost_task of the process (arch/x86/kvm/mmu/mmu.c:8013-8027, named "kvm-nx-lpage-recovery"). Thirteen descriptors against a limit of 524288 for each process (ulimit_n in the file) is not a bound, because the limit is per process and a process-per-VM design starts a new process for each guest; what is a bound on the host is what the kernel holds for each VM, memory for the page tables of the guest, an eventfd and an epoll registration for each device, and a thread. A second vCPU would add a thread and a descriptor for each guest and nothing else of this list.

CPU. For wick a boot is CPU work. One boot on straylight takes 283.6 ms (the median of 20 runs that fall into two groups, described under the scheduler below) from InstanceStart to the sentinel and the process’s scope has used 289.0 ms of CPU by then (cgroup_cpu_usage, the scope’s cpu.stat, all threads, including the time to start wick and the guest’s time to the end of its sentinel). Where the time goes is partly visible from the guest’s side. The guest writes its kernel log to a serial port, and chapter 24’s 8250 is emulated: every byte the kernel prints is a port write that leaves the guest, so the log costs exits. Adding quiet to the command line, which keeps most of the log off the console, takes the boot from 283.6 ms to 148.2 ms (min 145.4, max 157.4; section “boot, chapter 24’s arguments plus quiet”). The paper reports the same lever for Firecracker: its kernel command line “disables the standard logging to the serial console (saving up to 70ms of boot time)” (section 5.1). A guest whose console is off boots faster than one whose console is on by an amount that depends on how much the kernel says.

The scheduler. A guest is a thread; N guests are N runnable vCPU threads and a handful of idle ones, and the host’s scheduler divides 32 hardware threads among them. Nothing about KVM makes a vCPU thread special to it. The measurement is the parallel boot: N guests started at the same moment, each timed from its own InstanceStart to its own sentinel.

The series on straylight, 2026-10-04 UTC, is N=1 308.3, N=2 235.0, N=4 227.1, N=8 244.8, N=16 246.2, N=32 349.2, N=64 607.9, N=128 1166.1 ms for N = 1, 2, 4 and so on. The stop rule (the first N whose median is twice N = 1’s) gives N = 128: 1166.1 ms against 308.3 ms. But N = 1 is not one number here. Its 20 batch medians are eight at 220 to 225 ms, one at 257.0 ms and eleven at 308 to 324 ms (the batch_medians_us of the N = 1 line). The solo boots of the same run split the same way: nine at 218.8 to 250.1 ms (median 225.5) and eleven at 278.8 to 322.4 ms (median 317.5), and their overall median, 283.6 ms, is a value of the slow group. The groups are consecutive phases and not interleaved: the solo set ran eight fast, eleven slow and one fast, the N = 1 batches eight fast and then slow, and the N = 2 batches seven slow and then fast, so each N, like each set, ran mostly in one phase, which bears on every comparison between two N. The chapter does not choose a group: against the faster one the median has doubled by N = 64 (607.9 ms), against the slower only at N = 128. What puts a run in one phase or the other was not found. The CPU governor, powersave, is a candidate that was not tested, and the clock frequency was not recorded.

Where the point is depends on what else the host is doing. An earlier run of the same script on the same host, with the host busier (a 1-minute load average of 4.92 at its start, with 15.52 and 15.93 over the 5 and 15 minutes before; labs/ch28/measured-straylight-loaded.txt), put the boot point at N = 32 and the restore point at N = 32; this run, which began at 1.83 (1 minute), 3.32 and 7.49 over 5 and 15 minutes, puts them at N = 128 and N = 64. The chapter does not explain the point by the host’s thread count. talos, a quiet machine with eight threads, doubles at N = 16 (exercise (a)), twice its threads, while straylight’s 32 threads gave N = 32 in one run and N = 128 in the other. The file records /proc/loadavg before every series and every N; its 1-minute figure at a series’ start is mostly the script’s own previous batch, and the runnable-task count that follows it (the fourth field) is 1 to 5 at every start except the quiet set’s (26 runnable at that instant, with the same last process ID as the previous sample; the file shows no cause), so the host was otherwise quiet when each series began. The slowest guest of each batch is further out than the median (782.9 ms at N = 64 and 1607.9 ms at N = 128), because the last guests started find the others in the way. A boot is CPU work for wick (its CPU time is within a few milliseconds of its wall time, below), so the guests must queue for hardware threads sooner or later; where, here, was not predictable from the thread count.

What a restore saves, and what it costs

Chapter 27 made a guest again from two files. The saving is the guest kernel’s start: where a boot costs 283.6 ms (and 148.2 ms with quiet), a restore’s PUT /snapshot/load returns after 42.2 ms (min 39.9, max 45.5; section “restore of chapter 27’s snapshot”, from just before wick ctl starts until it returns, so it includes starting wick ctl), and the guest is running again when it does. The memory file is 134,217,728 bytes and the call reads all of it into the guest’s RAM before it resumes the guest (read_exact_volatile_from in snapshot/mod.rs; chapter 27): the load call is that read plus the state ioctls of chapter 27, and this measurement does not split the two.

One column of the file needs its explanation. The natural measurement of a restore is the time to the first tick, and that is not the restore’s cost. The snapshot is taken while the guest sleeps in the sleep 1 after tick 2, so the first thing a restored guest prints, tick 3, comes when what remains of that second ends: load_to_first_tick is 1046.8 ms (min 1044.5, max 1049.8). That is the guest’s own sleep and not the restore’s cost; it is in the file, and the restore’s figures in the chapter are the load call’s.

And the cost. A booted guest touches 25,312 KiB of its RAM; a restored guest has all of it: guest_ram_rss 131,072 KiB, VmHWM 133,528 KiB, memory.peak 133,014 KiB, against 27,656 and 27,208 for a boot. The file is read into every page, zero pages included. A restore trades the kernel’s start for memory, about 5 times the memory of a boot, and the memory is private to the guest like a booted guest’s. Firecracker does not pay it:

// firecracker v1.15.1, docs/snapshotting/snapshot-support.md:70-85
snapshot results in multiple files that are composing the full microVM snapshot:

- the guest memory file,
- the microVM state file,
- zero or more disk files (depending on how many the guest had; these are
  **managed by the users**).

The design allows sharing of memory pages and read only disks between multiple
microVMs. When loading a snapshot, instead of loading at resume time the full
contents from file to memory, Firecracker creates a
[MAP_PRIVATE mapping](http://man7.org/linux/man-pages/man2/mmap.2.html) of the
memory file, resulting in runtime on-demand loading of memory pages. Any
subsequent memory writes go to a copy-on-write anonymous memory mapping. This
has the advantage of very fast snapshot loading times, but comes with the cost
of having to keep the guest memory file around for the entire lifetime of the
resumed microVM.

A MAP_PRIVATE file mapping has three effects wick’s read does not. The call returns in a time that does not grow with the guest’s RAM, because nothing is read until it is touched. The pages the guest only reads are the page cache’s, shared by every guest restored from the same file; only the pages a guest writes are its own, copies. And the guest pays at first touch, a page fault and a read for each page. A second way to take that fault is to answer it in userspace. userfaultfd lets a process register a range of its memory and be told of each fault in it:

// linux v7.2.8, Documentation/admin-guide/mm/userfaultfd.rst:8-10
Userfaults allow the implementation of on-demand paging from userland
and more generally they allow userland to take control of various
memory page faults, something otherwise only the kernel code could do.

and Firecracker lets a snapshot be loaded that way, “having a dedicated userspace process for dealing with page faults” (docs/snapshotting/handling-page-faults-on-snapshot-resume.md:3-6), with /dev/userfaultfd and its file permissions for the descriptor (the same file, “Kernel 6.1”). The kernel’s own page says who may do what: any user may create a userfaultfd that traps userspace faults only, but “to also trap kernel page faults for the address space, either the process needs the CAP_SYS_PTRACE capability, or the system must have vm.unprivileged_userfaultfd set to 1. By default, vm.unprivileged_userfaultfd is set to 0”, or the process needs access to /dev/userfaultfd (userfaultfd.rst:63-80; whether KVM’s own accesses to guest RAM count as kernel faults is not in these pages, and Firecracker’s page opens /dev/userfaultfd for its handler). wick names it and refuses it, for three reasons that this chapter’s measurements and chapter 26 put side by side: a handler is a second thread or process that holds a descriptor to the guest’s RAM and answers every fault the guest takes; the host may need a privilege the book’s labs have never asked for (a file’s permission, or a sysctl, by the pages above); and the eager read costs a load call of 42.2 ms for 128 MiB on this host, which is small beside a boot’s 283.6 ms. What MAP_PRIVATE would buy is memory shared among guests restored from one file, which the memory column of the figure shows wick does not have.

Restores are also what parallel density is made of, and they bound differently. N restores at once read the same file N times into N private copies. The first N whose median load call is at least twice N = 1’s is 64: 149.6 ms against 48.7 ms at N = 1 (section “parallel restores”; N = 32 is 80.2 ms). Each restore moves 128 MiB from the page cache into the guest’s RAM, which is memory bandwidth, page faults for the new pages and CPU time to copy, and N restores move N times that: at N = 64 that is 8.0 GiB written into guests that print nothing for the next second. Which of those binds was not separated by this measurement. A restore’s doubling point (N = 64) comes earlier than the boots’ by the stop rule (N = 128) and level with the faster group of boots; a restore is cheaper in time for one guest (42.2 ms solo, 48.7 ms as the N = 1 batch, against a boot’s 283.6 or 308.3) and dearer in RAM for every guest. The solo and the N = 1 batch are the same operation measured two ways (the solo restore runs inside a systemd-run scope, the batch’s does not) and differ by 6.5 ms, which was not attributed. In the earlier, loaded run the solo restores fell into two groups, six near 55 ms, one at 77.9 ms and thirteen at 86 to 92.6 ms, with a median of 88.7 ms in the upper group (measured-straylight-loaded.txt); this run’s 20 values are one group.

Measuring without fooling yourself

A density number can be wrong in five ways, and the script closes four. One run: it takes 20 after a warm-up run it throws away, and reports the median with the minimum and the maximum, because a mean is dragged by the one boot that lost a CPU to something else. The wrong clock: every figure is a difference of two CLOCK_MONOTONIC readings in microseconds, taken by the same small program, stamp, which also prefixes each line of a guest’s console with the clock when the line arrived. A cold cache against a warm one: the page cache here is warm, the kernel image and the initramfs are in it after the first boot, and a cold cache needs privilege to drop and was not measured. Measuring the measurement: the script’s own cost is in the file: stamp_cost_us, 575 µs for two back-to-back stamp --now on this host (so one costs about half of that), which is what taking the start time after the ctl call returns adds to a boot’s start; and a boot’s figure begins when PUT /actions has returned and ends when the line === lab begin arrives, which is a few milliseconds after the kernel starts /init, because init mounts two file systems and runs dmesg first. Firecracker’s own measurement ends “at the start of the Linux guest user-space /sbin/init”, and the paper’s “when VMM process is forked and the guest kernel forks its init process” (section 5.1): neither is ours, and a comparison with their numbers is one of kind and not of digits. The fifth, the host, is the one the script cannot close, and it records what it can: /proc/loadavg before every series and every N, and the run began at a load average of 1.83 (1 minute), 3.32 and 7.49 over 5 and 15 minutes; the figure at the end of the run (53.70, 1 minute) is the run’s own 128 Firecracker guests and says nothing about neighbours. The CPU governor is powersave. A rerun can differ by the spread the file prints, and on this host it did (the Mechanism).

What the guest’s kernel configuration does to a boot is part of the measurement and not an afterthought. The same tinyconfig kernel, with the console quieted, boots in 148.2 ms where it took 283.6 ms; the same kernel with CONFIG_SMP built in and one vCPU boots about 15 to 24 ms slower, group for group (the group-by-group comparison in the last subsection of the second-vCPU discussion); a kernel with ACPI and PCI would add what it probes. A boot time quoted without its kernel and its command line is a number about nothing.

Firecracker, on the same guest

Firecracker v1.15.1 boots chapter 24’s guest, and the script measures it the way it measures wick. What is the same: the kernel build (chapter 24’s, as the bzImage wick loads and as the ELF vmlinux of the same build that Firecracker loads, 13,511,504 bytes), the initramfs, mem_size_mib 128, one vCPU, the serial console only, no network, no privilege, and the timing: the start time is taken when PUT /actions returns and the end is the line === lab begin reaching stamp, with wick ctl as the client for both. The version is the one the part is pinned to: nix build nixpkgs#firecracker --no-link --print-out-paths on straylight gave a store path whose bin/firecracker --version printed Firecracker v1.15.1, from the NixOS system’s own nixpkgs (/nix/store/fdqp78hgcxlr0a1ijxbn5mdma20zwj54-aw8r21zg20rp9g70m9w198b2l6dwl7iy-source, 26.05.20260914.c3eea5b (Yarara); nixos-version --json on straylight, 2026-10-04 UTC, printed "nixpkgsRevision":"c3eea5b2156db11c7eeeada3dc737711255b253e", and the script now records that output, which the committed file predates); the script refuses any other version. It booted on the first attempt, and no second attempt was made.

What differs, and each difference favours one side or the other. wick enters the bzImage and its decompression stub runs inside the measured time (chapter 24); Firecracker loads the uncompressed vmlinux, so the decompression is not in its figure. The command lines differ: chapter 24’s console=ttyS0 reboot=t panic=-1 rdinit=/init for wick, and console=ttyS0 reboot=k panic=1 rdinit=/init for Firecracker, which also inserts pci=off (src/vmm/src/builder.rs:205-208). And Firecracker reaches this kernel, which has no ACPI, through its MP-table path, the one its own changelog deprecated in 1.8.0: “Booting with microVM kernels that rely on MPTable on x86_64 is deprecated and support will be removed in v2.0 or later” (CHANGELOG.md:517-518); the guest’s log under Firecracker shows the kernel finding that table (the second-vCPU discussion quotes it).

The numbers, straylight, 2026-10-04 UTC, from the file’s sections “boot, chapter 24’s arguments” and “boot, Firecracker”: to the sentinel wick takes 283.6 ms (min 218.8, max 322.4) and Firecracker 436.5 ms (min 374.8, max 443.1); with quiet, 148.2 and 314.0 ms. The CPU time each used by then, from the process’s utime plus stime: wick 285.0 ms, Firecracker 180.0 ms, and with quiet 150.0 and 60.0 ms. The utime plus stime figures are in clock ticks of 10 ms, so they can show a difference of tens of milliseconds and not of a few; the cgroup’s cpu.stat is in microseconds (289.0 ms for wick). A wick boot is CPU from start to sentinel (wall 283.6 ms, CPU 289.0 ms by the cgroup and 285.0 ms by the process, equal within that resolution); a Firecracker boot is mostly idle, 256 ms of its 436.5 ms with the console on and 254 ms of its 314.0 ms with quiet. The chapter does not attribute that idle time. Firecracker’s parallel curve is flatter than wick’s, not flat: its medians are 1.27, 1.59 and 2.06 times its N = 1 value at N = 32, 64 and 128, wick’s 1.13, 1.97 and 3.78 times its own (against N = 1’s median of 308.3 ms, a value of the slower group), and by the same rule Firecracker doubles too, at N = 128 (897.1 ms against 435.1 ms). Guests that mostly wait may queue for CPUs later, but the chapter does not claim the idle time is the cause, and a flatter curve is not evidence of a cheaper boot. Firecracker’s own figures are 125 ms and 5 MiB, measured with the console off and its tuned kernel (SPECIFICATION.md:24-42); this is neither.

Memory: Firecracker’s process peaks at 28,420 KiB (VmHWM) with 23,364 KiB anonymous and 5,056 KiB file-backed, against wick’s 27,656, 25,596 and 2,060. Firecracker’s 5 MiB is the VMM’s threads, the overhead without the guest’s touched RAM, which this chapter’s bar splits out: VmHWM minus the guest’s touched RAM is 5,520 KiB for Firecracker and 2,344 KiB for wick here, and the guest’s own kernel differs in what it touches (22,900 against 25,312 KiB). The chapter does not attribute the difference in boot time; it is two programs, a decompressor and a command line apart, on one host.

The devices wick refuses

Seven things a general-purpose VMM offers are absent from wick, and each absence is a decision with a cost on three axes: the code in the VMM that the guest can reach, the state a snapshot would have to carry, and what the host has to give the VMM. Each entry below says what the thing is, what it would cost wick, and why hearth does not want it. The sources are the kernel’s documentation at the pinned tag, Firecracker at v1.15.1, Cloud Hypervisor’s documentation at v53.0 (the VMM that kept devices Firecracker dropped, the one chapter 23 compared) and QEMU’s.

GPU and VFIO passthrough. VFIO is the kernel’s framework for giving a userspace process direct access to a physical device, behind the IOMMU: “an IOMMU/device agnostic framework for exposing direct device access to userspace, in a secure, IOMMU protected environment” (Documentation/driver-api/vfio.rst:9-12). A passthrough GPU is a PCI device handed to a guest this way. It is a different VMM from wick, for reasons the sources give. The unit of ownership is not a device but an IOMMU group: “A group is a set of devices which is isolatable from all other devices in the system. Groups are therefore the unit of ownership used by VFIO” (vfio.rst, the section “Groups, Devices, and IOMMUs”), and Cloud Hypervisor’s guide says what that means for a graphics card, which shares its group with its audio function: “it is important to bind both devices to VFIO and pass them both through the VM, otherwise this could cause some functional and security issues” (docs/vfio.md:123-125). The device must first be taken away from its host driver (“a device must be unbound from its native driver before passing it to cloud-hypervisor”, the same file’s opening). The device DMAs into guest memory, so the guest’s memory has to be mapped for the device and pinned: the type 1 IOMMU driver pins the pages and charges them against the process’s locked-memory limit, and refuses past it unless the process holds CAP_IPC_LOCK:

// linux v7.2.8, drivers/vfio/vfio_iommu_type1.c:767-776
            if (acct_pages) {
                if (!dma->lock_cap &&
                    mm->locked_vm + lock_acct + acct_pages > limit) {
                    pr_warn("%s: RLIMIT_MEMLOCK (%ld) exceeded\n",
                        __func__, limit << PAGE_SHIFT);
                    ret = -ENOMEM;
                    goto unpin_out;
                }
                lock_acct += acct_pages;
            }

A pinned page cannot be paged out or moved while the device may write it, so the guest’s RAM is resident for the guest’s whole life: the zero-on-demand mapping of the memory paragraph above is gone, and with it overcommit (a consequence of pinning; the sources above give the pin and the limit, not that sentence). And the device’s own state is in hardware: Cloud Hypervisor snapshots a VFIO device only if it “advertise[s] the kernel VFIO migration v2 protocol”, and “The generic vfio_pci driver does not implement migration and is treated as non migratable” (docs/vfio.md:200-212), so a guest with a GPU has no chapter 27. For wick it would take a PCI bus (it has none: its devices are virtio-mmio windows), MSI interrupt routing, mapping the device’s registers into the guest, the IOMMU mapping and the pinning of all guest RAM, a host administrator who binds the device, and a limit or a capability the book’s unprivileged labs never needed. For hearth: a type-1 that wants a GPU is a passthrough machine, not this book.

vhost-user. In vhost-user, the device’s virtqueues are served not by the VMM but by another process on the host, the back-end, which the VMM, the front-end, connects to over a Unix socket: “the control plane needed to establish virtqueue sharing with a user space process on the same host. It uses communication over a Unix domain socket to share file descriptors in the ancillary data of the message” (QEMU docs/interop/vhost-user.rst at v10.1.0, lines 19-24), and the platform needs “a way for requesting shared memory represented by a file descriptor so it can be passed over a UNIX domain socket and then mapped by the other process” (lines 47-49 of the same file). That sentence is the cost to wick: its guest RAM is an anonymous private mapping, which no other process can map; a vhost-user device would need the RAM as a memfd or file mapped shared, and then the snapshot and restore of chapter 27, and the page-sharing of the section above, work on a different kind of memory. Cloud Hypervisor’s local live-migration example starts its source VM with --memory size=1G,shared=on (docs/live_migration.md:21), the same kind of memory. The second cost is the trusted base. A back-end sees the guest’s rings and the guest’s data buffers, in a process of its own that Firecracker’s design page says the customer provides: “For vhost-user devices, customers should implement rate limiting on the side of the vhost-user backend that they provide” (docs/design.md:138-140). Cloud Hypervisor has gone so far as a generic front-end: “Cloud Hypervisor deliberately does not have support for all types of virtio devices”, so that a back-end it knows nothing of can serve almost any device type (docs/generic-vhost-user.md:5-10). For hearth, a second process in the trusted base is the thing a type-1 with no host kernel does not have to run.

Hotplug. Chapter 23 met this one; hotplug is adding a vCPU, memory or a device to a running guest. Cloud Hypervisor supports “hot plugging of CPUs devices (x86 only), PCI devices and memory resizing”, and what it needs from the guest is the first thing wick does not have: “For hotplug on Cloud Hypervisor ACPI GED support is needed”, the ACPI generic event device, which tells the guest that something changed (docs/hotplug.md:3-7). For a vCPU the sequence is as above and then some: “The extra vCPU threads will be created and advertised to the running kernel. The kernel does not bring up the CPUs immediately and instead the user must ‘online’ them from inside the VM” (the same file). Firecracker’s memory hotplug is a virtio device, virtio-mem, with a guest driver (“CONFIG_VIRTIO_MEM needs to be enabled in the guest kernel”), and slots “that can be fully protected from guest accesses to prevent malicious guests from accessing the hotpluggable memory range when not allowed by the host” (docs/memory-hotplug.md:16-19 and :38-39). For wick it would take ACPI tables (it writes none), the second vCPU of the next subsection, and a device with a guest driver; and a guest that is created for one function call does not grow. For hearth, a guest’s memory and CPU are given when the guest is created.

Live migration. Live migration moves a running guest to another host with only a short pause. It needs three things wick lacks. The first is dirty tracking, a way to find the pages the guest wrote while they were being copied: KVM’s is KVM_MEM_LOG_DIRTY_PAGES on the memory slot (“to instruct KVM to keep track of writes to memory within the slot”, api.rst:1413-1416) and then KVM_GET_DIRTY_LOG, “return a bitmap containing any pages dirtied since the last call to this ioctl” (api.rst:354-392); wick sets the slot’s flags to 0 (vm.rs). The second is pre-copy: copy all memory while the guest runs, then the pages dirtied meanwhile, again and again, until the remainder is small enough to send in a pause whose length Cloud Hypervisor takes as a parameter, downtime_ms, “the maximum downtime the migration aims for, in milliseconds”, default 300 ms, with a postcopy mode that “resumes the destination first and faults guest pages in on demand over a dedicated connection” (docs/live_migration.md:366-383). The third is a wire protocol: the two VMMs speak a versioned one, whose messages start with a Start request that carries the version, accepted “plus the immediately previous protocol version” (the same file, “Version Compatibility”), over a socket or TCP with optional TLS. Chapter 27’s snapshot is the state half of a migration with the copy replaced by a file, which is as far as wick goes. For hearth: a type-1 with no network stack has no wire to speak on, and nothing in the guest contract of chapter 32 describes a second host.

The balloon. Chapter 23 quoted this page too; a balloon is how a host takes memory back from a running guest. Firecracker’s page: “A memory balloon device is a virtio device that can be used to reclaim and give back guest memory through API commands issued by the host. It does this by allocating memory in the guest, and then sending the addresses of that memory to the host; the host may then remove that memory at will” (docs/ballooning.md:5-8), with a warning that decides its place here (lines 56-57): “The balloon device is a paravirtualized virtio device that requires cooperation from a driver in the guest”. It is a density tool, a way to overcommit, and it works only on guests that cooperate. For wick it would take a virtio device of type 5 (virtio 1.2 section 5.5, p. 109-110: queues inflateq and deflateq, and statsq, free_page_vq and reporting_vq that exist only if a feature is negotiated), a driver in the guest, and a host-side removal of the pages the guest hands back from the guest’s mapping. wick’s answer to the same problem is smaller: the guest’s RAM costs what it touches, and a function-sized guest ends and returns all of it. For hearth, which gives a guest its memory when it creates the guest, a balloon is a negotiation with the guest that the hypervisor has no use for.

The metadata service (MMDS). Firecracker’s microVM metadata service lets a guest read configuration the host holds, over the network, from an address the VMM answers. “MMDS consists of three major logical components: the backend, the data store, and the minimalist HTTP/TCP/IPv4 stack (named Dumbo). They all exist within the Firecracker process, and outside the KVM boundary” (docs/mmds/mmds-design.md:3-5). A TCP and HTTP implementation inside the VMM, parsing frames the guest builds, is the trusted-base cost in one sentence. wick has the same capability by a smaller road: chapter 25’s vsock, over which a host process can hand a guest anything it wants, with the parsing in the host process that chose to listen. For hearth, a guest’s configuration is the boot-information block of chapter 32.

Rate limiters. A rate limiter caps what a guest’s device can do per second. Firecracker’s page: “the application of rate limiters to each volume and network interface to make sure host hardware resources are used fairly by multiple microVMs. These are implemented using a token bucket algorithm based on two buckets. One is associated with the number of operations per second and the other one with the bandwidth” (docs/design.md:129-134); the paper adds that “These rate limiters allow limits to be set on operations per second (IOPS for disk, packets per second for network) and on bandwidth for each device attached to each MicroVM” (section 3.3). It is a fairness tool for many guests on one host, which is this chapter’s subject, and it lives in the device model: each virtio device carries two buckets and a timer. wick has host-side limits instead, the ones chapter 26’s jail lets a cgroup apply from outside: Firecracker’s own design page says the same of CPU, “each Firecracker microVM can have its own dedicated quota of the CPU time via the cpu subsystem” (docs/design.md:184-190). For hearth, which has no host cgroups, how guests share a CPU is the hypervisor’s own policy and not a device to build.

The axes. The seven refusals are judged on the same three. Reachable code: vhost-user adds a second process to what the guest can attack, MMDS adds a TCP stack, passthrough adds a PCI bus and an IOMMU interface; the balloon, hotplug and rate limiters add device code that parses a guest’s writes. State: every device on the list is state a snapshot must carry or cannot (a passthrough device’s registers are in hardware), and a migration needs it as well, over a wire. Host: passthrough needs a bound device and locked memory, hotplug an ACPI event device, userfaultfd a permission, vhost-user shareable memory. A device that costs on all three, such as passthrough, is not a feature to add to wick; it is a different program, and what that program is called, in this book, is not wick.

The second vCPU wick refuses

PUT /machine-config with a vcpu_count other than 1 is a 400:

ctl: PUT /machine-config 400
{"fault_message":"vcpu_count 2 is not supported: wick runs one vCPU, so vcpu_count must be 1"}

(wick/src/vmm.rs, the PutMachineConfig arm; the lines above are wick ctl against a fresh wick on talos, 2026-10-04 UTC.) The refusal is a decision with reasons the last subsection gives. This one is the discussion of what accepting the request would take, and no code for it exists: the boot code maps one vCPU, sets no table that names a second, and the snapshot code saves one, so a vcpu_count of 2 would be a promise nothing tests. Every claim below carries its source, and where a source is the machine itself the run is named.

How a kernel finds its other processors

A guest kernel is started on one processor, the boot processor or BSP in x86 terms, and has to be told that others exist. Chapter 24’s guest says what it found, in its boot log (the guest’s init runs dmesg -n 1 only after the kernel has printed its early lines, so they are in the console output, between Linux version and === lab begin):

APIC: ACPI MADT or MP tables are not detected

That line is in the log of every chapter 24 boot (straylight, 2026-10-04 UTC, labs/ch28/measured-straylight.txt, the section “kernel log lines about processors and tables”, and grep -h 'MADT' labs/ch28/out/g/1/console.txt after make lab CH=28 on talos, 2026-10-04 UTC). The kernel prints it from the function that chooses how the boot processor will take interrupts:

// linux v7.2.8, arch/x86/kernel/apic/apic.c:1286-1292
    /* Check MP table or ACPI MADT configuration */
    if (!smp_found_config) {
        disable_ioapic_support();
        if (!acpi_lapic) {
            pr_info("APIC: ACPI MADT or MP tables are not detected\n");
            return APIC_VIRTUAL_WIRE_NO_CONFIG;
        }

Two kinds of table can set the variables the test reads. smp_found_config is set when the kernel finds an MP table (the older table chapter 23 named), the structure the Intel MultiProcessor Specification, version 1.4 (May 1997), defined for the first multiprocessor PCs; and an ACPI MADT (Multiple APIC Description Table), the part of ACPI that lists the local APICs and I/O APICs, sets acpi_lapic and smp_found_config both when the kernel parses it (arch/x86/kernel/acpi/boot.c:1261-1270). Neither is a configuration file the kernel reads from disk: each is a block of bytes that firmware, or here the VMM, left in memory, and the kernel finds the MP table by searching for a signature and the MADT through a pointer to ACPI’s root table. For the MP table the kernel searches, in this order, the bottom kilobyte of memory, the last kilobyte of base RAM, the 64 KiB of BIOS ROM, and then the Extended BIOS Data Area, whose segment it reads from the BIOS data area at 0x40E (arch/x86/kernel/mpparse.c:600-635). The first three are in the function’s own comment, and the fourth follows them:

// linux v7.2.8, arch/x86/kernel/mpparse.c:600-615
void __init mpparse_find_mptable(void)
{
    unsigned int address;

    /*
     * FIXME: Linux assumes you have 640K of base ram..
     * this continues the error...
     *
     * 1) Scan the bottom 1K for a signature
     * 2) Scan the top 1K of base RAM
     * 3) Scan the 64K of bios
     */
    if (smp_scan_config(0x0, 0x400) ||
        smp_scan_config(639 * 0x400, 0x400) ||
        smp_scan_config(0xF0000, 0x10000))
        return;

and what it looks for at each 16-byte step is the specification’s floating pointer structure:

// linux v7.2.8, arch/x86/kernel/mpparse.c:566-581
    while (length > 0) {
        bp = early_memremap(base, length);
        mpf = (struct mpf_intel *)bp;
        if ((*bp == SMP_MAGIC_IDENT) &&
            (mpf->length == 1) &&
            !mpf_checksum((unsigned char *)bp, 16) &&
            ((mpf->specification == 1)
             || (mpf->specification == 4))) {
#ifdef CONFIG_X86_LOCAL_APIC
            smp_found_config = 1;
#endif
            mpf_base = base;
            mpf_found = true;

            pr_info("found SMP MP-table at [mem %#010lx-%#010lx]\n",
                base, base + sizeof(*mpf) - 1);

The specification’s text for the structure is Table 4-1 (p. 4-3 and 4-4): a 16-byte structure on a 16-byte boundary whose first four bytes are the ASCII string _MP_, “serves as a search key”, followed by the physical address of the MP configuration table, a length in 16-byte units (1), a revision (04h for version 1.4), a checksum over all 16 bytes that makes them add up to zero, and feature bytes. The specification lists where it may be: “In the first kilobyte of Extended BIOS Data Area (EBDA)”, or “Within the last kilobyte of system base memory (e.g., 639K-640K for systems with 640 KB of base memory ...) if the EBDA segment is undefined”, or “In the BIOS ROM address space between 0F0000h and 0FFFFFh” (chapter 4, p. 4-2). The kernel’s scans cover those places (its first is the bottom kilobyte, which the specification does not list, and its EBDA scan comes last, mpparse.c:616-635). The configuration table behind the pointer is a header (Table 4-2, p. 4-5 and 4-6) and then entries (section 4.3), one for each kind of thing the kernel has to know: a processor entry for each CPU, with its local APIC ID, a flag that says it is usable and one that marks the bootstrap processor (section 4.3.1, Table 4-4); bus entries; I/O APIC entries; I/O interrupt assignment entries, “one entry per bus interrupt source”; and local interrupt assignment entries (sections 4.3.2 to 4.3.5). The one rule the specification puts on the APIC IDs of the processors is that they be unique: “They do not need to be consecutive” (section 4.3.1, p. 4-7).

Firecracker writes exactly this. setup_mptable at v1.15.1 takes the number of vCPUs, computes the size, and lays the structures out in the order above; the size function is the layout in one expression:

// firecracker v1.15.1, src/vmm/src/arch/x86_64/mptable.rs:106-114
fn compute_mp_size(num_cpus: u8) -> usize {
    mem::size_of::<mpspec::mpf_intel>()
        + mem::size_of::<mpspec::mpc_table>()
        + mem::size_of::<mpspec::mpc_cpu>() * (num_cpus as usize)
        + mem::size_of::<mpspec::mpc_ioapic>()
        + mem::size_of::<mpspec::mpc_bus>()
        + mem::size_of::<mpspec::mpc_intsrc>() * (GSI_LEGACY_END as usize + 1)
        + mem::size_of::<mpspec::mpc_lintsrc>() * 2
}

The floating pointer comes first, with physptr pointing at the byte after itself and the checksum computed over the 16 bytes; then one processor entry per vCPU, whose APIC ID is the vCPU’s index and whose flags mark vCPU 0 as the boot processor:

// firecracker v1.15.1, src/vmm/src/arch/x86_64/mptable.rs:156-165
        let mut mpf_intel = mpspec::mpf_intel {
            signature: SMP_MAGIC_IDENT,
            physptr: u32::try_from(base_mp.raw_value() + size).unwrap(),
            length: 1,
            specification: 4,
            ..mpspec::mpf_intel::default()
        };
        mpf_intel.checksum = mpf_intel_compute_checksum(&mpf_intel);
        mem.write_obj(mpf_intel, base_mp)
            .map_err(|_| MptableError::WriteMpfIntel)?;
// firecracker v1.15.1, src/vmm/src/arch/x86_64/mptable.rs:176-191
        let size = mem::size_of::<mpspec::mpc_cpu>() as u64;
        for cpu_id in 0..num_cpus {
            let mpc_cpu = mpspec::mpc_cpu {
                type_: mpspec::MP_PROCESSOR.try_into().unwrap(),
                apicid: cpu_id,
                apicver: APIC_VERSION,
                cpuflag: u8::try_from(mpspec::CPU_ENABLED).unwrap()
                    | if cpu_id == 0 {
                        u8::try_from(mpspec::CPU_BOOTPROCESSOR).unwrap()
                    } else {
                        0
                    },
                cpufeature: CPU_STEPPING,
                featureflag: CPU_FEATURE_APIC | CPU_FEATURE_FPU,
                ..Default::default()
            };

After the processors come the ISA bus, the I/O APIC (whose APIC ID is num_cpus + 1, line 139: the table’s ID space is the processors’ IDs and then the I/O APIC’s), one interrupt entry for each of the 24 legacy interrupt lines (GSI_LEGACY_END is 23, layout.rs:30), each routed to that I/O APIC, and the two local interrupt entries, ExtINT and NMI. The whole table is one block, 284 bytes plus 20 for each vCPU (the comment in layout.rs:87-88 says “284 + 20 * #vCPUS” and the size function above gives the same: 16+44+8+8+24×8+2×8=28416 + 44 + 8 + 8 + 24 \times 8 + 2 \times 8 = 284), and where it goes is a constant:

// firecracker v1.15.1, src/vmm/src/arch/x86_64/layout.rs:66-68
/// Start of memory region we will use for system data (MPTable, ACPI, etc). We are putting its
/// start address where EBDA normally starts, i.e. in the last 1 KiB of the first 640KiB of memory
pub const SYSTEM_MEM_START: u64 = 0x9fc00;

0x9fc00 is 639 * 0x400, the kernel’s second scan. The setup function says so where it is called (arch/x86_64/mod.rs:218: “Note that this puts the mptable at the last 1k of Linux’s 640k base RAM”), and the VMM tells the kernel not to use the bytes: the E820 map marks [0, 0x9fc00) as RAM and [0x9fc00, 0xe0000) as reserved (arch/x86_64/mod.rs:373-381; chapter 24’s E820, which wick builds, has 0 to 0x9fc00 as RAM and nothing reserved above it). The result is observable. Chapter 24’s kernel, the same vmlinux, started under Firecracker v1.15.1 on straylight (labs/ch28/measure.sh, 2026-10-04 UTC; the file’s section “kernel log lines about processors and tables: Firecracker”) prints, where under wick it printed the line above:

found SMP MP-table at [mem 0x0009fc00-0x0009fc0f]
Intel MultiProcessor Specification v1.4
MPTABLE: OEM ID: FC      
MPTABLE: Product ID: 000000000000
MPTABLE: APIC at: 0xFEE00000
Processor #0 (Bootup-CPU)
IOAPIC[0]: apic_id 2, version 17, address 0xfec00000, GSI 0-23
Processors: 1

(the specification line, the OEM ID, the product ID and the APIC address are printed twice, once from each of the kernel’s two passes over the table, the early one and the full one, mpparse_get_smp_config(true) and (false) at arch/x86/kernel/mpparse.c:477-540 and :542-550; the file has both). The OEM ID is Firecracker’s FC, the one processor is the boot processor, and the I/O APIC’s ID is 2, which is num_cpus + 1 for one CPU: the constants of setup_mptable seen from the guest. Since Firecracker 1.8.0 it also writes ACPI tables beside this one, CHANGELOG.md lines 468 to 472: “Added ACPI support to Firecracker for x86_64 microVMs. Currently, we pass ACPI tables with information about the available vCPUs, interrupt controllers, VirtIO and legacy x86 devices to the guest.” The MADT’s body is built by two lines of src/vmm/src/acpi/x86_64.rs: an I/O APIC with ID 0, and then one LocalAPIC::new(i) for each vCPU (lines 20 to 23). A kernel built with ACPI reads those, and the MP table is, since 1.8.0, the deprecated way (CHANGELOG.md:517-521: “Booting with microVM kernels that rely on MPTable on x86_64 is deprecated and support will be removed in v2.0 or later”). The book’s tinyconfig kernel has no ACPI, and Firecracker boots it by the older table: the sentences above are the log of that boot.

On RISC-V the list of processors is a node of the device tree, and a VMM that wants a second hart adds a second child to it. QEMU’s virt machine shows it: qemu-system-riscv64 -machine virt,dumpdtb=virt-smp2.dtb -smp 2 -m 128M -bios none, then dtc -I dtb -O dts virt-smp2.dtb (QEMU 11.1.1, talos, 2026-10-04 UTC), shows a cpus node with one cpu@N child for each hart:

cpus {
    #address-cells = <0x01>;
    #size-cells = <0x00>;
    timebase-frequency = <0x989680>;

    cpu@0 {
        phandle = <0x03>;
        device_type = "cpu";
        reg = <0x00>;
        status = "okay";
        compatible = "riscv";
        mmu-type = "riscv,sv57";
        ...
    };

    cpu@1 {
        phandle = <0x01>;
        device_type = "cpu";
        reg = <0x01>;
        status = "okay";
        compatible = "riscv";
        mmu-type = "riscv,sv57";
        ...
    };

(the riscv, property lines of each node are omitted, and the node’s interrupt-controller child.) reg is the hart’s ID, status = "okay" the “usable” flag. There is no signature to search for, no checksum and no table to forge. The device tree is the one description of the machine the board hands the kernel, the one chapter 2 showed ember receiving in a1, and the one hearth as metal consumes. x86 has two descriptions of the same fact, an old one in a fixed corner of low memory and a newer one the firmware points at; RISC-V has the one.

How the others start

The kernel now knows that a second processor exists. It is not running. On x86 an application processor, an AP, is a CPU that is not the boot processor, and it stays halted after reset until the boot processor wakes it with an inter-processor interrupt, an IPI: a message sent through the local APIC’s interrupt command register that raises an interrupt, or a startup signal, on another CPU’s local APIC. Two IPIs start an AP. The specification’s “universal start-up algorithm” is the sequence, Appendix B.4, Example B-1 (p. B-3 to B-5):

BSP sends AP an INIT IPI
BSP DELAYs (10mSec)
If (APIC_VERSION is not an 82489DX) {
    BSP sends AP a STARTUP IPI
    BSP DELAYs ( 200µSEC)
    BSP sends AP a STARTUP IPI
    BSP DELAYs ( 200µSEC)
}
BSP verifies synchronization with executing AP

The INIT IPI resets the target to its power-on state. The STARTUP IPI, SIPI, gives it an address: “The STARTUP IPI causes the target processor to start executing in Real Mode from address 000VV000h, where VV is an 8-bit vector that is part of the IPI message”, “issued only one time after RESET or after an INIT IPI reception” (B.4.2). The sequence is INIT, then two STARTUP IPIs, and the book’s shorthand for it is INIT-SIPI-SIPI. The AP begins in 16-bit real mode at an address in the first megabyte, and the kernel’s startup code for it says so in its first comment: “On entry to trampoline_start, the processor is in real mode with 16-bit addressing and 16-bit data” (arch/x86/realmode/rm/trampoline_64.S:14-15). The AP has to climb from real mode to long mode, by code of the kernel’s own, before it runs anything else; chapter 24’s setup_long_mode set up the boot vCPU’s registers directly in long mode, which is a VMM’s privilege and not an AP’s.

With the in-kernel interrupt controller chapter 24 created (KVM_CREATE_IRQCHIP), KVM emulates the IPIs, and the VMM never sees them. A vCPU that is not the boot processor is born waiting:

// linux v7.2.8, arch/x86/kvm/x86.c:11971-11974
    if (!irqchip_in_kernel(vcpu->kvm) || kvm_vcpu_is_reset_bsp(vcpu))
        kvm_set_mp_state(vcpu, KVM_MP_STATE_RUNNABLE);
    else
        kvm_set_mp_state(vcpu, KVM_MP_STATE_UNINITIALIZED);

and which vCPU is the boot processor is a vCPU ID, vCPU 0 unless KVM_SET_BOOT_CPU_ID says otherwise (api.rst:1645-1660: “Define which vcpu is the Bootstrap Processor (BSP). ... If this ioctl is not called, the default is vcpu 0.”; x86.c:12443-12446, kvm_vcpu_is_reset_bsp, compares bsp_vcpu_id with vcpu_id). The documentation defines the state KVM_GET_MP_STATE reports, the multiprocessing state of chapter 27:

// linux v7.2.8, Documentation/virt/kvm/api.rst:1536-1541
   KVM_MP_STATE_RUNNABLE         the vcpu is currently running
                                 [x86,arm64,riscv,loongarch]
   KVM_MP_STATE_UNINITIALIZED    the vcpu is an application processor (AP)
                                 which has not yet received an INIT signal [x86]
   KVM_MP_STATE_INIT_RECEIVED    the vcpu has received an INIT signal, and is
                                 now ready for a SIPI [x86]

A VMM may call KVM_RUN on such a vCPU at once. The call blocks in the kernel until the vCPU is woken, and then returns:

// linux v7.2.8, arch/x86/kvm/x86.c:11517-11547
    if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
        if (!vcpu->wants_to_run) {
            r = -EINTR;
            goto out;
        }

        /*
         * Don't bother switching APIC timer emulation from the
         * hypervisor timer to the software timer, the only way for the
         * APIC timer to be active is if userspace stuffed vCPU state,
         * i.e. put the vCPU into a nonsensical state.  Only an INIT
         * will transition the vCPU out of UNINITIALIZED (without more
         * state stuffing from userspace), which will reset the local
         * APIC and thus cancel the timer or drop the IRQ (if the timer
         * already expired).
         */
        kvm_vcpu_srcu_read_unlock(vcpu);
        kvm_vcpu_block(vcpu);
        kvm_vcpu_srcu_read_lock(vcpu);

        if (kvm_apic_accept_events(vcpu) < 0) {
            r = 0;
            goto out;
        }
        r = -EAGAIN;
        if (signal_pending(current)) {
            r = -EINTR;
            kvm_run->exit_reason = KVM_EXIT_INTR;
            ++vcpu->stat.signal_exits;
        }
        goto out;

The comment says what ends the wait: “Only an INIT will transition the vCPU out of UNINITIALIZED”. When the wait ends, KVM accepts the pending events (that is where INIT and SIPI are processed) and the ioctl returns EAGAIN, or EINTR if a signal is pending. When the boot processor’s kernel writes the interrupt command register, KVM’s local APIC code does the processing:

// linux v7.2.8, arch/x86/kvm/lapic.c:3609-3624
        kvm_vcpu_reset(vcpu, true);
        if (kvm_vcpu_is_bsp(apic->vcpu))
            kvm_set_mp_state(vcpu, KVM_MP_STATE_RUNNABLE);
        else
            kvm_set_mp_state(vcpu, KVM_MP_STATE_INIT_RECEIVED);
    }
    if (test_and_clear_bit(KVM_APIC_SIPI, &apic->pending_events)) {
        if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
            /* evaluate pending_events before reading the vector */
            smp_rmb();
            sipi_vector = apic->sipi_vector;
            kvm_x86_call(vcpu_deliver_sipi_vector)(vcpu,
                                   sipi_vector);
            kvm_set_mp_state(vcpu, KVM_MP_STATE_RUNNABLE);
        }
    }

The INIT resets the vCPU (kvm_vcpu_reset), whatever registers the VMM had set, and leaves it in INIT_RECEIVED; the SIPI, if the vCPU is in that state, delivers the vector (the real-mode start address) and makes it RUNNABLE. The blocked KVM_RUN returns EAGAIN, as the quotation above shows, and the VMM’s loop calls it again; the second call enters the guest at the SIPI’s address. Firecracker’s loop treats EAGAIN as handled (src/vmm/src/vstate/vcpu.rs:493, libc::EAGAIN => Ok(VcpuEmulation::Handled)), and so does wick’s (wick/src/vcpu.rs:255: EINTR or EAGAIN clears the immediate-exit byte and looks at the stop flag again), so the VMM learns of the INIT and the SIPI only that a call returned. So a VMM that accepts vcpu_count: 2 creates the second vCPU with KVM_CREATE_VCPU, whose argument is the vCPU ID and, “on x86”, the APIC ID (api.rst:307-312, “Parameters: vcpu id (apic id on x86)”); gives it CPUID with its own APIC ID in the leaves that carry it; and starts a second thread that runs KVM_RUN in a loop, with no registers set, because INIT will discard them. That is the claim made from the kernel’s code. Firecracker does not take advantage of it: it calls configure on every vCPU, setting the boot registers on the APs too (arch/x86_64/mod.rs:198-202, the loop over vcpus), and the INIT then makes the work moot. It also does the part that cannot be left out, the CPUID. Chapter 24’s set_apic_id already gives the one vCPU its ID in leaf 0x1 (ebx bits 31 to 24), leaves 0xb and 0x1f (edx) and leaf 0x8000001e (eax), the leaves the documentation names (api.rst:9537-9549); Firecracker’s normalisation sets leaf 0x1 and leaf 0xb for each cpu_index and, on AMD, leaf 0x8000001e (cpu_config/x86_64/cpuid/amd/normalize.rs:334); it does not set leaf 0x1f. It adds the fields that tell the guest how many processors the package holds:

// firecracker v1.15.1, src/vmm/src/cpu_config/x86_64/cpuid/normalize.rs:221-239
        // Maximum number of addressable IDs for logical processors in this physical package.
        //
        // The nearest power-of-2 integer that is not smaller than EBX[23:16] is the number of
        // unique initial APIC IDs reserved for addressing different logical processors in a
        // physical package. This field is only valid if CPUID.1.EDX.HTT[bit 28]= 1.
        let max_cpus_per_package = u32::from(
            get_max_cpus_per_package(cpu_count)
                .map_err(FeatureInformationError::GetMaxCpusPerPackage)?,
        );
        set_range(&mut leaf_1.result.ebx, 16..=23, max_cpus_per_package)
            .map_err(FeatureInformationError::SetMaxCpusPerPackage)?;

        // CPUID.01H:EBX[31:24]
        // Initial APIC ID.
        //
        // The 8-bit initial APIC ID in EBX[31:24] is replaced by the 32-bit x2APIC ID, available
        // in Leaf 0BH and Leaf 1FH.
        set_range(&mut leaf_1.result.ebx, 24..=31, u32::from(cpu_index))
            .map_err(FeatureInformationError::InitialApicId)?;
// firecracker v1.15.1, src/vmm/src/cpu_config/x86_64/cpuid/normalize.rs:294-296
                // CPUID.(EAX=0BH,ECX=N).EDX[31:0]
                // x2APIC ID of the current logical processor.
                subleaf.result.edx = u32::from(cpu_index);

Leaf 0x1’s edx bit 28 (HTT) is set when there is more than one CPU (normalize.rs:254-260). On a second vCPU wick would call set_apic_id with 1 where it calls it with VCPU_ID, and set the package-size fields.

The RISC-V counterpart is the HSM extension of the supervisor binary interface (SBI), the firmware interface chapter 18 defined (the SBI, reached by ecall). Among its seven hart states (ext-hsm.adoc:15-41) are STARTED and STOPPED, and START_PENDING is “Some other hart has requested to start (or power-up) the hart from the STOPPED state”; the call that makes the request is:

// riscv-sbi-doc v3.0, src/ext-hsm.adoc:83-90
struct sbiret sbi_hart_start(unsigned long hartid,
                             unsigned long start_addr,
                             unsigned long opaque)
----

Request the SBI implementation to start executing the target hart in
supervisor-mode, at the address specified by `start_addr`, with the
specific register values described in <<table_hsm_hart_start_regs>>.

where the start state is satp 0 (MMU off), sstatus.SIE 0, a0 the hart ID and a1 the opaque argument: one call and an address, in place of two IPIs, a real-mode trampoline and a mode climb. KVM’s own RISC-V states are the same shape: “The only states that are valid are KVM_MP_STATE_STOPPED and KVM_MP_STATE_RUNNABLE which reflect if the vcpu is paused or not” (api.rst:1590-1591), and chapter 20’s vcpu_sbi_ext_hsm is KVM’s side of sbi_hart_start. Chapter 37 meets hart_start in hearth.

What each vCPU costs the VMM

A vCPU is a file descriptor, one mapping of the 4 KiB-or-larger kvm_run page (chapter 24), and a thread: the thread is what KVM_RUN blocks, and what chapter 24’s kick (SIGRTMIN to one thread id, with that thread’s own immediate_exit byte) is aimed at. wick has four threads at its sentinel, wick’s main (VMM) thread, wick_api, wick_vcpu0 and a fourth the kernel makes for the VM, kvm-nx-lpage-re (labs/ch28/measured-straylight.txt, threads and /proc/PID/task of the first held wick): a second vCPU adds a fifth. Everything chapter 24 and chapter 27 built for the one thread becomes a loop over a list. Pause is “kick all, join all”, and Firecracker’s is that, in the order that matters: it sends Pause to every vCPU handle, and only then collects every answer:

// firecracker v1.15.1, src/vmm/src/lib.rs:528-543
    pub fn pause_vm(&mut self) -> Result<(), VmmError> {
        // Send the events.
        self.vcpus_handles
            .iter_mut()
            .try_for_each(|handle| handle.send_event(VcpuEvent::Pause))
            .map_err(|_| VmmError::VcpuMessage)?;

        // Check the responses.
        if self
            .vcpus_handles
            .iter()
            .map(|handle| handle.response_receiver().recv_timeout(RECV_TIMEOUT_SEC))
            .any(|response| !matches!(response, Ok(VcpuResponse::Paused)))
        {
            return Err(VmmError::VcpuMessage);
        }

Sending first and collecting second is what keeps the pause as short as the slowest vCPU and not the sum. The pending-exit rule of chapter 27 applies to each vCPU: any of them may be in the middle of a port write or an MMIO access, and each thread must complete its own half-done exit (set immediate_exit, enter KVM_RUN, expect EINTR) before it reports Paused. The answer deadline of chapter 27 applies to each, and the stale-answer bookkeeping becomes one outstanding request for each vCPU. The seccomp filter of chapter 26 has no clone3, so all the threads would be made before the filter goes on, which is how the one vCPU thread is made; tgkill’s rule pins the signal and not the target, so a list of thread IDs to kick is no change to the filter. A guest that wants a second CPU also costs the scheduler another runnable thread for each guest; the chapter did not measure that.

What it does to snapshots

Chapter 27’s order for the vCPU’s state was Firecracker’s, and one sentence of Firecracker’s comment was not needed for one vCPU:

// firecracker v1.15.1, src/vmm/src/arch/x86_64/vcpu.rs:563-564
        // KVM_GET_VCPU_EVENTS/KVM_SET_VCPU_EVENTS is unsafe if other vCPUs are
        // still running.

With one vCPU the other vCPUs are none, and chapter 27 quoted the sentence and moved on. With several, it is the rule that fixes the order of the whole snapshot: every vCPU is stopped before any vCPU’s state is read. Firecracker’s save_vcpu_states sends SaveState to each paused handle, and the pause above has already collected every answer (lib.rs:594-616, and pause_vm before it); wick’s version of the pause would stop the list and the snapshot code would read a vector of states. Three other things change. First, mp_state carries information. With one vCPU it is RUNNABLE or HALTED and chapter 27 saved it first because KVM_GET_MP_STATE “calls kvm_apic_accept_events(), which might modify vCPU/LAPIC state”; with several it also says which APs have not started (UNINITIALIZED) and which have been through INIT and wait for the SIPI (INIT_RECEIVED), and a restore has to set those states back. KVM allows it: KVM_SET_MP_STATE accepts UNINITIALIZED, HALTED, INIT_RECEIVED and SIPI_RECEIVED when the interrupt controller is in the kernel, and turns the obsolete SIPI_RECEIVED into INIT_RECEIVED with a pending SIPI (x86.c:11654-11682). Second, a vCPU that is UNINITIALIZED has not been reset by an INIT, so there is no guest state of its own to save; an INIT or SIPI latched in its local APIC and not yet accepted is another matter (the code above clears them as it accepts them, lapic.c:3609-3624), and whether a state file must carry them was not verified here. Third, the TSC. Each vCPU has its own TSC offset in the kernel, and a guest that reads the TSC on different CPUs expects them to agree. KVM keeps them together on write, so that a VMM that writes MSR_IA32_TSC to each vCPU in turn, a few milliseconds apart, does not give the guest CPUs different clocks:

// linux v7.2.8, arch/x86/kvm/x86.c:2403-2432
    if (vcpu->arch.virtual_tsc_khz) {
        if (data == 0) {
            /*
             * Force synchronization when creating a vCPU, or when
             * userspace explicitly writes a zero value.
             */
            synchronizing = true;
        } else if (kvm->arch.user_set_tsc) {
            u64 tsc_exp = kvm->arch.last_tsc_write +
                        nsec_to_cycles(vcpu, elapsed);
            u64 tsc_hz = vcpu->arch.virtual_tsc_khz * 1000LL;
            /*
             * Here lies UAPI baggage: when a user-initiated TSC write has
             * a small delta (1 second) of virtual cycle time against the
             * previously set vCPU, we assume that they were intended to be
             * in sync and the delta was only due to the racy nature of the
             * legacy API.
             *
             * This trick falls down when restoring a guest which genuinely
             * has been running for less time than the 1 second of imprecision
             * which we allow for in the legacy API. In this case, the first
             * value written by userspace (on any vCPU) should not be subject
             * to this 'correction' to make it sync up with values that only
             * come from the kernel's default vCPU creation. Make the 1-second
             * slop hack only trigger if the user_set_tsc flag is already set.
             */
            synchronizing = data < tsc_exp + tsc_hz &&
                    data + tsc_hz > tsc_exp;
        }
    }

and then, for a write that qualifies, the vCPU takes the same offset as the previous one:

// linux v7.2.8, arch/x86/kvm/x86.c:2441-2450
    if (synchronizing &&
        vcpu->arch.virtual_tsc_khz == kvm->arch.last_tsc_khz) {
        if (!kvm_check_tsc_unstable()) {
            offset = kvm->arch.cur_tsc_offset;
        } else {
            u64 delta = nsec_to_cycles(vcpu, elapsed);
            data += delta;
            offset = kvm_compute_l1_tsc_offset(vcpu, data);
        }
        matched = true;

This is called from the MSR_IA32_TSC case of KVM’s MSR write (x86.c:3655-3657: if (msr_info->host_initiated) kvm_synchronize_tsc(vcpu, &data);). Two things are in the source and not tested in this book. The one-second window applies only once kvm->arch.user_set_tsc is set, that is from the second userspace write on, and a write of 0 always synchronises (x86.c:2403-2410); so a restore that writes the vCPUs’ saved TSC values in turn gets the first as it is, and each later one is matched to the previous offset if it lies within a second of cycles of where the clock has put the last write (they were saved after the same pause, so they do), and is not matched if it does not. And the comment’s own warning is about the other case, a guest that has run for less than that second, whose first userspace write must not be pulled toward the values KVM gave its vCPUs at creation: the flag is why it is not. Chapter 27 scaled the TSC frequency for the one vCPU when the host’s differed (KVM_SET_TSC_KHZ); the same call would be made on every vCPU first (Firecracker’s builder.rs:463-475, quoted in chapter 27, loops for vcpu in &vcpus). The state file would need a list of vCPU states where it has one (its version is 1 and a reader of another version refuses it).

What it does to devices

Chapter 25’s rings were already shared between two threads: the vCPU thread, which rings the doorbell and takes the interrupt, and the VMM thread, which serves the queue. The device’s side has been written for that since chapter 22 (wick’s Bus holds each device behind an Arc<Mutex<..>>, bus.rs). With several vCPUs the driver’s side is concurrent too: two guest CPUs can add buffers to the same queue, and two vCPU threads can enter the same device’s registers at the same moment. The device sees them serialised by its mutex, and what keeps the guest’s two CPUs from corrupting one available ring is the guest kernel’s own locking; that is the guest kernel’s problem, not the VMM’s. What the VMM can do about the contention is the standard remedy, more queues. The virtio specification defines it for both of the devices wick has: for the network device, VIRTIO_NET_F_MQ, with automatic receive steering:

// virtio 1.2 (OASIS, July 2022), section 5.1.6.5.6, p. 95
5.1.6.5.6 Automatic receive steering in multiqueue mode
If the driver negotiates the VIRTIO_NET_F_MQ feature bit (depends on VIRTIO_NET_F_CTRL_VQ), it
MAY transmit outgoing packets on one of the multiple transmitq1...transmitqN and ask the device to queue
incoming packets into one of the multiple receiveq1...receiveqN depending on the packet flow.

(the feature is bit 22, VIRTIO_NET_F_MQ(22) Device supports multiqueue with automatic receive steering, p. 80, and it depends on a control queue the device would have to implement); and for the block device VIRTIO_BLK_F_MQ (12), “Device supports multiqueue”, with a num_queues field in the configuration space (p. 99). Each is a feature of the device: more queues, more doorbells, and a configuration field.

What it does to the guest kernel build

tinyconfig is a uniprocessor kernel. CONFIG_SMP is off, and everything that exists to share data between CPUs is compiled out: spinlocks that spin, per-CPU data in arrays, the RCU that is built for many CPUs. Turning SMP on and running olddefconfig (labs/ch28/build-variant.sh smp SMP, in ~/.cache/hp/ch28-smp, apart from chapter 24’s cache) makes the other options follow. scripts/diffconfig between chapter 24’s configuration and this one prints 85 lines, in the file’s section “kernel variant smp” (the diffconfig: lines): besides SMP n -> y, NR_CPUS 1 -> 2 (the number tinyconfig chooses once SMP is on), the tiny RCU and SRCU become the tree implementations (TINY_RCU, TINY_SRCU removed, TREE_RCU, TREE_SRCU added), CPU hotplug and the sibling and core scheduling domains (HOTPLUG_CPU, SCHED_SMT, SCHED_MC, SCHED_CLUSTER), queued spinlocks and rwlocks, per-VMA locks, and cpufreq with its governors (CPU_FREQ n -> y). The image is 1,811,456 bytes against chapter 24’s 1,704,960. Its solo boots on straylight fall into the same two phases as the base kernel’s, in the same file and run: the SMP kernel’s twelve fast boots lie at 235.3 to 245.2 ms (median 241.0) and its eight slow ones at 334.6 to 348.1 ms (median 341.4), against the base kernel’s nine at 218.8 to 250.1 ms (median 225.5) and eleven at 278.8 to 322.4 ms (median 317.5). Group for group the SMP build with no second processor to use it costs 15.5 ms in the fast phase and 23.9 ms in the slow one. The two sets’ overall medians are not compared: they are values of different groups (labs/ch28/measured-straylight.txt, sections “boot, chapter 24’s arguments” and “boot, smp kernel, one vCPU”). Exercise (f) boots that kernel under wick and reads why it still runs one CPU.

Why wick stops at one

A function-sized workload, the guest this book boots, a program that runs for milliseconds to seconds on one core, gains little from a second vCPU, and density loses a thread for each guest (the kernel’s scheduler sees one more runnable thread to place, and the host holds one more kvm_run page, file descriptor and stack). Nothing in hearth’s first guest needs one either, and what hearth does when it wants more than one of something is chapter 37’s subject: several guests, not several vCPUs.

Walkthrough

labs/ch28/ is a lab, a measurement and a reading exercise. The lab is eight guests at once. The measurement is measure.sh, with two small programs under it (stamp, and the statistics function summ) and a self-check that runs before the lab. The reading exercise is the lab’s README.md: a table of the reader’s own numbers beside straylight’s, and one line for each refused device.

The lab: eight guests

The guest is chapter 24’s, with three lines added to its init for the measurement and none that changes what the lab prints:

mount -t proc proc /proc
mount -t devtmpfs devtmpfs /dev
dmesg -n 1
echo "=== lab begin"
echo "init: userland up"
echo "init: kernel $(uname -r) $(uname -m)"
echo "=== lab end"
# measure.sh boots with `hold` on the command line and reads the VMM's memory while the guest is still up.
read -r cmdline < /proc/cmdline
case " $cmdline " in *" hold "*) exec sleep 600 ;; esac
exec >/dev/null 2>&1 </dev/null
reboot -f

hold on the kernel command line is the measurement’s: it keeps the guest up after its last line so that measure.sh can read the wick process’s memory while the guest is still there. make lab CH=28 boots without it, so the guest ends with reboot -f as chapter 24’s does. run.sh starts eight of these:

# One guest: its own directory, its own socket, chapter 24's three API calls.
guest() {
  local d=out/g/$1
  mkdir -p "$d"
  timeout -k 1 "$TIMEOUT" "$WICK" --api-sock "$d/api.sock" --id "ch28-$1" > "$d/console.txt" 2> "$d/wick.log" &
  local pid=$!
  local c=("$WICK" ctl --api-sock "$d/api.sock" --wait-ms 5000)
  "${c[@]}" PUT /machine-config @../ch24/api/machine-config.json >> "$d/ctl.txt" 2>&1
  "${c[@]}" PUT /boot-source @../ch24/api/boot-source.json >> "$d/ctl.txt" 2>&1
  "${c[@]}" PUT /actions @../ch24/api/start.json >> "$d/ctl.txt" 2>&1
  wait "$pid"
  echo $? > "$d/rc"
}
for n in $(seq 1 "$GUESTS"); do guest "$n" & done
wait

Each guest has its own directory, its own API socket and its own wick; the kernel and the initramfs are the same two files, opened by all eight and written by none. The eight functions run in the background and wait joins them. A guest passes when two things are true: its console holds both sentinels, === lab begin and === lab end, and its wick exited 0. The exit status alone is not a pass: chapter 24 explained that wick exits 0 on KVM_EXIT_SHUTDOWN, which a clean reboot -f and a triple fault both produce, so the sentinels are the evidence that the guest ran and the status is the evidence that it ended. The capture is nine lines, density: guest N PASS for each N in order and density: 8 of 8, and no time, no memory figure and no count other than the fixed eight, so that it is the same on talos, with eight threads, and on straylight, with thirty-two. The count is eight because it fits the smaller machine and is the same on both; a count that depended on the host’s cores would be layout.

make lab CH=28 IMPL=mine prints chapter 28 has no mine/: running the reference wick and runs the reference: there is nothing for a reader to write in this chapter’s lab, and a mine/ that made the lab pass or fail would be a decoy.

stamp

stamp is the measurement’s only clock. It copies its standard input to its standard output and puts the time before each line:

#include <stdio.h>
#include <string.h>
#include <time.h>
#include <unistd.h>

static long long now_us(void) {
    struct timespec ts;
    clock_gettime(CLOCK_MONOTONIC, &ts);
    return (long long)ts.tv_sec * 1000000LL + ts.tv_nsec / 1000;
}

static int write_all(const char *p, size_t n) {
    while (n > 0) {
        ssize_t w = write(1, p, n);
        if (w < 0) return -1;
        p += w;
        n -= (size_t)w;
    }
    return 0;
}

int main(int argc, char **argv) {
    if (argc == 2 && strcmp(argv[1], "--now") == 0) {
        printf("%lld\n", now_us());
        return 0;
    }
    if (argc != 1) {
        fprintf(stderr, "usage: stamp [--now]   (copies stdin, stamping each line)\n");
        return 2;
    }
    char in[4096], line[65536 + 32];
    size_t len = 0; /* bytes of the current line held in line[], after the stamp's room */
    const size_t room = 24;
    for (;;) {
        ssize_t n = read(0, in, sizeof in);
        if (n <= 0) break;
        long long t = now_us();
        for (ssize_t i = 0; i < n; i++) {
            if (len < sizeof line - room - 2) line[room + len++] = in[i];
            else if (in[i] == '\n') line[room + len - 1] = '\n'; /* a line cut at the cap still ends with its newline */
            if (in[i] == '\n') {
                char head[room];
                int h = snprintf(head, sizeof head, "%lld ", t);
                memcpy(line + room - h, head, (size_t)h);
                if (write_all(line + room - h, (size_t)h + len) < 0) return 1;
                len = 0;
            }
        }
    }
    if (len > 0) {
        char head[room];
        int h = snprintf(head, sizeof head, "%lld ", now_us());
        memcpy(line + room - h, head, (size_t)h);
        line[room + len++] = '\n';
        if (write_all(line + room - h, (size_t)h + len) < 0) return 1;
    }
    return 0;
}

The time is CLOCK_MONOTONIC in microseconds, which no one sets and which does not jump when the host’s wall clock does. A line is stamped when the read that delivered its newline returned, so a guest that prints === lab begin has the time at which the line reached the host’s end of the console, and not the time its first byte was written. The --now form prints the clock once and exits: a shell script takes a timestamp from the same clock as stamp puts on a console line, by running the program. That run costs a fork and an exec, and the file records the cost of one on the measured host (stamp_cost_us). The console reaches stamp through a named pipe, so that wick, stamp and the script are three processes with three process IDs.

summ and the self-check

The statistics are one function:

# summ N...: prints "median min max count" of the integers given. An even count's median is the mean of the middle two,
# rounded down.
summ() {
  [ $# -gt 0 ] || { echo "summ: no values" >&2; return 1; }
  local v=()
  mapfile -t v < <(printf '%s\n' "$@" | sort -n)
  local n=${#v[@]} med
  if (( n % 2 )); then med=${v[n/2]}; else med=$(( (v[n/2-1] + v[n/2]) / 2 )); fi
  echo "$med ${v[0]} ${v[n-1]} $n"
}

It sorts numerically and prints the median, the minimum, the maximum and the count; for an even count the median is the mean of the middle two, rounded down. selfcheck.sh, which make lab CH=28 runs before it starts the guests, gives summ inputs whose answers it knows: odd and even counts, one value, duplicates, an order that is wrong as text and right as numbers (9, 10 and 100), and a rounding; and it checks stamp against a three-line input with a carriage return and no final newline, against two lines written 200 ms apart, and against itself (--now twice must not go backwards). It prints nothing when it passes.

measure.sh: the three measurements

The script is run on one host and writes out/measured.txt. labs/ch28/measured-straylight.txt is the copy that came from straylight, and the chapter’s every figure is in it. Its header says what ran: the host, the CPU, the number of threads, the host kernel, the date, the wick commit, the command, the statistics rule, the guest kernel’s size and configuration hash, the cost of one stamp, the transparent huge page setting, the CPU governor, the load average, whether KSM is on, and ulimit -n. Then the three measurements, as measure.sh makes them.

1 and 2: boot to userland and memory at the sentinel. Each is one boot, in its own scope. read_mem is the measurement of memory:

# read_mem PID MIB: sets PEAK (memory.peak of the pid's scope, KiB), HWM, ANON, FILE, GUESTRSS, THP (KiB), CPU_US (the CPU the scope has used,
# all threads, from cpu.stat), PROC_CPU_US (utime + stime of the process, in ticks of 10 ms), FDS and THREADS (open descriptors and threads of the process).
read_mem() {
  local pid=$1 cg
  cg=$(sed -n 's/^0:://p' "/proc/$pid/cgroup")
  if [ -r "/sys/fs/cgroup$cg/memory.peak" ]; then PEAK=$(( $(< "/sys/fs/cgroup$cg/memory.peak") / 1024 )); else PEAK=; NOPEAK=1; fi
  HWM=$(status_kib "/proc/$pid/status" VmHWM)
  ANON=$(status_kib "/proc/$pid/status" RssAnon)
  FILE=$(status_kib "/proc/$pid/status" RssFile)
  GUESTRSS=$(guest_ram_rss "$pid" "$2")
  THP=$(status_kib "/proc/$pid/smaps_rollup" AnonHugePages)
  CPU_US=$(sed -n 's/^usage_usec //p' "/sys/fs/cgroup$cg/cpu.stat" 2> /dev/null)
  # utime + stime of the process (all its threads), in clock ticks of 10 ms, as microseconds
  local st; st=$(< "/proc/$pid/stat"); st=${st##*) }; set -- $st; PROC_CPU_US=$(( (${12} + ${13}) * 10000 ))
  FDS=$(ls "/proc/$pid/fd" | wc -l)
  THREADS=$(ls "/proc/$pid/task" | wc -l)
}

systemd-run --user --scope (in scope-wick.sh) moves a process into a new cgroup of its own and runs the command in place, so the process ID in the pid file is wick’s and the cgroup holds wick and nothing else. memory.peak of that cgroup is the high-water mark of everything the kernel charged to it, page cache included; VmHWM is the process’s own resident-set high-water mark; RssAnon and RssFile split it into the anonymous pages (the guest’s RAM, the heap, the stacks) and the file-backed ones (the binary); and the guest’s RAM is found by size, the one mapping in /proc/PID/smaps whose Size is exactly mem_size_mib MiB, whose own Rss is what the guest touched. cpu.stat’s usage_usec is the CPU the scope has used. And boot_solo does the boot:

# boot_solo DIR MIB BOOTJSON: one boot in its own scope, held at the sentinel. Sets BOOT_US and the read_mem values.
boot_solo() {
  local d=$1 t0 tb
  write_machine "$d.machine.json" "$2"
  start_wick "$d" scope
  api "$d" PUT /machine-config "@$d.machine.json"
  api "$d" PUT /boot-source "@$3"
  api "$d" PUT /actions "@$M/start.json"
  t0=$(now)
  if ../waitline.sh "$d/console.stamped" '=== lab end' 20; then
    tb=$(stamp_of "$d/console.stamped" '=== lab begin')
    BOOT_US=$(( tb - t0 ))
    read_mem "$(< "$d/pid")" "$2"
  else
    BOOT_US=; log "boot_solo: no sentinel in $d"
  fi
  finish_wick
}

It starts wick in a scope with its console in a named pipe read by stamp, makes chapter 24’s three API calls, and takes the start time when the last returns, InstanceStart having been acknowledged. waitline.sh waits (with a real deadline) for the line === lab end to appear in the stamped file; the time to the sentinel is the stamp of === lab begin minus the start time; memory is read while the guest is held at its sleep; and wick is killed. Every set is 20 of these after one that is thrown away. Three sets are run: chapter 24’s own arguments, the same with quiet added, and the same arguments with mem_size_mib halved to 64.

3: parallel boots. N guests started at once, N from 1 by doubling, each in its own directory, with batch:

# batch FN N: N guests of FN at once, all started together. Sets BATCH_MED (median of the N, microseconds), BATCH_MAX and BATCH_FAIL.
batch() {
  local fn=$1 n=$2 i vals=() r
  rm -rf "$M/b"; mkdir -p "$M/b"
  for i in $(seq 1 "$n"); do "$fn" "$M/b/$i" & done
  wait
  BATCH_FAIL=0; BATCH2_MED=
  local vals2=()
  for i in $(seq 1 "$n"); do
    r=$(< "$M/b/$i/result") || r=FAIL
    if [ "$r" = FAIL ]; then BATCH_FAIL=$(( BATCH_FAIL + 1 )); else vals+=("$r"); fi
    [ -f "$M/b/$i/result2" ] && vals2+=("$(< "$M/b/$i/result2")")
  done
  if [ ${#vals[@]} -gt 0 ]; then read -r BATCH_MED _ BATCH_MAX _ <<< "$(summ "${vals[@]}")"; else BATCH_MED=; BATCH_MAX=; fi
  if [ ${#vals2[@]} -gt 0 ]; then read -r BATCH2_MED _ _ _ <<< "$(summ "${vals2[@]}")"; fi
}

Every guest in a batch is a background subshell that starts its own wick, makes its own three calls, takes its own start time and, when wick exits, reads its own time to the sentinel from its own stamped console; batch collects the N figures and takes their median, and parallel_sets runs 20 batches for each N (after one thrown away) and reports the median, minimum and maximum of the batches’ medians, and the median of each batch’s slowest guest. It stops at the first N whose median is at least twice N = 1’s, and prints that N as the doubling point. A guest that fails (a missing sentinel or a non-zero exit) is counted in the line and left out of the median; the file says guest failures for each N, and every N in it has no failed guest.

The restore. The script makes chapter 27’s snapshot once (a boot of chapter 27’s guest with its disk, a wait for tick 2, PATCH /vm to pause, PUT /snapshot/create) and restores it in new processes: one at a time, each in a scope, for the load call’s time and the memory, and then N at once, as above. The result of a restore is the time from just before wick ctl PUT /snapshot/load is started to the moment it returns. The first-tick time is recorded beside it, for the reason the Mechanism gave.

The variants. make -C labs/ch28 variants builds, in ~/.cache/hp/ch28-smp and apart from chapter 24’s cache, the same kernel with CONFIG_SMP; the script boots it by the same function and reports its figures and the lines of its log that name processors. Firecracker is run last, by the same functions and with wick ctl as the client for both VMMs. That works because wick’s client stops reading a response at its headers when the status is a 1xx, 204 or 304, which RFC 9112 section 6.3 says have no body: Firecracker answers a PUT with 204 and Connection: keep-alive even when the request said Connection: close (the response’s bytes, HTTP/1.1 204 \r\nServer: Firecracker API\r\nConnection: keep-alive\r\n\r\n, are the input of the unit test a_204_304_or_1xx_response_has_no_body_and_is_not_waited_on), and a client that waits for the end of the stream never returns (chapter 24 has the rule where the client’s reader is listed).

The committed results

Every figure below is a line of labs/ch28/measured-straylight.txt, straylight, 2026-10-04 UTC, make -C labs/ch28 measure WICK_COMMIT=65dac67 through tools/remote-lab.sh; ms for times, medians of 20 runs, minimum and maximum in parentheses. WICK_COMMIT is a label the operator gives, and the file’s wick: line repeats it: the binary measured (2,869,656 bytes, the file’s same line) was built from a tree that also held the client’s 204 rule of the previous section, committed next as b580769, without which wick ctl cannot drive Firecracker; a build on straylight of wick/ at 3f55c6a, whose code differs from b580769 by one comment, is the same size.

  • Boot to userland, chapter 24’s arguments: 283.6 ms (218.8, 322.4), a value of the slow group: nine runs at 218.8 to 250.1 ms and eleven at 278.8 to 322.4 ms. With quiet: 148.2 (145.4, 157.4). Half the RAM: 269.6 (220.2, 324.6). The SMP kernel with one vCPU: twelve runs at 235.3 to 245.2 ms and eight at 334.6 to 348.1 ms, no overall median quoted. Firecracker v1.15.1: 436.5 (374.8, 443.1), and with quiet 314.0 (310.9, 346.8).
  • Memory at the sentinel (KiB): memory.peak 27,208 (26,696, 27,740); VmHWM 27,656; anonymous 25,596, file-backed 2,060; guest RAM touched 25,312 of 131,072 (mem_size_mib 128). With mem_size_mib 64: memory.peak 27,154 and guest RAM touched 25,248. A restore: memory.peak 133,014, VmHWM 133,528, guest RAM 131,072. Firecracker, a boot: VmHWM 28,420, anonymous 23,364, file-backed 5,056.
  • CPU used by the scope at the sentinel: wick boot 289.0 ms; quiet 154.1 ms; Firecracker 182.9 ms; Firecracker with quiet 71.7 ms.
  • Restore: the load call returns after 42.2 ms (39.9, 45.5); the first tick comes 1046.8 ms after the call began.
  • Parallel boots (median of the batch medians, ms): N=1 308.3, N=2 235.0, N=4 227.1, N=8 244.8, N=16 246.2, N=32 349.2, N=64 607.9, N=128 1166.1. Doubling point: N = 128.
  • Parallel restores (the load call, ms): N=1 48.7, N=2 47.8, N=4 46.7, N=8 47.0, N=16 54.3, N=32 80.2, N=64 149.6. Doubling point: N = 64.
  • Firecracker, parallel boots (ms): N=1 435.1, N=2 435.9, N=4 438.1, N=8 444.3, N=16 447.8, N=32 551.9, N=64 693.5, N=128 897.1. Doubling point: N = 128.
  • The SMP kernel: 1,811,456 bytes against 1,704,960; 85 lines of diffconfig output.

Exercises

Each answer is a run, or a sentence from a source with its lines. The runs of (b), (c) and (f) are in labs/ch28/measured-straylight.txt (straylight, 2026-10-04 UTC); the run of (a) is in labs/ch28/measured-talos.txt (talos, Intel i3-1315U, eight threads, Linux 7.2.5, 2026-10-04 UTC, RUNS=5 NMAX=16 SKIP_FC=1, the same script); (d), (e) and (g) are readings.

(a) Run the lab at N = 16 on a machine with 8 threads (GUESTS=16 labs/ch28/run.sh, after make lab CH=28 has built the guest) and explain the shape of the parallel boots on that machine.

Answer

(talos, 2026-10-04 UTC.) GUESTS=16 labs/ch28/run.sh after make lab CH=28: all sixteen guests pass and the last line is density: 16 of 16. The lab has no time in it, so the shape is in labs/ch28/measured-talos.txt (the same script, RUNS=5 NMAX=16 SKIP_FC=1, load average 0.71 at its start): the median time to the sentinel for N = 1, 2, 4, 8 and 16 guests at once is 155.8, 167.8, 188.1, 245.8 and 831.1 ms (the N = 16 batches range from 473.5 to 1,024.8 ms, the slowest guest of each batch at 989.0 ms in the median), and the first N at which it is twice N = 1’s is 16, twice the machine’s eight threads. Up to N = 8, the thread count, each guest has a thread to itself and the median still grows by about half (245.8 against 155.8 ms); at N = 16 two vCPU threads want each hardware thread. The restores of the same file double at N = 4 (25.7 ms at N = 1, 61.4 at N = 4), earlier than the boots. The file shows that they do and the sources do not say which resource binds, and the chapter does not claim one. (straylight, with four times the threads, has a boot point of N = 128 and a restore point of N = 64 in the run the chapter uses, and N = 32 and N = 32 in a busier one; see the Mechanism.)

(b) From /proc/PID/smaps_rollup of one wick with another running, which part of its memory is shared with the next wick?

Answer

The file-backed pages, which are the wick binary and the libraries it maps: the Mechanism’s figures from the section “sharing” of labs/ch28/measured-straylight.txt, where Shared_Clean, 2,052 KiB, is about the whole of the file-backed RssFile, 2,060 KiB, and Private_Dirty, 25,608 KiB, is the guest’s RAM and the heap. The same rollup’s Pss_File is 1,032 KiB, half of RssFile: with two processes mapping them, the shared pages are charged to each by half. Nothing of the guest is shared, so a second wick costs the machine its own guest RAM, its heap and its stacks and about half the binary again.

(c) Halve mem_size_mib. What changes in memory.peak, and why not by half?

Answer

memory.peak moves from 27,208 KiB (min 26,696, max 27,740) to 27,154 KiB (min 26,720, max 28,228), a fall of 54 KiB that is smaller than the spread within either set, so memory.peak does not tell the two apart; the tight figure is VmHWM, 27,656 to 27,592 KiB (min and max within 52 KiB in both). Not 64 MiB, because the guest’s RAM is an on-demand mapping and the guest touched 25,312 KiB of it with 128 MiB and 25,248 KiB with 64: its kernel, its initramfs and its own early allocations do not depend on how much RAM it could have had, and memory it never touches is never allocated by the host. The boot is not faster for the smaller guest: 269.6 ms (min 220.2, max 324.6) against 283.6 ms (min 218.8, max 322.4), the two runs falling into the same two groups; the chapter does not explain the difference. (Where transparent huge pages are on for every mapping, as on talos, thp: [always], the touched RAM is counted in 2 MiB units and halving the size changes nothing: labs/ch28/measured-talos.txt has guest_ram_rss 30,720 KiB, all of it AnonHugePages, for both sizes. straylight’s setting is madvise, and its figures are in 4 KiB pages.)

(d) Pick one refused device and list the KVM ioctls or the virtio sections it would add, from the sources.

Answer

Live migration, from api.rst at the pinned tag. A memory slot is registered with the flag KVM_MEM_LOG_DIRTY_PAGES in KVM_SET_USER_MEMORY_REGION (“to instruct KVM to keep track of writes to memory within the slot”, lines 1413-1416; wick sets the slot’s flags to 0). KVM_GET_DIRTY_LOG (section 4.8, lines 354-392) is a VM ioctl whose argument names the slot and a bitmap with “one bit per page” and returns “any pages dirtied since the last call to this ioctl”. KVM_CLEAR_DIRTY_LOG (section 4.117, lines 5029-5069) clears the dirty status of ranges of that bitmap, “mostly useful when KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2 is enabled” (section 7.18, the capability named in KVM_GET_DIRTY_LOG’s own text, lines 384-385). Three ioctls, a capability and a slot flag, in addition to the eleven vCPU and five VM state ioctls of chapter 27; the loop around them (copy, collect, copy again) and the wire are the VMM’s. The balloon, from the virtio specification: section 5.5 (p. 109-110) gives device ID 5; queues inflateq (0), deflateq (1), statsq (2, only with VIRTIO_BALLOON_F_STATS_VQ), free_page_vq (3, only with VIRTIO_BALLOON_F_FREE_PAGE_HINT) and reporting_vq (4, only with VIRTIO_BALLOON_F_PAGE_REPORTING); and feature bits 0 to 5.

(e) What would hearth measure instead of processes per host?

Answer

Not processes per host: a type-1 has none, and the descriptors, threads and cgroups of the Mechanism’s list do not exist in it. What remains of that list is memory per guest and the time to start one, so hearth would measure those, in its own terms. Memory per guest in bytes, counted by hearth and not read from a host: the guest’s RAM, the G-stage table that maps it (chapter 19: a 16 KiB root and 4 KiB tables below it) and the saved state of its vCPU. The time to start in the machine’s own clock, mtime ticks from the hypervisor’s decision to enter a guest to the guest’s first line on its console, read inside QEMU-as-metal, so that the host’s load cannot add to it. And the count of guests it can hold in a fixed amount of RAM, found by starting guests until it refuses one and printing the number. This is derived from the list above and not measured: hearth does not exist until chapter 33.

(f) Build the guest with CONFIG_SMP (make -C labs/ch28 variants), boot it under wick (labs/ch28/boot-variant.sh smp), and find in its log the line that says why it still runs one CPU.

Answer

(labs/ch28/boot-variant.sh smp, or labs/ch28/measured-straylight.txt, the section “kernel log lines about processors and tables: smp kernel under wick”, straylight, 2026-10-04 UTC.) The log, trimmed to its processor lines:

rcu:     RCU restricting CPUs from NR_CPUS=2 to nr_cpu_ids=1.
APIC: ACPI MADT or MP tables are not detected
APIC: Switch to virtual wire mode setup with no configuration
smpboot: SMP disabled
smp: Bringing up secondary CPUs ...
smpboot: Total of 1 processors activated (5988.66 BogoMIPS)

The kernel was built for two CPUs (NR_CPUS=2) and found one: nr_cpu_ids=1. The line that says why is APIC: ACPI MADT or MP tables are not detected: it is where __apic_intr_mode_select returns APIC_VIRTUAL_WIRE_NO_CONFIG (arch/x86/kernel/apic/apic.c:1286-1292), and native_smp_prepare_cpus answers that mode with disable_smp() (arch/x86/kernel/smpboot.c:1226-1230), whose first act is the smpboot: SMP disabled line (:1165). The same kernel under Firecracker would find the table the chapter quotes and report Processors: 1 with a Bootup-CPU; with a second MP table entry it would report two.

(g) From mptable.rs, how many bytes of guest memory describe two processors, and which entries would have to change to add a third?

Answer

compute_mp_size (mptable.rs:106-114) adds the sizes of seven structures, and the generated bindings fix each size (generated/mpspec.rs, the layout assertions at lines 78, 110, 139, 176, 159, 198 and 229): the floating pointer 16 bytes, the table header 44, a processor entry 20, the I/O APIC entry 8, the bus entry 8, an interrupt entry 8 for each of GSI_LEGACY_END + 1 = 24 lines (layout.rs:30), and two local interrupt entries of 8. For two processors: 16+44+2×20+8+8+24×8+2×8=32416 + 44 + 2 \times 20 + 8 + 8 + 24 \times 8 + 2 \times 8 = 324 bytes, 324 (284+20×2284 + 20 \times 2; the comment at layout.rs:87-88 says “284 + 20 * #vCPUS”; a script reading the sizes out of the bindings gives 304, 324 and 344 for one, two and three processors), of which the two processor entries are 40. A third processor adds one 20-byte entry (apicid 2). In the rest of the table three header fields change, length (by 20), oemcount (by 1) and the checksum; and, because the I/O APIC’s ID is num_cpus + 1 (mptable.rs:139), the I/O APIC entry’s apicid and the dstapic of each of the 24 interrupt entries, which name that ID as their destination, change from 3 to 4. The floating pointer is unchanged.

Lab

make lab CH=28
make lab CH=28 IMPL=mine
tools/remote-lab.sh lab CH=28
make -C labs/ch28 variants
labs/ch28/boot-variant.sh smp
make -C labs/ch28 measure WICK_COMMIT=$(git log -1 --format=%h -- wick)
tools/remote-lab.sh -C labs/ch28 measure WICK_COMMIT=$(git log -1 --format=%h -- wick)

make lab CH=28 boots eight guests and diffs labs/ch28/capture.txt; on both hosts the diff is empty. measure takes about 19 minutes on straylight with the defaults (RUNS=20, NMAX=128; the file’s finished: line) and writes labs/ch28/out/measured.txt; RUNS=5 NMAX=16 makes it short. labs/ch28/README.md is the reading lab: a table of the reader’s numbers beside straylight’s, and a line for each refused device from QEMU’s or Cloud Hypervisor’s documentation.

Further reading

results matching ""

    No results matching ""