20. KVM as an API
Why this layer exists
Chapter 19 wrote the hypervisor’s three jobs by hand: a G-stage table (gmap), an entry (hyp_enter, an sret with hstatus.SPV set) and an exit handler (hyp_trap, which read the guest’s ecall out of a trap frame). This chapter runs the same payload, byte for byte, under a hypervisor someone else wrote: KVM, the one built into Linux. The ordering is the point. KVM’s interface is a set of ioctl calls, and an ioctl can be read as a plain API only by someone who does not know what is behind it. A reader who has just written gmap reads KVM_SET_USER_MEMORY_REGION as the call that makes gmap unnecessary, KVM_RUN as hyp_enter plus the wait for hyp_trap, and KVM_EXIT_SYSTEM_EVENT as the same ecall arriving a second way: chapter 19’s hyp_trap read it from a trap frame in ember; here the VMM reads it from a shared page after KVM_RUN returns.
One ISA runs throughout. The kernel is chapter 15’s pinned Linux, riscv64, built once more with KVM compiled in; QEMU provides the H-extension (-cpu rv64,h=true, as in chapter 19); the VMM is a static riscv64 C program, and the guest is the eleven-instruction payload. KVM does no general instruction emulation: it runs the guest on the hart, and decodes only the loads and stores that reach a device (chapter 21) and the few instructions the H-extension traps to it, wfi among them (exercise (a)). The lab’s QEMU command has no -accel, so QEMU itself emulates the whole hart, H-extension included, and inside that emulated hart Linux executes sret into VS-mode exactly as ember did. Two levels are in play: the QEMU-booted Linux is the KVM host, and the payload is its guest. The ioctls this part uses (KVM_CREATE_VM, KVM_CREATE_VCPU, KVM_SET_USER_MEMORY_REGION, KVM_RUN) are architecture-independent; the register ids are not, and are the one place the lab is RISC-V’s alone. wick (Part V) is a VMM of this shape on a Linux host with /dev/kvm; chapters 21 and 22 grow this program a device and a virtqueue.
Mechanism
Three words, defined where this chapter first needs them. A vCPU is the object KVM keeps for one guest hart: its register file, its CSR shadows and its run state, all in kernel memory, and the file descriptor userspace uses to set them and run them. A memory slot is a record “guest-physical range G is backed by this range of the VMM’s own address space”, the unit in which the VMM hands a guest its RAM. A VM exit is the guest stopping for the hypervisor: on RISC-V, any trap from V=1 into HS (chapter 18). Most are finished inside KVM and the guest re-enters; KVM_RUN returning to the VMM is the subset of exits that KVM cannot finish itself.
Three descriptors
open("/dev/kvm") gives a handle on KVM itself. The first call on it is the version check, and the documentation says what to do with the answer:
// linux v7.2.8, Documentation/virt/kvm/api.rst:139-146
:Returns: the constant KVM_API_VERSION (=12)
This identifies the API version as the stable kvm API. It is not
expected that this number will change. However, Linux 2.6.20 and
2.6.21 report earlier versions; these are not documented and not
supported. Applications should refuse to run if KVM_GET_API_VERSION
returns a value other than 12. If this check passes, all ioctls
described as 'basic' will be available.
KVM_CREATE_VM on that descriptor returns a second one, the VM. It “has no virtual cpus and no memory”:
// linux v7.2.8, Documentation/virt/kvm/api.rst:156-158
:Returns: a VM fd that can be used to control the new virtual machine.
The new VM has no virtual cpus and no memory.
KVM_CREATE_VCPU on the VM descriptor returns the third, the vCPU. Three descriptors, three levels: ioctl on the first is about the whole of KVM (KVM_GET_API_VERSION), on the second about one guest’s memory and devices, on the third about one hart.
The memory slot feeds the G-stage
Chapter 19’s gmap walked an Sv39x4 table and wrote a leaf for each page. The VMM does none of that. It mmaps anonymous memory in its own address space and tells KVM that this range is the guest’s RAM at a guest-physical address:
// linux v7.2.8, Documentation/virt/kvm/api.rst:1381-1384
This ioctl allows the user to create, modify or delete a guest physical
memory slot. Bits 0-15 of "slot" specify the slot id and this value
should be less than the maximum number of user memory slots supported per
VM. The maximum allowed slots can be queried using KVM_CAP_NR_MEMSLOTS.
The last two sentences of the next paragraph decide how the VMM then loads the guest:
// linux v7.2.8, Documentation/virt/kvm/api.rst:1398-1402
Memory for the region is taken starting at the address denoted by the
field userspace_addr, which must point at user addressable memory for
the entire memory slot size. Any object may back this memory, including
anonymous memory, ordinary files, and hugetlbfs. Changes in the backing
of the memory region are automatically reflected into the guest.
The slot’s backing memory is the VMM’s, and it stays the VMM’s. The lab’s fread of the payload into the slot writes the guest’s code page; its read of mem + 0x1000 after the exit reads the guest’s data page. No copy crosses a boundary; the VMM and the guest share the pages, which is chapter 14’s “shared” axis spent in the open.
What the ioctl does not do is build the G-stage table. kvm_arch_init_vm calls kvm_riscv_mmu_alloc_pgd when the VM is created: a zeroed root of kvm_riscv_gstage_pgd_size bytes, the four-times-wide root chapter 19 declared as groot. The table’s depth is the widest G-stage mode the hart supports (kvm_riscv_gstage_max_pgd_levels), so on a hart with a wider mode than Sv39x4 the table is deeper than chapter 19’s three levels; the root is 16 KiB either way.
// linux v7.2.8, arch/riscv/kvm/mmu.c:664-682
int kvm_riscv_mmu_alloc_pgd(struct kvm *kvm)
{
struct page *pgd_page;
if (kvm->arch.pgd != NULL) {
kvm_err("kvm_arch already initialized?\n");
return -EINVAL;
}
pgd_page = alloc_pages(GFP_KERNEL | __GFP_ZERO,
get_order(kvm_riscv_gstage_pgd_size));
if (!pgd_page)
return -ENOMEM;
kvm->arch.pgd = page_to_virt(pgd_page);
kvm->arch.pgd_phys = page_to_phys(pgd_page);
kvm->arch.pgd_levels = kvm_riscv_gstage_max_pgd_levels;
return 0;
}
The slot is checked when it is registered (kvm_arch_prepare_memory_region, same file, line 171, rejects a range outside the guest-physical space the table can address and a writable slot over a read-only mapping) and the table is filled in later, one page at a time, by the fault the guest takes when it first touches the page. A guest-page fault, the fault class chapter 19 showed going to HS and never to the guest, is where KVM finds the slot:
// linux v7.2.8, arch/riscv/kvm/vcpu_exit.c:25-31
fault_addr = (trap->htval << 2) | (trap->stval & 0x3);
gfn = fault_addr >> PAGE_SHIFT;
memslot = gfn_to_memslot(vcpu->kvm, gfn);
hva = gfn_to_hva_memslot_prot(memslot, gfn, &writable);
if (kvm_is_error_hva(hva) ||
(trap->scause == EXC_STORE_GUEST_PAGE_FAULT && !writable)) {
If the guest-physical address belongs to a slot, KVM finds the host page behind it and installs a G-stage leaf, then resumes the guest without returning to the VMM:
// linux v7.2.8, arch/riscv/kvm/vcpu_exit.c:65-71
ret = kvm_riscv_mmu_map(vcpu, memslot, fault_addr, hva,
(trap->scause == EXC_STORE_GUEST_PAGE_FAULT) ? true : false,
&host_map);
if (ret < 0)
return ret;
return 1;
kvm_riscv_mmu_map is gmap made lazy: it walks the same table, allocates the lower levels from a per-vCPU cache, and writes the leaf with the permissions kvm_riscv_gstage_map_page chose. Chapter 19’s first mistake was a leaf without U. KVM’s protection values are Linux’s own page-protection macros, and every one of them is built on _PAGE_BASE:
// linux v7.2.8, arch/riscv/include/asm/pgtable.h:167-175
#define _PAGE_BASE (_PAGE_PRESENT | _PAGE_ACCESSED | _PAGE_USER)
#define PAGE_NONE __pgprot(_PAGE_PROT_NONE | _PAGE_READ)
#define PAGE_READ __pgprot(_PAGE_BASE | _PAGE_READ)
#define PAGE_WRITE __pgprot(_PAGE_BASE | _PAGE_READ | _PAGE_WRITE)
#define PAGE_EXEC __pgprot(_PAGE_BASE | _PAGE_EXEC)
#define PAGE_READ_EXEC __pgprot(_PAGE_BASE | _PAGE_READ | _PAGE_EXEC)
#define PAGE_WRITE_EXEC __pgprot(_PAGE_BASE | _PAGE_READ | \
_PAGE_EXEC | _PAGE_WRITE)
_PAGE_USER is in the base of every combination, so every G-stage leaf KVM writes has U=1 (gstage.c picks among these in lines 239 to 249). The rule from §14.1.5.1 chapter 19 quoted holds for Linux too, and Linux satisfies it by routing G-stage leaves through the user-page macros.
When the address has no slot, the fault is not a bug. It is a device: a load or store to an address nobody backed with memory is exactly what a memory-mapped register looks like from inside a guest. KVM decodes the instruction (the hardware’s htinst register, or a read of the guest’s instruction) and fills kvm_run with what the guest tried to do. This is where a device model takes over (chapter 21 defines the term and builds one); this chapter’s VMM reports the exit and fails. An instruction fetch from an unbacked address is different: the same function reflects an instruction access fault back into the guest (vcpu_exit.c:41-58), as a bare machine with no memory there would, rather than passing a fetch up as a device.
Registers: the id encoding
A vCPU’s registers are reached with KVM_SET_ONE_REG and KVM_GET_ONE_REG, each taking a struct kvm_one_reg of a 64-bit id and a pointer. RISC-V’s ids are documented in api.rst:
// linux v7.2.8, Documentation/virt/kvm/api.rst:2787-2791
RISC-V core registers represent the general execution state of a Guest VCPU
and it has the following id bit patterns::
0x8020 0000 02 <index into the kvm_riscv_core struct:24> (32bit Host)
0x8030 0000 02 <index into the kvm_riscv_core struct:24> (64bit Host)
The documentation lists the register behind each index, and the table starts:
// linux v7.2.8, Documentation/virt/kvm/api.rst:2798-2800
0x80x0 0000 0200 0000 regs.pc Program counter
0x80x0 0000 0200 0001 regs.ra Return address
0x80x0 0000 0200 0002 regs.sp Stack pointer
The index is the word offset of the register inside struct kvm_riscv_core, and the header defines the structure and the macro that computes the index from a member name:
// linux v7.2.8, arch/riscv/include/uapi/asm/kvm.h:65-68
struct kvm_riscv_core {
struct user_regs_struct regs;
unsigned long mode;
};
// linux v7.2.8, arch/riscv/include/uapi/asm/kvm.h:257-259
#define KVM_REG_RISCV_CORE (0x02 << KVM_REG_RISCV_TYPE_SHIFT)
#define KVM_REG_RISCV_CORE_REG(name) \
(offsetof(struct kvm_riscv_core, name) / sizeof(unsigned long))
struct user_regs_struct is Linux’s ptrace register layout, pc first, then ra, sp, gp, tp, t0 to t2, s0, s1, a0 to a7, s2 to s11, t3 to t6: regs.pc is index 0, regs.a0 is 10, regs.a7 is 17, and mode follows the 32 registers at index 32. offsetof takes a member path, so KVM_REG_RISCV_CORE_REG(regs.a0) is valid C; the full id is KVM_REG_RISCV (0x8000000000000000, the architecture tag) ORed with KVM_REG_SIZE_U64 (0x0030000000000000, the register is 8 bytes), KVM_REG_RISCV_CORE (0x02 << 24, the register group) and the index: 0x8030000002000000 for pc, which is the 0x8030 0000 02 <index> pattern above.
The mode register is the guest’s privilege mode and KVM_RISCV_MODE_S is 1. What it sets is the bit chapter 19 set by hand: sstatus.SPP in the vCPU’s saved state, the second of the two inputs to sret (hstatus.SPV, the first, KVM sets itself):
// linux v7.2.8, arch/riscv/kvm/vcpu_onereg.c:250-256
else if (reg_num == KVM_REG_RISCV_CORE_REG(mode)) {
if (reg_val == KVM_RISCV_MODE_S)
cntx->sstatus |= SR_SPP;
else
cntx->sstatus &= ~SR_SPP;
} else
return -ENOENT;
KVM’s reset state already has both bits (kvm_riscv_vcpu_context_reset sets them), and exercise (a) reads that.
KVM_RUN and the shared page
KVM_RUN has no argument. The result comes back through a page shared with the kernel, which the VMM maps from the vCPU descriptor, its size given by KVM_GET_VCPU_MMAP_SIZE:
// linux v7.2.8, Documentation/virt/kvm/api.rst:412-416
This ioctl is used to run a guest virtual cpu. While there are no
explicit parameters, there is an implicit parameter block that can be
obtained by mmap()ing the vcpu fd at offset 0, with the size given by
KVM_GET_VCPU_MMAP_SIZE. The parameter block is formatted as a 'struct
kvm_run' (see below).
The first fields of struct kvm_run are the exit reason and, in a union, the detail for each reason:
// linux v7.2.8, include/uapi/linux/kvm.h:224-234
struct kvm_run {
/* in */
__u8 request_interrupt_window;
__u8 HINT_UNSAFE_IN_KVM(immediate_exit);
__u8 padding1[6];
/* out */
__u32 exit_reason;
__u8 ready_for_interrupt_injection;
__u8 if_flag;
__u16 flags;
KVM_RUN returns 0 when the guest has stopped for a reason userspace has to see, and run->exit_reason says which. Everything else a trap can be, KVM handles and re-enters: a guest-page fault with a slot behind it, an SBI call it implements, a timer. The kernel dispatches in one function, kvm_riscv_vcpu_exit, and its cases are the same traps chapter 19’s hyp_trap took, behind the same test: a trap is the guest’s if hstatus.SPV is set.
// linux v7.2.8, arch/riscv/kvm/vcpu_exit.c:251-260
case EXC_INST_GUEST_PAGE_FAULT:
case EXC_LOAD_GUEST_PAGE_FAULT:
case EXC_STORE_GUEST_PAGE_FAULT:
if (vcpu->arch.guest_context.hstatus & HSTATUS_SPV)
ret = gstage_page_fault(vcpu, run, trap);
break;
case EXC_SUPERVISOR_SYSCALL:
if (vcpu->arch.guest_context.hstatus & HSTATUS_SPV)
ret = kvm_riscv_vcpu_sbi_ecall(vcpu, run);
break;
The entry is the other half. KVM’s switch function restores the guest’s registers and ends the way hyp_enter did:
// linux v7.2.8, arch/riscv/kvm/vcpu_switch.S:194-206
/*
* Parameters:
* A0 <= Pointer to struct kvm_vcpu_arch
*/
SYM_FUNC_START(__kvm_riscv_switch_to)
SAVE_HOST_GPRS
SAVE_HOST_AND_RESTORE_GUEST_CSRS .Lkvm_switch_return
RESTORE_GUEST_GPRS
/* Resume Guest using SRET */
sret
That sret is chapter 19’s hyp_enter, with a swap of the host’s and guest’s register files around it (SAVE_HOST_GPRS, RESTORE_GUEST_GPRS) that ember skipped because hyp_lab never returns: HS had nothing in its registers worth keeping. Exercise (e) lists what else KVM does that chapter 19 did not need to.
Exits: the two this part uses
The exit reasons are a long list (kvm.h:152-195, 0 to 43 at the tag). This part uses two.
KVM_EXIT_SYSTEM_EVENT (24) is the guest asking the platform to stop, restart or suspend. On RISC-V it is not a special instruction; it is an SBI call. The SBI is chapter 18’s and the system-reset call chapter 19’s: a7 = 0x53525354, a6 = 0 for sbi_system_reset, a0 = 0 for shutdown. KVM, not the VMM, is the SBI implementation the guest sees. Its table lists the extensions it implements, and the first entries are the ones a Linux guest needs from its firmware:
// linux v7.2.8, arch/riscv/kvm/vcpu_sbi.c:36-64
static const struct kvm_riscv_sbi_extension_entry sbi_ext[] = {
{
.ext_idx = KVM_RISCV_SBI_EXT_V01,
.ext_ptr = &vcpu_sbi_ext_v01,
},
{
.ext_idx = KVM_RISCV_SBI_EXT_MAX, /* Can't be disabled */
.ext_ptr = &vcpu_sbi_ext_base,
},
{
.ext_idx = KVM_RISCV_SBI_EXT_TIME,
.ext_ptr = &vcpu_sbi_ext_time,
},
{
.ext_idx = KVM_RISCV_SBI_EXT_IPI,
.ext_ptr = &vcpu_sbi_ext_ipi,
},
{
.ext_idx = KVM_RISCV_SBI_EXT_RFENCE,
.ext_ptr = &vcpu_sbi_ext_rfence,
},
{
.ext_idx = KVM_RISCV_SBI_EXT_SRST,
.ext_ptr = &vcpu_sbi_ext_srst,
},
{
.ext_idx = KVM_RISCV_SBI_EXT_HSM,
.ext_ptr = &vcpu_sbi_ext_hsm,
},
An ecall from VS arrives at the EXC_SUPERVISOR_SYSCALL case above and goes to kvm_riscv_vcpu_sbi_ecall, which finds the extension by the value of a7 and calls its handler. The SRST handler, for shutdown:
// linux v7.2.8, arch/riscv/kvm/vcpu_sbi_replace.c:157-162
case SBI_EXT_SRST_RESET:
switch (type) {
case SBI_SRST_RESET_TYPE_SHUTDOWN:
kvm_riscv_vcpu_sbi_system_reset(vcpu, run,
KVM_SYSTEM_EVENT_SHUTDOWN,
reason);
kvm_riscv_vcpu_sbi_system_reset stops every vCPU and writes the exit into the shared page:
// linux v7.2.8, arch/riscv/kvm/vcpu_sbi.c:150-169
void kvm_riscv_vcpu_sbi_system_reset(struct kvm_vcpu *vcpu,
struct kvm_run *run,
u32 type, u64 reason)
{
unsigned long i;
struct kvm_vcpu *tmp;
kvm_for_each_vcpu(i, tmp, vcpu->kvm) {
spin_lock(&tmp->arch.mp_state_lock);
WRITE_ONCE(tmp->arch.mp_state.mp_state, KVM_MP_STATE_STOPPED);
spin_unlock(&tmp->arch.mp_state_lock);
}
kvm_make_all_cpus_request(vcpu->kvm, KVM_REQ_SLEEP);
memset(&run->system_event, 0, sizeof(run->system_event));
run->system_event.type = type;
run->system_event.ndata = 1;
run->system_event.data[0] = reason;
run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
}
ndata is 1, data[0] is the reset reason from a1. The handler sets retdata->uexit (it is the line after the call at vcpu_sbi_replace.c:163), which makes kvm_riscv_vcpu_sbi_ecall return 0 and KVM_RUN return to userspace without advancing sepc. The guest’s registers stay as they were at the ecall: the VMM can read a7, a6 and t1 after the exit and finds the same values hyp_trap found in the trap frame in chapter 19.
This is why the guest needs no firmware of its own. The host kernel runs on OpenSBI (QEMU’s default firmware for virt; chapter 19’s ember ran with -bios none and was its own firmware); the guest has KVM, which answers its ecalls itself.
KVM_EXIT_MMIO (6) is the device exit and chapter 21’s subject. Its payload in kvm_run and the code that fills it:
// linux v7.2.8, include/uapi/linux/kvm.h:274-280
/* KVM_EXIT_MMIO */
struct {
__u64 phys_addr;
__u8 data[8];
__u32 len;
__u8 is_write;
} mmio;
// linux v7.2.8, arch/riscv/kvm/vcpu_insn.c:598-616
/* Update MMIO details in kvm_run struct */
run->mmio.is_write = true;
run->mmio.phys_addr = fault_addr;
run->mmio.len = len;
/* Try to handle MMIO access in the kernel */
if (!kvm_io_bus_write(vcpu, KVM_MMIO_BUS,
fault_addr, len, run->mmio.data)) {
/* Successfully handled MMIO access in the kernel so resume */
vcpu->stat.mmio_exit_kernel++;
kvm_riscv_vcpu_mmio_return(vcpu, run);
return 1;
}
/* Exit to userspace for MMIO emulation */
vcpu->stat.mmio_exit_user++;
run->exit_reason = KVM_EXIT_MMIO;
return 0;
kvm_io_bus_write first offers the access to devices that live inside the kernel; only if none claims it does KVM_RUN return with KVM_EXIT_MMIO. When the VMM resumes the vCPU after a read, kvm_arch_vcpu_ioctl_run completes the load with the bytes the VMM wrote into run->mmio.data before re-entering the guest:
// linux v7.2.8, arch/riscv/kvm/vcpu.c:872-876
switch (run->exit_reason) {
case KVM_EXIT_MMIO:
/* Process MMIO value returned from user-space */
ret = kvm_riscv_vcpu_mmio_return(vcpu, vcpu->run);
break;
This chapter’s loop prints an MMIO exit and gives up; exercise (b) provokes one.
What this VMM does not do, and where it runs
It injects no interrupts, and no lab in this part does (chapter 22’s guest driver polls; injection, through hvip on the hardware and an ioctl chapter 21 names, is Part V’s and Part VII’s). It starts one vCPU, loads no kernel and no device tree, and does not handle KVM_EXIT_RISCV_SBI, the exit KVM uses for extensions it forwards rather than implements. The H-extension has to be present: make doctor checks that this host’s QEMU accepts -cpu rv64,h=true, and a host without it fails there, not as a hang here. The lab needs no KVM on the machine you run it on, only QEMU with h=true: the KVM is the one in the QEMU-booted Linux, built with CONFIG_KVM=y, and the first line of its output is the check that it worked, /dev/kvm existing in that host. Without it the VMM dies on open and the diff fails; there is no skip path. The documented skip for a machine without KVM (spec §3) is Part V’s, where wick runs on the real host.
Walkthrough
The initramfs’s init is the chapter 15 shape: mount /proc, /sys, devtmpfs, quiet the kernel’s console with dmesg -n 1, and run the lab between two sentinel lines. The test for /dev/kvm is one line of output, and /vmm is the program below, given the payload.
mount -t proc proc /proc
mount -t sysfs sysfs /sys
mount -t devtmpfs devtmpfs /dev 2>/dev/null
dmesg -n 1
echo '=== lab begin'
[ -c /dev/kvm ] && echo /dev/kvm
/vmm /payload.bin
echo "vmm rc=$?"
echo '=== lab end'
poweroff -f
kvm_open opens the device and refuses any API version but 12, as the documentation said to.
static int kvm_open(void)
{
int kvm = open("/dev/kvm", O_RDWR | O_CLOEXEC);
if (kvm < 0) die("open /dev/kvm");
int api = ioctl(kvm, KVM_GET_API_VERSION, 0);
if (api != 12) { fprintf(stderr, "vmm: api %d\n", api); exit(1); }
printf("vmm: KVM_GET_API_VERSION %d\n", api);
return kvm;
}
vm_memory is gmap’s replacement. A 2 MiB anonymous mapping becomes slot 0 at guest-physical 0x80000000, where virt’s RAM starts; the payload is position-independent, so any address would do. The guest-physical address has its low 21 bits clear; mmap promises only page alignment for the host address, so the documentation’s recommendation that both addresses agree in their low 21 bits (so the host can back the slot with large pages) is not guaranteed, which costs nothing for a 2 MiB test slot. The function returns the host pointer: the VMM writes the guest’s code and reads its data through it.
/* Guest-physical memory is a host mapping handed to KVM with a slot:
* KVM fills the G-stage from this slot on guest-page faults. */
static void *vm_memory(int vm)
{
void *mem = mmap(NULL, GUEST_SIZE, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (mem == MAP_FAILED) die("mmap");
struct kvm_userspace_memory_region r = {
.slot = 0, .flags = 0,
.guest_phys_addr = GUEST_BASE,
.memory_size = GUEST_SIZE,
.userspace_addr = (uint64_t)(uintptr_t)mem,
};
if (ioctl(vm, KVM_SET_USER_MEMORY_REGION, &r) < 0) die("KVM_SET_USER_MEMORY_REGION");
printf("vmm: memory slot 0: 0x%lx bytes at gpa 0x%lx\n", GUEST_SIZE, GUEST_BASE);
return mem;
}
core_id, vcpu_set_reg and vcpu_get_reg are the id encoding of the Mechanism section in code. A register value passes by address, and the register’s width is in the id, so one pair of functions covers every core register.
/* One RISC-V core register by its index in struct kvm_riscv_core
* (asm/kvm.h: KVM_REG_RISCV_CORE_REG); api.rst: 0x8030 0000 02 <index>. */
static uint64_t core_id(unsigned long index)
{
return KVM_REG_RISCV | KVM_REG_SIZE_U64 | KVM_REG_RISCV_CORE | index;
}
static void vcpu_set_reg(int vcpu, unsigned long index, unsigned long val)
{
struct kvm_one_reg r = { .id = core_id(index), .addr = (uint64_t)(uintptr_t)&val };
if (ioctl(vcpu, KVM_SET_ONE_REG, &r) < 0) die("KVM_SET_ONE_REG");
}
static unsigned long vcpu_get_reg(int vcpu, unsigned long index)
{
unsigned long val = 0;
struct kvm_one_reg r = { .id = core_id(index), .addr = (uint64_t)(uintptr_t)&val };
if (ioctl(vcpu, KVM_GET_ONE_REG, &r) < 0) die("KVM_GET_ONE_REG");
return val;
}
vcpu_run_until_exit is KVM_RUN with a switch on the exit reason, wrapped in a loop that chapter 21 makes iterate (every case here returns). It accepts one outcome, a shutdown system event, and every other exit is a failure with a message. A lab that returned success after any KVM_RUN would pass even if the guest never ran. The KVM_EXIT_MMIO case prints what a device model will need, the direction, the address and the width, and refuses; chapter 21 replaces that case.
/* Run until the guest stops. Any exit but a shutdown system event is a
* failure here: chapter 21 is where MMIO exits become a device. */
static int vcpu_run_until_exit(int vcpu, struct kvm_run *run)
{
for (;;) {
if (ioctl(vcpu, KVM_RUN, 0) < 0) die("KVM_RUN");
switch (run->exit_reason) {
case KVM_EXIT_SYSTEM_EVENT:
printf("vmm: KVM_RUN exit %u (KVM_EXIT_SYSTEM_EVENT) type %u (%s) ndata %u\n",
run->exit_reason, run->system_event.type,
run->system_event.type == KVM_SYSTEM_EVENT_SHUTDOWN ? "SHUTDOWN" : "other",
run->system_event.ndata);
return run->system_event.type == KVM_SYSTEM_EVENT_SHUTDOWN ? 0 : 1;
case KVM_EXIT_MMIO:
printf("vmm: KVM_RUN exit %u (KVM_EXIT_MMIO) %s gpa 0x%llx len %u: no device here\n",
run->exit_reason, run->mmio.is_write ? "write" : "read",
run->mmio.phys_addr, run->mmio.len);
return 1;
default:
printf("vmm: KVM_RUN exit %u: unexpected\n", run->exit_reason);
return 1;
}
}
}
main is the sequence of the figure: open, create the VM, register the memory, copy the payload to the start of the slot, create the vCPU (the helper also maps kvm_run; its code is vmm.c’s vcpu_create, not a listing because it is three checked calls), set pc to the slot’s base, a0 to the data page’s guest-physical address (the same two things sepc and hyp_enter’s argument carried in chapter 19) and mode to S, run, then read a7, a6 and t1 back and the data page directly from the slot. The verdict needs both halves: the exit must be a shutdown, and the data page must hold the word the guest stored. The payload size in the capture is the file’s: 0x2c, the same eleven instructions chapter 19 counted.
Exercises
Each was run on straylight (QEMU 11.1.1, the lab’s kernel and initramfs) in a scratch copy of labs/ch20/, one edit at a time.
(a) Remove the mode register write and run. Then set mode to KVM_RISCV_MODE_U and run. What happens, and why?
Answer
Without the write, the run is the capture, byte for byte: the lab’s diff passes. (The mode=S line is the VMM’s own printf, so the text does not change; the guest’s behaviour is what matters, and it still reaches the shutdown with t1=0x600d5eed.) KVM’s reset path already put the vCPU in S:
// linux v7.2.8, arch/riscv/kvm/vcpu.c:74-74
cntx->sstatus = SR_SPP | SR_SPIE;
// linux v7.2.8, arch/riscv/kvm/vcpu.c:76-78
cntx->hstatus |= HSTATUS_VTW;
cntx->hstatus |= HSTATUS_SPVP;
cntx->hstatus |= HSTATUS_SPV;
SR_SPP is the sstatus.SPP bit that KVM_RISCV_MODE_S would have set, and HSTATUS_SPV is the other half of chapter 19’s sret contract, so the explicit write is redundant; the VMM keeps it so that the lab does not depend on a default.
With KVM_RISCV_MODE_U (mode = 0, clearing SPP) the run changes: KVM_RUN does not return. Observed: the output stops after the pc= line and QEMU is killed by timeout (25 s in this run). The source shows where the guest could go: the guest enters VU, its ecall is cause 8, and KVM’s default hedeleg delegates that cause to the guest, where chapter 19 set hedeleg = 0:
// linux v7.2.8, arch/riscv/kvm/vcpu_config.c:9-15
#define KVM_HEDELEG_DEFAULT (BIT(EXC_INST_MISALIGNED) | \
BIT(EXC_INST_ILLEGAL) | \
BIT(EXC_BREAKPOINT) | \
BIT(EXC_SYSCALL) | \
BIT(EXC_INST_PAGE_FAULT) | \
BIT(EXC_LOAD_PAGE_FAULT) | \
BIT(EXC_STORE_PAGE_FAULT))
(EXC_SYSCALL is cause 8, an ecall from U or VU.) So the guest traps into its own kernel at vstvec, which is 0, and nothing there is backed by a slot. Only the hang was observed; the loop through vstvec is what the source implies, not something the run printed. The point of the exercise is the contrast with chapter 19: a VU ecall is a trap the hypervisor can hand to the guest, and a VS ecall, the one the payload makes from S, cannot be (chapter 18: hedeleg bits 9 to 11 are read-only zero), which is why the shutdown call reaches KVM at all.
(b) Point a0 at 0x90000000, outside the slot. What exit arrives, and what does vcpu_insn.c put in it?
Answer
Observed:
vmm: KVM_RUN exit 6 (KVM_EXIT_MMIO) write gpa 0x90000000 len 8: no device here
vmm: guest a7=0x0 a6=0x0 t1=0x0
vmm: data page holds 0x0
vmm: FAIL
vmm rc=1
(The pc=... a0=... line above it still prints 0x80001000: it prints the constant the lab means to set, not the register.) The payload’s first memory access is sd t0, 0(a0), a store to a guest-physical address no slot covers. That is a store guest-page fault (code 23) into HS, gstage_page_fault finds no host address for the page and routes a store to kvm_riscv_vcpu_mmio_store (vcpu_exit.c:30-38), which decodes the 8-byte store, sets run->mmio.is_write, phys_addr and len (vcpu_insn.c:599-601, quoted in the Mechanism section), offers it to in-kernel devices, and, finding none, sets KVM_EXIT_MMIO. a7 and t1 read 0 because the guest never got past the store: t1 is loaded after it. The data page is 0 because the VMM zero-filled it by mmap and nothing wrote to it.
(c) Read the vCPU’s satp through KVM_REG_RISCV_CSR and print it after the exit. What is it, and what did chapter 19 write to the equivalent register?
Answer
Add after the run:
unsigned long satp = 0xdead;
struct kvm_one_reg r = {
.id = KVM_REG_RISCV | KVM_REG_SIZE_U64 | KVM_REG_RISCV_CSR |
KVM_REG_RISCV_CSR_GENERAL | KVM_REG_RISCV_CSR_REG(satp),
.addr = (uint64_t)(uintptr_t)&satp,
};
ioctl(vcpu, KVM_GET_ONE_REG, &r);
printf("vmm: guest satp=0x%lx\n", satp);
Observed: vmm: guest satp=0x0. satp here is the guest’s: struct kvm_riscv_csr (asm/kvm.h) lists sstatus to satp in the order of KVM’s saved VS-level registers (struct kvm_vcpu_csr, kvm_host.h:148-160, where the ninth field, satp’s slot, is vsatp), and kvm_arch_vcpu_put (vcpu.c:681) reads the hart’s vsatp into that field. Zero is Bare: the guest never enabled translation, so the VS-stage did nothing. It is the value chapter 19’s hyp_lab wrote to vsatp by hand; here a fresh vCPU starts with it (the reset memset of the CSR block, vcpu.c:64).
(d) Change the payload’s SBI extension id from SRST to an id KVM does not implement (0x12345678). What does the VMM see, and what did chapter 19 do with the same ecall?
Answer
Observed: the run hangs. The output stops after the pc= line, KVM_RUN never returns, and QEMU is killed by timeout. KVM looks the extension up, finds nothing, and answers the guest itself:
// linux v7.2.8, arch/riscv/kvm/vcpu_sbi.c:609-613
} else {
/* Return error for unsupported SBI calls */
cp->a0 = SBI_ERR_NOT_SUPPORTED;
goto ecall_done;
}
SBI_ERR_NOT_SUPPORTED goes into the guest’s a0, ecall_done adds 4 to sepc (vcpu_sbi.c:642-644), and the guest resumes after its ecall, at the payload’s j 1b, where it spins. No exit happens, because nothing in the path asks for one. The same edit under chapter 19’s ember (make lab CH=19 in a scratch copy on talos, payload changed to li a7, 0x12345678) prints H: VS ecall ext=0x12345678 fid=0x0 type=0x0 and the rest of the capture, PASS included: hyp_trap takes any VS ecall for the exit and never looks at a7 to decide. KVM treats the SBI as a contract it implements, one extension id at a time; chapter 19’s handler was a shutdown button.
(e) List what chapter 19 did that this VMM did not have to do, and name the file under arch/riscv/kvm/ or the layer below it that does each.
Answer
Four things, and one line each for where they went.
M-mode setup. Chapter 19’s gated medeleg branch and the PMP window from drop.c were the machine-mode half of the job. In this lab OpenSBI, QEMU’s default firmware for virt, does both before Linux starts; its boot banner lists the PMP-protected regions it set up, and KVM’s host side runs at HS with that delegation in place and adds only the guest-facing half: kvm_arch_enable_virtualization_cpu zeroes hedeleg and hideleg (kvm/main.c:44-45), and each vCPU load writes that vCPU’s own values (vcpu_config.c:76-94). The M-mode half is not in arch/riscv/kvm/.
The G-stage. gmap’s table, with U on every leaf, is mmu.c and gstage.c: kvm_riscv_mmu_alloc_pgd for the root, kvm_riscv_mmu_map and kvm_riscv_gstage_map_page for the leaves, filled on guest-page faults rather than up front.
The hgatp write and hfence.gvma. Chapter 19 required the fence after changing hgatp’s mode. KVM writes hgatp in kvm_riscv_mmu_update_hgatp (mmu.c:709-722) and, when the hart has no VMID bits, fences through kvm_riscv_local_hfence_gvma_all in tlb.c, which is chapter 19’s hfence.gvma zero, zero:
// linux v7.2.8, arch/riscv/kvm/tlb.c:75-78
void kvm_riscv_local_hfence_gvma_all(void)
{
asm volatile(HFENCE_GVMA(zero, zero) : : : "memory");
}
(With VMID bits, which KVM uses to tag translations per VM, the fence is needed less often; vmid.c manages the tags.)
The trap frame. trap_entry and struct trapframe were chapter 5’s, reused. KVM’s equivalent is vcpu_switch.S: __kvm_riscv_switch_to saves the host’s registers, restores the guest’s, and srets (quoted above), and the guest’s trap comes back to the label that follows. The difference is the one the quote’s comment shows: KVM has two register files to keep apart, a host’s and a guest’s, and chapter 19 had one.
(f) Place KVM on chapter 14’s three axes for two guests of one host, and compare with chapter 19’s answer.
Answer
Shared. Two guests of one host share no guest-physical memory with each other: kvm_arch_init_vm allocates a G-stage root per VM (vm.c:31-36), and each guest’s slot is a separate mapping in its own VMM process. What each guest does share is the kernel under it and, with its own VMM, the slot’s pages: this lab’s VMM reads the guest’s data page through its own mapping with no copy. Chapter 19’s guest shared the page with HS the same way, through the identity map.
TCB. The code whose bug breaks the isolation is the hardware, the host kernel with KVM in it (chapter 15’s whole Linux: a monolith, with CONFIG_KVM=y) and the VMM process for what it is allowed to do to its guest. KVM runs at HS in the kernel’s address space, so a bug in any driver of that kernel is in the guests’ TCB. Chapter 19’s was ember’s image, with nothing under it but the firmware. This is the line chapter 14 drew between wick, which has a host kernel, and hearth, which does not.
Copy. The guest’s memory is not copied on the way to the VMM; the VMM already has it mapped. A device access is the copy: an MMIO exit hands the VMM up to eight bytes through run->mmio.data and takes the answer back through the same field (chapter 21), one trap per register access. Chapter 19 had no such boundary because it had no device. What the chapter 14 budget says of the pair: KVM spends more on trusted (a kernel) to spend less on writing a hypervisor (an ioctl set), and the copy it cannot avoid is per device access, not per page.
Lab
make lab CH=20
make lab CH=20 IMPL=mine
labs/ch20/build.sh is chapter 15’s recipe with three changes: the cache is ~/.cache/hp/ch20/, scripts/config --enable KVM follows the defconfig step, and the initramfs is BusyBox plus every file in an overlay directory the caller names. defconfig at this tag has CONFIG_KVM=m, and a module needs a /lib/modules tree that the initramfs would have to carry; =y puts KVM in the Image. The kernel is built a second time because chapter 15’s has no KVM, and it is built once more for the three KVM chapters together: chapters 21 and 22 call labs/ch20/build.sh with their own overlay and output directories and reuse the cache. The script also runs make headers_install into ~/.cache/hp/ch20/hdr/, and the Makefile compiles the VMM with -I$(CACHE)/hdr/include: the VMM is built against the kernel it runs on, not against the host’s linux-headers package. One header detail is worth knowing: the installed asm/kvm.h uses offsetof without including <stddef.h>, so vmm.c includes it first.
ember/payload.S is built by make -C ../../ember HP_CH=19 build/payload.bin and copied into the overlay: the bytes chapter 19 embeds are the bytes the VMM loads. The VMM is labs/ch20/vmm.c, compiled static with the host’s cross compiler (riscv64-linux-gnu- or riscv64-unknown-linux-gnu-, found the way chapter 15 finds it), and the Makefile rebuilds it on every run because IMPL changes its source file without changing either file’s modification time.
Timings, measured on 2026-09-30: on straylight the cold start (clone both trees, build the KVM kernel and BusyBox) took 247 s, and a warm make lab CH=20 takes 11 to 12 s. On talos, with 8 build jobs, the kernel build alone took 933 s; the rest of the first run (headers, BusyBox, payload, boot) took 86 s, and a warm run takes 16 s. The first run on a new host is the long one; every later chapter run and every run of chapters 21 and 22 starts from the cache.
IMPL=mine replaces vm_memory’s body with printf("MINE: memory slot stub\n"); exit(1);: the chapter’s job is the slot, and the stub is the failing version of it. The run diverges there:
/dev/kvm
vmm: KVM_GET_API_VERSION 12
-vmm: memory slot 0: 0x200000 bytes at gpa 0x80000000
-vmm: payload 0x2c bytes at gpa 0x80000000, data page at gpa 0x80001000
-vmm: pc=0x80000000 a0=0x80001000 mode=S
-vmm: KVM_RUN exit 24 (KVM_EXIT_SYSTEM_EVENT) type 1 (SHUTDOWN) ndata 1
-vmm: guest a7=0x53525354 a6=0x0 t1=0x600d5eed
-vmm: data page holds 0x600d5eed
-vmm: PASS
-vmm rc=0
+MINE: memory slot stub
+vmm rc=1
(the diff of capture.txt against the run). Writing mmap and KVM_SET_USER_MEMORY_REGION is the lab; /dev/kvm and the API version line, which come before it, still match.
With the reference the capture is:
=== lab begin
/dev/kvm
vmm: KVM_GET_API_VERSION 12
vmm: memory slot 0: 0x200000 bytes at gpa 0x80000000
vmm: payload 0x2c bytes at gpa 0x80000000, data page at gpa 0x80001000
vmm: pc=0x80000000 a0=0x80001000 mode=S
vmm: KVM_RUN exit 24 (KVM_EXIT_SYSTEM_EVENT) type 1 (SHUTDOWN) ndata 1
vmm: guest a7=0x53525354 a6=0x0 t1=0x600d5eed
vmm: data page holds 0x600d5eed
vmm: PASS
vmm rc=0
=== lab end
It pins the exit reason (24) and system-event type (1), the registers the guest set (a7, a6, t1) and the data word; it refuses KVM_GET_VCPU_MMAP_SIZE, any address the host or the kernel chose, and the kernel’s boot messages (dmesg -n 1 before the begin sentinel). Two runs on straylight are byte-identical to each other and to capture.txt; the local run on talos matches too.
Further reading
Documentation/virt/kvm/api.rstat the pinned tag: §4.1, §4.2, §4.7, §4.10, §4.35, §4.68, §4.69 and thekvm_runstructure at the end.arch/riscv/kvm/at the same tag: the files the lab quotes arevcpu_exit.c,vcpu_sbi.c,vcpu_sbi_replace.c,vcpu_insn.c,mmu.c,gstage.c,vcpu_switch.Sandvcpu_onereg.c.- RISC-V Supervisor Binary Interface Specification, release 3.0: the System Reset Extension, the call the payload makes.
- Firecracker: Lightweight Virtualization for Serverless Applications (Agache et al., NSDI 2020): a minimal VMM over this ioctl set, the shape
wicktakes.