qemu · April 4, 2026·

QEMU Custom Device Module

Disclaimer: A Note on QEMU Version Coverage and Timeliness

This blog post was initiated based on observations of QEMU version v10.2.1. Please be aware that the information presented here may not align with updates in more recent or future releases in the official QEMU repository. Due to the fast-moving nature of technology and aggressive software development cycles, I find it necessary to provide this disclaimer to prevent any potential misinformation going forward.


Overview

In the previous blog post, we built a custom ARM Cortex-M4 machine using existing device modules from QEMU — PL011 UART, SP804 Timer, and PL061 GPIO. Those are well-tested, production-quality peripherals that QEMU ships with. We simply instantiated them in our machine with a few lines of code.

But real-world embedded development rarely stays that clean. The moment you move to a vendor-specific SoC, you encounter dozens of custom IP blocks — proprietary DMA controllers, hardware crypto engines, custom watchdogs, vendor-defined interrupt aggregators — none of which exist in QEMU's source tree. If you want to emulate that hardware accurately enough to run real firmware, you need to write your own device module.

In this blog post, we will:

  • Understand what a device module is and how it fits into QEMU's architecture
  • Learn when you need to write one — and when you don't
  • Build a complete SysBus-based MMIO peripheral from scratch with a register bank and IRQ generation
  • Integrate the new device into the ugur-m4 machine from the previous post and test it with bare-metal firmware

Toolchain and QEMU source setup are identical to the previous blog post. If you haven't set those up yet, please refer to QEMU Custom Basic Machine before continuing.


What Is a Device Module?

A device module in QEMU is a C implementation of a virtual hardware peripheral, registered in QEMU's QOM (QEMU Object Model) type system. It models the observable behavior of a hardware block from the software's perspective:

  • Responding to MMIO register reads and writes via callback functions
  • Asserting and deasserting interrupt lines (IRQs) to the CPU
  • Reacting to clock events, DMA requests, or GPIO signals
  • Maintaining internal state that reflects what the real hardware would hold

Device modules are the building blocks that machines compose. When we called pl011_create() or qdev_new("sp804") in the previous post, we were instantiating pre-written device modules. Now we will learn how to write one ourselves.


When Do You Need to Write a Device Module?

Before writing any code, it is worth asking: do I actually need to write a new device module? QEMU already ships hundreds of peripheral models. The answer depends on what you are trying to emulate.

You do NOT need to write one when:

  • QEMU already has a matching model (PL011, SP804, PL061, GIC, NVIC, VirtIO block/net, etc.)
  • The peripheral you need is close enough to an existing model that you can reuse or configure it
  • You are prototyping firmware that only relies on standard ARM Cortex-M peripherals
  • Your machine only needs a pass-through to the host (e.g., host serial, host block device)

You DO need to write one when:

  • Your SoC has a custom or proprietary IP block not present in QEMU (vendor DMA, custom crypto engine, custom watchdog, proprietary PMIC interface, etc.)
  • You are upstreaming QEMU support for a new board or SoC
  • An existing model does not accurately reflect the register-level behavior your firmware expects
  • You want to inject faults, simulate hardware delays, or add test instrumentation for CI/CD pipelines
  • Your firmware test suite directly pokes peripheral registers and expects specific side effects

A common real-world scenario: an embedded team develops against a custom register-mapped peripheral. Without a QEMU model, firmware cannot be tested in CI without physical hardware. Writing a device module — even a simplified behavioral one — unblocks the entire testing pipeline.


Types of Devices in QEMU

QEMU supports several device bus types. Each is appropriate for a different class of hardware connection:

Type Parent Class Typical Use Case
SysBus TYPE_SYS_BUS_DEVICE MMIO-mapped peripherals on ARM/RISC-V SoCs
PCI TYPE_PCI_DEVICE PCI/PCIe cards and endpoints
USB TYPE_USB_DEVICE USB peripherals and hubs
ISA TYPE_ISA_DEVICE Legacy x86 ISA bus devices

In this blog post, we will focus on SysBus devices, which is the most common type for ARM embedded development. SysBus devices are mapped directly into the system memory address space and can assert IRQ lines — exactly what most ARM SoC peripherals look like.


Device Design: ugur-mmio-dev

We will create a simple SysBus MMIO peripheral called ugur-mmio-dev. It has five memory-mapped 32-bit registers and one outgoing IRQ line.

Register Map

Offset Name Access Description
0x00 CONTROL R/W bit[0] = ENABLE, bit[1] = IRQ_FORCE
0x04 STATUS R/W bit[0] = BUSY
0x08 IRQ_ENABLE R/W bit[0] = enable IRQ on DATA write
0x0C IRQ_STATUS R/W bit[0] = IRQ pending (Write-1-to-Clear)
0x10 DATA R/W Any write to this register triggers an IRQ (if enabled)

IRQ Behavior

The device has two independent paths to assert its IRQ line:

  1. Normal path: Writing any value to the DATA register sets IRQ_STATUS[0]. If IRQ_ENABLE[0] is also set, the IRQ line is asserted.
  2. Force path: Setting CONTROL[1] (IRQ_FORCE) immediately asserts the IRQ regardless of IRQ_STATUS or IRQ_ENABLE. This is useful for testing interrupt handlers from firmware.

To acknowledge and clear the IRQ in the normal path, firmware writes 1 to IRQ_STATUS[0] (Write-1-to-Clear, or W1C). This clears the bit and deasserts the IRQ line. For the force path, firmware clears CONTROL[1].

This pattern — a control register, a status register, explicit interrupt enable/status registers, and a data register with side effects — is found in countless real-world peripherals and is a solid foundation to learn from.


Stage-1: Create the Files

# Navigate to the QEMU source root
$ cd $HOME/codes/qemu

# Create device files under hw/misc/
# This directory is the conventional home for custom or miscellaneous peripherals
$ touch hw/misc/ugur_mmio_dev.c
$ touch include/hw/misc/ugur_mmio_dev.h

Why hw/misc/? QEMU organizes device source files by hardware category: hw/uart/, hw/timer/, hw/gpio/, hw/dma/, and so on. The hw/misc/ directory is the conventional location for devices that do not belong to a specific category — custom, prototype, or vendor-specific peripherals belong here.


Stage-2: Header File

The header file defines the QOM type identity, register offsets, bit field constants, and the device state structure.

/* include/hw/misc/ugur_mmio_dev.h */
#ifndef UGUR_MMIO_DEV_H
#define UGUR_MMIO_DEV_H

#include "hw/sysbus.h"
#include "qom/object.h"

/* ── QOM type name ─────────────────────────────────────────────── */
#define TYPE_UGUR_MMIO_DEV    "ugur-mmio-dev"
OBJECT_DECLARE_SIMPLE_TYPE(UgurSimpleDevState, UGUR_MMIO_DEV)

/* ── Register offsets ──────────────────────────────────────────── */
#define UGUR_REG_CONTROL        0x00
#define UGUR_REG_STATUS         0x04
#define UGUR_REG_IRQ_ENABLE     0x08
#define UGUR_REG_IRQ_STATUS     0x0C
#define UGUR_REG_DATA           0x10
#define UGUR_REGS_SIZE          0x14    /* total MMIO footprint: 5 × 4 bytes */

/* ── CONTROL register bits ─────────────────────────────────────── */
#define CTRL_ENABLE             (1u << 0)
#define CTRL_IRQ_FORCE          (1u << 1)

/* ── IRQ_ENABLE / IRQ_STATUS bits ──────────────────────────────── */
#define IRQ_DATA_WRITE          (1u << 0)

/* ── Device state ──────────────────────────────────────────────── */
struct UgurSimpleDevState {
    SysBusDevice  parent_obj;   /* MUST be first — enables safe QOM upcasting */

    MemoryRegion  mmio;         /* MMIO region registered with the system bus */
    qemu_irq      irq;          /* outgoing IRQ line to the CPU / NVIC */

    /* Software mirror of the hardware registers */
    uint32_t      reg_control;
    uint32_t      reg_status;
    uint32_t      reg_irq_enable;
    uint32_t      reg_irq_status;
    uint32_t      reg_data;
};

#endif /* UGUR_MMIO_DEV_H */

Key points:

  • OBJECT_DECLARE_SIMPLE_TYPE — generates the UGUR_MMIO_DEV(obj) cast macro and the UgurSimpleDevState typedef. This is QOM boilerplate required for every device type, identical to what we used for the machine type in the previous post.
  • SysBusDevice parent_obj — must be the first field in the state struct. QEMU's QOM relies on C struct layout to safely cast between UgurSimpleDevState *, SysBusDevice *, and DeviceState * without runtime overhead.
  • MemoryRegion mmio — the MMIO region object that QEMU maps into the system address space. Its read and write callbacks are where all register accesses are handled.
  • qemu_irq irq — a handle to the outgoing interrupt line. qemu_set_irq(s->irq, 1) asserts the line; qemu_set_irq(s->irq, 0) releases it.
  • Register fields (reg_control, reg_status, etc.) — these hold the current value of each hardware register, forming the complete software-visible state of our virtual peripheral.

Stage-3: MemoryRegionOps — Read and Write Callbacks

The core of any MMIO device is its read and write callbacks. QEMU calls these functions whenever the CPU executes a load or store instruction that lands inside the device's address range.

/* hw/misc/ugur_mmio_dev.c */
#include "qemu/osdep.h"
#include "hw/misc/ugur_mmio_dev.h"
#include "hw/irq.h"
#include "qemu/log.h"

static void ugur_mmio_dev_update_irq(UgurSimpleDevState *s) {
    bool assert_irq = false;

    /* Condition 1: DATA write triggered IRQ and the interrupt is enabled */
    if ((s->reg_irq_enable & IRQ_DATA_WRITE) &&
        (s->reg_irq_status & IRQ_DATA_WRITE)) {
        assert_irq = true;
    }

    /* Condition 2: IRQ_FORCE bit in CONTROL overrides everything */
    if (s->reg_control & CTRL_IRQ_FORCE) {
        assert_irq = true;
    }

    qemu_set_irq(s->irq, assert_irq ? 1 : 0);
}

/* ── MMIO Read ─────────────────────────────────────────────────── */
static uint64_t ugur_mmio_dev_read(void *opaque, hwaddr offset,
                                      unsigned size)
{
    UgurSimpleDevState *s = UGUR_MMIO_DEV(opaque);

    switch (offset) {
    case UGUR_REG_CONTROL:    return s->reg_control;
    case UGUR_REG_STATUS:     return s->reg_status;
    case UGUR_REG_IRQ_ENABLE: return s->reg_irq_enable;
    case UGUR_REG_IRQ_STATUS: return s->reg_irq_status;
    case UGUR_REG_DATA:       return s->reg_data;
    default:
        qemu_log_mask(LOG_GUEST_ERROR,
            "ugur-mmio-dev: read from unknown offset 0x%" HWADDR_PRIx "\n",
            offset);
        return 0;
    }
}

/* ── MMIO Write ────────────────────────────────────────────────── */
static void ugur_mmio_dev_write(void *opaque, hwaddr offset,
                                   uint64_t value, unsigned size)
{
    UgurSimpleDevState *s = UGUR_MMIO_DEV(opaque);

    switch (offset) {
    case UGUR_REG_CONTROL:
        s->reg_control = (uint32_t)value;
        break;

    case UGUR_REG_STATUS:
        s->reg_status = (uint32_t)value;
        break;

    case UGUR_REG_IRQ_ENABLE:
        s->reg_irq_enable = (uint32_t)value;
        break;

    case UGUR_REG_IRQ_STATUS:
        /* W1C: writing a 1 to a bit clears that bit */
        s->reg_irq_status &= ~(uint32_t)value;
        break;

    case UGUR_REG_DATA:
        s->reg_data = (uint32_t)value;
        /* A write to DATA always sets the IRQ_DATA_WRITE status bit */
        s->reg_irq_status |= IRQ_DATA_WRITE;
        break;

    default:
        qemu_log_mask(LOG_GUEST_ERROR,
            "ugur-mmio-dev: write to unknown offset 0x%" HWADDR_PRIx
            " value 0x%" PRIx64 "\n", offset, value);
        return;
    }

    /* Recompute IRQ level after every register write */
    ugur_mmio_dev_update_irq(s);
}

/* ── MemoryRegionOps table ─────────────────────────────────────── */
static const MemoryRegionOps ugur_mmio_dev_ops = {
    .read       = ugur_mmio_dev_read,
    .write      = ugur_mmio_dev_write,
    .endianness = DEVICE_LITTLE_ENDIAN,
    .valid = {
        .min_access_size = 4,
        .max_access_size = 4,
    },
};

Several important details deserve explanation here:

  • void *opaque — QEMU passes the device state pointer as opaque when invoking the callbacks. We recover the typed pointer with the UGUR_MMIO_DEV(opaque) cast macro.
  • hwaddr offset — this is the byte offset from the start of the MMIO region, not an absolute address. So offset 0x00 is always UGUR_REG_CONTROL regardless of where in the physical address space the device is mapped.
  • LOG_GUEST_ERROR — the correct log mask for "guest firmware accessed an undefined register." This is distinct from LOG_UNIMP (a feature exists in hardware but is not yet modeled in QEMU) or error_report() (a QEMU-internal problem).
  • W1C on IRQ_STATUS: s->reg_irq_status &= ~(uint32_t)value — writing a 1 bit clears the corresponding status bit. This is the standard mechanism real hardware uses for interrupt acknowledgment: the firmware writes a mask of bits to clear, and the hardware deasserts those bits atomically.
  • DATA write side effect: Writing to DATA unconditionally sets IRQ_STATUS[0], then update_irq() decides whether to actually assert the IRQ based on IRQ_ENABLE. This separation of "event detection" from "interrupt signaling" is intentional and mirrors real hardware behavior.
  • DEVICE_LITTLE_ENDIAN — instructs QEMU to byte-swap accesses on big-endian host machines, ensuring the device behaves as a native little-endian peripheral on any host platform.
  • .valid.min_access_size = 4 / .max_access_size = 4 — restricts access to 32-bit word operations only. If firmware attempts an 8-bit or 16-bit access, QEMU will log a guest error instead of passing a partial value to the callback.

Stage-4: IRQ Logic

After every register write, we recompute whether the IRQ line should be asserted or deasserted. As shown in Stage-3, ugur_mmio_dev_update_irq() is defined at the top of the file, before the read/write callbacks, so it is always available when called.

  • ugur_mmio_dev_update_irq() — centralizing IRQ logic in one function is intentional. Any register write that could affect IRQ state calls this function afterward. Scattering qemu_irq_raise/lower calls across multiple code paths leads to subtle bugs where IRQ state drifts out of sync with register state.
  • qemu_set_irq(s->irq, level) — sets the IRQ line to the given level. It is safe to call even if the level has not changed; QEMU handles idempotency internally and will not generate spurious edge transitions.
  • CTRL_IRQ_FORCE is evaluated unconditionally after the normal path. This means even if IRQ_ENABLE is zero, the force bit can still assert the line — which is exactly the intended behavior for a software-controlled test injection point.

The IRQ line connected to s->irq ultimately reaches the NVIC inside the ugur-m4 machine. From the CPU's perspective, this looks identical to any other peripheral interrupt.


Stage-5: Realize and Reset Functions

Every QEMU device needs a realize function (called once when the device is instantiated and connected to the bus) and a reset function (called on every system reset). These are the lifecycle hooks that QOM provides for device initialization.

/* ── Reset ─────────────────────────────────────────────────────── */
static void ugur_mmio_dev_reset(DeviceState *dev)
{
    UgurSimpleDevState *s = UGUR_MMIO_DEV(dev);

    s->reg_control    = 0x00000000;
    s->reg_status     = 0x00000000;
    s->reg_irq_enable = 0x00000000;
    s->reg_irq_status = 0x00000000;
    s->reg_data       = 0x00000000;

    /* Guarantee the IRQ line is deasserted after reset */
    ugur_mmio_dev_update_irq(s);
}

/* ── Realize ────────────────────────────────────────────────────── */
static void ugur_mmio_dev_realize(DeviceState *dev, Error **errp)
{
    UgurSimpleDevState *s   = UGUR_MMIO_DEV(dev);
    SysBusDevice       *sbd = SYS_BUS_DEVICE(dev);

    /* 1. Initialize the MMIO region backed by our read/write callbacks */
    memory_region_init_io(&s->mmio, OBJECT(dev), &ugur_mmio_dev_ops,
                          s, TYPE_UGUR_MMIO_DEV, UGUR_REGS_SIZE);

    /* 2. Register the MMIO region as a sysbus memory window */
    sysbus_init_mmio(sbd, &s->mmio);

    /* 3. Initialize and register one outgoing IRQ line */
    sysbus_init_irq(sbd, &s->irq);

    /* 4. Perform a reset to initialize registers and IRQ line */
    ugur_mmio_dev_reset(DEVICE(s));
}

Realize function details:

  • memory_region_init_io() — creates the MMIO region backed by ugur_mmio_dev_ops. The UGUR_REGS_SIZE constant (0x14 = 20 bytes) defines the size of the address window the device occupies. The s pointer passed as opaque is what QEMU will forward to our read/write callbacks.
  • sysbus_init_mmio() — registers the MMIO region with the SysBus infrastructure. This does not map the region to a physical address yet; that happens later when the machine calls sysbus_mmio_map().
  • sysbus_init_irq() — registers one IRQ output slot. The machine will connect this slot to a specific NVIC input line using sysbus_connect_irq().
  • ugur_mmio_dev_reset(DEVICE(s)) — called at the end of realize to bring the device into a clean power-on state immediately after instantiation. This means the device is ready to use as soon as realize returns, without requiring an explicit system reset first.

Reset function details:

  • All registers are zeroed — this models the power-on reset state of the device.
  • ugur_mmio_dev_update_irq(s) is called at the end of reset. Without this call, a stale asserted IRQ from before the reset could remain active even though all the register state has been cleared, causing spurious interrupts after reset.

instance_init vs realize — a common source of confusion

QOM devices have two initialization hooks. instance_init is called when the object is first allocated in memory, before any properties are set or bus connections are made. realize is called after all properties have been configured and the device is ready to connect to the system. For MMIO devices, always use realize — it is the correct and safe place to call memory_region_init_io() and sysbus_init_irq(), because at that point the object hierarchy is complete.


Stage-6: TypeInfo and Registration

The final piece of a device module is registering it with the QOM type system so QEMU can instantiate it by name.

/* ── Class init ────────────────────────────────────────────────── */
static void ugur_mmio_dev_class_init(ObjectClass *klass, const void *data)
{
    DeviceClass *dc = DEVICE_CLASS(klass);

    dc->realize = ugur_mmio_dev_realize;
}

/* ── TypeInfo ───────────────────────────────────────────────────── */
static const TypeInfo ugur_mmio_dev_info = {
    .name          = TYPE_UGUR_MMIO_DEV,
    .parent        = TYPE_SYS_BUS_DEVICE,
    .instance_size = sizeof(UgurSimpleDevState),
    .class_init    = ugur_mmio_dev_class_init,
};

/* ── Registration ───────────────────────────────────────────────── */
static void ugur_mmio_dev_register(void)
{
    type_register_static(&ugur_mmio_dev_info);
}
type_init(ugur_mmio_dev_register)
  • ugur_mmio_dev_class_init() — populates the class vtable. Only dc->realize is set here. Reset is not registered via device_class_set_legacy_reset(); instead, ugur_mmio_dev_reset() is called explicitly from within realize (step 4 above). This is a valid pattern when you want the device to start in its reset state immediately upon instantiation, before any system-level reset event.
  • .parent = TYPE_SYS_BUS_DEVICE — declares this as a SysBus-type device, giving it MMIO mapping and IRQ capabilities from the parent class.
  • .instance_size = sizeof(UgurSimpleDevState) — tells QOM how many bytes to allocate per instance. This must always be the size of the concrete state struct.
  • type_register_static() — registers the device type in the global QOM type table.
  • type_init(ugur_mmio_dev_register) — ensures the registration function runs automatically during QEMU's early initialization phase, before any machine setup begins.

At this point, the device module is complete. qdev_new(TYPE_UGUR_MMIO_DEV) can now be called anywhere to instantiate it.

The complete source and header files are available here:

ugur_mmio_dev.h

ugur_mmio_dev.c


Stage-7: Build System Integration

Just like the ugur-m4 machine, the new device module must be registered in QEMU's build system before it can be compiled. Three files need to be updated.

hw/misc/Kconfig

Add the following entry to hw/misc/Kconfig:

config UGUR_MMIO_DEV
    bool
  • This declares UGUR_MMIO_DEV as a boolean build symbol. It has no default y of its own — it will be activated when the ugur-m4 machine selects it.

hw/misc/meson.build

Add the following line to hw/misc/meson.build:

system_ss.add(when: 'CONFIG_UGUR_MMIO_DEV', if_true: files('ugur_mmio_dev.c'))
  • system_ss is the source set for system-mode emulation targets.
  • when: 'CONFIG_UGUR_MMIO_DEV' — the file is compiled only when this symbol is enabled.
  • Note that unlike arm_common_ss used for the machine file, misc devices typically use system_ss because they are not architecture-specific.

hw/arm/Kconfig — Update UGUR_M4

Add select UGUR_MMIO_DEV to the existing UGUR_M4 block in hw/arm/Kconfig:

config UGUR_M4
    bool
    default y
    depends on TCG && ARM
    select ARM_V7M
    select PL011
    select ARM_TIMER
    select PL061
    select UNIMP
    select UGUR_MMIO_DEV    # ← add this line
  • The select keyword propagates the dependency upward: enabling UGUR_M4 automatically enables UGUR_MMIO_DEV, which causes ugur_mmio_dev.c to be compiled into the build.

No changes are needed to default.mak — the machine already has CONFIG_UGUR_M4=y, which will now pull in the device module as well.


Stage-8: Machine Integration

With the device module built, we add it to the ugur-m4 machine. This requires small additions to both the header and source files from the previous post.

Additions to ugur_m4.h

#include "hw/misc/ugur_mmio_dev.h"

/* ugur-mmio-dev base address and IRQ assignment */
#define UGUR_MMIO_DEV_BASE     0x40010000U
#define UGUR_MMIO_DEV_IRQ      40
  • 0x40010000 places the device in the peripheral address range, well above the UART (0x40000000), timer (0x40001000), and GPIO (0x40002000) from the previous post.
  • IRQ 40 is an unused slot in the ugur-m4 machine's NVIC mapping. In the STM32F407 vector table (which our bare-metal firmware uses), this slot corresponds to EXTI15_10_IRQHandler — we will reuse that handler name in the test firmware.

Additions to ugur_m4_init() in ugur_m4.c

/* ugur-mmio-dev */
dev = qdev_new(TYPE_UGUR_MMIO_DEV);
sbd = SYS_BUS_DEVICE(dev);
sysbus_realize_and_unref(sbd, &error_fatal);
sysbus_mmio_map(sbd, 0, UGUR_MMIO_DEV_BASE);
sysbus_connect_irq(sbd, 0, qdev_get_gpio_in(nvic, UGUR_MMIO_DEV_IRQ));

This is identical in structure to how SP804 and PL061 were added in the previous post:

  • qdev_new() — creates a new instance of the device by its registered type name.
  • sysbus_realize_and_unref() — finalizes the device and releases the extra reference taken by qdev_new().
  • sysbus_mmio_map(sbd, 0, ...) — maps the first MMIO region (index 0, the one we registered with sysbus_init_mmio() in realize) to the physical address 0x40010000.
  • sysbus_connect_irq(sbd, 0, ...) — wires the first IRQ output (index 0, registered with sysbus_init_irq()) to NVIC input 40.

The updated machine files are available here:

ugur_m4.h

ugur_m4.c


Stage-9: Build and Test

Configure and Build

$ cd $HOME/codes/qemu

# Configure (same as before — no new flags needed)
$ ./configure --target-list=arm-softmmu

# Build
$ make -j$(nproc)

Bare-Metal Test Code

We extend the demo.c from the previous post with a mmio_dev_test() function that exercises both IRQ paths.

/* ── ugur-mmio-dev register map ─────────────────────────────── */
#define MMIO_DEV_BASE         0x40010000U
#define MMIO_DEV_CONTROL      (*(volatile uint32_t *)(MMIO_DEV_BASE + 0x00))
#define MMIO_DEV_STATUS       (*(volatile uint32_t *)(MMIO_DEV_BASE + 0x04))
#define MMIO_DEV_IRQ_ENABLE   (*(volatile uint32_t *)(MMIO_DEV_BASE + 0x08))
#define MMIO_DEV_IRQ_STATUS   (*(volatile uint32_t *)(MMIO_DEV_BASE + 0x0C))
#define MMIO_DEV_DATA         (*(volatile uint32_t *)(MMIO_DEV_BASE + 0x10))

volatile uint32_t mmio_dev_irq_fired = 0;

/*
 * IRQ 40 handler.
 * In the STM32F407 vector table IRQ 40 = EXTI15_10_IRQHandler.
 * Our ugur-m4 machine maps IRQ 40 to ugur-mmio-dev, so we reuse
 * the same handler name — the CPU only cares about the vector address.
 */
void EXTI15_10_IRQHandler(void)
{
    mmio_dev_irq_fired++;

    /* Clear DATA-write IRQ if pending (W1C) */
    if (MMIO_DEV_IRQ_STATUS & 0x1) {
        MMIO_DEV_IRQ_STATUS = 0x1;
    }

    /* Clear IRQ_FORCE if it was the trigger */
    if (MMIO_DEV_CONTROL & 0x2) {
        MMIO_DEV_CONTROL &= ~0x2U;
    }
}

void mmio_dev_test(void)
{
    uart_puts("\r\n--- ugur-mmio-dev Test ---\r\n");

    /* Enable IRQ 40 in NVIC */
    nvic_irq_enable(40);

    /* ── Test 1: Normal path — DATA write triggers IRQ ────────── */
    uart_puts("Test 1: DATA write -> IRQ... ");
    mmio_dev_irq_fired = 0;
    MMIO_DEV_IRQ_ENABLE = 0x1;           /* enable DATA-write IRQ */
    MMIO_DEV_DATA       = 0xABCD1234;    /* triggers IRQ_STATUS[0] */
    while (mmio_dev_irq_fired == 0) {}   /* wait for handler */
    uart_puts("PASS\r\n");

    /* ── Test 2: Force path — CTRL_IRQ_FORCE ──────────────────── */
    uart_puts("Test 2: IRQ_FORCE bit -> IRQ... ");
    mmio_dev_irq_fired = 0;
    MMIO_DEV_IRQ_ENABLE = 0x0;           /* disable normal path */
    MMIO_DEV_CONTROL    = 0x2;           /* assert IRQ_FORCE */
    while (mmio_dev_irq_fired == 0) {}   /* wait for handler */
    uart_puts("PASS\r\n");

    uart_puts("--- All Tests PASSED ---\r\n");
}

Also add nvic_irq_enable(40) to main() alongside the other IRQ enables, and call mmio_dev_test() after:

/* Enable IRQs in the NVIC */
nvic_irq_enable(28);  /* SP804 Timer 1 → TIM2_IRQHandler       */
nvic_irq_enable(37);  /* PL011 UART    → USART1_IRQHandler     */
nvic_irq_enable(40);  /* ugur-mmio-dev → EXTI15_10_IRQHandler  */

/* ... */
mmio_dev_test();

Note: nvic_irq_enable(40) is also called inside mmio_dev_test() itself, which makes it redundant but harmless — enabling an already-enabled NVIC IRQ is idempotent.

The complete updated demo file is available here:

demo.c

The Makefile, linker script and startup code are shared with the previous post:

Makefile

stm32f4_flash.ld

startup_stm32f407xx.s

Build the Bare-Metal Binary

$ cd /path/to/baremetal
$ make          # produces build/demo.elf
$ make clean    # removes build/ directory

Run on ugur-m4

./qemu-system-arm \
    -M ugur-m4 \
    -kernel build/demo.elf \
    -serial mon:stdio -nographic

Expected Output

=== Custom Cortex-M4 QEMU Machine ===
Peripherals: PL011 UART | SP804 Timer | PL061 GPIO | ugur-mmio-dev

Timer started. You should see 'tick' every second.
Type anything to echo it back via UART RX interrupt.

--- ugur-mmio-dev Test ---
Test 1: DATA write -> IRQ... PASS
Test 2: IRQ_FORCE bit -> IRQ... PASS
--- All Tests PASSED ---

tick : 1
tick : 2
tick : 3
...

Interrupt Flow

DATA register write
  └─ ugur_mmio_dev_write()
       ├─ reg_irq_status |= IRQ_DATA_WRITE
       └─ ugur_mmio_dev_update_irq()
            └─ IRQ_ENABLE[0] && IRQ_STATUS[0] → qemu_set_irq(1)
                 └─ NVIC IRQ 40 asserted
                      └─ EXTI15_10_IRQHandler()
                           ├─ mmio_dev_irq_fired++
                           ├─ IRQ_STATUS W1C → clear bit
                           └─ ugur_mmio_dev_update_irq()  [via CONTROL write]
                                └─ no conditions met → qemu_set_irq(0)

Debugging with GDB

# Terminal 1 — QEMU in GDB server mode
./qemu-system-arm \
    -M ugur-m4 \
    -kernel build/demo.elf \
    -serial mon:stdio -nographic \
    -gdb tcp::5555 -S

# Terminal 2 — Connect GDB
arm-none-eabi-gdb build/demo.elf
(gdb) target remote :5555
(gdb) break EXTI15_10_IRQHandler
(gdb) continue

Alternatively, the provided run_gdb.py script automates this setup and places breakpoints on all interrupt handlers:

arm-none-eabi-gdb -x run_gdb.py

run_gdb.py

Useful register inspection commands:

(gdb) x/1xw 0x40010000    # CONTROL
(gdb) x/1xw 0x40010004    # STATUS
(gdb) x/1xw 0x40010008    # IRQ_ENABLE
(gdb) x/1xw 0x4001000C    # IRQ_STATUS
(gdb) x/1xw 0x40010010    # DATA
(gdb) p mmio_dev_irq_fired

Conclusion

In this blog post, we built a complete SysBus MMIO device module for QEMU from scratch. Starting from an empty .c file, we covered every layer of the implementation: the QOM type system and state struct, MMIO read/write callbacks with proper W1C semantics, centralized IRQ update logic, the realize and reset lifecycle hooks, TypeInfo registration, and full build system integration. We then integrated the device into the ugur-m4 machine and verified its behavior with bare-metal firmware that exercises both interrupt paths.

The ugur-mmio-dev is intentionally minimal, but the pattern it establishes — register bank, IRQ_ENABLE, IRQ_STATUS (W1C), and an IRQ force bit — scales directly to real-world peripherals. Most vendor-specific IP blocks are variations on exactly this structure.