
Recall first from Building, tracing and a full device
- Kconfig selects the device and Meson compiles its source into the target.
- HMP info qtree shows the instantiated device and info mtree shows its mapped region.
- A write to SCRATCH raises a level interrupt and a write of one to STATUS clears it.
Where KVM runs
3 min readThe last lessons used QEMU, but QEMU is only the userspace half. This lesson answers how the kernel half, KVM, exposes hardware virtualization through /dev/kvm and its ioctls.
Suppose a QEMU launch configured to use KVM fails at startup. You want to know whether the process could open /dev/kvm, whether it accepted the kernel's API version, and whether it could create a VM. Each of those operations can succeed or fail independently. The Linux KVM API documentation describes exactly which calls perform them and what each call returns. That lets you locate the failure before investigating the guest image or its devices. Linux KVM API documentation
KVM stands for Kernel-based Virtual Machine. It runs inside the host Linux kernel and uses the host processor's virtualization features to execute guest code. On x86, when KVM is built as loadable modules, kvm.ko provides the common KVM infrastructure. The CPU-specific module is kvm-intel.ko for Intel or kvm-amd.ko for AMD. These modules support the respective Intel VT-x and AMD-V hardware facilities. The exact files visible on a system depend on its kernel build and packaging. A kernel can also build the relevant code in, so a loaded-module listing alone is insufficient to determine whether KVM is available.
The Linux source tree places the arm64 implementation under arch/arm64/kvm and the RISC-V implementation under arch/riscv/kvm. These are source directories, and a userspace program on either architecture still uses /dev/kvm when the host kernel provides a working KVM interface. For an embedded target, the existence of an architecture implementation in the source tree tells you that Linux has code for that architecture. Using it on a specific board also depends on the CPU, the virtualization facilities available to Linux, and the kernel configuration.
A host program that uses KVM to create and manage virtual machines and provides the userspace components of the virtual machine. QEMU in KVM mode, Firecracker, and Cloud Hypervisor are examples. The VMM selects the machine configuration and provides its userspace device models. KVM performs the kernel operations that require access to the virtualization hardware. For example, the VMM can present a virtual serial device while KVM provides the facilities for executing the guest CPU. The two components cooperate to run one guest.
The process opening /dev/kvm is on the host side of the API. If Ubuntu is running inside a VM, that Ubuntu instance must itself have access to hardware virtualization for KVM to work there. The outer hypervisor determines whether the required facilities are exposed to the inner system. On WSL2 or in a VM, use the environment in which the VMM would actually run when checking for the device. A result from another Linux instance describes that instance's kernel and device access.
From the device path to a system descriptor
3 min readA C program typically starts with open("/dev/kvm", O_RDWR | O_CLOEXEC). O_RDWR requests read and write access. O_CLOEXEC asks Linux to close this descriptor if the process later successfully executes a new program. A successful open returns a nonnegative integer, including possibly zero. On failure it returns -1 and sets errno. Opening the device establishes access to the KVM system descriptor. The program can use that descriptor to query KVM or ask it to create a VM. open(2)
A quick inspection on Ubuntu is ls -l /dev/kvm. When the node exists, the listing lets you see its type, permissions, owner, and group. Those details help explain an open failure, but the listing does not perform the open in the VMM's process. If an actual open reports ENOENT for this path, investigate device availability in that environment. If it reports EACCES, investigate whether the process has permission to open the device. Keep the error attached to the call that produced it. A program that failed to open the device has no valid system descriptor on which to issue a KVM query.
The KVM interface mainly consists of KVM_* requests issued through ioctl. In C, <sys/ioctl.h> declares ioctl, and <linux/kvm.h> supplies the KVM request constants and API declarations. An ioctl names the operation with a request constant and identifies its target with a file descriptor. For example, ioctl(kvm_fd, KVM_GET_API_VERSION, 0) asks for the API version using the system descriptor. The third argument is zero because this request takes no input. Other requests use that position for a value or a pointer as defined by the individual request. Read the request's contract to determine its arguments and the meaning of its result. ioctl(2)
KVM_GET_API_VERSION returns the KVM API version, whose documented stable value is 12. A program checks for a syscall error and then compares the successful result with KVM_API_VERSION from <linux/kvm.h>. A syscall failure gives the program an errno to report. A successful call that returns an unexpected version gives it a version mismatch to report. That distinction matters because errno is meaningful here after a failed call. A matching version establishes that the kernel reports the expected base API. Support for optional features is a separate question covered later in the module.
Which descriptor each request uses
3 min readOnce the version check succeeds, the VMM can issue ioctl(kvm_fd, KVM_CREATE_VM, 0). The final zero selects the default machine type. On success, the return value is a new VM descriptor, which the program can store as vm_fd. The descriptor returned by open remains available for system-wide KVM operations. Issuing KVM_CREATE_VM again on that system descriptor can create another VM with its own descriptor. A VMM with multiple VMs can therefore use the appropriate vm_fd to direct subsequent requests to a particular machine.
KVM_GET_VCPU_MMAP_SIZE also uses the system descriptor. A call such as ioctl(kvm_fd, KVM_GET_VCPU_MMAP_SIZE, 0) returns the size in bytes to use when mapping the shared vCPU run area. The query can run before any vCPU is created, and it can also run before VM creation. Use the returned length. The kernel's documented size covers the mapping, so using the C expression sizeof(struct kvm_run) would answer a different question about the size of a structure in the userspace headers.
KVM_CREATE_VCPU uses the VM descriptor. For example, ioctl(vm_fd, KVM_CREATE_VCPU, 0) requests a vCPU with ID zero in that VM, as in a minimal x86 setup. This time, the final zero is a vCPU ID. The earlier zero in KVM_CREATE_VM selected a machine type, and the zero in the size query supplied no input. Reading three calls with the same last argument can make them look interchangeable. The request name and its descriptor give that argument its meaning. On success, KVM_CREATE_VCPU returns a new vCPU descriptor. The returned descriptor value is allocated by Linux and is independent of the vCPU ID passed to the request.
Suppose you are reviewing a VMM startup trace. A nonnegative return from KVM_CREATE_VM is a descriptor, while a positive return from KVM_GET_VCPU_MMAP_SIZE is a byte count. Even when two requests return integers, they can report different kinds of results. Save the three descriptors in separately named variables and keep the mapping length in its own variable. Check calls for failure before passing their results to subsequent operations. This makes it possible to diagnose a wrong-descriptor error by looking at which earlier call produced the value.
The relationship between the size query and the vCPU descriptor is easiest to see by naming both operations involved. The system ioctl supplies the length. A later mmap uses that length and the vCPU descriptor to obtain access to the shared run area. In this lesson, the important distinction is what the mapping refers to. It is the shared KVM run area for a vCPU. The VMM configures guest RAM separately. mmap(2)
The four requests establish the API version, a VM handle, the run mapping length, and a vCPU handle. When recording a startup result, write down the request, the descriptor it targeted, and what its return value means. That gives you enough information to tell whether the VMM reached vCPU creation and to identify which earlier result a failing call depended on.
The next lesson, VM, VCPU and guest memory, starts with the objects identified by these descriptors and explains how the VMM supplies the memory the guest will use.
Key takeaways
- KVM implements hardware virtualization in the Linux kernel, and a userspace VMM constructs and manages the virtual machine.
- Opening /dev/kvm returns a system descriptor used for system-level KVM requests.
- KVM_CREATE_VM and KVM_CREATE_VCPU return new descriptors for the objects they create.
- KVM_GET_VCPU_MMAP_SIZE returns the byte length used to map the shared vCPU run area.
Reflect
- Explain to a colleague, in two sentences: identify the KVM kernel components on x86, arm64, and RISC-V.
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
- Kernel documentationThe Definitive KVM API Documentation
- Man pageopen(2): open a file
- Man pageioctl(2): control a device
- Man pagemmap(2): map files or devices into memory
Official documentation first. Links checked when the lesson was published.