Module 11 · Lesson 24 of 107

A new QOM device type and its state

Declare a QOM SysBus device, define its per-instance state and properties, and explain how QEMU configures and realizes it.

  • Beginner to advanced
  • 7 min read
  • 13 min lab
What you will need

Ubuntu 24.04 in WSL2 or a VM and a QEMU source tree available for inspection

Your place in the module
By the end you can 4 objectives
  • Declare and register a QOM type derived from SysBusDevice.
  • Map two qdev properties to fields in a device instance.
  • Place initialization and validation in the correct lifecycle callbacks.
  • Identify the conditions for board-created and command-line-created instances.
Video coming soonA new QOM device type and its state
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from The event loop and the vCPU lifecycle
  • 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.
01

Declare the type and its instance state

2 min read

The last lesson showed how QEMU's object model describes existing devices. This lesson answers how to add a new one: the TypeInfo, the parent class, and the state properties.

QEMU's Arm PrimeCell UART model, implemented in hw/char/pl011.c, is a concrete example of a device that needs instance state. A machine can contain more than one UART. An operation on one UART must affect that UART's state, so QEMU needs a separate C object for each instance. Start with the same design requirement for a smaller device named mydev. It has a configurable starting count and an optional label. Each instance also has a working count that its implementation can update independently.

In QEMU, DeviceState is the base instance type for devices. A device derived from SysBusDevice gets that base through its parent. In C, declare the immediate parent as the first member, then declare the device's own fields. QOM can use the same object address through the parent type because the embedded parent begins at the start of the structure. OBJECT_DECLARE_SIMPLE_TYPE declares the instance type and provides the MYDEV() cast helper. The final argument, MYDEV, is the C token used for that helper. The string "mydev" is the registered name used for type lookup.

c
#include "qemu/osdep.h"
#include "hw/sysbus.h"
#include "hw/qdev-properties.h"
#include "qapi/error.h"
#include "qemu/module.h"

#define TYPE_MYDEV "mydev"
OBJECT_DECLARE_SIMPLE_TYPE(MyDevState, MYDEV)

struct MyDevState {
    SysBusDevice parent_obj;

    uint32_t initial_count;
    char *label;
    uint32_t count;
};

Read the three C blocks in order as one QEMU source file. They use QEMU's internal headers and belong in its source build, which provides the generated headers and build settings. The board-specific integration is separate from this declaration.

initial_count and label hold configuration supplied by the caller. count holds the current value of the model. Suppose a caller requests a starting count of 12. Realization can copy 12 into count, and later operations can change count while initial_count continues to describe the original configuration. A second instance gets its own storage for all three fields. If the two instances receive different values, each realization reads the configuration from its own object. The C field name matters to the implementation, while a property name is the spelling other code and command-line users see.

Device instance inheritanceDeviceStateSysBusDeviceMyDevStateConfiguration and working countDeviceStateSysBusDeviceMyDevStateConfiguration and workingcount
MyDevState embeds SysBusDevice, which provides the DeviceState base.

The type declaration below uses .parent = TYPE_SYS_BUS_DEVICE to tell QOM which parent class to inherit, and .instance_size = sizeof(MyDevState) to give QOM enough storage for the full structure. Both declarations must agree. If the structure changes when you add a field, sizeof(MyDevState) gives the updated size automatically. The callbacks identified in the declaration serve different purposes. Class initialization sets up behavior and property definitions shared by the type. Instance initialization runs for each newly created object.

02

Define properties and use them at realization

3 min read

A qdev property gives a device field a public name and a type. In DEFINE_PROP_UINT32("initial-count", MyDevState, initial_count, 0), the first argument is the name callers use, the next two locate the field in the instance structure, and the last argument supplies its default. DEFINE_PROP_STRING("label", MyDevState, label) ties the property label to the char *label field. With no label supplied, the field starts as NULL. The qdev string property manages the string storage. If device code needs to retain the text independently of the instance, it should make its own copy.

c
static Property mydev_properties[] = {
    DEFINE_PROP_UINT32("initial-count", MyDevState, initial_count, 0),
    DEFINE_PROP_STRING("label", MyDevState, label),
    DEFINE_PROP_END_OF_LIST(),
};

static void mydev_init(Object *obj)
{
    MyDevState *s = MYDEV(obj);

    s->count = 0;
}

static void mydev_realize(DeviceState *dev, Error **errp)
{
    MyDevState *s = MYDEV(dev);

    if (s->label && s->label[0] == '\0') {
        error_setg(errp, "mydev label must be nonempty when supplied");
        return;
    }

    s->count = s->initial_count;
}

static void mydev_class_init(ObjectClass *klass, void *data)
{
    DeviceClass *dc = DEVICE_CLASS(klass);

    (void)data;
    dc->realize = mydev_realize;
    dc->user_creatable = true;
    device_class_set_props(dc, mydev_properties);
}

For instance initialization, QOM has already provided the object's storage, and the caller still has to apply its explicit property settings. Use .instance_init for setup that can run as soon as the object is constructed. Here it shows where unconditional state initialization belongs. The assignment to zero is explicit for teaching purposes, since new instance storage is already zero-initialized. Reading initial_count here would be too early to obtain an explicit command-line or board value.

runs after the caller has set the requested property values. mydev_realize uses MYDEV(dev) to access the full instance from the base pointer it receives. It then checks a device-specific rule. Omitting label is allowed, while supplying an empty label causes realization to fail. An empty string is a valid string value, so accepting it as a property assignment and rejecting it during device setup are two distinct operations. error_setg reports the reason through errp, and the early return prevents the callback from applying the remaining setup.

If an allowed machine processes -device mydev,initial-count=12,label=demo, QEMU looks up mydev, creates an instance and matches the two option names against the property definitions. The unsigned integer property parses 12 and stores it in initial_count. The string property stores demo in label. Then mydev_realize validates the label and sets count to 12. Omitting initial-count lets the declared default of 0 apply. A misspelled property name or a value that the unsigned integer property cannot parse fails during property setting, before the device callback can use it. A later change to count is private model state because the property table exposes only initial-count and label.

Construction and realizationCreateinstanceRun instance_initSetexplicitpropertiesRun realizeValidateand copycountCreateinstanceRun instance_initSetexplicitpropertiesRun realizeValidateand copycount
Explicit property settings are applied after instance initialization and before realization.
03

Register the type and choose who creates it

2 min read

The final block makes the type known to QEMU. type_register_static registers the TypeInfo, and type_init arranges for the registration function to be run during QEMU's initialization. The implementation must be included in the QEMU build for the target you run. Once the type is registered, its name can be looked up. An instance is created when machine code or an accepted device option requests one.

c
static const TypeInfo mydev_type_info = {
    .name = TYPE_MYDEV,
    .parent = TYPE_SYS_BUS_DEVICE,
    .instance_size = sizeof(MyDevState),
    .instance_init = mydev_init,
    .class_init = mydev_class_init,
};

static void mydev_register_types(void)
{
    type_register_static(&mydev_type_info);
}

type_init(mydev_register_types)

Use board creation when the device belongs in the machine's hardware definition. The board initialization code calls qdev_new(TYPE_MYDEV) to create a DeviceState *. Before realization, it can set the same named properties with qdev_prop_set_uint32(dev, "initial-count", 12) and qdev_prop_set_string(dev, "label", "demo"). The board can then call sysbus_realize_and_unref(SYS_BUS_DEVICE(dev), errp). That helper attempts to realize the device on the system bus and drops the caller's reference. A caller using a recoverable error pointer checks the Boolean result and stops device setup if realization fails. In this route, the machine code supplies the instance count and configuration.

Use command-line creation when users should be able to request an instance explicitly. The option -device mydev,initial-count=12,label=demo is an option fragment for a QEMU build containing this type and a compatible machine. QEMU must consider the class user-creatable. The SysBusDevice parent class sets user_creatable to false for its subclasses, which is why mydev_class_init above sets dc->user_creatable = true. The selected machine must also permit dynamic creation of this SysBus device type: machine code opts in with machine_class_allow_dynamic_sysbus_dev(mc, TYPE_MYDEV), and machines without that call reject the option. Some machines restrict which SysBus types users can add. The parent type and the property table alone give no indication that a particular machine permits the request. Diagnose a rejected invocation by checking type availability, class and machine policy, and then the property names and values. Those checks address separate failure points.

Two ways to create mydevBoard codeCommand lineType lookupTYPE_MYDEVmydevSettingsTyped qdevsettersNamed deviceoptionsCreationrequirementBoardrequestsinstanceClass andmachinepermitDevice callbackmydev_realizemydev_realize
Board code and an accepted device option can both configure and realize an instance of the registered type.

A successful realization here produces a configured QEMU object with a working count. For the Linux guest, a board-defined peripheral needs a guest-visible interface and a way for Linux to identify it. The kernel's Platform Devices and Drivers and Device Drivers documentation describe the Linux side of that boundary. The next lesson, MMIO registers and IRQ lines, explains how to give the object registers the guest can access and an interrupt line the model can signal.

Key takeaways

  • TypeInfo declares the type name, parent, instance size, and initialization callbacks.
  • A SysBusDevice subclass embeds SysBusDevice first and stores its own fields after it.
  • Property setters write typed values into instance fields before realize runs.
  • The selected machine must permit a user-created SysBus device for -device to work.
Reflect
  1. Explain to a colleague, in two sentences: declare and register a QOM type derived from SysBusDevice.
  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

Official documentation first. Links checked when the lesson was published.

Find your next step

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