
Recall first from KVM on ARM and the EL2 design
- Linux needs access to EL2 at boot to provide ARM KVM, even when the host kernel later runs at EL1 in non-VHE mode.
- With VHE, the host kernel runs at EL2 while the guest kernel and guest applications run at EL1 and EL0.
- Stage-2 translation governs guest physical memory access, and the vGIC presents virtual interrupts to the guest.
Set the first vCPU's register state
4 min readThe last lesson set up the ARM design. This lesson answers the KVM_SET_ONE_REG API and PSCI, which boots and powers guest CPUs.
A VMM can load an AArch64 instruction into guest RAM and still fail to execute it. KVM needs the guest instruction address in the vCPU's program counter and the correct execution state in PSTATE. The KVM API documentation defines the two operations involved. KVM_ARM_VCPU_INIT initializes a vCPU for a selected CPU target, and KVM_SET_ONE_REG writes a specific register on that vCPU.
Start by opening /dev/kvm and using KVM_CHECK_EXTENSION with KVM_CAP_ONE_REG on the KVM file descriptor. A positive result reports support for the one-register interface. Zero reports that the capability is unavailable, and a failed ioctl requires its own error handling. The capability applies to the interface as a whole. To discover the IDs exposed by a particular initialized vCPU, use KVM_GET_REG_LIST on its file descriptor. The list takes a count and space for that many IDs. If the space is insufficient, KVM reports E2BIG and fills in the required count, which the VMM can use to allocate space and retry.
Create the VM, query KVM_ARM_PREFERRED_TARGET on the VM file descriptor, and use the returned struct kvm_vcpu_init as the starting configuration. Then create the vCPU with KVM_CREATE_VCPU and pass the configuration to KVM_ARM_VCPU_INIT on the vCPU file descriptor. The KVM_ARM_VCPU_* feature constants used with this structure identify bit positions in its features array. For example, KVM_ARM_VCPU_PSCI_0_2 requests PSCI 0.2 or later, and KVM_ARM_VCPU_POWER_OFF requests a powered-off initial state. The first vCPU in the UART lab starts powered on. Set its initial register values after initialization so the initialization reset precedes your writes.
Both KVM_SET_ONE_REG and KVM_GET_ONE_REG take a struct kvm_one_reg. Its id selects the register, and addr contains the userspace address of a buffer that holds the value. For a 64-bit register, point addr at a uint64_t. A set reads from that buffer, and a get writes to it. Keep the buffer valid for the duration of the ioctl and check the return value before using a read or assuming a write succeeded.
An ARM64 register ID combines the architecture tag KVM_REG_ARM64, a size tag such as KVM_REG_SIZE_U64, a register group, and a selector within that group. KVM_REG_ARM_CORE covers the general-purpose registers, including x0 through x30, and other state such as PC and PSTATE. The selector for a core register is its offset in struct kvm_regs, measured in 32-bit words. That unit also applies when the register value itself is 64 bits wide. For PC, this gives the following ID expression.
KVM_REG_ARM64 | KVM_REG_SIZE_U64 | KVM_REG_ARM_CORE |
(offsetof(struct kvm_regs, regs.pc) / sizeof(uint32_t))
Use <linux/kvm.h> from the AArch64 host headers for the KVM types and constants, <stddef.h> for offsetof, and <stdint.h> for the fixed-width types. Use regs.pstate for PSTATE and regs.regs[0] for x0 in the same offset expression. To pass a local uint64_t value to either ioctl, assign (uint64_t)(uintptr_t)&value to addr.
KVM_REG_ARM64_SYSREG selects the system-register space. Its selector encodes the instruction fields Op0, Op1, CRn, CRm, and Op2. For example, MPIDR_EL1 has the encoding S3_0_C0_C0_5. Its guest-visible value identifies a vCPU by affinity, which matters when choosing a PSCI target. The interrupt controller is not accessed through this register interface. For VGICv3 state, Linux documents a separate device interface: use KVM_GET_DEVICE_ATTR and KVM_SET_DEVICE_ATTR on the VGIC device file descriptor with the documented groups, such as KVM_DEV_ARM_VGIC_GRP_CPU_SYSREGS for CPU interface system registers. The next lesson explains the device itself.
Run an EL1 guest and handle its UART write
4 min readUse a small AArch64 assembly guest with a defined register contract. The host gives it a character in x0 and a UART address in x1. At the entry point, the guest executes strb w0, [x1], then branches to itself with b .. A single byte store lets the VMM implement a transmit-only UART with one register. It also gives you an unambiguous first result when debugging. A successful write proves the guest reached its entry instruction and used the address and character you supplied.
Set the guest entry PC to the aligned guest physical address where you loaded the instructions. This example uses the initialized vCPU's MMU-off reset state, so the guest's instruction and data addresses can be used directly as guest physical addresses. Set PSTATE to AArch64 EL1h with the debug, SError, IRQ, and FIQ masks set. The value is 0x3c5, formed from the EL1h mode value 0x5 and the mask bits 0x3c0. EL1h selects SP_EL1. The two-instruction guest needs no stack. If you add stack accesses, initialize SP_EL1 to a 16-byte-aligned stack top in guest RAM.
Keep assembly in .text and place the entry instruction first. On the AArch64 host, gcc -c guest.S -o guest.o assembles it, and objcopy -O binary -j .text guest.o guest.bin extracts the code for this relocation-free guest. Copy the bytes into the userspace buffer registered with KVM_SET_USER_MEMORY_REGION. Make the UART address fall outside every registered guest RAM slot. A store to a backed RAM address updates memory, while the lab needs a store to an unbacked address so KVM can return it for device emulation. Read back PC, PSTATE, x0, and x1 with KVM_GET_ONE_REG before the first run. Record the values alongside the guest memory layout so an incorrect entry address and an incorrect UART address are easy to distinguish.
Map the vCPU's shared struct kvm_run area before issuing KVM_RUN. Obtain its mapping length with KVM_GET_VCPU_MMAP_SIZE on the KVM file descriptor and map the vCPU file descriptor with MAP_SHARED and read and write protection. In the run loop, handle ioctl failure before inspecting exit_reason. When KVM_RUN succeeds and the reason is KVM_EXIT_MMIO, check that mmio.is_write is set, mmio.phys_addr matches the UART address, and mmio.len is one. The character is in mmio.data[0]. Print that byte and flush the output if you want it to appear immediately. Report any unexpected exit or access with enough information to identify it.
KVM completes the pending MMIO operation when userspace re-enters KVM_RUN. If your only goal is to observe one character, you can end the demo and tear down the VM after handling the exit. For a guest that continues, re-enter KVM and count on the guest's instruction stream to produce the next event. The final b . in the single-byte demo will keep executing if you resume it, so a second UART exit requires another guest store.
Going deeperWhat KVM switches when the guest runs
On guest entry, KVM installs the guest CPU state needed for execution, including guest EL1 system-register state and the EL2 controls that select the guest's stage-2 translation. EL2 returns into the guest with ERET. During this lab's UART store, the stage-2 data abort takes execution from guest EL1 to EL2. The exception records a return address and saved PSTATE in ELR_EL2 and SPSR_EL2. Exception information lets KVM identify and handle the access.
KVM preserves guest state when it takes the vCPU out of execution, including guest system-register values such as translation controls and table bases. It restores host state where needed before host execution uses those registers. The exact save and restore points depend on the host mode and register. With a non-VHE host, the host kernel runs at EL1, so entering the EL2 hypervisor from host EL1 and returning to the host kernel adds exception-level transitions. With VHE, the host kernel can run at EL2 and use the EL2 host register view. That reduces the cost of host-side transitions into and out of the hypervisor code. A guest EL1 access that requires EL2 handling still takes the exception, and an emulated UART access can still reach userspace.
Start a secondary vCPU with PSCI
3 min readthe Power State Coordination Interface, an Arm calling convention for CPU and system power operations supplies the guest's CPU startup request. For a guest using the hvc conduit, an EL1 caller puts the PSCI function ID and arguments in registers and executes hvc #0. With KVM's in-kernel PSCI emulation, an ordinary CPU_ON request is handled inside the kernel. The VMM is responsible for creating and configuring the vCPUs in advance. The guest chooses when to release each secondary.
For a two-vCPU VM, initialize the primary and secondary with KVM_ARM_VCPU_PSCI_0_2, and also set KVM_ARM_VCPU_POWER_OFF on the secondary's initialization configuration. Confirm the secondary's guest-visible affinity by reading its MPIDR_EL1 and extracting the affinity fields. Use the affinity value as the PSCI target, clearing the bits outside those fields. Selecting a target by guest affinity keeps the startup request independent of the physical CPU on which Linux schedules the vCPU thread.
For the AArch64 CPU_ON call, put the 64-bit CPU_ON function ID (PSCI_0_2_FN64_CPU_ON from <linux/psci.h>) in x0, the target affinity in x1, the secondary entry address in x2, and a context value in x3. Use an aligned entry address in guest RAM. Load the secondary code there before running the primary. The primary receives the PSCI return status in its own x0. A successful return means KVM accepted the power-on request. If the target is already on, PSCI reports ALREADY_ON.
On a successful request, KVM arranges reset state for the target vCPU with its PC set to the supplied entry address and its x0 set to the context value. It makes the target runnable and can wake a host thread already waiting to run it. The secondary executes guest instructions when the VMM runs it through its own KVM_RUN. The PSCI return on the primary and arrival at the entry point on the secondary are separate events. Guest software that needs confirmation of secondary initialization can have the secondary signal after it reaches a defined point.
In the UART demo, let the primary issue CPU_ON and then write a distinct success byte to the UART only if it received a successful PSCI status. The host can switch to the secondary's vCPU file descriptor and run mapping after that exit. This sequencing allows a single host thread to demonstrate the handoff. Give the secondary its own entry code that loads the agreed UART address into a register and stores the low byte of its incoming x0 there. The two bytes let you observe both the primary's return status and the secondary's arrival. A secondary that needs a stack or more arguments should establish them in its entry code or retrieve them from guest memory identified by the context value.
KVM starts the secondary at a guest-chosen address. The secondary can begin with a few instructions that use only its boot context, as in this lab. A larger guest also needs interrupt delivery and timekeeping once its CPUs are running. The ARM vGIC and virtual timer explains how KVM supplies those facilities.
Key takeaways
- KVM_ARM_VCPU_INIT selects the vCPU target and features before userspace sets its starting registers.
- ARM64 one-register IDs encode the register width and register group.
- The VMM handles the lab UART write through KVM_EXIT_MMIO.
- KVM handles PSCI CPU_ON in the kernel and starts an existing powered-off vCPU at the supplied entry address.
Reflect
- Explain to a colleague, in two sentences: construct ARM64 one-register IDs for core and system registers.
- 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 documentationKVM API: capabilities, vCPU initialization, and one-register access
- Kernel documentationARM VGICv3: KVM device attributes
- Kernel documentationBooting AArch64 Linux: secondary CPU boot protocol
Official documentation first. Links checked when the lesson was published.