27. Snapshots

A snapshot: three kinds of state, two files, a new process Process A, paused, holds a guest in three places. In KVM: for the vCPU, eleven pieces in the order they are saved (mp_state, regs, sregs, xsave, xcrs, debug_regs, lapic, tsc_khz, cpuid, msrs, vcpu_events; each row of the figure is a stretch of that one list, read top to bottom), and for the VM five (pit2, clock, pic master, pic slave, ioapic). In guest RAM: one bar of 128 MiB. In the VMM: the serial registers, the transport status, the queue cursors and the configuration. Arrows lead down into two files: the KVM and VMM state into state.json, the RAM into mem.bin. Process B, a new process, fills the same three places from the files in restore order: first tsc_khz, only when the host rate differs from the saved one by more than 250 parts per million, then cpuid, then mp_state, regs, sregs, xsave, xcrs, debug_regs, lapic, msrs and vcpu_events, then kvmclock_ctrl; and the VM pieces pit2, clock with its flags cleared, the two PICs and the ioapic. Two brackets mark the ordering constraints: the LAPIC is set after the segment and control registers and before the MSRs, and the TSC deadline MSR is set last among the MSRs. Below, what is in neither file: host sockets, the TAP queue and time. process A, paused in KVM per vCPU, in order: mp_state, regs, sregs, xsave, xcrs, debug_regs, lapic, tsc_khz, cpuid, msrs, vcpu_events per VM: pit2, clock, pic master, pic slave, ioapic in the VMM serial registers transport status queue cursors the config in guest RAM 128 MiB one bar state.json KVM and VMM state, as JSON mem.bin the RAM, byte for byte process B, new in KVM per vCPU, in order: (tsc_khz,) cpuid mp_state regs sregs xsave xcrs debug_regs lapic msrs vcpu_events kvmclock_ctrl per VM: pit2, clock (flags 0), pic master, pic slave, ioapic in the VMM serial: irqfd transport status queue cursors the config: fds then, last: vsock reset in guest RAM 128 MiB read in first LAPIC after SREGS, before MSRS TSC_DEADLINE last in neither file host sockets: a vsock connection is a descriptor in the old process the TAP's queue: frames in flight were never the guest's time: the guest's clock resumes at the snapshot instant

Why a snapshot is a claim

A running guest is three things: its memory, the state of its CPU, and the state of the devices it talks to. A snapshot is the claim that these three are all of it, and the claim has exactly one test: make the machine again in a process that has never run the guest and see whether it goes on. Whatever the snapshot left out is missing there, and the guest does not announce what; a guest that prints its next line is not proof of anything. Of the nineteen pieces of state the ablation table below leaves out, one at a time, eleven leave the lab printing its capture byte for byte every time, and the other eight break it.

Chapter 20’s VM was memory and one register file, and the register file was a hart’s: x0 to x31, pc and the CSRs. A KVM guest on x86 has three homes for its state, and the chapter is the tour of them. Some of it is in guest RAM, which is the easy part. Some is in the kernel: KVM keeps the interrupt controllers, the timer chip, the guest’s clock and the CPU’s own registers for the VMM, in objects the VMM can only read and write through ioctls, in an order the kernel’s own comments constrain. And some is in the VMM: a serial port’s registers, the two cursors of a virtqueue, the configuration that says which files and which TAP the devices were built over. The disk is in none of these: it is a file the user owns, and a snapshot of the memory over a disk that has changed is a corrupt guest.

Two things motivate the work, and chapter 28 measures the first. A restored guest costs a file read and eighteen ioctls of state (thirteen on the vCPU thread, five on the VMM thread; thirty-two ioctls in all before the filter, counted by labs/ch27/measure/ioctl-count.sh in an strace of the lab’s second process on talos, 2026-10-03), where a booted one costs a kernel’s whole start; a host that wants many guests wants them restored. And the claim is a discipline: the test that restoring in a new process is, applied to every piece of state, is how a VMM finds the state it forgot it had. hearth reuses the discipline on a smaller machine. Its snapshot is guest memory and the vCPU’s CSRs, with no device state to chase, because the hypervisor is the kernel there and a device is a structure in the same image; the three-homes question has one answer, and the ablation, in a form that fits on a page, is still how that snapshot is tested.

Mechanism

Sources: the Linux tree at tag v7.2.8, the pinned tree the book has quoted since chapter 15 (the hosts run 7.2.5 on talos and 6.18.51 on straylight, so a quotation says what the code at that tag says, and a behaviour claimed below was observed on a host, as the text says); Firecracker at v1.15.1 (src/vmm/src/arch/x86_64/{vcpu,vm}.rs, src/vmm/src/builder.rs, src/vmm/src/vstate/vcpu.rs, src/vmm/src/lib.rs, docs/snapshotting/snapshot-support.md and resources/seccomp/x86_64-unknown-linux-musl.json), whose save and restore order wick follows and whose differences the text names; kvm-bindings 0.14.1 and vm-superio 0.8.2, the versions wick/Cargo.lock pins; and virtio 1.2 (OASIS, July 2022). Measurements are from talos (Intel i3-1315U, Linux 7.2.5) and straylight (AMD, Linux 6.18.51), 2026-10-03, except where a line says otherwise.

Pause: a vCPU that is inside the kernel

A vCPU is a thread blocked in KVM_RUN, and the first problem of a snapshot is to get it out and keep it out. Chapter 24 built the kick: SIGRTMIN is sent to the vCPU thread, whose handler sets that thread’s own immediate_exit byte in the shared kvm_run page (Firecracker’s handler is only a fence and its VMM thread writes the byte through a second mapping of the page; chapter 24’s listing gives the lines), and the exit loop checks a stop flag before every KVM_RUN (the ch24-kick listing; this chapter does not list it again). The two halves are needed together because a signal alone can arrive after the flag check and before the kernel is entered, where nothing is waiting to be interrupted; the byte makes that KVM_RUN return at once. The documentation says exactly this:

// linux v7.2.8, Documentation/virt/kvm/api.rst:6591-6598
    __u8 immediate_exit;

This field is polled once when KVM_RUN starts; if non-zero, KVM_RUN
exits immediately, returning -EINTR.  In the common scenario where a
signal is used to "kick" a VCPU out of KVM_RUN, this field can be used
to avoid usage of KVM_SET_SIGNAL_MASK, which has worse scalability.
Rather than blocking the signal outside KVM_RUN, userspace can set up
a signal handler that sets run->immediate_exit to a non-zero value.

The second half of a pause is the part a hasty snapshot misses. An exit to userspace for a port write or an MMIO access is half done: KVM stopped at the instruction, userspace emulated it, and the instruction retires, rip advancing past it, only when userspace enters KVM_RUN again. KVM_GET_REGS shows the register file from before the retirement. Saved there, the guest restores onto the out instruction it had already executed once and executes it again, so a restored guest repeats a byte of the console. The documentation says what to do:

// linux v7.2.8, Documentation/virt/kvm/api.rst:6741-6755
.. note::

      For KVM_EXIT_IO, KVM_EXIT_MMIO, KVM_EXIT_OSI, KVM_EXIT_PAPR, KVM_EXIT_XEN,
      KVM_EXIT_EPR, KVM_EXIT_HYPERCALL, KVM_EXIT_TDX,
      KVM_EXIT_X86_RDMSR and KVM_EXIT_X86_WRMSR the corresponding
      operations are complete (and guest state is consistent) only after userspace
      has re-entered the kernel with KVM_RUN.  The kernel side will first finish
      incomplete operations and then check for pending signals.

      The pending state of the operation is not preserved in state which is
      visible to userspace, thus userspace should ensure that the operation is
      completed before performing a live migration.  Userspace can re-enter the
      guest with an unmasked signal pending or with the immediate_exit field set
      to complete pending operations without allowing any further instructions
      to be executed.

complete_pending_exit is that sentence in code: set immediate_exit, enter KVM_RUN, expect EINTR, clear the byte. It runs on the vCPU thread, after the loop saw the stop flag and before the thread reports Paused. Exercise (a) leaves it out and shows the repeated byte.

The thread then parks: it waits on a channel for its next request and does not end. That is a consequence of chapter 26, whose filter has no clone3, so no thread can be made after it: the vCPU thread is made when the machine is built, before the filter goes on, and lives for the machine’s life, running the guest between a Resume and a Pause. PATCH /vm {"state":"Paused"} sets the flag, sends the kick, and waits for the thread’s answer, up to five seconds (the VMM’s own bound; the 25 seconds of the ablation are a timeout around a whole run); {"state":"Resumed"} sends the thread a request that clears the flag and the stale byte and re-enters the exit loop. Both are idempotent, as Firecracker’s are: its paused vCPU answers a second Pause with Paused again, and its running vCPU answers Resume with Resumed (vstate/vcpu.rs:315-319 and :263-267), so a pause of a paused machine and a resume of a running one are 204 here too. One more thing happens on every pause, and Firecracker does it too (vstate/vcpu.rs:251-262, the running vCPU’s answer to Pause): KVM_KVMCLOCK_CTRL.

// linux v7.2.8, Documentation/virt/kvm/api.rst:2958-2979
4.70 KVM_KVMCLOCK_CTRL
----------------------

:Capability: KVM_CAP_KVMCLOCK_CTRL
:Architectures: Any that implement pvclocks (currently x86 only)
:Type: vcpu ioctl
:Parameters: None
:Returns: 0 on success, -1 on error

This ioctl sets a flag accessible to the guest indicating that the specified
vCPU has been paused by the host userspace.

The host will set a flag in the pvclock structure that is checked from the
soft lockup watchdog.  The flag is part of the pvclock structure that is
shared between guest and host, specifically the second bit of the flags
field of the pvclock_vcpu_time_info structure.  It will be set exclusively by
the host and read/cleared exclusively by the guest.  The guest operation of
checking and clearing the flag must be an atomic operation so
load-link/store-conditional, or equivalent must be used.  There are two cases
where the guest will clear the flag: when the soft lockup watchdog timer resets
itself or when a soft lockup is detected.  This ioctl can be called any time
after pausing the vcpu, but before it is resumed.

A guest whose clock stood still for a while would otherwise take the gap for a hang. The ioctl fails with EINVAL when the guest does not use kvm-clock, and that is not an error.

A request can outlive its wait, and the VMM thread must never block on the vCPU thread for ever, because it is the thread that serves the API. Every wait has the deadline. A pause that misses it is not undone: the flag is set and the kick has been sent, and the thread may park a moment later. So the handle remembers which request is outstanding. A Resume or a Call carries a number that its answer echoes (a pause is a flag and a kick, and its answer is the thread’s Paused); and the next request first reads answers until nothing is outstanding or its own deadline passes, so a request is never put on the channel behind one the thread has not answered. While a pause is outstanding GET / says Pausing, which is wick’s word (Firecracker’s schema has three states) and is neither Running nor Paused. GET / does not read the thread’s answers, so a client that polls it for Paused after a pause that missed its wait will see Pausing until a PATCH settles the request. A Resumed sent to a pausing machine resumes it, and the guest runs on; the same holds for the start’s own resume, which has the same deadline, and a machine whose resume is unanswered reads Running, never Paused. A request that cannot settle in time is a 400 whose message says that the thread has not answered and that nothing was lost (the result of a call that missed its wait is dropped). tests/boot.rs and tests/pause_timeout.rs drive the timeouts with a deadline of zero on a guest that spins: sixty rounds in which a pause, a call and a resume are each given no time, forty of pause, snapshot and resume through the API, and a start whose resume gets no time, with the state never Running while a pause is pending, never Paused for a guest that runs, and no round blocking.

The vCPU’s VcpuFd belongs to the vCPU thread: the one mapping of the kvm_run page is on it, and every write of immediate_exit is made there. State is therefore read and written on that thread. The VMM thread sends the parked thread a closure over a channel and waits for its result, which is how Firecracker’s vCPU thread serves SaveState (vstate/vcpu.rs:321-334: a recv in the paused state, one event at a time, a response on a second channel). A running thread refuses: the state of a vCPU that is inside KVM_RUN is not state, and KVM_GET_VCPU_EVENTS is “unsafe if other vCPUs are still running”, in Firecracker’s words below.

Where the state lives

Figure 27 draws the three homes, and the order the second one is read and written in is the content of the next two sections. In KVM, for the vCPU: eleven pieces, one for each ioctl that reads them: the multiprocessing state, the general registers, the special registers, the extended-state area, the extended control registers, the debug registers, the local APIC’s registers, the counter’s frequency, the CPUID the guest was given, the model-specific registers and the pending events. In KVM, for the VM: five: the timer chip, the clock, the two 8259 interrupt controllers and the IOAPIC. In guest RAM: everything the kernel and its processes keep in memory, in one range from guest address 0, which is also where the virtqueues’ rings are. In the VMM: the console’s UART registers, each virtio device’s transport registers and queue cursors, and the configuration. The next sections take them in that order, with each x86 term set against the RISC-V one the book has used.

The vCPU’s pieces

mp_state, the multiprocessing state, says whether the vCPU is runnable or has executed hlt and waits for an interrupt (KVM_MP_STATE_HALTED, “the vcpu has executed a HLT instruction and is waiting for an interrupt”, api.rst:1542-1543). hlt is x86’s wfi: chapter 6’s timer lab slept in wfi until the tick, and a guest asleep in the idle loop is HALTED when it is paused. The lab’s guest is RUNNABLE at its snapshot, because fp is spinning in it. It is read first, for a reason the order section quotes.

regs is rax to r15, rip and rflags: the general registers and the program counter, x1 to x31 and pc of RISC-V, with the flags word, which RISC-V spreads over sstatus and has no single register for. sregs is the “special” registers: the segment registers and the descriptor-table registers (the GDT and IDT bases, chapter 24’s long-mode setup), cr0, cr2, cr3, cr4, cr8, EFER, and the interrupt bitmap and APIC base. cr3 is satp’s page-table root, cr0, cr4 and EFER choose the mode (paging on or off, 32 or 64 bits), the work satp.MODE does, and the IDT’s base is stvec with a table of handlers behind it.

xsave is the floating-point and vector register state in the processor’s own save format: the x87 registers, xmm0 to xmm15, mxcsr, and, on a CPU that has them, the AVX upper halves, 4096 bytes of it in this lab. It is RISC-V’s F and D state, f0 to f31 and fcsr, which chapter 8 left unsaved by leaving mstatus.FS Off and compiling without floating point; a guest kernel with processes cannot, and the lab’s fp program holds eight of these registers across the snapshot for exactly that reason. The header at byte 512 says which components are out of their initial state. A vCPU whose guest has enabled a dynamic component (AMX) has a larger area, which only KVM_GET_XSAVE2 returns:

// linux v7.2.8, Documentation/virt/kvm/api.rst:6118-6140
4.134 KVM_GET_XSAVE2
--------------------

:Capability: KVM_CAP_XSAVE2
:Architectures: x86
:Type: vcpu ioctl
:Parameters: struct kvm_xsave (out)
:Returns: 0 on success, -1 on error


::

  struct kvm_xsave {
    __u32 region[1024];
    __u32 extra[0];
  };

This ioctl would copy current vcpu's xsave struct to the userspace. It
copies as many bytes as are returned by KVM_CHECK_EXTENSION(KVM_CAP_XSAVE2)
when invoked on the vm file descriptor. The size value returned by
KVM_CHECK_EXTENSION(KVM_CAP_XSAVE2) will always be at least 4096.
Currently, it is only greater than 4096 if a dynamic feature has been
enabled with ``arch_prctl()``, but this may change in the future.

wick asks KVM_CHECK_EXTENSION(KVM_CAP_XSAVE2) once, before the filter, and refuses to save a vCPU whose answer is above 4096 (extended state beyond 4096 bytes (AMX) is not supported) rather than save a truncated area; the lab guest and both hosts’ guests are at 4096. The documentation above says the check is made on the VM’s descriptor, and wick makes it on /dev/kvm’s: on x86 the answer is the same, because it is computed from the host’s supported components filtered by what the process may enable (arch/x86/kvm/x86.c:4544-4548 and kvm_get_filtered_xcr0 at x86.h:433-445), and not from anything the VM holds. A restore asks again, for a reason the Setting section gives. xcrs is XCR0, the register that says which of those components the guest has switched on, a mask where RISC-V’s sstatus.FS is a two-bit field for the floating-point unit alone. debug_regs are DR0 to DR3, DR6 and DR7, the hardware breakpoints and watchpoints, which RISC-V puts in its trigger module (tselect, tdata1).

lapic is the local APIC of chapter 24, a page of registers (KVM_GET_LAPIC copies “the Local APIC registers”, api.rst:2054, a 1 KiB structure here) that holds the interrupts pending and in service for this CPU, the priority registers, and the CPU’s timer. The timer is the piece that matters here. It has a mode (one-shot, periodic, or TSC-deadline, in which software writes the counter value at which it wants an interrupt), a divider and a current count, and it is stimecmp’s counterpart: where chapter 6 put a number in mtimecmp and took an interrupt when mtime passed it, a guest in TSC-deadline mode writes MSR_IA32_TSC_DEADLINE and takes one when the TSC passes it. A guest that is in hlt is waiting for exactly this timer, and a restored guest whose LAPIC state is missing waits for ever; exercise (b) finds where. tsc_khz is the counter’s frequency, the timebase-frequency of the device tree. cpuid is what the guest was told about the CPU: the list of leaves KVM_SET_CPUID2 set at boot (chapter 24, including the APIC ID the book had to set), RISC-V’s misa and ISA string. The guest chose its code paths by it at boot, and it must see the same answers after the restore.

vcpu_events are the exceptions, NMIs and interrupts that KVM has queued for the guest and not yet delivered, with the interrupt shadow (“Gets currently pending exceptions, interrupts, and NMIs as well as related states of the vcpu”, api.rst:1138-1139), the one instruction after sti in which interrupts still wait. RISC-V’s nearest thing is an interrupt pending in sip that has not been taken, and it has no shadow. And msrs, the model-specific registers of chapter 24 (it met EFER as one), are x86’s CSRs. They hold the syscall entry points, the segment bases, the kvm-clock pages’ addresses, the TSC and the TSC deadline, and the hundred or so other things that an x86 kernel keeps in a register of its own.

One more kind of vCPU state is not in the eleven, and wick makes sure that no guest can have it. A guest that has executed VMX or SVM instructions holds nested state, a second virtual machine’s control structures inside the first, and KVM keeps it apart: KVM_GET_NESTED_STATE and KVM_SET_NESTED_STATE (api.rst:4902-4999, sections 4.114 and 4.115, capability KVM_CAP_NESTED_STATE) are the pair that carries it, in a structure of its own with a VMX and an SVM format. A snapshot of the eleven pieces would restore a guest hypervisor’s host as if it were running no guest. So wick does not offer the feature. The CPUID it gives the guest has the VMX bit (leaf 1, ecx bit 5, Intel) and the SVM bit (leaf 0x80000001, ecx bit 2, AMD) cleared: setup_long_mode, chapter 24’s listing, makes one more call after set_apic_id, mask_nested_virtualization, in x86/regs.rs. A guest that cannot see the bit does not enter VMX or SVM operation, so there is no nested state to save, and a state file’s CPUID is passed through the same function when it is loaded, so a file that offers either bit does not give the restored guest the feature; the MSR list shrinks with it: KVM still lists the VMX capability registers (MSR_IA32_VMX_*, 0x480 to 0x491), but a read of one for a guest without the feature fails (arch/x86/kvm/vmx/vmx.c:2184-2186), which save_msrs already treats as a register that cannot be read here and leaves out; the lab’s state file holds no MSR_IA32_VMX_* entry on either host (labs/ch27/measure/msr-groups.py on both files, 2026-10-03). A VMM that wants a guest to run its own hypervisor has to save the nested state too; this one does not, and says so here and not at the first restore of a guest that tried.

The order, and why

The state is read and written in an order that Firecracker’s authors found by breaking it, and their comments are the reasons. For the read:

// firecracker v1.15.1, src/vmm/src/arch/x86_64/vcpu.rs:557-573
        // Ordering requirements:
        //
        // KVM_GET_MP_STATE calls kvm_apic_accept_events(), which might modify
        // vCPU/LAPIC state. As such, it must be done before most everything
        // else, otherwise we cannot restore everything and expect it to work.
        //
        // KVM_GET_VCPU_EVENTS/KVM_SET_VCPU_EVENTS is unsafe if other vCPUs are
        // still running.
        //
        // KVM_GET_LAPIC may change state of LAPIC before returning it.
        //
        // GET_VCPU_EVENTS should probably be last to save. The code looks as
        // it might as well be affected by internal state modifications of the
        // GET ioctls.
        //
        // SREGS saves/restores a pending interrupt, similar to what
        // VCPU_EVENTS also does.

And for the write:

// firecracker v1.15.1, src/vmm/src/arch/x86_64/vcpu.rs:653-672
        // Ordering requirements:
        //
        // KVM_GET_VCPU_EVENTS/KVM_SET_VCPU_EVENTS is unsafe if other vCPUs are
        // still running.
        //
        // Some SET ioctls (like set_mp_state) depend on kvm_vcpu_is_bsp(), so
        // if we ever change the BSP, we have to do that before restoring anything.
        // The same seems to be true for CPUID stuff.
        //
        // SREGS saves/restores a pending interrupt, similar to what
        // VCPU_EVENTS also does.
        //
        // SET_REGS clears pending exceptions unconditionally, thus, it must be
        // done before SET_VCPU_EVENTS, which restores it.
        //
        // SET_LAPIC must come after SET_SREGS, because the latter restores
        // the apic base msr.
        //
        // SET_LAPIC must come before SET_MSRS, because the TSC deadline MSR
        // only restores successfully, when the LAPIC is correctly configured.

wick follows both. The read is mp_state, regs, sregs, xsave, xcrs, debug_regs, lapic, tsc_khz, cpuid, msrs, vcpu_events (snapshot/vcpu.rs, the ch27-vcpu-save listing, whose comment cites these lines), and the write is cpuid (preceded by tsc_khz when the host’s rate differs from the saved one, below; the figure marks that conditional step with parentheses), mp_state, regs, sregs, xsave, xcrs, debug_regs, lapic, msrs, vcpu_events, kvmclock_ctrl. Four adjacencies are constraints, and the figure draws two as brackets. KVM_GET_MP_STATE first, because it “calls kvm_apic_accept_events(), which might modify vCPU/LAPIC state”; KVM_GET_VCPU_EVENTS last, because, in Firecracker’s hedge, it “should probably be last to save” and “might as well be affected by internal state modifications of the GET ioctls”. SET_REGS before SET_VCPU_EVENTS, because setting the registers clears pending exceptions. And the bracket that does the most work: SET_LAPIC after SET_SREGS, since the segment-register call restores the APIC base MSR, and before SET_MSRS, because “the TSC deadline MSR only restores successfully, when the LAPIC is correctly configured.” Exercise (c) does the last one in the wrong order. A fifth rule is not an adjacency: CPUID comes first, and Firecracker’s reason is again a suspicion (“Some SET ioctls (like set_mp_state) depend on kvm_vcpu_is_bsp() ... The same seems to be true for CPUID stuff”, vcpu.rs:658-660).

One more rule is about where the vCPU’s state sits relative to the VM’s and the devices’. Firecracker builds a restored machine in this order: the VM and the vCPUs, the memory, the TSC’s scaling, the vCPUs’ state, the VM’s state, then the devices.

// firecracker v1.15.1, src/vmm/src/builder.rs:460-497
    vm.restore_memory_regions(guest_memory, &microvm_state.vm_state.memory)
        .map_err(StartMicrovmError::Vm)?;

    #[cfg(target_arch = "x86_64")]
    {
        // Scale TSC to match, extract the TSC freq from the state if specified
        if let Some(state_tsc) = microvm_state.vcpu_states[0].tsc_khz {
            // Scale the TSC frequency for all VCPUs. If a TSC frequency is not specified in the
            // snapshot, by default it uses the host frequency.
            if vcpus[0].kvm_vcpu.is_tsc_scaling_required(state_tsc)? {
                for vcpu in &vcpus {
                    vcpu.kvm_vcpu.set_tsc_khz(state_tsc)?;
                }
            }
        }
    }

    // Restore vcpus kvm state.
    for (vcpu, state) in vcpus.iter_mut().zip(microvm_state.vcpu_states.iter()) {
        vcpu.kvm_vcpu
            .restore_state(state)
            .map_err(VcpuError::VcpuResponse)
            .map_err(BuildMicrovmFromSnapshotError::RestoreVcpus)?;
    }

    #[cfg(target_arch = "aarch64")]
    {
        if clock_realtime {
            return Err(BuildMicrovmFromSnapshotError::UnsupportedClockRealtime);
        }
        let mpidrs = construct_kvm_mpidrs(&microvm_state.vcpu_states);
        // Restore kvm vm state.
        vm.restore_state(&mpidrs, &microvm_state.vm_state)?;
    }

    // Restore kvm vm state.
    #[cfg(target_arch = "x86_64")]
    vm.restore_state(&microvm_state.vm_state, clock_realtime)?;

and says why the devices are last (builder.rs:504-507, quoted next: restoring VMGenID “injects an interrupt in the guest”, so the device manager must be restored after the KVM state, “otherwise the injected interrupt will be overwritten”):

// firecracker v1.15.1, src/vmm/src/builder.rs:504-507
    // Restore devices states.
    // Restoring VMGenID injects an interrupt in the guest to notify it about the new generation
    // ID. As a result, we need to restore DeviceManager after restoring the KVM state, otherwise
    // the injected interrupt will be overwritten.

wick has the same reason twice over. The console’s UART, built from its saved registers, raises the interrupt again if the registers say one was owed (Serial::from_state writes its eventfd), and the vsock device sends the guest a reset event (below): both are interrupts, and KVM_SET_IRQCHIP would erase an interrupt already in the 8259’s registers. The console’s eventfd is therefore not registered with KVM until the controllers’ state is back, and KVM injects an eventfd that is already pending when it is registered:

// linux v7.2.8, virt/kvm/eventfd.c:471-488
    /*
     * Register the irqfd with the eventfd by polling on the eventfd, and
     * simultaneously and the irqfd to KVM's list.  If there was en event
     * pending on the eventfd prior to registering, manually trigger IRQ
     * injection.
     */
    irqfd_pt.irqfd = irqfd;
    irqfd_pt.kvm = kvm;
    init_poll_funcptr(&irqfd_pt.pt, kvm_irqfd_register);

    events = vfs_poll(fd_file(f), &irqfd_pt.pt);

    ret = irqfd_pt.ret;
    if (ret)
        goto fail_poll;

    if (events & EPOLLIN)
        schedule_work(&irqfd->inject);

MSRs: a list the kernel hands you, and two you handle yourself

Which MSRs exist differs between CPUs, kernels and VM configurations, so a VMM does not write a list. It asks. KVM_GET_MSR_INDEX_LIST on the /dev/kvm descriptor returns the indices KVM can save and restore on this host (about a hundred: 90 on talos and 104 on straylight, by labs/ch27/measure/msr-list.py; the lab’s state files hold 78 and 104, because on talos the twelve VMX capability registers in the list cannot be read for a guest without VMX (arch/x86/kvm/vmx/vmx.c:2184-2186), and each short read ends a KVM_GET_MSRS call: thirteen calls there, one on straylight (chapter 26)), KVM_GET_MSRS on the vCPU reads at most 255 of them at a time (the kernel refuses nmsrs >= MAX_IO_MSRS, 256, with E2BIG: arch/x86/kvm/x86.c:93 and :4280; kvm-bindings’ KVM_MAX_MSR_ENTRIES is that 256, one more than a call may take) and returns how many it managed, and the first one it did not manage is at that position. The list holds registers that cannot be read in every configuration (the performance counters’ MSRs when the CPUID hides the PMU, for one), so a short read is not an error. Firecracker stops at it with VcpuGetMsr(msrs.as_slice()[nmsrs].index) and keeps a hand-written list of what to try (the hand-kept SERIALIZABLE_MSR_RANGES at arch/x86_64/msr.rs:144-240, the error at arch/x86_64/vcpu.rs:518-526); wick leaves the unreadable one out and goes on with the next, which is the ch27-msrs listing, and a restore refuses a state file that names an MSR the new host does not list, before it reaches KVM: a list that does not match is a state from another kind of machine.

wick saves every index KVM lists, which is more than Firecracker’s SERIALIZABLE_MSR_RANGES keeps: on both hosts the lab’s state file holds 17 Hyper-V indices (HV_X64_MSR_*, 0x40000000 to 0x400000f5), and on straylight 24 performance-counter and control indices as well (0xc0010000 to 0xc0010007, 0xc0010200 to 0xc001020b and 0xc0000300 to 0xc0000303), none of which Firecracker’s ranges contain (msr-groups.py, 2026-10-03). Restoring them is harmless on the host that saved them. This guest uses kvm-clock and not Hyper-V’s clocks, KVM ignores a host-initiated write to HV_X64_MSR_TIME_REF_COUNT and turns one to HV_X64_MSR_VP_RUNTIME into an offset against the thread’s own run time (arch/x86/kvm/hyperv.c:1494-1498 and :1598-1602), and a counter that is restored is one a diff of two snapshots shows moving, as exercise (e) does.

Two of them are not restored like the others. The TSC, MSR_IA32_TSC (0x10), is the guest’s cycle counter. The TSC deadline, MSR_IA32_TSC_DEADLINE (0x6e0), is the value the LAPIC timer compares it with, and KVM reads the TSC when the deadline is written to decide whether a timer has to be armed at all. Firecracker’s comment says what goes wrong, and the constant that fixes it:

// firecracker v1.15.1, src/vmm/src/arch/x86_64/vcpu.rs:40-48
/// A set of MSRs that should be restored separately after all other MSRs have already been restored
const DEFERRED_MSRS: [u32; 1] = [
    // MSR_IA32_TSC_DEADLINE must be restored after MSR_IA32_TSC, otherwise we risk "losing" timer
    // interrupts across the snapshot restore boundary (due to KVM querying MSR_IA32_TSC upon
    // writes to the TSC_DEADLINE MSR to determine whether it needs to prime a timer - if
    // MSR_IA32_TSC is not initialized correctly, it can wrongly assume no timer needs to be
    // primed, or the timer can be initialized with a wrong expiry).
    MSR_IA32_TSC_DEADLINE,
];

So the deadline is set last, in a call of its own, after every other MSR. And a deadline of zero, which is what a snapshot of a guest with no timer armed at that instant holds, is replaced by the TSC’s value, because Firecracker observed that “sometimes when taking a snapshot, the IA32_TSC_DEADLINE MSR is cleared, but the interrupt is not delivered to the guest, leading to a situation where one of the vCPUs never receives TSC interrupts after restoring” (arch/x86_64/vcpu.rs:385-413, whose function is fix_zero_tsc_deadline_msr). Both are in restore_msrs. Exercise (c) and the ablation table take the order away; nothing takes the zero-deadline replacement away, and it is not tested here.

The VM’s pieces

The VM’s own state is five pieces, read in the order the Firecracker save has them (arch/x86_64/vm.rs:181-219, and set in :132-162):

  • pit is the 8254 interval timer of chapter 24, which wick creates with the VM: three channels, each with a count, a mode and the time it was loaded.
  • clock is kvm-clock’s value, the guest’s monotonic clock as KVM keeps it. KVM_GET_CLOCK returns its flags, which on both hosts read 0xe: KVM_CLOCK_TSC_STABLE, KVM_CLOCK_REALTIME and KVM_CLOCK_HOST_TSC. Those flags must not go back. The documentation of the set side:
// linux v7.2.8, Documentation/virt/kvm/api.rst:1090-1111
4.30 KVM_SET_CLOCK
------------------

:Capability: KVM_CAP_ADJUST_CLOCK
:Architectures: x86
:Type: vm ioctl
:Parameters: struct kvm_clock_data (in)
:Returns: 0 on success, -1 on error

Sets the current timestamp of kvmclock to the value specified in its parameter.
In conjunction with KVM_GET_CLOCK, it is used to ensure monotonicity on scenarios
such as migration.

The following flags can be passed:

KVM_CLOCK_REALTIME
  If set, KVM will compare the value of the `realtime` field
  with the value of the host's real time clocksource at the instant when
  KVM_SET_CLOCK was called. The difference in elapsed time is added to the final
  kvmclock value that will be provided to guests.

Other flags returned by ``KVM_GET_CLOCK`` are accepted but ignored.

A KVM_SET_CLOCK that carries KVM_CLOCK_REALTIME adds the wall-clock time since the snapshot to the guest’s clock, which a restored guest would see as its clock jumping forward by however long the snapshot sat. restore clears the flags, as Firecracker does unless asked (clock_realtime: true on its LoadSnapshot, swagger lines 1634-1641), and the guest’s clock resumes from the instant of the snapshot.

  • pic_master, pic_slave, ioapic are the interrupt controllers, fetched with KVM_GET_IRQCHIP three times, with chip ids 0, 1 and 2: the 8259 pair that chapter 24 wired GSIs 0 to 15 through, and the IOAPIC. They are the PLIC’s counterpart, with a pending bit, a mask and an in-service bit for each line, and a restore that left them out would lose an interrupt that had been raised and not yet taken.

Device state

A virtio device’s state in the VMM is small, and chapter 22 already said why: the three rings of a queue are guest memory, which travels in the memory file, and what the device itself holds is two cursors, how far it has read the available ring (next_avail) and how far it has written the used ring (next_used). The rest of a device is the transport’s registers: the status byte, the accepted features, the register selectors and, for each queue, the size, the three ring addresses and whether the driver set it ready. ch27-transport-restore, below, sets all of it back, and its refusals are the point.

A state file is not trusted more than a guest. The transport’s rules for what a driver may write (a size that is a power of two within the device’s maximum, aligned ring addresses that are not 0, three rings inside guest memory and apart) are the rules a state must satisfy, so the restore sets each queue the way the driver’s writes would have and then runs the transport’s own QueueReady check. Then it checks what only a snapshot can get wrong: the cursors against the rings in memory. The device wrote used.idx when it advanced next_used, so the two must be equal; the driver cannot have made more buffers available than the queue holds, so avail.idx - next_avail is at most the queue’s size. The device cannot have used what it has not taken, so next_used is never ahead of next_avail, which is checked modulo the ring’s size too. A device restored with a cursor that disagrees with its ring serves a buffer twice or never; the first would let a hostile file make the device write a guest buffer the driver has since reused. The device is then given its queues through the same activate the guest’s DRIVER_OK would have called, and told the accepted features through the same ack_features.

Three things do not travel, and each has an answer. A doorbell that was ringing. The queue’s eventfd is a file descriptor in the old process; a buffer the driver offered and rang for, that the VMM had not yet served, is in the ring and not in the new process’s eventfd. A resume rings every ready queue’s doorbell once, which Resume does and Firecracker’s resume_vm does (lib.rs:505, kick_virtio_devices); a doorbell for an empty ring finds nothing to do. The TAP’s queue. The frames the host kernel had queued for the guest are the host’s and are not in the snapshot; a restored guest sees the loss a lossy network already has. The guest’s vsock connections. Each was a host Unix socket in the old process, and a descriptor is a number in a process, so a restored guest holds connections to nothing. The replies the device still owed, a reset for a connection request to a port with no listener, are not saved either: that guest socket has not connected, so the event below does not touch it, and it waits out its own connect timeout. The device tells the others so. The virtio specification has an event for exactly this:

// virtio 1.2 (OASIS, July 2022), section 5.10.6.7, p. 162
5.10.6.7 Device Events
Certain events are communicated by the device to the driver using the event virtqueue.
The event buffer is as follows:
#define VIRTIO_VSOCK_EVENT_TRANSPORT_RESET 0
struct virtio_vsock_event {
le32 id;
};
The VIRTIO_VSOCK_EVENT_TRANSPORT_RESET event indicates that communication has been inter-
rupted. This usually occurs if the guest has been physically migrated. The driver shuts down established
connections and the guest_cid configuration field is fetched again. Existing listen sockets remain but their
CID is updated to reflect the current guest_cid.
5.10.6.7.1 Driver Requirements: Device Operation: Device Events
Event virtqueue buffers SHOULD be replenished quickly so that no events are missed.
The guest_cid configuration field MUST be fetched to determine the current CID when a VIRTIO_VSOCK_-
EVENT_TRANSPORT_RESET event is received.
Existing connections MUST be shut down when a VIRTIO_VSOCK_EVENT_TRANSPORT_RESET event
is received.
Listen connections MUST remain operational with the current CID when a VIRTIO_VSOCK_EVENT_TRANS-
PORT_RESET event is received.

The device sends one VIRTIO_VSOCK_EVENT_TRANSPORT_RESET, in the first buffer the driver posted on the event queue, with an interrupt, after the interrupt controllers are restored (restored() in devices/vsock/mod.rs, and tests/snapshot_vsock.rs, which checks the id, the length, the interrupt and the driver that posted nothing). The Linux driver resets its sockets and reads the CID again:

// linux v7.2.8, net/vmw_vsock/virtio_transport.c:437-446
static void virtio_vsock_event_handle(struct virtio_vsock *vsock,
                      struct virtio_vsock_event *event)
{
    switch (le32_to_cpu(event->id)) {
    case VIRTIO_VSOCK_EVENT_TRANSPORT_RESET:
        virtio_vsock_update_guest_cid(vsock);
        vsock_for_each_connected_socket(&virtio_transport.transport,
                        virtio_vsock_reset_sock);
        break;
    }

A listening socket in the guest survives, as the specification says, and so does Firecracker’s documentation (snapshot-support.md:55-60: “vsock connections that are open when the snapshot is taken are closed, but existing vsock listen sockets in the guest still remain active and can accept new connections after resume”).

A fourth thing does travel, but not through the queues. An interrupt in flight. A device raises its interrupt by setting InterruptStatus and writing 1 to an eventfd that KVM watches, and KVM does not deliver it from the write. For an interrupt routed through the 8259 or the IOAPIC, the atomic path gives up: kvm_arch_set_irq_inatomic handles only MSI, Hyper-V SynIC and Xen routes and ends in return -EWOULDBLOCK (arch/x86/kvm/irq.c:241-277), and the eventfd’s wakeup, having already read the counter, schedules a work item that injects it (virt/kvm/eventfd.c:221-239). Between the write and that work item the interrupt is in no register a snapshot reads: the eventfd is empty and the 8259 does not have it yet. A snapshot taken in that window loses the interrupt, and the guest’s driver waits for a completion it was never told of. The witness is the status register, which is set before the write and cleared only by the driver’s acknowledge: a saved interrupt_status that is not 0 means an interrupt is owed. restore_slot raises the line once more when it is, after the controllers’ state is back (reraise_interrupt). The cost of being wrong the other way, an interrupt that was already injected and not yet acknowledged, is a second edge that the driver answers as one that is not its own, the same price Serial::from_state pays for the console. a_restored_transport_raises_an_owed_interrupt_again_and_only_then in mmio.rs pins both halves, and the reraise piece of the ablation table leaves it out.

The console is the last device and the simplest: the 8250’s eight registers and its receive FIFO, which vm-superio’s Serial::state returns and Serial::from_state rebuilds (and refuses, if the FIFO is longer than the hardware’s). The guest’s output goes wherever the new process was told to send it.

Time

Three clocks are in play and each has an answer. The guest’s monotonic clock, by its boot log (labs/ch27/measure/clock.sh, 2026-10-03, on both hosts: kvm-clock: Using msrs 4b564d01 and 4b564d00, clocksource: Switched to clocksource kvm-clock, then clocksource: Switched to clocksource tsc, and current_clocksource reads tsc), starts on kvm-clock and switches to the TSC, which the kernel does when it judges the TSC reliable; so the clock piece matters to a guest that stays on kvm-clock, which this one does not, and leaving it out is silent in the table below. With its flags cleared, a guest that does use it resumes at the instant of the snapshot and not later. The TSC is the MSR above, restored with the other MSRs, so the counter continues from the value it had; and if the host’s TSC frequency differs from the saved one by more than 250 parts per million, the restore asks KVM to scale it first (KVM_SET_TSC_KHZ, Firecracker’s is_tsc_scaling_required, vcpu.rs:634-644, and builder.rs:463-475 above), which the same host never needs. The wall clock, CLOCK_REALTIME, is derived from those and continues from the instant of the snapshot too, so it is wrong by however long the snapshot sat. Firecracker’s documentation says so, and what to do:

// firecracker v1.15.1, docs/snapshotting/snapshot-support.md:491-500
It is also worth knowing, a microVM that is restored from snapshot will be
resumed with the guest OS wall-clock continuing from the moment of the snapshot
creation. For this reason, the wall-clock should be updated to the current time,
on the guest-side. More details on how you could do this can be found at a
[related FAQ](../../FAQ.md#my-guest-wall-clock-is-drifting-how-can-i-fix-it).
When using `kvm-clock` as clock source on `x86_64`, it's possible to optionally
set the `clock_realtime: true` in the `LoadSnapshot` request to advance the
clock on the guest at restore time (host Linux >= 5.16 is required to support
this feature). Note that this may cause issues within the guest as the clock
will appear to suddenly jump.

wick has no clock_realtime: a guest that wants the right time after a restore sets it itself.

The file, and what is refused

The state file is JSON (serde_json), and a reader can open it. Its top level is magic, version, wick_version, config (the whole VmConfig the machine was built from, so a load needs no configuration of its own), vm, vcpu, serial and devices. Every struct has deny_unknown_fields, so a file with a field this wick does not know is refused and not half read, and version is 1: a reader of another version refuses the file.

The KVM structures are in it as hexadecimal strings of their bytes, not as kvm-bindings’ own serde would write them, and the reason is in that crate:

// kvm-bindings 0.14.1, src/serialize.rs:39-56
                        fn visit_bytes<E>(self, bytes: &[u8]) -> Result<Self::Value, E> {
                            let mut backing = [0u8; std::mem::size_of::<$typ>()];
                            let limit = bytes.len().min(backing.len());
                            backing[..limit].copy_from_slice(&bytes[..limit]);
                            Ok(backing)
                        }

                        fn visit_seq<A: serde::de::SeqAccess<'a>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
                            let mut backing = [0u8; std::mem::size_of::<$typ>()];

                            for backing_byte in &mut backing {
                                let Some(byte) = seq.next_element()? else { break };

                                *backing_byte = byte;
                            }

                            Ok(backing)
                        }

Both visitors take a byte array of any length, copy what is there and leave the rest zero. A state file cut short, or a lapic of 1,000 bytes where 1,024 are needed, would load as a structure with zeros at the end and no error; and the round-trip test could not see it, because it only meets arrays the crate itself wrote. Pod<T> in snapshot/mod.rs takes exactly size_of::<T>() bytes as hex digits and refuses anything else, using the crate’s implementations for the byte layout. The MSRs are the exception, as a list of [index, value] pairs a reader can search. The state is about 22,630 bytes on talos (78 MSRs, 55 CPUID entries) and 24,048 on straylight (104 MSRs, 67 CPUID entries), 2026-10-03; Firecracker’s is a binary format with a 64-bit CRC (snapshot-support.md:100-106: “only a partial measure to protect against accidental corruption”), and wick has none: it checks the file’s structure and the consistency of what it names, and a flipped bit in the memory file restores a corrupted guest. The memory file is the guest’s RAM and nothing else, byte for byte, 128 MiB here.

Two decisions shape how the files are made, and both come from chapter 26. A file the VMM makes after the filter is on needs an openat, and an openat is a call the filter cannot see into: it sees six integers, and the path is a pointer. The list therefore has one openat rule, which passes only AT_FDCWD as the directory, the flags O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC (0x800c1) and the mode 0600, so that no file made is executable or setuid: it can make a file that did not exist, and cannot open one that did, for reading or for writing, or follow a symbolic link. (AT_FDCWD does not confine the path: for an absolute path the kernel ignores the directory.) That is the cost, plainly: a compromised wick can create new files, of any content it likes, in any directory it can write. In the root form of the jail that is /run and the target of every --bind-rw of a directory; in the unprivileged form, the lab’s, the jail’s root and its /dev as well, because they are directories of the invoking user. It cannot read a file it did not already hold open, truncate or replace one, and the call is a refusal, not an overwrite, when a name is taken. Firecracker’s three thread filters allow a bare open (resources/seccomp/x86_64-unknown-linux-musl.json, lines 23, 519 and 797, the VMM, API and vCPU threads), and its VMM thread also fsync and, with comments that say they are for snapshots, stat (line 8, “Used when creating snapshots in vmm:persist::snapshot_memory_to_file through std::fs::File::metadata”) and ftruncate (lines 85-86). And the second decision follows from the first: the state file is not written to a temporary name and renamed, because rename cannot be restricted by argument either, and would let the same process replace any file it can write. The memory file is written first and flushed with fdatasync; the state file, which describes it, is written second, and a failure wick sees removes both files. A reader that opens the state file while it is being written sees a truncated JSON file and refuses it, and so does a reader after a kill in the middle of the write, which leaves the half-written file at that name and makes O_EXCL refuse to overwrite it.

What is refused is what the machine has no way to do. snapshot_type Diff is a 400: a diff snapshot is the pages written since the last one, which needs the kernel’s dirty-page log (KVM_GET_DIRTY_LOG), and wick never asks KVM to keep one. PUT /snapshot/load is pre-boot only, in a process with no boot source and no devices configured, since the snapshot holds its own; PUT /snapshot/create needs a paused machine. A load on a different kind of host is not refused by name, and Firecracker says why it is not safe:

// firecracker v1.15.1, docs/snapshotting/snapshot-support.md:660-665
Snapshots must be resumed on an software and hardware configuration which is
identical to what they were generated on. However, in limited cases, snapshots
can be resumed on identical hardware instances where they were taken on, but
using newer host kernel versions. While we do not provide any guarantees on this
setup (and do not recommend doing this in production), we are currently aware of
the compatibility table reported below:

The fields of Firecracker’s LoadSnapshot that name things wick does not have (mem_backend, track_dirty_pages, enable_diff_snapshots, network_overrides, clock_realtime) are unknown fields here. And the name wick keeps is one Firecracker’s own schema has deprecated: mem_file_path, in favour of mem_backend (“This parameter has been deprecated and it will be removed in future Firecracker release”, swagger lines 1610-1615), and wick, which has only the file, keeps the older name. The two also differ in what loading a memory file costs. Firecracker maps the file MAP_PRIVATE and lets the guest’s first touches page it in, “resulting in runtime on-demand loading of memory pages” (snapshot-support.md:78-85), so a load is fast and the file must outlive the guest; wick reads the whole file into guest RAM before it resumes the guest, so a load costs the read and the file can be deleted at once. Chapter 28 puts numbers on both.

The ablation: what the obvious test does not notice

A snapshot that restores a guest which then prints its next line has shown very little, and the lab’s second guest was built to show what the first one did not. labs/ch27/ablate.sh leaves one piece of state out of the restore at a time (an ablate build of wick, WICK_ABLATE=piece), runs the lab ten times, and sorts each run by what the guest did. There are nineteen pieces, counting the restore of the device’s re-raised interrupt. Ten runs on talos and ten on straylight for each piece, 2026-10-03; where the hosts differ, both are given. Eleven pieces are silent, six are loud and the same, and two are loud and different.

Silent: ten of ten runs on both hosts are the capture, byte for byte. Eleven pieces:

  • cpuid: replaced by the host’s supported list, which is what wick gave the guest at boot but for the APIC ID fields (chapter 24), which the guest read once.
  • mp_state: the guest is running fp when the snapshot is taken, which is RUNNABLE, the state a new vCPU starts in.
  • debug_regs, vcpu_events: no breakpoint was set (DR7 has its reset value) and no exception or interrupt was pending.
  • kvmclock_ctrl: it sets a flag only the guest’s soft-lockup watchdog reads.
  • pit: the guest does not use the PIT after boot (it uses the LAPIC timer), so a PIT in its reset state is not seen.
  • clock: the guest’s clocksource is the TSC, as the boot log above shows, and kvm-clock is not what it reads.
  • ioapic: wick routes every device interrupt through the PIC, and nothing programs the IOAPIC.
  • serial: the lab’s few lines print without the saved registers; the continuity test, which prints for ever, does see it.
  • irq_status: InterruptStatus was 0 when the snapshot was taken.
  • reraise: for the same reason, there was no owed interrupt to raise again; the window it closes is not one a lab can aim at, and the transport’s unit test is what exercises it.

Loud, and the same every time.

  • xsave: ten of ten on both hosts print tick 3 to tick 6, a right blk line and a Shutdown, and fp: CORRUPT xmm8. The guest runs on; only the program that held eight registers is told, and it is told on its first register. This is the ablation the guest was built for: no tick count shows it.
  • lapic, msrs, tsc_deadline, pic, and msrs_first (the MSRs set before the LAPIC, exercise (c)): ten of ten on both hosts print nothing after the restore and are ended by the 25-second bound (rc=124). For lapic and msrs_first the second snapshot of exercises (b) and (c) shows that the guest is not waiting in hlt: it is running fp’s loop, and nothing preempts it because the timer interrupt that would end init’s sleep 1 is never delivered. Where the guest waits for msrs, tsc_deadline and pic was not measured. For pic the cause is likely the same kind of thing: a restored 8259 pair in its reset state delivers no device interrupt at all, the console’s included, which chapter 24 showed userland output needs; that is a reading, not a run.

Loud, and different every time.

  • xcrs: XCR0 comes back as the reset’s 1, x87 only, while the guest kernel’s own state says SSE and AVX are on, and the guest’s next xsave or xrstor is a fault. Three outcomes, and a run takes any of them: a triple fault (Shutdown, rc=0, so a clean reboot and a crash are the same exit to wick, chapter 24), a hang (rc=124), and KVM’s InternalError (wick: FAIL, rc=1). Ten runs on each host, 2026-10-03: talos 3 triple faults, 6 hangs and 1 InternalError; straylight 3 triple faults, 5 hangs and 2 InternalError. No run printed a tick.
  • queue_cursors: the cursors come back as 0 while the rings in memory say the device had used 2 buffers, and the resume rings the doorbell once, so the device serves the two buffers the driver had already collected and writes into memory the guest has since reused. What follows is whatever those pages held. In this set of ten, on talos: five triple faults with no tick, one hang with no tick, two hangs after three ticks, one run with four ticks and a right blk line and the guest kernel’s own Corrupted page table at address 7ffd... where fp’s line should be, and one with four ticks, a right blk line and no fp line; on straylight: one run is the capture, one a triple fault, two hangs with no tick, three hangs after three ticks, one Corrupted page table, and two runs with four ticks, a right blk line and fp: registers intact, which are not equal to the capture and which a test of the registers alone would pass. A guest that prints its ticks is not proof here either, and the counts differ from one set of ten to the next.

The table is the chapter’s argument, and what it says is in three parts. A restore can be wrong in a way no tick shows (xsave, and queue_cursors on a lucky run). The pieces whose absence is silent on this guest are the ones this guest does not use, and a guest that uses them, a kvm-clock guest, a breakpoint, an IOAPIC, would show them: silent here means untested here, not safe to omit. And a snapshot has to be tested by something other than the guest’s own output: tests/snapshot_roundtrip.rs puts a value in every piece before it saves (poke) and compares every field after the restore, and the omissions run against it are caught by it, or by the continuity test or the transport’s unit tests, for every piece but one. The method is labs/ch27/measure/mutation.sh: one piece omitted per build of wick with the ablate feature, the snapshot tests and the transport’s unit tests run, and the tests that go red named; its first row, none, omits nothing and is green. Both hosts, 2026-10-03, give the same sets of red tests. One piece goes uncaught on both: kvmclock_ctrl, whose only effect is a flag in the guest’s clock page that the soft-lockup watchdog reads, and which nothing in the repository can see. (poke flips one CPUID bit, so that the cpuid row does not depend on which CPU the test runs on: the host’s supported list differs from the saved one otherwise only in the APIC ID, which is the CPU the ioctl ran on’s.) The chapter says so, and leaves it: Firecracker calls it for the reason in the quotation above, and a restore that skips it costs a false lockup warning, not a state.

Walkthrough

Everything new is in wick/src/snapshot/ (mod.rs, vcpu.rs, vm.rs, devices.rs), vcpu.rs’s parked thread and mmio.rs’s transport, and the tests are wick/tests/snapshot_roundtrip.rs and wick/tests/snapshot_vsock.rs. The kick is chapter 24’s ch24-kick and is not listed again.

The parked thread

/// The thread's life: parked, serving the VMM thread's requests, until a resume starts the exit loop; a pause brings it
/// back here. `None` means the handle was dropped; `Some` is the end of the guest.
fn serve(vcpu: &mut VcpuFd, pio: &Bus, mmio: &Bus, stop: &AtomicBool, cmd: &mpsc::Receiver<Cmd>, events: &mpsc::Sender<Event>) -> Option<VcpuStop> {
    loop {
        match cmd.recv().ok()? {
            Cmd::Call(n, f) => {
                f(vcpu);
                let _ = events.send(Event::CallDone(n));
            }
            Cmd::Resume(n) => {
                // A kick that landed while the thread was parked left a 1 in the page (the handler writes it whatever the
                // thread is doing); it and the stop flag are cleared here, on this thread, before the loop's first check.
                set_immediate_exit(0);
                stop.store(false, Ordering::SeqCst);
                let _ = events.send(Event::Resumed(n));
                match run_loop(vcpu, pio, mmio, stop) {
                    Leave::Ended(why) => return Some(why),
                    Leave::Paused => {
                        // Tell the guest's kvm-clock it was stopped by the host, so its soft-lockup watchdog does not take
                        // the gap for a hang (api.rst, KVM_KVMCLOCK_CTRL). `EINVAL` when kvm-clock is not in use: not an error.
                        let _ = vcpu.kvmclock_ctrl();
                        let _ = events.send(Event::Paused);
                    }
                }
            }
        }
    }
}

serve is the thread’s whole life after it has told the VMM thread it is ready. A Call(n, f) runs a closure on the VcpuFd, answers CallDone(n) and does nothing else; a Resume(n) clears the stale byte and the stop flag on this thread, in that order, and before it answers Resumed(n): the order that keeps a Pause sent right after a Resume from meeting a flag the thread has not cleared yet. Then it runs the exit loop (ch24-exit-loop: it returns Leave::Paused when it finds the stop flag, after the pending exit is completed, and Leave::Ended when the guest ends), and a pause comes back here, after kvmclock_ctrl, to answer Paused and wait again. None is the handle dropped while the thread is parked: a machine that was never started, or a load that failed.

/// Run `f` on the vCPU thread, which owns the `VcpuFd`, and return what it returns. Only a paused vCPU can: a running
/// one is inside `KVM_RUN`, and the state of a running vCPU is not state (`KVM_GET_VCPU_EVENTS` is "unsafe if other
/// vCPUs are still running", Firecracker's comment, arch/x86_64/vcpu.rs:557-572). The thread serves the request the way
/// Firecracker's serves `VcpuEvent::SaveState` (vstate/vcpu.rs:321-334): while parked, one request at a time. The wait has
/// a deadline; a call that misses it stays outstanding and is settled by the next request, and its result is lost.
pub fn call_within<R: Send + 'static>(&mut self, within: Duration, f: impl FnOnce(&mut VcpuFd) -> R + Send + 'static) -> Result<R> {
    self.settle(within)?;
    if !self.paused {
        return Err(Error::State("the vcpu is running: pause it first".into()));
    }
    self.seq += 1;
    let n = self.seq;
    let (tx, rx) = mpsc::channel();
    self.pending = Pending::Call(n);
    if self.cmd.send(Cmd::Call(n, Box::new(move |vcpu| drop(tx.send(f(vcpu)))))).is_err() {
        self.pending = Pending::Nothing;
        return Err(Error::State("the guest has ended".into()));
    }
    self.settle(within)?;
    rx.try_recv().map_err(|_| Error::State("the guest has ended".into()))
}

/// `call_within` the usual time.
pub fn call<R: Send + 'static>(&mut self, f: impl FnOnce(&mut VcpuFd) -> R + Send + 'static) -> Result<R> {
    self.call_within(ANSWER_TIMEOUT, f)
}

call_within is the VMM thread’s end, and the first thing it does is settle, which reads the answers of any request still outstanding (the Pause section’s rule). It refuses a running vCPU, numbers the closure and sends it, waits for its answer, up to the deadline, and takes the closure’s result from a channel of its own; if the thread is gone, the channel closes and the answer is “the guest has ended”. A call that misses its deadline stays outstanding, and its result is dropped when it is settled.

Reading a vCPU

/// Read the vCPU's state. The thread is parked and its pending exit is complete (`complete_pending_exit`), so nothing
/// moves under these calls. The order is Firecracker's (v1.15.1 arch/x86_64/vcpu.rs:556-615) and its comment is why:
/// `KVM_GET_MP_STATE` can change LAPIC state, so it is first; `KVM_GET_LAPIC` may change the LAPIC as it reads it;
/// `KVM_GET_VCPU_EVENTS` may be affected by the other reads, so it is last.
pub fn save(vcpu: &VcpuFd, probe: &Probe) -> Result<VcpuSaved> {
    let mp_state = vcpu.get_mp_state()?;
    let regs = vcpu.get_regs()?;
    let sregs = vcpu.get_sregs()?;
    if probe.xsave2_size > XSAVE_LEGACY_BYTES {
        return Err(Error::Snapshot(format!(
            "extended state beyond 4096 bytes (AMX) is not supported: KVM_CAP_XSAVE2 reports {} bytes",
            probe.xsave2_size
        )));
    }
    let xsave = vcpu.get_xsave()?;
    let xcrs = vcpu.get_xcrs()?;
    let debug_regs = vcpu.get_debug_regs()?;
    let lapic = vcpu.get_lapic()?;
    let tsc_khz = vcpu.get_tsc_khz().ok();
    let cpuid = vcpu.get_cpuid2(KVM_MAX_CPUID_ENTRIES)?.as_slice().iter().map(|e| Pod(*e)).collect();
    let msrs = save_msrs(vcpu, &probe.msr_indices)?;
    let vcpu_events = vcpu.get_vcpu_events()?;
    Ok(VcpuSaved {
        cpuid,
        mp_state: Pod(mp_state),
        regs: Pod(regs),
        sregs: Pod(sregs),
        xsave: Pod(xsave),
        xcrs: Pod(xcrs),
        debug_regs: Pod(debug_regs),
        lapic: Pod(lapic),
        msrs,
        vcpu_events: Pod(vcpu_events),
        tsc_khz,
    })
}

The Probe is what the thread cannot ask for. KVM_GET_MSR_INDEX_LIST and KVM_CHECK_EXTENSION are calls on the /dev/kvm descriptor, which the vCPU thread does not hold and the filter does not list, so the VMM thread asks both before the filter and hands the answers over in the closure. The reads themselves are the eleven ioctls of the figure, in the order of the comment; each is ?, so the first failure returns Error::Kvm and nothing is written.

/// Read every MSR the host lists, in chunks `KVM_GET_MSRS` takes (at most `MSR_CHUNK`, 255). It returns how many it read:
/// fewer than asked means the MSR at that position is one the host lists and will not give (KVM's list holds some it
/// cannot read, for instance PMU registers when CPUID hides the PMU). Firecracker stops there with an error and keeps a
/// hand-written list of what to try (v1.15.1 arch/x86_64/msr.rs:146-240, :524-526); `wick` leaves that one out and goes
/// on with the next. An MSR left out is one a guest cannot have been using through KVM's own save path.
fn save_msrs(vcpu: &VcpuFd, indices: &[u32]) -> Result<Vec<(u32, u64)>> {
    let mut saved = Vec::with_capacity(indices.len());
    let mut rest = indices;
    while !rest.is_empty() {
        let n = rest.len().min(MSR_CHUNK);
        let entries: Vec<kvm_msr_entry> = rest[..n].iter().map(|&index| kvm_msr_entry { index, ..Default::default() }).collect();
        let mut msrs = Msrs::from_entries(&entries).map_err(|e| snap("MSR list", format!("{e:?}")))?;
        let got = vcpu.get_msrs(&mut msrs)?;
        saved.extend(msrs.as_slice()[..got].iter().map(|e| (e.index, e.data)));
        // The MSR at position `got` is the one KVM refused: it is dropped, and the read resumes after it.
        rest = if got < n { &rest[got + 1..] } else { &rest[n..] };
    }
    Ok(saved)
}

/// Put the saved MSRs into the vCPU: every one but the TSC deadline first, in chunks, then the deadline alone. The deadline
/// is set last because KVM reads `MSR_IA32_TSC` when the deadline is written, to decide whether a timer must be armed
/// (Firecracker's comment, v1.15.1 arch/x86_64/vcpu.rs:36-48); and a saved deadline of 0 takes the TSC's value, so a timer
/// the guest had armed is not lost to a deadline that reads as "none" (`fix_zero_tsc_deadline_msr`, :385-413).
fn restore_msrs(vcpu: &VcpuFd, saved: &[(u32, u64)]) -> Result<()> {
    let tsc = saved.iter().find(|(i, _)| *i == MSR_IA32_TSC).map(|(_, v)| *v);
    let mut first: Vec<kvm_msr_entry> = Vec::with_capacity(saved.len());
    let mut deferred: Vec<kvm_msr_entry> = Vec::new();
    for &(index, mut data) in saved {
        if index == MSR_IA32_TSC_DEADLINE {
            if omit("tsc_deadline") {
                continue;
            }
            if data == 0 {
                data = tsc.unwrap_or(0);
            }
            deferred.push(kvm_msr_entry { index, data, ..Default::default() });
        } else {
            first.push(kvm_msr_entry { index, data, ..Default::default() });
        }
    }
    for list in [first, deferred] {
        for chunk in list.chunks(MSR_CHUNK) {
            let msrs = Msrs::from_entries(chunk).map_err(|e| snap("MSR list", format!("{e:?}")))?;
            let set = vcpu.set_msrs(&msrs).map_err(|e| snap("KVM_SET_MSRS", e))?;
            if set < chunk.len() {
                return Err(Error::Snapshot(format!("KVM would not set MSR {:#x} (the {}th of {} in its chunk)", chunk[set].index, set + 1, chunk.len())));
            }
        }
    }
    Ok(())
}

save_msrs drops the one MSR a short read points at and goes on after it. restore_msrs builds two lists, everything but the deadline and then the deadline, and sets each in chunks of at most 255 (MSR_CHUNK, the kernel’s limit above), naming the MSR the first refusal stops at: KVM_SET_MSRS returns how many it set, and a count that is short is an error, not a silent drop. The omit calls are the ablation’s hooks. In the shipped binary omit is a function that returns false; with --features ablate it reads WICK_ABLATE, and the table below was made by it.

Setting a vCPU

/// Set the saved state into a vCPU that has been created and has run nothing. The order is Firecracker's (v1.15.1
/// arch/x86_64/vcpu.rs:652-718), with its reasons: CPUID first, because `KVM_SET_MP_STATE` and others depend on it;
/// `SET_REGS` before `SET_VCPU_EVENTS`, because it clears pending exceptions; `SET_LAPIC` after `SET_SREGS`, because the
/// segment registers' set restores the APIC base MSR, and before `SET_MSRS`, because the TSC deadline "only restores
/// successfully, when the LAPIC is correctly configured".
pub fn restore(vcpu: &VcpuFd, saved: &VcpuSaved, probe: &Probe) -> Result<()> {
    // mine:begin
    // A guest whose TSC runs at one rate and a host at another more than 250 parts per million apart needs the guest's
    // rate asked for again (v1.15.1 builder.rs:463-475, vcpu.rs:634-644). The same host never does.
    if let Some(khz) = saved.tsc_khz {
        let host = vcpu.get_tsc_khz()?;
        if (i64::from(host) - i64::from(khz)).abs() * 1_000_000 > i64::from(khz) * 250 {
            vcpu.set_tsc_khz(khz).map_err(|e| snap("KVM_SET_TSC_KHZ", e))?;
        }
    }
    saved.check(probe)?;
    let entries: Vec<kvm_cpuid_entry2> = saved.cpuid.iter().map(|p| p.0).collect();
    #[cfg(feature = "ablate")]
    let entries = if omit("cpuid") { probe.supported_cpuid.clone() } else { entries };
    let mut cpuid = CpuId::from_entries(&entries).map_err(|e| snap("cpuid", format!("{e:?}")))?;
    // A state file is not trusted to say the guest has no nested virtualization: the bits are cleared as at a fresh boot.
    crate::x86::regs::mask_nested_virtualization(&mut cpuid);
    vcpu.set_cpuid2(&cpuid).map_err(|e| snap("KVM_SET_CPUID2", e))?;
    if !omit("mp_state") {
        vcpu.set_mp_state(saved.mp_state.0).map_err(|e| snap("KVM_SET_MP_STATE", e))?;
    }
    vcpu.set_regs(&saved.regs.0).map_err(|e| snap("KVM_SET_REGS", e))?;
    vcpu.set_sregs(&saved.sregs.0).map_err(|e| snap("KVM_SET_SREGS", e))?;
    if !omit("xsave") {
        // `KVM_SET_XSAVE` is `unsafe` in kvm-ioctls because since Linux 5.17 it may copy more than 4096 bytes when the process has
        // enabled a dynamic component with `arch_prctl()` (kvm-ioctls 0.25.0 src/ioctls/vcpu.rs:909-921), and the buffer is 4096.
        // That is the precondition: a host whose `KVM_CAP_XSAVE2` says 4096 is one where no such component can be enabled, which
        // `Probe` checks here as `save` does, and wick never calls `arch_prctl`.
        if probe.xsave2_size > XSAVE_LEGACY_BYTES {
            return Err(Error::Snapshot(format!("extended state beyond 4096 bytes (AMX) is not supported: KVM_CAP_XSAVE2 reports {} bytes", probe.xsave2_size)));
        }
        // SAFETY: the buffer is a whole `kvm_xsave` of 4096 bytes (`Pod` takes no other length) and `xsave2_size` is 4096, so the
        // kernel reads no more than it.
        unsafe { vcpu.set_xsave(&saved.xsave.0).map_err(|e| snap("KVM_SET_XSAVE", e))? };
    }
    if !omit("xcrs") {
        vcpu.set_xcrs(&saved.xcrs.0).map_err(|e| snap("KVM_SET_XCRS", e))?;
    }
    if !omit("debug_regs") {
        vcpu.set_debug_regs(&saved.debug_regs.0).map_err(|e| snap("KVM_SET_DEBUGREGS", e))?;
    }
    // Chapter 27's exercise (c): the MSRs before the local APIC (an `ablate` build with WICK_ABLATE=msrs_first).
    if omit("msrs_first") && !omit("msrs") {
        restore_msrs(vcpu, &saved.msrs)?;
    }
    if !omit("lapic") {
        vcpu.set_lapic(&saved.lapic.0).map_err(|e| snap("KVM_SET_LAPIC", e))?;
    }
    if !omit("msrs") && !omit("msrs_first") {
        restore_msrs(vcpu, &saved.msrs)?;
    }
    if !omit("vcpu_events") {
        vcpu.set_vcpu_events(&saved.vcpu_events.0).map_err(|e| snap("KVM_SET_VCPU_EVENTS", e))?;
    }
    // `EINVAL` is "the guest is not using kvm-clock": nothing to tell (api.rst, KVM_KVMCLOCK_CTRL).
    if !omit("kvmclock_ctrl") {
        match vcpu.kvmclock_ctrl() {
            Err(e) if e.errno() != libc::EINVAL => return Err(e.into()),
            _ => {}
        }
    }
    Ok(())
    // mine:end
}

The TSC check comes first, as in Firecracker, then the pure checks of the file (saved.check: counts, duplicates, an MSR the host does not list), then the setters in the order the comment gives. set_xsave is an unsafe fn in kvm-ioctls because, since Linux 5.17, KVM_SET_XSAVE may copy more than the 4096 bytes of struct kvm_xsave when the process has enabled a dynamic component (AMX) with arch_prctl() (kvm-ioctls 0.25.0, src/ioctls/vcpu.rs:909-921). The precondition is therefore not that Pod made the buffer exact. It is that no such component is enabled in this process, which wick never does and which restore checks first: KVM_CAP_XSAVE2 reports the size the process may have (the Mechanism’s note), and a host that says more than 4096 refuses the restore. This function’s body, between the mine:begin and mine:end lines, is what labs/ch27/mine/ replaces.

The VM

pub fn save(vm: &VmFd) -> Result<VmSaved> {
    let pit = vm.get_pit2()?;
    let clock = vm.get_clock()?;
    let (mut pic_master, mut pic_slave, mut ioapic) = (chip(KVM_IRQCHIP_PIC_MASTER), chip(KVM_IRQCHIP_PIC_SLAVE), chip(KVM_IRQCHIP_IOAPIC));
    vm.get_irqchip(&mut pic_master)?;
    vm.get_irqchip(&mut pic_slave)?;
    vm.get_irqchip(&mut ioapic)?;
    Ok(VmSaved { pit: Pod(pit), clock: Pod(clock), pic_master: Pod(pic_master), pic_slave: Pod(pic_slave), ioapic: Pod(ioapic) })
}

/// Set the saved state into a VM whose irqchip and PIT `Vm::new` created. The clock's saved flags are not passed back:
/// `KVM_GET_CLOCK` fills them with `KVM_CLOCK_TSC_STABLE`, `KVM_CLOCK_REALTIME` and `KVM_CLOCK_HOST_TSC` (0xe on both of
/// this book's hosts), and a `KVM_SET_CLOCK` that carries `KVM_CLOCK_REALTIME` adds the wall-clock time since the save to the
/// guest's kvmclock (`api.rst` 1090-1113). Cleared, the guest's clock resumes from the instant of the snapshot, which is
/// what the chapter's lab shows. Firecracker clears them too unless asked (`clock_realtime`, v1.15.1
/// arch/x86_64/vm.rs:140-150).
pub fn restore(vm: &VmFd, saved: &VmSaved) -> Result<()> {
    if !omit("pit") {
        vm.set_pit2(&saved.pit.0).map_err(|e| Error::Snapshot(format!("KVM_SET_PIT2: {e}")))?;
    }
    if !omit("clock") {
        let mut clock = saved.clock.0;
        clock.flags = 0;
        vm.set_clock(&clock).map_err(|e| Error::Snapshot(format!("KVM_SET_CLOCK: {e}")))?;
    }
    if !omit("pic") {
        vm.set_irqchip(&saved.pic_master.0).map_err(|e| Error::Snapshot(format!("KVM_SET_IRQCHIP (master PIC): {e}")))?;
        vm.set_irqchip(&saved.pic_slave.0).map_err(|e| Error::Snapshot(format!("KVM_SET_IRQCHIP (slave PIC): {e}")))?;
    }
    if !omit("ioapic") {
        vm.set_irqchip(&saved.ioapic.0).map_err(|e| Error::Snapshot(format!("KVM_SET_IRQCHIP (IOAPIC): {e}")))?;
    }
    Ok(())
}

Five reads, and five sets with the clock’s flags cleared. The chips are made with chip_id set before the call, because KVM_GET_IRQCHIP is in/out: the id selects which controller it fills.

The devices

/// Read the console's registers.
pub fn save_serial(serial: &Mutex<SerialDevice>) -> SerialSaved {
    serial.lock().unwrap_or_else(PoisonError::into_inner).state().into()
}

/// A console UART restored, and its interrupt eventfd, to be registered on GSI 4 after the VM's state is back.
pub fn restore_serial(out: Box<dyn Write + Send>, saved: &SerialSaved) -> Result<(Arc<Mutex<SerialDevice>>, vmm_sys_util::eventfd::EventFd)> {
    let state = if crate::snapshot::omit("serial") { SerialState::default() } else { saved.into() };
    SerialDevice::from_state(out, &state)
}

/// Read one device's transport and queues, under their own mutexes. The cursors come from the device's copy of each queue
/// once the driver has set `DRIVER_OK`: that copy is the one the device advances.
pub fn save_slot(index: usize, slot: &Slot) -> DeviceSaved {
    slot.transport.lock().unwrap_or_else(PoisonError::into_inner).save(index as u32, slot.device_type)
}

/// Put one device's saved state into the transport of its window, and let the device know it came back.
pub fn restore_slot(slot: &Slot, saved: &DeviceSaved) -> Result<()> {
    slot.transport.lock().unwrap_or_else(PoisonError::into_inner).restore(saved)?;
    slot.dev.lock().unwrap_or_else(PoisonError::into_inner).restored();
    slot.transport.lock().unwrap_or_else(PoisonError::into_inner).reraise_interrupt()?;
    Ok(())
}

The console is read under its mutex and rebuilt with a new eventfd that load registers after the VM’s state; a device is read and set through its transport, which holds the registers, and which asks the device for its cursors while the driver is live: the transport’s own copy of a queue only knows what the driver wrote, and it is the device’s copy that advances (the Active queues in each device). restore_slot ends by telling the device it came back, which for every device but vsock does nothing, and by raising the device’s interrupt again if the transport’s saved status says one was owed.

/// Put a saved state into a fresh transport, and into its device, such that the state is one the transport's own rules could
/// have reached: the same checks a driver's writes pass (a size that is a power of two within the device's maximum, aligned
/// addresses that are not 0, three rings in guest memory and apart), the same order of status bits, and a feature set the
/// device offered. A state file is not trusted more than a guest. On `Err` the transport is half set and must be dropped
/// with the machine it belongs to.
pub fn restore(&mut self, saved: &DeviceSaved) -> Result<()> {
    let bad = |why: String| Error::Snapshot(format!("device {}: {why}", saved.slot));
    if saved.queues.len() != self.queues.len() {
        return Err(bad(format!("{} queues in the state file, {} in the device", saved.queues.len(), self.queues.len())));
    }
    if saved.status & !KNOWN_STATUS_BITS != 0 {
        return Err(bad(format!("status {:#x} has bits no driver sets", saved.status)));
    }
    if saved.driver_features & !self.device_features != 0 {
        return Err(bad(format!("driver_features {:#x} has bits the device did not offer ({:#x})", saved.driver_features, self.device_features)));
    }
    let features_ok = saved.status & VIRTIO_CONFIG_S_FEATURES_OK != 0;
    if features_ok && saved.driver_features & (1 << VIRTIO_F_VERSION_1) == 0 {
        return Err(bad("FEATURES_OK is set and VIRTIO_F_VERSION_1 is not accepted".into()));
    }
    let driver_ok = saved.status & VIRTIO_CONFIG_S_DRIVER_OK != 0;
    let needs_reset = saved.status & VIRTIO_CONFIG_S_NEEDS_RESET != 0;
    if saved.activated && !(driver_ok && features_ok && !needs_reset) {
        return Err(bad("activated, and status is not FEATURES_OK and DRIVER_OK without NEEDS_RESET".into()));
    }
    if driver_ok && !saved.activated && !needs_reset {
        return Err(bad("DRIVER_OK is set, the device is not active, and NEEDS_RESET is not set: no transport reaches that".into()));
    }
    if saved.interrupt_status & !(VIRTIO_MMIO_INT_VRING | VIRTIO_MMIO_INT_CONFIG) != 0 {
        return Err(bad(format!("interrupt_status {:#x} has bits the register does not", saved.interrupt_status)));
    }
    for (i, q) in saved.queues.iter().enumerate() {
        self.restore_queue(i, q).map_err(|why| bad(format!("queue {i}: {why}")))?;
    }
    self.device_features_sel = saved.device_features_sel;
    self.driver_features_sel = saved.driver_features_sel;
    self.driver_features = saved.driver_features;
    self.queue_sel = saved.queue_sel;
    self.status = saved.status;
    if !crate::snapshot::omit("irq_status") {
        self.irq.restore_status(saved.interrupt_status);
    }
    if features_ok {
        let accepted = self.driver_features;
        self.device().ack_features(accepted);
    }
    if saved.activated {
        self.activate().map_err(|e| bad(format!("the device would not take its queues: {e}")))?;
        self.activated = true;
    }
    Ok(())
}

/// After the interrupt controllers' state is back: raise the interrupt again if the saved `InterruptStatus` says one was owed. A device's
/// interrupt is an edge written to an eventfd that KVM injects from a work queue, so a snapshot can read the 8259 in the
/// instant between the write and the injection, and the interrupt is then in no state at all; the guest's driver would wait
/// for a completion it was never told of. A repeated edge is a spurious interrupt the driver answers `IRQ_NONE` (the same
/// reason `Serial::from_state` raises the console's again). Not sent when the status is 0.
pub fn reraise_interrupt(&self) -> Result<()> {
    if self.irq.status() != 0 && !crate::snapshot::omit("reraise") {
        self.irq.pulse()?;
    }
    Ok(())
}

/// One queue, set the way a driver's writes would set it, then checked as `QueueReady` and `activate` check it.
fn restore_queue(&mut self, i: usize, saved: &QueueSaved) -> std::result::Result<(), String> {
    let max = self.queues[i].max_size();
    if saved.addrs_set > 0b111 {
        return Err(format!("addrs_set {:#b} names an address that does not exist", saved.addrs_set));
    }
    if saved.size_set && !(saved.size != 0 && saved.size.is_power_of_two() && saved.size <= max) {
        return Err(format!("size {} is not a power of two up to the device's {max}", saved.size));
    }
    if !saved.size_set && saved.size != max {
        return Err(format!("size {} with no QueueNum written: a queue has its maximum, {max}, until the driver sets one", saved.size));
    }
    for (bit, addr, align, name) in [(1u8, saved.desc_table, 16u64, "desc_table"), (2, saved.avail_ring, 2, "avail_ring"), (4, saved.used_ring, 4, "used_ring")] {
        if saved.addrs_set & bit != 0 && addr % align != 0 {
            return Err(format!("{name} {addr:#x} is not aligned to {align}"));
        }
        if saved.addrs_set & bit == 0 && addr != 0 {
            return Err(format!("{name} {addr:#x} was never written"));
        }
        if saved.ready && addr == 0 {
            return Err(format!("{name} is at address 0, which the transport refuses at QueueReady"));
        }
    }
    if saved.ready && (!saved.size_set || saved.addrs_set != 0b111) {
        return Err("ready, and the driver did not write the size and all three addresses".into());
    }
    let q = &mut self.queues[i];
    if saved.size_set {
        q.set_size(saved.size);
    }
    let split = |a: u64| (Some(a as u32), Some((a >> 32) as u32));
    let (lo, hi) = split(saved.desc_table);
    q.set_desc_table_address(lo, hi);
    let (lo, hi) = split(saved.avail_ring);
    q.set_avail_ring_address(lo, hi);
    let (lo, hi) = split(saved.used_ring);
    q.set_used_ring_address(lo, hi);
    let (next_avail, next_used) = if crate::snapshot::omit("queue_cursors") { (0, 0) } else { (saved.next_avail, saved.next_used) };
    q.set_next_avail(next_avail);
    q.set_next_used(next_used);
    self.size_set[i] = saved.size_set;
    self.addrs_set[i] = saved.addrs_set;
    if saved.ready {
        self.ready_queue(i);
        let q = &self.queues[i];
        if !q.ready() {
            // `ready_queue` said no without saying why; the two reasons it has are asked again.
            let q = &mut self.queues[i];
            q.set_ready(true);
            let (valid, apart) = (q.is_valid(self.mem.as_ref()), !rings_overlap(q));
            q.set_ready(false);
            return Err(if !valid { "the three rings are not in guest memory".into() } else if !apart { "two of the three rings overlap".into() } else { "the transport would not make it ready".into() });
        }
        let q = &self.queues[i];
        // The cursors must agree with the rings in guest memory. The device wrote `used.idx` when it advanced `next_used`,
        // and the driver cannot have made more buffers available than the queue holds.
        let idx = |ring: u64| self.mem.read_obj::<u16>(GuestAddress(ring + 2)).map_err(|e| format!("reading a ring's idx: {e}"));
        let (avail_idx, used_idx) = (idx(q.avail_ring())?, idx(q.used_ring())?);
        if used_idx != q.next_used() && !crate::snapshot::omit("queue_cursors") {
            return Err(format!("next_used is {} and the used ring in memory says {used_idx}", q.next_used()));
        }
        if avail_idx.wrapping_sub(q.next_avail()) > q.size() && !crate::snapshot::omit("queue_cursors") {
            return Err(format!("the available ring says {avail_idx} and next_avail is {}: more than {} buffers outstanding", q.next_avail(), q.size()));
        }
        // A device cannot have used what it has not taken from the ring: `next_used` is never ahead of `next_avail`.
        if q.next_avail().wrapping_sub(q.next_used()) > q.size() && !crate::snapshot::omit("queue_cursors") {
            return Err(format!("next_used {} is ahead of next_avail {}: the device would serve buffers the driver has reclaimed", q.next_used(), q.next_avail()));
        }
    }
    Ok(())
}

restore is the checklist of what a state must satisfy before the transport takes it: the status bits, the features against what the device offered, the order of the status bits (activated implies FEATURES_OK and DRIVER_OK, and a device that is not active with DRIVER_OK set must have asked for a reset), then each queue. restore_queue sets a queue through the same setters a driver’s writes reach, so the alignment, the size and the maximum are the ones write_queue enforces; it calls ready_queue, which is the check a driver’s QueueReady goes through (three rings inside guest memory and not overlapping, none at 0) and diagnoses which rule it broke; and it reads the two idx fields from memory and compares them with the cursors, and checks that next_used is not ahead of next_avail. On the way in, activate is called as the guest’s DRIVER_OK would, with queues that carry the restored cursors. On an error the transport is half set, which is allowed because the machine it belongs to is dropped with it.

Writing the files

/// Write the two files of a snapshot of a paused machine: the guest's RAM, then the state. The memory file goes first and is
/// flushed, so the state file, which describes it, exists only once everything it describes is on disk; and each is created new
/// (`CREATE_FLAGS`), so a failure removes only what this call made. The state is read first, so a machine that cannot be
/// saved (a vCPU whose XSAVE area is larger than 4096 bytes) leaves no file.
pub fn write_snapshot(vm: &Vm, snap: &Snapshot, snapshot_path: &str, mem_file_path: &str) -> Result<()> {
    let state = serde_json::to_vec(snap).map_err(|e| Error::Snapshot(format!("serialising the state: {e}")))?;
    let mut mem = create_file(mem_file_path, "memory file")?;
    let mut made = vec![mem_file_path.to_string()];
    let result = (|| {
        vm.mem.write_all_volatile_to(GuestAddress(0), &mut mem, vm.mem_size).map_err(|e| Error::Snapshot(format!("writing the memory file: {e}")))?;
        mem.sync_data()?;
        let mut file = create_file(snapshot_path, "state file")?;
        made.push(snapshot_path.to_string());
        file.write_all(&state)?;
        file.sync_data()?;
        Ok(())
    })();
    if result.is_err() {
        // `unlink` is on the filter's list already (the API socket is removed at exit).
        for path in made {
            let _ = std::fs::remove_file(path);
        }
    }
    result
}

create is the whole of the file-making. The state is serialised before any file exists, so a machine that cannot be saved (the XSAVE refusal, for one, happens earlier, in save) makes none. The memory file is made, filled by write_all_volatile_to straight from the guest’s mapping (a write of up to the whole RAM, with no copy through a buffer), and flushed; then the state file; and if anything fails, the files this call made are removed with unlink, a call already on the list for the sockets. create_file is the one place the O_EXCL flags are named, CREATE_FLAGS, and the unit test in seccomp.rs pins the JSON’s number to it.

Loading

/// Build the machine of a snapshot in this process, in Firecracker's order (v1.15.1 builder.rs:437-518): the VM and its
/// memory, the vCPU, the vCPU's state, the VM's state, then the devices; then the filter, because the thread exists.
/// The state is not touched until the whole file has been checked.
fn load_machine(&mut self, snapshot_path: &str, mem_file_path: &str, resume_vm: bool) -> Result<()> {
    let Snapshot { config, vm: vm_saved, vcpu: vcpu_saved, serial: serial_saved, devices: devices_saved, .. } = read_state(snapshot_path)?;
    let mem_mib = config.machine.mem_size_mib;
    let (mut mem_file, mem_len) = open_input(mem_file_path, "memory file", (crate::vm::MAX_MEM_MIB as u64) << 20)?;
    check_memory(&config, mem_len)?;

    let vm = Vm::new(mem_mib)?;
    let probe = Probe::new(&vm.kvm)?;
    vcpu_saved.check(&probe)?;
    // Straight from the file into guest RAM: no buffer the size of the guest.
    vm.mem
        .read_exact_volatile_from(GuestAddress(0), &mut mem_file, vm.mem_size)
        .map_err(|e| Error::Snapshot(format!("reading the memory file: {e}")))?;

    // The devices come from the configuration, as `InstanceStart` makes them: the same files and TAP names, opened now.
    self.config.machine = config.machine.clone();
    for drive in &config.drives {
        self.put_drive(drive.clone())?;
    }
    for iface in &config.network_interfaces {
        self.put_network_interface(iface.clone(), &crate::devices::net::open_tap)?;
    }
    if let Some(v) = &config.vsock {
        self.put_vsock(v.clone())?;
    }
    self.config.boot_source = config.boot_source.clone();
    let (_cmdline, mmio) = attach_devices(self, &vm, Cmdline::new(4096).map_err(|e| Error::Snapshot(format!("cmdline: {e}")))?)?;

    let console: Box<dyn Write + Send> = self.console_writer();
    let (serial, serial_irq) = devices::restore_serial(console, &serial_saved)?;
    let mut pio = crate::bus::Bus::new();
    pio.insert(crate::serial::SERIAL_PORT, 8, serial.clone())?;

    let vcpu = vm.fd.create_vcpu(0)?;
    let mut handle = spawn_vcpu_parked(vcpu, Arc::new(pio), Arc::new(mmio), self.done.try_clone()?)?;
    let p = probe.clone();
    handle.call(move |vcpu| vcpu::restore(vcpu, &vcpu_saved, &p))??;
    vm::restore(&vm.fd, &vm_saved)?;
    // The console's interrupt line is connected now, after the interrupt controllers' state: an interrupt it owes is raised then.
    vm.fd.register_irqfd(&serial_irq, crate::serial::SERIAL_IRQ)?;
    for (slot, saved) in self.devices.iter().zip(&devices_saved) {
        devices::restore_slot(slot, saved)?;
    }

    self.seccomp.apply()?;
    self.running = Some(Running { vm, vcpu: Some(handle), serial, probe });
    self.state = VmState::Paused;
    eprintln!("wick: snapshot loaded");
    if resume_vm {
        self.resume_vm()?;
    }
    Ok(())
}

Read the order against Firecracker’s. The state file is read and parsed first, and the memory file’s length checked against mem_size_mib, so a file that is wrong in a way the file can say costs no KVM call. Then the VM, the probe, the memory (one read into the guest’s mapping, no buffer), the devices (built from config through the same put_drive, put_network_interface and put_vsock a client’s requests use, and attach_devices, so the files and the TAP are opened by name at the load, with the same checks as at a PUT), the console, the vCPU thread parked, the vCPU’s state on that thread, the VM’s state, the console’s interrupt, the devices’ state, and last the filter, because the thread exists. A resume_vm runs the same Resume a client’s request would. snapshot_load wraps all of it: on any error before the filter it forgets what the load made, the descriptors and the devices (a machine configuration the client had put before it is kept) and returns the VMM to Not started, and the API goes on answering (after the filter nothing can be undone, because no thread can be made to build another machine, so a resume that fails leaves the machine loaded, Running if the resume was sent and is unanswered and Paused if it was not, and the client is told); tests/snapshot_roundtrip.rs’s load_refuses_garbage loads fifty-six state or memory files that are wrong in fifty-six ways, one after the other, into one process, and each answers 400 with its reason while GET / still says Not started; the file after them, the good one, loads.

The state file

A real one, from the lab’s first process (jq of out/snap/state.json on talos, 2026-10-03):

$ jq -c '{magic, version, wick_version}' out/snap/state.json
{"magic":"wick-snapshot","version":1,"wick_version":"0.1.0"}
$ jq -c keys out/snap/state.json
["config","devices","magic","serial","vcpu","version","vm","wick_version"]
$ jq -c '.vcpu | keys' out/snap/state.json
["cpuid","debug_regs","lapic","mp_state","msrs","regs","sregs","tsc_khz","vcpu_events","xcrs","xsave"]
$ jq -c '.vcpu.msrs[0:3], (.vcpu.msrs | length), (.vcpu.cpuid | length), .vcpu.tsc_khz' out/snap/state.json
[[372,0],[373,0],[374,0]]
78
55
2496000
$ jq -c '.config.drives, .devices[0].queues[0], (.devices[0] | del(.queues))' out/snap/state.json
[{"drive_id":"vda","path_on_host":"out/disk.img","is_root_device":false,"is_read_only":false}]
{"size":128,"size_set":true,"addrs_set":7,"ready":true,"desc_table":9904128,"avail_ring":9906176,"used_ring":9908224,"next_avail":2,"next_used":2}
{"slot":0,"device_type":2,"status":15,"driver_features":4294967808,"device_features_sel":0,"driver_features_sel":0,"interrupt_status":0,"queue_sel":0,"activated":true}

keys sorts what it lists; the file itself is in the order of the struct’s fields, magic first, the order the section above gives. The three MSRs shown are 0x174, 0x175 and 0x176, SYSENTER_CS, SYSENTER_ESP and SYSENTER_EIP, which a guest that has not used sysenter leaves at 0. The block device’s queue says what chapter 22 said a queue is: a size, three addresses, two cursors, both 2: two requests have been made available and both used. status 15 is ACKNOWLEDGE | DRIVER | DRIVER_OK | FEATURES_OK, and driver_features 4294967808 is VIRTIO_F_VERSION_1 (bit 32) and VIRTIO_BLK_F_FLUSH (bit 9).

Exercises

Each answer is a run on talos (Intel, 2026-10-02 for (a), (b) and (c), and 2026-10-03 for (d), (e) and (f)), and on straylight (AMD) where the two hosts differ or where the answer needs a second machine, in a scratch copy of wick/ and of labs/ch27/ with the edit the exercise names (the ablate feature builds the edits that are switches), on the lab’s own kernel and initramfs, bounded by timeout; the output of each run is kept outside the repository, one directory for each. The runs of (a), (b) and (c) still hold on the shipped wick: (a) exercises complete_exit, whose code is the same in the shipped wick, and (b) and (c) read rip in fp’s loop, whose text is the guest’s and not wick’s, and the ablation table of 2026-10-03 reproduces their lapic and msrs_first hangs ten of ten on both hosts; (d) is the table’s xsave row. Where an answer is a sentence from a manual and not a run, it says so.

(a) Leave out the completion of the pending exit (WICK_ABLATE=complete_exit in an ablate build: the pause returns as soon as the stop flag is seen). Take a snapshot of a guest that prints a counter in a loop, restore it in a new process, and join the two consoles. What repeats, and why does the lab’s own guest not show it?

Answer

An ablate build with WICK_ABLATE=complete_exit returns from the pause as soon as the stop flag is seen. The guest is wick/tests/init-count, which prints count N in an endless loop, so a pause is nearly always on a port write. Six snapshots of each kind, the two consoles joined, labs/ch27/measure/pending-exit.sh, talos:

with the completion, six rounds: the two consoles are one run of consecutive lines every time
without it, round 3: the first console ends   ...count 51
count 5
                     the second console begins 52
count 53...        (joined: count 552)
without it, round 5: the first console ends   ...count 59
coun
                     the second console begins nt 60
count 61...      (joined: counnt 60)

In round 3 the first process had printed the 5 of count 52 and the second printed it again: the saved rip was on the out that wrote it, the instruction had executed once, and the restored guest executed it again. In round 5 it is an n. In a third round the second process printed nothing at all, and the guest was stuck: three of the six rounds were wrong, two by a repeated byte and one by silence. The lab’s own guest does not show it because it is asleep when the snapshot is taken: a vCPU running fp or halted in the idle loop has no port write pending, and the pause lands between instructions. A pause is correct on every guest or it is not correct.

(b) Leave out the LAPIC (WICK_ABLATE=lapic) and run the lab. The guest never prints tick 3. Where is it waiting? Pause the restored process, snapshot it again, and read the answer out of the second state file (labs/ch27/measure/where-it-waits.sh does the two snapshots, and rip.py reads rip out of the regs string: kvm_regs is eighteen little-endian 64-bit words, rax to r15, then rip and rflags).

Answer

The guest is not waiting. A second snapshot of the hung process (labs/ch27/measure/where-it-waits.sh lapic, talos) reads:

mp_state RUNNABLE  rip 0x403110  rflags 0x246  rsp 0x7ffd6b5505f0  tsc_deadline 0x0

0x403110 in the lab’s fp is mov stop(%rip),%edx, the first instruction of its spin loop (objdump -d out/bin/fp). The restored guest is running fp, which never yields, and with the LAPIC’s state missing its timer is off: no timer interrupt is delivered, nothing preempts fp, and init, whose sleep 1 would end on one, never runs again. The deadline MSR reads 0 in the second state file because the LAPIC that holds the mode it needs is the reset’s. A guest that had been in hlt would show mp_state HALTED and wait in the same way, and a guest idling in a loop of its own would hide it entirely.

(c) Restore the MSRs before the LAPIC (WICK_ABLATE=msrs_first). Say what happens on each host, and which of the two comments of Firecracker’s the result agrees with.

Answer

The same hang on both hosts, ten of ten (the table). KVM_SET_MSRS does not fail: it returns the count it set, the deadline write is accepted, and the second snapshot of the hung process (where-it-waits.sh msrs_first, talos) reads rip 0x403110, fp’s loop again, and tsc_deadline 0x0. With the LAPIC not yet configured, KVM ignores a write to the deadline MSR, and the LAPIC that is set afterwards has its timer in deadline mode with nothing in the deadline. That is the second Firecracker comment: “SET_LAPIC must come before SET_MSRS, because the TSC deadline MSR only restores successfully, when the LAPIC is correctly configured.” The first, about SET_SREGS, restores the APIC base MSR that the LAPIC needs; this chapter did not test it. The failure is silent at the call and total in the guest, which is why a_restored_vcpu_and_vm_read_back_as_they_were_saved arms a deadline before it saves, and fails on this order.

(d) Leave out XSAVE (WICK_ABLATE=xsave). What does the lab print, on each host, and what would it print if fp were not running when the snapshot was taken?

Answer

What the table’s xsave row says, ten of ten on each host: the capture, with fp: CORRUPT xmm8 where fp: registers intact was. xmm8 is the first register fp compares, and it reports the first that differs; the restored vCPU’s XSAVE area is the reset’s, which holds none of the patterns. If fp were not on the vCPU when the snapshot was taken, the registers would already be in guest memory (the kernel saves a task’s FPU state when it switches it out), the restore would find them there, and the line would say intact with XSAVE left out. The pause lands in the sleep after tick 2, where fp is the only runnable process, so it is nearly always on the vCPU, and the table is the check that the test does its job: ten of ten. The lab’s guest could not otherwise tell: no clock, no ring and no tick depends on these registers.

(e) Take two snapshots from one pause, to two pairs of files, and cmp them. Which files are identical, and which fields of the state file differ, and why?

Answer

(labs/ch27/measure/snapshot-twice.sh, talos, 2026-10-03.) The two memory files are identical: the guest was paused and nothing wrote to its RAM between the calls. The two state files are the same size (22,630 bytes) and differ. By field of the state: every piece of the vCPU is identical (mp_state, regs, sregs, xsave, xcrs, debug_regs, lapic, vcpu_events, cpuid, tsc_khz), and so are pit, the three interrupt controllers, serial, devices and config. What differs is vm.clock and three MSRs, each a counter that runs with time even though the guest does not: MSR_IA32_TSC (0x10: 3564378107 then 3706977104), and two of Hyper-V’s paravirtual clocks that KVM exposes, 0x40000020 (the time reference count: 14344232 then 14915554) and 0x40000010 (the virtual processor’s run time: 14225648 then 14226893). The guest is stopped, the hardware counters it reads are not, and a snapshot is the state at an instant as read, not an instant. These are the counters the round-trip test names as legitimately different after a restore.

(f) Take the state file and memory file made on talos to straylight and load them there. Which call refuses them, and what does Firecracker’s documentation say about it? Then the other way round.

Answer

(labs/ch27/measure/other-host.sh, 2026-10-03.) The load is refused by wick’s own check, before a call of KVM is made, with a 400 and a message, and GET / still says Not started. On straylight, with the file from talos:

ctl: PUT /snapshot/load 400
{"fault_message":"snapshot: vcpu.msrs has MSR 0x3a, which this host's KVM does not list: the state is from another kind of machine"}

and on talos, with the file from straylight: MSR 0xc0010117. 0x3a is IA32_FEATURE_CONTROL, which Intel has and the AMD host’s KVM does not list. With the check left out (an ablate build, WICK_ABLATE=host_msr_list) the call of KVM that refuses the Intel file on the AMD host is KVM_SET_MSRS, which stops at the same register (KVM would not set MSR 0x3a (the 11th of 77 in its chunk)); and the AMD file on the Intel host gets as far as KVM_SET_XSAVE, which returns EINVAL (the reply is snapshot: KVM_SET_XSAVE: Invalid argument (os error 22)) because the saved area carries state components the Intel CPU does not have. The two refusals are what the Firecracker documentation says, in a different place: “Snapshots must be resumed on an software and hardware configuration which is identical to what they were generated on”, and the table it follows names the host kernel versions it has tried, not other processors.

Lab

make lab CH=27
make lab CH=27 IMPL=mine
tools/remote-lab.sh lab CH=27
labs/ch27/ablate.sh 10
make -C wick test clippy

labs/ch27/Makefile includes the shared labs/lab.wick.mk and adds one helper, the guest’s fp, built native and static into this lab’s own out/bin and staged into the initramfs overlay on every run (built binaries never travel between hosts). It is built with -ffixed-xmm8 to -ffixed-xmm15, so that the compiler never uses the eight registers fp loads: the only instructions that touch them are fp’s own.

int main(void) {
    for (int r = 0; r < 8; r++)
        for (int b = 0; b < 16; b++)
            pattern[r][b] = (uint8_t)(0xa5 ^ (r * 16 + b + 1));

    struct sigaction sa;
    memset(&sa, 0, sizeof sa);
    sa.sa_handler = on_term;
    sigemptyset(&sa.sa_mask);
    if (sigaction(SIGTERM, &sa, NULL) != 0) {
        perror("fp: sigaction");
        return 1;
    }

    __asm__ volatile(
        "movdqu   0(%0), %%xmm8\n\t"
        "movdqu  16(%0), %%xmm9\n\t"
        "movdqu  32(%0), %%xmm10\n\t"
        "movdqu  48(%0), %%xmm11\n\t"
        "movdqu  64(%0), %%xmm12\n\t"
        "movdqu  80(%0), %%xmm13\n\t"
        "movdqu  96(%0), %%xmm14\n\t"
        "movdqu 112(%0), %%xmm15\n\t"
        :
        : "r"(pattern)
        : "memory", "xmm8", "xmm9", "xmm10", "xmm11", "xmm12", "xmm13", "xmm14", "xmm15");

    // No call, no SSE: a read of `stop` and a branch.
    while (!stop) {
        __asm__ volatile("" ::: "memory");
    }

    __asm__ volatile(
        "movdqu %%xmm8,    0(%0)\n\t"
        "movdqu %%xmm9,   16(%0)\n\t"
        "movdqu %%xmm10,  32(%0)\n\t"
        "movdqu %%xmm11,  48(%0)\n\t"
        "movdqu %%xmm12,  64(%0)\n\t"
        "movdqu %%xmm13,  80(%0)\n\t"
        "movdqu %%xmm14,  96(%0)\n\t"
        "movdqu %%xmm15, 112(%0)\n\t"
        :
        : "r"(readback)
        : "memory");

    for (int r = 0; r < 8; r++) {
        if (memcmp(pattern[r], readback[r], 16) != 0) {
            printf("fp: CORRUPT xmm%d\n", r + 8);
            return 1;
        }
    }
    printf("fp: registers intact\n");
    return 0;
}

The loop calls nothing and touches no SSE register, so for as long as fp is the process the vCPU is running, the eight patterns are in the registers and nowhere else: not in guest memory, which holds them only in the signal frame the kernel writes when the handler runs. They are in the XSAVE area the snapshot carries, or they are not in the snapshot. The guest’s init:

mount -t proc proc /proc
mount -t devtmpfs devtmpfs /dev
dmesg -n 1
echo "=== lab begin"
# Sector 0 of the drive is read once before the first tick and once after the last: a virtqueue is in use on both sides of
# the snapshot, and the request after it needs the queue's cursors to be where they were.
blk() { set -- $(hexdump -n 16 -e '16/1 "%02x "' /dev/vda); echo "blk: sector 0: $*"; }
blk
# fp holds eight SSE registers and spins; the registers live in the vCPU's XSAVE area while it runs.
/bin/fp &
fp=$!
i=1
while [ $i -le 6 ]; do
  echo "tick $i"
  if [ $i -eq 5 ]; then
    kill -TERM $fp
    wait $fp
  fi
  i=$((i+1))
  sleep 1
done
blk
echo "=== lab end"
exec >/dev/null 2>&1 </dev/null
reboot -f

blk reads sector 0 of the drive with hexdump, once before tick 1 and once after tick 6: a virtqueue is used on both sides of the snapshot, and the second read is a request the restored device has to serve from the cursors it was given. fp is started in the background and told to stop after tick 5, and init waits for it, which is when its line is printed. Every sleep 1 ends on a LAPIC timer interrupt, so every snapshot taken in the sleep after tick 2 carries an armed timer.

run.sh is two wick processes. The first boots the guest, waits (with waitline.sh, which has a real deadline) for the line tick 2, pauses it, creates the snapshot, and is killed with kill; its exit status is not captured. The second is a new process on a new socket: one PUT /snapshot/load with resume_vm, then the wait for its exit. out/run.txt is the first process’s ctl: lines; its guest lines from === lab begin through tick 2; a separator; the second process’s ctl: line and its console from its first line through === lab end; the wick: lines of both logs; and the second process’s status. The pause lands in the sleep after tick 2, so tick 3 is the second process’s first line whichever side of the sleep’s timer the snapshot falls on: a run that shows tick 2 there, or a missing tick, is a defect in the pause or in the completion of the pending exit, and not a capture to adjust. The capture:

ctl: PUT /machine-config 204
ctl: PUT /boot-source 204
ctl: PUT /drives/vda 204
ctl: PUT /actions 204
ctl: PATCH /vm 204
ctl: PUT /snapshot/create 204
=== lab begin
blk: sector 0: 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f
tick 1
tick 2
--- restored in a new process ---
ctl: PUT /snapshot/load 204
tick 3
tick 4
tick 5
fp: registers intact
tick 6
blk: sector 0: 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f
=== lab end
wick: KVM API version 12
wick: memory 128 MiB
wick: boot protocol 64-bit entry
wick: InstanceStart
wick: virtio-mmio slot 0 type 2
wick: Paused
wick: snapshot created
wick: snapshot loaded
wick: Resumed
wick: virtio-mmio slot 0 type 2
wick: vcpu 0 exit Shutdown
wick: exit 0
wick rc=0

Ten runs on each host are byte-identical to it and to each other (talos, straylight, 2026-10-03, make lab CH=27 ten times, the md5sum of out/run.txt each time is 80d0343d2b27, the first twelve digits of 80d0343d2b2787153414dfe659780106, which is also the md5sum of capture.txt), and the capture made on talos is the one straylight matches.

The files and the calls, from labs/ch27/measure/times.sh (five runs on each host, 2026-10-03, the date +%s%N difference around one wick ctl call, so each includes the start of the ctl process, and the load also includes the second wick’s own start, up to the socket that ctl --wait-ms waits for): on talos, PATCH /vm 1 to 2 ms, PUT /snapshot/create 33 to 40 ms (37, 37, 40, 33, 36), PUT /snapshot/load with resume_vm 25 to 36 ms (25, 36, 29, 26, 27); on straylight, 1 to 2 ms, 118 to 799 ms (123, 153, 126, 118, 799) and 47 to 55 ms (55, 50, 50, 51, 47). The memory file is 134,217,728 bytes on both, and the state file 22,630 bytes on talos and 24,048 on straylight. A create is the write of 128 MiB and two fdatasync calls; a load is the read of the same. Both are the cost of the file system, and chapter 28 compares them with a boot.

make lab CH=27 IMPL=mine replaces the body of restore in snapshot/vcpu.rs with a line that prints MINE: vcpu restore stub and returns Ok(()). Memory is restored and the vCPU is not: a vCPU that KVM_CREATE_VCPU made and nothing set is in its reset state, at the reset vector of a real-mode machine whose memory is a guest’s, and the guest does not run at all:

--- restored in a new process ---
ctl: PUT /snapshot/load 204
wick: KVM API version 12
wick: memory 128 MiB
wick: boot protocol 64-bit entry
wick: InstanceStart
wick: virtio-mmio slot 0 type 2
wick: Paused
wick: snapshot created
MINE: vcpu restore stub
wick: snapshot loaded
wick: Resumed
wick: virtio-mmio slot 0 type 2
wick: FAIL vcpu 0 exit InternalError
wick: exit 1
wick rc=1

(make lab CH=27 IMPL=mine on talos, 2026-10-03: nothing after the ctl: line but the log, the MINE: line is in it, and the second process ends with KVM’s InternalError, a wick: FAIL line and status 1.)

labs/ch27/ablate.sh is the Mechanism’s table. It builds wick with the ablate feature and runs the lab ten times for each piece of state, with WICK_ABLATE naming the piece the restore leaves out, sorting each run by what the guest did after it. A run is the same as the capture, or one line: how many tick lines came after the restore, which fp line (if any), how many blk lines held the right bytes, how the second process ended (wick: vcpu 0 exit Shutdown, a wick: FAIL line, or the 25-second bound, rc=124). It takes about an hour on each host. The scripts in labs/ch27/measure/ made the rest of this chapter’s numbers: times.sh (the table above), clock.sh (the boot log’s clock lines), msr-groups.py (the MSR and CPUID counts of a state file, by group), ioctl-count.sh (the ioctl counts before the filter), mutation.sh (which test goes red when the restore leaves one piece out, the table’s last paragraph), pending-exit.sh, where-it-waits.sh, snapshot-twice.sh and other-host.sh (exercises (a), (b) and (c), (e) and (f)); none is part of make lab.

Further reading

  • Documentation/virt/kvm/api.rst at the pinned tag: sections 4.3, 4.11, 4.13, 4.18, 4.26, 4.29 to 4.31, 4.33, 4.38, 4.42 to 4.44, 4.56 to 4.58, 4.70, 4.72, 4.114, 4.115 and 4.134 for the ioctls this chapter saves, and the nested state it does not, and the note on KVM_RUN (lines 6741 to 6755) that a pause is built on.
  • docs/snapshotting/snapshot-support.md at Firecracker v1.15.1: what is saved, the MAP_PRIVATE memory file, diff snapshots, the vsock reset, the wall clock after a restore, and where a snapshot can be resumed.
  • Firecracker v1.15.1’s source, for the order and its reasons: src/vmm/src/arch/x86_64/vcpu.rs (save_state, restore_state, the deferred MSRs), vm.rs beside it, src/vmm/src/builder.rs (build_microvm_from_snapshot) and src/vmm/src/vstate/vcpu.rs (the vCPU thread’s states).
  • Intel 64 and IA-32 Architectures Software Developer’s Manual (Intel; the combined volumes at version 093, the one the page offered on 2026-10-03), Volume 3: the chapters on the local APIC (the timer’s modes, the TSC-deadline mode) and on system programming for processor extended states (XSAVE and XCR0); and AMD64 Architecture Programmer’s Manual, Volume 2: System Programming (AMD publication 24593, revision 3.45, 2026; the title is the one the AMD portal’s index gives the page), the chapters on the local APIC and on extended state, for the same two. The AMD page is a viewer whose title is drawn by script; the document behind it is publication 24593.
  • Virtio 1.2 (OASIS, July 2022), section 5.10.6.7, the transport-reset event.
  • Chapter 22, whose two ring cursors are a queue’s whole state; chapter 24, whose kick this chapter parks the thread after; chapter 25, whose devices are saved here; chapter 26, whose filter forbids a new thread and has one openat for the files this chapter makes; and chapter 28, which measures what a restore costs.

results matching ""

    No results matching ""