The Complete Guide to the Linux KVM API
A practical tour of the Linux KVM ioctl interface: system, VM and vCPU descriptors, memory slots, kvm_run exits, interrupts, CPUID, debugging and threads, in C.

Every virtual machine on a Linux host, whether it is started by QEMU, Firecracker, crosvm or a hundred-line program you wrote this afternoon, is created through the same interface: a character device, /dev/kvm, and a set of ioctl calls on file descriptors derived from it. That interface is the KVM API. It is small enough to hold in your head, stable enough that programs written years ago still run and expressive enough to build a complete virtual machine monitor on. This guide goes through it from the bottom: the three kinds of file descriptor, how a VM acquires memory and CPUs, how the kvm_run structure reports why the guest stopped, how to handle each exit, and how interrupts, CPUID, debugging and threads fit in. Every example is C against Linux 6.12 headers on x86-64, with architecture notes where Arm and RISC-V differ. The primary source is Documentation/virt/kvm/api.rst in the kernel tree, published at docs.kernel.org/virt/kvm/api.html, and this guide follows its structure. It assumes you know what a VM exit is, as explained in the complete guide to virtualization for systems programmers.
The shape of the interface
KVM exposes three levels of object, each represented by a file descriptor, and each with its own set of ioctls. The documentation calls them system ioctls, VM ioctls and vCPU ioctls.
| Level | How you get it | What it controls | Examples |
|---|---|---|---|
| System | open("/dev/kvm") | The KVM subsystem as a whole | KVM_GET_API_VERSION, KVM_CREATE_VM, KVM_CHECK_EXTENSION, KVM_GET_VCPU_MMAP_SIZE |
| VM | ioctl(kvm_fd, KVM_CREATE_VM, 0) | One virtual machine: its memory, interrupt chip, devices | KVM_SET_USER_MEMORY_REGION, KVM_CREATE_VCPU, KVM_CREATE_IRQCHIP, KVM_IRQ_LINE |
| vCPU | ioctl(vm_fd, KVM_CREATE_VCPU, id) | One virtual processor | KVM_RUN, KVM_GET_REGS, KVM_SET_SREGS, KVM_SET_CPUID2, KVM_SET_GUEST_DEBUG |
Sending an ioctl to the wrong level fails with ENOTTY. A VM lives as long as its file descriptor is open, so closing the VM fd (and every fd derived from it) destroys the machine. Everything here is per process: a VM created by one process cannot be used from another, and the kernel checks that vCPU ioctls come from the process that created the VM.
The structure of the data is just as simple. Guest memory is memory that your process owns, an ordinary mmap region, which you tell KVM to expose to the guest at a chosen guest physical address. The vCPU is a file descriptor whose KVM_RUN ioctl blocks while the guest executes on the real processor and returns when something needs your attention. The reason is written into a shared structure, struct kvm_run, that you map from the vCPU fd. The whole API is a loop around that.
Step 0: check the host
A program should confirm it can talk to KVM before doing anything else. KVM_GET_API_VERSION has returned 12 since kernel 2.6.22 and is documented as stable, so a different value means a different, incompatible interface. Then query capabilities with KVM_CHECK_EXTENSION:
#include <fcntl.h>
#include <linux/kvm.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <unistd.h>
static void check_cap(int fd, int cap, const char *name)
{
int r = ioctl(fd, KVM_CHECK_EXTENSION, cap);
printf("%-24s %d\n", name, r);
}
int main(void)
{
int kvm = open("/dev/kvm", O_RDWR | O_CLOEXEC);
if (kvm < 0) {
perror("open /dev/kvm");
return 1;
}
int version = ioctl(kvm, KVM_GET_API_VERSION, 0);
if (version != KVM_API_VERSION) {
fprintf(stderr, "unexpected KVM API version %d\n", version);
return 1;
}
printf("%-24s %d\n", "api version", version);
check_cap(kvm, KVM_CAP_USER_MEMORY, "user memory");
check_cap(kvm, KVM_CAP_NR_VCPUS, "recommended vcpus");
check_cap(kvm, KVM_CAP_MAX_VCPUS, "max vcpus");
check_cap(kvm, KVM_CAP_NR_MEMSLOTS, "memory slots");
check_cap(kvm, KVM_CAP_IRQCHIP, "in-kernel irqchip");
check_cap(kvm, KVM_CAP_ONE_REG, "one-reg interface");
printf("%-24s %d\n", "vcpu mmap size", ioctl(kvm, KVM_GET_VCPU_MMAP_SIZE, 0));
return 0;
}On a typical x86-64 desktop with Linux 6.12 the output looks like this. The capability numbers depend on the CPU and the kernel configuration, so yours will differ:
api version 12
user memory 1
recommended vcpus 1
max vcpus 1024
memory slots 32764
in-kernel irqchip 1
one-reg interface 0
vcpu mmap size 12288A value of 0 from KVM_CHECK_EXTENSION means "not supported", and a positive value means supported, sometimes with a number attached, as with the CPU and slot limits. KVM_CAP_ONE_REG is a register access interface used on Arm and PowerPC, so it reads 0 on x86. The recommended and maximum vCPU counts differ: the recommended number is a soft limit, the maximum is a hard one. The vCPU mapping size is the length you pass to mmap for the kvm_run structure, and it can be larger than sizeof(struct kvm_run) because the mapping also holds other per-vCPU pages such as the coalesced MMIO ring, so always ask the kernel instead of using the structure size.
A rule worth building into every VMM: before you rely on a feature, check the capability, and fail with a clear message when it is missing. The documentation marks each ioctl with the capability or version that introduced it.
Step 1: create a VM
int vm = ioctl(kvm, KVM_CREATE_VM, 0);
if (vm < 0) {
perror("KVM_CREATE_VM");
return 1;
}The argument is a machine type. On x86 it is 0. On Arm it can encode the intermediate physical address size, and on s390 it selects the kind of virtual machine. The call returns a new file descriptor. At this point the VM has no memory and no CPUs.
On x86, two historical ioctls are worth knowing even though recent kernels need them less. KVM_SET_TSS_ADDR tells KVM where to place a three-page region it uses to emulate parts of real-mode hardware, and KVM_SET_IDENTITY_MAP_ADDR places a page table used to run an unpaged guest. Both want addresses in guest physical space that the guest will not use, and QEMU puts them just below 4 GiB. A VMM that only runs 64-bit guests with paging on can ignore them. A VMM that boots in 16-bit real mode on an older Intel part without unrestricted guest support needs them.
Step 2: give it memory
Guest memory is host memory. You allocate it, then register it with the VM as a memory slot. The structure is:
struct kvm_userspace_memory_region {
__u32 slot;
__u32 flags;
__u64 guest_phys_addr;
__u64 memory_size; /* bytes */
__u64 userspace_addr; /* start of the memory in the host process */
};A slot maps the host range [userspace_addr, userspace_addr + memory_size) to the guest physical range starting at guest_phys_addr. The rules are strict: addresses and size must be page aligned, slots cannot overlap in guest physical space, and a size of zero deletes a slot. Allocate with mmap rather than malloc so the alignment is right and the memory is anonymous:
#define MEM_SIZE 0x200000 /* 2 MiB of guest RAM */
void *mem = mmap(NULL, MEM_SIZE, PROT_READ | PROT_WRITE,
MAP_SHARED | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
if (mem == MAP_FAILED) {
perror("mmap");
return 1;
}
struct kvm_userspace_memory_region region = {
.slot = 0,
.flags = 0,
.guest_phys_addr = 0x0,
.memory_size = MEM_SIZE,
.userspace_addr = (uint64_t)(uintptr_t)mem,
};
if (ioctl(vm, KVM_SET_USER_MEMORY_REGION, ®ion) < 0) {
perror("KVM_SET_USER_MEMORY_REGION");
return 1;
}Because the guest's RAM is your process's memory, you can read and write it directly: loading a kernel image is a memcpy into mem, inspecting a stack is a pointer dereference. The guest's physical address A is host address mem + A. The kernel also lets the host swap, merge and migrate this memory as it would any other, which is why KVM guests benefit from transparent huge pages, KSM and NUMA policy without any special support. Newer kernels add KVM_SET_USER_MEMORY_REGION2 (Linux 6.8) with a guest_memfd option for confidential computing, and the old call remains valid.
Two flags matter. KVM_MEM_LOG_DIRTY_PAGES makes KVM track which pages the guest writes, readable with KVM_GET_DIRTY_LOG, which is how live migration finds changed memory. KVM_MEM_READONLY makes the slot read-only for the guest: reads work, and writes cause a KVM_EXIT_MMIO exit rather than a write, which is how a VMM presents ROM or flash. The post on mapping guest memory goes through slots, dirty logging and read-only regions in detail.
Step 3: create a vCPU and map kvm_run
int vcpu = ioctl(vm, KVM_CREATE_VCPU, 0); /* vCPU id 0 */
if (vcpu < 0) {
perror("KVM_CREATE_VCPU");
return 1;
}
int run_size = ioctl(kvm, KVM_GET_VCPU_MMAP_SIZE, 0);
struct kvm_run *run = mmap(NULL, run_size, PROT_READ | PROT_WRITE,
MAP_SHARED, vcpu, 0);
if (run == MAP_FAILED) {
perror("mmap kvm_run");
return 1;
}The vCPU id is chosen by you, starting at 0, and must be below the maximum reported by KVM_CAP_MAX_VCPUS. On x86 id 0 is the bootstrap processor. The mmap on the vCPU file descriptor at offset 0 maps the shared kvm_run page. Every KVM_RUN reads some fields you set and writes the exit information you read.
Step 4: set up the registers
A new vCPU starts in the processor's reset state, which on x86 means 16-bit real mode with the instruction pointer at the reset vector, CS.base = 0xffff0000 and RIP = 0xfff0. For a test program you load code at a convenient address and point the vCPU at it. Two structures carry the state. struct kvm_regs, with KVM_GET_REGS and KVM_SET_REGS, holds the general registers, rip and rflags. struct kvm_sregs, with KVM_GET_SREGS and KVM_SET_SREGS, holds the segment registers, descriptor tables and control registers.
struct kvm_sregs sregs;
ioctl(vcpu, KVM_GET_SREGS, &sregs);
sregs.cs.base = 0;
sregs.cs.selector = 0;
ioctl(vcpu, KVM_SET_SREGS, &sregs);
struct kvm_regs regs = {
.rip = 0x1000, /* where the guest code is loaded */
.rflags = 0x2, /* bit 1 is always set */
};
ioctl(vcpu, KVM_SET_REGS, ®s);Starting from KVM_GET_SREGS and changing only what you need keeps the other segments in their valid reset state. Setting cs.base and cs.selector to zero makes real-mode code at physical address 0x1000 run with CS:IP = 0000:1000. The rflags value 0x2 sets the bit that reads as one in hardware. Recent kernels add it for you when you call KVM_SET_REGS, but writing it yourself keeps the program correct on kernels that do not, and it is one of the rules checked at VM entry, described in the post on validating guest state.
Step 5: a complete guest, and the run loop
Put the pieces together with a guest that writes a message to a serial port. The code is 16-bit real-mode machine code, written out as bytes so no assembler is needed:
#include <fcntl.h>
#include <linux/kvm.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <unistd.h>
#define MEM_SIZE 0x10000
static void die(const char *what)
{
perror(what);
exit(1);
}
int main(void)
{
/* mov dx,0x3f8 ; mov al,'H' ; out dx,al ; mov al,'i' ; out dx,al ;
mov al,'\n' ; out dx,al ; hlt */
const uint8_t code[] = {
0xba, 0xf8, 0x03,
0xb0, 'H', 0xee,
0xb0, 'i', 0xee,
0xb0, '\n', 0xee,
0xf4,
};
int kvm = open("/dev/kvm", O_RDWR | O_CLOEXEC);
if (kvm < 0) die("open /dev/kvm");
if (ioctl(kvm, KVM_GET_API_VERSION, 0) != KVM_API_VERSION) die("api version");
int vm = ioctl(kvm, KVM_CREATE_VM, 0);
if (vm < 0) die("KVM_CREATE_VM");
uint8_t *mem = mmap(NULL, MEM_SIZE, PROT_READ | PROT_WRITE,
MAP_SHARED | MAP_ANONYMOUS, -1, 0);
if (mem == MAP_FAILED) die("mmap");
memcpy(mem + 0x1000, code, sizeof(code));
struct kvm_userspace_memory_region region = {
.slot = 0,
.guest_phys_addr = 0,
.memory_size = MEM_SIZE,
.userspace_addr = (uint64_t)(uintptr_t)mem,
};
if (ioctl(vm, KVM_SET_USER_MEMORY_REGION, ®ion) < 0) die("set memory");
int vcpu = ioctl(vm, KVM_CREATE_VCPU, 0);
if (vcpu < 0) die("KVM_CREATE_VCPU");
int run_size = ioctl(kvm, KVM_GET_VCPU_MMAP_SIZE, 0);
struct kvm_run *run = mmap(NULL, run_size, PROT_READ | PROT_WRITE,
MAP_SHARED, vcpu, 0);
if (run == MAP_FAILED) die("mmap run");
struct kvm_sregs sregs;
if (ioctl(vcpu, KVM_GET_SREGS, &sregs) < 0) die("KVM_GET_SREGS");
sregs.cs.base = 0;
sregs.cs.selector = 0;
if (ioctl(vcpu, KVM_SET_SREGS, &sregs) < 0) die("KVM_SET_SREGS");
struct kvm_regs regs = { .rip = 0x1000, .rflags = 0x2 };
if (ioctl(vcpu, KVM_SET_REGS, ®s) < 0) die("KVM_SET_REGS");
for (;;) {
if (ioctl(vcpu, KVM_RUN, 0) < 0) die("KVM_RUN");
switch (run->exit_reason) {
case KVM_EXIT_HLT:
puts("guest halted");
return 0;
case KVM_EXIT_IO:
if (run->io.direction == KVM_EXIT_IO_OUT && run->io.port == 0x3f8)
putchar(*((char *)run + run->io.data_offset));
break;
case KVM_EXIT_FAIL_ENTRY:
fprintf(stderr, "entry failed: 0x%llx\n",
(unsigned long long)run->fail_entry.hardware_entry_failure_reason);
return 1;
case KVM_EXIT_INTERNAL_ERROR:
fprintf(stderr, "internal error, suberror %u\n", run->internal.suberror);
return 1;
default:
fprintf(stderr, "unhandled exit %u\n", run->exit_reason);
return 1;
}
}
}Compile with gcc -O2 -Wall hello-kvm.c -o hello-kvm and run as a user in the kvm group:
Hi
guest haltedThe program has the shape every VMM has: setup, then a loop of KVM_RUN and a switch on exit_reason. Three things are worth noticing. The guest's out dx, al instructions are not executed on any serial hardware. They cause KVM_EXIT_IO exits, KVM_RUN returns, and the program plays the part of the device by printing the byte. The byte itself is not in the exit structure: run->io.data_offset is an offset **from the start of the kvm_run page** to where the data sits, so the address is (char *)run + run->io.data_offset. And the loop never needs to resume explicitly: calling KVM_RUN again continues the guest after the instruction that exited, with the exit already completed from the guest's point of view.
The exit reasons
KVM_RUN returns zero on a normal exit, with run->exit_reason set, or -1 with errno set when the call itself failed. The reasons you will meet on x86:
| Exit reason | Meaning | What to do |
|---|---|---|
KVM_EXIT_IO | The guest executed IN or OUT | Emulate the port, fill data_offset for IN |
KVM_EXIT_MMIO | The guest touched an unmapped or read-only guest physical address | Emulate the device register at mmio.phys_addr |
KVM_EXIT_HLT | The guest executed HLT with interrupts handled outside the kernel | Wait for an event, or stop |
KVM_EXIT_SHUTDOWN | Triple fault | The guest crashed, report and stop |
KVM_EXIT_FAIL_ENTRY | The processor refused to enter the guest | Check the state, as in the validation post |
KVM_EXIT_INTERNAL_ERROR | KVM could not continue, such as an unemulatable instruction | Log internal.suberror and the vCPU state |
KVM_EXIT_INTR | A signal interrupted the call | Handle the signal and call KVM_RUN again |
KVM_EXIT_DEBUG | A guest-debug event (breakpoint or single step) | Report to the debugger |
KVM_EXIT_SYSTEM_EVENT | The guest requested shutdown or reset | Act on system_event.type |
KVM_EXIT_IRQ_WINDOW_OPEN | The guest can now accept an interrupt | Inject one that was waiting |
The exit data lives in a union inside kvm_run, so only the member matching the reason is valid. Reading run->io after an MMIO exit gives garbage. The post on handling KVM exits works through IO, MMIO and HLT in code.
An ioctl return of -1 with errno == EINTR is not an error: a signal arrived, and the call returned early. The errno == EAGAIN case, with immediate_exit or interrupt-related states, likewise means "try again". Anything else is a real failure. A VMM loop therefore distinguishes three cases: a negative return that is retryable, a negative return that is fatal, and a zero return with a reason to dispatch.
Memory-mapped I/O
For an emulated device with registers at a guest physical address, leave that address range unmapped by any slot. When the guest reads or writes it, the access finds no backing memory and KVM exits with KVM_EXIT_MMIO. The structure gives you everything:
case KVM_EXIT_MMIO: {
uint64_t addr = run->mmio.phys_addr;
uint32_t len = run->mmio.len;
if (run->mmio.is_write) {
uint64_t value = 0;
memcpy(&value, run->mmio.data, len);
uart_write(addr - UART_BASE, value, len);
} else {
uint64_t value = uart_read(addr - UART_BASE, len);
memcpy(run->mmio.data, &value, len); /* the guest reads this on resume */
}
break;
}For a read, you fill run->mmio.data before the next KVM_RUN, and KVM delivers it to the guest as the result of the load. A write needs no completion. The same applies to IN instructions: write the result into the data area at data_offset and re-enter. This asymmetry, where reads are completed by the next KVM_RUN, is the usual source of "my read returns garbage" bugs.
Interrupts
There are two ways to deliver interrupts. In the first, the kernel emulates the interrupt controller. KVM_CREATE_IRQCHIP (before creating vCPUs) makes an in-kernel PIC, IOAPIC and per-vCPU local APIC on x86, and you raise interrupts with KVM_IRQ_LINE:
ioctl(vm, KVM_CREATE_IRQCHIP, 0); /* before KVM_CREATE_VCPU */
/* ... later, when the emulated device wants to signal ... */
struct kvm_irq_level irq = { .irq = 4, .level = 1 };
ioctl(vm, KVM_IRQ_LINE, &irq);
irq.level = 0;
ioctl(vm, KVM_IRQ_LINE, &irq);This asserts and then deasserts line 4, typical of a legacy serial port. The kernel handles priority, masking and delivery, which is much faster than doing it in user space. The second way is for VMMs that emulate the controller themselves: they inject a vector into a vCPU with KVM_INTERRUPT, after checking run->ready_for_interrupt_injection, and use request_interrupt_window to be told when the guest becomes interruptible. The in-kernel route is the usual choice, and QEMU uses it by default under KVM.
For high-rate devices, eventfds avoid the user space round trip. KVM_IRQFD binds an eventfd to an interrupt, so any thread, or a kernel component like vhost, can raise the interrupt by writing to the eventfd. KVM_IOEVENTFD does the reverse: it binds a guest I/O or MMIO address to an eventfd, so a guest write to a doorbell register signals the eventfd inside the kernel with no KVM_RUN exit at all. These two calls are how virtio devices reach good performance, and the post on handling exits explains why.
CPUID and model-specific registers
The guest executes CPUID often, and every execution exits to KVM, which answers from a table you set. Ask the kernel for the CPUID entries the host can support with KVM_GET_SUPPORTED_CPUID, adjust them as needed and give them to each vCPU with KVM_SET_CPUID2 before running it:
#define MAX_ENTRIES 100
struct kvm_cpuid2 *cpuid =
malloc(sizeof(*cpuid) + MAX_ENTRIES * sizeof(struct kvm_cpuid_entry2));
cpuid->nent = MAX_ENTRIES;
if (ioctl(kvm, KVM_GET_SUPPORTED_CPUID, cpuid) < 0)
die("KVM_GET_SUPPORTED_CPUID");
/* ... edit entries here, for example hide a feature ... */
if (ioctl(vcpu, KVM_SET_CPUID2, cpuid) < 0)
die("KVM_SET_CPUID2");If the buffer is too small, the first call fails with E2BIG. Forgetting to call KVM_SET_CPUID2 leaves the guest with a minimal CPUID, which breaks many kernels. The post on guest CPUID goes through the leaf layout and what to modify. MSRs are the companion mechanism: KVM_GET_MSRS and KVM_SET_MSRS read and write them in bulk, and KVM_GET_MSR_INDEX_LIST lists the ones KVM can save and restore, which a VMM must preserve across migration.
Threads, signals and kicking a vCPU
A vCPU is a file descriptor, and KVM_RUN blocks the calling thread while the guest executes, so a multi-vCPU VM needs one thread per vCPU, each in its own KVM_RUN loop. A vCPU's ioctls must not run concurrently from two threads, and KVM_RUN must come from a thread of the process that created the VM. The kernel handles the rest, including scheduling vCPU threads like any other thread, which is why top -H and taskset work on guests.
To make a blocked vCPU return, for example when another thread wants to inject an interrupt or stop the machine, send its thread a signal. A signal arriving during KVM_RUN makes the call return -1 with EINTR, and run->exit_reason is KVM_EXIT_INTR. The race to avoid is a signal that arrives just before the vCPU thread enters KVM_RUN, which would be lost, leaving the thread blocked forever. The immediate_exit field in kvm_run fixes it: set it to 1 from the signal handler, and the next KVM_RUN returns at once with EINTR without entering the guest. A VMM sets run->immediate_exit = 0 before each entry and a handler sets it to 1 when it is asked to stop.
Debugging a guest
KVM_SET_GUEST_DEBUG lets a VMM implement a gdb stub. With the KVM_GUESTDBG_ENABLE flag, it can ask for single-stepping (KVM_GUESTDBG_SINGLESTEP), hardware breakpoints (KVM_GUESTDBG_USE_HW_BP) and software breakpoints (KVM_GUESTDBG_USE_SW_BP). A hit returns KVM_EXIT_DEBUG, and run->debug.arch has the vector and instruction pointer. The post on single-stepping guests builds a stepper from this. For quick inspection, read the vCPU state at an exit:
static void dump(int vcpu)
{
struct kvm_regs r;
struct kvm_sregs s;
ioctl(vcpu, KVM_GET_REGS, &r);
ioctl(vcpu, KVM_GET_SREGS, &s);
fprintf(stderr, "rip=%016llx rsp=%016llx rflags=%08llx cr0=%08llx cr3=%016llx cr4=%08llx\n",
r.rip, r.rsp, r.rflags, s.cr0, s.cr3, s.cr4);
}rip=000000000000100d rsp=0000000000000000 rflags=00000002 cr0=60000010 cr3=0000000000000000 cr4=00000000The values shown are what the example guest has after HLT: rip points just past the hlt byte at 0x100c, and cr0=60000010 is the real-mode reset value. Reading this at every unexpected exit is the cheapest debugger there is. On the host, trace-cmd record -e kvm or perf kvm stat show the exit stream, covered in the post on KVM tracepoints.
Dirty page tracking and what live migration needs
A VMM that wants to snapshot or migrate a running guest has to find out which pages changed since it last looked. KVM provides this through dirty logging. Create the memory slot with KVM_MEM_LOG_DIRTY_PAGES in flags, and the kernel starts recording writes to that slot in a bitmap. Read and clear it with KVM_GET_DIRTY_LOG:
#define PAGE_SIZE 4096UL
size_t pages = MEM_SIZE / PAGE_SIZE;
size_t bitmap_bytes = ((pages + 63) / 64) * 8; /* one bit per page, 64-bit aligned */
uint64_t *bitmap = calloc(1, bitmap_bytes);
struct kvm_dirty_log log = {
.slot = 0,
.dirty_bitmap = bitmap,
};
if (ioctl(vm, KVM_GET_DIRTY_LOG, &log) < 0)
die("KVM_GET_DIRTY_LOG");
for (size_t page = 0; page < pages; page++) {
if (bitmap[page / 64] & (1ULL << (page % 64)))
printf("page %zu is dirty\n", page);
}After a guest that wrote to its first and third pages ran for a while, a call prints:
page 0 is dirty
page 2 is dirtyEach call returns the pages dirtied since the previous call and resets the log, which is exactly the loop that pre-copy migration needs: copy everything, then repeatedly fetch the dirty bitmap and copy only those pages until the remainder is small. The bitmap length must cover the slot, rounded up to a multiple of eight bytes, and a buffer that is too small is a classic source of memory corruption in a VMM, since the kernel writes the full length. Newer kernels add a manual-protect mode, enabled through KVM_ENABLE_CAP with KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2, which lets the VMM clear dirty bits for just the ranges it has copied and reduces the pause caused by re-protecting all of memory on every fetch. The migration post in this series shows the QEMU side of the same process.
Enabling optional features with KVM_ENABLE_CAP
Some capabilities are not on by default. They change guest-visible behavior or cost something, so KVM wants you to ask. KVM_ENABLE_CAP, on the VM or on a vCPU depending on the capability, takes a struct kvm_enable_cap with the capability number and up to four arguments:
struct kvm_enable_cap cap = {
.cap = KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2,
.args = { KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE },
};
if (ioctl(vm, KVM_ENABLE_CAP, &cap) < 0)
perror("KVM_ENABLE_CAP (manual dirty log protect)");First check that the capability exists with KVM_CHECK_EXTENSION, since an unsupported one makes the enable call fail with EINVAL. The pattern covers a long list: split huge pages on dirty logging, exit-on-hypercall, disabling features such as the in-kernel PIT's reinjection, or letting user space handle MSR accesses (KVM_CAP_X86_USER_SPACE_MSR). Read the documentation entry for each one before enabling it, because a few change the exit behavior of the whole VM, and an exit reason you did not expect appears only after you turn the capability on.
Exceptions, NMIs and pending events
A VMM sometimes needs to inject an event into a vCPU other than an external interrupt: a page fault, a machine check or an NMI. On x86 the interface is KVM_GET_VCPU_EVENTS and KVM_SET_VCPU_EVENTS, which carry the pending exception, interrupt and NMI state in struct kvm_vcpu_events. They are the right interface for saving and restoring a vCPU that stopped mid-event, and for injecting a specific exception. A simple NMI uses KVM_NMI. When an emulated instruction faults in the guest's terms, such as a bad MMIO access that the guest should see as a bus error, the VMM can synthesize the exception through the events structure instead of terminating the VM. The older KVM_INTERRUPT ioctl, which injects a vector, is limited to cases without an in-kernel interrupt controller, so new code prefers the events interface for anything beyond external interrupts.
A worked example: a device with registers
Pulling the pieces together, here is the exit handler for a small virtual device the guest reaches by MMIO at 0xd0000000: a counter register at offset 0 that increments on every read and a status register at offset 4. The guest, a 32-bit protected mode program, would read the counter three times. The handler is the same shape as any device model:
#define DEV_BASE 0xd0000000ULL
#define DEV_SIZE 0x1000ULL
static uint32_t counter;
static uint32_t dev_read(uint64_t off)
{
switch (off) {
case 0x0: return counter++;
case 0x4: return 0x1; /* status: ready */
default: return 0;
}
}
static void dev_write(uint64_t off, uint32_t value)
{
if (off == 0x0)
counter = value;
}
/* inside the KVM_RUN loop */
case KVM_EXIT_MMIO: {
uint64_t addr = run->mmio.phys_addr;
if (addr < DEV_BASE || addr >= DEV_BASE + DEV_SIZE) {
fprintf(stderr, "stray MMIO at 0x%llx\n", (unsigned long long)addr);
return 1;
}
uint64_t off = addr - DEV_BASE;
if (run->mmio.is_write) {
uint32_t v = 0;
memcpy(&v, run->mmio.data, run->mmio.len);
dev_write(off, v);
} else {
uint32_t v = dev_read(off);
memcpy(run->mmio.data, &v, run->mmio.len);
}
break;
}With a guest that performs three 32-bit loads from 0xd0000000 and sends each result to a debug port, the host prints:
guest read: 0
guest read: 1
guest read: 2Notice that nothing in this handler is KVM-specific beyond the exit structure. That is deliberate and true of every real device model: the KVM API delivers the access, and the device code is plain C. Because every access to the range exits, a device with registers on a hot path costs an exit per access, which is the problem that ioeventfd addresses for write-only doorbell registers, and that coalesced MMIO addresses for batched writes. KVM_REGISTER_COALESCED_MMIO asks KVM to buffer writes to a range in a ring in the kvm_run mapping instead of exiting, and the VMM drains the ring the next time it gets control, which suits registers that only need ordering and not an immediate reaction, such as a framebuffer.
Setting up long mode by hand
The 16-bit real-mode example is the shortest path, but most useful guests run in 64-bit mode. A VMM that wants to skip firmware must construct the state a bootloader would: page tables, a GDT, control registers and EFER. The sequence is always the same. Build identity-mapped page tables in guest memory (a PML4 with one entry pointing to a PDPT, which points to a PD with 2 MiB pages covering the first few gibibytes). Write a GDT with a null descriptor and a 64-bit code segment. Then set the state:
sregs.cr3 = pml4_gpa; /* guest physical address of the PML4 */
sregs.cr4 = 0x20; /* CR4.PAE */
sregs.cr0 = 0x80000011; /* PG | NE | PE */
sregs.efer = 0x500; /* LME | LMA */
sregs.cs = (struct kvm_segment){
.base = 0, .limit = 0xffffffff, .selector = 0x8, .type = 11,
.present = 1, .dpl = 0, .db = 0, .s = 1, .l = 1, .g = 1,
};
/* data segments, TR and the descriptor tables must be filled in the same way */The easiest way to get the full state right is to follow the rules checked at VM entry, listed in the post on validating guest state, and to compare with a state captured from a guest that works. Only after that does KVM_SET_SREGS followed by KVM_RUN succeed. If the page tables are wrong, the first instruction fetch faults and the guest triple-faults, reported as KVM_EXIT_SHUTDOWN, as opposed to KVM_EXIT_FAIL_ENTRY for rejected register state.
Testing a VMM
A hypervisor is easy to test because a guest is just bytes. Write guests as tiny assembly or machine-code programs that exercise one thing, such as an I/O exit, an MMIO read or an interrupt, and end with a HLT or a write to a debug port that carries a result. A test harness loads each guest, runs the loop and compares the output and the exit sequence with what is expected. The KVM unit tests in the kernel tree (tools/testing/selftests/kvm) are the model: they build small guests in C, run them through the same ioctls and assert on exits and register state, and they are a good source of correct usage for each ioctl. For regression checks, record the number of exits of each kind in a run: a change that adds a thousand I/O exits to boot is visible long before a stopwatch notices.
Observing KVM from the host
Several host-side views complement what the VMM sees. Under /sys/kernel/debug/kvm/, with debugfs mounted, the kernel exports counters per VM and per vCPU, and the same statistics are available through a binary file descriptor interface (KVM_GET_STATS_FD) that a VMM can read without debugfs. The kvm tracepoints (kvm_exit, kvm_entry, kvm_pio, kvm_mmio, kvm_inj_virq among them) are listed under /sys/kernel/tracing/events/kvm/ and can be recorded with trace-cmd record -e kvm or perf. The perf kvm stat command summarizes exits by reason, which is the first tool to reach for when a guest is slower than it should be, and the post on tracepoints and perf kvm shows its output. The combination of a VMM that logs its own exits and the kernel's tracepoints gives two views of every exit, which narrows most problems quickly.
Saving and restoring vCPU state
Pausing a VM and resuming it later, on the same or another host, means capturing every piece of state the processor holds. On x86 the list is longer than registers and segments, and the order of restoration matters. A complete save collects the general registers (KVM_GET_REGS), the system registers (KVM_GET_SREGS, or KVM_GET_SREGS2 where available, which also carries the PDPTR values), the floating-point and vector state (KVM_GET_FPU and the larger KVM_GET_XSAVE), the model-specific registers (KVM_GET_MSRS over the list from KVM_GET_MSR_INDEX_LIST), the local APIC (KVM_GET_LAPIC), pending events (KVM_GET_VCPU_EVENTS), the multiprocessing state (KVM_GET_MP_STATE) and the extended control registers (KVM_GET_XCRS). The restore uses the matching KVM_SET_* calls, with KVM_SET_CPUID2 first of all, because the CPUID table decides which of the other state is valid for this vCPU. Restoring MSRs before CPUID can fail or silently drop values for features the guest has not been told about.
The VM level has its own state: the in-kernel interrupt controllers (KVM_GET_IRQCHIP), the PIT (KVM_GET_PIT2), the clock (KVM_GET_CLOCK, so a guest does not see time jump) and the memory contents. The rule of thumb is that anything the kernel emulates for you has a get and a set, and a VMM that forgets one produces a guest that boots from a snapshot and misbehaves minutes later. Checking the documentation's list of ioctls against your save routine is a cheap audit.
Compatibility and the stability promise
The KVM API is an ABI with a long-lived promise. The version number has been 12 for many years because the kernel adds capabilities and ioctls without changing existing ones, so a program built against old headers keeps working on new kernels. The reverse is not true: a program using a new ioctl fails with ENOTTY or EINVAL on an old kernel, which is why feature checks through KVM_CHECK_EXTENSION come first. Structure sizes also grow. Some ioctls take a structure whose size is part of the ioctl number, so a structure that gains fields gets a new ioctl, as with KVM_SET_USER_MEMORY_REGION2 beside the original, and KVM_GET_SREGS2 beside KVM_GET_SREGS. The kernel's documentation notes which ioctls are legacy but still supported.
For a VMM you ship to others, the practical advice is to compile against the headers of the oldest kernel you support, probe capabilities at run time, and keep fallbacks for the features that matter. For one you only run on your own machine, use the current headers and move on. Either way, resist the temptation to copy a structure definition into your own source: use <linux/kvm.h> from the installed kernel headers package, so you get the right layout for the architecture and kernel.
Errors and what they mean
errno | Common cause |
|---|---|
EACCES or EPERM on open | Not in the kvm group |
ENOENT on open | No /dev/kvm: module not loaded or virtualization disabled |
EINVAL on KVM_SET_USER_MEMORY_REGION | Misaligned address or size, overlapping slot, bad flags |
ENOMEM | Out of memory, or memory slot limit reached |
ENOTTY | The ioctl was sent to the wrong kind of file descriptor |
EEXIST | A vCPU id or slot already in use |
E2BIG | A buffer for CPUID or MSR lists was too small |
EINTR from KVM_RUN | A signal arrived, retry |
EFAULT | A pointer you passed is invalid |
For anything surprising, check dmesg on the host. KVM logs failures such as invalid guest state or an unhandled exit with the vCPU number.
Other architectures
The structure is the same on Arm and RISC-V: system, VM and vCPU descriptors, memory slots, KVM_RUN and kvm_run. What differs is the register interface and the initial state. Arm and RISC-V use the KVM_GET_ONE_REG and KVM_SET_ONE_REG ioctls, with register IDs that encode the architecture and size, instead of the kvm_regs and kvm_sregs structures. A new Arm vCPU must be initialized with KVM_ARM_VCPU_INIT and a target description from KVM_ARM_PREFERRED_TARGET, and the interrupt controller is created as a device with KVM_CREATE_DEVICE and type KVM_DEV_TYPE_ARM_VGIC_V3. MMIO and exit handling use the same exit reasons. The kernel documentation separates architecture-specific ioctls and marks them, so a portable VMM keeps a thin per-architecture layer.
How a real VMM is organized
Programs like QEMU, Firecracker and cloud-hypervisor add structure on top of this API, and the pattern is stable. A machine layer builds the VM, registers memory slots and creates the interrupt controller. A device layer holds emulated devices, each registering port ranges and MMIO ranges with a dispatcher, so that the exit handler looks up the address and calls the device. A vCPU thread per virtual CPU runs the KVM_RUN loop and a main thread handles the control interface and signals. The data path of fast devices is moved out of the exit loop with ioeventfd and irqfd, often to a separate process via vhost-user. And state save and restore, for migration and snapshots, uses KVM_GET_* and KVM_SET_* for every piece of vCPU and VM state. The post on writing a VMM in Rust shows this shape with the kvm-ioctls crate.
Security notes
KVM's interface is a privileged one in practice: a process that can open /dev/kvm can create VMs and consume host memory and CPU, so access is controlled by the group on the device. The guest is hostile by design, so the VMM must treat everything the guest does at an exit as untrusted input, including the sizes and addresses it passes to an emulated device. Most real VM escapes have been bugs in device emulation code, not in KVM itself. Keep emulated devices few, validate every access, drop privileges after setup with seccomp and run the VMM as an unprivileged user in its own namespace.
Boundaries
This interface is not for everyone. For a normal virtual machine, use QEMU or libvirt and do not write a VMM. Write against the KVM API when you need something QEMU is too large or too general for: a minimal microVM, a sandbox, a research hypervisor, a teaching tool or a way to run one binary in isolation. It is also Linux-specific. macOS has Hypervisor.framework, Windows has the Windows Hypervisor Platform and FreeBSD has bhyve's vmm(4), with similar concepts and different calls.
Where to go next
The posts in this series take the API one piece at a time. Start with setting up a workstation for KVM development without running as root, then what /dev/kvm is, then write a minimal hypervisor, then map guest memory, then handle exits. Continue with CPUID, single-stepping, the Rust version with kvm-ioctls and debugging with tracepoints. The kernel documentation page is the reference to keep open, and the header include/uapi/linux/kvm.h is where every ioctl number and structure is defined.


