24. Booting someone else’s kernel

What a VMM owes a kernel: memory it can find, in a mode it expects Guest physical memory as a vertical bar, low addresses at the top, not to scale, with what the VMM writes before the first instruction. The GDT at 0x500. The zero page, boot_params, at 0x7000. The identity page tables, PML4, PDPT and PD, at 0x9000 to 0xbfff. The kernel command line at 0x20000. The kernel at 0x100000, with its 64-bit entry at plus 0x200. The initramfs at the top of RAM. To the right, solid boxes name the four registers that point into the bar: GDTR holds 0x500, RSI holds 0x7000, CR3 holds 0x9000 and RIP holds 0x100200. Two dashed boxes name the fields inside boot_params that point at the command line and at the initramfs: cmd_line_ptr and ramdisk_image. 0x500GDT: four descriptors 0x7000boot_params, the zero page 0x9000 – 0xbfffidentity page tables 0x20000kernel command line 0x100000the kernel, 64-bit part +0x200the 64-bit entry … the rest of RAM … top of RAMinitramfs, page aligned GDTR = 0x500 RSI = 0x7000 CR3 = 0x9000 cmd_line_ptr RIP = 0x100200 ramdisk_image solid: a CPU register dashed: a boot_params field What a VMM owes a kernel: memory it can find, in a mode it expects

Why this layer exists

Chapter 20’s guest was eleven instructions the reader wrote: 0x2c bytes copied to the start of one memory slot, a pc set to its first byte, one KVM_RUN. That guest expects nothing of the machine it runs on, which is why a 152-line C program could host it. A Linux kernel expects a great deal and says none of it in its instructions. It needs to know how much memory there is and where, what its command line says, where its initial root filesystem sits, which CPU mode it was entered in, which page tables it is running on until it builds its own, and which interrupt controller will answer. On a PC the firmware answers all of this before the kernel’s first instruction, and chapter 23 deleted the firmware. A VMM with no firmware is the firmware: every answer a BIOS would have given is a number wick writes into guest memory or into a register before the vCPU first runs. This chapter lists those numbers, shows each as code, and shows in the exercises what the guest does when one is wrong.

It also builds the rest of wick that one guest needs. Chapter 23 drew three threads and a socket; this chapter writes them. An API thread reads one HTTP request at a time from a Unix socket and turns it into a message. A VMM thread owns the machine’s configuration and answers the messages. A vCPU thread runs KVM_RUN, as chapter 20’s vmm.c did. The lab starts wick, configures it with three requests, boots a real Linux v7.2.8 kernel to an init script that BusyBox runs, and watches the guest end itself with reboot -f. The host is x86-64 from here to the end of Part V, where chapter 20’s was RISC-V, so each x86 term is tied to the RISC-V one it replaces at first use.

The pieces reappear. Chapter 32’s guest contract is this chapter with every optional field deleted: a small boot-information block in place of the zero page defined below. hearth enters its guest the way wick does here, with the registers and memory laid out before the first instruction and no firmware in between.

Mechanism

Sources: the Linux tree at tag v7.2.8 (git.kernel.org, the stable tree); the crates at the versions wick/Cargo.lock pins (linux-loader 0.14.0, kvm-ioctls 0.25.0, event-manager 0.4.2, vm-superio 0.8.2); Firecracker at tag v1.15.1 (https://raw.githubusercontent.com/firecracker-microvm/firecracker/v1.15.1/…, fetched 2026-10-02). Every quoted block is re-extracted with sed -n from those, and its header names the file and lines. The Intel Software Developer’s Manual is cited by chapter and section titles as they stand in the PDF’s own outline (the combined volumes, fetched 2026-10-02 from https://cdrdv2.intel.com/v1/dl/getContent/671200; the outline was read, the page text of Volume 3 was not), and every bit position this chapter uses is quoted from the kernel’s own headers instead.

The 64-bit boot protocol

The Linux x86 tree documents how a boot loader hands over the kernel, in Documentation/arch/x86/boot.rst. Its last section is the one wick follows:

// linux v7.2.8, Documentation/arch/x86/boot.rst:1362-1399
64-bit Boot Protocol
====================

For machine with 64bit cpus and 64bit kernel, we could use 64bit bootloader
and we need a 64-bit boot protocol.

In 64-bit boot protocol, the first step in loading a Linux kernel
should be to setup the boot parameters (struct boot_params,
traditionally known as "zero page"). The memory for struct boot_params
could be allocated anywhere (even above 4G) and initialized to all zero.
Then, the setup header at offset 0x01f1 of kernel image on should be
loaded into struct boot_params and examined. The end of setup header
can be calculated as follows::

  0x0202 + byte value at offset 0x0201

In addition to read/modify/write the setup header of the struct
boot_params as that of 16-bit boot protocol, the boot loader should
also fill the additional fields of the struct boot_params as described
in chapter Documentation/arch/x86/zero-page.rst.

After setting up the struct boot_params, the boot loader can load
64-bit kernel in the same way as that of 16-bit boot protocol, but
kernel could be loaded above 4G.

In 64-bit boot protocol, the kernel is started by jumping to the
64-bit kernel entry point, which is the start address of loaded
64-bit kernel plus 0x200.

At entry, the CPU must be in 64-bit mode with paging enabled.
The range with setup_header.init_size from start address of loaded
kernel and zero page and command line buffer get ident mapping;
a GDT must be loaded with the descriptors for selectors
__BOOT_CS(0x10) and __BOOT_DS(0x18); both descriptors must be 4G flat
segment; __BOOT_CS must have execute/read permission, and __BOOT_DS
must have read/write permission; CS must be __BOOT_CS and DS, ES, SS
must be __BOOT_DS; interrupt must be disabled; %rsi must hold the base
address of the struct boot_params.

Read as a list of duties, in the order the paragraph states them:

  1. Fill a struct boot_params and pass its address in %rsi. The structure is “traditionally known as ‘zero page’”, a 4 KiB record whose fields hold the command line’s address, the memory map, the initial ramdisk’s address and size, and the setup header, a block of fields at offset 0x1f1 of the kernel image that the loader copies in, reads and partly fills. %rsi is the second argument register of the x86-64 calling convention; the entry convention gives the zero page the role that a1 gave the device tree in chapter 2, where ember was entered with a0 = hart ID and a1 = device tree. The difference is the format. A device tree is a self-describing tree a kernel walks; the zero page is a C structure at fixed offsets (zero-page.rst lists them), and the kernel reads fields by number.
  2. Enter at the loaded kernel’s start plus 0x200. The file is a bzImage, chapter 23’s word for the compressed image the x86 build produces: real-mode setup code the 64-bit protocol never runs, then a protected-mode part that starts a decompression stub. The stub’s 64-bit entry is at 0x200 in that part.
  3. Be in 64-bit mode, with paging on, and a GDT. The next section is about what that asks of the CPU.
  4. Interrupts off. rflags with IF clear. The kernel has no interrupt table yet; it installs one itself.

The stub at 0x200 says what it expects, in its own words:

// linux v7.2.8, arch/x86/boot/compressed/head_64.S:276-299
    .code64
    .org 0x200
SYM_CODE_START(startup_64)
    /*
     * 64bit entry is 0x200 and it is ABI so immutable!
     * We come here either from startup_32 or directly from a
     * 64bit bootloader.
     * If we come here from a bootloader, kernel(text+data+bss+brk),
     * ramdisk, zero_page, command line could be above 4G.
     * We depend on an identity mapped page table being provided
     * that maps our entire kernel(text+data+bss+brk), zero page
     * and command line.
     */

    cld
    cli

    /* Setup data segments. */
    xorl    %eax, %eax
    movl    %eax, %ds
    movl    %eax, %es
    movl    %eax, %ss
    movl    %eax, %fs
    movl    %eax, %gs

“ABI so immutable”: the offset is a promise. The stub needs what the protocol promised, identity-mapped page tables over the kernel, the zero page and the command line. Its first instructions load %ds, %es, %ss, %fs and %gs with the null selector, so the descriptors wick puts behind those registers are used by nothing. It reads init_size out of the zero page through %rsi a few lines later (head_64.S:329), and installs a GDT of its own and reloads %cs from it:

// linux v7.2.8, arch/x86/boot/compressed/head_64.S:357-366
    /* Make sure we have GDT with 32-bit code segment */
    leaq    gdt64(%rip), %rax
    addq    %rax, 2(%rax)
    lgdt    (%rax)

    /* Reload CS so IRET returns to a CS actually in the GDT */
    pushq    $__KERNEL_CS
    leaq    .Lon_kernel_cs(%rip), %rax
    pushq    %rax
    lretq

boot_params and the setup header

load_kernel gives the bzImage to linux-loader’s BzImage::load, which copies the protected-mode part to 0x100000 and returns the setup header it found in the file’s first sectors. The loader refuses a file that does not carry the header’s magic:

// linux-loader 0.14.0, src/loader/bzimage/mod.rs:126-130
        // If the `HdrS` magic number is not found at offset 0x202, the boot protocol version is
        // "old", the image type is assumed as zImage, not bzImage.
        if boot_header.header != 0x5372_6448 {
            return Err(Error::InvalidBzImage.into());
        }

HdrS is the four bytes the boot protocol puts at file offset 0x202. A file without them is not a bzImage to this loader. The document gives every header field a type: the loader reads some and writes others. wick writes type_of_loader (0x210), loadflags (0x211, “modify”), heap_end_ptr (0x224), ramdisk_image and ramdisk_size (0x218, 0x21c) and cmd_line_ptr (0x228), each “write (obligatory)” or “modify (obligatory)”. It reads version (0x206), initrd_addr_max (0x22c), kernel_alignment (0x230), relocatable_kernel (0x234), xloadflags (0x236), cmdline_size (0x238), pref_address (0x258) and init_size (0x260), each marked “read” (or, for kernel_alignment, “read/modify”), and setup_sects and syssize, to check the file’s size. The loader owns the writes and the image owns the reads; wick copies the whole setup header into the zero page, and because a header’s “write” fields hold whatever the image’s build left in them, it zeroes the ones it does not set (ramdisk_image and ramdisk_size before it sets them, ext_loader_ver, ext_loader_type, hardware_subarch, hardware_subarch_data and setup_data): a stale ramdisk address would be unpacked as an initramfs, and a stale setup_data list is walked by the stub.

The command line is a NUL-terminated string at an address the loader picks, written into cmd_line_ptr:

// linux v7.2.8, Documentation/arch/x86/boot.rst:617-626
Field name:    cmd_line_ptr
Type:        write (obligatory)
Offset/size:    0x228/4
Protocol:    2.02+
============    ==================

  Set this field to the linear address of the kernel command line.
  The kernel command line can be located anywhere between the end of
  the setup heap and 0xA0000; it does not have to be located in the
  same 64K segment as the real-mode code itself.

wick puts it at 0x20000, below the 0xA0000 ceiling and above the GDT, the zero page and the page tables. console=ttyS0 tells the kernel the 8250 is its console; rdinit=/init names the program to run from the initial ramdisk; reboot=t and panic=-1 are the two that end the lab, below. The line’s length is limited by a field the loader only reads, and the document says so under cmdline_size:

// linux v7.2.8, Documentation/arch/x86/boot.rst:727-737
============    ============
Field name:    cmdline_size
Type:        read
Offset/size:    0x238/4
Protocol:    2.06+
============    ============

  The maximum size of the command line without the terminating
  zero. This means that the command line can contain at most
  cmdline_size characters. With protocol version 2.05 and earlier, the
  maximum size was 255.

This image’s value is 2047 (read from file offset 0x238). check_cmdline in x86/boot.rs refuses a longer line with Error::Config, which the API turns into 400 (exercise (d)), because chapter 25 appends virtio_mmio.device= entries to the end of the line and the end is what a kernel would cut.

The memory map is the E820 map, named for the BIOS call (INT 15h, function E820h) that returns it: a list of (address, size, type) records, in the zero page at offset 0x2d0, 0x1e8 holding the count. It is where an x86 kernel learns which physical addresses are RAM, as the memory node of a device tree tells a kernel that reads one (ember never parses its tree, chapter 2, but the board’s DRAM at 0x80000000 is what that node would say). A PC’s RAM is not one range: conventional memory up to 0x9fc00, where the BIOS’s extended data area (EBDA) starts, a hole for the video buffer and the BIOS itself (up to 0xfffff), then RAM again from 1 MiB. wick reports the PC’s shape with two records, which the guest’s own log prints back, from the lab’s boot on talos (2026-10-02), where the kernel labels every entry BIOS-e820 whoever wrote it:

BIOS-provided physical RAM map:
BIOS-e820: [mem 0x0000000000000000-0x000000000009fbff]  System RAM
BIOS-e820: [gap 0x000000000009fc00-0x00000000000fffff]
BIOS-e820: [mem 0x0000000000100000-0x0000000007ffffff]  System RAM

The type is E820_RAM, 1:

// linux v7.2.8, arch/x86/include/uapi/asm/e820.h:31-31
#define E820_RAM    1

The initial ramdisk, the initrd, is the cpio archive the kernel unpacks into a memory file system and runs /init from. wick copies it to the top of RAM, rounded down to a page, which the guest’s log confirms for this image on a 128 MiB guest: RAMDISK: [mem 0x07d7e000-0x07ffffff]. The loader must keep it at or below the highest address the image allows, and clear of the memory the decompressor works in:

// linux v7.2.8, Documentation/arch/x86/boot.rst:635-646
Field name:    initrd_addr_max
Type:        read
Offset/size:    0x22c/4
Protocol:    2.03+
============    ===============

  The maximum address that may be occupied by the initial
  ramdisk/ramfs contents.  For boot protocols 2.02 or earlier, this
  field is not present, and the maximum address is 0x37FFFFFF.  (This
  address is defined as the address of the highest safe byte, so if
  your ramdisk is exactly 131072 bytes long and this field is
  0x37FFFFFF, you can start your ramdisk at 0x37FE0000.)

init_size is the memory the decompressor needs from the kernel’s runtime start address, and the document says where that is, which is not always where the file was loaded:

// linux v7.2.8, Documentation/arch/x86/boot.rst:897-905
  The kernel runtime start address is determined by the following algorithm::

   if (relocatable_kernel) {
    if (load_address < pref_address)
        load_address = pref_address;
    runtime_start = align_up(load_address, kernel_alignment);
   } else {
    runtime_start = pref_address;
   }

For a kernel that cannot relocate, pref_address (0x258):

// linux v7.2.8, Documentation/arch/x86/boot.rst:876-882
  This field, if nonzero, represents a preferred load address for the
  kernel.  A relocating bootloader should attempt to load at this
  address if possible.

  A non-relocatable kernel will unconditionally move itself and to run
  at this address. A relocatable kernel will move itself to this address if it
  loaded below this address.

This image is such a kernel (# CONFIG_RELOCATABLE is not set in the lab’s .config; relocatable_kernel at 0x234 is 0). Its pref_address is 0x1000000 and its init_size is 0xc2d000 (12.2 MiB, file offset 0x260), so the footprint ends at 0x1c2d000, 28.2 MiB, and a guest needs at least 29 MiB for the kernel alone. load_kernel computes that and refuses a smaller guest with Error::Loader, which the API turns into 400 naming the minimum; the initrd on top of it makes 31 MiB the smallest guest this image and this initramfs boot in (the Walkthrough shows the runs). Vm::new’s own floor of 16 MiB is the VMM’s; the image decides the real minimum.

Long mode, and the registers that name it

Chapter 23 defined real mode and long mode and said why a VMM that loads the kernel itself skips the walk between them. wick writes the registers as if the walk had finished. That holds on the two machines this book ran on, neither of which has 5-level paging (la57): the image’s xloadflags has XLF_5LEVEL_ENABLED set (header.S:376-382, 0x61), and on a CPU with la57 the stub finds CR4.LA57 clear against the 5-level mode it wants (compressed/pgtable_64.c:122-137) and takes a trampoline that drops to 32-bit protected mode with paging off, below 1 MiB, and comes back. That branch exists and this book has not run it; it needs low memory backed and identity-mapped, which wick provides, and possibly the TSS and identity-map regions below. Four registers carry the result:

  • CR0 is a control register of flag bits: bit 0, PE (protection enable), and bit 31, PG (paging on). CR0.PG is the on switch that satp.MODE is on RISC-V (chapter 4).
  • CR4 bit 5, PAE (physical-address extension), selects the page-table format that long mode requires.
  • EFER is a model-specific register, an MSR: a register outside the general file, numbered by a 32-bit value in ecx and read with rdmsr and written with wrmsr, privileged instructions. An MSR is the x86 counterpart of a CSR (chapter 3), with a wider number that is an operand in a register rather than 12 bits in the instruction. EFER is MSR 0xc0000080; bit 8, LME (long mode enable), is what software sets, and bit 10, LMA (long mode active), is what the CPU sets when PG and LME are both on. wick writes both.
  • CR3 holds the physical address of the root of the page tables, which is the role of satp’s PPN field. What satp.MODE says in one field (translation is on, in this format) is spread over three: CR0.PG, CR4.PAE and EFER.LME.

The kernel’s own headers fix the positions. EFER’s number:

// linux v7.2.8, arch/x86/include/asm/msr-index.h:10-10
#define MSR_EFER        0xc0000080 /* extended feature register */

and the bits:

// linux v7.2.8, arch/x86/include/uapi/asm/processor-flags.h:105-106
#define X86_CR4_PAE_BIT        5 /* enable physical address extensions */
#define X86_CR4_PAE        _BITUL(X86_CR4_PAE_BIT)
// linux v7.2.8, arch/x86/include/asm/msr-index.h:22-23
#define _EFER_LME        8  /* Long mode enable */
#define _EFER_LMA        10 /* Long mode active (read-only) */

CR0.PE and CR0.PG are bits 0 and 31 (processor-flags.h:51 and :71 in the same file). The SDM sections are Control Registers and Extended Feature Enable Register in Volume 3A, chapter 2.

Paging is the same idea as chapter 4’s Sv39 with one more level. The root table is a page of 512 eight-byte entries (a PML4); each entry names a page of the next level (PDPT, PD, PT), and each level takes nine bits of the virtual address. A PD entry with its PS bit (bit 7) set is a 2 MiB leaf, which is Sv39’s superpage (chapter 4): the walk stops one level early and the entry carries the page’s physical address directly. wick maps all of guest RAM to itself, virtual address equal to physical, which is the “ident mapping” of the quote above and more than it asks. The quote says the map covers init_size bytes “from start address of loaded kernel”, and that holds only when the kernel runs where it was loaded. The stub works at its runtime start plus init_size (head_64.S:329-334), and for this image that is 0x1c2d000, not 0x100000 + init_size: with the map limited to 14 MiB (which covers the documented range) the guest faults at its first push (rip=0x100239, cr2=0x1bf73f8), and 14, 16, 26 and 28 MiB all end in an empty console and a Shutdown exit, while 30 MiB boots (an independent check on talos, 2026-10-01). The map must reach the runtime footprint, the zero page and the command line. One PML4 entry, one PDPT entry, and one PD entry per 2 MiB of RAM:

/// Identity page tables over all of guest RAM: PML4 -> PDPT -> PD of 2 MiB pages. boot.rst 1392-1393 asks
/// for the kernel's `init_size` bytes from its load address, the zero page and the command line to be mapped;
/// the stub actually works at `runtime_start + init_size` (compressed/head_64.S:329-334), which for the lab
/// image is 0x1c2d000, not 0x100000 + init_size. The map must reach that; all of RAM is more than the minimum.
fn write_page_tables(vm: &Vm) -> Result<()> {
    let put = |value: u64, at: u64| {
        vm.mem
            .write_obj(value, GuestAddress(at))
            .map_err(|e| Error::Memory(format!("writing the page tables: {e}")))
    };
    put(PDPT_ADDR | 0x3, PML4_ADDR)?; // present | writable
    put(PD_ADDR | 0x3, PDPT_ADDR)?;
    // Present | writable | PS (bit 7: a 2 MiB page). One PD page holds 512 entries, 1 GiB.
    for i in 0..(vm.mem_size as u64).div_ceil(TWO_MIB) {
        put((i << 21) | 0x83, PD_ADDR + 8 * i)?;
    }
    Ok(())
}

Present and writable are bits 0 and 1 (_PAGE_BIT_PRESENT, _PAGE_BIT_RW, and _PAGE_BIT_PSE for bit 7 are in arch/x86/include/asm/pgtable_types.h:10-17), so a leaf is (address) | 0x83, and the two upper entries are (next table) | 0x3. No NX bit is set, so everything is executable, where an Sv39 PTE needs its X bit. One PD page holds 512 entries, which is 1 GiB, and that is why Vm::new (in the Walkthrough) refuses a guest larger than 1 GiB. The three tables sit in the three pages 0x9000 to 0xbfff, below the kernel and above the zero page.

The GDT is the part of this with no RISC-V counterpart. An x86 CPU has six segment registers (CS, DS, ES, FS, GS, SS), and each holds a 16-bit selector plus a hidden cached descriptor: a base, a limit, a type and a privilege level. In 32-bit modes the base and limit relocate and bound every access; in long mode the bases and limits of CS, DS, ES and SS are ignored (FS and GS keep their bases) and the code segment’s L bit is what selects 64-bit code. The descriptors live in the global descriptor table (GDT), an array of eight-byte records in memory, and a selector’s top bits are an index into it. A boot protocol that predates long mode and a kernel that still asks for these by number make it a relic that must be present: __BOOT_CS is entry 2, selector 0x10, and __BOOT_DS is entry 3, selector 0x18.

// linux v7.2.8, arch/x86/include/asm/segment.h:22-26
#define GDT_ENTRY_BOOT_CS    2
#define GDT_ENTRY_BOOT_DS    3
#define GDT_ENTRY_BOOT_TSS    4
#define __BOOT_CS        (GDT_ENTRY_BOOT_CS*8)
#define __BOOT_DS        (GDT_ENTRY_BOOT_DS*8)

wick’s table is four entries, the two the document names behind two null ones:

/// Null, null, `__BOOT_CS` (0x10: 64-bit code, execute/read) and `__BOOT_DS` (0x18: data,
/// read/write); "both descriptors must be 4G flat segment" (boot.rst line 1395).
const GDT: [u64; 4] = [0, 0, 0x00af_9b00_0000_ffff, 0x00cf_9300_0000_ffff];

fn write_gdt(vm: &Vm) -> Result<()> {
    for (i, entry) in GDT.iter().enumerate() {
        vm.mem
            .write_obj(*entry, GuestAddress(GDT_ADDR + 8 * i as u64))
            .map_err(|e| Error::Memory(format!("writing the GDT: {e}")))?;
    }
    Ok(())
}

0x00af9b000000ffff unpacks, from the low byte up, to a limit of 0xffff, base 0, an access byte of 0x9b (present, privilege 0, a code or data segment, type 0xb: code, execute and read, accessed) and a flags nibble of 0xa over a limit nibble of 0xf, which is a 4 KiB granularity bit (G) and the long-mode bit L, so the limit is 0xfffff pages, 4 GiB, flat. The data descriptor 0x00cf93000000ffff has access 0x93 (data, read and write, accessed) and flags 0xc: granularity and the 32-bit size bit (D/B), no L. The SDM sections are Segment Descriptors and Code- and Data-Segment Descriptor Types in Volume 3A, chapter 3. Firecracker’s table for the same protocol puts these two at entries 1 and 2 (regs.rs, the LinuxBoot arm, lines 210 to 216 at v1.15.1), not at the 2 and 3 the document names. It boots anyway: the CPU runs on the cached descriptors KVM was given, and the stub installs its own GDT before any selector would be read from the boot table. wick follows the document.

KVM does not execute lgdt or mov %ax, %ds for the VMM. KVM_SET_SREGS writes the whole special-register file in one structure, so wick sets GDTR and each segment register’s cached descriptor directly, and writes the table into memory because the protocol says a GDT must be loaded. Nothing reads it: with the write skipped the guest still boots (an independent check on talos), since the stub’s first instructions null the data selectors and install their own table, as the quote above shows. It is there to satisfy the document, and so that a kernel that did read it would find what GDTR says:

fn set_sregs(vcpu: &VcpuFd) -> Result<()> {
    // Start from what KVM has: `get_sregs` returns a valid task register and LDT, and zeroing them makes the
    // first `KVM_RUN` fail with `FailEntry(0x80000021)` on Intel.
    let mut sregs = vcpu.get_sregs()?;
    // "CS must be __BOOT_CS and DS, ES, SS must be __BOOT_DS" (boot.rst line 1397-1398).
    // Code: type 0xb = execute/read, accessed; l = 1 selects 64-bit mode.
    let code = segment(BOOT_CS, 0xb, 1, 0);
    // Data: type 0x3 = read/write, accessed; db = 1 (32-bit default size).
    let data = segment(BOOT_DS, 0x3, 0, 1);
    sregs.cs = code;
    sregs.ds = data;
    sregs.es = data;
    sregs.fs = data;
    sregs.gs = data;
    sregs.ss = data;
    sregs.gdt.base = GDT_ADDR;
    sregs.gdt.limit = (GDT.len() * 8 - 1) as u16;
    sregs.cr3 = PML4_ADDR;
    // CR4.PAE (bit 5): long mode needs physical-address extension page tables (boot.rst line 1391,
    // "64-bit mode with paging enabled").
    sregs.cr4 = 0x20;
    // CR0.PE (bit 0) | CR0.PG (bit 31): "64-bit mode with paging enabled" (boot.rst line 1391).
    sregs.cr0 = 0x8000_0001;
    // EFER.LME (bit 8) | EFER.LMA (bit 10): long mode enabled and active (boot.rst line 1391).
    sregs.efer = 0x500;
    vcpu.set_sregs(&sregs)?;
    Ok(())
}

set_sregs starts from get_sregs, not from zeroes, and that is load-bearing: it keeps the task register and the LDT that KVM set at reset, and a kvm_sregs with those zeroed makes the first KVM_RUN fail with FailEntry(0x80000021) on talos (Intel). On straylight (AMD) the same patch boots normally (checked 2026-10-02), so the failure is one VMX checks and SVM does not. Finally the general registers, with KVM_SET_REGS: the first instruction (rip), the zero page (rsi), and rflags, whose bit 1 is reserved and always reads 1 and whose bit 9, IF, is the interrupt flag, the role sstatus.SIE plays on RISC-V; rflags = 2 is “interrupts off”:

fn set_regs(vcpu: &VcpuFd, boot: &BootInfo) -> Result<()> {
    let regs = kvm_regs {
        rip: boot.entry,
        // "%rsi must hold the base address of the struct boot_params" (boot.rst line 1398-1399).
        rsi: boot.boot_params,
        // Bit 1 is reserved and always set; IF (bit 9) is clear: "interrupt must be disabled".
        rflags: 2,
        ..Default::default()
    };
    vcpu.set_regs(&regs)?;
    Ok(())
}

The figure at the top draws all of it: the memory the VMM wrote, and the four registers (GDTR, RSI, CR3, RIP) and two zero-page fields (cmd_line_ptr, ramdisk_image) that point into it.

What KVM needs on x86 that chapter 20 did not

Chapter 20’s VM was a VM fd, one memory slot and one vCPU. On x86 Vm::new does four more things before the first vCPU exists, and setup_long_mode adds KVM_SET_CPUID2, KVM_SET_SREGS and KVM_SET_REGS after it.

KVM_SET_TSS_ADDR and KVM_SET_IDENTITY_MAP_ADDR each reserve a region of guest-physical space that no slot or device may use:

// linux v7.2.8, Documentation/virt/kvm/api.rst:1447-1455
This ioctl defines the physical address of a three-page region in the guest
physical address space.  The region must be within the first 4GB of the
guest physical address space and must not conflict with any memory slot
or any mmio address.  The guest may malfunction if it accesses this memory
region.

This ioctl is required on Intel-based hosts.  This is needed on Intel hardware
because of a quirk in the virtualization implementation (see the internals
documentation when it pops into existence).
// linux v7.2.8, Documentation/virt/kvm/api.rst:1630-1641
This ioctl defines the physical address of a one-page region in the guest
physical address space.  The region must be within the first 4GB of the
guest physical address space and must not conflict with any memory slot
or any mmio address.  The guest may malfunction if it accesses this memory
region.

Setting the address to 0 will result in resetting the address to its default
(0xfffbc000).

This ioctl is required on Intel-based hosts.  This is needed on Intel hardware
because of a quirk in the virtualization implementation (see the internals
documentation when it pops into existence).

The documentation gives no reason beyond a “quirk in the virtualization implementation”, and says the guest “may malfunction” if it touches the region; wick places both just under 4 GiB (0xfffbd000 and 0xfffbc000), where no RAM or device is, and calls them on every host; the lab passes on both machines it is run on, an Intel one and an AMD one, neither with la57. With both calls removed the lab guest boots on talos (an independent check, 2026-10-01); that is all the check showed. The reason they exist is in KVM’s source, not in api.rst: vmx_set_tss_addr returns at once when the host has “unrestricted guest” (arch/x86/kvm/vmx/vmx.c:5258-5259), and the identity map is used only when EPT is on and unrestricted guest is off (:3462), so they matter to a guest that runs unpaged on a host without it, and not to this one on talos.

KVM_CREATE_IRQCHIP gives the guest an interrupt controller in the kernel, and KVM_CREATE_PIT2 a timer:

// linux v7.2.8, Documentation/virt/kvm/api.rst:856-859
Creates an interrupt controller model in the kernel.
On x86, creates a virtual ioapic, a virtual PIC (two PICs, nested), and sets up
future vcpus to have a local APIC.  IRQ routing for GSIs 0-15 is set to both
PIC and IOAPIC; GSI 16-23 only go to the IOAPIC.
// linux v7.2.8, Documentation/virt/kvm/api.rst:3030-3032
Creates an in-kernel device model for the i8254 PIT. This call is only valid
after enabling in-kernel irqchip support via KVM_CREATE_IRQCHIP. The following
parameters have to be passed::

The PIC plays the part the PLIC played for ember (chapter 5: the UART was source 10), sixteen lines wide. Chapter 23 defined the PIC and the IOAPIC and said why a guest with no ACPI or MP table never finds the second: every device interrupt arrives through the PIC, on GSIs 0 to 15, which the quote says reach both controllers. The PIT, chapter 23’s interval timer, is the 8254, the PC’s original timer chip: a counter that raises a line when it reaches zero, the job mtimecmp does for ember (chapter 6). The local APIC is the per-CPU interrupt unit, with a timer and inter-processor interrupts of its own: the part of the job that the CLINT did for ember’s hart (chapter 6), and the quote says every vCPU gets one. The guest’s log reports TSC deadline timer available, the local APIC’s timer mode, and tsc: Detected 2496.000 MHz processor on talos, the kernel’s measurement of the TSC, the time-stamp counter: a free-running cycle counter per CPU, read with rdtsc, which is mtime’s counterpart. With both in the kernel, a guest hlt and a timer tick never leave KVM: in the run counted below (talos, 2026-10-02), the exit loop saw no Hlt exit at all.

KVM_SET_CPUID2 sets the answers to the cpuid instruction. x86 has no misa or device-tree riscv,isa string; software asks the CPU what it supports by executing cpuid with a leaf number, and a VMM decides what the guest hears. The documentation’s recipe for KVM_GET_SUPPORTED_CPUID is to build the guest’s list from it:

// linux v7.2.8, Documentation/virt/kvm/api.rst:1794-1800
This ioctl returns x86 cpuid features which are supported by both the
hardware and kvm in its default configuration.  Userspace can use the
information returned by this ioctl to construct cpuid information (for
KVM_SET_CPUID2) that is consistent with hardware, kernel, and
userspace capabilities, and with user requirements (for example, the
user may wish to constrain cpuid to emulate older hardware, or for
feature consistency across a cluster).

The request is KVM_SET_CPUID2 (include/uapi/linux/kvm.h:1371, _IOW(KVMIO, 0x90, struct kvm_cpuid2)); api.rst has no section of its own for it, only the sentence above and a caveat in KVM_SET_CPUID’s section that setting it after KVM_RUN “may cause guest instability”. KVM’s list includes the hypervisor leaves, so the guest announces what it found:

// linux v7.2.8, Documentation/virt/kvm/x86/cpuid.rst:16-25
function: KVM_CPUID_SIGNATURE (0x40000000)

returns::

   eax = 0x40000001
   ebx = 0x4b4d564b
   ecx = 0x564b4d56
   edx = 0x4d

Note that this value in ebx, ecx and edx corresponds to the string "KVMKVMKVM".

The guest’s early log says Hypervisor detected: KVM and kvm-clock: Using msrs 4b564d01 and 4b564d00: the second is the paravirtual clock, which the next leaf, KVM_CPUID_FEATURES (0x40000001), advertises as KVM_FEATURE_CLOCKSOURCE2, “kvmclock available at msrs 0x4b564d00 and 0x4b564d01” (cpuid.rst:52-53). The signature leaf is in the list KVM builds (arch/x86/kvm/cpuid.c:1982).

Passing the list through unchanged is not enough. The entries are the host’s, the host CPU’s APIC ID among them, and the guest compares the APIC ID in its cpuid with the one its local APIC reports (arch/x86/kernel/cpu/topology_common.c:209-211): with the host’s, a vCPU thread on a host CPU whose APIC ID is 0x1e gives [Firmware Bug]: CPU 0: APIC ID mismatch. CPUID: 0x001e APIC: 0x0000 in the guest’s log, which happened in 5 of 10 lab runs on talos and appears in straylight’s console too. The documentation says the pass-through “requires some care” and where the ID is:

// linux v7.2.8, Documentation/virt/kvm/api.rst:9537-9549
CPU topology
~~~~~~~~~~~~

Several CPUID values include topology information for the host CPU:
0x0b and 0x1f for Intel systems, 0x8000001e for AMD systems.  Different
versions of KVM return different values for this information and userspace
should not rely on it.  Currently they return all zeroes.

If userspace wishes to set up a guest topology, it should be careful that
the values of these three leaves differ for each CPU.  In particular,
the APIC ID is found in EDX for all subleaves of 0x0b and 0x1f, and in EAX
for 0x8000001e; the latter also encodes the core id and node id in bits
7:0 of EBX and ECX respectively.

set_apic_id sets leaf 1’s EBX[31:24] (the initial APIC ID) and the topology leaves to the vCPU’s id before KVM_SET_CPUID2:

/// `KVM_GET_SUPPORTED_CPUID` returns the host's `cpuid`, APIC ID included, and the guest checks its APIC ID
/// against the one its local APIC reports (`[Firmware Bug]: CPU 0: APIC ID mismatch`). The documentation says
/// pass-through "requires some care"; it names the ID's place in leaves 0xb and 0x1f (EDX of every subleaf) and
/// 0x8000001e (EAX) (api.rst:9537-9549); leaf 1 EBX[31:24] is the initial APIC ID. Set each to the vCPU's id.
fn set_apic_id(cpuid: &mut CpuId, id: u32) {
    for e in cpuid.as_mut_slice() {
        match e.function {
            0x1 => e.ebx = (e.ebx & 0x00ff_ffff) | (id << 24),
            0xb | 0x1f => e.edx = id,
            // EBX and ECX (core id and node id, api.rst:9547-9549) are left alone: KVM returns them as 0, "Do not
            // return host topology information" (arch/x86/kvm/cpuid.c:1839-1841), which is vCPU 0's core and node.
            0x8000_001e => e.eax = id,
            _ => {}
        }
    }
}

the_guest_log_does_not_depend_on_the_host_cpu boots pinned to the highest host CPU and asserts the console holds no APIC ID mismatch line. It does not assert the absence of every [Firmware Bug] line: straylight’s console still has [Firmware Bug]: TSC doesn't count with P0 frequency!, which is that AMD CPU’s own and does not depend on the thread’s placement.

KVM_SET_SREGS and KVM_SET_REGS replace chapter 20’s KVM_SET_ONE_REG for the registers the protocol names: two structures, copied whole, where RISC-V asked for one register per call by id.

// linux v7.2.8, Documentation/virt/kvm/api.rst:487-495
  struct kvm_sregs {
    struct kvm_segment cs, ds, es, fs, gs, ss;
    struct kvm_segment tr, ldt;
    struct kvm_dtable gdt, idt;
    __u64 cr0, cr2, cr3, cr4, cr8;
    __u64 efer;
    __u64 apic_base;
    __u64 interrupt_bitmap[(KVM_NR_INTERRUPTS + 63) / 64];
  };

The last one is KVM_IRQFD, which is chapter 21’s missing half. An irqfd is an eventfd that KVM turns into an interrupt line (chapter 23 gave the one sentence; this is the mechanism):

// linux v7.2.8, Documentation/virt/kvm/api.rst:3187-3193
Allows setting an eventfd to directly trigger a guest interrupt.
kvm_irqfd.fd specifies the file descriptor to use as the eventfd and
kvm_irqfd.gsi specifies the irqchip pin toggled by this event.  When
an event is triggered on the eventfd, an interrupt is injected into
the guest using the specified gsi pin.  The irqfd is removed using
the KVM_IRQFD_FLAG_DEASSIGN flag, specifying both kvm_irqfd.fd
and kvm_irqfd.gsi.

The VMM registers an eventfd and a GSI once; from then on any thread, including a device model running on the vCPU thread, raises the interrupt by writing the integer 1 to the eventfd, and KVM injects it, with no ioctl and no signal. SerialDevice::new does it for GSI 4, the line the PC wires to its first serial port.

Exits, the 8250, and why its interrupt matters

Chapter 20’s loop had one exit it accepted, and chapter 21 added KVM_EXIT_MMIO for devices. On x86 the second device address space, port I/O (chapter 21 named it: 16-bit port numbers reached by in and out), arrives as KVM_EXIT_IO. The struct is in chapter 21; its use is in this loop:

// linux v7.2.8, Documentation/virt/kvm/api.rst:6706-6710
If exit_reason is KVM_EXIT_IO, then the vcpu has
executed a port I/O instruction which could not be satisfied by kvm.
data_offset describes where the data is located (KVM_EXIT_IO_OUT) or
where kvm expects application code to place the data for the next
KVM_RUN invocation (KVM_EXIT_IO_IN).  Data format is a packed array.
fn run_loop(vcpu: &mut VcpuFd, pio: &Bus, mmio: &Bus, stop: &AtomicBool) -> Leave {
    loop {
        if stop.load(Ordering::SeqCst) {
            return complete_pending_exit(vcpu);
        }
        match vcpu.run() {
            Ok(VcpuExit::IoOut(port, data)) => {
                pio.write(port as u64, data);
            }
            Ok(VcpuExit::IoIn(port, data)) => {
                // A port nobody claims reads as all ones, as on a bus with nothing driving it.
                if !pio.read(port as u64, data) {
                    data.fill(0xff);
                }
            }
            Ok(VcpuExit::MmioWrite(addr, data)) => {
                mmio.write(addr, data);
            }
            Ok(VcpuExit::MmioRead(addr, data)) => {
                if !mmio.read(addr, data) {
                    data.fill(0xff);
                }
            }
            Ok(VcpuExit::Shutdown) => return Leave::Ended(VcpuStop::Shutdown),
            Ok(other) => return Leave::Ended(VcpuStop::Failed(format!("{other:?}"))),
            // A kick, or a spurious signal: clear what the handler set and look at the flag again
            // (Firecracker clears it the same way, vstate/vcpu.rs:395-396).
            Err(e) if e.errno() == libc::EINTR || e.errno() == libc::EAGAIN => set_immediate_exit(0),
            Err(e) => return Leave::Ended(VcpuStop::Failed(format!("{e:?}"))),
        }
    }
}

kvm-ioctls has already turned data_offset into a slice, so the loop sees IoOut(port, data) and IoIn(port, data): the first goes to the port bus, the second is filled in by the device or, if no device claims the port, with all ones, “as on a bus with nothing driving it”, which is what a real PC reads from an empty port. The same rule covers unclaimed MMIO reads. The loop’s one success path is Shutdown; any other exit reason ends the run as Failed, with its name, because a lab that accepted every exit would pass a guest that never ran. Shutdown is a triple fault: the CPU faults while delivering a fault while delivering a fault, which on a real machine resets it. KVM reports it as KVM_EXIT_SHUTDOWN, and reboot=t is how the guest asks for one on purpose: the kernel clears the interrupt table and executes int3.

// linux v7.2.8, arch/x86/kernel/reboot.c:659-661
        case BOOT_TRIPLE:
            idt_invalidate();
            __asm__ __volatile__("int3");
// linux v7.2.8, arch/x86/kvm/x86.c:857-861
    if (prev_nr == DF_VECTOR) {
        /* triple fault -> shutdown */
        kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
        return;
    }

A Linux guest probes more than it uses. Counting the exits of one lab boot with a ten-line patch to the loop in a scratch copy (talos, 2026-10-02; the same boot on straylight, AMD, in parentheses): 14,082 exits (15,456), of which 6,857 (7,517) are writes to port 0x3f8, one per byte of console output, and 6,676 (7,349) are reads of 0x3fd, the 8250’s line-status register that the driver polls before each byte. The 8250’s own other registers account for 497 more (0x3f9, the interrupt-enable register, 127 reads and 278 writes; 0x3fa, 0x3fb, 0x3fc, 0x3fe and three reads of 0x3f8). The rest are the kernel probing hardware that is not there: 16 reads of port 0x60 and 17 of 0x64 (the keyboard controller, the i8042), and 3 reads and 3 writes each at ports 0x2e9, 0x2f9 and 0x3e9, the kernel’s probe of the PC’s other three serial ports, answered with 0xff. On straylight there is also one MmioRead at 0xfed803c0, a register of the AMD chipset the kernel reads once and which the loop answers with all ones; on talos there are none. Neither host’s counts are pinned by the lab: they depend on the kernel’s log text and on the host’s CPU, and the capture refuses them.

The 8250 is the PC’s serial port: eight byte-wide registers at port 0x3f8 to 0x3ff, the family chapter 2’s ns16550a belongs to. vm-superio’s Serial is its register model, SerialDevice puts it on the port bus and the console writes its output to stdout, one flush per byte so a guest that dies leaves its last line behind. The device matters for a second reason besides output. It is interrupt driven, and without the interrupt the guest’s userland output never leaves:

pub fn new(vm: &Vm, out: Box<dyn Write + Send>) -> Result<Arc<Mutex<SerialDevice>>> {
    let evt = EventFd::new(libc::EFD_NONBLOCK)?;
    // Without the irqfd the guest's tty layer never learns the transmit buffer drained and
    // userland output is lost; only kernel printk, which polls, appears.
    vm.fd.register_irqfd(&evt, SERIAL_IRQ)?;
    let serial = Serial::new(IrqTrigger(evt), out);
    Ok(Arc::new(Mutex::new(SerialDevice { serial, errors: 0 })))
}

The kernel has two ways to write a byte to the 8250. printk, the kernel’s own log, writes by polling: it waits for the line-status register to say the transmitter is empty, then stores the byte. The tty layer, the path init’s echo takes, queues bytes and asks the UART to interrupt when it can take them, by setting the “transmit holding register empty” enable bit, THRI, in the interrupt-enable register:

// linux v7.2.8, drivers/tty/serial/8250/8250.h:202-206
    if (up->ier & UART_IER_THRI)
        return false;
    up->ier |= UART_IER_THRI;
    serial_out(up, UART_IER, up->ier);
    return true;

Setting the bit sends nothing. The bytes leave from the interrupt handler, which runs when the UART says the register is empty and the bit is set:

// linux v7.2.8, drivers/tty/serial/8250/8250_port.c:1835-1837
    if ((status & UART_LSR_THRE) && (up->ier & UART_IER_THRI)) {
        if (!up->dma || up->dma->tx_err)
            serial8250_tx_chars(up);

Exercise (a) deletes the irqfd and shows what that costs.

The three threads and the request channel

The figure of chapter 23 had three threads; here they are. The API thread (wick_api) is the accept loop of the Walkthrough: one connection at a time, http::read_request, routes::parse, a call to the VMM thread, http::write_response. It holds no guest memory and no KVM handle. The VMM thread is the process’s main thread; it runs Vmm::run, an event loop over epoll that owns the configuration, the state (NotStarted, Running, Paused) and, once the guest exists, the Vm. The vCPU thread (wick_vcpu0) runs the exit loop above.

The API thread and the VMM thread talk through a channel of requests, each carrying the sender its reply comes back on. A thread that sleeps in epoll_wait can be woken by a file descriptor and by nothing else, and a Rust mpsc::Receiver is not a file descriptor, so every send is followed by a write to an eventfd (chapter 23) that the loop is waiting on:

/// The API thread's end: a queue of requests, each carrying the sender its reply goes back on, and
/// an eventfd that wakes the VMM thread's loop.
pub struct VmmChannel {
    tx: mpsc::Sender<Envelope>,
    wake: EventFd,
}

impl VmmChannel {
    /// Send one request and wait for its answer.
    pub fn call(&self, req: Request) -> Result<Reply> {
        let (reply_tx, reply_rx) = mpsc::channel();
        let gone = || Error::State("the VMM thread is not running".into());
        self.tx.send((req, reply_tx)).map_err(|_| gone())?;
        self.wake.write(1)?;
        reply_rx.recv().map_err(|_| gone())?
    }
}

call is synchronous: the API thread has nothing else to do while the VMM thread answers, and the answer, Ok(Reply) or Err(Error), is all the API thread ever learns of the machine.

The loop uses event-manager 0.4.2, the rust-vmm crate that wraps epoll. Its EventManager<T> is generic over one subscriber type, so a program with several kinds of event source needs either an enum of them or a boxed trait object. wick has the other option: Vmm is the only subscriber, and its two eventfds (the request channel’s and the vCPU thread’s done) are told apart by the integer each was registered with, which Events::with_data attaches and events.data() returns:

/// The VMM thread's loop. Blocks until the guest's vCPU stops; returns the process's exit code:
/// 0 for a `Shutdown` exit, 1 for anything else.
pub fn run(self) -> i32 {
    // `EventManager` is generic over one subscriber type, so `Vmm` is the only subscriber and
    // tells its two eventfds apart by the token each was registered with.
    let mut manager = match EventManager::<Vmm>::new() {
        Ok(m) => m,
        Err(e) => {
            eprintln!("wick: FAIL event loop: {e:?}");
            return 1;
        }
    };
    let id = manager.add_subscriber(self);
    loop {
        if let Err(e) = manager.run() {
            eprintln!("wick: FAIL event loop: {e:?}");
            return 1;
        }
        // INVARIANT: `id` names the one subscriber added above and it is never removed.
        if let Some(code) = manager.subscriber_mut(id).expect("the vmm subscriber").exit_code {
            return code;
        }
    }
}

When the guest ends, the vCPU thread writes 1 to done (a pause also ends the exit loop, and only returns the thread to its parked state; chapter 27). The VMM thread joins it, and the exit is Shutdown (code 0, wick: vcpu 0 exit Shutdown) or anything else (code 1, wick: FAIL vcpu 0 exit …). That is the whole success condition: wick exits 0 only after a Shutdown exit following an InstanceStart, never because a timer expired or a request said so. The Lab section shows what that condition does not prove.

A running guest can be stopped from outside only by signalling its thread, because a thread inside KVM_RUN can receive nothing else. The kick is how, and the vCPU thread listens for it so that the VMM thread never writes into a page the vCPU thread is using:

/// Stop a running guest and wait until the thread has parked. Only the vCPU thread ever writes its `immediate_exit`:
/// this function sets the flag, then sends `SIGRTMIN`, and `kick_handler` does the write on the target thread. The flag is
/// stored before the signal, so wherever the signal lands the thread reaches the flag check with `stop == true`:
///
/// 1. Just after a resume, before the loop's first check: `MY_RUN` is set (the thread sets it before it reports ready),
///    so the handler may write `immediate_exit = 1`, and the first flag check sees `stop` before any `KVM_RUN` is made.
/// 2. In user mode, between the flag check and `KVM_RUN`: the handler sets `immediate_exit = 1`,
///    so the `KVM_RUN` that follows returns `EINTR` at once without entering the guest.
/// 3. Inside `KVM_RUN`: the signal makes it return `EINTR`; the handler runs on the way out,
///    before Rust sees the error.
///
/// Both `EINTR` paths clear `immediate_exit` and `continue` to the flag check, which now completes the pending exit,
/// parks the thread and answers `Paused`. A handler that fires after that (a second kick, or a signal that was in
/// flight) leaves a stale 1 in the page; the next resume clears it on the vCPU thread before the loop's first check, and
/// nothing reads the byte in between. Firecracker v1.15.1 differs: its handler is only a fence (vstate/vcpu.rs:113-115)
/// and its VMM thread writes `immediate_exit` (:608-609) through a second mapping of the same page: the VMM side holds a
/// dup'd vCPU fd with its own mmap (`copy_kvm_vcpu_fd` :157-165, `VcpuHandle.vcpu_fd` :565). wick has one mapping and
/// keeps every write on the vCPU thread. A paused vCPU is paused: this returns at once.
pub fn pause_within(&mut self, within: Duration) -> Result<()> {
    // A request still outstanding is settled first; a pause that is outstanding is the one wanted.
    self.settle(within)?;
    if self.paused {
        return Ok(());
    }
    self.stop.store(true, Ordering::SeqCst);
    self.pending = Pending::Pause;
    self.kick();
    self.settle(within)
}

The signal is sent with tgkill of the process id and thread id that were read before the filter went on, and not with pthread_kill, because glibc’s makes a getpid call first and chapter 26’s list has none. Nothing in this chapter calls the kick in production: the request that does, PATCH /vm with Paused, is chapter 27’s, and wick/tests/boot.rs exercises it against a guest that spins (a_kick_right_after_resume_is_never_lost pauses and resumes it 200 times with no delay between, each pause bounded by two seconds, without a lost kick). It is here because the thread layout the chapter draws is the one the kick needs: one thread owns the page, the other asks.

The axes

Chapter 14’s three axes for one wick guest, from what this chapter built. Shared: the host kernel, and KVM inside it, between every guest of the machine; and, inside one process, the guest’s RAM. GuestMemoryMmap is one mapping in the wick process, which the vCPU thread, the VMM thread and any device model can all address; the API thread’s code never takes a pointer into it, but nothing in the process boundary stops it from doing so, which is chapter 26’s seccomp filter’s job, not the type system’s. Trusted: KVM and the host kernel below it, wick itself, and the two files the API client names, which are the operator’s: the API client is trusted to name a real kernel and a real initramfs, and the guest that runs inside them is not. What wick does check is the name and the file. A path must be a regular file, and the type is read from metadata before anything is opened (a FIFO would block the VMM thread in open and stop the control plane), the open is non-blocking, the length is non-zero (a /proc file reports none) and no longer than guest RAM, and the initrd’s read is capped at that bound (read_capped), so a sparse 3 GiB initrd or a /proc file cannot make wick allocate without limit; the kernel image is read by linux-loader, bounded by the file’s own length (already checked against RAM) and by guest memory. Of the kernel’s own header it checks what it reads, each against what it governs: the file’s size against setup_sects and syssize (a consistency check, not proof), version at least 2.12, xloadflags declaring the 64-bit entry, kernel_alignment a power of two for a relocatable kernel, initrd_addr_max and the initrd’s end, cmdline_size and the command line’s length, and the footprint against guest RAM. What it cannot check is that init_size and pref_address tell the truth: a header that lies about init_size (0 or 0x1000 were tried) boots into the same silence as a guest that is too small, and a non-relocatable kernel ignores the header’s pref_address and uses the address it was compiled for (LOAD_PHYSICAL_ADDR, head_64.S:325), so wick takes both on the image’s word. The copy: a guest’s console costs one exit per byte, as counted above, and each byte is handled by the vCPU thread in its exit handler; the kernel and the initrd are copied once, into guest RAM, by load_kernel (2.6 MB of initrd for this lab). The guest never copies a page to the VMM: it shares them.

Walkthrough

The listings are in the order a boot runs them: the guest’s build, the VM, the memory the VMM writes, the CPU, the run, and then the control plane that started it. Each is the repository’s file, kept equal to it by make sync.

The guest

labs/ch24/build.sh builds the kernel and the initramfs the labs of chapters 24 to 28 boot. Its configuration block is the part that is the chapter’s:

fetch "$linux" "$LINUX_URL" "$LINUX_TAG"
if [ ! -f "$linux/arch/x86/boot/bzImage" ]; then
  logged "$cache/linux-tinyconfig.log" make -C "$linux" ARCH=x86_64 CROSS_COMPILE= tinyconfig
  opts="64BIT PRINTK TTY SERIAL_8250 SERIAL_8250_CONSOLE EARLY_PRINTK BLK_DEV_INITRD
    BINFMT_ELF BINFMT_SCRIPT BLOCK NETDEVICES HYPERVISOR_GUEST KVM_GUEST PARAVIRT
    VIRTIO_MENU VIRTIO VIRTIO_MMIO VIRTIO_MMIO_CMDLINE_DEVICES VIRTIO_BLK VIRTIO_NET
    VSOCKETS VIRTIO_VSOCKETS NET INET UNIX PROC_FS SYSFS DEVTMPFS DEVTMPFS_MOUNT"
  args=()
  for o in $opts; do args+=(-e "$o"); done
  # A shallow tag clone would otherwise give uname -r a +/-g suffix.
  ( cd "$linux" && scripts/config --file .config "${args[@]}" -d LOCALVERSION_AUTO )
  logged "$cache/linux-olddefconfig.log" make -C "$linux" ARCH=x86_64 CROSS_COMPILE= olddefconfig
  # olddefconfig silently drops an option whose dependencies are off.
  for o in $opts; do
    grep -q "^CONFIG_$o=y\$" "$linux/.config" || { echo "build.sh: CONFIG_$o did not stick in the kernel config" >&2; exit 1; }
  done
  logged "$cache/linux-build.log" make -C "$linux" -j"$JOBS" ARCH=x86_64 CROSS_COMPILE= bzImage
fi

It starts from tinyconfig, the smallest kernel the tree can configure, and turns on exactly what the lab needs: 64BIT; a console (PRINTK, TTY, SERIAL_8250, SERIAL_8250_CONSOLE, EARLY_PRINTK); an initrd and its executable formats (BLK_DEV_INITRD, BINFMT_ELF, BINFMT_SCRIPT, for the #!/bin/sh of init); the paravirtual pieces (HYPERVISOR_GUEST, KVM_GUEST, PARAVIRT); and the virtio drivers and the network, socket and file-system options that chapters 25 to 27 use, enabled now so that one kernel serves them all. olddefconfig silently drops an option whose dependencies are off, which is why the loop after it greps for every option: without BLOCK, NETDEVICES, VIRTIO_MENU or HYPERVISOR_GUEST, the virtio and paravirt options vanish with no message, and a kernel without virtio_blk fails chapter 25 in the wrong place. The result is a 1.7 MB bzImage (1,704,960 bytes for the lab’s build on talos) and, with BusyBox and the lab’s init, a 2.6 MB uncompressed cpio (2,626,560 bytes: ls -l labs/ch24/out/initramfs.cpio after make lab CH=24 on talos, 2026-10-02). labs/ch24/overlay/init is the program the kernel runs first:

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"
exec >/dev/null 2>&1 </dev/null
reboot -f

The VM

Vm::new does chapter 20’s three steps and the four x86 ones of the Mechanism section, then registers RAM as slot 0 at guest-physical address 0:

pub fn new(mem_size_mib: usize) -> Result<Vm> {
    check_mem_mib(mem_size_mib)?;
    let mem_size = mem_size_mib << 20;
    let kvm = Kvm::new()?;
    // api.rst:144-145: "Applications should refuse to run if KVM_GET_API_VERSION returns a value other than 12."
    let api = kvm.get_api_version();
    if api != 12 {
        return Err(Error::Config(format!("KVM API version {api}: wick needs 12")));
    }
    let fd = kvm.create_vm()?;
    fd.set_tss_address(TSS_ADDR)?;
    fd.set_identity_map_address(IDENTITY_MAP_ADDR)?;
    fd.create_irq_chip()?;
    // The speaker flag keeps writes to port 0x61 inside the kernel (Firecracker v1.15.1 src/vmm/src/arch/x86_64/vm.rs:169-177).
    fd.create_pit2(kvm_pit_config { flags: KVM_PIT_SPEAKER_DUMMY, ..Default::default() })?;

    let mem = GuestMemoryMmap::from_ranges(&[(GuestAddress(0), mem_size)])
        .map_err(|e| Error::Memory(e.to_string()))?;
    let host = mem
        .get_host_address(GuestAddress(0))
        .map_err(|e| Error::Memory(e.to_string()))?;
    let region = kvm_userspace_memory_region {
        slot: 0,
        flags: 0,
        guest_phys_addr: 0,
        memory_size: mem_size as u64,
        userspace_addr: host as u64,
    };
    // SAFETY: `host` is the start of the mapping `mem` owns, `mem_size` bytes long, and the
    // returned Vm keeps the Arc alive for as long as the VM fd exists.
    unsafe { fd.set_user_memory_region(region)? };
    Ok(Vm { kvm, fd, mem: Arc::new(mem), mem_size })
}

get_host_address and set_user_memory_region are chapter 20’s mmap and KVM_SET_USER_MEMORY_REGION; the second is unsafe because KVM keeps the host address, and the SAFETY comment names what keeps it valid (the Vm owns the Arc of the mapping for as long as the VM fd lives).

The memory the VMM writes

load_kernel is the order of the protocol’s duties: load, check, command line, initrd, zero page.

/// Load `kernel` (a bzImage), `initrd` and `cmdline` into guest memory and return the entry
/// point. `cmdline` must be final: it is checked against the image's limit and written now.
pub fn load_kernel(vm: &Vm, kernel: &Path, initrd: Option<&Path>, cmdline: &Cmdline) -> Result<BootInfo> {
    let mem: &GuestMemoryMmap = vm.mem.as_ref();
    let mem_size = vm.mem_size as u64;

    let (mut f, file_len) = open_bounded(kernel, mem_size, "kernel")?;
    let loaded = BzImage::load(mem, None, &mut f, Some(GuestAddress(HIMEM_START)))
        .map_err(|e| Error::Loader(format!("{}: {e}", kernel.display())))?;
    let hdr = loaded
        .setup_header
        .ok_or_else(|| Error::Loader("the bzImage has no setup header".into()))?;
    let version = hdr.version;
    check_protocol(version)?;
    check_image_size(file_len, hdr.setup_sects, hdr.syssize)?;
    let (xloadflags, init_size, addr_max, max_cmdline) =
        (hdr.xloadflags, hdr.init_size as u64, hdr.initrd_addr_max, hdr.cmdline_size);
    if xloadflags & XLF_KERNEL_64 == 0 {
        return Err(Error::Loader(format!(
            "{}: xloadflags {xloadflags:#x} lacks XLF_KERNEL_64, no 64-bit entry point",
            kernel.display()
        )));
    }
    // The decompressor works in `init_size` bytes from the kernel's *runtime* start address (boot.rst
    // 885-905), which is not the load address: `pref_address` for a kernel that cannot relocate.
    let (relocatable, pref_address, alignment) = (hdr.relocatable_kernel, hdr.pref_address, hdr.kernel_alignment);
    let footprint = kernel_footprint(loaded.kernel_end, loaded.kernel_load.0, relocatable != 0, pref_address, alignment as u64, init_size)?;
    if footprint > mem_size {
        return Err(Error::Loader(format!(
            "the kernel's footprint ends at {footprint:#x}, past the {mem_size:#x} bytes of guest RAM: this image needs a guest of at least {} MiB",
            footprint.div_ceil(1 << 20)
        )));
    }

    let cmdline_len = cmdline
        .as_cstring()
        .map_err(|e| Error::Loader(format!("command line: {e}")))?
        .as_bytes()
        .len();
    check_cmdline(cmdline_len, max_cmdline)?;
    load_cmdline(mem, GuestAddress(CMDLINE_ADDR), cmdline).map_err(|e| Error::Loader(format!("command line: {e}")))?;

    let initrd = match initrd {
        None => None,
        Some(path) => {
            let (file, _) = open_bounded(path, mem_size, "initrd")?;
            let data = read_capped(file, mem_size, path)?;
            let addr = initrd_load_addr(mem_size, data.len() as u64, footprint, addr_max)?;
            mem.write_slice(&data, GuestAddress(addr))
                .map_err(|e| Error::Memory(format!("writing the initrd: {e}")))?;
            Some((addr, data.len() as u32))
        }
    };

    let bp = fill_boot_params(hdr, initrd, mem_size);
    let params = BootParams::new::<boot_params>(&bp, GuestAddress(ZERO_PAGE));
    LinuxBootConfigurator::write_bootparams::<GuestMemoryMmap>(&params, mem)
        .map_err(|e| Error::Loader(format!("writing boot_params: {e}")))?;

    Ok(BootInfo { entry: loaded.kernel_load.0 + ENTRY_OFFSET, boot_params: ZERO_PAGE })
}

open_bounded comes first (a regular, non-empty file no longer than guest RAM, opened without blocking), then BzImage::load places the protected-mode part at 0x100000 and returns the header. linux-loader loads whatever bytes follow the setup sectors and never looks at syssize, so a truncated image is accepted and dies silently; check_image_size requires the file’s length to equal (setup_sects, or 4 if it is 0, plus the boot sector) × 512 + syssize × 16, with at most 15 bytes over for the paragraph rounding (a consistency check, not proof; a distribution kernel signed for Secure Boot has a signature appended after that length and would be refused, which is stated from the rule and not run here, and is acceptable for a VMM that boots kernels its operator built), and check_protocol refuses a header older than 2.12. xloadflags bit 0 is checked next (XLF_KERNEL_64, “this kernel has the legacy 64-bit entry point at 0x200”, boot.rst:706), because everything after assumes that entry exists. The footprint is the larger of where the loaded bytes end and where init_size bytes from the runtime start end (kernel_footprint, the Mechanism section’s algorithm). That arithmetic is checked: the header is a client-named file’s, and a pref_address near the top of the address space would wrap to a footprint that looks small, so a sum that overflows is an Error::Loader. The 2.12 floor is xloadflags’s own version (boot.rst:699; pref_address is “2.10+”, :873), and the error names the version found. A relocatable image whose kernel_alignment is not a power of two is refused too, since the kernel does mask arithmetic with it (head_64.S:317-321). Then the command line is measured against cmdline_size, and written, and the initrd is placed:

/// Where an initrd of `size` bytes goes: the top of RAM, aligned down to a page, the way Firecracker
/// does it (v1.15.1 src/vmm/src/arch/x86_64/mod.rs:159-173, `initrd_load_addr`). It must sit below
/// `initrd_addr_max` (boot.rst 635, the highest legal byte) and clear of the kernel's `footprint`.
fn initrd_load_addr(mem_size: u64, size: u64, footprint: u64, addr_max: u32) -> Result<u64> {
    if size == 0 {
        return Err(Error::Loader("the initrd is empty".into()));
    }
    if size > mem_size {
        return Err(Error::Loader(format!("initrd of {size} bytes does not fit in {mem_size} bytes of guest RAM")));
    }
    let addr = (mem_size - size) & !(PAGE_SIZE - 1);
    let last = addr.checked_add(size - 1).ok_or_else(|| Error::Loader("the initrd's end overflows".into()))?;
    if last > addr_max as u64 {
        return Err(Error::Loader(format!(
            "initrd would end at {last:#x}, above initrd_addr_max {addr_max:#x}"
        )));
    }
    if addr < footprint {
        return Err(Error::Loader(format!(
            "initrd at {addr:#x} overlaps the kernel, whose footprint ends at {footprint:#x}"
        )));
    }
    Ok(addr)
}

The top of RAM, aligned down to a page, is where Firecracker puts the initrd too (initrd_load_addr, src/vmm/src/arch/x86_64/mod.rs:159-173 at v1.15.1); the two refusals are the two limits the document names, initrd_addr_max and the kernel’s own footprint. Measured from the load address (0x100000), the footprint comes out 15 MiB too low, and a guest too small for it is accepted and dies silently. On talos (2026-10-02), with a build of wick that measured from the load address, PUT /machine-config of 16, 20 and 28 MiB and the lab’s other requests gave PUT /actions 204, an empty console and wick: vcpu 0 exit Shutdown with exit code 0 (derived from nm and the disassembly of the stub; the runs show only the silence, and the registers at the Shutdown exit of an independent check on talos (2026-10-01) agree for 28 MiB: at 16 and 20 MiB the stub’s stack pointer, 0x1bf7400, is itself past the end of RAM, so its first push faults; at 28 MiB the stack is inside RAM and the stub gets further: it copies _bss - startup_32 bytes (head_64.S:419-424; _bss is 0x19c400) to 0x1a57000, the copy ends at 0x1bf3400, inside RAM, the stub jumps to it and faults clearing its BSS, which runs to 0x1c0b960 (_ebss is 0x1b4960, head_64.S:450-455); the examiner’s registers at the exit were rip=0x1becd97, in the relocated copy, and rdi and cr2 both 0x1c00000). With the footprint measured from the runtime start, as listed, the same three sizes give PUT /actions 400 and {"fault_message":"kernel loader: the kernel's footprint ends at 0x1c2d000, past the 0x1000000 bytes of guest RAM: this image needs a guest of at least 29 MiB"} (and 0x1400000, 0x1c00000 for 20 and 28); 29 and 30 MiB are refused because the initrd would overlap the footprint (initrd at 0x1a7e000 overlaps the kernel, whose footprint ends at 0x1c2d000), and 31 and 32 MiB boot. wick/tests/boot.rs pins the first three. The zero page is the next two listings. The E820 map is written first, two records:

/// Two RAM ranges, the way a PC BIOS would report them: conventional memory below the
/// EBDA at 0x9fc00, and everything from 1 MiB up. The hole between is the legacy BIOS area.
fn fill_e820(bp: &mut boot_params, mem_size: u64) {
    bp.e820_table[0].addr = 0;
    bp.e820_table[0].size = 0x9fc00;
    bp.e820_table[0].r#type = E820_RAM;
    bp.e820_table[1].addr = HIMEM_START;
    bp.e820_table[1].size = mem_size - HIMEM_START;
    bp.e820_table[1].r#type = E820_RAM;
    bp.e820_entries = 2;
}

and the rest of the zero page is the header the image carried plus what only the loader knows:

/// The zero page: the header the kernel image carried, plus what only the loader knows.
/// `cmdline_size` stays as the image set it: the loader only reads that field (boot.rst 728-737).
fn fill_boot_params(hdr: setup_header, initrd: Option<(u64, u32)>, mem_size: u64) -> boot_params {
    let mut bp = boot_params { hdr, ..Default::default() };
    // The image's header carries whatever its build left in the fields a loader owns. Zero them (boot.rst
    // "write" fields wick does not set): a stale ramdisk or setup_data would be believed by the kernel.
    bp.hdr.ramdisk_image = 0;
    bp.hdr.ramdisk_size = 0;
    bp.hdr.ext_loader_ver = 0;
    bp.hdr.ext_loader_type = 0;
    bp.hdr.hardware_subarch = 0;
    bp.hdr.hardware_subarch_data = 0;
    bp.hdr.setup_data = 0;
    bp.hdr.type_of_loader = LOADER_UNDEFINED;
    bp.hdr.cmd_line_ptr = CMDLINE_ADDR as u32;
    bp.hdr.loadflags |= CAN_USE_HEAP;
    bp.hdr.heap_end_ptr = 0xe000; // harmless in the 64-bit protocol
    if let Some((addr, size)) = initrd {
        bp.hdr.ramdisk_image = addr as u32;
        bp.hdr.ramdisk_size = size;
    }
    fill_e820(&mut bp, mem_size);
    bp
}

boot_params { hdr, ..Default::default() } is the document’s “initialized to all zero”, with the setup header copied in; type_of_loader is 0xff, the document’s “otherwise” for a boot loader with no assigned ID:

// linux v7.2.8, Documentation/arch/x86/boot.rst:419-421
  If your boot loader has an assigned ID (see table below), enter
  0xTV here, where T is an identifier for the boot loader and V is
  a version number.  Otherwise, enter 0xFF here.

and a non-zero type_of_loader is what makes the kernel look at the initrd at all: setup.c:355-357 and :369-371 return with “No initrd provided by bootloader” when it is 0, and a run of the lab with wick writing 0 there (on talos, 2026-10-02) printed no RAMDISK: line and ended in Kernel panic - not syncing: VFS: Unable to mount root fs. loadflags keeps the image’s own bits and adds CAN_USE_HEAP, which the document says only affects the 16-bit setup code wick never runs. cmdline_size is untouched. Written to 0x7000, this is what %rsi will point at.

The CPU

setup_long_mode is the sequence the Mechanism section described, in the order its dependencies need: the CPUID answers, the memory the registers will point at, the special registers, the general registers.

pub fn setup_long_mode(vm: &Vm, vcpu: &VcpuFd, boot: &BootInfo) -> Result<()> {
    let mut cpuid = vm.kvm.get_supported_cpuid(KVM_MAX_CPUID_ENTRIES)?;
    set_apic_id(&mut cpuid, VCPU_ID);
    mask_nested_virtualization(&mut cpuid);
    vcpu.set_cpuid2(&cpuid)?;
    write_gdt(vm)?;
    write_page_tables(vm)?;
    set_sregs(vcpu)?;
    set_regs(vcpu, boot)
}

The GDT, page tables, special registers and general registers are the four listings above in the Mechanism section. One line of setup_long_mode is chapter 27’s: mask_nested_virtualization clears the VMX bit (leaf 1, ecx bit 5, Intel) and the SVM bit (leaf 0x80000001, ecx bit 2, AMD) from the CPUID the guest is given, so that no guest holds nested state that a snapshot would have to carry.

The run

The vCPU thread is the exit loop (above) in a thread of its own. spawn_vcpu_parked hands the VcpuFd to wick_vcpu0, which sets itself up and waits on a channel; VcpuHandle::resume lets it run the loop, and it writes to done when the guest ends (spawn_vcpu is the two calls together, for callers that want no wait). The thread lives as long as the machine: a kick (above) does not end it but parks it again, which chapter 27 builds on. The 8250 is SerialDevice, above. What starts all of it is InstanceStart:

/// Build the machine from the configuration and start its vCPU. Everything that can fail before the filter goes on runs
/// before the state changes, so such a failure leaves the VMM `NotStarted` and serving. The one step after the filter,
/// releasing the thread, can fail too, and then the machine stays built: `Running` if the resume was sent and is unanswered,
/// `Paused` if the thread never got it (chapter 24).
fn instance_start(&mut self) -> Result<()> {
    if self.state != VmState::NotStarted {
        return Err(Error::State("InstanceStart can only be called once".into()));
    }
    let boot = self
        .config
        .boot_source
        .clone()
        .ok_or_else(|| Error::Config("no boot source: PUT /boot-source before InstanceStart".into()))?;
    let mem_mib = self.config.machine.mem_size_mib;

    let vm = Vm::new(mem_mib)?;
    let (cmdline, mmio) = attach_devices(self, &vm, build_cmdline(effective_boot_args(&boot))?)?;
    let info = load_kernel(&vm, Path::new(&boot.kernel_image_path), boot.initrd_path.as_deref().map(Path::new), &cmdline)?;

    let vcpu = vm.fd.create_vcpu(0)?;
    setup_long_mode(&vm, &vcpu, &info)?;
    let console = self.console_writer();
    let mut pio = Bus::new();
    let serial = SerialDevice::new(&vm, console)?;
    pio.insert(SERIAL_PORT, 8, serial.clone())?;
    let probe = Probe::new(&vm.kvm)?;
    let api_version = vm.kvm.get_api_version();
    // Chapter 26: every thread exists before the filter does, because the filter cannot let a thread be made. The vCPU
    // thread is made parked, the filter goes on (it covers the parked thread), and the thread is then started.
    let mut handle = spawn_vcpu_parked(vcpu, Arc::new(pio), Arc::new(mmio), self.done.try_clone()?)?;
    self.seccomp.apply()?;
    // From here on no thread can be made, so nothing may return the VMM to `NotStarted`: a resume that fails leaves the machine
    // built, and the client is told.
    let resumed = handle.resume_within(self.answer_timeout);
    self.running = Some(Running { vm, vcpu: Some(handle), serial, probe });
    // A resume that missed its deadline was still sent: the guest runs, and `sync_state` says what the handle knows.
    self.state = VmState::Paused;
    self.sync_state();
    resumed?;

    // The log lines of a start are printed once the last step that can fail has succeeded.
    eprintln!("wick: KVM API version {api_version}");
    eprintln!("wick: memory {mem_mib} MiB");
    eprintln!("wick: boot protocol 64-bit entry");
    eprintln!("wick: InstanceStart");
    Ok(())
}

The call to attach_devices takes the command line just built and returns it with the MMIO bus the vCPU will use, after attaching the virtio devices; it belongs to chapter 25, and this chapter’s lab configures none, so it does nothing here, the command line comes back unchanged and the bus is empty. Everything fallible happens before self.state changes, so a failed InstanceStart (a missing file, a bad kernel, a command line that is too long) leaves the VMM NotStarted and still serving, and the error is the reply. The one step after the point of no return is releasing the parked thread, once the filter (chapter 26) is on and no second machine could be built: if that fails the machine stays built, and the error is still the reply: the machine reads Running if the resume was sent and has not been answered (chapter 27), and Paused if the thread never received it. The guest console is a Console that locks stdout and flushes on every write; the default boot_args are the four words of the lab’s line, reboot=t and panic=-1 the two that end a guest. reboot=t is the kernel’s “triple fault” reboot method (kernel-parameters.txt: “Force a triple fault (init)”) and exercise (b) shows what the default does instead. The three log lines wick: KVM API version 12, wick: memory 128 MiB and wick: boot protocol 64-bit entry are in the capture; Vm::new refuses an API version other than 12, as api.rst:144-145 says to (chapter 20’s check). The lines from spawn_vcpu_parked to handle.resume() belong to chapter 26: the seccomp filter cannot let a thread be made, so the vCPU thread is made first and parked, the filter goes on (it covers the parked thread), and only then does the thread run; the API version is read before the filter because KVM_GET_API_VERSION is not on its list. With no policy set (the default) apply does nothing.

The HTTP, hand-written

wick’s API server is about 200 lines of HTTP (197 lines of code in wick/src/api/http.rs, before its tests, not counting blank and comment lines), hand-written because Firecracker’s own server, micro_http, is a git dependency (chapter 23) and the crate of that name on crates.io is a different project. It speaks the smallest HTTP that curl and wick ctl can use: GET, PUT and PATCH, one request per connection, a Content-Length body or none, no keep-alive, no chunked encoding, no TLS, no pipelining. Each omission is a case the parser does not have to get right. The caps are MAX_HEAD, 8192 bytes for the request line and headers, and MAX_BODY, 51200, Firecracker’s default payload limit (HTTP_MAX_PAYLOAD_SIZE, src/vmm/src/lib.rs:212-213 at v1.15.1, overridable with --http-api-max-payload-size, src/firecracker/src/main.rs:254-258). The reader never holds more than the two together. The types and the limits:

/// Request line plus headers, including the final blank line.
pub const MAX_HEAD: usize = 8192;
/// Firecracker's default payload limit (`micro_http` `MAX_PAYLOAD_SIZE`, 51200).
pub const MAX_BODY: usize = 51200;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Method {
    Get,
    Put,
    Patch,
}

impl Method {
    pub fn as_str(self) -> &'static str {
        match self {
            Method::Get => "GET",
            Method::Put => "PUT",
            Method::Patch => "PATCH",
        }
    }
}

#[derive(Debug, PartialEq, Eq)]
pub struct HttpRequest {
    pub method: Method,
    pub uri: String,
    pub body: Vec<u8>,
}

/// Why a request was refused. `status` is what the server answers; `Io` has no answer, the
/// connection is dropped.
#[derive(Debug, PartialEq, Eq)]
pub enum ParseError {
    /// 400.
    Bad(&'static str),
    /// 405.
    MethodNotAllowed,
    /// 413.
    TooLarge,
    /// The peer vanished, timed out or never spoke.
    Io,
}

impl ParseError {
    pub fn status(&self) -> Option<u16> {
        match self {
            ParseError::Bad(_) => Some(400),
            ParseError::MethodNotAllowed => Some(405),
            ParseError::TooLarge => Some(413),
            ParseError::Io => None,
        }
    }
}

and read_request:

/// Read one request. The reader takes the head one byte at a time and stops at the blank line, so it
/// never consumes a byte past the head it parsed and never holds more than `MAX_HEAD + MAX_BODY`.
pub fn read_request<R: Read>(r: &mut R) -> Result<HttpRequest, ParseError> {
    let head = read_head(r)?;
    let (request_line, headers) = split_head(&head)?;

    let mut parts = request_line.split(' ');
    let (method, uri, version) = match (parts.next(), parts.next(), parts.next(), parts.next()) {
        (Some(m), Some(u), Some(v), None) => (m, u, v),
        _ => return Err(ParseError::Bad("the request line is not METHOD URI VERSION")),
    };
    if version != "HTTP/1.1" && version != "HTTP/1.0" {
        return Err(ParseError::Bad("the HTTP version is not 1.1 or 1.0"));
    }
    if !uri.starts_with('/') || !uri.bytes().all(|b| (0x21..=0x7e).contains(&b)) {
        return Err(ParseError::Bad("the URI must start with / and hold printable ASCII"));
    }
    let method = match method {
        "GET" => Method::Get,
        "PUT" => Method::Put,
        "PATCH" => Method::Patch,
        _ => return Err(ParseError::MethodNotAllowed),
    };

    let mut length = None;
    for line in headers {
        let (name, value) = header(line)?;
        if name.eq_ignore_ascii_case("transfer-encoding") {
            return Err(ParseError::Bad("Transfer-Encoding is not supported"));
        }
        if name.eq_ignore_ascii_case("content-length") {
            let n = content_length(value)?;
            if length.replace(n).is_some() {
                return Err(ParseError::Bad("duplicate Content-Length"));
            }
        }
    }
    if length.is_none() && method != Method::Get {
        return Err(ParseError::Bad("PUT and PATCH need a Content-Length"));
    }
    let body = read_body(r, length.unwrap_or(0))?;
    Ok(HttpRequest { method, uri: uri.to_string(), body })
}

Reading the head one byte at a time is deliberate. It stops at the blank line, so it cannot consume a byte of anything after the request, and it refuses a bare \n where it reads it instead of waiting for a terminator that will not come (a_bare_lf_is_refused_at_once_without_waiting_for_more feeds it a reader that fails the test if asked for another byte). read_body takes exactly Content-Length bytes with Read::take, so a client that promises 50 KiB and sends none costs one 50 KiB buffer and the rest of its request’s time, both bounded. The error type has four cases: Bad (400), MethodNotAllowed (405), TooLarge (413) and Io, which has no status because the peer is gone. Each rule in the function has a unit test in the file, written against a &[u8], including the ones that refuse: a Content-Length that is not one plain number (+2, 0x2, -1, twice), a head that reaches MAX_HEAD with no blank line, Transfer-Encoding at all, a URI that is not printable ASCII starting /. The helpers that listing calls are the rest of the reader:

/// Bytes up to and including the first `\r\n\r\n`. A bare `\n` is refused where it is read.
fn read_head<R: Read>(r: &mut R) -> Result<Vec<u8>, ParseError> {
    let mut head = Vec::with_capacity(512);
    let mut byte = [0u8; 1];
    loop {
        match r.read(&mut byte) {
            Ok(0) if head.is_empty() => return Err(ParseError::Io),
            Ok(0) => return Err(ParseError::Bad("the request ended inside its head")),
            Ok(_) => {}
            Err(e) if e.kind() == ErrorKind::Interrupted => continue,
            Err(_) => return Err(ParseError::Io),
        }
        if byte[0] == b'\n' && head.last() != Some(&b'\r') {
            return Err(ParseError::Bad("a line ends with a bare LF"));
        }
        head.push(byte[0]);
        if head.ends_with(b"\r\n\r\n") {
            return Ok(head);
        }
        if head.len() >= MAX_HEAD {
            return Err(ParseError::TooLarge);
        }
    }
}

/// The head as text: the first line, then the header lines. Every line ends `\r\n`, so none holds
/// a CR or LF of its own.
fn split_head(head: &[u8]) -> Result<(&str, Vec<&str>), ParseError> {
    let text = std::str::from_utf8(head).map_err(|_| ParseError::Bad("the head is not UTF-8"))?;
    let mut lines: Vec<&str> = text[..text.len() - 4].split("\r\n").collect();
    if lines.iter().any(|l| l.contains(['\r', '\n'])) {
        return Err(ParseError::Bad("a line holds a stray CR"));
    }
    let first = lines.remove(0);
    Ok((first, lines))
}

fn header(line: &str) -> Result<(&str, &str), ParseError> {
    let (name, value) = line.split_once(':').ok_or(ParseError::Bad("a header has no colon"))?;
    if name.is_empty() || name.bytes().any(|b| b <= b' ' || b == 0x7f) {
        return Err(ParseError::Bad("a header name is empty or holds whitespace"));
    }
    Ok((name, value.trim_matches([' ', '\t'])))
}

/// Digits only: no sign, no space, no hex. A number too long for a u64 is above the cap too.
fn content_length(value: &str) -> Result<usize, ParseError> {
    if value.is_empty() || !value.bytes().all(|b| b.is_ascii_digit()) {
        return Err(ParseError::Bad("Content-Length is not a number"));
    }
    match value.parse::<usize>() {
        Ok(n) if n <= MAX_BODY => Ok(n),
        _ => Err(ParseError::TooLarge),
    }
}

/// Exactly `len` bytes, and `len` is at most `MAX_BODY`, so the buffer is allocated once at its final
/// size and never grows past the cap.
fn read_body<R: Read>(r: &mut R, len: usize) -> Result<Vec<u8>, ParseError> {
    let mut body = Vec::with_capacity(len);
    match r.take(len as u64).read_to_end(&mut body) {
        Ok(n) if n == len => Ok(body),
        Ok(_) => Err(ParseError::Bad("the body is shorter than its Content-Length")),
        Err(_) => Err(ParseError::Io),
    }
}

fn reason(status: u16) -> &'static str {
    match status {
        200 => "OK",
        204 => "No Content",
        400 => "Bad Request",
        404 => "Not Found",
        405 => "Method Not Allowed",
        413 => "Payload Too Large",
        _ => "Unknown",
    }
}

The writing half, which wick ctl also uses:

/// One response, then the connection closes.
pub fn write_response<W: Write>(w: &mut W, status: u16, body: &str) -> std::io::Result<()> {
    let mut out = format!("HTTP/1.1 {status} {}\r\n", reason(status));
    if !body.is_empty() {
        out.push_str("Content-Type: application/json\r\n");
    }
    out.push_str(&format!("Content-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()));
    w.write_all(out.as_bytes())?;
    w.flush()
}

/// The client's side, for `wick ctl` and the tests.
pub fn write_request<W: Write>(w: &mut W, method: Method, uri: &str, body: &[u8]) -> std::io::Result<()> {
    let mut out = format!("{} {uri} HTTP/1.1\r\nHost: localhost\r\nAccept: application/json\r\n", method.as_str());
    if !body.is_empty() {
        out.push_str("Content-Type: application/json\r\n");
    }
    if !body.is_empty() || method != Method::Get {
        out.push_str(&format!("Content-Length: {}\r\n", body.len()));
    }
    out.push_str("Connection: close\r\n\r\n");
    w.write_all(out.as_bytes())?;
    w.write_all(body)?;
    w.flush()
}

and the client’s reader of a response, wick ctl’s and the tests’:

/// The status and the body of a response: none for a 1xx, 204 or 304, else `Content-Length` bytes, or to the end of the stream.
pub fn read_response<R: Read>(r: &mut R) -> Result<(u16, String), ParseError> {
    let head = read_head(r)?;
    let (status_line, headers) = split_head(&head)?;
    let mut parts = status_line.splitn(3, ' ');
    let status = match (parts.next(), parts.next()) {
        (Some("HTTP/1.1" | "HTTP/1.0"), Some(code)) => {
            code.parse::<u16>().map_err(|_| ParseError::Bad("the status code is not a number"))?
        }
        _ => return Err(ParseError::Bad("the status line is not HTTP/1.x CODE REASON")),
    };
    let mut length = None;
    for line in headers {
        let (name, value) = header(line)?;
        if name.eq_ignore_ascii_case("content-length") {
            length = Some(content_length(value)?);
        }
    }
    // RFC 9112 section 6.3, rule 1: a response to a HEAD request and any 1xx, 204 or 304 response is "always terminated by the
    // first empty line after the header fields", whatever its headers say. `wick ctl` sends no HEAD request. A 1xx is returned as the response itself: `wick ctl` does not read past interim responses (RFC 9110 section 15.2), and no server it talks to sends one.
    let body = match length {
        _ if status < 200 || status == 204 || status == 304 => Vec::new(),
        Some(n) => read_body(r, n)?,
        None => {
            let mut body = Vec::new();
            r.take(MAX_BODY as u64).read_to_end(&mut body).map_err(|_| ParseError::Io)?;
            body
        }
    };
    String::from_utf8(body).map(|b| (status, b)).map_err(|_| ParseError::Bad("the body is not UTF-8"))
}

A 1xx, 204 or 304 response has no body whatever its headers say (RFC 9112 section 6.3, rule 1), so the reader stops at the blank line after the headers. wick’s own server closes after every response, so a reader that waited for the end of the stream would work against it; against a server that keeps the connection open after a 204, as Firecracker’s does, such a reader never returns, and chapter 28 drives Firecracker with this one.

The API thread

routes::parse maps a method and path to the Request the VMM thread understands:

/// Turn one HTTP request into a `Request` for the VMM thread. Every refusal is an `Error::Config`;
/// `status` says which HTTP status that error is.
pub fn parse(method: Method, uri: &str, body: &[u8]) -> Result<Request> {
    // The methods a resource takes; a path in no arm is unknown. A query string is part of the path.
    let (allowed, build): (Method, Build) = match uri {
        "/" => (Method::Get, |_| Ok(Request::GetInstanceInfo)),
        "/machine-config" => (Method::Put, |b| Ok(Request::PutMachineConfig(json::<MachineConfig>(b)?))),
        "/boot-source" => (Method::Put, |b| Ok(Request::PutBootSource(json::<BootSource>(b)?))),
        "/actions" => (Method::Put, |b| action(&json::<Action>(b)?.action_type)),
        _ => return more_routes::parse(method, uri, body).unwrap_or(Err(Error::Config(NO_SUCH_RESOURCE.into()))),
    };
    if method != allowed {
        return Err(Error::Config(METHOD_NOT_ALLOWED.into()));
    }
    build(body)
}

The last arm hands a path this table does not hold to more_routes::parse, one line that belongs to chapter 25 (it is where PUT /drives/{drive_id} and the later chapters’ paths live); none exists in this chapter, so every other path is still 404. The paths and field names are Firecracker’s, a strict subset: PUT /machine-config, PUT /boot-source, PUT /actions with {"action_type":"InstanceStart"}, and GET /. An unknown path is 404, a known path with the wrong method is 405, and a body that is not JSON, or has a field the schema lacks (every body type is #[serde(deny_unknown_fields)]), is 400 with the parser’s own message. SendCtrlAltDel is refused with 400: Firecracker delivers it through an emulated i8042 keyboard controller, wick has none, and the guests end with reboot -f. Error has no variant for “not found”, so the three refusals are all Error::Config and status tells them apart by their messages, which are constants in the same file.

The thread that runs it:

/// The accept loop. It never returns: the process ends when the VMM loop does. The kick signal's handler
/// is installed for the whole process without `SA_RESTART`, so a blocking call here would fail with
/// `EINTR` if a signal were ever sent to the process rather than to the vCPU thread; `accept` and the
/// reads in `http` retry it.
fn serve(listener: UnixListener, channel: &VmmChannel, id: &str, read_timeout: Duration) {
    loop {
        let mut stream = match listener.accept() {
            Ok((stream, _)) => stream,
            Err(e) if e.kind() == ErrorKind::Interrupted => continue,
            Err(e) => {
                eprintln!("wick: api accept: {e}");
                continue;
            }
        };
        let _ = stream.set_write_timeout(Some(read_timeout));
        let (status, body, in_flight) = respond(&mut stream, channel, id, read_timeout);
        if let Some(status) = status {
            std::thread::sleep(Duration::from_millis(WRITE_DELAY_MS.load(Ordering::Relaxed)));
            // The client may have gone; there is nobody to tell.
            let _ = http::write_response(&mut stream, status, &body);
            RESPONSES_WRITTEN.fetch_add(1, Ordering::SeqCst);
            drop(in_flight);
            // A reset from unread bytes can destroy any answer, a 204 as much as a 400.
            refuse_politely(&mut stream);
        }
    }
}

/// Closing a socket with unread data resets the connection, which can destroy the answer before the client
/// reads it, and a refusal or a pipelined second request leaves data unread. Say we are done writing, then
/// swallow what the client still sends, up to the most a request may hold and for one second.
fn refuse_politely(stream: &mut UnixStream) {
    let _ = stream.shutdown(Shutdown::Write);
    let deadline = Instant::now() + Duration::from_secs(1);
    let mut left = http::MAX_HEAD + http::MAX_BODY;
    let mut buf = [0u8; 4096];
    while left > 0 && Instant::now() < deadline {
        let _ = stream.set_read_timeout(Some(Duration::from_millis(100)));
        match stream.read(&mut buf) {
            Ok(0) | Err(_) => return,
            Ok(n) => left = left.saturating_sub(n),
        }
    }
}

/// A reader that gives the whole request one deadline: before each read the socket's timeout is set to
/// the time that is left, and when none is left the read fails.
struct Deadline<'a> {
    stream: &'a mut UnixStream,
    until: Instant,
}

impl Read for Deadline<'_> {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        let left = self.until.saturating_duration_since(Instant::now());
        if left.is_zero() {
            return Err(std::io::Error::new(ErrorKind::TimedOut, "the request took too long"));
        }
        self.stream.set_read_timeout(Some(left))?;
        self.stream.read(buf)
    }
}

/// One connection's whole conversation: the status to write (none when the peer is gone), the body, and
/// the `RESPONSE_IN_FLIGHT` guard, taken once a request has been read (so a silent client never delays
/// the exit) and kept until the response is written.
fn respond(stream: &mut UnixStream, channel: &VmmChannel, id: &str, read_timeout: Duration) -> (Option<u16>, String, Option<MutexGuard<'static, ()>>) {
    // One deadline for the whole request, not one timeout per read: a client that drips a byte at a time
    // still runs out of time.
    let read = http::read_request(&mut Deadline { stream, until: Instant::now() + read_timeout });
    if read == Err(ParseError::Io) {
        return (None, String::new(), None);
    }
    let guard = Some(RESPONSE_IN_FLIGHT.lock().unwrap_or_else(PoisonError::into_inner));
    let request = match read {
        Ok(r) => r,
        Err(ParseError::Bad(why)) => return (Some(400), fault(why), guard),
        Err(ParseError::MethodNotAllowed) => return (Some(405), fault("method not allowed"), guard),
        Err(ParseError::TooLarge) => return (Some(413), fault("the request is larger than the API takes"), guard),
        Err(ParseError::Io) => return (None, String::new(), guard), // handled above; kept so the match stays exhaustive
    };
    let request = match routes::parse(request.method, &request.uri, &request.body) {
        Ok(r) => r,
        Err(e) => return (Some(routes::status(&e)), fault(&e.to_string()), guard),
    };
    let (status, body) = match channel.call(request) {
        Ok(Reply::Empty) => (Some(204), String::new()),
        Ok(Reply::InstanceInfo { state, vmm_version }) => {
            // INVARIANT: a struct of three strings always serialises.
            let body = serde_json::to_string(&InstanceInfo { id, state: &state, vmm_version: &vmm_version }).expect("serialise the instance info");
            (Some(200), body)
        }
        Err(e) => (Some(400), fault(&e.to_string())),
    };
    (status, body, guard)
}

A request has 5 seconds in all (READ_TIMEOUT, one deadline for the whole request, not a timeout per read: a client that drips a byte every two seconds is cut off at five, a_client_that_drips_bytes_cannot_hold_the_api), so a client that connects and says nothing, or sends half a head and stops, cannot hold the thread: one connection is served at a time, and the next is waiting. The mapping is the schema’s: 204 with no body for every success but GET /, which is 200 with {"id":…,"state":…,"vmm_version":…} (Firecracker’s InstanceInfo names; state is Not started, Running or Paused, or Pausing, wick’s own fourth word, while a pause chapter 27 sends is unanswered); every Error from the VMM thread is 400 with {"fault_message":"…"}. The thread has no way to stop. The process ends when the VMM loop returns, and main first takes RESPONSE_IN_FLIGHT, the lock the thread holds from the moment it has read a request until the response is written: without it a guest that shuts down right after InstanceStart could end the process between the VMM thread’s reply and the API thread’s write, and the client would read end-of-file instead of 204 (the_exit_waits_for_a_reply_that_is_being_written delays the write by 600 ms to force it). The thread’s comment on the lock says why it cannot deadlock. refuse_politely runs after every response, not only refusals, because bytes left unread after a complete request (a pipelined second one) reset the connection and can destroy a 200 (a_pipelined_second_request_does_not_destroy_the_first_answer). The drain is bounded too, by one second and by MAX_HEAD + MAX_BODY bytes, so one connection holds the thread for the 5 seconds of its request, the VMM thread’s answer and about one second more (a response this small does not fill the socket, so its write does not wait on the client). In the roughly 16 ms between the vCPU’s Shutdown and the process’s exit a request is answered 400 with the VMM thread is not running. wick removes its socket when the loop ends, but not when timeout kills it; run.sh removes it either way, and a second wick on a path that another is serving refuses to start (wick: FAIL … is in use) instead of taking the socket over.

PUT /boot-source opens the kernel and the initrd when it arrives and answers 400 naming the file if either cannot be opened, as Firecracker does at the same point (boot_source.rs:75-77, called from resources.rs:336). The command line is built at the PUT too, so characters the loader would refuse (non-ASCII, say) are a 400 there, as Firecracker’s BootConfig::new does (boot_source.rs:81-85); the length limit lives in the image’s header, which the PUT does not read, so an over-long boot_args is refused by InstanceStart. wick/tests/api.rs is the contract of this thread, against a real socket and a real Vmm with no guest: a wrong method, an unknown path, a body that is not JSON or has an unknown field, vcpu_count other than 1 (wick runs one vCPU), mem_size_mib of 8, a head and a body over the caps, bytes that are not HTTP, a silent client, and after every one of them a GET / that still answers Not started; plus two tests that do boot a guest and send the configuration requests and a second InstanceStart into it.

wick ctl

The client is the same http module. wick ctl --api-sock PATH [--wait-ms N] METHOD URI [@FILE] sends one request, prints ctl: METHOD URI STATUS and the body on its own line when there is one, and exits 0 on a 2xx, 1 on any other status, and 2 when it cannot connect. --wait-ms retries the connect every 10 ms for that long, so a script can start wick in the background and call it at once without a sleep:

/// Connect, write one request, read one response. `wait` keeps retrying the connect every 10 ms for that
/// long, so a script can start `wick` and call it without sleeping first.
pub fn request_waiting(sock: &Path, wait: Duration, method: Method, uri: &str, body: &[u8]) -> Result<(u16, String)> {
    let start = Instant::now();
    let mut stream = loop {
        match UnixStream::connect(sock) {
            Ok(s) => break s,
            Err(_) if start.elapsed() < wait => std::thread::sleep(Duration::from_millis(10)),
            Err(e) => return Err(Error::Io(std::io::Error::new(e.kind(), format!("connect {}: {e}", sock.display())))),
        }
    };
    http::write_request(&mut stream, method, uri, body)?;
    http::read_response(&mut stream).map_err(|e| Error::Io(std::io::Error::new(std::io::ErrorKind::InvalidData, format!("bad response from {}: {e:?}", sock.display()))))
}

pub fn request(sock: &Path, method: Method, uri: &str, body: &[u8]) -> Result<(u16, String)> {
    request_waiting(sock, Duration::ZERO, method, uri, body)
}

Exercises

Each answer is a run on talos (Intel, 2026-10-02) in a scratch copy of wick/ with one edit (the runs’ output is kept outside the repository, in directories named ex/out-… below), on the lab’s own kernel and initramfs, bounded by timeout, except where the answer says otherwise. The edits are one line each; the lab’s labs/ch24/api/ bodies and the lab’s boot-source.json were used with the one field the exercise changes.

(a) In SerialDevice::new, delete the register_irqfd call and run the lab. What appears, what does not, and what ends the run?

Answer

The lab’s diff fails. The kernel’s own log prints in full, up to Run /init as init process, and not one line of init’s output follows: no === lab begin. Run at the lab’s 60 s bound, it ends after 32 s: the log gains reboot: Restarting system, wick logs vcpu 0 exit Shutdown and exits 0 (output directory ex/out-a3). With a 20 s bound the same run is cut off at wick rc=124, with nothing after Run /init (ex/out-a).

The two halves take the paths the Mechanism section described: the kernel’s log polls, and init’s echo waits for an interrupt that GSI 4 never delivers, so its bytes stay in the queue. The 32 s are the tty’s close wait: init closes the console (exec >/dev/null) before reboot -f, and a close waits for the queue to drain for up to closing_wait, which the tty core defaults to 30 seconds:

// linux v7.2.8, drivers/tty/tty_port.c:96-96
    port->closing_wait = (3000 * HZ) / 100;

(With the interrupt working the queue drains in microseconds and the close returns at once; that close is how the lab’s last lines get out.) The edit leaves a guest that is alive, logs normally, and silently loses every byte a program writes, which is why the lab pins init’s lines and not the kernel’s.

(b) Remove reboot=t from boot_args and run the lab. What happens, and where is the guest? (An empty or blank boot_args is not this experiment: wick treats it as absent and applies the default command line, because a guest with neither console= nor reboot=t prints nothing and never ends.)

Answer

The guest prints its three lines and reboot: Restarting system, and then nothing, until timeout ends the run with its 124: six runs at a 40 s bound all did (ex/out-b-run1 to out-b-run6), as did a 100 s run (ex/out-b2). One earlier run, with a 20 s bound and a counting build, ended in a Shutdown exit and rc=0 (ex/out-b), so the hang is the usual outcome and not a certain one. A copy of wick that stops the vCPU after 12 s and prints its registers, in five runs (ex/out-w1 to out-w5), found the guest in real mode, not long mode: cr0=0x60000010 (PE and PG both clear), cs.base=0x0 and rip at 0x39e3 (three runs), 0xaa and 0x508. 0x508 is inside the GDT wick wrote.

The kernel’s reboot code tries methods in order and the default list is the source’s own:

// linux v7.2.8, arch/x86/kernel/reboot.c:605-636
    for (;;) {
        /* Could also try the reset bit in the Hammer NB */
        switch (reboot_type) {
        case BOOT_ACPI:
            acpi_reboot();
            reboot_type = BOOT_KBD;
            break;

        case BOOT_KBD:
            mach_reboot_fixups(); /* For board specific fixups */

            for (i = 0; i < 10; i++) {
                kb_wait();
                udelay(50);
                outb(0xfe, 0x64); /* Pulse reset low */
                udelay(50);
            }
            if (attempt == 0 && orig_reboot_type == BOOT_ACPI) {
                attempt = 1;
                reboot_type = BOOT_ACPI;
            } else {
                reboot_type = BOOT_EFI;
            }
            break;

        case BOOT_EFI:
            efi_reboot(reboot_mode, NULL);
            reboot_type = BOOT_BIOS;
            break;

        case BOOT_BIOS:
            machine_real_restart(MRR_BIOS);

ACPI does nothing without tables; then the keyboard-controller path pulses port 0x64, twice around the loop (the default type is ACPI, and a first KBD pass hands back to it once), and kb_wait reads 0x64 up to 0x10000 times per call, waiting for bit 1, input-buffer-full, to clear:

// linux v7.2.8, arch/x86/kernel/reboot.c:522-531
static inline void kb_wait(void)
{
    int i;

    for (i = 0; i < 0x10000; i++) {
        if ((inb(0x64) & 0x02) == 0)
            break;
        udelay(2);
    }
}

wick answers an unclaimed port with 0xff, whose bit 1 is set forever, so every call runs all 65,536 reads. In the counting run that ended, port 0x64 had 1,310,737 reads: 20 * 65536 = 1,310,720 from the two passes of ten calls, and 17 from the probe at boot. After those loops comes the BIOS step: machine_real_restart leaves long mode through a real-mode trampoline and jumps to the BIOS reset vector, where a PC’s firmware would be, and wick has none. The registers above are what that looks like from outside: real mode, a low rip. The trace stops there: nothing past that point was observed. That run shows one write each to ports 0x70 and 0x71 in its final counts, the CMOS write that machine_real_restart makes first (reboot.c:114), so it did take that path, and something in what followed faulted. reboot=t skips all of it: the BOOT_TRIPLE case is a triple fault, and a triple fault is the one exit the loop is written to accept.

(c) Make the exit loop answer an unclaimed port read with 0 instead of 0xff (data.fill(0), the IoIn arm only). Run the lab, and then time it against the reference.

Answer

The lab’s guest lines are unchanged and wick exits 0, so the capture’s guest section still passes. Two things differ. The guest’s log has i8042: Can't read CTR while initializing i8042 and i8042 i8042: probe with driver i8042 failed with error -5 where the reference has i8042: No controller found, and the run is slower: 0.71 s against 0.20 s, measured over three runs of each, from wick’s start to its exit (talos, 2026-10-02).

The kernel’s keyboard-controller probe is written for a bus that reads all ones. With 0xff, the status register claims a byte waiting in the output buffer, the probe’s flush never empties it, and it gives up at once:

// linux v7.2.8, drivers/input/serio/i8042.c:931-936
static int i8042_controller_check(void)
{
    if (i8042_flush()) {
        pr_info("No controller found\n");
        return -ENODEV;
    }

With 0 the controller looks present and idle. The probe then issues a command and waits for the answer, 10,000 times 50 microseconds, which is the half second the run gained:

// linux v7.2.8, drivers/input/serio/i8042.c:230-239
static int i8042_wait_read(void)
{
    int i = 0;

    while ((~i8042_read_status() & I8042_STR_OBF) && (i < I8042_CTL_TIMEOUT)) {
        udelay(50);
        i++;
    }
    return -(i == I8042_CTL_TIMEOUT);
}

(I8042_CTL_TIMEOUT is 10000, i8042.h:34.) The wrong answer boots, passes, and costs 3.5 times the boot. All ones is not an arbitrary default; it is what an undriven bus reads, which is what the guest’s probes are written against.

(d) Send PUT /boot-source with a boot_args of 2,147 bytes, then InstanceStart. What does wick answer at each step, why, and what would the kernel have done with the line?

Answer

The PUT is accepted and the start is not, and the machine stays Not started and serving:

ctl: PUT /boot-source 204
ctl: PUT /actions 400
{"fault_message":"the kernel command line is 2147 bytes, longer than the 2047 the kernel reads (setup_header.cmdline_size)"}
ctl: GET / 200
{"id":"ex","state":"Not started","vmm_version":"0.1.0"}

The field is 2047 here, COMMAND_LINE_SIZE - 1 (arch/x86/boot/header.S:384, COMMAND_LINE_SIZE is 2048 in arch/x86/include/asm/setup.h:7), and the document says what an over-long line gets from the kernel:

// linux v7.2.8, Documentation/arch/x86/boot.rst:1049-1052
The kernel command line is a null-terminated string. The maximum
length can be retrieved from the field cmdline_size.  Before protocol
version 2.06, the maximum was 255 characters.  A string that is too
long will be automatically truncated by the kernel.

To see it, the same run with check_cmdline disabled and an initramfs whose init prints /proc/cmdline (a 2,140-byte line ending ... x=aaaa...a tailmark=end): cmdline bytes: 2049 (2,048 characters and the newline), cmdline tail: aaaaaaaaaaaaaaaaaaaaaaa. The last word, tailmark=end, is gone, with no message. The kernel copies a fixed 2,048 bytes of the buffer, memcpy(boot_command_line, command_line, COMMAND_LINE_SIZE) (arch/x86/kernel/head64.c:210), so what it keeps is the first 2,048 bytes of whatever the loader wrote.

(e) With a guest running, send PUT /machine-config, a second InstanceStart and SendCtrlAltDel. What are the statuses and the messages?

Answer

Run against a guest whose init sleeps two seconds before reboot -f (wick/tests/init-linger), so the requests arrive while it is running:

ctl: PUT /actions 204
ctl: GET / 200
{"id":"ex","state":"Running","vmm_version":"0.1.0"}
ctl: PUT /machine-config 400
{"fault_message":"PUT /machine-config is pre-boot only: the microVM has already started"}
ctl: PUT /actions 400
{"fault_message":"InstanceStart can only be called once"}
ctl: PUT /actions 400
{"fault_message":"SendCtrlAltDel is not implemented: wick has no i8042 to deliver it through; end the guest with reboot -f"}
wick rc=0

The first two are Error::State, right input at the wrong time, from pre_boot and instance_start; the third is Error::Config, from routes::parse, which never builds the request. All three are 400 with a fault_message, and wick exits 0 afterwards: the guest runs to its end through the refused requests.

(f) Delete the XLF_KERNEL_64 check in load_kernel and hand PUT /boot-source chapter 15’s RISC-V Image. What refuses it, and where? Then clear bit 0 of the lab bzImage’s xloadflags and run both versions.

Answer

The RISC-V Image is refused before the deleted check is reached, by the loader crate, and the same way with and without the check:

ctl: PUT /actions 400
{"fault_message":"kernel loader: .../labs/ch15/out/Image: Kernel Loader: failed to load bzImage kernel image: Kernel Loader: Invalid bzImage"}

It is BzImage::load, which looks for HdrS at file offset 0x202 and finds something else (linux-loader 0.14.0, src/loader/bzimage/mod.rs:128-130, quoted above). The XLF_KERNEL_64 check is for a different failure: an image that is a valid bzImage and says it has no 64-bit entry. The lab’s bzImage with xloadflags changed from 0x61 to 0x60 (one byte at file offset 0x236) is that image. With the check, InstanceStart is 400:

{"fault_message":"kernel loader: .../bzImage-noxlf: xloadflags 0x60 lacks XLF_KERNEL_64, no 64-bit entry point"}

Without it, the guest boots and prints its three lines, because the bit only declares that the entry exists and this image’s entry is there regardless. The check trusts nothing but the declaration, which is its job; it does not verify the code at +0x200.

Lab

make lab CH=24
make lab CH=24 IMPL=mine
tools/remote-lab.sh lab CH=24
make -C wick test clippy

labs/lab.wick.mk is the rule set the labs of chapters 24 to 28 share: build wick (for IMPL=mine, rsync wick/ without target/ to labs/ch24/out/wick-mine/ and lay labs/ch24/mine/ over it, so the reference tree is never touched), build the guest through build.sh, run run.sh, and diff the result against capture.txt. run.sh starts wick in the background on out/api.sock, configures it with three wick ctl calls (PUT /machine-config, PUT /boot-source, PUT /actions, the bodies being the three files in labs/ch24/api/), waits for it, and writes out/run.txt: the ctl lines, the guest’s lines between its two sentinels, and wick’s own wick: log lines, which are stderr, and wick rc=. The same script shape, with a different request sequence, is chapters 25 to 27’s.

The capture:

ctl: GET / 200
{"id":"ch24","state":"Not started","vmm_version":"0.1.0"}
ctl: PUT /machine-config 204
ctl: PUT /boot-source 204
ctl: PUT /actions 204
=== lab begin
init: userland up
init: kernel 7.2.8 x86_64
=== lab end
wick: KVM API version 12
wick: memory 128 MiB
wick: boot protocol 64-bit entry
wick: InstanceStart
wick: vcpu 0 exit Shutdown
wick: exit 0
wick rc=0

It pins the control plane’s answers (GET / before the start, the three requests’ statuses), the guest’s two verdict lines (init: userland up and the kernel’s release and machine from uname), and wick’s account of the run: the KVM API version 12 (chapter 20’s check, now wick’s own refusal and log line), the memory, the boot protocol, the start, the Shutdown exit and the exit code. It refuses everything that varies: the kernel’s log (it has the build host’s name, timestamps and memory sizes, and, before set_apic_id, the host CPU’s APIC ID), every address, the exit counts above and the time. Three runs on talos (one cold) and five on straylight (one cold), the second host an AMD machine, are byte-identical to capture.txt, so also to each other (checked with cmp, 2026-10-02).

Timings, measured on 2026-10-02 with make lab CH=24 timed by date: a cold run on straylight (rm -rf ~/.cache/hp/ch24, then the lab through tools/remote-lab.sh; two git clones, the kernel build, BusyBox, the lab) took 196 s, started 02:35Z; cold on talos (the same rm -rf, then make lab CH=24 directly) took 425 s, started 03:07Z. A cold run prints nothing from the kernel and BusyBox builds but the two pin lines build.sh writes, the commits of the two trees; a failed step prints the tail of its log instead. A warm make lab CH=24 takes 0.25 to 0.27 s on talos and 0.33 to 0.34 s on straylight (three runs each, including the check that cargo has nothing to build). The cold run’s one-time cost is the kernel and BusyBox; every later run and every run of chapters 25 to 28 starts from the cache in ~/.cache/hp/ch24/.

IMPL=mine replaces the body of fill_boot_params with eprintln!("MINE: boot_params stub"); boot_params::default(): the chapter’s job is the zero page and the stub is the zero page with nothing in it. The diff of capture.txt against that run:

 ctl: PUT /actions 204
-=== lab begin
-init: userland up
-init: kernel 7.2.8 x86_64
-=== lab end
+MINE: boot_params stub
 wick: KVM API version 12
 wick: memory 128 MiB
 wick: boot protocol 64-bit entry

The MINE: line is stderr and run.sh keeps MINE: lines beside wick: ones, so it is in the diff. out/console.txt is empty: not one byte, not even the kernel’s first line. Everything the VMM controls is fine: the requests are answered, the start is accepted, the vCPU runs. The guest never reaches userland, and the decompression stub’s first instructions say where it stops. This kernel is not relocatable, so the stub’s relocation arithmetic is compiled out:

// linux v7.2.8, arch/x86/boot/compressed/head_64.S:314-334
    /* Start with the delta to where the kernel will run at. */
#ifdef CONFIG_RELOCATABLE
    leaq    startup_32(%rip) /* - $startup_32 */, %rbp
    movl    BP_kernel_alignment(%rsi), %eax
    decl    %eax
    addq    %rax, %rbp
    notq    %rax
    andq    %rax, %rbp
    cmpq    $LOAD_PHYSICAL_ADDR, %rbp
    jae    1f
#endif
    movq    $LOAD_PHYSICAL_ADDR, %rbp
1:

    /* Target address to relocate to for decompression */
    movl    BP_init_size(%rsi), %ebx
    subl    $ rva(_end), %ebx
    addq    %rbp, %rbx

    /* Set up the stack */
    leaq    rva(boot_stack_end)(%rbx), %rsp

and objdump -d arch/x86/boot/compressed/vmlinux of the lab’s build shows what is left (offsets from the stub’s entry at 0x200):

 20e:    48 c7 c5 00 00 00 01     mov    $0x1000000,%rbp
 215:    8b 9e 60 02 00 00        mov    0x260(%rsi),%ebx
 21b:    81 eb 00 60 1d 00        sub    $0x1d6000,%ebx
 221:    48 01 eb                 add    %rbp,%rbx
 224:    48 8d a3 00 04 1a 00     lea    0x1a0400(%rbx),%rsp

The decompression target is LOAD_PHYSICAL_ADDR, 0x1000000, whatever the zero page holds, and the only zero-page field read is init_size, at 0x260(%rsi). That is this configuration’s property: RELOCATABLE is default y (arch/x86/Kconfig:2033-2035) and tinyconfig turns it off, so the lab’s kernel is the unusual case, and a relocatable one also reads kernel_alignment. An independent check on talos (2026-10-01) booted a RELOCATABLE kernel (init_size 0xc2d000), RELOCATABLE with RANDOMIZE_BASE (0xc5b000) and an SMP kernel (0xbdb000) at 31 to 1024 MiB: all 21 runs reached === lab end. With a zero page of zeros, %ebx is 0 - 0x1d6000, which wraps in 32 bits to 0xffe2a000; adding %rbp puts %rbx at 0x100e2a000 and %rsp at 0x100fca400, above 4 GiB and outside the 128 MiB the page tables map. The first use of that stack, the push $0x10 at 0x239, faults, and nothing has installed a handler for the fault, so it becomes a triple fault. That is a reading of the source and the disassembly; the run shows the silence and the Shutdown.

The rule for reading any lab of this part follows. The run’s last lines are wick: vcpu 0 exit Shutdown, wick: exit 0 and wick rc=0, the same as the reference’s: an exit code of 0 means the vCPU ended in KVM_EXIT_SHUTDOWN, which a clean reboot -f under reboot=t and a triple fault share, so wick cannot tell a guest that crashed from one that finished. The pass criterion is the capture’s guest verdict lines, between the sentinels. A guest that never reaches Shutdown is cut off by timeout and shows as wick rc=124 (exercise (b)); a guest that runs and logs but loses its programs’ output can end with rc=0 too (exercise (a)). The wick: FAIL arm, for any other exit, is covered by a unit test of stop_verdict, not by a lab.

Further reading

results matching ""

    No results matching ""