Skip to contentSkip to conversation

Support message-based DMA in vfio-user server

PATCH Superseded Mattias Nissler 2 participants 12 messages May 7, 2024 – May 13, 2024

v9 of 12 Superseded Latest is v12 →

lore
Share & tools
lore
#0 lore raw

v9 cover Support message-based DMA in vfio-user server

This series adds basic support for message-based DMA in qemu's vfio-user server. This is useful for cases where the client does not provide file descriptors for accessing system memory via memory mappings. My motivating use case is to hook up device models as PCIe endpoints to a hardware design. This works by bridging the PCIe transaction layer to vfio-user, and the endpoint does not access memory directly, but sends memory requests TLPs to the hardware design in order to perform DMA.

Note that more work is needed to make message-based DMA work well: qemu currently breaks down DMA accesses into chunks of size 8 bytes at maximum, each of which will be handled in a separate vfio-user DMA request message. This is quite terrible for large DMA accesses, such as when nvme reads and writes page-sized blocks for example. Thus, I would like to improve qemu to be able to perform larger accesses, at least for indirect memory regions. I have something working locally, but since this will likely result in more involved surgery and discussion, I am leaving this to be addressed in a separate patch.

Changes from v1:

* Address Stefan's review comments. In particular, enforce an allocation limit and don't drop the map client callbacks given that map requests can fail when hitting size limits.

* libvfio-user version bump now included in the series.

* Tested as well on big-endian s390x. This uncovered another byte order issue in vfio-user server code that I've included a fix for.

Changes from v2:

* Add a preparatory patch to make bounce buffering an AddressSpace-specific concept.

* The total buffer size limit parameter is now per AdressSpace and can be configured for PCIDevice via a property.

* Store a magic value in first bytes of bounce buffer struct as a best effort measure to detect invalid pointers in address_space_unmap.

Changes from v3:

* libvfio-user now supports twin-socket mode which uses separate sockets for client->server and server->client commands, respectively. This addresses the concurrent command bug triggered by server->client DMA access commands. See
https://github.com/nutanix/libvfio-user/issues/279 for details.

* Add missing teardown code in do_address_space_destroy.

* Fix bounce buffer size bookkeeping race condition.

* Generate unmap notification callbacks unconditionally.

* Some cosmetic fixes.

Changes from v4:

* Fix accidentally dropped memory_region_unref, control flow restored to match previous code to simplify review.

* Some cosmetic fixes.

Changes from v5:

* Unregister indirect memory region in libvfio-user dma_unregister callback.

Changes from v6:

* Rebase, resolve straightforward merge conflict in system/dma-helpers.c

Changes from v7:

* Rebase (applied cleanly)

* Restore various Reviewed-by and Tested-by tags that I failed to carry forward (I double-checked that the patches haven't changed since the reviewed version)

Changes from v8:

* Rebase (clean)

* Change bounce buffer size accounting to use uint32_t so it works also on hosts that don't support uint64_t atomics, such as mipsel. As a consequence overflows are a real concern now, so switch to a cmpxchg loop for allocating bounce buffer space.

Mattias Nissler (5):
softmmu: Per-AddressSpace bounce buffering
softmmu: Support concurrent bounce buffers
Update subprojects/libvfio-user
vfio-user: Message-based DMA support
vfio-user: Fix config space access byte order

 hw/pci/pci.c                  |   8 ++
 hw/remote/trace-events        |   2 +
 hw/remote/vfio-user-obj.c     | 104 +++++++++++++++++++++----
 include/exec/cpu-common.h     |   2 -
 include/exec/memory.h         |  41 +++++++++-
 include/hw/pci/pci_device.h   |   3 +
 subprojects/libvfio-user.wrap |   2 +-
 system/dma-helpers.c          |   4 +-
 system/memory.c               |   8 ++
 system/physmem.c              | 143 ++++++++++++++++++----------------
 10 files changed, 228 insertions(+), 89 deletions(-)
Signature · 1 line
2.43.2
#1 lore raw

PATCH v9 1/5 softmmu: Per-AddressSpace bounce buffering

Instead of using a single global bounce buffer, give each AddressSpace its own bounce buffer. The MapClient callback mechanism moves to AddressSpace accordingly.

This is in preparation for generalizing bounce buffer handling further to allow multiple bounce buffers, with a total allocation limit configured per AddressSpace.

---
 include/exec/cpu-common.h |   2 -
 include/exec/memory.h     |  45 ++++++++++++++++-
 system/dma-helpers.c      |   4 +-
 system/memory.c           |   7 +++
 system/physmem.c          | 101 ++++++++++++++++----------------------
 5 files changed, 93 insertions(+), 66 deletions(-)
include/exec/cpu-common.h +0 -2
index 8bc397e251..815342d043 100644
@@ -147,8 +147,6 @@ void *cpu_physical_memory_map(hwaddr addr,
                               bool is_write);
 void cpu_physical_memory_unmap(void *buffer, hwaddr len,
                                bool is_write, hwaddr access_len);
-void cpu_register_map_client(QEMUBH *bh);
-void cpu_unregister_map_client(QEMUBH *bh);
 
 bool cpu_physical_memory_is_io(hwaddr phys_addr);
 
include/exec/memory.h +43 -2

69 lines not on this page · raw message

system/dma-helpers.c +2 -2
index 9b221cf94e..74013308f5 100644
@@ -169,7 +169,7 @@ static void dma_blk_cb(void *opaque, int ret)
     if (dbs->iov.size == 0) {
         trace_dma_map_wait(dbs);
         dbs->bh = aio_bh_new(ctx, reschedule_dma, dbs);
-        cpu_register_map_client(dbs->bh);
+        address_space_register_map_client(dbs->sg->as, dbs->bh);
         return;
     }
 
@@ -197,7 +197,7 @@ static void dma_aio_cancel(BlockAIOCB *acb)
     }
 
     if (dbs->bh) {
-        cpu_unregister_map_client(dbs->bh);
+        address_space_unregister_map_client(dbs->sg->as, dbs->bh);
         qemu_bh_delete(dbs->bh);
         dbs->bh = NULL;
     }
system/memory.c +7 -0
index 49f1cb2c38..642a449f8c 100644
@@ -3174,6 +3174,9 @@ void address_space_init(AddressSpace *as, MemoryRegion *root, const char *name)
     as->ioeventfds = NULL;
     QTAILQ_INIT(&as->listeners);
     QTAILQ_INSERT_TAIL(&address_spaces, as, address_spaces_link);
+    as->bounce.in_use = false;
+    qemu_mutex_init(&as->map_client_list_lock);
+    QLIST_INIT(&as->map_client_list);
     as->name = g_strdup(name ? name : "anonymous");
     address_space_update_topology(as);
     address_space_update_ioeventfds(as);
@@ -3181,6 +3184,10 @@ void address_space_init(AddressSpace *as, MemoryRegion *root, const char *name)
 
 static void do_address_space_destroy(AddressSpace *as)
 {
+    assert(!qatomic_read(&as->bounce.in_use));
+    assert(QLIST_EMPTY(&as->map_client_list));
+    qemu_mutex_destroy(&as->map_client_list_lock);
+
     assert(QTAILQ_EMPTY(&as->listeners));
 
     flatview_unref(as->current_map);
system/physmem.c +41 -60

179 lines not on this page · raw message

Signature · 1 line
2.43.2
#2 lore raw

Re: [PATCH v9 1/5] softmmu: Per-AddressSpace bounce buffering

Quoted 11 lines · Mattias Nissler

Instead of using a single global bounce buffer, give each AddressSpace its own bounce buffer. The MapClient callback mechanism moves to AddressSpace accordingly.

This is in preparation for generalizing bounce buffer handling further to allow multiple bounce buffers, with a total allocation limit configured per AddressSpace.

Quoted 7 lines
---
  include/exec/cpu-common.h |   2 -
  include/exec/memory.h     |  45 ++++++++++++++++-
  system/dma-helpers.c      |   4 +-
  system/memory.c           |   7 +++
  system/physmem.c          | 101 ++++++++++++++++----------------------
  5 files changed, 93 insertions(+), 66 deletions(-)

This patch has been split in 2 simpler -- IMHO -- parts here:
https://lore.kernel.org/qemu-devel/[email protected]/

#3 lore raw

PATCH v9 2/5 softmmu: Support concurrent bounce buffers

In reply to Mattias Nissler

When DMA memory can't be directly accessed, as is the case when running the device model in a separate process without shareable DMA file descriptors, bounce buffering is used.

It is not uncommon for device models to request mapping of several DMA regions at the same time. Examples include:
* net devices, e.g. when transmitting a packet that is split across several TX descriptors (observed with igb)
* USB host controllers, when handling a packet with multiple data TRBs (observed with xhci)

Previously, qemu only provided a single bounce buffer per AddressSpace and would fail DMA map requests while the buffer was already in use. In turn, this would cause DMA failures that ultimately manifest as hardware errors from the guest perspective.

This change allocates DMA bounce buffers dynamically instead of supporting only a single buffer. Thus, multiple DMA mappings work correctly also when RAM can't be mmap()-ed.

The total bounce buffer allocation size is limited individually for each AddressSpace. The default limit is 4096 bytes, matching the previous maximum buffer size. A new x-max-bounce-buffer-size parameter is provided to configure the limit for PCI devices.

---
 hw/pci/pci.c                |  8 ++++
 include/exec/memory.h       | 14 +++----
 include/hw/pci/pci_device.h |  3 ++
 system/memory.c             |  5 ++-
 system/physmem.c            | 82 ++++++++++++++++++++++++++-----------
 5 files changed, 76 insertions(+), 36 deletions(-)
hw/pci/pci.c +8 -0
index 324c1302d2..69934bfbbf 100644
@@ -85,6 +85,8 @@ static Property pci_props[] = {
                     QEMU_PCIE_ERR_UNC_MASK_BITNR, true),
     DEFINE_PROP_BIT("x-pcie-ari-nextfn-1", PCIDevice, cap_present,
                     QEMU_PCIE_ARI_NEXTFN_1_BITNR, false),
+    DEFINE_PROP_UINT32("x-max-bounce-buffer-size", PCIDevice,
+                       max_bounce_buffer_size, DEFAULT_MAX_BOUNCE_BUFFER_SIZE),
     DEFINE_PROP_END_OF_LIST()
 };
 
@@ -1204,6 +1206,8 @@ static PCIDevice *do_pci_register_device(PCIDevice *pci_dev,
                        "bus master container", UINT64_MAX);
     address_space_init(&pci_dev->bus_master_as,
                        &pci_dev->bus_master_container_region, pci_dev->name);
+    pci_dev->bus_master_as.max_bounce_buffer_size =
+        pci_dev->max_bounce_buffer_size;
 
     if (phase_check(PHASE_MACHINE_READY)) {
         pci_init_bus_master(pci_dev);
@@ -2633,6 +2637,10 @@ static void pci_device_class_init(ObjectClass *klass, void *data)
     k->unrealize = pci_qdev_unrealize;
     k->bus_type = TYPE_PCI_BUS;
     device_class_set_props(k, pci_props);
+    object_class_property_set_description(
+        klass, "x-max-bounce-buffer-size",
+        "Maximum buffer size allocated for bounce buffers used for mapped "
+        "access to indirect DMA memory");
 }
 
 static void pci_device_class_base_init(ObjectClass *klass, void *data)
include/exec/memory.h +5 -9
index d417d7f363..2ea1e99da2 100644
@@ -1117,13 +1117,7 @@ typedef struct AddressSpaceMapClient {
     QLIST_ENTRY(AddressSpaceMapClient) link;
 } AddressSpaceMapClient;
 
-typedef struct {
-    MemoryRegion *mr;
-    void *buffer;
-    hwaddr addr;
-    hwaddr len;
-    bool in_use;
-} BounceBuffer;
+#define DEFAULT_MAX_BOUNCE_BUFFER_SIZE (4096)
 
 /**
  * struct AddressSpace: describes a mapping of addresses to #MemoryRegion objects
@@ -1143,8 +1137,10 @@ struct AddressSpace {
     QTAILQ_HEAD(, MemoryListener) listeners;
     QTAILQ_ENTRY(AddressSpace) address_spaces_link;
 
-    /* Bounce buffer to use for this address space. */
-    BounceBuffer bounce;
+    /* Maximum DMA bounce buffer size used for indirect memory map requests */
+    uint32_t max_bounce_buffer_size;
+    /* Total size of bounce buffers currently allocated, atomically accessed */
+    uint32_t bounce_buffer_size;
     /* List of callbacks to invoke when buffers free up */
     QemuMutex map_client_list_lock;
     QLIST_HEAD(, AddressSpaceMapClient) map_client_list;
include/hw/pci/pci_device.h +3 -0
index d3dd0f64b2..253b48a688 100644
@@ -160,6 +160,9 @@ struct PCIDevice {
     /* ID of standby device in net_failover pair */
     char *failover_pair_id;
     uint32_t acpi_index;
+
+    /* Maximum DMA bounce buffer size used for indirect memory map requests */
+    uint32_t max_bounce_buffer_size;
 };
 
 static inline int pci_intx(PCIDevice *pci_dev)
system/memory.c +3 -2
index 642a449f8c..c288ed354a 100644
@@ -3174,7 +3174,8 @@ void address_space_init(AddressSpace *as, MemoryRegion *root, const char *name)
     as->ioeventfds = NULL;
     QTAILQ_INIT(&as->listeners);
     QTAILQ_INSERT_TAIL(&address_spaces, as, address_spaces_link);
-    as->bounce.in_use = false;
+    as->max_bounce_buffer_size = DEFAULT_MAX_BOUNCE_BUFFER_SIZE;
+    as->bounce_buffer_size = 0;
     qemu_mutex_init(&as->map_client_list_lock);
     QLIST_INIT(&as->map_client_list);
     as->name = g_strdup(name ? name : "anonymous");
@@ -3184,7 +3185,7 @@ void address_space_init(AddressSpace *as, MemoryRegion *root, const char *name)
 
 static void do_address_space_destroy(AddressSpace *as)
 {
-    assert(!qatomic_read(&as->bounce.in_use));
+    assert(qatomic_read(&as->bounce_buffer_size) == 0);
     assert(QLIST_EMPTY(&as->map_client_list));
     qemu_mutex_destroy(&as->map_client_list_lock);
 
system/physmem.c +57 -25

127 lines not on this page · raw message

Signature · 1 line
2.43.2
#4 lore raw

Re: [PATCH v9 2/5] softmmu: Support concurrent bounce buffers

Quoted 55 lines · Mattias Nissler

When DMA memory can't be directly accessed, as is the case when running the device model in a separate process without shareable DMA file descriptors, bounce buffering is used.

It is not uncommon for device models to request mapping of several DMA regions at the same time. Examples include:
* net devices, e.g. when transmitting a packet that is split across several TX descriptors (observed with igb)
* USB host controllers, when handling a packet with multiple data TRBs (observed with xhci)

Previously, qemu only provided a single bounce buffer per AddressSpace and would fail DMA map requests while the buffer was already in use. In turn, this would cause DMA failures that ultimately manifest as hardware errors from the guest perspective.

This change allocates DMA bounce buffers dynamically instead of supporting only a single buffer. Thus, multiple DMA mappings work correctly also when RAM can't be mmap()-ed.

The total bounce buffer allocation size is limited individually for each AddressSpace. The default limit is 4096 bytes, matching the previous maximum buffer size. A new x-max-bounce-buffer-size parameter is provided to configure the limit for PCI devices.

---
  hw/pci/pci.c                |  8 ++++
  include/exec/memory.h       | 14 +++----
  include/hw/pci/pci_device.h |  3 ++
  system/memory.c             |  5 ++-
  system/physmem.c            | 82 ++++++++++++++++++++++++++-----------
  5 files changed, 76 insertions(+), 36 deletions(-)
include/exec/memory.h +1 -7
index d417d7f363..2ea1e99da2 100644
@@ -1117,13 +1117,7 @@ typedef struct AddressSpaceMapClient {
      QLIST_ENTRY(AddressSpaceMapClient) link;
  } AddressSpaceMapClient;
 
-typedef struct {
-    MemoryRegion *mr;
-    void *buffer;
-    hwaddr addr;
-    hwaddr len;
-    bool in_use;
-} BounceBuffer;
+#define DEFAULT_MAX_BOUNCE_BUFFER_SIZE (4096)
 
  /**
   * struct AddressSpace: describes a mapping of addresses to #MemoryRegion objects

include/exec/memory.h struct AddressSpace { · line 1141

Quoted 7 lines
include/exec/memory.h +2 -2
@@ -1143,8 +1137,10 @@ struct AddressSpace {
      QTAILQ_HEAD(, MemoryListener) listeners;
      QTAILQ_ENTRY(AddressSpace) address_spaces_link;
 
-    /* Bounce buffer to use for this address space. */
-    BounceBuffer bounce;
+    /* Maximum DMA bounce buffer size used for indirect memory map requests */
+    uint32_t max_bounce_buffer_size;

Alternatively size_t.

include/exec/memory.h struct AddressSpace { · line 1143

Quoted 2 lines
include/exec/memory.h +2 -0
+    /* Total size of bounce buffers currently allocated, atomically accessed */
+    uint32_t bounce_buffer_size;

Ditto.

Quoted 8 lines
include/exec/memory.h +0 -0
      /* List of callbacks to invoke when buffers free up */
      QemuMutex map_client_list_lock;
      QLIST_HEAD(, AddressSpaceMapClient) map_client_list;
include/hw/pci/pci_device.h +0 -0
index d3dd0f64b2..253b48a688 100644

include/hw/pci/pci_device.h struct PCIDevice { · line 165

Quoted 6 lines
include/hw/pci/pci_device.h +3 -0
@@ -160,6 +160,9 @@ struct PCIDevice {
      /* ID of standby device in net_failover pair */
      char *failover_pair_id;
      uint32_t acpi_index;
+
+    /* Maximum DMA bounce buffer size used for indirect memory map requests */
+    uint32_t max_bounce_buffer_size;

Ditto.

Quoted 14 lines
include/hw/pci/pci_device.h +0 -0
  };
 
 
system/physmem.c +3 -0
index 632da6508a..cd61758da0 100644
@@ -3046,6 +3046,20 @@ void cpu_flush_icache_range(hwaddr start, hwaddr len)
                                       NULL, len, FLUSH_CACHE);
  }
 
+/*
+ * A magic value stored in the first 8 bytes of the bounce buffer struct. Used
+ * to detect illegal pointers passed to address_space_unmap.

system/physmem.c void cpu_flush_icache_range(hwaddr start, hwaddr len) · line 3061

Quoted 10 lines
system/physmem.c +10 -0
+ */
+#define BOUNCE_BUFFER_MAGIC 0xb4017ceb4ffe12ed
+
+typedef struct {
+    uint64_t magic;
+    MemoryRegion *mr;
+    hwaddr addr;
+    uint32_t len;
+    uint8_t buffer[];
+} BounceBuffer;

Eh, you moved it back here. Never mind.

Quoted 17 lines
system/physmem.c +3 -2
+
  static void
  address_space_unregister_map_client_do(AddressSpaceMapClient *client)
  {
@@ -3071,9 +3085,9 @@ void address_space_register_map_client(AddressSpace *as, QEMUBH *bh)
      qemu_mutex_lock(&as->map_client_list_lock);
      client->bh = bh;
      QLIST_INSERT_HEAD(&as->map_client_list, client, link);
-    /* Write map_client_list before reading in_use.  */
+    /* Write map_client_list before reading bounce_buffer_size. */
      smp_mb();
-    if (!qatomic_read(&as->bounce.in_use)) {
+    if (qatomic_read(&as->bounce_buffer_size) < as->max_bounce_buffer_size) {
          address_space_notify_map_clients_locked(as);
      }
      qemu_mutex_unlock(&as->map_client_list_lock);

system/physmem.c void *address_space_map(AddressSpace *as, · line 3220

Quoted 5 lines
system/physmem.c +1 -1
@@ -3203,28 +3217,40 @@ void *address_space_map(AddressSpace *as,
      mr = flatview_translate(fv, addr, &xlat, &l, is_write, attrs);
 
      if (!memory_access_is_direct(mr, is_write)) {
-        if (qatomic_xchg(&as->bounce.in_use, true)) {
+        uint32_t used = qatomic_read(&as->bounce_buffer_size);

Nitpicking again, size_t seems clearer. Otherwise LGTM.

#5 lore raw

Re: [PATCH v9 2/5] softmmu: Support concurrent bounce buffers

Quoted 60 lines · Philippe Mathieu-Daudé
Quoted 58 lines · Mattias Nissler

When DMA memory can't be directly accessed, as is the case when running the device model in a separate process without shareable DMA file descriptors, bounce buffering is used.

It is not uncommon for device models to request mapping of several DMA regions at the same time. Examples include:
* net devices, e.g. when transmitting a packet that is split across several TX descriptors (observed with igb)
* USB host controllers, when handling a packet with multiple data TRBs (observed with xhci)

Previously, qemu only provided a single bounce buffer per AddressSpace and would fail DMA map requests while the buffer was already in use. In turn, this would cause DMA failures that ultimately manifest as hardware errors from the guest perspective.

This change allocates DMA bounce buffers dynamically instead of supporting only a single buffer. Thus, multiple DMA mappings work correctly also when RAM can't be mmap()-ed.

The total bounce buffer allocation size is limited individually for each AddressSpace. The default limit is 4096 bytes, matching the previous maximum buffer size. A new x-max-bounce-buffer-size parameter is provided to configure the limit for PCI devices.

---
  hw/pci/pci.c                |  8 ++++
  include/exec/memory.h       | 14 +++----
  include/hw/pci/pci_device.h |  3 ++
  system/memory.c             |  5 ++-
  system/physmem.c            | 82 ++++++++++++++++++++++++++-----------
  5 files changed, 76 insertions(+), 36 deletions(-)
include/exec/memory.h +1 -7
index d417d7f363..2ea1e99da2 100644
@@ -1117,13 +1117,7 @@ typedef struct AddressSpaceMapClient {
      QLIST_ENTRY(AddressSpaceMapClient) link;
  } AddressSpaceMapClient;
 
-typedef struct {
-    MemoryRegion *mr;
-    void *buffer;
-    hwaddr addr;
-    hwaddr len;
-    bool in_use;
-} BounceBuffer;
+#define DEFAULT_MAX_BOUNCE_BUFFER_SIZE (4096)
 
  /**
   * struct AddressSpace: describes a mapping of addresses to #MemoryRegion objects
@@ -1143,8 +1137,10 @@ struct AddressSpace {
      QTAILQ_HEAD(, MemoryListener) listeners;
      QTAILQ_ENTRY(AddressSpace) address_spaces_link;
 
Quoted 6 lines

include/exec/memory.h struct AddressSpace { · line 1141

Quoted 4 lines
include/exec/memory.h +2 -2
-    /* Bounce buffer to use for this address space. */
-    BounceBuffer bounce;
+    /* Maximum DMA bounce buffer size used for indirect memory map requests */
+    uint32_t max_bounce_buffer_size;

Alternatively size_t.

While switching things over, I was surprised to find that DEFINE_PROP_SIZE wants a uint64_t field rather than a size_t field. There is a DEFINE_PROP_SIZE32 variant for uint32_t though. Considering my options, assuming that we want to use size_t for everything other than the property:

(1) Make PCIDevice::max_bounce_buffer_size size_t and have the preprocessor select DEFINE_PROP_SIZE/DEFINE_PROP_SIZE32. This makes the qdev property type depend on the host. Ugh.

(2) Make PCIDevice::max_bounce_buffer_size uint64_t and clamp if needed when used. Weird to allow larger values that are then clamped, although it probably doesn't matter in practice since address space is limited to 4GB anyways.

(3) Make PCIDevice::max_bounce_buffer_size uint32_t and accept the limitation that the largest bounce buffer limit is 4GB even on 64-bit hosts.

#3 seemed most pragmatic, so I'll go with that.

Quoted 74 lines

include/exec/memory.h struct AddressSpace { · line 1143

Quoted 3 lines
include/exec/memory.h +2 -0
+    /* Total size of bounce buffers currently allocated, atomically accessed */
+    uint32_t bounce_buffer_size;

Ditto.

Quoted 8 lines
include/exec/memory.h +0 -0
      /* List of callbacks to invoke when buffers free up */
      QemuMutex map_client_list_lock;
      QLIST_HEAD(, AddressSpaceMapClient) map_client_list;
include/hw/pci/pci_device.h +0 -0
index d3dd0f64b2..253b48a688 100644

include/hw/pci/pci_device.h struct PCIDevice { · line 165

Quoted 6 lines
include/hw/pci/pci_device.h +3 -0
@@ -160,6 +160,9 @@ struct PCIDevice {
      /* ID of standby device in net_failover pair */
      char *failover_pair_id;
      uint32_t acpi_index;
+
+    /* Maximum DMA bounce buffer size used for indirect memory map requests */
+    uint32_t max_bounce_buffer_size;

Ditto.

Quoted 14 lines
include/hw/pci/pci_device.h +0 -0
  };
 
 
system/physmem.c +3 -0
index 632da6508a..cd61758da0 100644
@@ -3046,6 +3046,20 @@ void cpu_flush_icache_range(hwaddr start, hwaddr len)
                                       NULL, len, FLUSH_CACHE);
  }
 
+/*
+ * A magic value stored in the first 8 bytes of the bounce buffer struct. Used
+ * to detect illegal pointers passed to address_space_unmap.

system/physmem.c void cpu_flush_icache_range(hwaddr start, hwaddr len) · line 3061

Quoted 10 lines
system/physmem.c +10 -0
+ */
+#define BOUNCE_BUFFER_MAGIC 0xb4017ceb4ffe12ed
+
+typedef struct {
+    uint64_t magic;
+    MemoryRegion *mr;
+    hwaddr addr;
+    uint32_t len;
+    uint8_t buffer[];
+} BounceBuffer;

Eh, you moved it back here. Never mind.

Quoted 17 lines
system/physmem.c +3 -2
+
  static void
  address_space_unregister_map_client_do(AddressSpaceMapClient *client)
  {
@@ -3071,9 +3085,9 @@ void address_space_register_map_client(AddressSpace *as, QEMUBH *bh)
      qemu_mutex_lock(&as->map_client_list_lock);
      client->bh = bh;
      QLIST_INSERT_HEAD(&as->map_client_list, client, link);
-    /* Write map_client_list before reading in_use.  */
+    /* Write map_client_list before reading bounce_buffer_size. */
      smp_mb();
-    if (!qatomic_read(&as->bounce.in_use)) {
+    if (qatomic_read(&as->bounce_buffer_size) < as->max_bounce_buffer_size) {
          address_space_notify_map_clients_locked(as);
      }
      qemu_mutex_unlock(&as->map_client_list_lock);

system/physmem.c void *address_space_map(AddressSpace *as, · line 3220

Quoted 5 lines
system/physmem.c +1 -1
@@ -3203,28 +3217,40 @@ void *address_space_map(AddressSpace *as,
      mr = flatview_translate(fv, addr, &xlat, &l, is_write, attrs);
 
      if (!memory_access_is_direct(mr, is_write)) {
-        if (qatomic_xchg(&as->bounce.in_use, true)) {
+        uint32_t used = qatomic_read(&as->bounce_buffer_size);

Nitpicking again, size_t seems clearer. Otherwise LGTM.

#6 lore raw

Re: [PATCH v9 2/5] softmmu: Support concurrent bounce buffers

Quoted 66 lines · Mattias Nissler
Quoted 43 lines · Philippe Mathieu-Daudé
Quoted 41 lines · Mattias Nissler

When DMA memory can't be directly accessed, as is the case when running the device model in a separate process without shareable DMA file descriptors, bounce buffering is used.

It is not uncommon for device models to request mapping of several DMA regions at the same time. Examples include:
* net devices, e.g. when transmitting a packet that is split across several TX descriptors (observed with igb)
* USB host controllers, when handling a packet with multiple data TRBs (observed with xhci)

Previously, qemu only provided a single bounce buffer per AddressSpace and would fail DMA map requests while the buffer was already in use. In turn, this would cause DMA failures that ultimately manifest as hardware errors from the guest perspective.

This change allocates DMA bounce buffers dynamically instead of supporting only a single buffer. Thus, multiple DMA mappings work correctly also when RAM can't be mmap()-ed.

The total bounce buffer allocation size is limited individually for each AddressSpace. The default limit is 4096 bytes, matching the previous maximum buffer size. A new x-max-bounce-buffer-size parameter is provided to configure the limit for PCI devices.

---
   hw/pci/pci.c                |  8 ++++
   include/exec/memory.h       | 14 +++----
   include/hw/pci/pci_device.h |  3 ++
   system/memory.c             |  5 ++-
   system/physmem.c            | 82 ++++++++++++++++++++++++++-----------
   5 files changed, 76 insertions(+), 36 deletions(-)

/**
* struct AddressSpace: describes a mapping of addresses to #MemoryRegion objects

include/exec/memory.h +0 -0
@@ -1143,8 +1137,10 @@ struct AddressSpace {
       QTAILQ_HEAD(, MemoryListener) listeners;
       QTAILQ_ENTRY(AddressSpace) address_spaces_link;
 
Quoted 6 lines

include/exec/memory.h struct AddressSpace { · line 1141

Quoted 4 lines
include/exec/memory.h +2 -2
-    /* Bounce buffer to use for this address space. */
-    BounceBuffer bounce;
+    /* Maximum DMA bounce buffer size used for indirect memory map requests */
+    uint32_t max_bounce_buffer_size;

Alternatively size_t.

While switching things over, I was surprised to find that DEFINE_PROP_SIZE wants a uint64_t field rather than a size_t field. There is a DEFINE_PROP_SIZE32 variant for uint32_t though. Considering my options, assuming that we want to use size_t for everything other than the property:

(1) Make PCIDevice::max_bounce_buffer_size size_t and have the preprocessor select DEFINE_PROP_SIZE/DEFINE_PROP_SIZE32. This makes the qdev property type depend on the host. Ugh.

(2) Make PCIDevice::max_bounce_buffer_size uint64_t and clamp if needed when used. Weird to allow larger values that are then clamped, although it probably doesn't matter in practice since address space is limited to 4GB anyways.

Quoted 5 lines

(3) Make PCIDevice::max_bounce_buffer_size uint32_t and accept the limitation that the largest bounce buffer limit is 4GB even on 64-bit hosts.

#3 seemed most pragmatic, so I'll go with that.

LGTM, thanks for updating.

Quoted 7 lines
Quoted 7 lines

include/exec/memory.h struct AddressSpace { · line 1143

Quoted 5 lines
include/exec/memory.h +2 -0
+    /* Total size of bounce buffers currently allocated, atomically accessed */
+    uint32_t bounce_buffer_size;

Ditto.

#7 lore raw

Re: [PATCH v9 2/5] softmmu: Support concurrent bounce buffers

Quoted 68 lines · Philippe Mathieu-Daudé
Quoted 66 lines · Mattias Nissler
Quoted 43 lines · Philippe Mathieu-Daudé
Quoted 41 lines · Mattias Nissler

When DMA memory can't be directly accessed, as is the case when running the device model in a separate process without shareable DMA file descriptors, bounce buffering is used.

It is not uncommon for device models to request mapping of several DMA regions at the same time. Examples include:
* net devices, e.g. when transmitting a packet that is split across several TX descriptors (observed with igb)
* USB host controllers, when handling a packet with multiple data TRBs (observed with xhci)

Previously, qemu only provided a single bounce buffer per AddressSpace and would fail DMA map requests while the buffer was already in use. In turn, this would cause DMA failures that ultimately manifest as hardware errors from the guest perspective.

This change allocates DMA bounce buffers dynamically instead of supporting only a single buffer. Thus, multiple DMA mappings work correctly also when RAM can't be mmap()-ed.

The total bounce buffer allocation size is limited individually for each AddressSpace. The default limit is 4096 bytes, matching the previous maximum buffer size. A new x-max-bounce-buffer-size parameter is provided to configure the limit for PCI devices.

---
   hw/pci/pci.c                |  8 ++++
   include/exec/memory.h       | 14 +++----
   include/hw/pci/pci_device.h |  3 ++
   system/memory.c             |  5 ++-
   system/physmem.c            | 82 ++++++++++++++++++++++++++-----------
   5 files changed, 76 insertions(+), 36 deletions(-)

/**
* struct AddressSpace: describes a mapping of addresses to #MemoryRegion objects

include/exec/memory.h +0 -0
@@ -1143,8 +1137,10 @@ struct AddressSpace {
       QTAILQ_HEAD(, MemoryListener) listeners;
       QTAILQ_ENTRY(AddressSpace) address_spaces_link;
 
Quoted 6 lines

include/exec/memory.h struct AddressSpace { · line 1141

Quoted 4 lines
include/exec/memory.h +2 -2
-    /* Bounce buffer to use for this address space. */
-    BounceBuffer bounce;
+    /* Maximum DMA bounce buffer size used for indirect memory map requests */
+    uint32_t max_bounce_buffer_size;

Alternatively size_t.

While switching things over, I was surprised to find that DEFINE_PROP_SIZE wants a uint64_t field rather than a size_t field. There is a DEFINE_PROP_SIZE32 variant for uint32_t though. Considering my options, assuming that we want to use size_t for everything other than the property:

(1) Make PCIDevice::max_bounce_buffer_size size_t and have the preprocessor select DEFINE_PROP_SIZE/DEFINE_PROP_SIZE32. This makes the qdev property type depend on the host. Ugh.

(2) Make PCIDevice::max_bounce_buffer_size uint64_t and clamp if needed when used. Weird to allow larger values that are then clamped, although it probably doesn't matter in practice since address space is limited to 4GB anyways.

Quoted 7 lines
Quoted 5 lines

(3) Make PCIDevice::max_bounce_buffer_size uint32_t and accept the limitation that the largest bounce buffer limit is 4GB even on 64-bit hosts.

#3 seemed most pragmatic, so I'll go with that.

LGTM, thanks for updating.

No problem, can I ask you to provide a formal R-B on the v10 #4 patch
[1] then, so the series will be ready to go in?

[1] https://lists.nongnu.org/archive/html/qemu-devel/2024-05/msg01382.html

Quoted 9 lines
Quoted 8 lines
Quoted 8 lines

include/exec/memory.h struct AddressSpace { · line 1143

Quoted 6 lines
include/exec/memory.h +2 -0
+    /* Total size of bounce buffers currently allocated, atomically accessed */
+    uint32_t bounce_buffer_size;

Ditto.

#8 lore raw

Re: [PATCH v9 2/5] softmmu: Support concurrent bounce buffers

Phil,

Did you accidentally miss this in your pull request [1] or did you leave it out intentionally?

It's still missing the Reviewed bit after the atomic cmpxchg change prompted by the size_t switch, so that might be the reason - I'm just trying to figure out what the next step is for this patch.

Thanks,
Mattias

[1] https://lists.nongnu.org/archive/html/qemu-devel/2024-05/msg01712.html

Quoted 92 lines · Mattias Nissler
Quoted 68 lines · Philippe Mathieu-Daudé
Quoted 66 lines · Mattias Nissler
Quoted 43 lines · Philippe Mathieu-Daudé
Quoted 41 lines · Mattias Nissler

When DMA memory can't be directly accessed, as is the case when running the device model in a separate process without shareable DMA file descriptors, bounce buffering is used.

It is not uncommon for device models to request mapping of several DMA regions at the same time. Examples include:
* net devices, e.g. when transmitting a packet that is split across several TX descriptors (observed with igb)
* USB host controllers, when handling a packet with multiple data TRBs (observed with xhci)

Previously, qemu only provided a single bounce buffer per AddressSpace and would fail DMA map requests while the buffer was already in use. In turn, this would cause DMA failures that ultimately manifest as hardware errors from the guest perspective.

This change allocates DMA bounce buffers dynamically instead of supporting only a single buffer. Thus, multiple DMA mappings work correctly also when RAM can't be mmap()-ed.

The total bounce buffer allocation size is limited individually for each AddressSpace. The default limit is 4096 bytes, matching the previous maximum buffer size. A new x-max-bounce-buffer-size parameter is provided to configure the limit for PCI devices.

---
   hw/pci/pci.c                |  8 ++++
   include/exec/memory.h       | 14 +++----
   include/hw/pci/pci_device.h |  3 ++
   system/memory.c             |  5 ++-
   system/physmem.c            | 82 ++++++++++++++++++++++++++-----------
   5 files changed, 76 insertions(+), 36 deletions(-)

/**
* struct AddressSpace: describes a mapping of addresses to #MemoryRegion objects

include/exec/memory.h +0 -0
@@ -1143,8 +1137,10 @@ struct AddressSpace {
       QTAILQ_HEAD(, MemoryListener) listeners;
       QTAILQ_ENTRY(AddressSpace) address_spaces_link;
 
Quoted 6 lines

include/exec/memory.h struct AddressSpace { · line 1141

Quoted 4 lines
include/exec/memory.h +2 -2
-    /* Bounce buffer to use for this address space. */
-    BounceBuffer bounce;
+    /* Maximum DMA bounce buffer size used for indirect memory map requests */
+    uint32_t max_bounce_buffer_size;

Alternatively size_t.

While switching things over, I was surprised to find that DEFINE_PROP_SIZE wants a uint64_t field rather than a size_t field. There is a DEFINE_PROP_SIZE32 variant for uint32_t though. Considering my options, assuming that we want to use size_t for everything other than the property:

(1) Make PCIDevice::max_bounce_buffer_size size_t and have the preprocessor select DEFINE_PROP_SIZE/DEFINE_PROP_SIZE32. This makes the qdev property type depend on the host. Ugh.

(2) Make PCIDevice::max_bounce_buffer_size uint64_t and clamp if needed when used. Weird to allow larger values that are then clamped, although it probably doesn't matter in practice since address space is limited to 4GB anyways.

Quoted 7 lines
Quoted 5 lines

(3) Make PCIDevice::max_bounce_buffer_size uint32_t and accept the limitation that the largest bounce buffer limit is 4GB even on 64-bit hosts.

#3 seemed most pragmatic, so I'll go with that.

LGTM, thanks for updating.

No problem, can I ask you to provide a formal R-B on the v10 #4 patch
[1] then, so the series will be ready to go in?

[1] https://lists.nongnu.org/archive/html/qemu-devel/2024-05/msg01382.html

Quoted 9 lines
Quoted 8 lines
Quoted 8 lines

include/exec/memory.h struct AddressSpace { · line 1143

Quoted 6 lines
include/exec/memory.h +2 -0
+    /* Total size of bounce buffers currently allocated, atomically accessed */
+    uint32_t bounce_buffer_size;

Ditto.

#9 lore raw

PATCH v9 3/5 Update subprojects/libvfio-user

In reply to Mattias Nissler

Brings in assorted bug fixes. The following are of particular interest with respect to message-based DMA support:

* bb308a2 "Fix address calculation for message-based DMA" Corrects a bug in DMA address calculation.

* 1569a37 "Pass server->client command over a separate socket pair" Adds support for separate sockets for either command direction, addressing a bug where libvfio-user gets confused if both client and server send commands concurrently.

---
 subprojects/libvfio-user.wrap | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
subprojects/libvfio-user.wrap +1 -1
index 416955ca45..cdf0a7a375 100644
@@ -1,4 +1,4 @@
 [wrap-git]
 url = https://gitlab.com/qemu-project/libvfio-user.git
-revision = 0b28d205572c80b568a1003db2c8f37ca333e4d7
+revision = 1569a37a54ecb63bd4008708c76339ccf7d06115
 depth = 1
Signature · 1 line
2.43.2
#10 lore raw

PATCH v9 4/5 vfio-user: Message-based DMA support

In reply to Mattias Nissler

Wire up support for DMA for the case where the vfio-user client does not provide mmap()-able file descriptors, but DMA requests must be performed via the VFIO-user protocol. This installs an indirect memory region, which already works for pci_dma_{read,write}, and pci_dma_map works thanks to the existing DMA bounce buffering support.

Note that while simple scenarios work with this patch, there's a known race condition in libvfio-user that will mess up the communication channel. See https://github.com/nutanix/libvfio-user/issues/279 for details as well as a proposed fix.

---
 hw/remote/trace-events    |   2 +
 hw/remote/vfio-user-obj.c | 100 ++++++++++++++++++++++++++++++++------
 2 files changed, 87 insertions(+), 15 deletions(-)
hw/remote/trace-events +2 -0
index 0d1b7d56a5..358a68fb34 100644
@@ -9,6 +9,8 @@ vfu_cfg_read(uint32_t offset, uint32_t val) "vfu: cfg: 0x%x -> 0x%x"
 vfu_cfg_write(uint32_t offset, uint32_t val) "vfu: cfg: 0x%x <- 0x%x"
 vfu_dma_register(uint64_t gpa, size_t len) "vfu: registering GPA 0x%"PRIx64", %zu bytes"
 vfu_dma_unregister(uint64_t gpa) "vfu: unregistering GPA 0x%"PRIx64""
+vfu_dma_read(uint64_t gpa, size_t len) "vfu: DMA read 0x%"PRIx64", %zu bytes"
+vfu_dma_write(uint64_t gpa, size_t len) "vfu: DMA write 0x%"PRIx64", %zu bytes"
 vfu_bar_register(int i, uint64_t addr, uint64_t size) "vfu: BAR %d: addr 0x%"PRIx64" size 0x%"PRIx64""
 vfu_bar_rw_enter(const char *op, uint64_t addr) "vfu: %s request for BAR address 0x%"PRIx64""
 vfu_bar_rw_exit(const char *op, uint64_t addr) "vfu: Finished %s of BAR address 0x%"PRIx64""
hw/remote/vfio-user-obj.c +85 -15

128 lines not on this page · raw message

Signature · 1 line
2.43.2
#11 lore raw

PATCH v9 5/5 vfio-user: Fix config space access byte order

In reply to Mattias Nissler

PCI config space is little-endian, so on a big-endian host we need to perform byte swaps for values as they are passed to and received from the generic PCI config space access machinery.

---
 hw/remote/vfio-user-obj.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
hw/remote/vfio-user-obj.c +2 -2
index a15e291c9a..0e93d7a7b4 100644
@@ -281,7 +281,7 @@ static ssize_t vfu_object_cfg_access(vfu_ctx_t *vfu_ctx, char * const buf,
     while (bytes > 0) {
         len = (bytes > pci_access_width) ? pci_access_width : bytes;
         if (is_write) {
-            memcpy(&val, ptr, len);
+            val = ldn_le_p(ptr, len);
             pci_host_config_write_common(o->pci_dev, offset,
                                          pci_config_size(o->pci_dev),
                                          val, len);
@@ -289,7 +289,7 @@ static ssize_t vfu_object_cfg_access(vfu_ctx_t *vfu_ctx, char * const buf,
         } else {
             val = pci_host_config_read_common(o->pci_dev, offset,
                                               pci_config_size(o->pci_dev), len);
-            memcpy(ptr, &val, len);
+            stn_le_p(ptr, len, val);
             trace_vfu_cfg_read(offset, val);
         }
         offset += len;
Signature · 1 line
2.43.2