Write a simple MMIO device model (register read/write callbacks).
#include <stdint.h>
#include <stdbool.h>
/* a timer device: CTRL @0x00 (bit0 enable, bit1 irq_en), COUNT @0x04 (ro), LOAD @0x08, STATUS @0x0C (w1c) */
typedef struct {
uint32_t ctrl, count, load, status;
void (*set_irq)(int level);
} timer_dev_t;
static void update_irq(timer_dev_t *d)
{
d->set_irq((d->ctrl & 2u) && (d->status & 1u));
}
uint32_t timer_mmio_read(timer_dev_t *d, uint64_t off)
{
switch (off) {
case 0x00: return d->ctrl;
case 0x04: return d->count;
case 0x08: return d->load;
case 0x0C: return d->status;
default: return 0; /* log "guest error: bad offset" */
}
}
void timer_mmio_write(timer_dev_t *d, uint64_t off, uint32_t val)
{
switch (off) {
case 0x00: d->ctrl = val & 3u; if (val & 1u) d->count = d->load; break;
case 0x08: d->load = val; break;
case 0x0C: d->status &= ~val; break; /* write-1-to-clear */
default: break; /* COUNT is read-only: ignore writes */
}
update_irq(d);
}
void timer_tick(timer_dev_t *d) /* called by the emulator's clock */
{
if (!(d->ctrl & 1u)) return;
if (d->count && --d->count == 0) {
d->status |= 1u; /* expired */
d->count = d->load; /* auto-reload */
update_irq(d);
}
}
Points: a device model is a state struct plus read/write handlers keyed by register offset, exactly like QEMU's MemoryRegionOps; implement access semantics faithfully (read-only, write-1-to-clear, side effects on write); recompute the interrupt line after every state change; ignore or log invalid offsets and sizes instead of crashing (the guest can be malicious); a reset function should restore documented reset values. In QEMU you would also add migration state (VMStateDescription).