Skip to contentSkip to conversation

vhost-user: Add SHMEM_MAP/UNMAP requests

PATCH In review Albert Esteve 3 participants 12 messages Mar 4 – Apr 14

lore
Share & tools
lore
#0 lore raw

v14 cover vhost-user: Add SHMEM_MAP/UNMAP requests

Hi all,

v13->v14
- Switched F_SHMEM id to 21 to avoid collision after rebasing
- Fixed all occurrences of shmem->mr.size to memory_region_size()
- Other small fixes following reviews from previous version v12->v13
- SMEM_UNMAP spec update to explicitly state the use of VHOST_USER_PROTOCOL_F_REPLY_ACK for replies
- Removed confusing remark for 0-sized regions in GET_SHMEM_CONFIG
v11->v12
- Refined VIRTIO Shared Memory Region configuration mem size spec description
- Removed unused name in vhost-user-base's vub_device_realize to avoid build error
- Initialize shmem in vhost_user_backend_handle_shmem_unmap to avoid compiler being confused
- Added stub for memory_region_init_ram_from_fd in memory.h for windows builds
- Use memory_region_size for shmem_region handlers instead of accessing size member directly in shmem mrs
v10->v11
- Rebase to grab commit fde5930cc37175cfcd0f03a089e26f4458a52311 and explicitly unset reply_ack on the SHMEM_MAP/UNMAP msg.
- Mention mapping cleanup on device reset in the spec.

This patch series implements dynamic fd-backed memory mapping support for vhost-user backends, enabling backends to dynamically request memory mappings and unmappings during runtime through the new VHOST_USER_BACKEND_SHMEM_MAP/UNMAP protocol messages.

This feature benefits various VIRTIO devices that require dynamic shared memory management, including virtiofs (for DAX mappings), virtio-gpu (for resource sharing), and the recently standardized virtio-media.

The implementation introduces a QOM-based architecture for managing shared memory lifecycle:

- VirtioSharedMemoryMapping: an intermediate object that manages individual memory mappings by acting as generic container for regions declared in any vhost-user device type
- Dynamic Mapping: backends can request mappings via SHMEM_MAP messages, with the frontend creating MemoryRegions from the provided file descriptors and adding them as subregions

When a SHMEM_MAP request is received, the frontend:
1. Creates VirtioSharedMemoryMapping to manage the mapping lifecycle
2. Maps the provided fd with memory_region_init_ram_from_fd()
3. Creates a MemoryRegion backed by the mapped memory
4. Adds it as a subregion of the appropiate VIRTIO Shared Memory Region

The QOM reference counting ensures automatic cleanup when mappings are removed or the device is destroyed.

This patch also includes:
- VHOST_USER_GET_SHMEM_CONFIG: a new frontend request allowing generic vhost-user devices to query shared memory configuration from backends at device initialization, enabling the generic vhost-user-device frontend to work with any backend regardless of specific shared memory requirements.

The implementation has been tested with rust-vmm based backends.

Albert Esteve (7):
vhost-user: Add VirtIO Shared Memory map request vhost_user.rst: Align VhostUserMsg excerpt members vhost_user.rst: Add SHMEM_MAP/_UNMAP to spec
vhost_user: Add frontend get_shmem_config command vhost_user.rst: Add GET_SHMEM_CONFIG message
qmp: add shmem feature map
vhost-user-device: Add shared memory BAR

 docs/interop/vhost-user.rst               | 104 ++++++++
 hw/virtio/vhost-user-base.c               |  46 +++-
 hw/virtio/vhost-user-test-device-pci.c    |  42 +++-
 hw/virtio/vhost-user.c                    | 274 ++++++++++++++++++++++
 hw/virtio/virtio-qmp.c                    |   3 +
 hw/virtio/virtio.c                        | 201 ++++++++++++++++
 include/hw/virtio/vhost-backend.h         |  10 +
 include/hw/virtio/vhost-user.h            |   1 +
 include/hw/virtio/virtio.h                | 136 +++++++++++
 include/system/memory.h                   |   2 +-
 subprojects/libvhost-user/libvhost-user.c |  70 ++++++
 subprojects/libvhost-user/libvhost-user.h |  54 +++++
 system/memory.c                           |  14 ++
 13 files changed, 951 insertions(+), 6 deletions(-)
Signature · 1 line
2.52.0
#1 lore raw

PATCH v14 1/7 vhost-user: Add VirtIO Shared Memory map request

Add SHMEM_MAP/UNMAP requests to vhost-user for dynamic management of VIRTIO Shared Memory mappings.

This implementation introduces VirtioSharedMemoryMapping as a unified QOM object that manages both the mapping metadata and MemoryRegion lifecycle. This object provides reference-counted lifecycle management with automatic cleanup of file descriptors and memory regions through QOM finalization.

This request allows backends to dynamically map file descriptors into a VIRTIO Shared Memory Region identified by their shmid. Maps are created using memory_region_init_ram_from_fd() with configurable read/write permissions, and the resulting MemoryRegions are added as subregions to the shmem container region. The mapped memory is then advertised to the guest VIRTIO drivers as a base address plus offset for reading and writting according to the requested mmap flags.

The backend can unmap memory ranges within a given VIRTIO Shared Memory Region to free resources. Upon receiving this message, the frontend removes the MemoryRegion as a subregion and automatically unreferences the VirtioSharedMemoryMapping object, triggering cleanup if no other references exist.

Error handling has been improved to ensure consistent behavior across handlers that manage their own vhost_user_send_resp() calls. Since these handlers clear the VHOST_USER_NEED_REPLY_MASK flag, explicit error checking ensures proper connection closure on failures, maintaining the expected error flow.

Note the memory region commit for these operations needs to be delayed until after we reply to the backend to avoid deadlocks. Otherwise, the MemoryListener would send a VHOST_USER_SET_MEM_TABLE message before the reply.

---
 hw/virtio/vhost-user.c                    | 274 ++++++++++++++++++++++
 hw/virtio/virtio.c                        | 201 ++++++++++++++++
 include/hw/virtio/virtio.h                | 134 +++++++++++
 include/system/memory.h                   |   2 +-
 subprojects/libvhost-user/libvhost-user.c |  70 ++++++
 subprojects/libvhost-user/libvhost-user.h |  54 +++++
 system/memory.c                           |  14 ++
 7 files changed, 748 insertions(+), 1 deletion(-)
hw/virtio/vhost-user.c +274 -0
index bb8f8eab77..ff0d1d0ad9 100644
@@ -104,6 +104,7 @@ typedef enum VhostUserRequest {
     VHOST_USER_GET_SHARED_OBJECT = 41,
     VHOST_USER_SET_DEVICE_STATE_FD = 42,
     VHOST_USER_CHECK_DEVICE_STATE = 43,
+    VHOST_USER_GET_SHMEM_CONFIG = 44,
     VHOST_USER_MAX
 } VhostUserRequest;
 
@@ -115,6 +116,8 @@ typedef enum VhostUserBackendRequest {
     VHOST_USER_BACKEND_SHARED_OBJECT_ADD = 6,
     VHOST_USER_BACKEND_SHARED_OBJECT_REMOVE = 7,
     VHOST_USER_BACKEND_SHARED_OBJECT_LOOKUP = 8,
+    VHOST_USER_BACKEND_SHMEM_MAP = 9,
+    VHOST_USER_BACKEND_SHMEM_UNMAP = 10,
     VHOST_USER_BACKEND_MAX
 }  VhostUserBackendRequest;
 
@@ -136,6 +139,12 @@ typedef struct VhostUserMemRegMsg {
     VhostUserMemoryRegion region;
 } VhostUserMemRegMsg;
 
+typedef struct VhostUserShMemConfig {
+    uint32_t nregions;
+    uint32_t padding;
+    uint64_t memory_sizes[VIRTIO_MAX_SHMEM_REGIONS];
+} VhostUserShMemConfig;
+
 typedef struct VhostUserLog {
     uint64_t mmap_size;
     uint64_t mmap_offset;
@@ -192,6 +201,23 @@ typedef struct VhostUserShared {
     unsigned char uuid[16];
 } VhostUserShared;
 
+/* For the flags field of VhostUserMMap */
+#define VHOST_USER_FLAG_MAP_RW (1u << 0)
+
+typedef struct {
+    /* VIRTIO Shared Memory Region ID */
+    uint8_t shmid;
+    uint8_t padding[7];
+    /* File offset */
+    uint64_t fd_offset;
+    /* Offset within the VIRTIO Shared Memory Region */
+    uint64_t shm_offset;
+    /* Size of the mapping */
+    uint64_t len;
+    /* Flags for the mmap operation, from VHOST_USER_FLAG_MAP_* */
+    uint64_t flags;
+} VhostUserMMap;
+
 typedef struct {
     VhostUserRequest request;
 
@@ -224,6 +250,8 @@ typedef union {
         VhostUserInflight inflight;
         VhostUserShared object;
         VhostUserTransferDeviceState transfer_state;
+        VhostUserMMap mmap;
+        VhostUserShMemConfig shmem;
 } VhostUserPayload;
 
 typedef struct VhostUserMsg {
@@ -1771,6 +1799,196 @@ vhost_user_backend_handle_shared_object_lookup(struct vhost_user *u,
     return 0;
 }
 
+/**
+ * vhost_user_backend_handle_shmem_map() - Handle SHMEM_MAP backend request
+ * @dev: vhost device
+ * @ioc: QIOChannel for communication
+ * @hdr: vhost-user message header
+ * @payload: message payload containing mapping details
+ * @fd: file descriptor for the shared memory region
+ *
+ * Handles VHOST_USER_BACKEND_SHMEM_MAP requests from the backend. Creates
+ * a VhostUserShmemObject to manage the shared memory mapping and adds it
+ * to the appropriate VirtIO shared memory region. The VhostUserShmemObject
+ * serves as an intermediate parent for the MemoryRegion, ensuring proper
+ * lifecycle management with reference counting.
+ *
+ * Returns: 0 on success, negative errno on failure
+ */
+static int
+vhost_user_backend_handle_shmem_map(struct vhost_dev *dev,
+                                    QIOChannel *ioc,
+                                    VhostUserHeader *hdr,
+                                    VhostUserPayload *payload,
+                                    int fd)
+{
+    VirtioSharedMemory *shmem;
+    VhostUserMMap *vu_mmap = &payload->mmap;
+    VirtioSharedMemoryMapping *existing;
+    Error *local_err = NULL;
+    int ret = 0;
+
+    if (fd < 0) {
+        error_report("Bad fd for map");
+        ret = -EBADF;
+        goto send_reply;
+    }
+
+    if (QSIMPLEQ_EMPTY(&dev->vdev->shmem_list)) {
+        error_report("Device has no VIRTIO Shared Memory Regions. "
+                     "Requested ID: %d", vu_mmap->shmid);
+        ret = -EFAULT;
+        goto send_reply;
+    }
+
+    shmem = virtio_find_shmem_region(dev->vdev, vu_mmap->shmid);
+    if (!shmem) {
+        error_report("VIRTIO Shared Memory Region at "
+                     "ID %d not found or uninitialized", vu_mmap->shmid);
+        ret = -EFAULT;
+        goto send_reply;
+    }
+
+    if ((vu_mmap->shm_offset + vu_mmap->len) < vu_mmap->len ||
+        (vu_mmap->shm_offset + vu_mmap->len) > memory_region_size(&shmem->mr)) {
+        error_report("Bad offset/len for mmap %" PRIx64 "+%" PRIx64,
+                     vu_mmap->shm_offset, vu_mmap->len);
+        ret = -EFAULT;
+        goto send_reply;
+    }
+
+    QTAILQ_FOREACH(existing, &shmem->mmaps, link) {
+        if (ranges_overlap(existing->offset, existing->len,
+                           vu_mmap->shm_offset, vu_mmap->len)) {
+            error_report("VIRTIO Shared Memory mapping overlap");
+            ret = -EFAULT;
+            goto send_reply;
+        }
+    }
+
+    memory_region_transaction_begin();
+
+    /* Create VirtioSharedMemoryMapping object */
+    VirtioSharedMemoryMapping *mapping = virtio_shared_memory_mapping_new(
+        vu_mmap->shmid, fd, vu_mmap->fd_offset, vu_mmap->shm_offset,
+        vu_mmap->len, vu_mmap->flags & VHOST_USER_FLAG_MAP_RW);
+
+    if (!mapping) {
+        ret = -EFAULT;
+        goto send_reply_commit;
+    }
+
+    /* Add the mapping to the shared memory region */
+    if (virtio_add_shmem_map(shmem, mapping) != 0) {
+        error_report("Failed to add shared memory mapping");
+        object_unref(OBJECT(mapping));
+        ret = -EFAULT;
+        goto send_reply_commit;
+    }
+
+send_reply_commit:
+    /* Send reply and commit after transaction started */
+    if (hdr->flags & VHOST_USER_NEED_REPLY_MASK) {
+        payload->u64 = !!ret;
+        hdr->size = sizeof(payload->u64);
+        if (!vhost_user_send_resp(ioc, hdr, payload, &local_err)) {
+            error_report_err(local_err);
+            memory_region_transaction_commit();
+            return -EFAULT;
+        }
+    }
+    memory_region_transaction_commit();
+    return 0;
+
+send_reply:
+    if (hdr->flags & VHOST_USER_NEED_REPLY_MASK) {
+        payload->u64 = !!ret;
+        hdr->size = sizeof(payload->u64);
+        if (!vhost_user_send_resp(ioc, hdr, payload, &local_err)) {
+            error_report_err(local_err);
+            return -EFAULT;
+        }
+    }
+    return 0;
+}
+
+/**
+ * vhost_user_backend_handle_shmem_unmap() - Handle SHMEM_UNMAP backend request
+ * @dev: vhost device
+ * @ioc: QIOChannel for communication
+ * @hdr: vhost-user message header
+ * @payload: message payload containing unmapping details
+ *
+ * Handles VHOST_USER_BACKEND_SHMEM_UNMAP requests from the backend. Removes
+ * the specified memory mapping from the VirtIO shared memory region. This
+ * automatically unreferences the associated VhostUserShmemObject, which may
+ * trigger its finalization and cleanup (munmap, close fd) if no other
+ * references exist.
+ *
+ * Returns: 0 on success, negative errno on failure
+ */
+static int
+vhost_user_backend_handle_shmem_unmap(struct vhost_dev *dev,
+                                      QIOChannel *ioc,
+                                      VhostUserHeader *hdr,
+                                      VhostUserPayload *payload)
+{
+    VirtioSharedMemory *shmem = NULL;
+    VirtioSharedMemoryMapping *mmap = NULL;
+    VhostUserMMap *vu_mmap = &payload->mmap;
+    Error *local_err = NULL;
+    int ret = 0;
+
+    if (QSIMPLEQ_EMPTY(&dev->vdev->shmem_list)) {
+        error_report("Device has no VIRTIO Shared Memory Regions. "
+                     "Requested ID: %d", vu_mmap->shmid);
+        ret = -EFAULT;
+        goto send_reply;
+    }
+
+    shmem = virtio_find_shmem_region(dev->vdev, vu_mmap->shmid);
+    if (!shmem) {
+        error_report("VIRTIO Shared Memory Region at "
+                     "ID %d not found or uninitialized", vu_mmap->shmid);
+        ret = -EFAULT;
+        goto send_reply;
+    }
+
+    if ((vu_mmap->shm_offset + vu_mmap->len) < vu_mmap->len ||
+        (vu_mmap->shm_offset + vu_mmap->len) > memory_region_size(&shmem->mr)) {
+        error_report("Bad offset/len for unmmap %" PRIx64 "+%" PRIx64,
+                     vu_mmap->shm_offset, vu_mmap->len);
+        ret = -EFAULT;
+        goto send_reply;
+    }
+
+    mmap = virtio_find_shmem_map(shmem, vu_mmap->shm_offset, vu_mmap->len);
+    if (!mmap) {
+        error_report("Shared memory mapping not found at offset %" PRIx64
+                     " with length %" PRIx64,
+                     vu_mmap->shm_offset, vu_mmap->len);
+        ret = -EFAULT;
+        goto send_reply;
+    }
+
+send_reply:
+    if (hdr->flags & VHOST_USER_NEED_REPLY_MASK) {
+        payload->u64 = !!ret;
+        hdr->size = sizeof(payload->u64);
+        if (!vhost_user_send_resp(ioc, hdr, payload, &local_err)) {
+            error_report_err(local_err);
+            return -EFAULT;
+        }
+    }
+
+    if (!ret && shmem && mmap) {
+        /* Free the MemoryRegion only after reply */
+        virtio_del_shmem_map(shmem, vu_mmap->shm_offset, vu_mmap->len);
+    }
+
+    return 0;
+}
+
 static void close_backend_channel(struct vhost_user *u)
 {
     g_source_destroy(u->backend_src);
@@ -1844,6 +2062,21 @@ static gboolean backend_read(QIOChannel *ioc, GIOCondition condition,
         ret = vhost_user_backend_handle_shared_object_lookup(dev->opaque,
                                                              &payload.object);
         break;
+    case VHOST_USER_BACKEND_SHMEM_MAP:
+        /* Handler manages its own response, check error and close connection */
+        reply_ack = false;
+        if (vhost_user_backend_handle_shmem_map(dev, ioc, &hdr, &payload,
+                                                fd ? fd[0] : -1) < 0) {
+            goto err;
+        }
+        break;
+    case VHOST_USER_BACKEND_SHMEM_UNMAP:
+        /* Handler manages its own response, check error and close connection */
+        reply_ack = false;
+        if (vhost_user_backend_handle_shmem_unmap(dev, ioc, &hdr, &payload) < 0) {
+            goto err;
+        }
+        break;
     default:
         error_report("Received unexpected msg type: %d.", hdr.request);
         ret = -EINVAL;
@@ -3028,6 +3261,46 @@ static int vhost_user_check_device_state(struct vhost_dev *dev, Error **errp)
     return 0;
 }
 
+static int vhost_user_get_shmem_config(struct vhost_dev *dev,
+                                       int *nregions,
+                                       uint64_t *memory_sizes,
+                                       Error **errp)
+{
+    int ret;
+    VhostUserMsg msg = {
+        .hdr.request = VHOST_USER_GET_SHMEM_CONFIG,
+        .hdr.flags = VHOST_USER_VERSION,
+    };
+
+    if (!virtio_has_feature(dev->protocol_features,
+                            VHOST_USER_PROTOCOL_F_SHMEM)) {
+        *nregions = 0;
+        return 0;
+    }
+
+    ret = vhost_user_write(dev, &msg, NULL, 0);
+    if (ret < 0) {
+        return ret;
+    }
+
+    ret = vhost_user_read(dev, &msg);
+    if (ret < 0) {
+        return ret;
+    }
+
+    if (msg.payload.shmem.nregions > VIRTIO_MAX_SHMEM_REGIONS) {
+        error_setg(errp, "Received too many shared memory regions: %d",
+                   msg.payload.shmem.nregions);
+        return -EINVAL;
+    }
+
+    *nregions = msg.payload.shmem.nregions;
+    memcpy(memory_sizes,
+           &msg.payload.shmem.memory_sizes,
+           sizeof(uint64_t) * VIRTIO_MAX_SHMEM_REGIONS);
+    return 0;
+}
+
 const VhostOps user_ops = {
         .backend_type = VHOST_BACKEND_TYPE_USER,
         .vhost_backend_init = vhost_user_backend_init,
@@ -3066,4 +3339,5 @@ const VhostOps user_ops = {
         .vhost_supports_device_state = vhost_user_supports_device_state,
         .vhost_set_device_state_fd = vhost_user_set_device_state_fd,
         .vhost_check_device_state = vhost_user_check_device_state,
+        .vhost_get_shmem_config = vhost_user_get_shmem_config,
 };
hw/virtio/virtio.c +201 -0

245 lines not on this page · raw message

include/hw/virtio/virtio.h +134 -0

152 lines not on this page · raw message

include/system/memory.h +1 -1
index 0562af3136..4526c5ac99 100644
@@ -1489,6 +1489,7 @@ bool memory_region_init_ram_from_file(MemoryRegion *mr,
                                       const char *path,
                                       ram_addr_t offset,
                                       Error **errp);
+#endif
 
 /**
  * memory_region_init_ram_from_fd:  Initialize RAM memory region with a
@@ -1518,7 +1519,6 @@ bool memory_region_init_ram_from_fd(MemoryRegion *mr,
                                     int fd,
                                     ram_addr_t offset,
                                     Error **errp);
-#endif
 
 /**
  * memory_region_init_ram_ptr:  Initialize RAM memory region from a
subprojects/libvhost-user/libvhost-user.c +70 -0

76 lines not on this page · raw message

subprojects/libvhost-user/libvhost-user.h +54 -0

84 lines not on this page · raw message

system/memory.c +14 -0
index c51d0798a8..5fe18d6757 100644
@@ -1691,6 +1691,20 @@ bool memory_region_init_ram_from_fd(MemoryRegion *mr,
     }
     return true;
 }
+#else
+bool memory_region_init_ram_from_fd(MemoryRegion *mr,
+                                    Object *owner,
+                                    const char *name,
+                                    uint64_t size,
+                                    uint32_t ram_flags,
+                                    int fd,
+                                    ram_addr_t offset,
+                                    Error **errp)
+{
+    error_setg(errp,
+               "memory_region_init_ram_from_fd is not supported on this platform");
+    return false;
+}
 #endif
 
 void memory_region_init_ram_ptr(MemoryRegion *mr,
Signature · 1 line
2.52.0
#2 lore raw

PATCH v14 2/7 vhost_user.rst: Align VhostUserMsg excerpt members

In reply to Albert Esteve

Add missing members to the VhostUserMsg excerpt in the vhost-user spec documentation.

---
 docs/interop/vhost-user.rst | 4 ++++
 1 file changed, 4 insertions(+)
docs/interop/vhost-user.rst +4 -0
index 137c9f3669..4c1538cf88 100644
@@ -366,11 +366,15 @@ In QEMU the vhost-user message is implemented with the following struct:
           struct vhost_vring_state state;
           struct vhost_vring_addr addr;
           VhostUserMemory memory;
+          VhostUserMemRegMsg mem_reg;
           VhostUserLog log;
           struct vhost_iotlb_msg iotlb;
           VhostUserConfig config;
+          VhostUserCryptoSession session;
           VhostUserVringArea area;
           VhostUserInflight inflight;
+          VhostUserShared object;
+          VhostUserTransferDeviceState transfer_state;
       };
   } QEMU_PACKED VhostUserMsg;
 
Signature · 1 line
2.52.0
#3 lore raw

PATCH v14 3/7 vhost_user.rst: Add SHMEM_MAP/_UNMAP to spec

In reply to Albert Esteve

Add SHMEM_MAP/_UNMAP request to the vhost-user
spec documentation.

---
 docs/interop/vhost-user.rst | 61 +++++++++++++++++++++++++++++++++++++
 1 file changed, 61 insertions(+)
docs/interop/vhost-user.rst +61 -0
index 4c1538cf88..08a5e43988 100644
@@ -350,6 +350,27 @@ Device state transfer parameters
   In the future, additional phases might be added e.g. to allow
   iterative migration while the device is running.
 
+MMAP request
+^^^^^^^^^^^^
+
++-------+---------+-----------+------------+-----+-------+
+| shmid | padding | fd_offset | shm_offset | len | flags |
++-------+---------+-----------+------------+-----+-------+
+
+:shmid: a 8-bit shared memory region identifier
+
+:fd_offset: a 64-bit offset of this area from the start
+            of the supplied file descriptor
+
+:shm_offset: a 64-bit offset from the start of the
+             pointed shared memory region
+
+:len: a 64-bit size of the memory to map
+
+:flags: a 64-bit value:
+  - 0: Pages are mapped read-only
+  - 1: Pages are mapped read-write
+
 C structure
 -----------
 
@@ -375,6 +396,7 @@ In QEMU the vhost-user message is implemented with the following struct:
           VhostUserInflight inflight;
           VhostUserShared object;
           VhostUserTransferDeviceState transfer_state;
+          VhostUserMMap mmap;
       };
   } QEMU_PACKED VhostUserMsg;
 
@@ -1067,6 +1089,7 @@ Protocol features
   #define VHOST_USER_PROTOCOL_F_SHARED_OBJECT           18
   #define VHOST_USER_PROTOCOL_F_DEVICE_STATE            19
   #define VHOST_USER_PROTOCOL_F_GET_VRING_BASE_INFLIGHT 20
+  #define VHOST_USER_PROTOCOL_F_SHMEM_MAP               21
 
 Front-end message types
 -----------------------
@@ -1888,6 +1911,44 @@ is sent by the front-end.
   when the operation is successful, or non-zero otherwise. Note that if the
   operation fails, no fd is sent to the backend.
 
+``VHOST_USER_BACKEND_SHMEM_MAP``
+  :id: 9
+  :equivalent ioctl: N/A
+  :request payload: fd and ``struct VhostUserMMap``
+  :reply payload: N/A
+
+  When the ``VHOST_USER_PROTOCOL_F_SHMEM`` protocol feature has been
+  successfully negotiated, this message can be submitted by the backends to
+  advertise a new mapping to be made in a given VIRTIO Shared Memory Region.
+  Upon receiving the message, the front-end will mmap the given fd into the
+  VIRTIO Shared Memory Region with the requested ``shmid``.
+  If ``VHOST_USER_PROTOCOL_F_REPLY_ACK`` is negotiated, and
+  back-end set the ``VHOST_USER_NEED_REPLY`` flag, the front-end
+  must respond with zero when operation is successfully completed,
+  or non-zero otherwise.
+
+  Mapping over an already existing map is not allowed and requests shall fail.
+  Therefore, the memory range in the request must correspond with a valid,
+  free region of the VIRTIO Shared Memory Region. Also, note that mappings
+  consume resources and that the request can fail when there are no resources
+  available. Lastly, mappings are automatically unmapped by the front-end
+  across device reset operation.
+
+``VHOST_USER_BACKEND_SHMEM_UNMAP``
+  :id: 10
+  :equivalent ioctl: N/A
+  :request payload: ``struct VhostUserMMap``
+  :reply payload: N/A
+
+  When the ``VHOST_USER_PROTOCOL_F_SHMEM`` protocol feature has been
+  successfully negotiated, this message can be submitted by the backends so
+  that the front-end un-mmaps a given range (``shm_offset``, ``len``) in the
+  VIRTIO Shared Memory Region with the requested ``shmid``. Note that the
+  given range shall correspond to the entirety of a valid mapped region.
+  If ``VHOST_USER_PROTOCOL_F_REPLY_ACK`` is negotiated, and the back-end
+  sets the ``VHOST_USER_NEED_REPLY`` flag, the front-end must respond with
+  zero when operation is successfully completed, or non-zero otherwise.
+
 .. _reply_ack:
 
 VHOST_USER_PROTOCOL_F_REPLY_ACK
Signature · 1 line
2.52.0
#4 lore raw

PATCH v14 4/7 vhost_user: Add frontend get_shmem_config command

In reply to Albert Esteve

The frontend can use this command to retrieve VirtIO Shared Memory Regions configuration from the backend. The response contains the number of shared memory regions, their size, and shmid.

This is useful when the frontend is unaware of specific backend type and configuration,
for example, in the vhost-user-device case.

---
 include/hw/virtio/vhost-backend.h | 10 ++++++++++
 include/hw/virtio/vhost-user.h    |  1 +
 include/hw/virtio/virtio.h        |  2 ++
 3 files changed, 13 insertions(+)
include/hw/virtio/vhost-backend.h +10 -0
index ff94fa1734..ce58b4d2d6 100644
@@ -163,6 +163,15 @@ typedef int (*vhost_set_device_state_fd_op)(struct vhost_dev *dev,
                                             int *reply_fd,
                                             Error **errp);
 typedef int (*vhost_check_device_state_op)(struct vhost_dev *dev, Error **errp);
+/*
+ * Max regions is VIRTIO_MAX_SHMEM_REGIONS, so that is the maximum
+ * number of memory_sizes that will be accepted.
+ */
+typedef int (*vhost_get_shmem_config_op)(struct vhost_dev *dev,
+                                         int *nregions,
+                                         uint64_t *memory_sizes,
+                                         Error **errp);
+
 
 typedef struct VhostOps {
     VhostBackendType backend_type;
@@ -220,6 +229,7 @@ typedef struct VhostOps {
     vhost_supports_device_state_op vhost_supports_device_state;
     vhost_set_device_state_fd_op vhost_set_device_state_fd;
     vhost_check_device_state_op vhost_check_device_state;
+    vhost_get_shmem_config_op vhost_get_shmem_config;
 } VhostOps;
 
 int vhost_backend_update_device_iotlb(struct vhost_dev *dev,
include/hw/virtio/vhost-user.h +1 -0
index 53fe996686..0d8c7f1006 100644
@@ -33,6 +33,7 @@ enum VhostUserProtocolFeature {
     VHOST_USER_PROTOCOL_F_SHARED_OBJECT = 18,
     VHOST_USER_PROTOCOL_F_DEVICE_STATE = 19,
     VHOST_USER_PROTOCOL_F_GET_VRING_BASE_INFLIGHT = 20,
+    VHOST_USER_PROTOCOL_F_SHMEM = 21,
     VHOST_USER_PROTOCOL_F_MAX
 };
 
include/hw/virtio/virtio.h +2 -0
index 2dcf58639d..3d1b1b5e6d 100644
@@ -82,6 +82,8 @@ typedef struct VirtQueueElement
 
 #define VIRTIO_NO_VECTOR 0xffff
 
+#define VIRTIO_MAX_SHMEM_REGIONS 256
+
 /* special index value used internally for config irqs */
 #define VIRTIO_CONFIG_IRQ_IDX -1
 
Signature · 1 line
2.52.0
#5 lore raw

PATCH v14 5/7 vhost_user.rst: Add GET_SHMEM_CONFIG message

In reply to Albert Esteve

Add GET_SHMEM_CONFIG vhost-user frontend
message to the spec documentation.

---
 docs/interop/vhost-user.rst | 39 +++++++++++++++++++++++++++++++++++++
 1 file changed, 39 insertions(+)
docs/interop/vhost-user.rst +39 -0
index 08a5e43988..4ee663d10b 100644
@@ -371,6 +371,22 @@ MMAP request
   - 0: Pages are mapped read-only
   - 1: Pages are mapped read-write
 
+VIRTIO Shared Memory Region configuration
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
++-------------+---------+------------+----+--------------+
+| num regions | padding | mem size 0 | .. | mem size 255 |
++-------------+---------+------------+----+--------------+
+
+:num regions: a 32-bit number of regions
+
+:padding: 32-bit
+
+:mem size: an array of 256 64-bit fields representing the size of each
+           VIRTIO Shared Memory Region. ``num regions`` specifies the
+           number of valid regions (non-zero size). The array index
+           corresponds to the shared memory ID (shmid).
+
 C structure
 -----------
 
@@ -397,6 +413,7 @@ In QEMU the vhost-user message is implemented with the following struct:
           VhostUserShared object;
           VhostUserTransferDeviceState transfer_state;
           VhostUserMMap mmap;
+          VhostUserShMemConfig shmem;
       };
   } QEMU_PACKED VhostUserMsg;
 
@@ -1777,6 +1794,28 @@ Front-end message types
   Using this function requires prior negotiation of the
   ``VHOST_USER_PROTOCOL_F_DEVICE_STATE`` feature.
 
+``VHOST_USER_GET_SHMEM_CONFIG``
+  :id: 44
+  :equivalent ioctl: N/A
+  :request payload: N/A
+  :reply payload: ``struct VhostUserShMemConfig``
+
+  When the ``VHOST_USER_PROTOCOL_F_SHMEM`` protocol feature has been
+  successfully negotiated, this message can be submitted by the front-end
+  to gather the VIRTIO Shared Memory Region configuration. The back-end will
+  respond with the number of VIRTIO Shared Memory Regions it requires, and
+  each shared memory region size in an array. The shared memory IDs are
+  represented by the array index. The information returned shall comply
+  with the following rules:
+
+  * The shared information will remain valid and unchanged for the entire
+    lifetime of the connection.
+
+  * The Shared Memory Region size must be a multiple of the page size
+    supported by mmap(2).
+
+  * The size may be 0 if the region is unused.
+
 Back-end message types
 ----------------------
 
Signature · 1 line
2.52.0
#6 lore raw

PATCH v14 6/7 qmp: add shmem feature map

In reply to Albert Esteve

Add new vhost-user protocol
VHOST_USER_PROTOCOL_F_SHMEM feature to
feature map.

---
 hw/virtio/virtio-qmp.c | 3 +++
 1 file changed, 3 insertions(+)
hw/virtio/virtio-qmp.c +3 -0
index 968299fda0..e3d0a10a59 100644
@@ -127,6 +127,9 @@ static const qmp_virtio_feature_map_t vhost_user_protocol_map[] = {
     FEATURE_ENTRY(VHOST_USER_PROTOCOL_F_DEVICE_STATE, \
             "VHOST_USER_PROTOCOL_F_DEVICE_STATE: Backend device state transfer "
             "supported"),
+    FEATURE_ENTRY(VHOST_USER_PROTOCOL_F_SHMEM, \
+                "VHOST_USER_PROTOCOL_F_SHMEM: Backend shared memory mapping "
+                "supported"),
     { -1, "" }
 };
 
Signature · 1 line
2.52.0
#7 lore raw

PATCH v14 7/7 vhost-user-device: Add shared memory BAR

In reply to Albert Esteve

Add shared memory BAR support to vhost-user-device-pci to enable direct file mapping for VIRTIO Shared Memory Regions.

The implementation creates a consolidated shared memory BAR that contains all VIRTIO Shared Memory Regions as subregions. Each region is configured with its proper shmid, size, and offset within the BAR. The number and size of regions are retrieved via VHOST_USER_GET_SHMEM_CONFIG message sent by vhost-user-base during realization after virtio_init().

Specifically, it uses BAR 4 to avoid conflicts, as it is currently unused.

The shared memory BAR is only created when the backend supports VHOST_USER_PROTOCOL_F_SHMEM and has configured shared memory regions. This maintains backward compatibility with backends that do not support shared memory functionality.

---
 hw/virtio/vhost-user-base.c            | 46 ++++++++++++++++++++++++--
 hw/virtio/vhost-user-test-device-pci.c | 42 +++++++++++++++++++++--
 2 files changed, 83 insertions(+), 5 deletions(-)
hw/virtio/vhost-user-base.c +43 -3
index 01ab9ca56b..de42ea46e5 100644
@@ -16,6 +16,7 @@
 #include "hw/virtio/virtio-bus.h"
 #include "hw/virtio/vhost-user-base.h"
 #include "qemu/error-report.h"
+#include "migration/blocker.h"
 
 static void vub_start(VirtIODevice *vdev)
 {
@@ -276,7 +277,8 @@ static void vub_device_realize(DeviceState *dev, Error **errp)
 {
     VirtIODevice *vdev = VIRTIO_DEVICE(dev);
     VHostUserBase *vub = VHOST_USER_BASE(dev);
-    int ret;
+    uint64_t memory_sizes[VIRTIO_MAX_SHMEM_REGIONS];
+    int i, ret, nregions, regions_processed = 0;
 
     if (!vub->chardev.chr) {
         error_setg(errp, "vhost-user-base: missing chardev");
@@ -319,7 +321,7 @@ static void vub_device_realize(DeviceState *dev, Error **errp)
 
     /* Allocate queues */
     vub->vqs = g_ptr_array_sized_new(vub->num_vqs);
-    for (int i = 0; i < vub->num_vqs; i++) {
+    for (i = 0; i < vub->num_vqs; i++) {
         g_ptr_array_add(vub->vqs,
                         virtio_add_queue(vdev, vub->vq_size,
                                          vub_handle_output));
@@ -333,11 +335,49 @@ static void vub_device_realize(DeviceState *dev, Error **errp)
                          VHOST_BACKEND_TYPE_USER, 0, errp);
 
     if (ret < 0) {
-        do_vhost_user_cleanup(vdev, vub);
+        goto err;
+    }
+
+    ret = vub->vhost_dev.vhost_ops->vhost_get_shmem_config(&vub->vhost_dev,
+                                                           &nregions,
+                                                           memory_sizes,
+                                                           errp);
+
+    if (ret < 0) {
+        goto err;
+    }
+
+    for (i = 0; i < VIRTIO_MAX_SHMEM_REGIONS && regions_processed < nregions; i++) {
+        if (memory_sizes[i]) {
+            regions_processed++;
+            if (vub->vhost_dev.migration_blocker == NULL) {
+                error_setg(&vub->vhost_dev.migration_blocker,
+                       "Migration disabled: devices with VIRTIO Shared Memory "
+                       "Regions do not support migration yet.");
+                ret = migrate_add_blocker_normal(
+                    &vub->vhost_dev.migration_blocker,
+                    errp);
+
+                if (ret < 0) {
+                    goto err;
+                }
+            }
+
+            if (memory_sizes[i] % qemu_real_host_page_size() != 0) {
+                error_setg(errp, "Shared memory %d size must be a multiple of "
+                                 "the host page size", i);
+                goto err;
+            }
+
+            virtio_new_shmem_region(vdev, i, memory_sizes[i]);
+        }
     }
 
     qemu_chr_fe_set_handlers(&vub->chardev, NULL, NULL, vub_event, NULL,
                              dev, NULL, true);
+    return;
+err:
+    do_vhost_user_cleanup(vdev, vub);
 }
 
 static void vub_device_unrealize(DeviceState *dev)
hw/virtio/vhost-user-test-device-pci.c +40 -2

60 lines not on this page · raw message

Signature · 1 line
2.52.0
#8 lore raw
In reply to Albert Esteve
Quoted 1 line · Albert Esteve

Hi all,

Thanks!

This is now fully reviewed, Michael can we queue it?

Thanks,
Stefano

Quoted 90 lines

v13->v14
- Switched F_SHMEM id to 21 to avoid collision after rebasing
- Fixed all occurrences of shmem->mr.size to memory_region_size()
- Other small fixes following reviews from previous version v12->v13
- SMEM_UNMAP spec update to explicitly state the use of VHOST_USER_PROTOCOL_F_REPLY_ACK for replies
- Removed confusing remark for 0-sized regions in GET_SHMEM_CONFIG
v11->v12
- Refined VIRTIO Shared Memory Region configuration mem size spec description
- Removed unused name in vhost-user-base's vub_device_realize to avoid build error
- Initialize shmem in vhost_user_backend_handle_shmem_unmap to avoid compiler being confused
- Added stub for memory_region_init_ram_from_fd in memory.h for windows builds
- Use memory_region_size for shmem_region handlers instead of accessing size member directly in shmem mrs
v10->v11
- Rebase to grab commit fde5930cc37175cfcd0f03a089e26f4458a52311 and explicitly unset reply_ack on the SHMEM_MAP/UNMAP msg.
- Mention mapping cleanup on device reset in the spec.

This patch series implements dynamic fd-backed memory mapping support for vhost-user backends, enabling backends to dynamically request memory mappings and unmappings during runtime through the new VHOST_USER_BACKEND_SHMEM_MAP/UNMAP protocol messages.

This feature benefits various VIRTIO devices that require dynamic shared memory management, including virtiofs (for DAX mappings), virtio-gpu (for resource sharing), and the recently standardized virtio-media.

The implementation introduces a QOM-based architecture for managing shared memory lifecycle:

- VirtioSharedMemoryMapping: an intermediate object that manages individual memory mappings by acting as generic container for regions declared in any vhost-user device type
- Dynamic Mapping: backends can request mappings via SHMEM_MAP messages, with the frontend creating MemoryRegions from the provided file descriptors and adding them as subregions

When a SHMEM_MAP request is received, the frontend:
1. Creates VirtioSharedMemoryMapping to manage the mapping lifecycle
2. Maps the provided fd with memory_region_init_ram_from_fd()
3. Creates a MemoryRegion backed by the mapped memory
4. Adds it as a subregion of the appropiate VIRTIO Shared Memory Region

The QOM reference counting ensures automatic cleanup when mappings are removed or the device is destroyed.

This patch also includes:
- VHOST_USER_GET_SHMEM_CONFIG: a new frontend request allowing generic vhost-user devices to query shared memory configuration from backends at device initialization, enabling the generic vhost-user-device frontend to work with any backend regardless of specific shared memory requirements.

The implementation has been tested with rust-vmm based backends.

Albert Esteve (7):
vhost-user: Add VirtIO Shared Memory map request vhost_user.rst: Align VhostUserMsg excerpt members vhost_user.rst: Add SHMEM_MAP/_UNMAP to spec
vhost_user: Add frontend get_shmem_config command vhost_user.rst: Add GET_SHMEM_CONFIG message
qmp: add shmem feature map
vhost-user-device: Add shared memory BAR

docs/interop/vhost-user.rst               | 104 ++++++++
hw/virtio/vhost-user-base.c               |  46 +++-
hw/virtio/vhost-user-test-device-pci.c    |  42 +++-
hw/virtio/vhost-user.c                    | 274 ++++++++++++++++++++++
hw/virtio/virtio-qmp.c                    |   3 +
hw/virtio/virtio.c                        | 201 ++++++++++++++++
include/hw/virtio/vhost-backend.h         |  10 +
include/hw/virtio/vhost-user.h            |   1 +
include/hw/virtio/virtio.h                | 136 +++++++++++
include/system/memory.h                   |   2 +-
subprojects/libvhost-user/libvhost-user.c |  70 ++++++
subprojects/libvhost-user/libvhost-user.h |  54 +++++
system/memory.c                           |  14 ++
13 files changed, 951 insertions(+), 6 deletions(-)
Signature · 1 line
2.52.0
#9 lore raw
Quoted 9 lines · Stefano Garzarella
Quoted 1 line · Albert Esteve

Hi all,

Thanks!

This is now fully reviewed, Michael can we queue it?

Thanks,
Stefano

yes, I tagged it already.

Quoted 90 lines
Quoted 90 lines

v13->v14
- Switched F_SHMEM id to 21 to avoid collision after rebasing
- Fixed all occurrences of shmem->mr.size to memory_region_size()
- Other small fixes following reviews from previous version v12->v13
- SMEM_UNMAP spec update to explicitly state the use of VHOST_USER_PROTOCOL_F_REPLY_ACK for replies
- Removed confusing remark for 0-sized regions in GET_SHMEM_CONFIG
v11->v12
- Refined VIRTIO Shared Memory Region configuration mem size spec description
- Removed unused name in vhost-user-base's vub_device_realize to avoid build error
- Initialize shmem in vhost_user_backend_handle_shmem_unmap to avoid compiler being confused
- Added stub for memory_region_init_ram_from_fd in memory.h for windows builds
- Use memory_region_size for shmem_region handlers instead of accessing size member directly in shmem mrs
v10->v11
- Rebase to grab commit fde5930cc37175cfcd0f03a089e26f4458a52311 and explicitly unset reply_ack on the SHMEM_MAP/UNMAP msg.
- Mention mapping cleanup on device reset in the spec.

This patch series implements dynamic fd-backed memory mapping support for vhost-user backends, enabling backends to dynamically request memory mappings and unmappings during runtime through the new VHOST_USER_BACKEND_SHMEM_MAP/UNMAP protocol messages.

This feature benefits various VIRTIO devices that require dynamic shared memory management, including virtiofs (for DAX mappings), virtio-gpu (for resource sharing), and the recently standardized virtio-media.

The implementation introduces a QOM-based architecture for managing shared memory lifecycle:

- VirtioSharedMemoryMapping: an intermediate object that manages individual memory mappings by acting as generic container for regions declared in any vhost-user device type
- Dynamic Mapping: backends can request mappings via SHMEM_MAP messages, with the frontend creating MemoryRegions from the provided file descriptors and adding them as subregions

When a SHMEM_MAP request is received, the frontend:
1. Creates VirtioSharedMemoryMapping to manage the mapping lifecycle
2. Maps the provided fd with memory_region_init_ram_from_fd()
3. Creates a MemoryRegion backed by the mapped memory
4. Adds it as a subregion of the appropiate VIRTIO Shared Memory Region

The QOM reference counting ensures automatic cleanup when mappings are removed or the device is destroyed.

This patch also includes:
- VHOST_USER_GET_SHMEM_CONFIG: a new frontend request allowing generic vhost-user devices to query shared memory configuration from backends at device initialization, enabling the generic vhost-user-device frontend to work with any backend regardless of specific shared memory requirements.

The implementation has been tested with rust-vmm based backends.

Albert Esteve (7):
vhost-user: Add VirtIO Shared Memory map request vhost_user.rst: Align VhostUserMsg excerpt members vhost_user.rst: Add SHMEM_MAP/_UNMAP to spec
vhost_user: Add frontend get_shmem_config command vhost_user.rst: Add GET_SHMEM_CONFIG message
qmp: add shmem feature map
vhost-user-device: Add shared memory BAR

docs/interop/vhost-user.rst               | 104 ++++++++
hw/virtio/vhost-user-base.c               |  46 +++-
hw/virtio/vhost-user-test-device-pci.c    |  42 +++-
hw/virtio/vhost-user.c                    | 274 ++++++++++++++++++++++
hw/virtio/virtio-qmp.c                    |   3 +
hw/virtio/virtio.c                        | 201 ++++++++++++++++
include/hw/virtio/vhost-backend.h         |  10 +
include/hw/virtio/vhost-user.h            |   1 +
include/hw/virtio/virtio.h                | 136 +++++++++++
include/system/memory.h                   |   2 +-
subprojects/libvhost-user/libvhost-user.c |  70 ++++++
subprojects/libvhost-user/libvhost-user.h |  54 +++++
system/memory.c                           |  14 ++
13 files changed, 951 insertions(+), 6 deletions(-)
Signature · 1 line
2.52.0
#10 lore raw
Quoted 7 lines · Michael S. Tsirkin
Quoted 5 lines · Stefano Garzarella
Quoted 1 line · Albert Esteve

Hi all,

Thanks!

Quoted 7 lines
Quoted 4 lines

This is now fully reviewed, Michael can we queue it?

Thanks,
Stefano

yes, I tagged it already.

Michael, I think we missed this series for v11.0 :-(

Can we use this for the next cycle, or Albert should repost it?

Thanks,
Stefano

#11 lore raw
Quoted 14 lines · Stefano Garzarella
Quoted 13 lines · Michael S. Tsirkin
Quoted 9 lines · Stefano Garzarella
Quoted 1 line · Albert Esteve

Hi all,

Thanks!

This is now fully reviewed, Michael can we queue it?

Thanks,
Stefano

Quoted 8 lines
Quoted 1 line

yes, I tagged it already.

Michael, I think we missed this series for v11.0 :-(

Can we use this for the next cycle, or Albert should repost it?

Thanks,
Stefano

Indeed. Sorry I was less focused than usual. We can use it I think.

Signature · 1 line
MST