Skip to contentSkip to conversation

VIRTIO-IOMMU device

PATCH Superseded Eric Auger 8 participants 89 messages Nov 22, 2019 – Jan 9, 2020

v11 of 16 Superseded Latest is v16 →

lore
Share & tools
lore

Eric Auger

author
#0 lore raw

v11 cover VIRTIO-IOMMU device

This series implements the QEMU virtio-iommu device.

This matches the v0.12 spec and the corresponding virtio-iommu driver upstreamed in 5.3.

The pci proxy for the virtio-iommu device is instantiated using "-device virtio-iommu-pci". This series still relies on ACPI IORT/DT integration. Note the ACPI IORT integration is not yet upstreamed and testing needs to be based on Jean-Philippe's additional kernel patches [1].

Work is ongoing to remove IORT adherence and allow the bindings between the IOMMU and the root complex to be defined and written into the PCI device configuration space. The outcome of this work is uncertain at this stage though. See [2].

So only patches 1-11 fully rely on upstreamed kernel code. Others should be considered as RFC.

This respin allows people to test on ARM and x86. It also brings migration support (tested on ARM) and various cleanups. Reserved regions are now passed through an array of properties. A libqos test also is introduced to test the virtio-iommu API.

Note integration with vhost devices and vfio devices is not part of this series. Please follow Bharat's respins [3].

The 1st Patch ("migration: Support QLIST migration") was sent separately [4].

Best Regards

Eric

This series can be found at:
https://github.com/eauger/qemu/tree/v4.2-rc2-virtio-iommu-v11

[1] kernel branch to be used for guest

    https://github.com/eauger/linux/tree/v5.4-rc8-virtio-iommu-iort

[2] [RFC 00/13] virtio-iommu on non-devicetree platforms
[3] VFIO/VHOST integration is not part of this series. Please follow [PATCH RFC v5 0/5] virtio-iommu: VFIO integration respins
[4] [PATCH v6] migration: Support QLIST migration

Testing:
- tested with guest using virtio-net-pci (,vhost=off,iommu_platform,disable-modern=off,disable-legacy=on) and virtio-blk-pci
- migration on ARM
- on x86 PC machine I get some AHCI non translated transactions, very early. This does not prevent the guest from boot and behaving properly. Warnings look like:
qemu-system-x86_64: virtio_iommu_translate sid=250 is not known!!
qemu-system-x86_64: no buffer available in event queue to report event
qemu-system-x86_64: AHCI: Failed to start FIS receive engine: bad FIS receive buffer address

History:

v10 -> v11:
- introduce virtio_iommu_handle_req macro
- migration support
- introduce DEFINE_PROP_INTERVAL and pass reserved regions through an array of those
- domain gtree simplification

v9 -> v10:
- rebase on 4.1.0-rc2, compliance with 0.12 spec
- removed ACPI part
- cleanup (see individual change logs)
- moved to a PATCH series

v8 -> v9:
- virtio-iommu-pci device needs to be instantiated from the command line (RID is not imposed anymore).
- tail structure properly initialized

v7 -> v8:
- virtio-iommu-pci added
- virt instantiation modified
- DT and ACPI modified to exclude the iommu RID from the mapping
- VIRTIO_IOMMU_F_BYPASS, VIRTIO_F_VERSION_1 features exposed

v6 -> v7:
- rebase on qemu 3.0.0-rc3
- minor update against v0.7
- fix issue with EP not on pci.0 and ACPI probing
- change the instantiation method

v5 -> v6:
- minor update against v0.6 spec
- fix g_hash_table_lookup in virtio_iommu_find_add_as
- replace some error_reports by qemu_log_mask(LOG_GUEST_ERROR, ...)

v4 -> v5:
- event queue and fault reporting
- we now return the IOAPIC MSI region if the virtio-iommu is instantiated in a PC machine.
- we bypass transactions on MSI HW region and fault on reserved ones.
- We support ACPI boot with mach-virt (based on IORT proposal)
- We moved to the new driver naming conventions
- simplified mach-virt instantiation
- worked around the disappearing of pci_find_primary_bus
- in virtio_iommu_translate, check the dev->as is not NULL
- initialize as->device_list in virtio_iommu_get_as
- initialize bufstate.error to false in virtio_iommu_probe

v3 -> v4:
- probe request support although no reserved region is returned at the moment
- unmap semantics less strict, as specified in v0.4
- device registration, attach/detach revisited
- split into smaller patches to ease review
- propose a way to inform the IOMMU mr about the page_size_mask of underlying HW IOMMU, if any
- remove warning associated with the translation of the MSI doorbell

v2 -> v3:
- rebase on top of 2.10-rc0 and especially
[PATCH qemu v9 0/2] memory/iommu: QOM'fy IOMMU MemoryRegion
- add mutex init
- fix as->mappings deletion using g_tree_ref/unref
- when a dev is attached whereas it is already attached to another address space, first detach it
- fix some error values
- page_sizes = TARGET_PAGE_MASK;
- I haven't changed the unmap() semantics yet, waiting for the next virtio-iommu spec revision.

v1 -> v2:
- fix redefinition of viommu_as typedef

Eric Auger (20):
migration: Support QLIST migration
virtio-iommu: Add skeleton
virtio-iommu: Decode the command payload
virtio-iommu: Add the iommu regions
virtio-iommu: Endpoint and domains structs and helpers
virtio-iommu: Implement attach/detach command
virtio-iommu: Implement map/unmap
virtio-iommu: Implement translate
virtio-iommu: Implement fault reporting
virtio-iommu-pci: Add virtio iommu pci support hw/arm/virt: Add the virtio-iommu device tree mappings
qapi: Introduce DEFINE_PROP_INTERVAL
virtio-iommu: Implement probe request
virtio-iommu: Handle reserved regions in the translation process
virtio-iommu-pci: Add array of Interval properties hw/arm/virt-acpi-build: Introduce fill_iort_idmap helper hw/arm/virt-acpi-build: Add virtio-iommu node in IORT table
virtio-iommu: Support migration
pc: Add support for virtio-iommu-pci
tests: Add virtio-iommu test

 hw/arm/virt-acpi-build.c         |  91 ++-
 hw/arm/virt.c                    |  53 +-
 hw/core/qdev-properties.c        |  90 +++
 hw/i386/acpi-build.c             |  72 +++
 hw/i386/pc.c                     |  15 +-
 hw/virtio/Kconfig                |   5 +
 hw/virtio/Makefile.objs          |   2 +
 hw/virtio/trace-events           |  22 +
 hw/virtio/virtio-iommu-pci.c     |  91 +++
 hw/virtio/virtio-iommu.c         | 952 +++++++++++++++++++++++++++++++
 include/exec/memory.h            |   6 +
 include/hw/acpi/acpi-defs.h      |  21 +-
 include/hw/arm/virt.h            |   2 +
 include/hw/i386/pc.h             |   2 +
 include/hw/pci/pci.h             |   1 +
 include/hw/qdev-properties.h     |   3 +
 include/hw/virtio/virtio-iommu.h |  67 +++
 include/migration/vmstate.h      |  21 +
 include/qemu/queue.h             |  39 ++
 include/qemu/typedefs.h          |   1 +
 migration/trace-events           |   5 +
 migration/vmstate-types.c        |  70 +++
 qdev-monitor.c                   |   1 +
 tests/Makefile.include           |   2 +
 tests/libqos/virtio-iommu.c      | 177 ++++++
 tests/libqos/virtio-iommu.h      |  45 ++
 tests/test-vmstate.c             | 170 ++++++
 tests/virtio-iommu-test.c        | 261 +++++++++
 28 files changed, 2253 insertions(+), 34 deletions(-)
 create mode 100644 hw/virtio/virtio-iommu-pci.c
 create mode 100644 hw/virtio/virtio-iommu.c
 create mode 100644 include/hw/virtio/virtio-iommu.h
 create mode 100644 tests/libqos/virtio-iommu.c
 create mode 100644 tests/libqos/virtio-iommu.h
 create mode 100644 tests/virtio-iommu-test.c
Signature · 1 line
2.20.1
author
#1 lore raw

PATCH v11 1/20 migration: Support QLIST migration

Support QLIST migration using the same principle as QTAILQ:
94869d5c52 ("migration: migrate QTAILQ").

The VMSTATE_QLIST_V macro has the same proto as VMSTATE_QTAILQ_V. The change mainly resides in QLIST RAW macros: QLIST_RAW_INSERT_HEAD and QLIST_RAW_REVERSE.

Tests also are provided.

---

v5 - v6:
- by doing more advanced testing with virtio-iommu migration I noticed this was broken. "prev" field was not set properly. I improved the tests to manipulate both the next and prev fields.
- Removed Peter and Juan's R-b

---
 include/migration/vmstate.h |  21 +++++
 include/qemu/queue.h        |  39 +++++++++
 migration/trace-events      |   5 ++
 migration/vmstate-types.c   |  70 +++++++++++++++
 tests/test-vmstate.c        | 170 ++++++++++++++++++++++++++++++++++++
 5 files changed, 305 insertions(+)
include/migration/vmstate.h +21 -0
index ac4f46a67d..08683d93c6 100644
@@ -227,6 +227,7 @@ extern const VMStateInfo vmstate_info_tmp;
 extern const VMStateInfo vmstate_info_bitmap;
 extern const VMStateInfo vmstate_info_qtailq;
 extern const VMStateInfo vmstate_info_gtree;
+extern const VMStateInfo vmstate_info_qlist;
 
 #define type_check_2darray(t1,t2,n,m) ((t1(*)[n][m])0 - (t2*)0)
 /*
@@ -796,6 +797,26 @@ extern const VMStateInfo vmstate_info_gtree;
     .offset       = offsetof(_state, _field),                                  \
 }
 
+/*
+ * For migrating a QLIST
+ * Target QLIST needs be properly initialized.
+ * _type: type of QLIST element
+ * _next: name of QLIST_ENTRY entry field in QLIST element
+ * _vmsd: VMSD for QLIST element
+ * size: size of QLIST element
+ * start: offset of QLIST_ENTRY in QTAILQ element
+ */
+#define VMSTATE_QLIST_V(_field, _state, _version, _vmsd, _type, _next)  \
+{                                                                        \
+    .name         = (stringify(_field)),                                 \
+    .version_id   = (_version),                                          \
+    .vmsd         = &(_vmsd),                                            \
+    .size         = sizeof(_type),                                       \
+    .info         = &vmstate_info_qlist,                                 \
+    .offset       = offsetof(_state, _field),                            \
+    .start        = offsetof(_type, _next),                              \
+}
+
 /* _f : field name
    _f_n : num of elements field_name
    _n : num of elements
include/qemu/queue.h +39 -0
index 4764d93ea3..4d4554a7ce 100644
@@ -501,4 +501,43 @@ union {                                                                 \
         QTAILQ_RAW_TQH_CIRC(head)->tql_prev = QTAILQ_RAW_TQE_CIRC(elm, entry);  \
 } while (/*CONSTCOND*/0)
 
+#define QLIST_RAW_FIRST(head)                                                  \
+        field_at_offset(head, 0, void *)
+
+#define QLIST_RAW_NEXT(elm, entry)                                             \
+        field_at_offset(elm, entry, void *)
+
+#define QLIST_RAW_PREVIOUS(elm, entry)                                         \
+        field_at_offset(elm, entry + sizeof(void *), void *)
+
+#define QLIST_RAW_FOREACH(elm, head, entry)                                    \
+        for ((elm) = *QLIST_RAW_FIRST(head);                                   \
+             (elm);                                                            \
+             (elm) = *QLIST_RAW_NEXT(elm, entry))
+
+#define QLIST_RAW_INSERT_HEAD(head, elm, entry) do {                           \
+        void *first = *QLIST_RAW_FIRST(head);                                  \
+        *QLIST_RAW_FIRST(head) = elm;                                          \
+        *QLIST_RAW_PREVIOUS(elm, entry) = QLIST_RAW_FIRST(head);               \
+        if (first) {                                                           \
+            *QLIST_RAW_NEXT(elm, entry) = first;                               \
+            *QLIST_RAW_PREVIOUS(first, entry) = QLIST_RAW_NEXT(elm, entry);    \
+        } else {                                                               \
+            *QLIST_RAW_NEXT(elm, entry) = NULL;                                \
+        }                                                                      \
+} while (0)
+
+#define QLIST_RAW_REVERSE(head, elm, entry) do {                               \
+        void *iter = *QLIST_RAW_FIRST(head), *prev = NULL, *next;              \
+        while (iter) {                                                         \
+            next = *QLIST_RAW_NEXT(iter, entry);                               \
+            *QLIST_RAW_PREVIOUS(iter, entry) = QLIST_RAW_NEXT(next, entry);    \
+            *QLIST_RAW_NEXT(iter, entry) = prev;                               \
+            prev = iter;                                                       \
+            iter = next;                                                       \
+        }                                                                      \
+        *QLIST_RAW_FIRST(head) = prev;                                         \
+        *QLIST_RAW_PREVIOUS(prev, entry) = QLIST_RAW_FIRST(head);              \
+} while (0)
+
 #endif /* QEMU_SYS_QUEUE_H */
migration/trace-events +5 -0
index 6dee7b5389..e0a33cffca 100644
@@ -76,6 +76,11 @@ get_gtree_end(const char *field_name, const char *key_vmsd_name, const char *val
 put_gtree(const char *field_name, const char *key_vmsd_name, const char *val_vmsd_name, uint32_t nnodes) "%s(%s/%s) nnodes=%d"
 put_gtree_end(const char *field_name, const char *key_vmsd_name, const char *val_vmsd_name, int ret) "%s(%s/%s) %d"
 
+get_qlist(const char *field_name, const char *vmsd_name, int version_id) "%s(%s v%d)"
+get_qlist_end(const char *field_name, const char *vmsd_name) "%s(%s)"
+put_qlist(const char *field_name, const char *vmsd_name, int version_id) "%s(%s v%d)"
+put_qlist_end(const char *field_name, const char *vmsd_name) "%s(%s)"
+
 # qemu-file.c
 qemu_file_fclose(void) ""
 
migration/vmstate-types.c +70 -0

73 lines not on this page · raw message

tests/test-vmstate.c +170 -0

194 lines not on this page · raw message

Signature · 1 line
2.20.1
#2 lore raw

Re: [PATCH for-5.0 v11 01/20] migration: Support QLIST migration

Quoted 188 lines · * Eric Auger ([email protected]) wrote:

Support QLIST migration using the same principle as QTAILQ:
94869d5c52 ("migration: migrate QTAILQ").

The VMSTATE_QLIST_V macro has the same proto as VMSTATE_QTAILQ_V. The change mainly resides in QLIST RAW macros: QLIST_RAW_INSERT_HEAD and QLIST_RAW_REVERSE.

Tests also are provided.

---

v5 - v6:
- by doing more advanced testing with virtio-iommu migration I noticed this was broken. "prev" field was not set properly. I improved the tests to manipulate both the next and prev fields.
- Removed Peter and Juan's R-b

---
 include/migration/vmstate.h |  21 +++++
 include/qemu/queue.h        |  39 +++++++++
 migration/trace-events      |   5 ++
 migration/vmstate-types.c   |  70 +++++++++++++++
 tests/test-vmstate.c        | 170 ++++++++++++++++++++++++++++++++++++
 5 files changed, 305 insertions(+)
include/migration/vmstate.h +21 -0
index ac4f46a67d..08683d93c6 100644
@@ -227,6 +227,7 @@ extern const VMStateInfo vmstate_info_tmp;
 extern const VMStateInfo vmstate_info_bitmap;
 extern const VMStateInfo vmstate_info_qtailq;
 extern const VMStateInfo vmstate_info_gtree;
+extern const VMStateInfo vmstate_info_qlist;
 
 #define type_check_2darray(t1,t2,n,m) ((t1(*)[n][m])0 - (t2*)0)
 /*
@@ -796,6 +797,26 @@ extern const VMStateInfo vmstate_info_gtree;
     .offset       = offsetof(_state, _field),                                  \
 }
 
+/*
+ * For migrating a QLIST
+ * Target QLIST needs be properly initialized.
+ * _type: type of QLIST element
+ * _next: name of QLIST_ENTRY entry field in QLIST element
+ * _vmsd: VMSD for QLIST element
+ * size: size of QLIST element
+ * start: offset of QLIST_ENTRY in QTAILQ element
+ */
+#define VMSTATE_QLIST_V(_field, _state, _version, _vmsd, _type, _next)  \
+{                                                                        \
+    .name         = (stringify(_field)),                                 \
+    .version_id   = (_version),                                          \
+    .vmsd         = &(_vmsd),                                            \
+    .size         = sizeof(_type),                                       \
+    .info         = &vmstate_info_qlist,                                 \
+    .offset       = offsetof(_state, _field),                            \
+    .start        = offsetof(_type, _next),                              \
+}
+
 /* _f : field name
    _f_n : num of elements field_name
    _n : num of elements
include/qemu/queue.h +39 -0
index 4764d93ea3..4d4554a7ce 100644
@@ -501,4 +501,43 @@ union {                                                                 \
         QTAILQ_RAW_TQH_CIRC(head)->tql_prev = QTAILQ_RAW_TQE_CIRC(elm, entry);  \
 } while (/*CONSTCOND*/0)
 
+#define QLIST_RAW_FIRST(head)                                                  \
+        field_at_offset(head, 0, void *)
+
+#define QLIST_RAW_NEXT(elm, entry)                                             \
+        field_at_offset(elm, entry, void *)
+
+#define QLIST_RAW_PREVIOUS(elm, entry)                                         \
+        field_at_offset(elm, entry + sizeof(void *), void *)
+
+#define QLIST_RAW_FOREACH(elm, head, entry)                                    \
+        for ((elm) = *QLIST_RAW_FIRST(head);                                   \
+             (elm);                                                            \
+             (elm) = *QLIST_RAW_NEXT(elm, entry))
+
+#define QLIST_RAW_INSERT_HEAD(head, elm, entry) do {                           \
+        void *first = *QLIST_RAW_FIRST(head);                                  \
+        *QLIST_RAW_FIRST(head) = elm;                                          \
+        *QLIST_RAW_PREVIOUS(elm, entry) = QLIST_RAW_FIRST(head);               \
+        if (first) {                                                           \
+            *QLIST_RAW_NEXT(elm, entry) = first;                               \
+            *QLIST_RAW_PREVIOUS(first, entry) = QLIST_RAW_NEXT(elm, entry);    \
+        } else {                                                               \
+            *QLIST_RAW_NEXT(elm, entry) = NULL;                                \
+        }                                                                      \
+} while (0)
+
+#define QLIST_RAW_REVERSE(head, elm, entry) do {                               \
+        void *iter = *QLIST_RAW_FIRST(head), *prev = NULL, *next;              \
+        while (iter) {                                                         \
+            next = *QLIST_RAW_NEXT(iter, entry);                               \
+            *QLIST_RAW_PREVIOUS(iter, entry) = QLIST_RAW_NEXT(next, entry);    \
+            *QLIST_RAW_NEXT(iter, entry) = prev;                               \
+            prev = iter;                                                       \
+            iter = next;                                                       \
+        }                                                                      \
+        *QLIST_RAW_FIRST(head) = prev;                                         \
+        *QLIST_RAW_PREVIOUS(prev, entry) = QLIST_RAW_FIRST(head);              \
+} while (0)
+
 #endif /* QEMU_SYS_QUEUE_H */
migration/trace-events +5 -0
index 6dee7b5389..e0a33cffca 100644
@@ -76,6 +76,11 @@ get_gtree_end(const char *field_name, const char *key_vmsd_name, const char *val
 put_gtree(const char *field_name, const char *key_vmsd_name, const char *val_vmsd_name, uint32_t nnodes) "%s(%s/%s) nnodes=%d"
 put_gtree_end(const char *field_name, const char *key_vmsd_name, const char *val_vmsd_name, int ret) "%s(%s/%s) %d"
 
+get_qlist(const char *field_name, const char *vmsd_name, int version_id) "%s(%s v%d)"
+get_qlist_end(const char *field_name, const char *vmsd_name) "%s(%s)"
+put_qlist(const char *field_name, const char *vmsd_name, int version_id) "%s(%s v%d)"
+put_qlist_end(const char *field_name, const char *vmsd_name) "%s(%s)"
+
 # qemu-file.c
 qemu_file_fclose(void) ""
 
migration/vmstate-types.c +50 -0
index 7236cf92bc..1eee36773a 100644
@@ -843,3 +843,73 @@ const VMStateInfo vmstate_info_gtree = {
     .get  = get_gtree,
     .put  = put_gtree,
 };
+
+static int put_qlist(QEMUFile *f, void *pv, size_t unused_size,
+                     const VMStateField *field, QJSON *vmdesc)
+{
+    const VMStateDescription *vmsd = field->vmsd;
+    /* offset of the QTAILQ entry in a QTAILQ element*/
+    size_t entry_offset = field->start;
+    void *elm;
+    int ret;
+
+    trace_put_qlist(field->name, vmsd->name, vmsd->version_id);
+    QLIST_RAW_FOREACH(elm, pv, entry_offset) {
+        qemu_put_byte(f, true);
+        ret = vmstate_save_state(f, vmsd, elm, vmdesc);
+        if (ret) {
+            error_report("%s: failed to save %s (%d)", field->name,
+                         vmsd->name, ret);
+            return ret;
+        }
+    }
+    qemu_put_byte(f, false);
+    trace_put_qlist_end(field->name, vmsd->name);
+
+    return 0;
+}
+
+static int get_qlist(QEMUFile *f, void *pv, size_t unused_size,
+                     const VMStateField *field)
+{
+    int ret = 0;
+    const VMStateDescription *vmsd = field->vmsd;
+    /* size of a QLIST element */
+    size_t size = field->size;
+    /* offset of the QLIST entry in a QLIST element */
+    size_t entry_offset = field->start;
+    int version_id = field->version_id;
+    void *elm;
+
+    trace_get_qlist(field->name, vmsd->name, vmsd->version_id);
+    if (version_id > vmsd->version_id) {
+        error_report("%s %s",  vmsd->name, "too new");
+        return -EINVAL;
+    }
+    if (version_id < vmsd->minimum_version_id) {
+        error_report("%s %s",  vmsd->name, "too old");
+        return -EINVAL;
+    }
+
+    while (qemu_get_byte(f)) {
+        elm = g_malloc(size);

migration/vmstate-types.c const VMStateInfo vmstate_info_gtree = { · line 905

Quoted 10 lines
migration/vmstate-types.c +10 -0
+        ret = vmstate_load_state(f, vmsd, elm, version_id);
+        if (ret) {
+            error_report("%s: failed to load %s (%d)", field->name,
+                         vmsd->name, ret);
+            g_free(elm);
+            return ret;
+        }
+        QLIST_RAW_INSERT_HEAD(pv, elm, entry_offset);
+    }
+    QLIST_RAW_REVERSE(pv, elm, entry_offset);

Can you explain why you need to do a REVERSE on the loaded list, rather than using doing a QLIST_INSERT_AFTER to always insert at the end?

Other than that it looks good.

Dave

Quoted 215 lines
migration/vmstate-types.c +10 -0
+    trace_get_qlist_end(field->name, vmsd->name);
+
+    return ret;
+}
+
+const VMStateInfo vmstate_info_qlist = {
+    .name = "qlist",
+    .get  = get_qlist,
+    .put  = put_qlist,
+};
tests/test-vmstate.c +170 -0
index 1e5be1d4ff..9660f932b9 100644
@@ -926,6 +926,28 @@ static const VMStateDescription vmstate_domain = {
     }
 };
 
+/* test QLIST Migration */
+
+typedef struct TestQListElement {
+    uint32_t  id;
+    QLIST_ENTRY(TestQListElement) next;
+} TestQListElement;
+
+typedef struct TestQListContainer {
+    uint32_t  id;
+    QLIST_HEAD(, TestQListElement) list;
+} TestQListContainer;
+
+static const VMStateDescription vmstate_qlist_element = {
+    .name = "test/queue list",
+    .version_id = 1,
+    .minimum_version_id = 1,
+    .fields = (VMStateField[]) {
+        VMSTATE_UINT32(id, TestQListElement),
+        VMSTATE_END_OF_LIST()
+    }
+};
+
 static const VMStateDescription vmstate_iommu = {
     .name = "iommu",
     .version_id = 1,
@@ -939,6 +961,18 @@ static const VMStateDescription vmstate_iommu = {
     }
 };
 
+static const VMStateDescription vmstate_container = {
+    .name = "test/container/qlist",
+    .version_id = 1,
+    .minimum_version_id = 1,
+    .fields = (VMStateField[]) {
+        VMSTATE_UINT32(id, TestQListContainer),
+        VMSTATE_QLIST_V(list, TestQListContainer, 1, vmstate_qlist_element,
+                        TestQListElement, next),
+        VMSTATE_END_OF_LIST()
+    }
+};
+
 uint8_t first_domain_dump[] = {
     /* id */
     0x00, 0x0, 0x0, 0x6,
@@ -1229,6 +1263,140 @@ static void test_gtree_load_iommu(void)
     qemu_fclose(fload);
 }
 
+static uint8_t qlist_dump[] = {
+    0x00, 0x00, 0x00, 0x01, /* container id */
+    0x1, /* start of a */
+    0x00, 0x00, 0x00, 0x0a,
+    0x1, /* start of b */
+    0x00, 0x00, 0x0b, 0x00,
+    0x1, /* start of c */
+    0x00, 0x0c, 0x00, 0x00,
+    0x1, /* start of d */
+    0x0d, 0x00, 0x00, 0x00,
+    0x0, /* end of list */
+    QEMU_VM_EOF, /* just to ensure we won't get EOF reported prematurely */
+};
+
+static TestQListContainer *alloc_container(void)
+{
+    TestQListElement *a = g_malloc(sizeof(TestQListElement));
+    TestQListElement *b = g_malloc(sizeof(TestQListElement));
+    TestQListElement *c = g_malloc(sizeof(TestQListElement));
+    TestQListElement *d = g_malloc(sizeof(TestQListElement));
+    TestQListContainer *container = g_malloc(sizeof(TestQListContainer));
+
+    a->id = 0x0a;
+    b->id = 0x0b00;
+    c->id = 0xc0000;
+    d->id = 0xd000000;
+    container->id = 1;
+
+    QLIST_INIT(&container->list);
+    QLIST_INSERT_HEAD(&container->list, d, next);
+    QLIST_INSERT_HEAD(&container->list, c, next);
+    QLIST_INSERT_HEAD(&container->list, b, next);
+    QLIST_INSERT_HEAD(&container->list, a, next);
+    return container;
+}
+
+static void free_container(TestQListContainer *container)
+{
+    TestQListElement *iter, *tmp;
+
+    QLIST_FOREACH_SAFE(iter, &container->list, next, tmp) {
+        QLIST_REMOVE(iter, next);
+        g_free(iter);
+    }
+    g_free(container);
+}
+
+static void compare_containers(TestQListContainer *c1, TestQListContainer *c2)
+{
+    TestQListElement *first_item_c1, *first_item_c2;
+
+    while (!QLIST_EMPTY(&c1->list)) {
+        first_item_c1 = QLIST_FIRST(&c1->list);
+        first_item_c2 = QLIST_FIRST(&c2->list);
+        assert(first_item_c2);
+        assert(first_item_c1->id == first_item_c2->id);
+        QLIST_REMOVE(first_item_c1, next);
+        QLIST_REMOVE(first_item_c2, next);
+        g_free(first_item_c1);
+        g_free(first_item_c2);
+    }
+    assert(QLIST_EMPTY(&c2->list));
+}
+
+/*
+ * Check the prev & next fields are correct by doing list
+ * manipulations on the container. We will do that for both
+ * the source and the destination containers
+ */
+static void manipulate_container(TestQListContainer *c)
+{
+     TestQListElement *prev, *iter = QLIST_FIRST(&c->list);
+     TestQListElement *elem;
+
+     elem = g_malloc(sizeof(TestQListElement));
+     elem->id = 0x12;
+     QLIST_INSERT_AFTER(iter, elem, next);
+
+     elem = g_malloc(sizeof(TestQListElement));
+     elem->id = 0x13;
+     QLIST_INSERT_HEAD(&c->list, elem, next);
+
+     while (iter) {
+        prev = iter;
+        iter = QLIST_NEXT(iter, next);
+     }
+
+     elem = g_malloc(sizeof(TestQListElement));
+     elem->id = 0x14;
+     QLIST_INSERT_BEFORE(prev, elem, next);
+
+     elem = g_malloc(sizeof(TestQListElement));
+     elem->id = 0x15;
+     QLIST_INSERT_AFTER(prev, elem, next);
+
+     QLIST_REMOVE(prev, next);
+     g_free(prev);
+}
+
+static void test_save_qlist(void)
+{
+    TestQListContainer *container = alloc_container();
+
+    save_vmstate(&vmstate_container, container);
+    compare_vmstate(qlist_dump, sizeof(qlist_dump));
+    free_container(container);
+}
+
+static void test_load_qlist(void)
+{
+    QEMUFile *fsave, *fload;
+    TestQListContainer *orig_container = alloc_container();
+    TestQListContainer *dest_container = g_malloc0(sizeof(TestQListContainer));
+    char eof;
+
+    QLIST_INIT(&dest_container->list);
+
+    fsave = open_test_file(true);
+    qemu_put_buffer(fsave, qlist_dump, sizeof(qlist_dump));
+    g_assert(!qemu_file_get_error(fsave));
+    qemu_fclose(fsave);
+
+    fload = open_test_file(false);
+    vmstate_load_state(fload, &vmstate_container, dest_container, 1);
+    eof = qemu_get_byte(fload);
+    g_assert(!qemu_file_get_error(fload));
+    g_assert_cmpint(eof, ==, QEMU_VM_EOF);
+    manipulate_container(orig_container);
+    manipulate_container(dest_container);
+    compare_containers(orig_container, dest_container);
+    free_container(orig_container);
+    free_container(dest_container);
+}
+
 typedef struct TmpTestStruct {
     TestStruct *parent;
     int64_t diff;
@@ -1353,6 +1521,8 @@ int main(int argc, char **argv)
     g_test_add_func("/vmstate/gtree/load/loaddomain", test_gtree_load_domain);
     g_test_add_func("/vmstate/gtree/save/saveiommu", test_gtree_save_iommu);
     g_test_add_func("/vmstate/gtree/load/loadiommu", test_gtree_load_iommu);
+    g_test_add_func("/vmstate/qlist/save/saveqlist", test_save_qlist);
+    g_test_add_func("/vmstate/qlist/load/loadqlist", test_load_qlist);
     g_test_add_func("/vmstate/tmp_struct", test_tmp_struct);
     g_test_run();
 
Signature · 1 line
2.20.1

--
Dr. David Alan Gilbert / [email protected] / Manchester, UK

#3 lore raw

Re: [PATCH for-5.0 v11 01/20] migration: Support QLIST migration

Quoted 25 lines · Dr. David Alan Gilbert
Quoted 13 lines · * Eric Auger ([email protected]) wrote:

Support QLIST migration using the same principle as QTAILQ:
94869d5c52 ("migration: migrate QTAILQ").

The VMSTATE_QLIST_V macro has the same proto as VMSTATE_QTAILQ_V. The change mainly resides in QLIST RAW macros: QLIST_RAW_INSERT_HEAD and QLIST_RAW_REVERSE.

Tests also are provided.

migration/vmstate-types.c +2 -0
+    while (qemu_get_byte(f)) {
+        elm = g_malloc(size);

migration/vmstate-types.c const VMStateInfo vmstate_info_gtree = { · line 905

Quoted 10 lines
migration/vmstate-types.c +10 -0
+        ret = vmstate_load_state(f, vmsd, elm, version_id);
+        if (ret) {
+            error_report("%s: failed to load %s (%d)", field->name,
+                         vmsd->name, ret);
+            g_free(elm);
+            return ret;
+        }
+        QLIST_RAW_INSERT_HEAD(pv, elm, entry_offset);
+    }
+    QLIST_RAW_REVERSE(pv, elm, entry_offset);
Quoted 5 lines

Can you explain why you need to do a REVERSE on the loaded list, rather than using doing a QLIST_INSERT_AFTER to always insert at the end?

Other than that it looks good.

This was my fault (integrated as this is).

Old code had a "walk to the end of the list" and then insert. I told it was way faster just to insert and the beggining and then reverse. I didn't noticed that we had the previous element to know where to insert.

Eric, feel free to send a patch on top of this, or I will do it.

Later, Juan.

author
#4 lore raw

Re: [PATCH for-5.0 v11 01/20] migration: Support QLIST migration

Hi Juan,

Quoted 30 lines · Juan Quintela
Quoted 29 lines · Dr. David Alan Gilbert
Quoted 13 lines · * Eric Auger ([email protected]) wrote:

Support QLIST migration using the same principle as QTAILQ:
94869d5c52 ("migration: migrate QTAILQ").

The VMSTATE_QLIST_V macro has the same proto as VMSTATE_QTAILQ_V. The change mainly resides in QLIST RAW macros: QLIST_RAW_INSERT_HEAD and QLIST_RAW_REVERSE.

Tests also are provided.

migration/vmstate-types.c +2 -0
+    while (qemu_get_byte(f)) {
+        elm = g_malloc(size);

migration/vmstate-types.c const VMStateInfo vmstate_info_gtree = { · line 905

Quoted 10 lines
migration/vmstate-types.c +10 -0
+        ret = vmstate_load_state(f, vmsd, elm, version_id);
+        if (ret) {
+            error_report("%s: failed to load %s (%d)", field->name,
+                         vmsd->name, ret);
+            g_free(elm);
+            return ret;
+        }
+        QLIST_RAW_INSERT_HEAD(pv, elm, entry_offset);
+    }
+    QLIST_RAW_REVERSE(pv, elm, entry_offset);

Can you explain why you need to do a REVERSE on the loaded list, rather than using doing a QLIST_INSERT_AFTER to always insert at the end?

Quoted 8 lines
Quoted 1 line

Other than that it looks good.

This was my fault (integrated as this is).

Old code had a "walk to the end of the list" and then insert. I told it was way faster just to insert and the beggining and then reverse. I didn't noticed that we had the previous element to know where to insert.

Not sure I get your comment. To insert at the end one needs to walk though the list. The head has no prev pointer pointing to the tail as opposed to the queue. So I understood Dave's comment as "just explain why you prefered this solution against the QLIST_INSERT_AFTER alternative.

Thanks

Eric

Quoted 7 lines

Eric, feel free to send a patch on top of this, or I will do it.

Later, Juan.

#5 lore raw

Re: [PATCH for-5.0 v11 01/20] migration: Support QLIST migration

Quoted 42 lines · Auger Eric

Hi Juan,

Quoted 30 lines · Juan Quintela
Quoted 29 lines · Dr. David Alan Gilbert
Quoted 13 lines · * Eric Auger ([email protected]) wrote:

Support QLIST migration using the same principle as QTAILQ:
94869d5c52 ("migration: migrate QTAILQ").

The VMSTATE_QLIST_V macro has the same proto as VMSTATE_QTAILQ_V. The change mainly resides in QLIST RAW macros: QLIST_RAW_INSERT_HEAD and QLIST_RAW_REVERSE.

Tests also are provided.

migration/vmstate-types.c +2 -0
+    while (qemu_get_byte(f)) {
+        elm = g_malloc(size);

migration/vmstate-types.c const VMStateInfo vmstate_info_gtree = { · line 905

Quoted 10 lines
migration/vmstate-types.c +10 -0
+        ret = vmstate_load_state(f, vmsd, elm, version_id);
+        if (ret) {
+            error_report("%s: failed to load %s (%d)", field->name,
+                         vmsd->name, ret);
+            g_free(elm);
+            return ret;
+        }
+        QLIST_RAW_INSERT_HEAD(pv, elm, entry_offset);
+    }
+    QLIST_RAW_REVERSE(pv, elm, entry_offset);

Can you explain why you need to do a REVERSE on the loaded list, rather than using doing a QLIST_INSERT_AFTER to always insert at the end?

Quoted 8 lines
Quoted 1 line

Other than that it looks good.

This was my fault (integrated as this is).

Old code had a "walk to the end of the list" and then insert. I told it was way faster just to insert and the beggining and then reverse. I didn't noticed that we had the previous element to know where to insert.

Quoted 4 lines

Not sure I get your comment. To insert at the end one needs to walk though the list. The head has no prev pointer pointing to the tail as opposed to the queue. So I understood Dave's comment as "just explain why you prefered this solution against the QLIST_INSERT_AFTER alternative.

You have the previous inserted element, so it is kind of easy O:-)

    prev = NULL;
    while (qemu_get_byte(f)) {
        elm = g_malloc(size);
        ret = vmstate_load_state(f, vmsd, elm, version_id);
        if (ret) {
            error_report("%s: failed to load %s (%d)", field->name,
                         vmsd->name, ret);
            g_free(elm);
            return ret;
        }
        if (!prev) {
            QLIST_RAW_INSERT_HEAD(pv, elm, entry_offset);
        } else {
            QLIST_RAW_INSERT_AFTER(prev, elm, entry_offset);
        }
        prev = elm;
    }

And yes, I realize that there is no QLIST_RAW_INSTERT_AFTER() (it is QLIST_INSERT_AFTER). And no, I haven't took the time to understand the different between QLIST and QLIST_RAW. From a quick look, it seems that QLIST_RAW is embededed inside other structure.

But as said, we can move that to another patch.

Later, Juan.

author
#6 lore raw

Re: [PATCH for-5.0 v11 01/20] migration: Support QLIST migration

Hi Juan,

Quoted 68 lines · Juan Quintela
Quoted 42 lines · Auger Eric

Hi Juan,

Quoted 30 lines · Juan Quintela
Quoted 29 lines · Dr. David Alan Gilbert
Quoted 13 lines · * Eric Auger ([email protected]) wrote:

Support QLIST migration using the same principle as QTAILQ:
94869d5c52 ("migration: migrate QTAILQ").

The VMSTATE_QLIST_V macro has the same proto as VMSTATE_QTAILQ_V. The change mainly resides in QLIST RAW macros: QLIST_RAW_INSERT_HEAD and QLIST_RAW_REVERSE.

Tests also are provided.

migration/vmstate-types.c +2 -0
+    while (qemu_get_byte(f)) {
+        elm = g_malloc(size);

migration/vmstate-types.c const VMStateInfo vmstate_info_gtree = { · line 905

Quoted 10 lines
migration/vmstate-types.c +10 -0
+        ret = vmstate_load_state(f, vmsd, elm, version_id);
+        if (ret) {
+            error_report("%s: failed to load %s (%d)", field->name,
+                         vmsd->name, ret);
+            g_free(elm);
+            return ret;
+        }
+        QLIST_RAW_INSERT_HEAD(pv, elm, entry_offset);
+    }
+    QLIST_RAW_REVERSE(pv, elm, entry_offset);

Can you explain why you need to do a REVERSE on the loaded list, rather than using doing a QLIST_INSERT_AFTER to always insert at the end?

Quoted 8 lines
Quoted 1 line

Other than that it looks good.

This was my fault (integrated as this is).

Old code had a "walk to the end of the list" and then insert. I told it was way faster just to insert and the beggining and then reverse. I didn't noticed that we had the previous element to know where to insert.

Quoted 4 lines

Not sure I get your comment. To insert at the end one needs to walk though the list. The head has no prev pointer pointing to the tail as opposed to the queue. So I understood Dave's comment as "just explain why you prefered this solution against the QLIST_INSERT_AFTER alternative.

You have the previous inserted element, so it is kind of easy O:-)

    prev = NULL;
    while (qemu_get_byte(f)) {
        elm = g_malloc(size);
        ret = vmstate_load_state(f, vmsd, elm, version_id);
        if (ret) {
            error_report("%s: failed to load %s (%d)", field->name,
                         vmsd->name, ret);
            g_free(elm);
            return ret;
        }
        if (!prev) {
            QLIST_RAW_INSERT_HEAD(pv, elm, entry_offset);
        } else {
            QLIST_RAW_INSERT_AFTER(prev, elm, entry_offset);
        }
        prev = elm;
    }
Quoted 4 lines

And yes, I realize that there is no QLIST_RAW_INSTERT_AFTER() (it is QLIST_INSERT_AFTER). And no, I haven't took the time to understand the different between QLIST and QLIST_RAW. From a quick look, it seems that QLIST_RAW is embededed inside other structure.

Ah OK I get it now. Yes indeed that looks simpler.

Quoted 2 lines

But as said, we can move that to another patch.

OK.

Thanks

Eric

Quoted 4 lines

Later, Juan.

author
#7 lore raw

PATCH v11 2/20 virtio-iommu: Add skeleton

In reply to Eric Auger

This patchs adds the skeleton for the virtio-iommu device.

---

v9 -> v10:
- mutex initialized here
- initialize tail
- included hw/qdev-properties.h
- removed g_memdup
- removed s->config.domain_range.start = 0;

v9 -> v10:
- expose VIRTIO_IOMMU_F_MMIO feature
- s/domain_bits/domain_range struct
- change error codes
- enforce unmigratable
- Kconfig

v7 -> v8:
- expose VIRTIO_IOMMU_F_BYPASS and VIRTIO_F_VERSION_1 features
- set_config dummy implementation + tracing
- add trace in get_features
- set the features on realize() and store the acked ones
- remove inclusion of linux/virtio_iommu.h

v6 -> v7:
- removed qapi-event.h include
- add primary_bus and associated property

v4 -> v5:
- use the new v0.5 terminology (domain, endpoint)
- add the event virtqueue

v3 -> v4:
- use page_size_mask instead of page_sizes
- added set_features()
- added some traces (reset, set_status, set_features)
- empty virtio_iommu_set_config() as the driver MUST NOT write to device configuration fields
- add get_config trace

v2 -> v3:
- rebase on 2.10-rc0, ie. use IOMMUMemoryRegion and remove iommu_ops.
- advertise VIRTIO_IOMMU_F_MAP_UNMAP feature
- page_sizes set to TARGET_PAGE_SIZE

Conflicts:
hw/virtio/trace-events

---
 hw/virtio/Kconfig                |   5 +
 hw/virtio/Makefile.objs          |   1 +
 hw/virtio/trace-events           |   8 +
 hw/virtio/virtio-iommu.c         | 274 +++++++++++++++++++++++++++++++
 include/hw/virtio/virtio-iommu.h |  62 +++++++
 5 files changed, 350 insertions(+)
 create mode 100644 hw/virtio/virtio-iommu.c
 create mode 100644 include/hw/virtio/virtio-iommu.h
hw/virtio/Kconfig +5 -0
index 3724ff8bac..a30107b439 100644
@@ -6,6 +6,11 @@ config VIRTIO_RNG
     default y
     depends on VIRTIO
 
+config VIRTIO_IOMMU
+    bool
+    default y
+    depends on VIRTIO
+
 config VIRTIO_PCI
     bool
     default y if PCI_DEVICES
hw/virtio/Makefile.objs +1 -0
index e2f70fbb89..f68ac14a90 100644
@@ -16,6 +16,7 @@ obj-$(call land,$(CONFIG_VIRTIO_CRYPTO),$(CONFIG_VIRTIO_PCI)) += virtio-crypto-p
 obj-$(CONFIG_VIRTIO_PMEM) += virtio-pmem.o
 common-obj-$(call land,$(CONFIG_VIRTIO_PMEM),$(CONFIG_VIRTIO_PCI)) += virtio-pmem-pci.o
 obj-$(call land,$(CONFIG_VHOST_USER_FS),$(CONFIG_VIRTIO_PCI)) += vhost-user-fs-pci.o
+obj-$(CONFIG_VIRTIO_IOMMU) += virtio-iommu.o
 obj-$(CONFIG_VHOST_VSOCK) += vhost-vsock.o
 
 ifeq ($(CONFIG_VIRTIO_PCI),y)
hw/virtio/trace-events +8 -0
index e28ba48da6..f7dac39213 100644
@@ -53,3 +53,11 @@ virtio_mmio_write_offset(uint64_t offset, uint64_t value) "virtio_mmio_write off
 virtio_mmio_guest_page(uint64_t size, int shift) "guest page size 0x%" PRIx64 " shift %d"
 virtio_mmio_queue_write(uint64_t value, int max_size) "mmio_queue write 0x%" PRIx64 " max %d"
 virtio_mmio_setting_irq(int level) "virtio_mmio setting IRQ %d"
+
+# hw/virtio/virtio-iommu.c
+virtio_iommu_device_reset(void) "reset!"
+virtio_iommu_get_features(uint64_t features) "device supports features=0x%"PRIx64
+virtio_iommu_set_features(uint64_t features) "features accepted by the driver =0x%"PRIx64
+virtio_iommu_device_status(uint8_t status) "driver status = %d"
+virtio_iommu_get_config(uint64_t page_size_mask, uint64_t start, uint64_t end, uint32_t domain_range, uint32_t probe_size) "page_size_mask=0x%"PRIx64" start=0x%"PRIx64" end=0x%"PRIx64" domain_range=%d probe_size=0x%x"
+virtio_iommu_set_config(uint64_t page_size_mask, uint64_t start, uint64_t end, uint32_t domain_range, uint32_t probe_size) "page_size_mask=0x%"PRIx64" start=0x%"PRIx64" end=0x%"PRIx64" domain_bits=%d probe_size=0x%x"
hw/virtio/virtio-iommu.c new file +274 -0

274 lines not on this page · raw message

include/hw/virtio/virtio-iommu.h new file +62 -0

62 lines not on this page · raw message

Signature · 1 line
2.20.1
#8 lore raw

Re: [PATCH for-5.0 v11 02/20] virtio-iommu: Add skeleton

Hi Eric,

include/hw/virtio/virtio-iommu.h line 53

Quoted 7 lines · Eric Auger
include/hw/virtio/virtio-iommu.h new file +7 -0
+typedef struct VirtIOIOMMU {
+    VirtIODevice parent_obj;
+    VirtQueue *req_vq;
+    VirtQueue *event_vq;
+    struct virtio_iommu_config config;
+    uint64_t features;
+    uint64_t acked_features;

We already have guest_features in the parent object.

include/hw/virtio/virtio-iommu.h line 55

Quoted 2 lines
include/hw/virtio/virtio-iommu.h new file +2 -0
+    GHashTable *as_by_busptr;
+    IOMMUPciBus *as_by_bus_num[IOMMU_PCI_BUS_MAX];

Doesn't seem used anymore.

Thanks,
Jean

Quoted 11 lines
include/hw/virtio/virtio-iommu.h new file +7 -0
+    PCIBus *primary_bus;
+    GTree *domains;
+    QemuMutex mutex;
+    GTree *endpoints;
+} VirtIOIOMMU;
+
+#endif
Signature · 1 line
2.20.1
author
#9 lore raw

Re: [PATCH for-5.0 v11 02/20] virtio-iommu: Add skeleton

Hi Jean,

Quoted 11 lines · Jean-Philippe Brucker

Hi Eric,

include/hw/virtio/virtio-iommu.h line 53

Quoted 7 lines · Eric Auger
include/hw/virtio/virtio-iommu.h new file +7 -0
+typedef struct VirtIOIOMMU {
+    VirtIODevice parent_obj;
+    VirtQueue *req_vq;
+    VirtQueue *event_vq;
+    struct virtio_iommu_config config;
+    uint64_t features;
+    uint64_t acked_features;
Quoted 1 line

We already have guest_features in the parent object.

That's correct. I also removed the set_features() specific implementation as I can rely on the default one.

Quoted 5 lines

include/hw/virtio/virtio-iommu.h line 55

Quoted 3 lines
include/hw/virtio/virtio-iommu.h new file +2 -0
+    GHashTable *as_by_busptr;
+    IOMMUPciBus *as_by_bus_num[IOMMU_PCI_BUS_MAX];

Doesn't seem used anymore.

removed

Quoted 4 lines

Thanks,
Jean

Quoted 12 lines
Quoted 11 lines
include/hw/virtio/virtio-iommu.h new file +7 -0
+    PCIBus *primary_bus;
+    GTree *domains;
+    QemuMutex mutex;
+    GTree *endpoints;
+} VirtIOIOMMU;
+
+#endif
Signature · 1 line
2.20.1

Thanks

Eric

author
#10 lore raw

PATCH v11 3/20 virtio-iommu: Decode the command payload

In reply to Eric Auger

This patch adds the command payload decoding and introduces the functions that will do the actual command handling. Those functions are not yet implemented.

---

v10 -> v11:
- use a macro for handle command functions

v9 -> v10:
- make virtio_iommu_handle_* more compact and
remove get_payload_size

v7 -> v8:
- handle new domain parameter in detach
- remove reserved checks

v5 -> v6:
- change map/unmap semantics (remove size)

v4 -> v5:
- adopt new v0.5 terminology

v3 -> v4:
- no flags field anymore in struct virtio_iommu_req_unmap
- test reserved on attach/detach, change trace proto
- rebase on v2.10.0.

---
 hw/virtio/trace-events   |  4 +++
 hw/virtio/virtio-iommu.c | 76 +++++++++++++++++++++++++++++++++-------
 2 files changed, 68 insertions(+), 12 deletions(-)
hw/virtio/trace-events +4 -0
index f7dac39213..c7276116e7 100644
@@ -61,3 +61,7 @@ virtio_iommu_set_features(uint64_t features) "features accepted by the driver =0
 virtio_iommu_device_status(uint8_t status) "driver status = %d"
 virtio_iommu_get_config(uint64_t page_size_mask, uint64_t start, uint64_t end, uint32_t domain_range, uint32_t probe_size) "page_size_mask=0x%"PRIx64" start=0x%"PRIx64" end=0x%"PRIx64" domain_range=%d probe_size=0x%x"
 virtio_iommu_set_config(uint64_t page_size_mask, uint64_t start, uint64_t end, uint32_t domain_range, uint32_t probe_size) "page_size_mask=0x%"PRIx64" start=0x%"PRIx64" end=0x%"PRIx64" domain_bits=%d probe_size=0x%x"
+virtio_iommu_attach(uint32_t domain_id, uint32_t ep_id) "domain=%d endpoint=%d"
+virtio_iommu_detach(uint32_t domain_id, uint32_t ep_id) "domain=%d endpoint=%d"
+virtio_iommu_map(uint32_t domain_id, uint64_t virt_start, uint64_t virt_end, uint64_t phys_start, uint32_t flags) "domain=%d virt_start=0x%"PRIx64" virt_end=0x%"PRIx64 " phys_start=0x%"PRIx64" flags=%d"
+virtio_iommu_unmap(uint32_t domain_id, uint64_t virt_start, uint64_t virt_end) "domain=%d virt_start=0x%"PRIx64" virt_end=0x%"PRIx64
hw/virtio/virtio-iommu.c +64 -12

95 lines not on this page · raw message

Signature · 1 line
2.20.1
Reviewed-by on v11 3/20
#11 lore raw

Re: [PATCH for-5.0 v11 03/20] virtio-iommu: Decode the command payload

Quoted 5 lines · Eric Auger

This patch adds the command payload decoding and introduces the functions that will do the actual command handling. Those functions are not yet implemented.

Which isn't worth much since I don't have prior QEMU experience but I did stare at this code for a while and work on future extensions.

Thanks,
Jean

Reviewed-by on v11 3/20
#12 lore raw

Re: [PATCH for-5.0 v11 03/20] virtio-iommu: Decode the command payload

In reply to Eric Auger
Quoted 5 lines · Eric Auger

This patch adds the command payload decoding and introduces the functions that will do the actual command handling. Those functions are not yet implemented.

I would simply squash this into previous patch to avoid removing lines from newly introduced, but this is ok too so to keep Jean's r-b:

Signature · 1 line
Peter Xu
author
#13 lore raw

PATCH v11 4/20 virtio-iommu: Add the iommu regions

In reply to Eric Auger

This patch initializes the iommu memory regions so that PCIe end point transactions get translated. The translation function is not yet implemented though.

---

v10 -> v11:
- use g_hash_table_new_full for allocating as_by_busptr

v9 -> v10:
- remove pc/virt machine headers
- virtio_iommu_find_add_as: mr_index introduced in that patch and name properly freed

v6 -> v7:
- use primary_bus
- rebase on new translate proto featuring iommu_idx

v5 -> v6:
- include qapi/error.h
- fix g_hash_table_lookup key in virtio_iommu_find_add_as

v4 -> v5:
- use PCI bus handle as a key
- use get_primary_pci_bus() callback

v3 -> v4:
- add trace_virtio_iommu_init_iommu_mr

v2 -> v3:
- use IOMMUMemoryRegion
- iommu mr name built with BDF
- rename smmu_get_sid into virtio_iommu_get_sid and use PCI_BUILD_BDF

---
 hw/virtio/trace-events           |  2 +
 hw/virtio/virtio-iommu.c         | 92 ++++++++++++++++++++++++++++++++
 include/hw/virtio/virtio-iommu.h |  2 +
 3 files changed, 96 insertions(+)
hw/virtio/trace-events +2 -0
index c7276116e7..b32169d56c 100644
@@ -65,3 +65,5 @@ virtio_iommu_attach(uint32_t domain_id, uint32_t ep_id) "domain=%d endpoint=%d"
 virtio_iommu_detach(uint32_t domain_id, uint32_t ep_id) "domain=%d endpoint=%d"
 virtio_iommu_map(uint32_t domain_id, uint64_t virt_start, uint64_t virt_end, uint64_t phys_start, uint32_t flags) "domain=%d virt_start=0x%"PRIx64" virt_end=0x%"PRIx64 " phys_start=0x%"PRIx64" flags=%d"
 virtio_iommu_unmap(uint32_t domain_id, uint64_t virt_start, uint64_t virt_end) "domain=%d virt_start=0x%"PRIx64" virt_end=0x%"PRIx64
+virtio_iommu_translate(const char *name, uint32_t rid, uint64_t iova, int flag) "mr=%s rid=%d addr=0x%"PRIx64" flag=%d"
+virtio_iommu_init_iommu_mr(char *iommu_mr) "init %s"
hw/virtio/virtio-iommu.c +92 -0

131 lines not on this page · raw message

include/hw/virtio/virtio-iommu.h +2 -0
index 4d47b6abeb..f55f48d304 100644
@@ -28,6 +28,8 @@
 #define VIRTIO_IOMMU(obj) \
         OBJECT_CHECK(VirtIOIOMMU, (obj), TYPE_VIRTIO_IOMMU)
 
+#define TYPE_VIRTIO_IOMMU_MEMORY_REGION "virtio-iommu-memory-region"
+
 #define IOMMU_PCI_BUS_MAX      256
 #define IOMMU_PCI_DEVFN_MAX    256
 
Signature · 1 line
2.20.1
Reviewed-by on v11 4/20
#14 lore raw

Re: [PATCH for-5.0 v11 04/20] virtio-iommu: Add the iommu regions

Two small things below, but looks good overall

Quoted 15 lines · Eric Auger
hw/virtio/virtio-iommu.c +15 -0
+static AddressSpace *virtio_iommu_find_add_as(PCIBus *bus, void *opaque,
+                                              int devfn)
+{
+    VirtIOIOMMU *s = opaque;
+    IOMMUPciBus *sbus = g_hash_table_lookup(s->as_by_busptr, bus);
+    static uint32_t mr_index;
+    IOMMUDevice *sdev;
+
+    if (!sbus) {
+        sbus = g_malloc0(sizeof(IOMMUPciBus) +
+                         sizeof(IOMMUDevice *) * IOMMU_PCI_DEVFN_MAX);
+        sbus->bus = bus;
+        g_hash_table_insert(s->as_by_busptr, bus, sbus);
+    }
+

hw/virtio/virtio-iommu.c line 68

Quoted 10 lines
hw/virtio/virtio-iommu.c +10 -0
+    sdev = sbus->pbdev[devfn];
+    if (!sdev) {
+        char *name = g_strdup_printf("%s-%d-%d",
+                                     TYPE_VIRTIO_IOMMU_MEMORY_REGION,
+                                     mr_index++, devfn);
+        sdev = sbus->pbdev[devfn] = g_malloc0(sizeof(IOMMUDevice));
+
+        sdev->viommu = s;
+        sdev->bus = bus;
+        sdev->devfn = devfn;

It might be better to store the endpoint ID in IOMMUDevice, then you could get rid of virtio_iommu_get_sid(), and remove a tiny bit of overhead in virtio_iommu_translate(). But I doubt it's significant.

[...]

hw/virtio/virtio-iommu.c static const TypeInfo virtio_iommu_info = { · line 411

Quoted 7 lines
hw/virtio/virtio-iommu.c +7 -0
+static const TypeInfo virtio_iommu_memory_region_info = {
+    .parent = TYPE_IOMMU_MEMORY_REGION,
+    .name = TYPE_VIRTIO_IOMMU_MEMORY_REGION,
+    .class_init = virtio_iommu_memory_region_class_init,
+};
+
+

nit: newline.

Thanks,
Jean

author
#15 lore raw

Re: [PATCH for-5.0 v11 04/20] virtio-iommu: Add the iommu regions

Hi Jean,

Quoted 26 lines · Jean-Philippe Brucker

Two small things below, but looks good overall

Quoted 21 lines · Eric Auger
hw/virtio/virtio-iommu.c +21 -0
+static AddressSpace *virtio_iommu_find_add_as(PCIBus *bus, void *opaque,
+                                              int devfn)
+{
+    VirtIOIOMMU *s = opaque;
+    IOMMUPciBus *sbus = g_hash_table_lookup(s->as_by_busptr, bus);
+    static uint32_t mr_index;
+    IOMMUDevice *sdev;
+
+    if (!sbus) {
+        sbus = g_malloc0(sizeof(IOMMUPciBus) +
+                         sizeof(IOMMUDevice *) * IOMMU_PCI_DEVFN_MAX);
+        sbus->bus = bus;
+        g_hash_table_insert(s->as_by_busptr, bus, sbus);
+    }
+
+    sdev = sbus->pbdev[devfn];
+    if (!sdev) {
+        char *name = g_strdup_printf("%s-%d-%d",
+                                     TYPE_VIRTIO_IOMMU_MEMORY_REGION,
+                                     mr_index++, devfn);
+        sdev = sbus->pbdev[devfn] = g_malloc0(sizeof(IOMMUDevice));
Quoted 8 lines

hw/virtio/virtio-iommu.c line 68

Quoted 4 lines
hw/virtio/virtio-iommu.c +4 -0
+
+        sdev->viommu = s;
+        sdev->bus = bus;
+        sdev->devfn = devfn;

It might be better to store the endpoint ID in IOMMUDevice, then you could get rid of virtio_iommu_get_sid(), and remove a tiny bit of overhead in virtio_iommu_translate(). But I doubt it's significant.

virtio_iommu_find_add_as() gets called on PCI bus enumeration. At that point, the bus number may not be resolved. So I cannot retrieve and set the bus_number in this function.

When virtio_iommu_get_sid() is called we are sure pci_bus_num(dev->bus) returns a correct value.

Quoted 11 lines

[...]

hw/virtio/virtio-iommu.c static const TypeInfo virtio_iommu_info = { · line 411

Quoted 7 lines
hw/virtio/virtio-iommu.c +7 -0
+static const TypeInfo virtio_iommu_memory_region_info = {
+    .parent = TYPE_IOMMU_MEMORY_REGION,
+    .name = TYPE_VIRTIO_IOMMU_MEMORY_REGION,
+    .class_init = virtio_iommu_memory_region_class_init,
+};
+
+

nit: newline.

Thanks

Eric

Quoted 4 lines

Thanks,
Jean

author
#17 lore raw

PATCH v11 5/20 virtio-iommu: Endpoint and domains structs and helpers

In reply to Eric Auger

This patch introduce domain and endpoint internal datatypes. Both are stored in RB trees. The domain owns a list of endpoints attached to it.

Helpers to get/put end points and domains are introduced. get() helpers will become static in subsequent patches.

---

v10 -> v11:
- fixed interval_cmp (<= -> < and >= -> >)
- removed unused viommu field from endpoint
- removed Bharat's R-b

v9 -> v10:
- added Bharat's R-b

v6 -> v7:
- on virtio_iommu_find_add_as the bus number computation may not be finalized yet so we cannot register the EPs at that time. Hence, let's remove the get_endpoint and also do not use the bus number for building the memory region name string (only used for debug though).

v4 -> v5:
- initialize as->endpoint_list

v3 -> v4:
- new separate patch

---
 hw/virtio/trace-events   |   4 ++
 hw/virtio/virtio-iommu.c | 117 +++++++++++++++++++++++++++++++++++++++
 2 files changed, 121 insertions(+)
hw/virtio/trace-events +4 -0
index b32169d56c..a373bdebb3 100644
@@ -67,3 +67,7 @@ virtio_iommu_map(uint32_t domain_id, uint64_t virt_start, uint64_t virt_end, uin
 virtio_iommu_unmap(uint32_t domain_id, uint64_t virt_start, uint64_t virt_end) "domain=%d virt_start=0x%"PRIx64" virt_end=0x%"PRIx64
 virtio_iommu_translate(const char *name, uint32_t rid, uint64_t iova, int flag) "mr=%s rid=%d addr=0x%"PRIx64" flag=%d"
 virtio_iommu_init_iommu_mr(char *iommu_mr) "init %s"
+virtio_iommu_get_endpoint(uint32_t ep_id) "Alloc endpoint=%d"
+virtio_iommu_put_endpoint(uint32_t ep_id) "Free endpoint=%d"
+virtio_iommu_get_domain(uint32_t domain_id) "Alloc domain=%d"
+virtio_iommu_put_domain(uint32_t domain_id) "Free domain=%d"
hw/virtio/virtio-iommu.c +117 -0

149 lines not on this page · raw message

Signature · 1 line
2.20.1
#18 lore raw

Re: [PATCH for-5.0 v11 05/20] virtio-iommu: Endpoint and domains structs and helpers

hw/virtio/virtio-iommu.c line 51

Quoted 11 lines · Eric Auger
hw/virtio/virtio-iommu.c +11 -0
+typedef struct viommu_domain {
+    uint32_t id;
+    GTree *mappings;
+    QLIST_HEAD(, viommu_endpoint) endpoint_list;
+} viommu_domain;
+
+typedef struct viommu_endpoint {
+    uint32_t id;
+    viommu_domain *domain;
+    QLIST_ENTRY(viommu_endpoint) next;
+} viommu_endpoint;

There might be a way to merge viommu_endpoint and the IOMMUDevice structure introduced in patch 4, since they both represent one endpoint. Maybe virtio_iommu_find_add_pci_as() could add the IOMMUDevice to s->endpoints, and IOMMUDevice could store the endpoint ID rather than bus and devfn.

hw/virtio/virtio-iommu.c line 56

Quoted 4 lines
hw/virtio/virtio-iommu.c +4 -0
+typedef struct viommu_interval {
+    uint64_t low;
+    uint64_t high;
+} viommu_interval;

I guess these should be named in CamelCase? Although if we're allowed to choose my vote goes to underscores :)

Thanks,
Jean

author
#19 lore raw

Re: [PATCH for-5.0 v11 05/20] virtio-iommu: Endpoint and domains structs and helpers

Hi Jean,

Quoted 10 lines · Jean-Philippe Brucker
Quoted 9 lines · Eric Auger
hw/virtio/virtio-iommu.c +9 -0
+typedef struct viommu_domain {
+    uint32_t id;
+    GTree *mappings;
+    QLIST_HEAD(, viommu_endpoint) endpoint_list;
+} viommu_domain;
+
+typedef struct viommu_endpoint {
+    uint32_t id;
+    viommu_domain *domain;
Quoted 8 lines

hw/virtio/virtio-iommu.c line 51

Quoted 2 lines
hw/virtio/virtio-iommu.c +2 -0
+    QLIST_ENTRY(viommu_endpoint) next;
+} viommu_endpoint;

There might be a way to merge viommu_endpoint and the IOMMUDevice structure introduced in patch 4, since they both represent one endpoint. Maybe virtio_iommu_find_add_pci_as() could add the IOMMUDevice to s->endpoints, and IOMMUDevice could store the endpoint ID rather than bus and devfn.

On PCI bus enumeration we locally store the PCI bus hierarchy under the form of GHashTable of IOMMUDevice indexed by iommu_pci_bus pointer. Those are all the devices attached to the downstream buses. We also use an array of iommu pci bus pointers indexed by bus number that is lazily populated due to the fact, at enumeration time we do know the bus number yet. As you pointed, I haven't used the array of iommu pci bus pointers indexed by bus number in this series and I should actually. Currently I am not checking on attach that the sid effectively corresponds to a sid protected by this iommu. I will add this in my next version. The above structures are used in intel_iommu and smmu code as well and I think eventually this may be factorized a common base class..

on the other hand the gtree of viommu_endpoint - soon renamed in CamelCase form ;-) - corresponds to the EPs that are actually attached to any domain. It is indexed by sid and not by bus pointer. This is more adapted to the virtio-iommu case.

So, despite your suggestion, I am tempted to keep the different structures as the first ones are common to all iommu emulation code and the last is adapted to the virtio-iommu operations.

Thoughts?

Eric

Quoted 12 lines

hw/virtio/virtio-iommu.c line 56

Quoted 5 lines
hw/virtio/virtio-iommu.c +4 -0
+typedef struct viommu_interval {
+    uint64_t low;
+    uint64_t high;
+} viommu_interval;

I guess these should be named in CamelCase? Although if we're allowed to choose my vote goes to underscores :)

Thanks,
Jean

#20 lore raw

Re: [PATCH for-5.0 v11 05/20] virtio-iommu: Endpoint and domains structs and helpers

Quoted 39 lines · Auger Eric

Hi Jean,

Quoted 10 lines · Jean-Philippe Brucker
Quoted 9 lines · Eric Auger
hw/virtio/virtio-iommu.c +9 -0
+typedef struct viommu_domain {
+    uint32_t id;
+    GTree *mappings;
+    QLIST_HEAD(, viommu_endpoint) endpoint_list;
+} viommu_domain;
+
+typedef struct viommu_endpoint {
+    uint32_t id;
+    viommu_domain *domain;
Quoted 8 lines

hw/virtio/virtio-iommu.c line 51

Quoted 2 lines
hw/virtio/virtio-iommu.c +2 -0
+    QLIST_ENTRY(viommu_endpoint) next;
+} viommu_endpoint;

There might be a way to merge viommu_endpoint and the IOMMUDevice structure introduced in patch 4, since they both represent one endpoint. Maybe virtio_iommu_find_add_pci_as() could add the IOMMUDevice to s->endpoints, and IOMMUDevice could store the endpoint ID rather than bus and devfn.

On PCI bus enumeration we locally store the PCI bus hierarchy under the form of GHashTable of IOMMUDevice indexed by iommu_pci_bus pointer. Those are all the devices attached to the downstream buses. We also use an array of iommu pci bus pointers indexed by bus number that is lazily populated due to the fact, at enumeration time we do know the bus number yet. As you pointed, I haven't used the array of iommu pci bus pointers indexed by bus number in this series and I should actually. Currently I am not checking on attach that the sid effectively corresponds to a sid protected by this iommu. I will add this in my next version. The above structures are used in intel_iommu and smmu code as well and I think eventually this may be factorized a common base class..

on the other hand the gtree of viommu_endpoint - soon renamed in CamelCase form ;-) - corresponds to the EPs that are actually attached to any domain. It is indexed by sid and not by bus pointer. This is more adapted to the virtio-iommu case.

Quoted 5 lines

So, despite your suggestion, I am tempted to keep the different structures as the first ones are common to all iommu emulation code and the last is adapted to the virtio-iommu operations.

Thoughts?

Makes sense, it seems better to keep them separate. I had missed that the PCI bus number is resolved later, and started to move the endpoint ID into IOMMUDevice when adding MMIO support, but I'll need to revisit this.

I'll be off for two weeks, have a nice holiday!

Thanks,
Jean

author
#21 lore raw

Re: [PATCH for-5.0 v11 05/20] virtio-iommu: Endpoint and domains structs and helpers

Hi Jean,

Quoted 44 lines · Jean-Philippe Brucker
Quoted 43 lines · Auger Eric

Hi Jean,

Quoted 10 lines · Jean-Philippe Brucker
Quoted 9 lines · Eric Auger
hw/virtio/virtio-iommu.c +9 -0
+typedef struct viommu_domain {
+    uint32_t id;
+    GTree *mappings;
+    QLIST_HEAD(, viommu_endpoint) endpoint_list;
+} viommu_domain;
+
+typedef struct viommu_endpoint {
+    uint32_t id;
+    viommu_domain *domain;
Quoted 8 lines

hw/virtio/virtio-iommu.c line 51

Quoted 2 lines
hw/virtio/virtio-iommu.c +2 -0
+    QLIST_ENTRY(viommu_endpoint) next;
+} viommu_endpoint;

There might be a way to merge viommu_endpoint and the IOMMUDevice structure introduced in patch 4, since they both represent one endpoint. Maybe virtio_iommu_find_add_pci_as() could add the IOMMUDevice to s->endpoints, and IOMMUDevice could store the endpoint ID rather than bus and devfn.

On PCI bus enumeration we locally store the PCI bus hierarchy under the form of GHashTable of IOMMUDevice indexed by iommu_pci_bus pointer. Those are all the devices attached to the downstream buses. We also use an array of iommu pci bus pointers indexed by bus number that is lazily populated due to the fact, at enumeration time we do know the bus number yet. As you pointed, I haven't used the array of iommu pci bus pointers indexed by bus number in this series and I should actually. Currently I am not checking on attach that the sid effectively corresponds to a sid protected by this iommu. I will add this in my next version. The above structures are used in intel_iommu and smmu code as well and I think eventually this may be factorized a common base class..

on the other hand the gtree of viommu_endpoint - soon renamed in CamelCase form ;-) - corresponds to the EPs that are actually attached to any domain. It is indexed by sid and not by bus pointer. This is more adapted to the virtio-iommu case.

So, despite your suggestion, I am tempted to keep the different structures as the first ones are common to all iommu emulation code and the last is adapted to the virtio-iommu operations.

Quoted 7 lines
Quoted 1 line

Thoughts?

Makes sense, it seems better to keep them separate. I had missed that the PCI bus number is resolved later, and started to move the endpoint ID into IOMMUDevice when adding MMIO support, but I'll need to revisit this.

I'll be off for two weeks, have a nice holiday!

Thanks, you too.

Merry Christmas! :-)

Eric

Quoted 4 lines

Thanks,
Jean

author
#22 lore raw

PATCH v11 6/20 virtio-iommu: Implement attach/detach command

In reply to Eric Auger

This patch implements the endpoint attach/detach to/from a domain.

---

---
 hw/virtio/virtio-iommu.c | 43 ++++++++++++++++++++++++++++++++--------
 1 file changed, 35 insertions(+), 8 deletions(-)
hw/virtio/virtio-iommu.c +35 -8
index 235bde2203..138d5b2a9c 100644
@@ -77,11 +77,12 @@ static gint interval_cmp(gconstpointer a, gconstpointer b, gpointer user_data)
 static void virtio_iommu_detach_endpoint_from_domain(viommu_endpoint *ep)
 {
     QLIST_REMOVE(ep, next);
+    g_tree_unref(ep->domain->mappings);
     ep->domain = NULL;
 }
 
-viommu_endpoint *virtio_iommu_get_endpoint(VirtIOIOMMU *s, uint32_t ep_id);
-viommu_endpoint *virtio_iommu_get_endpoint(VirtIOIOMMU *s, uint32_t ep_id)
+static viommu_endpoint *virtio_iommu_get_endpoint(VirtIOIOMMU *s,
+                                                  uint32_t ep_id)
 {
     viommu_endpoint *ep;
 
@@ -102,15 +103,14 @@ static void virtio_iommu_put_endpoint(gpointer data)
 
     if (ep->domain) {
         virtio_iommu_detach_endpoint_from_domain(ep);
-        g_tree_unref(ep->domain->mappings);
     }
 
     trace_virtio_iommu_put_endpoint(ep->id);
     g_free(ep);
 }
 
-viommu_domain *virtio_iommu_get_domain(VirtIOIOMMU *s, uint32_t domain_id);
-viommu_domain *virtio_iommu_get_domain(VirtIOIOMMU *s, uint32_t domain_id)
+static viommu_domain *virtio_iommu_get_domain(VirtIOIOMMU *s,
+                                              uint32_t domain_id)
 {
     viommu_domain *domain;
 
@@ -137,7 +137,6 @@ static void virtio_iommu_put_domain(gpointer data)
     QLIST_FOREACH_SAFE(iter, &domain->endpoint_list, next, tmp) {
         virtio_iommu_detach_endpoint_from_domain(iter);
     }
-    g_tree_destroy(domain->mappings);
     trace_virtio_iommu_put_domain(domain->id);
     g_free(domain);
 }
@@ -186,10 +185,27 @@ static int virtio_iommu_attach(VirtIOIOMMU *s,
 {
     uint32_t domain_id = le32_to_cpu(req->domain);
     uint32_t ep_id = le32_to_cpu(req->endpoint);
+    viommu_domain *domain;
+    viommu_endpoint *ep;
 
     trace_virtio_iommu_attach(domain_id, ep_id);
 
-    return VIRTIO_IOMMU_S_UNSUPP;
+    ep = virtio_iommu_get_endpoint(s, ep_id);
+    if (ep->domain) {
+        /*
+         * the device is already attached to a domain,
+         * detach it first
+         */
+        virtio_iommu_detach_endpoint_from_domain(ep);
+    }
+
+    domain = virtio_iommu_get_domain(s, domain_id);
+    QLIST_INSERT_HEAD(&domain->endpoint_list, ep, next);
+
+    ep->domain = domain;
+    g_tree_ref(domain->mappings);
+
+    return VIRTIO_IOMMU_S_OK;
 }
 
 static int virtio_iommu_detach(VirtIOIOMMU *s,
@@ -197,10 +213,21 @@ static int virtio_iommu_detach(VirtIOIOMMU *s,
 {
     uint32_t domain_id = le32_to_cpu(req->domain);
     uint32_t ep_id = le32_to_cpu(req->endpoint);
+    viommu_endpoint *ep;
 
     trace_virtio_iommu_detach(domain_id, ep_id);
 
-    return VIRTIO_IOMMU_S_UNSUPP;
+    ep = g_tree_lookup(s->endpoints, GUINT_TO_POINTER(ep_id));
+    if (!ep) {
+        return VIRTIO_IOMMU_S_NOENT;
+    }
+
+    if (!ep->domain) {
+        return VIRTIO_IOMMU_S_INVAL;
+    }
+
+    virtio_iommu_detach_endpoint_from_domain(ep);
+    return VIRTIO_IOMMU_S_OK;
 }
 
 static int virtio_iommu_map(VirtIOIOMMU *s,
Signature · 1 line
2.20.1
#23 lore raw

Re: [PATCH for-5.0 v11 06/20] virtio-iommu: Implement attach/detach command

Quoted 24 lines · Eric Auger
hw/virtio/virtio-iommu.c +3 -3
index 235bde2203..138d5b2a9c 100644
@@ -77,11 +77,12 @@ static gint interval_cmp(gconstpointer a, gconstpointer b, gpointer user_data)
 static void virtio_iommu_detach_endpoint_from_domain(viommu_endpoint *ep)
 {
     QLIST_REMOVE(ep, next);
+    g_tree_unref(ep->domain->mappings);
     ep->domain = NULL;
 }
 
-viommu_endpoint *virtio_iommu_get_endpoint(VirtIOIOMMU *s, uint32_t ep_id);
-viommu_endpoint *virtio_iommu_get_endpoint(VirtIOIOMMU *s, uint32_t ep_id)
+static viommu_endpoint *virtio_iommu_get_endpoint(VirtIOIOMMU *s,
+                                                  uint32_t ep_id)
 {
     viommu_endpoint *ep;
 
@@ -102,15 +103,14 @@ static void virtio_iommu_put_endpoint(gpointer data)
 
     if (ep->domain) {
         virtio_iommu_detach_endpoint_from_domain(ep);
-        g_tree_unref(ep->domain->mappings);

hw/virtio/virtio-iommu.c static void virtio_iommu_put_endpoint(gpointer data) · line 113

Quoted 10 lines
hw/virtio/virtio-iommu.c +2 -2
     }
 
     trace_virtio_iommu_put_endpoint(ep->id);
     g_free(ep);
 }
 
-viommu_domain *virtio_iommu_get_domain(VirtIOIOMMU *s, uint32_t domain_id);
-viommu_domain *virtio_iommu_get_domain(VirtIOIOMMU *s, uint32_t domain_id)
+static viommu_domain *virtio_iommu_get_domain(VirtIOIOMMU *s,
+                                              uint32_t domain_id)

Looks like the above change belong to patch 5?

hw/virtio/virtio-iommu.c static void virtio_iommu_put_domain(gpointer data) · line 140

Quoted 8 lines
hw/virtio/virtio-iommu.c +0 -1
 {
     viommu_domain *domain;
 
@@ -137,7 +137,6 @@ static void virtio_iommu_put_domain(gpointer data)
     QLIST_FOREACH_SAFE(iter, &domain->endpoint_list, next, tmp) {
         virtio_iommu_detach_endpoint_from_domain(iter);
     }
-    g_tree_destroy(domain->mappings);

When created by virtio_iommu_get_domain(), mappings has one reference. Then for each attach (including the first one) an additional reference is taken, and freed by virtio_iommu_detach_endpoint_from_domain(). So I think there are two problems:

* virtio_iommu_put_domain() drops one ref for each endpoint, but we still have one reference to mappings, so they're not freed. We do need this g_tree_destroy()

* After detaching all the endpoints, the guest may reuse the domain ID for another domain, but the previous mappings haven't been erased. Not sure how to fix this using the g_tree refs, because dropping all the references will free the internal tree data and it won't be reusable.

Thanks,
Jean

author
#24 lore raw

Re: [PATCH for-5.0 v11 06/20] virtio-iommu: Implement attach/detach command

Hi Jean,

Quoted 31 lines · Jean-Philippe Brucker
Quoted 30 lines · Eric Auger
hw/virtio/virtio-iommu.c +3 -3
index 235bde2203..138d5b2a9c 100644
@@ -77,11 +77,12 @@ static gint interval_cmp(gconstpointer a, gconstpointer b, gpointer user_data)
 static void virtio_iommu_detach_endpoint_from_domain(viommu_endpoint *ep)
 {
     QLIST_REMOVE(ep, next);
+    g_tree_unref(ep->domain->mappings);
     ep->domain = NULL;
 }
 
-viommu_endpoint *virtio_iommu_get_endpoint(VirtIOIOMMU *s, uint32_t ep_id);
-viommu_endpoint *virtio_iommu_get_endpoint(VirtIOIOMMU *s, uint32_t ep_id)
+static viommu_endpoint *virtio_iommu_get_endpoint(VirtIOIOMMU *s,
+                                                  uint32_t ep_id)
 {
     viommu_endpoint *ep;
 
@@ -102,15 +103,14 @@ static void virtio_iommu_put_endpoint(gpointer data)
 
     if (ep->domain) {
         virtio_iommu_detach_endpoint_from_domain(ep);
-        g_tree_unref(ep->domain->mappings);
     }
 
     trace_virtio_iommu_put_endpoint(ep->id);
     g_free(ep);
 }
 
Quoted 6 lines

hw/virtio/virtio-iommu.c static void virtio_iommu_put_endpoint(gpointer data) · line 113

Quoted 4 lines
hw/virtio/virtio-iommu.c +2 -2
-viommu_domain *virtio_iommu_get_domain(VirtIOIOMMU *s, uint32_t domain_id);
-viommu_domain *virtio_iommu_get_domain(VirtIOIOMMU *s, uint32_t domain_id)
+static viommu_domain *virtio_iommu_get_domain(VirtIOIOMMU *s,
+                                              uint32_t domain_id)

Looks like the above change belong to patch 5?

virtio_iommu_get_domain was not used yet in last patch. I turn it into static now it gets used.

Quoted 15 lines

hw/virtio/virtio-iommu.c static void virtio_iommu_put_domain(gpointer data) · line 140

Quoted 9 lines
hw/virtio/virtio-iommu.c +0 -1
 {
     viommu_domain *domain;
 
@@ -137,7 +137,6 @@ static void virtio_iommu_put_domain(gpointer data)
     QLIST_FOREACH_SAFE(iter, &domain->endpoint_list, next, tmp) {
         virtio_iommu_detach_endpoint_from_domain(iter);
     }
-    g_tree_destroy(domain->mappings);

When created by virtio_iommu_get_domain(), mappings has one reference. Then for each attach (including the first one) an additional reference is taken, and freed by virtio_iommu_detach_endpoint_from_domain(). So I think there are two problems:

Quoted 8 lines

* virtio_iommu_put_domain() drops one ref for each endpoint, but we still have one reference to mappings, so they're not freed. We do need this g_tree_destroy()

* After detaching all the endpoints, the guest may reuse the domain ID for another domain, but the previous mappings haven't been erased. Not sure how to fix this using the g_tree refs, because dropping all the references will free the internal tree data and it won't be reusable.

You're perfectly right, mappings were not destroyed and I missed that. So I made 2 modifications:
- do not increment the ref count on the first EP addition
- destroy the domain when its EP list get empty.

Thanks

Eric

Quoted 4 lines

Thanks,
Jean

author
#25 lore raw

PATCH v11 7/20 virtio-iommu: Implement map/unmap

In reply to Eric Auger

This patch implements virtio_iommu_map/unmap.

---

v10 -> v11:
- revisit the implementation of unmap according to Peter's suggestion
- removed virt_addr and size from viommu_mapping struct
- use g_tree_lookup_extended()
- return VIRTIO_IOMMU_S_RANGE in case a mapping were
to be split on unmap (instead of INVAL)

v5 -> v6:
- use new v0.6 fields
- replace error_report by qemu_log_mask

v3 -> v4:
- implement unmap semantics as specified in v0.4

---
 hw/virtio/trace-events   |  1 +
 hw/virtio/virtio-iommu.c | 65 ++++++++++++++++++++++++++++++++++++++--
 2 files changed, 64 insertions(+), 2 deletions(-)
hw/virtio/trace-events +1 -0
index a373bdebb3..f25359cee2 100644
@@ -65,6 +65,7 @@ virtio_iommu_attach(uint32_t domain_id, uint32_t ep_id) "domain=%d endpoint=%d"
 virtio_iommu_detach(uint32_t domain_id, uint32_t ep_id) "domain=%d endpoint=%d"
 virtio_iommu_map(uint32_t domain_id, uint64_t virt_start, uint64_t virt_end, uint64_t phys_start, uint32_t flags) "domain=%d virt_start=0x%"PRIx64" virt_end=0x%"PRIx64 " phys_start=0x%"PRIx64" flags=%d"
 virtio_iommu_unmap(uint32_t domain_id, uint64_t virt_start, uint64_t virt_end) "domain=%d virt_start=0x%"PRIx64" virt_end=0x%"PRIx64
+virtio_iommu_unmap_done(uint32_t domain_id, uint64_t virt_start, uint64_t virt_end) "domain=%d virt_start=0x%"PRIx64" virt_end=0x%"PRIx64
 virtio_iommu_translate(const char *name, uint32_t rid, uint64_t iova, int flag) "mr=%s rid=%d addr=0x%"PRIx64" flag=%d"
 virtio_iommu_init_iommu_mr(char *iommu_mr) "init %s"
 virtio_iommu_get_endpoint(uint32_t ep_id) "Alloc endpoint=%d"
hw/virtio/virtio-iommu.c +63 -2

95 lines not on this page · raw message

Signature · 1 line
2.20.1
#26 lore raw

Re: [PATCH for-5.0 v11 07/20] virtio-iommu: Implement map/unmap

hw/virtio/virtio-iommu.c static int virtio_iommu_map(VirtIOIOMMU *s, · line 249

Quoted 7 lines · Eric Auger
hw/virtio/virtio-iommu.c +3 -0
@@ -238,10 +244,35 @@ static int virtio_iommu_map(VirtIOIOMMU *s,
     uint64_t virt_start = le64_to_cpu(req->virt_start);
     uint64_t virt_end = le64_to_cpu(req->virt_end);
     uint32_t flags = le32_to_cpu(req->flags);
+    viommu_domain *domain;
+    viommu_interval *interval;
+    viommu_mapping *mapping;

Additional checks would be good. Most importantly we need to return S_INVAL if we don't recognize a bit in flags (a MUST in the spec). It might be good to check that addresses are aligned on the page granule as well, and return S_RANGE if they aren't (a SHOULD in the spec), but I don't care as much.

hw/virtio/virtio-iommu.c static int virtio_iommu_map(VirtIOIOMMU *s, · line 258

Quoted 9 lines
hw/virtio/virtio-iommu.c +9 -0
+
+    interval = g_malloc0(sizeof(*interval));
+
+    interval->low = virt_start;
+    interval->high = virt_end;
+
+    domain = g_tree_lookup(s->domains, GUINT_TO_POINTER(domain_id));
+    if (!domain) {
+        return VIRTIO_IOMMU_S_NOENT;

Leaks interval, I guess you could allocate it after this block.

Thanks,
Jean

Quoted 18 lines
hw/virtio/virtio-iommu.c +14 -1
+    }
+
+    mapping = g_tree_lookup(domain->mappings, (gpointer)interval);
+    if (mapping) {
+        g_free(interval);
+        return VIRTIO_IOMMU_S_INVAL;
+    }
 
     trace_virtio_iommu_map(domain_id, virt_start, virt_end, phys_start, flags);
 
-    return VIRTIO_IOMMU_S_UNSUPP;
+    mapping = g_malloc0(sizeof(*mapping));
+    mapping->phys_addr = phys_start;
+    mapping->flags = flags;
+
+    g_tree_insert(domain->mappings, interval, mapping);
+
+    return VIRTIO_IOMMU_S_OK;
author
#27 lore raw

Re: [PATCH for-5.0 v11 07/20] virtio-iommu: Implement map/unmap

Hi jean,

Quoted 11 lines · Jean-Philippe Brucker

hw/virtio/virtio-iommu.c static int virtio_iommu_map(VirtIOIOMMU *s, · line 249

Quoted 7 lines · Eric Auger
hw/virtio/virtio-iommu.c +3 -0
@@ -238,10 +244,35 @@ static int virtio_iommu_map(VirtIOIOMMU *s,
     uint64_t virt_start = le64_to_cpu(req->virt_start);
     uint64_t virt_end = le64_to_cpu(req->virt_end);
     uint32_t flags = le32_to_cpu(req->flags);
+    viommu_domain *domain;
+    viommu_interval *interval;
+    viommu_mapping *mapping;

Additional checks would be good. Most importantly we need to return S_INVAL if we don't recognize a bit in flags (a MUST in the spec).

Sure

It

Quoted 3 lines

might be good to check that addresses are aligned on the page granule as well, and return S_RANGE if they aren't (a SHOULD in the spec), but I don't care as much.

with KVM accelerated guest I don't have access to the guest page size, hence the choice of not checking it.

Quoted 12 lines

hw/virtio/virtio-iommu.c static int virtio_iommu_map(VirtIOIOMMU *s, · line 258

Quoted 10 lines
hw/virtio/virtio-iommu.c +9 -0
+
+    interval = g_malloc0(sizeof(*interval));
+
+    interval->low = virt_start;
+    interval->high = virt_end;
+
+    domain = g_tree_lookup(s->domains, GUINT_TO_POINTER(domain_id));
+    if (!domain) {
+        return VIRTIO_IOMMU_S_NOENT;

Leaks interval, I guess you could allocate it after this block.

Sure

Thanks!

Eric

Quoted 23 lines

Thanks,
Jean

Quoted 18 lines
hw/virtio/virtio-iommu.c +14 -1
+    }
+
+    mapping = g_tree_lookup(domain->mappings, (gpointer)interval);
+    if (mapping) {
+        g_free(interval);
+        return VIRTIO_IOMMU_S_INVAL;
+    }
 
     trace_virtio_iommu_map(domain_id, virt_start, virt_end, phys_start, flags);
 
-    return VIRTIO_IOMMU_S_UNSUPP;
+    mapping = g_malloc0(sizeof(*mapping));
+    mapping->phys_addr = phys_start;
+    mapping->flags = flags;
+
+    g_tree_insert(domain->mappings, interval, mapping);
+
+    return VIRTIO_IOMMU_S_OK;
author
#28 lore raw

PATCH v11 8/20 virtio-iommu: Implement translate

In reply to Eric Auger

This patch implements the translate callback

---

v10 -> v11:
- take into account the new value struct and use
g_tree_lookup_extended
- switched to error_report_once

v6 -> v7:
- implemented bypass-mode

v5 -> v6:
- replace error_report by qemu_log_mask

v4 -> v5:
- check the device domain is not NULL
- s/printf/error_report
- set flags to IOMMU_NONE in case of all translation faults

---
 hw/virtio/trace-events   |  1 +
 hw/virtio/virtio-iommu.c | 63 +++++++++++++++++++++++++++++++++++++++-
 2 files changed, 63 insertions(+), 1 deletion(-)
hw/virtio/trace-events +1 -0
index f25359cee2..de7cbb3c8f 100644
@@ -72,3 +72,4 @@ virtio_iommu_get_endpoint(uint32_t ep_id) "Alloc endpoint=%d"
 virtio_iommu_put_endpoint(uint32_t ep_id) "Free endpoint=%d"
 virtio_iommu_get_domain(uint32_t domain_id) "Alloc domain=%d"
 virtio_iommu_put_domain(uint32_t domain_id) "Free domain=%d"
+virtio_iommu_translate_out(uint64_t virt_addr, uint64_t phys_addr, uint32_t sid) "0x%"PRIx64" -> 0x%"PRIx64 " for sid=%d"
hw/virtio/virtio-iommu.c +62 -1

81 lines not on this page · raw message

Signature · 1 line
2.20.1
#30 lore raw

Re: [PATCH for-5.0 v11 08/20] virtio-iommu: Implement translate

In reply to Eric Auger
Quoted 56 lines · Eric Auger

This patch implements the translate callback

---

v10 -> v11:
- take into account the new value struct and use
g_tree_lookup_extended
- switched to error_report_once

v6 -> v7:
- implemented bypass-mode

v5 -> v6:
- replace error_report by qemu_log_mask

v4 -> v5:
- check the device domain is not NULL
- s/printf/error_report
- set flags to IOMMU_NONE in case of all translation faults

---
 hw/virtio/trace-events   |  1 +
 hw/virtio/virtio-iommu.c | 63 +++++++++++++++++++++++++++++++++++++++-
 2 files changed, 63 insertions(+), 1 deletion(-)
hw/virtio/trace-events +1 -0
index f25359cee2..de7cbb3c8f 100644
@@ -72,3 +72,4 @@ virtio_iommu_get_endpoint(uint32_t ep_id) "Alloc endpoint=%d"
 virtio_iommu_put_endpoint(uint32_t ep_id) "Free endpoint=%d"
 virtio_iommu_get_domain(uint32_t domain_id) "Alloc domain=%d"
 virtio_iommu_put_domain(uint32_t domain_id) "Free domain=%d"
+virtio_iommu_translate_out(uint64_t virt_addr, uint64_t phys_addr, uint32_t sid) "0x%"PRIx64" -> 0x%"PRIx64 " for sid=%d"
hw/virtio/virtio-iommu.c +9 -0
index f0a56833a2..a83666557b 100644
@@ -412,19 +412,80 @@ static IOMMUTLBEntry virtio_iommu_translate(IOMMUMemoryRegion *mr, hwaddr addr,
                                             int iommu_idx)
 {
     IOMMUDevice *sdev = container_of(mr, IOMMUDevice, iommu_mr);
+    viommu_interval interval, *mapping_key;
+    viommu_mapping *mapping_value;
+    VirtIOIOMMU *s = sdev->viommu;
+    viommu_endpoint *ep;
+    bool bypass_allowed;
     uint32_t sid;
+    bool found;
+
+    interval.low = addr;
+    interval.high = addr + 1;
 
     IOMMUTLBEntry entry = {
         .target_as = &address_space_memory,

hw/virtio/virtio-iommu.c static IOMMUTLBEntry virtio_iommu_translate(IOMMUMemoryRegion *mr, hwaddr addr, · line 436

Quoted 10 lines
hw/virtio/virtio-iommu.c +4 -1
         .iova = addr,
         .translated_addr = addr,
-        .addr_mask = ~(hwaddr)0,
+        .addr_mask = (1 << ctz32(s->config.page_size_mask)) - 1,
         .perm = IOMMU_NONE,
     };
 
+    bypass_allowed = virtio_has_feature(s->acked_features,
+                                        VIRTIO_IOMMU_F_BYPASS);
+

Would it be easier to check bypass_allowed here once and then drop the latter [1] and [2] check?

hw/virtio/virtio-iommu.c static IOMMUTLBEntry virtio_iommu_translate(IOMMUMemoryRegion *mr, hwaddr addr, · line 444

Quoted 8 lines
hw/virtio/virtio-iommu.c +5 -0
     sid = virtio_iommu_get_sid(sdev);
 
     trace_virtio_iommu_translate(mr->parent_obj.name, sid, addr, flag);
+    qemu_mutex_lock(&s->mutex);
+
+    ep = g_tree_lookup(s->endpoints, GUINT_TO_POINTER(sid));
+    if (!ep) {
+        if (!bypass_allowed) {

[1]

hw/virtio/virtio-iommu.c static IOMMUTLBEntry virtio_iommu_translate(IOMMUMemoryRegion *mr, hwaddr addr, · line 453

Quoted 9 lines
hw/virtio/virtio-iommu.c +9 -0
+            error_report_once("%s sid=%d is not known!!", __func__, sid);
+        } else {
+            entry.perm = flag;
+        }
+        goto unlock;
+    }
+
+    if (!ep->domain) {
+        if (!bypass_allowed) {

[2]

Quoted 7 lines
hw/virtio/virtio-iommu.c +7 -0
+            qemu_log_mask(LOG_GUEST_ERROR,
+                          "%s %02x:%02x.%01x not attached to any domain\n",
+                          __func__, PCI_BUS_NUM(sid),
+                          PCI_SLOT(sid), PCI_FUNC(sid));
+        } else {
+            entry.perm = flag;
+        }

hw/virtio/virtio-iommu.c static IOMMUTLBEntry virtio_iommu_translate(IOMMUMemoryRegion *mr, hwaddr addr, · line 470

Quoted 10 lines
hw/virtio/virtio-iommu.c +10 -0
+        goto unlock;
+    }
+
+    found = g_tree_lookup_extended(ep->domain->mappings, (gpointer)(&interval),
+                                   (void **)&mapping_key,
+                                   (void **)&mapping_value);
+    if (!found) {
+        qemu_log_mask(LOG_GUEST_ERROR,
+                      "%s no mapping for 0x%"PRIx64" for sid=%d\n",
+                      __func__, addr, sid);

I would still suggest that we use the same logging interface (either error_report_once() or qemu_log_mask(), not use them randomly).

hw/virtio/virtio-iommu.c static IOMMUTLBEntry virtio_iommu_translate(IOMMUMemoryRegion *mr, hwaddr addr, · line 480

Quoted 10 lines
hw/virtio/virtio-iommu.c +10 -0
+        goto unlock;
+    }
+
+    if (((flag & IOMMU_RO) &&
+            !(mapping_value->flags & VIRTIO_IOMMU_MAP_F_READ)) ||
+        ((flag & IOMMU_WO) &&
+            !(mapping_value->flags & VIRTIO_IOMMU_MAP_F_WRITE))) {
+        qemu_log_mask(LOG_GUEST_ERROR,
+                      "Permission error on 0x%"PRIx64"(%d): allowed=%d\n",
+                      addr, flag, mapping_value->flags);

(Btw, IIUC this may not be a guest error. Say, what if the device is
simply broken?)

Quoted 14 lines
hw/virtio/virtio-iommu.c +8 -0
+        goto unlock;
+    }
+    entry.translated_addr = addr - mapping_key->low + mapping_value->phys_addr;
+    entry.perm = flag;
+    trace_virtio_iommu_translate_out(addr, entry.translated_addr, sid);
+
+unlock:
+    qemu_mutex_unlock(&s->mutex);
     return entry;
 }
 
Signature · 1 line
2.20.1
Signature · 1 line
Peter Xu
author
#31 lore raw

Re: [PATCH for-5.0 v11 08/20] virtio-iommu: Implement translate

Hi Peter,

Quoted 64 lines · Peter Xu
Quoted 63 lines · Eric Auger

This patch implements the translate callback

---

v10 -> v11:
- take into account the new value struct and use
g_tree_lookup_extended
- switched to error_report_once

v6 -> v7:
- implemented bypass-mode

v5 -> v6:
- replace error_report by qemu_log_mask

v4 -> v5:
- check the device domain is not NULL
- s/printf/error_report
- set flags to IOMMU_NONE in case of all translation faults

---
 hw/virtio/trace-events   |  1 +
 hw/virtio/virtio-iommu.c | 63 +++++++++++++++++++++++++++++++++++++++-
 2 files changed, 63 insertions(+), 1 deletion(-)
hw/virtio/trace-events +1 -0
index f25359cee2..de7cbb3c8f 100644
@@ -72,3 +72,4 @@ virtio_iommu_get_endpoint(uint32_t ep_id) "Alloc endpoint=%d"
 virtio_iommu_put_endpoint(uint32_t ep_id) "Free endpoint=%d"
 virtio_iommu_get_domain(uint32_t domain_id) "Alloc domain=%d"
 virtio_iommu_put_domain(uint32_t domain_id) "Free domain=%d"
+virtio_iommu_translate_out(uint64_t virt_addr, uint64_t phys_addr, uint32_t sid) "0x%"PRIx64" -> 0x%"PRIx64 " for sid=%d"
hw/virtio/virtio-iommu.c +10 -1
index f0a56833a2..a83666557b 100644
@@ -412,19 +412,80 @@ static IOMMUTLBEntry virtio_iommu_translate(IOMMUMemoryRegion *mr, hwaddr addr,
                                             int iommu_idx)
 {
     IOMMUDevice *sdev = container_of(mr, IOMMUDevice, iommu_mr);
+    viommu_interval interval, *mapping_key;
+    viommu_mapping *mapping_value;
+    VirtIOIOMMU *s = sdev->viommu;
+    viommu_endpoint *ep;
+    bool bypass_allowed;
     uint32_t sid;
+    bool found;
+
+    interval.low = addr;
+    interval.high = addr + 1;
 
     IOMMUTLBEntry entry = {
         .target_as = &address_space_memory,
         .iova = addr,
         .translated_addr = addr,
-        .addr_mask = ~(hwaddr)0,
+        .addr_mask = (1 << ctz32(s->config.page_size_mask)) - 1,
         .perm = IOMMU_NONE,
     };
 
Quoted 6 lines

hw/virtio/virtio-iommu.c static IOMMUTLBEntry virtio_iommu_translate(IOMMUMemoryRegion *mr, hwaddr addr, · line 436

Quoted 3 lines
hw/virtio/virtio-iommu.c +3 -0
+    bypass_allowed = virtio_has_feature(s->acked_features,
+                                        VIRTIO_IOMMU_F_BYPASS);
+

Would it be easier to check bypass_allowed here once and then drop the latter [1] and [2] check?

bypass_allowed does not mean you systematically bypass. You bypass if the SID is unknown or if the device is not attached to any domain. Otherwise you translate. But maybe I miss your point.

Quoted 42 lines

hw/virtio/virtio-iommu.c static IOMMUTLBEntry virtio_iommu_translate(IOMMUMemoryRegion *mr, hwaddr addr, · line 444

Quoted 9 lines
hw/virtio/virtio-iommu.c +5 -0
     sid = virtio_iommu_get_sid(sdev);
 
     trace_virtio_iommu_translate(mr->parent_obj.name, sid, addr, flag);
+    qemu_mutex_lock(&s->mutex);
+
+    ep = g_tree_lookup(s->endpoints, GUINT_TO_POINTER(sid));
+    if (!ep) {
+        if (!bypass_allowed) {

[1]

hw/virtio/virtio-iommu.c static IOMMUTLBEntry virtio_iommu_translate(IOMMUMemoryRegion *mr, hwaddr addr, · line 453

Quoted 9 lines
hw/virtio/virtio-iommu.c +9 -0
+            error_report_once("%s sid=%d is not known!!", __func__, sid);
+        } else {
+            entry.perm = flag;
+        }
+        goto unlock;
+    }
+
+    if (!ep->domain) {
+        if (!bypass_allowed) {

[2]

Quoted 7 lines
hw/virtio/virtio-iommu.c +7 -0
+            qemu_log_mask(LOG_GUEST_ERROR,
+                          "%s %02x:%02x.%01x not attached to any domain\n",
+                          __func__, PCI_BUS_NUM(sid),
+                          PCI_SLOT(sid), PCI_FUNC(sid));
+        } else {
+            entry.perm = flag;
+        }

hw/virtio/virtio-iommu.c static IOMMUTLBEntry virtio_iommu_translate(IOMMUMemoryRegion *mr, hwaddr addr, · line 470

Quoted 10 lines
hw/virtio/virtio-iommu.c +10 -0
+        goto unlock;
+    }
+
+    found = g_tree_lookup_extended(ep->domain->mappings, (gpointer)(&interval),
+                                   (void **)&mapping_key,
+                                   (void **)&mapping_value);
+    if (!found) {
+        qemu_log_mask(LOG_GUEST_ERROR,
+                      "%s no mapping for 0x%"PRIx64" for sid=%d\n",
+                      __func__, addr, sid);
Quoted 2 lines

I would still suggest that we use the same logging interface (either error_report_once() or qemu_log_mask(), not use them randomly).

OK I will switch to error_report_once() then

Quoted 26 lines

hw/virtio/virtio-iommu.c static IOMMUTLBEntry virtio_iommu_translate(IOMMUMemoryRegion *mr, hwaddr addr, · line 480

Quoted 11 lines
hw/virtio/virtio-iommu.c +10 -0
+        goto unlock;
+    }
+
+    if (((flag & IOMMU_RO) &&
+            !(mapping_value->flags & VIRTIO_IOMMU_MAP_F_READ)) ||
+        ((flag & IOMMU_WO) &&
+            !(mapping_value->flags & VIRTIO_IOMMU_MAP_F_WRITE))) {
+        qemu_log_mask(LOG_GUEST_ERROR,
+                      "Permission error on 0x%"PRIx64"(%d): allowed=%d\n",
+                      addr, flag, mapping_value->flags);

(Btw, IIUC this may not be a guest error. Say, what if the device is
simply broken?)

Quoted 11 lines
hw/virtio/virtio-iommu.c +8 -0
+        goto unlock;
+    }
+    entry.translated_addr = addr - mapping_key->low + mapping_value->phys_addr;
+    entry.perm = flag;
+    trace_virtio_iommu_translate_out(addr, entry.translated_addr, sid);
+
+unlock:
+    qemu_mutex_unlock(&s->mutex);
     return entry;
 }
 
Quoted 4 lines
Quoted 3 lines
Signature · 1 line
2.20.1

Thanks

Eric

#32 lore raw

Re: [PATCH for-5.0 v11 08/20] virtio-iommu: Implement translate

Quoted 72 lines · Auger Eric

Hi Peter,

Quoted 64 lines · Peter Xu
Quoted 63 lines · Eric Auger

This patch implements the translate callback

---

v10 -> v11:
- take into account the new value struct and use
g_tree_lookup_extended
- switched to error_report_once

v6 -> v7:
- implemented bypass-mode

v5 -> v6:
- replace error_report by qemu_log_mask

v4 -> v5:
- check the device domain is not NULL
- s/printf/error_report
- set flags to IOMMU_NONE in case of all translation faults

---
 hw/virtio/trace-events   |  1 +
 hw/virtio/virtio-iommu.c | 63 +++++++++++++++++++++++++++++++++++++++-
 2 files changed, 63 insertions(+), 1 deletion(-)
hw/virtio/trace-events +1 -0
index f25359cee2..de7cbb3c8f 100644
@@ -72,3 +72,4 @@ virtio_iommu_get_endpoint(uint32_t ep_id) "Alloc endpoint=%d"
 virtio_iommu_put_endpoint(uint32_t ep_id) "Free endpoint=%d"
 virtio_iommu_get_domain(uint32_t domain_id) "Alloc domain=%d"
 virtio_iommu_put_domain(uint32_t domain_id) "Free domain=%d"
+virtio_iommu_translate_out(uint64_t virt_addr, uint64_t phys_addr, uint32_t sid) "0x%"PRIx64" -> 0x%"PRIx64 " for sid=%d"
hw/virtio/virtio-iommu.c +10 -1
index f0a56833a2..a83666557b 100644
@@ -412,19 +412,80 @@ static IOMMUTLBEntry virtio_iommu_translate(IOMMUMemoryRegion *mr, hwaddr addr,
                                             int iommu_idx)
 {
     IOMMUDevice *sdev = container_of(mr, IOMMUDevice, iommu_mr);
+    viommu_interval interval, *mapping_key;
+    viommu_mapping *mapping_value;
+    VirtIOIOMMU *s = sdev->viommu;
+    viommu_endpoint *ep;
+    bool bypass_allowed;
     uint32_t sid;
+    bool found;
+
+    interval.low = addr;
+    interval.high = addr + 1;
 
     IOMMUTLBEntry entry = {
         .target_as = &address_space_memory,
         .iova = addr,
         .translated_addr = addr,
-        .addr_mask = ~(hwaddr)0,
+        .addr_mask = (1 << ctz32(s->config.page_size_mask)) - 1,
         .perm = IOMMU_NONE,
     };
 
Quoted 6 lines

hw/virtio/virtio-iommu.c static IOMMUTLBEntry virtio_iommu_translate(IOMMUMemoryRegion *mr, hwaddr addr, · line 436

Quoted 3 lines
hw/virtio/virtio-iommu.c +3 -0
+    bypass_allowed = virtio_has_feature(s->acked_features,
+                                        VIRTIO_IOMMU_F_BYPASS);
+

Would it be easier to check bypass_allowed here once and then drop the latter [1] and [2] check?

Quoted 3 lines

bypass_allowed does not mean you systematically bypass. You bypass if the SID is unknown or if the device is not attached to any domain. Otherwise you translate. But maybe I miss your point.

Ah ok, then could I ask how will this VIRTIO_IOMMU_F_BYPASS be used? For example, I think VT-d defines passthrough in a totally different way in that the PT mark will be stored in the per-device context entries, then we can allow a specific device to be pass-through when doing DMA. That information is explicit (e.g., unknown SID will always fail the DMA), and per-device.

Here do you mean that you just don't put a device into any domain to show it wants to use PT? Then I'm not sure how do you identify whether this is a legal PT or a malicious device (e.g., an unknown device that even does not have any driver bound to it, which will also satisfy "unknown SID" and "not attached to any domain", iiuc).

Thanks,

Signature · 1 line
Peter Xu
author
#33 lore raw

Re: [PATCH for-5.0 v11 08/20] virtio-iommu: Implement translate

Hi Peter,

Quoted 84 lines · Peter Xu
Quoted 72 lines · Auger Eric

Hi Peter,

Quoted 64 lines · Peter Xu
Quoted 63 lines · Eric Auger

This patch implements the translate callback

---

v10 -> v11:
- take into account the new value struct and use
g_tree_lookup_extended
- switched to error_report_once

v6 -> v7:
- implemented bypass-mode

v5 -> v6:
- replace error_report by qemu_log_mask

v4 -> v5:
- check the device domain is not NULL
- s/printf/error_report
- set flags to IOMMU_NONE in case of all translation faults

---
 hw/virtio/trace-events   |  1 +
 hw/virtio/virtio-iommu.c | 63 +++++++++++++++++++++++++++++++++++++++-
 2 files changed, 63 insertions(+), 1 deletion(-)
hw/virtio/trace-events +1 -0
index f25359cee2..de7cbb3c8f 100644
@@ -72,3 +72,4 @@ virtio_iommu_get_endpoint(uint32_t ep_id) "Alloc endpoint=%d"
 virtio_iommu_put_endpoint(uint32_t ep_id) "Free endpoint=%d"
 virtio_iommu_get_domain(uint32_t domain_id) "Alloc domain=%d"
 virtio_iommu_put_domain(uint32_t domain_id) "Free domain=%d"
+virtio_iommu_translate_out(uint64_t virt_addr, uint64_t phys_addr, uint32_t sid) "0x%"PRIx64" -> 0x%"PRIx64 " for sid=%d"
hw/virtio/virtio-iommu.c +10 -1
index f0a56833a2..a83666557b 100644
@@ -412,19 +412,80 @@ static IOMMUTLBEntry virtio_iommu_translate(IOMMUMemoryRegion *mr, hwaddr addr,
                                             int iommu_idx)
 {
     IOMMUDevice *sdev = container_of(mr, IOMMUDevice, iommu_mr);
+    viommu_interval interval, *mapping_key;
+    viommu_mapping *mapping_value;
+    VirtIOIOMMU *s = sdev->viommu;
+    viommu_endpoint *ep;
+    bool bypass_allowed;
     uint32_t sid;
+    bool found;
+
+    interval.low = addr;
+    interval.high = addr + 1;
 
     IOMMUTLBEntry entry = {
         .target_as = &address_space_memory,
         .iova = addr,
         .translated_addr = addr,
-        .addr_mask = ~(hwaddr)0,
+        .addr_mask = (1 << ctz32(s->config.page_size_mask)) - 1,
         .perm = IOMMU_NONE,
     };
 
Quoted 6 lines

hw/virtio/virtio-iommu.c static IOMMUTLBEntry virtio_iommu_translate(IOMMUMemoryRegion *mr, hwaddr addr, · line 436

Quoted 3 lines
hw/virtio/virtio-iommu.c +3 -0
+    bypass_allowed = virtio_has_feature(s->acked_features,
+                                        VIRTIO_IOMMU_F_BYPASS);
+

Would it be easier to check bypass_allowed here once and then drop the latter [1] and [2] check?

Quoted 3 lines

bypass_allowed does not mean you systematically bypass. You bypass if the SID is unknown or if the device is not attached to any domain. Otherwise you translate. But maybe I miss your point.

Ah ok, then could I ask how will this VIRTIO_IOMMU_F_BYPASS be used? For example, I think VT-d defines passthrough in a totally different way in that the PT mark will be stored in the per-device context entries, then we can allow a specific device to be pass-through when doing DMA. That information is explicit (e.g., unknown SID will always fail the DMA), and per-device.

Quoted 5 lines

Here do you mean that you just don't put a device into any domain to show it wants to use PT? Then I'm not sure how do you identify whether this is a legal PT or a malicious device (e.g., an unknown device that even does not have any driver bound to it, which will also satisfy "unknown SID" and "not attached to any domain", iiuc).

The virtio-iommu spec currently says:

"If the VIRTIO_IOMMU_F_BYPASS feature is negotiated, all accesses from unattached endpoints are
allowed and translated by the IOMMU using the identity function. If the feature is not negotiated, any
memory access from an unattached endpoint fails. Upon attaching an endpoint in bypass mode to a new
domain, any memory access from the endpoint fails, since the domain does not contain any mapping.
"

I guess this can serve the purpose of devices doing early accesses, before the guest OS gets the hand and maps them?

Thanks

Eric

Quoted 3 lines

Thanks,

#34 lore raw

Re: [PATCH for-5.0 v11 08/20] virtio-iommu: Implement translate

Quoted 105 lines · Auger Eric

Hi Peter,

Quoted 84 lines · Peter Xu
Quoted 72 lines · Auger Eric

Hi Peter,

Quoted 64 lines · Peter Xu
Quoted 63 lines · Eric Auger

This patch implements the translate callback

---

v10 -> v11:
- take into account the new value struct and use
g_tree_lookup_extended
- switched to error_report_once

v6 -> v7:
- implemented bypass-mode

v5 -> v6:
- replace error_report by qemu_log_mask

v4 -> v5:
- check the device domain is not NULL
- s/printf/error_report
- set flags to IOMMU_NONE in case of all translation faults

---
 hw/virtio/trace-events   |  1 +
 hw/virtio/virtio-iommu.c | 63 +++++++++++++++++++++++++++++++++++++++-
 2 files changed, 63 insertions(+), 1 deletion(-)
hw/virtio/trace-events +1 -0
index f25359cee2..de7cbb3c8f 100644
@@ -72,3 +72,4 @@ virtio_iommu_get_endpoint(uint32_t ep_id) "Alloc endpoint=%d"
 virtio_iommu_put_endpoint(uint32_t ep_id) "Free endpoint=%d"
 virtio_iommu_get_domain(uint32_t domain_id) "Alloc domain=%d"
 virtio_iommu_put_domain(uint32_t domain_id) "Free domain=%d"
+virtio_iommu_translate_out(uint64_t virt_addr, uint64_t phys_addr, uint32_t sid) "0x%"PRIx64" -> 0x%"PRIx64 " for sid=%d"
hw/virtio/virtio-iommu.c +10 -1
index f0a56833a2..a83666557b 100644
@@ -412,19 +412,80 @@ static IOMMUTLBEntry virtio_iommu_translate(IOMMUMemoryRegion *mr, hwaddr addr,
                                             int iommu_idx)
 {
     IOMMUDevice *sdev = container_of(mr, IOMMUDevice, iommu_mr);
+    viommu_interval interval, *mapping_key;
+    viommu_mapping *mapping_value;
+    VirtIOIOMMU *s = sdev->viommu;
+    viommu_endpoint *ep;
+    bool bypass_allowed;
     uint32_t sid;
+    bool found;
+
+    interval.low = addr;
+    interval.high = addr + 1;
 
     IOMMUTLBEntry entry = {
         .target_as = &address_space_memory,
         .iova = addr,
         .translated_addr = addr,
-        .addr_mask = ~(hwaddr)0,
+        .addr_mask = (1 << ctz32(s->config.page_size_mask)) - 1,
         .perm = IOMMU_NONE,
     };
 
Quoted 6 lines

hw/virtio/virtio-iommu.c static IOMMUTLBEntry virtio_iommu_translate(IOMMUMemoryRegion *mr, hwaddr addr, · line 436

Quoted 3 lines
hw/virtio/virtio-iommu.c +3 -0
+    bypass_allowed = virtio_has_feature(s->acked_features,
+                                        VIRTIO_IOMMU_F_BYPASS);
+

Would it be easier to check bypass_allowed here once and then drop the latter [1] and [2] check?

Quoted 3 lines

bypass_allowed does not mean you systematically bypass. You bypass if the SID is unknown or if the device is not attached to any domain. Otherwise you translate. But maybe I miss your point.

Ah ok, then could I ask how will this VIRTIO_IOMMU_F_BYPASS be used? For example, I think VT-d defines passthrough in a totally different way in that the PT mark will be stored in the per-device context entries, then we can allow a specific device to be pass-through when doing DMA. That information is explicit (e.g., unknown SID will always fail the DMA), and per-device.

Quoted 5 lines

Here do you mean that you just don't put a device into any domain to show it wants to use PT? Then I'm not sure how do you identify whether this is a legal PT or a malicious device (e.g., an unknown device that even does not have any driver bound to it, which will also satisfy "unknown SID" and "not attached to any domain", iiuc).

The virtio-iommu spec currently says:

"If the VIRTIO_IOMMU_F_BYPASS feature is negotiated, all accesses from unattached endpoints are
allowed and translated by the IOMMU using the identity function. If the feature is not negotiated, any
memory access from an unattached endpoint fails. Upon attaching an endpoint in bypass mode to a new
domain, any memory access from the endpoint fails, since the domain does not contain any mapping.
"

Quoted 2 lines

I guess this can serve the purpose of devices doing early accesses, before the guest OS gets the hand and maps them?

OK, so there's no global enablement knob for virtio-iommu? Hmm... Then:

- This flag is a must for all virtio-iommu emulation, right? (otherwise I can't see how system bootstraps..)

- Should this flag be gone right after OS starts (otherwise I think we still have the issue that any malicious device can be seen as in PT mode as default)? How is that done?

Thanks,

Signature · 1 line
Peter Xu
author
#35 lore raw

Re: [PATCH for-5.0 v11 08/20] virtio-iommu: Implement translate

Hi Peter, jean,

Quoted 106 lines · Peter Xu
Quoted 105 lines · Auger Eric

Hi Peter,

Quoted 84 lines · Peter Xu
Quoted 72 lines · Auger Eric

Hi Peter,

Quoted 64 lines · Peter Xu
Quoted 63 lines · Eric Auger

This patch implements the translate callback

---

v10 -> v11:
- take into account the new value struct and use
g_tree_lookup_extended
- switched to error_report_once

v6 -> v7:
- implemented bypass-mode

v5 -> v6:
- replace error_report by qemu_log_mask

v4 -> v5:
- check the device domain is not NULL
- s/printf/error_report
- set flags to IOMMU_NONE in case of all translation faults

---
 hw/virtio/trace-events   |  1 +
 hw/virtio/virtio-iommu.c | 63 +++++++++++++++++++++++++++++++++++++++-
 2 files changed, 63 insertions(+), 1 deletion(-)
hw/virtio/trace-events +1 -0
index f25359cee2..de7cbb3c8f 100644
@@ -72,3 +72,4 @@ virtio_iommu_get_endpoint(uint32_t ep_id) "Alloc endpoint=%d"
 virtio_iommu_put_endpoint(uint32_t ep_id) "Free endpoint=%d"
 virtio_iommu_get_domain(uint32_t domain_id) "Alloc domain=%d"
 virtio_iommu_put_domain(uint32_t domain_id) "Free domain=%d"
+virtio_iommu_translate_out(uint64_t virt_addr, uint64_t phys_addr, uint32_t sid) "0x%"PRIx64" -> 0x%"PRIx64 " for sid=%d"
hw/virtio/virtio-iommu.c +10 -1
index f0a56833a2..a83666557b 100644
@@ -412,19 +412,80 @@ static IOMMUTLBEntry virtio_iommu_translate(IOMMUMemoryRegion *mr, hwaddr addr,
                                             int iommu_idx)
 {
     IOMMUDevice *sdev = container_of(mr, IOMMUDevice, iommu_mr);
+    viommu_interval interval, *mapping_key;
+    viommu_mapping *mapping_value;
+    VirtIOIOMMU *s = sdev->viommu;
+    viommu_endpoint *ep;
+    bool bypass_allowed;
     uint32_t sid;
+    bool found;
+
+    interval.low = addr;
+    interval.high = addr + 1;
 
     IOMMUTLBEntry entry = {
         .target_as = &address_space_memory,
         .iova = addr,
         .translated_addr = addr,
-        .addr_mask = ~(hwaddr)0,
+        .addr_mask = (1 << ctz32(s->config.page_size_mask)) - 1,
         .perm = IOMMU_NONE,
     };
 
Quoted 6 lines

hw/virtio/virtio-iommu.c static IOMMUTLBEntry virtio_iommu_translate(IOMMUMemoryRegion *mr, hwaddr addr, · line 436

Quoted 3 lines
hw/virtio/virtio-iommu.c +3 -0
+    bypass_allowed = virtio_has_feature(s->acked_features,
+                                        VIRTIO_IOMMU_F_BYPASS);
+

Would it be easier to check bypass_allowed here once and then drop the latter [1] and [2] check?

Quoted 3 lines

bypass_allowed does not mean you systematically bypass. You bypass if the SID is unknown or if the device is not attached to any domain. Otherwise you translate. But maybe I miss your point.

Ah ok, then could I ask how will this VIRTIO_IOMMU_F_BYPASS be used? For example, I think VT-d defines passthrough in a totally different way in that the PT mark will be stored in the per-device context entries, then we can allow a specific device to be pass-through when doing DMA. That information is explicit (e.g., unknown SID will always fail the DMA), and per-device.

Quoted 5 lines

Here do you mean that you just don't put a device into any domain to show it wants to use PT? Then I'm not sure how do you identify whether this is a legal PT or a malicious device (e.g., an unknown device that even does not have any driver bound to it, which will also satisfy "unknown SID" and "not attached to any domain", iiuc).

The virtio-iommu spec currently says:

"If the VIRTIO_IOMMU_F_BYPASS feature is negotiated, all accesses from unattached endpoints are
allowed and translated by the IOMMU using the identity function. If the feature is not negotiated, any
memory access from an unattached endpoint fails. Upon attaching an endpoint in bypass mode to a new
domain, any memory access from the endpoint fails, since the domain does not contain any mapping.
"

Quoted 4 lines
Quoted 2 lines

I guess this can serve the purpose of devices doing early accesses, before the guest OS gets the hand and maps them?

OK, so there's no global enablement knob for virtio-iommu? Hmm... Then:

well this is a global knob. If this is bot negotiated any unmapped device can PT.

My assumption above must be wrong as this is a negotiated feature so anyway the virtio-iommu driver should be involved.

I don't really remember the rationale of the feature bit tbh.

In "[virtio-dev] RE: [RFC] virtio-iommu version 0.4 " Jean discussed that with Kevein. Sorry I cannot find the link.

" If the endpoint is not attached to any address space, then the device MAY abort the transaction."

Kevin> From definition of BYPASS, it's orthogonal to whether there is an address space attached, then should we still allow "May abort" behavior?

Jean> The behavior is left as an implementation choice, and I'm not sure it's worth enforcing in the architecture. If the endpoint isn't attached to any domain then (unless VIRTIO_IOMMU_F_BYPASS is negotiated), it isn't necessarily able to do DMA at all. The virtio-iommu device may setup DMA mastering lazily, in which case any DMA transaction would abort, or have setup DMA already, in which case the endpoint can access MEM_T_BYPASS regions.

Hopefully Jean will remember and comment on this.

Thanks

Eric

Quoted 10 lines

- This flag is a must for all virtio-iommu emulation, right? (otherwise I can't see how system bootstraps..)

- Should this flag be gone right after OS starts (otherwise I think we still have the issue that any malicious device can be seen as in PT mode as default)? How is that done?

Thanks,

#36 lore raw

Re: [PATCH for-5.0 v11 08/20] virtio-iommu: Implement translate

Quoted 59 lines · Auger Eric
Quoted 59 lines
Quoted 59 lines
Quoted 41 lines
Quoted 30 lines
Quoted 24 lines
Quoted 24 lines
(quoted diff) +10 -1
@@ -412,19 +412,80 @@ static IOMMUTLBEntry virtio_iommu_translate(IOMMUMemoryRegion *mr, hwaddr addr,
                                             int iommu_idx)
 {
     IOMMUDevice *sdev = container_of(mr, IOMMUDevice, iommu_mr);
+    viommu_interval interval, *mapping_key;
+    viommu_mapping *mapping_value;
+    VirtIOIOMMU *s = sdev->viommu;
+    viommu_endpoint *ep;
+    bool bypass_allowed;
     uint32_t sid;
+    bool found;
+
+    interval.low = addr;
+    interval.high = addr + 1;
 
     IOMMUTLBEntry entry = {
         .target_as = &address_space_memory,
         .iova = addr,
         .translated_addr = addr,
-        .addr_mask = ~(hwaddr)0,
+        .addr_mask = (1 << ctz32(s->config.page_size_mask)) - 1,
         .perm = IOMMU_NONE,
     };
 
Quoted 6 lines

Review static IOMMUTLBEntry virtio_iommu_translate(IOMMUMemoryRegion *mr, hwaddr addr, · line 436

Quoted 3 lines
(quoted diff) +3 -0
+    bypass_allowed = virtio_has_feature(s->acked_features,
+                                        VIRTIO_IOMMU_F_BYPASS);
+

Would it be easier to check bypass_allowed here once and then drop the latter [1] and [2] check?

Quoted 3 lines

bypass_allowed does not mean you systematically bypass. You bypass if the SID is unknown or if the device is not attached to any domain. Otherwise you translate. But maybe I miss your point.

Ah ok, then could I ask how will this VIRTIO_IOMMU_F_BYPASS be used? For example, I think VT-d defines passthrough in a totally different way in that the PT mark will be stored in the per-device context entries, then we can allow a specific device to be pass-through when doing DMA. That information is explicit (e.g., unknown SID will always fail the DMA), and per-device.

Quoted 5 lines

Here do you mean that you just don't put a device into any domain to show it wants to use PT? Then I'm not sure how do you identify whether this is a legal PT or a malicious device (e.g., an unknown device that even does not have any driver bound to it, which will also satisfy "unknown SID" and "not attached to any domain", iiuc).

The virtio-iommu spec currently says:

"If the VIRTIO_IOMMU_F_BYPASS feature is negotiated, all accesses from unattached endpoints are
allowed and translated by the IOMMU using the identity function. If the feature is not negotiated, any
memory access from an unattached endpoint fails. Upon attaching an endpoint in bypass mode to a new
domain, any memory access from the endpoint fails, since the domain does not contain any mapping.
"

Quoted 4 lines
Quoted 4 lines
Quoted 2 lines

I guess this can serve the purpose of devices doing early accesses, before the guest OS gets the hand and maps them?

OK, so there's no global enablement knob for virtio-iommu? Hmm... Then:

There is at the virtio transport level: the driver sets status to FEATURES_OK once it accepted the feature bits, and to DRIVER_OK once its fully operational. The virtio-iommu spec says:

If the driver does not accept the VIRTIO_IOMMU_F_BYPASS feature, the device SHOULD NOT let endpoints access the guest-physical address space.

So before features negotiation, there is no access. Afterwards it depends if the VIRTIO_IOMMU_F_BYPASS has been accepted by the driver.

Quoted 7 lines

well this is a global knob. If this is bot negotiated any unmapped device can PT.

My assumption above must be wrong as this is a negotiated feature so anyway the virtio-iommu driver should be involved.

I don't really remember the rationale of the feature bit tbh.

I don't remember writing down a rationale for this bit, it was in the very first version (I think someone suggested it during the initial internal discussion) and I didn't remove it afterwards because it seems useful:

Say a guest only wants to use the vIOMMU for userspace assignment and wants all other endpoints to bypass translation, which is our primary use-case. In other words booting Linux with iommu.passthrough=1. It can either create an identity domain for each endpoint (one MAP request with VA==PA) or it can set the VIRTIO_IOMMU_F_BYPASS bit. The device-side implementation should be more efficient with the latter, since you don't need to lookup the domain + address space for each access.

Quoted 5 lines

In "[virtio-dev] RE: [RFC] virtio-iommu version 0.4 " Jean discussed that with Kevein. Sorry I cannot find the link.

" If the endpoint is not attached to any address space, then the device MAY abort the transaction."

Hmm, that was regarding a "bypass" reserved memory region, which isn't in the current spec.

Quoted 11 lines

Kevin> From definition of BYPASS, it's orthogonal to whether there is an address space attached, then should we still allow "May abort" behavior?

Jean> The behavior is left as an implementation choice, and I'm not sure it's worth enforcing in the architecture. If the endpoint isn't attached to any domain then (unless VIRTIO_IOMMU_F_BYPASS is negotiated), it isn't necessarily able to do DMA at all. The virtio-iommu device may setup DMA mastering lazily, in which case any DMA transaction would abort, or have setup DMA already, in which case the endpoint can access MEM_T_BYPASS regions.

Quoted 9 lines

Hopefully Jean will remember and comment on this.

Thanks

Eric

Quoted 3 lines

- This flag is a must for all virtio-iommu emulation, right? (otherwise I can't see how system bootstraps..)

What do you mean by system bootstrap?

One thing I've been wondering, and may be related, is how to handle a bootloader that wants to read for example an initrd from a virtio-block device that's behind the IOMMU. Either we allow the device to let any DMA bypass the device until FEATURES_OK, which is a source of vulnerabilities [1], or we have to implement some support for the virtio-iommu in the BIOS. Again the F_BYPASS bit would help for this, since all the BIOS has to do is set it on boot. However, F_BYPASS is optional, and more complex support is needed for setting up identity mappings.

[1] See "IOMMU protection against I/O attacks: a vulnerability and a proof of concept" by Morgan et al, where a malicious device bypassing the IOMMU overwrites the IOMMU configuration as it is being created by the OS. Arguably we're not too concerned about malicious devices at the moment, but I'm not comfortable relaxing this.

Quoted 3 lines
Quoted 3 lines

- Should this flag be gone right after OS starts (otherwise I think we still have the issue that any malicious device can be seen as in PT mode as default)? How is that done?

Yes bypass mode assumes that devices and drivers aren't malicious, and the IOMMU is only used for things like assigning devices to guest userspace, or having large contiguous DMA buffers.

Thanks,
Jean

#37 lore raw

Re: [PATCH for-5.0 v11 08/20] virtio-iommu: Implement translate

Quoted 9 lines · Jean-Philippe Brucker

There is at the virtio transport level: the driver sets status to FEATURES_OK once it accepted the feature bits, and to DRIVER_OK once its fully operational. The virtio-iommu spec says:

If the driver does not accept the VIRTIO_IOMMU_F_BYPASS feature, the device SHOULD NOT let endpoints access the guest-physical address space.

So before features negotiation, there is no access. Afterwards it depends if the VIRTIO_IOMMU_F_BYPASS has been accepted by the driver.

Before enabling virtio-iommu device, should we still let the devices to access the whole system address space? I believe that's at least what Intel IOMMUs are doing. From code-wise, its:

    if (likely(s->dmar_enabled)) {
        success = vtd_do_iommu_translate(vtd_as, vtd_as->bus, vtd_as->devfn,
                                         addr, flag & IOMMU_WO, &iotlb);
    } else {
        /* DMAR disabled, passthrough, use 4k-page*/
        iotlb.iova = addr & VTD_PAGE_MASK_4K;
        iotlb.translated_addr = addr & VTD_PAGE_MASK_4K;
        iotlb.addr_mask = ~VTD_PAGE_MASK_4K;
        iotlb.perm = IOMMU_RW;
        success = true;
    }

From hardware-wise, an IOMMU should be close to transparent if you never enable it, imho.

Otherwise I'm confused on how a guest (with virtio-iommu) could boot with a normal BIOS that does not contain a virtio-iommu driver. For example, what if the BIOS needs to read some block sectors (as you mentioned)?

Quoted 4 lines
Quoted 2 lines
Quoted 2 lines

- This flag is a must for all virtio-iommu emulation, right? (otherwise I can't see how system bootstraps..)

What do you mean by system bootstrap?

Sorry, I meant when the system boots before the OS.

Quoted 4 lines

One thing I've been wondering, and may be related, is how to handle a bootloader that wants to read for example an initrd from a virtio-block device that's behind the IOMMU.

My understanding is that virtio devices are special in that they can use the VIRTIO_F_IOMMU_PLATFORM flag to bypass any vIOMMU (though, I don't think that'll work when virtio hardwares comes to the world.. because they can't really bypass the IOMMU hardware).

Quoted 13 lines

Either we allow the device to let any DMA
bypass the device until FEATURES_OK, which is a source of vulnerabilities [1], or we have to implement some support for the virtio-iommu in the BIOS. Again the F_BYPASS bit would help for this, since all the BIOS has to do is set it on boot. However, F_BYPASS is optional, and more complex support is needed for setting up identity mappings.

[1] See "IOMMU protection against I/O attacks: a vulnerability and a proof of concept" by Morgan et al, where a malicious device bypassing the IOMMU overwrites the IOMMU configuration as it is being created by the OS. Arguably we're not too concerned about malicious devices at the moment, but I'm not comfortable relaxing this.

Quoted 7 lines
Quoted 3 lines
Quoted 3 lines

- Should this flag be gone right after OS starts (otherwise I think we still have the issue that any malicious device can be seen as in PT mode as default)? How is that done?

Yes bypass mode assumes that devices and drivers aren't malicious, and the IOMMU is only used for things like assigning devices to guest userspace, or having large contiguous DMA buffers.

Yes I agree. However again when the BYPASS flag was introduced, have you thought of introducing that flag per-device? IMHO that could be better because you have a finer granularity on controlling all these, so you'll be able to reject malicious devices but at the meantime grant permission to trusted devices.

Thanks,

Signature · 1 line
Peter Xu
#38 lore raw

Re: [PATCH for-5.0 v11 08/20] virtio-iommu: Implement translate

Quoted 27 lines · Peter Xu
Quoted 9 lines · Jean-Philippe Brucker

There is at the virtio transport level: the driver sets status to FEATURES_OK once it accepted the feature bits, and to DRIVER_OK once its fully operational. The virtio-iommu spec says:

If the driver does not accept the VIRTIO_IOMMU_F_BYPASS feature, the device SHOULD NOT let endpoints access the guest-physical address space.

So before features negotiation, there is no access. Afterwards it depends if the VIRTIO_IOMMU_F_BYPASS has been accepted by the driver.

Before enabling virtio-iommu device, should we still let the devices to access the whole system address space? I believe that's at least what Intel IOMMUs are doing. From code-wise, its:

    if (likely(s->dmar_enabled)) {
        success = vtd_do_iommu_translate(vtd_as, vtd_as->bus, vtd_as->devfn,
                                         addr, flag & IOMMU_WO, &iotlb);
    } else {
        /* DMAR disabled, passthrough, use 4k-page*/
        iotlb.iova = addr & VTD_PAGE_MASK_4K;
        iotlb.translated_addr = addr & VTD_PAGE_MASK_4K;
        iotlb.addr_mask = ~VTD_PAGE_MASK_4K;
        iotlb.perm = IOMMU_RW;
        success = true;
    }
Quoted 2 lines

From hardware-wise, an IOMMU should be close to transparent if you never enable it, imho.

For hardware that's not necessarily the best choice. As cited in my previous reply it has been shown to introduce vulnerabilities since malicious devices can DMA during boot, before the OS takes control of the IOMMU. The Arm SMMU allows an implementation to adopt a deny policy by default.

Quoted 4 lines

Otherwise I'm confused on how a guest (with virtio-iommu) could boot with a normal BIOS that does not contain a virtio-iommu driver. For example, what if the BIOS needs to read some block sectors (as you mentioned)?

Ideally we should aim at supporting the device in both the BIOS and the OS. Failing that, there should at least be a way to instantiate a virtio-iommu device that is blocking by default, that cannot be bypassed unless the controlling software decides to allow it. Could the bypass policy be a command-line option to the virtio-iommu device?

[...]

Quoted 9 lines
Quoted 3 lines

Yes bypass mode assumes that devices and drivers aren't malicious, and the IOMMU is only used for things like assigning devices to guest userspace, or having large contiguous DMA buffers.

Yes I agree. However again when the BYPASS flag was introduced, have you thought of introducing that flag per-device? IMHO that could be better because you have a finer granularity on controlling all these, so you'll be able to reject malicious devices but at the meantime grant permission to trusted devices.

At the moment that per-device behavior can be emulated by sending an ATTACH request followed by identity MAP. It could be a little more efficient to add a "bypass" flag to the ATTACH request and avoid setting up the identity mapping manually, since the device then wouldn't need to look up the mapping on translation, but I don't know how much it would improve performance. The device could also cache the fact that the address space is identity-mapped, for the same result. The domain lookup has to happen in any case, so you can never get the full iommu-free performance with these mechanisms.

Thanks,
Jean

#39 lore raw

Re: [PATCH for-5.0 v11 08/20] virtio-iommu: Implement translate

Quoted 28 lines · Jean-Philippe Brucker
Quoted 27 lines · Peter Xu
Quoted 9 lines · Jean-Philippe Brucker

There is at the virtio transport level: the driver sets status to FEATURES_OK once it accepted the feature bits, and to DRIVER_OK once its fully operational. The virtio-iommu spec says:

If the driver does not accept the VIRTIO_IOMMU_F_BYPASS feature, the device SHOULD NOT let endpoints access the guest-physical address space.

So before features negotiation, there is no access. Afterwards it depends if the VIRTIO_IOMMU_F_BYPASS has been accepted by the driver.

Before enabling virtio-iommu device, should we still let the devices to access the whole system address space? I believe that's at least what Intel IOMMUs are doing. From code-wise, its:

    if (likely(s->dmar_enabled)) {
        success = vtd_do_iommu_translate(vtd_as, vtd_as->bus, vtd_as->devfn,
                                         addr, flag & IOMMU_WO, &iotlb);
    } else {
        /* DMAR disabled, passthrough, use 4k-page*/
        iotlb.iova = addr & VTD_PAGE_MASK_4K;
        iotlb.translated_addr = addr & VTD_PAGE_MASK_4K;
        iotlb.addr_mask = ~VTD_PAGE_MASK_4K;
        iotlb.perm = IOMMU_RW;
        success = true;
    }
Quoted 8 lines
Quoted 2 lines

From hardware-wise, an IOMMU should be close to transparent if you never enable it, imho.

For hardware that's not necessarily the best choice. As cited in my previous reply it has been shown to introduce vulnerabilities since malicious devices can DMA during boot, before the OS takes control of the IOMMU. The Arm SMMU allows an implementation to adopt a deny policy by default.

I see. But then how to read a sector from the block to at least boot an OS if we use a default-deny policy? Does it still need a mapping that is established somehow by someone before hand?

Quoted 23 lines
Quoted 5 lines

Otherwise I'm confused on how a guest (with virtio-iommu) could boot with a normal BIOS that does not contain a virtio-iommu driver. For example, what if the BIOS needs to read some block sectors (as you mentioned)?

Ideally we should aim at supporting the device in both the BIOS and the OS. Failing that, there should at least be a way to instantiate a virtio-iommu device that is blocking by default, that cannot be bypassed unless the controlling software decides to allow it. Could the bypass policy be a command-line option to the virtio-iommu device?

[...]

Quoted 9 lines
Quoted 3 lines

Yes bypass mode assumes that devices and drivers aren't malicious, and the IOMMU is only used for things like assigning devices to guest userspace, or having large contiguous DMA buffers.

Yes I agree. However again when the BYPASS flag was introduced, have you thought of introducing that flag per-device? IMHO that could be better because you have a finer granularity on controlling all these, so you'll be able to reject malicious devices but at the meantime grant permission to trusted devices.

Quoted 9 lines

At the moment that per-device behavior can be emulated by sending an ATTACH request followed by identity MAP. It could be a little more efficient to add a "bypass" flag to the ATTACH request and avoid setting up the identity mapping manually, since the device then wouldn't need to look up the mapping on translation, but I don't know how much it would improve performance. The device could also cache the fact that the address space is identity-mapped, for the same result. The domain lookup has to happen in any case, so you can never get the full iommu-free performance with these mechanisms.

IMHO it's really a matter of whether virtio-iommu wants to have a device layer besides the domain layer for the initial versions (just like VT-d has a device context, then it points to a domain, so it has these two layers). But I agree for the bypass feature it should work (though trying to detect "a device is put into an identital domain is bypassed" is still a bit tricky to me). And after all virtio-iommu is always extensible when needs come.

Thanks,

Signature · 1 line
Peter Xu
#40 lore raw

Re: [PATCH for-5.0 v11 08/20] virtio-iommu: Implement translate

Quoted 38 lines · Peter Xu
Quoted 28 lines · Jean-Philippe Brucker
Quoted 27 lines · Peter Xu
Quoted 9 lines · Jean-Philippe Brucker

There is at the virtio transport level: the driver sets status to FEATURES_OK once it accepted the feature bits, and to DRIVER_OK once its fully operational. The virtio-iommu spec says:

If the driver does not accept the VIRTIO_IOMMU_F_BYPASS feature, the device SHOULD NOT let endpoints access the guest-physical address space.

So before features negotiation, there is no access. Afterwards it depends if the VIRTIO_IOMMU_F_BYPASS has been accepted by the driver.

Before enabling virtio-iommu device, should we still let the devices to access the whole system address space? I believe that's at least what Intel IOMMUs are doing. From code-wise, its:

    if (likely(s->dmar_enabled)) {
        success = vtd_do_iommu_translate(vtd_as, vtd_as->bus, vtd_as->devfn,
                                         addr, flag & IOMMU_WO, &iotlb);
    } else {
        /* DMAR disabled, passthrough, use 4k-page*/
        iotlb.iova = addr & VTD_PAGE_MASK_4K;
        iotlb.translated_addr = addr & VTD_PAGE_MASK_4K;
        iotlb.addr_mask = ~VTD_PAGE_MASK_4K;
        iotlb.perm = IOMMU_RW;
        success = true;
    }
Quoted 8 lines
Quoted 2 lines

From hardware-wise, an IOMMU should be close to transparent if you never enable it, imho.

For hardware that's not necessarily the best choice. As cited in my previous reply it has been shown to introduce vulnerabilities since malicious devices can DMA during boot, before the OS takes control of the IOMMU. The Arm SMMU allows an implementation to adopt a deny policy by default.

Quoted 3 lines

I see. But then how to read a sector from the block to at least boot an OS if we use a default-deny policy? Does it still need a mapping that is established somehow by someone before hand?

Yes, it looks like EDK II uses IOMMU operations in order to access those devices on platforms where the IOMMU isn't default-bypass (AMD SEV support is provided by edk2, and a VT-d driver seems provided by edk2-platforms). However for OVMF we could just set the bypass feature bit in virtio-iommu device, which doesn't even requires setting up the virtqueue.

I'm missing a piece of the puzzle for Arm platforms though, because it looks like Trusted Firmware-A sets up the default-deny policy on reset even when it wasn't hardwired, but doesn't provide a service to create SMMUv3 mappings for the bootloader.

Thanks,
Jean

author
#41 lore raw

Re: [PATCH for-5.0 v11 08/20] virtio-iommu: Implement translate

Hi Jean-Philippe, Peter,

Quoted 49 lines · Jean-Philippe Brucker
Quoted 38 lines · Peter Xu
Quoted 28 lines · Jean-Philippe Brucker
Quoted 27 lines · Peter Xu
Quoted 9 lines · Jean-Philippe Brucker

There is at the virtio transport level: the driver sets status to FEATURES_OK once it accepted the feature bits, and to DRIVER_OK once its fully operational. The virtio-iommu spec says:

If the driver does not accept the VIRTIO_IOMMU_F_BYPASS feature, the device SHOULD NOT let endpoints access the guest-physical address space.

So before features negotiation, there is no access. Afterwards it depends if the VIRTIO_IOMMU_F_BYPASS has been accepted by the driver.

Before enabling virtio-iommu device, should we still let the devices to access the whole system address space? I believe that's at least what Intel IOMMUs are doing. From code-wise, its:

    if (likely(s->dmar_enabled)) {
        success = vtd_do_iommu_translate(vtd_as, vtd_as->bus, vtd_as->devfn,
                                         addr, flag & IOMMU_WO, &iotlb);
    } else {
        /* DMAR disabled, passthrough, use 4k-page*/
        iotlb.iova = addr & VTD_PAGE_MASK_4K;
        iotlb.translated_addr = addr & VTD_PAGE_MASK_4K;
        iotlb.addr_mask = ~VTD_PAGE_MASK_4K;
        iotlb.perm = IOMMU_RW;
        success = true;
    }
Quoted 8 lines
Quoted 2 lines

From hardware-wise, an IOMMU should be close to transparent if you never enable it, imho.

For hardware that's not necessarily the best choice. As cited in my previous reply it has been shown to introduce vulnerabilities since malicious devices can DMA during boot, before the OS takes control of the IOMMU. The Arm SMMU allows an implementation to adopt a deny policy by default.

Quoted 3 lines

I see. But then how to read a sector from the block to at least boot an OS if we use a default-deny policy? Does it still need a mapping that is established somehow by someone before hand?

Yes, it looks like EDK II uses IOMMU operations in order to access those devices on platforms where the IOMMU isn't default-bypass (AMD SEV support is provided by edk2, and a VT-d driver seems provided by edk2-platforms). However for OVMF we could just set the bypass feature bit in virtio-iommu device, which doesn't even requires setting up the virtqueue.

Quoted 8 lines

I'm missing a piece of the puzzle for Arm platforms though, because it looks like Trusted Firmware-A sets up the default-deny policy on reset even when it wasn't hardwired, but doesn't provide a service to create SMMUv3 mappings for the bootloader.

Thanks,
Jean

I think we have a concrete example for the above discussion. The AHCI. When running the virtio-iommu on x86 I get messages like:

virtio_iommu_translate sid=250 is not known!! no buffer available in event queue to report event

and a bunch of "AHCI: Failed to start FIS receive engine: bad FIS receive buffer address" messages (For each port)

This was reported in my cover letter (*). This happens very early in the boot process, before the OS get the hand and before the virtio-iommu driver creates any mapping. It does not prevent the guest from booting though.

Currently the virtio-iommu device checks the VIRTIO_IOMMU_F_BYPASS. If I overwrite it to true in the device, then, the guest boots without those messages.

I share Peter's concern about having a different default policy than x86.

Thanks

Eric

Note the migration issue reported in the cover letter is fixed now and was due to the migration priority unset.

#42 lore raw

Re: [PATCH for-5.0 v11 08/20] virtio-iommu: Implement translate

Quoted 70 lines · Auger Eric

Hi Jean-Philippe, Peter,

Quoted 49 lines · Jean-Philippe Brucker
Quoted 38 lines · Peter Xu
Quoted 28 lines · Jean-Philippe Brucker
Quoted 27 lines · Peter Xu
Quoted 9 lines · Jean-Philippe Brucker

There is at the virtio transport level: the driver sets status to FEATURES_OK once it accepted the feature bits, and to DRIVER_OK once its fully operational. The virtio-iommu spec says:

If the driver does not accept the VIRTIO_IOMMU_F_BYPASS feature, the device SHOULD NOT let endpoints access the guest-physical address space.

So before features negotiation, there is no access. Afterwards it depends if the VIRTIO_IOMMU_F_BYPASS has been accepted by the driver.

Before enabling virtio-iommu device, should we still let the devices to access the whole system address space? I believe that's at least what Intel IOMMUs are doing. From code-wise, its:

    if (likely(s->dmar_enabled)) {
        success = vtd_do_iommu_translate(vtd_as, vtd_as->bus, vtd_as->devfn,
                                         addr, flag & IOMMU_WO, &iotlb);
    } else {
        /* DMAR disabled, passthrough, use 4k-page*/
        iotlb.iova = addr & VTD_PAGE_MASK_4K;
        iotlb.translated_addr = addr & VTD_PAGE_MASK_4K;
        iotlb.addr_mask = ~VTD_PAGE_MASK_4K;
        iotlb.perm = IOMMU_RW;
        success = true;
    }
Quoted 8 lines
Quoted 2 lines

From hardware-wise, an IOMMU should be close to transparent if you never enable it, imho.

For hardware that's not necessarily the best choice. As cited in my previous reply it has been shown to introduce vulnerabilities since malicious devices can DMA during boot, before the OS takes control of the IOMMU. The Arm SMMU allows an implementation to adopt a deny policy by default.

Quoted 3 lines

I see. But then how to read a sector from the block to at least boot an OS if we use a default-deny policy? Does it still need a mapping that is established somehow by someone before hand?

Yes, it looks like EDK II uses IOMMU operations in order to access those devices on platforms where the IOMMU isn't default-bypass (AMD SEV support is provided by edk2, and a VT-d driver seems provided by edk2-platforms). However for OVMF we could just set the bypass feature bit in virtio-iommu device, which doesn't even requires setting up the virtqueue.

Quoted 8 lines

I'm missing a piece of the puzzle for Arm platforms though, because it looks like Trusted Firmware-A sets up the default-deny policy on reset even when it wasn't hardwired, but doesn't provide a service to create SMMUv3 mappings for the bootloader.

Thanks,
Jean

I think we have a concrete example for the above discussion. The AHCI. When running the virtio-iommu on x86 I get messages like:

virtio_iommu_translate sid=250 is not known!! no buffer available in event queue to report event

and a bunch of "AHCI: Failed to start FIS receive engine: bad FIS receive buffer address" messages (For each port)

Quoted 8 lines

This was reported in my cover letter (*). This happens very early in the boot process, before the OS get the hand and before the virtio-iommu driver creates any mapping. It does not prevent the guest from booting though.

Currently the virtio-iommu device checks the VIRTIO_IOMMU_F_BYPASS. If I overwrite it to true in the device, then, the guest boots without those messages.

Oh that's good, I was afraid it was an issue in Linux.

Quoted 1 line

I share Peter's concern about having a different default policy than x86.

Yes I'd say just align with whatever policy is already in place. Do you think we could add a command-line option to let people disable default-bypass, though? That would be a convenient way to make the IOMMU protection airtight for those who need it.

Thanks,
Jean

author
#43 lore raw

Re: [PATCH for-5.0 v11 08/20] virtio-iommu: Implement translate

Hi Jean,

Quoted 80 lines · Jean-Philippe Brucker
Quoted 70 lines · Auger Eric

Hi Jean-Philippe, Peter,

Quoted 49 lines · Jean-Philippe Brucker
Quoted 38 lines · Peter Xu
Quoted 28 lines · Jean-Philippe Brucker
Quoted 27 lines · Peter Xu
Quoted 9 lines · Jean-Philippe Brucker

There is at the virtio transport level: the driver sets status to FEATURES_OK once it accepted the feature bits, and to DRIVER_OK once its fully operational. The virtio-iommu spec says:

If the driver does not accept the VIRTIO_IOMMU_F_BYPASS feature, the device SHOULD NOT let endpoints access the guest-physical address space.

So before features negotiation, there is no access. Afterwards it depends if the VIRTIO_IOMMU_F_BYPASS has been accepted by the driver.

Before enabling virtio-iommu device, should we still let the devices to access the whole system address space? I believe that's at least what Intel IOMMUs are doing. From code-wise, its:

    if (likely(s->dmar_enabled)) {
        success = vtd_do_iommu_translate(vtd_as, vtd_as->bus, vtd_as->devfn,
                                         addr, flag & IOMMU_WO, &iotlb);
    } else {
        /* DMAR disabled, passthrough, use 4k-page*/
        iotlb.iova = addr & VTD_PAGE_MASK_4K;
        iotlb.translated_addr = addr & VTD_PAGE_MASK_4K;
        iotlb.addr_mask = ~VTD_PAGE_MASK_4K;
        iotlb.perm = IOMMU_RW;
        success = true;
    }
Quoted 8 lines
Quoted 2 lines

From hardware-wise, an IOMMU should be close to transparent if you never enable it, imho.

For hardware that's not necessarily the best choice. As cited in my previous reply it has been shown to introduce vulnerabilities since malicious devices can DMA during boot, before the OS takes control of the IOMMU. The Arm SMMU allows an implementation to adopt a deny policy by default.

Quoted 3 lines

I see. But then how to read a sector from the block to at least boot an OS if we use a default-deny policy? Does it still need a mapping that is established somehow by someone before hand?

Yes, it looks like EDK II uses IOMMU operations in order to access those devices on platforms where the IOMMU isn't default-bypass (AMD SEV support is provided by edk2, and a VT-d driver seems provided by edk2-platforms). However for OVMF we could just set the bypass feature bit in virtio-iommu device, which doesn't even requires setting up the virtqueue.

Quoted 8 lines

I'm missing a piece of the puzzle for Arm platforms though, because it looks like Trusted Firmware-A sets up the default-deny policy on reset even when it wasn't hardwired, but doesn't provide a service to create SMMUv3 mappings for the bootloader.

Thanks,
Jean

I think we have a concrete example for the above discussion. The AHCI. When running the virtio-iommu on x86 I get messages like:

virtio_iommu_translate sid=250 is not known!! no buffer available in event queue to report event

and a bunch of "AHCI: Failed to start FIS receive engine: bad FIS receive buffer address" messages (For each port)

Quoted 8 lines

This was reported in my cover letter (*). This happens very early in the boot process, before the OS get the hand and before the virtio-iommu driver creates any mapping. It does not prevent the guest from booting though.

Currently the virtio-iommu device checks the VIRTIO_IOMMU_F_BYPASS. If I overwrite it to true in the device, then, the guest boots without those messages.

Quoted 8 lines

Oh that's good, I was afraid it was an issue in Linux.

Quoted 1 line

I share Peter's concern about having a different default policy than x86.

Yes I'd say just align with whatever policy is already in place. Do you think we could add a command-line option to let people disable default-bypass, though? That would be a convenient way to make the IOMMU protection airtight for those who need it.

Yes I could easily add a device option to disable the default bypass.

Shall we change the meaning of the F_BYPASS feature then? If exposed by the device, the device does bypass by default, otherwise it doesn't. This would be controlled by the device option.

The driver then could have means to overwrite this behavior once loaded?

Thanks

Eric

Quoted 4 lines

Thanks,
Jean

#44 lore raw

Re: [PATCH for-5.0 v11 08/20] virtio-iommu: Implement translate

Quoted 11 lines · Auger Eric
Quoted 6 lines
Quoted 1 line

I share Peter's concern about having a different default policy than x86.

Yes I'd say just align with whatever policy is already in place. Do you think we could add a command-line option to let people disable default-bypass, though? That would be a convenient way to make the IOMMU protection airtight for those who need it.

Yes I could easily add a device option to disable the default bypass.

Shall we change the meaning of the F_BYPASS feature then? If exposed by the device, the device does bypass by default, otherwise it doesn't. This would be controlled by the device option.

For a device that doesn't do bypass by default, the driver wouldn't have the ability to enable bypass (feature bit not offered, not negotiable).

Quoted 1 line

The driver then could have means to overwrite this behavior once loaded?

Let's keep the bypass feature bit for this. If the bit is offered, the driver chooses to enable or disable it. If the bit is not offered or not negotiated, then the behavior is deny. If the bit is offered and negotiated then the behavior is allow.

We can say that before features negotiation (latched at features register write, I think, in practice?) the behavior is platform dependent. The current wording about bypass intends to discourage unsafe choices but makes a strong statement only about the device behavior after features negotiation.

We could add a second feature bit specifically for the boot bypass behavior. It wouldn't be useful to the OS (the driver doesn't have a choice) but could present a bit in config space that allows a firmware to disable boot-bypass in a way that is sticky across reset. So when the OS resets the device after taking it over, it doesn't accidentally enable bypass. I wouldn't bother though. If a FW/bootloader is able to support virtio-iommu, the user might as well instantiate the device with the default-deny option.

Thanks,
Jean

author
#45 lore raw

Re: [PATCH for-5.0 v11 08/20] virtio-iommu: Implement translate

Hi,

Quoted 23 lines · Jean-Philippe Brucker
Quoted 11 lines · Auger Eric
Quoted 6 lines
Quoted 1 line

I share Peter's concern about having a different default policy than x86.

Yes I'd say just align with whatever policy is already in place. Do you think we could add a command-line option to let people disable default-bypass, though? That would be a convenient way to make the IOMMU protection airtight for those who need it.

Yes I could easily add a device option to disable the default bypass.

Shall we change the meaning of the F_BYPASS feature then? If exposed by the device, the device does bypass by default, otherwise it doesn't. This would be controlled by the device option.

For a device that doesn't do bypass by default, the driver wouldn't have the ability to enable bypass (feature bit not offered, not negotiable).

Quoted 1 line

The driver then could have means to overwrite this behavior once loaded?

Let's keep the bypass feature bit for this. If the bit is offered, the driver chooses to enable or disable it. If the bit is not offered or not negotiated, then the behavior is deny. If the bit is offered and negotiated then the behavior is allow.

Quoted 5 lines

We can say that before features negotiation (latched at features register write, I think, in practice?) the behavior is platform dependent. The current wording about bypass intends to discourage unsafe choices but makes a strong statement only about the device behavior after features negotiation.

OK. May be worth adding in the spec later.

By the way what is the plan for the vote?

Thanks

Eric

Quoted 14 lines

We could add a second feature bit specifically for the boot bypass behavior. It wouldn't be useful to the OS (the driver doesn't have a choice) but could present a bit in config space that allows a firmware to disable boot-bypass in a way that is sticky across reset. So when the OS resets the device after taking it over, it doesn't accidentally enable bypass. I wouldn't bother though. If a FW/bootloader is able to support virtio-iommu, the user might as well instantiate the device with the default-deny option.

Thanks,
Jean

#46 lore raw

Re: [PATCH for-5.0 v11 08/20] virtio-iommu: Implement translate

Quoted 26 lines · Auger Eric

Hi,

Quoted 23 lines · Jean-Philippe Brucker
Quoted 11 lines · Auger Eric
Quoted 6 lines
Quoted 1 line

I share Peter's concern about having a different default policy than x86.

Yes I'd say just align with whatever policy is already in place. Do you think we could add a command-line option to let people disable default-bypass, though? That would be a convenient way to make the IOMMU protection airtight for those who need it.

Yes I could easily add a device option to disable the default bypass.

Shall we change the meaning of the F_BYPASS feature then? If exposed by the device, the device does bypass by default, otherwise it doesn't. This would be controlled by the device option.

For a device that doesn't do bypass by default, the driver wouldn't have the ability to enable bypass (feature bit not offered, not negotiable).

Quoted 1 line

The driver then could have means to overwrite this behavior once loaded?

Let's keep the bypass feature bit for this. If the bit is offered, the driver chooses to enable or disable it. If the bit is not offered or not negotiated, then the behavior is deny. If the bit is offered and negotiated then the behavior is allow.

Quoted 8 lines
Quoted 5 lines

We can say that before features negotiation (latched at features register write, I think, in practice?) the behavior is platform dependent. The current wording about bypass intends to discourage unsafe choices but makes a strong statement only about the device behavior after features negotiation.

OK. May be worth adding in the spec later.

By the way what is the plan for the vote?

The ballot closed and the spec is accepted for virtio-v1.2-cs01, with the condition that the stale statement about padding is removed
(https://lists.oasis-open.org/archives/virtio-dev/201911/msg00083.html)

Thanks,
Jean

author
#47 lore raw

Re: [PATCH for-5.0 v11 08/20] virtio-iommu: Implement translate

Hi Jean,

Quoted 32 lines · Jean-Philippe Brucker
Quoted 31 lines · Auger Eric

Hi,

Quoted 28 lines · Jean-Philippe Brucker
Quoted 11 lines · Auger Eric
Quoted 6 lines
Quoted 1 line

I share Peter's concern about having a different default policy than x86.

Yes I'd say just align with whatever policy is already in place. Do you think we could add a command-line option to let people disable default-bypass, though? That would be a convenient way to make the IOMMU protection airtight for those who need it.

Yes I could easily add a device option to disable the default bypass.

Shall we change the meaning of the F_BYPASS feature then? If exposed by the device, the device does bypass by default, otherwise it doesn't. This would be controlled by the device option.

For a device that doesn't do bypass by default, the driver wouldn't have the ability to enable bypass (feature bit not offered, not negotiable).

Quoted 1 line

The driver then could have means to overwrite this behavior once loaded?

Let's keep the bypass feature bit for this. If the bit is offered, the driver chooses to enable or disable it. If the bit is not offered or not negotiated, then the behavior is deny. If the bit is offered and negotiated then the behavior is allow.

We can say that before features negotiation (latched at features register write, I think, in practice?) the behavior is platform dependent. The current wording about bypass intends to discourage unsafe choices but makes a strong statement only about the device behavior after features negotiation.

Quoted 7 lines
Quoted 3 lines

OK. May be worth adding in the spec later.

By the way what is the plan for the vote?

The ballot closed and the spec is accepted for virtio-v1.2-cs01, with the condition that the stale statement about padding is removed
(https://lists.oasis-open.org/archives/virtio-dev/201911/msg00083.html)

Ah OK. Sorry I missed the outcome. Congratulations!

Eric

Quoted 4 lines

Thanks,
Jean

author
#48 lore raw

PATCH v11 9/20 virtio-iommu: Implement fault reporting

In reply to Eric Auger

The event queue allows to report asynchronous errors. The translate function now injects faults when relevant.

---

v10 -> v11:
- change a virtio_error into an error_report_once
(no buffer available for output faults)

---
 hw/virtio/trace-events   |  1 +
 hw/virtio/virtio-iommu.c | 69 +++++++++++++++++++++++++++++++++++++---
 2 files changed, 65 insertions(+), 5 deletions(-)
hw/virtio/trace-events +1 -0
index de7cbb3c8f..a572eb71aa 100644
@@ -73,3 +73,4 @@ virtio_iommu_put_endpoint(uint32_t ep_id) "Free endpoint=%d"
 virtio_iommu_get_domain(uint32_t domain_id) "Alloc domain=%d"
 virtio_iommu_put_domain(uint32_t domain_id) "Free domain=%d"
 virtio_iommu_translate_out(uint64_t virt_addr, uint64_t phys_addr, uint32_t sid) "0x%"PRIx64" -> 0x%"PRIx64 " for sid=%d"
+virtio_iommu_report_fault(uint8_t reason, uint32_t flags, uint32_t endpoint, uint64_t addr) "FAULT reason=%d flags=%d endpoint=%d address =0x%"PRIx64
hw/virtio/virtio-iommu.c +64 -5

107 lines not on this page · raw message

Signature · 1 line
2.20.1
#49 lore raw

Re: [PATCH for-5.0 v11 09/20] virtio-iommu: Implement fault reporting

hw/virtio/virtio-iommu.c static IOMMUTLBEntry virtio_iommu_translate(IOMMUMemoryRegion *mr, hwaddr addr, · line 493

Quoted 6 lines · Eric Auger
hw/virtio/virtio-iommu.c +2 -0
@@ -443,6 +489,8 @@ static IOMMUTLBEntry virtio_iommu_translate(IOMMUMemoryRegion *mr, hwaddr addr,
     if (!ep) {
         if (!bypass_allowed) {
             error_report_once("%s sid=%d is not known!!", __func__, sid);
+            virtio_iommu_report_fault(s, VIRTIO_IOMMU_FAULT_R_UNKNOWN,
+                                      0, sid, 0);

I guess we could report the faulting address as well, it can be useful for diagnostics.

hw/virtio/virtio-iommu.c static IOMMUTLBEntry virtio_iommu_translate(IOMMUMemoryRegion *mr, hwaddr addr, · line 507

Quoted 9 lines
hw/virtio/virtio-iommu.c +2 -0
         } else {
             entry.perm = flag;
         }
@@ -455,6 +503,8 @@ static IOMMUTLBEntry virtio_iommu_translate(IOMMUMemoryRegion *mr, hwaddr addr,
                           "%s %02x:%02x.%01x not attached to any domain\n",
                           __func__, PCI_BUS_NUM(sid),
                           PCI_SLOT(sid), PCI_FUNC(sid));
+            virtio_iommu_report_fault(s, VIRTIO_IOMMU_FAULT_R_DOMAIN,
+                                      0, sid, 0);

Here as well, especially since that error would get propagated by a linux guest to the device driver

hw/virtio/virtio-iommu.c static IOMMUTLBEntry virtio_iommu_translate(IOMMUMemoryRegion *mr, hwaddr addr, · line 522

Quoted 9 lines
hw/virtio/virtio-iommu.c +2 -0
         } else {
             entry.perm = flag;
         }
@@ -468,16 +518,25 @@ static IOMMUTLBEntry virtio_iommu_translate(IOMMUMemoryRegion *mr, hwaddr addr,
         qemu_log_mask(LOG_GUEST_ERROR,
                       "%s no mapping for 0x%"PRIx64" for sid=%d\n",
                       __func__, addr, sid);
+        virtio_iommu_report_fault(s, VIRTIO_IOMMU_FAULT_R_MAPPING,
+                                  0, sid, addr);

Flag VIRTIO_IOMMU_FAULT_F_ADDRESS denotes a valid address field

Thanks,
Jean

author
#50 lore raw

PATCH v11 10/20 virtio-iommu-pci: Add virtio iommu pci support

In reply to Eric Auger

This patch adds virtio-iommu-pci, which is the pci proxy for the virtio-iommu device.

---

v10 -> v11:
- add the reserved_regions array property

v9 -> v10:
- include "hw/qdev-properties.h" header

v8 -> v9:
- add the msi-bypass property
- create virtio-iommu-pci.c

---
 hw/virtio/Makefile.objs          |  1 +
 hw/virtio/virtio-iommu-pci.c     | 91 ++++++++++++++++++++++++++++++++
 include/hw/pci/pci.h             |  1 +
 include/hw/virtio/virtio-iommu.h |  1 +
 qdev-monitor.c                   |  1 +
 5 files changed, 95 insertions(+)
 create mode 100644 hw/virtio/virtio-iommu-pci.c
hw/virtio/Makefile.objs +1 -0
index f68ac14a90..33e6bc591a 100644
@@ -29,6 +29,7 @@ obj-$(CONFIG_VIRTIO_INPUT_HOST) += virtio-input-host-pci.o
 obj-$(CONFIG_VIRTIO_INPUT) += virtio-input-pci.o
 obj-$(CONFIG_VIRTIO_RNG) += virtio-rng-pci.o
 obj-$(CONFIG_VIRTIO_BALLOON) += virtio-balloon-pci.o
+obj-$(CONFIG_VIRTIO_IOMMU) += virtio-iommu-pci.o
 obj-$(CONFIG_VIRTIO_9P) += virtio-9p-pci.o
 obj-$(CONFIG_VIRTIO_SCSI) += virtio-scsi-pci.o
 obj-$(CONFIG_VIRTIO_BLK) += virtio-blk-pci.o
hw/virtio/virtio-iommu-pci.c new file +91 -0

91 lines not on this page · raw message

include/hw/pci/pci.h +1 -0
index db75c6dfd0..d7715c826a 100644
@@ -86,6 +86,7 @@ extern bool pci_available;
 #define PCI_DEVICE_ID_VIRTIO_9P          0x1009
 #define PCI_DEVICE_ID_VIRTIO_VSOCK       0x1012
 #define PCI_DEVICE_ID_VIRTIO_PMEM        0x1013
+#define PCI_DEVICE_ID_VIRTIO_IOMMU       0x1014
 
 #define PCI_VENDOR_ID_REDHAT             0x1b36
 #define PCI_DEVICE_ID_REDHAT_BRIDGE      0x0001
include/hw/virtio/virtio-iommu.h +1 -0
index f55f48d304..1ab6993d29 100644
@@ -25,6 +25,7 @@
 #include "hw/pci/pci.h"
 
 #define TYPE_VIRTIO_IOMMU "virtio-iommu-device"
+#define TYPE_VIRTIO_IOMMU_PCI "virtio-iommu-device-base"
 #define VIRTIO_IOMMU(obj) \
         OBJECT_CHECK(VirtIOIOMMU, (obj), TYPE_VIRTIO_IOMMU)
 
qdev-monitor.c +1 -0
index e6b112eb0a..e61ca62061 100644
@@ -66,6 +66,7 @@ static const QDevAlias qdev_alias_table[] = {
     { "virtio-input-host-ccw", "virtio-input-host", QEMU_ARCH_S390X },
     { "virtio-input-host-pci", "virtio-input-host",
             QEMU_ARCH_ALL & ~QEMU_ARCH_S390X },
+    { "virtio-iommu-pci", "virtio-iommu", QEMU_ARCH_ALL & ~QEMU_ARCH_S390X },
     { "virtio-keyboard-ccw", "virtio-keyboard", QEMU_ARCH_S390X },
     { "virtio-keyboard-pci", "virtio-keyboard",
             QEMU_ARCH_ALL & ~QEMU_ARCH_S390X },
Signature · 1 line
2.20.1
author
#52 lore raw

PATCH v11 11/20 hw/arm/virt: Add the virtio-iommu device tree mappings

In reply to Eric Auger

Adds the "virtio,pci-iommu" node in the host bridge node and the RID mapping, excluding the IOMMU RID.

---

v10 -> v11:
- remove msi_bypass

v8 -> v9:
- disable msi-bypass property
- addition of the subnode is handled is the hotplug handler and IOMMU RID is notimposed anymore

v6 -> v7:
- align to the smmu instantiation code

v4 -> v5:
- VirtMachineClass no_iommu added in this patch
- Use object_resolve_path_type

---
 hw/arm/virt.c                | 53 +++++++++++++++++++++++++++++++-----
 hw/virtio/virtio-iommu-pci.c |  3 --
 include/hw/arm/virt.h        |  2 ++
 3 files changed, 48 insertions(+), 10 deletions(-)
hw/arm/virt.c +46 -7
index d4bedc2607..cb6a95e7c8 100644
@@ -32,6 +32,7 @@
 #include "qemu-common.h"
 #include "qemu/units.h"
 #include "qemu/option.h"
+#include "monitor/qdev.h"
 #include "qapi/error.h"
 #include "hw/sysbus.h"
 #include "hw/boards.h"
@@ -54,6 +55,7 @@
 #include "qemu/error-report.h"
 #include "qemu/module.h"
 #include "hw/pci-host/gpex.h"
+#include "hw/virtio/virtio-pci.h"
 #include "hw/arm/sysbus-fdt.h"
 #include "hw/platform-bus.h"
 #include "hw/qdev-properties.h"
@@ -71,6 +73,7 @@
 #include "hw/mem/pc-dimm.h"
 #include "hw/mem/nvdimm.h"
 #include "hw/acpi/generic_event_device.h"
+#include "hw/virtio/virtio-iommu.h"
 
 #define DEFINE_VIRT_MACHINE_LATEST(major, minor, latest) \
     static void virt_##major##_##minor##_class_init(ObjectClass *oc, \
@@ -1181,6 +1184,30 @@ static void create_smmu(const VirtMachineState *vms, qemu_irq *pic,
     g_free(node);
 }
 
+static void create_virtio_iommu(VirtMachineState *vms, Error **errp)
+{
+    const char compat[] = "virtio,pci-iommu";
+    uint16_t bdf = vms->virtio_iommu_bdf;
+    char *node;
+
+    vms->iommu_phandle = qemu_fdt_alloc_phandle(vms->fdt);
+
+    node = g_strdup_printf("%s/virtio_iommu@%d", vms->pciehb_nodename, bdf);
+    qemu_fdt_add_subnode(vms->fdt, node);
+    qemu_fdt_setprop(vms->fdt, node, "compatible", compat, sizeof(compat));
+    qemu_fdt_setprop_sized_cells(vms->fdt, node, "reg",
+                                 1, bdf << 8, 1, 0, 1, 0,
+                                 1, 0, 1, 0);
+
+    qemu_fdt_setprop_cell(vms->fdt, node, "#iommu-cells", 1);
+    qemu_fdt_setprop_cell(vms->fdt, node, "phandle", vms->iommu_phandle);
+    g_free(node);
+
+    qemu_fdt_setprop_cells(vms->fdt, vms->pciehb_nodename, "iommu-map",
+                           0x0, vms->iommu_phandle, 0x0, bdf,
+                           bdf + 1, vms->iommu_phandle, bdf + 1, 0xffff - bdf);
+}
+
 static void create_pcie(VirtMachineState *vms, qemu_irq *pic)
 {
     hwaddr base_mmio = vms->memmap[VIRT_PCIE_MMIO].base;
@@ -1258,7 +1285,7 @@ static void create_pcie(VirtMachineState *vms, qemu_irq *pic)
         }
     }
 
-    nodename = g_strdup_printf("/pcie@%" PRIx64, base);
+    nodename = vms->pciehb_nodename = g_strdup_printf("/pcie@%" PRIx64, base);
     qemu_fdt_add_subnode(vms->fdt, nodename);
     qemu_fdt_setprop_string(vms->fdt, nodename,
                             "compatible", "pci-host-ecam-generic");
@@ -1301,13 +1328,17 @@ static void create_pcie(VirtMachineState *vms, qemu_irq *pic)
     if (vms->iommu) {
         vms->iommu_phandle = qemu_fdt_alloc_phandle(vms->fdt);
 
-        create_smmu(vms, pic, pci->bus);
+        switch (vms->iommu) {
+        case VIRT_IOMMU_SMMUV3:
+            create_smmu(vms, pic, pci->bus);
+            qemu_fdt_setprop_cells(vms->fdt, nodename, "iommu-map",
+                                   0x0, vms->iommu_phandle, 0x0, 0x10000);
+            break;
+        default:
+            g_assert_not_reached();
+        }
 
-        qemu_fdt_setprop_cells(vms->fdt, nodename, "iommu-map",
-                               0x0, vms->iommu_phandle, 0x0, 0x10000);
     }
-
-    g_free(nodename);
 }
 
 static void create_platform_bus(VirtMachineState *vms, qemu_irq *pic)
@@ -1972,6 +2003,13 @@ static void virt_machine_device_plug_cb(HotplugHandler *hotplug_dev,
     if (object_dynamic_cast(OBJECT(dev), TYPE_PC_DIMM)) {
         virt_memory_plug(hotplug_dev, dev, errp);
     }
+    if (object_dynamic_cast(OBJECT(dev), TYPE_VIRTIO_IOMMU_PCI)) {
+        PCIDevice *pdev = PCI_DEVICE(dev);
+
+        vms->iommu = VIRT_IOMMU_VIRTIO;
+        vms->virtio_iommu_bdf = pci_get_bdf(pdev);
+        create_virtio_iommu(vms, errp);
+    }
 }
 
 static void virt_machine_device_unplug_request_cb(HotplugHandler *hotplug_dev,
@@ -1985,7 +2023,8 @@ static HotplugHandler *virt_machine_get_hotplug_handler(MachineState *machine,
                                                         DeviceState *dev)
 {
     if (object_dynamic_cast(OBJECT(dev), TYPE_SYS_BUS_DEVICE) ||
-       (object_dynamic_cast(OBJECT(dev), TYPE_PC_DIMM))) {
+       (object_dynamic_cast(OBJECT(dev), TYPE_PC_DIMM)) ||
+       (object_dynamic_cast(OBJECT(dev), TYPE_VIRTIO_IOMMU_PCI))) {
         return HOTPLUG_HANDLER(machine);
     }
 
hw/virtio/virtio-iommu-pci.c +0 -3
index 280230b31e..4cfae1f9df 100644
@@ -31,9 +31,6 @@ struct VirtIOIOMMUPCI {
 
 static Property virtio_iommu_pci_properties[] = {
     DEFINE_PROP_UINT32("class", VirtIOPCIProxy, class_code, 0),
-    DEFINE_PROP_ARRAY("reserved-regions", VirtIOIOMMUPCI,
-                      vdev.nb_reserved_regions, vdev.reserved_regions,
-                      qdev_prop_interval, Interval),
     DEFINE_PROP_END_OF_LIST(),
 };
 
include/hw/arm/virt.h +2 -0
index 0b41083e9d..32fb1142ef 100644
@@ -124,8 +124,10 @@ typedef struct {
     bool virt;
     int32_t gic_version;
     VirtIOMMUType iommu;
+    uint16_t virtio_iommu_bdf;
     struct arm_boot_info bootinfo;
     MemMapEntry *memmap;
+    char *pciehb_nodename;
     const int *irqmap;
     int smp_cpus;
     void *fdt;
Signature · 1 line
2.20.1
Reviewed-by on v11 11/20
#53 lore raw

Re: [PATCH for-5.0 v11 11/20] hw/arm/virt: Add the virtio-iommu device tree mappings

hw/virtio/virtio-iommu-pci.c struct VirtIOIOMMUPCI { · line 36

Quoted 11 lines · Eric Auger
hw/virtio/virtio-iommu-pci.c +0 -3
index 280230b31e..4cfae1f9df 100644
@@ -31,9 +31,6 @@ struct VirtIOIOMMUPCI {
 
 static Property virtio_iommu_pci_properties[] = {
     DEFINE_PROP_UINT32("class", VirtIOPCIProxy, class_code, 0),
-    DEFINE_PROP_ARRAY("reserved-regions", VirtIOIOMMUPCI,
-                      vdev.nb_reserved_regions, vdev.reserved_regions,
-                      qdev_prop_interval, Interval),

Belongs in patch 10?

Apart from that

author
#54 lore raw

PATCH v11 12/20 qapi: Introduce DEFINE_PROP_INTERVAL

In reply to Eric Auger

Introduce a new property defining a labelled interval:
<low address>,<high address>,label.

This will be used to encode reserved IOVA regions. The label is left undefined to ease reuse accross use cases.

For instance, in virtio-iommu use case, reserved IOVA regions will be passed by the machine code to the virtio-iommu-pci device (an array of those). The label will match the virtio_iommu_probe_resv_mem subtype value:
- VIRTIO_IOMMU_RESV_MEM_T_RESERVED (0)
- VIRTIO_IOMMU_RESV_MEM_T_MSI (1)

This is used to inform the virtio-iommu-pci device it should bypass the MSI region: 0xfee00000, 0xfeefffff, 1.

---
 hw/core/qdev-properties.c    | 90 ++++++++++++++++++++++++++++++++++++
 include/exec/memory.h        |  6 +++
 include/hw/qdev-properties.h |  3 ++
 include/qemu/typedefs.h      |  1 +
 4 files changed, 100 insertions(+)
hw/core/qdev-properties.c +90 -0
index ac28890e5a..8d70f34e37 100644
@@ -13,6 +13,7 @@
 #include "qapi/visitor.h"
 #include "chardev/char.h"
 #include "qemu/uuid.h"
+#include "qemu/cutils.h"
 
 void qdev_prop_set_after_realize(DeviceState *dev, const char *name,
                                   Error **errp)
@@ -585,6 +586,95 @@ const PropertyInfo qdev_prop_macaddr = {
     .set   = set_mac,
 };
 
+/* --- Labelled Interval --- */
+
+/*
+ * accepted syntax versions:
+ *   <low address>,<high address>,<type>
+ *   where low/high addresses are uint64_t in hexa (feat. 0x prefix)
+ *   and type is an unsigned integer
+ */
+static void get_interval(Object *obj, Visitor *v, const char *name,
+                         void *opaque, Error **errp)
+{
+    DeviceState *dev = DEVICE(obj);
+    Property *prop = opaque;
+    Interval *interval = qdev_get_prop_ptr(dev, prop);
+    char buffer[64];
+    char *p = buffer;
+
+    snprintf(buffer, sizeof(buffer), "0x%"PRIx64",0x%"PRIx64",%d",
+             interval->low, interval->high, interval->type);
+
+    visit_type_str(v, name, &p, errp);
+}
+
+static void set_interval(Object *obj, Visitor *v, const char *name,
+                         void *opaque, Error **errp)
+{
+    DeviceState *dev = DEVICE(obj);
+    Property *prop = opaque;
+    Interval *interval = qdev_get_prop_ptr(dev, prop);
+    Error *local_err = NULL;
+    unsigned int type;
+    gchar **fields;
+    uint64_t addr;
+    char *str;
+    int ret;
+
+    if (dev->realized) {
+        qdev_prop_set_after_realize(dev, name, errp);
+        return;
+    }
+
+    visit_type_str(v, name, &str, &local_err);
+    if (local_err) {
+        error_propagate(errp, local_err);
+        return;
+    }
+
+    fields = g_strsplit(str, ",", 3);
+
+    ret = qemu_strtou64(fields[0], NULL, 16, &addr);
+    if (!ret) {
+        interval->low = addr;
+    } else {
+        error_setg(errp, "Failed to decode interval low addr");
+        error_append_hint(errp,
+                          "should be an address in hexa with 0x prefix\n");
+        goto out;
+    }
+
+    ret = qemu_strtou64(fields[1], NULL, 16, &addr);
+    if (!ret) {
+        interval->high = addr;
+    } else {
+        error_setg(errp, "Failed to decode interval high addr");
+        error_append_hint(errp,
+                          "should be an address in hexa with 0x prefix\n");
+        goto out;
+    }
+
+    ret = qemu_strtoui(fields[2], NULL, 10, &type);
+    if (!ret) {
+        interval->type = type;
+    } else {
+        error_setg(errp, "Failed to decode interval type");
+        error_append_hint(errp, "should be an unsigned int in decimal\n");
+    }
+out:
+    g_free(str);
+    g_strfreev(fields);
+    return;
+}
+
+const PropertyInfo qdev_prop_interval = {
+    .name  = "labelled_interval",
+    .description = "Labelled interval, example: 0xFEE00000,0xFEEFFFFF,0",
+    .get   = get_interval,
+    .set   = set_interval,
+};
+
 /* --- on/off/auto --- */
 
 const PropertyInfo qdev_prop_on_off_auto = {
include/exec/memory.h +6 -0
index e499dc215b..e238d1c352 100644
@@ -57,6 +57,12 @@ struct MemoryRegionMmio {
     CPUWriteMemoryFunc *write[3];
 };
 
+struct Interval {
+    hwaddr low;
+    hwaddr high;
+    unsigned int type;
+};
+
 typedef struct IOMMUTLBEntry IOMMUTLBEntry;
 
 /* See address_space_translate: bit 0 is read, bit 1 is write.  */
include/hw/qdev-properties.h +3 -0
index c6a8cb5516..2ba7c8711b 100644
@@ -20,6 +20,7 @@ extern const PropertyInfo qdev_prop_chr;
 extern const PropertyInfo qdev_prop_tpm;
 extern const PropertyInfo qdev_prop_ptr;
 extern const PropertyInfo qdev_prop_macaddr;
+extern const PropertyInfo qdev_prop_interval;
 extern const PropertyInfo qdev_prop_on_off_auto;
 extern const PropertyInfo qdev_prop_losttickpolicy;
 extern const PropertyInfo qdev_prop_blockdev_on_error;
@@ -202,6 +203,8 @@ extern const PropertyInfo qdev_prop_pcie_link_width;
     DEFINE_PROP(_n, _s, _f, qdev_prop_drive_iothread, BlockBackend *)
 #define DEFINE_PROP_MACADDR(_n, _s, _f)         \
     DEFINE_PROP(_n, _s, _f, qdev_prop_macaddr, MACAddr)
+#define DEFINE_PROP_INTERVAL(_n, _s, _f)         \
+    DEFINE_PROP(_n, _s, _f, qdev_prop_interval, Interval)
 #define DEFINE_PROP_ON_OFF_AUTO(_n, _s, _f, _d) \
     DEFINE_PROP_SIGNED(_n, _s, _f, _d, qdev_prop_on_off_auto, OnOffAuto)
 #define DEFINE_PROP_LOSTTICKPOLICY(_n, _s, _f, _d) \
include/qemu/typedefs.h +1 -0
index 375770a80f..a827c9a3fe 100644
@@ -58,6 +58,7 @@ typedef struct ISABus ISABus;
 typedef struct ISADevice ISADevice;
 typedef struct IsaDma IsaDma;
 typedef struct MACAddr MACAddr;
+typedef struct Interval Interval;
 typedef struct MachineClass MachineClass;
 typedef struct MachineState MachineState;
 typedef struct MemoryListener MemoryListener;
Signature · 1 line
2.20.1
#55 lore raw

Re: [PATCH for-5.0 v11 12/20] qapi: Introduce DEFINE_PROP_INTERVAL

Quoted 137 lines · * Eric Auger ([email protected]) wrote:

Introduce a new property defining a labelled interval:
<low address>,<high address>,label.

This will be used to encode reserved IOVA regions. The label is left undefined to ease reuse accross use cases.

For instance, in virtio-iommu use case, reserved IOVA regions will be passed by the machine code to the virtio-iommu-pci device (an array of those). The label will match the virtio_iommu_probe_resv_mem subtype value:
- VIRTIO_IOMMU_RESV_MEM_T_RESERVED (0)
- VIRTIO_IOMMU_RESV_MEM_T_MSI (1)

This is used to inform the virtio-iommu-pci device it should bypass the MSI region: 0xfee00000, 0xfeefffff, 1.

---
 hw/core/qdev-properties.c    | 90 ++++++++++++++++++++++++++++++++++++
 include/exec/memory.h        |  6 +++
 include/hw/qdev-properties.h |  3 ++
 include/qemu/typedefs.h      |  1 +
 4 files changed, 100 insertions(+)
hw/core/qdev-properties.c +90 -0
index ac28890e5a..8d70f34e37 100644
@@ -13,6 +13,7 @@
 #include "qapi/visitor.h"
 #include "chardev/char.h"
 #include "qemu/uuid.h"
+#include "qemu/cutils.h"
 
 void qdev_prop_set_after_realize(DeviceState *dev, const char *name,
                                   Error **errp)
@@ -585,6 +586,95 @@ const PropertyInfo qdev_prop_macaddr = {
     .set   = set_mac,
 };
 
+/* --- Labelled Interval --- */
+
+/*
+ * accepted syntax versions:
+ *   <low address>,<high address>,<type>
+ *   where low/high addresses are uint64_t in hexa (feat. 0x prefix)
+ *   and type is an unsigned integer
+ */
+static void get_interval(Object *obj, Visitor *v, const char *name,
+                         void *opaque, Error **errp)
+{
+    DeviceState *dev = DEVICE(obj);
+    Property *prop = opaque;
+    Interval *interval = qdev_get_prop_ptr(dev, prop);
+    char buffer[64];
+    char *p = buffer;
+
+    snprintf(buffer, sizeof(buffer), "0x%"PRIx64",0x%"PRIx64",%d",
+             interval->low, interval->high, interval->type);
+
+    visit_type_str(v, name, &p, errp);
+}
+
+static void set_interval(Object *obj, Visitor *v, const char *name,
+                         void *opaque, Error **errp)
+{
+    DeviceState *dev = DEVICE(obj);
+    Property *prop = opaque;
+    Interval *interval = qdev_get_prop_ptr(dev, prop);
+    Error *local_err = NULL;
+    unsigned int type;
+    gchar **fields;
+    uint64_t addr;
+    char *str;
+    int ret;
+
+    if (dev->realized) {
+        qdev_prop_set_after_realize(dev, name, errp);
+        return;
+    }
+
+    visit_type_str(v, name, &str, &local_err);
+    if (local_err) {
+        error_propagate(errp, local_err);
+        return;
+    }
+
+    fields = g_strsplit(str, ",", 3);
+
+    ret = qemu_strtou64(fields[0], NULL, 16, &addr);
+    if (!ret) {
+        interval->low = addr;
+    } else {
+        error_setg(errp, "Failed to decode interval low addr");
+        error_append_hint(errp,
+                          "should be an address in hexa with 0x prefix\n");
+        goto out;
+    }
+
+    ret = qemu_strtou64(fields[1], NULL, 16, &addr);
+    if (!ret) {
+        interval->high = addr;
+    } else {
+        error_setg(errp, "Failed to decode interval high addr");
+        error_append_hint(errp,
+                          "should be an address in hexa with 0x prefix\n");
+        goto out;
+    }
+
+    ret = qemu_strtoui(fields[2], NULL, 10, &type);
+    if (!ret) {
+        interval->type = type;
+    } else {
+        error_setg(errp, "Failed to decode interval type");
+        error_append_hint(errp, "should be an unsigned int in decimal\n");
+    }
+out:
+    g_free(str);
+    g_strfreev(fields);
+    return;
+}
+
+const PropertyInfo qdev_prop_interval = {
+    .name  = "labelled_interval",
+    .description = "Labelled interval, example: 0xFEE00000,0xFEEFFFFF,0",
+    .get   = get_interval,
+    .set   = set_interval,
+};
+
 /* --- on/off/auto --- */
 
 const PropertyInfo qdev_prop_on_off_auto = {
include/exec/memory.h +0 -0
index e499dc215b..e238d1c352 100644

include/exec/memory.h struct MemoryRegionMmio { · line 65

Quoted 9 lines
include/exec/memory.h +6 -0
@@ -57,6 +57,12 @@ struct MemoryRegionMmio {
     CPUWriteMemoryFunc *write[3];
 };
 
+struct Interval {
+    hwaddr low;
+    hwaddr high;
+    unsigned int type;
+};
+

Just an observation that 'Interval' is a very generic name. We've got 'AddrRange' but that's Int128.

Dave

Quoted 39 lines
include/exec/memory.h +0 -0
 typedef struct IOMMUTLBEntry IOMMUTLBEntry;
 
 /* See address_space_translate: bit 0 is read, bit 1 is write.  */
include/hw/qdev-properties.h +3 -0
index c6a8cb5516..2ba7c8711b 100644
@@ -20,6 +20,7 @@ extern const PropertyInfo qdev_prop_chr;
 extern const PropertyInfo qdev_prop_tpm;
 extern const PropertyInfo qdev_prop_ptr;
 extern const PropertyInfo qdev_prop_macaddr;
+extern const PropertyInfo qdev_prop_interval;
 extern const PropertyInfo qdev_prop_on_off_auto;
 extern const PropertyInfo qdev_prop_losttickpolicy;
 extern const PropertyInfo qdev_prop_blockdev_on_error;
@@ -202,6 +203,8 @@ extern const PropertyInfo qdev_prop_pcie_link_width;
     DEFINE_PROP(_n, _s, _f, qdev_prop_drive_iothread, BlockBackend *)
 #define DEFINE_PROP_MACADDR(_n, _s, _f)         \
     DEFINE_PROP(_n, _s, _f, qdev_prop_macaddr, MACAddr)
+#define DEFINE_PROP_INTERVAL(_n, _s, _f)         \
+    DEFINE_PROP(_n, _s, _f, qdev_prop_interval, Interval)
 #define DEFINE_PROP_ON_OFF_AUTO(_n, _s, _f, _d) \
     DEFINE_PROP_SIGNED(_n, _s, _f, _d, qdev_prop_on_off_auto, OnOffAuto)
 #define DEFINE_PROP_LOSTTICKPOLICY(_n, _s, _f, _d) \
include/qemu/typedefs.h +1 -0
index 375770a80f..a827c9a3fe 100644
@@ -58,6 +58,7 @@ typedef struct ISABus ISABus;
 typedef struct ISADevice ISADevice;
 typedef struct IsaDma IsaDma;
 typedef struct MACAddr MACAddr;
+typedef struct Interval Interval;
 typedef struct MachineClass MachineClass;
 typedef struct MachineState MachineState;
 typedef struct MemoryListener MemoryListener;
Signature · 1 line
2.20.1

--
Dr. David Alan Gilbert / [email protected] / Manchester, UK

author
#56 lore raw

Re: [PATCH for-5.0 v11 12/20] qapi: Introduce DEFINE_PROP_INTERVAL

Hi Dave,

Quoted 141 lines · Dr. David Alan Gilbert
Quoted 140 lines · * Eric Auger ([email protected]) wrote:

Introduce a new property defining a labelled interval:
<low address>,<high address>,label.

This will be used to encode reserved IOVA regions. The label is left undefined to ease reuse accross use cases.

For instance, in virtio-iommu use case, reserved IOVA regions will be passed by the machine code to the virtio-iommu-pci device (an array of those). The label will match the virtio_iommu_probe_resv_mem subtype value:
- VIRTIO_IOMMU_RESV_MEM_T_RESERVED (0)
- VIRTIO_IOMMU_RESV_MEM_T_MSI (1)

This is used to inform the virtio-iommu-pci device it should bypass the MSI region: 0xfee00000, 0xfeefffff, 1.

---
 hw/core/qdev-properties.c    | 90 ++++++++++++++++++++++++++++++++++++
 include/exec/memory.h        |  6 +++
 include/hw/qdev-properties.h |  3 ++
 include/qemu/typedefs.h      |  1 +
 4 files changed, 100 insertions(+)
hw/core/qdev-properties.c +90 -0
index ac28890e5a..8d70f34e37 100644
@@ -13,6 +13,7 @@
 #include "qapi/visitor.h"
 #include "chardev/char.h"
 #include "qemu/uuid.h"
+#include "qemu/cutils.h"
 
 void qdev_prop_set_after_realize(DeviceState *dev, const char *name,
                                   Error **errp)
@@ -585,6 +586,95 @@ const PropertyInfo qdev_prop_macaddr = {
     .set   = set_mac,
 };
 
+/* --- Labelled Interval --- */
+
+/*
+ * accepted syntax versions:
+ *   <low address>,<high address>,<type>
+ *   where low/high addresses are uint64_t in hexa (feat. 0x prefix)
+ *   and type is an unsigned integer
+ */
+static void get_interval(Object *obj, Visitor *v, const char *name,
+                         void *opaque, Error **errp)
+{
+    DeviceState *dev = DEVICE(obj);
+    Property *prop = opaque;
+    Interval *interval = qdev_get_prop_ptr(dev, prop);
+    char buffer[64];
+    char *p = buffer;
+
+    snprintf(buffer, sizeof(buffer), "0x%"PRIx64",0x%"PRIx64",%d",
+             interval->low, interval->high, interval->type);
+
+    visit_type_str(v, name, &p, errp);
+}
+
+static void set_interval(Object *obj, Visitor *v, const char *name,
+                         void *opaque, Error **errp)
+{
+    DeviceState *dev = DEVICE(obj);
+    Property *prop = opaque;
+    Interval *interval = qdev_get_prop_ptr(dev, prop);
+    Error *local_err = NULL;
+    unsigned int type;
+    gchar **fields;
+    uint64_t addr;
+    char *str;
+    int ret;
+
+    if (dev->realized) {
+        qdev_prop_set_after_realize(dev, name, errp);
+        return;
+    }
+
+    visit_type_str(v, name, &str, &local_err);
+    if (local_err) {
+        error_propagate(errp, local_err);
+        return;
+    }
+
+    fields = g_strsplit(str, ",", 3);
+
+    ret = qemu_strtou64(fields[0], NULL, 16, &addr);
+    if (!ret) {
+        interval->low = addr;
+    } else {
+        error_setg(errp, "Failed to decode interval low addr");
+        error_append_hint(errp,
+                          "should be an address in hexa with 0x prefix\n");
+        goto out;
+    }
+
+    ret = qemu_strtou64(fields[1], NULL, 16, &addr);
+    if (!ret) {
+        interval->high = addr;
+    } else {
+        error_setg(errp, "Failed to decode interval high addr");
+        error_append_hint(errp,
+                          "should be an address in hexa with 0x prefix\n");
+        goto out;
+    }
+
+    ret = qemu_strtoui(fields[2], NULL, 10, &type);
+    if (!ret) {
+        interval->type = type;
+    } else {
+        error_setg(errp, "Failed to decode interval type");
+        error_append_hint(errp, "should be an unsigned int in decimal\n");
+    }
+out:
+    g_free(str);
+    g_strfreev(fields);
+    return;
+}
+
+const PropertyInfo qdev_prop_interval = {
+    .name  = "labelled_interval",
+    .description = "Labelled interval, example: 0xFEE00000,0xFEEFFFFF,0",
+    .get   = get_interval,
+    .set   = set_interval,
+};
+
 /* --- on/off/auto --- */
 
 const PropertyInfo qdev_prop_on_off_auto = {
include/exec/memory.h +0 -0
index e499dc215b..e238d1c352 100644
@@ -57,6 +57,12 @@ struct MemoryRegionMmio {
     CPUWriteMemoryFunc *write[3];
 };
 
Quoted 9 lines

include/exec/memory.h struct MemoryRegionMmio { · line 65

Quoted 6 lines
include/exec/memory.h +6 -0
+struct Interval {
+    hwaddr low;
+    hwaddr high;
+    unsigned int type;
+};
+

Just an observation that 'Interval' is a very generic name. We've got 'AddrRange' but that's Int128.

As it is defined in memory.h it may make sense to rename it ReservedRegion then?

Thanks

Eric

Quoted 45 lines

Dave

Quoted 39 lines
include/exec/memory.h +0 -0
 typedef struct IOMMUTLBEntry IOMMUTLBEntry;
 
 /* See address_space_translate: bit 0 is read, bit 1 is write.  */
include/hw/qdev-properties.h +3 -0
index c6a8cb5516..2ba7c8711b 100644
@@ -20,6 +20,7 @@ extern const PropertyInfo qdev_prop_chr;
 extern const PropertyInfo qdev_prop_tpm;
 extern const PropertyInfo qdev_prop_ptr;
 extern const PropertyInfo qdev_prop_macaddr;
+extern const PropertyInfo qdev_prop_interval;
 extern const PropertyInfo qdev_prop_on_off_auto;
 extern const PropertyInfo qdev_prop_losttickpolicy;
 extern const PropertyInfo qdev_prop_blockdev_on_error;
@@ -202,6 +203,8 @@ extern const PropertyInfo qdev_prop_pcie_link_width;
     DEFINE_PROP(_n, _s, _f, qdev_prop_drive_iothread, BlockBackend *)
 #define DEFINE_PROP_MACADDR(_n, _s, _f)         \
     DEFINE_PROP(_n, _s, _f, qdev_prop_macaddr, MACAddr)
+#define DEFINE_PROP_INTERVAL(_n, _s, _f)         \
+    DEFINE_PROP(_n, _s, _f, qdev_prop_interval, Interval)
 #define DEFINE_PROP_ON_OFF_AUTO(_n, _s, _f, _d) \
     DEFINE_PROP_SIGNED(_n, _s, _f, _d, qdev_prop_on_off_auto, OnOffAuto)
 #define DEFINE_PROP_LOSTTICKPOLICY(_n, _s, _f, _d) \
include/qemu/typedefs.h +1 -0
index 375770a80f..a827c9a3fe 100644
@@ -58,6 +58,7 @@ typedef struct ISABus ISABus;
 typedef struct ISADevice ISADevice;
 typedef struct IsaDma IsaDma;
 typedef struct MACAddr MACAddr;
+typedef struct Interval Interval;
 typedef struct MachineClass MachineClass;
 typedef struct MachineState MachineState;
 typedef struct MemoryListener MemoryListener;
Signature · 1 line
2.20.1

--
Dr. David Alan Gilbert / [email protected] / Manchester, UK

#57 lore raw

Re: [PATCH for-5.0 v11 12/20] qapi: Introduce DEFINE_PROP_INTERVAL

In reply to Eric Auger
Quoted 5 lines · Eric Auger

Introduce a new property defining a labelled interval:
<low address>,<high address>,label.

This will be used to encode reserved IOVA regions. The label is left undefined to ease reuse accross use cases.

What does the last sentence mean?

Quoted 9 lines

For instance, in virtio-iommu use case, reserved IOVA regions will be passed by the machine code to the virtio-iommu-pci device (an array of those). The label will match the virtio_iommu_probe_resv_mem subtype value:
- VIRTIO_IOMMU_RESV_MEM_T_RESERVED (0)
- VIRTIO_IOMMU_RESV_MEM_T_MSI (1)

This is used to inform the virtio-iommu-pci device it should bypass the MSI region: 0xfee00000, 0xfeefffff, 1.

So the "label" part of "<low address>,<high address>,label" is a number?

Is a number appropriate for your use case, or would an enum be better?

Quoted 5 lines

hw/core/qdev-properties.c | 90 ++++++++++++++++++++++++++++++++++++ include/exec/memory.h | 6 +++ include/hw/qdev-properties.h | 3 ++ include/qemu/typedefs.h | 1 + 4 files changed, 100 insertions(+)

Subject has 'qapi:', but it's actually about qdev. Please adjust the subject.

Quoted 13 lines
hw/core/qdev-properties.c +1 -0
index ac28890e5a..8d70f34e37 100644
@@ -13,6 +13,7 @@
 #include "qapi/visitor.h"
 #include "chardev/char.h"
 #include "qemu/uuid.h"
+#include "qemu/cutils.h"
 
 void qdev_prop_set_after_realize(DeviceState *dev, const char *name,
                                   Error **errp)

hw/core/qdev-properties.c const PropertyInfo qdev_prop_macaddr = { · line 592

Quoted 7 lines
hw/core/qdev-properties.c +4 -0
@@ -585,6 +586,95 @@ const PropertyInfo qdev_prop_macaddr = {
     .set   = set_mac,
 };
 
+/* --- Labelled Interval --- */
+
+/*
+ * accepted syntax versions:

"versions"?

hw/core/qdev-properties.c const PropertyInfo qdev_prop_macaddr = { · line 594

Quoted 2 lines
hw/core/qdev-properties.c +2 -0
+ *   <low address>,<high address>,<type>
+ *   where low/high addresses are uint64_t in hexa (feat. 0x prefix)

"hexa" is not a word.

I'm afraid I don't get the parenthesis.

hw/core/qdev-properties.c const PropertyInfo qdev_prop_macaddr = { · line 607

Quoted 13 lines
hw/core/qdev-properties.c +13 -0
+ *   and type is an unsigned integer
+ */
+static void get_interval(Object *obj, Visitor *v, const char *name,
+                         void *opaque, Error **errp)
+{
+    DeviceState *dev = DEVICE(obj);
+    Property *prop = opaque;
+    Interval *interval = qdev_get_prop_ptr(dev, prop);
+    char buffer[64];
+    char *p = buffer;
+
+    Snprintf(buffer, sizeof(buffer), "0x%"PRIx64",0x%"PRIx64",%d",
+             interval->low, interval->high, interval->type);

interval->type is unsigned. Use %u, not %d.

Quoted 21 lines
hw/core/qdev-properties.c +21 -0
+
+    visit_type_str(v, name, &p, errp);
+}
+
+static void set_interval(Object *obj, Visitor *v, const char *name,
+                         void *opaque, Error **errp)
+{
+    DeviceState *dev = DEVICE(obj);
+    Property *prop = opaque;
+    Interval *interval = qdev_get_prop_ptr(dev, prop);
+    Error *local_err = NULL;
+    unsigned int type;
+    gchar **fields;
+    uint64_t addr;
+    char *str;
+    int ret;
+
+    if (dev->realized) {
+        qdev_prop_set_after_realize(dev, name, errp);
+        return;
+    }

hw/core/qdev-properties.c const PropertyInfo qdev_prop_macaddr = { · line 638

Quoted 10 lines
hw/core/qdev-properties.c +10 -0
+
+    visit_type_str(v, name, &str, &local_err);
+    if (local_err) {
+        error_propagate(errp, local_err);
+        return;
+    }
+
+    fields = g_strsplit(str, ",", 3);
+
+    ret = qemu_strtou64(fields[0], NULL, 16, &addr);

Aha, the 0x prefix is actually optional.

hw/core/qdev-properties.c const PropertyInfo qdev_prop_macaddr = { · line 644

Quoted 6 lines
hw/core/qdev-properties.c +6 -0
+    if (!ret) {
+        interval->low = addr;
+    } else {
+        error_setg(errp, "Failed to decode interval low addr");
+        error_append_hint(errp,
+                          "should be an address in hexa with 0x prefix\n");

"hexa" is not a word, and the 0x prefix is actually optional.

hw/core/qdev-properties.c const PropertyInfo qdev_prop_macaddr = { · line 646

Quoted 2 lines
hw/core/qdev-properties.c +2 -0
+        goto out;
+    }

I prefer

       if (error) {
           handle error
           bail out
       }
       handle success

over

       if (success) {
           handle success
       if (error) {
           handle error
           bail out
       }

In this case:

       if (ret) {
           error_setg(errp, "Failed to decode interval low addr");
           error_append_hint(errp,
                             "should be an address in hexa with 0x prefix\n");
           goto out;
       }
       interval->low = addr;

hw/core/qdev-properties.c const PropertyInfo qdev_prop_macaddr = { · line 648

Quoted 2 lines
hw/core/qdev-properties.c +2 -0
+
+    ret = qemu_strtou64(fields[1], NULL, 16, &addr);

Crash if @str doesn't contain ',', because the g_strsplit(str, ",", 3) yields { [0] = str, NULL }.

hw/core/qdev-properties.c const PropertyInfo qdev_prop_macaddr = { · line 658

Quoted 10 lines
hw/core/qdev-properties.c +10 -0
+    if (!ret) {
+        interval->high = addr;
+    } else {
+        error_setg(errp, "Failed to decode interval high addr");
+        error_append_hint(errp,
+                          "should be an address in hexa with 0x prefix\n");
+        goto out;
+    }
+
+    ret = qemu_strtoui(fields[2], NULL, 10, &type);

Likewise, crash if @str contains only one ','.

I wouldn't use g_strsplit() here. After

    ret = qemu_strtoui(str, &endptr, 16, &interval->low);

@endptr points behind the address. So:

    if (ret || *endptr != ',') {
        handle error ...
        goto out
    }

    ret = qemu_strtoui(endptr + 1, &endptr, 16, &interval->high);

and so forth.

Note that the if (ret || *endptr != ',') checks for two distinct errors. Distinct error messages might be more helpful.

Quoted 27 lines
hw/core/qdev-properties.c +19 -0
+    if (!ret) {
+        interval->type = type;
+    } else {
+        error_setg(errp, "Failed to decode interval type");
+        error_append_hint(errp, "should be an unsigned int in decimal\n");
+    }
+out:
+    g_free(str);
+    g_strfreev(fields);
+    return;
+}
+
+const PropertyInfo qdev_prop_interval = {
+    .name  = "labelled_interval",
+    .description = "Labelled interval, example: 0xFEE00000,0xFEEFFFFF,0",
+    .get   = get_interval,
+    .set   = set_interval,
+};
+
 /* --- on/off/auto --- */
 
 const PropertyInfo qdev_prop_on_off_auto = {
include/exec/memory.h +0 -0
index e499dc215b..e238d1c352 100644

include/exec/memory.h struct MemoryRegionMmio { · line 64

Quoted 8 lines
include/exec/memory.h +5 -0
@@ -57,6 +57,12 @@ struct MemoryRegionMmio {
     CPUWriteMemoryFunc *write[3];
 };
 
+struct Interval {
+    hwaddr low;
+    hwaddr high;
+    unsigned int type;
+};

This isn't an interval. An interval consists of two values, not three.

The third one is called "type" here, and "label" elsewhere. Pick one and stick to it.

Then pick a name for the triple. Elsewhere, you call it "labelled interval".

Quoted 37 lines
include/exec/memory.h +1 -0
+
 typedef struct IOMMUTLBEntry IOMMUTLBEntry;
 
 /* See address_space_translate: bit 0 is read, bit 1 is write.  */
include/hw/qdev-properties.h +3 -0
index c6a8cb5516..2ba7c8711b 100644
@@ -20,6 +20,7 @@ extern const PropertyInfo qdev_prop_chr;
 extern const PropertyInfo qdev_prop_tpm;
 extern const PropertyInfo qdev_prop_ptr;
 extern const PropertyInfo qdev_prop_macaddr;
+extern const PropertyInfo qdev_prop_interval;
 extern const PropertyInfo qdev_prop_on_off_auto;
 extern const PropertyInfo qdev_prop_losttickpolicy;
 extern const PropertyInfo qdev_prop_blockdev_on_error;
@@ -202,6 +203,8 @@ extern const PropertyInfo qdev_prop_pcie_link_width;
     DEFINE_PROP(_n, _s, _f, qdev_prop_drive_iothread, BlockBackend *)
 #define DEFINE_PROP_MACADDR(_n, _s, _f)         \
     DEFINE_PROP(_n, _s, _f, qdev_prop_macaddr, MACAddr)
+#define DEFINE_PROP_INTERVAL(_n, _s, _f)         \
+    DEFINE_PROP(_n, _s, _f, qdev_prop_interval, Interval)
 #define DEFINE_PROP_ON_OFF_AUTO(_n, _s, _f, _d) \
     DEFINE_PROP_SIGNED(_n, _s, _f, _d, qdev_prop_on_off_auto, OnOffAuto)
 #define DEFINE_PROP_LOSTTICKPOLICY(_n, _s, _f, _d) \
include/qemu/typedefs.h +1 -0
index 375770a80f..a827c9a3fe 100644
@@ -58,6 +58,7 @@ typedef struct ISABus ISABus;
 typedef struct ISADevice ISADevice;
 typedef struct IsaDma IsaDma;
 typedef struct MACAddr MACAddr;
+typedef struct Interval Interval;
 typedef struct MachineClass MachineClass;
 typedef struct MachineState MachineState;
 typedef struct MemoryListener MemoryListener;
author
#58 lore raw

Re: [PATCH for-5.0 v11 12/20] qapi: Introduce DEFINE_PROP_INTERVAL

Hi Markus,

Quoted 9 lines · Markus Armbruster
Quoted 5 lines · Eric Auger

Introduce a new property defining a labelled interval:
<low address>,<high address>,label.

This will be used to encode reserved IOVA regions. The label is left undefined to ease reuse accross use cases.

What does the last sentence mean?

The dilemma was shall I specialize this property such as ReservedRegion or shall I leave it generic enough to serve somebody else use case. I first chose the latter but now I think I should rather call it something like ReservedRegion as in any case it has addresses and an integer label.

Quoted 8 lines
Quoted 8 lines

For instance, in virtio-iommu use case, reserved IOVA regions will be passed by the machine code to the virtio-iommu-pci device (an array of those). The label will match the virtio_iommu_probe_resv_mem subtype value:
- VIRTIO_IOMMU_RESV_MEM_T_RESERVED (0)
- VIRTIO_IOMMU_RESV_MEM_T_MSI (1)

Quoted 4 lines
Quoted 2 lines

This is used to inform the virtio-iommu-pci device it should bypass the MSI region: 0xfee00000, 0xfeefffff, 1.

So the "label" part of "<low address>,<high address>,label" is a number?

yes it is.

Quoted 2 lines

Is a number appropriate for your use case, or would an enum be better?

I think a number is OK. There might be other types of reserved regions in the future. Also if we want to allow somebody else to reuse that property in another context, I would rather leave it open?

Quoted 8 lines
Quoted 6 lines

hw/core/qdev-properties.c | 90 ++++++++++++++++++++++++++++++++++++ include/exec/memory.h | 6 +++ include/hw/qdev-properties.h | 3 ++ include/qemu/typedefs.h | 1 + 4 files changed, 100 insertions(+)

Subject has 'qapi:', but it's actually about qdev. Please adjust the subject.

OK

Quoted 17 lines
Quoted 17 lines
hw/core/qdev-properties.c +1 -0
index ac28890e5a..8d70f34e37 100644
@@ -13,6 +13,7 @@
 #include "qapi/visitor.h"
 #include "chardev/char.h"
 #include "qemu/uuid.h"
+#include "qemu/cutils.h"
 
 void qdev_prop_set_after_realize(DeviceState *dev, const char *name,
                                   Error **errp)
@@ -585,6 +586,95 @@ const PropertyInfo qdev_prop_macaddr = {
     .set   = set_mac,
 };
 
Quoted 6 lines

hw/core/qdev-properties.c const PropertyInfo qdev_prop_macaddr = { · line 592

Quoted 4 lines
hw/core/qdev-properties.c +4 -0
+/* --- Labelled Interval --- */
+
+/*
+ * accepted syntax versions:

"versions"?

s/versions/version

Quoted 5 lines

hw/core/qdev-properties.c const PropertyInfo qdev_prop_macaddr = { · line 594

Quoted 3 lines
hw/core/qdev-properties.c +2 -0
+ *   <low address>,<high address>,<type>
+ *   where low/high addresses are uint64_t in hexa (feat. 0x prefix)

"hexa" is not a word.

OK

Quoted 2 lines

I'm afraid I don't get the parenthesis.

I wanted to mention the 0x prefix was needed but as you mentionned below it is not needed actually.

Quoted 16 lines
Quoted 4 lines
hw/core/qdev-properties.c +3 -0
+ *   and type is an unsigned integer
+ */
+static void get_interval(Object *obj, Visitor *v, const char *name,

hw/core/qdev-properties.c const PropertyInfo qdev_prop_macaddr = { · line 607

Quoted 10 lines
hw/core/qdev-properties.c +10 -0
+                         void *opaque, Error **errp)
+{
+    DeviceState *dev = DEVICE(obj);
+    Property *prop = opaque;
+    Interval *interval = qdev_get_prop_ptr(dev, prop);
+    char buffer[64];
+    char *p = buffer;
+
+    Snprintf(buffer, sizeof(buffer), "0x%"PRIx64",0x%"PRIx64",%d",
+             interval->low, interval->high, interval->type);

interval->type is unsigned. Use %u, not %d.

OK

Quoted 35 lines
Quoted 22 lines
hw/core/qdev-properties.c +21 -0
+
+    visit_type_str(v, name, &p, errp);
+}
+
+static void set_interval(Object *obj, Visitor *v, const char *name,
+                         void *opaque, Error **errp)
+{
+    DeviceState *dev = DEVICE(obj);
+    Property *prop = opaque;
+    Interval *interval = qdev_get_prop_ptr(dev, prop);
+    Error *local_err = NULL;
+    unsigned int type;
+    gchar **fields;
+    uint64_t addr;
+    char *str;
+    int ret;
+
+    if (dev->realized) {
+        qdev_prop_set_after_realize(dev, name, errp);
+        return;
+    }

hw/core/qdev-properties.c const PropertyInfo qdev_prop_macaddr = { · line 638

Quoted 10 lines
hw/core/qdev-properties.c +10 -0
+
+    visit_type_str(v, name, &str, &local_err);
+    if (local_err) {
+        error_propagate(errp, local_err);
+        return;
+    }
+
+    fields = g_strsplit(str, ",", 3);
+
+    ret = qemu_strtou64(fields[0], NULL, 16, &addr);

Aha, the 0x prefix is actually optional.

Quoted 8 lines

hw/core/qdev-properties.c const PropertyInfo qdev_prop_macaddr = { · line 644

Quoted 6 lines
hw/core/qdev-properties.c +6 -0
+    if (!ret) {
+        interval->low = addr;
+    } else {
+        error_setg(errp, "Failed to decode interval low addr");
+        error_append_hint(errp,
+                          "should be an address in hexa with 0x prefix\n");

"hexa" is not a word, and the 0x prefix is actually optional.

OK

Quoted 23 lines

hw/core/qdev-properties.c const PropertyInfo qdev_prop_macaddr = { · line 646

Quoted 3 lines
hw/core/qdev-properties.c +2 -0
+        goto out;
+    }

I prefer

       if (error) {
           handle error
           bail out
       }
       handle success

over

       if (success) {
           handle success
       if (error) {
           handle error
           bail out
       }

In this case:

Quoted 7 lines
       if (ret) {
           error_setg(errp, "Failed to decode interval low addr");
           error_append_hint(errp,
                             "should be an address in hexa with 0x prefix\n");
           goto out;
       }
       interval->low = addr;

OK

Quoted 34 lines

hw/core/qdev-properties.c const PropertyInfo qdev_prop_macaddr = { · line 648

Quoted 4 lines
hw/core/qdev-properties.c +2 -0
+
+    ret = qemu_strtou64(fields[1], NULL, 16, &addr);

Crash if @str doesn't contain ',', because the g_strsplit(str, ",", 3) yields { [0] = str, NULL }.

hw/core/qdev-properties.c const PropertyInfo qdev_prop_macaddr = { · line 658

Quoted 10 lines
hw/core/qdev-properties.c +10 -0
+    if (!ret) {
+        interval->high = addr;
+    } else {
+        error_setg(errp, "Failed to decode interval high addr");
+        error_append_hint(errp,
+                          "should be an address in hexa with 0x prefix\n");
+        goto out;
+    }
+
+    ret = qemu_strtoui(fields[2], NULL, 10, &type);

Likewise, crash if @str contains only one ','.

I wouldn't use g_strsplit() here. After

    ret = qemu_strtoui(str, &endptr, 16, &interval->low);

@endptr points behind the address. So:

    if (ret || *endptr != ',') {
        handle error ...
        goto out
    }

    ret = qemu_strtoui(endptr + 1, &endptr, 16, &interval->high);
Quoted 4 lines

and so forth.

Note that the if (ret || *endptr != ',') checks for two distinct errors. Distinct error messages might be more helpful.

OK I will revisit that.

Quoted 39 lines
Quoted 28 lines
hw/core/qdev-properties.c +19 -0
+    if (!ret) {
+        interval->type = type;
+    } else {
+        error_setg(errp, "Failed to decode interval type");
+        error_append_hint(errp, "should be an unsigned int in decimal\n");
+    }
+out:
+    g_free(str);
+    g_strfreev(fields);
+    return;
+}
+
+const PropertyInfo qdev_prop_interval = {
+    .name  = "labelled_interval",
+    .description = "Labelled interval, example: 0xFEE00000,0xFEEFFFFF,0",
+    .get   = get_interval,
+    .set   = set_interval,
+};
+
 /* --- on/off/auto --- */
 
 const PropertyInfo qdev_prop_on_off_auto = {
include/exec/memory.h +0 -0
index e499dc215b..e238d1c352 100644

include/exec/memory.h struct MemoryRegionMmio { · line 64

Quoted 8 lines
include/exec/memory.h +5 -0
@@ -57,6 +57,12 @@ struct MemoryRegionMmio {
     CPUWriteMemoryFunc *write[3];
 };
 
+struct Interval {
+    hwaddr low;
+    hwaddr high;
+    unsigned int type;
+};

This isn't an interval. An interval consists of two values, not three.

Quoted 5 lines

The third one is called "type" here, and "label" elsewhere. Pick one and stick to it.

Then pick a name for the triple. Elsewhere, you call it "labelled interval".

I would tend to use ReservedRegion now if nobody objects.

Thank you for the review!

Eric

Quoted 40 lines
Quoted 38 lines
include/exec/memory.h +1 -0
+
 typedef struct IOMMUTLBEntry IOMMUTLBEntry;
 
 /* See address_space_translate: bit 0 is read, bit 1 is write.  */
include/hw/qdev-properties.h +3 -0
index c6a8cb5516..2ba7c8711b 100644
@@ -20,6 +20,7 @@ extern const PropertyInfo qdev_prop_chr;
 extern const PropertyInfo qdev_prop_tpm;
 extern const PropertyInfo qdev_prop_ptr;
 extern const PropertyInfo qdev_prop_macaddr;
+extern const PropertyInfo qdev_prop_interval;
 extern const PropertyInfo qdev_prop_on_off_auto;
 extern const PropertyInfo qdev_prop_losttickpolicy;
 extern const PropertyInfo qdev_prop_blockdev_on_error;
@@ -202,6 +203,8 @@ extern const PropertyInfo qdev_prop_pcie_link_width;
     DEFINE_PROP(_n, _s, _f, qdev_prop_drive_iothread, BlockBackend *)
 #define DEFINE_PROP_MACADDR(_n, _s, _f)         \
     DEFINE_PROP(_n, _s, _f, qdev_prop_macaddr, MACAddr)
+#define DEFINE_PROP_INTERVAL(_n, _s, _f)         \
+    DEFINE_PROP(_n, _s, _f, qdev_prop_interval, Interval)
 #define DEFINE_PROP_ON_OFF_AUTO(_n, _s, _f, _d) \
     DEFINE_PROP_SIGNED(_n, _s, _f, _d, qdev_prop_on_off_auto, OnOffAuto)
 #define DEFINE_PROP_LOSTTICKPOLICY(_n, _s, _f, _d) \
include/qemu/typedefs.h +1 -0
index 375770a80f..a827c9a3fe 100644
@@ -58,6 +58,7 @@ typedef struct ISABus ISABus;
 typedef struct ISADevice ISADevice;
 typedef struct IsaDma IsaDma;
 typedef struct MACAddr MACAddr;
+typedef struct Interval Interval;
 typedef struct MachineClass MachineClass;
 typedef struct MachineState MachineState;
 typedef struct MemoryListener MemoryListener;
#59 lore raw

Re: [PATCH for-5.0 v11 12/20] qapi: Introduce DEFINE_PROP_INTERVAL

Quoted 27 lines · Auger Eric

Hi Markus,

Quoted 9 lines · Markus Armbruster
Quoted 5 lines · Eric Auger

Introduce a new property defining a labelled interval:
<low address>,<high address>,label.

This will be used to encode reserved IOVA regions. The label is left undefined to ease reuse accross use cases.

What does the last sentence mean?

The dilemma was shall I specialize this property such as ReservedRegion or shall I leave it generic enough to serve somebody else use case. I first chose the latter but now I think I should rather call it something like ReservedRegion as in any case it has addresses and an integer label.

Quoted 11 lines
Quoted 10 lines

For instance, in virtio-iommu use case, reserved IOVA regions will be passed by the machine code to the virtio-iommu-pci device (an array of those). The label will match the virtio_iommu_probe_resv_mem subtype value:
- VIRTIO_IOMMU_RESV_MEM_T_RESERVED (0)
- VIRTIO_IOMMU_RESV_MEM_T_MSI (1)

This is used to inform the virtio-iommu-pci device it should bypass the MSI region: 0xfee00000, 0xfeefffff, 1.

Quoted 7 lines
Quoted 1 line

So the "label" part of "<low address>,<high address>,label" is a number?

yes it is.

Quoted 2 lines

Is a number appropriate for your use case, or would an enum be better?

I think a number is OK. There might be other types of reserved regions in the future. Also if we want to allow somebody else to reuse that property in another context, I would rather leave it open?

I'd prioritize the user interface over possible reuse (which might never happen). Mind, I'm not telling you using numbers is a bad user interface. In general, enums are nicer, but I don't know enough about this particular case.

Quoted 3 lines
Quoted 3 lines
Quoted 3 lines

[...]

Quoted 16 lines
Quoted 16 lines

include/exec/memory.h struct MemoryRegionMmio { · line 64

Quoted 13 lines
include/exec/memory.h +5 -0
index e499dc215b..e238d1c352 100644
@@ -57,6 +57,12 @@ struct MemoryRegionMmio {
     CPUWriteMemoryFunc *write[3];
 };
 
+struct Interval {
+    hwaddr low;
+    hwaddr high;
+    unsigned int type;
+};

This isn't an interval. An interval consists of two values, not three.

Quoted 6 lines
Quoted 5 lines

The third one is called "type" here, and "label" elsewhere. Pick one and stick to it.

Then pick a name for the triple. Elsewhere, you call it "labelled interval".

I would tend to use ReservedRegion now if nobody objects.

Sounds good to me.

Quoted 1 line

Thank you for the review!

You're welcome!

author
#60 lore raw

PATCH v11 13/20 virtio-iommu: Implement probe request

In reply to Eric Auger

This patch implements the PROBE request. At the moment, no reserved regions are returned as none are registered per device. Only a NONE property is returned.

---
v9 -> v10
- fully rewrite the code in preparation of
reserved_regions array property introduction

v8 -> v9:
- fix filling of properties (changes induced by v0.7 -> v0.8 spec evolution)
- return VIRTIO_IOMMU_S_INVAL in case of error

v7 -> v8:
- adapt to removal of value filed in virtio_iommu_probe_property

v6 -> v7:
- adapt to the change in virtio_iommu_probe_resv_mem fields
- use get_endpoint() instead of directly checking the EP was registered.

v4 -> v5:
- initialize bufstate.error to false
- add cpu_to_le64(size)

---
 hw/virtio/trace-events           |  1 +
 hw/virtio/virtio-iommu.c         | 89 +++++++++++++++++++++++++++++++-
 include/hw/virtio/virtio-iommu.h |  2 +
 3 files changed, 90 insertions(+), 2 deletions(-)
hw/virtio/trace-events +1 -0
index a572eb71aa..b7bc8ac6d1 100644
@@ -74,3 +74,4 @@ virtio_iommu_get_domain(uint32_t domain_id) "Alloc domain=%d"
 virtio_iommu_put_domain(uint32_t domain_id) "Free domain=%d"
 virtio_iommu_translate_out(uint64_t virt_addr, uint64_t phys_addr, uint32_t sid) "0x%"PRIx64" -> 0x%"PRIx64 " for sid=%d"
 virtio_iommu_report_fault(uint8_t reason, uint32_t flags, uint32_t endpoint, uint64_t addr) "FAULT reason=%d flags=%d endpoint=%d address =0x%"PRIx64
+virtio_iommu_fill_resv_property(uint32_t devid, uint8_t subtype, uint64_t start, uint64_t end) "dev= %d, type=%d start=0x%"PRIx64" end=0x%"PRIx64
hw/virtio/virtio-iommu.c +87 -2

134 lines not on this page · raw message

include/hw/virtio/virtio-iommu.h +2 -0
index 1ab6993d29..4176785368 100644
@@ -57,6 +57,8 @@ typedef struct VirtIOIOMMU {
     GHashTable *as_by_busptr;
     IOMMUPciBus *as_by_bus_num[IOMMU_PCI_BUS_MAX];
     PCIBus *primary_bus;
+    Interval *reserved_regions;
+    uint32_t nb_reserved_regions;
     GTree *domains;
     QemuMutex mutex;
     GTree *endpoints;
Signature · 1 line
2.20.1
author
#63 lore raw

PATCH v11 14/20 virtio-iommu: Handle reserved regions in the translation process

In reply to Eric Auger

When translating an address we need to check if it belongs to a reserved virtual address range. If it does, there are 2 cases:

- it belongs to a RESERVED region: the guest should neither use this address in a MAP not instruct the end-point to DMA on them. We report an error

- It belongs to an MSI region: we bypass the translation.

---

v10 -> v11:
- directly use the reserved_regions properties array

v9 -> v10:
- in case of MSI region, we immediatly return

---
 hw/virtio/virtio-iommu.c | 17 +++++++++++++++++
 1 file changed, 17 insertions(+)
hw/virtio/virtio-iommu.c +17 -0
index 1ce2218935..c5b202fab7 100644
@@ -548,6 +548,7 @@ static IOMMUTLBEntry virtio_iommu_translate(IOMMUMemoryRegion *mr, hwaddr addr,
     uint32_t sid, flags;
     bool bypass_allowed;
     bool found;
+    int i;
 
     interval.low = addr;
     interval.high = addr + 1;
@@ -580,6 +581,22 @@ static IOMMUTLBEntry virtio_iommu_translate(IOMMUMemoryRegion *mr, hwaddr addr,
         goto unlock;
     }
 
+    for (i = 0; i < s->nb_reserved_regions; i++) {
+        if (interval.low >= s->reserved_regions[i].low &&
+            interval.low <= s->reserved_regions[i].high) {
+            switch (s->reserved_regions[i].type) {
+            case VIRTIO_IOMMU_RESV_MEM_T_MSI:
+                entry.perm = flag;
+                goto unlock;
+            case VIRTIO_IOMMU_RESV_MEM_T_RESERVED:
+            default:
+                virtio_iommu_report_fault(s, VIRTIO_IOMMU_FAULT_R_MAPPING,
+                                          0, sid, addr);
+            goto unlock;
+           }
+        }
+    }
+
     if (!ep->domain) {
         if (!bypass_allowed) {
             qemu_log_mask(LOG_GUEST_ERROR,
Signature · 1 line
2.20.1
#64 lore raw

Re: [PATCH for-5.0 v11 14/20] virtio-iommu: Handle reserved regions in the translation process

hw/virtio/virtio-iommu.c static IOMMUTLBEntry virtio_iommu_translate(IOMMUMemoryRegion *mr, hwaddr addr, · line 594

Quoted 11 lines · Eric Auger
hw/virtio/virtio-iommu.c +11 -0
+    for (i = 0; i < s->nb_reserved_regions; i++) {
+        if (interval.low >= s->reserved_regions[i].low &&
+            interval.low <= s->reserved_regions[i].high) {
+            switch (s->reserved_regions[i].type) {
+            case VIRTIO_IOMMU_RESV_MEM_T_MSI:
+                entry.perm = flag;
+                goto unlock;
+            case VIRTIO_IOMMU_RESV_MEM_T_RESERVED:
+            default:
+                virtio_iommu_report_fault(s, VIRTIO_IOMMU_FAULT_R_MAPPING,
+                                          0, sid, addr);

Needs the VIRTIO_IOMMU_FAULT_F_ADDRESS flag.

Thanks,
Jean

#65 lore raw

Re: [PATCH for-5.0 v11 14/20] virtio-iommu: Handle reserved regions in the translation process

In reply to Eric Auger
Quoted 35 lines · Eric Auger

When translating an address we need to check if it belongs to a reserved virtual address range. If it does, there are 2 cases:

- it belongs to a RESERVED region: the guest should neither use this address in a MAP not instruct the end-point to DMA on them. We report an error

- It belongs to an MSI region: we bypass the translation.

---

v10 -> v11:
- directly use the reserved_regions properties array

v9 -> v10:
- in case of MSI region, we immediatly return

---
 hw/virtio/virtio-iommu.c | 17 +++++++++++++++++
 1 file changed, 17 insertions(+)
hw/virtio/virtio-iommu.c +1 -0
index 1ce2218935..c5b202fab7 100644
@@ -548,6 +548,7 @@ static IOMMUTLBEntry virtio_iommu_translate(IOMMUMemoryRegion *mr, hwaddr addr,
     uint32_t sid, flags;
     bool bypass_allowed;
     bool found;
+    int i;
 
     interval.low = addr;
     interval.high = addr + 1;

hw/virtio/virtio-iommu.c static IOMMUTLBEntry virtio_iommu_translate(IOMMUMemoryRegion *mr, hwaddr addr, · line 590

Quoted 10 lines
hw/virtio/virtio-iommu.c +7 -0
@@ -580,6 +581,22 @@ static IOMMUTLBEntry virtio_iommu_translate(IOMMUMemoryRegion *mr, hwaddr addr,
         goto unlock;
     }
 
+    for (i = 0; i < s->nb_reserved_regions; i++) {
+        if (interval.low >= s->reserved_regions[i].low &&
+            interval.low <= s->reserved_regions[i].high) {
+            switch (s->reserved_regions[i].type) {
+            case VIRTIO_IOMMU_RESV_MEM_T_MSI:
+                entry.perm = flag;
+                goto unlock;

Might be a bit clearer to break here instead of goto, then..

hw/virtio/virtio-iommu.c static IOMMUTLBEntry virtio_iommu_translate(IOMMUMemoryRegion *mr, hwaddr addr, · line 591

Quoted 1 line
hw/virtio/virtio-iommu.c +1 -0
+            case VIRTIO_IOMMU_RESV_MEM_T_RESERVED:
               /* Passthrough */

hw/virtio/virtio-iommu.c static IOMMUTLBEntry virtio_iommu_translate(IOMMUMemoryRegion *mr, hwaddr addr, · line 595

Quoted 4 lines
hw/virtio/virtio-iommu.c +4 -0
+            default:
+                virtio_iommu_report_fault(s, VIRTIO_IOMMU_FAULT_R_MAPPING,
+                                          0, sid, addr);
+            goto unlock;

.. do the same thing here, and...

hw/virtio/virtio-iommu.c static IOMMUTLBEntry virtio_iommu_translate(IOMMUMemoryRegion *mr, hwaddr addr, · line 596

Quoted 1 line
hw/virtio/virtio-iommu.c +1 -0
+           }

.. goto unlock here..

Quoted 9 lines
hw/virtio/virtio-iommu.c +3 -0
+        }
+    }
+
     if (!ep->domain) {
         if (!bypass_allowed) {
             qemu_log_mask(LOG_GUEST_ERROR,
Signature · 1 line
2.20.1
Signature · 1 line
Peter Xu
author
#66 lore raw

PATCH v11 15/20 virtio-iommu-pci: Add array of Interval properties

In reply to Eric Auger

The machine may need to pass reserved regions to the virtio-iommu-pci device (such as the MSI window on x86). So let's add an array of Interval properties.

---
 hw/virtio/virtio-iommu-pci.c | 3 +++
 1 file changed, 3 insertions(+)
hw/virtio/virtio-iommu-pci.c +3 -0
index 4cfae1f9df..280230b31e 100644
@@ -31,6 +31,9 @@ struct VirtIOIOMMUPCI {
 
 static Property virtio_iommu_pci_properties[] = {
     DEFINE_PROP_UINT32("class", VirtIOPCIProxy, class_code, 0),
+    DEFINE_PROP_ARRAY("reserved-regions", VirtIOIOMMUPCI,
+                      vdev.nb_reserved_regions, vdev.reserved_regions,
+                      qdev_prop_interval, Interval),
     DEFINE_PROP_END_OF_LIST(),
 };
 
Signature · 1 line
2.20.1
author
#68 lore raw

PATCH v11 16/20 hw/arm/virt-acpi-build: Introduce fill_iort_idmap helper

In reply to Eric Auger

To avoid code duplication, let's introduce an helper that fills one IORT ID mappings array index.

---

v8: new

---
 hw/arm/virt-acpi-build.c | 43 ++++++++++++++++++++++++----------------
 1 file changed, 26 insertions(+), 17 deletions(-)
hw/arm/virt-acpi-build.c +26 -17
index 4cd50175e0..825f3a79c0 100644
@@ -368,6 +368,17 @@ static void acpi_dsdt_add_power_button(Aml *scope)
     aml_append(scope, dev);
 }
 
+static inline void
+fill_iort_idmap(AcpiIortIdMapping *idmap, int i,
+                uint32_t input_base, uint32_t id_count,
+                uint32_t output_base, uint32_t output_reference)
+{
+    idmap[i].input_base = cpu_to_le32(input_base);
+    idmap[i].id_count = cpu_to_le32(id_count);
+    idmap[i].output_base = cpu_to_le32(output_base);
+    idmap[i].output_reference = cpu_to_le32(output_reference);
+}
+
 static void
 build_iort(GArray *table_data, BIOSLinker *linker, VirtMachineState *vms)
 {
@@ -426,13 +437,12 @@ build_iort(GArray *table_data, BIOSLinker *linker, VirtMachineState *vms)
         smmu->gerr_gsiv = cpu_to_le32(irq + 2);
         smmu->sync_gsiv = cpu_to_le32(irq + 3);
 
-        /* Identity RID mapping covering the whole input RID range */
-        idmap = &smmu->id_mapping_array[0];
-        idmap->input_base = 0;
-        idmap->id_count = cpu_to_le32(0xFFFF);
-        idmap->output_base = 0;
-        /* output IORT node is the ITS group node (the first node) */
-        idmap->output_reference = cpu_to_le32(iort_node_offset);
+        /*
+         * Identity RID mapping covering the whole input RID range.
+         * The output IORT node is the ITS group node (the first node).
+         */
+        fill_iort_idmap(smmu->id_mapping_array, 0, 0, 0xffff, 0,
+                        iort_node_offset);
     }
 
     /* Root Complex Node */
@@ -450,18 +460,17 @@ build_iort(GArray *table_data, BIOSLinker *linker, VirtMachineState *vms)
     rc->memory_properties.memory_flags = 0x3; /* CCA = CPM = DCAS = 1 */
     rc->pci_segment_number = 0; /* MCFG pci_segment */
 
-    /* Identity RID mapping covering the whole input RID range */
-    idmap = &rc->id_mapping_array[0];
-    idmap->input_base = 0;
-    idmap->id_count = cpu_to_le32(0xFFFF);
-    idmap->output_base = 0;
-
     if (vms->iommu == VIRT_IOMMU_SMMUV3) {
-        /* output IORT node is the smmuv3 node */
-        idmap->output_reference = cpu_to_le32(smmu_offset);
+        /* Identity RID mapping and output IORT node is the iommu node */
+        fill_iort_idmap(rc->id_mapping_array, 0, 0, 0xFFFF, 0,
+                        smmu_offset);
     } else {
-        /* output IORT node is the ITS group node (the first node) */
-        idmap->output_reference = cpu_to_le32(iort_node_offset);
+        /*
+         * Identity RID mapping and the output IORT node is the ITS group
+         * node (the first node).
+         */
+        fill_iort_idmap(rc->id_mapping_array, 0, 0, 0xFFFF, 0,
+                        iort_node_offset);
     }
 
     /*
Signature · 1 line
2.20.1
Reviewed-by on v11 16/20
#69 lore raw

Re: [PATCH for-5.0 v11 16/20] hw/arm/virt-acpi-build: Introduce fill_iort_idmap helper

Quoted 8 lines · Eric Auger

build_iort(GArray *table_data, BIOSLinker *linker, VirtMachineState *vms) {

hw/arm/virt-acpi-build.c +0 -2
@@ -426,13 +437,12 @@ build_iort(GArray *table_data, BIOSLinker *linker, VirtMachineState *vms)
         smmu->gerr_gsiv = cpu_to_le32(irq + 2);
         smmu->sync_gsiv = cpu_to_le32(irq + 3);
 
-        /* Identity RID mapping covering the whole input RID range */
-        idmap = &smmu->id_mapping_array[0];

hw/arm/virt-acpi-build.c build_iort(GArray *table_data, BIOSLinker *linker, VirtMachineState *vms) · line 444

Quoted 10 lines
hw/arm/virt-acpi-build.c +5 -5
-        idmap->input_base = 0;
-        idmap->id_count = cpu_to_le32(0xFFFF);
-        idmap->output_base = 0;
-        /* output IORT node is the ITS group node (the first node) */
-        idmap->output_reference = cpu_to_le32(iort_node_offset);
+        /*
+         * Identity RID mapping covering the whole input RID range.
+         * The output IORT node is the ITS group node (the first node).
+         */
+        fill_iort_idmap(smmu->id_mapping_array, 0, 0, 0xffff, 0,

nit: the other calls use uppercase hex digits

author
#70 lore raw

PATCH v11 17/20 hw/arm/virt-acpi-build: Add virtio-iommu node in IORT table

In reply to Eric Auger

This patch builds the virtio-iommu node in the ACPI IORT table.

The RID space of the root complex, which spans 0x0-0x10000 maps to streamid space 0x0-0x10000 in the virtio-iommu which in turn maps to deviceid space 0x0-0x10000 in the ITS group.

The iommu RID is excluded as described in virtio-iommu specification.

---
v8 -> v9:
- iommu RID is not fixed anymore

v7 -> v8:
- exclude the iommu RID (0x8) in the root complex ID mapping

---
 hw/arm/virt-acpi-build.c    | 50 ++++++++++++++++++++++++++++++-------
 include/hw/acpi/acpi-defs.h | 21 +++++++++++++++-
 2 files changed, 61 insertions(+), 10 deletions(-)
hw/arm/virt-acpi-build.c +41 -9
index 825f3a79c0..1e22cbbbfd 100644
@@ -386,14 +386,14 @@ build_iort(GArray *table_data, BIOSLinker *linker, VirtMachineState *vms)
     AcpiIortIdMapping *idmap;
     AcpiIortItsGroup *its;
     AcpiIortTable *iort;
-    AcpiIortSmmu3 *smmu;
-    size_t node_size, iort_node_offset, iort_length, smmu_offset = 0;
+    size_t node_size, iort_node_offset, iort_length, iommu_offset = 0;
     AcpiIortRC *rc;
+    int nb_rc_idmappings = 1;
 
     iort = acpi_data_push(table_data, sizeof(*iort));
 
-    if (vms->iommu == VIRT_IOMMU_SMMUV3) {
-        nb_nodes = 3; /* RC, ITS, SMMUv3 */
+    if (vms->iommu) {
+        nb_nodes = 3; /* RC, ITS, IOMMU */
     } else {
         nb_nodes = 2; /* RC, ITS */
     }
@@ -419,9 +419,9 @@ build_iort(GArray *table_data, BIOSLinker *linker, VirtMachineState *vms)
 
     if (vms->iommu == VIRT_IOMMU_SMMUV3) {
         int irq =  vms->irqmap[VIRT_SMMU] + ARM_SPI_BASE;
+        AcpiIortSmmu3 *smmu;
 
-        /* SMMUv3 node */
-        smmu_offset = iort_node_offset + node_size;
+        iommu_offset = iort_node_offset + node_size;
         node_size = sizeof(*smmu) + sizeof(*idmap);
         iort_length += node_size;
         smmu = acpi_data_push(table_data, node_size);
@@ -443,16 +443,38 @@ build_iort(GArray *table_data, BIOSLinker *linker, VirtMachineState *vms)
          */
         fill_iort_idmap(smmu->id_mapping_array, 0, 0, 0xffff, 0,
                         iort_node_offset);
+    } else if (vms->iommu == VIRT_IOMMU_VIRTIO) {
+        AcpiIortPVIommuPCI *iommu;
+
+        nb_rc_idmappings = 2;
+        iommu_offset = iort_node_offset + node_size;
+        node_size = sizeof(*iommu) + 2 * sizeof(*idmap);
+        iort_length += node_size;
+        iommu = acpi_data_push(table_data, node_size);
+
+        iommu->type = ACPI_IORT_NODE_PARAVIRT;
+        iommu->length = cpu_to_le16(node_size);
+        iommu->mapping_count = cpu_to_le32(2);
+        iommu->mapping_offset = cpu_to_le32(sizeof(*iommu));
+        iommu->devid = cpu_to_le32(vms->virtio_iommu_bdf);
+        iommu->model = cpu_to_le32(ACPI_IORT_NODE_PV_VIRTIO_IOMMU_PCI);
+
+        /*
+         * Identity RID mapping covering the whole input RID range
+         * output IORT node is the ITS group node (the first node)
+         */
+        fill_iort_idmap(iommu->id_mapping_array, 0, 0, 0xffff, 0,
+                        iort_node_offset);
     }
 
     /* Root Complex Node */
-    node_size = sizeof(*rc) + sizeof(*idmap);
+    node_size = sizeof(*rc) + nb_rc_idmappings * sizeof(*idmap);
     iort_length += node_size;
     rc = acpi_data_push(table_data, node_size);
 
     rc->type = ACPI_IORT_NODE_PCI_ROOT_COMPLEX;
     rc->length = cpu_to_le16(node_size);
-    rc->mapping_count = cpu_to_le32(1);
+    rc->mapping_count = cpu_to_le32(nb_rc_idmappings);
     rc->mapping_offset = cpu_to_le32(sizeof(*rc));
 
     /* fully coherent device */
@@ -463,7 +485,17 @@ build_iort(GArray *table_data, BIOSLinker *linker, VirtMachineState *vms)
     if (vms->iommu == VIRT_IOMMU_SMMUV3) {
         /* Identity RID mapping and output IORT node is the iommu node */
         fill_iort_idmap(rc->id_mapping_array, 0, 0, 0xFFFF, 0,
-                        smmu_offset);
+                        iommu_offset);
+    } else if (vms->iommu == VIRT_IOMMU_VIRTIO) {
+        /*
+         * Identity mapping with the IOMMU RID (0x8) excluded. The output
+         * IORT node is the iommu node.
+         */
+        fill_iort_idmap(rc->id_mapping_array, 0, 0, vms->virtio_iommu_bdf, 0,
+                        iommu_offset);
+        fill_iort_idmap(rc->id_mapping_array, 1, vms->virtio_iommu_bdf + 1,
+                        0xFFFF - vms->virtio_iommu_bdf,
+                        vms->virtio_iommu_bdf + 1, iommu_offset);
     } else {
         /*
          * Identity RID mapping and the output IORT node is the ITS group
include/hw/acpi/acpi-defs.h +20 -1
index 57a3f58b0c..ba06f41fc0 100644
@@ -581,7 +581,8 @@ enum {
         ACPI_IORT_NODE_NAMED_COMPONENT = 0x01,
         ACPI_IORT_NODE_PCI_ROOT_COMPLEX = 0x02,
         ACPI_IORT_NODE_SMMU = 0x03,
-        ACPI_IORT_NODE_SMMU_V3 = 0x04
+        ACPI_IORT_NODE_SMMU_V3 = 0x04,
+        ACPI_IORT_NODE_PARAVIRT = 0x80
 };
 
 struct AcpiIortIdMapping {
@@ -610,6 +611,24 @@ typedef struct AcpiIortItsGroup AcpiIortItsGroup;
 
 #define ACPI_IORT_SMMU_V3_COHACC_OVERRIDE 1
 
+struct AcpiIortPVIommuPCI {
+    ACPI_IORT_NODE_HEADER_DEF
+    uint32_t devid;
+    uint8_t reserved2[12];
+    uint32_t model;
+    uint32_t flags;
+    uint8_t reserved3[16];
+    AcpiIortIdMapping id_mapping_array[0];
+} QEMU_PACKED;
+typedef struct AcpiIortPVIommuPCI AcpiIortPVIommuPCI;
+
+enum {
+    ACPI_IORT_NODE_PV_VIRTIO_IOMMU     = 0x0,
+    ACPI_IORT_NODE_PV_VIRTIO_IOMMU_PCI = 0x1,
+};
+
+#define ACPI_IORT_NODE_PV_CACHE_COHERENT    (1 << 0)
+
 struct AcpiIortSmmu3 {
     ACPI_IORT_NODE_HEADER_DEF
     uint64_t base_address;
Signature · 1 line
2.20.1
Reviewed-by on v11 17/20
#71 lore raw

Re: [PATCH for-5.0 v11 17/20] hw/arm/virt-acpi-build: Add virtio-iommu node in IORT table

Quoted 10 lines · Eric Auger

This patch builds the virtio-iommu node in the ACPI IORT table.

The RID space of the root complex, which spans 0x0-0x10000 maps to streamid space 0x0-0x10000 in the virtio-iommu which in turn maps to deviceid space 0x0-0x10000 in the ITS group.

The iommu RID is excluded as described in virtio-iommu specification.

Although VIOT changes the layout of the IORT node slightly, the implementation should stay pretty much the same.

author
#72 lore raw

PATCH v11 18/20 virtio-iommu: Support migration

In reply to Eric Auger

Add Migration support. We rely on recently added gtree and qlist migration. Besides, we have to fixup end point <-> domain link.

Indeed each domain has a list of endpoints attached to it. And each endpoint has a pointer to its domain.

Raw gtree and qlist migration cannot handle this as it re-allocates all the nodes while reconstructing the trees/lists.

So in post_load we re-construct the relationship between endpoints and domains.

---
 hw/virtio/virtio-iommu.c | 127 ++++++++++++++++++++++++++++++++++++---
 1 file changed, 117 insertions(+), 10 deletions(-)
hw/virtio/virtio-iommu.c +117 -10
index c5b202fab7..4e92fc0c95 100644
@@ -692,16 +692,6 @@ static void virtio_iommu_set_features(VirtIODevice *vdev, uint64_t val)
     trace_virtio_iommu_set_features(dev->acked_features);
 }
 
-/*
- * Migration is not yet supported: most of the state consists
- * of balanced binary trees which are not yet ready for getting
- * migrated
- */
-static const VMStateDescription vmstate_virtio_iommu_device = {
-    .name = "virtio-iommu-device",
-    .unmigratable = 1,
-};
-
 static gint int_cmp(gconstpointer a, gconstpointer b, gpointer user_data)
 {
     uint ua = GPOINTER_TO_UINT(a);
@@ -778,6 +768,123 @@ static void virtio_iommu_instance_init(Object *obj)
 {
 }
 
+#define VMSTATE_INTERVAL                               \
+{                                                      \
+    .name = "interval",                                \
+    .version_id = 1,                                   \
+    .minimum_version_id = 1,                           \
+    .fields = (VMStateField[]) {                       \
+        VMSTATE_UINT64(low, viommu_interval),          \
+        VMSTATE_UINT64(high, viommu_interval),         \
+        VMSTATE_END_OF_LIST()                          \
+    }                                                  \
+}
+
+#define VMSTATE_MAPPING                               \
+{                                                     \
+    .name = "mapping",                                \
+    .version_id = 1,                                  \
+    .minimum_version_id = 1,                          \
+    .fields = (VMStateField[]) {                      \
+        VMSTATE_UINT64(phys_addr, viommu_mapping),    \
+        VMSTATE_UINT32(flags, viommu_mapping),        \
+        VMSTATE_END_OF_LIST()                         \
+    },                                                \
+}
+
+static const VMStateDescription vmstate_interval_mapping[2] = {
+    VMSTATE_MAPPING,   /* value */
+    VMSTATE_INTERVAL   /* key   */
+};
+
+static int domain_preload(void *opaque)
+{
+    viommu_domain *domain = opaque;
+
+    domain->mappings = g_tree_new_full((GCompareDataFunc)interval_cmp,
+                                       NULL, g_free, g_free);
+    return 0;
+}
+
+static const VMStateDescription vmstate_endpoint = {
+    .name = "endpoint",
+    .version_id = 1,
+    .minimum_version_id = 1,
+    .fields = (VMStateField[]) {
+        VMSTATE_UINT32(id, viommu_endpoint),
+        VMSTATE_END_OF_LIST()
+    }
+};
+
+static const VMStateDescription vmstate_domain = {
+    .name = "domain",
+    .version_id = 1,
+    .minimum_version_id = 1,
+    .pre_load = domain_preload,
+    .fields = (VMStateField[]) {
+        VMSTATE_UINT32(id, viommu_domain),
+        VMSTATE_GTREE_V(mappings, viommu_domain, 1,
+                        vmstate_interval_mapping,
+                        viommu_interval, viommu_mapping),
+        VMSTATE_QLIST_V(endpoint_list, viommu_domain, 1,
+                        vmstate_endpoint, viommu_endpoint, next),
+        VMSTATE_END_OF_LIST()
+    }
+};
+
+static gboolean reconstruct_ep_domain_link(gpointer key, gpointer value,
+                                           gpointer data)
+{
+    viommu_domain *d = (viommu_domain *)value;
+    viommu_endpoint *iter, *tmp;
+    viommu_endpoint *ep = (viommu_endpoint *)data;
+
+    QLIST_FOREACH_SAFE(iter, &d->endpoint_list, next, tmp) {
+        if (iter->id == ep->id) {
+            /* remove the ep */
+            QLIST_REMOVE(iter, next);
+            g_free(iter);
+            /* replace it with the good one */
+            QLIST_INSERT_HEAD(&d->endpoint_list, ep, next);
+            /* update the domain */
+            ep->domain = d;
+            return true; /* stop the search */
+        }
+    }
+    return false; /* continue the traversal */
+}
+
+static gboolean fix_endpoint(gpointer key, gpointer value, gpointer data)
+{
+    VirtIOIOMMU *s = (VirtIOIOMMU *)data;
+
+    g_tree_foreach(s->domains, reconstruct_ep_domain_link, value);
+    return false;
+}
+
+static int iommu_post_load(void *opaque, int version_id)
+{
+    VirtIOIOMMU *s = opaque;
+
+    g_tree_foreach(s->endpoints, fix_endpoint, s);
+    return 0;
+}
+
+static const VMStateDescription vmstate_virtio_iommu_device = {
+    .name = "virtio-iommu-device",
+    .minimum_version_id = 1,
+    .version_id = 1,
+    .post_load = iommu_post_load,
+    .fields = (VMStateField[]) {
+        VMSTATE_GTREE_DIRECT_KEY_V(domains, VirtIOIOMMU, 1,
+                                   &vmstate_domain, viommu_domain),
+        VMSTATE_GTREE_DIRECT_KEY_V(endpoints, VirtIOIOMMU, 1,
+                                   &vmstate_endpoint, viommu_endpoint),
+        VMSTATE_END_OF_LIST()
+    },
+};
+
+
 static const VMStateDescription vmstate_virtio_iommu = {
     .name = "virtio-iommu",
     .minimum_version_id = 1,
Signature · 1 line
2.20.1
Acked-by on v11 18/20
#73 lore raw

Re: [PATCH for-5.0 v11 18/20] virtio-iommu: Support migration

Quoted 6 lines · * Eric Auger ([email protected]) wrote:

Add Migration support. We rely on recently added gtree and qlist migration. Besides, we have to fixup end point <-> domain link.

Indeed each domain has a list of endpoints attached to it. And each endpoint has a pointer to its domain.

Quoted 7 lines

Raw gtree and qlist migration cannot handle this as it re-allocates all the nodes while reconstructing the trees/lists.

So in post_load we re-construct the relationship between endpoints and domains.

From the migration side of things,

Quoted 152 lines
---
 hw/virtio/virtio-iommu.c | 127 ++++++++++++++++++++++++++++++++++++---
 1 file changed, 117 insertions(+), 10 deletions(-)
hw/virtio/virtio-iommu.c +117 -10
index c5b202fab7..4e92fc0c95 100644
@@ -692,16 +692,6 @@ static void virtio_iommu_set_features(VirtIODevice *vdev, uint64_t val)
     trace_virtio_iommu_set_features(dev->acked_features);
 }
 
-/*
- * Migration is not yet supported: most of the state consists
- * of balanced binary trees which are not yet ready for getting
- * migrated
- */
-static const VMStateDescription vmstate_virtio_iommu_device = {
-    .name = "virtio-iommu-device",
-    .unmigratable = 1,
-};
-
 static gint int_cmp(gconstpointer a, gconstpointer b, gpointer user_data)
 {
     uint ua = GPOINTER_TO_UINT(a);
@@ -778,6 +768,123 @@ static void virtio_iommu_instance_init(Object *obj)
 {
 }
 
+#define VMSTATE_INTERVAL                               \
+{                                                      \
+    .name = "interval",                                \
+    .version_id = 1,                                   \
+    .minimum_version_id = 1,                           \
+    .fields = (VMStateField[]) {                       \
+        VMSTATE_UINT64(low, viommu_interval),          \
+        VMSTATE_UINT64(high, viommu_interval),         \
+        VMSTATE_END_OF_LIST()                          \
+    }                                                  \
+}
+
+#define VMSTATE_MAPPING                               \
+{                                                     \
+    .name = "mapping",                                \
+    .version_id = 1,                                  \
+    .minimum_version_id = 1,                          \
+    .fields = (VMStateField[]) {                      \
+        VMSTATE_UINT64(phys_addr, viommu_mapping),    \
+        VMSTATE_UINT32(flags, viommu_mapping),        \
+        VMSTATE_END_OF_LIST()                         \
+    },                                                \
+}
+
+static const VMStateDescription vmstate_interval_mapping[2] = {
+    VMSTATE_MAPPING,   /* value */
+    VMSTATE_INTERVAL   /* key   */
+};
+
+static int domain_preload(void *opaque)
+{
+    viommu_domain *domain = opaque;
+
+    domain->mappings = g_tree_new_full((GCompareDataFunc)interval_cmp,
+                                       NULL, g_free, g_free);
+    return 0;
+}
+
+static const VMStateDescription vmstate_endpoint = {
+    .name = "endpoint",
+    .version_id = 1,
+    .minimum_version_id = 1,
+    .fields = (VMStateField[]) {
+        VMSTATE_UINT32(id, viommu_endpoint),
+        VMSTATE_END_OF_LIST()
+    }
+};
+
+static const VMStateDescription vmstate_domain = {
+    .name = "domain",
+    .version_id = 1,
+    .minimum_version_id = 1,
+    .pre_load = domain_preload,
+    .fields = (VMStateField[]) {
+        VMSTATE_UINT32(id, viommu_domain),
+        VMSTATE_GTREE_V(mappings, viommu_domain, 1,
+                        vmstate_interval_mapping,
+                        viommu_interval, viommu_mapping),
+        VMSTATE_QLIST_V(endpoint_list, viommu_domain, 1,
+                        vmstate_endpoint, viommu_endpoint, next),
+        VMSTATE_END_OF_LIST()
+    }
+};
+
+static gboolean reconstruct_ep_domain_link(gpointer key, gpointer value,
+                                           gpointer data)
+{
+    viommu_domain *d = (viommu_domain *)value;
+    viommu_endpoint *iter, *tmp;
+    viommu_endpoint *ep = (viommu_endpoint *)data;
+
+    QLIST_FOREACH_SAFE(iter, &d->endpoint_list, next, tmp) {
+        if (iter->id == ep->id) {
+            /* remove the ep */
+            QLIST_REMOVE(iter, next);
+            g_free(iter);
+            /* replace it with the good one */
+            QLIST_INSERT_HEAD(&d->endpoint_list, ep, next);
+            /* update the domain */
+            ep->domain = d;
+            return true; /* stop the search */
+        }
+    }
+    return false; /* continue the traversal */
+}
+
+static gboolean fix_endpoint(gpointer key, gpointer value, gpointer data)
+{
+    VirtIOIOMMU *s = (VirtIOIOMMU *)data;
+
+    g_tree_foreach(s->domains, reconstruct_ep_domain_link, value);
+    return false;
+}
+
+static int iommu_post_load(void *opaque, int version_id)
+{
+    VirtIOIOMMU *s = opaque;
+
+    g_tree_foreach(s->endpoints, fix_endpoint, s);
+    return 0;
+}
+
+static const VMStateDescription vmstate_virtio_iommu_device = {
+    .name = "virtio-iommu-device",
+    .minimum_version_id = 1,
+    .version_id = 1,
+    .post_load = iommu_post_load,
+    .fields = (VMStateField[]) {
+        VMSTATE_GTREE_DIRECT_KEY_V(domains, VirtIOIOMMU, 1,
+                                   &vmstate_domain, viommu_domain),
+        VMSTATE_GTREE_DIRECT_KEY_V(endpoints, VirtIOIOMMU, 1,
+                                   &vmstate_endpoint, viommu_endpoint),
+        VMSTATE_END_OF_LIST()
+    },
+};
+
+
 static const VMStateDescription vmstate_virtio_iommu = {
     .name = "virtio-iommu",
     .minimum_version_id = 1,
Signature · 1 line
2.20.1

--
Dr. David Alan Gilbert / [email protected] / Manchester, UK

Reviewed-by on v11 18/20
#74 lore raw

Re: [PATCH for-5.0 v11 18/20] virtio-iommu: Support migration

In reply to Eric Auger

hw/virtio/virtio-iommu.c static void virtio_iommu_instance_init(Object *obj) · line 882

Quoted 10 lines · Eric Auger
hw/virtio/virtio-iommu.c +10 -0
+static const VMStateDescription vmstate_virtio_iommu_device = {
+    .name = "virtio-iommu-device",
+    .minimum_version_id = 1,
+    .version_id = 1,
+    .post_load = iommu_post_load,
+    .fields = (VMStateField[]) {
+        VMSTATE_GTREE_DIRECT_KEY_V(domains, VirtIOIOMMU, 1,
+                                   &vmstate_domain, viommu_domain),
+        VMSTATE_GTREE_DIRECT_KEY_V(endpoints, VirtIOIOMMU, 1,
+                                   &vmstate_endpoint, viommu_endpoint),

So if I understand correctly these fields are state that is modified by the guest? We don't need to save/load fields that cannot be modified by the guest, static information that is created from the QEMU command-line.

I think the above covers everything we need to migrate in VirtIOIOMMU then, except for acked_features, which (as I pointed out on another patch) seems redundant anyway since there is vdev->guest_features.

Quoted 12 lines
hw/virtio/virtio-iommu.c +5 -0
+        VMSTATE_END_OF_LIST()
+    },
+};
+
+
 static const VMStateDescription vmstate_virtio_iommu = {
     .name = "virtio-iommu",
     .minimum_version_id = 1,
Signature · 1 line
2.20.1
author
#75 lore raw

Re: [PATCH for-5.0 v11 18/20] virtio-iommu: Support migration

Hi Jean,

Quoted 12 lines · Jean-Philippe Brucker

hw/virtio/virtio-iommu.c static void virtio_iommu_instance_init(Object *obj) · line 882

Quoted 10 lines · Eric Auger
hw/virtio/virtio-iommu.c +10 -0
+static const VMStateDescription vmstate_virtio_iommu_device = {
+    .name = "virtio-iommu-device",
+    .minimum_version_id = 1,
+    .version_id = 1,
+    .post_load = iommu_post_load,
+    .fields = (VMStateField[]) {
+        VMSTATE_GTREE_DIRECT_KEY_V(domains, VirtIOIOMMU, 1,
+                                   &vmstate_domain, viommu_domain),
+        VMSTATE_GTREE_DIRECT_KEY_V(endpoints, VirtIOIOMMU, 1,
+                                   &vmstate_endpoint, viommu_endpoint),
Quoted 3 lines

So if I understand correctly these fields are state that is modified by the guest? We don't need to save/load fields that cannot be modified by the guest, static information that is created from the QEMU command-line.

Yes that's correct.

Quoted 4 lines

I think the above covers everything we need to migrate in VirtIOIOMMU then, except for acked_features, which (as I pointed out on another patch) seems redundant anyway since there is vdev->guest_features.

you're right, acked features were not properly migrated.

Quoted 2 lines

Thanks!

Eric

Quoted 14 lines
Quoted 13 lines
hw/virtio/virtio-iommu.c +5 -0
+        VMSTATE_END_OF_LIST()
+    },
+};
+
+
 static const VMStateDescription vmstate_virtio_iommu = {
     .name = "virtio-iommu",
     .minimum_version_id = 1,
Signature · 1 line
2.20.1
#76 lore raw

Re: [PATCH for-5.0 v11 18/20] virtio-iommu: Support migration

In reply to Eric Auger

hw/virtio/virtio-iommu.c static void virtio_iommu_instance_init(Object *obj) · line 882

Quoted 10 lines · Eric Auger
hw/virtio/virtio-iommu.c +10 -0
+static const VMStateDescription vmstate_virtio_iommu_device = {
+    .name = "virtio-iommu-device",
+    .minimum_version_id = 1,
+    .version_id = 1,
+    .post_load = iommu_post_load,
+    .fields = (VMStateField[]) {
+        VMSTATE_GTREE_DIRECT_KEY_V(domains, VirtIOIOMMU, 1,
+                                   &vmstate_domain, viommu_domain),
+        VMSTATE_GTREE_DIRECT_KEY_V(endpoints, VirtIOIOMMU, 1,
+                                   &vmstate_endpoint, viommu_endpoint),

IIUC vmstate_domain already contains all the endpoint information (in endpoint_list of vmstate_domain), but here we migrate it twice. I suppose that's why now we need reconstruct_ep_domain_link() to fixup the duplicated migration?

Then I'll instead ask whether we can skip migrating here? Then in post_load we simply:

  foreach(domain)
    foreach(endpoint in domain)
      g_tree_insert(s->endpoints);

It might help to avoid the reconstruct_ep_domain_link ugliness?

And besides, I also agree with Jean that the endpoint data structure could be reused with IOMMUDevice somehow.

Thanks,

Signature · 1 line
Peter Xu
author
#77 lore raw

Re: [PATCH for-5.0 v11 18/20] virtio-iommu: Support migration

Hi Peter,

Quoted 12 lines · Peter Xu

hw/virtio/virtio-iommu.c static void virtio_iommu_instance_init(Object *obj) · line 882

Quoted 10 lines · Eric Auger
hw/virtio/virtio-iommu.c +10 -0
+static const VMStateDescription vmstate_virtio_iommu_device = {
+    .name = "virtio-iommu-device",
+    .minimum_version_id = 1,
+    .version_id = 1,
+    .post_load = iommu_post_load,
+    .fields = (VMStateField[]) {
+        VMSTATE_GTREE_DIRECT_KEY_V(domains, VirtIOIOMMU, 1,
+                                   &vmstate_domain, viommu_domain),
+        VMSTATE_GTREE_DIRECT_KEY_V(endpoints, VirtIOIOMMU, 1,
+                                   &vmstate_endpoint, viommu_endpoint),
Quoted 2 lines

IIUC vmstate_domain already contains all the endpoint information (in endpoint_list of vmstate_domain), but here we migrate it twice.

I migrated both because at that time I considered we could have endpoints not attached to any domains but I think I can now simplify based on the fact any EP is attached.

I

Quoted 2 lines

suppose that's why now we need reconstruct_ep_domain_link() to fixup the duplicated migration?

Even if I only migrate the domain gtree, I need to reconstruct the ep->domain which was not migrated, on purpose, as it pointed to the old domain in the origin.

Quoted 9 lines

Then I'll instead ask whether we can skip migrating here? Then in post_load we simply:

  foreach(domain)
    foreach(endpoint in domain)
      g_tree_insert(s->endpoints);

It might help to avoid the reconstruct_ep_domain_link ugliness?

I agree that it is simpler. Also need to update the ep->domain as mentionned above. Thank you for the suggestion.

Quoted 3 lines

And besides, I also agree with Jean that the endpoint data structure could be reused with IOMMUDevice somehow.

As I replied to Jean, I think it makes sense to keep both structures as endpoints are not indexed by the same key and the bus number is resolved later.

Thanks

Eric

Quoted 3 lines

Thanks,

author
#78 lore raw

PATCH v11 19/20 pc: Add support for virtio-iommu-pci

In reply to Eric Auger

The virtio-iommu-pci is instantiated through the -device QEMU option. However if instantiated it also requires an IORT ACPI table to describe the ID mappings between the root complex and the iommu.

This patch adds the generation of the IORT table if the virtio-iommu-pci device is instantiated.

We also declare the [0xfee00000 - 0xfeefffff] MSI reserved region so that it gets bypassed by the IOMMU.

---
 hw/i386/acpi-build.c | 72 ++++++++++++++++++++++++++++++++++++++++++++
 hw/i386/pc.c         | 15 ++++++++-
 include/hw/i386/pc.h |  2 ++
 3 files changed, 88 insertions(+), 1 deletion(-)
hw/i386/acpi-build.c +72 -0
index 12ff55fcfb..f09cabdcae 100644
@@ -2744,6 +2744,72 @@ static bool acpi_get_mcfg(AcpiMcfgInfo *mcfg)
     return true;
 }
 
+static inline void
+fill_iort_idmap(AcpiIortIdMapping *idmap, int i,
+                uint32_t input_base, uint32_t id_count,
+                uint32_t output_base, uint32_t output_reference)
+{
+    idmap[i].input_base = cpu_to_le32(input_base);
+    idmap[i].id_count = cpu_to_le32(id_count);
+    idmap[i].output_base = cpu_to_le32(output_base);
+    idmap[i].output_reference = cpu_to_le32(output_reference);
+}
+
+static void
+build_iort(GArray *table_data, BIOSLinker *linker, PCMachineState *pcms)
+{
+    size_t iommu_node_size, rc_node_size, iommu_node_offset;
+    int iort_start = table_data->len;
+    AcpiIortPVIommuPCI *iommu;
+    AcpiIortIdMapping *idmap;
+    AcpiIortTable *iort;
+    size_t iort_length;
+    AcpiIortRC *rc;
+
+    iort = acpi_data_push(table_data, sizeof(*iort));
+    iort_length = sizeof(*iort);
+    iort->node_count = cpu_to_le32(2);
+
+    /* virtio-iommu node */
+
+    iommu_node_offset = sizeof(*iort);
+    iort->node_offset = cpu_to_le32(iommu_node_offset);
+    iommu_node_size = sizeof(*iommu);
+    iort_length += iommu_node_offset;
+    iommu = acpi_data_push(table_data, iommu_node_size);
+    iommu->type = ACPI_IORT_NODE_PARAVIRT;
+    iommu->length = cpu_to_le16(iommu_node_size);
+    iommu->mapping_count = 0;
+    iommu->devid = cpu_to_le32(pcms->virtio_iommu_bdf);
+    iommu->model = cpu_to_le32(ACPI_IORT_NODE_PV_VIRTIO_IOMMU_PCI);
+
+    /* Root Complex Node */
+    rc_node_size = sizeof(*rc) + 2 * sizeof(*idmap);
+    iort_length += rc_node_size;
+    rc = acpi_data_push(table_data, rc_node_size);
+
+    rc->type = ACPI_IORT_NODE_PCI_ROOT_COMPLEX;
+    rc->length = cpu_to_le16(rc_node_size);
+    rc->mapping_count = cpu_to_le32(2);
+    rc->mapping_offset = cpu_to_le32(sizeof(*rc));
+
+    /* fully coherent device */
+    rc->memory_properties.cache_coherency = cpu_to_le32(1);
+    rc->memory_properties.memory_flags = 0x3; /* CCA = CPM = DCAS = 1 */
+    rc->pci_segment_number = 0; /* MCFG pci_segment */
+    fill_iort_idmap(rc->id_mapping_array, 0, 0, pcms->virtio_iommu_bdf, 0,
+                    iommu_node_offset);
+    fill_iort_idmap(rc->id_mapping_array, 1, pcms->virtio_iommu_bdf + 1,
+                    0xFFFF - pcms->virtio_iommu_bdf,
+                    pcms->virtio_iommu_bdf + 1, iommu_node_offset);
+
+    iort = (AcpiIortTable *)(table_data->data + iort_start);
+    iort->length = cpu_to_le32(iort_length);
+
+    build_header(linker, table_data, (void *)(table_data->data + iort_start),
+                 "IORT", table_data->len - iort_start, 0, NULL, NULL);
+}
+
 static
 void acpi_build(AcpiBuildTables *tables, MachineState *machine)
 {
@@ -2835,6 +2901,12 @@ void acpi_build(AcpiBuildTables *tables, MachineState *machine)
             build_slit(tables_blob, tables->linker, machine);
         }
     }
+
+    if (pcms->virtio_iommu) {
+        acpi_add_table(table_offsets, tables_blob);
+        build_iort(tables_blob, tables->linker, pcms);
+    }
+
     if (acpi_get_mcfg(&mcfg)) {
         acpi_add_table(table_offsets, tables_blob);
         build_mcfg(tables_blob, tables->linker, &mcfg);
hw/i386/pc.c +14 -1
index ac08e63604..af984ee041 100644
@@ -84,6 +84,7 @@
 #include "hw/net/ne2000-isa.h"
 #include "standard-headers/asm-x86/bootparam.h"
 #include "hw/virtio/virtio-pmem-pci.h"
+#include "hw/virtio/virtio-iommu.h"
 #include "hw/mem/memory-device.h"
 #include "sysemu/replay.h"
 #include "qapi/qmp/qerror.h"
@@ -1940,6 +1941,11 @@ static void pc_machine_device_pre_plug_cb(HotplugHandler *hotplug_dev,
         pc_cpu_pre_plug(hotplug_dev, dev, errp);
     } else if (object_dynamic_cast(OBJECT(dev), TYPE_VIRTIO_PMEM_PCI)) {
         pc_virtio_pmem_pci_pre_plug(hotplug_dev, dev, errp);
+    } else if (object_dynamic_cast(OBJECT(dev), TYPE_VIRTIO_IOMMU_PCI)) {
+        /* we declare a VIRTIO_IOMMU_RESV_MEM_T_MSI region */
+        qdev_prop_set_uint32(dev, "len-reserved-regions", 1);
+        qdev_prop_set_string(dev, "reserved-regions[0]",
+                             "0xfee00000, 0xfeefffff, 1");
     }
 }
 
@@ -1952,6 +1958,12 @@ static void pc_machine_device_plug_cb(HotplugHandler *hotplug_dev,
         pc_cpu_plug(hotplug_dev, dev, errp);
     } else if (object_dynamic_cast(OBJECT(dev), TYPE_VIRTIO_PMEM_PCI)) {
         pc_virtio_pmem_pci_plug(hotplug_dev, dev, errp);
+    } else if (object_dynamic_cast(OBJECT(dev), "virtio-iommu-pci")) {
+        PCMachineState *pcms = PC_MACHINE(hotplug_dev);
+        PCIDevice *pdev = PCI_DEVICE(dev);
+
+        pcms->virtio_iommu = true;
+        pcms->virtio_iommu_bdf = pci_get_bdf(pdev);
     }
 }
 
@@ -1990,7 +2002,8 @@ static HotplugHandler *pc_get_hotplug_handler(MachineState *machine,
 {
     if (object_dynamic_cast(OBJECT(dev), TYPE_PC_DIMM) ||
         object_dynamic_cast(OBJECT(dev), TYPE_CPU) ||
-        object_dynamic_cast(OBJECT(dev), TYPE_VIRTIO_PMEM_PCI)) {
+        object_dynamic_cast(OBJECT(dev), TYPE_VIRTIO_PMEM_PCI) ||
+        object_dynamic_cast(OBJECT(dev), "virtio-iommu-pci")) {
         return HOTPLUG_HANDLER(machine);
     }
 
include/hw/i386/pc.h +2 -0
index 1f86eba3f9..221b4c6ef9 100644
@@ -49,6 +49,8 @@ struct PCMachineState {
     bool smbus_enabled;
     bool sata_enabled;
     bool pit_enabled;
+    bool virtio_iommu;
+    uint16_t virtio_iommu_bdf;
 
     /* NUMA information: */
     uint64_t numa_nodes;
Signature · 1 line
2.20.1
Reviewed-by on v11 19/20
#79 lore raw

Re: [PATCH for-5.0 v11 19/20] pc: Add support for virtio-iommu-pci

Quoted 11 lines · Eric Auger

The virtio-iommu-pci is instantiated through the -device QEMU option. However if instantiated it also requires an IORT ACPI table to describe the ID mappings between the root complex and the iommu.

This patch adds the generation of the IORT table if the virtio-iommu-pci device is instantiated.

We also declare the [0xfee00000 - 0xfeefffff] MSI reserved region so that it gets bypassed by the IOMMU.

It would be nice to factor the IORT code with arm, but this looks OK.

author
#80 lore raw

Re: [PATCH for-5.0 v11 19/20] pc: Add support for virtio-iommu-pci

Hi Jean,

Quoted 8 lines · Jean-Philippe Brucker
Quoted 7 lines · Eric Auger

The virtio-iommu-pci is instantiated through the -device QEMU option. However if instantiated it also requires an IORT ACPI table to describe the ID mappings between the root complex and the iommu.

This patch adds the generation of the IORT table if the virtio-iommu-pci device is instantiated.

Quoted 6 lines
Quoted 4 lines

We also declare the [0xfee00000 - 0xfeefffff] MSI reserved region so that it gets bypassed by the IOMMU.

It would be nice to factor the IORT code with arm, but this looks OK.

I factorized the iort table code generation. Not sure this will be used eventually but well.

Thanks

Eric

Quoted 3 lines
#81 lore raw

Re: [PATCH for-5.0 v11 19/20] pc: Add support for virtio-iommu-pci

In reply to Eric Auger
Quoted 11 lines · Eric Auger

The virtio-iommu-pci is instantiated through the -device QEMU option. However if instantiated it also requires an IORT ACPI table to describe the ID mappings between the root complex and the iommu.

This patch adds the generation of the IORT table if the virtio-iommu-pci device is instantiated.

We also declare the [0xfee00000 - 0xfeefffff] MSI reserved region so that it gets bypassed by the IOMMU.

So I'd like us to use virtio config space in preference to ACPI.

Guest bits for that are not ready yet, but I think it's better to wait than maintaining both ACPI and config space forever later.

Could you send a smaller patchset without pci/acpi bits for now?

Quoted 158 lines
---
 hw/i386/acpi-build.c | 72 ++++++++++++++++++++++++++++++++++++++++++++
 hw/i386/pc.c         | 15 ++++++++-
 include/hw/i386/pc.h |  2 ++
 3 files changed, 88 insertions(+), 1 deletion(-)
hw/i386/acpi-build.c +72 -0
index 12ff55fcfb..f09cabdcae 100644
@@ -2744,6 +2744,72 @@ static bool acpi_get_mcfg(AcpiMcfgInfo *mcfg)
     return true;
 }
 
+static inline void
+fill_iort_idmap(AcpiIortIdMapping *idmap, int i,
+                uint32_t input_base, uint32_t id_count,
+                uint32_t output_base, uint32_t output_reference)
+{
+    idmap[i].input_base = cpu_to_le32(input_base);
+    idmap[i].id_count = cpu_to_le32(id_count);
+    idmap[i].output_base = cpu_to_le32(output_base);
+    idmap[i].output_reference = cpu_to_le32(output_reference);
+}
+
+static void
+build_iort(GArray *table_data, BIOSLinker *linker, PCMachineState *pcms)
+{
+    size_t iommu_node_size, rc_node_size, iommu_node_offset;
+    int iort_start = table_data->len;
+    AcpiIortPVIommuPCI *iommu;
+    AcpiIortIdMapping *idmap;
+    AcpiIortTable *iort;
+    size_t iort_length;
+    AcpiIortRC *rc;
+
+    iort = acpi_data_push(table_data, sizeof(*iort));
+    iort_length = sizeof(*iort);
+    iort->node_count = cpu_to_le32(2);
+
+    /* virtio-iommu node */
+
+    iommu_node_offset = sizeof(*iort);
+    iort->node_offset = cpu_to_le32(iommu_node_offset);
+    iommu_node_size = sizeof(*iommu);
+    iort_length += iommu_node_offset;
+    iommu = acpi_data_push(table_data, iommu_node_size);
+    iommu->type = ACPI_IORT_NODE_PARAVIRT;
+    iommu->length = cpu_to_le16(iommu_node_size);
+    iommu->mapping_count = 0;
+    iommu->devid = cpu_to_le32(pcms->virtio_iommu_bdf);
+    iommu->model = cpu_to_le32(ACPI_IORT_NODE_PV_VIRTIO_IOMMU_PCI);
+
+    /* Root Complex Node */
+    rc_node_size = sizeof(*rc) + 2 * sizeof(*idmap);
+    iort_length += rc_node_size;
+    rc = acpi_data_push(table_data, rc_node_size);
+
+    rc->type = ACPI_IORT_NODE_PCI_ROOT_COMPLEX;
+    rc->length = cpu_to_le16(rc_node_size);
+    rc->mapping_count = cpu_to_le32(2);
+    rc->mapping_offset = cpu_to_le32(sizeof(*rc));
+
+    /* fully coherent device */
+    rc->memory_properties.cache_coherency = cpu_to_le32(1);
+    rc->memory_properties.memory_flags = 0x3; /* CCA = CPM = DCAS = 1 */
+    rc->pci_segment_number = 0; /* MCFG pci_segment */
+    fill_iort_idmap(rc->id_mapping_array, 0, 0, pcms->virtio_iommu_bdf, 0,
+                    iommu_node_offset);
+    fill_iort_idmap(rc->id_mapping_array, 1, pcms->virtio_iommu_bdf + 1,
+                    0xFFFF - pcms->virtio_iommu_bdf,
+                    pcms->virtio_iommu_bdf + 1, iommu_node_offset);
+
+    iort = (AcpiIortTable *)(table_data->data + iort_start);
+    iort->length = cpu_to_le32(iort_length);
+
+    build_header(linker, table_data, (void *)(table_data->data + iort_start),
+                 "IORT", table_data->len - iort_start, 0, NULL, NULL);
+}
+
 static
 void acpi_build(AcpiBuildTables *tables, MachineState *machine)
 {
@@ -2835,6 +2901,12 @@ void acpi_build(AcpiBuildTables *tables, MachineState *machine)
             build_slit(tables_blob, tables->linker, machine);
         }
     }
+
+    if (pcms->virtio_iommu) {
+        acpi_add_table(table_offsets, tables_blob);
+        build_iort(tables_blob, tables->linker, pcms);
+    }
+
     if (acpi_get_mcfg(&mcfg)) {
         acpi_add_table(table_offsets, tables_blob);
         build_mcfg(tables_blob, tables->linker, &mcfg);
hw/i386/pc.c +14 -1
index ac08e63604..af984ee041 100644
@@ -84,6 +84,7 @@
 #include "hw/net/ne2000-isa.h"
 #include "standard-headers/asm-x86/bootparam.h"
 #include "hw/virtio/virtio-pmem-pci.h"
+#include "hw/virtio/virtio-iommu.h"
 #include "hw/mem/memory-device.h"
 #include "sysemu/replay.h"
 #include "qapi/qmp/qerror.h"
@@ -1940,6 +1941,11 @@ static void pc_machine_device_pre_plug_cb(HotplugHandler *hotplug_dev,
         pc_cpu_pre_plug(hotplug_dev, dev, errp);
     } else if (object_dynamic_cast(OBJECT(dev), TYPE_VIRTIO_PMEM_PCI)) {
         pc_virtio_pmem_pci_pre_plug(hotplug_dev, dev, errp);
+    } else if (object_dynamic_cast(OBJECT(dev), TYPE_VIRTIO_IOMMU_PCI)) {
+        /* we declare a VIRTIO_IOMMU_RESV_MEM_T_MSI region */
+        qdev_prop_set_uint32(dev, "len-reserved-regions", 1);
+        qdev_prop_set_string(dev, "reserved-regions[0]",
+                             "0xfee00000, 0xfeefffff, 1");
     }
 }
 
@@ -1952,6 +1958,12 @@ static void pc_machine_device_plug_cb(HotplugHandler *hotplug_dev,
         pc_cpu_plug(hotplug_dev, dev, errp);
     } else if (object_dynamic_cast(OBJECT(dev), TYPE_VIRTIO_PMEM_PCI)) {
         pc_virtio_pmem_pci_plug(hotplug_dev, dev, errp);
+    } else if (object_dynamic_cast(OBJECT(dev), "virtio-iommu-pci")) {
+        PCMachineState *pcms = PC_MACHINE(hotplug_dev);
+        PCIDevice *pdev = PCI_DEVICE(dev);
+
+        pcms->virtio_iommu = true;
+        pcms->virtio_iommu_bdf = pci_get_bdf(pdev);
     }
 }
 
@@ -1990,7 +2002,8 @@ static HotplugHandler *pc_get_hotplug_handler(MachineState *machine,
 {
     if (object_dynamic_cast(OBJECT(dev), TYPE_PC_DIMM) ||
         object_dynamic_cast(OBJECT(dev), TYPE_CPU) ||
-        object_dynamic_cast(OBJECT(dev), TYPE_VIRTIO_PMEM_PCI)) {
+        object_dynamic_cast(OBJECT(dev), TYPE_VIRTIO_PMEM_PCI) ||
+        object_dynamic_cast(OBJECT(dev), "virtio-iommu-pci")) {
         return HOTPLUG_HANDLER(machine);
     }
 
include/hw/i386/pc.h +2 -0
index 1f86eba3f9..221b4c6ef9 100644
@@ -49,6 +49,8 @@ struct PCMachineState {
     bool smbus_enabled;
     bool sata_enabled;
     bool pit_enabled;
+    bool virtio_iommu;
+    uint16_t virtio_iommu_bdf;
 
     /* NUMA information: */
     uint64_t numa_nodes;
Signature · 1 line
2.20.1
author
#82 lore raw

Re: [PATCH for-5.0 v11 19/20] pc: Add support for virtio-iommu-pci

Hi Michael,

Quoted 13 lines · Michael S. Tsirkin
Quoted 11 lines · Eric Auger

The virtio-iommu-pci is instantiated through the -device QEMU option. However if instantiated it also requires an IORT ACPI table to describe the ID mappings between the root complex and the iommu.

This patch adds the generation of the IORT table if the virtio-iommu-pci device is instantiated.

We also declare the [0xfee00000 - 0xfeefffff] MSI reserved region so that it gets bypassed by the IOMMU.

Quoted 7 lines

So I'd like us to use virtio config space in preference to ACPI.

Guest bits for that are not ready yet, but I think it's better to wait than maintaining both ACPI and config space forever later.

Could you send a smaller patchset without pci/acpi bits for now?

Yes I am about to send v12.

Indeed I hope the DT integration in ARM virt can land in 5.0. All the kernel dependencies are resolved and it complies with the voted spec.

Then I will push the non DT integration when Jean's series get stabilized and spec updated.

Thanks

Eric

Quoted 160 lines
Quoted 159 lines
---
 hw/i386/acpi-build.c | 72 ++++++++++++++++++++++++++++++++++++++++++++
 hw/i386/pc.c         | 15 ++++++++-
 include/hw/i386/pc.h |  2 ++
 3 files changed, 88 insertions(+), 1 deletion(-)
hw/i386/acpi-build.c +72 -0
index 12ff55fcfb..f09cabdcae 100644
@@ -2744,6 +2744,72 @@ static bool acpi_get_mcfg(AcpiMcfgInfo *mcfg)
     return true;
 }
 
+static inline void
+fill_iort_idmap(AcpiIortIdMapping *idmap, int i,
+                uint32_t input_base, uint32_t id_count,
+                uint32_t output_base, uint32_t output_reference)
+{
+    idmap[i].input_base = cpu_to_le32(input_base);
+    idmap[i].id_count = cpu_to_le32(id_count);
+    idmap[i].output_base = cpu_to_le32(output_base);
+    idmap[i].output_reference = cpu_to_le32(output_reference);
+}
+
+static void
+build_iort(GArray *table_data, BIOSLinker *linker, PCMachineState *pcms)
+{
+    size_t iommu_node_size, rc_node_size, iommu_node_offset;
+    int iort_start = table_data->len;
+    AcpiIortPVIommuPCI *iommu;
+    AcpiIortIdMapping *idmap;
+    AcpiIortTable *iort;
+    size_t iort_length;
+    AcpiIortRC *rc;
+
+    iort = acpi_data_push(table_data, sizeof(*iort));
+    iort_length = sizeof(*iort);
+    iort->node_count = cpu_to_le32(2);
+
+    /* virtio-iommu node */
+
+    iommu_node_offset = sizeof(*iort);
+    iort->node_offset = cpu_to_le32(iommu_node_offset);
+    iommu_node_size = sizeof(*iommu);
+    iort_length += iommu_node_offset;
+    iommu = acpi_data_push(table_data, iommu_node_size);
+    iommu->type = ACPI_IORT_NODE_PARAVIRT;
+    iommu->length = cpu_to_le16(iommu_node_size);
+    iommu->mapping_count = 0;
+    iommu->devid = cpu_to_le32(pcms->virtio_iommu_bdf);
+    iommu->model = cpu_to_le32(ACPI_IORT_NODE_PV_VIRTIO_IOMMU_PCI);
+
+    /* Root Complex Node */
+    rc_node_size = sizeof(*rc) + 2 * sizeof(*idmap);
+    iort_length += rc_node_size;
+    rc = acpi_data_push(table_data, rc_node_size);
+
+    rc->type = ACPI_IORT_NODE_PCI_ROOT_COMPLEX;
+    rc->length = cpu_to_le16(rc_node_size);
+    rc->mapping_count = cpu_to_le32(2);
+    rc->mapping_offset = cpu_to_le32(sizeof(*rc));
+
+    /* fully coherent device */
+    rc->memory_properties.cache_coherency = cpu_to_le32(1);
+    rc->memory_properties.memory_flags = 0x3; /* CCA = CPM = DCAS = 1 */
+    rc->pci_segment_number = 0; /* MCFG pci_segment */
+    fill_iort_idmap(rc->id_mapping_array, 0, 0, pcms->virtio_iommu_bdf, 0,
+                    iommu_node_offset);
+    fill_iort_idmap(rc->id_mapping_array, 1, pcms->virtio_iommu_bdf + 1,
+                    0xFFFF - pcms->virtio_iommu_bdf,
+                    pcms->virtio_iommu_bdf + 1, iommu_node_offset);
+
+    iort = (AcpiIortTable *)(table_data->data + iort_start);
+    iort->length = cpu_to_le32(iort_length);
+
+    build_header(linker, table_data, (void *)(table_data->data + iort_start),
+                 "IORT", table_data->len - iort_start, 0, NULL, NULL);
+}
+
 static
 void acpi_build(AcpiBuildTables *tables, MachineState *machine)
 {
@@ -2835,6 +2901,12 @@ void acpi_build(AcpiBuildTables *tables, MachineState *machine)
             build_slit(tables_blob, tables->linker, machine);
         }
     }
+
+    if (pcms->virtio_iommu) {
+        acpi_add_table(table_offsets, tables_blob);
+        build_iort(tables_blob, tables->linker, pcms);
+    }
+
     if (acpi_get_mcfg(&mcfg)) {
         acpi_add_table(table_offsets, tables_blob);
         build_mcfg(tables_blob, tables->linker, &mcfg);
hw/i386/pc.c +14 -1
index ac08e63604..af984ee041 100644
@@ -84,6 +84,7 @@
 #include "hw/net/ne2000-isa.h"
 #include "standard-headers/asm-x86/bootparam.h"
 #include "hw/virtio/virtio-pmem-pci.h"
+#include "hw/virtio/virtio-iommu.h"
 #include "hw/mem/memory-device.h"
 #include "sysemu/replay.h"
 #include "qapi/qmp/qerror.h"
@@ -1940,6 +1941,11 @@ static void pc_machine_device_pre_plug_cb(HotplugHandler *hotplug_dev,
         pc_cpu_pre_plug(hotplug_dev, dev, errp);
     } else if (object_dynamic_cast(OBJECT(dev), TYPE_VIRTIO_PMEM_PCI)) {
         pc_virtio_pmem_pci_pre_plug(hotplug_dev, dev, errp);
+    } else if (object_dynamic_cast(OBJECT(dev), TYPE_VIRTIO_IOMMU_PCI)) {
+        /* we declare a VIRTIO_IOMMU_RESV_MEM_T_MSI region */
+        qdev_prop_set_uint32(dev, "len-reserved-regions", 1);
+        qdev_prop_set_string(dev, "reserved-regions[0]",
+                             "0xfee00000, 0xfeefffff, 1");
     }
 }
 
@@ -1952,6 +1958,12 @@ static void pc_machine_device_plug_cb(HotplugHandler *hotplug_dev,
         pc_cpu_plug(hotplug_dev, dev, errp);
     } else if (object_dynamic_cast(OBJECT(dev), TYPE_VIRTIO_PMEM_PCI)) {
         pc_virtio_pmem_pci_plug(hotplug_dev, dev, errp);
+    } else if (object_dynamic_cast(OBJECT(dev), "virtio-iommu-pci")) {
+        PCMachineState *pcms = PC_MACHINE(hotplug_dev);
+        PCIDevice *pdev = PCI_DEVICE(dev);
+
+        pcms->virtio_iommu = true;
+        pcms->virtio_iommu_bdf = pci_get_bdf(pdev);
     }
 }
 
@@ -1990,7 +2002,8 @@ static HotplugHandler *pc_get_hotplug_handler(MachineState *machine,
 {
     if (object_dynamic_cast(OBJECT(dev), TYPE_PC_DIMM) ||
         object_dynamic_cast(OBJECT(dev), TYPE_CPU) ||
-        object_dynamic_cast(OBJECT(dev), TYPE_VIRTIO_PMEM_PCI)) {
+        object_dynamic_cast(OBJECT(dev), TYPE_VIRTIO_PMEM_PCI) ||
+        object_dynamic_cast(OBJECT(dev), "virtio-iommu-pci")) {
         return HOTPLUG_HANDLER(machine);
     }
 
include/hw/i386/pc.h +2 -0
index 1f86eba3f9..221b4c6ef9 100644
@@ -49,6 +49,8 @@ struct PCMachineState {
     bool smbus_enabled;
     bool sata_enabled;
     bool pit_enabled;
+    bool virtio_iommu;
+    uint16_t virtio_iommu_bdf;
 
     /* NUMA information: */
     uint64_t numa_nodes;
Signature · 1 line
2.20.1
author
#83 lore raw

PATCH v11 20/20 tests: Add virtio-iommu test

In reply to Eric Auger

This adds the framework to test the virtio-iommu-pci device and tests exercising the attach/detach, map/unmap API.

To run the tests:
make tests/qos-test QTEST_QEMU_BINARY=x86_64-softmmu/qemu-system-x86_64 tests/qos-test V=1

---
 tests/Makefile.include      |   2 +
 tests/libqos/virtio-iommu.c | 177 ++++++++++++++++++++++++
 tests/libqos/virtio-iommu.h |  45 +++++++
 tests/virtio-iommu-test.c   | 261 ++++++++++++++++++++++++++++++++++++
 4 files changed, 485 insertions(+)
 create mode 100644 tests/libqos/virtio-iommu.c
 create mode 100644 tests/libqos/virtio-iommu.h
 create mode 100644 tests/virtio-iommu-test.c
tests/Makefile.include +2 -0
index 8566f5f119..76a303c4fb 100644
@@ -734,6 +734,7 @@ qos-test-obj-y += tests/libqos/virtio-net.o
 qos-test-obj-y += tests/libqos/virtio-pci.o
 qos-test-obj-y += tests/libqos/virtio-pci-modern.o
 qos-test-obj-y += tests/libqos/virtio-rng.o
+qos-test-obj-y += tests/libqos/virtio-iommu.o
 qos-test-obj-y += tests/libqos/virtio-scsi.o
 qos-test-obj-y += tests/libqos/virtio-serial.o
 
@@ -773,6 +774,7 @@ qos-test-obj-$(CONFIG_VIRTFS) += tests/virtio-9p-test.o
 qos-test-obj-y += tests/virtio-blk-test.o
 qos-test-obj-y += tests/virtio-net-test.o
 qos-test-obj-y += tests/virtio-rng-test.o
+qos-test-obj-y += tests/virtio-iommu-test.o
 qos-test-obj-y += tests/virtio-scsi-test.o
 qos-test-obj-y += tests/virtio-serial-test.o
 qos-test-obj-y += tests/vmxnet3-test.o
tests/libqos/virtio-iommu.c new file +177 -0

177 lines not on this page · raw message

tests/libqos/virtio-iommu.h new file +45 -0

45 lines not on this page · raw message

tests/virtio-iommu-test.c new file +261 -0

261 lines not on this page · raw message

Signature · 1 line
2.20.1
#84 lore raw
In reply to Eric Auger
Patchew URL: https://patchew.org/QEMU/[email protected]/

Patchew URL: https://patchew.org/QEMU/[email protected]/

Hi,

This series failed the docker-mingw@fedora build test. Please find the testing commands and their output below. If you have Docker installed, you can probably reproduce it locally.

=== TEST SCRIPT BEGIN ===
#! /bin/bash
export ARCH=x86_64
make docker-image-fedora V=1 NETWORK=1
time make docker-test-mingw@fedora J=14 NETWORK=1
=== TEST SCRIPT END ===

CC x86_64-softmmu/hw/virtio/virtio-scsi-pci.o
CC x86_64-softmmu/hw/virtio/virtio-blk-pci.o
/tmp/qemu-test/src/hw/virtio/virtio-iommu.c: In function 'int_cmp':
/tmp/qemu-test/src/hw/virtio/virtio-iommu.c:697:5: error: unknown type name 'uint'; did you mean 'guint'?

     uint ua = GPOINTER_TO_UINT(a);
     ^~~~
     guint
/tmp/qemu-test/src/hw/virtio/virtio-iommu.c:698:5: error: unknown type name 'uint'; did you mean 'guint'?
     uint ub = GPOINTER_TO_UINT(b);
     ^~~~
     guint

make[1]: *** [/tmp/qemu-test/src/rules.mak:69: hw/virtio/virtio-iommu.o] Error 1 make[1]: *** Waiting for unfinished jobs....
CC aarch64-softmmu/accel/tcg/tcg-runtime.o
CC aarch64-softmmu/accel/tcg/tcg-runtime-gvec.o
---

  CC      aarch64-softmmu/hw/block/dataplane/virtio-blk.o
  CC      aarch64-softmmu/hw/char/exynos4210_uart.o
  CC      aarch64-softmmu/hw/char/omap_uart.o

make: *** [Makefile:491: x86_64-softmmu/all] Error 2
make: *** Waiting for unfinished jobs....
CC aarch64-softmmu/hw/char/digic-uart.o
CC aarch64-softmmu/hw/char/stm32f2xx_usart.o
---
CC aarch64-softmmu/hw/arm/boot.o
CC aarch64-softmmu/hw/arm/sysbus-fdt.o
/tmp/qemu-test/src/hw/virtio/virtio-iommu.c: In function 'int_cmp':
/tmp/qemu-test/src/hw/virtio/virtio-iommu.c:697:5: error: unknown type name 'uint'; did you mean 'guint'?

     uint ua = GPOINTER_TO_UINT(a);
     ^~~~
     guint
/tmp/qemu-test/src/hw/virtio/virtio-iommu.c:698:5: error: unknown type name 'uint'; did you mean 'guint'?
     uint ub = GPOINTER_TO_UINT(b);
     ^~~~
     guint

make[1]: *** [/tmp/qemu-test/src/rules.mak:69: hw/virtio/virtio-iommu.o] Error 1 make[1]: *** Waiting for unfinished jobs....
make: *** [Makefile:491: aarch64-softmmu/all] Error 2
Traceback (most recent call last):
File "./tests/docker/docker.py", line 662, in <module>

    sys.exit(main())

---
raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['sudo', '-n', 'docker', 'run', '--label', 'com.qemu.instance.uuid=028df3325d7c4927a1c334040016728f', '-u', '1003', '--security-opt', 'seccomp=unconfined', '--rm', '-e', 'TARGET_LIST=', '-e', 'EXTRA_CONFIGURE_OPTS=', '-e', 'V=', '-e', 'J=14', '-e', 'DEBUG=', '-e', 'SHOW_ENV=', '-e', 'CCACHE_DIR=/var/tmp/ccache', '-v', '/home/patchew2/.cache/qemu-docker-ccache:/var/tmp/ccache:z', '-v', '/var/tmp/patchew-tester-tmp-cuthbude/src/docker-src.2019-11-22-16.49.52.5210:/var/tmp/qemu:z,ro', 'qemu:fedora', '/var/tmp/qemu/run', 'test-mingw']' returned non-zero exit status 2. filter=--filter=label=com.qemu.instance.uuid=028df3325d7c4927a1c334040016728f
make[1]: *** [docker-run] Error 1
make[1]: Leaving directory `/var/tmp/patchew-tester-tmp-cuthbude/src'
make: *** [docker-run-test-mingw@fedora] Error 2

real 6m21.012s
user 0m8.319s

The full log is available at
http://patchew.org/logs/[email protected]/testing.docker-mingw@fedora/?type=message.
---
Email generated automatically by Patchew [https://patchew.org/].
Please send your feedback to [email protected]

#85 lore raw
In reply to Eric Auger
Quoted 10 lines · Eric Auger

This series implements the QEMU virtio-iommu device.

This matches the v0.12 spec and the corresponding virtio-iommu driver upstreamed in 5.3.

The pci proxy for the virtio-iommu device is instantiated using "-device virtio-iommu-pci". This series still relies on ACPI IORT/DT integration. Note the ACPI IORT integration is not yet upstreamed and testing needs to be based on Jean-Philippe's additional kernel patches [1].

Or the config space approach? I really liked that one.

Quoted 184 lines

Work is ongoing to remove IORT adherence and allow the bindings between the IOMMU and the root complex to be defined and written into the PCI device configuration space. The outcome of this work is uncertain at this stage though. See [2].

So only patches 1-11 fully rely on upstreamed kernel code. Others should be considered as RFC.

This respin allows people to test on ARM and x86. It also brings migration support (tested on ARM) and various cleanups. Reserved regions are now passed through an array of properties. A libqos test also is introduced to test the virtio-iommu API.

Note integration with vhost devices and vfio devices is not part of this series. Please follow Bharat's respins [3].

The 1st Patch ("migration: Support QLIST migration") was sent separately [4].

Best Regards

Eric

This series can be found at:
https://github.com/eauger/qemu/tree/v4.2-rc2-virtio-iommu-v11

[1] kernel branch to be used for guest

    https://github.com/eauger/linux/tree/v5.4-rc8-virtio-iommu-iort

[2] [RFC 00/13] virtio-iommu on non-devicetree platforms
[3] VFIO/VHOST integration is not part of this series. Please follow [PATCH RFC v5 0/5] virtio-iommu: VFIO integration respins
[4] [PATCH v6] migration: Support QLIST migration

Testing:
- tested with guest using virtio-net-pci (,vhost=off,iommu_platform,disable-modern=off,disable-legacy=on) and virtio-blk-pci
- migration on ARM
- on x86 PC machine I get some AHCI non translated transactions, very early. This does not prevent the guest from boot and behaving properly. Warnings look like:
qemu-system-x86_64: virtio_iommu_translate sid=250 is not known!!
qemu-system-x86_64: no buffer available in event queue to report event
qemu-system-x86_64: AHCI: Failed to start FIS receive engine: bad FIS receive buffer address

History:

v10 -> v11:
- introduce virtio_iommu_handle_req macro
- migration support
- introduce DEFINE_PROP_INTERVAL and pass reserved regions through an array of those
- domain gtree simplification

v9 -> v10:
- rebase on 4.1.0-rc2, compliance with 0.12 spec
- removed ACPI part
- cleanup (see individual change logs)
- moved to a PATCH series

v8 -> v9:
- virtio-iommu-pci device needs to be instantiated from the command line (RID is not imposed anymore).
- tail structure properly initialized

v7 -> v8:
- virtio-iommu-pci added
- virt instantiation modified
- DT and ACPI modified to exclude the iommu RID from the mapping
- VIRTIO_IOMMU_F_BYPASS, VIRTIO_F_VERSION_1 features exposed

v6 -> v7:
- rebase on qemu 3.0.0-rc3
- minor update against v0.7
- fix issue with EP not on pci.0 and ACPI probing
- change the instantiation method

v5 -> v6:
- minor update against v0.6 spec
- fix g_hash_table_lookup in virtio_iommu_find_add_as
- replace some error_reports by qemu_log_mask(LOG_GUEST_ERROR, ...)

v4 -> v5:
- event queue and fault reporting
- we now return the IOAPIC MSI region if the virtio-iommu is instantiated in a PC machine.
- we bypass transactions on MSI HW region and fault on reserved ones.
- We support ACPI boot with mach-virt (based on IORT proposal)
- We moved to the new driver naming conventions
- simplified mach-virt instantiation
- worked around the disappearing of pci_find_primary_bus
- in virtio_iommu_translate, check the dev->as is not NULL
- initialize as->device_list in virtio_iommu_get_as
- initialize bufstate.error to false in virtio_iommu_probe

v3 -> v4:
- probe request support although no reserved region is returned at the moment
- unmap semantics less strict, as specified in v0.4
- device registration, attach/detach revisited
- split into smaller patches to ease review
- propose a way to inform the IOMMU mr about the page_size_mask of underlying HW IOMMU, if any
- remove warning associated with the translation of the MSI doorbell

v2 -> v3:
- rebase on top of 2.10-rc0 and especially
[PATCH qemu v9 0/2] memory/iommu: QOM'fy IOMMU MemoryRegion
- add mutex init
- fix as->mappings deletion using g_tree_ref/unref
- when a dev is attached whereas it is already attached to another address space, first detach it
- fix some error values
- page_sizes = TARGET_PAGE_MASK;
- I haven't changed the unmap() semantics yet, waiting for the next virtio-iommu spec revision.

v1 -> v2:
- fix redefinition of viommu_as typedef

Eric Auger (20):
migration: Support QLIST migration
virtio-iommu: Add skeleton
virtio-iommu: Decode the command payload
virtio-iommu: Add the iommu regions
virtio-iommu: Endpoint and domains structs and helpers
virtio-iommu: Implement attach/detach command
virtio-iommu: Implement map/unmap
virtio-iommu: Implement translate
virtio-iommu: Implement fault reporting
virtio-iommu-pci: Add virtio iommu pci support hw/arm/virt: Add the virtio-iommu device tree mappings
qapi: Introduce DEFINE_PROP_INTERVAL
virtio-iommu: Implement probe request
virtio-iommu: Handle reserved regions in the translation process
virtio-iommu-pci: Add array of Interval properties hw/arm/virt-acpi-build: Introduce fill_iort_idmap helper hw/arm/virt-acpi-build: Add virtio-iommu node in IORT table
virtio-iommu: Support migration
pc: Add support for virtio-iommu-pci
tests: Add virtio-iommu test

 hw/arm/virt-acpi-build.c         |  91 ++-
 hw/arm/virt.c                    |  53 +-
 hw/core/qdev-properties.c        |  90 +++
 hw/i386/acpi-build.c             |  72 +++
 hw/i386/pc.c                     |  15 +-
 hw/virtio/Kconfig                |   5 +
 hw/virtio/Makefile.objs          |   2 +
 hw/virtio/trace-events           |  22 +
 hw/virtio/virtio-iommu-pci.c     |  91 +++
 hw/virtio/virtio-iommu.c         | 952 +++++++++++++++++++++++++++++++
 include/exec/memory.h            |   6 +
 include/hw/acpi/acpi-defs.h      |  21 +-
 include/hw/arm/virt.h            |   2 +
 include/hw/i386/pc.h             |   2 +
 include/hw/pci/pci.h             |   1 +
 include/hw/qdev-properties.h     |   3 +
 include/hw/virtio/virtio-iommu.h |  67 +++
 include/migration/vmstate.h      |  21 +
 include/qemu/queue.h             |  39 ++
 include/qemu/typedefs.h          |   1 +
 migration/trace-events           |   5 +
 migration/vmstate-types.c        |  70 +++
 qdev-monitor.c                   |   1 +
 tests/Makefile.include           |   2 +
 tests/libqos/virtio-iommu.c      | 177 ++++++
 tests/libqos/virtio-iommu.h      |  45 ++
 tests/test-vmstate.c             | 170 ++++++
 tests/virtio-iommu-test.c        | 261 +++++++++
 28 files changed, 2253 insertions(+), 34 deletions(-)
 create mode 100644 hw/virtio/virtio-iommu-pci.c
 create mode 100644 hw/virtio/virtio-iommu.c
 create mode 100644 include/hw/virtio/virtio-iommu.h
 create mode 100644 tests/libqos/virtio-iommu.c
 create mode 100644 tests/libqos/virtio-iommu.h
 create mode 100644 tests/virtio-iommu-test.c
Signature · 1 line
2.20.1
author
#86 lore raw

Hi Michael,

Quoted 6 lines · Michael S. Tsirkin
Quoted 5 lines · Eric Auger

This series implements the QEMU virtio-iommu device.

This matches the v0.12 spec and the corresponding virtio-iommu driver upstreamed in 5.3.

Quoted 7 lines
Quoted 5 lines

The pci proxy for the virtio-iommu device is instantiated using "-device virtio-iommu-pci". This series still relies on ACPI IORT/DT integration. Note the ACPI IORT integration is not yet upstreamed and testing needs to be based on Jean-Philippe's additional kernel patches [1].

Or the config space approach? I really liked that one.

Yes this corresponds to the paragraph below.

Quoted 6 lines
Quoted 6 lines

Work is ongoing to remove IORT adherence and allow the bindings between the IOMMU and the root complex to be defined and written into the PCI device configuration space. The outcome of this work is uncertain at this stage though. See [2].

Thanks

Eric

Quoted 181 lines
Quoted 179 lines

So only patches 1-11 fully rely on upstreamed kernel code. Others should be considered as RFC.

This respin allows people to test on ARM and x86. It also brings migration support (tested on ARM) and various cleanups. Reserved regions are now passed through an array of properties. A libqos test also is introduced to test the virtio-iommu API.

Note integration with vhost devices and vfio devices is not part of this series. Please follow Bharat's respins [3].

The 1st Patch ("migration: Support QLIST migration") was sent separately [4].

Best Regards

Eric

This series can be found at:
https://github.com/eauger/qemu/tree/v4.2-rc2-virtio-iommu-v11

[1] kernel branch to be used for guest

    https://github.com/eauger/linux/tree/v5.4-rc8-virtio-iommu-iort

[2] [RFC 00/13] virtio-iommu on non-devicetree platforms
[3] VFIO/VHOST integration is not part of this series. Please follow [PATCH RFC v5 0/5] virtio-iommu: VFIO integration respins
[4] [PATCH v6] migration: Support QLIST migration

Testing:
- tested with guest using virtio-net-pci (,vhost=off,iommu_platform,disable-modern=off,disable-legacy=on) and virtio-blk-pci
- migration on ARM
- on x86 PC machine I get some AHCI non translated transactions, very early. This does not prevent the guest from boot and behaving properly. Warnings look like:
qemu-system-x86_64: virtio_iommu_translate sid=250 is not known!!
qemu-system-x86_64: no buffer available in event queue to report event
qemu-system-x86_64: AHCI: Failed to start FIS receive engine: bad FIS receive buffer address

History:

v10 -> v11:
- introduce virtio_iommu_handle_req macro
- migration support
- introduce DEFINE_PROP_INTERVAL and pass reserved regions through an array of those
- domain gtree simplification

v9 -> v10:
- rebase on 4.1.0-rc2, compliance with 0.12 spec
- removed ACPI part
- cleanup (see individual change logs)
- moved to a PATCH series

v8 -> v9:
- virtio-iommu-pci device needs to be instantiated from the command line (RID is not imposed anymore).
- tail structure properly initialized

v7 -> v8:
- virtio-iommu-pci added
- virt instantiation modified
- DT and ACPI modified to exclude the iommu RID from the mapping
- VIRTIO_IOMMU_F_BYPASS, VIRTIO_F_VERSION_1 features exposed

v6 -> v7:
- rebase on qemu 3.0.0-rc3
- minor update against v0.7
- fix issue with EP not on pci.0 and ACPI probing
- change the instantiation method

v5 -> v6:
- minor update against v0.6 spec
- fix g_hash_table_lookup in virtio_iommu_find_add_as
- replace some error_reports by qemu_log_mask(LOG_GUEST_ERROR, ...)

v4 -> v5:
- event queue and fault reporting
- we now return the IOAPIC MSI region if the virtio-iommu is instantiated in a PC machine.
- we bypass transactions on MSI HW region and fault on reserved ones.
- We support ACPI boot with mach-virt (based on IORT proposal)
- We moved to the new driver naming conventions
- simplified mach-virt instantiation
- worked around the disappearing of pci_find_primary_bus
- in virtio_iommu_translate, check the dev->as is not NULL
- initialize as->device_list in virtio_iommu_get_as
- initialize bufstate.error to false in virtio_iommu_probe

v3 -> v4:
- probe request support although no reserved region is returned at the moment
- unmap semantics less strict, as specified in v0.4
- device registration, attach/detach revisited
- split into smaller patches to ease review
- propose a way to inform the IOMMU mr about the page_size_mask of underlying HW IOMMU, if any
- remove warning associated with the translation of the MSI doorbell

v2 -> v3:
- rebase on top of 2.10-rc0 and especially
[PATCH qemu v9 0/2] memory/iommu: QOM'fy IOMMU MemoryRegion
- add mutex init
- fix as->mappings deletion using g_tree_ref/unref
- when a dev is attached whereas it is already attached to another address space, first detach it
- fix some error values
- page_sizes = TARGET_PAGE_MASK;
- I haven't changed the unmap() semantics yet, waiting for the next virtio-iommu spec revision.

v1 -> v2:
- fix redefinition of viommu_as typedef

Eric Auger (20):
migration: Support QLIST migration
virtio-iommu: Add skeleton
virtio-iommu: Decode the command payload
virtio-iommu: Add the iommu regions
virtio-iommu: Endpoint and domains structs and helpers
virtio-iommu: Implement attach/detach command
virtio-iommu: Implement map/unmap
virtio-iommu: Implement translate
virtio-iommu: Implement fault reporting
virtio-iommu-pci: Add virtio iommu pci support hw/arm/virt: Add the virtio-iommu device tree mappings
qapi: Introduce DEFINE_PROP_INTERVAL
virtio-iommu: Implement probe request
virtio-iommu: Handle reserved regions in the translation process
virtio-iommu-pci: Add array of Interval properties hw/arm/virt-acpi-build: Introduce fill_iort_idmap helper hw/arm/virt-acpi-build: Add virtio-iommu node in IORT table
virtio-iommu: Support migration
pc: Add support for virtio-iommu-pci
tests: Add virtio-iommu test

 hw/arm/virt-acpi-build.c         |  91 ++-
 hw/arm/virt.c                    |  53 +-
 hw/core/qdev-properties.c        |  90 +++
 hw/i386/acpi-build.c             |  72 +++
 hw/i386/pc.c                     |  15 +-
 hw/virtio/Kconfig                |   5 +
 hw/virtio/Makefile.objs          |   2 +
 hw/virtio/trace-events           |  22 +
 hw/virtio/virtio-iommu-pci.c     |  91 +++
 hw/virtio/virtio-iommu.c         | 952 +++++++++++++++++++++++++++++++
 include/exec/memory.h            |   6 +
 include/hw/acpi/acpi-defs.h      |  21 +-
 include/hw/arm/virt.h            |   2 +
 include/hw/i386/pc.h             |   2 +
 include/hw/pci/pci.h             |   1 +
 include/hw/qdev-properties.h     |   3 +
 include/hw/virtio/virtio-iommu.h |  67 +++
 include/migration/vmstate.h      |  21 +
 include/qemu/queue.h             |  39 ++
 include/qemu/typedefs.h          |   1 +
 migration/trace-events           |   5 +
 migration/vmstate-types.c        |  70 +++
 qdev-monitor.c                   |   1 +
 tests/Makefile.include           |   2 +
 tests/libqos/virtio-iommu.c      | 177 ++++++
 tests/libqos/virtio-iommu.h      |  45 ++
 tests/test-vmstate.c             | 170 ++++++
 tests/virtio-iommu-test.c        | 261 +++++++++
 28 files changed, 2253 insertions(+), 34 deletions(-)
 create mode 100644 hw/virtio/virtio-iommu-pci.c
 create mode 100644 hw/virtio/virtio-iommu.c
 create mode 100644 include/hw/virtio/virtio-iommu.h
 create mode 100644 tests/libqos/virtio-iommu.c
 create mode 100644 tests/libqos/virtio-iommu.h
 create mode 100644 tests/virtio-iommu-test.c
Signature · 1 line
2.20.1
#87 lore raw
Quoted 9 lines · Auger Eric

Hi Michael,

Quoted 6 lines · Michael S. Tsirkin
Quoted 5 lines · Eric Auger

This series implements the QEMU virtio-iommu device.

This matches the v0.12 spec and the corresponding virtio-iommu driver upstreamed in 5.3.

Quoted 14 lines
Quoted 7 lines
Quoted 5 lines

The pci proxy for the virtio-iommu device is instantiated using "-device virtio-iommu-pci". This series still relies on ACPI IORT/DT integration. Note the ACPI IORT integration is not yet upstreamed and testing needs to be based on Jean-Philippe's additional kernel patches [1].

Or the config space approach? I really liked that one.

Yes this corresponds to the paragraph below.

Quoted 6 lines
Quoted 6 lines

Work is ongoing to remove IORT adherence and allow the bindings between the IOMMU and the root complex to be defined and written into the PCI device configuration space. The outcome of this work is uncertain at this stage though. See [2].

Oh right. Why is it uncertain? Anything can be done to help?

Quoted 185 lines

Thanks

Eric

Quoted 181 lines
Quoted 179 lines

So only patches 1-11 fully rely on upstreamed kernel code. Others should be considered as RFC.

This respin allows people to test on ARM and x86. It also brings migration support (tested on ARM) and various cleanups. Reserved regions are now passed through an array of properties. A libqos test also is introduced to test the virtio-iommu API.

Note integration with vhost devices and vfio devices is not part of this series. Please follow Bharat's respins [3].

The 1st Patch ("migration: Support QLIST migration") was sent separately [4].

Best Regards

Eric

This series can be found at:
https://github.com/eauger/qemu/tree/v4.2-rc2-virtio-iommu-v11

[1] kernel branch to be used for guest

    https://github.com/eauger/linux/tree/v5.4-rc8-virtio-iommu-iort

[2] [RFC 00/13] virtio-iommu on non-devicetree platforms
[3] VFIO/VHOST integration is not part of this series. Please follow [PATCH RFC v5 0/5] virtio-iommu: VFIO integration respins
[4] [PATCH v6] migration: Support QLIST migration

Testing:
- tested with guest using virtio-net-pci (,vhost=off,iommu_platform,disable-modern=off,disable-legacy=on) and virtio-blk-pci
- migration on ARM
- on x86 PC machine I get some AHCI non translated transactions, very early. This does not prevent the guest from boot and behaving properly. Warnings look like:
qemu-system-x86_64: virtio_iommu_translate sid=250 is not known!!
qemu-system-x86_64: no buffer available in event queue to report event
qemu-system-x86_64: AHCI: Failed to start FIS receive engine: bad FIS receive buffer address

History:

v10 -> v11:
- introduce virtio_iommu_handle_req macro
- migration support
- introduce DEFINE_PROP_INTERVAL and pass reserved regions through an array of those
- domain gtree simplification

v9 -> v10:
- rebase on 4.1.0-rc2, compliance with 0.12 spec
- removed ACPI part
- cleanup (see individual change logs)
- moved to a PATCH series

v8 -> v9:
- virtio-iommu-pci device needs to be instantiated from the command line (RID is not imposed anymore).
- tail structure properly initialized

v7 -> v8:
- virtio-iommu-pci added
- virt instantiation modified
- DT and ACPI modified to exclude the iommu RID from the mapping
- VIRTIO_IOMMU_F_BYPASS, VIRTIO_F_VERSION_1 features exposed

v6 -> v7:
- rebase on qemu 3.0.0-rc3
- minor update against v0.7
- fix issue with EP not on pci.0 and ACPI probing
- change the instantiation method

v5 -> v6:
- minor update against v0.6 spec
- fix g_hash_table_lookup in virtio_iommu_find_add_as
- replace some error_reports by qemu_log_mask(LOG_GUEST_ERROR, ...)

v4 -> v5:
- event queue and fault reporting
- we now return the IOAPIC MSI region if the virtio-iommu is instantiated in a PC machine.
- we bypass transactions on MSI HW region and fault on reserved ones.
- We support ACPI boot with mach-virt (based on IORT proposal)
- We moved to the new driver naming conventions
- simplified mach-virt instantiation
- worked around the disappearing of pci_find_primary_bus
- in virtio_iommu_translate, check the dev->as is not NULL
- initialize as->device_list in virtio_iommu_get_as
- initialize bufstate.error to false in virtio_iommu_probe

v3 -> v4:
- probe request support although no reserved region is returned at the moment
- unmap semantics less strict, as specified in v0.4
- device registration, attach/detach revisited
- split into smaller patches to ease review
- propose a way to inform the IOMMU mr about the page_size_mask of underlying HW IOMMU, if any
- remove warning associated with the translation of the MSI doorbell

v2 -> v3:
- rebase on top of 2.10-rc0 and especially
[PATCH qemu v9 0/2] memory/iommu: QOM'fy IOMMU MemoryRegion
- add mutex init
- fix as->mappings deletion using g_tree_ref/unref
- when a dev is attached whereas it is already attached to another address space, first detach it
- fix some error values
- page_sizes = TARGET_PAGE_MASK;
- I haven't changed the unmap() semantics yet, waiting for the next virtio-iommu spec revision.

v1 -> v2:
- fix redefinition of viommu_as typedef

Eric Auger (20):
migration: Support QLIST migration
virtio-iommu: Add skeleton
virtio-iommu: Decode the command payload
virtio-iommu: Add the iommu regions
virtio-iommu: Endpoint and domains structs and helpers
virtio-iommu: Implement attach/detach command
virtio-iommu: Implement map/unmap
virtio-iommu: Implement translate
virtio-iommu: Implement fault reporting
virtio-iommu-pci: Add virtio iommu pci support hw/arm/virt: Add the virtio-iommu device tree mappings
qapi: Introduce DEFINE_PROP_INTERVAL
virtio-iommu: Implement probe request
virtio-iommu: Handle reserved regions in the translation process
virtio-iommu-pci: Add array of Interval properties hw/arm/virt-acpi-build: Introduce fill_iort_idmap helper hw/arm/virt-acpi-build: Add virtio-iommu node in IORT table
virtio-iommu: Support migration
pc: Add support for virtio-iommu-pci
tests: Add virtio-iommu test

 hw/arm/virt-acpi-build.c         |  91 ++-
 hw/arm/virt.c                    |  53 +-
 hw/core/qdev-properties.c        |  90 +++
 hw/i386/acpi-build.c             |  72 +++
 hw/i386/pc.c                     |  15 +-
 hw/virtio/Kconfig                |   5 +
 hw/virtio/Makefile.objs          |   2 +
 hw/virtio/trace-events           |  22 +
 hw/virtio/virtio-iommu-pci.c     |  91 +++
 hw/virtio/virtio-iommu.c         | 952 +++++++++++++++++++++++++++++++
 include/exec/memory.h            |   6 +
 include/hw/acpi/acpi-defs.h      |  21 +-
 include/hw/arm/virt.h            |   2 +
 include/hw/i386/pc.h             |   2 +
 include/hw/pci/pci.h             |   1 +
 include/hw/qdev-properties.h     |   3 +
 include/hw/virtio/virtio-iommu.h |  67 +++
 include/migration/vmstate.h      |  21 +
 include/qemu/queue.h             |  39 ++
 include/qemu/typedefs.h          |   1 +
 migration/trace-events           |   5 +
 migration/vmstate-types.c        |  70 +++
 qdev-monitor.c                   |   1 +
 tests/Makefile.include           |   2 +
 tests/libqos/virtio-iommu.c      | 177 ++++++
 tests/libqos/virtio-iommu.h      |  45 ++
 tests/test-vmstate.c             | 170 ++++++
 tests/virtio-iommu-test.c        | 261 +++++++++
 28 files changed, 2253 insertions(+), 34 deletions(-)
 create mode 100644 hw/virtio/virtio-iommu-pci.c
 create mode 100644 hw/virtio/virtio-iommu.c
 create mode 100644 include/hw/virtio/virtio-iommu.h
 create mode 100644 tests/libqos/virtio-iommu.c
 create mode 100644 tests/libqos/virtio-iommu.h
 create mode 100644 tests/virtio-iommu-test.c
Signature · 1 line
2.20.1
author
#88 lore raw

Hi Michael,

Quoted 20 lines · Michael S. Tsirkin
Quoted 19 lines · Auger Eric

Hi Michael,

Quoted 6 lines · Michael S. Tsirkin
Quoted 5 lines · Eric Auger

This series implements the QEMU virtio-iommu device.

This matches the v0.12 spec and the corresponding virtio-iommu driver upstreamed in 5.3.

Quoted 7 lines
Quoted 5 lines

The pci proxy for the virtio-iommu device is instantiated using "-device virtio-iommu-pci". This series still relies on ACPI IORT/DT integration. Note the ACPI IORT integration is not yet upstreamed and testing needs to be based on Jean-Philippe's additional kernel patches [1].

Or the config space approach? I really liked that one.

Yes this corresponds to the paragraph below.

Quoted 2 lines
Quoted 2 lines
Quoted 6 lines
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines

Work is ongoing to remove IORT adherence and allow the bindings between the IOMMU and the root complex to be defined and written into the PCI device configuration space. The outcome of this work is uncertain at this stage though. See [2].

Oh right. Why is it uncertain? Anything can be done to help?

Jean's series was sent on the same day as this QEMU respin. My understanding is we still need a way to handle platform devices. Also the binding info layout needs to be revised and integrated into the spec
+ voted. Those are the uncertainties I wanted to point out.

Thanks

Eric

Quoted 188 lines
Quoted 186 lines

Thanks

Eric

Quoted 181 lines
Quoted 179 lines

So only patches 1-11 fully rely on upstreamed kernel code. Others should be considered as RFC.

This respin allows people to test on ARM and x86. It also brings migration support (tested on ARM) and various cleanups. Reserved regions are now passed through an array of properties. A libqos test also is introduced to test the virtio-iommu API.

Note integration with vhost devices and vfio devices is not part of this series. Please follow Bharat's respins [3].

The 1st Patch ("migration: Support QLIST migration") was sent separately [4].

Best Regards

Eric

This series can be found at:
https://github.com/eauger/qemu/tree/v4.2-rc2-virtio-iommu-v11

[1] kernel branch to be used for guest

    https://github.com/eauger/linux/tree/v5.4-rc8-virtio-iommu-iort

[2] [RFC 00/13] virtio-iommu on non-devicetree platforms
[3] VFIO/VHOST integration is not part of this series. Please follow [PATCH RFC v5 0/5] virtio-iommu: VFIO integration respins
[4] [PATCH v6] migration: Support QLIST migration

Testing:
- tested with guest using virtio-net-pci (,vhost=off,iommu_platform,disable-modern=off,disable-legacy=on) and virtio-blk-pci
- migration on ARM
- on x86 PC machine I get some AHCI non translated transactions, very early. This does not prevent the guest from boot and behaving properly. Warnings look like:
qemu-system-x86_64: virtio_iommu_translate sid=250 is not known!!
qemu-system-x86_64: no buffer available in event queue to report event
qemu-system-x86_64: AHCI: Failed to start FIS receive engine: bad FIS receive buffer address

History:

v10 -> v11:
- introduce virtio_iommu_handle_req macro
- migration support
- introduce DEFINE_PROP_INTERVAL and pass reserved regions through an array of those
- domain gtree simplification

v9 -> v10:
- rebase on 4.1.0-rc2, compliance with 0.12 spec
- removed ACPI part
- cleanup (see individual change logs)
- moved to a PATCH series

v8 -> v9:
- virtio-iommu-pci device needs to be instantiated from the command line (RID is not imposed anymore).
- tail structure properly initialized

v7 -> v8:
- virtio-iommu-pci added
- virt instantiation modified
- DT and ACPI modified to exclude the iommu RID from the mapping
- VIRTIO_IOMMU_F_BYPASS, VIRTIO_F_VERSION_1 features exposed

v6 -> v7:
- rebase on qemu 3.0.0-rc3
- minor update against v0.7
- fix issue with EP not on pci.0 and ACPI probing
- change the instantiation method

v5 -> v6:
- minor update against v0.6 spec
- fix g_hash_table_lookup in virtio_iommu_find_add_as
- replace some error_reports by qemu_log_mask(LOG_GUEST_ERROR, ...)

v4 -> v5:
- event queue and fault reporting
- we now return the IOAPIC MSI region if the virtio-iommu is instantiated in a PC machine.
- we bypass transactions on MSI HW region and fault on reserved ones.
- We support ACPI boot with mach-virt (based on IORT proposal)
- We moved to the new driver naming conventions
- simplified mach-virt instantiation
- worked around the disappearing of pci_find_primary_bus
- in virtio_iommu_translate, check the dev->as is not NULL
- initialize as->device_list in virtio_iommu_get_as
- initialize bufstate.error to false in virtio_iommu_probe

v3 -> v4:
- probe request support although no reserved region is returned at the moment
- unmap semantics less strict, as specified in v0.4
- device registration, attach/detach revisited
- split into smaller patches to ease review
- propose a way to inform the IOMMU mr about the page_size_mask of underlying HW IOMMU, if any
- remove warning associated with the translation of the MSI doorbell

v2 -> v3:
- rebase on top of 2.10-rc0 and especially
[PATCH qemu v9 0/2] memory/iommu: QOM'fy IOMMU MemoryRegion
- add mutex init
- fix as->mappings deletion using g_tree_ref/unref
- when a dev is attached whereas it is already attached to another address space, first detach it
- fix some error values
- page_sizes = TARGET_PAGE_MASK;
- I haven't changed the unmap() semantics yet, waiting for the next virtio-iommu spec revision.

v1 -> v2:
- fix redefinition of viommu_as typedef

Eric Auger (20):
migration: Support QLIST migration
virtio-iommu: Add skeleton
virtio-iommu: Decode the command payload
virtio-iommu: Add the iommu regions
virtio-iommu: Endpoint and domains structs and helpers
virtio-iommu: Implement attach/detach command
virtio-iommu: Implement map/unmap
virtio-iommu: Implement translate
virtio-iommu: Implement fault reporting
virtio-iommu-pci: Add virtio iommu pci support hw/arm/virt: Add the virtio-iommu device tree mappings
qapi: Introduce DEFINE_PROP_INTERVAL
virtio-iommu: Implement probe request
virtio-iommu: Handle reserved regions in the translation process
virtio-iommu-pci: Add array of Interval properties hw/arm/virt-acpi-build: Introduce fill_iort_idmap helper hw/arm/virt-acpi-build: Add virtio-iommu node in IORT table
virtio-iommu: Support migration
pc: Add support for virtio-iommu-pci
tests: Add virtio-iommu test

 hw/arm/virt-acpi-build.c         |  91 ++-
 hw/arm/virt.c                    |  53 +-
 hw/core/qdev-properties.c        |  90 +++
 hw/i386/acpi-build.c             |  72 +++
 hw/i386/pc.c                     |  15 +-
 hw/virtio/Kconfig                |   5 +
 hw/virtio/Makefile.objs          |   2 +
 hw/virtio/trace-events           |  22 +
 hw/virtio/virtio-iommu-pci.c     |  91 +++
 hw/virtio/virtio-iommu.c         | 952 +++++++++++++++++++++++++++++++
 include/exec/memory.h            |   6 +
 include/hw/acpi/acpi-defs.h      |  21 +-
 include/hw/arm/virt.h            |   2 +
 include/hw/i386/pc.h             |   2 +
 include/hw/pci/pci.h             |   1 +
 include/hw/qdev-properties.h     |   3 +
 include/hw/virtio/virtio-iommu.h |  67 +++
 include/migration/vmstate.h      |  21 +
 include/qemu/queue.h             |  39 ++
 include/qemu/typedefs.h          |   1 +
 migration/trace-events           |   5 +
 migration/vmstate-types.c        |  70 +++
 qdev-monitor.c                   |   1 +
 tests/Makefile.include           |   2 +
 tests/libqos/virtio-iommu.c      | 177 ++++++
 tests/libqos/virtio-iommu.h      |  45 ++
 tests/test-vmstate.c             | 170 ++++++
 tests/virtio-iommu-test.c        | 261 +++++++++
 28 files changed, 2253 insertions(+), 34 deletions(-)
 create mode 100644 hw/virtio/virtio-iommu-pci.c
 create mode 100644 hw/virtio/virtio-iommu.c
 create mode 100644 include/hw/virtio/virtio-iommu.h
 create mode 100644 tests/libqos/virtio-iommu.c
 create mode 100644 tests/libqos/virtio-iommu.h
 create mode 100644 tests/virtio-iommu-test.c
Signature · 1 line
2.20.1