vhost-user: isolated memory
v2 cover vhost-user: isolated memory
This patch series implements a memory isolation mode in vhost-user. The purpose of this mode is to provide the option of additional security by eliminating direct access of guest memory by vhost-user devices. At a high level this works by:
1. Adding qdev and qapi properties required to enable isolation mode for various devices.
2. Allocating an isolation memory region in an anonymous file and mapping it to host memory. This isolation region will hold the bounce buffers and vrings necessary to move data.
3. Using a vhost-iova-tree to allocate and track the mapping between guest regions and their corresponding bounce buffers in the isolation memory.
4. Creating shadow virtqueues to intercept request notifications. As kick and call events are received by an svq, it copies buffer contents and descriptors between isolation and guest memory before notifying the backend or guest.
Note: This project is currently in a partially functional state. While the overall method will stay the same, the implementation is planned to move up into vhost to simplify some elements of initializing and using the shadow virtqueues.
However, the desire is to make this work public at this stage for comment on the overall approach.
Based-on: [email protected]
---
Changelog:
V2:
Series:
- Updates to svq address translation moved to a different patch series.
- The "shadow vq cleanup" has been merged into the earlier patch
handling svq setup.
- Link to v1: https://lore.kernel.org/qemu-devel/[email protected]
Individual Patches:
vhost-user: Consolidate chardev property definitions
- Patch author updated from ConKite to Connor Kite
util/iova-tree: g_tree_foreach wrapper
- Added clarification comments about the function passed to iova_tree_foreach
hw/virtio: iova_tree_foreach wrapper
- Corrected comment about GTraverseFUnc end condition
hw/virtio/vhost-shadow-virtqueue: used callback
- Changed name of "used_handler" to "used_callback"
- Added handling if callback returns with error value
- Comments added clarifying callback return values
hw/virtio/vhost-shadow-virtqueue: specified vring placement
- Formatting improvements
- Change hwaddr to void * for pointers to host memory
- Bounds checking added when allocating vrings
vhost-user: add memory_isolation to VhostUserState
- Updated net_passt_vhost_user_init signature that is active when !defined(CONFIG_VHOST_USER)
- Comment updates for clarity
hw/virtio/vhost-user: create isolation region
- Formatting fixes
- Many comments added
- Read-after-zeroing bug fixed in cleanup_isolation_regions
- User-after-free bug in init_isolation_regions fixed by removing duplicate calls, and consolidating those steps in cleanup_isolation_regions
- Data unique to isolation mode consolidated in IsolationModeCtx struct
- Vring memory size calculations now only done via an API exposed by vhost-shadow-virtqueue
- Isolation region memfd file given a unique name
- Iova-tree IOVA space now starts at 0 + page_size to avoid exposing qemu addresses
- buffer_regions array moved changed from GArray to dynamically allocated array of predetermined size. Avoids GArray formatting ugliness
Note: Devicies implemented with multiple vhost threads, like virtio-net, are not currently supported. Work is still required to update the vring allocation code to run only for vq_index=0 and propagate to the other vhost-user instances.
hw/virtio/vhost-user: send isolation regions to device
- Formatting improvements
- Vring region combined with contiguous buffer region in IOVA space to avoid wasting one of the available region slots that can be sent to the back-end
- Traversal callback for filling out msg regions renamed to vhost_user_fill_msg_reg_from_tree and simplified
- Check added if postcopy is in use as it is not currently supported
hw/virtio/vhost-user: add shadow virtqueues and eventfd intercepts
- Vring mapping now occurs during the vhost_user_set_mem_tables call, which means that vring addresses can be sent to the backend when expected by vhost
- The svq's device-facing event notifiers are now cleaned up in case of error or reset
- Bounds checking on vq index added in various locations
- SVQ cleanup code added
hw/virtio/vhost-user: handle data movement with shadow vqs
- Removed unecessary changes to elements during handling
- Fixed incorrect memcpy of used buffers in reverse direction
- Formatting improvements
- Bounds and error checking to handle mapping failures or buffers with invalid ranges
- Add error if isolation mode is used while IOMMU is active
- Add error if isolation mode is used with packed vrings
vhost-user: Add memory-isolation qdev property to vhost-user devices
- Patch moved to end of patch series
- Fixed overlong lines
backends/cryptodev-vhost-user: add memory isolation bool
- Fixed style in qapi and added "since" field
- Clarification added to comments
- The memory_isolation bool can no longer be set in vhost-cryptodev once initialization finishes
net/vhost-user: add memory isolation
- Moved to the back of the patch series
- Dead code removed by hard-coding memory_isolation args to vhost_user_init
---
Connor Kite (13):
vhost-user: Consolidate chardev property definitions util/iova-tree: g_tree_foreach wrapper
hw/virtio: iova_tree_foreach wrapper hw/virtio/vhost-shadow-virtqueue: used callback hw/virtio/vhost-shadow-virtqueue: specified vring placement
vhost-user: add memory_isolation to VhostUserState hw/virtio/vhost-user: create isolation region hw/virtio/vhost-user: send isolation regions to device hw/virtio/vhost-user: add shadow virtqueues and eventfd intercepts hw/virtio/vhost-user: handle data movement with shadow vqs
vhost-user: Add memory-isolation qdev property to vhost-user devices backends/cryptodev-vhost-user: add memory isolation bool net/vhost-user: add memory isolation
backends/cryptodev-vhost-user.c | 28 +- backends/vhost-user.c | 4 +- hw/block/vhost-user-blk.c | 4 +- hw/display/vhost-user-gpu.c | 4 +- hw/scsi/vhost-user-scsi.c | 5 +- hw/virtio/vhost-iova-tree.c | 15 + hw/virtio/vhost-iova-tree.h | 2 + hw/virtio/vhost-shadow-virtqueue.c | 80 ++++- hw/virtio/vhost-shadow-virtqueue.h | 25 +- hw/virtio/vhost-stub.c | 3 +- hw/virtio/vhost-user-base.c | 14 +- hw/virtio/vhost-user-fs.c | 5 +- hw/virtio/vhost-user-gpio.c | 4 - hw/virtio/vhost-user-i2c.c | 5 - hw/virtio/vhost-user-input.c | 5 - hw/virtio/vhost-user-rng.c | 5 - hw/virtio/vhost-user-rtc.c | 4 - hw/virtio/vhost-user-scmi.c | 5 +- hw/virtio/vhost-user-snd.c | 1 - hw/virtio/vhost-user-spi.c | 5 - hw/virtio/vhost-user-test-device.c | 1 - hw/virtio/vhost-user-vsock.c | 5 +- hw/virtio/vhost-user.c | 657 ++++++++++++++++++++++++++++++++++- include/hw/virtio/vhost-user-base.h | 1 + include/hw/virtio/vhost-user-blk.h | 1 + include/hw/virtio/vhost-user-fs.h | 1 + include/hw/virtio/vhost-user-scmi.h | 1 + include/hw/virtio/vhost-user-vsock.h | 1 + include/hw/virtio/vhost-user.h | 6 +- include/hw/virtio/virtio-gpu.h | 1 + include/hw/virtio/virtio-scsi.h | 1 + include/qemu/iova-tree.h | 21 ++ include/system/vhost-user-backend.h | 3 +- net/passt.c | 19 +- net/vhost-user.c | 11 +- qapi/net.json | 16 +- qapi/qom.json | 8 +- util/iova-tree.c | 5 + 38 files changed, 903 insertions(+), 79 deletions(-)
---
base-commit: 88aac004fb1bef50277d8484f4aeacf2e8cb9e38
change-id: 20260604-vhost-user-isolated-memory-070ed4833ee7
Best regards,
Signature · 1 line
Connor Kite <[email protected]>
RFC PATCH v2 1/13 vhost-user: Consolidate chardev property definitions
Move chardev qdev property definitions from children into VHostUserBase. This reduces code duplication and allows children to simply inherit the property during initialization.
--- hw/virtio/vhost-user-base.c | 9 +++++++++ hw/virtio/vhost-user-gpio.c | 4 ---- hw/virtio/vhost-user-i2c.c | 5 ----- hw/virtio/vhost-user-input.c | 5 ----- hw/virtio/vhost-user-rng.c | 5 ----- hw/virtio/vhost-user-rtc.c | 4 ---- hw/virtio/vhost-user-snd.c | 1 - hw/virtio/vhost-user-spi.c | 5 ----- hw/virtio/vhost-user-test-device.c | 1 - 9 files changed, 9 insertions(+), 30 deletions(-)
hw/virtio/vhost-user-base.c +9 -0
@@ -407,9 +407,16 @@ static void vub_device_unrealize(DeviceState *dev)do_vhost_user_cleanup (vdev, vub); } +/*Define common qdev properties. Inherited by all children*/ +static const Property vub_properties[] = { +DEFINE_PROP_CHR ("chardev" , VHostUserBase, chardev) +}; + +static void vub_class_init (ObjectClass *klass,const void *data) {VirtioDeviceClass *vdc =VIRTIO_DEVICE_CLASS (klass); +DeviceClass *dc =DEVICE_CLASS (klass); vdc->realize = vub_device_realize; vdc->unrealize = vub_device_unrealize;
@@ -417,6 +424,8 @@ static void vub_class_init(ObjectClass *klass, const void *data) vdc->get_config = vub_get_config; vdc->set_config = vub_set_config; vdc->set_status = vub_set_status; + +device_class_set_props (dc, vub_properties); }static const TypeInfo vub_types[] = {
hw/virtio/vhost-user-gpio.c +0 -4
@@ -14,9 +14,6 @@#include "standard-headers/linux/virtio_ids.h" #include "standard-headers/linux/virtio_gpio.h" -static const Property vgpio_properties[] = { -DEFINE_PROP_CHR ("chardev" , VHostUserBase, chardev), -};static void vgpio_realize (DeviceState *dev,Error **errp) {
@@ -42,7 +39,6 @@ static void vu_gpio_class_init(ObjectClass *klass, const void *data)VHostUserBaseClass *vubc =VHOST_USER_BASE_CLASS (klass); dc->vmsd = &vu_gpio_vmstate; -device_class_set_props (dc, vgpio_properties);device_class_set_parent_realize (dc, vgpio_realize, &vubc->parent_realize);set_bit (DEVICE_CATEGORY_INPUT , dc->categories);
hw/virtio/vhost-user-i2c.c +0 -5
@@ -14,10 +14,6 @@#include "qemu/error-report.h" #include "standard-headers/linux/virtio_ids.h" -static const Property vi2c_properties[] = { -DEFINE_PROP_CHR ("chardev" , VHostUserBase, chardev), -}; -static void vi2c_realize (DeviceState *dev,Error **errp) {VHostUserBase *vub =VHOST_USER_BASE (dev);
@@ -42,7 +38,6 @@ static void vu_i2c_class_init(ObjectClass *klass, const void *data)VHostUserBaseClass *vubc =VHOST_USER_BASE_CLASS (klass); dc->vmsd = &vu_i2c_vmstate; -device_class_set_props (dc, vi2c_properties);device_class_set_parent_realize (dc, vi2c_realize, &vubc->parent_realize);set_bit (DEVICE_CATEGORY_INPUT , dc->categories);
hw/virtio/vhost-user-input.c +0 -5
@@ -7,10 +7,6 @@#include "qemu/osdep.h" #include "hw/virtio/virtio-input.h" -static const Property vinput_properties[] = { -DEFINE_PROP_CHR ("chardev" , VHostUserBase, chardev), -}; -static void vinput_realize (DeviceState *dev,Error **errp) {VHostUserBase *vub =VHOST_USER_BASE (dev);
@@ -36,7 +32,6 @@ static void vhost_input_class_init(ObjectClass *klass, const void *data)DeviceClass *dc =DEVICE_CLASS (klass); dc->vmsd = &vmstate_vhost_input; -device_class_set_props (dc, vinput_properties);device_class_set_parent_realize (dc, vinput_realize, &vubc->parent_realize);set_bit (DEVICE_CATEGORY_INPUT , dc->categories);
hw/virtio/vhost-user-rng.c +0 -5
@@ -20,10 +20,6 @@ static const VMStateDescription vu_rng_vmstate = { .unmigratable = 1, }; -static const Property vrng_properties[] = { -DEFINE_PROP_CHR ("chardev" , VHostUserBase, chardev), -}; -static void vu_rng_base_realize (DeviceState *dev,Error **errp) {VHostUserBase *vub =VHOST_USER_BASE (dev);
@@ -43,7 +39,6 @@ static void vu_rng_class_init(ObjectClass *klass, const void *data)VHostUserBaseClass *vubc =VHOST_USER_BASE_CLASS (klass); dc->vmsd = &vu_rng_vmstate; -device_class_set_props (dc, vrng_properties);device_class_set_parent_realize (dc, vu_rng_base_realize, &vubc->parent_realize);
hw/virtio/vhost-user-rtc.c +0 -4
@@ -19,9 +19,6 @@ static const VMStateDescription vu_rtc_vmstate = { .unmigratable = 1, }; -static const Property vrtc_properties[] = { -DEFINE_PROP_CHR ("chardev" , VHostUserBase, chardev), -};static void vu_rtc_base_realize (DeviceState *dev,Error **errp) {
@@ -42,7 +39,6 @@ static void vu_rtc_class_init(ObjectClass *klass, const void *data)VHostUserBaseClass *vubc =VHOST_USER_BASE_CLASS (klass); dc->vmsd = &vu_rtc_vmstate; -device_class_set_props (dc, vrtc_properties);device_class_set_parent_realize (dc, vu_rtc_base_realize, &vubc->parent_realize);
hw/virtio/vhost-user-snd.c +0 -1
@@ -34,7 +34,6 @@ static const VMStateDescription vu_snd_vmstate = { };static const Property vsnd_properties[] = { -DEFINE_PROP_CHR ("chardev" , VHostUserBase, chardev),DEFINE_PROP_BIT64 ("controls" , VHostUserBase, parent_obj.host_features,VIRTIO_SND_F_CTLS , false), };
hw/virtio/vhost-user-spi.c +0 -5
@@ -15,10 +15,6 @@#include "standard-headers/linux/virtio_ids.h" #include "standard-headers/linux/virtio_spi.h" -static const Property vspi_properties[] = { -DEFINE_PROP_CHR ("chardev" , VHostUserBase, chardev), -}; -static void vspi_realize (DeviceState *dev,Error **errp) {VHostUserBase *vub =VHOST_USER_BASE (dev);
@@ -44,7 +40,6 @@ static void vu_spi_class_init(ObjectClass *klass, const void *data)VHostUserBaseClass *vubc =VHOST_USER_BASE_CLASS (klass); dc->vmsd = &vu_spi_vmstate; -device_class_set_props (dc, vspi_properties);device_class_set_parent_realize (dc, vspi_realize, &vubc->parent_realize);set_bit (DEVICE_CATEGORY_INPUT , dc->categories);
hw/virtio/vhost-user-test-device.c +0 -1
@@ -30,7 +30,6 @@ static const VMStateDescription vud_vmstate = { };static const Property vud_properties[] = { -DEFINE_PROP_CHR ("chardev" , VHostUserBase, chardev),DEFINE_PROP_UINT16 ("virtio-id" , VHostUserBase, virtio_id,0 ),DEFINE_PROP_UINT32 ("vq_size" , VHostUserBase, vq_size,64 ),DEFINE_PROP_UINT32 ("num_vqs" , VHostUserBase, num_vqs,1 ),
Signature · 1 line
2.43.0
RFC PATCH v2 2/13 util/iova-tree: g_tree_foreach wrapper
In reply to Connor KiteAdd a wrapper to iova-tree to call g_tree_foreach. Provides a means to execute some function on each node of the iova-tree.
--- include/qemu/iova-tree.h | 21 +++++++++++++++++++++ util/iova-tree.c | 5 +++++ 2 files changed, 26 insertions(+)
include/qemu/iova-tree.h +21 -0
@@ -161,4 +161,25 @@ int iova_tree_alloc_map(IOVATree *tree, DMAMap *map, hwaddr iova_begin,*/ void iova_tree_destroy (IOVATree *tree); +/** +* iova_tree_foreach: +* +* @tree: the iova tree to traverse +* @func: the function called at every node. A true return value ends traversal. +* Arguments: +* gpointer key: key of current node +* gpointer value: value of current node +* gpointer data: data passed in at g_tree_foreach call +* Return: gboolean +* @data: an argument passed to func +* +* Wrapper to call g_tree_foreach on the underlying g_tree. g_tree_foreach will +* traverse through every node of the tree, barring an early return. At each +* node, g_tree_foreach calls func with pointers to the node key, node value, +* and a pointer to data passed in by the caller. +* +* Return: None +*/ +void iova_tree_foreach (IOVATree *tree,GTraverseFunc func,gpointer data); +#endif
util/iova-tree.c +5 -0
@@ -303,3 +303,8 @@ int gpa_tree_insert(IOVATree *tree, const DMAMap *map)return IOVA_OK ; } + +void iova_tree_foreach (IOVATree *tree,GTraverseFunc func,gpointer data) +{ +g_tree_foreach (tree->tree, func, data); +}
Signature · 1 line
2.43.0
RFC PATCH v2 3/13 hw/virtio: iova_tree_foreach wrapper
In reply to Connor KiteAdd a wrapper to vhost-iova-tree that calls iova_tree_foreach on the underlying iova_map. This provides a means to execute some function on each node of the tree.
--- hw/virtio/vhost-iova-tree.c | 15 +++++++++++++++ hw/virtio/vhost-iova-tree.h | 2 ++ 2 files changed, 17 insertions(+)
hw/virtio/vhost-iova-tree.c +15 -0
@@ -189,3 +189,18 @@ void vhost_iova_tree_remove_gpa(VhostIOVATree *iova_tree, DMAMap map)iova_tree_remove (iova_tree->gpa_iova_map, map);iova_tree_remove (iova_tree->iova_map, map); } + + +/** +* Traverse through the iova tree in sorted order +* +* @tree: The VhostIOVATree +* @func: Function called at every node. A true return value ends traversal +* @data: An argument passed to func +*/ +void vhost_iova_tree_foreach (VhostIOVATree *tree, +GTraverseFunc func, +gpointer data) +{ +iova_tree_foreach (tree->iova_map, func, data); +}
hw/virtio/vhost-iova-tree.h +2 -0
@@ -29,5 +29,7 @@ const DMAMap *vhost_iova_tree_find_gpa(const VhostIOVATree *iova_tree,int vhost_iova_tree_map_alloc_gpa (VhostIOVATree *iova_tree,DMAMap *map,hwaddr taddr);void vhost_iova_tree_remove_gpa (VhostIOVATree *iova_tree,DMAMap map); +void vhost_iova_tree_foreach (VhostIOVATree *tree,GTraverseFunc func, +gpointer data);#endif
Signature · 1 line
2.43.0
RFC PATCH v2 4/13 hw/virtio/vhost-shadow-virtqueue: used callback
In reply to Connor KiteAdds a callback to shadow virtqueues in order to enable non-default processing of used vring elements from the device.
--- hw/virtio/vhost-shadow-virtqueue.c | 9 +++++++++ hw/virtio/vhost-shadow-virtqueue.h | 16 ++++++++++++++++ 2 files changed, 25 insertions(+)
hw/virtio/vhost-shadow-virtqueue.c +9 -0
@@ -675,6 +675,15 @@ static void vhost_svq_flush(VhostShadowVirtqueue *svq,break ; } +if (svq->ops && svq->ops->used_callback) { +int r = svq->ops->used_callback (svq, elem, svq->ops_opaque); + +if (r <0 ) { +/* VQ or handler is broken. Do not set guest notifier */ +return ; + } + } +if (unlikely (i >= svq->vring.num)) { qemu_log_mask(LOG_GUEST_ERROR, "More than %u used buffers obtained in a %u size SVQ",
hw/virtio/vhost-shadow-virtqueue.h +16 -0
@@ -56,8 +56,24 @@ typedef int (*VirtQueueAvailCallback)(VhostShadowVirtqueue *svq, VirtQueueElement *elem, void *vq_callback_opaque); +/** +* Callback to handle a used buffer +* +* @svq: Shadow virtqueue +* @elem: Element placed in the queue by the device +* @vq_callback_opaque: Used to pass arguments to callback +* +* Returns 0 if the vq is running as expected. Returns a negative errno on +* failure. The callback should not add used elements to the vq shadowed +* by the svq as that is done separately after the callback returns. +*/ +typedef int (*VirtQueueUsedCallback )(VhostShadowVirtqueue *svq, +VirtQueueElement *elem, +void *vq_callback_opaque); +typedef struct VhostShadowVirtqueueOps {VirtQueueAvailCallback avail_handler; +VirtQueueUsedCallback used_callback; }VhostShadowVirtqueueOps ;/* Shadow virtqueue to relay notifications */
Signature · 1 line
2.43.0
RFC PATCH v2 5/13 hw/virtio/vhost-shadow-virtqueue: specified vring placement
In reply to Connor KiteBy default svq vrings are placed in an anonymous memory map. As svqs will be leveraged to enable memory isolation in vhost-user, it is useful to be able to place the vrings in a shared isolation memory region.
Adds the option to specify vring placement by providing a vring base address before starting the svq.
--- hw/virtio/vhost-shadow-virtqueue.c | 69 ++++++++++++++++++++++++++++++++------ hw/virtio/vhost-shadow-virtqueue.h | 8 ++++- 2 files changed, 66 insertions(+), 11 deletions(-)
hw/virtio/vhost-shadow-virtqueue.c +59 -10
@@ -812,6 +812,13 @@ size_t vhost_svq_device_area_size(const VhostShadowVirtqueue *svq)return ROUND_UP (used_size,qemu_real_host_page_size ()); } +size_t vhost_svq_vring_total_size (VirtIODevice *vdev,VirtQueue *vq) +{ +VhostShadowVirtqueue svq; + svq.vring.num =virtio_queue_get_num (vdev,virtio_get_queue_index (vq)); +return vhost_svq_driver_area_size (&svq) +vhost_svq_device_area_size (&svq); +} +/** * Set a new file descriptor for the guest to kick the SVQ and notify for avail *
@@ -842,6 +849,19 @@ void vhost_svq_set_svq_kick_fd(VhostShadowVirtqueue *svq, int svq_kick_fd) } } +/** +* Set vring base address if using fixed locations +* +* @svq: Shadow Virtqueue +* @addr: Points to new base address +*/ + +void vhost_svq_set_base_addr (VhostShadowVirtqueue *svq,void *addr) + { + svq->base_addr = addr; + } + +/** * Start the shadow virtqueue operation. *
@@ -849,8 +869,10 @@ void vhost_svq_set_svq_kick_fd(VhostShadowVirtqueue *svq, int svq_kick_fd)* @vdev: VirtIO device * @vq: Virtqueue to shadow * @iova_tree: Tree to perform descriptors translations +* +* Return 0 on success, -errno on failure */ -void vhost_svq_start (VhostShadowVirtqueue *svq,VirtIODevice *vdev, +int vhost_svq_start (VhostShadowVirtqueue *svq,VirtIODevice *vdev,VirtQueue *vq,VhostIOVATree *iova_tree) {size_t desc_size;
@@ -868,14 +890,27 @@ void vhost_svq_start(VhostShadowVirtqueue *svq, VirtIODevice *vdev, svq->vring.num =virtio_queue_get_num (vdev,virtio_get_queue_index (vq)); svq->num_free = svq->vring.num; - svq->vring.desc =mmap (NULL ,vhost_svq_driver_area_size (svq), -PROT_READ |PROT_WRITE ,MAP_SHARED |MAP_ANONYMOUS , --1 ,0 ); desc_size =sizeof (vring_desc_t) * svq->vring.num; - svq->vring.avail = (void *)((char *)svq->vring.desc + desc_size); - svq->vring.used =mmap (NULL ,vhost_svq_device_area_size (svq), -PROT_READ |PROT_WRITE ,MAP_SHARED |MAP_ANONYMOUS , --1 ,0 ); +if (svq->base_addr ==NULL ) { + svq->vring.desc =mmap (NULL ,vhost_svq_driver_area_size (svq), +PROT_READ |PROT_WRITE ,MAP_SHARED |MAP_ANONYMOUS , +-1 ,0 ); + svq->vring.avail = (void *)((char *)svq->vring.desc + desc_size); + svq->vring.used =mmap (NULL ,vhost_svq_device_area_size (svq), +PROT_READ |PROT_WRITE ,MAP_SHARED |MAP_ANONYMOUS , +-1 ,0 ); + }else { + svq->vring.desc = (void *)svq->base_addr; + svq->vring.avail = (void *)((char *)svq->vring.desc + desc_size); + svq->vring.used = (void *)((char *)svq->base_addr + +vhost_svq_driver_area_size (svq)); + +if ((uint64_t )svq->vring.used +vhost_svq_device_area_size (svq) -1 < + (uint64_t )svq->vring.desc) { +error_report ("Invalid shadow vring location" ); +return -ENOMEM ; + } + } svq->desc_state =g_new0 (SVQDescState, svq->vring.num);if (virtio_vdev_has_feature (svq->vdev,VIRTIO_F_IN_ORDER )) { svq->batch_last.id =VIRTIO_RING_NOT_IN_BATCH ;
@@ -884,6 +919,8 @@ void vhost_svq_start(VhostShadowVirtqueue *svq, VirtIODevice *vdev, svq->desc_state[i].next = i +1 ; } } + +return 0 ; }/**
@@ -920,8 +957,19 @@ void vhost_svq_stop(VhostShadowVirtqueue *svq) } svq->vq =NULL ;g_free (svq->desc_state); -munmap (svq->vring.desc,vhost_svq_driver_area_size (svq)); -munmap (svq->vring.used,vhost_svq_device_area_size (svq)); + +if (!svq->base_addr) { +munmap (svq->vring.desc,vhost_svq_driver_area_size (svq)); +munmap (svq->vring.used,vhost_svq_device_area_size (svq)); + }else { +if (svq->vring.desc) { +memset (svq->vring.desc,0 ,vhost_svq_driver_area_size (svq)); + } +if (svq->vring.used) { +memset (svq->vring.used,0 ,vhost_svq_device_area_size (svq)); + } + } +event_notifier_set_handler (&svq->hdev_call,NULL ); }
@@ -940,6 +988,7 @@ VhostShadowVirtqueue *vhost_svq_new(const VhostShadowVirtqueueOps *ops,event_notifier_init_fd (&svq->svq_kick,VHOST_FILE_UNBIND ); svq->ops = ops; svq->ops_opaque = ops_opaque; + svq->base_addr =NULL ;return svq; }
hw/virtio/vhost-shadow-virtqueue.h +7 -1
@@ -150,6 +150,9 @@ typedef struct VhostShadowVirtqueue {/* Size of SVQ vring free descriptors */ uint16_t num_free; + +/* Location assigned to vrings if not in default anon memory map */ +void *base_addr; } VhostShadowVirtqueue;bool vhost_svq_valid_features (uint64_t features,Error **errp);
@@ -169,8 +172,9 @@ void vhost_svq_get_vring_addr(const VhostShadowVirtqueue *svq, struct vhost_vring_addr *addr);size_t vhost_svq_driver_area_size (const VhostShadowVirtqueue *svq);size_t vhost_svq_device_area_size (const VhostShadowVirtqueue *svq); +size_t vhost_svq_vring_total_size (VirtIODevice *vdev,VirtQueue *vq); -void vhost_svq_start (VhostShadowVirtqueue *svq,VirtIODevice *vdev, +int vhost_svq_start (VhostShadowVirtqueue *svq,VirtIODevice *vdev,VirtQueue *vq,VhostIOVATree *iova_tree);void vhost_svq_stop (VhostShadowVirtqueue *svq);
@@ -178,6 +182,8 @@ VhostShadowVirtqueue *vhost_svq_new(const VhostShadowVirtqueueOps *ops, void *ops_opaque);void vhost_svq_free (gpointer vq); +void vhost_svq_set_base_addr (VhostShadowVirtqueue *svq,void *addr); +G_DEFINE_AUTOPTR_CLEANUP_FUNC (VhostShadowVirtqueue, vhost_svq_free);#endif
Signature · 1 line
2.43.0
RFC PATCH v2 6/13 vhost-user: add memory_isolation to VhostUserState
In reply to Connor KiteAdd a memory_isolation bool to the VhostUserState struct. This bool is set within vhost_user_init(), which takes a memory_isolation bool as an argument.
Refactor all call locations of vhost_user_init to include the new argument.
--- backends/cryptodev-vhost-user.c | 2 +- backends/vhost-user.c | 4 ++-- hw/block/vhost-user-blk.c | 3 ++- hw/display/vhost-user-gpu.c | 3 ++- hw/scsi/vhost-user-scsi.c | 3 ++- hw/virtio/vhost-stub.c | 3 ++- hw/virtio/vhost-user-base.c | 3 ++- hw/virtio/vhost-user-fs.c | 3 ++- hw/virtio/vhost-user-scmi.c | 3 ++- hw/virtio/vhost-user-vsock.c | 3 ++- hw/virtio/vhost-user.c | 5 ++++- include/hw/virtio/vhost-user.h | 6 +++++- include/system/vhost-user-backend.h | 3 ++- net/passt.c | 14 ++++++++++---- net/vhost-user.c | 8 +++++--- 15 files changed, 45 insertions(+), 21 deletions(-)
backends/cryptodev-vhost-user.c +1 -1
@@ -213,7 +213,7 @@ static void cryptodev_vhost_user_init( } } -if (!vhost_user_init (&s->vhost_user, &s->chr, errp)) { +if (!vhost_user_init (&s->vhost_user, &s->chr, false, errp)) {return ; }
backends/vhost-user.c +2 -2
@@ -22,13 +22,13 @@int vhost_user_backend_dev_init (VhostUserBackend *b,VirtIODevice *vdev, -unsigned nvqs,Error **errp) +unsigned nvqs,bool memory_isolation,Error **errp) {int ret;assert (!b->vdev && vdev); -if (!vhost_user_init (&b->vhost_user, &b->chr, errp)) { +if (!vhost_user_init (&b->vhost_user, &b->chr, memory_isolation, errp)) {return -1 ; }
hw/block/vhost-user-blk.c +2 -1
@@ -505,7 +505,8 @@ static void vhost_user_blk_device_realize(DeviceState *dev, Error **errp)return ; } -if (!vhost_user_init (&s->vhost_user, &s->chardev, errp)) { +if (!vhost_user_init (&s->vhost_user, &s->chardev, + false, errp)) {return ; }
hw/display/vhost-user-gpu.c +2 -1
@@ -663,7 +663,8 @@ vhost_user_gpu_device_realize(DeviceState *qdev, Error **errp)VirtIODevice *vdev =VIRTIO_DEVICE (g);vhost_dev_set_config_notifier (&g->vhost->dev, &config_ops); -if (vhost_user_backend_dev_init (g->vhost, vdev,2 , errp) <0 ) { +if (vhost_user_backend_dev_init (g->vhost, vdev,2 , false, + errp) <0 ) {return ; }
hw/scsi/vhost-user-scsi.c +2 -1
@@ -276,7 +276,8 @@ static void vhost_user_scsi_realize(DeviceState *dev, Error **errp)return ; } -if (!vhost_user_init (&s->vhost_user, &vs->conf.chardev, errp)) { +if (!vhost_user_init (&s->vhost_user, &vs->conf.chardev, + false, errp)) { goto free_virtio; }
hw/virtio/vhost-stub.c +2 -1
@@ -12,7 +12,8 @@ unsigned int vhost_get_free_memslots(void)return UINT_MAX ; } -bool vhost_user_init (VhostUserState *user,CharFrontend *chr,Error **errp) +bool vhost_user_init (VhostUserState *user,CharFrontend *chr, +bool memory_isolation,Error **errp) {return false; }
hw/virtio/vhost-user-base.c +2 -1
@@ -317,7 +317,8 @@ static void vub_device_realize(DeviceState *dev, Error **errp) vub->vhost_user.supports_config = true; } -if (!vhost_user_init (&vub->vhost_user, &vub->chardev, errp)) { +if (!vhost_user_init (&vub->vhost_user, &vub->chardev, + false, errp)) {return ; }
hw/virtio/vhost-user-fs.c +2 -1
@@ -238,7 +238,8 @@ static void vuf_device_realize(DeviceState *dev, Error **errp)return ; } -if (!vhost_user_init (&fs->vhost_user, &fs->conf.chardev, errp)) { +if (!vhost_user_init (&fs->vhost_user, &fs->conf.chardev, + false, errp)) {return ; }
hw/virtio/vhost-user-scmi.c +2 -1
@@ -244,7 +244,8 @@ static void vu_scmi_device_realize(DeviceState *dev, Error **errp) vdev->host_features |= (1ULL <<VIRTIO_SCMI_F_P2A_CHANNELS ); -if (!vhost_user_init (&scmi->vhost_user, &scmi->chardev, errp)) { +if (!vhost_user_init (&scmi->vhost_user, &scmi->chardev, + false, errp)) {return ; }
hw/virtio/vhost-user-vsock.c +2 -1
@@ -106,7 +106,8 @@ static void vuv_device_realize(DeviceState *dev, Error **errp)return ; } -if (!vhost_user_init (&vsock->vhost_user, &vsock->conf.chardev, errp)) { +if (!vhost_user_init (&vsock->vhost_user, &vsock->conf.chardev, + false, errp)) {return ; }
hw/virtio/vhost-user.c +4 -1
@@ -3121,13 +3121,16 @@ static void vhost_user_state_destroy(gpointer data)vhost_user_host_notifier_remove (n,NULL , true); } -bool vhost_user_init (VhostUserState *user,CharFrontend *chr,Error **errp) +bool vhost_user_init (VhostUserState *user,CharFrontend *chr, +bool memory_isolation, +Error **errp) {if (user->chr) {error_setg (errp,"Cannot initialize vhost-user state" );return false; } user->chr = chr; + user->memory_isolation = memory_isolation; user->memory_slots =0 ; user->notifiers =g_ptr_array_new_full (VIRTIO_QUEUE_MAX /4 , &vhost_user_state_destroy);
include/hw/virtio/vhost-user.h +5 -1
@@ -66,6 +66,7 @@ typedef struct VhostUserHostNotifier {* @chr: the character backend for the socket * @notifiers: GPtrArray of @VhostUserHostnotifier * @memory_slots: +* @memory_isolation: determines whether data is shared or copied */ typedef struct VhostUserState { CharFrontend *chr;
@@ -73,12 +74,14 @@ typedef struct VhostUserState {int memory_slots;bool supports_config;bool supports_inflight_migration; +bool memory_isolation; } VhostUserState;/** * vhost_user_init() - initialise shared vhost_user state * @user: allocated area for storing shared state * @chr: the chardev for the vhost socket +* @memory_isolation: restrict direct access to guest memory from back-end * @errp: error handle * * User can either directly g_new() space for the state or embed
@@ -87,7 +90,8 @@ typedef struct VhostUserState {* * Return: true on success, false on error while setting errp. */ -bool vhost_user_init (VhostUserState *user,CharFrontend *chr,Error **errp); +bool vhost_user_init (VhostUserState *user,CharFrontend *chr, +bool memory_isolation,Error **errp);/** * vhost_user_cleanup() - cleanup state
include/system/vhost-user-backend.h +2 -1
@@ -41,7 +41,8 @@ struct VhostUserBackend { };int vhost_user_backend_dev_init (VhostUserBackend *b,VirtIODevice *vdev, -unsigned nvqs,Error **errp); +unsigned nvqs,bool memory_isolation, +Error **errp);void vhost_user_backend_start (VhostUserBackend *b);int vhost_user_backend_stop (VhostUserBackend *b);
net/passt.c +10 -4
@@ -433,7 +433,9 @@ static void passt_vhost_user_event(void *opaque, QEMUChrEvent event) } } -static int net_passt_vhost_user_init (NetPasstState *s,Error **errp) +static int net_passt_vhost_user_init (NetPasstState *s, +bool memory_isolation, +Error **errp) {Chardev *chr;int sv[2 ];
@@ -457,7 +459,8 @@ static int net_passt_vhost_user_init(NetPasstState *s, Error **errp) s->vhost_user = g_new0(struct VhostUserState, 1);if (!qemu_chr_fe_init (&s->vhost_chr, chr, errp) || - !vhost_user_init (s->vhost_user, &s->vhost_chr, errp)) { + !vhost_user_init (s->vhost_user, &s->vhost_chr, memory_isolation, + errp)) { goto err; }
@@ -487,7 +490,8 @@ err: return -1; }#else -static int net_passt_vhost_user_init (NetPasstState *s,Error **errp) +static int net_passt_vhost_user_init (NetPasstState *s,bool memory_isolation, +Error **errp) {error_setg (errp,"vhost-user support has not been built" );
@@ -735,7 +739,9 @@ int net_init_passt(const Netdev *netdev, const char *name, s->pidfile = pidfile;if (netdev->u.passt.has_vhost_user && netdev->u.passt.vhost_user) { -if (net_passt_vhost_user_init (s, errp) ==-1 ) { +bool memory_isolation = false; + +if (net_passt_vhost_user_init (s, memory_isolation, errp) ==-1 ) {qemu_del_net_client (nc);return -1 ; }
net/vhost-user.c +5 -3
@@ -370,7 +370,7 @@ static void net_vhost_user_event(void *opaque, QEMUChrEvent event)static int net_vhost_user_init (NetClientState *peer,const char *device,const char *name,Chardev *chr, -int queues) +int queues,bool memory_isolation) {Error *err =NULL ;NetClientState *nc, *nc0 =NULL ;
@@ -390,7 +390,7 @@ static int net_vhost_user_init(NetClientState *peer, const char *device, nc0 = nc; s =DO_UPCAST (NetVhostUserState, nc, nc);if (!qemu_chr_fe_init (&s->chr, chr, &err) || - !vhost_user_init (user, &s->chr, &err)) { + !vhost_user_init (user, &s->chr, memory_isolation, &err)) {error_report_err (err); goto err; }
@@ -459,6 +459,7 @@ int net_init_vhost_user(const Netdev *netdev, const char *name,int queues;const NetdevVhostUserOptions *vhost_user_opts;Chardev *chr; +bool memory_isolation = false;assert (netdev->type ==NET_CLIENT_DRIVER_VHOST_USER ); vhost_user_opts = &netdev->u.vhost_user;
@@ -476,5 +477,6 @@ int net_init_vhost_user(const Netdev *netdev, const char *name,return -1 ; } -return net_vhost_user_init (peer,"vhost_user" , name, chr, queues); +return net_vhost_user_init (peer,"vhost_user" , name, chr, queues, + memory_isolation); }
Signature · 1 line
2.43.0
RFC PATCH v2 7/13 hw/virtio/vhost-user: create isolation region
In reply to Connor KiteIf memory isolation mode is active for the vhost-user device adds features to:
- Gather the size required for bounce buffers and vrings in shared isolation region
- Allocate the required space in an anonymous file
- Create a vhost-iova-tree with space to map entire isolation region
- Map guest memory regions and shared vrings into the tree
- Release these resources upon backend cleanup
--- hw/virtio/vhost-user.c | 136 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 136 insertions(+)
hw/virtio/vhost-user.c +136 -0
@@ -18,6 +18,7 @@#include "hw/virtio/vhost-backend.h" #include "hw/virtio/virtio.h" #include "hw/virtio/virtio-net.h" +#include "hw/virtio/vhost-iova-tree.h" #include "chardev/char-fe.h" #include "io/channel-socket.h" #include "system/kvm.h"
@@ -25,6 +26,7 @@#include "qemu/main-loop.h" #include "qemu/uuid.h" #include "qemu/sockets.h" +#include "qemu/memfd.h" #include "system/runstate.h" #include "system/cryptodev.h" #include "migration/postcopy-ram.h"
@@ -320,6 +322,17 @@ static VhostUserMsg m __attribute__ ((unused));/* The version of the protocol we support */ #define VHOST_USER_VERSION (0x1) +/* Memory region shared with back-end when memory-isolation is active */ +typedef struct { +void *shared_mem_addr;/* mapped shared memory */ +VhostIOVATree *tree;/* controls mapping of regions into IOVA space */ +void *vring_hva_addr;/* beginning of vring region in shared memory */ +size_t vring_region_size;/* amount of shared memory reserved for vrings */ +size_t size;/* size of the mapped shared memory */ +int fd;/* descriptor of anonymous file backing shared iso region */ +Int128 iso_iova_offset;/* translation from IOVA to hva of iso region */ +}IsolationModeCtx ; +struct vhost_user {struct vhost_dev *dev;/* Shared between vhost devs of the same virtio device */
@@ -353,6 +366,9 @@ struct vhost_user {* by the backend (see @features). */ uint64_t protocol_features; + +/* Data specfic to isolated memory mode */ +IsolationModeCtx iso_mem_ctx; };struct scrub_regions {
@@ -1112,6 +1128,125 @@ static int vhost_user_set_mem_table_postcopy(struct vhost_dev *dev,return 0 ; } +static void cleanup_isolation_regions (struct vhost_dev *dev) +{ +struct vhost_user *u = dev->opaque; +if (u->iso_mem_ctx.shared_mem_addr) { +vhost_iova_tree_delete (u->iso_mem_ctx.tree); +qemu_memfd_free (u->iso_mem_ctx.shared_mem_addr, + u->iso_mem_ctx.size, + u->iso_mem_ctx.fd); +memset (&u->iso_mem_ctx,0 ,sizeof (IsolationModeCtx)); + } +} + +__attribute__((unused)) +static int init_isolation_regions (struct vhost_dev *dev, +VhostUserMsg *msg, +int *fds,size_t *fd_num) +{ +Error *err =NULL ; +struct vhost_user *u = dev->opaque; +uint32_t nregions = dev->mem->nregions; + + g_autofree DMAMap *buffer_regions = g_new0(DMAMap, nregions); +size_t buffer_reg_size =0 ; +size_t total_vring_size =0 ; +size_t total_mmap_size; +char *reg_name; +uint64_t first_IOVA_addr; +uint64_t last_IOVA_addr; +DMAMap *map; +DMAMap vring_map; +int r; + + msg->hdr.request =VHOST_USER_SET_MEM_TABLE ; + +/* In case of reset, clear old regions */ +cleanup_isolation_regions (dev); + +/* Gather information for bounce buffers to be mapped */ +for (u_int32_t i =0 ; i < nregions; i++) { +hwaddr size =ROUND_UP (dev->mem->regions[i].memory_size, +qemu_real_host_page_size ()); + buffer_regions[i].size = size -1 ; + buffer_regions[i].perm =IOMMU_RW ; + + buffer_reg_size += size; + } + +/* Get space required for all vrings */ +for (int i =0 ; i < dev->nvqs; i++) { +VirtQueue *vq =virtio_get_queue (dev->vdev, dev->vq_index + i); + total_vring_size +=vhost_svq_vring_total_size (dev->vdev, vq); + } + + total_mmap_size = buffer_reg_size + total_vring_size; + u->iso_mem_ctx.size = total_mmap_size; + +/* Allocate and map an anonymous file to hold the isolation region */ + reg_name =g_strconcat ("iso_mem_" , dev->vdev->name,NULL ); + u->iso_mem_ctx.shared_mem_addr =qemu_memfd_alloc (reg_name, + total_mmap_size, +F_SEAL_GROW |F_SEAL_SHRINK |F_SEAL_SEAL , + &u->iso_mem_ctx.fd, &err); + +assert (u->iso_mem_ctx.fd >=0 ); +g_free (reg_name); + +if (err) { +error_report_err (err); +cleanup_isolation_regions (dev); +return -1 ; + } + +/* vhost-iova-tree enforces non-zero lower address */ + first_IOVA_addr =qemu_real_host_page_size (); + last_IOVA_addr = first_IOVA_addr + total_mmap_size -1 ; +assert (last_IOVA_addr > first_IOVA_addr); + +/* Use 128-bit operation in case of large negative offset */ + u->iso_mem_ctx.iso_iova_offset = +int128_sub (int128_make64 ((uint64_t )u->iso_mem_ctx.shared_mem_addr), +int128_make64 (first_IOVA_addr)); + +/* +* Instantiates iova tree sized to map bounce buffers and vrings to the +* isolation region in host va. +*/ + u->iso_mem_ctx.tree = +vhost_iova_tree_new (first_IOVA_addr, last_IOVA_addr); + +/* Map vrings into IOVA tree */ + vring_map.perm =IOMMU_RW ; + vring_map.size = total_vring_size -1 ; + r =vhost_iova_tree_map_alloc (u->iso_mem_ctx.tree, &vring_map, + (hwaddr )u->iso_mem_ctx.shared_mem_addr); + +if (r !=IOVA_OK ) { +cleanup_isolation_regions (dev); +return r; + } + + u->iso_mem_ctx.vring_hva_addr = (void *)int128_get64 ( +int128_add (int128_make64 (vring_map.iova), + u->iso_mem_ctx.iso_iova_offset)); + u->iso_mem_ctx.vring_region_size = total_vring_size; + +for (int i =0 ; i < nregions; i++) { + map = &buffer_regions[i]; + r =vhost_iova_tree_map_alloc_gpa (u->iso_mem_ctx.tree, map, + dev->mem->regions[i].guest_phys_addr); + +if (r !=IOVA_OK ) { +cleanup_isolation_regions (dev); +return r; + } + } + +return 0 ; +} +static int vhost_user_set_mem_table (struct vhost_dev *dev,struct vhost_memory *mem) {
@@ -2684,6 +2819,7 @@ static int vhost_user_backend_cleanup(struct vhost_dev *dev)g_free (u->region_rb_offset); u->region_rb_offset =NULL ; u->region_rb_len =0 ; +cleanup_isolation_regions (dev);g_free (u); dev->opaque =0 ;
Signature · 1 line
2.43.0
RFC PATCH v2 8/13 hw/virtio/vhost-user: send isolation regions to device
In reply to Connor KiteAdds features to fill a vhost_user_set_mem_table message with the addresses of isolation memory regions corresponding to bounce buffers and vrings.
--- hw/virtio/vhost-user.c | 118 ++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 117 insertions(+), 1 deletion(-)
hw/virtio/vhost-user.c +117 -1
@@ -1140,7 +1140,77 @@ static void cleanup_isolation_regions(struct vhost_dev *dev) } } -__attribute__((unused)) +typedef struct { +VhostUserMsg *msg; +struct vhost_user *u; +int *fds; +size_t fds_size; +uint64_t vring_iova; +size_t vring_size; +bool vring_node_visited; +size_t *idx; +}IOVATreeTraversalArgs ; + +static gboolean vhost_user_fill_msg_reg_from_tree (gpointer key, +gpointer value, +gpointer data) +{ +IOVATreeTraversalArgs *args = data; +struct vhost_user *u; +VhostUserMsg *msg = args->msg; +DMAMap *map = key; +uint64_t offset; + +assert (args && key && value); +if (!args->vring_node_visited) { + args->vring_node_visited = true; +return false; + } + + u = args->u; +assert (*args->idx < args->fds_size); + + args->fds[*args->idx] = args->u->iso_mem_ctx.fd; + +/* +* If the number of regions is fixed, it would be wasteful to use one for +* only the vrings. The first vhost_iova_tree element is always +* reserved for the vrings, so we can simply combine the first and second +* elements, which are contiguous in IOVA space, when sending regions to +* the backend. +*/ +if (*args->idx ==0 ) { + offset = u->iso_mem_ctx.vring_hva_addr - u->iso_mem_ctx.shared_mem_addr; + msg->payload.memory.regions[*args->idx].userspace_addr = + args->vring_iova; +/* +* The size from the iova tree is inclusive, so 1 is added to it. +* args->vring_size is exclusive, so no addition is required. +*/ + msg->payload.memory.regions[*args->idx].memory_size = + args->vring_size + map->size +1 ; + msg->payload.memory.regions[*args->idx].guest_phys_addr = + args->vring_iova; + msg->payload.memory.regions[*args->idx].mmap_offset = offset; + }else { +/* Use 128 bit operation in unlikely case of negative iso_iova_offset */ + offset =int128_get64 (int128_add (int128_make64 (map->iova), + u->iso_mem_ctx.iso_iova_offset)) - + (uint64_t )u->iso_mem_ctx.shared_mem_addr; + + msg->payload.memory.regions[*args->idx].userspace_addr = map->iova; + msg->payload.memory.regions[*args->idx].memory_size = map->size +1 ; + msg->payload.memory.regions[*args->idx].guest_phys_addr = map->iova; + msg->payload.memory.regions[*args->idx].mmap_offset = offset; + } + +assert (offset + msg->payload.memory.regions[*args->idx].memory_size <= + u->iso_mem_ctx.size); + (*args->idx)++; + +return false; +} +static int init_isolation_regions (struct vhost_dev *dev,VhostUserMsg *msg,int *fds,size_t *fd_num)
@@ -1159,6 +1229,7 @@ static int init_isolation_regions(struct vhost_dev *dev,DMAMap *map;DMAMap vring_map;int r; +IOVATreeTraversalArgs trav_args; msg->hdr.request =VHOST_USER_SET_MEM_TABLE ;
@@ -1244,6 +1315,27 @@ static int init_isolation_regions(struct vhost_dev *dev, } } + *fd_num =0 ; + trav_args.idx = fd_num; + trav_args.fds = fds; + trav_args.msg = msg; + trav_args.u = u; + trav_args.vring_iova = vring_map.iova; + trav_args.vring_size = total_vring_size; + trav_args.fds_size = nregions; + trav_args.vring_node_visited = false; + +vhost_iova_tree_foreach (u->iso_mem_ctx.tree, + vhost_user_fill_msg_reg_from_tree, &trav_args); + + msg->payload.memory.nregions = *fd_num; + +assert (*fd_num == nregions); + + msg->hdr.size =sizeof (msg->payload.memory.nregions); + msg->hdr.size +=sizeof (msg->payload.memory.padding); + msg->hdr.size += *fd_num *sizeof (VhostUserMemoryRegion); +return 0 ; }
@@ -1251,6 +1343,7 @@ static int vhost_user_set_mem_table(struct vhost_dev *dev, struct vhost_memory *mem) {struct vhost_user *u = dev->opaque; +bool memory_isolation = u->user->memory_isolation;int fds[VHOST_MEMORY_BASELINE_NREGIONS ];size_t fd_num =0 ;bool do_postcopy = u->postcopy_listen && u->postcopy_fd.handler;
@@ -1262,6 +1355,11 @@ static int vhost_user_set_mem_table(struct vhost_dev *dev,int ret;if (do_postcopy) { +/* Postcopy is not supported with memory isolation yet */ +if (memory_isolation) { +return -1 ; + } +/* * Postcopy has enough differences that it's best done in it's own * version
@@ -1278,6 +1376,24 @@ static int vhost_user_set_mem_table(struct vhost_dev *dev, msg.hdr.flags |=VHOST_USER_NEED_REPLY_MASK ; } +if (memory_isolation) { + ret =init_isolation_regions (dev, &msg, fds, &fd_num); +if (ret <0 ) { +return ret; + } + + ret =vhost_user_write (dev, &msg, fds, fd_num); +if (ret <0 ) { +return ret; + } + +if (reply_supported) { +return process_message_reply (dev, &msg); + } + +return 0 ; + } +if (config_mem_slots) { ret =vhost_user_add_remove_regions (dev, &msg, reply_supported, false);if (ret <0 ) {
Signature · 1 line
2.43.0
RFC PATCH v2 9/13 hw/virtio/vhost-user: add shadow virtqueues and eventfd intercepts
In reply to Connor KiteAdds shadow virtqueues that will eventually be used to transfer data between device and host via bounce buffers when isolation mode is active. The svqs are initalized, and eventfd assignments are intercepted so that notifications come to svqs first before the guest or backend receive them.
--- hw/virtio/vhost-user.c | 136 ++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 119 insertions(+), 17 deletions(-)
hw/virtio/vhost-user.c +119 -17
@@ -18,6 +18,7 @@#include "hw/virtio/vhost-backend.h" #include "hw/virtio/virtio.h" #include "hw/virtio/virtio-net.h" +#include "hw/virtio/vhost-shadow-virtqueue.h" #include "hw/virtio/vhost-iova-tree.h" #include "chardev/char-fe.h" #include "io/channel-socket.h"
@@ -331,6 +332,7 @@ typedef struct {size_t size;/* size of the mapped shared memory */ int fd;/* descriptor of anonymous file backing shared iso region */ Int128 iso_iova_offset;/* translation from IOVA to hva of iso region */ +GPtrArray *shadow_vqs;/* shadow vqs with vrings in iso region*/ } IsolationModeCtx;struct vhost_user {
@@ -1128,15 +1130,38 @@ static int vhost_user_set_mem_table_postcopy(struct vhost_dev *dev,return 0 ; } -static void cleanup_isolation_regions (struct vhost_dev *dev) +static void vhost_user_svq_cleanup (struct vhost_user *u,bool reset) +{ +VhostShadowVirtqueue *svq; +for (int i =0 ; i < u->iso_mem_ctx.shadow_vqs->len; i++) { + svq =g_ptr_array_index (u->iso_mem_ctx.shadow_vqs, i); +vhost_svq_stop (svq); +event_notifier_cleanup (&svq->hdev_call); +event_notifier_cleanup (&svq->hdev_kick); + } + +if (!reset) { +g_ptr_array_free (u->iso_mem_ctx.shadow_vqs, true); + } +} + +static void cleanup_isolation_regions (struct vhost_dev *dev,bool reset) {struct vhost_user *u = dev->opaque;if (u->iso_mem_ctx.shared_mem_addr) { +vhost_user_svq_cleanup (u, reset);vhost_iova_tree_delete (u->iso_mem_ctx.tree);qemu_memfd_free (u->iso_mem_ctx.shared_mem_addr, u->iso_mem_ctx.size, u->iso_mem_ctx.fd); + +GPtrArray *temp = u->iso_mem_ctx.shadow_vqs;memset (&u->iso_mem_ctx,0 ,sizeof (IsolationModeCtx)); + +if (!reset) { + u->iso_mem_ctx.shadow_vqs = temp; + } + } }
@@ -1234,7 +1259,7 @@ static int init_isolation_regions(struct vhost_dev *dev, msg->hdr.request =VHOST_USER_SET_MEM_TABLE ;/* In case of reset, clear old regions */ -cleanup_isolation_regions (dev); +cleanup_isolation_regions (dev, true);/* Gather information for bounce buffers to be mapped */ for (u_int32_t i =0 ; i < nregions; i++) {
@@ -1267,7 +1292,7 @@ static int init_isolation_regions(struct vhost_dev *dev,if (err) {error_report_err (err); -cleanup_isolation_regions (dev); +cleanup_isolation_regions (dev, false);return -1 ; }
@@ -1295,7 +1320,7 @@ static int init_isolation_regions(struct vhost_dev *dev, (hwaddr)u->iso_mem_ctx.shared_mem_addr);if (r !=IOVA_OK ) { -cleanup_isolation_regions (dev); +cleanup_isolation_regions (dev, false);return r; }
@@ -1310,7 +1335,7 @@ static int init_isolation_regions(struct vhost_dev *dev, dev->mem->regions[i].guest_phys_addr);if (r !=IOVA_OK ) { -cleanup_isolation_regions (dev); +cleanup_isolation_regions (dev, false);return r; } }
@@ -1738,11 +1763,49 @@ static int vhost_set_vring_file(struct vhost_dev *dev,return 0 ; } +static int vhost_user_get_vq_index (struct vhost_dev *dev,int idx) +{ +assert (idx >= dev->vq_index && idx < dev->vq_index + dev->nvqs); + +return idx; +} +static int vhost_user_set_vring_kick (struct vhost_dev *dev,struct vhost_vring_file *file) { -int ret =vhost_set_vring_file (dev,VHOST_USER_SET_VRING_KICK , file); +struct vhost_user *u = dev->opaque; +int svq_idx = file->index - dev->vq_index; +VhostShadowVirtqueue *svq =NULL ; +struct vhost_vring_file vr_file = *file; +int ret; + +vhost_user_get_vq_index (dev, file->index);/* bounds checking */ + +if (u->user->memory_isolation) { + svq =g_ptr_array_index (u->iso_mem_ctx.shadow_vqs, svq_idx); +vhost_svq_set_svq_kick_fd (svq, file->fd); + +if (file->fd !=-1 ) { +if (!svq->hdev_kick.initialized) { + ret =event_notifier_init (&svq->hdev_kick,0 ); +if (ret <0 ) { +event_notifier_cleanup (&svq->hdev_kick); +error_report ("Failed to create kick event notifier" ); +return ret; + } + } + + vr_file.fd =event_notifier_get_fd (&svq->hdev_kick); + }else { +event_notifier_cleanup (&svq->hdev_kick); + } + } + + ret =vhost_set_vring_file (dev,VHOST_USER_SET_VRING_KICK , &vr_file);if (ret <0 ) { +if (svq !=NULL ) { +event_notifier_cleanup (&svq->hdev_kick); + }return ret; }
@@ -1750,15 +1813,18 @@ static int vhost_user_set_vring_kick(struct vhost_dev *dev,* Inject a kick in case the back-end only starts vring processing upon * receiving a kick. The spec suggests this to improve compatibility. */ -if (file->fd !=-1 ) { +if (vr_file.fd !=-1 ) {uint64_t val =1 ;ssize_t nwritten;do { - nwritten =write (file->fd, &val,sizeof (val)); + nwritten =write (vr_file.fd, &val,sizeof (val)); }while (nwritten <0 && errno ==EINTR );if (nwritten <0 && errno !=EAGAIN /* back-end can already read */ ) { +if (svq !=NULL ) { +event_notifier_cleanup (&svq->hdev_kick); + }return -errno; } }
@@ -1769,7 +1835,35 @@ static int vhost_user_set_vring_kick(struct vhost_dev *dev,static int vhost_user_set_vring_call (struct vhost_dev *dev,struct vhost_vring_file *file) { -return vhost_set_vring_file (dev,VHOST_USER_SET_VRING_CALL , file); +struct vhost_user *u = dev->opaque; +int svq_idx = file->index - dev->vq_index; +VhostShadowVirtqueue *svq =NULL ; +struct vhost_vring_file vr_file = *file; +int ret; + +vhost_user_get_vq_index (dev, file->index);/* bounds checking */ + +if (u->user->memory_isolation) { + svq =g_ptr_array_index (u->iso_mem_ctx.shadow_vqs, svq_idx); +vhost_svq_set_svq_call_fd (svq, file->fd); + +if (file->fd !=-1 ) { +if (!svq->hdev_call.initialized) { + ret =event_notifier_init (&svq->hdev_call,0 ); +if (ret <0 ) { +event_notifier_cleanup (&svq->hdev_call); +error_report ("Failed to create call event notifier" ); +return ret; + } + } + + vr_file.fd =event_notifier_get_fd (&svq->hdev_call); + }else { +event_notifier_cleanup (&svq->hdev_call); + } + } + +return vhost_set_vring_file (dev,VHOST_USER_SET_VRING_CALL , &vr_file); } static int vhost_user_set_vring_err(struct vhost_dev *dev,
@@ -2763,6 +2857,17 @@ static int vhost_user_postcopy_notifier(NotifierWithReturn *notifier,return 0 ; } +static void vhost_user_init_svq (struct vhost_dev *dev,struct vhost_user *u) +{ +/*Modified from vhost-vdpa*/ + u->iso_mem_ctx.shadow_vqs =g_ptr_array_new_full (dev->nvqs, vhost_svq_free); +for (int i =0 ; i < dev->nvqs; i++) { +VhostShadowVirtqueue *svq; + svq =vhost_svq_new (NULL ,NULL ); +g_ptr_array_add (u->iso_mem_ctx.shadow_vqs, svq); + } +} +static int vhost_user_backend_init (struct vhost_dev *dev,void *opaque,Error **errp) {
@@ -2907,6 +3012,10 @@ static int vhost_user_backend_init(struct vhost_dev *dev, void *opaque, u->postcopy_notifier.notify = vhost_user_postcopy_notifier;postcopy_add_notifier (&u->postcopy_notifier); +if (vus->memory_isolation) { +vhost_user_init_svq (dev, u); + } +return 0 ; }
@@ -2935,20 +3044,13 @@ static int vhost_user_backend_cleanup(struct vhost_dev *dev)g_free (u->region_rb_offset); u->region_rb_offset =NULL ; u->region_rb_len =0 ; -cleanup_isolation_regions (dev); +cleanup_isolation_regions (dev, false);g_free (u); dev->opaque =0 ;return 0 ; } -static int vhost_user_get_vq_index (struct vhost_dev *dev,int idx) -{ -assert (idx >= dev->vq_index && idx < dev->vq_index + dev->nvqs); - -return idx; -} -static int vhost_user_memslots_limit (struct vhost_dev *dev) {struct vhost_user *u = dev->opaque;
Signature · 1 line
2.43.0
RFC PATCH v2 10/13 hw/virtio/vhost-user: handle data movement with shadow vqs
In reply to Connor Kite- Add start logic for shadow virtqueues, which sets vring addresses.
- Update logic for sending vring addresses to backend to point to the shadow vrings when isolation mode is active.
- Implement handlers for intercepted avail and used descriptors. These handlers copy buffer contents between bounce buffers in the isolation region and the buffers made available by the guest
- Implement logic to stop svqs
--- hw/virtio/vhost-shadow-virtqueue.c | 2 +- hw/virtio/vhost-shadow-virtqueue.h | 1 + hw/virtio/vhost-user.c | 292 ++++++++++++++++++++++++++++++++++++- 3 files changed, 286 insertions(+), 9 deletions(-)
hw/virtio/vhost-shadow-virtqueue.c +1 -1
@@ -350,7 +350,7 @@ int vhost_svq_add(VhostShadowVirtqueue *svq, const struct iovec *out_sg, }/* Convenience wrapper to add a guest's element to SVQ */ -static int vhost_svq_add_element (VhostShadowVirtqueue *svq, +int vhost_svq_add_element (VhostShadowVirtqueue *svq,VirtQueueElement *elem) { return vhost_svq_add(svq, elem->out_sg, elem->out_num, elem->out_addr,
hw/virtio/vhost-shadow-virtqueue.h +1 -0
@@ -183,6 +183,7 @@ VhostShadowVirtqueue *vhost_svq_new(const VhostShadowVirtqueueOps *ops,void vhost_svq_free (gpointer vq);void vhost_svq_set_base_addr (VhostShadowVirtqueue *svq,void *addr); +int vhost_svq_add_element (VhostShadowVirtqueue *svq,VirtQueueElement *elem);G_DEFINE_AUTOPTR_CLEANUP_FUNC (VhostShadowVirtqueue, vhost_svq_free);
hw/virtio/vhost-user.c +284 -8
342 lines not on this page · raw message
Signature · 1 line
2.43.0
RFC PATCH v2 11/13 vhost-user: Add memory-isolation qdev property to vhost-user devices
In reply to Connor KiteIn support of future work to add a memory isolation mode to vhost-user devices, a qdev property, "memory-isolation", is added to all vhost-user devices. This is simply a bool representing whether the mode is active or not.
--- hw/block/vhost-user-blk.c | 3 ++- hw/display/vhost-user-gpu.c | 3 ++- hw/scsi/vhost-user-scsi.c | 4 +++- hw/virtio/vhost-user-base.c | 6 ++++-- hw/virtio/vhost-user-fs.c | 4 +++- hw/virtio/vhost-user-scmi.c | 4 +++- hw/virtio/vhost-user-vsock.c | 4 +++- include/hw/virtio/vhost-user-base.h | 1 + include/hw/virtio/vhost-user-blk.h | 1 + include/hw/virtio/vhost-user-fs.h | 1 + include/hw/virtio/vhost-user-scmi.h | 1 + include/hw/virtio/vhost-user-vsock.h | 1 + include/hw/virtio/virtio-gpu.h | 1 + include/hw/virtio/virtio-scsi.h | 1 + 14 files changed, 27 insertions(+), 8 deletions(-)
hw/block/vhost-user-blk.c +2 -1
@@ -506,7 +506,7 @@ static void vhost_user_blk_device_realize(DeviceState *dev, Error **errp) }if (!vhost_user_init (&s->vhost_user, &s->chardev, - false, errp)) { + s->memory_isolation, errp)) {return ; }
@@ -632,6 +632,7 @@ static const VMStateDescription vmstate_vhost_user_blk = {static const Property vhost_user_blk_properties[] = {DEFINE_PROP_CHR ("chardev" , VHostUserBlk, chardev), +DEFINE_PROP_BOOL ("memory-isolation" , VHostUserBlk, memory_isolation, false),DEFINE_PROP_UINT16 ("num-queues" , VHostUserBlk, num_queues,VHOST_USER_BLK_AUTO_NUM_QUEUES ),DEFINE_PROP_UINT32 ("queue-size" , VHostUserBlk, queue_size,128 ),
hw/display/vhost-user-gpu.c +2 -1
@@ -663,7 +663,7 @@ vhost_user_gpu_device_realize(DeviceState *qdev, Error **errp)VirtIODevice *vdev =VIRTIO_DEVICE (g);vhost_dev_set_config_notifier (&g->vhost->dev, &config_ops); -if (vhost_user_backend_dev_init (g->vhost, vdev,2 , false, +if (vhost_user_backend_dev_init (g->vhost, vdev,2 , g->memory_isolation, errp) <0 ) {return ; }
@@ -698,6 +698,7 @@ static struct vhost_dev *vhost_user_gpu_get_vhost(VirtIODevice *vdev)static const Property vhost_user_gpu_properties[] = {VIRTIO_GPU_BASE_PROPERTIES (VhostUserGPU, parent_obj.conf), +DEFINE_PROP_BOOL ("memory-isolation" , VhostUserGPU, memory_isolation, false), }; static void
hw/scsi/vhost-user-scsi.c +3 -1
@@ -277,7 +277,7 @@ static void vhost_user_scsi_realize(DeviceState *dev, Error **errp) }if (!vhost_user_init (&s->vhost_user, &vs->conf.chardev, - false, errp)) { + vs->conf.memory_isolation, errp)) { goto free_virtio; }
@@ -347,6 +347,8 @@ static void vhost_user_scsi_unrealize(DeviceState *dev)static const Property vhost_user_scsi_properties[] = {DEFINE_PROP_CHR ("chardev" , VirtIOSCSICommon, conf.chardev), +DEFINE_PROP_BOOL ("memory-isolation" , VirtIOSCSICommon, + conf.memory_isolation, false),DEFINE_PROP_UINT32 ("boot_tpgt" , VirtIOSCSICommon, conf.boot_tpgt,0 ),DEFINE_PROP_UINT32 ("num_queues" , VirtIOSCSICommon, conf.num_queues,VIRTIO_SCSI_AUTO_NUM_QUEUES ),
hw/virtio/vhost-user-base.c +4 -2
@@ -318,7 +318,7 @@ static void vub_device_realize(DeviceState *dev, Error **errp) }if (!vhost_user_init (&vub->vhost_user, &vub->chardev, - false, errp)) { + vub->memory_isolation, errp)) {return ; }
@@ -410,7 +410,9 @@ static void vub_device_unrealize(DeviceState *dev)/*Define common qdev properties. Inherited by all children*/ static const Property vub_properties[] = { -DEFINE_PROP_CHR ("chardev" , VHostUserBase, chardev) +DEFINE_PROP_CHR ("chardev" , VHostUserBase, chardev), +DEFINE_PROP_BOOL ("memory-isolation" , VHostUserBase, memory_isolation, + false), };
hw/virtio/vhost-user-fs.c +3 -1
@@ -239,7 +239,7 @@ static void vuf_device_realize(DeviceState *dev, Error **errp) }if (!vhost_user_init (&fs->vhost_user, &fs->conf.chardev, - false, errp)) { + fs->conf.memory_isolation, errp)) {return ; }
@@ -411,6 +411,8 @@ static const VMStateDescription vuf_backend_vmstate = {static const Property vuf_properties[] = {DEFINE_PROP_CHR ("chardev" , VHostUserFS, conf.chardev), +DEFINE_PROP_BOOL ("memory-isolation" , VHostUserFS, conf.memory_isolation, + false),DEFINE_PROP_STRING ("tag" , VHostUserFS, conf.tag),DEFINE_PROP_UINT16 ("num-request-queues" , VHostUserFS, conf.num_request_queues,1 ),
hw/virtio/vhost-user-scmi.c +3 -1
@@ -245,7 +245,7 @@ static void vu_scmi_device_realize(DeviceState *dev, Error **errp) vdev->host_features |= (1ULL <<VIRTIO_SCMI_F_P2A_CHANNELS );if (!vhost_user_init (&scmi->vhost_user, &scmi->chardev, - false, errp)) { + scmi->memory_isolation, errp)) {return ; }
@@ -288,6 +288,8 @@ static const VMStateDescription vu_scmi_vmstate = {static const Property vu_scmi_properties[] = {DEFINE_PROP_CHR ("chardev" , VHostUserSCMI, chardev), +DEFINE_PROP_BOOL ("memory-isolation" , VHostUserSCMI, memory_isolation, + false), };static void vu_scmi_class_init (ObjectClass *klass,const void *data)
hw/virtio/vhost-user-vsock.c +3 -1
@@ -107,7 +107,7 @@ static void vuv_device_realize(DeviceState *dev, Error **errp) }if (!vhost_user_init (&vsock->vhost_user, &vsock->conf.chardev, - false, errp)) { + vsock->conf.memory_isolation, errp)) {return ; }
@@ -155,6 +155,8 @@ static void vuv_device_unrealize(DeviceState *dev)static const Property vuv_properties[] = {DEFINE_PROP_CHR ("chardev" , VHostUserVSock, conf.chardev), +DEFINE_PROP_BOOL ("memory-isolation" , VHostUserVSock, conf.memory_isolation, + false), };static void vuv_class_init (ObjectClass *klass,const void *data)
include/hw/virtio/vhost-user-base.h +1 -0
@@ -25,6 +25,7 @@ struct VHostUserBase {uint32_t num_vqs;uint32_t vq_size;/* can't exceed VIRTIO_QUEUE_MAX */ uint32_t config_size; +bool memory_isolation;/* State tracking */ VhostUserState vhost_user;struct vhost_virtqueue *vhost_vq;
include/hw/virtio/vhost-user-blk.h +1 -0
@@ -30,6 +30,7 @@ OBJECT_DECLARE_SIMPLE_TYPE(VHostUserBlk, VHOST_USER_BLK)struct VHostUserBlk {VirtIODevice parent_obj;CharFrontend chardev; +bool memory_isolation;int32_t bootindex;struct virtio_blk_config blkcfg;uint16_t num_queues;
include/hw/virtio/vhost-user-fs.h +1 -0
@@ -28,6 +28,7 @@ typedef struct {char *tag;uint16_t num_request_queues;uint16_t queue_size; +bool memory_isolation; } VHostUserFSConf;struct VHostUserFS {
include/hw/virtio/vhost-user-scmi.h +1 -0
@@ -19,6 +19,7 @@ OBJECT_DECLARE_SIMPLE_TYPE(VHostUserSCMI, VHOST_USER_SCMI);struct VHostUserSCMI {VirtIODevice parent;CharFrontend chardev; +bool memory_isolation;struct vhost_virtqueue *vhost_vqs;struct vhost_dev vhost_dev;VhostUserState vhost_user;
include/hw/virtio/vhost-user-vsock.h +1 -0
@@ -21,6 +21,7 @@ OBJECT_DECLARE_SIMPLE_TYPE(VHostUserVSock, VHOST_USER_VSOCK)typedef struct {CharFrontend chardev; +bool memory_isolation; }VHostUserVSockConf ;struct VHostUserVSock {
include/hw/virtio/virtio-gpu.h +1 -0
@@ -276,6 +276,7 @@ struct VhostUserGPU {CharFrontend vhost_chr;QemuDmaBuf *dmabuf[VIRTIO_GPU_MAX_SCANOUTS ];bool backend_blocked; +bool memory_isolation; };#define MAX_SLOTS 4096
include/hw/virtio/virtio-scsi.h +1 -0
@@ -59,6 +59,7 @@ struct VirtIOSCSIConf {char *vhostfd;char *wwpn;CharFrontend chardev; +bool memory_isolation;uint32_t boot_tpgt;IOThread *iothread;IOThreadVirtQueueMappingList *iothread_vq_mapping_list;
Signature · 1 line
2.43.0
RFC PATCH v2 12/13 backends/cryptodev-vhost-user: add memory isolation bool
In reply to Connor KiteAdd a memory_isolation property to CryptoDevBackendVhostUser and add add it as an optional member of CryptodevVhostUserProperties in qapi.
This is needed to be able to specify memory isolation for cryptodev-vhost-user objects, and the bool will eventually be passed to vhost_user_init() in a future patch.
--- backends/cryptodev-vhost-user.c | 28 +++++++++++++++++++++++++++- qapi/qom.json | 8 +++++++- 2 files changed, 34 insertions(+), 2 deletions(-)
backends/cryptodev-vhost-user.c +27 -1
@@ -49,6 +49,7 @@ struct CryptoDevBackendVhostUser {CharFrontend chr;char *chr_name;bool opened; +bool memory_isolation;CryptoDevBackendVhost *vhost_crypto[MAX_CRYPTO_QUEUE_NUM ]; };
@@ -213,7 +214,7 @@ static void cryptodev_vhost_user_init( } } -if (!vhost_user_init (&s->vhost_user, &s->chr, false, errp)) { +if (!vhost_user_init (&s->vhost_user, &s->chr, s->memory_isolation, errp)) {return ; }
@@ -392,6 +393,27 @@ static void cryptodev_vhost_user_finalize(Object *obj)g_free (s->chr_name); } +static void cryptodev_vhost_user_set_mem_isolation (Object *obj,bool value, +Error **errp) +{ +CryptoDevBackendVhostUser *s = +CRYPTODEV_BACKEND_VHOST_USER (obj); + +if (s->opened) { +error_setg (errp,"Property 'memory-isolation' can no longer be set" ); + }else { + s->memory_isolation = value; + } +} + +static bool cryptodev_vhost_user_get_mem_isolation (Object *obj,Error **errp) +{ +CryptoDevBackendVhostUser *s = +CRYPTODEV_BACKEND_VHOST_USER (obj); + +return s->memory_isolation; +} +static void cryptodev_vhost_user_class_init (ObjectClass *oc,const void *data) {
@@ -407,6 +429,10 @@ cryptodev_vhost_user_class_init(ObjectClass *oc, const void *data) cryptodev_vhost_user_get_chardev, cryptodev_vhost_user_set_chardev); +object_class_property_add_bool (oc,"memory-isolation" , + cryptodev_vhost_user_get_mem_isolation, + cryptodev_vhost_user_set_mem_isolation); + }static const TypeInfo cryptodev_vhost_user_info = {
qapi/qom.json +7 -1
@@ -350,11 +350,17 @@ # @chardev: the name of a Unix domain socket character device that # connects to the vhost-user server # +# @memory-isolation: disable direct access from vhost-user back-end +# to guest memory. The back-end will instead access data via +# bounce buffers residing in the QEMU virtual address space. +# (default: false) (Since 11.2) +# # Since: 2.12 ## { 'struct': 'CryptodevVhostUserProperties', 'base': 'CryptodevBackendProperties', - 'data': { 'chardev': 'str' }, + 'data': { 'chardev': 'str', + '*memory-isolation': 'bool' }, 'if': 'CONFIG_VHOST_CRYPTO' } ##
Signature · 1 line
2.43.0
RFC PATCH v2 13/13 net/vhost-user: add memory isolation
In reply to Connor KiteAdd a memory-isolation property to NetdevPassOptions and NetDevVhostUserOptions in net.json. This property will be used for vhost-user devices to disable access to guest memory from vhost-user backends.
--- net/passt.c | 5 +++++ net/vhost-user.c | 3 +++ qapi/net.json | 16 ++++++++++++---- 3 files changed, 20 insertions(+), 4 deletions(-)
net/passt.c +5 -0
@@ -741,6 +741,11 @@ int net_init_passt(const Netdev *netdev, const char *name,if (netdev->u.passt.has_vhost_user && netdev->u.passt.vhost_user) {bool memory_isolation = false; +if (netdev->u.passt.has_memory_isolation && + netdev->u.passt.memory_isolation) { + memory_isolation = true; + } +if (net_passt_vhost_user_init (s, memory_isolation, errp) ==-1 ) {qemu_del_net_client (nc);return -1 ;
net/vhost-user.c +3 -0
@@ -477,6 +477,9 @@ int net_init_vhost_user(const Netdev *netdev, const char *name,return -1 ; } + memory_isolation = vhost_user_opts->has_memory_isolation ? + vhost_user_opts->memory_isolation : false; +return net_vhost_user_init (peer,"vhost_user" , name, chr, queues, memory_isolation); }
qapi/net.json +12 -4
@@ -213,6 +213,9 @@ # # @param: parameter to pass to passt command # +# @memory-isolation: isolate guest memory from vhost-user back-end +# (default: false) (Since 11.2) +# # Since: 10.1 ## { 'struct': 'NetdevPasstOptions',
@@ -250,7 +253,8 @@ '*ipv6': 'bool', '*tcp-ports': ['PasstPortForward'], '*udp-ports': ['PasstPortForward'], - '*param': ['PasstParameter'] }, + '*param': ['PasstParameter'], + '*memory-isolation': 'bool'}, 'if': 'CONFIG_PASST' } ##
@@ -685,13 +689,17 @@ # @queues: number of queues to be created for multiqueue vhost-user # (default: 1) (Since 2.5) # +# @memory-isolation: isolate guest memory from vhost-user back-end +# (default: false) (Since 11.2) +# # Since: 2.1 ## { 'struct': 'NetdevVhostUserOptions', 'data': { - 'chardev': 'str', - '*vhostforce': 'bool', - '*queues': 'int' } } + 'chardev': 'str', + '*vhostforce': 'bool', + '*queues': 'int', + '*memory-isolation': 'bool' } } ## # @NetdevVhostVDPAOptions:
Signature · 1 line
2.43.0
Re: [PATCH RFC v2 08/13] hw/virtio/vhost-user: send isolation regions to device
In reply to Connor KiteQuoted 160 lines · Connor Kite
Adds features to fill a
vhost_user_set_mem_tablemessage with the addresses of isolation memory regions corresponding to bounce buffers and vrings.Signed-off-by Connor Kite <[email protected]>--- hw/virtio/vhost-user.c | 118 ++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 117 insertions(+), 1 deletion(-)hw/virtio/vhost-user.c +107
-1@@ -1140,7 +1140,77 @@ static void cleanup_isolation_regions(struct vhost_dev *dev) } } -__attribute__((unused)) +typedef struct { +VhostUserMsg *msg; +struct vhost_user *u; +int *fds; +size_t fds_size; +uint64_t vring_iova; +size_t vring_size; +bool vring_node_visited; +size_t *idx; +}IOVATreeTraversalArgs ; + +static gboolean vhost_user_fill_msg_reg_from_tree (gpointer key, +gpointer value, +gpointer data) +{ +IOVATreeTraversalArgs *args = data; +struct vhost_user *u; +VhostUserMsg *msg = args->msg; +DMAMap *map = key; +uint64_t offset; + +assert (args && key && value); +if (!args->vring_node_visited) { + args->vring_node_visited = true; +return false; + } + + u = args->u; +assert (*args->idx < args->fds_size); + + args->fds[*args->idx] = args->u->iso_mem_ctx.fd; + +/* +* If the number of regions is fixed, it would be wasteful to use one for +* only the vrings. The first vhost_iova_tree element is always +* reserved for the vrings, so we can simply combine the first and second +* elements, which are contiguous in IOVA space, when sending regions to +* the backend. +*/ +if (*args->idx ==0 ) { + offset = u->iso_mem_ctx.vring_hva_addr - u->iso_mem_ctx.shared_mem_addr; + msg->payload.memory.regions[*args->idx].userspace_addr = + args->vring_iova; +/* +* The size from the iova tree is inclusive, so 1 is added to it. +* args->vring_size is exclusive, so no addition is required. +*/ + msg->payload.memory.regions[*args->idx].memory_size = + args->vring_size + map->size +1 ; + msg->payload.memory.regions[*args->idx].guest_phys_addr = + args->vring_iova; + msg->payload.memory.regions[*args->idx].mmap_offset = offset; + }else { +/* Use 128 bit operation in unlikely case of negative iso_iova_offset */ + offset =int128_get64 (int128_add (int128_make64 (map->iova), + u->iso_mem_ctx.iso_iova_offset)) - + (uint64_t )u->iso_mem_ctx.shared_mem_addr; + + msg->payload.memory.regions[*args->idx].userspace_addr = map->iova; + msg->payload.memory.regions[*args->idx].memory_size = map->size +1 ; + msg->payload.memory.regions[*args->idx].guest_phys_addr = map->iova; + msg->payload.memory.regions[*args->idx].mmap_offset = offset; + } + +assert (offset + msg->payload.memory.regions[*args->idx].memory_size <= + u->iso_mem_ctx.size); + (*args->idx)++; + +return false; +} +static int init_isolation_regions (struct vhost_dev *dev,VhostUserMsg *msg,int *fds,size_t *fd_num)@@ -1159,6 +1229,7 @@ static int init_isolation_regions(struct vhost_dev *dev,DMAMap *map;DMAMap vring_map;int r; +IOVATreeTraversalArgs trav_args; msg->hdr.request =VHOST_USER_SET_MEM_TABLE ;@@ -1244,6 +1315,27 @@ static int init_isolation_regions(struct vhost_dev *dev, } } + *fd_num =0 ; + trav_args.idx = fd_num; + trav_args.fds = fds; + trav_args.msg = msg; + trav_args.u = u; + trav_args.vring_iova = vring_map.iova; + trav_args.vring_size = total_vring_size; + trav_args.fds_size = nregions; + trav_args.vring_node_visited = false; + +vhost_iova_tree_foreach (u->iso_mem_ctx.tree, + vhost_user_fill_msg_reg_from_tree, &trav_args); + + msg->payload.memory.nregions = *fd_num; + +assert (*fd_num == nregions); + + msg->hdr.size =sizeof (msg->payload.memory.nregions); + msg->hdr.size +=sizeof (msg->payload.memory.padding); + msg->hdr.size += *fd_num *sizeof (VhostUserMemoryRegion); +return 0 ; }@@ -1251,6 +1343,7 @@ static int vhost_user_set_mem_table(struct vhost_dev *dev, struct vhost_memory *mem) {struct vhost_user *u = dev->opaque; +bool memory_isolation = u->user->memory_isolation;int fds[VHOST_MEMORY_BASELINE_NREGIONS ];size_t fd_num =0 ;bool do_postcopy = u->postcopy_listen && u->postcopy_fd.handler;@@ -1262,6 +1355,11 @@ static int vhost_user_set_mem_table(struct vhost_dev *dev,int ret;if (do_postcopy) { +/* Postcopy is not supported with memory isolation yet */ +if (memory_isolation) { +return -1 ; + } +/* * Postcopy has enough differences that it's best done in it's own * version @@ -1278,6 +1376,24 @@ static int vhost_user_set_mem_table(struct vhost_dev *dev, msg.hdr.flags |=VHOST_USER_NEED_REPLY_MASK ; } +if (memory_isolation) { + ret =init_isolation_regions (dev, &msg, fds, &fd_num); +if (ret <0 ) { +return ret; + } + + ret =vhost_user_write (dev, &msg, fds, fd_num); +if (ret <0 ) {
hw/virtio/vhost-user.c static int vhost_user_set_mem_table(struct vhost_dev *dev, · line 1396
Quoted 10 lines
hw/virtio/vhost-user.c +10
-0+return ret; + } + +if (reply_supported) { +return process_message_reply (dev, &msg); + } + +return 0 ; + } +
This bypasses vhost_user_fill_set_mem_table_msg() below and suppresses the error saying: "Failed initializing vhost-user memory map, consider using -object memory-backend-file share=on"
However, vhost-user doesn't work even with memory isolation in such a case because vhost_user_no_private_memslots() always returns true and that makes vhost_section() filter private memory out. This restriction is unnecessary with memory isolation and can be removed instead of restoring the error.
This also lacks handling of VHOST_USER_PROTOCOL_F_CONFIGURE_MEM_SLOTS, and will overflow fds and VhostUserMemory::regions when VHOST_USER_GET_MAX_MEM_SLOTS is larger than VHOST_MEMORY_BASELINE_NREGIONS.
Regards,
Akihiko Odaki
Quoted 4 lines
hw/virtio/vhost-user.c +0
-0if (config_mem_slots) { ret =vhost_user_add_remove_regions (dev, &msg, reply_supported, false);if (ret <0 ) {
Re: [PATCH RFC v2 09/13] hw/virtio/vhost-user: add shadow virtqueues and eventfd intercepts
In reply to Connor KiteQuoted 24 lines · Connor Kite
Adds shadow virtqueues that will eventually be used to transfer data between device and host via bounce buffers when isolation mode is active. The svqs are initalized, and eventfd assignments are intercepted so that notifications come to svqs first before the guest or backend receive them.
Signed-off-by Connor Kite <[email protected]>--- hw/virtio/vhost-user.c | 136 ++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 119 insertions(+), 17 deletions(-)hw/virtio/vhost-user.c +1
-0@@ -18,6 +18,7 @@#include "hw/virtio/vhost-backend.h" #include "hw/virtio/virtio.h" #include "hw/virtio/virtio-net.h" +#include "hw/virtio/vhost-shadow-virtqueue.h" #include "hw/virtio/vhost-iova-tree.h" #include "chardev/char-fe.h" #include "io/channel-socket.h"
hw/virtio/vhost-user.c typedef struct { · line 335
Quoted 4 lines
hw/virtio/vhost-user.c +1
-0@@ -331,6 +332,7 @@ typedef struct {size_t size;/* size of the mapped shared memory */ int fd;/* descriptor of anonymous file backing shared iso region */ Int128 iso_iova_offset;/* translation from IOVA to hva of iso region */ +GPtrArray *shadow_vqs;/* shadow vqs with vrings in iso region*/
A whitespace problem remains here.
Quoted 17 lines
hw/virtio/vhost-user.c +9
-1} IsolationModeCtx;struct vhost_user {@@ -1128,15 +1130,38 @@ static int vhost_user_set_mem_table_postcopy(struct vhost_dev *dev,return 0 ; } -static void cleanup_isolation_regions (struct vhost_dev *dev) +static void vhost_user_svq_cleanup (struct vhost_user *u,bool reset) +{ +VhostShadowVirtqueue *svq; +for (int i =0 ; i < u->iso_mem_ctx.shadow_vqs->len; i++) { + svq =g_ptr_array_index (u->iso_mem_ctx.shadow_vqs, i); +vhost_svq_stop (svq); +event_notifier_cleanup (&svq->hdev_call); +event_notifier_cleanup (&svq->hdev_kick); + }
hw/virtio/vhost-user.c static int vhost_user_set_mem_table_postcopy(struct vhost_dev *dev, · line 1151
Quoted 10 lines
hw/virtio/vhost-user.c +7
-0+ +if (!reset) { +g_ptr_array_free (u->iso_mem_ctx.shadow_vqs, true); + } +} + +static void cleanup_isolation_regions (struct vhost_dev *dev,bool reset) {struct vhost_user *u = dev->opaque;if (u->iso_mem_ctx.shared_mem_addr) {
If vhost_dev_init() fails after vhost_user_init_svq(), shadow_vqs is present but shared_mem_addr is not because init_isolation_regions() is not called yet. shadow_vqs will be leaked then.
hw/virtio/vhost-user.c static int vhost_user_set_mem_table_postcopy(struct vhost_dev *dev, · line 1158
Quoted 7 lines
hw/virtio/vhost-user.c +3
-0+vhost_user_svq_cleanup (u, reset);vhost_iova_tree_delete (u->iso_mem_ctx.tree);qemu_memfd_free (u->iso_mem_ctx.shared_mem_addr, u->iso_mem_ctx.size, u->iso_mem_ctx.fd); + +GPtrArray *temp = u->iso_mem_ctx.shadow_vqs;
This is a mixed declaration prohibited in docs/devel/style.rst
hw/virtio/vhost-user.c static int vhost_user_set_mem_table_postcopy(struct vhost_dev *dev, · line 1161
Quoted 3 lines
hw/virtio/vhost-user.c +2
-0memset (&u->iso_mem_ctx,0 ,sizeof (IsolationModeCtx)); + +if (!reset) {
This condition is inverted. When reset is true, vhost_user_svq_cleanup() retains the array so the pointer to it should be kept.
Quoted 57 lines
hw/virtio/vhost-user.c +14
-5+ u->iso_mem_ctx.shadow_vqs = temp; + }> + } }@@ -1234,7 +1259,7 @@ static int init_isolation_regions(struct vhost_dev *dev, msg->hdr.request =VHOST_USER_SET_MEM_TABLE ;/* In case of reset, clear old regions */ -cleanup_isolation_regions (dev); +cleanup_isolation_regions (dev, true);/* Gather information for bounce buffers to be mapped */ for (u_int32_t i =0 ; i < nregions; i++) {@@ -1267,7 +1292,7 @@ static int init_isolation_regions(struct vhost_dev *dev,if (err) {error_report_err (err); -cleanup_isolation_regions (dev); +cleanup_isolation_regions (dev, false);return -1 ; }@@ -1295,7 +1320,7 @@ static int init_isolation_regions(struct vhost_dev *dev, (hwaddr)u->iso_mem_ctx.shared_mem_addr);if (r !=IOVA_OK ) { -cleanup_isolation_regions (dev); +cleanup_isolation_regions (dev, false);return r; }@@ -1310,7 +1335,7 @@ static int init_isolation_regions(struct vhost_dev *dev, dev->mem->regions[i].guest_phys_addr);if (r !=IOVA_OK ) { -cleanup_isolation_regions (dev); +cleanup_isolation_regions (dev, false);return r; } }@@ -1738,11 +1763,49 @@ static int vhost_set_vring_file(struct vhost_dev *dev,return 0 ; } +static int vhost_user_get_vq_index (struct vhost_dev *dev,int idx) +{ +assert (idx >= dev->vq_index && idx < dev->vq_index + dev->nvqs); + +return idx; +} +static int vhost_user_set_vring_kick (struct vhost_dev *dev,struct vhost_vring_file *file) { -int ret =vhost_set_vring_file (dev,VHOST_USER_SET_VRING_KICK , file); +struct vhost_user *u = dev->opaque;
hw/virtio/vhost-user.c static int vhost_set_vring_file(struct vhost_dev *dev, · line 1786
Quoted 10 lines
hw/virtio/vhost-user.c +10
-0+int svq_idx = file->index - dev->vq_index; +VhostShadowVirtqueue *svq =NULL ; +struct vhost_vring_file vr_file = *file; +int ret; + +vhost_user_get_vq_index (dev, file->index);/* bounds checking */ + +if (u->user->memory_isolation) { + svq =g_ptr_array_index (u->iso_mem_ctx.shadow_vqs, svq_idx); +vhost_svq_set_svq_kick_fd (svq, file->fd);
The svq->svq_kick EventNotifier is left set in the error paths.
Regards,
Akihiko Odaki
Quoted 70 lines
hw/virtio/vhost-user.c +45
-3+ +if (file->fd !=-1 ) { +if (!svq->hdev_kick.initialized) { + ret =event_notifier_init (&svq->hdev_kick,0 ); +if (ret <0 ) { +event_notifier_cleanup (&svq->hdev_kick); +error_report ("Failed to create kick event notifier" ); +return ret; + } + } + + vr_file.fd =event_notifier_get_fd (&svq->hdev_kick); + }else { +event_notifier_cleanup (&svq->hdev_kick); + } + } + + ret =vhost_set_vring_file (dev,VHOST_USER_SET_VRING_KICK , &vr_file);if (ret <0 ) { +if (svq !=NULL ) { +event_notifier_cleanup (&svq->hdev_kick); + }return ret; }@@ -1750,15 +1813,18 @@ static int vhost_user_set_vring_kick(struct vhost_dev *dev,* Inject a kick in case the back-end only starts vring processing upon * receiving a kick. The spec suggests this to improve compatibility. */ -if (file->fd !=-1 ) { +if (vr_file.fd !=-1 ) {uint64_t val =1 ;ssize_t nwritten;do { - nwritten =write (file->fd, &val,sizeof (val)); + nwritten =write (vr_file.fd, &val,sizeof (val)); }while (nwritten <0 && errno ==EINTR );if (nwritten <0 && errno !=EAGAIN /* back-end can already read */ ) { +if (svq !=NULL ) { +event_notifier_cleanup (&svq->hdev_kick); + }return -errno; } }@@ -1769,7 +1835,35 @@ static int vhost_user_set_vring_kick(struct vhost_dev *dev,static int vhost_user_set_vring_call (struct vhost_dev *dev,struct vhost_vring_file *file) { -return vhost_set_vring_file (dev,VHOST_USER_SET_VRING_CALL , file); +struct vhost_user *u = dev->opaque; +int svq_idx = file->index - dev->vq_index; +VhostShadowVirtqueue *svq =NULL ; +struct vhost_vring_file vr_file = *file; +int ret; + +vhost_user_get_vq_index (dev, file->index);/* bounds checking */ + +if (u->user->memory_isolation) { + svq =g_ptr_array_index (u->iso_mem_ctx.shadow_vqs, svq_idx); +vhost_svq_set_svq_call_fd (svq, file->fd); + +if (file->fd !=-1 ) { +if (!svq->hdev_call.initialized) { + ret =event_notifier_init (&svq->hdev_call,0 ); +if (ret <0 ) { +event_notifier_cleanup (&svq->hdev_call); +error_report ("Failed to create call event notifier" ); +return ret;
hw/virtio/vhost-user.c static int vhost_user_set_vring_kick(struct vhost_dev *dev, · line 1866
Quoted 10 lines
hw/virtio/vhost-user.c +10
-0+ } + } + + vr_file.fd =event_notifier_get_fd (&svq->hdev_call); + }else { +event_notifier_cleanup (&svq->hdev_call); + } + } + +return vhost_set_vring_file (dev,VHOST_USER_SET_VRING_CALL , &vr_file);
Clean up svq->hdev_call when this fails.
Quoted 55 lines
hw/virtio/vhost-user.c +16
-8} static int vhost_user_set_vring_err(struct vhost_dev *dev,@@ -2763,6 +2857,17 @@ static int vhost_user_postcopy_notifier(NotifierWithReturn *notifier,return 0 ; } +static void vhost_user_init_svq (struct vhost_dev *dev,struct vhost_user *u) +{ +/*Modified from vhost-vdpa*/ + u->iso_mem_ctx.shadow_vqs =g_ptr_array_new_full (dev->nvqs, vhost_svq_free); +for (int i =0 ; i < dev->nvqs; i++) { +VhostShadowVirtqueue *svq; + svq =vhost_svq_new (NULL ,NULL ); +g_ptr_array_add (u->iso_mem_ctx.shadow_vqs, svq); + } +} +static int vhost_user_backend_init (struct vhost_dev *dev,void *opaque,Error **errp) {@@ -2907,6 +3012,10 @@ static int vhost_user_backend_init(struct vhost_dev *dev, void *opaque, u->postcopy_notifier.notify = vhost_user_postcopy_notifier;postcopy_add_notifier (&u->postcopy_notifier); +if (vus->memory_isolation) { +vhost_user_init_svq (dev, u); + } +return 0 ; }@@ -2935,20 +3044,13 @@ static int vhost_user_backend_cleanup(struct vhost_dev *dev)g_free (u->region_rb_offset); u->region_rb_offset =NULL ; u->region_rb_len =0 ; -cleanup_isolation_regions (dev); +cleanup_isolation_regions (dev, false);g_free (u); dev->opaque =0 ;return 0 ; } -static int vhost_user_get_vq_index (struct vhost_dev *dev,int idx) -{ -assert (idx >= dev->vq_index && idx < dev->vq_index + dev->nvqs); - -return idx; -} -static int vhost_user_memslots_limit (struct vhost_dev *dev) {struct vhost_user *u = dev->opaque;
Re: [PATCH RFC v2 04/13] hw/virtio/vhost-shadow-virtqueue: used callback
In reply to Connor KiteQuoted 14 lines · Connor Kite
Adds a callback to shadow virtqueues in order to enable non-default processing of used vring elements from the device.
Signed-off-by Connor Kite <[email protected]>--- hw/virtio/vhost-shadow-virtqueue.c | 9 +++++++++ hw/virtio/vhost-shadow-virtqueue.h | 16 ++++++++++++++++ 2 files changed, 25 insertions(+)hw/virtio/vhost-shadow-virtqueue.c +0
-0
hw/virtio/vhost-shadow-virtqueue.c static void vhost_svq_flush(VhostShadowVirtqueue *svq, · line 682
Quoted 8 lines
hw/virtio/vhost-shadow-virtqueue.c +5
-0@@ -675,6 +675,15 @@ static void vhost_svq_flush(VhostShadowVirtqueue *svq,break ; } +if (svq->ops && svq->ops->used_callback) { +int r = svq->ops->used_callback (svq, elem, svq->ops_opaque); + +if (r <0 ) { +/* VQ or handler is broken. Do not set guest notifier */
This comment is extraneous. It is obvious that event_notifier_set() below is not called, and it is same with the existing error path below.
What matters here is the difference with the existing error path. Why doesn't it call virtqueue_fill() nor virtqueue_flush()? They need to be addressed here.
Regards,
Akihiko Odaki
Quoted 37 lines
hw/virtio/vhost-shadow-virtqueue.c +4
-0+return ; + } + } +if (unlikely (i >= svq->vring.num)) { qemu_log_mask(LOG_GUEST_ERROR, "More than %u used buffers obtained in a %u size SVQ",hw/virtio/vhost-shadow-virtqueue.h +16
-0@@ -56,8 +56,24 @@ typedef int (*VirtQueueAvailCallback)(VhostShadowVirtqueue *svq, VirtQueueElement *elem, void *vq_callback_opaque); +/** +* Callback to handle a used buffer +* +* @svq: Shadow virtqueue +* @elem: Element placed in the queue by the device +* @vq_callback_opaque: Used to pass arguments to callback +* +* Returns 0 if the vq is running as expected. Returns a negative errno on +* failure. The callback should not add used elements to the vq shadowed +* by the svq as that is done separately after the callback returns. +*/ +typedef int (*VirtQueueUsedCallback )(VhostShadowVirtqueue *svq, +VirtQueueElement *elem, +void *vq_callback_opaque); +typedef struct VhostShadowVirtqueueOps {VirtQueueAvailCallback avail_handler; +VirtQueueUsedCallback used_callback; }VhostShadowVirtqueueOps ;/* Shadow virtqueue to relay notifications */
Re: [PATCH RFC v2 13/13] net/vhost-user: add memory isolation
In reply to Connor KiteQuoted 4 lines · Connor Kite
Add a memory-isolation property to NetdevPassOptions and NetDevVhostUserOptions in net.json. This property will be used for vhost-user devices to disable access to guest memory from vhost-user backends.
The cover letter says multiqueue is not supported but the code just continues with multiqueue and breaks.
Regards,
Akihiko Odaki
Quoted 84 lines
Signed-off-by Connor Kite <[email protected]>--- net/passt.c | 5 +++++ net/vhost-user.c | 3 +++ qapi/net.json | 16 ++++++++++++---- 3 files changed, 20 insertions(+), 4 deletions(-)net/passt.c +5
-0@@ -741,6 +741,11 @@ int net_init_passt(const Netdev *netdev, const char *name,if (netdev->u.passt.has_vhost_user && netdev->u.passt.vhost_user) {bool memory_isolation = false; +if (netdev->u.passt.has_memory_isolation && + netdev->u.passt.memory_isolation) { + memory_isolation = true; + } +if (net_passt_vhost_user_init (s, memory_isolation, errp) ==-1 ) {qemu_del_net_client (nc);return -1 ;net/vhost-user.c +3
-0@@ -477,6 +477,9 @@ int net_init_vhost_user(const Netdev *netdev, const char *name,return -1 ; } + memory_isolation = vhost_user_opts->has_memory_isolation ? + vhost_user_opts->memory_isolation : false; +return net_vhost_user_init (peer,"vhost_user" , name, chr, queues, memory_isolation); }qapi/net.json +12
-4@@ -213,6 +213,9 @@ # # @param: parameter to pass to passt command # +# @memory-isolation: isolate guest memory from vhost-user back-end +# (default: false) (Since 11.2) +# # Since: 10.1 ## { 'struct': 'NetdevPasstOptions',@@ -250,7 +253,8 @@ '*ipv6': 'bool', '*tcp-ports': ['PasstPortForward'], '*udp-ports': ['PasstPortForward'], - '*param': ['PasstParameter'] }, + '*param': ['PasstParameter'], + '*memory-isolation': 'bool'}, 'if': 'CONFIG_PASST' } ##@@ -685,13 +689,17 @@ # @queues: number of queues to be created for multiqueue vhost-user # (default: 1) (Since 2.5) # +# @memory-isolation: isolate guest memory from vhost-user back-end +# (default: false) (Since 11.2) +# # Since: 2.1 ## { 'struct': 'NetdevVhostUserOptions', 'data': { - 'chardev': 'str', - '*vhostforce': 'bool', - '*queues': 'int' } } + 'chardev': 'str', + '*vhostforce': 'bool', + '*queues': 'int', + '*memory-isolation': 'bool' } } ## # @NetdevVhostVDPAOptions:
Re: [PATCH RFC v2 07/13] hw/virtio/vhost-user: create isolation region
In reply to Connor KiteQuoted 37 lines · Connor Kite
If memory isolation mode is active for the vhost-user device adds features to:
- Gather the size required for bounce buffers and vrings in shared isolation region
- Allocate the required space in an anonymous file
- Create a vhost-iova-tree with space to map entire isolation region
- Map guest memory regions and shared vrings into the tree
- Release these resources upon backend cleanupSigned-off-by Connor Kite <[email protected]>--- hw/virtio/vhost-user.c | 136 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 136 insertions(+)hw/virtio/vhost-user.c +2
-0@@ -18,6 +18,7 @@#include "hw/virtio/vhost-backend.h" #include "hw/virtio/virtio.h" #include "hw/virtio/virtio-net.h" +#include "hw/virtio/vhost-iova-tree.h" #include "chardev/char-fe.h" #include "io/channel-socket.h" #include "system/kvm.h" @@ -25,6 +26,7 @@#include "qemu/main-loop.h" #include "qemu/uuid.h" #include "qemu/sockets.h" +#include "qemu/memfd.h" #include "system/runstate.h" #include "system/cryptodev.h" #include "migration/postcopy-ram.h" @@ -320,6 +322,17 @@ static VhostUserMsg m __attribute__ ((unused));/* The version of the protocol we support */ #define VHOST_USER_VERSION (0x1)
hw/virtio/vhost-user.c static VhostUserMsg m __attribute__ ((unused)); · line 333
Quoted 10 lines
hw/virtio/vhost-user.c +9
-0+/* Memory region shared with back-end when memory-isolation is active */ +typedef struct { + void *shared_mem_addr; /* mapped shared memory */ + VhostIOVATree *tree; /* controls mapping of regions into IOVA space */ + void *vring_hva_addr; /* beginning of vring region in shared memory */ + size_t vring_region_size; /* amount of shared memory reserved for vrings */ + size_t size; /* size of the mapped shared memory */ + int fd; /* descriptor of anonymous file backing shared iso region */ + Int128 iso_iova_offset; /* translation from IOVA to hva of iso region */
This Int128 usage is misleading. The value derived from iso_iova_offset is always consumed with int128_get64(), which asserts the value fits in 64-bit. But we actually need to enforce that the address before translation resides in the shared memory. So making iso_iova_offset Int128 is not a good way to assert the real invariant.
Furthermore, "[PATCH RFC v2 10/13] hw/virtio/vhost-user: handle data movement with shadow vqs" has:
ptrdiff_t offset = u->iso_mem_ctx.iso_iova_offset;
If defined(CONFIG_INT128) && !defined(CONFIG_TCG_INTERPRETER), this will overflow with u->iso_mem_ctx.iso_iova_offset > PTRDIFF_MAX. Otherwise, Int128 will be a struct, which causes a compilation error.
uintptr_t is sufficient if the invariant is enforced in some alternative way. A negative offset would be represented as wraparound, and a positive one will never result in wraparound. Just always ensure the address before translation resides in the shared memory.
Regards,
Akihiko Odaki
Quoted 37 lines
hw/virtio/vhost-user.c +23
-0+} IsolationModeCtx; +struct vhost_user {struct vhost_dev *dev;/* Shared between vhost devs of the same virtio device */ @@ -353,6 +366,9 @@ struct vhost_user {* by the backend (see @features). */ uint64_t protocol_features; + +/* Data specfic to isolated memory mode */ +IsolationModeCtx iso_mem_ctx; };struct scrub_regions {@@ -1112,6 +1128,125 @@ static int vhost_user_set_mem_table_postcopy(struct vhost_dev *dev,return 0 ; } +static void cleanup_isolation_regions (struct vhost_dev *dev) +{ +struct vhost_user *u = dev->opaque; +if (u->iso_mem_ctx.shared_mem_addr) { +vhost_iova_tree_delete (u->iso_mem_ctx.tree); +qemu_memfd_free (u->iso_mem_ctx.shared_mem_addr, + u->iso_mem_ctx.size, + u->iso_mem_ctx.fd); +memset (&u->iso_mem_ctx,0 ,sizeof (IsolationModeCtx)); + } +} + +__attribute__((unused)) +static int init_isolation_regions (struct vhost_dev *dev, +VhostUserMsg *msg, +int *fds,size_t *fd_num) +{ +Error *err =NULL ;
hw/virtio/vhost-user.c static int vhost_user_set_mem_table_postcopy(struct vhost_dev *dev, · line 1158
Quoted 10 lines
hw/virtio/vhost-user.c +10
-0+struct vhost_user *u = dev->opaque; +uint32_t nregions = dev->mem->nregions; + + g_autofree DMAMap *buffer_regions = g_new0(DMAMap, nregions); +size_t buffer_reg_size =0 ; +size_t total_vring_size =0 ; +size_t total_mmap_size; +char *reg_name; +uint64_t first_IOVA_addr; +uint64_t last_IOVA_addr;
Variables should be lower_case_with_underscores as per:docs/devel/style.rst
Quoted 103 lines
hw/virtio/vhost-user.c +92
-0+DMAMap *map; +DMAMap vring_map; +int r; + + msg->hdr.request =VHOST_USER_SET_MEM_TABLE ; + +/* In case of reset, clear old regions */ +cleanup_isolation_regions (dev); + +/* Gather information for bounce buffers to be mapped */ +for (u_int32_t i =0 ; i < nregions; i++) { +hwaddr size =ROUND_UP (dev->mem->regions[i].memory_size, +qemu_real_host_page_size ()); + buffer_regions[i].size = size -1 ; + buffer_regions[i].perm =IOMMU_RW ; + + buffer_reg_size += size; + } + +/* Get space required for all vrings */ +for (int i =0 ; i < dev->nvqs; i++) { +VirtQueue *vq =virtio_get_queue (dev->vdev, dev->vq_index + i); + total_vring_size +=vhost_svq_vring_total_size (dev->vdev, vq); + } + + total_mmap_size = buffer_reg_size + total_vring_size; + u->iso_mem_ctx.size = total_mmap_size; + +/* Allocate and map an anonymous file to hold the isolation region */ + reg_name =g_strconcat ("iso_mem_" , dev->vdev->name,NULL ); + u->iso_mem_ctx.shared_mem_addr =qemu_memfd_alloc (reg_name, + total_mmap_size, +F_SEAL_GROW |F_SEAL_SHRINK |F_SEAL_SEAL , + &u->iso_mem_ctx.fd, &err); + +assert (u->iso_mem_ctx.fd >=0 ); +g_free (reg_name); + +if (err) { +error_report_err (err); +cleanup_isolation_regions (dev); +return -1 ; + } + +/* vhost-iova-tree enforces non-zero lower address */ + first_IOVA_addr =qemu_real_host_page_size (); + last_IOVA_addr = first_IOVA_addr + total_mmap_size -1 ; +assert (last_IOVA_addr > first_IOVA_addr); + +/* Use 128-bit operation in case of large negative offset */ + u->iso_mem_ctx.iso_iova_offset = +int128_sub (int128_make64 ((uint64_t )u->iso_mem_ctx.shared_mem_addr), +int128_make64 (first_IOVA_addr)); + +/* +* Instantiates iova tree sized to map bounce buffers and vrings to the +* isolation region in host va. +*/ + u->iso_mem_ctx.tree = +vhost_iova_tree_new (first_IOVA_addr, last_IOVA_addr); + +/* Map vrings into IOVA tree */ + vring_map.perm =IOMMU_RW ; + vring_map.size = total_vring_size -1 ; + r =vhost_iova_tree_map_alloc (u->iso_mem_ctx.tree, &vring_map, + (hwaddr )u->iso_mem_ctx.shared_mem_addr); + +if (r !=IOVA_OK ) { +cleanup_isolation_regions (dev); +return r; + } + + u->iso_mem_ctx.vring_hva_addr = (void *)int128_get64 ( +int128_add (int128_make64 (vring_map.iova), + u->iso_mem_ctx.iso_iova_offset)); + u->iso_mem_ctx.vring_region_size = total_vring_size; + +for (int i =0 ; i < nregions; i++) { + map = &buffer_regions[i]; + r =vhost_iova_tree_map_alloc_gpa (u->iso_mem_ctx.tree, map, + dev->mem->regions[i].guest_phys_addr); + +if (r !=IOVA_OK ) { +cleanup_isolation_regions (dev); +return r; + } + } + +return 0 ; +} +static int vhost_user_set_mem_table (struct vhost_dev *dev,struct vhost_memory *mem) {@@ -2684,6 +2819,7 @@ static int vhost_user_backend_cleanup(struct vhost_dev *dev)g_free (u->region_rb_offset); u->region_rb_offset =NULL ; u->region_rb_len =0 ; +cleanup_isolation_regions (dev);g_free (u); dev->opaque =0 ;
Re: [PATCH RFC v2 10/13] hw/virtio/vhost-user: handle data movement with shadow vqs
In reply to Connor KiteQuoted 73 lines · Connor Kite
- Add start logic for shadow virtqueues, which sets vring addresses.
- Update logic for sending vring addresses to backend to point to the shadow vrings when isolation mode is active.
- Implement handlers for intercepted avail and used descriptors. These handlers copy buffer contents between bounce buffers in the isolation region and the buffers made available by the guest
- Implement logic to stop svqsSigned-off-by Connor Kite <[email protected]>--- hw/virtio/vhost-shadow-virtqueue.c | 2 +- hw/virtio/vhost-shadow-virtqueue.h | 1 + hw/virtio/vhost-user.c | 292 ++++++++++++++++++++++++++++++++++++- 3 files changed, 286 insertions(+), 9 deletions(-)hw/virtio/vhost-shadow-virtqueue.c +1
-1@@ -350,7 +350,7 @@ int vhost_svq_add(VhostShadowVirtqueue *svq, const struct iovec *out_sg, }/* Convenience wrapper to add a guest's element to SVQ */ -static int vhost_svq_add_element (VhostShadowVirtqueue *svq, +int vhost_svq_add_element (VhostShadowVirtqueue *svq,VirtQueueElement *elem) { return vhost_svq_add(svq, elem->out_sg, elem->out_num, elem->out_addr,hw/virtio/vhost-shadow-virtqueue.h +1
-0@@ -183,6 +183,7 @@ VhostShadowVirtqueue *vhost_svq_new(const VhostShadowVirtqueueOps *ops,void vhost_svq_free (gpointer vq);void vhost_svq_set_base_addr (VhostShadowVirtqueue *svq,void *addr); +int vhost_svq_add_element (VhostShadowVirtqueue *svq,VirtQueueElement *elem);G_DEFINE_AUTOPTR_CLEANUP_FUNC (VhostShadowVirtqueue, vhost_svq_free);hw/virtio/vhost-user.c +25
-0@@ -1364,6 +1364,231 @@ static int init_isolation_regions(struct vhost_dev *dev,return 0 ; } +static inline int vhost_user_get_reg_idx (struct vhost_dev *dev,hwaddr gpa) +{ +int i; +struct vhost_memory_region *reg; + +for (i =0 ; i < dev->mem->nregions; i++) { + reg = dev->mem->regions + i; + +if (gpa >= reg->guest_phys_addr && + reg->guest_phys_addr + reg->memory_size > gpa) { +return i; + } + } + +return -1 ; +} + +static int vhost_user_svq_handle_used (VhostShadowVirtqueue *svq, +VirtQueueElement *elem, + void *opaque)> +{ +uint64_t offset; +void *dst; +void *src; +size_t len, rem; +void *reg_last_addr;
hw/virtio/vhost-user.c static int init_isolation_regions(struct vhost_dev *dev, · line 1401
Quoted 10 lines
hw/virtio/vhost-user.c +10
-0+void *reg_first_addr; +struct vhost_dev *dev = opaque; +struct vhost_user *u = dev->opaque; +void *shmem_addr = u->iso_mem_ctx.shared_mem_addr; +size_t shmem_size = u->iso_mem_ctx.size; +const DMAMap *map; +DMAMap needle; +int reg_idx; + +for (int i =0 ; i < elem->in_num; i++) {
vhost_svq_flush() has the len parameter, but this callback does not take it, and consequently copies every writable iovec in full, which may not be ideal.
Quoted 140 lines
hw/virtio/vhost-user.c +140
-0+ needle.translated_addr = elem->in_addr[i]; + needle.size = elem->in_sg[i].iov_len -1 ; + map =vhost_iova_tree_find_gpa (svq->iova_tree, &needle); + +if (!map) { +return -EFAULT ; + } + + offset = needle.translated_addr - map->translated_addr; + src = (void *)int128_get64 (int128_add (int128_make64 (map->iova + + offset), u->iso_mem_ctx.iso_iova_offset)); + dst = elem->in_sg[i].iov_base; + len = elem->in_sg[i].iov_len; + +/* Confirm that buffer range is fully within iso region */ +if ((uint64_t )src + len -1 > (uint64_t )shmem_addr + shmem_size -1 || + (uint64_t )src + len <= (uint64_t )src || + (uint64_t )src < (uint64_t )shmem_addr) { + +return -EFAULT ; + } + + reg_idx =vhost_user_get_reg_idx (dev, needle.translated_addr); +if (reg_idx <0 ) { +return -EFAULT ; + } + + reg_first_addr = (void *)dev->mem->regions[reg_idx].userspace_addr; + reg_last_addr = (void *)(dev->mem->regions[reg_idx].userspace_addr + + dev->mem->regions[reg_idx].memory_size -1 ); + +/* Confirm that hva from elem matches expected vhost memory region */ +if (dst < reg_first_addr || dst > reg_last_addr) { +return -EFAULT ; + } + +/* +* copy buffer contents from shared memory into guest memory. If +* the buffer extends across region boundaries, it must be split and +* copied to the correct regions. +*/ +while ((uint64_t )reg_last_addr - (uint64_t )dst +1 < len) { + rem = ((uint64_t )dst + len -1 ) - (uint64_t )reg_last_addr; + len -= rem; +memcpy (dst, src, len); + + reg_idx++; +if (reg_idx >= dev->mem->nregions) { +return -EFAULT ; + } + + src = (void *)((uint64_t )src + len); + dst = (void *)dev->mem->regions[reg_idx].userspace_addr; + len = rem; + reg_first_addr = (void *)dev->mem->regions[reg_idx].userspace_addr; + reg_last_addr = (void *)(dev->mem->regions[reg_idx].userspace_addr + + dev->mem->regions[reg_idx].memory_size -1 ); + } + +memcpy (dst, src, len); + } + +return 0 ; +} + +static int vhost_user_svq_handle_avail (VhostShadowVirtqueue *svq, +VirtQueueElement *elem, +void *opaque) +{ +hwaddr offset; +const DMAMap *map; +DMAMap needle; +void *dst; +void *src; +void *reg_first_addr; +void *reg_last_addr; +size_t len, rem; +struct vhost_dev *dev = opaque; +struct vhost_user *u = dev->opaque; +void *shmem_addr = u->iso_mem_ctx.shared_mem_addr; +size_t shmem_size = u->iso_mem_ctx.size; +int reg_idx; + +for (int i =0 ; i < elem->out_num; i++) { + needle.translated_addr = elem->out_addr[i]; + needle.size = elem->out_sg[i].iov_len -1 ; + map =vhost_iova_tree_find_gpa (svq->iova_tree, &needle); + +if (!map) { +return -EFAULT ; + } + + offset = needle.translated_addr - map->translated_addr; + dst = (void *)int128_get64 (int128_add (int128_make64 (map->iova + + offset), u->iso_mem_ctx.iso_iova_offset)); + src = elem->out_sg[i].iov_base; + len = elem->out_sg[i].iov_len; + +/* Confirm that buffer range is fully within iso region */ +if ((uint64_t )dst + len -1 > (uint64_t )shmem_addr + shmem_size -1 || + (uint64_t )dst + len <= (uint64_t )dst || + (uint64_t )dst < (uint64_t )shmem_addr) { + +return -EFAULT ; + } + + reg_idx =vhost_user_get_reg_idx (dev, needle.translated_addr); +if (reg_idx <0 ) { +return -EFAULT ; + } + + reg_first_addr = (void *)dev->mem->regions[reg_idx].userspace_addr; + reg_last_addr = (void *)(dev->mem->regions[reg_idx].userspace_addr + + dev->mem->regions[reg_idx].memory_size -1 ); + +/* Confirm that hva from elem matches expected vhost memory region */ +if (src < reg_first_addr || src > reg_last_addr) { +return -EFAULT ; + } + +/* +* copy buffer contents from guest memory into shared memory. If +* the buffer extends across region boundaries, it must be split and +* copied from the correct regions. +*/ +while ((uint64_t )reg_last_addr - (uint64_t )src +1 < len) { + rem = ((uint64_t )src + len -1 ) - (uint64_t )reg_last_addr; + len -= rem; +memcpy (dst, src, len); + + reg_idx++; +if (reg_idx >= dev->mem->nregions) { +return -EFAULT ; + } + + dst = (void *)((uint64_t )dst + len); + src = (void *)dev->mem->regions[reg_idx].userspace_addr; + len = rem; + + reg_first_addr = (void *)dev->mem->regions[reg_idx].userspace_addr;
hw/virtio/vhost-user.c static int init_isolation_regions(struct vhost_dev *dev, · line 1552
Quoted 10 lines
hw/virtio/vhost-user.c +10
-0+ reg_last_addr = (void *)(dev->mem->regions[reg_idx].userspace_addr + + dev->mem->regions[reg_idx].memory_size -1 ); + } + +memcpy (dst, src, len); + } + +vhost_svq_add_element (svq, elem); + +return 0 ;
This dismisses the return value of vhost_svq_add_element() and disables the handling of -ENOSPC in the caller, vhost_handle_guest_kick().
Quoted 43 lines
hw/virtio/vhost-user.c +39
-0+} + +static int vhost_user_get_vq_index (struct vhost_dev *dev,int idx) +{ +assert (idx >= dev->vq_index && idx < dev->vq_index + dev->nvqs); + +return idx; +} + +static int vhost_user_svqs_vring_map (struct vhost_dev *dev) +{ +int ret; +struct vhost_user *u = dev->opaque; +void *vring_base = u->iso_mem_ctx.vring_hva_addr; +uint64_t vring_last = (uint64_t )vring_base + + u->iso_mem_ctx.vring_region_size -1 ; + +for (int i =0 ; i < u->iso_mem_ctx.shadow_vqs->len; i++) { +vhost_user_get_vq_index (dev, dev->vq_index + i);/* bounds checking */ + +VirtQueue *vq =virtio_get_queue (dev->vdev, dev->vq_index + i); +VhostShadowVirtqueue *svq = +g_ptr_array_index (u->iso_mem_ctx.shadow_vqs, i); + +assert ((uint64_t )vring_base + +vhost_svq_vring_total_size (dev->vdev, vq) -1 <= vring_last); + +vhost_svq_set_base_addr (svq, vring_base); + ret =vhost_svq_start (svq, dev->vdev, vq, u->iso_mem_ctx.tree); +if (ret <0 ) { +return ret; + } + vring_base = (void *)((uint64_t )vring_base + +vhost_svq_vring_total_size (dev->vdev, vq)); + } + +return 0 ; +} +static int vhost_user_set_mem_table (struct vhost_dev *dev,struct vhost_memory *mem) {
hw/virtio/vhost-user.c static int vhost_user_set_mem_table(struct vhost_dev *dev, · line 1639
Quoted 8 lines
hw/virtio/vhost-user.c +5
-0@@ -1407,6 +1632,11 @@ static int vhost_user_set_mem_table(struct vhost_dev *dev,return ret; } + ret =vhost_user_svqs_vring_map (dev); +if (ret <0 ) { +return ret; + } +
This leads to vhost_svq_start() calls, that runs: event_notifier_set_handler(&svq->hdev_call, vhost_svq_handle_call)
However, svq->hdev_call may not be properly initialized because init_isolation_regions() above here calls cleanup_isolation_regions(), and that may have cleaned up svq->hdev_call.
Quoted 37 lines
hw/virtio/vhost-user.c +9
-7ret =vhost_user_write (dev, &msg, fds, fd_num);if (ret <0 ) {return ret;@@ -1763,13 +1993,6 @@ static int vhost_set_vring_file(struct vhost_dev *dev,return 0 ; } -static int vhost_user_get_vq_index (struct vhost_dev *dev,int idx) -{ -assert (idx >= dev->vq_index && idx < dev->vq_index + dev->nvqs); - -return idx; -} -static int vhost_user_set_vring_kick (struct vhost_dev *dev,struct vhost_vring_file *file) {@@ -1875,6 +2098,8 @@ static int vhost_user_set_vring_err(struct vhost_dev *dev,static int vhost_user_set_vring_addr (struct vhost_dev *dev,struct vhost_vring_addr *addr) { +struct vhost_user *u = dev->opaque; +ptrdiff_t offset = u->iso_mem_ctx.iso_iova_offset;VhostUserMsg msg = { .hdr.request =VHOST_USER_SET_VRING_ADDR , .hdr.flags =VHOST_USER_VERSION ,@@ -1882,6 +2107,25 @@ static int vhost_user_set_vring_addr(struct vhost_dev *dev, .hdr.size = sizeof(msg.payload.addr), }; +if (u->user->memory_isolation) { +int svq_idx; +VhostShadowVirtqueue *svq; +struct vhost_vring_addr svq_addr; + +vhost_user_get_vq_index (dev, addr->index);/* bounds checking */ + svq_idx = addr->index - dev->vq_index;
hw/virtio/vhost-user.c static int vhost_user_set_vring_addr(struct vhost_dev *dev, · line 2126
Quoted 10 lines
hw/virtio/vhost-user.c +10
-0+ svq =g_ptr_array_index (u->iso_mem_ctx.shadow_vqs, + svq_idx); + + svq_addr.avail_user_addr = (uint64_t )(uintptr_t )svq->vring.avail - + offset; + svq_addr.desc_user_addr = (uint64_t )(uintptr_t )svq->vring.desc - offset; + svq_addr.used_user_addr = (uint64_t )(uintptr_t )svq->vring.used - offset; + svq_addr.index = addr->index; + + msg.payload.addr = svq_addr;
flags and log_guest_addr of svq_addr are left uninitialized and written to the backend. The current compiler’s optional stack-zeroing flag masks this locally, but supported older compilers need explicit initialization.
Quoted 26 lines
hw/virtio/vhost-user.c +8
-1+ } +/* * wait for a reply if logging is enabled to make sure * backend is actually logging changes @@ -2857,13 +3101,18 @@ static int vhost_user_postcopy_notifier(NotifierWithReturn *notifier,return 0 ; } +static const VhostShadowVirtqueueOps vhost_user_svq_ops = { + .avail_handler = vhost_user_svq_handle_avail, + .used_callback = vhost_user_svq_handle_used +}; +static void vhost_user_init_svq (struct vhost_dev *dev,struct vhost_user *u) {/*Modified from vhost-vdpa*/ u->iso_mem_ctx.shadow_vqs =g_ptr_array_new_full (dev->nvqs, vhost_svq_free);for (int i =0 ; i < dev->nvqs; i++) {VhostShadowVirtqueue *svq; - svq =vhost_svq_new (NULL ,NULL ); + svq =vhost_svq_new (&vhost_user_svq_ops, dev);g_ptr_array_add (u->iso_mem_ctx.shadow_vqs, svq); } }
hw/virtio/vhost-user.c void vhost_user_async_close(DeviceState *d, · line 3816
Quoted 6 lines
hw/virtio/vhost-user.c +3
-0@@ -3562,8 +3811,35 @@ void vhost_user_async_close(DeviceState *d, } } +static void vhost_user_svqs_stop (struct vhost_dev *dev) +{ +struct vhost_user *u = dev->opaque;
Please add a blank line after declaration for consistency.
Quoted 16 lines
hw/virtio/vhost-user.c +14
-0+for (int i =0 ; i < u->iso_mem_ctx.shadow_vqs->len; i++) { +vhost_svq_stop (g_ptr_array_index (u->iso_mem_ctx.shadow_vqs, i)); + } +} +static int vhost_user_dev_start (struct vhost_dev *dev,bool started) { +struct vhost_user *u = dev->opaque; +if (u->user->memory_isolation) { +if (vhost_dev_has_iommu (dev)) { +error_report ("Memory isolation is not supported with IOMMU enabled." +"Please disable one and try again" ); +return -1 ; + } + +if (virtio_vdev_has_feature (dev->vdev,VIRTIO_F_RING_PACKED )) {
hw/virtio/vhost-user.c void vhost_user_async_close(DeviceState *d, · line 3842
Quoted 10 lines
hw/virtio/vhost-user.c +10
-0+error_report ("Memory isolation is not supported with packed" +"vrings. Please use split vrings" ); +return -1 ; + } + +if (!started) { +vhost_user_svqs_stop (dev); + } + } +
do_vhost_dev_stop() calls vhost_user_dev_start(false) before disabling backend vrings, and vhost_user_dev_start(false) leads to vhost_user_svqs_stop() here. The backend can still access those rings concurrently, and process requests vhost_user_svqs_stop() returned to the guest with virtqueue_unpop().
vhost-vdpa enforces the correct ordering by calling vhost_vdpa_suspend() before vhost_vdpa_svqs_stop().
Regards,
Akihiko Odaki
Quoted 4 lines
hw/virtio/vhost-user.c +0
-0if (!vhost_user_has_protocol_feature (dev,VHOST_USER_PROTOCOL_F_STATUS )) {return 0 ; }
Re: [PATCH RFC v2 04/13] hw/virtio/vhost-shadow-virtqueue: used callback
In reply to Akihiko OdakiQuoted 8 lines · Akihiko Odaki
hw/virtio/vhost-shadow-virtqueue.c static void vhost_svq_flush(VhostShadowVirtqueue *svq, · line 682
Quoted 4 lines
hw/virtio/vhost-shadow-virtqueue.c +3
-0+ +if (r <0 ) { +/* VQ or handler is broken. Do not set guest notifier */ This comment is extraneous. It is obvious that
event_notifier_set()below is not called, and it is same with the existing error path below.
Quoted 7 lines
What matters here is the difference with the existing error path. Why doesn't it call
virtqueue_fill()norvirtqueue_flush()? They need to be addressed here.Regards,
Akihiko Odaki
Here, apart from not calling event_notifier_set (not notifying the guest), we are also not calling vhost_svq_enable_notification, so the device is directed not to send any more call notifications. If the guest isn't receiving notifications, and the device isn't sending them, is there a purpose to flushing the current element? With the current implementation, I'm not sure there is a path to re-enable calls on either the front-end or back-end, but maybe a case could be made that it's good hygiene to flush the known bad element? For now, I will add the calls to add and flush the element
Thank you!
Connor
Re: [PATCH RFC v2 13/13] net/vhost-user: add memory isolation
In reply to Akihiko OdakiQuoted 7 lines · Akihiko Odaki
Quoted 4 lines · Connor Kite
Add a memory-isolation property to NetdevPassOptions and NetDevVhostUserOptions in net.json. This property will be used for vhost-user devices to disable access to guest memory from vhost-user backends.
Quoted 7 lines
The cover letter says multiqueue is not supported but the code just continues with multiqueue and breaks.
Regards,
Akihiko OdakiQuoted 1 line
Adding multiqueue support is my main focus for Rev 3! My testing so far hasn't included backends with the multiqueue option, but I will correct that.
Thanks!
Connor
Re: [PATCH RFC v2 04/13] hw/virtio/vhost-shadow-virtqueue: used callback
In reply to Connor KiteQuoted 18 lines · Connor Kite
Quoted 8 lines · Akihiko Odaki
hw/virtio/vhost-shadow-virtqueue.c static void vhost_svq_flush(VhostShadowVirtqueue *svq, · line 682
Quoted 4 lines
hw/virtio/vhost-shadow-virtqueue.c +3
-0+ +if (r <0 ) { +/* VQ or handler is broken. Do not set guest notifier */ This comment is extraneous. It is obvious that
event_notifier_set()below is not called, and it is same with the existing error path below.Quoted 7 lines
What matters here is the difference with the existing error path. Why doesn't it call
virtqueue_fill()norvirtqueue_flush()? They need to be addressed here.Regards,
Akihiko Odaki
Quoted 9 lines
Here, apart from not calling
event_notifier_set(not notifying the guest), we are also not callingvhost_svq_enable_notification, so the device is directed not to send any more call notifications. If the guest isn't receiving notifications, and the device isn't sending them, is there a purpose to flushing the current element? With the current implementation, I'm not sure there is a path to re-enable calls on either the front-end or back-end, but maybe a case could be made that it's good hygiene to flush the known bad element? For now, I will add the calls to add and flush the element
Skipping event_notifier_set() only suppresses this guest interrupt, and
disabling SVQ notifications only suppresses backend call notifications; it does not stop backend ring processing. The error should be propagated with virtio_error().
I looked into the virtqueue_fill() and virtqueue_flush() calls in the existing error path. The virtqueue_fill() call detaches the element and publishes it to the guest. Detaching the element is necessary and should be done in the new error path too. On the other hand, publishing the failed element is wrong and should not be done.
virtqueue_flush(vq, i) is still required to publish and account for the preceding successfully filled elements.
Regards,
Akihiko Odaki
Re: [PATCH RFC v2 12/13] backends/cryptodev-vhost-user: add memory isolation bool
In reply to Connor KiteQuoted 9 lines · Connor Kite
Add a
memory_isolationproperty to CryptoDevBackendVhostUser and add add it as an optional member of CryptodevVhostUserProperties in qapi.This is needed to be able to specify memory isolation for cryptodev-vhost-user objects, and the bool will eventually be passed to
vhost_user_init()in a future patch.Signed-off-by Connor Kite <[email protected]>
[...]
qapi/qom.json line 356
Quoted 12 lines
qapi/qom.json +4
-0@@ -350,11 +350,17 @@ # @chardev: the name of a Unix domain socket character device that # connects to the vhost-user server # +# @memory-isolation: disable direct access from vhost-user back-end +# to guest memory. The back-end will instead access data via +# bounce buffers residing in the QEMU virtual address space. +# (default: false) (Since 11.2)
We spell it "backend" elsewhere in doc comments.
Any guidance on when to enable it?
Quoted 11 lines
qapi/qom.json +3
-1+# # Since: 2.12 ## { 'struct': 'CryptodevVhostUserProperties', 'base': 'CryptodevBackendProperties', - 'data': { 'chardev': 'str' }, + 'data': { 'chardev': 'str', + '*memory-isolation': 'bool' }, 'if': 'CONFIG_VHOST_CRYPTO' } ##
Re: [PATCH RFC v2 13/13] net/vhost-user: add memory isolation
In reply to Connor KiteQuoted 6 lines · Connor Kite
Add a memory-isolation property to NetdevPassOptions and NetDevVhostUserOptions in net.json. This property will be used for vhost-user devices to disable access to guest memory from vhost-user backends.
Signed-off-by Connor Kite <[email protected]>
[...]
qapi/net.json line 218
Quoted 11 lines
qapi/net.json +3
-0@@ -213,6 +213,9 @@ # # @param: parameter to pass to passt command # +# @memory-isolation: isolate guest memory from vhost-user back-end +# (default: false) (Since 11.2) +#
Any guidance on when to enable it?
Quoted 14 lines
qapi/net.json +2
-1# Since: 10.1 ## { 'struct': 'NetdevPasstOptions',@@ -250,7 +253,8 @@ '*ipv6': 'bool', '*tcp-ports': ['PasstPortForward'], '*udp-ports': ['PasstPortForward'], - '*param': ['PasstParameter'] }, + '*param': ['PasstParameter'], + '*memory-isolation': 'bool'}, 'if': 'CONFIG_PASST' } ##
qapi/net.json line 693
Quoted 5 lines
qapi/net.json +2
-0@@ -685,13 +689,17 @@ # @queues: number of queues to be created for multiqueue vhost-user # (default: 1) (Since 2.5) # +# @memory-isolation: isolate guest memory from vhost-user back-end +# (default: false) (Since 11.2)
Likewise.
Quoted 15 lines
qapi/net.json +5
-3+# # Since: 2.1 ## { 'struct': 'NetdevVhostUserOptions', 'data': { - 'chardev': 'str', - '*vhostforce': 'bool', - '*queues': 'int' } } + 'chardev': 'str', + '*vhostforce': 'bool', + '*queues': 'int', + '*memory-isolation': 'bool' } } ## # @NetdevVhostVDPAOptions:
Re: [PATCH RFC v2 09/13] hw/virtio/vhost-user: add shadow virtqueues and eventfd intercepts
In reply to Akihiko OdakiQuoted 4 lines · Akihiko Odaki
A whitespace problem remains here.
Got it! This is fixed now
Quoted 23 lines
Quoted 23 lines
} IsolationModeCtx; struct vhost_user {hw/virtio/vhost-user.c +15
-1@@ -1128,15 +1130,38 @@ static int vhost_user_set_mem_table_postcopy(struct vhost_dev *dev,return 0 ; } -static void cleanup_isolation_regions (struct vhost_dev *dev) +static void vhost_user_svq_cleanup (struct vhost_user *u,bool reset) +{ +VhostShadowVirtqueue *svq; +for (int i =0 ; i < u->iso_mem_ctx.shadow_vqs->len; i++) { + svq =g_ptr_array_index (u->iso_mem_ctx.shadow_vqs, i); +vhost_svq_stop (svq); +event_notifier_cleanup (&svq->hdev_call); +event_notifier_cleanup (&svq->hdev_kick); + } + +if (!reset) { +g_ptr_array_free (u->iso_mem_ctx.shadow_vqs, true); + } +} +
Quoted 9 lines
hw/virtio/vhost-user.c static int vhost_user_set_mem_table_postcopy(struct vhost_dev *dev, · line 1151
Quoted 4 lines
hw/virtio/vhost-user.c +1
-0+static void cleanup_isolation_regions (struct vhost_dev *dev,bool reset) {struct vhost_user *u = dev->opaque;if (u->iso_mem_ctx.shared_mem_addr) {If
vhost_dev_init()fails aftervhost_user_init_svq(),shadow_vqsis present butshared_mem_addris not becauseinit_isolation_regions()is not called yet.shadow_vqswill be leaked then.
Good catch! The call to vhost_user_svq_cleanup will be moved out of the conditional statement so it always runs during cleanup. I also realized that it is possible for an error to occur after the call to qemu_memfd_alloc but before the iova tree is allocated, so I am adding a check before calling vhost_iova_tree_delete.
Quoted 9 lines
hw/virtio/vhost-user.c static int vhost_user_set_mem_table_postcopy(struct vhost_dev *dev, · line 1158
Quoted 7 lines
hw/virtio/vhost-user.c +3
-0+vhost_user_svq_cleanup (u, reset);vhost_iova_tree_delete (u->iso_mem_ctx.tree);qemu_memfd_free (u->iso_mem_ctx.shared_mem_addr, u->iso_mem_ctx.size, u->iso_mem_ctx.fd); + +GPtrArray *temp = u->iso_mem_ctx.shadow_vqs;This is a mixed declaration prohibited in
docs/devel/style.rst
Got it! I will fix this.
Quoted 8 lines
hw/virtio/vhost-user.c static int vhost_user_set_mem_table_postcopy(struct vhost_dev *dev, · line 1161
Quoted 4 lines
hw/virtio/vhost-user.c +2
-0memset (&u->iso_mem_ctx,0 ,sizeof (IsolationModeCtx)); + +if (!reset) {This condition is inverted. When reset is true,
vhost_user_svq_cleanup()retains the array so the pointer to it should be kept.
You are right! This is now fixed
...
Quoted 9 lines
Quoted 9 lines
hw/virtio/vhost-user.c +5
-1static int vhost_user_set_vring_kick (struct vhost_dev *dev,struct vhost_vring_file *file) { -int ret =vhost_set_vring_file (dev,VHOST_USER_SET_VRING_KICK , file); +struct vhost_user *u = dev->opaque; +int svq_idx = file->index - dev->vq_index; +VhostShadowVirtqueue *svq =NULL ; +struct vhost_vring_file vr_file = *file; +int ret;
Quoted 9 lines
hw/virtio/vhost-user.c static int vhost_set_vring_file(struct vhost_dev *dev, · line 1786
Quoted 6 lines
hw/virtio/vhost-user.c +6
-0+ +vhost_user_get_vq_index (dev, file->index);/* bounds checking */ + +if (u->user->memory_isolation) { + svq =g_ptr_array_index (u->iso_mem_ctx.shadow_vqs, svq_idx); +vhost_svq_set_svq_kick_fd (svq, file->fd);The
svq->svq_kickEventNotifier is left set in the error paths.
I did not want to close the svq_kick notifier, since it shares its fd with the host notifier in the underlying vq, and closing that from here might be unexpected. However, a safer alternative is probably to call vhost_svq_set_svq_kck_fd with -1 to simply unbind the notifier, which I suspect is what you are actually recommending here.
Quoted 3 lines
Regards,
Akihiko Odaki
...
Quoted 28 lines
Quoted 28 lines
hw/virtio/vhost-user.c +23
-1@@ -1769,7 +1835,35 @@ static int vhost_user_set_vring_kick(struct vhost_dev *dev,static int vhost_user_set_vring_call (struct vhost_dev *dev,struct vhost_vring_file *file) { -return vhost_set_vring_file (dev,VHOST_USER_SET_VRING_CALL , file); +struct vhost_user *u = dev->opaque; +int svq_idx = file->index - dev->vq_index; +VhostShadowVirtqueue *svq =NULL ; +struct vhost_vring_file vr_file = *file; +int ret; + +vhost_user_get_vq_index (dev, file->index);/* bounds checking */ + +if (u->user->memory_isolation) { + svq =g_ptr_array_index (u->iso_mem_ctx.shadow_vqs, svq_idx); +vhost_svq_set_svq_call_fd (svq, file->fd); + +if (file->fd !=-1 ) { +if (!svq->hdev_call.initialized) { + ret =event_notifier_init (&svq->hdev_call,0 ); +if (ret <0 ) { +event_notifier_cleanup (&svq->hdev_call); +error_report ("Failed to create call event notifier" ); +return ret; + } + } + + vr_file.fd =event_notifier_get_fd (&svq->hdev_call);
Quoted 9 lines
hw/virtio/vhost-user.c static int vhost_user_set_vring_kick(struct vhost_dev *dev, · line 1866
Quoted 6 lines
hw/virtio/vhost-user.c +6
-0+ }else { +event_notifier_cleanup (&svq->hdev_call); + } + } + +return vhost_set_vring_file (dev,VHOST_USER_SET_VRING_CALL , &vr_file);Clean up
svq->hdev_callwhen this fails.
Did you mean cleanup svq->svq_call, similar to your feedback on svq->svq_kick? I believe svq->hdev_call already gets cleaned up on failure. I'll go ahead and add a call to vhost_svq_set_svq_call_fd with fd=-1 here as well.
Thank you!
Connor
Re: [PATCH RFC v2 04/13] hw/virtio/vhost-shadow-virtqueue: used callback
In reply to Akihiko OdakiQuoted 13 lines · Akihiko Odaki
Skipping
event_notifier_set()only suppresses this guest interrupt, and disabling SVQ notifications only suppresses backend call notifications; it does not stop backend ring processing. The error should be propagated withvirtio_error().I looked into the
virtqueue_fill()andvirtqueue_flush()calls in the existing error path. Thevirtqueue_fill()call detaches the element and publishes it to the guest. Detaching the element is necessary and should be done in the new error path too. On the other hand, publishing the failed element is wrong and should not be done.
Quoted 5 lines
virtqueue_flush(vq, i)is still required to publish and account for the preceding successfully filled elements.Regards,
Akihiko Odaki
Thank you for the explanation! I was not aware of virtio_error. This error path will now follow the following order:
if (r < 0) {
virtio_error(svq->vdev, "Vhost shadow virtqueue error while
handling used element.\n");
virtqueue_detach_element(vq, elem, 0);
g_free(elem);
virtqueue_flush(vq, i);
return;
}One thing still seems a little strange here about how vq->inuse is modified by these operations. The count provided to virtqueue_flush in the svq code is the number of elements that have been added. However, depending on which type of flush occurs, the value of vq->inuse is decreased by either this count (virtqueue_split_flush) or the number of descriptors in the flushed elements (virtqueue_packed_flush, virtqueue_ordered_flush). Also, the virtqueue_detach_element always decrements vq->inuse by the number of descriptors.
I'm possibly just misunderstanding something, but this seems like vq->inuse could potentially end up in an incorrect state. Maybe that doesn't matter in this case once virtio_error gets called...
Re: [PATCH RFC v2 13/13] net/vhost-user: add memory isolation
In reply to Markus ArmbrusterQuoted 4 lines · Markus Armbruster
Any guidance on when to enable it?
...
Quoted 2 lines
Likewise.
In both cases, you would enable this for added security. There's obviously a performance hit, but it prevents a potentially misbehaving vhost-user backend from reading or modifying undesired portions of guest memory, since data transfer occurs wholly via bounce buffers. This may be more useful in the generic netdev vhost user case than it is with the passt version, but the goal is for the mode to be accessible for any vhost-user device.
Do you think guidance is needed here in net.json? I was thinking that, if isolation-mode gets to a point of being merged, then information like this would make sense somewhere in the online documentation, but I'm happy to add something here as well. I was just trying to be similarly short and to-the-point as the other option descriptions for these structs.
Thanks!
Connor
Re: [PATCH RFC v2 07/13] hw/virtio/vhost-user: create isolation region
In reply to Akihiko OdakiQuoted 26 lines · Akihiko Odaki
hw/virtio/vhost-user.c static VhostUserMsg m __attribute__ ((unused)); · line 333
Quoted 10 lines
hw/virtio/vhost-user.c +9
-0+/* Memory region shared with back-end when memory-isolation is active */ +typedef struct { + void *shared_mem_addr; /* mapped shared memory */ + VhostIOVATree *tree; /* controls mapping of regions into IOVA space */ + void *vring_hva_addr; /* beginning of vring region in shared memory */ + size_t vring_region_size; /* amount of shared memory reserved for vrings */ + size_t size; /* size of the mapped shared memory */ + int fd; /* descriptor of anonymous file backing shared iso region */ + Int128 iso_iova_offset; /* translation from IOVA to hva of iso region */This Int128 usage is misleading. The value derived from
iso_iova_offsetis always consumed withint128_get64(), which asserts the value fits in 64-bit. But we actually need to enforce that the address before translation resides in the shared memory. So makingiso_iova_offsetInt128 is not a good way to assert the real invariant.Furthermore, "[PATCH RFC v2 10/13] hw/virtio/vhost-user: handle data movement with shadow vqs" has:
ptrdiff_t offset = u->iso_mem_ctx.iso_iova_offset;If
defined(CONFIG_INT128)&& !defined(CONFIG_TCG_INTERPRETER), this will overflow withu->iso_mem_ctx.iso_iova_offset>PTRDIFF_MAX. Otherwise, Int128 will be a struct, which causes a compilation error.
Quoted 8 lines
uintptr_tis sufficient if the invariant is enforced in some alternative way. A negative offset would be represented as wraparound, and a positive one will never result in wraparound. Just always ensure the address before translation resides in the shared memory.Regards,
Akihiko Odaki
Your point is taken on the Int128! I also got similar feedback from Stefan Hajnoczi and Hanna CzenCzek that it was unnecessary complication. Will move it to uintptr_t and double check the bounds-checking on translations in the later patches to confirm that it didn't depend on the Int128 type.
Also, I thought I had moved all cases of ptrdiff_t to Int128, but I apparently missed that one. The offset must have been less than PTRDIFF_MAX in testing since this didn't come up. Will fix and change to uintptr_t as well.
Thank you once again!
Connor
Re: [PATCH RFC v2 13/13] net/vhost-user: add memory isolation
In reply to Connor KiteQuoted 10 lines · Connor Kite
Quoted 4 lines · Markus Armbruster
Any guidance on when to enable it?
...
Quoted 2 lines
Likewise.
Quoted 7 lines
In both cases, you would enable this for added security. There's obviously a performance hit, but it prevents a potentially misbehaving vhost-user backend from reading or modifying undesired portions of guest memory, since data transfer occurs wholly via bounce buffers. This may be more useful in the generic netdev vhost user case than it is with the passt version, but the goal is for the mode to be accessible for any vhost-user device.
Work this into the commit message, please.
Quoted 6 lines
Do you think guidance is needed here in net.json? I was thinking that, if isolation-mode gets to a point of being merged, then information like this would make sense somewhere in the online documentation, but I'm happy to add something here as well. I was just trying to be similarly short and to-the-point as the other option descriptions for these structs.
I think it needs to be somewhere in the user documentation. We have so many configuration options, and so little guidance on what to do with them.
The doc comments in the QAPI schema are reference documentation (they go into the "QEMU QMP Reference Manual"). Reference documentation should be concise and to the point. When you have more useful things to say than fit there, you need to find nother place, and maybe link to it from the reference docs.
I suggest to try adding brief guidance to the doc comment, and then we see how we feel about it.
Re: [PATCH RFC v2 04/13] hw/virtio/vhost-shadow-virtqueue: used callback
In reply to Connor KiteQuoted 21 lines · Connor Kite
Quoted 13 lines · Akihiko Odaki
Skipping
event_notifier_set()only suppresses this guest interrupt, and disabling SVQ notifications only suppresses backend call notifications; it does not stop backend ring processing. The error should be propagated withvirtio_error().I looked into the
virtqueue_fill()andvirtqueue_flush()calls in the existing error path. Thevirtqueue_fill()call detaches the element and publishes it to the guest. Detaching the element is necessary and should be done in the new error path too. On the other hand, publishing the failed element is wrong and should not be done.Quoted 5 lines
virtqueue_flush(vq, i)is still required to publish and account for the preceding successfully filled elements.Regards,
Akihiko Odaki
Quoted 8 lines
Thank you for the explanation! I was not aware of
virtio_error. This error path will now follow the following order:if (r < 0) { virtio_error(svq->vdev, "Vhost shadow virtqueue error while handling used element.\n"); virtqueue_detach_element(vq, elem, 0); g_free(elem);
This must be removed. elem is declared g_autofree, so returning after an explicit free would free it twice.
Quoted 1 line
virtqueue_flush(vq, i);
virtio_error() must come last. It sets vdev->broken, after which virtqueue_flush() takes its disabled-device shortcut and merely subtracts i; it does not publish the preceding used entries.
Quoted 13 lines
return; }One thing still seems a little strange here about how
vq->inuseis modified by these operations. The count provided tovirtqueue_flushin the svq code is the number of elements that have been added. However, depending on which type of flush occurs, the value ofvq->inuseis decreased by either this count (virtqueue_split_flush) or the number of descriptors in the flushed elements (virtqueue_packed_flush,virtqueue_ordered_flush). Also, thevirtqueue_detach_elementalways decrementsvq->inuseby the number of descriptors.
Quoted 3 lines
I'm possibly just misunderstanding something, but this seems like
vq->inusecould potentially end up in an incorrect state. Maybe that doesn't matter in this case oncevirtio_errorgets called...
The corresponding virtqueue_pop() function that increments vq->inuse also changes the count conditionally with the negotiated features, so I expect they are balanced.
Regards,
Akihiko Odaki
Re: [PATCH RFC v2 05/13] hw/virtio/vhost-shadow-virtqueue: specified vring placement
In reply to Connor KiteQuoted 18 lines · Connor Kite
By default svq vrings are placed in an anonymous memory map. As svqs will be leveraged to enable memory isolation in vhost-user, it is useful to be able to place the vrings in a shared isolation memory region.
Adds the option to specify vring placement by providing a vring base address before starting the svq.
Signed-off-by Connor Kite <[email protected]>--- hw/virtio/vhost-shadow-virtqueue.c | 69 ++++++++++++++++++++++++++++++++------ hw/virtio/vhost-shadow-virtqueue.h | 8 ++++- 2 files changed, 66 insertions(+), 11 deletions(-)hw/virtio/vhost-shadow-virtqueue.c +0
-0
hw/virtio/vhost-shadow-virtqueue.c size_t vhost_svq_device_area_size(const VhostShadowVirtqueue *svq) · line 815
Quoted 4 lines
hw/virtio/vhost-shadow-virtqueue.c +1
-0@@ -812,6 +812,13 @@ size_t vhost_svq_device_area_size(const VhostShadowVirtqueue *svq)return ROUND_UP (used_size,qemu_real_host_page_size ()); } +size_t vhost_svq_vring_total_size (VirtIODevice *vdev,VirtQueue *vq)
If this function is not used in this patch, it probably should not be introduced here.
hw/virtio/vhost-shadow-virtqueue.c size_t vhost_svq_device_area_size(const VhostShadowVirtqueue *svq) · line 819
Quoted 4 lines
hw/virtio/vhost-shadow-virtqueue.c +4
-0+{ +VhostShadowVirtqueue svq; + svq.vring.num =virtio_queue_get_num (vdev,virtio_get_queue_index (vq)); +return vhost_svq_driver_area_size (&svq) +vhost_svq_device_area_size (&svq);
I’m not 100 % happy about this (initializing a pseudo svq), might be better to make it so there are vhost_svq_driver/device_area_size() variants that take the num directly, and then have vhost_svq_driver/device_area_size() be wrappers around it, but, well. At least the implementations are right above it so one can verify that nothing else in VhostShadowVirtqueue is used. (It’s just that one should not *have* to verify.)
Quoted 58 lines
hw/virtio/vhost-shadow-virtqueue.c +27
-8+} +/** * Set a new file descriptor for the guest to kick the SVQ and notify for avail * @@ -842,6 +849,19 @@ void vhost_svq_set_svq_kick_fd(VhostShadowVirtqueue *svq, int svq_kick_fd) } } +/** +* Set vring base address if using fixed locations +* +* @svq: Shadow Virtqueue +* @addr: Points to new base address +*/ + +void vhost_svq_set_base_addr (VhostShadowVirtqueue *svq,void *addr) + { + svq->base_addr = addr; + } + +/** * Start the shadow virtqueue operation. * @@ -849,8 +869,10 @@ void vhost_svq_set_svq_kick_fd(VhostShadowVirtqueue *svq, int svq_kick_fd)* @vdev: VirtIO device * @vq: Virtqueue to shadow * @iova_tree: Tree to perform descriptors translations +* +* Return 0 on success, -errno on failure */ -void vhost_svq_start (VhostShadowVirtqueue *svq,VirtIODevice *vdev, +int vhost_svq_start (VhostShadowVirtqueue *svq,VirtIODevice *vdev,VirtQueue *vq,VhostIOVATree *iova_tree) {size_t desc_size;@@ -868,14 +890,27 @@ void vhost_svq_start(VhostShadowVirtqueue *svq, VirtIODevice *vdev, svq->vring.num =virtio_queue_get_num (vdev,virtio_get_queue_index (vq)); svq->num_free = svq->vring.num; - svq->vring.desc =mmap (NULL ,vhost_svq_driver_area_size (svq), -PROT_READ |PROT_WRITE ,MAP_SHARED |MAP_ANONYMOUS , --1 ,0 ); desc_size =sizeof (vring_desc_t) * svq->vring.num; - svq->vring.avail = (void *)((char *)svq->vring.desc + desc_size); - svq->vring.used =mmap (NULL ,vhost_svq_device_area_size (svq), -PROT_READ |PROT_WRITE ,MAP_SHARED |MAP_ANONYMOUS , --1 ,0 ); +if (svq->base_addr ==NULL ) { + svq->vring.desc =mmap (NULL ,vhost_svq_driver_area_size (svq), +PROT_READ |PROT_WRITE ,MAP_SHARED |MAP_ANONYMOUS , +-1 ,0 ); + svq->vring.avail = (void *)((char *)svq->vring.desc + desc_size); + svq->vring.used =mmap (NULL ,vhost_svq_device_area_size (svq), +PROT_READ |PROT_WRITE ,MAP_SHARED |MAP_ANONYMOUS , +-1 ,0 ); + }else {
hw/virtio/vhost-shadow-virtqueue.c void vhost_svq_start(VhostShadowVirtqueue *svq, VirtIODevice *vdev, · line 912
Quoted 10 lines
hw/virtio/vhost-shadow-virtqueue.c +10
-0+ svq->vring.desc = (void *)svq->base_addr; + svq->vring.avail = (void *)((char *)svq->vring.desc + desc_size); + svq->vring.used = (void *)((char *)svq->base_addr + +vhost_svq_driver_area_size (svq)); + +if ((uint64_t )svq->vring.used +vhost_svq_device_area_size (svq) -1 < + (uint64_t )svq->vring.desc) { +error_report ("Invalid shadow vring location" ); +return -ENOMEM ; + }
Why does this check exist?
What needs to be done here is proper bounds checking. That either .used + device_area_size() or desc + vhost_svq_vring_total_size() does not exceed the end of the memory region that has been allocated for the vrings. It is clear that such an allocation would never wrap around the end of memory because no allocation ever does.
Quoted 20 lines
hw/virtio/vhost-shadow-virtqueue.c +4
-2+ } svq->desc_state =g_new0 (SVQDescState, svq->vring.num);if (virtio_vdev_has_feature (svq->vdev,VIRTIO_F_IN_ORDER )) { svq->batch_last.id =VIRTIO_RING_NOT_IN_BATCH ;@@ -884,6 +919,8 @@ void vhost_svq_start(VhostShadowVirtqueue *svq, VirtIODevice *vdev, svq->desc_state[i].next = i +1 ; } } + +return 0 ; }/** @@ -920,8 +957,19 @@ void vhost_svq_stop(VhostShadowVirtqueue *svq) } svq->vq =NULL ;g_free (svq->desc_state); -munmap (svq->vring.desc,vhost_svq_driver_area_size (svq)); -munmap (svq->vring.used,vhost_svq_device_area_size (svq)); +
hw/virtio/vhost-shadow-virtqueue.c void vhost_svq_stop(VhostShadowVirtqueue *svq) · line 970
Quoted 10 lines
hw/virtio/vhost-shadow-virtqueue.c +10
-0+if (!svq->base_addr) { +munmap (svq->vring.desc,vhost_svq_driver_area_size (svq)); +munmap (svq->vring.used,vhost_svq_device_area_size (svq)); + }else { +if (svq->vring.desc) { +memset (svq->vring.desc,0 ,vhost_svq_driver_area_size (svq)); + } +if (svq->vring.used) { +memset (svq->vring.used,0 ,vhost_svq_device_area_size (svq)); + }
Why the memset()?
Hanna
Quoted 48 lines
hw/virtio/vhost-shadow-virtqueue.c +3
-0+ } +event_notifier_set_handler (&svq->hdev_call,NULL ); }@@ -940,6 +988,7 @@ VhostShadowVirtqueue *vhost_svq_new(const VhostShadowVirtqueueOps *ops,event_notifier_init_fd (&svq->svq_kick,VHOST_FILE_UNBIND ); svq->ops = ops; svq->ops_opaque = ops_opaque; + svq->base_addr =NULL ;return svq; }hw/virtio/vhost-shadow-virtqueue.h +7
-1@@ -150,6 +150,9 @@ typedef struct VhostShadowVirtqueue {/* Size of SVQ vring free descriptors */ uint16_t num_free; + +/* Location assigned to vrings if not in default anon memory map */ +void *base_addr; } VhostShadowVirtqueue;bool vhost_svq_valid_features (uint64_t features,Error **errp);@@ -169,8 +172,9 @@ void vhost_svq_get_vring_addr(const VhostShadowVirtqueue *svq, struct vhost_vring_addr *addr);size_t vhost_svq_driver_area_size (const VhostShadowVirtqueue *svq);size_t vhost_svq_device_area_size (const VhostShadowVirtqueue *svq); +size_t vhost_svq_vring_total_size (VirtIODevice *vdev,VirtQueue *vq); -void vhost_svq_start (VhostShadowVirtqueue *svq,VirtIODevice *vdev, +int vhost_svq_start (VhostShadowVirtqueue *svq,VirtIODevice *vdev,VirtQueue *vq,VhostIOVATree *iova_tree);void vhost_svq_stop (VhostShadowVirtqueue *svq);@@ -178,6 +182,8 @@ VhostShadowVirtqueue *vhost_svq_new(const VhostShadowVirtqueueOps *ops, void *ops_opaque);void vhost_svq_free (gpointer vq); +void vhost_svq_set_base_addr (VhostShadowVirtqueue *svq,void *addr); +G_DEFINE_AUTOPTR_CLEANUP_FUNC (VhostShadowVirtqueue, vhost_svq_free);#endif
Re: [PATCH RFC v2 07/13] hw/virtio/vhost-user: create isolation region
In reply to Connor KiteQuoted 9 lines · Connor Kite
If memory isolation mode is active for the vhost-user device adds features to:
- Gather the size required for bounce buffers and vrings in shared isolation region
- Allocate the required space in an anonymous file
- Create a vhost-iova-tree with space to map entire isolation region
- Map guest memory regions and shared vrings into the tree
- Release these resources upon backend cleanup
Quoted 4 lines
Signed-off-by Connor Kite <[email protected]>--- hw/virtio/vhost-user.c | 136 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 136 insertions(+)
qemu does not compile with this patch applied because the "hw/virtio/vhost-shadow-virtqueue.h" include is missing.
Quoted 24 lines
hw/virtio/vhost-user.c +2
-0@@ -18,6 +18,7 @@#include "hw/virtio/vhost-backend.h" #include "hw/virtio/virtio.h" #include "hw/virtio/virtio-net.h" +#include "hw/virtio/vhost-iova-tree.h" #include "chardev/char-fe.h" #include "io/channel-socket.h" #include "system/kvm.h" @@ -25,6 +26,7 @@#include "qemu/main-loop.h" #include "qemu/uuid.h" #include "qemu/sockets.h" +#include "qemu/memfd.h" #include "system/runstate.h" #include "system/cryptodev.h" #include "migration/postcopy-ram.h" @@ -320,6 +322,17 @@ static VhostUserMsg m __attribute__ ((unused));/* The version of the protocol we support */ #define VHOST_USER_VERSION (0x1)
hw/virtio/vhost-user.c static VhostUserMsg m __attribute__ ((unused)); · line 334
Quoted 10 lines
hw/virtio/vhost-user.c +10
-0+/* Memory region shared with back-end when memory-isolation is active */ +typedef struct { +void *shared_mem_addr;/* mapped shared memory */ +VhostIOVATree *tree;/* controls mapping of regions into IOVA space */ +void *vring_hva_addr;/* beginning of vring region in shared memory */ +size_t vring_region_size;/* amount of shared memory reserved for vrings */ +size_t size;/* size of the mapped shared memory */ +int fd;/* descriptor of anonymous file backing shared iso region */ +Int128 iso_iova_offset;/* translation from IOVA to hva of iso region */ +}IsolationModeCtx ;
Can you put the comments above each field instead of inline?
Quoted 29 lines
hw/virtio/vhost-user.c +15
-0+struct vhost_user {struct vhost_dev *dev;/* Shared between vhost devs of the same virtio device */ @@ -353,6 +366,9 @@ struct vhost_user {* by the backend (see @features). */ uint64_t protocol_features; + +/* Data specfic to isolated memory mode */ +IsolationModeCtx iso_mem_ctx; };struct scrub_regions {@@ -1112,6 +1128,125 @@ static int vhost_user_set_mem_table_postcopy(struct vhost_dev *dev,return 0 ; } +static void cleanup_isolation_regions (struct vhost_dev *dev) +{ +struct vhost_user *u = dev->opaque; +if (u->iso_mem_ctx.shared_mem_addr) { +vhost_iova_tree_delete (u->iso_mem_ctx.tree); +qemu_memfd_free (u->iso_mem_ctx.shared_mem_addr, + u->iso_mem_ctx.size, + u->iso_mem_ctx.fd); +memset (&u->iso_mem_ctx,0 ,sizeof (IsolationModeCtx)); + } +}
hw/virtio/vhost-user.c static int vhost_user_set_mem_table_postcopy(struct vhost_dev *dev, · line 1151
Quoted 10 lines
hw/virtio/vhost-user.c +10
-0+ +__attribute__((unused)) +static int init_isolation_regions (struct vhost_dev *dev, +VhostUserMsg *msg, +int *fds,size_t *fd_num) +{ +Error *err =NULL ; +struct vhost_user *u = dev->opaque; +uint32_t nregions = dev->mem->nregions; +
I don’t really feel like this empty line helps readability as it seems arbitrarily placed.
Quoted 8 lines
hw/virtio/vhost-user.c +8
-0+ g_autofree DMAMap *buffer_regions = g_new0(DMAMap, nregions); +size_t buffer_reg_size =0 ; +size_t total_vring_size =0 ; +size_t total_mmap_size; +char *reg_name; +uint64_t first_IOVA_addr; +uint64_t last_IOVA_addr; +DMAMap *map;
hw/virtio/vhost-user.c static int vhost_user_set_mem_table_postcopy(struct vhost_dev *dev, · line 1169
Quoted 10 lines
hw/virtio/vhost-user.c +10
-0+DMAMap vring_map; +int r; + + msg->hdr.request =VHOST_USER_SET_MEM_TABLE ; + +/* In case of reset, clear old regions */ +cleanup_isolation_regions (dev); + +/* Gather information for bounce buffers to be mapped */ +for (u_int32_t i =0 ; i < nregions; i++) {
uint32_t please, not u_int32_t.
Quoted 15 lines
hw/virtio/vhost-user.c +15
-0+hwaddr size =ROUND_UP (dev->mem->regions[i].memory_size, +qemu_real_host_page_size ()); + buffer_regions[i].size = size -1 ; + buffer_regions[i].perm =IOMMU_RW ; + + buffer_reg_size += size; + } + +/* Get space required for all vrings */ +for (int i =0 ; i < dev->nvqs; i++) { +VirtQueue *vq =virtio_get_queue (dev->vdev, dev->vq_index + i); + total_vring_size +=vhost_svq_vring_total_size (dev->vdev, vq); + } + + total_mmap_size = buffer_reg_size + total_vring_size;
hw/virtio/vhost-user.c static int vhost_user_set_mem_table_postcopy(struct vhost_dev *dev, · line 1194
Quoted 10 lines
hw/virtio/vhost-user.c +10
-0+ u->iso_mem_ctx.size = total_mmap_size; + +/* Allocate and map an anonymous file to hold the isolation region */ + reg_name =g_strconcat ("iso_mem_" , dev->vdev->name,NULL ); + u->iso_mem_ctx.shared_mem_addr =qemu_memfd_alloc (reg_name, + total_mmap_size, +F_SEAL_GROW |F_SEAL_SHRINK |F_SEAL_SEAL , + &u->iso_mem_ctx.fd, &err); + +assert (u->iso_mem_ctx.fd >=0 );
Does it make sense to check that before we took a look (via err) whether the function even succeeded?
hw/virtio/vhost-user.c static int vhost_user_set_mem_table_postcopy(struct vhost_dev *dev, · line 1200
Quoted 6 lines
hw/virtio/vhost-user.c +6
-0+g_free (reg_name); + +if (err) { +error_report_err (err); +cleanup_isolation_regions (dev); +return -1 ;
Are you sure you can run cleanup_isolation_regions() if qemu_memfd_alloc() left some fields in basically undefined state?
General note: We usually use goto fail and fail: patterns in qemu for common clean-up paths (in this case cleanup_isolation_regions()).
hw/virtio/vhost-user.c static int vhost_user_set_mem_table_postcopy(struct vhost_dev *dev, · line 1208
Quoted 8 lines
hw/virtio/vhost-user.c +8
-0+ } + +/* vhost-iova-tree enforces non-zero lower address */ + first_IOVA_addr =qemu_real_host_page_size (); + last_IOVA_addr = first_IOVA_addr + total_mmap_size -1 ; +assert (last_IOVA_addr > first_IOVA_addr); + +/* Use 128-bit operation in case of large negative offset */
Yeah, as discussed (last week and with Akihiko on this thread), I think all 128-bit operations can be replaced by uintptr_t operation with its well-defined two's complement overflow/representation.
Hanna
Quoted 53 lines
hw/virtio/vhost-user.c +42
-0+ u->iso_mem_ctx.iso_iova_offset = +int128_sub (int128_make64 ((uint64_t )u->iso_mem_ctx.shared_mem_addr), +int128_make64 (first_IOVA_addr)); + +/* +* Instantiates iova tree sized to map bounce buffers and vrings to the +* isolation region in host va. +*/ + u->iso_mem_ctx.tree = +vhost_iova_tree_new (first_IOVA_addr, last_IOVA_addr); + +/* Map vrings into IOVA tree */ + vring_map.perm =IOMMU_RW ; + vring_map.size = total_vring_size -1 ; + r =vhost_iova_tree_map_alloc (u->iso_mem_ctx.tree, &vring_map, + (hwaddr )u->iso_mem_ctx.shared_mem_addr); + +if (r !=IOVA_OK ) { +cleanup_isolation_regions (dev); +return r; + } + + u->iso_mem_ctx.vring_hva_addr = (void *)int128_get64 ( +int128_add (int128_make64 (vring_map.iova), + u->iso_mem_ctx.iso_iova_offset)); + u->iso_mem_ctx.vring_region_size = total_vring_size; + +for (int i =0 ; i < nregions; i++) { + map = &buffer_regions[i]; + r =vhost_iova_tree_map_alloc_gpa (u->iso_mem_ctx.tree, map, + dev->mem->regions[i].guest_phys_addr); + +if (r !=IOVA_OK ) { +cleanup_isolation_regions (dev); +return r; + } + } + +return 0 ; +} +static int vhost_user_set_mem_table (struct vhost_dev *dev,struct vhost_memory *mem) {@@ -2684,6 +2819,7 @@ static int vhost_user_backend_cleanup(struct vhost_dev *dev)g_free (u->region_rb_offset); u->region_rb_offset =NULL ; u->region_rb_len =0 ; +cleanup_isolation_regions (dev);g_free (u); dev->opaque =0 ;
Re: [PATCH RFC v2 08/13] hw/virtio/vhost-user: send isolation regions to device
In reply to Connor KiteQuoted 47 lines · Connor Kite
Adds features to fill a
vhost_user_set_mem_tablemessage with the addresses of isolation memory regions corresponding to bounce buffers and vrings.Signed-off-by Connor Kite <[email protected]>--- hw/virtio/vhost-user.c | 118 ++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 117 insertions(+), 1 deletion(-)hw/virtio/vhost-user.c +29
-1@@ -1140,7 +1140,77 @@ static void cleanup_isolation_regions(struct vhost_dev *dev) } } -__attribute__((unused)) +typedef struct { +VhostUserMsg *msg; +struct vhost_user *u; +int *fds; +size_t fds_size; +uint64_t vring_iova; +size_t vring_size; +bool vring_node_visited; +size_t *idx; +}IOVATreeTraversalArgs ; + +static gboolean vhost_user_fill_msg_reg_from_tree (gpointer key, +gpointer value, +gpointer data) +{ +IOVATreeTraversalArgs *args = data; +struct vhost_user *u; +VhostUserMsg *msg = args->msg; +DMAMap *map = key; +uint64_t offset; + +assert (args && key && value); +if (!args->vring_node_visited) { + args->vring_node_visited = true; +return false; + } + + u = args->u; +assert (*args->idx < args->fds_size);
hw/virtio/vhost-user.c static void cleanup_isolation_regions(struct vhost_dev *dev) · line 1181
Quoted 10 lines
hw/virtio/vhost-user.c +10
-0+ + args->fds[*args->idx] = args->u->iso_mem_ctx.fd; + +/* +* If the number of regions is fixed, it would be wasteful to use one for +* only the vrings. The first vhost_iova_tree element is always +* reserved for the vrings, so we can simply combine the first and second +* elements, which are contiguous in IOVA space, when sending regions to +* the backend. +*/
I am not sure it makes sense to optimize here if it makes the code more complicated and the eventual goal would rather be to have a dedicated memory area for the device I/O memory rather than a full mirror of guest memory. Specifically because that full mirror already is quite wasteful, so… it was my understanding that the full mirror is mostly for testing anyway.
Hanna
Quoted 117 lines
hw/virtio/vhost-user.c +78
-0+if (*args->idx ==0 ) { + offset = u->iso_mem_ctx.vring_hva_addr - u->iso_mem_ctx.shared_mem_addr; + msg->payload.memory.regions[*args->idx].userspace_addr = + args->vring_iova; +/* +* The size from the iova tree is inclusive, so 1 is added to it. +* args->vring_size is exclusive, so no addition is required. +*/ + msg->payload.memory.regions[*args->idx].memory_size = + args->vring_size + map->size +1 ; + msg->payload.memory.regions[*args->idx].guest_phys_addr = + args->vring_iova; + msg->payload.memory.regions[*args->idx].mmap_offset = offset; + }else { +/* Use 128 bit operation in unlikely case of negative iso_iova_offset */ + offset =int128_get64 (int128_add (int128_make64 (map->iova), + u->iso_mem_ctx.iso_iova_offset)) - + (uint64_t )u->iso_mem_ctx.shared_mem_addr; + + msg->payload.memory.regions[*args->idx].userspace_addr = map->iova; + msg->payload.memory.regions[*args->idx].memory_size = map->size +1 ; + msg->payload.memory.regions[*args->idx].guest_phys_addr = map->iova; + msg->payload.memory.regions[*args->idx].mmap_offset = offset; + } + +assert (offset + msg->payload.memory.regions[*args->idx].memory_size <= + u->iso_mem_ctx.size); + (*args->idx)++; + +return false; +} +static int init_isolation_regions (struct vhost_dev *dev,VhostUserMsg *msg,int *fds,size_t *fd_num)@@ -1159,6 +1229,7 @@ static int init_isolation_regions(struct vhost_dev *dev,DMAMap *map;DMAMap vring_map;int r; +IOVATreeTraversalArgs trav_args; msg->hdr.request =VHOST_USER_SET_MEM_TABLE ;@@ -1244,6 +1315,27 @@ static int init_isolation_regions(struct vhost_dev *dev, } } + *fd_num =0 ; + trav_args.idx = fd_num; + trav_args.fds = fds; + trav_args.msg = msg; + trav_args.u = u; + trav_args.vring_iova = vring_map.iova; + trav_args.vring_size = total_vring_size; + trav_args.fds_size = nregions; + trav_args.vring_node_visited = false; + +vhost_iova_tree_foreach (u->iso_mem_ctx.tree, + vhost_user_fill_msg_reg_from_tree, &trav_args); + + msg->payload.memory.nregions = *fd_num; + +assert (*fd_num == nregions); + + msg->hdr.size =sizeof (msg->payload.memory.nregions); + msg->hdr.size +=sizeof (msg->payload.memory.padding); + msg->hdr.size += *fd_num *sizeof (VhostUserMemoryRegion); +return 0 ; }@@ -1251,6 +1343,7 @@ static int vhost_user_set_mem_table(struct vhost_dev *dev, struct vhost_memory *mem) {struct vhost_user *u = dev->opaque; +bool memory_isolation = u->user->memory_isolation;int fds[VHOST_MEMORY_BASELINE_NREGIONS ];size_t fd_num =0 ;bool do_postcopy = u->postcopy_listen && u->postcopy_fd.handler;@@ -1262,6 +1355,11 @@ static int vhost_user_set_mem_table(struct vhost_dev *dev,int ret;if (do_postcopy) { +/* Postcopy is not supported with memory isolation yet */ +if (memory_isolation) { +return -1 ; + } +/* * Postcopy has enough differences that it's best done in it's own * version @@ -1278,6 +1376,24 @@ static int vhost_user_set_mem_table(struct vhost_dev *dev, msg.hdr.flags |=VHOST_USER_NEED_REPLY_MASK ; } +if (memory_isolation) { + ret =init_isolation_regions (dev, &msg, fds, &fd_num); +if (ret <0 ) { +return ret; + } + + ret =vhost_user_write (dev, &msg, fds, fd_num); +if (ret <0 ) { +return ret; + } + +if (reply_supported) { +return process_message_reply (dev, &msg); + } + +return 0 ; + } +if (config_mem_slots) { ret =vhost_user_add_remove_regions (dev, &msg, reply_supported, false);if (ret <0 ) {
Re: [PATCH RFC v2 09/13] hw/virtio/vhost-user: add shadow virtqueues and eventfd intercepts
In reply to Connor KiteQuoted 32 lines · Connor Kite
Adds shadow virtqueues that will eventually be used to transfer data between device and host via bounce buffers when isolation mode is active. The svqs are initalized, and eventfd assignments are intercepted so that notifications come to svqs first before the guest or backend receive them.
Signed-off-by Connor Kite <[email protected]>--- hw/virtio/vhost-user.c | 136 ++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 119 insertions(+), 17 deletions(-)hw/virtio/vhost-user.c +2
-0@@ -18,6 +18,7 @@#include "hw/virtio/vhost-backend.h" #include "hw/virtio/virtio.h" #include "hw/virtio/virtio-net.h" +#include "hw/virtio/vhost-shadow-virtqueue.h" #include "hw/virtio/vhost-iova-tree.h" #include "chardev/char-fe.h" #include "io/channel-socket.h" @@ -331,6 +332,7 @@ typedef struct {size_t size;/* size of the mapped shared memory */ int fd;/* descriptor of anonymous file backing shared iso region */ Int128 iso_iova_offset;/* translation from IOVA to hva of iso region */ +GPtrArray *shadow_vqs;/* shadow vqs with vrings in iso region*/ } IsolationModeCtx;struct vhost_user {
hw/virtio/vhost-user.c static int vhost_user_set_mem_table_postcopy(struct vhost_dev *dev, · line 1133
Quoted 5 lines
hw/virtio/vhost-user.c +1
-1@@ -1128,15 +1130,38 @@ static int vhost_user_set_mem_table_postcopy(struct vhost_dev *dev,return 0 ; } -static void cleanup_isolation_regions (struct vhost_dev *dev) +static void vhost_user_svq_cleanup (struct vhost_user *u,bool reset)
It would be nice if there were documentation on what reset is supposed to do, because as-is I am confused that…
hw/virtio/vhost-user.c static int vhost_user_set_mem_table_postcopy(struct vhost_dev *dev, · line 1144
Quoted 11 lines
hw/virtio/vhost-user.c +11
-0+{ +VhostShadowVirtqueue *svq; +for (int i =0 ; i < u->iso_mem_ctx.shadow_vqs->len; i++) { + svq =g_ptr_array_index (u->iso_mem_ctx.shadow_vqs, i); +vhost_svq_stop (svq); +event_notifier_cleanup (&svq->hdev_call); +event_notifier_cleanup (&svq->hdev_kick); + } + +if (!reset) { +g_ptr_array_free (u->iso_mem_ctx.shadow_vqs, true);
…this function retains the array allocation when reset is true, but…
Quoted 4 lines
hw/virtio/vhost-user.c +4
-0+ } +} + +static void cleanup_isolation_regions (struct vhost_dev *dev,bool reset)
hw/virtio/vhost-user.c static int vhost_user_set_mem_table_postcopy(struct vhost_dev *dev, · line 1158
Quoted 10 lines
hw/virtio/vhost-user.c +3
-0{struct vhost_user *u = dev->opaque;if (u->iso_mem_ctx.shared_mem_addr) { +vhost_user_svq_cleanup (u, reset);vhost_iova_tree_delete (u->iso_mem_ctx.tree);qemu_memfd_free (u->iso_mem_ctx.shared_mem_addr, u->iso_mem_ctx.size, u->iso_mem_ctx.fd); + +GPtrArray *temp = u->iso_mem_ctx.shadow_vqs;
(Please don’t mix declarations and code.)
hw/virtio/vhost-user.c static int vhost_user_set_mem_table_postcopy(struct vhost_dev *dev, · line 1162
Quoted 4 lines
hw/virtio/vhost-user.c +3
-0memset (&u->iso_mem_ctx,0 ,sizeof (IsolationModeCtx)); + +if (!reset) { + u->iso_mem_ctx.shadow_vqs = temp;
…this function retains the array allocation only when reset is false.
Quoted 42 lines
hw/virtio/vhost-user.c +6
-4+ } + } }@@ -1234,7 +1259,7 @@ static int init_isolation_regions(struct vhost_dev *dev, msg->hdr.request =VHOST_USER_SET_MEM_TABLE ;/* In case of reset, clear old regions */ -cleanup_isolation_regions (dev); +cleanup_isolation_regions (dev, true);/* Gather information for bounce buffers to be mapped */ for (u_int32_t i =0 ; i < nregions; i++) {@@ -1267,7 +1292,7 @@ static int init_isolation_regions(struct vhost_dev *dev,if (err) {error_report_err (err); -cleanup_isolation_regions (dev); +cleanup_isolation_regions (dev, false);return -1 ; }@@ -1295,7 +1320,7 @@ static int init_isolation_regions(struct vhost_dev *dev, (hwaddr)u->iso_mem_ctx.shared_mem_addr);if (r !=IOVA_OK ) { -cleanup_isolation_regions (dev); +cleanup_isolation_regions (dev, false);return r; }@@ -1310,7 +1335,7 @@ static int init_isolation_regions(struct vhost_dev *dev, dev->mem->regions[i].guest_phys_addr);if (r !=IOVA_OK ) { -cleanup_isolation_regions (dev); +cleanup_isolation_regions (dev, false);return r; } }
hw/virtio/vhost-user.c static int vhost_set_vring_file(struct vhost_dev *dev, · line 1766
Quoted 4 lines
hw/virtio/vhost-user.c +1
-0@@ -1738,11 +1763,49 @@ static int vhost_set_vring_file(struct vhost_dev *dev,return 0 ; } +static int vhost_user_get_vq_index (struct vhost_dev *dev,int idx)
Slight nudge: It would be less churn just to pull up the declaration, not the whole function.
Quoted 7 lines
hw/virtio/vhost-user.c +6
-0+{ +assert (idx >= dev->vq_index && idx < dev->vq_index + dev->nvqs); + +return idx; +} + static int vhost_user_set_vring_kick(struct vhost_dev *dev,
hw/virtio/vhost-user.c static int vhost_set_vring_file(struct vhost_dev *dev, · line 1782
Quoted 10 lines
hw/virtio/vhost-user.c +7
-1struct vhost_vring_file *file) { -int ret =vhost_set_vring_file (dev,VHOST_USER_SET_VRING_KICK , file); +struct vhost_user *u = dev->opaque; +int svq_idx = file->index - dev->vq_index; +VhostShadowVirtqueue *svq =NULL ; +struct vhost_vring_file vr_file = *file; +int ret; + +vhost_user_get_vq_index (dev, file->index);/* bounds checking */
I think it would be nicer to use the return value, i.e.
svq_idx = vhost_user_get_vq_index(dev, file->index) - dev_vq_index;
Quoted 17 lines
hw/virtio/vhost-user.c +17
-0+ +if (u->user->memory_isolation) { + svq =g_ptr_array_index (u->iso_mem_ctx.shadow_vqs, svq_idx); +vhost_svq_set_svq_kick_fd (svq, file->fd); + +if (file->fd !=-1 ) { +if (!svq->hdev_kick.initialized) { + ret =event_notifier_init (&svq->hdev_kick,0 ); +if (ret <0 ) { +event_notifier_cleanup (&svq->hdev_kick); +error_report ("Failed to create kick event notifier" ); +return ret; + } + } + + vr_file.fd =event_notifier_get_fd (&svq->hdev_kick); + }else {
hw/virtio/vhost-user.c static int vhost_set_vring_file(struct vhost_dev *dev, · line 1809
Quoted 10 lines
hw/virtio/vhost-user.c +8
-0+event_notifier_cleanup (&svq->hdev_kick); + } + } + + ret =vhost_set_vring_file (dev,VHOST_USER_SET_VRING_KICK , &vr_file);if (ret <0 ) { +if (svq !=NULL ) { +event_notifier_cleanup (&svq->hdev_kick); + }return ret;
The same pattern exists below, too, which might be another case for a fail pattern.
Another note: What happens here if file->fd == -1? Should we then not rather do the opposite? (Which probably doesn’t really work) Or maybe rather clean up only at the end, when it’s no longer possible to run into an error, in case of file->fd == -1?
Hanna
Quoted 112 lines
hw/virtio/vhost-user.c +50
-11}@@ -1750,15 +1813,18 @@ static int vhost_user_set_vring_kick(struct vhost_dev *dev,* Inject a kick in case the back-end only starts vring processing upon * receiving a kick. The spec suggests this to improve compatibility. */ -if (file->fd !=-1 ) { +if (vr_file.fd !=-1 ) {uint64_t val =1 ;ssize_t nwritten;do { - nwritten =write (file->fd, &val,sizeof (val)); + nwritten =write (vr_file.fd, &val,sizeof (val)); }while (nwritten <0 && errno ==EINTR );if (nwritten <0 && errno !=EAGAIN /* back-end can already read */ ) { +if (svq !=NULL ) { +event_notifier_cleanup (&svq->hdev_kick); + }return -errno; } }@@ -1769,7 +1835,35 @@ static int vhost_user_set_vring_kick(struct vhost_dev *dev,static int vhost_user_set_vring_call (struct vhost_dev *dev,struct vhost_vring_file *file) { -return vhost_set_vring_file (dev,VHOST_USER_SET_VRING_CALL , file); +struct vhost_user *u = dev->opaque; +int svq_idx = file->index - dev->vq_index; +VhostShadowVirtqueue *svq =NULL ; +struct vhost_vring_file vr_file = *file; +int ret; + +vhost_user_get_vq_index (dev, file->index);/* bounds checking */ + +if (u->user->memory_isolation) { + svq =g_ptr_array_index (u->iso_mem_ctx.shadow_vqs, svq_idx); +vhost_svq_set_svq_call_fd (svq, file->fd); + +if (file->fd !=-1 ) { +if (!svq->hdev_call.initialized) { + ret =event_notifier_init (&svq->hdev_call,0 ); +if (ret <0 ) { +event_notifier_cleanup (&svq->hdev_call); +error_report ("Failed to create call event notifier" ); +return ret; + } + } + + vr_file.fd =event_notifier_get_fd (&svq->hdev_call); + }else { +event_notifier_cleanup (&svq->hdev_call); + } + } + +return vhost_set_vring_file (dev,VHOST_USER_SET_VRING_CALL , &vr_file); } static int vhost_user_set_vring_err(struct vhost_dev *dev,@@ -2763,6 +2857,17 @@ static int vhost_user_postcopy_notifier(NotifierWithReturn *notifier,return 0 ; } +static void vhost_user_init_svq (struct vhost_dev *dev,struct vhost_user *u) +{ +/*Modified from vhost-vdpa*/ + u->iso_mem_ctx.shadow_vqs =g_ptr_array_new_full (dev->nvqs, vhost_svq_free); +for (int i =0 ; i < dev->nvqs; i++) { +VhostShadowVirtqueue *svq; + svq =vhost_svq_new (NULL ,NULL ); +g_ptr_array_add (u->iso_mem_ctx.shadow_vqs, svq); + } +} +static int vhost_user_backend_init (struct vhost_dev *dev,void *opaque,Error **errp) {@@ -2907,6 +3012,10 @@ static int vhost_user_backend_init(struct vhost_dev *dev, void *opaque, u->postcopy_notifier.notify = vhost_user_postcopy_notifier;postcopy_add_notifier (&u->postcopy_notifier); +if (vus->memory_isolation) { +vhost_user_init_svq (dev, u); + } +return 0 ; }@@ -2935,20 +3044,13 @@ static int vhost_user_backend_cleanup(struct vhost_dev *dev)g_free (u->region_rb_offset); u->region_rb_offset =NULL ; u->region_rb_len =0 ; -cleanup_isolation_regions (dev); +cleanup_isolation_regions (dev, false);g_free (u); dev->opaque =0 ;return 0 ; } -static int vhost_user_get_vq_index (struct vhost_dev *dev,int idx) -{ -assert (idx >= dev->vq_index && idx < dev->vq_index + dev->nvqs); - -return idx; -} -static int vhost_user_memslots_limit (struct vhost_dev *dev) {struct vhost_user *u = dev->opaque;
Re: [PATCH RFC v2 05/13] hw/virtio/vhost-shadow-virtqueue: specified vring placement
In reply to Connor KiteQuoted 38 lines · Connor Kite
By default svq vrings are placed in an anonymous memory map. As svqs will be leveraged to enable memory isolation in vhost-user, it is useful to be able to place the vrings in a shared isolation memory region.
Adds the option to specify vring placement by providing a vring base address before starting the svq.
Signed-off-by Connor Kite <[email protected]>--- hw/virtio/vhost-shadow-virtqueue.c | 69 ++++++++++++++++++++++++++++++++------ hw/virtio/vhost-shadow-virtqueue.h | 8 ++++- 2 files changed, 66 insertions(+), 11 deletions(-)hw/virtio/vhost-shadow-virtqueue.c +9
-0@@ -812,6 +812,13 @@ size_t vhost_svq_device_area_size(const VhostShadowVirtqueue *svq)return ROUND_UP (used_size,qemu_real_host_page_size ()); } +size_t vhost_svq_vring_total_size (VirtIODevice *vdev,VirtQueue *vq) +{ +VhostShadowVirtqueue svq; + svq.vring.num =virtio_queue_get_num (vdev,virtio_get_queue_index (vq)); +return vhost_svq_driver_area_size (&svq) +vhost_svq_device_area_size (&svq); +} +/** * Set a new file descriptor for the guest to kick the SVQ and notify for avail * @@ -842,6 +849,19 @@ void vhost_svq_set_svq_kick_fd(VhostShadowVirtqueue *svq, int svq_kick_fd) } } +/** +* Set vring base address if using fixed locations
hw/virtio/vhost-shadow-virtqueue.c void vhost_svq_set_svq_kick_fd(VhostShadowVirtqueue *svq, int svq_kick_fd) · line 863
Quoted 10 lines
hw/virtio/vhost-shadow-virtqueue.c +10
-0+* +* @svq: Shadow Virtqueue +* @addr: Points to new base address +*/ + +void vhost_svq_set_base_addr (VhostShadowVirtqueue *svq,void *addr) + { + svq->base_addr = addr; + } +
Would it work to keep that allocation detail in SVQ, instead of letting it leak outside? Something like a flag to allocate the areas with mmap or qemu_memfd_alloc, instead of the base_addr itself.
Quoted 128 lines
hw/virtio/vhost-shadow-virtqueue.c +40
-10+/** * Start the shadow virtqueue operation. * @@ -849,8 +869,10 @@ void vhost_svq_set_svq_kick_fd(VhostShadowVirtqueue *svq, int svq_kick_fd)* @vdev: VirtIO device * @vq: Virtqueue to shadow * @iova_tree: Tree to perform descriptors translations +* +* Return 0 on success, -errno on failure */ -void vhost_svq_start (VhostShadowVirtqueue *svq,VirtIODevice *vdev, +int vhost_svq_start (VhostShadowVirtqueue *svq,VirtIODevice *vdev,VirtQueue *vq,VhostIOVATree *iova_tree) {size_t desc_size;@@ -868,14 +890,27 @@ void vhost_svq_start(VhostShadowVirtqueue *svq, VirtIODevice *vdev, svq->vring.num =virtio_queue_get_num (vdev,virtio_get_queue_index (vq)); svq->num_free = svq->vring.num; - svq->vring.desc =mmap (NULL ,vhost_svq_driver_area_size (svq), -PROT_READ |PROT_WRITE ,MAP_SHARED |MAP_ANONYMOUS , --1 ,0 ); desc_size =sizeof (vring_desc_t) * svq->vring.num; - svq->vring.avail = (void *)((char *)svq->vring.desc + desc_size); - svq->vring.used =mmap (NULL ,vhost_svq_device_area_size (svq), -PROT_READ |PROT_WRITE ,MAP_SHARED |MAP_ANONYMOUS , --1 ,0 ); +if (svq->base_addr ==NULL ) { + svq->vring.desc =mmap (NULL ,vhost_svq_driver_area_size (svq), +PROT_READ |PROT_WRITE ,MAP_SHARED |MAP_ANONYMOUS , +-1 ,0 ); + svq->vring.avail = (void *)((char *)svq->vring.desc + desc_size); + svq->vring.used =mmap (NULL ,vhost_svq_device_area_size (svq), +PROT_READ |PROT_WRITE ,MAP_SHARED |MAP_ANONYMOUS , +-1 ,0 ); + }else { + svq->vring.desc = (void *)svq->base_addr; + svq->vring.avail = (void *)((char *)svq->vring.desc + desc_size); + svq->vring.used = (void *)((char *)svq->base_addr + +vhost_svq_driver_area_size (svq)); + +if ((uint64_t )svq->vring.used +vhost_svq_device_area_size (svq) -1 < + (uint64_t )svq->vring.desc) { +error_report ("Invalid shadow vring location" ); +return -ENOMEM ; + } + } svq->desc_state =g_new0 (SVQDescState, svq->vring.num);if (virtio_vdev_has_feature (svq->vdev,VIRTIO_F_IN_ORDER )) { svq->batch_last.id =VIRTIO_RING_NOT_IN_BATCH ;@@ -884,6 +919,8 @@ void vhost_svq_start(VhostShadowVirtqueue *svq, VirtIODevice *vdev, svq->desc_state[i].next = i +1 ; } } + +return 0 ; }/** @@ -920,8 +957,19 @@ void vhost_svq_stop(VhostShadowVirtqueue *svq) } svq->vq =NULL ;g_free (svq->desc_state); -munmap (svq->vring.desc,vhost_svq_driver_area_size (svq)); -munmap (svq->vring.used,vhost_svq_device_area_size (svq)); + +if (!svq->base_addr) { +munmap (svq->vring.desc,vhost_svq_driver_area_size (svq)); +munmap (svq->vring.used,vhost_svq_device_area_size (svq)); + }else { +if (svq->vring.desc) { +memset (svq->vring.desc,0 ,vhost_svq_driver_area_size (svq)); + } +if (svq->vring.used) { +memset (svq->vring.used,0 ,vhost_svq_device_area_size (svq)); + } + } +event_notifier_set_handler (&svq->hdev_call,NULL ); }@@ -940,6 +988,7 @@ VhostShadowVirtqueue *vhost_svq_new(const VhostShadowVirtqueueOps *ops,event_notifier_init_fd (&svq->svq_kick,VHOST_FILE_UNBIND ); svq->ops = ops; svq->ops_opaque = ops_opaque; + svq->base_addr =NULL ;return svq; }hw/virtio/vhost-shadow-virtqueue.h +7
-2@@ -150,6 +150,9 @@ typedef struct VhostShadowVirtqueue {/* Size of SVQ vring free descriptors */ uint16_t num_free; + +/* Location assigned to vrings if not in default anon memory map */ +void *base_addr; } VhostShadowVirtqueue;bool vhost_svq_valid_features (uint64_t features,Error **errp);@@ -169,8 +172,9 @@ void vhost_svq_get_vring_addr(const VhostShadowVirtqueue *svq, struct vhost_vring_addr *addr);size_t vhost_svq_driver_area_size (const VhostShadowVirtqueue *svq);size_t vhost_svq_device_area_size (const VhostShadowVirtqueue *svq); +size_t vhost_svq_vring_total_size (VirtIODevice *vdev,VirtQueue *vq); -void vhost_svq_start (VhostShadowVirtqueue *svq,VirtIODevice *vdev, +int vhost_svq_start (VhostShadowVirtqueue *svq,VirtIODevice *vdev,VirtQueue *vq,VhostIOVATree *iova_tree);void vhost_svq_stop (VhostShadowVirtqueue *svq);@@ -178,6 +182,8 @@ VhostShadowVirtqueue *vhost_svq_new(const VhostShadowVirtqueueOps *ops, void *ops_opaque);void vhost_svq_free (gpointer vq); +void vhost_svq_set_base_addr (VhostShadowVirtqueue *svq,void *addr); +G_DEFINE_AUTOPTR_CLEANUP_FUNC (VhostShadowVirtqueue, vhost_svq_free);#endif --2.43.0
Re: [PATCH RFC v2 10/13] hw/virtio/vhost-user: handle data movement with shadow vqs
In reply to Connor KiteQuoted 226 lines · Connor Kite
- Add start logic for shadow virtqueues, which sets vring addresses.
- Update logic for sending vring addresses to backend to point to the shadow vrings when isolation mode is active.
- Implement handlers for intercepted avail and used descriptors. These handlers copy buffer contents between bounce buffers in the isolation region and the buffers made available by the guest
- Implement logic to stop svqsSigned-off-by Connor Kite <[email protected]>--- hw/virtio/vhost-shadow-virtqueue.c | 2 +- hw/virtio/vhost-shadow-virtqueue.h | 1 + hw/virtio/vhost-user.c | 292 ++++++++++++++++++++++++++++++++++++- 3 files changed, 286 insertions(+), 9 deletions(-)hw/virtio/vhost-shadow-virtqueue.c +1
-1@@ -350,7 +350,7 @@ int vhost_svq_add(VhostShadowVirtqueue *svq, const struct iovec *out_sg, }/* Convenience wrapper to add a guest's element to SVQ */ -static int vhost_svq_add_element (VhostShadowVirtqueue *svq, +int vhost_svq_add_element (VhostShadowVirtqueue *svq,VirtQueueElement *elem) { return vhost_svq_add(svq, elem->out_sg, elem->out_num, elem->out_addr,hw/virtio/vhost-shadow-virtqueue.h +1
-0@@ -183,6 +183,7 @@ VhostShadowVirtqueue *vhost_svq_new(const VhostShadowVirtqueueOps *ops,void vhost_svq_free (gpointer vq);void vhost_svq_set_base_addr (VhostShadowVirtqueue *svq,void *addr); +int vhost_svq_add_element (VhostShadowVirtqueue *svq,VirtQueueElement *elem);G_DEFINE_AUTOPTR_CLEANUP_FUNC (VhostShadowVirtqueue, vhost_svq_free);hw/virtio/vhost-user.c +177
-0@@ -1364,6 +1364,231 @@ static int init_isolation_regions(struct vhost_dev *dev,return 0 ; } +static inline int vhost_user_get_reg_idx (struct vhost_dev *dev,hwaddr gpa) +{ +int i; +struct vhost_memory_region *reg; + +for (i =0 ; i < dev->mem->nregions; i++) { + reg = dev->mem->regions + i; + +if (gpa >= reg->guest_phys_addr && + reg->guest_phys_addr + reg->memory_size > gpa) { +return i; + } + } + +return -1 ; +} + +static int vhost_user_svq_handle_used (VhostShadowVirtqueue *svq, +VirtQueueElement *elem, +void *opaque) +{ +uint64_t offset; +void *dst; +void *src; +size_t len, rem; +void *reg_last_addr; +void *reg_first_addr; +struct vhost_dev *dev = opaque; +struct vhost_user *u = dev->opaque; +void *shmem_addr = u->iso_mem_ctx.shared_mem_addr; +size_t shmem_size = u->iso_mem_ctx.size; +const DMAMap *map; +DMAMap needle; +int reg_idx; + +for (int i =0 ; i < elem->in_num; i++) { + needle.translated_addr = elem->in_addr[i]; + needle.size = elem->in_sg[i].iov_len -1 ; + map =vhost_iova_tree_find_gpa (svq->iova_tree, &needle); + +if (!map) { +return -EFAULT ; + } + + offset = needle.translated_addr - map->translated_addr; + src = (void *)int128_get64 (int128_add (int128_make64 (map->iova + + offset), u->iso_mem_ctx.iso_iova_offset)); + dst = elem->in_sg[i].iov_base; + len = elem->in_sg[i].iov_len; + +/* Confirm that buffer range is fully within iso region */ +if ((uint64_t )src + len -1 > (uint64_t )shmem_addr + shmem_size -1 || + (uint64_t )src + len <= (uint64_t )src || + (uint64_t )src < (uint64_t )shmem_addr) { + +return -EFAULT ; + } + + reg_idx =vhost_user_get_reg_idx (dev, needle.translated_addr); +if (reg_idx <0 ) { +return -EFAULT ; + } + + reg_first_addr = (void *)dev->mem->regions[reg_idx].userspace_addr; + reg_last_addr = (void *)(dev->mem->regions[reg_idx].userspace_addr + + dev->mem->regions[reg_idx].memory_size -1 ); + +/* Confirm that hva from elem matches expected vhost memory region */ +if (dst < reg_first_addr || dst > reg_last_addr) { +return -EFAULT ; + } + +/* +* copy buffer contents from shared memory into guest memory. If +* the buffer extends across region boundaries, it must be split and +* copied to the correct regions. +*/ +while ((uint64_t )reg_last_addr - (uint64_t )dst +1 < len) { + rem = ((uint64_t )dst + len -1 ) - (uint64_t )reg_last_addr; + len -= rem; +memcpy (dst, src, len); + + reg_idx++; +if (reg_idx >= dev->mem->nregions) { +return -EFAULT ; + } + + src = (void *)((uint64_t )src + len); + dst = (void *)dev->mem->regions[reg_idx].userspace_addr; + len = rem; + reg_first_addr = (void *)dev->mem->regions[reg_idx].userspace_addr; + reg_last_addr = (void *)(dev->mem->regions[reg_idx].userspace_addr + + dev->mem->regions[reg_idx].memory_size -1 ); + } + +memcpy (dst, src, len); + } + +return 0 ; +} + +static int vhost_user_svq_handle_avail (VhostShadowVirtqueue *svq, +VirtQueueElement *elem, +void *opaque) +{ +hwaddr offset; +const DMAMap *map; +DMAMap needle; +void *dst; +void *src; +void *reg_first_addr; +void *reg_last_addr; +size_t len, rem; +struct vhost_dev *dev = opaque; +struct vhost_user *u = dev->opaque; +void *shmem_addr = u->iso_mem_ctx.shared_mem_addr; +size_t shmem_size = u->iso_mem_ctx.size; +int reg_idx; + +for (int i =0 ; i < elem->out_num; i++) { + needle.translated_addr = elem->out_addr[i]; + needle.size = elem->out_sg[i].iov_len -1 ; + map =vhost_iova_tree_find_gpa (svq->iova_tree, &needle); + +if (!map) { +return -EFAULT ; + } + + offset = needle.translated_addr - map->translated_addr; + dst = (void *)int128_get64 (int128_add (int128_make64 (map->iova + + offset), u->iso_mem_ctx.iso_iova_offset)); + src = elem->out_sg[i].iov_base; + len = elem->out_sg[i].iov_len; + +/* Confirm that buffer range is fully within iso region */ +if ((uint64_t )dst + len -1 > (uint64_t )shmem_addr + shmem_size -1 || + (uint64_t )dst + len <= (uint64_t )dst || + (uint64_t )dst < (uint64_t )shmem_addr) { + +return -EFAULT ; + } + + reg_idx =vhost_user_get_reg_idx (dev, needle.translated_addr); +if (reg_idx <0 ) { +return -EFAULT ; + } + + reg_first_addr = (void *)dev->mem->regions[reg_idx].userspace_addr; + reg_last_addr = (void *)(dev->mem->regions[reg_idx].userspace_addr + + dev->mem->regions[reg_idx].memory_size -1 ); + +/* Confirm that hva from elem matches expected vhost memory region */ +if (src < reg_first_addr || src > reg_last_addr) { +return -EFAULT ; + } + +/* +* copy buffer contents from guest memory into shared memory. If +* the buffer extends across region boundaries, it must be split and +* copied from the correct regions. +*/ +while ((uint64_t )reg_last_addr - (uint64_t )src +1 < len) { + rem = ((uint64_t )src + len -1 ) - (uint64_t )reg_last_addr; + len -= rem; +memcpy (dst, src, len); + + reg_idx++; +if (reg_idx >= dev->mem->nregions) { +return -EFAULT ; + } + + dst = (void *)((uint64_t )dst + len); + src = (void *)dev->mem->regions[reg_idx].userspace_addr; + len = rem; + + reg_first_addr = (void *)dev->mem->regions[reg_idx].userspace_addr; + reg_last_addr = (void *)(dev->mem->regions[reg_idx].userspace_addr +
hw/virtio/vhost-user.c static int init_isolation_regions(struct vhost_dev *dev, · line 1553
Quoted 10 lines
hw/virtio/vhost-user.c +10
-0+ dev->mem->regions[reg_idx].memory_size - 1); + } + +memcpy (dst, src, len); + } + +vhost_svq_add_element (svq, elem); + +return 0 ; +}
You can handle all buffer memcpy operations within the SVQ itself, and the net CVQ could also reuse and benefit from this. Indirect descriptor optimizations proposed in other threads can also benefit from this. That would make the patches much simpler.
Quoted 162 lines
hw/virtio/vhost-user.c +97
-9+ +static int vhost_user_get_vq_index (struct vhost_dev *dev,int idx) +{ +assert (idx >= dev->vq_index && idx < dev->vq_index + dev->nvqs); + +return idx; +} + +static int vhost_user_svqs_vring_map (struct vhost_dev *dev) +{ +int ret; +struct vhost_user *u = dev->opaque; +void *vring_base = u->iso_mem_ctx.vring_hva_addr; +uint64_t vring_last = (uint64_t )vring_base + + u->iso_mem_ctx.vring_region_size -1 ; + +for (int i =0 ; i < u->iso_mem_ctx.shadow_vqs->len; i++) { +vhost_user_get_vq_index (dev, dev->vq_index + i);/* bounds checking */ + +VirtQueue *vq =virtio_get_queue (dev->vdev, dev->vq_index + i); +VhostShadowVirtqueue *svq = +g_ptr_array_index (u->iso_mem_ctx.shadow_vqs, i); + +assert ((uint64_t )vring_base + +vhost_svq_vring_total_size (dev->vdev, vq) -1 <= vring_last); + +vhost_svq_set_base_addr (svq, vring_base); + ret =vhost_svq_start (svq, dev->vdev, vq, u->iso_mem_ctx.tree); +if (ret <0 ) { +return ret; + } + vring_base = (void *)((uint64_t )vring_base + +vhost_svq_vring_total_size (dev->vdev, vq)); + } + +return 0 ; +} +static int vhost_user_set_mem_table (struct vhost_dev *dev,struct vhost_memory *mem) {@@ -1407,6 +1632,11 @@ static int vhost_user_set_mem_table(struct vhost_dev *dev,return ret; } + ret =vhost_user_svqs_vring_map (dev); +if (ret <0 ) { +return ret; + } + ret =vhost_user_write (dev, &msg, fds, fd_num);if (ret <0 ) {return ret;@@ -1763,13 +1993,6 @@ static int vhost_set_vring_file(struct vhost_dev *dev,return 0 ; } -static int vhost_user_get_vq_index (struct vhost_dev *dev,int idx) -{ -assert (idx >= dev->vq_index && idx < dev->vq_index + dev->nvqs); - -return idx; -} -static int vhost_user_set_vring_kick (struct vhost_dev *dev,struct vhost_vring_file *file) {@@ -1875,6 +2098,8 @@ static int vhost_user_set_vring_err(struct vhost_dev *dev,static int vhost_user_set_vring_addr (struct vhost_dev *dev,struct vhost_vring_addr *addr) { +struct vhost_user *u = dev->opaque; +ptrdiff_t offset = u->iso_mem_ctx.iso_iova_offset;VhostUserMsg msg = { .hdr.request =VHOST_USER_SET_VRING_ADDR , .hdr.flags =VHOST_USER_VERSION ,@@ -1882,6 +2107,25 @@ static int vhost_user_set_vring_addr(struct vhost_dev *dev, .hdr.size = sizeof(msg.payload.addr), }; +if (u->user->memory_isolation) { +int svq_idx; +VhostShadowVirtqueue *svq; +struct vhost_vring_addr svq_addr; + +vhost_user_get_vq_index (dev, addr->index);/* bounds checking */ + svq_idx = addr->index - dev->vq_index; + svq =g_ptr_array_index (u->iso_mem_ctx.shadow_vqs, + svq_idx); + + svq_addr.avail_user_addr = (uint64_t )(uintptr_t )svq->vring.avail - + offset; + svq_addr.desc_user_addr = (uint64_t )(uintptr_t )svq->vring.desc - offset; + svq_addr.used_user_addr = (uint64_t )(uintptr_t )svq->vring.used - offset; + svq_addr.index = addr->index; + + msg.payload.addr = svq_addr; + } +/* * wait for a reply if logging is enabled to make sure * backend is actually logging changes @@ -2857,13 +3101,18 @@ static int vhost_user_postcopy_notifier(NotifierWithReturn *notifier,return 0 ; } +static const VhostShadowVirtqueueOps vhost_user_svq_ops = { + .avail_handler = vhost_user_svq_handle_avail, + .used_callback = vhost_user_svq_handle_used +}; +static void vhost_user_init_svq (struct vhost_dev *dev,struct vhost_user *u) {/*Modified from vhost-vdpa*/ u->iso_mem_ctx.shadow_vqs =g_ptr_array_new_full (dev->nvqs, vhost_svq_free);for (int i =0 ; i < dev->nvqs; i++) {VhostShadowVirtqueue *svq; - svq =vhost_svq_new (NULL ,NULL ); + svq =vhost_svq_new (&vhost_user_svq_ops, dev);g_ptr_array_add (u->iso_mem_ctx.shadow_vqs, svq); } }@@ -3562,8 +3811,35 @@ void vhost_user_async_close(DeviceState *d, } } +static void vhost_user_svqs_stop (struct vhost_dev *dev) +{ +struct vhost_user *u = dev->opaque; +for (int i =0 ; i < u->iso_mem_ctx.shadow_vqs->len; i++) { +vhost_svq_stop (g_ptr_array_index (u->iso_mem_ctx.shadow_vqs, i)); + } +} +static int vhost_user_dev_start (struct vhost_dev *dev,bool started) { +struct vhost_user *u = dev->opaque; +if (u->user->memory_isolation) { +if (vhost_dev_has_iommu (dev)) { +error_report ("Memory isolation is not supported with IOMMU enabled." +"Please disable one and try again" ); +return -1 ; + } + +if (virtio_vdev_has_feature (dev->vdev,VIRTIO_F_RING_PACKED )) { +error_report ("Memory isolation is not supported with packed" +"vrings. Please use split vrings" ); +return -1 ; + } + +if (!started) { +vhost_user_svqs_stop (dev); + } + } +if (!vhost_user_has_protocol_feature (dev,VHOST_USER_PROTOCOL_F_STATUS )) {return 0 ; } --2.43.0
Re: [PATCH RFC v2 08/13] hw/virtio/vhost-user: send isolation regions to device
In reply to Connor KiteQuoted 79 lines · Connor Kite
Adds features to fill a
vhost_user_set_mem_tablemessage with the addresses of isolation memory regions corresponding to bounce buffers and vrings.Signed-off-by Connor Kite <[email protected]>--- hw/virtio/vhost-user.c | 118 ++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 117 insertions(+), 1 deletion(-)hw/virtio/vhost-user.c +60
-1@@ -1140,7 +1140,77 @@ static void cleanup_isolation_regions(struct vhost_dev *dev) } } -__attribute__((unused)) +typedef struct { +VhostUserMsg *msg; +struct vhost_user *u; +int *fds; +size_t fds_size; +uint64_t vring_iova; +size_t vring_size; +bool vring_node_visited; +size_t *idx; +}IOVATreeTraversalArgs ; + +static gboolean vhost_user_fill_msg_reg_from_tree (gpointer key, +gpointer value, +gpointer data) +{ +IOVATreeTraversalArgs *args = data; +struct vhost_user *u; +VhostUserMsg *msg = args->msg; +DMAMap *map = key; +uint64_t offset; + +assert (args && key && value); +if (!args->vring_node_visited) { + args->vring_node_visited = true; +return false; + } + + u = args->u; +assert (*args->idx < args->fds_size); + + args->fds[*args->idx] = args->u->iso_mem_ctx.fd; + +/* +* If the number of regions is fixed, it would be wasteful to use one for +* only the vrings. The first vhost_iova_tree element is always +* reserved for the vrings, so we can simply combine the first and second +* elements, which are contiguous in IOVA space, when sending regions to +* the backend. +*/ +if (*args->idx ==0 ) { + offset = u->iso_mem_ctx.vring_hva_addr - u->iso_mem_ctx.shared_mem_addr; + msg->payload.memory.regions[*args->idx].userspace_addr = + args->vring_iova; +/* +* The size from the iova tree is inclusive, so 1 is added to it. +* args->vring_size is exclusive, so no addition is required. +*/ + msg->payload.memory.regions[*args->idx].memory_size = + args->vring_size + map->size +1 ; + msg->payload.memory.regions[*args->idx].guest_phys_addr = + args->vring_iova; + msg->payload.memory.regions[*args->idx].mmap_offset = offset; + }else { +/* Use 128 bit operation in unlikely case of negative iso_iova_offset */ + offset =int128_get64 (int128_add (int128_make64 (map->iova), + u->iso_mem_ctx.iso_iova_offset)) - + (uint64_t )u->iso_mem_ctx.shared_mem_addr; + + msg->payload.memory.regions[*args->idx].userspace_addr = map->iova; + msg->payload.memory.regions[*args->idx].memory_size = map->size +1 ;
hw/virtio/vhost-user.c static void cleanup_isolation_regions(struct vhost_dev *dev) · line 1212
Quoted 10 lines
hw/virtio/vhost-user.c +10
-0+ msg->payload.memory.regions[*args->idx].guest_phys_addr = map->iova; + msg->payload.memory.regions[*args->idx].mmap_offset = offset; + } + +assert (offset + msg->payload.memory.regions[*args->idx].memory_size <= + u->iso_mem_ctx.size); + (*args->idx)++; + +return false; +}
The iterator is already inconvenient in the gtree, and the plan is to remove its usage when glib minimum version is updated and support for better functions are mandatory. Why not add a function to SVQ to write the nodes into an array and avoid moving the interface up?
Quoted 89 lines
hw/virtio/vhost-user.c +47
-1+static int init_isolation_regions (struct vhost_dev *dev,VhostUserMsg *msg,int *fds,size_t *fd_num)@@ -1159,6 +1229,7 @@ static int init_isolation_regions(struct vhost_dev *dev,DMAMap *map;DMAMap vring_map;int r; +IOVATreeTraversalArgs trav_args; msg->hdr.request =VHOST_USER_SET_MEM_TABLE ;@@ -1244,6 +1315,27 @@ static int init_isolation_regions(struct vhost_dev *dev, } } + *fd_num =0 ; + trav_args.idx = fd_num; + trav_args.fds = fds; + trav_args.msg = msg; + trav_args.u = u; + trav_args.vring_iova = vring_map.iova; + trav_args.vring_size = total_vring_size; + trav_args.fds_size = nregions; + trav_args.vring_node_visited = false; + +vhost_iova_tree_foreach (u->iso_mem_ctx.tree, + vhost_user_fill_msg_reg_from_tree, &trav_args); + + msg->payload.memory.nregions = *fd_num; + +assert (*fd_num == nregions); + + msg->hdr.size =sizeof (msg->payload.memory.nregions); + msg->hdr.size +=sizeof (msg->payload.memory.padding); + msg->hdr.size += *fd_num *sizeof (VhostUserMemoryRegion); +return 0 ; }@@ -1251,6 +1343,7 @@ static int vhost_user_set_mem_table(struct vhost_dev *dev, struct vhost_memory *mem) {struct vhost_user *u = dev->opaque; +bool memory_isolation = u->user->memory_isolation;int fds[VHOST_MEMORY_BASELINE_NREGIONS ];size_t fd_num =0 ;bool do_postcopy = u->postcopy_listen && u->postcopy_fd.handler;@@ -1262,6 +1355,11 @@ static int vhost_user_set_mem_table(struct vhost_dev *dev,int ret;if (do_postcopy) { +/* Postcopy is not supported with memory isolation yet */ +if (memory_isolation) { +return -1 ; + } +/* * Postcopy has enough differences that it's best done in it's own * version @@ -1278,6 +1376,24 @@ static int vhost_user_set_mem_table(struct vhost_dev *dev, msg.hdr.flags |=VHOST_USER_NEED_REPLY_MASK ; } +if (memory_isolation) { + ret =init_isolation_regions (dev, &msg, fds, &fd_num); +if (ret <0 ) { +return ret; + } + + ret =vhost_user_write (dev, &msg, fds, fd_num); +if (ret <0 ) { +return ret; + } + +if (reply_supported) { +return process_message_reply (dev, &msg); + } + +return 0 ; + } +if (config_mem_slots) { ret =vhost_user_add_remove_regions (dev, &msg, reply_supported, false);if (ret <0 ) { --2.43.0
Re: [PATCH RFC v2 05/13] hw/virtio/vhost-shadow-virtqueue: specified vring placement
In reply to Eugenio Perez MartinQuoted 38 lines · Eugenio Perez Martin
Quoted 36 lines · Connor Kite
By default svq vrings are placed in an anonymous memory map. As svqs will be leveraged to enable memory isolation in vhost-user, it is useful to be able to place the vrings in a shared isolation memory region.
Adds the option to specify vring placement by providing a vring base address before starting the svq.
Signed-off-by Connor Kite <[email protected]>--- hw/virtio/vhost-shadow-virtqueue.c | 69 ++++++++++++++++++++++++++++++++------ hw/virtio/vhost-shadow-virtqueue.h | 8 ++++- 2 files changed, 66 insertions(+), 11 deletions(-)hw/virtio/vhost-shadow-virtqueue.c +7
-0@@ -812,6 +812,13 @@ size_t vhost_svq_device_area_size(const VhostShadowVirtqueue *svq)return ROUND_UP (used_size,qemu_real_host_page_size ()); } +size_t vhost_svq_vring_total_size (VirtIODevice *vdev,VirtQueue *vq) +{ +VhostShadowVirtqueue svq; + svq.vring.num =virtio_queue_get_num (vdev,virtio_get_queue_index (vq)); +return vhost_svq_driver_area_size (&svq) +vhost_svq_device_area_size (&svq); +} +/** * Set a new file descriptor for the guest to kick the SVQ and notify for avail * @@ -842,6 +849,19 @@ void vhost_svq_set_svq_kick_fd(VhostShadowVirtqueue *svq, int svq_kick_fd) } }
Quoted 17 lines
hw/virtio/vhost-shadow-virtqueue.c void vhost_svq_set_svq_kick_fd(VhostShadowVirtqueue *svq, int svq_kick_fd) · line 863
Quoted 12 lines
hw/virtio/vhost-shadow-virtqueue.c +12
-0+/** +* Set vring base address if using fixed locations +* +* @svq: Shadow Virtqueue +* @addr: Points to new base address +*/ + +void vhost_svq_set_base_addr (VhostShadowVirtqueue *svq,void *addr) + { + svq->base_addr = addr; + } +Would it work to keep that allocation detail in SVQ, instead of letting it leak outside? Something like a flag to allocate the areas with mmap or
qemu_memfd_alloc, instead of thebase_addritself.
For the purposes of the isolation mode as it currently stands, I'm not sure the allocation can be entirely hidden without adding significant complexity. The vrings need to be allocated in a region that gets sent to the vhost-user backend. If VHOST_USER_PROTOCOL_F_CONFIGURE_MEM_SLOTS isn't negotiated, then we are limited to 8 regions in total, so it is beneficial to be able to allocate them all in the same region, and in fact, the vrings are currently tacked onto the beginning of one of the bounce buffer regions so that they don't count against the limit.
Having said that, a longer term desire would be to update the isolation region implementation such that it is no longer organized as a 1:1 copy of guest memory in terms of size and number of subregions. We would then need an allocator when copying guest buffers into the shared region, but it would be much less wasteful, and we could guarantee that only 1 region need be sent to the backend for the bounce buffers. At that point, the vrings could be mapped into their own region. There would need to be some mechanism to ensure they all get mapped into the same region, but I think those implementation details could be kept within SVQ.
Thanks!
Connor
Re: [PATCH RFC v2 05/13] hw/virtio/vhost-shadow-virtqueue: specified vring placement
Quoted 59 lines · Connor Kite
Quoted 38 lines · Eugenio Perez Martin
Quoted 36 lines · Connor Kite
By default svq vrings are placed in an anonymous memory map. As svqs will be leveraged to enable memory isolation in vhost-user, it is useful to be able to place the vrings in a shared isolation memory region.
Adds the option to specify vring placement by providing a vring base address before starting the svq.
Signed-off-by Connor Kite <[email protected]>--- hw/virtio/vhost-shadow-virtqueue.c | 69 ++++++++++++++++++++++++++++++++------ hw/virtio/vhost-shadow-virtqueue.h | 8 ++++- 2 files changed, 66 insertions(+), 11 deletions(-)hw/virtio/vhost-shadow-virtqueue.c +7
-0@@ -812,6 +812,13 @@ size_t vhost_svq_device_area_size(const VhostShadowVirtqueue *svq)return ROUND_UP (used_size,qemu_real_host_page_size ()); } +size_t vhost_svq_vring_total_size (VirtIODevice *vdev,VirtQueue *vq) +{ +VhostShadowVirtqueue svq; + svq.vring.num =virtio_queue_get_num (vdev,virtio_get_queue_index (vq)); +return vhost_svq_driver_area_size (&svq) +vhost_svq_device_area_size (&svq); +} +/** * Set a new file descriptor for the guest to kick the SVQ and notify for avail * @@ -842,6 +849,19 @@ void vhost_svq_set_svq_kick_fd(VhostShadowVirtqueue *svq, int svq_kick_fd) } }Quoted 17 lines
hw/virtio/vhost-shadow-virtqueue.c void vhost_svq_set_svq_kick_fd(VhostShadowVirtqueue *svq, int svq_kick_fd) · line 863
Quoted 12 lines
hw/virtio/vhost-shadow-virtqueue.c +12
-0+/** +* Set vring base address if using fixed locations +* +* @svq: Shadow Virtqueue +* @addr: Points to new base address +*/ + +void vhost_svq_set_base_addr (VhostShadowVirtqueue *svq,void *addr) + { + svq->base_addr = addr; + } +Would it work to keep that allocation detail in SVQ, instead of letting it leak outside? Something like a flag to allocate the areas with mmap or
qemu_memfd_alloc, instead of thebase_addritself.
Quoted 10 lines
For the purposes of the isolation mode as it currently stands, I'm not sure the allocation can be entirely hidden without adding significant complexity. The vrings need to be allocated in a region that gets sent to the vhost-user backend. If
VHOST_USER_PROTOCOL_F_CONFIGURE_MEM_SLOTSisn't negotiated, then we are limited to 8 regions in total, so it is beneficial to be able to allocate them all in the same region, and in fact, the vrings are currently tacked onto the beginning of one of the bounce buffer regions so that they don't count against the limit.
Ok I see. Would it work if those details are encapsulated in a new struct, perhaps named SVQDeviceMemory, which all ShadowVirtQueue from a given device uses to allocate all memory together? It could use that explanation as a comment too.
I'm very bad at naming things so feel free to rename it :).
Quoted 11 lines
Having said that, a longer term desire would be to update the isolation region implementation such that it is no longer organized as a 1:1 copy of guest memory in terms of size and number of subregions. We would then need an allocator when copying guest buffers into the shared region, but it would be much less wasteful, and we could guarantee that only 1 region need be sent to the backend for the bounce buffers. At that point, the vrings could be mapped into their own region. There would need to be some mechanism to ensure they all get mapped into the same region, but I think those implementation details could be kept within SVQ.
That would be great, and the work on optimizing SVQ indirect descriptors could use it too.
Re: [PATCH RFC v2 13/13] net/vhost-user: add memory isolation
In reply to Markus ArmbrusterQuoted 33 lines · Markus Armbruster
Quoted 10 lines · Connor Kite
Quoted 4 lines · Markus Armbruster
Any guidance on when to enable it?
...
Quoted 2 lines
Likewise.
Quoted 7 lines
In both cases, you would enable this for added security. There's obviously a performance hit, but it prevents a potentially misbehaving vhost-user backend from reading or modifying undesired portions of guest memory, since data transfer occurs wholly via bounce buffers. This may be more useful in the generic netdev vhost user case than it is with the passt version, but the goal is for the mode to be accessible for any vhost-user device.
Work this into the commit message, please.
Quoted 6 lines
Do you think guidance is needed here in net.json? I was thinking that, if isolation-mode gets to a point of being merged, then information like this would make sense somewhere in the online documentation, but I'm happy to add something here as well. I was just trying to be similarly short and to-the-point as the other option descriptions for these structs.
I think it needs to be somewhere in the user documentation. We have so many configuration options, and so little guidance on what to do with them.
Quoted 9 lines
The doc comments in the QAPI schema are reference documentation (they go into the "QEMU QMP Reference Manual"). Reference documentation should be concise and to the point. When you have more useful things to say than fit there, you need to find nother place, and maybe link to it from the reference docs.
I suggest to try adding brief guidance to the doc comment, and then we see how we feel about it.
Here is the vhost-user documentation:docs/system/devices/virtio/vhost-user.rst
You could add a section to this document explaining the memory isolation feature.
Stefan