
Recall first from MMIO exits and their exit reasons
- A userspace MMIO device occupies a GPA range that the VMM leaves outside its RAM slots.
- KVM resolves many EPT violations in the kernel and reports KVM_EXIT_MMIO when an emulated access needs userspace.
- The VMM fills the read buffer before re-entering KVM_RUN, which completes the pending I/O operation.
Which exit are you trying to avoid?
2 min readThe last lesson showed every I/O access exits to userspace. This lesson answers two mechanisms, the coalesced-MMIO ring and ioeventfd, that skip that round-trip for hot devices.
The Linux 6.8 KVM API describes a real performance problem. A stream of device writes can make the vCPU thread return to userspace repeatedly even though the guest can continue before the device model processes each individual write. A second case arises when a write simply tells a device that work is available. The host may need to wake a consumer, but it can do that without first returning the vCPU thread to the VMM.
Count two distinct events. A hardware VM exit transfers control from the running guest to the host's KVM code. A userspace exit occurs when KVM_RUN returns with an exit reason such as KVM_EXIT_MMIO or KVM_EXIT_IO. KVM can handle an intercepted access in the kernel and resume guest execution within the same KVM_RUN call. A measurement taken in the VMM's exit loop only sees the second event.
With a QEMU device model in userspace, each I/O exit delivered for that device sends the vCPU thread back to QEMU. QEMU dispatches the access to the device model, supplies data for a read when required, and calls KVM_RUN again. With an in-kernel irqchip, KVM handles the interrupt controller accesses supported by that implementation without a userspace exit. With a kernel vhost-backed virtio device configured to use ioeventfd for guest notifications, a kernel backend can receive the notification and process queued data without a userspace exit for each notification. QEMU still configures the device and handles accesses assigned to its userspace model.
Before choosing an optimization, look at what the guest expects from the access. A read that requires a value from the userspace model must get that value before guest execution can continue. A write whose address and bytes must reach the model can be deferred when the device permits it. A notification write can use ioeventfd when the consumer already knows what to do from the eventfd and any work data available elsewhere. Those two kinds of writes are the focus of this lesson.
Coalesced MMIO defers device writes
3 min readSuppose the guest writes repeatedly to a device memory window. The userspace model needs the individual addresses and bytes, but it can apply a group of writes later, before the next operation that depends on them. KVM lets the VMM register an address range for coalesced MMIO. On an eligible write with room in the ring, KVM records the access in shared memory and resumes the guest. The VMM can then process multiple pending writes when it regains control, saving a KVM_RUN return and re-entry for each write that was successfully queued.
deferred delivery of eligible guest MMIO writes as entries in a shared ring that userspace drains preserves a record of each queued write. Two writes to the same address can produce two entries. The reduction comes from processing several entries together. A model that tracks the sequence of writes can therefore still apply the operations in order.
Going deeperRing layout, overflow and device ordering
Check KVM_CAP_COALESCED_MMIO with KVM_CHECK_EXTENSION. A positive result gives the page offset of the coalesced I/O ring in the vCPU mapping. The UAPI name for this page offset on architectures such as x86 is KVM_COALESCED_MMIO_PAGE_OFFSET. Convert the offset from pages to bytes using the host page size. The VM ioctl KVM_REGISTER_COALESCED_MMIO takes a struct kvm_coalesced_mmio_zone describing the guest physical range. For MMIO, use its address and size fields and leave the PIO selector clear.
The shared struct kvm_coalesced_mmio_ring has a first index for the next entry userspace consumes and a last index for the next slot KVM fills. An entry has the access address, length and data bytes. KVM publishes the next producer index after filling the entry. The VMM uses the corresponding memory ordering when consuming the entry and publishes its updated consumer index after processing it. A multi-vCPU VMM must coordinate draining the shared ring so that two vCPU threads cannot consume the same entry.
When the ring has no free slot, KVM declines to queue the current write. That write follows normal handling and returns as KVM_EXIT_MMIO if it needs userspace emulation. Earlier entries remain pending. Drain those entries before applying the current write in the ordinary handler. Dropping the current write would lose a guest operation. Handling it ahead of queued writes could produce the wrong device state. Use the same ordering when servicing a read that needs to observe the results of the earlier writes, and make sure pending writes are drained before collecting final device state.
The range is a device-specific choice. For example, a VMM may use coalescing on a VGA memory aperture where its device model can defer writes and apply them before dependent operations. This depends on the model's handling of that window. Registers that trigger an operation with immediate effects, or writes whose effects must be visible to another observer before it proceeds, require the VMM to preserve that timing. Placing such registers in a coalesced range without arranging the required synchronization can break the device contract. A guest may also continue running after a queued write, so a device that needs prompt processing cannot depend on a future unrelated exit for service.
ioeventfd handles notification writes
4 min readConsider a guest that puts work descriptions in shared memory and then writes a notification register. The backend can determine which queue to inspect from the identity of the notification, and it can read the descriptions directly from memory. That protocol makes the MMIO write suitable for ioeventfd. If writes to the register instead carry commands with different meanings, the backend needs a way to distinguish them. A fixed data match can select a particular command value, while unmatched writes can still go through normal emulation.
a KVM binding that signals a host eventfd when a guest write matches a registered I/O address and access specification is configured with the VM ioctl KVM_IOEVENTFD. The registration specifies the guest physical address for MMIO, the access width in bytes for a fixed-width match, and the host eventfd. The same ioctl supports port I/O on hosts with that facility. For PIO set KVM_IOEVENTFD_FLAG_PIO and supply the port number in the address field. Set KVM_IOEVENTFD_FLAG_DATAMATCH and supply datamatch when you want to accept only a specific write value. With the data-match flag clear, a fixed-width registration accepts any value of the registered width. Reads and unmatched writes follow their ordinary path.
KVM signals the eventfd directly and completes the matching access in the kernel. A userspace consumer can wait for the descriptor to become readable and do work on another thread or in its event loop. A kernel consumer such as a vhost backend can receive the notification in the kernel. In either case, the vCPU thread can continue guest execution without waiting for userspace to emulate the write. The guest protocol still determines when the work is ready for the consumer, including any required ordering between writing shared memory and notifying the device.
An eventfd created without EFD_SEMAPHORE returns its accumulated counter as a uint64_t and resets the counter on a successful read. For example, a consumer that reads only after the guest has finished a burst can collect the signals in a single read. The counter gives the number of notifications accumulated since the previous read. The bytes of the MMIO access have no representation in that counter. This is the practical difference from coalesced MMIO, where the consumer receives the actual bytes and address of each deferred write.
For the measurement, use your existing mini-VMM and choose a dedicated MMIO register reached by an aligned 32-bit guest store. Use an address in the device region outside guest RAM. Give that write the meaning “notify,” so that counting notifications is enough to model the register for the exercise. Use a separate completion access that always returns to the VMM. An explicit completion access lets both runs stop after the same workload and gives the host a point at which it can read the accumulated counter without needing a worker thread.
Use <linux/kvm.h> and <sys/ioctl.h> for the KVM interface and <sys/eventfd.h> for eventfd(). Check KVM_CAP_IOEVENTFD with KVM_CHECK_EXTENSION on the KVM system descriptor. Handle an ioctl error separately from a zero result indicating unsupported functionality. Open the eventfd with initial count zero and flags EFD_CLOEXEC | EFD_NONBLOCK, and check that creation succeeds. Zero-initialize a struct kvm_ioeventfd, then fill addr with the guest physical register address, len with the width in bytes and fd with the returned descriptor. Leave flags clear for the first run with ioeventfd enabled. Pass the structure to KVM_IOEVENTFD on the VM descriptor and require a successful return before running the guest. For explicit teardown, repeat the registration with KVM_IOEVENTFD_FLAG_DEASSIGN added to the original flags, check the result, then close the descriptor and check the close result.
Instrument the existing KVM_RUN loop by incrementing a counter only for KVM_EXIT_MMIO writes to the chosen guest physical address with the expected length. Run the guest first with the ordinary handler and then with the eventfd registered. Keep the same guest store count and completion condition. For the second run, use read() after completion to read the eventfd into a uint64_t, retry on EINTR, and check for an exact-size read. With no other consumer, EAGAIN on the nonblocking descriptor at that point means there was no pending signal. If the MMIO exit count remains high, compare the registered address and width with the values seen in the ordinary handler.
Report both counts and their difference. With one access per store, the ordinary count should equal the number of guest stores, the registered run should have zero exits for those writes, and the eventfd count should equal the number of stores. These are checks to apply to your own results. The completion access belongs outside the register-specific counter. A drop in that counter measures avoided userspace returns for the notification register. Measuring hardware VM exits or elapsed time would answer different questions.
The next lesson, “The in-kernel irqchip and irqfd,” follows the notification in the other direction. It explains how a host-side event can request a guest interrupt and where the in-kernel interrupt controller fits.
Key takeaways
- KVM can handle an access after a hardware VM exit and resume the guest inside the same KVM_RUN call.
- Coalesced MMIO records eligible writes for later processing by userspace.
- ioeventfd signals a host eventfd on matching guest writes without returning those accesses to userspace.
- An eventfd counter records notifications, while the device protocol defines where the work data lives.
Reflect
- Explain to a colleague, in two sentences: distinguish hardware VM exits from KVM_RUN returns to userspace.
- 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: coalesced I/O and KVM_IOEVENTFD
- Man pageeventfd(2): event notification file descriptor
Official documentation first. Links checked when the lesson was published.