mini-firecracker: A microVM Monitor Small Enough to Read

Sandboxing options sit on a rough spectrum. At one end is the container: a fenced-off process that is still a process. At the other is the virtual machine: a second computer with its own kernel and interrupts. In between are two projects that are neither: gVisor, a kernel in userspace that intercepts the guest’s syscalls, and Firecracker, a virtual machine with everything a VM normally provides stripped out. Both answer the same complaint (containers are weak, VMs are heavy) from opposite directions.

I spent a few weeks on the gVisor end: mini-sentry, the signals post and the tour of gVisor. This post is about the other end, where I built a small version of Firecracker.

mini-firecracker is about 5,300 lines of Go with one external dependency (golang.org/x/sys), for Linux, KVM and x86_64 only. It boots a real Linux kernel, gives it a virtio-blk disk backed by a file and a virtio-net interface backed by a tap device, provides a serial console for the guest’s shell, and can dump a running VM to disk and restore it into a new process in under 300 ms. That last feature is what made AWS Lambda economical.

The main demo, from the README, snapshots a VM partway through boot and resumes it elsewhere:

# Take a snapshot 800 ms into the boot.
$ ./mini-fc run \
      --kernel testdata/vmlinux-5.10.245 --mem 512 \
      --drive path=ubuntu-24.04.squashfs,ro \
      --net   tap=minifc0 \
      --cmdline "console=ttyS0 reboot=k panic=1 root=/dev/vda rootfstype=squashfs ro init=/bin/sh" \
      --snapshot-after 800ms --snapshot-to /tmp/snap
[mini-fc] snapshot written to /tmp/snap

# Restore and interact.
$ (sleep 1.5; printf '
    ip link set eth0 up
    ip addr add 172.16.0.2/30 dev eth0
    ping -c 3 172.16.0.1
    exit
  ') | ./mini-fc restore --from /tmp/snap
[mini-fc] restored from /tmp/snap in 262 ms
# ping -c 3 172.16.0.1
PING 172.16.0.1 (172.16.0.1) 56(84) bytes of data.
64 bytes from 172.16.0.1: icmp_seq=1 ttl=64 time=0.264 ms
3 packets transmitted, 3 received, 0% packet loss

That’s a whole VM lifecycle (boot, shell, network, pause, serialize to disk, resume in another process, continue) using about five kilobytes of structured state plus a 512 MiB memory file. Having now built a small version at each end of the spectrum, the distance between them turned out shorter than I expected.

The VMM is mostly a switch statement

Each VM is one Go process. It owns:

  • a file descriptor for /dev/kvm and a VM-level descriptor created from it;
  • an in-kernel interrupt chip and a programmable interval timer;
  • one anonymous mmap used as guest RAM, registered as KVM memory slot zero;
  • one vCPU, pinned to a goroutine with runtime.LockOSThread because KVM is a per-thread interface;
  • a minimal 16550A UART stub at the traditional port 0x3f8, which the kernel talks to as soon as it starts;
  • virtio-MMIO device slots at 4 KB intervals starting at 0xd0000000.

The hot path is a single-threaded loop around KVM_RUN with a switch on why the guest stopped:

func (v *VMM) Run() error {
    runtime.LockOSThread()
    for {
        if err := v.vcpu.Run(); err != nil { return err }
        switch v.vcpu.ExitReason() {
        case kvm.ExitIO:          v.handleIO()
        case kvm.ExitMMIO:        v.handleMMIO()
        case kvm.ExitHLT:         return nil
        case kvm.ExitShutdown:    return errShutdown
        case kvm.ExitSystemEvent: ...
        ...
        }
    }
}

KVM_EXIT_IO goes to the serial stub or to a small check for writes to the reboot port. KVM_EXIT_MMIO goes to whichever virtio transport owns the address the guest touched. Everything else returns cleanly or becomes an error. Asynchronous work runs in other goroutines (one reads frames from the tap into the guest’s RX queue, another pauses the VM at a set time so it can be snapshotted) and signals the guest by pulsing the in-kernel interrupt chip with KVM_IRQ_LINE.

I expected the VMM to be big. It’s a switch statement plus a few helpers, mostly in one file.

Booting a kernel with PVH

Booting a real Linux kernel without a BIOS turned out to be simpler than I expected.

Firecracker, and mini-firecracker after it, uses PVH, a fast-boot protocol from Xen that lets a hypervisor skip firmware entirely and start the kernel at a 32-bit protected-mode entry point, with one pointer in EBX. The kernel’s ELF image has an XEN_ELFNOTE_PHYS32_ENTRY note naming that entry address. The boot steps:

  1. Load the program segments into guest memory at their declared p_paddrs.
  2. Write an hvm_start_info struct at a known location, with the cmdline and a memory map.
  3. Set up flat 32-bit segments with a stub GDT.
  4. Put the start-info pointer in EBX and call KVM_RUN.

The kernel handles everything after that itself: long mode, page tables, interrupt setup. The package that does this is about 600 lines including the ELF parser and the start-info builder. Seeing the first kernel banner come out of my stub serial port felt unearned. None of my code teaches the kernel anything; it just sets up the starting state.

virtio: descriptors, two rings and a doorbell

Once the guest is booted and printing to serial, it needs a disk and a network. That’s what virtio is for.

virtio is a device-emulation contract between hypervisor and guest built on three shared-memory areas per queue: a descriptor table, an available ring and a used ring. The guest puts buffer descriptors in the table and their indices in the available ring. The device takes them, does the work, writes results and puts completed descriptors in the used ring. The guest notifies the device by writing the queue index to a doorbell register; the device notifies the guest by raising an interrupt. That’s the whole mechanism: no device-specific negotiation beyond feature bits, no framing beyond each descriptor’s len, and no locking beyond what the queue indices already imply.

mini-firecracker implements the modern virtio-MMIO transport (version 2), the split virtqueue, and two devices on top:

  • virtio-blk, backed by a host file. The guest sees /dev/vda; the host sees whatever squashfs or raw image you gave it. Translating between them is a few dozen lines of descriptor parsing plus pread/pwrite. mini-fc appends a cmdline fragment per --drive, like virtio_mmio.device=4K@0xd0000000:5, which tells the kernel where the device is. With root=/dev/vda and init=/bin/sh, the guest mounts its root and drops you at a shell on the same serial port.
  • virtio-net, which uses the same transport and ring code as virtio-blk. The differences are that it has two queues (receive and transmit) and is backed by a Linux tap device instead of a file. Transmit is synchronous: when the guest kicks the TX queue, mini-fc walks the buffer chain and writes the Ethernet frames to the tap fd. Receive is asynchronous because the host decides when frames arrive: a goroutine blocks on the tap fd, and when a frame comes in it takes a buffer from the guest’s RX queue, prepends the 12-byte virtio_net_hdr, copies the frame in and pulses the IRQ. With a tap created on the host beforehand, the guest gets an eth0 that answers pings with sub-millisecond latency in both directions.

Snapshot and restore

Snapshot/restore is the Firecracker feature that makes Lambda’s economics work. A fleet of pre-booted interpreters, set up with the customer’s exact image, can be thawed into running VMs faster than requests arrive. Restoring in tens of milliseconds makes cold starts mostly a non-issue.

A mini-firecracker snapshot is a directory:

  • manifest.json: kernel path, cmdline, memory size, drive and network bindings; the configuration needed to rebuild the VMM.
  • state.json: vCPU registers, VM state and each virtio device’s internal bookkeeping, with larger opaque blobs base64-encoded so the JSON stays readable.
  • memory.bin: the raw guest RAM.

Restore reverses each step. It mmaps a fresh memory region, copies the RAM in, replays the KVM_SET_* ioctls in the dependency order the kernel requires (clock, IRQ chips, PIT, CPUID, SREGS, REGS, XSAVE, XCRS, FPU, LAPIC, MP state, events, MSRs), and calls KVM_RUN again. The snapshot code, including device serialization, is under 800 lines.

Restore takes 65–77 ms for a 128 MiB boot-only snapshot and 260–290 ms for the 512 MiB shell-plus-network case. The larger number is mostly the memory.bin copy, which mmap(MAP_PRIVATE, fd) on the snapshot file would avoid. I haven’t written that optimization yet.

The rest of this post is the three bugs that taught me the most.

Bug 1: the 6.1 kernel had cmdline device registration compiled out

The cmdline fragment virtio_mmio.device=<size>@<base>:<irq> is the documented way for Linux to learn about an MMIO device when there’s no Device Tree or ACPI. mini-firecracker generates these automatically, and on Firecracker’s CI 5.10 kernel they work as documented.

On Firecracker’s CI 6.1 kernel they didn’t work at all. I spent a long time looking in guest userspace, the virtio dispatch code and the cmdline I was appending, and finally in the kernel binary itself:

$ strings testdata/vmlinux-6.1.155 | grep -iE "Registering device virtio-mmio|virtio_mmio_cmdline"
$

Nothing. The cmdline-registration code was configured out at build time. Firecracker’s CI kernel assumes devices are discovered through generated ACPI tables on x86, so it leaves those symbols out. mini-firecracker doesn’t generate ACPI tables, so it pins the 5.10 kernel until I write a small ACPI-table emitter.

The lesson: “documented Linux interface” and “compiled into every kernel” are different things. Kernel builds pick from a menu of options, and your hypervisor has to support the same options the guest kernel was built with.

Bug 2: the serial console ate userspace output

Getting the kernel to print through the serial port was the easy part. When the shell took over, I got an asymmetric failure: typing worked and each character echoed, but ls / returned to the prompt and printed nothing. The kernel had logged “Run /bin/sh as init process”, and after that all userspace output disappeared.

The asymmetry was the clue. Kernel printk writes to the UART using the polled path: direct outb instructions to the transmit register, each waiting for the previous one to drain. Userspace write() calls go through the tty layer, which uses the interrupt-driven path: write one byte to the transmit holding register, enable the transmitter-ready bit in the interrupt-enable register, wait for the interrupt saying the byte is out, then send the next byte. If that interrupt never comes, the tty driver waits forever, the second byte never goes out, and the file descriptor still looks fine.

My first UART stub had no interrupt-identification register and no way to raise IRQ 4 when the transmit holding register emptied. About forty lines of extra state fixed it: track the interrupt-enable bits, fire IRQ 4 when transmit is enabled and on each write to the holding register, and model the interrupt-identification register with its priority scheme and clear-on-read behavior. After that, all tty output from guest userspace showed up.

A second bug turned up in the same session. Writes to port 0x3f8 while the line-control register’s DLAB bit was set were going to my terminal, when they should have set the baud-rate divisor latches. As a result, every shell session started with a stray \x0c control character. One check on the DLAB bit fixed it.

The lesson: the kernel being happy with a device doesn’t mean the device is correct. The kernel uses polled paths for its own output and interrupt-driven paths for everyone else’s. A stub that only implements the polled path supports the kernel and makes guest userspace look dead.

Bug 3: restore without MSRs

The first snapshot-and-restore round trip worked, which should have made me suspicious. The guest resumed in 77 ms, printed five lines of correct output, and then:

[mini-fc] restored from /tmp/snap1 in 77.258217ms
[    0.472834] i8042: Can't read CTR while initializing i8042
[    0.480069] Segment Routing with IPv6
[    0.482567] bpfilter: Loaded bpfilter_umh pid 148
[    0.483268] traps: PANIC: double fault, error_code: 0x0
[    0.483287] RIP: 0000:0x0

RIP at zero points straight at the problem. On x86-64, the SYSCALL instruction gets the kernel’s syscall entry point from the model-specific register MSR_LSTAR (0xC0000082). If MSR_LSTAR is zero when SYSCALL runs, every syscall jumps to address zero and the CPU double-faults soon after. The bpfilter module had forked its userspace helper, the helper made its first syscall, and the CPU jumped to the address in the MSR, which was zero.

I’d saved every general-purpose register, every segment, the interrupt chips’ state and all of memory, but none of the model-specific registers. The fix is KVM_GET_MSR_INDEX_LIST, which returns the list of MSRs that can safely round-trip, plus KVM_GET_MSRS and KVM_SET_MSRS to read and write them in bulk. About eighty lines. After that, every snapshot point I tested round-tripped cleanly.

A rule of thumb I took from this: if a restored VM breaks at syscall entry, you forgot the MSRs. If it breaks in floating-point code, you forgot the XSAVE area. If its wall-clock time jumps backwards, you forgot the kvmclock MSRs. Every half-restored machine I’ve watched fail so far traced back to missing state, usually MSRs.

Numbers

Restore times on the three workloads I test with:

WorkloadMemRestore
Kernel boot only, no devices128 MiB65–77 ms
virtio-blk plus interactive shell512 MiB285 ms
virtio-blk plus virtio-net plus ping512 MiB262 ms

Line counts by package:

ComponentLoC
pkg/kvm — ioctl wrappers, state save/restore~1,100
pkg/boot — ELF, PVH, initial vCPU registers~600
pkg/virtio — transport, virtqueue, block, net~700
pkg/vmm — KVM_RUN loop, serial, snapshot glue~1,100
pkg/snapshot — on-disk format~250
pkg/tap — /dev/net/tun wrapper~100
Other — CLI, host check, docs, tests~1,400
Total~5,300

One external dependency (golang.org/x/sys) and a statically linked binary of about 4 MB.

What I learned

  1. The core of a microVM monitor is thin. A working VMM is KVM_RUN inside a switch on the exit reason. virtio is a 16-byte descriptor format, two queue indices in shared memory and a doorbell. A snapshot is about sixteen KVM_GET_* ioctls, an mmap, and a list of MSRs you remembered to include. I expected a lot of arcane knowledge and found a short list of contracts, each easy to honor once you know it exists.
  2. What makes Firecracker production-grade is everything around the microVM. That means the jailer that wraps the VMM in a seccomp profile, a chroot and a cgroup, and pins down exactly which syscalls the VMM itself may make. It means the REST API the orchestrator drives, and the CPU-template system that pins guest-visible CPUID leaves so a snapshot taken on one CPU generation restores on another without the guest noticing. And it means I/O and network rate limiters, metrics, and fixes for every CVE that has come out of the KVM stack. mini-firecracker stops once the concept works, which is where the easy part ends.
  3. Building a small version makes the big one readable. Firecracker’s Rust is clean and worth reading on its own, but after building a small version I can open firecracker/src/vmm/src/persist.rs and recognize, in the order of its calls, the double fault I hit at midnight and its MSR fix. The small version doesn’t replace the big one; it helps you read it.

What’s missing

For anyone tempted to extend this or mistake it for a production tool, here’s what it doesn’t do, roughly in order of how much it will hurt:

  • Snapshotting an idle guest doesn’t work. The pause flag is only checked at the next KVM_RUN boundary, and a guest sitting in HLT stays in the kernel until an interrupt wakes it. The standard fix is KVM_SET_SIGNAL_MASK plus a tgkill to the vCPU’s OS thread.
  • Restore copies memory from disk into a fresh mmap. The Lambda-grade approach is mmap(MAP_PRIVATE, fd) on the snapshot file: the first guest write to a page copies it, unread pages stay on disk, and a 512 MiB restore drops from 260–290 ms to low single-digit milliseconds.
  • No ACPI table emitter, so the Firecracker CI 6.1 kernel doesn’t work. The 5.10 kernel is pinned in the testdata.
  • No jailer, REST API, PCI, GPU or live migration. Keeping it small enough to read is the point.

Next on this axis, I’d like to build a common benchmark harness: runc, runsc, mini-fc and real Firecracker on the same host, same workloads, same instrumentation. After a few weeks with each, I expect those numbers to be the most interesting part.

The code is at github.com/mtclinton/mini-firecracker. Its gVisor-side sibling is github.com/mtclinton/mini-sentry, and the posts about it are linked at the top.