Module 11 · Lesson 23 of 107

The event loop and the vCPU lifecycle

Trace work between QEMU’s event loop and vCPUs, then use the monitor and guest device tree to identify a UART’s MMIO range and interrupt.

  • Beginner to advanced
  • 10 min read
  • 30 min lab
What you will need

Ubuntu 24.04 in WSL2 or a VM, qemu-system-arm, device-tree-compiler, and an ARM64 Linux Image with PL011 console support plus a matching bootable initramfs

Your place in the module
By the end you can 4 objectives
  • Trace an asynchronous completion from submission to guest interrupt delivery
  • Distinguish the TCG cpu_exec loop from the KVM execution loop
  • Match QEMU launch options to the machine, accelerator, and device backends they configure
  • Correlate an emulated UART with its MemoryRegion and interrupt configuration
Video coming soonThe event loop and the vCPU lifecycle
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from Memory regions, IRQ lines and timers
  • A mapped MMIO region dispatches accesses to device callbacks using offsets within the region.
  • A qemu_irq identifies a receiving input, and the device drives that input with a level.
  • A QEMUTimer deadline is an absolute timestamp in the timer's chosen clock domain.
01

How QEMU dispatches host events

4 min read

The last lesson covered the device primitives. This lesson answers how the event loop, bottom halves and vCPU threads share the work, and the key command-line and monitor surfaces.

A KVM vCPU can be inside KVM_RUN while a request arrives at the QEMU monitor. The kernel API describes KVM_RUN as an operation on an individual vCPU file descriptor. QEMU can leave that host thread in the kernel while its main thread receives the monitor input. This distinction matters for device work too. To understand who handles a request, identify both what caused it and which execution context owns its callback. The KVM API

The main loop runs on QEMU's main thread in system emulation. It waits for events such as file descriptor readiness and timer deadlines, then dispatches ready callbacks. QEMU integrates the default GLib main context, a GMainContext, into this loop. GLib sources contribute file descriptors and wait deadlines, and the main loop dispatches ready sources after waiting. QEMU also services its own event sources through this integration. The OS readiness model is straightforward. Given a set of watched descriptors and a timeout, a wait can return when input arrives or the timeout expires. A cross-thread notifier can make a watched descriptor ready so newly scheduled work gets considered promptly. Linux eventfd can provide that notification. poll(2) eventfd(2)

gives code a way to request work after returning from the current call. Scheduling a BH makes it eligible to run when that context is serviced. It can also notify a context that is waiting. Multiple schedules of the same pending BH can coalesce, so code that needs to account for every completion must store those completions separately. The callback can then process the recorded work when it runs.

AIO means asynchronous I/O. A device can submit host I/O and return while the operation is outstanding. The backend eventually reports completion, and QEMU handles the result in the appropriate context. An AioContext groups event handling for work such as descriptor callbacks, timers, and BHs. A BH can carry deferred work whether or not that work was caused by I/O. AIO submission, completion notification, and execution of a completion callback are distinct steps. The exact backend determines how those steps are implemented.

Consider a guest driver that issues a virtual disk request and then waits for its completion. Suppose the device backend submits asynchronous I/O and uses a BH on the main AioContext to process the completion. The vCPU can continue executing after submission. The host I/O finishes, the owning context is notified as needed, and the callback publishes the completion to the guest before raising or requesting an interrupt. If the target vCPU is idle and can take the interrupt, the accelerator can wake it. If it is already executing, it observes the pending interrupt through the accelerator's interrupt handling path. A different device may complete a register access directly on the vCPU thread, during the instruction that caused it.

An asynchronous device completionvCPU threadDevice backendMain contextSubmit devicerequestSchedule completionBHPublish completionRequest interrupt delivery1. vCPU thread → DevicebackendSubmit device request2. Device backend → MaincontextSchedule completion BH3. Main context → MaincontextPublish completion4. Main context → vCPU threadRequest interrupt delivery
One possible asynchronous completion path, using a bottom half in the main AioContext.
Going deeperThe main thread, IOThreads, and shared state

Older QEMU code and discussions use iothread for the main thread that services I/O events. The Big QEMU Lock, or BQL, was historically called the iothread mutex. It serializes access to legacy device and machine state shared by the main thread and vCPU threads. The main loop can release it during its blocking wait, and vCPU threads can execute guest code outside it. A vCPU can acquire the lock for operations that require BQL protection, such as invoking a conventional MMIO device callback. Consequently, an event loop can stay responsive during guest execution and still wait for a vCPU that is holding the BQL.

An IOThread object, created with -object iothread,id=io0, creates a dedicated host thread with its own AioContext. Supported devices or backends must be associated with that thread for their work to run there. It is possible for a device's data path to use an IOThread while its configuration remains coordinated with the main thread. Code servicing an IOThread must synchronize access to shared state according to the device and backend contracts. Merely moving a callback to another context gives it a new execution thread, with the corresponding need for synchronization.

02

What a vCPU thread does

4 min read

System emulation creates CPU objects as the machine is built. -smp determines how many vCPUs the guest starts with and can describe their topology. Each CPU object holds or refers to state such as its architectural registers, pending work, and whether it is halted. The accelerator creates the host execution context. KVM and multi-threaded TCG normally use a host thread per vCPU. Single-threaded TCG can run multiple vCPUs in turn on one host thread. The guest can therefore see multiple CPUs even when QEMU is using a single thread to execute their instructions.

A vCPU execution thread repeatedly checks whether it may run, enters the accelerator's execution path, handles the reason it returned, and checks for work again. In shorthand, this is the accelerator's CPU execution loop, sometimes described as accel->cpu_exec. Read that as a description of the architecture. QEMU's TCG and KVM paths have different entry points and thread loops. A loop can also process work queued for its CPU, wait while idle, or acknowledge a stop request. When the VM resumes, CPUs that are eligible to run reenter the execution path. A halted CPU can remain idle until an event makes it runnable.

For TCG, the thread enters the TCG execution path through a wrapper that calls cpu_exec. Within cpu_exec, QEMU can execute many translated blocks. It checks for conditions that need attention, such as a pending interrupt or a request to exit translated execution. Some guest exceptions are handled inside the CPU execution machinery. Conditions such as a halt, debug stop, or explicit exit request can return control to the surrounding vCPU thread loop. The main loop can request that a vCPU leave translated execution so it can observe a VM state change. Ordinary translated execution and device callbacks can therefore occur during the same call to cpu_exec.

For KVM, the corresponding userspace execution routine is kvm_cpu_exec. It calls the KVM_RUN ioctl for that vCPU. The host kernel enters guest execution on the calling thread and can handle some events in the kernel. When KVM needs userspace service, KVM_RUN can return with an exit reason. For example, QEMU can handle an MMIO exit by looking up the guest physical address, performing the device access, and reentering KVM when appropriate. QEMU generally releases the BQL before entering KVM_RUN and reacquires it for userspace handling that needs it. A kick can prompt a running vCPU to leave guest execution so the thread can respond to queued work or a stop request. It can also wake an idle thread. The KVM API

The vCPU thread loopCheck runstateEnteracceleratorTCG or KVMHandlereturnServicequeued workExit from step 1: CPU idle or stoppedWait for work↻ Repeat from step 1Check runstateEnteracceleratorTCG or KVMExit from step 1: CPU idle orstoppedWait for workHandlereturnServicequeued work↻ Repeat from step 1
The outer vCPU loop checks run state again after the accelerator returns control.
Going deeperFlatView, dispatch, and RCU

A vCPU doing MMIO and a device doing DMA may both need to resolve an address through a QEMU AddressSpace. QEMU derives a FlatView from the MemoryRegion topology of an address space. It resolves aliases and overlapping mappings to produce visible ranges with offsets into their backing regions. The FlatView has an associated dispatch structure, AddressSpaceDispatch, whose page-based lookup maps addresses to memory region sections. A lookup can then supply the selected region and the offset needed for a RAM or device access. TCG can cache translation information for repeated accesses. With KVM, ordinary guest RAM accesses can proceed in hardware using KVM's memory mappings. A userspace MMIO exit can still require an address-space lookup in QEMU.

QEMU publishes updated views using read-copy-update, or RCU. Readers in an RCU read-side critical section can use a published mapping while an update prepares and publishes a replacement. Retirement of the old view is deferred until readers that could still be using it have finished. This protects the lifetime of the mapping seen by an in-flight lookup. A device callback still follows the synchronization rules for its mutable registers and queues. RCU protection of the mapping does not grant exclusive access to that device state. What is RCU?

03

Inspecting the running machine

4 min read

The launch arguments establish which CPU and device state you can inspect. -M selects the board or machine model. -cpu selects the guest CPU model, -smp configures the vCPUs and their topology, and -m configures guest RAM. -accel tcg selects software execution, which makes the ARM64 example usable on x86 hosts and on setups without usable KVM. -accel kvm requires a compatible host architecture and access to a working KVM interface. The accelerator and the CPU model must also be compatible.

-device adds a guest-visible device model where the machine supports it. Its properties can refer to host backends by ID. For example, -drive if=none,id=disk0,file=guest.qcow2,format=qcow2 defines a disk backend and -device virtio-blk-pci,drive=disk0 attaches it to a guest-visible device. Similarly, -netdev user,id=net0 defines a network backend and -device virtio-net-pci,netdev=net0 attaches it to a virtual NIC. -chardev socket,id=mon0,path=./hmp.sock,server=on,wait=off defines a character backend on a local Unix socket. -mon chardev=mon0,mode=readline connects an HMP monitor to it. On the ARM virt machine, the board supplies the PL011 used below.

HMP, the Human Monitor Protocol, accepts interactive commands. QMP, the QEMU Machine Protocol, uses JSON for requests, replies, and asynchronous events. With -qmp unix:./qmp.sock,server=on,wait=off, a local client can connect to the separate QMP endpoint. After the greeting, send {"execute":"qmp_capabilities"} before issuing commands such as {"execute":"query-status"} or {"execute":"query-cpus-fast"}. Those queries report VM run state and CPU information, respectively. Use structured QMP replies when writing a client. HMP's text is arranged for interactive reading.

With a matching ARM64 Image and initramfs.img in the current directory, this command starts an ARM virt guest. The kernel needs built-in PL011 console support, and the initramfs should provide a bootable userspace. The multiplexed terminal uses Ctrl-a c to switch between the guest serial console and HMP.

bash
qemu-system-aarch64 -M virt -cpu cortex-a57 -accel tcg \
  -smp 2 -m 512M -kernel Image -initrd initramfs.img \
  -append 'console=ttyAMA0' -display none \
  -serial mon:stdio

In HMP, info qtree shows the realized devices and buses. Find the pl011 device and examine its MMIO information and IRQ output. info mtree shows MemoryRegion mappings. Find the PL011 region in the system memory address space and compare its base with the device's MMIO base. info registers shows architectural registers for the selected vCPU. Use cpu 0 or cpu 1 to select a CPU in this two-vCPU guest. Use stop before comparing register snapshots so guest execution cannot change the samples between commands. cont resumes execution. If both CPUs show similar register values, that alone says little about the device routing.

Evidence for the UART mappingHMP infoqtreeIdentifythe UARTmodelHMP infomtreeMatch theMMIO rangeGuestdevice treeDecode theGICspecifierHMP infoqtreeIdentifythe UARTmodelHMP infomtreeMatch theMMIO rangeGuestdevice treeDecode theGICspecifier
Use the device and memory trees for the UART mapping, then the device tree for its interrupt route.

The interrupt output listed in info qtree describes the device connection point. On this board, the generated device tree gives the guest-facing interrupt specifier. To inspect it from the Ubuntu host, use a second invocation with the original machine options and dumpdtb added. QEMU writes the device tree and exits. Decompile the binary with dtc from the device-tree-compiler package.

bash
qemu-system-aarch64 -M virt,dumpdtb=virt.dtb -cpu cortex-a57 \
  -accel tcg -smp 2 -m 512M -kernel Image \
  -initrd initramfs.img -append 'console=ttyAMA0' \
  -display none
dtc -I dtb -O dts -o virt.dts virt.dtb

Find the node whose compatible property includes arm,pl011. Decode reg using the parent node's address and size cell counts. Device tree cells are 32 bits each, with the high cell first in a multi-cell value. The property gives a base and a length. HMP shows a start and an inclusive end, so add the length to the base and subtract one to compare the end addresses. Follow interrupt-parent, which can be inherited, to the GIC node. In the three-cell GIC interrupt specifier used here, the cells describe interrupt type, interrupt number within that type, and trigger flags. Type 0 means shared peripheral interrupt, or SPI. Add 32 to the SPI index if you report the architectural GIC interrupt ID. Label it separately from any Linux IRQ number shown in the guest's /proc/interrupts, which Linux assigns through its IRQ subsystem.

You have now traced a device from its model to the address a guest can access and the interrupt the board advertises. The next lesson, A new QOM device type and its state, begins with the device object that holds the state behind those interfaces.

Key takeaways

  • The main event loop dispatches host events while runnable vCPUs execute through their accelerator.
  • A bottom half runs in its owning AioContext, which can belong to the main loop or a dedicated IOThread.
  • TCG executes translated guest code inside QEMU, while KVM enters the guest through KVM_RUN.
  • The device tree supplies interrupt routing evidence that complements the HMP device and memory trees.
Reflect
  1. Explain to a colleague, in two sentences: trace an asynchronous completion from submission to guest interrupt delivery
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. 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

Find your next step

↑ ↓ to move · Enter to open · Esc to close