Create a device in QEMU

This document explains how QEMU parses and initializes devices specified via the -device command-line option.


1. Parsing the -device Option

During command-line parsing, all parameters following -device are stored in:

qemu_device_opts

Each -device instance becomes a QemuOpts structure that records driver name and key-value properties.


2. Registering Device Types

Before devices can be instantiated, their types must be registered. This happens during module initialization:

module_call_init(MODULE_INIT_DEVICE)

This step ensures all device types are added to the system’s internal device registry.


3. Creating Devices from Parsed Options

QEMU iterates over all parsed device options:

qemu_opts_foreach(&qemu_device_opts, device_init_func, NULL, 1)

For each option entry, device_init_func() is invoked, which eventually calls:

qdev_device_add(opts)

4. Inside qdev_device_add()

The core device creation logic happens here.

a) Get Driver Name

driver = qemu_opt_get(opts, "driver")

b) Locate Device Type

info = qdev_find_info(NULL, driver)

This retrieves the corresponding DeviceInfo structure.

c) Get Bus Path

path = qemu_opt_get(opts, "bus")

d) Resolve Bus Instance

If a bus path is provided:

  • If path starts with "/", search from main_system_bus
  • Otherwise, use recursive search

Internally:

  • qbus_find() finds root bus
  • qbus_find_recursive() walks the hierarchy
  • qbus_find_dev() locates device
  • qbus_find_bus() locates child bus

If no path is provided, QEMU automatically selects an appropriate bus using recursive search.

e) Create Device Object

dev = qdev_create_from_info(bus, info)

This returns a DeviceState instance.

f) Assign Device ID (Optional)

if (qemu_opts_id(opts))
    qdev->id = qemu_opts_id(opts);

g) Set Device Properties

qemu_opt_foreach(opts, set_property, qdev, 1)

All key-value pairs passed via -device are applied here.

h) Initialize Device

qdev_init(dev)

This triggers:

dev->info->init()

At this stage, the device is fully constructed and ready for use.


5. Summary of Execution Flow


-device option
   ↓
parse → qemu_device_opts
   ↓
module_call_init(MODULE_INIT_DEVICE)
   ↓
qemu_opts_foreach(...)
   ↓
device_init_func()
   ↓
qdev_device_add()
   ↓
bus resolution
   ↓
qdev_create_from_info()
   ↓
set properties
   ↓
qdev_init()
   ↓
dev->info->init()

Key Concepts

  • QemuOpts: stores parsed command-line options
  • DeviceInfo: metadata for device type
  • DeviceState: runtime device instance
  • BusState: bus topology representation

Understanding this flow is essential when debugging:

  • -device creation failures
  • Bus resolution issues
  • Property misconfiguration
  • Device initialization crashes

This pipeline represents the core of QEMU’s device model infrastructure.

← Previous Post
Next Post →

Leave a Comment