Skip to contentSkip to conversation

hw/arm: Introduce generic FDT-driven machine

PATCH Superseded Ruslan Ruslichenko 5 participants 43 messages Feb 19 – Mar 2 Arm/Amlogic Meson SoC support

v2 of 3 Superseded Latest is v3 →

lore
Share & tools
lore
#0 lore raw

v2 cover hw/arm: Introduce generic FDT-driven machine

From: Ruslan Ruslichenko <[email protected]>

This patch series introduces a new ARM machine model, arm-generic-fdt, and the underlying infrastructure required to instantiate a QEMU machine entirely from a Device Tree.

Key Features in v2
This version add support for an sbsa-ref compatible platform. Major additions include:

GICv3: via the FDTGenericIntc interface.
GPEX PCI Host: Dynamic mapping of MMIO windows via aliases and irq routing via a new gsi-irqs property. Block Devices: New support for binding QEMU block backends to FDT nodes using blockdev.
Testing: Added two new functional tests ensuring the machine can boot successfully similar sbsa-ref platform.

Also addressed comments received in v1.

Origin & Motivation
This feature originates from the AMD QEMU repository (https://github.com/Xilinx/qemu).

Currently, adding support for a new ARM board in QEMU requires writing a dedicated C source file to define the memory map, instantiate devices, and wire interrupts. Any modification to the board configuration requires a corresponding change in the source code and a rebuild of the QEMU binary.

This series introduces an alternative approach: defining the board configuration via a Device Tree Blob (DTB) provided at the command line. The new arm-generic-fdt machine parses this DTB at runtime to dynamically construct the system topology.

Beyond providing more flexible board creation, this infrastructure is a prerequisite for enabling Hardware Co-Simulation workflows (e.g., using the Remote-Port protocol: https://mail.gnu.org/archive/html/qemu-devel/2026-02/msg01760.html).
In mixed simulation environments where QEMU emulates the CPU subsystem and an external simulator (such as SystemC) handles custom logic, the memory map and interrupt lines often need to change dynamically based on the external hardware configuration, making static C models impractical.

Implementation Overview
The series implements an FDT loading framework in hw/core/fdt_generic_util.c capable of:

Parsing and creating device models from FDT nodes.
Setting QOM properties based on FDT properties.
Connecting IRQs for SysBus devices (via FDTGenericIntc). Mapping memory regions for IO devices or system RAM (via FDTGenericMMap). Attaching block devices specified via blockdev interface.
NOTE: GPIO wiring for non-SysBus devices is not supported yet.

Testing
Testing can be performed by two scripts within patch series.
Pre-compiled dtb binaries for tests are currently placed at tests/data/dtb/aarch64/arm-generic-fdt.

The Device Trees sources used for testing can be found by following links:

Hardware DTS (used with -hw-dtb): https://gist.github.com/ruslichenkor/82245d89fb2a64dc7f1b694504cb840e#file-arm64-sbsa-hw-dts

Guest DTS (used with -dtb): https://gist.github.com/ruslichenkor/82245d89fb2a64dc7f1b694504cb840e#file-arm64-sbsa-guest-dts

Also example command to launch VM is following:

/qemu/build/qemu-system-aarch64

	-machine arm-generic-fdt \
	-hw-dtb arm64-sbsa-hw.dtb
	-dtb sbsa-ref.dtb
	-serial mon:stdio \
	-netdev user,id=net0
	-device e1000e,netdev=net0 \
	-device bochs-display \
	-blockdev driver=file,filename=./SBSA_FLASH0.fd,node-name=pflash0 \
	-blockdev driver=file,filename=./SBSA_FLASH1.fd,node-name=pflash1 \
	-device usb-kbd -device usb-tablet \
	-drive file=./alpine-standard-3.23.3-aarch64.iso,if=none,id=cdrom0,readonly=on \
	-device ide-cd,bus=ahci.0,unit=0,drive=cdrom0

Open Questions
Location of Test Binaries:
I have added the compiled Device Tree Blobs (DTB) required for the functional tests into tests/data/dtb.

Question: Is this the preferred location for static test binaries, or should they be placed elsewhere?

Patch Summary
hw/core: Add Generic FDT parsing infrastructure and utility functions (fdt_generic_util) hw/arm: Add the arm-generic-fdt machine model
hw/core/sysbus: Add IO memory mapping for standard SysBus devices system/memory: Allow MemoryRegions to be configured from FDT
hw/intc: Add FDT support for ARM GICv3 (IRQ translation and default wiring) hw/pci-host: Add gsi-irqs property for INTx mapping
target/arm: Add FDT support for CPU timers

BR,
Ruslan Ruslichenko

Ruslan Ruslichenko (33):
system/device_tree: update qemu_fdt_getprop_cell system/device_tree: add few parsing and traversal helpers util/log: add log entry for fdt generic utils
hw/core: introduce generic FDT device model registry hw/core/fdt_generic: implement FDT machine creation helpers hw/core/fdt_generic: add cpu clusters management hw/core/fdt_generic_util: implement main fdt parse routine hw/core/fdt_generic_util: implement fdt_init_qdev
qdev: Add qdev_prop_get_array_elem_type() helper hw/core/fdt_generic_util: initilize qdev properties from fdt hw/core/fdt_generic_util: actually realize device hw/core/fdt_generic_util: add TYPE_FDT_GENERIC_MMAP hw/core/fdt_generic_util: add TYPE_FDT_GENERIC_INTC hw/core/fdt_generic_util: implement fdt_get_irq/_info API hw/core/fdt_generic_util: map device memory hw/core/fdt_generic_util: Connect device irqs hw/core/fdt_generic_util: realize cpu clusters
hw/core: add fdt_generic to the build
hw/core/machine: add '-hw-dtb' option for machine
hw/arm: add generic ARM machine initialized by FDT hw/core/sysbus: implement FDT_GENERIC_MMAP_CLASS interface hw/intc/arm_gic: implement FDT_GENERIC_INTC and fdt support target/arm/cpu: add fdt support for armv8-timer qom/object: export object_resolve_link()
system/memory: add setters for MemoryRegion properties system/memory: implement FDT_GENERIC_MMAP interface hw/core/fdt_generic_util: initialize serial devices system/memory: add QOM aliases for fdt support hw/intc/arm_gicv3: Implement FDTGenericIntc interface hw/core/fdt_generic_util: Add deferred device initialization support hw/core/fdt_generic_util: Add blockdev binding support hw/pci-host: add gsi-irqs property array tests/functional: Add functional tests for arm-generic-fdt machine

 hw/arm/arm_generic_fdt.c                      |  180 +++
 hw/arm/boot.c                                 |    8 +-
 hw/arm/meson.build                            |    2 +
 hw/arm/raspi4b.c                              |    8 +-
 hw/arm/vexpress.c                             |    4 +-
 hw/core/fdt_generic.c                         |  286 ++++
 hw/core/fdt_generic_util.c                    | 1414 +++++++++++++++++
 hw/core/machine.c                             |   19 +
 hw/core/meson.build                           |    2 +
 hw/core/qdev-properties.c                     |   12 +
 hw/core/sysbus.c                              |   28 +
 hw/intc/arm_gic.c                             |   32 +
 hw/intc/arm_gic_common.c                      |   50 +
 hw/intc/arm_gicv3.c                           |   45 +
 hw/intc/arm_gicv3_common.c                    |   68 +
 hw/pci-host/gpex.c                            |    6 +
 include/hw/core/boards.h                      |    1 +
 include/hw/core/fdt_generic.h                 |  135 ++
 include/hw/core/fdt_generic_util.h            |  140 ++
 include/hw/core/qdev-properties.h             |    1 +
 include/hw/pci-host/gpex.h                    |    3 +
 include/qemu/log.h                            |    1 +
 include/qom/object.h                          |   12 +
 include/system/device_tree.h                  |   35 +-
 qemu-options.hx                               |    9 +
 qom/object.c                                  |    2 +-
 system/device_tree.c                          |  237 ++-
 system/memory.c                               |  378 ++++-
 system/vl.c                                   |    3 +
 target/arm/cpu.c                              |  115 ++
 .../arm-generic-fdt/arm64-sbsa-guest.dtb      |  Bin 0 -> 673 bytes
 .../aarch64/arm-generic-fdt/arm64-sbsa-hw.dtb |  Bin 0 -> 5414 bytes
 tests/functional/aarch64/meson.build          |    2 +
 .../aarch64/test_arm_generic_fdt.py           |  114 ++
 .../aarch64/test_arm_generic_fdt_alpine.py    |   61 +
 util/log.c                                    |    1 +
 36 files changed, 3386 insertions(+), 28 deletions(-)
 create mode 100644 hw/arm/arm_generic_fdt.c
 create mode 100644 hw/core/fdt_generic.c
 create mode 100644 hw/core/fdt_generic_util.c
 create mode 100644 include/hw/core/fdt_generic.h
 create mode 100644 include/hw/core/fdt_generic_util.h
 create mode 100644 tests/data/dtb/aarch64/arm-generic-fdt/arm64-sbsa-guest.dtb
 create mode 100644 tests/data/dtb/aarch64/arm-generic-fdt/arm64-sbsa-hw.dtb
 create mode 100755 tests/functional/aarch64/test_arm_generic_fdt.py
 create mode 100755 tests/functional/aarch64/test_arm_generic_fdt_alpine.py
Signature · 1 line
2.43.0
#1 lore raw

PATCH v2 2/33 system/device_tree: add few parsing and traversal helpers

From: Ruslan Ruslichenko <[email protected]>

The patch adds few utility functions for parsing FDT nodes. The helpers are required for upcoming Hardware device tree feature.

---
 include/system/device_tree.h |  30 +++++
 system/device_tree.c         | 221 +++++++++++++++++++++++++++++++++++
 2 files changed, 251 insertions(+)
include/system/device_tree.h +30 -0
index 5667ff9538..9d6b570bdb 100644
@@ -116,6 +116,11 @@ const void *qemu_fdt_getprop(void *fdt, const char *node_path,
 uint32_t qemu_fdt_getprop_cell(void *fdt, const char *node_path,
                                const char *property, int cell_id,
                                Error **errp);
+
+const void *qemu_fdt_getprop_inherited(void *fdt, const char *node_path,
+                             const char *property, int *lenp, Error **errp);
+uint32_t qemu_fdt_getprop_cell_inherited(void *fdt, const char *node_path,
+                               const char *property, int cell_id, Error **errp);
 uint32_t qemu_fdt_get_phandle(void *fdt, const char *path);
 uint32_t qemu_fdt_alloc_phandle(void *fdt);
 int qemu_fdt_nop_node(void *fdt, const char *node_path);
@@ -191,6 +196,31 @@ int qemu_fdt_setprop_sized_cells_from_array(void *fdt,
                                                 qdt_tmp);                 \
     })
 
+typedef struct QEMUDevtreeProp {
+    const char *name;
+    int len;
+    const void *value;
+} QEMUDevtreeProp;
+
+/* node queries */
+
+int qemu_devtree_get_num_children(void *fdt, const char *node_path);
+int qemu_devtree_get_children(void *fdt, const char *node_path,
+                                     int max_paths, char **returned_paths);
+int qemu_devtree_num_props(void *fdt, const char *node_path);
+QEMUDevtreeProp *qemu_devtree_get_props(void *fdt, const char *node_path);
+
+/* node getters */
+
+int qemu_devtree_get_node_by_phandle(void *fdt, char *node_path, int phandle);
+int qemu_devtree_getparent(void *fdt, char *node_path,
+                           const char *current);
+
+/* misc */
+
+int devtree_get_num_nodes(void *fdt);
+
+#define DT_PATH_LENGTH 1024
 
 /**
  * qemu_fdt_randomize_seeds:
system/device_tree.c +221 -0

233 lines not on this page · raw message

Signature · 1 line
2.43.0
#2 lore raw

Re: [PATCH v2 02/33] system/device_tree: add few parsing and traversal helpers

Quoted 29 lines · Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]>

The patch adds few utility functions for parsing FDT nodes. The helpers are required for upcoming Hardware device tree feature.

---
 include/system/device_tree.h |  30 +++++
 system/device_tree.c         | 221 +++++++++++++++++++++++++++++++++++
 2 files changed, 251 insertions(+)
include/system/device_tree.h +5 -0
index 5667ff9538..9d6b570bdb 100644
@@ -116,6 +116,11 @@ const void *qemu_fdt_getprop(void *fdt, const char *node_path,
 uint32_t qemu_fdt_getprop_cell(void *fdt, const char *node_path,
                                const char *property, int cell_id,
                                Error **errp);
+
+const void *qemu_fdt_getprop_inherited(void *fdt, const char *node_path,
+                             const char *property, int *lenp, Error **errp);
+uint32_t qemu_fdt_getprop_cell_inherited(void *fdt, const char *node_path,
+                               const char *property, int cell_id, Error **errp);
 uint32_t qemu_fdt_get_phandle(void *fdt, const char *path);
 uint32_t qemu_fdt_alloc_phandle(void *fdt);
 int qemu_fdt_nop_node(void *fdt, const char *node_path);

include/system/device_tree.h int qemu_fdt_setprop_sized_cells_from_array(void *fdt, · line 203

Quoted 8 lines
include/system/device_tree.h +5 -0
@@ -191,6 +196,31 @@ int qemu_fdt_setprop_sized_cells_from_array(void *fdt,
                                                 qdt_tmp);                 \
     })
 
+typedef struct QEMUDevtreeProp {
+    const char *name;
+    int len;
+    const void *value;
+} QEMUDevtreeProp;

If you need this, it really starts to seem to me that keeping the data structure in fdt is not the right choice any more. I've thought for a while that with increasing handling of the device tree by qemu, we should maybe have a "live" device tree representation (with pointers) that we use for manipulation. Right before boot, that can be serialized into fdt.

fdt is, fundamentally, a serialization format. Direct fdt manipulation with libfdt was really only intended as something to allow firmwares and similarly minimal programs to make small tweaks. Once manipulation becomes extensive, fdt is no longer a good choice of data structure.

Quoted 98 lines
include/system/device_tree.h +20 -0
+
+/* node queries */
+
+int qemu_devtree_get_num_children(void *fdt, const char *node_path);
+int qemu_devtree_get_children(void *fdt, const char *node_path,
+                                     int max_paths, char **returned_paths);
+int qemu_devtree_num_props(void *fdt, const char *node_path);
+QEMUDevtreeProp *qemu_devtree_get_props(void *fdt, const char *node_path);
+
+/* node getters */
+
+int qemu_devtree_get_node_by_phandle(void *fdt, char *node_path, int phandle);
+int qemu_devtree_getparent(void *fdt, char *node_path,
+                           const char *current);
+
+/* misc */
+
+int devtree_get_num_nodes(void *fdt);
+
+#define DT_PATH_LENGTH 1024
 
 /**
  * qemu_fdt_randomize_seeds:
system/device_tree.c +67 -0
index d2db7bd355..fc34c660db 100644
@@ -464,6 +464,103 @@ uint32_t qemu_fdt_getprop_cell(void *fdt, const char *node_path,
     return be32_to_cpu(p[cell_id]);
 }
 
+const void *qemu_fdt_getprop_inherited(void *fdt, const char *node_path,
+                             const char *property, int *lenp, Error **errp)
+{
+    const void *found_val = NULL;
+    int found_len = 0;
+    int curr_offset = 0;
+    int temp_len;
+    char **tokens;
+    char **iter;
+
+    found_val = fdt_getprop(fdt, 0, property, &found_len);
+
+    tokens = g_strsplit(node_path + 1, "/", -1);
+
+    for (iter = tokens; *iter != NULL; iter++) {
+        if (**iter == '\0') {
+            continue;
+        }
+
+        curr_offset = fdt_subnode_offset(fdt, curr_offset, *iter);
+        if (curr_offset < 0) {
+            error_setg(errp, "%s: Path '%s' not found",
+                       __func__, *iter);
+            g_strfreev(tokens);
+            return NULL;
+        }
+
+        const void *val = fdt_getprop(fdt, curr_offset, property, &temp_len);
+        if (val) {
+            found_val = val;
+            found_len = temp_len;
+        }
+    }
+    g_strfreev(tokens);
+
+    if (!found_val) {
+        error_setg(errp, "%s: Property '%s' not found",
+                   __func__, property);
+        return NULL;
+    }
+
+    if (lenp) {
+        *lenp = found_len;
+    }
+
+    return found_val;
+}
+
+uint32_t qemu_fdt_getprop_cell_inherited(void *fdt, const char *node_path,
+                               const char *property, int cell_id, Error **errp)
+{
+    int len;
+    const uint32_t *p;
+
+    p = qemu_fdt_getprop_inherited(fdt, node_path, property, &len, errp);
+    if (!p) {
+        return 0;
+    }
+    if (len < (cell_id + 1) * 4) {
+        error_setg(errp,
+                   "%s: %s/%s is too short, need %d bytes for cell ind %d",
+                   __func__, node_path, property, (cell_id + 1) * 4, cell_id);
+        return 0;
+    }
+    return be32_to_cpu(p[cell_id]);
+}
+

system/device_tree.c uint32_t qemu_fdt_getprop_cell(void *fdt, const char *node_path, · line 543

Quoted 10 lines
system/device_tree.c +10 -0
+int qemu_devtree_getparent(void *fdt, char *node_path, const char *current)
+{
+    const char *sep;
+    int len;
+
+    if (!current || !node_path) {
+        return -FDT_ERR_NOTFOUND;
+    }
+
+    if (current[0] == '/' && current[1] == 0) {

strcmp() against "/" is maybe marginally more costly, but clearer in meaning.

Quoted 6 lines
system/device_tree.c +6 -0
+        return -FDT_ERR_NOTFOUND;
+    }
+
+    sep = strrchr(current, '/');
+    if (!sep) {
+        return -FDT_ERR_BADPATH;

system/device_tree.c uint32_t qemu_fdt_getprop_cell(void *fdt, const char *node_path, · line 559

Quoted 10 lines
system/device_tree.c +10 -0
+    }
+
+    if (sep == current) {
+        len = 1;
+    } else {
+        len = sep - current;
+    }
+
+    memcpy(node_path, current, len);
+    node_path[len] = '\0';

This assumes node_path points to a long enough buffer. Returning a g_strndup()ed copy of the parent path might be a nicer interface?

Quoted 141 lines
system/device_tree.c +128 -0
+
+    return 0;
+}
+
 uint32_t qemu_fdt_get_phandle(void *fdt, const char *path)
 {
     uint32_t r;
@@ -631,6 +728,130 @@ out:
     return ret;
 }
 
+int qemu_devtree_num_props(void *fdt, const char *node_path)
+{
+    int offset = fdt_path_offset(fdt, node_path);
+    int ret = 0;
+
+    for (offset = fdt_first_property_offset(fdt, offset);
+            offset != -FDT_ERR_NOTFOUND;
+            offset = fdt_next_property_offset(fdt, offset)) {
+        ret++;
+    }
+    return ret;
+}
+
+QEMUDevtreeProp *qemu_devtree_get_props(void *fdt, const char *node_path)
+{
+    QEMUDevtreeProp *ret = g_new0(QEMUDevtreeProp,
+                                    qemu_devtree_num_props(fdt, node_path) + 1);
+    int offset = fdt_path_offset(fdt, node_path);
+    int i = 0;
+
+    for (offset = fdt_first_property_offset(fdt, offset);
+            offset != -FDT_ERR_NOTFOUND;
+            offset = fdt_next_property_offset(fdt, offset)) {
+        const char *propname;
+        const void *val = fdt_getprop_by_offset(fdt, offset, &propname,
+                                                    &ret[i].len);
+
+        ret[i].name = propname;
+        ret[i].value = val;
+        i++;
+    }
+    return ret;
+}
+
+int qemu_devtree_get_children(void *fdt, const char *node_path,
+                                     int max_paths, char **returned_paths) {
+    int count = 0;
+    int subnode;
+    const char *name;
+    int offset = fdt_path_offset(fdt, node_path);
+
+    if (offset < 0) {
+        return offset;
+    }
+
+    bool is_root = (strcmp(node_path, "/") == 0);
+
+    fdt_for_each_subnode(subnode, fdt, offset) {
+        if (count >= max_paths) {
+            break;
+        }
+        name = fdt_get_name(fdt, subnode, NULL);
+        if (returned_paths) {
+            returned_paths[count] = g_strdup_printf("%s/%s",
+                                                is_root ? "" : node_path, name);
+        }
+
+        ++count;
+    }
+
+    return count;
+}
+
+int qemu_devtree_get_num_children(void *fdt, const char *node_path)
+{
+    int count = 0;
+    int subnode;
+    int offset = fdt_path_offset(fdt, node_path);
+
+    if (offset < 0) {
+        return offset;
+    }
+
+    fdt_for_each_subnode(subnode, fdt, offset) {
+        ++count;
+    }
+
+    return count;
+}
+
+int qemu_devtree_get_node_by_phandle(void *fdt, char *node_path, int phandle)
+{
+    int offset = 0, cur_depth = 0;
+    int path_lens[64] = { 0 };
+
+    for (offset = 0; offset >= 0; offset = fdt_next_node(fdt, offset,
+                                                         &cur_depth)) {
+        if (cur_depth > 64) {
+            break;
+        }
+        const char *name = fdt_get_name(fdt, offset, NULL);
+
+        int parent_len = (cur_depth > 0) ? path_lens[cur_depth - 1] : 0;
+        int len = snprintf(node_path + parent_len,
+                             DT_PATH_LENGTH - parent_len,
+                             "%s%s",
+                             (parent_len > 1) ? "/" : "",
+                             (cur_depth == 0) ? "/" : name);
+
+        path_lens[cur_depth] = parent_len + len;
+
+        if (fdt_get_phandle(fdt, offset) == phandle) {
+            return 0;
+        }
+    }
+
+    return -FDT_ERR_NOTFOUND;
+}
+
+int devtree_get_num_nodes(void *fdt)
+{
+    int num_nodes = 0;
+    int depth = 0, offset = 0;
+
+    for (;;) {
+        offset = fdt_next_node(fdt, offset, &depth);
+        num_nodes++;
+        if (offset <= 0 || depth <= 0) {
+            break;
+        }
+    }
+    return num_nodes;
+}
+
 void qmp_dumpdtb(const char *filename, Error **errp)
 {
     ERRP_GUARD();
Signature · 1 line
2.43.0
Signature · 4 lines
David Gibson (he or they)	| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you, not the other way
				| around.
http://www.ozlabs.org/~dgibson
#3 lore raw

Re: [PATCH v2 02/33] system/device_tree: add few parsing and traversal helpers

Quoted 47 lines · David Gibson
Quoted 29 lines · Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]>

The patch adds few utility functions for parsing FDT nodes. The helpers are required for upcoming Hardware device tree feature.

---
 include/system/device_tree.h |  30 +++++
 system/device_tree.c         | 221 +++++++++++++++++++++++++++++++++++
 2 files changed, 251 insertions(+)
include/system/device_tree.h +5 -0
index 5667ff9538..9d6b570bdb 100644
@@ -116,6 +116,11 @@ const void *qemu_fdt_getprop(void *fdt, const char *node_path,
 uint32_t qemu_fdt_getprop_cell(void *fdt, const char *node_path,
                                const char *property, int cell_id,
                                Error **errp);
+
+const void *qemu_fdt_getprop_inherited(void *fdt, const char *node_path,
+                             const char *property, int *lenp, Error **errp);
+uint32_t qemu_fdt_getprop_cell_inherited(void *fdt, const char *node_path,
+                               const char *property, int cell_id, Error **errp);
 uint32_t qemu_fdt_get_phandle(void *fdt, const char *path);
 uint32_t qemu_fdt_alloc_phandle(void *fdt);
 int qemu_fdt_nop_node(void *fdt, const char *node_path);

include/system/device_tree.h int qemu_fdt_setprop_sized_cells_from_array(void *fdt, · line 203

Quoted 8 lines
include/system/device_tree.h +5 -0
@@ -191,6 +196,31 @@ int qemu_fdt_setprop_sized_cells_from_array(void *fdt,
                                                 qdt_tmp);                 \
     })
 
+typedef struct QEMUDevtreeProp {
+    const char *name;
+    int len;
+    const void *value;
+} QEMUDevtreeProp;

If you need this, it really starts to seem to me that keeping the data structure in fdt is not the right choice any more. I've thought for a while that with increasing handling of the device tree by qemu, we should maybe have a "live" device tree representation (with pointers) that we use for manipulation. Right before boot, that can be serialized into fdt.

Quoted 6 lines

fdt is, fundamentally, a serialization format. Direct fdt manipulation with libfdt was really only intended as something to allow firmwares and similarly minimal programs to make small tweaks. Once manipulation becomes extensive, fdt is no longer a good choice of data structure.

For this series, the generic machine is strictly read-only regarding the FDT (we only parse it to instantiate devices, we don't manipulate or rewrite the tree).

So to simplify things, I can drop the QEMUDevtreeProp wrapper and just use standard
libfdt iteration macros (like fdt_for_each_property_offset) to keep the footprint
as small as possible.

Would this approach be acceptable for now? I can prepare this modification along with other review comments for v3 patch series.

Quoted 275 lines
Quoted 98 lines
include/system/device_tree.h +20 -0
+
+/* node queries */
+
+int qemu_devtree_get_num_children(void *fdt, const char *node_path);
+int qemu_devtree_get_children(void *fdt, const char *node_path,
+                                     int max_paths, char **returned_paths);
+int qemu_devtree_num_props(void *fdt, const char *node_path);
+QEMUDevtreeProp *qemu_devtree_get_props(void *fdt, const char *node_path);
+
+/* node getters */
+
+int qemu_devtree_get_node_by_phandle(void *fdt, char *node_path, int phandle);
+int qemu_devtree_getparent(void *fdt, char *node_path,
+                           const char *current);
+
+/* misc */
+
+int devtree_get_num_nodes(void *fdt);
+
+#define DT_PATH_LENGTH 1024
 
 /**
  * qemu_fdt_randomize_seeds:
system/device_tree.c +67 -0
index d2db7bd355..fc34c660db 100644
@@ -464,6 +464,103 @@ uint32_t qemu_fdt_getprop_cell(void *fdt, const char *node_path,
     return be32_to_cpu(p[cell_id]);
 }
 
+const void *qemu_fdt_getprop_inherited(void *fdt, const char *node_path,
+                             const char *property, int *lenp, Error **errp)
+{
+    const void *found_val = NULL;
+    int found_len = 0;
+    int curr_offset = 0;
+    int temp_len;
+    char **tokens;
+    char **iter;
+
+    found_val = fdt_getprop(fdt, 0, property, &found_len);
+
+    tokens = g_strsplit(node_path + 1, "/", -1);
+
+    for (iter = tokens; *iter != NULL; iter++) {
+        if (**iter == '\0') {
+            continue;
+        }
+
+        curr_offset = fdt_subnode_offset(fdt, curr_offset, *iter);
+        if (curr_offset < 0) {
+            error_setg(errp, "%s: Path '%s' not found",
+                       __func__, *iter);
+            g_strfreev(tokens);
+            return NULL;
+        }
+
+        const void *val = fdt_getprop(fdt, curr_offset, property, &temp_len);
+        if (val) {
+            found_val = val;
+            found_len = temp_len;
+        }
+    }
+    g_strfreev(tokens);
+
+    if (!found_val) {
+        error_setg(errp, "%s: Property '%s' not found",
+                   __func__, property);
+        return NULL;
+    }
+
+    if (lenp) {
+        *lenp = found_len;
+    }
+
+    return found_val;
+}
+
+uint32_t qemu_fdt_getprop_cell_inherited(void *fdt, const char *node_path,
+                               const char *property, int cell_id, Error **errp)
+{
+    int len;
+    const uint32_t *p;
+
+    p = qemu_fdt_getprop_inherited(fdt, node_path, property, &len, errp);
+    if (!p) {
+        return 0;
+    }
+    if (len < (cell_id + 1) * 4) {
+        error_setg(errp,
+                   "%s: %s/%s is too short, need %d bytes for cell ind %d",
+                   __func__, node_path, property, (cell_id + 1) * 4, cell_id);
+        return 0;
+    }
+    return be32_to_cpu(p[cell_id]);
+}
+

system/device_tree.c uint32_t qemu_fdt_getprop_cell(void *fdt, const char *node_path, · line 543

Quoted 10 lines
system/device_tree.c +10 -0
+int qemu_devtree_getparent(void *fdt, char *node_path, const char *current)
+{
+    const char *sep;
+    int len;
+
+    if (!current || !node_path) {
+        return -FDT_ERR_NOTFOUND;
+    }
+
+    if (current[0] == '/' && current[1] == 0) {

strcmp() against "/" is maybe marginally more costly, but clearer in meaning.

Quoted 6 lines
system/device_tree.c +6 -0
+        return -FDT_ERR_NOTFOUND;
+    }
+
+    sep = strrchr(current, '/');
+    if (!sep) {
+        return -FDT_ERR_BADPATH;

system/device_tree.c uint32_t qemu_fdt_getprop_cell(void *fdt, const char *node_path, · line 559

Quoted 10 lines
system/device_tree.c +10 -0
+    }
+
+    if (sep == current) {
+        len = 1;
+    } else {
+        len = sep - current;
+    }
+
+    memcpy(node_path, current, len);
+    node_path[len] = '\0';

This assumes node_path points to a long enough buffer. Returning a g_strndup()ed copy of the parent path might be a nicer interface?

Quoted 139 lines
system/device_tree.c +128 -1
+
+    return 0;
+}
+
 uint32_t qemu_fdt_get_phandle(void *fdt, const char *path)
 {
     uint32_t r;
@@ -631,6 +728,130 @@ out:
     return ret;
 }
 
+int qemu_devtree_num_props(void *fdt, const char *node_path)
+{
+    int offset = fdt_path_offset(fdt, node_path);
+    int ret = 0;
+
+    for (offset = fdt_first_property_offset(fdt, offset);
+            offset != -FDT_ERR_NOTFOUND;
+            offset = fdt_next_property_offset(fdt, offset)) {
+        ret++;
+    }
+    return ret;
+}
+
+QEMUDevtreeProp *qemu_devtree_get_props(void *fdt, const char *node_path)
+{
+    QEMUDevtreeProp *ret = g_new0(QEMUDevtreeProp,
+                                    qemu_devtree_num_props(fdt, node_path) + 1);
+    int offset = fdt_path_offset(fdt, node_path);
+    int i = 0;
+
+    for (offset = fdt_first_property_offset(fdt, offset);
+            offset != -FDT_ERR_NOTFOUND;
+            offset = fdt_next_property_offset(fdt, offset)) {
+        const char *propname;
+        const void *val = fdt_getprop_by_offset(fdt, offset, &propname,
+                                                    &ret[i].len);
+
+        ret[i].name = propname;
+        ret[i].value = val;
+        i++;
+    }
+    return ret;
+}
+
+int qemu_devtree_get_children(void *fdt, const char *node_path,
+                                     int max_paths, char **returned_paths) {
+    int count = 0;
+    int subnode;
+    const char *name;
+    int offset = fdt_path_offset(fdt, node_path);
+
+    if (offset < 0) {
+        return offset;
+    }
+
+    bool is_root = (strcmp(node_path, "/") == 0);
+
+    fdt_for_each_subnode(subnode, fdt, offset) {
+        if (count >= max_paths) {
+            break;
+        }
+        name = fdt_get_name(fdt, subnode, NULL);
+        if (returned_paths) {
+            returned_paths[count] = g_strdup_printf("%s/%s",
+                                                is_root ? "" : node_path, name);
+        }
+
+        ++count;
+    }
+
+    return count;
+}
+
+int qemu_devtree_get_num_children(void *fdt, const char *node_path)
+{
+    int count = 0;
+    int subnode;
+    int offset = fdt_path_offset(fdt, node_path);
+
+    if (offset < 0) {
+        return offset;
+    }
+
+    fdt_for_each_subnode(subnode, fdt, offset) {
+        ++count;
+    }
+
+    return count;
+}
+
+int qemu_devtree_get_node_by_phandle(void *fdt, char *node_path, int phandle)
+{
+    int offset = 0, cur_depth = 0;
+    int path_lens[64] = { 0 };
+
+    for (offset = 0; offset >= 0; offset = fdt_next_node(fdt, offset,
+                                                         &cur_depth)) {
+        if (cur_depth > 64) {
+            break;
+        }
+        const char *name = fdt_get_name(fdt, offset, NULL);
+
+        int parent_len = (cur_depth > 0) ? path_lens[cur_depth - 1] : 0;
+        int len = snprintf(node_path + parent_len,
+                             DT_PATH_LENGTH - parent_len,
+                             "%s%s",
+                             (parent_len > 1) ? "/" : "",
+                             (cur_depth == 0) ? "/" : name);
+
+        path_lens[cur_depth] = parent_len + len;
+
+        if (fdt_get_phandle(fdt, offset) == phandle) {
+            return 0;
+        }
+    }
+
+    return -FDT_ERR_NOTFOUND;
+}
+
+int devtree_get_num_nodes(void *fdt)
+{
+    int num_nodes = 0;
+    int depth = 0, offset = 0;
+
+    for (;;) {
+        offset = fdt_next_node(fdt, offset, &depth);
+        num_nodes++;
+        if (offset <= 0 || depth <= 0) {
+            break;
+        }
+    }
+    return num_nodes;
+}
+
 void qmp_dumpdtb(const char *filename, Error **errp)
 {
     ERRP_GUARD();
--
Quoted 2 lines

2.43.0

--

Quoted 4 lines
David Gibson (he or they)       | I'll have my music baroque, and my code
david AT gibson.dropbear.id.au  | minimalist, thank you, not the other way
                                | around.

http://www.ozlabs.org/~dgibson

--
BR,
Ruslan Ruslichenko

#4 lore raw

PATCH v2 3/33 util/log: add log entry for fdt generic utils

In reply to Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]>

Introduce dedicated log mask for hardware device
tree processing, to selectively enable diagnostic
for FDT-based machine creation.

---
 include/qemu/log.h | 1 +
 util/log.c         | 1 +
 2 files changed, 2 insertions(+)
include/qemu/log.h +1 -0
index 7effba4da4..984879fbd3 100644
@@ -38,6 +38,7 @@ bool qemu_log_separate(void);
 #define CPU_LOG_TB_VPU     (1u << 21)
 #define LOG_TB_OP_PLUGIN   (1u << 22)
 #define LOG_INVALID_MEM    (1u << 23)
+#define LOG_FDT            (1u << 24)
 
 /* Lock/unlock output. */
 
util/log.c +1 -0
index c44d66b5ce..c8310ddc58 100644
@@ -523,6 +523,7 @@ const QEMULogItem qemu_log_items[] = {
       "include VPU registers in the 'cpu' logging" },
     { LOG_INVALID_MEM, "invalid_mem",
       "log invalid memory accesses" },
+    { LOG_FDT, "fdt", "log Device Tree info." },
     { 0, NULL, NULL },
 };
 
Signature · 1 line
2.43.0
#5 lore raw

PATCH v2 4/33 hw/core: introduce generic FDT device model registry

In reply to Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]>

Introduce infrastructure to instantiate device models directly from the device tree.

This includes the registry of known device models with associated init functions and key API methods to operate it.

The MIT license of fdt_generic.c preserved as in original file from https://github.com/Xilinx/qemu.git repo.

The license for fdt_generic.h derived from matching fdt_generic.c file.

---
 hw/core/fdt_generic.c         | 139 ++++++++++++++++++++++++++++++++++
 include/hw/core/fdt_generic.h |  78 +++++++++++++++++++
 2 files changed, 217 insertions(+)
 create mode 100644 hw/core/fdt_generic.c
 create mode 100644 include/hw/core/fdt_generic.h
hw/core/fdt_generic.c new file +139 -0
new file mode 100644
index 0000000000..d3ab8f9132
@@ -0,0 +1,139 @@
+// SPDX-License-Identifier: MIT
+/*
+ * Tables of FDT device models and their init functions. Keyed by compatibility
+ * strings, device instance names.
+ *
+ * Copyright (c) 2010 PetaLogix Qld Pty Ltd.
+ * Copyright (c) 2010 Peter A. G. Crosthwaite <[email protected]>.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+#include "qemu/osdep.h"
+#include "hw/core/fdt_generic.h"
+#include "hw/core/qdev-properties.h"
+#include "qemu/log.h"
+
+#ifndef FDT_GENERIC_ERR_DEBUG
+#define FDT_GENERIC_ERR_DEBUG 0
+#endif
+#define DB_PRINT(lvl, ...) do { \
+    if (FDT_GENERIC_ERR_DEBUG > (lvl)) { \
+        qemu_log_mask(LOG_FDT, ": %s: ", __func__); \
+        qemu_log_mask(LOG_FDT, ## __VA_ARGS__); \
+    } \
+} while (0)
+
+#define FDT_GENERIC_MAX_PATTERN_LEN 1024
+
+typedef struct TableListNode {
+    struct TableListNode *next;
+    char key[FDT_GENERIC_MAX_PATTERN_LEN];
+    FDTInitFn fdt_init;
+    void *opaque;
+} TableListNode;
+
+/* add a node to the table specified by *head_p */
+
+static void add_to_table(
+        FDTInitFn fdt_init,
+        const char *key,
+        void *opaque,
+        TableListNode **head_p)
+{
+    TableListNode *nn = malloc(sizeof(*nn));
+    nn->next = *head_p;
+    strcpy(nn->key, key);
+    nn->fdt_init = fdt_init;
+    nn->opaque = opaque;
+    *head_p = nn;
+}
+
+/* FIXME: add return codes that differentiate between not found and error */
+
+/*
+ * search a table for a key string and call the fdt init function if found.
+ * Returns 0 if a match is found, 1 otherwise
+ */
+
+static int fdt_init_search_table(
+        char *node_path,
+        FDTMachineInfo *fdti,
+        const char *key, /* string to match */
+        TableListNode **head) /* head of the list to search */
+{
+    TableListNode *iter;
+
+    for (iter = *head; iter != NULL; iter = iter->next) {
+        if (!strcmp(key, iter->key)) {
+            if (iter->fdt_init) {
+                return iter->fdt_init(node_path, fdti, iter->opaque);
+            }
+            return 0;
+        }
+    }
+
+    return 1;
+}
+
+TableListNode *compat_list_head;
+
+void add_to_compat_table(FDTInitFn fdt_init, const char *compat, void *opaque)
+{
+    add_to_table(fdt_init, compat, opaque, &compat_list_head);
+}
+
+int fdt_init_compat(char *node_path, FDTMachineInfo *fdti, const char *compat)
+{
+    return fdt_init_search_table(node_path, fdti, compat, &compat_list_head);
+}
+
+TableListNode *inst_bind_list_head;
+
+void add_to_inst_bind_table(FDTInitFn fdt_init, const char *name, void *opaque)
+{
+    add_to_table(fdt_init, name, opaque, &inst_bind_list_head);
+}
+
+int fdt_init_inst_bind(char *node_path, FDTMachineInfo *fdti,
+        const char *name)
+{
+    return fdt_init_search_table(node_path, fdti, name, &inst_bind_list_head);
+}
+
+static void dump_table(TableListNode *head)
+{
+    TableListNode *iter;
+
+    for (iter = head; iter != NULL; iter = iter->next) {
+        printf("key : %s, opaque data %p\n", head->key, head->opaque);
+    }
+}
+
+void dump_compat_table(void)
+{
+    printf("FDT COMPATIBILITY TABLE:\n");
+    dump_table(compat_list_head);
+}
+
+void dump_inst_bind_table(void)
+{
+    printf("FDT INSTANCE BINDING TABLE:\n");
+    dump_table(inst_bind_list_head);
+}
include/hw/core/fdt_generic.h new file +78 -0

78 lines not on this page · raw message

Signature · 1 line
2.43.0
#6 lore raw

PATCH v2 5/33 hw/core/fdt_generic: implement FDT machine creation helpers

In reply to Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]>

The patch adds infrastructure to parse device tree and associate fdt nodes and created objects.

This will be used during instantiating machine from the devices tree.

---
 hw/core/fdt_generic.c         | 70 +++++++++++++++++++++++++++++++++++
 include/hw/core/fdt_generic.h | 26 ++++++++++++-
 2 files changed, 95 insertions(+), 1 deletion(-)
hw/core/fdt_generic.c +70 -0
index d3ab8f9132..b3ef0b7d0a 100644
@@ -28,7 +28,10 @@
 #include "qemu/osdep.h"
 #include "hw/core/fdt_generic.h"
 #include "hw/core/qdev-properties.h"
+#include "migration/vmstate.h"
+#include "qemu/coroutine.h"
 #include "qemu/log.h"
+#include "system/reset.h"
 
 #ifndef FDT_GENERIC_ERR_DEBUG
 #define FDT_GENERIC_ERR_DEBUG 0
@@ -137,3 +140,70 @@ void dump_inst_bind_table(void)
     printf("FDT INSTANCE BINDING TABLE:\n");
     dump_table(inst_bind_list_head);
 }
+
+void fdt_init_yield(FDTMachineInfo *fdti)
+{
+    static int yield_index;
+    int this_yield = yield_index++;
+
+    DB_PRINT(1, "Yield #%d\n", this_yield);
+    qemu_co_queue_wait(fdti->cq, NULL);
+    DB_PRINT(1, "Unyield #%d\n", this_yield);
+}
+
+void fdt_init_set_opaque(FDTMachineInfo *fdti, char *node_path, void *opaque)
+{
+    FDTDevOpaque *dp;
+    for (dp = fdti->dev_opaques;
+        dp->node_path && strcmp(dp->node_path, node_path);
+        dp++)
+        ;
+    if (!dp->node_path) {
+        dp->node_path = strdup(node_path);
+    }
+    dp->opaque = opaque;
+}
+
+int fdt_init_has_opaque(FDTMachineInfo *fdti, char *node_path)
+{
+    FDTDevOpaque *dp;
+    for (dp = fdti->dev_opaques; dp->node_path; dp++) {
+        if (!strcmp(dp->node_path, node_path)) {
+            return 1;
+         }
+    }
+    return 0;
+}
+
+void *fdt_init_get_opaque(FDTMachineInfo *fdti, char *node_path)
+{
+    FDTDevOpaque *dp;
+    for (dp = fdti->dev_opaques; dp->node_path; dp++) {
+        if (!strcmp(dp->node_path, node_path)) {
+            return dp->opaque;
+        }
+    }
+    return NULL;
+}
+
+FDTMachineInfo *fdt_init_new_fdti(void *fdt)
+{
+    FDTMachineInfo *fdti = g_malloc0(sizeof(*fdti));
+    fdti->fdt = fdt;
+    fdti->cq = g_malloc0(sizeof(*(fdti->cq)));
+    qemu_co_queue_init(fdti->cq);
+    fdti->dev_opaques = g_malloc0(sizeof(*(fdti->dev_opaques)) *
+        (devtree_get_num_nodes(fdt) + 1));
+    return fdti;
+}
+
+void fdt_init_destroy_fdti(FDTMachineInfo *fdti)
+{
+    FDTDevOpaque *dp;
+
+    for (dp = fdti->dev_opaques; dp->node_path; dp++) {
+        g_free(dp->node_path);
+    }
+    g_free(fdti->dev_opaques);
+    g_free(fdti);
+}
include/hw/core/fdt_generic.h +25 -1
index 614a234868..a21e3c2440 100644
@@ -8,9 +8,33 @@
 #define FDT_GENERIC_H
 
 #include "qemu/help-texts.h"
+#include "hw/core/irq.h"
 #include "system/device_tree.h"
+#include "qemu/coroutine.h"
+
+typedef struct FDTDevOpaque {
+    char *node_path;
+    void *opaque;
+} FDTDevOpaque;
+
+typedef struct FDTMachineInfo {
+    /* the fdt blob */
+    void *fdt;
+    /* irq descriptors for top level int controller */
+    qemu_irq *irq_base;
+    /* per-device specific opaques */
+    FDTDevOpaque *dev_opaques;
+    /* recheck coroutine queue */
+    CoQueue *cq;
+} FDTMachineInfo;
 
-typedef struct FDTMachineInfo FDTMachineInfo;
+/*
+ * create a new FDTMachineInfo. The client is responsible for setting irq_base.
+ * Client must call fdt_init_destroy_fdti to cleanup
+ */
+
+FDTMachineInfo *fdt_init_new_fdti(void *fdt);
+void fdt_init_destroy_fdti(FDTMachineInfo *fdti);
 
 typedef int (*FDTInitFn)(char *, FDTMachineInfo *, void *);
 
Signature · 1 line
2.43.0
#7 lore raw

PATCH v2 6/33 hw/core/fdt_generic: add cpu clusters management

In reply to Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]>

Add support for grouping CPUs into clusters during FDT machine instantiation.

The clusters are automatically created if CPU parent is not already an existing cluster.

---
 hw/core/fdt_generic.c         | 77 +++++++++++++++++++++++++++++++++++
 include/hw/core/fdt_generic.h | 13 ++++++
 2 files changed, 90 insertions(+)
hw/core/fdt_generic.c +77 -0
index b3ef0b7d0a..3c28f42491 100644
@@ -31,6 +31,7 @@
 #include "migration/vmstate.h"
 #include "qemu/coroutine.h"
 #include "qemu/log.h"
+#include "hw/cpu/cluster.h"
 #include "system/reset.h"
 
 #ifndef FDT_GENERIC_ERR_DEBUG
@@ -175,6 +176,75 @@ int fdt_init_has_opaque(FDTMachineInfo *fdti, char *node_path)
     return 0;
 }
 
+static int get_next_cpu_cluster_id(void)
+{
+    static int i;
+
+    return i++;
+}
+
+void fdt_init_register_user_cpu_cluster(FDTMachineInfo *fdti, Object *cluster)
+{
+    int i = get_next_cpu_cluster_id();
+    DeviceState *dev = DEVICE(cluster);
+    FDTCPUCluster *cl;
+
+    qdev_prop_set_uint32(dev, "cluster-id", i);
+
+    cl = g_new0(FDTCPUCluster, 1);
+    cl->cpu_cluster = cluster;
+    cl->next = fdti->clusters;
+    cl->user = true;
+
+    fdti->clusters = cl;
+
+    DB_PRINT(0, "%s: Registered user-defined cpu cluster with id %d\n",
+             object_get_canonical_path(cluster), i);
+}
+
+static void *fdt_init_add_cpu_cluster(FDTMachineInfo *fdti, char *compat)
+{
+    FDTCPUCluster *cl = g_malloc0(sizeof(*cl));
+    int i = get_next_cpu_cluster_id();
+    char *name = g_strdup_printf("cluster%d", i);
+    Object *obj;
+
+    obj = object_new(TYPE_CPU_CLUSTER);
+    object_property_add_child(object_get_root(), name, OBJECT(obj));
+    qdev_prop_set_uint32(DEVICE(obj), "cluster-id", i);
+
+    cl->cpu_type = g_strdup(compat);
+    cl->cpu_cluster = obj;
+    cl->next = fdti->clusters;
+
+    fdti->clusters = cl;
+
+    g_free(name);
+
+    return obj;
+}
+
+void *fdt_init_get_cpu_cluster(FDTMachineInfo *fdti, Object *parent,
+                               char *compat)
+{
+    FDTCPUCluster *cl = fdti->clusters;
+
+    if (object_dynamic_cast(parent, TYPE_CPU_CLUSTER)) {
+        /* The direct parent of this CPU is a CPU cluster. Use it. */
+        return parent;
+    }
+
+    while (cl) {
+        if (!cl->user && !strcmp(compat, cl->cpu_type)) {
+            return cl->cpu_cluster;
+        }
+        cl = cl->next;
+    }
+
+    /* No cluster found so create and return a new one */
+    return fdt_init_add_cpu_cluster(fdti, compat);
+}
+
 void *fdt_init_get_opaque(FDTMachineInfo *fdti, char *node_path)
 {
     FDTDevOpaque *dp;
@@ -199,8 +269,15 @@ FDTMachineInfo *fdt_init_new_fdti(void *fdt)
 
 void fdt_init_destroy_fdti(FDTMachineInfo *fdti)
 {
+    FDTCPUCluster *cl = fdti->clusters;
     FDTDevOpaque *dp;
 
+    while (cl) {
+        FDTCPUCluster *tmp = cl;
+        cl = cl->next;
+        g_free(tmp->cpu_type);
+        g_free(tmp);
+    }
     for (dp = fdti->dev_opaques; dp->node_path; dp++) {
         g_free(dp->node_path);
     }
include/hw/core/fdt_generic.h +13 -0
index a21e3c2440..46b7dc084b 100644
@@ -17,6 +17,13 @@ typedef struct FDTDevOpaque {
     void *opaque;
 } FDTDevOpaque;
 
+typedef struct FDTCPUCluster {
+    char *cpu_type;
+    void *cpu_cluster;
+    void *next;
+    bool user;
+} FDTCPUCluster;
+
 typedef struct FDTMachineInfo {
     /* the fdt blob */
     void *fdt;
@@ -26,6 +33,8 @@ typedef struct FDTMachineInfo {
     FDTDevOpaque *dev_opaques;
     /* recheck coroutine queue */
     CoQueue *cq;
+    /* list of all CPU clusters */
+    FDTCPUCluster *clusters;
 } FDTMachineInfo;
 
 /*
@@ -73,6 +82,10 @@ void fdt_init_set_opaque(FDTMachineInfo *fdti, char *node_path, void *opaque);
 int fdt_init_has_opaque(FDTMachineInfo *fdti, char *node_path);
 void *fdt_init_get_opaque(FDTMachineInfo *fdti, char *node_path);
 
+void *fdt_init_get_cpu_cluster(FDTMachineInfo *fdti, Object *parent,
+                               char *compat);
+void fdt_init_register_user_cpu_cluster(FDTMachineInfo *fdti, Object *cluster);
+
 /* statically register a FDTInitFn as being associate with a compatibility */
 
 #define fdt_register_compatibility_opaque(function, compat, n, opaque) \
Signature · 1 line
2.43.0
#8 lore raw

PATCH v2 7/33 hw/core/fdt_generic_util: implement main fdt parse routine

In reply to Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]>

Implement main fdt_generic_create_machine() routine.

As of now do the following:

- parse each node and subnode in device tree
- check node has correct compatible or device types
- call fdt_init_qdev() which will eventually create device object.

The MIT license of fdt_generic_util.c preserved as in original file from https://github.com/Xilinx/qemu.git repo.

The license for fdt_generic_util.h derived from matching fdt_generic_util.c file.

---
 hw/core/fdt_generic_util.c         | 245 +++++++++++++++++++++++++++++
 include/hw/core/fdt_generic_util.h |  19 +++
 2 files changed, 264 insertions(+)
 create mode 100644 hw/core/fdt_generic_util.c
 create mode 100644 include/hw/core/fdt_generic_util.h
hw/core/fdt_generic_util.c new file +245 -0
new file mode 100644
index 0000000000..3606c11349
@@ -0,0 +1,245 @@
+// SPDX-License-Identifier: MIT
+/*
+ * Utility functions for fdt generic framework
+ *
+ * Copyright (c) 2009 Edgar E. Iglesias.
+ * Copyright (c) 2009 Michal Simek.
+ * Copyright (c) 2011 PetaLogix Qld Pty Ltd.
+ * Copyright (c) 2011 Peter A. G. Crosthwaite <[email protected]>.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+#include "qemu/osdep.h"
+#include "hw/core/fdt_generic_util.h"
+#include "system/memory.h"
+#include "system/address-spaces.h"
+#include "hw/core/sysbus.h"
+#include "qapi/error.h"
+#include "qemu/error-report.h"
+#include "system/system.h"
+#include "system/reset.h"
+#include "qemu/cutils.h"
+#include "qemu/log.h"
+#include "qemu/config-file.h"
+#include "hw/core/boards.h"
+#include "qemu/option.h"
+
+#ifndef FDT_GENERIC_UTIL_ERR_DEBUG
+#define FDT_GENERIC_UTIL_ERR_DEBUG 3
+#endif
+#define DB_PRINT(lvl, ...) do { \
+    if (FDT_GENERIC_UTIL_ERR_DEBUG > (lvl)) { \
+        qemu_log_mask(LOG_FDT, ": %s: ", __func__); \
+        qemu_log_mask(LOG_FDT, ## __VA_ARGS__); \
+    } \
+} while (0)
+
+#define DB_PRINT_NP(lvl, ...) do { \
+    if (FDT_GENERIC_UTIL_ERR_DEBUG > (lvl)) { \
+        qemu_log_mask(LOG_FDT, "%s", node_path); \
+        DB_PRINT((lvl), ## __VA_ARGS__); \
+    } \
+} while (0)
+
+/* FIXME: wrap direct calls into libfdt */
+
+#include <libfdt.h>
+#include <stdlib.h>
+
+static int fdt_generic_num_cpus;
+
+static int simple_bus_fdt_init(char *bus_node_path, FDTMachineInfo *fdti);
+
+FDTMachineInfo *fdt_generic_create_machine(void *fdt, qemu_irq *cpu_irq)
+{
+    char node_path[DT_PATH_LENGTH];
+    FDTMachineInfo *fdti = fdt_init_new_fdti(fdt);
+
+    fdti->irq_base = cpu_irq;
+
+    /* parse the device tree */
+    if (!fdt_get_path(fdt, 0, node_path, DT_PATH_LENGTH)) {
+        memory_region_transaction_begin();
+        fdt_init_set_opaque(fdti, node_path, NULL);
+        simple_bus_fdt_init(node_path, fdti);
+        while (qemu_co_enter_next(fdti->cq, NULL)) {
+            ;
+        }
+        memory_region_transaction_commit();
+    } else {
+        fprintf(stderr, "FDT: ERROR: cannot get root node from device tree %s\n"
+            , node_path);
+    }
+
+    /* FIXME: Populate these from DTS and create CPU clusters.  */
+    current_machine->smp.cores = fdt_generic_num_cpus;
+    current_machine->smp.cpus = fdt_generic_num_cpus;
+    current_machine->smp.max_cpus = fdt_generic_num_cpus;
+
+    DB_PRINT(0, "FDT: Device tree scan complete\n");
+    return fdti;
+}
+
+struct FDTInitNodeArgs {
+    char *node_path;
+    char *parent_path;
+    FDTMachineInfo *fdti;
+};
+
+static int fdt_init_qdev(char *node_path, FDTMachineInfo *fdti, char *compat);
+
+static int check_compat(const char *prefix, const char *compat,
+                        char *node_path, FDTMachineInfo *fdti)
+{
+    char *compat_prefixed = g_strconcat(prefix, compat, NULL);
+    const int done = !fdt_init_compat(node_path, fdti, compat_prefixed);
+    g_free(compat_prefixed);
+    return done;
+}
+
+static void fdt_init_node(void *args)
+{
+    struct FDTInitNodeArgs *a = args;
+    char *node_path = a->node_path;
+    FDTMachineInfo *fdti = a->fdti;
+    g_free(a);
+
+    simple_bus_fdt_init(node_path, fdti);
+
+    const char *prop;
+    char *all_compats = NULL, *node_name;
+    char *device_type = NULL;
+    int prop_len;
+
+    DB_PRINT_NP(1, "enter\n");
+
+    /* try instance binding first */
+    node_name = strrchr(node_path, '/') + 1;
+    DB_PRINT_NP(1, "node with name: %s\n", node_name ? node_name : "(none)");
+    if (!node_name) {
+        printf("FDT: ERROR: nameless node: %s\n", node_path);
+    }
+    if (!fdt_init_inst_bind(node_path, fdti, node_name)) {
+        DB_PRINT_NP(0, "instance bind successful\n");
+        goto exit;
+    }
+
+    /* fallback to compatibility binding */
+    prop = qemu_fdt_getprop(fdti->fdt, node_path, "compatible",
+                                       &prop_len, NULL);
+    all_compats = g_memdup2(prop, prop_len);
+    if (all_compats) {
+        char *compat = all_compats;
+        char * const end = &all_compats[prop_len - 1]; /* points to nul */
+
+        while (compat < end) {
+            if (check_compat("compatible:", compat, node_path, fdti)) {
+                goto exit;
+            }
+
+            if (!fdt_init_qdev(node_path, fdti, compat)) {
+                check_compat("postinit:", compat, node_path, fdti);
+                goto exit;
+            }
+
+            /* Scan forward to the end of the current compat. */
+            while (compat < end && *compat) {
+                ++compat;
+            }
+
+            /* Replace nul with space for the debug printf below. */
+            if (compat < end) {
+                *compat++ = ' ';
+            }
+        };
+    } else {
+        DB_PRINT_NP(0, "no compatibility found\n");
+    }
+
+    /*
+     * Try to create the device using device_type property
+     * Not every device tree node has compatible  property, so
+     * try with device_type.
+     */
+    prop = qemu_fdt_getprop(fdti->fdt, node_path,
+                            "device_type", &prop_len, NULL);
+    device_type = g_memdup2(prop, prop_len);
+    if (device_type) {
+        if (check_compat("device_type:", device_type, node_path, fdti)) {
+            goto exit;
+        }
+
+        if (!fdt_init_qdev(node_path, fdti, device_type)) {
+            goto exit;
+        }
+    }
+
+    if (all_compats) {
+        DB_PRINT_NP(0, "FDT: Unsupported peripheral invalidated - "
+                    "compatibilities %s\n", all_compats);
+        qemu_fdt_setprop_string(fdti->fdt, node_path, "compatible",
+                                "invalidated");
+    }
+exit:
+
+    DB_PRINT_NP(1, "exit\n");
+
+    if (!fdt_init_has_opaque(fdti, node_path)) {
+        fdt_init_set_opaque(fdti, node_path, NULL);
+    }
+    g_free(node_path);
+    g_free(all_compats);
+    g_free(device_type);
+    return;
+}
+
+static int simple_bus_fdt_init(char *node_path, FDTMachineInfo *fdti)
+{
+    int i;
+    char **children;
+    int num_children = qemu_devtree_get_num_children(fdti->fdt, node_path);
+
+    if (num_children <= 0) {
+        return 0;
+    }
+
+    children = g_malloc0(sizeof(*children) * num_children);
+
+    num_children = qemu_devtree_get_children(fdti->fdt, node_path, num_children,
+                                             children);
+
+    DB_PRINT_NP(num_children ? 0 : 1, "num child devices: %d\n", num_children);
+
+    for (i = 0; i < num_children; i++) {
+        struct FDTInitNodeArgs *init_args = g_malloc0(sizeof(*init_args));
+        init_args->node_path = children[i];
+        init_args->fdti = fdti;
+        qemu_coroutine_enter(qemu_coroutine_create(fdt_init_node, init_args));
+    }
+
+    g_free(children);
+    return 0;
+}
+
+static int fdt_init_qdev(char *node_path, FDTMachineInfo *fdti, char *compat)
+{
+    return 0;
+}
+
include/hw/core/fdt_generic_util.h new file +19 -0
new file mode 100644
index 0000000000..e18c4f9c8b
@@ -0,0 +1,19 @@
+// SPDX-License-Identifier: MIT
+
+#ifndef FDT_GENERIC_UTIL_H
+#define FDT_GENERIC_UTIL_H
+
+#include "qemu/help-texts.h"
+#include "fdt_generic.h"
+#include "system/memory.h"
+#include "qom/object.h"
+
+/*
+ * create a fdt_generic machine. the top level cpu irqs are required for
+ * systems instantiating interrupt devices. The client is responsible for
+ * destroying the returned FDTMachineInfo (using fdt_init_destroy_fdti)
+ */
+
+FDTMachineInfo *fdt_generic_create_machine(void *fdt, qemu_irq *cpu_irq);
+
+#endif /* FDT_GENERIC_UTIL_H */
Signature · 1 line
2.43.0
#9 lore raw

PATCH v2 8/33 hw/core/fdt_generic_util: implement fdt_init_qdev

In reply to Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]>

Implement main routine to create device object from compat.

The following steps implemented:

- parse node compatible and device types
- try to create object from compat
- set correct parent based on device tree.

---
 hw/core/fdt_generic_util.c | 222 +++++++++++++++++++++++++++++++++++++
 1 file changed, 222 insertions(+)
hw/core/fdt_generic_util.c +222 -0
index 3606c11349..8131511e70 100644
@@ -40,6 +40,7 @@
 #include "qemu/config-file.h"
 #include "hw/core/boards.h"
 #include "qemu/option.h"
+#include "hw/cpu/cluster.h"
 
 #ifndef FDT_GENERIC_UTIL_ERR_DEBUG
 #define FDT_GENERIC_UTIL_ERR_DEBUG 3
@@ -238,8 +239,229 @@ static int simple_bus_fdt_init(char *node_path, FDTMachineInfo *fdti)
     return 0;
 }
 
+/* FIXME: figure out a real solution to this */
+
+#define DIGIT(a) ((a) >= '0' && (a) <= '9')
+#define LOWER_CASE(a) ((a) >= 'a' && (a) <= 'z')
+
+static void trim_version(char *x)
+{
+    long result;
+
+    for (;;) {
+        x = strchr(x, '-');
+        if (!x) {
+            return;
+        }
+        if (DIGIT(x[1])) {
+            /* Try to trim Xilinx version suffix */
+            const char *p;
+
+            qemu_strtol(x + 1, &p, 0, &result);
+
+            if (*p == '.') {
+                *x = 0;
+                return;
+            } else if (*p == 0) {
+                return;
+            }
+        } else if (x[1] == 'r' && x[3] == 'p') {
+            /* Try to trim ARM version suffix */
+            if (DIGIT(x[2]) && DIGIT(x[4])) {
+                *x = 0;
+                return;
+            }
+        }
+        x++;
+    }
+}
+
+static void substitute_char(char *s, char a, char b)
+{
+    for (;;) {
+        s = strchr(s, a);
+        if (!s) {
+            return;
+        }
+        *s = b;
+        s++;
+    }
+}
+
+static inline const char *trim_vendor(const char *s)
+{
+    /* FIXME: be more intelligent */
+    const char *ret = memchr(s, ',', strlen(s));
+    return ret ? ret + 1 : s;
+}
+
+static Object *fdt_create_from_compat(const char *compat, char **dev_type)
+{
+    Object *ret = NULL;
+    char *c = g_strdup(compat);
+
+    /* Try to create the object */
+    ret = object_new(c);
+
+    if (!ret) {
+        /* Trim the version off the end and try again */
+        trim_version(c);
+        ret = object_new(c);
+
+        if (!ret) {
+            /* Replace commas with full stops */
+            substitute_char(c, ',', '.');
+            ret = object_new(c);
+        }
+    }
+
+    if (!ret) {
+        /*
+         * Restart with the orginal string and now replace commas with full
+         * stops and try again. This means that versions are still included.
+         */
+        g_free(c);
+        c = g_strdup(compat);
+        substitute_char(c, ',', '.');
+        ret = object_new(c);
+    }
+
+    if (dev_type) {
+        *dev_type = c;
+    } else {
+        g_free(c);
+    }
+
+    if (!ret) {
+        const char *no_vendor = trim_vendor(compat);
+
+        if (no_vendor != compat) {
+            return fdt_create_from_compat(no_vendor, dev_type);
+        }
+    }
+    return ret;
+}
+
+/*
+ * Error handler for device creation failure.
+ *
+ * We look for qemu-fdt-abort-on-error properties up the tree.
+ * If we find one, we abort with the provided error message.
+ */
+static void fdt_dev_error(FDTMachineInfo *fdti, char *node_path, char *compat)
+{
+    const char *abort_on_error;
+    const char *warn_on_error;
+
+    warn_on_error = qemu_fdt_getprop_inherited(fdti->fdt, node_path,
+                                   "qemu-fdt-warn-on-error", 0, NULL);
+    abort_on_error = qemu_fdt_getprop_inherited(fdti->fdt, node_path,
+                                   "qemu-fdt-abort-on-error", 0, NULL);
+    if (warn_on_error) {
+        if (strncmp("device_type", compat, strlen("device_type"))) {
+            warn_report("%s: %s", compat, warn_on_error);
+        }
+    }
+
+    if (abort_on_error) {
+        error_report("Failed to create %s", compat);
+        error_setg(&error_fatal, "%s", abort_on_error);
+    }
+}
+
 static int fdt_init_qdev(char *node_path, FDTMachineInfo *fdti, char *compat)
 {
+    Object *dev, *parent;
+    char *dev_type = NULL;
+    char parent_node_path[DT_PATH_LENGTH];
+
+    if (!compat) {
+        return 1;
+    }
+    dev = fdt_create_from_compat(compat, &dev_type);
+    if (!dev) {
+        DB_PRINT_NP(1, "no match found for %s\n", compat);
+        fdt_dev_error(fdti, node_path, compat);
+        return 1;
+    }
+    DB_PRINT_NP(1, "matched compat %s\n", compat);
+
+    /* Do this super early so fdt_generic_num_cpus is correct ASAP */
+    if (object_dynamic_cast(dev, TYPE_CPU)) {
+        fdt_generic_num_cpus++;
+        DB_PRINT_NP(0, "is a CPU - total so far %d\n", fdt_generic_num_cpus);
+    }
+
+    if (qemu_devtree_getparent(fdti->fdt, parent_node_path, node_path)) {
+        abort();
+    }
+    while (!fdt_init_has_opaque(fdti, parent_node_path) &&
+           !object_dynamic_cast(dev, TYPE_CPU)) {
+        fdt_init_yield(fdti);
+    }
+
+    parent = fdt_init_get_opaque(fdti, parent_node_path);
+
+    if (object_dynamic_cast(dev, TYPE_CPU)) {
+        parent = fdt_init_get_cpu_cluster(fdti, parent, compat);
+    }
+
+    if (dev->parent) {
+        DB_PRINT_NP(0, "Node already parented - skipping node\n");
+    } else if (parent) {
+        DB_PRINT_NP(1, "parenting node\n");
+        object_property_add_child(OBJECT(parent),
+                              strdup(strrchr(node_path, '/') + 1),
+                              OBJECT(dev));
+        if (object_dynamic_cast(dev, TYPE_DEVICE)) {
+            Object *parent_bus = parent;
+            unsigned int depth = 0;
+
+            DB_PRINT_NP(1, "bus parenting node\n");
+            /* Look for an FDT ancestor that is a Bus.  */
+            while (parent_bus && !object_dynamic_cast(parent_bus, TYPE_BUS)) {
+                /*
+                 * Assert against insanely deep hierarchies which are an
+                 * indication of loops.
+                 */
+                assert(depth < 4096);
+
+                parent_bus = parent_bus->parent;
+                depth++;
+            }
+
+            if (!parent_bus
+                && object_dynamic_cast(OBJECT(dev), TYPE_SYS_BUS_DEVICE)) {
+                /*
+                 * Didn't find any bus. Use the default sysbus one.
+                 * This allows ad-hoc busses belonging to sysbus devices to be
+                 * visible to -device bus=x.
+                 */
+                parent_bus = OBJECT(sysbus_get_default());
+            }
+
+            if (parent_bus) {
+                qdev_set_parent_bus(DEVICE(dev), BUS(parent_bus),
+                                    &error_abort);
+            }
+        }
+    } else {
+        DB_PRINT_NP(1, "orphaning node\n");
+        if (object_dynamic_cast(OBJECT(dev), TYPE_SYS_BUS_DEVICE)) {
+            qdev_set_parent_bus(DEVICE(dev), BUS(sysbus_get_default()),
+                                &error_abort);
+        }
+
+        /* FIXME: Make this go away (centrally) */
+        object_property_add_child(
+                              object_get_root(),
+                              strrchr(node_path, '/') + 1,
+                              OBJECT(dev));
+    }
+    fdt_init_set_opaque(fdti, node_path, dev);
+
+    g_free(dev_type);
+
     return 0;
 }
 
Signature · 1 line
2.43.0
#10 lore raw

PATCH v2 9/33 qdev: Add qdev_prop_get_array_elem_type() helper

In reply to Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]>

Add a helper function to retrieve the element type of a qdev array property.

This is required to initialize objects from a HW device tree, as neither device tree properties nor object's property array reveal underlying property type.

---
 hw/core/qdev-properties.c         | 12 ++++++++++++
 include/hw/core/qdev-properties.h |  1 +
 2 files changed, 13 insertions(+)
hw/core/qdev-properties.c +12 -0
index ba8461e9a4..f92ccc35d8 100644
@@ -950,6 +950,18 @@ void qdev_prop_set_array(DeviceState *dev, const char *name, QList *values)
     qobject_unref(values);
 }
 
+const char *qdev_prop_get_array_elem_type(DeviceState *dev, const char *name)
+{
+    const Property *prop;
+
+    prop = qdev_prop_find(dev, name);
+    if (!prop || prop->info != &qdev_prop_array) {
+        return NULL;
+    }
+
+    return prop->arrayinfo->type;
+}
+
 static GPtrArray *global_props(void)
 {
     static GPtrArray *gp;
include/hw/core/qdev-properties.h +1 -0
index d8745d4c65..19fed85248 100644
@@ -218,6 +218,7 @@ void qdev_prop_set_enum(DeviceState *dev, const char *name, int value);
 
 /* Takes ownership of @values */
 void qdev_prop_set_array(DeviceState *dev, const char *name, QList *values);
+const char *qdev_prop_get_array_elem_type(DeviceState *dev, const char *name);
 
 void *object_field_prop_ptr(Object *obj, const Property *prop);
 
Signature · 1 line
2.43.0
#11 lore raw

PATCH v2 10/33 hw/core/fdt_generic_util: initilize qdev properties from fdt

In reply to Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]>

The patch adds possibility to read and parse device tree node properties and set them to newly created object.

---
 hw/core/fdt_generic_util.c | 222 +++++++++++++++++++++++++++++++++++++
 1 file changed, 222 insertions(+)
hw/core/fdt_generic_util.c +222 -0
index 8131511e70..2a3862b9ac 100644
@@ -40,7 +40,9 @@
 #include "qemu/config-file.h"
 #include "hw/core/boards.h"
 #include "qemu/option.h"
+#include "hw/core/qdev-properties.h"
 #include "hw/cpu/cluster.h"
+#include "qobject/qlist.h"
 
 #ifndef FDT_GENERIC_UTIL_ERR_DEBUG
 #define FDT_GENERIC_UTIL_ERR_DEBUG 3
@@ -342,6 +344,25 @@ static Object *fdt_create_from_compat(const char *compat, char **dev_type)
     return ret;
 }
 
+/*FIXME: roll into device tree functionality */
+
+static inline uint64_t get_int_be(const void *p, int len)
+{
+    switch (len) {
+    case 1:
+        return *((uint8_t *)p);
+    case 2:
+        return be16_to_cpu(*((uint16_t *)p));
+    case 4:
+        return be32_to_cpu(*((uint32_t *)p));
+    case 8:
+        return be32_to_cpu(*((uint64_t *)p));
+    default:
+        fprintf(stderr, "unsupported integer length\n");
+        abort();
+    }
+}
+
 /*
  * Error handler for device creation failure.
  *
@@ -369,10 +390,185 @@ static void fdt_dev_error(FDTMachineInfo *fdti, char *node_path, char *compat)
     }
 }
 
+static void fdt_init_qdev_link_prop(Object *obj, ObjectProperty *p,
+                                    FDTMachineInfo *fdti,
+                                    const char *node_path,
+                                    const QEMUDevtreeProp *prop)
+{
+    int len = prop->len;
+    const void *val = prop->value;
+    const char *propname = prop->name;
+
+    Object *linked_dev, *proxy;
+    char target_node_path[DT_PATH_LENGTH];
+    g_autofree char *propname_target = g_strconcat(propname, "-target", NULL);
+    Error *errp = NULL;
+
+    if (qemu_devtree_get_node_by_phandle(fdti->fdt, target_node_path,
+                                         get_int_be(val, len))) {
+        abort();
+    }
+
+    while (!fdt_init_has_opaque(fdti, target_node_path)) {
+        fdt_init_yield(fdti);
+    }
+    linked_dev = fdt_init_get_opaque(fdti, target_node_path);
+
+    proxy = linked_dev ? object_property_get_link(linked_dev,
+                                                  propname_target,
+                                                  &errp) : NULL;
+    if (!errp && proxy) {
+        DB_PRINT_NP(0, "detected proxy object for %s connection\n", propname);
+        linked_dev = proxy;
+    }
+
+    if (!linked_dev) {
+        linked_dev = object_resolve_link(obj, propname,
+                                         target_node_path, &errp);
+        if (!linked_dev) {
+            return;
+        }
+    }
+
+    errp = NULL;
+    object_property_set_link(obj, propname, linked_dev, &errp);
+    if (errp) {
+        /* Unable to set the property, maybe it is a memory alias? */
+        MemoryRegion *alias_mr;
+        int offset = len / 2;
+        int region = 0;
+
+        if (len > 4) {
+            region = get_int_be(val + offset, len - offset);
+        }
+
+        alias_mr = sysbus_mmio_get_region(SYS_BUS_DEVICE(linked_dev), region);
+
+        object_property_set_link(obj, propname, OBJECT(alias_mr), &error_abort);
+
+    }
+
+    DB_PRINT_NP(0, "set link %s\n", propname);
+}
+
+static void fdt_init_qdev_scalar_prop(Object *obj, ObjectProperty *p,
+                                      FDTMachineInfo *fdti,
+                                      const char *node_path,
+                                      const QEMUDevtreeProp *prop)
+{
+    const char *propname = trim_vendor(prop->name);
+    const void *val = prop->value;
+    int len = prop->len;
+
+    /* FIXME: handle generically using accessors and stuff */
+    if (!strncmp(p->type, "link", 4)) {
+        fdt_init_qdev_link_prop(obj, p, fdti, node_path, prop);
+        return;
+    }
+
+    if (!strcmp(p->type, "uint8") || !strcmp(p->type, "uint16") ||
+        !strcmp(p->type, "uint32") || !strcmp(p->type, "uint64") ||
+        !strcmp(p->type, "int8") || !strcmp(p->type, "int16") ||
+        !strcmp(p->type, "int32") || !strcmp(p->type, "int64")) {
+        object_property_set_int(obj, propname,
+                                get_int_be(val, len), &error_abort);
+        DB_PRINT_NP(0, "set property %s to 0x%llx\n", propname,
+                    (unsigned long long)get_int_be(val, len));
+        return;
+    }
+
+    if (!strcmp(p->type, "boolean") || !strcmp(p->type, "bool")) {
+        object_property_set_bool(obj, propname,
+                                 !!get_int_be(val, len), &error_abort);
+        DB_PRINT_NP(0, "set property %s to %s\n", propname,
+                    get_int_be(val, len) ? "true" : "false");
+        return;
+    }
+
+    if (!strcmp(p->type, "string") || !strcmp(p->type, "str")) {
+        object_property_set_str(obj, propname,
+                                (const char *)val, &error_abort);
+        DB_PRINT_NP(0, "set property %s to %s\n", propname, (const char *)val);
+        return;
+    }
+
+    DB_PRINT_NP(0, "WARNING: property is of unknown type\n");
+}
+
+static size_t fdt_array_elem_len(FDTMachineInfo *fdti,
+                                 const char *node_path,
+                                 const char *propname)
+{
+    g_autofree char *elem_cells_propname = NULL;
+    Error *err = NULL;
+    uint32_t elem_cells;
+
+    /*
+     * Default element size to 1 uint32_t cell, unless it is explicitly
+     * given in the same FDT node (not inherited).
+     */
+    elem_cells_propname = g_strconcat("#", propname, "-cells", NULL);
+    elem_cells = qemu_fdt_getprop_cell(fdti->fdt, node_path,
+                                       elem_cells_propname, 0, &err);
+
+    return (err ? 1 : elem_cells) * 4;
+}
+
+static void fdt_init_qdev_array_prop(Object *obj,
+                                     FDTMachineInfo *fdti,
+                                     const char *node_path,
+                                     QEMUDevtreeProp *prop)
+{
+    const char *propname = trim_vendor(prop->name);
+    int nr = prop->len;
+    uint32_t elem_len;
+    QList *qlist = qlist_new();
+    const char *prop_type;
+    const void *prop_value = prop->value;
+
+    if (!prop->value || !nr) {
+        return;
+    }
+
+    elem_len = fdt_array_elem_len(fdti, node_path, propname);
+    if (nr % elem_len) {
+        return;
+    }
+
+    nr /= elem_len;
+
+    prop_type = qdev_prop_get_array_elem_type(DEVICE(obj), propname);
+    if (!prop_type) {
+        DB_PRINT_NP(0, "fail to get property array elem type\n");
+        return;
+    }
+
+    while (nr--) {
+        if (!strcmp(prop_type, "uint8") || !strcmp(prop_type, "uint16") ||
+            !strcmp(prop_type, "uint32") || !strcmp(prop_type, "uint64") ||
+            !strcmp(prop_type, "int8") || !strcmp(prop_type, "int16") ||
+            !strcmp(prop_type, "int32") || !strcmp(prop_type, "int64")) {
+                qlist_append_int(qlist, get_int_be(prop_value, elem_len));
+        } else if (!strcmp(prop_type, "boolean") || !strcmp(prop_type, "bool")) {
+            qlist_append_bool(qlist, !!get_int_be(prop_value, elem_len));
+        } else if (!strcmp(prop_type, "string") || !strcmp(prop_type, "str")) {
+            qlist_append_str(qlist, (const char *)prop_value);
+        }
+
+        prop_value += elem_len;
+
+        /* TBD: add link type support */
+    }
+
+    qdev_prop_set_array(DEVICE(obj), propname, qlist);
+    DB_PRINT_NP(0, "set property %s propname to <list>\n", propname);
+}
+
 static int fdt_init_qdev(char *node_path, FDTMachineInfo *fdti, char *compat)
 {
     Object *dev, *parent;
     char *dev_type = NULL;
+    QEMUDevtreeProp *prop, *props;
     char parent_node_path[DT_PATH_LENGTH];
 
     if (!compat) {
@@ -460,7 +656,33 @@ static int fdt_init_qdev(char *node_path, FDTMachineInfo *fdti, char *compat)
     }
     fdt_init_set_opaque(fdti, node_path, dev);
 
+    props = qemu_devtree_get_props(fdti->fdt, node_path);
+    for (prop = props; prop->name; prop++) {
+        const char *propname = trim_vendor(prop->name);
+        ObjectProperty *p = NULL;
+
+        p = object_property_find(OBJECT(dev), propname);
+        if (p) {
+            DB_PRINT_NP(1, "matched property: %s of type %s, len %d\n",
+                                            propname, p->type, prop->len);
+        }
+        if (!p) {
+            continue;
+        }
+
+        if (!strcmp(p->type, "list")) {
+            fdt_init_qdev_array_prop(dev, fdti, node_path, prop);
+        }
+
+        if (!strcmp(propname, "type")) {
+            continue;
+        }
+
+        fdt_init_qdev_scalar_prop(OBJECT(dev), p, fdti, node_path, prop);
+    }
+
     g_free(dev_type);
+    g_free(props);
 
     return 0;
 }
Signature · 1 line
2.43.0
#12 lore raw

PATCH v2 11/33 hw/core/fdt_generic_util: actually realize device

In reply to Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]>

Actually realize objects with TYPE_DEVICE after main allocations done and properties set for qdev.

---
 hw/core/fdt_generic_util.c | 24 ++++++++++++++++++++++++
 1 file changed, 24 insertions(+)
hw/core/fdt_generic_util.c +24 -0
index 2a3862b9ac..43fa862f31 100644
@@ -681,6 +681,30 @@ static int fdt_init_qdev(char *node_path, FDTMachineInfo *fdti, char *compat)
         fdt_init_qdev_scalar_prop(OBJECT(dev), p, fdti, node_path, prop);
     }
 
+    if (object_dynamic_cast(dev, TYPE_DEVICE)) {
+        DeviceClass *dc = DEVICE_GET_CLASS(dev);
+        const char *short_name = strrchr(node_path, '/') + 1;
+
+        /* Regular TYPE_DEVICE houskeeping */
+        DB_PRINT_NP(0, "Short naming node: %s\n", short_name);
+        (DEVICE(dev))->id = g_strdup(short_name);
+
+        if (object_dynamic_cast(dev, TYPE_CPU_CLUSTER)) {
+            /*
+             * CPU clusters must be realized at the end to make sure all child
+             * CPUs are parented.
+             */
+            fdt_init_register_user_cpu_cluster(fdti, OBJECT(dev));
+        } else {
+            object_property_set_bool(OBJECT(dev), "realized", true,
+                                     &error_fatal);
+            if (dc->legacy_reset) {
+                qemu_register_reset((void (*)(void *))dc->legacy_reset,
+                                    dev);
+            }
+        }
+    }
+
     g_free(dev_type);
     g_free(props);
 
Signature · 1 line
2.43.0
#13 lore raw

PATCH v2 12/33 hw/core/fdt_generic_util: add TYPE_FDT_GENERIC_MMAP

In reply to Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]>

Add new FDT_GENERIC_MMAP class and interface to allow devices to register own handlers for mapping memory regions in device tree's 'reg' property.

---
 hw/core/fdt_generic_util.c         | 11 ++++++++
 include/hw/core/fdt_generic_util.h | 44 ++++++++++++++++++++++++++++++
 2 files changed, 55 insertions(+)
hw/core/fdt_generic_util.c +11 -0
index 43fa862f31..a9ae56d1c3 100644
@@ -711,3 +711,14 @@ static int fdt_init_qdev(char *node_path, FDTMachineInfo *fdti, char *compat)
     return 0;
 }
 
+static const TypeInfo fdt_generic_mmap_info = {
+    .name          = TYPE_FDT_GENERIC_MMAP,
+    .parent        = TYPE_INTERFACE,
+    .class_size = sizeof(FDTGenericMMapClass),
+};
+
+static void fdt_generic_register_types(void)
+{
+    type_register_static(&fdt_generic_mmap_info);
+}
+type_init(fdt_generic_register_types)
include/hw/core/fdt_generic_util.h +44 -0

48 lines not on this page · raw message

Signature · 1 line
2.43.0
#14 lore raw

PATCH v2 13/33 hw/core/fdt_generic_util: add TYPE_FDT_GENERIC_INTC

In reply to Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]>

Add TYPE_FDT_GENERIC_INTC class and interface to allow interrupt controllers to register callback which can be used to get IRQ's from this controller.

Optionally, interrupt controllers may also provide auto_parent() callabck which can be used to attach it to corresponding CPU's or other interrupt parent.

---
 hw/core/fdt_generic_util.c         |  7 ++++
 include/hw/core/fdt_generic_util.h | 59 ++++++++++++++++++++++++++++++
 2 files changed, 66 insertions(+)
hw/core/fdt_generic_util.c +7 -0
index a9ae56d1c3..d1465eafc1 100644
@@ -711,6 +711,12 @@ static int fdt_init_qdev(char *node_path, FDTMachineInfo *fdti, char *compat)
     return 0;
 }
 
+static const TypeInfo fdt_generic_intc_info = {
+    .name          = TYPE_FDT_GENERIC_INTC,
+    .parent        = TYPE_INTERFACE,
+    .class_size = sizeof(FDTGenericIntcClass),
+};
+
 static const TypeInfo fdt_generic_mmap_info = {
     .name          = TYPE_FDT_GENERIC_MMAP,
     .parent        = TYPE_INTERFACE,
@@ -719,6 +725,7 @@ static const TypeInfo fdt_generic_mmap_info = {
 
 static void fdt_generic_register_types(void)
 {
+    type_register_static(&fdt_generic_intc_info);
     type_register_static(&fdt_generic_mmap_info);
 }
 type_init(fdt_generic_register_types)
include/hw/core/fdt_generic_util.h +59 -0

65 lines not on this page · raw message

Signature · 1 line
2.43.0
#15 lore raw

PATCH v2 14/33 hw/core/fdt_generic_util: implement fdt_get_irq/_info API

In reply to Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]>

Both interfaces may be used by devices to get IRQ information based device tree entry.
Both methods will identify interrupt parent for a device and retrieve irq entry.

---
 hw/core/fdt_generic_util.c         | 267 +++++++++++++++++++++++++++++
 include/hw/core/fdt_generic_util.h |  18 ++
 2 files changed, 285 insertions(+)
hw/core/fdt_generic_util.c +267 -0
index d1465eafc1..dcacc5033b 100644
@@ -70,6 +70,11 @@ static int fdt_generic_num_cpus;
 
 static int simple_bus_fdt_init(char *bus_node_path, FDTMachineInfo *fdti);
 
+static void fdt_get_irq_info_from_intc(FDTMachineInfo *fdti, qemu_irq *ret,
+                                       char *intc_node_path,
+                                       uint32_t *cells, uint32_t num_cells,
+                                       uint32_t max, Error **errp);
+
 FDTMachineInfo *fdt_generic_create_machine(void *fdt, qemu_irq *cpu_irq)
 {
     char node_path[DT_PATH_LENGTH];
@@ -241,6 +246,268 @@ static int simple_bus_fdt_init(char *node_path, FDTMachineInfo *fdti)
     return 0;
 }
 
+static void fdt_get_irq_info_from_intc(FDTMachineInfo *fdti, qemu_irq *ret,
+                                       char *intc_node_path,
+                                       uint32_t *cells, uint32_t num_cells,
+                                       uint32_t max, Error **errp)
+{
+    FDTGenericIntcClass *intc_fdt_class;
+    DeviceState *intc;
+
+    while (!fdt_init_has_opaque(fdti, intc_node_path) &&
+           qemu_in_coroutine()) {
+        fdt_init_yield(fdti);
+    }
+    intc = DEVICE(fdt_init_get_opaque(fdti, intc_node_path));
+
+    if (!intc) {
+        goto fail;
+    }
+
+    while (!intc->realized && qemu_in_coroutine()) {
+        fdt_init_yield(fdti);
+    }
+
+    if (!intc->realized) {
+        goto fail;
+    }
+
+    intc_fdt_class = FDT_GENERIC_INTC_GET_CLASS(intc);
+    if (!intc_fdt_class) {
+        goto fail;
+    }
+
+    intc_fdt_class->get_irq(FDT_GENERIC_INTC(intc), ret, cells, num_cells,
+                            max, errp);
+
+    return;
+fail:
+    error_setg(errp, "%s", __func__);
+}
+
+static uint32_t imap_cache[32 * 1024];
+static bool imap_cached;
+
+qemu_irq *fdt_get_irq_info(FDTMachineInfo *fdti, char *node_path, int irq_idx,
+                          char *info, bool *map_mode) {
+    void *fdt = fdti->fdt;
+    uint32_t intc_phandle, intc_cells, cells[32];
+    char intc_node_path[DT_PATH_LENGTH];
+    qemu_irq *ret = NULL;
+    int i;
+    Error *errp = NULL;
+
+    intc_phandle = qemu_fdt_getprop_cell_inherited(fdt, node_path,
+                                                   "interrupt-parent",
+                                                   0, &errp);
+    if (errp) {
+        errp = NULL;
+        intc_cells = qemu_fdt_getprop_cell_inherited(fdt, node_path,
+                                           "#interrupt-cells", 0, &errp);
+        *map_mode = true;
+    } else {
+        if (qemu_devtree_get_node_by_phandle(fdt, intc_node_path,
+                                             intc_phandle)) {
+            goto fail;
+        }
+
+        /* Check if the device is using interrupt-maps */
+        qemu_fdt_getprop_cell(fdt, node_path, "interrupt-map-mask", 0,
+                              &errp);
+        if (!errp) {
+            errp = NULL;
+            intc_cells = qemu_fdt_getprop_cell_inherited(fdt, node_path,
+                                               "#interrupt-cells", 0,
+                                               &errp);
+            *map_mode = true;
+        } else {
+            errp = NULL;
+            intc_cells = qemu_fdt_getprop_cell_inherited(fdt, intc_node_path,
+                                               "#interrupt-cells", 0,
+                                               &errp);
+            *map_mode = false;
+        }
+    }
+
+    if (errp) {
+        goto fail;
+    }
+
+    DB_PRINT_NP(2, "%s intc_phandle: %d\n", node_path, intc_phandle);
+
+    for (i = 0; i < intc_cells; ++i) {
+        cells[i] = qemu_fdt_getprop_cell(fdt, node_path, "interrupts",
+                                        intc_cells * irq_idx + i, &errp);
+        if (errp) {
+            goto fail;
+        }
+    }
+
+    if (*map_mode) {
+        int k;
+        ret = g_new0(qemu_irq, 1);
+        int num_matches = 0;
+        int len;
+        g_autofree uint32_t *imap_mask = g_new(uint32_t, intc_cells);
+        const uint32_t *prop;
+        uint32_t *imap;
+        bool use_parent = false;
+
+        for (k = 0; k < intc_cells; ++k) {
+            imap_mask[k] = qemu_fdt_getprop_cell_inherited(fdt, node_path,
+                                                 "interrupt-map-mask", k + 2,
+                                                 &errp);
+            if (errp) {
+                goto fail;
+            }
+        }
+
+        /* Check if the device has an interrupt-map property */
+        prop = qemu_fdt_getprop(fdt, node_path, "interrupt-map", &len,
+                                  &errp);
+        imap = g_memdup2(prop, len);
+        if (!imap || errp) {
+            /*
+             * If the device doesn't have an interrupt-map, try again with
+             * inheritance. This will return the parents interrupt-map
+             */
+            use_parent = true;
+            errp = NULL;
+
+            prop = qemu_fdt_getprop_inherited(fdt, node_path, "interrupt-map",
+                                      &len, &errp);
+            if (!imap_cached) {
+                memcpy(imap_cache, prop, len);
+                imap_cached = true;
+            }
+            imap = imap_cache;
+
+            if (errp) {
+                goto fail;
+            }
+        }
+
+        len /= sizeof(uint32_t);
+
+        i = 0;
+        assert(imap);
+        while (i < len) {
+            if (!use_parent) {
+                /*
+                 * Only re-sync the interrupt-map when the device has it's
+                 * own map, to save time.
+                 */
+                prop = qemu_fdt_getprop(fdt, node_path, "interrupt-map", &len,
+                                          &errp);
+                if (imap != imap_cache) {
+                    g_free(imap);
+                }
+                imap = g_memdup2(prop, len);
+                if (errp) {
+                    goto fail;
+                }
+
+                len /= sizeof(uint32_t);
+            }
+
+            bool match = true;
+            uint32_t new_intc_cells, new_cells[32];
+            i++; i++; /* FIXME: do address cells properly */
+            for (k = 0; k < intc_cells; ++k) {
+                uint32_t  map_val = be32_to_cpu(imap[i++]);
+                if ((cells[k] ^ map_val) & imap_mask[k]) {
+                    match = false;
+                }
+            }
+            /*
+             * when caching, we hackishly store the number of cells for
+             * the parent in the MSB. +1, so zero MSB means non cachd
+             * and the full lookup is needed.
+             */
+            intc_phandle = be32_to_cpu(imap[i++]);
+            if (intc_phandle & (0xffu << 24)) {
+                new_intc_cells = (intc_phandle >> 24) - 1;
+            } else {
+                if (qemu_devtree_get_node_by_phandle(fdt, intc_node_path,
+                                                     intc_phandle)) {
+                    goto fail;
+                }
+                new_intc_cells = qemu_fdt_getprop_cell(fdt, intc_node_path,
+                                                       "#interrupt-cells", 0,
+                                                       &errp);
+                imap[i - 1] = cpu_to_be32(intc_phandle |
+                                            (new_intc_cells + 1) << 24);
+                if (errp) {
+                    goto fail;
+                }
+            }
+            for (k = 0; k < new_intc_cells; ++k) {
+                new_cells[k] = be32_to_cpu(imap[i++]);
+            }
+            if (match) {
+                num_matches++;
+                ret = g_renew(qemu_irq, ret, num_matches + 1);
+                if (intc_phandle & (0xffu << 24)) {
+                    if (qemu_devtree_get_node_by_phandle(fdt, intc_node_path,
+                                                         intc_phandle &
+                                                         ((1 << 24) - 1))) {
+                        goto fail;
+                    }
+                }
+
+                DB_PRINT_NP(2, "Getting IRQ information: %s -> 0x%x (%s)\n",
+                            node_path, intc_phandle, intc_node_path);
+
+                memset(&ret[num_matches], 0, sizeof(*ret));
+                fdt_get_irq_info_from_intc(fdti, &ret[num_matches - 1],
+                                           intc_node_path, new_cells,
+                                           new_intc_cells, 1, NULL);
+                if (info) {
+                    sprintf(info, "%s", intc_node_path);
+                    info += strlen(info) + 1;
+                }
+            }
+        }
+
+        if (imap != imap_cache) {
+            g_free(imap);
+        }
+        return ret;
+    }
+
+    DB_PRINT_NP(2, "Getting IRQ information: %s -> %s\n",
+                node_path, intc_node_path);
+
+    ret = g_new0(qemu_irq, fdt_generic_num_cpus + 2);
+    fdt_get_irq_info_from_intc(fdti, ret, intc_node_path, cells, intc_cells,
+                               fdt_generic_num_cpus, &errp);
+
+    if (errp) {
+        goto fail;
+    }
+
+    /* FIXME: Phase out this info bussiness */
+    if (info) {
+        sprintf(info, "%s", intc_node_path);
+    }
+
+    return ret;
+
+fail:
+    if (errp) {
+        sprintf(info, "%s", error_get_pretty(errp));
+    } else {
+        sprintf(info, "(none)");
+    }
+    return NULL;
+}
+
+qemu_irq *fdt_get_irq(FDTMachineInfo *fdti, char *node_path, int irq_idx,
+                      bool *map_mode)
+{
+    return fdt_get_irq_info(fdti, node_path, irq_idx, NULL, map_mode);
+}
+
 /* FIXME: figure out a real solution to this */
 
 #define DIGIT(a) ((a) >= '0' && (a) <= '9')
include/hw/core/fdt_generic_util.h +18 -0
index c5aaa58dd6..dfc9fa3632 100644
@@ -16,6 +16,24 @@
 
 FDTMachineInfo *fdt_generic_create_machine(void *fdt, qemu_irq *cpu_irq);
 
+/*
+ * get an irq for a device. The interrupt parent of a device is idenitified
+ * and the specified irq (by the interrupts device-tree property) is retrieved
+ */
+
+qemu_irq *fdt_get_irq(FDTMachineInfo *fdti, char *node_path, int irq_idx,
+                      bool *map_mode);
+
+/*
+ * same as above, but poulates err with non-zero if something goes wrong, and
+ * populates info with a human readable string giving some basic information
+ * about the interrupt connection found (or not found). Both arguments are
+ * optional (i.e. can be NULL)
+ */
+
+qemu_irq *fdt_get_irq_info(FDTMachineInfo *fdti, char *node_path, int irq_idx,
+                           char *info, bool *map_mode);
+
 #define TYPE_FDT_GENERIC_INTC "fdt-generic-intc"
 
 #define FDT_GENERIC_INTC_CLASS(klass) \
Signature · 1 line
2.43.0
#16 lore raw

PATCH v2 15/33 hw/core/fdt_generic_util: map device memory

In reply to Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]>

Parse device mmio regions provided within 'reg' and 'reg-extened' device tree properties.
Call corresponding device interface class handlers to create memory regions.

---
 hw/core/fdt_generic_util.c | 129 +++++++++++++++++++++++++++++++++++++
 1 file changed, 129 insertions(+)
hw/core/fdt_generic_util.c +129 -0
index dcacc5033b..838ed9a85c 100644
@@ -630,6 +630,22 @@ static inline uint64_t get_int_be(const void *p, int len)
     }
 }
 
+/* FIXME: use structs instead of parallel arrays */
+
+static const char *fdt_generic_reg_size_prop_names[] = {
+    "#address-cells",
+    "#size-cells",
+    "#bus-cells",
+    "#priority-cells",
+};
+
+static const int fdt_generic_reg_cells_defaults[] = {
+    1,
+    1,
+    0,
+    0,
+};
+
 /*
  * Error handler for device creation failure.
  *
@@ -831,6 +847,117 @@ static void fdt_init_qdev_array_prop(Object *obj,
     DB_PRINT_NP(0, "set property %s propname to <list>\n", propname);
 }
 
+static void fdt_parse_node_reg_prop(FDTMachineInfo *fdti, char *node_path,
+                            Object *dev)
+{
+    FDTGenericRegPropInfo reg = {0};
+    Object *parent;
+    char parent_path[DT_PATH_LENGTH];
+    int cell_idx = 0;
+    bool extended = true;
+    Error *errp = NULL;
+    int i;
+
+    if (!object_dynamic_cast(dev, TYPE_SYS_BUS_DEVICE) &&
+        !object_dynamic_cast(dev, TYPE_FDT_GENERIC_MMAP))
+        return;
+
+    qemu_fdt_getprop_cell(fdti->fdt, node_path, "reg-extended", 0,
+                            &errp);
+    if (errp) {
+        error_free(errp);
+        errp = NULL;
+        extended = false;
+        qemu_devtree_getparent(fdti->fdt, parent_path, node_path);
+    }
+
+    parent = fdt_init_get_opaque(fdti, parent_path);
+
+    for (reg.n = 0;; reg.n++) {
+        char ph_parent[DT_PATH_LENGTH];
+        const char *pnp = parent_path;
+
+        reg.parents = g_renew(Object *, reg.parents, reg.n + 1);
+        reg.parents[reg.n] = parent;
+
+        if (extended) {
+            int p_ph = qemu_fdt_getprop_cell(fdti->fdt, node_path,
+                                                "reg-extended", cell_idx++,
+                                                &errp);
+            if (errp) {
+                error_free(errp);
+                errp = NULL;
+                goto exit_reg_parse;
+            }
+            if (qemu_devtree_get_node_by_phandle(fdti->fdt, ph_parent,
+                                                    p_ph)) {
+                goto exit_reg_parse;
+            }
+
+            while (!fdt_init_has_opaque(fdti, ph_parent) &&
+                   qemu_in_coroutine()) {
+                fdt_init_yield(fdti);
+            }
+
+            if (!fdt_init_has_opaque(fdti, ph_parent)) {
+                goto exit_reg_parse;
+            }
+
+            reg.parents[reg.n] = fdt_init_get_opaque(fdti, ph_parent);
+            pnp = ph_parent;
+        }
+
+        for (i = 0; i < FDT_GENERIC_REG_TUPLE_LENGTH; ++i) {
+            const char *size_prop_name = fdt_generic_reg_size_prop_names[i];
+            int nc = qemu_fdt_getprop_cell_inherited(fdti->fdt, node_path,
+                                            size_prop_name, 0, &errp);
+            uint64_t val = 0;
+
+            if (errp) {
+                int size_default = fdt_generic_reg_cells_defaults[i];
+
+                DB_PRINT_NP(0, "WARNING: no %s for %s container, assuming "
+                            "default of %d\n", size_prop_name, pnp,
+                            size_default);
+                nc = size_default;
+                error_free(errp);
+                errp = NULL;
+            }
+
+            reg.x[i] = g_renew(uint64_t, reg.x[i], reg.n + 1);
+            for (int j = 0; j < nc; ++j) {
+                val <<= 32;
+                val |= qemu_fdt_getprop_cell(fdti->fdt, node_path,
+                                            extended ? "reg-extended"
+                                                        : "reg",
+                                            cell_idx + j, &errp);
+               if (errp) {
+                    val = 0;
+                    break;
+               }
+            }
+            reg.x[i][reg.n] = val;
+            cell_idx += nc;
+            if (errp) {
+                goto exit_reg_parse;
+            }
+        }
+    }
+
+exit_reg_parse:
+    if (object_dynamic_cast(dev, TYPE_FDT_GENERIC_MMAP)) {
+        FDTGenericMMapClass *fmc = FDT_GENERIC_MMAP_GET_CLASS(dev);
+        if (fmc->parse_reg) {
+            while (fmc->parse_reg(FDT_GENERIC_MMAP(dev), reg,
+                                  &error_abort) && qemu_in_coroutine()) {
+                fdt_init_yield(fdti);
+            }
+        }
+    }
+
+    return;
+}
+
 static int fdt_init_qdev(char *node_path, FDTMachineInfo *fdti, char *compat)
 {
     Object *dev, *parent;
@@ -972,6 +1099,8 @@ static int fdt_init_qdev(char *node_path, FDTMachineInfo *fdti, char *compat)
         }
     }
 
+    fdt_parse_node_reg_prop(fdti, node_path, dev);
+
     g_free(dev_type);
     g_free(props);
 
Signature · 1 line
2.43.0
#17 lore raw

PATCH v2 16/33 hw/core/fdt_generic_util: Connect device irqs

In reply to Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]>

The patch implements IRQ wiring logic for fdt created devices.

The wiring performed in two stages. As devices are created, their IRQs saved in the list.
After all devices processed, fdt_init_all_irqs() goes through all IRQs and does actual wiring. For IRQs which have multiple source, shared IRQ handler allocated.

For interrupt controllers with auto_parent callback implemented and their fdt node has 'interrupt and 'interrupts-extended' properties empty,
the auto_parent() will be called to connect them to their interrupt-parent, for example to CPUs.

---
 hw/core/fdt_generic_util.c    | 154 ++++++++++++++++++++++++++++++++++
 include/hw/core/fdt_generic.h |  12 +++
 2 files changed, 166 insertions(+)
hw/core/fdt_generic_util.c +154 -0
index 838ed9a85c..63390e2f17 100644
@@ -75,6 +75,88 @@ static void fdt_get_irq_info_from_intc(FDTMachineInfo *fdti, qemu_irq *ret,
                                        uint32_t *cells, uint32_t num_cells,
                                        uint32_t max, Error **errp);
 
+typedef struct QEMUIRQSharedState {
+    qemu_irq sink;
+    int num;
+    bool (*merge_fn)(bool *, int);
+/* FIXME: remove artificial limit */
+#define MAX_IRQ_SHARED_INPUTS 256
+    bool inputs[MAX_IRQ_SHARED_INPUTS];
+} QEMUIRQSharedState;
+
+static bool qemu_irq_shared_or_handler(bool *inputs, int n)
+{
+    int i;
+
+    assert(n < MAX_IRQ_SHARED_INPUTS);
+
+    for (i = 0; i < n; ++i) {
+        if (inputs[i]) {
+            return true;
+        }
+    }
+    return false;
+}
+
+static void qemu_irq_shared_handler(void *opaque, int n, int level)
+{
+    QEMUIRQSharedState *s = opaque;
+
+    assert(n < MAX_IRQ_SHARED_INPUTS);
+    s->inputs[n] = level;
+    qemu_set_irq(s->sink, s->merge_fn(s->inputs, s->num));
+}
+
+static void fdt_init_all_irqs(FDTMachineInfo *fdti)
+{
+    while (fdti->irqs) {
+        FDTIRQConnection *first = fdti->irqs;
+        qemu_irq sink = first->irq;
+        bool (*merge_fn)(bool *, int) = first->merge_fn;
+        int num_sources = 0;
+        FDTIRQConnection *irq;
+
+        for (irq = first; irq; irq = irq->next) {
+            if (irq->irq == sink) { /* Same sink */
+                num_sources++;
+            }
+        }
+        if (num_sources > 1) {
+            QEMUIRQSharedState *s = g_malloc0(sizeof *s);
+            s->sink = sink;
+            s->merge_fn = merge_fn;
+            qemu_irq *sources = qemu_allocate_irqs(qemu_irq_shared_handler, s,
+                                                   num_sources);
+            for (irq = first; irq; irq = irq->next) {
+                if (irq->irq == sink) {
+                    char *shared_irq_name = g_strdup_printf("shared-irq-%p",
+                                                            *sources);
+
+                    if (irq->merge_fn != merge_fn) {
+                        fprintf(stderr, "ERROR: inconsistent IRQ merge fns\n");
+                        exit(1);
+                    }
+
+                    object_property_add_child(OBJECT(irq->dev), shared_irq_name,
+                                              OBJECT(*sources));
+                    g_free(shared_irq_name);
+                    irq->irq = *(sources++);
+                    s->num++;
+                }
+            }
+        }
+        DB_PRINT(0, "%s: connected to %s irq line %d (%s)\n",
+                 first->sink_info ? first->sink_info : "",
+                 object_get_canonical_path(OBJECT(first->dev)),
+                 first->i, first->name ? first->name : "");
+
+        qdev_connect_gpio_out_named(DEVICE(first->dev), first->name, first->i,
+                                    first->irq);
+        fdti->irqs = first->next;
+        g_free(first);
+    }
+}
+
 FDTMachineInfo *fdt_generic_create_machine(void *fdt, qemu_irq *cpu_irq)
 {
     char node_path[DT_PATH_LENGTH];
@@ -90,6 +172,7 @@ FDTMachineInfo *fdt_generic_create_machine(void *fdt, qemu_irq *cpu_irq)
         while (qemu_co_enter_next(fdti->cq, NULL)) {
             ;
         }
+        fdt_init_all_irqs(fdti);
         memory_region_transaction_commit();
     } else {
         fprintf(stderr, "FDT: ERROR: cannot get root node from device tree %s\n"
@@ -958,6 +1041,75 @@ exit_reg_parse:
     return;
 }
 
+static void fdt_parse_node_irq_prop(FDTMachineInfo *fdti, char *node_path,
+                            Object *dev)
+{
+    int is_intc;
+    int i, j;
+
+    if (!object_dynamic_cast(dev, TYPE_SYS_BUS_DEVICE)) {
+        return;
+    }
+
+    {
+        int len;
+        fdt_get_property(fdti->fdt, fdt_path_offset(fdti->fdt, node_path),
+                                "interrupt-controller", &len);
+        is_intc = len >= 0;
+        DB_PRINT_NP(is_intc ? 0 : 1, "is interrupt controller: %c\n",
+                    is_intc ? 'y' : 'n');
+    }
+    /* connect irq */
+    j = 0;
+    for (i = 0;; i++) {
+        char irq_info[6 * 1024];
+        char *irq_info_p = irq_info;
+        bool map_mode;
+        int len = -1;
+        qemu_irq *irqs = fdt_get_irq_info(fdti, node_path, i, irq_info,
+                                            &map_mode);
+        /* INTCs inferr their top level, if no IRQ connection specified */
+        fdt_get_property(fdti->fdt, fdt_path_offset(fdti->fdt, node_path),
+                            "interrupts-extended", &len);
+        if (!irqs && is_intc && i == 0 && len <= 0) {
+            FDTGenericIntc *id = (FDTGenericIntc *)object_dynamic_cast(
+                                    dev, TYPE_FDT_GENERIC_INTC);
+            FDTGenericIntcClass *idc = FDT_GENERIC_INTC_GET_CLASS(id);
+            if (id && idc->auto_parent) {
+                Error *err = NULL;
+                idc->auto_parent(id, &err);
+            } else {
+                irqs = fdti->irq_base;
+            }
+        }
+        if (!irqs) {
+            break;
+        }
+        while (*irqs) {
+            FDTIRQConnection *irq = g_new0(FDTIRQConnection, 1);
+            *irq = (FDTIRQConnection) {
+                .dev = DEVICE(dev),
+                .name = SYSBUS_DEVICE_GPIO_IRQ,
+                .merge_fn = qemu_irq_shared_or_handler,
+                .i = j,
+                .irq = *irqs,
+                .sink_info = g_strdup(irq_info_p),
+                .next = fdti->irqs
+            };
+            if (!map_mode) {
+                j++;
+            } else {
+                irq_info_p += strlen(irq_info_p) + 1;
+            }
+            fdti->irqs = irq;
+            irqs++;
+        }
+        if (map_mode) {
+            j++;
+        }
+    }
+}
+
 static int fdt_init_qdev(char *node_path, FDTMachineInfo *fdti, char *compat)
 {
     Object *dev, *parent;
@@ -1101,6 +1253,8 @@ static int fdt_init_qdev(char *node_path, FDTMachineInfo *fdti, char *compat)
 
     fdt_parse_node_reg_prop(fdti, node_path, dev);
 
+    fdt_parse_node_irq_prop(fdti, node_path, dev);
+
     g_free(dev_type);
     g_free(props);
 
include/hw/core/fdt_generic.h +12 -0
index 46b7dc084b..ad9e249156 100644
@@ -24,6 +24,16 @@ typedef struct FDTCPUCluster {
     bool user;
 } FDTCPUCluster;
 
+typedef struct FDTIRQConnection {
+    DeviceState *dev;
+    const char *name;
+    int i;
+    bool (*merge_fn)(bool *, int);
+    qemu_irq irq;
+    char *sink_info; /* Debug only */
+    void *next;
+} FDTIRQConnection;
+
 typedef struct FDTMachineInfo {
     /* the fdt blob */
     void *fdt;
@@ -33,6 +43,8 @@ typedef struct FDTMachineInfo {
     FDTDevOpaque *dev_opaques;
     /* recheck coroutine queue */
     CoQueue *cq;
+    /* list of all IRQ connections */
+    FDTIRQConnection *irqs;
     /* list of all CPU clusters */
     FDTCPUCluster *clusters;
 } FDTMachineInfo;
Signature · 1 line
2.43.0
#18 lore raw

PATCH v2 17/33 hw/core/fdt_generic_util: realize cpu clusters

In reply to Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]>

Realize cpu clusters at the end of fdt machine creation process, as they need to be created after cpu's nodes are realized.

---
 hw/core/fdt_generic_util.c | 11 +++++++++++
 1 file changed, 11 insertions(+)
hw/core/fdt_generic_util.c +11 -0
index 63390e2f17..3179248142 100644
@@ -157,6 +157,16 @@ static void fdt_init_all_irqs(FDTMachineInfo *fdti)
     }
 }
 
+static void fdt_init_cpu_clusters(FDTMachineInfo *fdti)
+{
+    FDTCPUCluster *cl = fdti->clusters;
+
+    while (cl) {
+        qdev_realize(DEVICE(cl->cpu_cluster), NULL, &error_fatal);
+        cl = cl->next;
+    }
+}
+
 FDTMachineInfo *fdt_generic_create_machine(void *fdt, qemu_irq *cpu_irq)
 {
     char node_path[DT_PATH_LENGTH];
@@ -172,6 +182,7 @@ FDTMachineInfo *fdt_generic_create_machine(void *fdt, qemu_irq *cpu_irq)
         while (qemu_co_enter_next(fdti->cq, NULL)) {
             ;
         }
+        fdt_init_cpu_clusters(fdti);
         fdt_init_all_irqs(fdti);
         memory_region_transaction_commit();
     } else {
Signature · 1 line
2.43.0
#19 lore raw

PATCH v2 18/33 hw/core: add fdt_generic to the build

In reply to Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]>

Add fdt_generic.c and fdt_generic_util.c to build by default.

---
 hw/core/meson.build | 2 ++
 1 file changed, 2 insertions(+)
hw/core/meson.build +2 -0
index 8a96567de8..b5ba8160e6 100644
@@ -29,6 +29,8 @@ system_ss.add(when: 'CONFIG_EIF', if_true: [files('eif.c'), zlib, libcbor, gnutl
 
 system_ss.add(files(
   'cpu-system.c',
+  'fdt_generic.c',
+  'fdt_generic_util.c',
   'fw-path-provider.c',
   'hotplug.c',
   'loader.c',
Signature · 1 line
2.43.0
#20 lore raw

PATCH v2 19/33 hw/core/machine: add '-hw-dtb' option for machine

In reply to Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]>

Add new '-hw-dtb' command-line option and corresponding MachineState property.
The 'hw-dtb' option allows to specify a Device tree binary with hardware description which Qemu should emulate.

---
 hw/core/machine.c        | 19 +++++++++++++++++++
 include/hw/core/boards.h |  1 +
 qemu-options.hx          |  9 +++++++++
 system/vl.c              |  3 +++
 4 files changed, 32 insertions(+)
hw/core/machine.c +19 -0
index d4ef620c17..affd24cd49 100644
@@ -363,6 +363,20 @@ static void machine_set_dtb(Object *obj, const char *value, Error **errp)
     ms->dtb = g_strdup(value);
 }
 
+static char *machine_get_hw_dtb(Object *obj, Error **errp)
+{
+    MachineState *ms = MACHINE(obj);
+
+    return g_strdup(ms->hw_dtb);
+}
+
+static void machine_set_hw_dtb(Object *obj, const char *value, Error **errp)
+{
+    MachineState *ms = MACHINE(obj);
+
+    ms->hw_dtb = g_strdup(value);
+}
+
 static char *machine_get_dumpdtb(Object *obj, Error **errp)
 {
     MachineState *ms = MACHINE(obj);
@@ -1145,6 +1159,11 @@ static void machine_class_init(ObjectClass *oc, const void *data)
     object_class_property_set_description(oc, "dtb",
         "Linux kernel device tree file");
 
+    object_class_property_add_str(oc, "hw-dtb",
+                            machine_get_hw_dtb, machine_set_hw_dtb);
+    object_class_property_set_description(oc, "hw-dtb",
+                "A device tree binary used to describe the hardware to QEMU");
+
     object_class_property_add_str(oc, "dumpdtb",
         machine_get_dumpdtb, machine_set_dumpdtb);
     object_class_property_set_description(oc, "dumpdtb",
include/hw/core/boards.h +1 -0
index edbe8d03e5..722b79b5e4 100644
@@ -403,6 +403,7 @@ struct MachineState {
 
     void *fdt;
     char *dtb;
+    char *hw_dtb;
     char *dumpdtb;
     int phandle_start;
     char *dt_compatible;
qemu-options.hx +9 -0
index 33fcfe7ce6..1568f3ce4c 100644
@@ -4518,6 +4518,15 @@ SRST(initrd)
 
 ERST
 
+DEF("hw-dtb", HAS_ARG, QEMU_OPTION_hw_dtb, \
+    "-hw-dtb file    use 'file' as device tree image\n", QEMU_ARCH_ALL)
+SRST
+``-hw-dtb file``
+    Use <file> as a device tree binary (dtb) image used to create the
+    emulated machine. This dtb will not be passed to the kernel, use -dtb
+    for that.
+ERST
+
 DEF("dtb", HAS_ARG, QEMU_OPTION_dtb, \
     "-dtb    file    use 'file' as device tree image\n", QEMU_ARCH_ALL)
 SRST
system/vl.c +3 -0
index aa9a155041..c890da586c 100644
@@ -3020,6 +3020,9 @@ void qemu_init(int argc, char **argv)
             case QEMU_OPTION_dtb:
                 qdict_put_str(machine_opts_dict, "dtb", optarg);
                 break;
+            case QEMU_OPTION_hw_dtb:
+                qdict_put_str(machine_opts_dict, "hw-dtb", optarg);
+                break;
             case QEMU_OPTION_cdrom:
                 drive_add(IF_DEFAULT, 2, optarg, CDROM_OPTS);
                 break;
Signature · 1 line
2.43.0
#21 lore raw

PATCH v2 20/33 hw/arm: add generic ARM machine initialized by FDT

From: Ruslan Ruslichenko <[email protected]>

This patch introduces new ARM machine model, which is fully instantiated from a Device Tree description.

This model uses fdt_generic framework to dynamically construct system topology based on provided DTB, instead of standard machines which rely on hardcoded models in C files.

This allows to contruct machines with custom memory maps, device structures without the need to modify and re-build QEMU sources each time.

---
 hw/arm/arm_generic_fdt.c | 180 +++++++++++++++++++++++++++++++++++++++
 hw/arm/meson.build       |   2 +
 2 files changed, 182 insertions(+)
 create mode 100644 hw/arm/arm_generic_fdt.c
hw/arm/arm_generic_fdt.c new file +180 -0
new file mode 100644
index 0000000000..49206269aa
@@ -0,0 +1,180 @@
+// SPDX-License-Identifier: GPL-2.0-or-later
+/*
+ * Copyright (c) 2012 Xilinx. Inc
+ * Copyright (c) 2012 Peter A.G. Crosthwaite ([email protected])
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version
+ * 2 of the License, or (at your option) any later version.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include "qemu/osdep.h"
+#include "cpu.h"
+#include "hw/core/boards.h"
+#include "hw/core/loader.h"
+#include "hw/core/hw-error.h"
+#include "qapi/error.h"
+#include "hw/block/flash.h"
+#include "qemu/error-report.h"
+#include "qemu/log.h"
+#include "qemu/config-file.h"
+#include "qemu/option.h"
+#include "system/system.h"
+#include "system/qtest.h"
+#include "hw/arm/boot.h"
+#include "hw/arm/machines-qom.h"
+
+#include <libfdt.h>
+#include "hw/core/fdt_generic_util.h"
+
+#define GENERAL_MACHINE_NAME "arm-generic-fdt"
+
+#define QTEST_RUNNING (qtest_enabled() && qtest_driver())
+
+#define SMP_BOOT_ADDR 0xfffffff0
+/* Meaningless, but keeps arm boot happy */
+#define SMP_BOOTREG_ADDR 0xfffffffc
+
+static struct arm_boot_info arm_generic_fdt_binfo = {};
+
+typedef struct {
+    ram_addr_t ram_kernel_base;
+    ram_addr_t ram_kernel_size;
+} memory_info;
+
+typedef struct {
+    int fdt_size;
+    char *dtb;
+} FdtBlob;
+
+FdtBlob sw_fdt;
+
+static memory_info init_memory(void *fdt, ram_addr_t ram_size)
+{
+    FDTMachineInfo *fdti;
+    MemoryRegion *mem_area;
+    memory_info kernel_info;
+    Error *errp = NULL;
+    char **node_path;
+
+    /* Find a memory node or add new one if needed */
+    node_path = qemu_fdt_node_unit_path(fdt, "memory", &errp);
+    if (errp) {
+        error_report_err(errp);
+        exit(1);
+    }
+    if (!g_str_has_prefix(node_path[0], "/memory")) {
+        error_report("Failed to find /memory node");
+        exit(1);
+    }
+
+    /* Instantiate peripherals from the FDT.  */
+    fdti = fdt_generic_create_machine(fdt, NULL);
+
+    mem_area = MEMORY_REGION(object_resolve_path(node_path[0], NULL));
+
+    kernel_info.ram_kernel_base = object_property_get_int(OBJECT(mem_area),
+                                                            "addr", NULL);
+
+    kernel_info.ram_kernel_size = object_property_get_int(OBJECT(mem_area),
+                                                          "size", NULL);
+
+    if (kernel_info.ram_kernel_size == -1) {
+        kernel_info.ram_kernel_size = ram_size;
+    }
+
+    fdt_init_destroy_fdti(fdti);
+    g_strfreev(node_path);
+
+    return kernel_info;
+}
+
+static void *get_ref_dtb(const struct arm_boot_info *binfo, int *fdt_size)
+{
+    *fdt_size = sw_fdt.fdt_size;
+    return sw_fdt.dtb;
+}
+
+static void arm_generic_fdt_init(MachineState *machine)
+{
+    void *fdt = NULL;
+    int fdt_size;
+    const char *hw_dtb_arg, *dtb_arg;
+    memory_info kernel_info;
+
+    dtb_arg = machine->dtb;
+    hw_dtb_arg = machine->hw_dtb;
+    if (!dtb_arg && !hw_dtb_arg) {
+        if (!QTEST_RUNNING) {
+            /*
+             * Just return without error if running qtest, as we never have a
+             * device tree
+             */
+            hw_error("DTB must be specified for %s machine model\n",
+                     MACHINE_GET_CLASS(machine)->name);
+        }
+        return;
+    }
+
+    /* Software dtb is always the -dtb arg */
+    if (dtb_arg) {
+        sw_fdt.dtb = load_device_tree(dtb_arg, &sw_fdt.fdt_size);
+        if (!sw_fdt.dtb) {
+            error_report("Error: Unable to load Device Tree %s", dtb_arg);
+            exit(1);
+        }
+    }
+
+    /* If the user provided a -hw-dtb, use it as the hw description.  */
+    if (hw_dtb_arg) {
+        fdt = load_device_tree(hw_dtb_arg, &fdt_size);
+        if (!fdt) {
+            error_report("Error: Unable to load Device Tree %s", hw_dtb_arg);
+            exit(1);
+        }
+    } else if (sw_fdt.dtb) {
+        fdt = sw_fdt.dtb;
+        fdt_size = sw_fdt.fdt_size;
+    }
+
+    kernel_info = init_memory(fdt, machine->ram_size);
+
+    arm_generic_fdt_binfo.get_dtb = get_ref_dtb;
+    arm_generic_fdt_binfo.ram_size = kernel_info.ram_kernel_size;
+    arm_generic_fdt_binfo.kernel_filename = machine->kernel_filename;
+    arm_generic_fdt_binfo.kernel_cmdline = machine->kernel_cmdline;
+    arm_generic_fdt_binfo.initrd_filename = machine->initrd_filename;
+    arm_generic_fdt_binfo.smp_loader_start = SMP_BOOT_ADDR;
+    arm_generic_fdt_binfo.smp_bootreg_addr = SMP_BOOTREG_ADDR;
+    arm_generic_fdt_binfo.board_id = 0xd32;
+    arm_generic_fdt_binfo.loader_start = kernel_info.ram_kernel_base;
+    arm_generic_fdt_binfo.psci_conduit = QEMU_PSCI_CONDUIT_SMC;
+
+    if (!machine->kernel_filename) {
+        arm_generic_fdt_binfo.firmware_loaded = true;
+        arm_generic_fdt_binfo.psci_conduit = QEMU_PSCI_CONDUIT_DISABLED;
+    }
+
+    arm_load_kernel(ARM_CPU(first_cpu), machine, &arm_generic_fdt_binfo);
+
+    return;
+}
+
+static void arm_generic_fdt_machine_init(MachineClass *mc)
+{
+    mc->desc = "ARM device tree driven machine model";
+    mc->init = arm_generic_fdt_init;
+    mc->max_cpus = 64;
+    mc->default_cpus = 4;
+
+    mc->pci_allow_0_address = true;
+    mc->minimum_page_bits = 12;
+    mc->smp_props.clusters_supported = true;
+
+}
+
+DEFINE_MACHINE_ARM("arm-generic-fdt", arm_generic_fdt_machine_init)
hw/arm/meson.build +2 -0
index 47cdc51d13..1ef0b8c2c1 100644
@@ -1,4 +1,6 @@
 arm_ss = ss.source_set()
+arm_ss.add(files('arm_generic_fdt.c'))
+
 arm_common_ss = ss.source_set()
 arm_common_ss.add(when: 'CONFIG_ARM_VIRT', if_true: files('virt.c'))
 arm_common_ss.add(when: 'CONFIG_ACPI', if_true: files('virt-acpi-build.c'))
Signature · 1 line
2.43.0
#22 lore raw

PATCH v2 21/33 hw/core/sysbus: implement FDT_GENERIC_MMAP_CLASS interface

In reply to Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]>

The patch implements FDTGenericMMap interface for sysbus device class. The implementation maps device's MMIO regions based on 'reg' property in the Device tree.

This enables automatic memory mapping for the most QEMU peripherals without the need of device-specific FDT handling code.

---
 hw/core/sysbus.c | 28 ++++++++++++++++++++++++++++
 1 file changed, 28 insertions(+)
hw/core/sysbus.c +28 -0
index 3adf2f2faf..78b7827708 100644
@@ -23,6 +23,8 @@
 #include "monitor/monitor.h"
 #include "system/address-spaces.h"
 
+#include "hw/core/fdt_generic_util.h"
+
 static void sysbus_dev_print(Monitor *mon, DeviceState *dev, int indent);
 static char *sysbus_get_fw_dev_path(DeviceState *dev);
 
@@ -291,11 +293,32 @@ static char *sysbus_get_fw_dev_path(DeviceState *dev)
     return g_strdup(qdev_fw_name(dev));
 }
 
+static bool sysbus_parse_reg(FDTGenericMMap *obj, FDTGenericRegPropInfo reg,
+                             Error **errp)
+{
+    int i;
+
+    for (i = 0; i < reg.n; ++i) {
+        MemoryRegion *mr_parent = (MemoryRegion *)
+            object_dynamic_cast(reg.parents[i], TYPE_MEMORY_REGION);
+        if (!mr_parent) {
+            /* evil */
+            mr_parent = get_system_memory();
+        }
+        memory_region_add_subregion_overlap(mr_parent, reg.a[i],
+                                 sysbus_mmio_get_region(SYS_BUS_DEVICE(obj), i),
+                                 reg.p[i]);
+    }
+    return false;
+}
+
 static void sysbus_device_class_init(ObjectClass *klass, const void *data)
 {
     DeviceClass *k = DEVICE_CLASS(klass);
+    FDTGenericMMapClass *fmc = FDT_GENERIC_MMAP_CLASS(klass);
     k->realize = sysbus_device_realize;
     k->bus_type = TYPE_SYSTEM_BUS;
+    fmc->parse_reg = sysbus_parse_reg;
     /*
      * device_add plugs devices into a suitable bus.  For "real" buses,
      * that actually connects the device.  For sysbus, the connections
@@ -354,6 +377,11 @@ static const TypeInfo sysbus_types[] = {
         .abstract       = true,
         .class_size     = sizeof(SysBusDeviceClass),
         .class_init     = sysbus_device_class_init,
+        .interfaces = (InterfaceInfo[]) {
+        { TYPE_FDT_GENERIC_MMAP },
+        { },
+    },
+
     },
     {
         .name           = TYPE_DYNAMIC_SYS_BUS_DEVICE,
Signature · 1 line
2.43.0
#23 lore raw

PATCH v2 22/33 hw/intc/arm_gic: implement FDT_GENERIC_INTC and fdt support

In reply to Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]>

The patch implements TYPE_FDT_GENERIC_INTC interface, which enables GIC to be instantiated and wired via the device tree description.

The implemented interface method are following:
1. 'get_irq': Parses device tree interrupt specifiers and return correct qemu_irq for devices which has IRQ's wired to GIC.
2. 'auto_parent': Automatically connect the GIC's output signals to the CPU's found in current machine configuration.

---
 hw/intc/arm_gic.c        | 32 +++++++++++++++++++++++++
 hw/intc/arm_gic_common.c | 50 ++++++++++++++++++++++++++++++++++++++++
 2 files changed, 82 insertions(+)
hw/intc/arm_gic.c +32 -0
index 4d4b79e6f3..2be44d8e5b 100644
@@ -24,12 +24,15 @@
 #include "gic_internal.h"
 #include "qapi/error.h"
 #include "hw/core/cpu.h"
+#include "hw/core/boards.h"
 #include "qemu/log.h"
 #include "qemu/module.h"
 #include "trace.h"
 #include "system/kvm.h"
 #include "system/qtest.h"
 
+#include "hw/core/fdt_generic_util.h"
+
 /* #define DEBUG_GIC */
 
 #ifdef DEBUG_GIC
@@ -2162,12 +2165,41 @@ static void arm_gic_realize(DeviceState *dev, Error **errp)
 
 }
 
+static void arm_gic_fdt_auto_parent(FDTGenericIntc *obj, Error **errp)
+{
+    GICState *s = ARM_GIC(obj);
+    SysBusDevice *sbd = SYS_BUS_DEVICE(obj);
+    int num_cpus = current_machine->smp.cpus;
+    CPUState *cs;
+    int i = 0;
+
+    for (cs = first_cpu; cs; cs = CPU_NEXT(cs)) {
+        if (i >= s->num_cpu) {
+            break;
+        }
+
+        sysbus_connect_irq(sbd, i,
+                           qdev_get_gpio_in(DEVICE(cs), 0));
+        sysbus_connect_irq(sbd, i + num_cpus,
+                           qdev_get_gpio_in(DEVICE(cs), 1));
+        sysbus_connect_irq(sbd, i + 2 * num_cpus,
+                           qdev_get_gpio_in(DEVICE(cs), 2));
+        sysbus_connect_irq(sbd, i + 3 * num_cpus,
+                           qdev_get_gpio_in(DEVICE(cs), 3));
+        i++;
+    }
+
+    /* FIXME: Add some error checking */
+}
+
 static void arm_gic_class_init(ObjectClass *klass, const void *data)
 {
     DeviceClass *dc = DEVICE_CLASS(klass);
     ARMGICClass *agc = ARM_GIC_CLASS(klass);
+    FDTGenericIntcClass *fgic = FDT_GENERIC_INTC_CLASS(klass);
 
     device_class_set_parent_realize(dc, arm_gic_realize, &agc->parent_realize);
+    fgic->auto_parent = arm_gic_fdt_auto_parent;
 }
 
 static const TypeInfo arm_gic_info = {
hw/intc/arm_gic_common.c +50 -0

80 lines not on this page · raw message

Signature · 1 line
2.43.0
#24 lore raw

PATCH v2 23/33 target/arm/cpu: add fdt support for armv8-timer

In reply to Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]>

Implement FDT compatibility, so that timer can initilize and wire irqs based on device tree information.

---
 target/arm/cpu.c | 115 +++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 115 insertions(+)
target/arm/cpu.c +115 -0
index 7542444b18..6e68aa457e 100644
@@ -54,6 +54,8 @@
 #include "target/arm/gtimer.h"
 
 #include "trace.h"
+#include "hw/core/fdt_generic_util.h"
+
 
 static void arm_cpu_set_pc(CPUState *cs, vaddr value)
 {
@@ -2455,3 +2457,116 @@ static void arm_cpu_register_types(void)
 }
 
 type_init(arm_cpu_register_types)
+
+#ifndef CONFIG_USER_ONLY
+
+static Object *fdt_armv8_timer_get_intc(FDTMachineInfo *fdti, char *node_path)
+{
+    char intc_node_path[DT_PATH_LENGTH];
+    uint32_t intc_phandle;
+    Error *errp = NULL;
+    DeviceState *intc;
+
+    intc_phandle = qemu_fdt_getprop_cell_inherited(fdti->fdt, node_path,
+                                         "interrupt-parent",
+                                         0, &errp);
+
+    /* There must be an interrupt-parent */
+    if (errp ||
+        qemu_devtree_get_node_by_phandle(fdti->fdt,
+                                         intc_node_path, intc_phandle)) {
+        g_assert_not_reached();
+    }
+
+    while (!fdt_init_has_opaque(fdti, intc_node_path)) {
+        fdt_init_yield(fdti);
+    }
+
+    intc = DEVICE(fdt_init_get_opaque(fdti, intc_node_path));
+
+    while (!intc->realized) {
+        fdt_init_yield(fdti);
+    }
+
+    return OBJECT(intc);
+}
+
+static int armv8_timer_fdt_init(char *node_path, FDTMachineInfo *fdti,
+                                void *priv)
+{
+    Object *intc = fdt_armv8_timer_get_intc(fdti, node_path);
+    CPUState *cpu;
+    bool map_mode = false;
+    qemu_irq *sec_irqs = NULL;
+    qemu_irq *ns_irqs;
+    qemu_irq *v_irqs;
+    qemu_irq *h_irqs;
+    uint32_t first_cpu_idx;
+    uint32_t num_cpu;
+    bool has_sec_ext;
+    Error *err = NULL;
+
+    first_cpu_idx = object_property_get_uint(intc, "first-cpu-idx", &err);
+    if (!err) {
+        num_cpu = object_property_get_uint(intc, "num-cpu", &err);
+        assert(!err);
+        has_sec_ext = object_property_get_bool(intc, "has-security-extensions",
+                                               &err);
+        assert(!err);
+    } else {
+        /*
+         * Connect all CPUs with the ARM_FEATURE_GENERIC_TIMER set for
+         * backwards compatibility when the 'first-cpu-idx' property does not
+         * exist.
+         */
+        num_cpu = 0;
+        has_sec_ext = true;
+    }
+
+    if (has_sec_ext) {
+        sec_irqs = fdt_get_irq(fdti, node_path, 0, &map_mode);
+        ns_irqs = fdt_get_irq(fdti, node_path, 1, &map_mode);
+        v_irqs = fdt_get_irq(fdti, node_path, 2, &map_mode);
+        h_irqs = fdt_get_irq(fdti, node_path, 3, &map_mode);
+    } else {
+        ns_irqs = fdt_get_irq(fdti, node_path, 0, &map_mode);
+        v_irqs = fdt_get_irq(fdti, node_path, 1, &map_mode);
+        h_irqs = fdt_get_irq(fdti, node_path, 2, &map_mode);
+    }
+
+    assert(!map_mode); /* not supported for PPI */
+
+    for (cpu = first_cpu; cpu; cpu = CPU_NEXT(cpu)) {
+        ARMCPU *acpu = ARM_CPU(cpu);
+        bool is_gic_cpu;
+
+        if (!arm_feature(&acpu->env, ARM_FEATURE_GENERIC_TIMER)) {
+            continue;
+        }
+
+        is_gic_cpu = cpu->cpu_index >= first_cpu_idx &&
+                     cpu->cpu_index < (first_cpu_idx + num_cpu);
+
+        if (!num_cpu || is_gic_cpu) {
+
+            assert(*ns_irqs);
+            assert(*v_irqs);
+            assert(*h_irqs);
+            qdev_connect_gpio_out(DEVICE(acpu), 0, *ns_irqs++);
+            qdev_connect_gpio_out(DEVICE(acpu), 1, *v_irqs++);
+            qdev_connect_gpio_out(DEVICE(acpu), 2, *h_irqs++);
+
+            if (has_sec_ext) {
+                assert(*sec_irqs);
+                qdev_connect_gpio_out(DEVICE(acpu), 3, *sec_irqs++);
+            }
+        }
+    }
+
+    return 0;
+}
+
+fdt_register_compatibility(armv8_timer_fdt_init,
+                           "compatible:arm,armv8-timer");
+
+#endif
Signature · 1 line
2.43.0
#25 lore raw

PATCH v2 24/33 qom/object: export object_resolve_link()

In reply to Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]>

Export object_resovle_link() for use by other
subsystems.

This allow callers to resolve object path and verify type contrains of a link property.

---
 include/qom/object.h | 12 ++++++++++++
 qom/object.c         |  2 +-
 2 files changed, 13 insertions(+), 1 deletion(-)
include/qom/object.h +12 -0
index 26df6137b9..1573d41d4f 100644
@@ -2034,6 +2034,18 @@ int object_child_foreach_recursive(Object *obj,
  */
 Object *object_property_add_new_container(Object *obj, const char *name);
 
+/*
+ * object_resolve_link:
+ *
+ * Lookup an object and ensure its type matches the link property type.  This
+ * is similar to object_resolve_path() except type verification against the
+ * link property is performed.
+ *
+ * Returns: The matched object or NULL on path lookup failures.
+ */
+Object *object_resolve_link(Object *obj, const char *name,
+    const char *path, Error **errp);
+
 /**
  * object_property_help:
  * @name: the name of the property
qom/object.c +1 -1
index ff8ede8a32..7e16765cb4 100644
@@ -1904,7 +1904,7 @@ static void object_get_link_property(Object *obj, Visitor *v,
  *
  * Returns: The matched object or NULL on path lookup failures.
  */
-static Object *object_resolve_link(Object *obj, const char *name,
+Object *object_resolve_link(Object *obj, const char *name,
                                    const char *path, Error **errp)
 {
     const char *type;
Signature · 1 line
2.43.0
#26 lore raw

PATCH v2 25/33 system/memory: add setters for MemoryRegion properties

In reply to Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]>

Currently, MemoryRegion properties such as addr, size, priority and container are read-only and don't have setters.

This patch implements the missing setters function, so that properties can be modified dynamically.

The changes allow MemoryRegions objects to be fully configured via properties, which enables them be created from a device tree description.

---
 system/memory.c | 221 ++++++++++++++++++++++++++++++++++++++++++++++--
 1 file changed, 216 insertions(+), 5 deletions(-)
system/memory.c +216 -5
index c51d0798a8..fc1f6cff0c 100644
@@ -55,6 +55,9 @@ static GHashTable *flat_views;
 
 typedef struct AddrRange AddrRange;
 
+static void memory_region_update_container_subregions(MemoryRegion *subregion);
+static void memory_region_readd_subregion(MemoryRegion *mr);
+
 /*
  * Note that signed integers are needed for negative offsetting in aliases
  * (large MemoryRegion::alias_offset).
@@ -1251,6 +1254,73 @@ void memory_region_init(MemoryRegion *mr,
     memory_region_do_init(mr, owner, name, size);
 }
 
+static void memory_region_get_addr(Object *obj, Visitor *v, const char *name,
+                                   void *opaque, Error **errp)
+{
+    MemoryRegion *mr = MEMORY_REGION(obj);
+    uint64_t value = mr->addr;
+
+    visit_type_uint64(v, name, &value, errp);
+}
+
+static void memory_region_set_addr(Object *obj, Visitor *v, const char *name,
+                                   void *opaque, Error **errp)
+{
+    MemoryRegion *mr = MEMORY_REGION(obj);
+    Error *local_err = NULL;
+    uint64_t value;
+
+    visit_type_uint64(v, name, &value, &local_err);
+    if (local_err) {
+        error_propagate(errp, local_err);
+        return;
+    }
+
+    memory_region_set_address(mr, value);
+}
+
+static void memory_region_set_container(Object *obj, Visitor *v,
+                                        const char *name, void *opaque,
+                                        Error **errp)
+{
+    MemoryRegion *mr = MEMORY_REGION(obj);
+    Error *local_err = NULL;
+    MemoryRegion *old_container = mr->container;
+    MemoryRegion *new_container = NULL;
+    char *path = NULL;
+
+    visit_type_str(v, name, &path, &local_err);
+
+    if (!local_err && strcmp(path, "") != 0) {
+        new_container = MEMORY_REGION(object_resolve_link(obj, name, path,
+                                      &local_err));
+        while (new_container->alias) {
+            new_container = new_container->alias;
+        }
+    }
+
+    if (local_err) {
+        error_propagate(errp, local_err);
+        return;
+    }
+
+    object_ref(OBJECT(new_container));
+
+    memory_region_transaction_begin();
+    memory_region_ref(mr);
+    if (old_container) {
+        memory_region_del_subregion(old_container, mr);
+    }
+    mr->container = new_container;
+    if (new_container) {
+        memory_region_update_container_subregions(mr);
+    }
+    memory_region_unref(mr);
+    memory_region_transaction_commit();
+
+    object_unref(OBJECT(old_container));
+}
+
 static void memory_region_get_container(Object *obj, Visitor *v,
                                         const char *name, void *opaque,
                                         Error **errp)
@@ -1275,6 +1345,53 @@ static Object *memory_region_resolve_container(Object *obj, void *opaque,
     return OBJECT(mr->container);
 }
 
+static void memory_region_set_alias(const Object *obj, const char *name,
+                                    Object *val, Error **errp)
+{
+    MemoryRegion *mr = MEMORY_REGION(obj);
+    MemoryRegion *subregion, *next;
+
+    /*
+     * Be conservative and only allow one shotting for the mo
+     * FIXME: Use a softer error than assert
+     */
+    assert(!mr->alias);
+
+    /*
+     * FIXME: check we don't already have subregions and
+     * anything else that might be mutex with aliasing
+     */
+
+    memory_region_transaction_begin();
+    QTAILQ_FOREACH_SAFE(subregion, &mr->subregions, subregions_link, next) {
+        object_property_set_link(OBJECT(subregion), "container",
+                                 OBJECT(val), errp);
+    }
+    memory_region_ref(mr);
+    mr->alias = MEMORY_REGION(val);
+    mr->alias->mapped_via_alias++;
+    memory_region_unref(mr);
+    memory_region_transaction_commit();
+    /* FIXME: add cleanup destructors etc etc */
+}
+
+static void memory_region_set_alias_offset_prop(Object *obj, Visitor *v,
+                                                const char *name,
+                                                void *opaque, Error **errp)
+{
+    MemoryRegion *mr = MEMORY_REGION(obj);
+    Error *local_err = NULL;
+    uint64_t value;
+
+    visit_type_uint64(v, name, &value, &local_err);
+    if (local_err) {
+        error_propagate(errp, local_err);
+        return;
+    }
+
+    memory_region_set_alias_offset(mr, value);
+}
+
 static void memory_region_get_priority(Object *obj, Visitor *v,
                                        const char *name, void *opaque,
                                        Error **errp)
@@ -1285,6 +1402,70 @@ static void memory_region_get_priority(Object *obj, Visitor *v,
     visit_type_int32(v, name, &value, errp);
 }
 
+static void memory_region_set_priority(Object *obj, Visitor *v,
+                                       const char *name, void *opaque,
+                                       Error **errp)
+{
+    MemoryRegion *mr = MEMORY_REGION(obj);
+    Error *local_err = NULL;
+    int32_t value;
+
+    visit_type_uint32(v, name, (uint32_t *)&value, &error_abort);
+    if (local_err) {
+        error_propagate(errp, local_err);
+        return;
+    }
+
+    if (mr->priority != value) {
+        mr->priority = value;
+        memory_region_readd_subregion(mr);
+    }
+}
+
+static void memory_region_do_set_ram(MemoryRegion *mr)
+{
+    if (mr->addr) {
+        qemu_ram_free(mr->ram_block);
+    }
+    if (int128_eq(mr->size, int128_make64(0))) {
+        return;
+    }
+    if (mr->ram) {
+        mr->ram_block = qemu_ram_alloc(int128_get64(mr->size),
+                                       RAM_SHARED, mr, &error_abort);
+    }
+}
+
+static void memory_region_set_ram(Object *obj, Visitor *v, const char *name,
+                                  void *opaque, Error **errp)
+{
+    MemoryRegion *mr = MEMORY_REGION(obj);
+    Error *local_err = NULL;
+    uint8_t value;
+
+    visit_type_uint8(v, name, &value, &error_abort);
+    if (local_err) {
+        error_propagate(errp, local_err);
+        return;
+    }
+
+    mr->dirty_log_mask |= tcg_enabled() ? (1 << DIRTY_MEMORY_CODE) : 0;
+    /* FIXME: Sanitize error handling */
+    /* FIXME: Probably need all that transactions stuff */
+    if (mr->ram == value) {
+        return;
+    }
+
+    mr->ram = value;
+    mr->terminates = !!value; /*FIXME: Wrong */
+
+    if (int128_eq(int128_2_64(), mr->size)) {
+        return;
+    }
+
+    memory_region_do_set_ram(mr);
+}
+
 static void memory_region_get_size(Object *obj, Visitor *v, const char *name,
                                    void *opaque, Error **errp)
 {
@@ -1294,6 +1475,19 @@ static void memory_region_get_size(Object *obj, Visitor *v, const char *name,
     visit_type_uint64(v, name, &value, errp);
 }
 
+static void memory_region_set_object_size(Object *obj, Visitor *v,
+                                          const char *name, void *opaque,
+                                          Error **errp)
+{
+    MemoryRegion *mr = MEMORY_REGION(obj);
+    Error *local_err = NULL;
+    uint64_t size;
+
+    visit_type_uint64(v, name, &size, &local_err);
+
+    memory_region_set_size(mr, size);
+}
+
 static void memory_region_initfn(Object *obj)
 {
     MemoryRegion *mr = MEMORY_REGION(obj);
@@ -1309,19 +1503,33 @@ static void memory_region_initfn(Object *obj)
     op = object_property_add(OBJECT(mr), "container",
                              "link<" TYPE_MEMORY_REGION ">",
                              memory_region_get_container,
-                             NULL, /* memory_region_set_container */
+                             memory_region_set_container,
                              NULL, NULL);
     op->resolve = memory_region_resolve_container;
 
-    object_property_add_uint64_ptr(OBJECT(mr), "addr",
-                                   &mr->addr, OBJ_PROP_FLAG_READ);
+    object_property_add_link(OBJECT(mr), "alias", TYPE_MEMORY_REGION,
+                             (Object **)&mr->alias,
+                             memory_region_set_alias,
+                             0);
+    object_property_add(OBJECT(mr), "alias-offset", "uint64",
+                        NULL,  /* FIXME: Add getter */
+                        memory_region_set_alias_offset_prop,
+                        NULL, NULL);
+    object_property_add(OBJECT(mr), "addr", "uint64",
+                        memory_region_get_addr,
+                        memory_region_set_addr,
+                        NULL, NULL);
     object_property_add(OBJECT(mr), "priority", "uint32",
                         memory_region_get_priority,
-                        NULL, /* memory_region_set_priority */
+                        memory_region_set_priority,
+                        NULL, NULL);
+    object_property_add(OBJECT(mr), "ram", "uint8",
+                        NULL, /* FIXME: Add getter */
+                        memory_region_set_ram,
                         NULL, NULL);
     object_property_add(OBJECT(mr), "size", "uint64",
                         memory_region_get_size,
-                        NULL, /* memory_region_set_size, */
+                        memory_region_set_object_size,
                         NULL, NULL);
 }
 
@@ -2730,6 +2938,9 @@ void memory_region_set_size(MemoryRegion *mr, uint64_t size)
     }
     memory_region_transaction_begin();
     mr->size = s;
+    if (mr->ram) {
+        memory_region_do_set_ram(mr);
+    }
     memory_region_update_pending = true;
     memory_region_transaction_commit();
 }
Signature · 1 line
2.43.0
#27 lore raw

PATCH v2 26/33 system/memory: implement FDT_GENERIC_MMAP interface

In reply to Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]>

The patch implements TYPE_FDT_GENERIC_MMAP interface for the MemoryRegion class.

This enables memory region objects to be automatically constructed by FDT parser based on the 'reg' property in the Device tree. The implementation parses register tuples and set base address, size and priority properties.

Optionally parent container can be set of newly created memory region.

---
 system/memory.c | 58 +++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 58 insertions(+)
system/memory.c +58 -0
index fc1f6cff0c..81e6846c60 100644
@@ -38,6 +38,8 @@
 
 #include "memory-internal.h"
 
+#include "hw/core/fdt_generic_util.h"
+
 //#define DEBUG_UNASSIGNED
 
 static unsigned memory_region_transaction_depth;
@@ -3783,6 +3785,57 @@ static gboolean mtree_info_flatview_free(gpointer key, gpointer value,
     return true;
 }
 
+static bool memory_region_parse_reg(FDTGenericMMap *obj,
+    FDTGenericRegPropInfo reg, Error **errp)
+{
+    MemoryRegion *mr = MEMORY_REGION(obj);
+    uint64_t base_addr = ~0ull;
+    uint64_t total_size = 0;
+    uint64_t max_addr = 0;
+    int i;
+
+    if (!reg.n) {
+        return false;
+    }
+
+    for (i = 0; i < reg.n; ++i) {
+        base_addr = MIN(base_addr, reg.a[i]);
+        max_addr = MAX(max_addr, reg.a[i] + reg.s[i]);
+        total_size += reg.s[i];
+        if (reg.p[i] != reg.p[0]) {
+            error_setg(errp, "FDT generic memory parser does not support"
+                       "mixed priorities");
+            return false;
+        }
+    }
+
+    if (total_size != max_addr - base_addr) {
+        error_setg(errp, "FDT generic memory parse does not "
+        "spport discontiguous or overlapping memory regions");
+        return false;
+    }
+
+    /*
+     * FIXME: parent should not be optional but we need to implement
+     * reg-extended in kernel before we can do things properly
+     */
+    if (reg.parents[0]) {
+        object_property_set_link(OBJECT(mr), "container", reg.parents[0],
+                                 &error_abort);
+    }
+    object_property_set_int(OBJECT(mr), "size", total_size, &error_abort);
+    object_property_set_int(OBJECT(mr), "addr", base_addr, &error_abort);
+    object_property_set_int(OBJECT(mr), "priority", reg.p[0], &error_abort);
+    return false;
+}
+
+static void memory_region_class_init(ObjectClass *oc, const void *data)
+{
+    FDTGenericMMapClass *fmc = FDT_GENERIC_MMAP_CLASS(oc);
+
+    fmc->parse_reg = memory_region_parse_reg;
+}
+
 static void mtree_info_flatview(bool dispatch_tree, bool owner)
 {
     struct FlatViewInfo fvi = {
@@ -4037,6 +4090,11 @@ static const TypeInfo memory_region_info = {
     .instance_size      = sizeof(MemoryRegion),
     .instance_init      = memory_region_initfn,
     .instance_finalize  = memory_region_finalize,
+    .class_init         = memory_region_class_init,
+    .interfaces         = (InterfaceInfo[]) {
+        { TYPE_FDT_GENERIC_MMAP },
+        { },
+    },
 };
 
 static const TypeInfo iommu_memory_region_info = {
Signature · 1 line
2.43.0
#28 lore raw

PATCH v2 27/33 hw/core/fdt_generic_util: initialize serial devices

In reply to Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]>

The patch adds proper handling and registration for serial devices instantiated via FDT.

The devices with 'chardev' properties are connected to serial backends, if corresponding dts property serial id number is set.

---
 hw/core/fdt_generic_util.c | 9 +++++++++
 1 file changed, 9 insertions(+)
hw/core/fdt_generic_util.c +9 -0
index 3179248142..c58a9ccdc7 100644
@@ -36,6 +36,7 @@
 #include "system/system.h"
 #include "system/reset.h"
 #include "qemu/cutils.h"
+#include "chardev/char.h"
 #include "qemu/log.h"
 #include "qemu/config-file.h"
 #include "hw/core/boards.h"
@@ -1216,6 +1217,7 @@ static int fdt_init_qdev(char *node_path, FDTMachineInfo *fdti, char *compat)
     props = qemu_devtree_get_props(fdti->fdt, node_path);
     for (prop = props; prop->name; prop++) {
         const char *propname = trim_vendor(prop->name);
+        int len = prop->len;
         ObjectProperty *p = NULL;
 
         p = object_property_find(OBJECT(dev), propname);
@@ -1235,6 +1237,13 @@ static int fdt_init_qdev(char *node_path, FDTMachineInfo *fdti, char *compat)
             continue;
         }
 
+        /* Special case for chardevs.  */
+        if (!strcmp(propname, "chardev") && !strcmp(p->type, "str")) {
+            qdev_prop_set_chr(DEVICE(dev), "chardev",
+                              serial_hd(get_int_be(prop->value, len)));
+            continue;
+        }
+
         fdt_init_qdev_scalar_prop(OBJECT(dev), p, fdti, node_path, prop);
     }
 
Signature · 1 line
2.43.0
#29 lore raw

PATCH v2 28/33 system/memory: add QOM aliases for fdt support

In reply to Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]>

The patch registers FDT compatibility handlers and QOM aliases of memory subsystem, so that memory regions can be created from a device tree model.

The alias 'qemu:system-memory' could be used to attach subregion to root address space.
The system memory can also be attached to another container with other priority, which may be used for implementing secure memory structures.

Also 'qemu-memory-region' types can be used to create new memory regions.

---
 system/memory.c | 99 +++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 99 insertions(+)
system/memory.c +99 -0
index 81e6846c60..66b5f6a484 100644
@@ -4120,3 +4120,102 @@ static void memory_register_types(void)
 }
 
 type_init(memory_register_types)
+
+static int sysmem_fdt_init(char *node_path, FDTMachineInfo *fdti,
+                           void *priv)
+{
+    int priority = 0;
+    uint32_t container_phandle;
+    MemoryRegion *container;
+    char container_node_path[DT_PATH_LENGTH];
+    Error *errp = NULL;
+
+    fdt_init_set_opaque(fdti, node_path, OBJECT(get_system_memory()));
+
+    /* allow to set system_memory region as subregion */
+    container_phandle = qemu_fdt_getprop_cell(fdti->fdt, node_path,
+                                            "container",
+                                            0, &errp);
+    if (!errp) {
+        /*
+         * TBD: move reg_info work to fdt_generic_util.c
+         */
+        int sc = 0;
+        sc = qemu_fdt_getprop_cell(fdti->fdt, node_path, "#address-cells",
+                                    0, &errp);
+        if (!errp && sc) {
+            error_report("can't change sysmem address");
+            return -1;
+        }
+
+        if (errp) {
+            error_free(errp); errp = NULL;
+        }
+
+        sc = qemu_fdt_getprop_cell(fdti->fdt, node_path,
+                                    "#size-cells", 0, &errp);
+        if (!errp && sc) {
+            error_report("can't change sysmem size");
+            return -1;
+        }
+
+        error_free(errp); errp = NULL;
+        /* Check for custom "#priority-cells" extension */
+        sc = qemu_fdt_getprop_cell(fdti->fdt, node_path,
+                                    "#priority-cells", 0, &errp);
+        if (errp) {
+            /* priotity is optional */
+            priority = 0;
+            error_free(errp); errp = NULL;
+        } else if (sc) {
+            priority = qemu_fdt_getprop_cell(fdti->fdt, node_path,
+                                    "reg", 0, &errp);
+            if (errp) {
+                error_report("failed to read priority from reg");
+                error_free(errp);
+                return -1;
+            }
+        }
+
+        if (qemu_devtree_get_node_by_phandle(fdti->fdt, container_node_path,
+                                             container_phandle)) {
+            error_report("failed to get contaier node");
+            return -1;
+        }
+
+        while (!fdt_init_has_opaque(fdti, container_node_path)) {
+            fdt_init_yield(fdti);
+        }
+
+        container = MEMORY_REGION(fdt_init_get_opaque(fdti,
+                                                      container_node_path));
+
+        memory_region_add_subregion_overlap(container, 0,
+                                            get_system_memory(), priority);
+    } else {
+        /* container is optional property */
+        error_free(errp);
+        errp = NULL;
+    }
+
+    return 0;
+}
+
+
+fdt_register_compatibility(sysmem_fdt_init, "compatible:qemu:system-memory");
+
+static const TypeInfo fdt_qom_aliases[] = {
+    {   .name = "qemu-memory-region",       .parent = "memory-region"  },
+    {   .name = "simple-bus",               .parent = "memory-region"  },
+};
+
+static void fdt_memory_types(void)
+{
+    int i;
+
+    for (i = 0; i < ARRAY_SIZE(fdt_qom_aliases); ++i) {
+        type_register_static(&fdt_qom_aliases[i]);
+    }
+}
+
+type_init(fdt_memory_types)
Signature · 1 line
2.43.0
#30 lore raw

PATCH v2 29/33 hw/intc/arm_gicv3: Implement FDTGenericIntc interface

In reply to Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]>

This patch implements the FDTGenericIntc interface for the ARM GICv3 interrupt controller.

This enables the generic FDT machine infrastructure to automatically wire up the GIC and resolve interrupts defined in the Device Tree.

---
 hw/intc/arm_gicv3.c        | 45 +++++++++++++++++++++++++
 hw/intc/arm_gicv3_common.c | 68 ++++++++++++++++++++++++++++++++++++++
 2 files changed, 113 insertions(+)
hw/intc/arm_gicv3.c +45 -0
index 542f81ea49..e7e98ef9a5 100644
@@ -18,9 +18,13 @@
 #include "qemu/osdep.h"
 #include "qapi/error.h"
 #include "qemu/module.h"
+#include "hw/core/cpu.h"
+#include "hw/core/boards.h"
 #include "hw/intc/arm_gicv3.h"
 #include "gicv3_internal.h"
 
+#include "hw/core/fdt_generic_util.h"
+
 static bool irqbetter(GICv3CPUState *cs, int irq, uint8_t prio, bool nmi)
 {
     /* Return true if this IRQ at this priority should take
@@ -452,14 +456,55 @@ static void arm_gic_realize(DeviceState *dev, Error **errp)
     gicv3_init_cpuif(s);
 }
 
+static void arm_gic_fdt_auto_parent(FDTGenericIntc *obj, Error **errp)
+{
+    GICv3State *s = ARM_GICV3(obj);
+    SysBusDevice *sbd = SYS_BUS_DEVICE(obj);
+    int num_cpus = s->num_cpu;
+    CPUState *cs;
+    int i = 0;
+
+    for (cs = first_cpu; cs; cs = CPU_NEXT(cs)) {
+        if (i >= s->num_cpu) {
+            break;
+        }
+
+        sysbus_connect_irq(sbd, i,
+                           qdev_get_gpio_in(DEVICE(cs), 0));
+        sysbus_connect_irq(sbd, i + num_cpus,
+                           qdev_get_gpio_in(DEVICE(cs), 1));
+        sysbus_connect_irq(sbd, i + 2 * num_cpus,
+                           qdev_get_gpio_in(DEVICE(cs), 2));
+        sysbus_connect_irq(sbd, i + 3 * num_cpus,
+                           qdev_get_gpio_in(DEVICE(cs), 3));
+        sysbus_connect_irq(sbd, i + 4 * num_cpus,
+                           qdev_get_gpio_in(DEVICE(cs), 4));
+        sysbus_connect_irq(sbd, i + 5 * num_cpus,
+                           qdev_get_gpio_in(DEVICE(cs), 5));
+
+        if (s->maint_irq) {
+            int intbase = s->num_irq - GIC_INTERNAL + i * GIC_INTERNAL;
+            qemu_irq irq = qdev_get_gpio_in(DEVICE(sbd),
+                                intbase + s->maint_irq);
+            qdev_connect_gpio_out_named(DEVICE(cs),
+                                               "gicv3-maintenance-interrupt",
+                                                0, irq);
+        }
+
+        i++;
+    }
+}
+
 static void arm_gicv3_class_init(ObjectClass *klass, const void *data)
 {
     DeviceClass *dc = DEVICE_CLASS(klass);
     ARMGICv3CommonClass *agcc = ARM_GICV3_COMMON_CLASS(klass);
     ARMGICv3Class *agc = ARM_GICV3_CLASS(klass);
+    FDTGenericIntcClass *fgic = FDT_GENERIC_INTC_CLASS(klass);
 
     agcc->post_load = arm_gicv3_post_load;
     device_class_set_parent_realize(dc, arm_gic_realize, &agc->parent_realize);
+    fgic->auto_parent = arm_gic_fdt_auto_parent;
 }
 
 static const TypeInfo arm_gicv3_info = {
hw/intc/arm_gicv3_common.c +68 -0

98 lines not on this page · raw message

Signature · 1 line
2.43.0
#31 lore raw

PATCH v2 30/33 hw/core/fdt_generic_util: Add deferred device initialization support

In reply to Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]>

Add a mechanism to defer device initialization
until after the main FDT traversal.

This introduces a deferred queue in FDTMachineInfo. Devices in this queue are processed in fdt_init_deferred(), which handles their realization, reset registration, and resource parsing (interrupts and memory regions).

This allows resolving initialization where devices need to be realized on latest stages or outside of co-routine context.

---
 hw/core/fdt_generic_util.c    | 45 +++++++++++++++++++++++++++++++++++
 include/hw/core/fdt_generic.h |  8 +++++++
 2 files changed, 53 insertions(+)
hw/core/fdt_generic_util.c +45 -0
index c58a9ccdc7..4ed9602d47 100644
@@ -99,6 +99,11 @@ static bool qemu_irq_shared_or_handler(bool *inputs, int n)
     return false;
 }
 
+static void fdt_parse_node_reg_prop(FDTMachineInfo *fdti, char *node_path,
+                             Object *dev);
+static void fdt_parse_node_irq_prop(FDTMachineInfo *fdti, char *node_path,
+                             Object *dev);
+
 static void qemu_irq_shared_handler(void *opaque, int n, int level)
 {
     QEMUIRQSharedState *s = opaque;
@@ -168,6 +173,45 @@ static void fdt_init_cpu_clusters(FDTMachineInfo *fdti)
     }
 }
 
+static void fdt_init_deferred(FDTMachineInfo *fdti)
+{
+    while (fdti->deferred) {
+        FDTDeferredNode *dnode = fdti->deferred;
+        DeviceClass *dc = DEVICE_GET_CLASS(dnode->dev);
+        int length = 0;
+
+        int offset = fdt_path_offset(fdti->fdt, dnode->node_path);
+        if (offset < 0) {
+            error_report("%s Couldn't find node %s: %s", __func__,
+                         dnode->node_path, fdt_strerror(offset));
+        }
+        const char *blockdev = fdt_stringlist_get(fdti->fdt, offset,
+                                              "blockdev-node-name", 0, &length);
+
+        DB_PRINT(0, "FDT: Deferred realize node: %s\n",
+                 dnode->node_path);
+
+        if (blockdev && object_property_find(OBJECT(dnode->dev), "drive")) {
+            fdt_attach_blockdev(fdti, dnode->node_path, OBJECT(dnode->dev));
+        }
+
+        object_property_set_bool(OBJECT(dnode->dev), "realized", true,
+                                &error_fatal);
+        if (dc->legacy_reset) {
+            qemu_register_reset((void (*)(void *))dc->legacy_reset,
+                                dnode->dev);
+        }
+
+        fdt_parse_node_reg_prop(fdti, dnode->node_path, OBJECT(dnode->dev));
+
+        fdt_parse_node_irq_prop(fdti, dnode->node_path, OBJECT(dnode->dev));
+
+        fdti->deferred = dnode->next;
+        g_free(dnode->node_path);
+        g_free(dnode);
+    }
+}
+
 FDTMachineInfo *fdt_generic_create_machine(void *fdt, qemu_irq *cpu_irq)
 {
     char node_path[DT_PATH_LENGTH];
@@ -183,6 +227,7 @@ FDTMachineInfo *fdt_generic_create_machine(void *fdt, qemu_irq *cpu_irq)
         while (qemu_co_enter_next(fdti->cq, NULL)) {
             ;
         }
+        fdt_init_deferred(fdti);
         fdt_init_cpu_clusters(fdti);
         fdt_init_all_irqs(fdti);
         memory_region_transaction_commit();
include/hw/core/fdt_generic.h +8 -0
index ad9e249156..dc2d7a8876 100644
@@ -34,6 +34,12 @@ typedef struct FDTIRQConnection {
     void *next;
 } FDTIRQConnection;
 
+typedef struct FDTDeferredNode {
+    DeviceState *dev;
+    char *node_path;
+    void *next;
+} FDTDeferredNode;
+
 typedef struct FDTMachineInfo {
     /* the fdt blob */
     void *fdt;
@@ -47,6 +53,8 @@ typedef struct FDTMachineInfo {
     FDTIRQConnection *irqs;
     /* list of all CPU clusters */
     FDTCPUCluster *clusters;
+    /* list of devices for deferred init */
+    FDTDeferredNode *deferred;
 } FDTMachineInfo;
 
 /*
Signature · 1 line
2.43.0
#32 lore raw

PATCH v2 31/33 hw/core/fdt_generic_util: Add blockdev binding support

In reply to Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]>

The path add possibility to bind to QEMU block backends via the blockdev-node-name property.

This enables support for the modern -blockdev command line option.

---
 hw/core/fdt_generic_util.c | 82 ++++++++++++++++++++++++++++++++++----
 1 file changed, 75 insertions(+), 7 deletions(-)
hw/core/fdt_generic_util.c +75 -7
index 4ed9602d47..68dfeee096 100644
@@ -75,6 +75,8 @@ static void fdt_get_irq_info_from_intc(FDTMachineInfo *fdti, qemu_irq *ret,
                                        char *intc_node_path,
                                        uint32_t *cells, uint32_t num_cells,
                                        uint32_t max, Error **errp);
+static bool fdt_attach_blockdev(FDTMachineInfo *fdti,
+                                const char *node_path, Object *dev);
 
 typedef struct QEMUIRQSharedState {
     qemu_irq sink;
@@ -241,6 +243,8 @@ FDTMachineInfo *fdt_generic_create_machine(void *fdt, qemu_irq *cpu_irq)
     current_machine->smp.cpus = fdt_generic_num_cpus;
     current_machine->smp.max_cpus = fdt_generic_num_cpus;
 
+    bdrv_drain_all();
+
     DB_PRINT(0, "FDT: Device tree scan complete\n");
     return fdti;
 }
@@ -987,6 +991,52 @@ static void fdt_init_qdev_array_prop(Object *obj,
     DB_PRINT_NP(0, "set property %s propname to <list>\n", propname);
 }
 
+/*
+ * Try to attach by matching drive created by '-blockdev node-name=LABEL'
+ * iff the FDT node contains property 'blockdev-node-name=LABEL'.
+ *
+ * Return false unless the given node_path has the property.
+ *
+ * Presence of the property also disables the node from ever attached
+ * to any drive created by the legacy '-drive' QEMU option.
+ *
+ * For more on '-blockdev', see:
+ *   http://events17.linuxfoundation.org/sites/events/files/slides/talk_11.pdf
+ */
+static bool fdt_attach_blockdev(FDTMachineInfo *fdti,
+                                const char *node_path, Object *dev)
+{
+    static const char propname[] = "blockdev-node-name";
+    const char *label;
+
+    /* Inspect FDT node for blockdev-only binding */
+    label = qemu_fdt_getprop(fdti->fdt, node_path, propname,
+                             NULL, NULL);
+
+    /* Skip legacy node */
+    if (!label) {
+        return false;
+    }
+
+    /*
+     * Missing matching bdev is not an error: attachment is optional.
+     *
+     * error_setg() aborts, never returns: 'goto ret' is just sanity.
+     */
+    if (!label[0]) {
+        error_setg(&error_abort, "FDT-node '%s': property '%s' = <empty>",
+                   node_path, propname);
+        return false;
+    }
+
+    if (!bdrv_find_node(label)) {
+        return false;
+    }
+
+    object_property_set_str(OBJECT(dev), "drive", label, NULL);
+    return true;
+}
+
 static void fdt_parse_node_reg_prop(FDTMachineInfo *fdti, char *node_path,
                             Object *dev)
 {
@@ -1173,6 +1223,7 @@ static int fdt_init_qdev(char *node_path, FDTMachineInfo *fdti, char *compat)
     char *dev_type = NULL;
     QEMUDevtreeProp *prop, *props;
     char parent_node_path[DT_PATH_LENGTH];
+    bool defer_realize = false;
 
     if (!compat) {
         return 1;
@@ -1289,6 +1340,11 @@ static int fdt_init_qdev(char *node_path, FDTMachineInfo *fdti, char *compat)
             continue;
         }
 
+        if (!strcmp(propname, "drive")) {
+            defer_realize = true;
+            continue;
+        }
+
         fdt_init_qdev_scalar_prop(OBJECT(dev), p, fdti, node_path, prop);
     }
 
@@ -1307,18 +1363,30 @@ static int fdt_init_qdev(char *node_path, FDTMachineInfo *fdti, char *compat)
              */
             fdt_init_register_user_cpu_cluster(fdti, OBJECT(dev));
         } else {
-            object_property_set_bool(OBJECT(dev), "realized", true,
-                                     &error_fatal);
-            if (dc->legacy_reset) {
-                qemu_register_reset((void (*)(void *))dc->legacy_reset,
-                                    dev);
+            if (defer_realize) {
+                FDTDeferredNode *dnode = g_new0(FDTDeferredNode, 1);
+                *dnode = (FDTDeferredNode) {
+                        .dev = DEVICE(dev),
+                        .node_path = g_strdup(node_path),
+                        .next = fdti->deferred
+                };
+                fdti->deferred = dnode;
+            } else {
+                object_property_set_bool(OBJECT(dev), "realized", true,
+                                        &error_fatal);
+                if (dc->legacy_reset) {
+                    qemu_register_reset((void (*)(void *))dc->legacy_reset,
+                                        dev);
+                }
             }
         }
     }
 
-    fdt_parse_node_reg_prop(fdti, node_path, dev);
+    if (!defer_realize) {
+        fdt_parse_node_reg_prop(fdti, node_path, dev);
 
-    fdt_parse_node_irq_prop(fdti, node_path, dev);
+        fdt_parse_node_irq_prop(fdti, node_path, dev);
+    }
 
     g_free(dev_type);
     g_free(props);
Signature · 1 line
2.43.0
#33 lore raw

PATCH v2 32/33 hw/pci-host: add gsi-irqs property array

In reply to Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]>

Add a new gsi-irqs array property to the GPEX PCI host controller. This enables them to be configured on realize callback.

This is required to init GPEX PCI host from a static configuration, such as Hardware device tree.

---
 hw/pci-host/gpex.c         | 6 ++++++
 include/hw/pci-host/gpex.h | 3 +++
 2 files changed, 9 insertions(+)
hw/pci-host/gpex.c +6 -0
index e66784ce51..6125b2c319 100644
@@ -148,6 +148,10 @@ static void gpex_host_realize(DeviceState *dev, Error **errp)
         s->irq[i].irq_num = -1;
     }
 
+    for (i = 0; i < s->gsi_irq_num; i++) {
+        gpex_set_irq_num(s, i, s->gsi_irqs[i]);
+    }
+
     pci->bus = pci_register_root_bus(dev, "pcie.0", gpex_set_irq,
                                      gpex_swizzle_map_irq_fn,
                                      s, &s->io_mmio, &s->io_ioport, 0,
@@ -190,6 +194,8 @@ static const Property gpex_host_properties[] = {
     DEFINE_PROP_SIZE(PCI_HOST_ABOVE_4G_MMIO_SIZE, GPEXHost,
                      gpex_cfg.mmio64.size, 0),
     DEFINE_PROP_UINT8("num-irqs", GPEXHost, num_irqs, PCI_NUM_PINS),
+    DEFINE_PROP_ARRAY("gsi-irqs", GPEXHost, gsi_irq_num,
+                      gsi_irqs, qdev_prop_uint32, uint32_t),
 };
 
 static void gpex_host_class_init(ObjectClass *klass, const void *data)
include/hw/pci-host/gpex.h +3 -0
index 1da9c85bce..f8e9874756 100644
@@ -64,6 +64,9 @@ struct GPEXHost {
     GPEXIrq *irq;
     uint8_t num_irqs;
 
+    uint32_t *gsi_irqs;
+    uint32_t gsi_irq_num;
+
     bool allow_unmapped_accesses;
 
     struct GPEXConfig gpex_cfg;
Signature · 1 line
2.43.0
#34 lore raw

PATCH v2 33/33 tests/functional: Add functional tests for arm-generic-fdt machine

In reply to Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]>

This patch adds functional tests for the new arm-generic-fdt machine type. It introduces two new test suites:

1. test_arm_generic_fdt.py: Validates the firmware boot chain (TF-A and EDK2). It checks the console output for specific patterns indicating successful execution of BL1, BL2, BL31, and UEFI stages.

2. test_arm_generic_fdt_alpine.py: Validates a full OS boot by launching an Alpine Linux ISO and waiting for the welcome message.

To support these tests, two pre-compiled Device Tree Blob (DTB) files are added to tests/data.

The tests reuse the existing firmware assets and Alpine ISO infrastructure from the sbsa-ref tests.

---
 .../arm-generic-fdt/arm64-sbsa-guest.dtb      | Bin 0 -> 673 bytes
 .../aarch64/arm-generic-fdt/arm64-sbsa-hw.dtb | Bin 0 -> 5414 bytes
 tests/functional/aarch64/meson.build          |   2 +
 .../aarch64/test_arm_generic_fdt.py           | 114 ++++++++++++++++++
 .../aarch64/test_arm_generic_fdt_alpine.py    |  61 ++++++++++
 5 files changed, 177 insertions(+)
 create mode 100644 tests/data/dtb/aarch64/arm-generic-fdt/arm64-sbsa-guest.dtb
 create mode 100644 tests/data/dtb/aarch64/arm-generic-fdt/arm64-sbsa-hw.dtb
 create mode 100755 tests/functional/aarch64/test_arm_generic_fdt.py
 create mode 100755 tests/functional/aarch64/test_arm_generic_fdt_alpine.py
tests/data/dtb/aarch64/arm-generic-fdt/arm64-sbsa-guest.dtb new file binary +0 -0
new file mode 100644
index 0000000000000000000000000000000000000000..5f2a1e9b2826eec45ed97e6dd704649a05d0af4c
GIT binary patch
tests/data/dtb/aarch64/arm-generic-fdt/arm64-sbsa-hw.dtb new file binary +0 -0
new file mode 100644
index 0000000000000000000000000000000000000000..0f12655f9c4b4f12556dd0c55c3bc552ff3f8a5e
GIT binary patch
tests/functional/aarch64/meson.build +2 -0
index 49eca12058..3ec20f5bb2 100644
@@ -41,6 +41,8 @@ tests_aarch64_system_thorough = [
   'sbsaref',
   'sbsaref_alpine',
   'sbsaref_freebsd',
+  'arm_generic_fdt',
+  'arm_generic_fdt_alpine',
   'smmu',
   'tcg_plugins',
   'tuxrun',
tests/functional/aarch64/test_arm_generic_fdt.py new file +114 -0

114 lines not on this page · raw message

tests/functional/aarch64/test_arm_generic_fdt_alpine.py new file +61 -0

61 lines not on this page · raw message

Signature · 1 line
2.43.0
#35 lore raw

Re: [PATCH v2 19/33] hw/core/machine: add '-hw-dtb' option for machine

In reply to Ruslan Ruslichenko

Hi!

Quoted 42 lines · Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]>

Add new '-hw-dtb' command-line option and corresponding MachineState property.
The 'hw-dtb' option allows to specify a Device tree binary with hardware description which Qemu should emulate.

---
  hw/core/machine.c        | 19 +++++++++++++++++++
  include/hw/core/boards.h |  1 +
  qemu-options.hx          |  9 +++++++++
  system/vl.c              |  3 +++
  4 files changed, 32 insertions(+)
hw/core/machine.c +14 -0
index d4ef620c17..affd24cd49 100644
@@ -363,6 +363,20 @@ static void machine_set_dtb(Object *obj, const char *value, Error **errp)
      ms->dtb = g_strdup(value);
  }
 
+static char *machine_get_hw_dtb(Object *obj, Error **errp)
+{
+    MachineState *ms = MACHINE(obj);
+
+    return g_strdup(ms->hw_dtb);
+}
+
+static void machine_set_hw_dtb(Object *obj, const char *value, Error **errp)
+{
+    MachineState *ms = MACHINE(obj);
+
+    ms->hw_dtb = g_strdup(value);
+}
+
  static char *machine_get_dumpdtb(Object *obj, Error **errp)
  {
      MachineState *ms = MACHINE(obj);

hw/core/machine.c static void machine_class_init(ObjectClass *oc, const void *data) · line 1165

Quoted 7 lines
hw/core/machine.c +4 -0
@@ -1145,6 +1159,11 @@ static void machine_class_init(ObjectClass *oc, const void *data)
      object_class_property_set_description(oc, "dtb",
          "Linux kernel device tree file");
 
+    object_class_property_add_str(oc, "hw-dtb",
+                            machine_get_hw_dtb, machine_set_hw_dtb);
+    object_class_property_set_description(oc, "hw-dtb",
+                "A device tree binary used to describe the hardware to QEMU");

Do the hardware dtbs differ from the ones that are passed to the Linux kernel? If not, I think you likely could use the existing "dtb" property for your new feature?

...

Quoted 6 lines
qemu-options.hx +0 -0
index 33fcfe7ce6..1568f3ce4c 100644
@@ -4518,6 +4518,15 @@ SRST(initrd)
 

qemu-options.hx SRST(initrd) · line 4528

Quoted 10 lines
qemu-options.hx +8 -0
  ERST
 
+DEF("hw-dtb", HAS_ARG, QEMU_OPTION_hw_dtb, \
+    "-hw-dtb file    use 'file' as device tree image\n", QEMU_ARCH_ALL)
+SRST
+``-hw-dtb file``
+    Use <file> as a device tree binary (dtb) image used to create the
+    emulated machine. This dtb will not be passed to the kernel, use -dtb
+    for that.
+ERST

Please don't add any new top level options if it is not really necessary. We already got too much duplicated logic in QEMU, so we try to avoid this nowadays. In your case here, it should be fine to simply configure the hw-dtb via the -machine property.

Thanks,
Thomas

#36 lore raw

Re: [PATCH v2 19/33] hw/core/machine: add '-hw-dtb' option for machine

Quoted 43 lines · Thomas Huth

Hi!

Quoted 40 lines · Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]> Add new '-hw-dtb' command-line option and corresponding MachineState property.
The 'hw-dtb' option allows to specify a Device tree binary with hardware description which Qemu should emulate.

---
  hw/core/machine.c        | 19 +++++++++++++++++++
  include/hw/core/boards.h |  1 +
  qemu-options.hx          |  9 +++++++++
  system/vl.c              |  3 +++
  4 files changed, 32 insertions(+)
hw/core/machine.c +13 -0
index d4ef620c17..affd24cd49 100644
@@ -363,6 +363,20 @@ static void machine_set_dtb(Object *obj, const char *value, Error **errp)
      ms->dtb = g_strdup(value);
  }
  +static char *machine_get_hw_dtb(Object *obj, Error **errp)
+{
+    MachineState *ms = MACHINE(obj);
+
+    return g_strdup(ms->hw_dtb);
+}
+
+static void machine_set_hw_dtb(Object *obj, const char *value, Error **errp)
+{
+    MachineState *ms = MACHINE(obj);
+
+    ms->hw_dtb = g_strdup(value);
+}
+
  static char *machine_get_dumpdtb(Object *obj, Error **errp)
  {
      MachineState *ms = MACHINE(obj);
@@ -1145,6 +1159,11 @@ static void machine_class_init(ObjectClass *oc, const void *data)
      object_class_property_set_description(oc, "dtb",
          "Linux kernel device tree file");
Quoted 8 lines

hw/core/machine.c static void machine_class_init(ObjectClass *oc, const void *data) · line 1165

Quoted 4 lines
hw/core/machine.c +3 -0
  +    object_class_property_add_str(oc, "hw-dtb",
+                            machine_get_hw_dtb, machine_set_hw_dtb);
+    object_class_property_set_description(oc, "hw-dtb",
+                "A device tree binary used to describe the hardware to QEMU");

Do the hardware dtbs differ from the ones that are passed to the Linux kernel? If not, I think you likely could use the existing "dtb" property for your new feature?

They have to - the normal DTB cannot define the whole system because its only concerned with reporting what the kernel can see to the kernel and not defining the whole system including what the firmware sees.

Quoted 24 lines

...

Quoted 5 lines
qemu-options.hx +0 -0
index 33fcfe7ce6..1568f3ce4c 100644

qemu-options.hx SRST(initrd) · line 4526

Quoted 9 lines
qemu-options.hx +7 -0
@@ -4518,6 +4518,15 @@ SRST(initrd)
    ERST
  +DEF("hw-dtb", HAS_ARG, QEMU_OPTION_hw_dtb, \
+    "-hw-dtb file    use 'file' as device tree image\n", QEMU_ARCH_ALL)
+SRST
+``-hw-dtb file``
+    Use <file> as a device tree binary (dtb) image used to create the
+    emulated machine. This dtb will not be passed to the kernel, use -dtb
+    for that.
+ERST

Please don't add any new top level options if it is not really necessary. We already got too much duplicated logic in QEMU, so we try to avoid this nowadays. In your case here, it should be fine to simply configure the hw-dtb via the -machine property.

Thanks,
Thomas

Signature · 2 lines
Alex Bennée
Virtualisation Tech Lead @ Linaro
#37 lore raw

Re: [PATCH v2 19/33] hw/core/machine: add '-hw-dtb' option for machine

Quoted 55 lines · Alex Bennée
Quoted 43 lines · Thomas Huth

Hi!

Quoted 40 lines · Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]> Add new '-hw-dtb' command-line option and corresponding MachineState property.
The 'hw-dtb' option allows to specify a Device tree binary with hardware description which Qemu should emulate.

---
  hw/core/machine.c        | 19 +++++++++++++++++++
  include/hw/core/boards.h |  1 +
  qemu-options.hx          |  9 +++++++++
  system/vl.c              |  3 +++
  4 files changed, 32 insertions(+)
hw/core/machine.c +13 -0
index d4ef620c17..affd24cd49 100644
@@ -363,6 +363,20 @@ static void machine_set_dtb(Object *obj, const char *value, Error **errp)
      ms->dtb = g_strdup(value);
  }
  +static char *machine_get_hw_dtb(Object *obj, Error **errp)
+{
+    MachineState *ms = MACHINE(obj);
+
+    return g_strdup(ms->hw_dtb);
+}
+
+static void machine_set_hw_dtb(Object *obj, const char *value, Error **errp)
+{
+    MachineState *ms = MACHINE(obj);
+
+    ms->hw_dtb = g_strdup(value);
+}
+
  static char *machine_get_dumpdtb(Object *obj, Error **errp)
  {
      MachineState *ms = MACHINE(obj);
@@ -1145,6 +1159,11 @@ static void machine_class_init(ObjectClass *oc, const void *data)
      object_class_property_set_description(oc, "dtb",
          "Linux kernel device tree file");
Quoted 8 lines

hw/core/machine.c static void machine_class_init(ObjectClass *oc, const void *data) · line 1165

Quoted 4 lines
hw/core/machine.c +3 -0
  +    object_class_property_add_str(oc, "hw-dtb",
+                            machine_get_hw_dtb, machine_set_hw_dtb);
+    object_class_property_set_description(oc, "hw-dtb",
+                "A device tree binary used to describe the hardware to QEMU");

Do the hardware dtbs differ from the ones that are passed to the Linux kernel? If not, I think you likely could use the existing "dtb" property for your new feature?

Quoted 4 lines

They have to - the normal DTB cannot define the whole system because its only concerned with reporting what the kernel can see to the kernel and not defining the whole system including what the firmware sees.

Yes, Indeed.
Normal DTB was explored, but there is not enough information to create QEMU models from it.
Thus we need to have a separate device tree.

Quoted 13 lines
Quoted 13 lines

...

Quoted 11 lines
qemu-options.hx +4 -0
index 33fcfe7ce6..1568f3ce4c 100644
@@ -4518,6 +4518,15 @@ SRST(initrd)
    ERST
  +DEF("hw-dtb", HAS_ARG, QEMU_OPTION_hw_dtb, \
+    "-hw-dtb file    use 'file' as device tree image\n", QEMU_ARCH_ALL)
+SRST
+``-hw-dtb file``
+    Use <file> as a device tree binary (dtb) image used to create the
Quoted 8 lines
Quoted 8 lines

qemu-options.hx SRST(initrd) · line 4528

Quoted 3 lines
qemu-options.hx +3 -0
+    emulated machine. This dtb will not be passed to the kernel, use -dtb
+    for that.
+ERST

Please don't add any new top level options if it is not really necessary. We already got too much duplicated logic in QEMU, so we try to avoid this nowadays. In your case here, it should be fine to simply configure the hw-dtb via the -machine property.

Agreed. As for now there is only one user of this hw option, we can move to the arm-generic-fdt machine option itself. I'll move this for the next version.

Quoted 7 lines
Quoted 3 lines

Thanks,
Thomas

--
Alex Bennée
Virtualisation Tech Lead @ Linaro

--
BR,
Ruslan Ruslichenko

#38 lore raw

Re: [PATCH v2 19/33] hw/core/machine: add '-hw-dtb' option for machine

Quoted 61 lines · Ruslan Ruslichenko
Quoted 55 lines · Alex Bennée
Quoted 43 lines · Thomas Huth

Hi!

Quoted 40 lines · Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]> Add new '-hw-dtb' command-line option and corresponding MachineState property.
The 'hw-dtb' option allows to specify a Device tree binary with hardware description which Qemu should emulate.

---
  hw/core/machine.c        | 19 +++++++++++++++++++
  include/hw/core/boards.h |  1 +
  qemu-options.hx          |  9 +++++++++
  system/vl.c              |  3 +++
  4 files changed, 32 insertions(+)
hw/core/machine.c +13 -0
index d4ef620c17..affd24cd49 100644
@@ -363,6 +363,20 @@ static void machine_set_dtb(Object *obj, const char *value, Error **errp)
      ms->dtb = g_strdup(value);
  }
  +static char *machine_get_hw_dtb(Object *obj, Error **errp)
+{
+    MachineState *ms = MACHINE(obj);
+
+    return g_strdup(ms->hw_dtb);
+}
+
+static void machine_set_hw_dtb(Object *obj, const char *value, Error **errp)
+{
+    MachineState *ms = MACHINE(obj);
+
+    ms->hw_dtb = g_strdup(value);
+}
+
  static char *machine_get_dumpdtb(Object *obj, Error **errp)
  {
      MachineState *ms = MACHINE(obj);
@@ -1145,6 +1159,11 @@ static void machine_class_init(ObjectClass *oc, const void *data)
      object_class_property_set_description(oc, "dtb",
          "Linux kernel device tree file");
Quoted 8 lines

hw/core/machine.c static void machine_class_init(ObjectClass *oc, const void *data) · line 1165

Quoted 4 lines
hw/core/machine.c +3 -0
  +    object_class_property_add_str(oc, "hw-dtb",
+                            machine_get_hw_dtb, machine_set_hw_dtb);
+    object_class_property_set_description(oc, "hw-dtb",
+                "A device tree binary used to describe the hardware to QEMU");

Do the hardware dtbs differ from the ones that are passed to the Linux kernel? If not, I think you likely could use the existing "dtb" property for your new feature?

Quoted 4 lines

They have to - the normal DTB cannot define the whole system because its only concerned with reporting what the kernel can see to the kernel and not defining the whole system including what the firmware sees.

Quoted 4 lines

Yes, Indeed.
Normal DTB was explored, but there is not enough information to create QEMU models from it.
Thus we need to have a separate device tree.

What additional data is needed that's not present in dtb from firmware and what if that additional data is passed to the kernel? I think the kernel would just ignore the additional data that it doesn't need so one dtb might be enough even if it has to be more detailed than what the kernel normally gets. If that works we don't need a separate option.

This series seems to be more complex than Bernhard's e500-fdt experiment (I've linked to that in <https://lists.nongnu.org/archive/html/qemu-devel/2026-01/msg05470.html>) Bernhard's patch only added minimal support for creating devices from fdt and then put additional logic in the devices instead of handling them in generic code. Would such an approach lead to simpler fdt handling? If not why is the additional complexity needed?

Regards,
BALATON Zoltan

#39 lore raw

Re: [PATCH v2 19/33] hw/core/machine: add '-hw-dtb' option for machine

Quoted 68 lines · BALATON Zoltan
Quoted 61 lines · Ruslan Ruslichenko
Quoted 55 lines · Alex Bennée
Quoted 43 lines · Thomas Huth

Hi!

Quoted 40 lines · Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]> Add new '-hw-dtb' command-line option and corresponding MachineState property.
The 'hw-dtb' option allows to specify a Device tree binary with hardware description which Qemu should emulate.

---
  hw/core/machine.c        | 19 +++++++++++++++++++
  include/hw/core/boards.h |  1 +
  qemu-options.hx          |  9 +++++++++
  system/vl.c              |  3 +++
  4 files changed, 32 insertions(+)
hw/core/machine.c +13 -0
index d4ef620c17..affd24cd49 100644
@@ -363,6 +363,20 @@ static void machine_set_dtb(Object *obj, const char *value, Error **errp)
      ms->dtb = g_strdup(value);
  }
  +static char *machine_get_hw_dtb(Object *obj, Error **errp)
+{
+    MachineState *ms = MACHINE(obj);
+
+    return g_strdup(ms->hw_dtb);
+}
+
+static void machine_set_hw_dtb(Object *obj, const char *value, Error **errp)
+{
+    MachineState *ms = MACHINE(obj);
+
+    ms->hw_dtb = g_strdup(value);
+}
+
  static char *machine_get_dumpdtb(Object *obj, Error **errp)
  {
      MachineState *ms = MACHINE(obj);
@@ -1145,6 +1159,11 @@ static void machine_class_init(ObjectClass *oc, const void *data)
      object_class_property_set_description(oc, "dtb",
          "Linux kernel device tree file");
Quoted 8 lines

hw/core/machine.c static void machine_class_init(ObjectClass *oc, const void *data) · line 1165

Quoted 4 lines
hw/core/machine.c +3 -0
  +    object_class_property_add_str(oc, "hw-dtb",
+                            machine_get_hw_dtb, machine_set_hw_dtb);
+    object_class_property_set_description(oc, "hw-dtb",
+                "A device tree binary used to describe the hardware to QEMU");

Do the hardware dtbs differ from the ones that are passed to the Linux kernel? If not, I think you likely could use the existing "dtb" property for your new feature?

Quoted 4 lines

They have to - the normal DTB cannot define the whole system because its only concerned with reporting what the kernel can see to the kernel and not defining the whole system including what the firmware sees.

Quoted 4 lines

Yes, Indeed.
Normal DTB was explored, but there is not enough information to create QEMU models from it.
Thus we need to have a separate device tree.

Quoted 6 lines

What additional data is needed that's not present in dtb from firmware and what if that additional data is passed to the kernel? I think the kernel would just ignore the additional data that it doesn't need so one dtb might be enough even if it has to be more detailed than what the kernel normally gets. If that works we don't need a separate option.

Here are few specific examples:

1. DTS compatibles and QOM type names are all different.
Using Linux device tree would require to maintain some massive hardcoded mapping even for devices that otherwise don't require any special handling.

2. Object properties. We would probably need to make sure there is no conflicts and all properties are either ignored by Linux drivers or have exactly the same meaning.

3. Devices mapped to Secure Firmwares only. Those are not accessible by Linux and trying to initialize them from the Linux kernel would cause memory aborts.

4. Connecting devices to backends such as serial, block devices, etc. We need to specify corresponding 'chardev' and 'driver' properties.

5. Interrupt wiring. Some hardware lines are transparent to Linux, but need be wired by QEMU. For example, interrupt controllers are wired to CPUs, etc. If we would want to initialize it from dts eventually, this would need to be passed somehow.

Overall, my understanding is Device models typically need to support booting existing
OS images and device trees from regular platform builds.
And at least due points 2-4, we cannot use them directly.
Since we still need to modify the device tree for QEMU anyway, having support for unified DTS doesn't really make sense.

Quoted 8 lines

This series seems to be more complex than Bernhard's e500-fdt experiment (I've linked to that in
<https://lists.nongnu.org/archive/html/qemu-devel/2026-01/msg05470.html>)
Bernhard's patch only added minimal support for creating devices from fdt and then put additional logic in the devices instead of handling them in generic code. Would such an approach lead to simpler fdt handling? If not why is the additional complexity needed?

Most devices can be created from generic code. Supporting one common approach to initialize some specific device class would be simpler and more maintainable than writing a custom FDT handler logic within each device model.

Quoted 2 lines

Regards,
BALATON Zoltan

--
BR,
Ruslan Ruslichenko

#40 lore raw

Re: [PATCH v2 19/33] hw/core/machine: add '-hw-dtb' option for machine

Quoted 75 lines · Ruslan Ruslichenko
Quoted 67 lines · BALATON Zoltan
Quoted 61 lines · Ruslan Ruslichenko
Quoted 55 lines · Alex Bennée
Quoted 43 lines · Thomas Huth

Hi!

Quoted 40 lines · Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]> Add new '-hw-dtb' command-line option and corresponding MachineState property.
The 'hw-dtb' option allows to specify a Device tree binary with hardware description which Qemu should emulate.

---
  hw/core/machine.c        | 19 +++++++++++++++++++
  include/hw/core/boards.h |  1 +
  qemu-options.hx          |  9 +++++++++
  system/vl.c              |  3 +++
  4 files changed, 32 insertions(+)
hw/core/machine.c +13 -0
index d4ef620c17..affd24cd49 100644
@@ -363,6 +363,20 @@ static void machine_set_dtb(Object *obj, const char *value, Error **errp)
      ms->dtb = g_strdup(value);
  }
  +static char *machine_get_hw_dtb(Object *obj, Error **errp)
+{
+    MachineState *ms = MACHINE(obj);
+
+    return g_strdup(ms->hw_dtb);
+}
+
+static void machine_set_hw_dtb(Object *obj, const char *value, Error **errp)
+{
+    MachineState *ms = MACHINE(obj);
+
+    ms->hw_dtb = g_strdup(value);
+}
+
  static char *machine_get_dumpdtb(Object *obj, Error **errp)
  {
      MachineState *ms = MACHINE(obj);
@@ -1145,6 +1159,11 @@ static void machine_class_init(ObjectClass *oc, const void *data)
      object_class_property_set_description(oc, "dtb",
          "Linux kernel device tree file");
Quoted 8 lines

hw/core/machine.c static void machine_class_init(ObjectClass *oc, const void *data) · line 1165

Quoted 4 lines
hw/core/machine.c +3 -0
  +    object_class_property_add_str(oc, "hw-dtb",
+                            machine_get_hw_dtb, machine_set_hw_dtb);
+    object_class_property_set_description(oc, "hw-dtb",
+                "A device tree binary used to describe the hardware to QEMU");

Do the hardware dtbs differ from the ones that are passed to the Linux kernel? If not, I think you likely could use the existing "dtb" property for your new feature?

Quoted 4 lines

They have to - the normal DTB cannot define the whole system because its only concerned with reporting what the kernel can see to the kernel and not defining the whole system including what the firmware sees.

Quoted 4 lines

Yes, Indeed.
Normal DTB was explored, but there is not enough information to create QEMU models from it.
Thus we need to have a separate device tree.

Quoted 6 lines

What additional data is needed that's not present in dtb from firmware and what if that additional data is passed to the kernel? I think the kernel would just ignore the additional data that it doesn't need so one dtb might be enough even if it has to be more detailed than what the kernel normally gets. If that works we don't need a separate option.

Quoted 5 lines

Here are few specific examples:

1. DTS compatibles and QOM type names are all different.
Using Linux device tree would require to maintain some massive hardcoded mapping even for devices that otherwise don't require any special handling.

Bernhard's patches had the same issue and solved it by adding subclasses with names matching the dtb. I think that would not work but a better approach is to allow alias names for devices (we already have machine name aliases I thought something similar for devices) that would solve this issue without too much additional complexity. Then the device would just need an additional line registering an alias name to match the dtb name (or more of different machines have different compatible names).

Quoted 9 lines

2. Object properties. We would probably need to make sure there is no conflicts and all properties are either ignored by Linux drivers or have exactly the same meaning.

3. Devices mapped to Secure Firmwares only. Those are not accessible by Linux and trying to initialize them from the Linux kernel would cause memory aborts.

4. Connecting devices to backends such as serial, block devices, etc. We need to specify corresponding 'chardev' and 'driver' properties.

This is probably not part of the machine but a specific invocation so these should be specified on the command line and not in the machine definion.

Quoted 9 lines

5. Interrupt wiring. Some hardware lines are transparent to Linux, but need be wired by QEMU. For example, interrupt controllers are wired to CPUs, etc. If we would want to initialize it from dts eventually, this would need to be passed somehow.

Overall, my understanding is Device models typically need to support booting existing
OS images and device trees from regular platform builds. And at least due points 2-4, we cannot use them directly.

Some of the points may be solved other than modifying dtb but some may indeed need extensions so a separate hw-dtb may be needed in more complex cases.

Quoted 2 lines

Since we still need to modify the device tree for QEMU anyway, having support for unified DTS doesn't really make sense.

However it may be worthwile to try keeping the modifications minimal so for simple machines like the e500-ppc that has no secure world or other things not described by the normal dtb it could just use the regular dtb and the hw-dtb option would be optional for more complex machines that need it.

Quoted 11 lines
Quoted 7 lines

This series seems to be more complex than Bernhard's e500-fdt experiment (I've linked to that in
<https://lists.nongnu.org/archive/html/qemu-devel/2026-01/msg05470.html>)
Bernhard's patch only added minimal support for creating devices from fdt and then put additional logic in the devices instead of handling them in generic code. Would such an approach lead to simpler fdt handling? If not why is the additional complexity needed?

Most devices can be created from generic code. Supporting one common approach to initialize some specific device class would be simpler and more maintainable than writing a custom FDT handler logic within each device model.

I think putting device specific knowledge in generic code is against the object oriented design of QEMU and would be less maintainable because it would not belong to the device maintainers that way. If you have common code for some device classes then those devices probably have a superclass where this code could be put. The problem of mapping property names to device specific properties could also be done easier within a device model which has better knowledge of the device and then we would not need a global table mapping these. So while at first look it may seem more fragmented putting some logic in devices instead of a central place it's better fits the object model and groups device specific logic in the device model which is more maintainable than a global mapping that does not belong to any device but touches several unrelated devices.

Regards,
BALATON Zoltan

#41 lore raw

Re: [PATCH v2 19/33] hw/core/machine: add '-hw-dtb' option for machine

Quoted 125 lines · BALATON Zoltan
Quoted 79 lines · Ruslan Ruslichenko
Quoted 71 lines · BALATON Zoltan
Quoted 65 lines · Ruslan Ruslichenko
Quoted 59 lines · Alex Bennée
Quoted 47 lines · Thomas Huth

Hi!

Quoted 44 lines · Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]> Add new '-hw-dtb' command-line option and corresponding MachineState property.
The 'hw-dtb' option allows to specify a Device tree binary with hardware description which Qemu should emulate.

---
  hw/core/machine.c        | 19 +++++++++++++++++++
  include/hw/core/boards.h |  1 +
  qemu-options.hx          |  9 +++++++++
  system/vl.c              |  3 +++
  4 files changed, 32 insertions(+)
hw/core/machine.c +13 -0
index d4ef620c17..affd24cd49 100644
@@ -363,6 +363,20 @@ static void machine_set_dtb(Object *obj, const 
 char *value, Error **errp)
      ms->dtb = g_strdup(value);
  }
  +static char *machine_get_hw_dtb(Object *obj, Error **errp)
+{
+    MachineState *ms = MACHINE(obj);
+
+    return g_strdup(ms->hw_dtb);
+}
+
+static void machine_set_hw_dtb(Object *obj, const char *value, Error 
 **errp)
+{
+    MachineState *ms = MACHINE(obj);
+
+    ms->hw_dtb = g_strdup(value);
+}
+
  static char *machine_get_dumpdtb(Object *obj, Error **errp)
  {
      MachineState *ms = MACHINE(obj);
@@ -1145,6 +1159,11 @@ static void machine_class_init(ObjectClass *oc, 
 const void *data)
      object_class_property_set_description(oc, "dtb",
          "Linux kernel device tree file");
  +    object_class_property_add_str(oc, "hw-dtb",
Quoted 8 lines

hw/core/machine.c static void machine_class_init(ObjectClass *oc, · line 1166

Quoted 4 lines
hw/core/machine.c +3 -0
+                            machine_get_hw_dtb, machine_set_hw_dtb);
+    object_class_property_set_description(oc, "hw-dtb",
+                "A device tree binary used to describe the hardware 
 to QEMU");

Do the hardware dtbs differ from the ones that are passed to the Linux kernel? If not, I think you likely could use the existing "dtb" property for your new feature?

Quoted 4 lines

They have to - the normal DTB cannot define the whole system because its only concerned with reporting what the kernel can see to the kernel and not defining the whole system including what the firmware sees.

Quoted 4 lines

Yes, Indeed.
Normal DTB was explored, but there is not enough information to create QEMU models from it.
Thus we need to have a separate device tree.

Quoted 6 lines

What additional data is needed that's not present in dtb from firmware and what if that additional data is passed to the kernel? I think the kernel would just ignore the additional data that it doesn't need so one dtb might be enough even if it has to be more detailed than what the kernel normally gets. If that works we don't need a separate option.

Quoted 5 lines

Here are few specific examples:

1. DTS compatibles and QOM type names are all different.
Using Linux device tree would require to maintain some massive hardcoded mapping even for devices that otherwise don't require any special handling.

Bernhard's patches had the same issue and solved it by adding subclasses with names matching the dtb. I think that would not work but a better approach is to allow alias names for devices (we already have machine name aliases I thought something similar for devices) that would solve this issue without too much additional complexity. Then the device would just need an additional line registering an alias name to match the dtb name (or more of different machines have different compatible names).

Quoted 9 lines

2. Object properties. We would probably need to make sure there is no conflicts and all properties are either ignored by Linux drivers or have exactly the same meaning.

3. Devices mapped to Secure Firmwares only. Those are not accessible by Linux and trying to initialize them from the Linux kernel would cause memory aborts.

4. Connecting devices to backends such as serial, block devices, etc. We need to specify corresponding 'chardev' and 'driver' properties.

This is probably not part of the machine but a specific invocation so these should be specified on the command line and not in the machine definion.

Quoted 9 lines

5. Interrupt wiring. Some hardware lines are transparent to Linux, but need be wired by QEMU. For example, interrupt controllers are wired to CPUs, etc. If we would want to initialize it from dts eventually, this would need to be passed somehow.

Overall, my understanding is Device models typically need to support booting existing
OS images and device trees from regular platform builds. And at least due points 2-4, we cannot use them directly.

Some of the points may be solved other than modifying dtb but some may indeed need extensions so a separate hw-dtb may be needed in more complex cases.

Quoted 2 lines

Since we still need to modify the device tree for QEMU anyway, having support for unified DTS doesn't really make sense.

However it may be worthwile to try keeping the modifications minimal so for simple machines like the e500-ppc that has no secure world or other things not described by the normal dtb it could just use the regular dtb and the hw-dtb option would be optional for more complex machines that need it.

Quoted 8 lines
Quoted 7 lines

This series seems to be more complex than Bernhard's e500-fdt experiment (I've linked to that in
<https://lists.nongnu.org/archive/html/qemu-devel/2026-01/msg05470.html>)
Bernhard's patch only added minimal support for creating devices from fdt and then put additional logic in the devices instead of handling them in generic code. Would such an approach lead to simpler fdt handling? If not why is the additional complexity needed?

Quoted 5 lines
Quoted 3 lines

Most devices can be created from generic code. Supporting one common approach to initialize some specific device class would be simpler and more maintainable than writing a custom FDT handler logic within each device model.

I think putting device specific knowledge in generic code is against the object oriented design of QEMU and would be less maintainable because it would not belong to the device maintainers that way. If you have common code for some device classes then those devices probably have a superclass where this code could be put. The problem of mapping property names to device specific properties could also be done easier within a device model which has better knowledge of the device and then we would not need a global table mapping these. So while at first look it may seem more fragmented putting some logic in devices instead of a central place it's better fits the object model and groups device specific logic in the device model which is more maintainable than a global mapping that does not belong to any device but touches several unrelated devices.

It does not help that Google randomly refuses my emails saying it's spam if I cc it to more than one gmail user. See my reply above if you've missed the previous mail. Hopefully this gets through.

Regards,
BALATON Zoltan

#42 lore raw

Re: [PATCH v2 19/33] hw/core/machine: add '-hw-dtb' option for machine

Quoted 129 lines · BALATON Zoltan
Quoted 127 lines · BALATON Zoltan
Quoted 80 lines · Ruslan Ruslichenko
Quoted 72 lines · BALATON Zoltan
Quoted 66 lines · Ruslan Ruslichenko
Quoted 59 lines · Alex Bennée
Quoted 47 lines · Thomas Huth

Hi!

Quoted 44 lines · Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]> Add new '-hw-dtb' command-line option and corresponding MachineState property.
The 'hw-dtb' option allows to specify a Device tree binary with hardware description which Qemu should emulate.

---
  hw/core/machine.c        | 19 +++++++++++++++++++
  include/hw/core/boards.h |  1 +
  qemu-options.hx          |  9 +++++++++
  system/vl.c              |  3 +++
  4 files changed, 32 insertions(+)
hw/core/machine.c +13 -0
index d4ef620c17..affd24cd49 100644
@@ -363,6 +363,20 @@ static void machine_set_dtb(Object *obj, const
 char *value, Error **errp)
      ms->dtb = g_strdup(value);
  }
  +static char *machine_get_hw_dtb(Object *obj, Error **errp)
+{
+    MachineState *ms = MACHINE(obj);
+
+    return g_strdup(ms->hw_dtb);
+}
+
+static void machine_set_hw_dtb(Object *obj, const char *value, Error
 **errp)
+{
+    MachineState *ms = MACHINE(obj);
+
+    ms->hw_dtb = g_strdup(value);
+}
+
  static char *machine_get_dumpdtb(Object *obj, Error **errp)
  {
      MachineState *ms = MACHINE(obj);
@@ -1145,6 +1159,11 @@ static void machine_class_init(ObjectClass *oc,
 const void *data)
      object_class_property_set_description(oc, "dtb",
          "Linux kernel device tree file");
  +    object_class_property_add_str(oc, "hw-dtb",
Quoted 8 lines

hw/core/machine.c static void machine_class_init(ObjectClass *oc, · line 1166

Quoted 4 lines
hw/core/machine.c +3 -0
+                            machine_get_hw_dtb, machine_set_hw_dtb);
+    object_class_property_set_description(oc, "hw-dtb",
+                "A device tree binary used to describe the hardware
 to QEMU");

Do the hardware dtbs differ from the ones that are passed to the Linux kernel? If not, I think you likely could use the existing "dtb" property for your new feature?

Quoted 4 lines

They have to - the normal DTB cannot define the whole system because its only concerned with reporting what the kernel can see to the kernel and not defining the whole system including what the firmware sees.

Quoted 4 lines

Yes, Indeed.
Normal DTB was explored, but there is not enough information to create QEMU models from it.
Thus we need to have a separate device tree.

Quoted 6 lines

What additional data is needed that's not present in dtb from firmware and what if that additional data is passed to the kernel? I think the kernel would just ignore the additional data that it doesn't need so one dtb might be enough even if it has to be more detailed than what the kernel normally gets. If that works we don't need a separate option.

Quoted 6 lines

Here are few specific examples:

1. DTS compatibles and QOM type names are all different. Using Linux device tree would require to maintain some massive hardcoded mapping
even for devices that otherwise don't require any special handling.

Bernhard's patches had the same issue and solved it by adding subclasses with names matching the dtb. I think that would not work but a better approach is to allow alias names for devices (we already have machine name aliases I thought something similar for devices) that would solve this issue without too much additional complexity. Then the device would just need an additional line registering an alias name to match the dtb name (or more of different machines have different compatible names).

Quoted 5 lines

2. Object properties. We would probably need to make sure there is no conflicts
and all properties are either ignored by Linux drivers or have exactly the same meaning.

Quoted 7 lines

3. Devices mapped to Secure Firmwares only. Those are not accessible by Linux
and trying to initialize them from the Linux kernel would cause memory aborts.

4. Connecting devices to backends such as serial, block devices, etc. We need to specify corresponding 'chardev' and 'driver' properties.

This is probably not part of the machine but a specific invocation so these should be specified on the command line and not in the machine definion.

Quoted 11 lines

5. Interrupt wiring. Some hardware lines are transparent to Linux, but need be
wired by QEMU. For example, interrupt controllers are wired to CPUs, etc. If we would want to initialize it from dts eventually, this would need to be
passed somehow.

Overall, my understanding is Device models typically need to support booting existing
OS images and device trees from regular platform builds. And at least due points 2-4, we cannot use them directly.

Some of the points may be solved other than modifying dtb but some may indeed need extensions so a separate hw-dtb may be needed in more complex cases.

Quoted 8 lines
Quoted 8 lines
Quoted 3 lines

Since we still need to modify the device tree for QEMU anyway, having support
for unified DTS doesn't really make sense.

However it may be worthwile to try keeping the modifications minimal so for simple machines like the e500-ppc that has no secure world or other things not described by the normal dtb it could just use the regular dtb and the hw-dtb option would be optional for more complex machines that need it.

In fact, machine code now decides which device tree binary to pass to the generic fdt parser.
So e500-ppc can indeed use a normal dtb instead and if corresponding aliases are registered
then the machine should be created with the fdt_generic framework too. However, for more complex cases we would indeed need HW dtb.

Quoted 14 lines
Quoted 14 lines
Quoted 13 lines
Quoted 8 lines

This series seems to be more complex than Bernhard's e500-fdt experiment (I've linked to that in
<https://lists.nongnu.org/archive/html/qemu-devel/2026-01/msg05470.html>)
Bernhard's patch only added minimal support for creating devices from fdt and then put additional logic in the devices instead of handling them in generic code. Would such an approach lead to simpler fdt handling? If not why is the additional complexity needed?

Most devices can be created from generic code. Supporting one common approach to initialize some specific device class would be simpler and more maintainable than writing a custom FDT handler logic within each device model.

Quoted 13 lines
Quoted 4 lines

I think putting device specific knowledge in generic code is against the object oriented design of QEMU and would be less maintainable because it would not belong to the device maintainers that way. If you have common code for some device classes then those devices probably have a superclass where

Quoted 8 lines

this code could be put. The problem of mapping property names to device specific properties could also be done easier within a device model which has better knowledge of the device and then we would not need a global table mapping these. So while at first look it may seem more fragmented putting some logic in devices instead of a central place it's better fits the object model and groups device specific logic in the device model which is more maintainable than a global mapping that does not belong to any device but touches several unrelated devices.

Currently, there are only a few special cases for serial, blockdev type devices to set up their properties, but no awareness about any device class. Even this may probably be improved to be more generic in future too.
All other properties are set without any specific mapping to device class, so the parsing logic is generic.
The complexity exists because fdt_generic handles the logic for machine construction,
such as creating custom memory regions, mapping devices to these regions, and parsing irq-maps.
Specifically, this generic memory mapping logic was required to instantiate secure devices and create the correct address space mapping for the PCIe bus in order to build the sbsa-ref example machine.

Quoted 6 lines

It does not help that Google randomly refuses my emails saying it's spam if I cc it to more than one gmail user. See my reply above if you've missed the previous mail. Hopefully this gets through.

Regards,
BALATON Zoltan

--
BR,
Ruslan Ruslichenko