Implement trap-and-emulate for an MMIO access in C.
Short answer: When a guest accesses emulated MMIO, the hypervisor handles the trap by dispatching the physical address, width and direction to the device. The returned read value is delivered to the guest.
#include <stdint.h>
#include <stdbool.h>
#define BASE UINT64_C(0x10000000)
static uint32_t control;
struct mmio_exit {
uint64_t addr, data;
unsigned size;
bool write;
};
bool emulate(struct mmio_exit *e)
{
if (e->addr != BASE || e->size != 4) return false;
if (e->write) control = (uint32_t)e->data & 0x7;
else e->data = control;
return true;
}
For example, a write of 0xff to BASE stores 7; a following read returns 7. In KVM, userspace receives KVM_EXIT_MMIO via KVM_RUN, fills the read buffer or consumes the write buffer, then re-enters KVM_RUN to complete the access. This is a teaching callback, not the actual KVM ABI. Unsupported accesses require defined bus-error/device behavior, and a real VMM validates widths, endianness and guest addresses.