Skip to contentSkip to conversation

vfio: Adopt iommufd

PATCH Applied Zhenzhong Duan 5 participants 38 messages Nov 21, 2023 – Nov 28, 2023 Arm/Amlogic Meson SoC support

lore
Share & tools
lore
#0 lore raw

v7 cover vfio: Adopt iommufd

Hi,

Thanks all for giving guides and comments on previous series, this is the remaining part of the iommufd support.

Besides suggested changes in v6, I'd like to highlight two changes for final review:
1. Instantiate can_be_deleted callback to fix race where iommufd object can be deleted before vfio device
2. After careful re-thinking, I'd like to follow Nicolin's suggestion in v5, remove is_ioas check which indeed looks heavy just for tracepoint. In fact we can get corresponding info by looking over trace context.

PATCH 1: Introduce iommufd object
PATCH 2-9: add IOMMUFD container and cdev support PATCH 10-17: fd passing for cdev and linking to IOMMUFD PATCH 18: make VFIOContainerBase parameter const PATCH 19-21: Compile out for IOMMUFD for arm, s390x and x86 PATCH 22-26: vfio device init code cleanup
PATCH 27: add iommufd doc

We have done wide test with different combinations, e.g:
- PCI device were tested
- FD passing and hot reset with some trick.
- device hotplug test with legacy and iommufd backends
- with or without vIOMMU for legacy and iommufd backends
- divices linked to different iommufds
- VFIO migration with a E800 net card(no dirty sync support) passthrough
- platform, ccw and ap were only compile-tested due to environment limit
- test mdev pass through with mtty and mix with real device and different BE
- test iommufd object hotplug/unplug and mix with vfio device plug/unplug

Given some iommufd kernel limitations, the iommufd backend is not yet fully on par with the legacy backend w.r.t. features like:
- p2p mappings (you will see related error traces)
- dirty page sync
- and etc.

qemu code: https://github.com/yiliu1765/qemu/commits/zhenzhong/iommufd_cdev_v7
Based on vfio-next, commit id: c487fb8a50

--------------------------------------------------------------------------

Below are some background and graph about the design:

With the introduction of iommufd, the Linux kernel provides a generic interface for userspace drivers to propagate their DMA mappings to kernel for assigned devices. This series does the porting of the VFIO devices onto the /dev/iommu uapi and let it coexist with the legacy implementation.

At QEMU level, interactions with the /dev/iommu are abstracted by a new iommufd object (compiled in with the CONFIG_IOMMUFD option).

Any QEMU device (e.g. vfio device) wishing to use /dev/iommu must be linked with an iommufd object. In this series, the vfio-pci device is granted with such capability (other VFIO devices are not yet ready):

It gets a new optional parameter named iommufd which allows to pass an iommufd object:

    -object iommufd,id=iommufd0
    -device vfio-pci,host=0000:02:00.0,iommufd=iommufd0

Note the /dev/iommu and vfio cdev can be externally opened by a management layer. In such a case the fd is passed:

-object iommufd,id=iommufd0,fd=22
-device vfio-pci,iommufd=iommufd0,fd=23

If the fd parameter is not passed, the fd is opened by QEMU. See https://www.mail-archive.com/[email protected]/msg937155.html
for detailed discuss on this requirement.

If no iommufd option is passed to the vfio-pci device, iommufd is not used and the end-user gets the behavior based on the legacy vfio iommu interfaces:

    -device vfio-pci,host=0000:02:00.0

While the legacy kernel interface is group-centric, the new iommufd interface is device-centric, relying on device fd and iommufd.

To support both interfaces in the QEMU VFIO device we reworked the vfio container abstraction so that the generic VFIO code can use either backend.

The VFIOContainer object becomes a base object derived into
a) the legacy VFIO container and
b) the new iommufd based container.

The base object implements generic code such as code related to memory_listener and address space management whereas the derived objects implement callbacks specific to either BE, legacy and iommufd. Indeed each backend has its own way to setup secure context and dma management interface. The below diagram shows how it looks like with both BEs.

VFIO AddressSpace/Memory
+-------+ +----------+ +-----+ +-----+
| pci | | platform | | ap | | ccw |
+---+---+ +----+-----+ +--+--+ +--+--+ +----------------------+
| | | | | AddressSpace |
| | | | +------------+---------+
+---V-----------V-----------V--------V----+ /
| VFIOAddressSpace | <------------+
| | | MemoryListener
| VFIOContainer list |
+-------+----------------------------+----+
| |
| |
+-------V------+ +--------V----------+
| iommufd | | vfio legacy |
| container | | container |
+-------+------+ +--------+----------+
| |
| /dev/iommu | /dev/vfio/vfio
| /dev/vfio/devices/vfioX | /dev/vfio/$group_id
Userspace | |
============+============================+===========================

Kernel      |  device fd                 |
            +---------------+            | group/container fd
            | (BIND_IOMMUFD |            | (SET_CONTAINER/SET_IOMMU)
            |  ATTACH_IOAS) |            | device fd
            |               |            |
            |       +-------V------------V-----------------+
    iommufd |       |                vfio                  |
(map/unmap  |       +---------+--------------------+-------+
ioas_copy)  |                 |                    | map/unmap
            |                 |                    |
     +------V------+    +-----V------+      +------V--------+
     | iommfd core |    |  device    |      |  vfio iommu   |
     +-------------+    +------------+      +---------------+

[Secure Context setup]
- iommufd BE: uses device fd and iommufd to setup secure context (bind_iommufd, attach_ioas)
- vfio legacy BE: uses group fd and container fd to setup secure context (set_container, set_iommu)
[Device access]
- iommufd BE: device fd is opened through /dev/vfio/devices/vfioX
- vfio legacy BE: device fd is retrieved from group fd ioctl [DMA Mapping flow]
1. VFIOAddressSpace receives MemoryRegion add/del via MemoryListener
2. VFIO populates DMA map/unmap via the container BEs
*) iommufd BE: uses iommufd
*) vfio legacy BE: uses container fd

Changelog:
v7:
- Add iommufd doc (Cedric)
- Abstract iommufd_cdev_get_realized_vpdev in hot reset code (Eric)
- Add docs for vfio_device_get_name and return bool (Philippe)
- Remove is_ioas parameter (Nicolin)
- Include the general cleanup patchset in this series
- Instantiate can_be_deleted callback
- qom.json (Since: 8.2) -> (Since: 9.0)
- Add new R-b, T-b from Eric

v6:
- simplify CONFIG_IOMMUFD checking code further (Cédric)
- check iommufd_cdev_kvm_device_add return value (Cédric)
- dirrectory -> directory (Cédric)
- propagate iommufd_cdev_get_info_iova_range err and print as warning (Cédric)
- introduce a helper vfio_device_set_fd (Cédric)
- Move #include "sysemu/iommufd.h" in platform.c (Cédric)
- simplify iommufd backend uAPI, remove alloc_hwpt, get/put_ioas
- Remove CONFIG_IOMMUFD check in meson.build and treat iommufd.c general
- Add Matthew and Cédric's RB

v5:
- Change to use Kconfig for CONFIG_IOMMUFD and drop stub file (Cédric)
- Add (uintptr_t) to info->allowed_iovas (Cédric)
- Switch to IOAS attach/detach and hide hwpt (Jason)
- move chardev_open.[h|c] under the IOMMUFD entry (Cédric)
- Move vfio_legacy_pci_hot_reset into container.c (Cédric)
- Add missed pgsizes initialization in vfio_get_info_iova_range
- split linking iommufd patch into three to be cleaner
- Fix comments on PCI BAR unmap

v4:
- add CONFIG_IOMMUFD check for IOMMUFDProperties (Markus)
- add doc for default case without fd (Markus)
- Fix build issue reported by Markus and Cédric
- Simply use SPDX identifier in new file (Cédric)
- make vfio_container_init/destroy helper a seperate patch (Cédric)
- make vrdl_list movement a seperate patch (Cédric)
- add const for some callback parameters (Cédric)
- add g_assert in VFIOIOMMUOps callback (Cédric)
- introduce pci_hot_reset callback (Cédric)
- remove VFIOIOMMUSpaprOps (Cédric)
- initialize g_autofree to NULL (Cédric)
- adjust func name prefix and trace event in iommufd.c (Cédric)
- add RB

v3:
- Rename base container as VFIOContainerBase and legacy container as container (Cédric)
- Drop VFIO_IOMMU_BACKEND_OPS class and use struct instead (Cédric)
- Cleanup container.c by introducing spapr backend and move spapr code out (Cédric)
- Introduce vfio_iommu_spapr_ops (Cédric)
- Add doc of iommufd in qom.json and have iommufd member sorted (Markus)
- patch19 and patch21 are splitted to two parts to facilitate review

v2:
- patch "vfio: Add base container" in v1 is split into patch1-15 per Cédric
- add fd passing to platform/ap/ccw vfio device
- add (uintptr_t) cast in iommufd_backend_map_dma() per Cédric
- rename char_dev.h to chardev_open.h for same naming scheme per Daniel
- add full copyright per Daniel and Jason

Note changelog below are from full IOMMUFD series:

v1:
- Alloc hwpt instead of using auto hwpt
- elaborate iommufd code per Nicolin
- consolidate two patches and drop as.c
- typo error fix and function rename

rfcv4:
- rebase on top of v8.0.3
- Add one patch from Yi which is about vfio device add in kvm
- Remove IOAS_COPY optimization and focus on functions in this patchset
- Fix wrong name issue reported and fix suggested by Matthew
- Fix compilation issue reported and fix sugggsted by Nicolin
- Use query_dirty_bitmap callback to replace get_dirty_bitmap for better granularity
- Add dev_iter_next() callback to avoid adding so many callback at container scope, add VFIODevice.hwpt to support that
- Restore all functions back to common from container whenever possible, mainly migration and reset related functions
- Add --enable/disable-iommufd config option, enabled by default in linux
- Remove VFIODevice.hwpt_next as it's redundant with VFIODevice.next
- Adapt new VFIO_DEVICE_PCI_HOT_RESET uAPI for IOMMUFD backed device
- vfio_kvm_device_add/del_group call vfio_kvm_device_add/del_fd to remove redundant code
- Add FD passing support for vfio device backed by IOMMUFD
- Fix hot unplug resource leak issue in vfio_legacy_detach_device()
- Fix FD leak in vfio_get_devicefd()

rfcv3:
- rebase on top of v7.2.0
- Fix the compilation with CONFIG_IOMMUFD unset by using true classes for VFIO backends
- Fix use after free in error path, reported by Alister
- Split common.c in several steps to ease the review

rfcv2:
- remove the first three patches of rfcv1
- add open cdev helper suggested by Jason
- remove the QOMification of the VFIOContainer and simply use standard ops (David)
- add "-object iommufd" suggested by Alex

Thanks
Zhenzhong

Cédric Le Goater (3):
hw/arm: Activate IOMMUFD for virt machines
kconfig: Activate IOMMUFD for s390x machines
hw/i386: Activate IOMMUFD for q35 machines

Eric Auger (2):
backends/iommufd: Introduce the iommufd object vfio/pci: Allow the selection of a given iommu backend

Yi Liu (2):
util/char_dev: Add open_cdev()
vfio/iommufd: Implement the iommufd backend

Zhenzhong Duan (20):
vfio/common: return early if space isn't empty vfio/iommufd: Relax assert check for iommufd backend vfio/iommufd: Add support for iova_ranges and pgsizes vfio/pci: Extract out a helper vfio_pci_get_pci_hot_reset_info vfio/pci: Introduce a vfio pci hot reset interface vfio/iommufd: Enable pci hot reset through iommufd cdev interface vfio/pci: Make vfio cdev pre-openable by passing a file handle vfio/platform: Allow the selection of a given iommu backend vfio/platform: Make vfio cdev pre-openable by passing a file handle vfio/ap: Allow the selection of a given iommu backend vfio/ap: Make vfio cdev pre-openable by passing a file handle vfio/ccw: Allow the selection of a given iommu backend vfio/ccw: Make vfio cdev pre-openable by passing a file handle
vfio: Make VFIOContainerBase poiner parameter const in VFIOIOMMUOps
callbacks
vfio/pci: Move VFIODevice initializations in vfio_instance_init vfio/platform: Move VFIODevice initializations in
vfio_platform_instance_init
vfio/ap: Move VFIODevice initializations in vfio_ap_instance_init vfio/ccw: Move VFIODevice initializations in vfio_ccw_instance_init
vfio: Introduce a helper function to initialize VFIODevice docs/devel: Add VFIO iommufd backend documentation

 MAINTAINERS                           |  11 +
 docs/devel/index-internals.rst        |   1 +
 docs/devel/vfio-iommufd.rst           | 166 +++++++
 qapi/qom.json                         |  19 +
 hw/vfio/pci.h                         |   6 +
 include/hw/vfio/vfio-common.h         |  29 +-
 include/hw/vfio/vfio-container-base.h |  15 +-
 include/qemu/chardev_open.h           |  16 +
 include/sysemu/iommufd.h              |  38 ++
 backends/iommufd.c                    | 245 ++++++++++
 hw/vfio/ap.c                          |  47 +-
 hw/vfio/ccw.c                         |  53 ++-
 hw/vfio/common.c                      |  24 +-
 hw/vfio/container-base.c              |   6 +-
 hw/vfio/container.c                   | 208 ++++++++-
 hw/vfio/helpers.c                     |  54 +++
 hw/vfio/iommufd.c                     | 630 ++++++++++++++++++++++++++
 hw/vfio/pci.c                         | 218 ++-------
 hw/vfio/platform.c                    |  44 +-
 util/chardev_open.c                   |  81 ++++
 backends/Kconfig                      |   4 +
 backends/meson.build                  |   1 +
 backends/trace-events                 |  10 +
 hw/arm/Kconfig                        |   1 +
 hw/i386/Kconfig                       |   1 +
 hw/s390x/Kconfig                      |   1 +
 hw/vfio/meson.build                   |   3 +
 hw/vfio/trace-events                  |  11 +
 qemu-options.hx                       |  12 +
 util/meson.build                      |   1 +
 30 files changed, 1706 insertions(+), 250 deletions(-)
 create mode 100644 docs/devel/vfio-iommufd.rst
 create mode 100644 include/qemu/chardev_open.h
 create mode 100644 include/sysemu/iommufd.h
 create mode 100644 backends/iommufd.c
 create mode 100644 hw/vfio/iommufd.c
 create mode 100644 util/chardev_open.c
Signature · 1 line
2.34.1
#1 lore raw

PATCH v7 1/27 backends/iommufd: Introduce the iommufd object

From: Eric Auger <[email protected]>

Introduce an iommufd object which allows the interaction with the host /dev/iommu device.

The /dev/iommu can have been already pre-opened outside of qemu, in which case the fd can be passed directly along with the iommufd object:

This allows the iommufd object to be shared accross several subsystems (VFIO, VDPA, ...). For example, libvirt would open the /dev/iommu once.

If no fd is passed along with the iommufd object, the /dev/iommu is opened by the qemu code.

---
 MAINTAINERS              |   8 ++
 qapi/qom.json            |  19 +++
 include/sysemu/iommufd.h |  38 ++++++
 backends/iommufd.c       | 245 +++++++++++++++++++++++++++++++++++++++
 backends/Kconfig         |   4 +
 backends/meson.build     |   1 +
 backends/trace-events    |  10 ++
 qemu-options.hx          |  12 ++
 8 files changed, 337 insertions(+)
 create mode 100644 include/sysemu/iommufd.h
 create mode 100644 backends/iommufd.c
MAINTAINERS +8 -0
index 695e0bd34f..a5a446914a 100644
@@ -2167,6 +2167,14 @@ F: hw/vfio/ap.c
 F: docs/system/s390x/vfio-ap.rst
 L: [email protected]
 
+iommufd
+M: Yi Liu <[email protected]>
+M: Eric Auger <[email protected]>
+M: Zhenzhong Duan <[email protected]>
+S: Supported
+F: backends/iommufd.c
+F: include/sysemu/iommufd.h
+
 vhost
 M: Michael S. Tsirkin <[email protected]>
 S: Supported
qapi/qom.json +19 -0
index c53ef978ff..95516ba325 100644
@@ -794,6 +794,23 @@
 { 'struct': 'VfioUserServerProperties',
   'data': { 'socket': 'SocketAddress', 'device': 'str' } }
 
+##
+# @IOMMUFDProperties:
+#
+# Properties for iommufd objects.
+#
+# @fd: file descriptor name previously passed via 'getfd' command,
+#     which represents a pre-opened /dev/iommu.  This allows the
+#     iommufd object to be shared accross several subsystems
+#     (VFIO, VDPA, ...), and the file descriptor to be shared
+#     with other process, e.g. DPDK.  (default: QEMU opens
+#     /dev/iommu by itself)
+#
+# Since: 9.0
+##
+{ 'struct': 'IOMMUFDProperties',
+  'data': { '*fd': 'str' } }
+
 ##
 # @RngProperties:
 #
@@ -934,6 +951,7 @@
     'input-barrier',
     { 'name': 'input-linux',
       'if': 'CONFIG_LINUX' },
+    'iommufd',
     'iothread',
     'main-loop',
     { 'name': 'memory-backend-epc',
@@ -1003,6 +1021,7 @@
       'input-barrier':              'InputBarrierProperties',
       'input-linux':                { 'type': 'InputLinuxProperties',
                                       'if': 'CONFIG_LINUX' },
+      'iommufd':                    'IOMMUFDProperties',
       'iothread':                   'IothreadProperties',
       'main-loop':                  'MainLoopProperties',
       'memory-backend-epc':         { 'type': 'MemoryBackendEpcProperties',
include/sysemu/iommufd.h new file +38 -0
new file mode 100644
index 0000000000..9c5524b0ed
@@ -0,0 +1,38 @@
+#ifndef SYSEMU_IOMMUFD_H
+#define SYSEMU_IOMMUFD_H
+
+#include "qom/object.h"
+#include "qemu/thread.h"
+#include "exec/hwaddr.h"
+#include "exec/cpu-common.h"
+
+#define TYPE_IOMMUFD_BACKEND "iommufd"
+OBJECT_DECLARE_TYPE(IOMMUFDBackend, IOMMUFDBackendClass, IOMMUFD_BACKEND)
+
+struct IOMMUFDBackendClass {
+    ObjectClass parent_class;
+};
+
+struct IOMMUFDBackend {
+    Object parent;
+
+    /*< protected >*/
+    int fd;            /* /dev/iommu file descriptor */
+    bool owned;        /* is the /dev/iommu opened internally */
+    QemuMutex lock;
+    uint32_t users;
+
+    /*< public >*/
+};
+
+int iommufd_backend_connect(IOMMUFDBackend *be, Error **errp);
+void iommufd_backend_disconnect(IOMMUFDBackend *be);
+
+int iommufd_backend_alloc_ioas(IOMMUFDBackend *be, uint32_t *ioas_id,
+                               Error **errp);
+void iommufd_backend_free_id(IOMMUFDBackend *be, uint32_t id);
+int iommufd_backend_map_dma(IOMMUFDBackend *be, uint32_t ioas_id, hwaddr iova,
+                            ram_addr_t size, void *vaddr, bool readonly);
+int iommufd_backend_unmap_dma(IOMMUFDBackend *be, uint32_t ioas_id,
+                              hwaddr iova, ram_addr_t size);
+#endif
backends/iommufd.c new file +245 -0

245 lines not on this page · raw message

backends/Kconfig +4 -0
index f35abc1609..2cb23f62fa 100644
@@ -1 +1,5 @@
 source tpm/Kconfig
+
+config IOMMUFD
+    bool
+    depends on VFIO
backends/meson.build +1 -0
index 914c7c4afb..9a5cea480d 100644
@@ -20,6 +20,7 @@ if have_vhost_user
   system_ss.add(when: 'CONFIG_VIRTIO', if_true: files('vhost-user.c'))
 endif
 system_ss.add(when: 'CONFIG_VIRTIO_CRYPTO', if_true: files('cryptodev-vhost.c'))
+system_ss.add(when: 'CONFIG_IOMMUFD', if_true: files('iommufd.c'))
 if have_vhost_user_crypto
   system_ss.add(when: 'CONFIG_VIRTIO_CRYPTO', if_true: files('cryptodev-vhost-user.c'))
 endif
backends/trace-events +10 -0
index 652eb76a57..d45c6e31a6 100644
@@ -5,3 +5,13 @@ dbus_vmstate_pre_save(void)
 dbus_vmstate_post_load(int version_id) "version_id: %d"
 dbus_vmstate_loading(const char *id) "id: %s"
 dbus_vmstate_saving(const char *id) "id: %s"
+
+# iommufd.c
+iommufd_backend_connect(int fd, bool owned, uint32_t users, int ret) "fd=%d owned=%d users=%d (%d)"
+iommufd_backend_disconnect(int fd, uint32_t users) "fd=%d users=%d"
+iommu_backend_set_fd(int fd) "pre-opened /dev/iommu fd=%d"
+iommufd_backend_map_dma(int iommufd, uint32_t ioas, uint64_t iova, uint64_t size, void *vaddr, bool readonly, int ret) " iommufd=%d ioas=%d iova=0x%"PRIx64" size=0x%"PRIx64" addr=%p readonly=%d (%d)"
+iommufd_backend_unmap_dma_non_exist(int iommufd, uint32_t ioas, uint64_t iova, uint64_t size, int ret) " Unmap nonexistent mapping: iommufd=%d ioas=%d iova=0x%"PRIx64" size=0x%"PRIx64" (%d)"
+iommufd_backend_unmap_dma(int iommufd, uint32_t ioas, uint64_t iova, uint64_t size, int ret) " iommufd=%d ioas=%d iova=0x%"PRIx64" size=0x%"PRIx64" (%d)"
+iommufd_backend_alloc_ioas(int iommufd, uint32_t ioas, int ret) " iommufd=%d ioas=%d (%d)"
+iommufd_backend_free_id(int iommufd, uint32_t id, int ret) " iommufd=%d id=%d (%d)"
qemu-options.hx +12 -0
index 42fd09e4de..5fe8ea57d2 100644
@@ -5224,6 +5224,18 @@ SRST
 
         The ``share`` boolean option is on by default with memfd.
 
+    ``-object iommufd,id=id[,fd=fd]``
+        Creates an iommufd backend which allows control of DMA mapping
+        through the ``/dev/iommu`` device.
+
+        The ``id`` parameter is a unique ID which frontends (such as
+        vfio-pci of vdpa) will use to connect with the iommufd backend.
+
+        The ``fd`` parameter is an optional pre-opened file descriptor
+        resulting from ``/dev/iommu`` opening. Usually the iommufd is shared
+        across all subsystems, bringing the benefit of centralized
+        reference counting.
+
     ``-object rng-builtin,id=id``
         Creates a random number generator backend which obtains entropy
         from QEMU builtin functions. The ``id`` parameter is a unique ID
Signature · 1 line
2.34.1
#2 lore raw

PATCH v7 2/27 util/char_dev: Add open_cdev()

In reply to Zhenzhong Duan

From: Yi Liu <[email protected]>

/dev/vfio/devices/vfioX may not exist. In that case it is still possible to open /dev/char/$major:$minor instead. Add helper function to abstract the cdev open.

---
 MAINTAINERS                 |  2 +
 include/qemu/chardev_open.h | 16 ++++++++
 util/chardev_open.c         | 81 +++++++++++++++++++++++++++++++++++++
 util/meson.build            |  1 +
 4 files changed, 100 insertions(+)
 create mode 100644 include/qemu/chardev_open.h
 create mode 100644 util/chardev_open.c
MAINTAINERS +2 -0
index a5a446914a..ca70bb4e64 100644
@@ -2174,6 +2174,8 @@ M: Zhenzhong Duan <[email protected]>
 S: Supported
 F: backends/iommufd.c
 F: include/sysemu/iommufd.h
+F: include/qemu/chardev_open.h
+F: util/chardev_open.c
 
 vhost
 M: Michael S. Tsirkin <[email protected]>
include/qemu/chardev_open.h new file +16 -0
new file mode 100644
index 0000000000..64e8fcfdcb
@@ -0,0 +1,16 @@
+/*
+ * QEMU Chardev Helper
+ *
+ * Copyright (C) 2023 Intel Corporation.
+ *
+ * Authors: Yi Liu <[email protected]>
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2.  See
+ * the COPYING file in the top-level directory.
+ */
+
+#ifndef QEMU_CHARDEV_OPEN_H
+#define QEMU_CHARDEV_OPEN_H
+
+int open_cdev(const char *devpath, dev_t cdev);
+#endif
util/chardev_open.c new file +81 -0

81 lines not on this page · raw message

util/meson.build +1 -0
index c2322ef6e7..174c133368 100644
@@ -108,6 +108,7 @@ if have_block
     util_ss.add(files('filemonitor-stub.c'))
   endif
   util_ss.add(when: 'CONFIG_LINUX', if_true: files('vfio-helpers.c'))
+  util_ss.add(when: 'CONFIG_LINUX', if_true: files('chardev_open.c'))
 endif
 
 if cpu == 'aarch64'
Signature · 1 line
2.34.1
#3 lore raw

PATCH v7 3/27 vfio/common: return early if space isn't empty

In reply to Zhenzhong Duan

This is a trivial optimization. If there is active container in space, vfio_reset_handler will never be unregistered. So revert the check of space->containers and return early.

---
 hw/vfio/common.c | 9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)
hw/vfio/common.c +6 -3
index 572ae7c934..934f4f5446 100644
@@ -1462,10 +1462,13 @@ VFIOAddressSpace *vfio_get_address_space(AddressSpace *as)
 
 void vfio_put_address_space(VFIOAddressSpace *space)
 {
-    if (QLIST_EMPTY(&space->containers)) {
-        QLIST_REMOVE(space, list);
-        g_free(space);
+    if (!QLIST_EMPTY(&space->containers)) {
+        return;
     }
+
+    QLIST_REMOVE(space, list);
+    g_free(space);
+
     if (QLIST_EMPTY(&vfio_address_spaces)) {
         qemu_unregister_reset(vfio_reset_handler, NULL);
     }
Signature · 1 line
2.34.1
#4 lore raw

PATCH v7 4/27 vfio/iommufd: Implement the iommufd backend

In reply to Zhenzhong Duan

From: Yi Liu <[email protected]>

The iommufd backend is implemented based on the new /dev/iommu user API. This backend obviously depends on CONFIG_IOMMUFD.

So far, the iommufd backend doesn't support dirty page sync yet.

---
 include/hw/vfio/vfio-common.h |  11 +
 hw/vfio/common.c              |   6 +
 hw/vfio/iommufd.c             | 422 ++++++++++++++++++++++++++++++++++
 hw/vfio/meson.build           |   3 +
 hw/vfio/trace-events          |  10 +
 5 files changed, 452 insertions(+)
 create mode 100644 hw/vfio/iommufd.c
include/hw/vfio/vfio-common.h +11 -0
index 24ecc0e7ee..3dac5c167e 100644
@@ -89,6 +89,14 @@ typedef struct VFIOHostDMAWindow {
     QLIST_ENTRY(VFIOHostDMAWindow) hostwin_next;
 } VFIOHostDMAWindow;
 
+typedef struct IOMMUFDBackend IOMMUFDBackend;
+
+typedef struct VFIOIOMMUFDContainer {
+    VFIOContainerBase bcontainer;
+    IOMMUFDBackend *be;
+    uint32_t ioas_id;
+} VFIOIOMMUFDContainer;
+
 typedef struct VFIODeviceOps VFIODeviceOps;
 
 typedef struct VFIODevice {
@@ -116,6 +124,8 @@ typedef struct VFIODevice {
     OnOffAuto pre_copy_dirty_page_tracking;
     bool dirty_pages_supported;
     bool dirty_tracking;
+    int devid;
+    IOMMUFDBackend *iommufd;
 } VFIODevice;
 
 struct VFIODeviceOps {
@@ -201,6 +211,7 @@ typedef QLIST_HEAD(VFIODeviceList, VFIODevice) VFIODeviceList;
 extern VFIOGroupList vfio_group_list;
 extern VFIODeviceList vfio_device_list;
 extern const VFIOIOMMUOps vfio_legacy_ops;
+extern const VFIOIOMMUOps vfio_iommufd_ops;
 extern const MemoryListener vfio_memory_listener;
 extern int vfio_kvm_device_fd;
 
hw/vfio/common.c +6 -0
index 934f4f5446..6569732b7a 100644
@@ -19,6 +19,7 @@
  */
 
 #include "qemu/osdep.h"
+#include CONFIG_DEVICES /* CONFIG_IOMMUFD */
 #include <sys/ioctl.h>
 #ifdef CONFIG_KVM
 #include <linux/kvm.h>
@@ -1503,6 +1504,11 @@ int vfio_attach_device(char *name, VFIODevice *vbasedev,
 {
     const VFIOIOMMUOps *ops = &vfio_legacy_ops;
 
+#ifdef CONFIG_IOMMUFD
+    if (vbasedev->iommufd) {
+        ops = &vfio_iommufd_ops;
+    }
+#endif
     return ops->attach_device(name, vbasedev, as, errp);
 }
 
hw/vfio/iommufd.c new file +422 -0

422 lines not on this page · raw message

hw/vfio/meson.build +3 -0
index eb6ce6229d..e5d98b6adc 100644
@@ -7,6 +7,9 @@ vfio_ss.add(files(
   'spapr.c',
   'migration.c',
 ))
+vfio_ss.add(when: 'CONFIG_IOMMUFD', if_true: files(
+  'iommufd.c',
+))
 vfio_ss.add(when: 'CONFIG_VFIO_PCI', if_true: files(
   'display.c',
   'pci-quirks.c',
hw/vfio/trace-events +10 -0
index 08a1f9dfa4..3340c93af0 100644
@@ -164,3 +164,13 @@ vfio_state_pending_estimate(const char *name, uint64_t precopy, uint64_t postcop
 vfio_state_pending_exact(const char *name, uint64_t precopy, uint64_t postcopy, uint64_t stopcopy_size, uint64_t precopy_init_size, uint64_t precopy_dirty_size) " (%s) precopy 0x%"PRIx64" postcopy 0x%"PRIx64" stopcopy size 0x%"PRIx64" precopy initial size 0x%"PRIx64" precopy dirty size 0x%"PRIx64
 vfio_vmstate_change(const char *name, int running, const char *reason, const char *dev_state) " (%s) running %d reason %s device state %s"
 vfio_vmstate_change_prepare(const char *name, int running, const char *reason, const char *dev_state) " (%s) running %d reason %s device state %s"
+
+#iommufd.c
+
+iommufd_cdev_connect_and_bind(int iommufd, const char *name, int devfd, int devid) " [iommufd=%d] Successfully bound device %s (fd=%d): output devid=%d"
+iommufd_cdev_getfd(const char *dev, int devfd) " %s (fd=%d)"
+iommufd_cdev_attach_ioas_hwpt(int iommufd, const char *name, int devfd, int id) " [iommufd=%d] Successfully attached device %s (%d) to id=%d"
+iommufd_cdev_detach_ioas_hwpt(int iommufd, const char *name) " [iommufd=%d] Successfully detached %s"
+iommufd_cdev_fail_attach_existing_container(const char *msg) " %s"
+iommufd_cdev_alloc_ioas(int iommufd, int ioas_id) " [iommufd=%d] new IOMMUFD container with ioasid=%d"
+iommufd_cdev_device_info(char *name, int devfd, int num_irqs, int num_regions, int flags) " %s (%d) num_irqs=%d num_regions=%d flags=%d"
Signature · 1 line
2.34.1
#5 lore raw

PATCH v7 5/27 vfio/iommufd: Relax assert check for iommufd backend

In reply to Zhenzhong Duan

Currently iommufd doesn't support dirty page sync yet, but it will not block us doing live migration if VFIO migration is force enabled.

So in this case we allow set_dirty_page_tracking to be NULL. Note we don't need same change for query_dirty_bitmap because when dirty page sync isn't supported, query_dirty_bitmap will never be called.

---
 hw/vfio/container-base.c | 4 ++++
 hw/vfio/container.c      | 4 ----
 2 files changed, 4 insertions(+), 4 deletions(-)
hw/vfio/container-base.c +4 -0
index 71f7274973..eee2dcfe76 100644
@@ -55,6 +55,10 @@ void vfio_container_del_section_window(VFIOContainerBase *bcontainer,
 int vfio_container_set_dirty_page_tracking(VFIOContainerBase *bcontainer,
                                            bool start)
 {
+    if (!bcontainer->dirty_pages_supported) {
+        return 0;
+    }
+
     g_assert(bcontainer->ops->set_dirty_page_tracking);
     return bcontainer->ops->set_dirty_page_tracking(bcontainer, start);
 }
hw/vfio/container.c +0 -4
index 6bacf38222..ed2d721b2b 100644
@@ -216,10 +216,6 @@ static int vfio_legacy_set_dirty_page_tracking(VFIOContainerBase *bcontainer,
         .argsz = sizeof(dirty),
     };
 
-    if (!bcontainer->dirty_pages_supported) {
-        return 0;
-    }
-
     if (start) {
         dirty.flags = VFIO_IOMMU_DIRTY_PAGES_FLAG_START;
     } else {
Signature · 1 line
2.34.1
#6 lore raw

PATCH v7 6/27 vfio/iommufd: Add support for iova_ranges and pgsizes

In reply to Zhenzhong Duan

Some vIOMMU such as virtio-iommu use IOVA ranges from host side to setup reserved ranges for passthrough device, so that guest will not use an IOVA range beyond host support.

Use an uAPI of IOMMUFD to get IOVA ranges of host side and pass to vIOMMU just like the legacy backend, if this fails, fallback to 64bit IOVA range.

Also use out_iova_alignment returned from uAPI as pgsizes instead of qemu_real_host_page_size() as a fallback.

---
 hw/vfio/iommufd.c | 56 ++++++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 55 insertions(+), 1 deletion(-)
hw/vfio/iommufd.c +55 -1
index 6d31aeac7b..01b448e840 100644
@@ -261,6 +261,53 @@ static int iommufd_cdev_ram_block_discard_disable(bool state)
     return ram_block_uncoordinated_discard_disable(state);
 }
 
+static int iommufd_cdev_get_info_iova_range(VFIOIOMMUFDContainer *container,
+                                            uint32_t ioas_id, Error **errp)
+{
+    VFIOContainerBase *bcontainer = &container->bcontainer;
+    struct iommu_ioas_iova_ranges *info;
+    struct iommu_iova_range *iova_ranges;
+    int ret, sz, fd = container->be->fd;
+
+    info = g_malloc0(sizeof(*info));
+    info->size = sizeof(*info);
+    info->ioas_id = ioas_id;
+
+    ret = ioctl(fd, IOMMU_IOAS_IOVA_RANGES, info);
+    if (ret && errno != EMSGSIZE) {
+        goto error;
+    }
+
+    sz = info->num_iovas * sizeof(struct iommu_iova_range);
+    info = g_realloc(info, sizeof(*info) + sz);
+    info->allowed_iovas = (uintptr_t)(info + 1);
+
+    ret = ioctl(fd, IOMMU_IOAS_IOVA_RANGES, info);
+    if (ret) {
+        goto error;
+    }
+
+    iova_ranges = (struct iommu_iova_range *)(uintptr_t)info->allowed_iovas;
+
+    for (int i = 0; i < info->num_iovas; i++) {
+        Range *range = g_new(Range, 1);
+
+        range_set_bounds(range, iova_ranges[i].start, iova_ranges[i].last);
+        bcontainer->iova_ranges =
+            range_list_insert(bcontainer->iova_ranges, range);
+    }
+    bcontainer->pgsizes = info->out_iova_alignment;
+
+    g_free(info);
+    return 0;
+
+error:
+    ret = -errno;
+    g_free(info);
+    error_setg_errno(errp, errno, "Cannot get IOVA ranges");
+    return ret;
+}
+
 static int iommufd_cdev_attach(const char *name, VFIODevice *vbasedev,
                                AddressSpace *as, Error **errp)
 {
@@ -335,7 +382,14 @@ static int iommufd_cdev_attach(const char *name, VFIODevice *vbasedev,
         goto err_discard_disable;
     }
 
-    bcontainer->pgsizes = qemu_real_host_page_size();
+    ret = iommufd_cdev_get_info_iova_range(container, ioas_id, &err);
+    if (ret) {
+        error_append_hint(&err,
+                   "Fallback to default 64bit IOVA range and 4K page size\n");
+        warn_report_err(err);
+        err = NULL;
+        bcontainer->pgsizes = qemu_real_host_page_size();
+    }
 
     bcontainer->listener = vfio_memory_listener;
     memory_listener_register(&bcontainer->listener, bcontainer->space->as);
Signature · 1 line
2.34.1
#7 lore raw

PATCH v7 7/27 vfio/pci: Extract out a helper vfio_pci_get_pci_hot_reset_info

In reply to Zhenzhong Duan

This helper will be used by both legacy and iommufd backends.

No functional changes intended.

---
 hw/vfio/pci.h |  3 +++
 hw/vfio/pci.c | 54 +++++++++++++++++++++++++++++++++++----------------
 2 files changed, 40 insertions(+), 17 deletions(-)
hw/vfio/pci.h +3 -0
index fba8737ab2..1006061afb 100644
@@ -218,6 +218,9 @@ void vfio_probe_igd_bar4_quirk(VFIOPCIDevice *vdev, int nr);
 
 extern const PropertyInfo qdev_prop_nv_gpudirect_clique;
 
+int vfio_pci_get_pci_hot_reset_info(VFIOPCIDevice *vdev,
+                                    struct vfio_pci_hot_reset_info **info_p);
+
 int vfio_populate_vga(VFIOPCIDevice *vdev, Error **errp);
 
 int vfio_pci_igd_opregion_init(VFIOPCIDevice *vdev,
hw/vfio/pci.c +37 -17

83 lines not on this page · raw message

Signature · 1 line
2.34.1
#8 lore raw

PATCH v7 8/27 vfio/pci: Introduce a vfio pci hot reset interface

In reply to Zhenzhong Duan

Legacy vfio pci and iommufd cdev have different process to hot reset vfio device, expand current code to abstract out pci_hot_reset callback for legacy vfio, this same interface will also be used by iommufd cdev vfio device.

Rename vfio_pci_hot_reset to vfio_legacy_pci_hot_reset and move it into container.c.

vfio_pci_[pre/post]_reset and vfio_pci_host_match are exported so they could be called in legacy and iommufd pci_hot_reset callback.

---
 hw/vfio/pci.h                         |   3 +
 include/hw/vfio/vfio-container-base.h |   3 +
 hw/vfio/container.c                   | 170 ++++++++++++++++++++++++++
 hw/vfio/pci.c                         | 168 +------------------------
 4 files changed, 182 insertions(+), 162 deletions(-)
hw/vfio/pci.h +3 -0
index 1006061afb..6e64a2654e 100644
@@ -218,6 +218,9 @@ void vfio_probe_igd_bar4_quirk(VFIOPCIDevice *vdev, int nr);
 
 extern const PropertyInfo qdev_prop_nv_gpudirect_clique;
 
+void vfio_pci_pre_reset(VFIOPCIDevice *vdev);
+void vfio_pci_post_reset(VFIOPCIDevice *vdev);
+bool vfio_pci_host_match(PCIHostDeviceAddress *addr, const char *name);
 int vfio_pci_get_pci_hot_reset_info(VFIOPCIDevice *vdev,
                                     struct vfio_pci_hot_reset_info **info_p);
 
include/hw/vfio/vfio-container-base.h +3 -0
index 4b6f017c6f..45bb19c767 100644
@@ -106,6 +106,9 @@ struct VFIOIOMMUOps {
     int (*set_dirty_page_tracking)(VFIOContainerBase *bcontainer, bool start);
     int (*query_dirty_bitmap)(VFIOContainerBase *bcontainer, VFIOBitmap *vbmap,
                               hwaddr iova, hwaddr size);
+    /* PCI specific */
+    int (*pci_hot_reset)(VFIODevice *vbasedev, bool single);
+
     /* SPAPR specific */
     int (*add_window)(VFIOContainerBase *bcontainer,
                       MemoryRegionSection *section,
hw/vfio/container.c +170 -0

186 lines not on this page · raw message

hw/vfio/pci.c +6 -162

193 lines not on this page · raw message

Signature · 1 line
2.34.1
#9 lore raw

Re: [PATCH v7 08/27] vfio/pci: Introduce a vfio pci hot reset interface

Hi Zhenzhong,

Quoted 24 lines · Zhenzhong Duan

Legacy vfio pci and iommufd cdev have different process to hot reset vfio device, expand current code to abstract out pci_hot_reset callback for legacy vfio, this same interface will also be used by iommufd cdev vfio device.

Rename vfio_pci_hot_reset to vfio_legacy_pci_hot_reset and move it into container.c.

vfio_pci_[pre/post]_reset and vfio_pci_host_match are exported so they could be called in legacy and iommufd pci_hot_reset callback.

---
  hw/vfio/pci.h                         |   3 +
  include/hw/vfio/vfio-container-base.h |   3 +
  hw/vfio/container.c                   | 170 ++++++++++++++++++++++++++
  hw/vfio/pci.c                         | 168 +------------------------
  4 files changed, 182 insertions(+), 162 deletions(-)

hw/vfio/pci.c int vfio_pci_get_pci_hot_reset_info(VFIOPCIDevice *vdev, · line 2489

Quoted 5 lines
hw/vfio/pci.c +1 -0
@@ -2485,166 +2485,10 @@ int vfio_pci_get_pci_hot_reset_info(VFIOPCIDevice *vdev,
 
  static int vfio_pci_hot_reset(VFIOPCIDevice *vdev, bool single)
  {
 
+    return ops->pci_hot_reset(vbasedev, single);

At this point vfio_iommufd_ops.pci_hot_reset is NULL. Worth checking for non-NULL before calling.

Quoted 3 lines
(quoted diff) +0 -0
  }
 
  /*
#10 lore raw

RE: [PATCH v7 08/27] vfio/pci: Introduce a vfio pci hot reset interface

Hi Philippe,

Quoted 34 lines

-----Original Message-----
From: Philippe Mathieu-Daudé <[email protected]>
Sent: Wednesday, November 22, 2023 2:39 AM
Subject: Re: [PATCH v7 08/27] vfio/pci: Introduce a vfio pci hot reset interface

Hi Zhenzhong,

Review int

Quoted 24 lines · Zhenzhong Duan

Legacy vfio pci and iommufd cdev have different process to hot reset vfio device, expand current code to abstract out pci_hot_reset callback for legacy vfio, this same interface will also be used by iommufd cdev vfio device.

Rename vfio_pci_hot_reset to vfio_legacy_pci_hot_reset and move it into container.c.

vfio_pci_[pre/post]_reset and vfio_pci_host_match are exported so they could be called in legacy and iommufd pci_hot_reset callback.

---
  hw/vfio/pci.h                         |   3 +
  include/hw/vfio/vfio-container-base.h |   3 +
  hw/vfio/container.c                   | 170 ++++++++++++++++++++++++++
  hw/vfio/pci.c                         | 168 +------------------------
  4 files changed, 182 insertions(+), 162 deletions(-)
(quoted diff) +0 -0
@@ -2485,166 +2485,10 @@ int

vfio_pci_get_pci_hot_reset_info(VFIOPCIDevice *vdev,

Quoted 1 line
Quoted 7 lines
Quoted 4 lines
  static int vfio_pci_hot_reset(VFIOPCIDevice *vdev, bool single)
  {

+ return ops->pci_hot_reset(vbasedev, single);

At this point vfio_iommufd_ops.pci_hot_reset is NULL. Worth checking for non-NULL before calling.

Yes, vfio_iommufd_ops.pci_hot_reset is NULL here. But we could only use Iommufd backend after:
"[PATCH v7 10/27] vfio/pci: Allow the selection of a given iommu backend"

With "[PATCH v7 09/27] vfio/iommufd: Enable pci hot reset through iommufd cdev interface" set vfio_iommufd_ops.pci_hot_reset.

Looks not an issue for me.

Thanks
Zhenzhong

#11 lore raw

PATCH v7 9/27 vfio/iommufd: Enable pci hot reset through iommufd cdev interface

In reply to Zhenzhong Duan

Implement the newly introduced pci_hot_reset callback named iommufd_cdev_pci_hot_reset to do iommufd specific check and reset operation.

---
 hw/vfio/iommufd.c    | 150 +++++++++++++++++++++++++++++++++++++++++++
 hw/vfio/trace-events |   1 +
 2 files changed, 151 insertions(+)
hw/vfio/iommufd.c +150 -0
index 01b448e840..6e53e013ef 100644
@@ -24,6 +24,7 @@
 #include "sysemu/reset.h"
 #include "qemu/cutils.h"
 #include "qemu/chardev_open.h"
+#include "pci.h"
 
 static int iommufd_cdev_map(VFIOContainerBase *bcontainer, hwaddr iova,
                             ram_addr_t size, void *vaddr, bool readonly)
@@ -468,9 +469,158 @@ static void iommufd_cdev_detach(VFIODevice *vbasedev)
     close(vbasedev->fd);
 }
 
+static VFIODevice *iommufd_cdev_pci_find_by_devid(__u32 devid)
+{
+    VFIODevice *vbasedev_iter;
+
+    QLIST_FOREACH(vbasedev_iter, &vfio_device_list, global_next) {
+        if (vbasedev_iter->bcontainer->ops != &vfio_iommufd_ops) {
+            continue;
+        }
+        if (devid == vbasedev_iter->devid) {
+            return vbasedev_iter;
+        }
+    }
+    return NULL;
+}
+
+static VFIOPCIDevice *
+iommufd_cdev_dep_get_realized_vpdev(struct vfio_pci_dependent_device *dep_dev,
+                                    VFIODevice *reset_dev)
+{
+    VFIODevice *vbasedev_tmp;
+
+    if (dep_dev->devid == reset_dev->devid ||
+        dep_dev->devid == VFIO_PCI_DEVID_OWNED) {
+        return NULL;
+    }
+
+    vbasedev_tmp = iommufd_cdev_pci_find_by_devid(dep_dev->devid);
+    if (!vbasedev_tmp || !vbasedev_tmp->dev->realized ||
+        vbasedev_tmp->type != VFIO_DEVICE_TYPE_PCI) {
+        return NULL;
+    }
+
+    return container_of(vbasedev_tmp, VFIOPCIDevice, vbasedev);
+}
+
+static int iommufd_cdev_pci_hot_reset(VFIODevice *vbasedev, bool single)
+{
+    VFIOPCIDevice *vdev = container_of(vbasedev, VFIOPCIDevice, vbasedev);
+    struct vfio_pci_hot_reset_info *info = NULL;
+    struct vfio_pci_dependent_device *devices;
+    struct vfio_pci_hot_reset *reset;
+    int ret, i;
+    bool multi = false;
+
+    trace_vfio_pci_hot_reset(vdev->vbasedev.name, single ? "one" : "multi");
+
+    if (!single) {
+        vfio_pci_pre_reset(vdev);
+    }
+    vdev->vbasedev.needs_reset = false;
+
+    ret = vfio_pci_get_pci_hot_reset_info(vdev, &info);
+
+    if (ret) {
+        goto out_single;
+    }
+
+    assert(info->flags & VFIO_PCI_HOT_RESET_FLAG_DEV_ID);
+
+    devices = &info->devices[0];
+
+    if (!(info->flags & VFIO_PCI_HOT_RESET_FLAG_DEV_ID_OWNED)) {
+        if (!vdev->has_pm_reset) {
+            for (i = 0; i < info->count; i++) {
+                if (devices[i].devid == VFIO_PCI_DEVID_NOT_OWNED) {
+                    error_report("vfio: Cannot reset device %s, "
+                                 "depends on device %04x:%02x:%02x.%x "
+                                 "which is not owned.",
+                                 vdev->vbasedev.name, devices[i].segment,
+                                 devices[i].bus, PCI_SLOT(devices[i].devfn),
+                                 PCI_FUNC(devices[i].devfn));
+                }
+            }
+        }
+        ret = -EPERM;
+        goto out_single;
+    }
+
+    trace_vfio_pci_hot_reset_has_dep_devices(vdev->vbasedev.name);
+
+    for (i = 0; i < info->count; i++) {
+        VFIOPCIDevice *tmp;
+
+        trace_iommufd_cdev_pci_hot_reset_dep_devices(devices[i].segment,
+                                                     devices[i].bus,
+                                                     PCI_SLOT(devices[i].devfn),
+                                                     PCI_FUNC(devices[i].devfn),
+                                                     devices[i].devid);
+
+        /*
+         * If a VFIO cdev device is resettable, all the dependent devices
+         * are either bound to same iommufd or within same iommu_groups as
+         * one of the iommufd bound devices.
+         */
+        assert(devices[i].devid != VFIO_PCI_DEVID_NOT_OWNED);
+
+        tmp = iommufd_cdev_dep_get_realized_vpdev(&devices[i], &vdev->vbasedev);
+        if (!tmp) {
+            continue;
+        }
+
+        if (single) {
+            ret = -EINVAL;
+            goto out_single;
+        }
+        vfio_pci_pre_reset(tmp);
+        tmp->vbasedev.needs_reset = false;
+        multi = true;
+    }
+
+    if (!single && !multi) {
+        ret = -EINVAL;
+        goto out_single;
+    }
+
+    /* Use zero length array for hot reset with iommufd backend */
+    reset = g_malloc0(sizeof(*reset));
+    reset->argsz = sizeof(*reset);
+
+     /* Bus reset! */
+    ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_PCI_HOT_RESET, reset);
+    g_free(reset);
+    if (ret) {
+        ret = -errno;
+    }
+
+    trace_vfio_pci_hot_reset_result(vdev->vbasedev.name,
+                                    ret ? strerror(errno) : "Success");
+
+    /* Re-enable INTx on affected devices */
+    for (i = 0; i < info->count; i++) {
+        VFIOPCIDevice *tmp;
+
+        tmp = iommufd_cdev_dep_get_realized_vpdev(&devices[i], &vdev->vbasedev);
+        if (!tmp) {
+            continue;
+        }
+        vfio_pci_post_reset(tmp);
+    }
+out_single:
+    if (!single) {
+        vfio_pci_post_reset(vdev);
+    }
+    g_free(info);
+
+    return ret;
+}
+
 const VFIOIOMMUOps vfio_iommufd_ops = {
     .dma_map = iommufd_cdev_map,
     .dma_unmap = iommufd_cdev_unmap,
     .attach_device = iommufd_cdev_attach,
     .detach_device = iommufd_cdev_detach,
+    .pci_hot_reset = iommufd_cdev_pci_hot_reset,
 };
hw/vfio/trace-events +1 -0
index 3340c93af0..8fdde54456 100644
@@ -174,3 +174,4 @@ iommufd_cdev_detach_ioas_hwpt(int iommufd, const char *name) " [iommufd=%d] Succ
 iommufd_cdev_fail_attach_existing_container(const char *msg) " %s"
 iommufd_cdev_alloc_ioas(int iommufd, int ioas_id) " [iommufd=%d] new IOMMUFD container with ioasid=%d"
 iommufd_cdev_device_info(char *name, int devfd, int num_irqs, int num_regions, int flags) " %s (%d) num_irqs=%d num_regions=%d flags=%d"
+iommufd_cdev_pci_hot_reset_dep_devices(int domain, int bus, int slot, int function, int dev_id) "\t%04x:%02x:%02x.%x devid %d"
Signature · 1 line
2.34.1
#12 lore raw

PATCH v7 10/27 vfio/pci: Allow the selection of a given iommu backend

In reply to Zhenzhong Duan

From: Eric Auger <[email protected]>

Now we support two types of iommu backends, let's add the capability to select one of them. This depends on whether an iommufd object has been linked with the vfio-pci device:

If the user wants to use the legacy backend, it shall not link the vfio-pci device with any iommufd object:

-device vfio-pci,host=0000:02:00.0

This is called the legacy mode/backend.

If the user wants to use the iommufd backend (/dev/iommu) it shall pass an iommufd object id in the vfio-pci device options:

-object iommufd,id=iommufd0
-device vfio-pci,host=0000:02:00.0,iommufd=iommufd0

---
 hw/vfio/pci.c | 6 ++++++
 1 file changed, 6 insertions(+)
hw/vfio/pci.c +6 -0
index d00c3472c7..c5984b0598 100644
@@ -19,6 +19,7 @@
  */
 
 #include "qemu/osdep.h"
+#include CONFIG_DEVICES /* CONFIG_IOMMUFD */
 #include <linux/vfio.h>
 #include <sys/ioctl.h>
 
@@ -42,6 +43,7 @@
 #include "qapi/error.h"
 #include "migration/blocker.h"
 #include "migration/qemu-file.h"
+#include "sysemu/iommufd.h"
 
 #define TYPE_VFIO_PCI_NOHOTPLUG "vfio-pci-nohotplug"
 
@@ -3386,6 +3388,10 @@ static Property vfio_pci_dev_properties[] = {
      * DEFINE_PROP_STRING("vfiofd", VFIOPCIDevice, vfiofd_name),
      * DEFINE_PROP_STRING("vfiogroupfd, VFIOPCIDevice, vfiogroupfd_name),
      */
+#ifdef CONFIG_IOMMUFD
+    DEFINE_PROP_LINK("iommufd", VFIOPCIDevice, vbasedev.iommufd,
+                     TYPE_IOMMUFD_BACKEND, IOMMUFDBackend *),
+#endif
     DEFINE_PROP_END_OF_LIST(),
 };
 
Signature · 1 line
2.34.1
#13 lore raw

PATCH v7 11/27 vfio/pci: Make vfio cdev pre-openable by passing a file handle

In reply to Zhenzhong Duan

This gives management tools like libvirt a chance to open the vfio cdev with privilege and pass FD to qemu. This way qemu never needs to have privilege to open a VFIO or iommu cdev node.

Together with the earlier support of pre-opening /dev/iommu device, now we have full support of passing a vfio device to unprivileged qemu by management tool. This mode is no more considered for the legacy backend. So let's remove the "TODO" comment.

Add helper functions vfio_device_set_fd() and vfio_device_get_name() to set fd and get device name, they will also be used by other vfio devices.

There is no easy way to check if a device is mdev with FD passing, so fail the x-balloon-allowed check unconditionally in this case.

There is also no easy way to get BDF as name with FD passing, so we fake a name by VFIO_FD[fd].

---
 include/hw/vfio/vfio-common.h |  4 ++++
 hw/vfio/helpers.c             | 43 +++++++++++++++++++++++++++++++++++
 hw/vfio/iommufd.c             | 12 ++++++----
 hw/vfio/pci.c                 | 28 +++++++++++++----------
 4 files changed, 71 insertions(+), 16 deletions(-)
include/hw/vfio/vfio-common.h +4 -0
index 3dac5c167e..697bf24a35 100644
@@ -251,4 +251,8 @@ int vfio_devices_query_dirty_bitmap(VFIOContainerBase *bcontainer,
                                     hwaddr size);
 int vfio_get_dirty_bitmap(VFIOContainerBase *bcontainer, uint64_t iova,
                                  uint64_t size, ram_addr_t ram_addr);
+
+/* Returns 0 on success, or a negative errno. */
+int vfio_device_get_name(VFIODevice *vbasedev, Error **errp);
+void vfio_device_set_fd(VFIODevice *vbasedev, const char *str, Error **errp);
 #endif /* HW_VFIO_VFIO_COMMON_H */
hw/vfio/helpers.c +43 -0

52 lines not on this page · raw message

hw/vfio/iommufd.c +8 -4
index 6e53e013ef..5accd26484 100644
@@ -320,11 +320,15 @@ static int iommufd_cdev_attach(const char *name, VFIODevice *vbasedev,
     uint32_t ioas_id;
     Error *err = NULL;
 
-    devfd = iommufd_cdev_getfd(vbasedev->sysfsdev, errp);
-    if (devfd < 0) {
-        return devfd;
+    if (vbasedev->fd < 0) {
+        devfd = iommufd_cdev_getfd(vbasedev->sysfsdev, errp);
+        if (devfd < 0) {
+            return devfd;
+        }
+        vbasedev->fd = devfd;
+    } else {
+        devfd = vbasedev->fd;
     }
-    vbasedev->fd = devfd;
 
     ret = iommufd_cdev_connect_and_bind(vbasedev, errp);
     if (ret) {
hw/vfio/pci.c +16 -12
index c5984b0598..445d58c8e5 100644
@@ -2944,17 +2944,19 @@ static void vfio_realize(PCIDevice *pdev, Error **errp)
     VFIODevice *vbasedev = &vdev->vbasedev;
     char *tmp, *subsys;
     Error *err = NULL;
-    struct stat st;
     int i, ret;
     bool is_mdev;
     char uuid[UUID_STR_LEN];
     char *name;
 
-    if (!vbasedev->sysfsdev) {
+    if (vbasedev->fd < 0 && !vbasedev->sysfsdev) {
         if (!(~vdev->host.domain || ~vdev->host.bus ||
               ~vdev->host.slot || ~vdev->host.function)) {
             error_setg(errp, "No provided host device");
             error_append_hint(errp, "Use -device vfio-pci,host=DDDD:BB:DD.F "
+#ifdef CONFIG_IOMMUFD
+                              "or -device vfio-pci,fd=DEVICE_FD "
+#endif
                               "or -device vfio-pci,sysfsdev=PATH_TO_DEVICE\n");
             return;
         }
@@ -2964,13 +2966,9 @@ static void vfio_realize(PCIDevice *pdev, Error **errp)
                             vdev->host.slot, vdev->host.function);
     }
 
-    if (stat(vbasedev->sysfsdev, &st) < 0) {
-        error_setg_errno(errp, errno, "no such host device");
-        error_prepend(errp, VFIO_MSG_PREFIX, vbasedev->sysfsdev);
+    if (vfio_device_get_name(vbasedev, errp) < 0) {
         return;
     }
-
-    vbasedev->name = g_path_get_basename(vbasedev->sysfsdev);
     vbasedev->ops = &vfio_pci_ops;
     vbasedev->type = VFIO_DEVICE_TYPE_PCI;
     vbasedev->dev = DEVICE(vdev);
@@ -3330,6 +3328,7 @@ static void vfio_instance_init(Object *obj)
     vdev->host.bus = ~0U;
     vdev->host.slot = ~0U;
     vdev->host.function = ~0U;
+    vdev->vbasedev.fd = -1;
 
     vdev->nv_gpudirect_clique = 0xFF;
 
@@ -3383,11 +3382,6 @@ static Property vfio_pci_dev_properties[] = {
                                    qdev_prop_nv_gpudirect_clique, uint8_t),
     DEFINE_PROP_OFF_AUTO_PCIBAR("x-msix-relocation", VFIOPCIDevice, msix_relo,
                                 OFF_AUTOPCIBAR_OFF),
-    /*
-     * TODO - support passed fds... is this necessary?
-     * DEFINE_PROP_STRING("vfiofd", VFIOPCIDevice, vfiofd_name),
-     * DEFINE_PROP_STRING("vfiogroupfd, VFIOPCIDevice, vfiogroupfd_name),
-     */
 #ifdef CONFIG_IOMMUFD
     DEFINE_PROP_LINK("iommufd", VFIOPCIDevice, vbasedev.iommufd,
                      TYPE_IOMMUFD_BACKEND, IOMMUFDBackend *),
@@ -3395,6 +3389,13 @@ static Property vfio_pci_dev_properties[] = {
     DEFINE_PROP_END_OF_LIST(),
 };
 
+#ifdef CONFIG_IOMMUFD
+static void vfio_pci_set_fd(Object *obj, const char *str, Error **errp)
+{
+    vfio_device_set_fd(&VFIO_PCI(obj)->vbasedev, str, errp);
+}
+#endif
+
 static void vfio_pci_dev_class_init(ObjectClass *klass, void *data)
 {
     DeviceClass *dc = DEVICE_CLASS(klass);
@@ -3402,6 +3403,9 @@ static void vfio_pci_dev_class_init(ObjectClass *klass, void *data)
 
     dc->reset = vfio_pci_reset;
     device_class_set_props(dc, vfio_pci_dev_properties);
+#ifdef CONFIG_IOMMUFD
+    object_class_property_add_str(klass, "fd", NULL, vfio_pci_set_fd);
+#endif
     dc->desc = "VFIO-based PCI device assignment";
     set_bit(DEVICE_CATEGORY_MISC, dc->categories);
     pdc->realize = vfio_realize;
Signature · 1 line
2.34.1
#14 lore raw

PATCH v7 12/27 vfio/platform: Allow the selection of a given iommu backend

In reply to Zhenzhong Duan

Now we support two types of iommu backends, let's add the capability to select one of them. This depends on whether an iommufd object has been linked with the vfio-platform device:

If the user wants to use the legacy backend, it shall not link the vfio-platform device with any iommufd object:

-device vfio-platform,host=XXX

This is called the legacy mode/backend.

If the user wants to use the iommufd backend (/dev/iommu) it shall pass an iommufd object id in the vfio-platform device options:

-object iommufd,id=iommufd0
-device vfio-platform,host=XXX,iommufd=iommufd0

---
 hw/vfio/platform.c | 6 ++++++
 1 file changed, 6 insertions(+)
hw/vfio/platform.c +6 -0
index 8e3d4ac458..98ae4bc655 100644
@@ -15,11 +15,13 @@
  */
 
 #include "qemu/osdep.h"
+#include CONFIG_DEVICES /* CONFIG_IOMMUFD */
 #include "qapi/error.h"
 #include <sys/ioctl.h>
 #include <linux/vfio.h>
 
 #include "hw/vfio/vfio-platform.h"
+#include "sysemu/iommufd.h"
 #include "migration/vmstate.h"
 #include "qemu/error-report.h"
 #include "qemu/lockable.h"
@@ -649,6 +651,10 @@ static Property vfio_platform_dev_properties[] = {
     DEFINE_PROP_UINT32("mmap-timeout-ms", VFIOPlatformDevice,
                        mmap_timeout, 1100),
     DEFINE_PROP_BOOL("x-irqfd", VFIOPlatformDevice, irqfd_allowed, true),
+#ifdef CONFIG_IOMMUFD
+    DEFINE_PROP_LINK("iommufd", VFIOPlatformDevice, vbasedev.iommufd,
+                     TYPE_IOMMUFD_BACKEND, IOMMUFDBackend *),
+#endif
     DEFINE_PROP_END_OF_LIST(),
 };
 
Signature · 1 line
2.34.1
#15 lore raw

PATCH v7 13/27 vfio/platform: Make vfio cdev pre-openable by passing a file handle

In reply to Zhenzhong Duan

This gives management tools like libvirt a chance to open the vfio cdev with privilege and pass FD to qemu. This way qemu never needs to have privilege to open a VFIO or iommu cdev node.

---
 hw/vfio/platform.c | 32 ++++++++++++++++++++++++--------
 1 file changed, 24 insertions(+), 8 deletions(-)
hw/vfio/platform.c +24 -8
index 98ae4bc655..a97d9c6234 100644
@@ -531,14 +531,13 @@ static VFIODeviceOps vfio_platform_ops = {
  */
 static int vfio_base_device_init(VFIODevice *vbasedev, Error **errp)
 {
-    struct stat st;
     int ret;
 
-    /* @sysfsdev takes precedence over @host */
-    if (vbasedev->sysfsdev) {
+    /* @fd takes precedence over @sysfsdev which takes precedence over @host */
+    if (vbasedev->fd < 0 && vbasedev->sysfsdev) {
         g_free(vbasedev->name);
         vbasedev->name = g_path_get_basename(vbasedev->sysfsdev);
-    } else {
+    } else if (vbasedev->fd < 0) {
         if (!vbasedev->name || strchr(vbasedev->name, '/')) {
             error_setg(errp, "wrong host device name");
             return -EINVAL;
@@ -548,10 +547,9 @@ static int vfio_base_device_init(VFIODevice *vbasedev, Error **errp)
                                              vbasedev->name);
     }
 
-    if (stat(vbasedev->sysfsdev, &st) < 0) {
-        error_setg_errno(errp, errno,
-                         "failed to get the sysfs host device file status");
-        return -errno;
+    ret = vfio_device_get_name(vbasedev, errp);
+    if (ret) {
+        return ret;
     }
 
     ret = vfio_attach_device(vbasedev->name, vbasedev,
@@ -658,6 +656,20 @@ static Property vfio_platform_dev_properties[] = {
     DEFINE_PROP_END_OF_LIST(),
 };
 
+static void vfio_platform_instance_init(Object *obj)
+{
+    VFIOPlatformDevice *vdev = VFIO_PLATFORM_DEVICE(obj);
+
+    vdev->vbasedev.fd = -1;
+}
+
+#ifdef CONFIG_IOMMUFD
+static void vfio_platform_set_fd(Object *obj, const char *str, Error **errp)
+{
+    vfio_device_set_fd(&VFIO_PLATFORM_DEVICE(obj)->vbasedev, str, errp);
+}
+#endif
+
 static void vfio_platform_class_init(ObjectClass *klass, void *data)
 {
     DeviceClass *dc = DEVICE_CLASS(klass);
@@ -665,6 +677,9 @@ static void vfio_platform_class_init(ObjectClass *klass, void *data)
 
     dc->realize = vfio_platform_realize;
     device_class_set_props(dc, vfio_platform_dev_properties);
+#ifdef CONFIG_IOMMUFD
+    object_class_property_add_str(klass, "fd", NULL, vfio_platform_set_fd);
+#endif
     dc->vmsd = &vfio_platform_vmstate;
     dc->desc = "VFIO-based platform device assignment";
     sbc->connect_irq_notifier = vfio_start_irqfd_injection;
@@ -677,6 +692,7 @@ static const TypeInfo vfio_platform_dev_info = {
     .name = TYPE_VFIO_PLATFORM,
     .parent = TYPE_SYS_BUS_DEVICE,
     .instance_size = sizeof(VFIOPlatformDevice),
+    .instance_init = vfio_platform_instance_init,
     .class_init = vfio_platform_class_init,
     .class_size = sizeof(VFIOPlatformDeviceClass),
 };
Signature · 1 line
2.34.1
#16 lore raw

PATCH v7 14/27 vfio/ap: Allow the selection of a given iommu backend

In reply to Zhenzhong Duan

Now we support two types of iommu backends, let's add the capability to select one of them. This depends on whether an iommufd object has been linked with the vfio-ap device:

if the user wants to use the legacy backend, it shall not link the vfio-ap device with any iommufd object:

-device vfio-ap,sysfsdev=/sys/bus/mdev/devices/XXX

This is called the legacy mode/backend.

If the user wants to use the iommufd backend (/dev/iommu) it shall pass an iommufd object id in the vfio-ap device options:

-object iommufd,id=iommufd0
-device vfio-ap,sysfsdev=/sys/bus/mdev/devices/XXX,iommufd=iommufd0

---
 hw/vfio/ap.c | 6 ++++++
 1 file changed, 6 insertions(+)
hw/vfio/ap.c +6 -0
index bbf69ff55a..80629609ae 100644
@@ -11,10 +11,12 @@
  */
 
 #include "qemu/osdep.h"
+#include CONFIG_DEVICES /* CONFIG_IOMMUFD */
 #include <linux/vfio.h>
 #include <sys/ioctl.h>
 #include "qapi/error.h"
 #include "hw/vfio/vfio-common.h"
+#include "sysemu/iommufd.h"
 #include "hw/s390x/ap-device.h"
 #include "qemu/error-report.h"
 #include "qemu/event_notifier.h"
@@ -204,6 +206,10 @@ static void vfio_ap_unrealize(DeviceState *dev)
 
 static Property vfio_ap_properties[] = {
     DEFINE_PROP_STRING("sysfsdev", VFIOAPDevice, vdev.sysfsdev),
+#ifdef CONFIG_IOMMUFD
+    DEFINE_PROP_LINK("iommufd", VFIOAPDevice, vdev.iommufd,
+                     TYPE_IOMMUFD_BACKEND, IOMMUFDBackend *),
+#endif
     DEFINE_PROP_END_OF_LIST(),
 };
 
Signature · 1 line
2.34.1
#17 lore raw

PATCH v7 15/27 vfio/ap: Make vfio cdev pre-openable by passing a file handle

In reply to Zhenzhong Duan

This gives management tools like libvirt a chance to open the vfio cdev with privilege and pass FD to qemu. This way qemu never needs to have privilege to open a VFIO or iommu cdev node.

---
 hw/vfio/ap.c | 23 ++++++++++++++++++++++-
 1 file changed, 22 insertions(+), 1 deletion(-)
hw/vfio/ap.c +22 -1
index 80629609ae..f180e4a32a 100644
@@ -160,7 +160,10 @@ static void vfio_ap_realize(DeviceState *dev, Error **errp)
     VFIOAPDevice *vapdev = VFIO_AP_DEVICE(dev);
     VFIODevice *vbasedev = &vapdev->vdev;
 
-    vbasedev->name = g_path_get_basename(vbasedev->sysfsdev);
+    if (vfio_device_get_name(vbasedev, errp) < 0) {
+        return;
+    }
+
     vbasedev->ops = &vfio_ap_ops;
     vbasedev->type = VFIO_DEVICE_TYPE_AP;
     vbasedev->dev = dev;
@@ -230,11 +233,28 @@ static const VMStateDescription vfio_ap_vmstate = {
     .unmigratable = 1,
 };
 
+static void vfio_ap_instance_init(Object *obj)
+{
+    VFIOAPDevice *vapdev = VFIO_AP_DEVICE(obj);
+
+    vapdev->vdev.fd = -1;
+}
+
+#ifdef CONFIG_IOMMUFD
+static void vfio_ap_set_fd(Object *obj, const char *str, Error **errp)
+{
+    vfio_device_set_fd(&VFIO_AP_DEVICE(obj)->vdev, str, errp);
+}
+#endif
+
 static void vfio_ap_class_init(ObjectClass *klass, void *data)
 {
     DeviceClass *dc = DEVICE_CLASS(klass);
 
     device_class_set_props(dc, vfio_ap_properties);
+#ifdef CONFIG_IOMMUFD
+    object_class_property_add_str(klass, "fd", NULL, vfio_ap_set_fd);
+#endif
     dc->vmsd = &vfio_ap_vmstate;
     dc->desc = "VFIO-based AP device assignment";
     set_bit(DEVICE_CATEGORY_MISC, dc->categories);
@@ -249,6 +269,7 @@ static const TypeInfo vfio_ap_info = {
     .name = TYPE_VFIO_AP_DEVICE,
     .parent = TYPE_AP_DEVICE,
     .instance_size = sizeof(VFIOAPDevice),
+    .instance_init = vfio_ap_instance_init,
     .class_init = vfio_ap_class_init,
 };
 
Signature · 1 line
2.34.1
#18 lore raw

PATCH v7 16/27 vfio/ccw: Allow the selection of a given iommu backend

In reply to Zhenzhong Duan

Now we support two types of iommu backends, let's add the capability to select one of them. This depends on whether an iommufd object has been linked with the vfio-ccw device:

If the user wants to use the legacy backend, it shall not link the vfio-ccw device with any iommufd object:

-device vfio-ccw,sysfsdev=/sys/bus/mdev/devices/XXX

This is called the legacy mode/backend.

If the user wants to use the iommufd backend (/dev/iommu) it shall pass an iommufd object id in the vfio-ccw device options:

-object iommufd,id=iommufd0
-device vfio-ccw,sysfsdev=/sys/bus/mdev/devices/XXX,iommufd=iommufd0

---
 hw/vfio/ccw.c | 6 ++++++
 1 file changed, 6 insertions(+)
hw/vfio/ccw.c +6 -0
index d857bb8d0f..d2d58bb677 100644
@@ -15,12 +15,14 @@
  */
 
 #include "qemu/osdep.h"
+#include CONFIG_DEVICES /* CONFIG_IOMMUFD */
 #include <linux/vfio.h>
 #include <linux/vfio_ccw.h>
 #include <sys/ioctl.h>
 
 #include "qapi/error.h"
 #include "hw/vfio/vfio-common.h"
+#include "sysemu/iommufd.h"
 #include "hw/s390x/s390-ccw.h"
 #include "hw/s390x/vfio-ccw.h"
 #include "hw/qdev-properties.h"
@@ -677,6 +679,10 @@ static void vfio_ccw_unrealize(DeviceState *dev)
 static Property vfio_ccw_properties[] = {
     DEFINE_PROP_STRING("sysfsdev", VFIOCCWDevice, vdev.sysfsdev),
     DEFINE_PROP_BOOL("force-orb-pfch", VFIOCCWDevice, force_orb_pfch, false),
+#ifdef CONFIG_IOMMUFD
+    DEFINE_PROP_LINK("iommufd", VFIOCCWDevice, vdev.iommufd,
+                     TYPE_IOMMUFD_BACKEND, IOMMUFDBackend *),
+#endif
     DEFINE_PROP_END_OF_LIST(),
 };
 
Signature · 1 line
2.34.1
#19 lore raw

PATCH v7 17/27 vfio/ccw: Make vfio cdev pre-openable by passing a file handle

In reply to Zhenzhong Duan

This gives management tools like libvirt a chance to open the vfio cdev with privilege and pass FD to qemu. This way qemu never needs to have privilege to open a VFIO or iommu cdev node.

---
 hw/vfio/ccw.c | 25 ++++++++++++++++++++++---
 1 file changed, 22 insertions(+), 3 deletions(-)
hw/vfio/ccw.c +22 -3
index d2d58bb677..2afdf17dbe 100644
@@ -590,11 +590,12 @@ static void vfio_ccw_realize(DeviceState *dev, Error **errp)
         }
     }
 
+    if (vfio_device_get_name(vbasedev, errp) < 0) {
+        return;
+    }
+
     vbasedev->ops = &vfio_ccw_ops;
     vbasedev->type = VFIO_DEVICE_TYPE_CCW;
-    vbasedev->name = g_strdup_printf("%x.%x.%04x", vcdev->cdev.hostid.cssid,
-                           vcdev->cdev.hostid.ssid,
-                           vcdev->cdev.hostid.devid);
     vbasedev->dev = dev;
 
     /*
@@ -691,12 +692,29 @@ static const VMStateDescription vfio_ccw_vmstate = {
     .unmigratable = 1,
 };
 
+static void vfio_ccw_instance_init(Object *obj)
+{
+    VFIOCCWDevice *vcdev = VFIO_CCW(obj);
+
+    vcdev->vdev.fd = -1;
+}
+
+#ifdef CONFIG_IOMMUFD
+static void vfio_ccw_set_fd(Object *obj, const char *str, Error **errp)
+{
+    vfio_device_set_fd(&VFIO_CCW(obj)->vdev, str, errp);
+}
+#endif
+
 static void vfio_ccw_class_init(ObjectClass *klass, void *data)
 {
     DeviceClass *dc = DEVICE_CLASS(klass);
     S390CCWDeviceClass *cdc = S390_CCW_DEVICE_CLASS(klass);
 
     device_class_set_props(dc, vfio_ccw_properties);
+#ifdef CONFIG_IOMMUFD
+    object_class_property_add_str(klass, "fd", NULL, vfio_ccw_set_fd);
+#endif
     dc->vmsd = &vfio_ccw_vmstate;
     dc->desc = "VFIO-based subchannel assignment";
     set_bit(DEVICE_CATEGORY_MISC, dc->categories);
@@ -714,6 +732,7 @@ static const TypeInfo vfio_ccw_info = {
     .name = TYPE_VFIO_CCW,
     .parent = TYPE_S390_CCW,
     .instance_size = sizeof(VFIOCCWDevice),
+    .instance_init = vfio_ccw_instance_init,
     .class_init = vfio_ccw_class_init,
 };
 
Signature · 1 line
2.34.1
#20 lore raw

PATCH v7 18/27 vfio: Make VFIOContainerBase poiner parameter const in VFIOIOMMUOps callbacks

In reply to Zhenzhong Duan

Some of the callbacks in VFIOIOMMUOps pass VFIOContainerBase poiner, those callbacks only need read access to the sub object of VFIOContainerBase. So make VFIOContainerBase, VFIOContainer and VFIOIOMMUFDContainer as const in these callbacks.

Local functions called by those callbacks also need same changes to avoid build error.

---
 include/hw/vfio/vfio-common.h         | 12 ++++++----
 include/hw/vfio/vfio-container-base.h | 12 ++++++----
 hw/vfio/common.c                      |  9 +++----
 hw/vfio/container-base.c              |  2 +-
 hw/vfio/container.c                   | 34 ++++++++++++++-------------
 hw/vfio/iommufd.c                     |  8 +++----
 6 files changed, 42 insertions(+), 35 deletions(-)
include/hw/vfio/vfio-common.h +7 -5
index 697bf24a35..efcba19f66 100644
@@ -244,13 +244,15 @@ bool vfio_migration_realize(VFIODevice *vbasedev, Error **errp);
 void vfio_migration_exit(VFIODevice *vbasedev);
 
 int vfio_bitmap_alloc(VFIOBitmap *vbmap, hwaddr size);
-bool vfio_devices_all_running_and_mig_active(VFIOContainerBase *bcontainer);
-bool vfio_devices_all_device_dirty_tracking(VFIOContainerBase *bcontainer);
-int vfio_devices_query_dirty_bitmap(VFIOContainerBase *bcontainer,
+bool
+vfio_devices_all_running_and_mig_active(const VFIOContainerBase *bcontainer);
+bool
+vfio_devices_all_device_dirty_tracking(const VFIOContainerBase *bcontainer);
+int vfio_devices_query_dirty_bitmap(const VFIOContainerBase *bcontainer,
                                     VFIOBitmap *vbmap, hwaddr iova,
                                     hwaddr size);
-int vfio_get_dirty_bitmap(VFIOContainerBase *bcontainer, uint64_t iova,
-                                 uint64_t size, ram_addr_t ram_addr);
+int vfio_get_dirty_bitmap(const VFIOContainerBase *bcontainer, uint64_t iova,
+                          uint64_t size, ram_addr_t ram_addr);
 
 /* Returns 0 on success, or a negative errno. */
 int vfio_device_get_name(VFIODevice *vbasedev, Error **errp);
include/hw/vfio/vfio-container-base.h +7 -5
index 45bb19c767..2ae297ccda 100644
@@ -82,7 +82,7 @@ void vfio_container_del_section_window(VFIOContainerBase *bcontainer,
                                        MemoryRegionSection *section);
 int vfio_container_set_dirty_page_tracking(VFIOContainerBase *bcontainer,
                                            bool start);
-int vfio_container_query_dirty_bitmap(VFIOContainerBase *bcontainer,
+int vfio_container_query_dirty_bitmap(const VFIOContainerBase *bcontainer,
                                       VFIOBitmap *vbmap,
                                       hwaddr iova, hwaddr size);
 
@@ -93,18 +93,20 @@ void vfio_container_destroy(VFIOContainerBase *bcontainer);
 
 struct VFIOIOMMUOps {
     /* basic feature */
-    int (*dma_map)(VFIOContainerBase *bcontainer,
+    int (*dma_map)(const VFIOContainerBase *bcontainer,
                    hwaddr iova, ram_addr_t size,
                    void *vaddr, bool readonly);
-    int (*dma_unmap)(VFIOContainerBase *bcontainer,
+    int (*dma_unmap)(const VFIOContainerBase *bcontainer,
                      hwaddr iova, ram_addr_t size,
                      IOMMUTLBEntry *iotlb);
     int (*attach_device)(const char *name, VFIODevice *vbasedev,
                          AddressSpace *as, Error **errp);
     void (*detach_device)(VFIODevice *vbasedev);
     /* migration feature */
-    int (*set_dirty_page_tracking)(VFIOContainerBase *bcontainer, bool start);
-    int (*query_dirty_bitmap)(VFIOContainerBase *bcontainer, VFIOBitmap *vbmap,
+    int (*set_dirty_page_tracking)(const VFIOContainerBase *bcontainer,
+                                   bool start);
+    int (*query_dirty_bitmap)(const VFIOContainerBase *bcontainer,
+                              VFIOBitmap *vbmap,
                               hwaddr iova, hwaddr size);
     /* PCI specific */
     int (*pci_hot_reset)(VFIODevice *vbasedev, bool single);
hw/vfio/common.c +5 -4
index 6569732b7a..08a3e57672 100644
@@ -204,7 +204,7 @@ static bool vfio_devices_all_dirty_tracking(VFIOContainerBase *bcontainer)
     return true;
 }
 
-bool vfio_devices_all_device_dirty_tracking(VFIOContainerBase *bcontainer)
+bool vfio_devices_all_device_dirty_tracking(const VFIOContainerBase *bcontainer)
 {
     VFIODevice *vbasedev;
 
@@ -221,7 +221,8 @@ bool vfio_devices_all_device_dirty_tracking(VFIOContainerBase *bcontainer)
  * Check if all VFIO devices are running and migration is active, which is
  * essentially equivalent to the migration being in pre-copy phase.
  */
-bool vfio_devices_all_running_and_mig_active(VFIOContainerBase *bcontainer)
+bool
+vfio_devices_all_running_and_mig_active(const VFIOContainerBase *bcontainer)
 {
     VFIODevice *vbasedev;
 
@@ -1139,7 +1140,7 @@ static int vfio_device_dma_logging_report(VFIODevice *vbasedev, hwaddr iova,
     return 0;
 }
 
-int vfio_devices_query_dirty_bitmap(VFIOContainerBase *bcontainer,
+int vfio_devices_query_dirty_bitmap(const VFIOContainerBase *bcontainer,
                                     VFIOBitmap *vbmap, hwaddr iova,
                                     hwaddr size)
 {
@@ -1162,7 +1163,7 @@ int vfio_devices_query_dirty_bitmap(VFIOContainerBase *bcontainer,
     return 0;
 }
 
-int vfio_get_dirty_bitmap(VFIOContainerBase *bcontainer, uint64_t iova,
+int vfio_get_dirty_bitmap(const VFIOContainerBase *bcontainer, uint64_t iova,
                           uint64_t size, ram_addr_t ram_addr)
 {
     bool all_device_dirty_tracking =
hw/vfio/container-base.c +1 -1
index eee2dcfe76..1ffd25bbfa 100644
@@ -63,7 +63,7 @@ int vfio_container_set_dirty_page_tracking(VFIOContainerBase *bcontainer,
     return bcontainer->ops->set_dirty_page_tracking(bcontainer, start);
 }
 
-int vfio_container_query_dirty_bitmap(VFIOContainerBase *bcontainer,
+int vfio_container_query_dirty_bitmap(const VFIOContainerBase *bcontainer,
                                       VFIOBitmap *vbmap,
                                       hwaddr iova, hwaddr size)
 {
hw/vfio/container.c +18 -16
index 1dbf9b9a17..b22feb8ded 100644
@@ -61,11 +61,11 @@ static int vfio_ram_block_discard_disable(VFIOContainer *container, bool state)
     }
 }
 
-static int vfio_dma_unmap_bitmap(VFIOContainer *container,
+static int vfio_dma_unmap_bitmap(const VFIOContainer *container,
                                  hwaddr iova, ram_addr_t size,
                                  IOMMUTLBEntry *iotlb)
 {
-    VFIOContainerBase *bcontainer = &container->bcontainer;
+    const VFIOContainerBase *bcontainer = &container->bcontainer;
     struct vfio_iommu_type1_dma_unmap *unmap;
     struct vfio_bitmap *bitmap;
     VFIOBitmap vbmap;
@@ -117,11 +117,12 @@ unmap_exit:
 /*
  * DMA - Mapping and unmapping for the "type1" IOMMU interface used on x86
  */
-static int vfio_legacy_dma_unmap(VFIOContainerBase *bcontainer, hwaddr iova,
-                                 ram_addr_t size, IOMMUTLBEntry *iotlb)
+static int vfio_legacy_dma_unmap(const VFIOContainerBase *bcontainer,
+                                 hwaddr iova, ram_addr_t size,
+                                 IOMMUTLBEntry *iotlb)
 {
-    VFIOContainer *container = container_of(bcontainer, VFIOContainer,
-                                            bcontainer);
+    const VFIOContainer *container = container_of(bcontainer, VFIOContainer,
+                                                  bcontainer);
     struct vfio_iommu_type1_dma_unmap unmap = {
         .argsz = sizeof(unmap),
         .flags = 0,
@@ -174,11 +175,11 @@ static int vfio_legacy_dma_unmap(VFIOContainerBase *bcontainer, hwaddr iova,
     return 0;
 }
 
-static int vfio_legacy_dma_map(VFIOContainerBase *bcontainer, hwaddr iova,
+static int vfio_legacy_dma_map(const VFIOContainerBase *bcontainer, hwaddr iova,
                                ram_addr_t size, void *vaddr, bool readonly)
 {
-    VFIOContainer *container = container_of(bcontainer, VFIOContainer,
-                                            bcontainer);
+    const VFIOContainer *container = container_of(bcontainer, VFIOContainer,
+                                                  bcontainer);
     struct vfio_iommu_type1_dma_map map = {
         .argsz = sizeof(map),
         .flags = VFIO_DMA_MAP_FLAG_READ,
@@ -207,11 +208,12 @@ static int vfio_legacy_dma_map(VFIOContainerBase *bcontainer, hwaddr iova,
     return -errno;
 }
 
-static int vfio_legacy_set_dirty_page_tracking(VFIOContainerBase *bcontainer,
-                                               bool start)
+static int
+vfio_legacy_set_dirty_page_tracking(const VFIOContainerBase *bcontainer,
+                                    bool start)
 {
-    VFIOContainer *container = container_of(bcontainer, VFIOContainer,
-                                            bcontainer);
+    const VFIOContainer *container = container_of(bcontainer, VFIOContainer,
+                                                  bcontainer);
     int ret;
     struct vfio_iommu_type1_dirty_bitmap dirty = {
         .argsz = sizeof(dirty),
@@ -233,12 +235,12 @@ static int vfio_legacy_set_dirty_page_tracking(VFIOContainerBase *bcontainer,
     return ret;
 }
 
-static int vfio_legacy_query_dirty_bitmap(VFIOContainerBase *bcontainer,
+static int vfio_legacy_query_dirty_bitmap(const VFIOContainerBase *bcontainer,
                                           VFIOBitmap *vbmap,
                                           hwaddr iova, hwaddr size)
 {
-    VFIOContainer *container = container_of(bcontainer, VFIOContainer,
-                                            bcontainer);
+    const VFIOContainer *container = container_of(bcontainer, VFIOContainer,
+                                                  bcontainer);
     struct vfio_iommu_type1_dirty_bitmap *dbitmap;
     struct vfio_iommu_type1_dirty_bitmap_get *range;
     int ret;
hw/vfio/iommufd.c +4 -4
index 5accd26484..87a561c545 100644
@@ -26,10 +26,10 @@
 #include "qemu/chardev_open.h"
 #include "pci.h"
 
-static int iommufd_cdev_map(VFIOContainerBase *bcontainer, hwaddr iova,
+static int iommufd_cdev_map(const VFIOContainerBase *bcontainer, hwaddr iova,
                             ram_addr_t size, void *vaddr, bool readonly)
 {
-    VFIOIOMMUFDContainer *container =
+    const VFIOIOMMUFDContainer *container =
         container_of(bcontainer, VFIOIOMMUFDContainer, bcontainer);
 
     return iommufd_backend_map_dma(container->be,
@@ -37,11 +37,11 @@ static int iommufd_cdev_map(VFIOContainerBase *bcontainer, hwaddr iova,
                                    iova, size, vaddr, readonly);
 }
 
-static int iommufd_cdev_unmap(VFIOContainerBase *bcontainer,
+static int iommufd_cdev_unmap(const VFIOContainerBase *bcontainer,
                               hwaddr iova, ram_addr_t size,
                               IOMMUTLBEntry *iotlb)
 {
-    VFIOIOMMUFDContainer *container =
+    const VFIOIOMMUFDContainer *container =
         container_of(bcontainer, VFIOIOMMUFDContainer, bcontainer);
 
     /* TODO: Handle dma_unmap_bitmap with iotlb args (migration) */
Signature · 1 line
2.34.1
#21 lore raw

PATCH v7 19/27 hw/arm: Activate IOMMUFD for virt machines

In reply to Zhenzhong Duan

From: Cédric Le Goater <[email protected]>

---
 hw/arm/Kconfig | 1 +
 1 file changed, 1 insertion(+)
hw/arm/Kconfig +1 -0
index 3ada335a24..660f49db49 100644
@@ -8,6 +8,7 @@ config ARM_VIRT
     imply TPM_TIS_SYSBUS
     imply TPM_TIS_I2C
     imply NVDIMM
+    imply IOMMUFD
     select ARM_GIC
     select ACPI
     select ARM_SMMUV3
Signature · 1 line
2.34.1
#22 lore raw

PATCH v7 20/27 kconfig: Activate IOMMUFD for s390x machines

In reply to Zhenzhong Duan

From: Cédric Le Goater <[email protected]>

---
 hw/s390x/Kconfig | 1 +
 1 file changed, 1 insertion(+)
hw/s390x/Kconfig +1 -0
index 4c068d7960..26ad104485 100644
@@ -6,6 +6,7 @@ config S390_CCW_VIRTIO
     imply VFIO_CCW
     imply WDT_DIAG288
     imply PCIE_DEVICES
+    imply IOMMUFD
     select PCI_EXPRESS
     select S390_FLIC
     select S390_FLIC_KVM if KVM
Signature · 1 line
2.34.1
#23 lore raw

PATCH v7 21/27 hw/i386: Activate IOMMUFD for q35 machines

In reply to Zhenzhong Duan

From: Cédric Le Goater <[email protected]>

---
 hw/i386/Kconfig | 1 +
 1 file changed, 1 insertion(+)
hw/i386/Kconfig +1 -0
index 55850791df..a1846be6f7 100644
@@ -95,6 +95,7 @@ config Q35
     imply E1000E_PCI_EXPRESS
     imply VMPORT
     imply VMMOUSE
+    imply IOMMUFD
     select PC_PCI
     select PC_ACPI
     select PCI_EXPRESS_Q35
Signature · 1 line
2.34.1
#24 lore raw

PATCH v7 22/27 vfio/pci: Move VFIODevice initializations in vfio_instance_init

In reply to Zhenzhong Duan

Some of the VFIODevice initializations is in vfio_realize, move all of them in vfio_instance_init.

No functional change intended.

---
 hw/vfio/pci.c | 10 ++++++----
 1 file changed, 6 insertions(+), 4 deletions(-)
hw/vfio/pci.c +6 -4
index 445d58c8e5..87405584d7 100644
@@ -2969,9 +2969,6 @@ static void vfio_realize(PCIDevice *pdev, Error **errp)
     if (vfio_device_get_name(vbasedev, errp) < 0) {
         return;
     }
-    vbasedev->ops = &vfio_pci_ops;
-    vbasedev->type = VFIO_DEVICE_TYPE_PCI;
-    vbasedev->dev = DEVICE(vdev);
 
     /*
      * Mediated devices *might* operate compatibly with discarding of RAM, but
@@ -3320,6 +3317,7 @@ static void vfio_instance_init(Object *obj)
 {
     PCIDevice *pci_dev = PCI_DEVICE(obj);
     VFIOPCIDevice *vdev = VFIO_PCI(obj);
+    VFIODevice *vbasedev = &vdev->vbasedev;
 
     device_add_bootindex_property(obj, &vdev->bootindex,
                                   "bootindex", NULL,
@@ -3328,7 +3326,11 @@ static void vfio_instance_init(Object *obj)
     vdev->host.bus = ~0U;
     vdev->host.slot = ~0U;
     vdev->host.function = ~0U;
-    vdev->vbasedev.fd = -1;
+
+    vbasedev->type = VFIO_DEVICE_TYPE_PCI;
+    vbasedev->ops = &vfio_pci_ops;
+    vbasedev->dev = DEVICE(vdev);
+    vbasedev->fd = -1;
 
     vdev->nv_gpudirect_clique = 0xFF;
 
Signature · 1 line
2.34.1
#25 lore raw

PATCH v7 23/27 vfio/platform: Move VFIODevice initializations in vfio_platform_instance_init

In reply to Zhenzhong Duan

Some of the VFIODevice initializations is in vfio_platform_realize, move all of them in vfio_platform_instance_init.

No functional change intended.

---
 hw/vfio/platform.c | 10 +++++-----
 1 file changed, 5 insertions(+), 5 deletions(-)
hw/vfio/platform.c +5 -5
index a97d9c6234..506eb8193f 100644
@@ -581,10 +581,6 @@ static void vfio_platform_realize(DeviceState *dev, Error **errp)
     VFIODevice *vbasedev = &vdev->vbasedev;
     int i, ret;
 
-    vbasedev->type = VFIO_DEVICE_TYPE_PLATFORM;
-    vbasedev->dev = dev;
-    vbasedev->ops = &vfio_platform_ops;
-
     qemu_mutex_init(&vdev->intp_mutex);
 
     trace_vfio_platform_realize(vbasedev->sysfsdev ?
@@ -659,8 +655,12 @@ static Property vfio_platform_dev_properties[] = {
 static void vfio_platform_instance_init(Object *obj)
 {
     VFIOPlatformDevice *vdev = VFIO_PLATFORM_DEVICE(obj);
+    VFIODevice *vbasedev = &vdev->vbasedev;
 
-    vdev->vbasedev.fd = -1;
+    vbasedev->type = VFIO_DEVICE_TYPE_PLATFORM;
+    vbasedev->ops = &vfio_platform_ops;
+    vbasedev->dev = DEVICE(vdev);
+    vbasedev->fd = -1;
 }
 
 #ifdef CONFIG_IOMMUFD
Signature · 1 line
2.34.1
#26 lore raw

PATCH v7 24/27 vfio/ap: Move VFIODevice initializations in vfio_ap_instance_init

In reply to Zhenzhong Duan

Some of the VFIODevice initializations is in vfio_ap_realize, move all of them in vfio_ap_instance_init.

No functional change intended.

---
 hw/vfio/ap.c | 26 +++++++++++++-------------
 1 file changed, 13 insertions(+), 13 deletions(-)
hw/vfio/ap.c +13 -13
index f180e4a32a..95fe7cd98b 100644
@@ -164,18 +164,6 @@ static void vfio_ap_realize(DeviceState *dev, Error **errp)
         return;
     }
 
-    vbasedev->ops = &vfio_ap_ops;
-    vbasedev->type = VFIO_DEVICE_TYPE_AP;
-    vbasedev->dev = dev;
-
-    /*
-     * vfio-ap devices operate in a way compatible with discarding of
-     * memory in RAM blocks, as no pages are pinned in the host.
-     * This needs to be set before vfio_get_device() for vfio common to
-     * handle ram_block_discard_disable().
-     */
-    vapdev->vdev.ram_block_discard_allowed = true;
-
     ret = vfio_attach_device(vbasedev->name, vbasedev,
                              &address_space_memory, errp);
     if (ret) {
@@ -236,8 +224,20 @@ static const VMStateDescription vfio_ap_vmstate = {
 static void vfio_ap_instance_init(Object *obj)
 {
     VFIOAPDevice *vapdev = VFIO_AP_DEVICE(obj);
+    VFIODevice *vbasedev = &vapdev->vdev;
 
-    vapdev->vdev.fd = -1;
+    vbasedev->type = VFIO_DEVICE_TYPE_AP;
+    vbasedev->ops = &vfio_ap_ops;
+    vbasedev->dev = DEVICE(vapdev);
+    vbasedev->fd = -1;
+
+    /*
+     * vfio-ap devices operate in a way compatible with discarding of
+     * memory in RAM blocks, as no pages are pinned in the host.
+     * This needs to be set before vfio_get_device() for vfio common to
+     * handle ram_block_discard_disable().
+     */
+    vbasedev->ram_block_discard_allowed = true;
 }
 
 #ifdef CONFIG_IOMMUFD
Signature · 1 line
2.34.1
#27 lore raw

PATCH v7 25/27 vfio/ccw: Move VFIODevice initializations in vfio_ccw_instance_init

In reply to Zhenzhong Duan

Some of the VFIODevice initializations is in vfio_ccw_realize, move all of them in vfio_ccw_instance_init.

No functional change intended.

---
 hw/vfio/ccw.c | 30 +++++++++++++++---------------
 1 file changed, 15 insertions(+), 15 deletions(-)
hw/vfio/ccw.c +15 -15
index 2afdf17dbe..6305a4c1b8 100644
@@ -594,20 +594,6 @@ static void vfio_ccw_realize(DeviceState *dev, Error **errp)
         return;
     }
 
-    vbasedev->ops = &vfio_ccw_ops;
-    vbasedev->type = VFIO_DEVICE_TYPE_CCW;
-    vbasedev->dev = dev;
-
-    /*
-     * All vfio-ccw devices are believed to operate in a way compatible with
-     * discarding of memory in RAM blocks, ie. pages pinned in the host are
-     * in the current working set of the guest driver and therefore never
-     * overlap e.g., with pages available to the guest balloon driver.  This
-     * needs to be set before vfio_get_device() for vfio common to handle
-     * ram_block_discard_disable().
-     */
-    vbasedev->ram_block_discard_allowed = true;
-
     ret = vfio_attach_device(cdev->mdevid, vbasedev,
                              &address_space_memory, errp);
     if (ret) {
@@ -695,8 +681,22 @@ static const VMStateDescription vfio_ccw_vmstate = {
 static void vfio_ccw_instance_init(Object *obj)
 {
     VFIOCCWDevice *vcdev = VFIO_CCW(obj);
+    VFIODevice *vbasedev = &vcdev->vdev;
+
+    vbasedev->type = VFIO_DEVICE_TYPE_CCW;
+    vbasedev->ops = &vfio_ccw_ops;
+    vbasedev->dev = DEVICE(vcdev);
+    vbasedev->fd = -1;
 
-    vcdev->vdev.fd = -1;
+    /*
+     * All vfio-ccw devices are believed to operate in a way compatible with
+     * discarding of memory in RAM blocks, ie. pages pinned in the host are
+     * in the current working set of the guest driver and therefore never
+     * overlap e.g., with pages available to the guest balloon driver.  This
+     * needs to be set before vfio_get_device() for vfio common to handle
+     * ram_block_discard_disable().
+     */
+    vbasedev->ram_block_discard_allowed = true;
 }
 
 #ifdef CONFIG_IOMMUFD
Signature · 1 line
2.34.1
#28 lore raw

PATCH v7 26/27 vfio: Introduce a helper function to initialize VFIODevice

In reply to Zhenzhong Duan

Introduce a helper function to replace the common code to initialize VFIODevice in pci, platform, ap and ccw VFIO device.

No functional change intended.

---
 include/hw/vfio/vfio-common.h |  2 ++
 hw/vfio/ap.c                  |  8 ++------
 hw/vfio/ccw.c                 |  8 ++------
 hw/vfio/helpers.c             | 11 +++++++++++
 hw/vfio/pci.c                 |  6 ++----
 hw/vfio/platform.c            |  6 ++----
 6 files changed, 21 insertions(+), 20 deletions(-)
include/hw/vfio/vfio-common.h +2 -0
index efcba19f66..b8aa8a5495 100644
@@ -257,4 +257,6 @@ int vfio_get_dirty_bitmap(const VFIOContainerBase *bcontainer, uint64_t iova,
 /* Returns 0 on success, or a negative errno. */
 int vfio_device_get_name(VFIODevice *vbasedev, Error **errp);
 void vfio_device_set_fd(VFIODevice *vbasedev, const char *str, Error **errp);
+void vfio_device_init(VFIODevice *vbasedev, int type, VFIODeviceOps *ops,
+                      DeviceState *dev, bool ram_discard);
 #endif /* HW_VFIO_VFIO_COMMON_H */
hw/vfio/ap.c +2 -6
index 95fe7cd98b..e157aa1ff7 100644
@@ -226,18 +226,14 @@ static void vfio_ap_instance_init(Object *obj)
     VFIOAPDevice *vapdev = VFIO_AP_DEVICE(obj);
     VFIODevice *vbasedev = &vapdev->vdev;
 
-    vbasedev->type = VFIO_DEVICE_TYPE_AP;
-    vbasedev->ops = &vfio_ap_ops;
-    vbasedev->dev = DEVICE(vapdev);
-    vbasedev->fd = -1;
-
     /*
      * vfio-ap devices operate in a way compatible with discarding of
      * memory in RAM blocks, as no pages are pinned in the host.
      * This needs to be set before vfio_get_device() for vfio common to
      * handle ram_block_discard_disable().
      */
-    vbasedev->ram_block_discard_allowed = true;
+    vfio_device_init(vbasedev, VFIO_DEVICE_TYPE_AP, &vfio_ap_ops,
+                     DEVICE(vapdev), true);
 }
 
 #ifdef CONFIG_IOMMUFD
hw/vfio/ccw.c +2 -6
index 6305a4c1b8..90e4a53437 100644
@@ -683,11 +683,6 @@ static void vfio_ccw_instance_init(Object *obj)
     VFIOCCWDevice *vcdev = VFIO_CCW(obj);
     VFIODevice *vbasedev = &vcdev->vdev;
 
-    vbasedev->type = VFIO_DEVICE_TYPE_CCW;
-    vbasedev->ops = &vfio_ccw_ops;
-    vbasedev->dev = DEVICE(vcdev);
-    vbasedev->fd = -1;
-
     /*
      * All vfio-ccw devices are believed to operate in a way compatible with
      * discarding of memory in RAM blocks, ie. pages pinned in the host are
@@ -696,7 +691,8 @@ static void vfio_ccw_instance_init(Object *obj)
      * needs to be set before vfio_get_device() for vfio common to handle
      * ram_block_discard_disable().
      */
-    vbasedev->ram_block_discard_allowed = true;
+    vfio_device_init(vbasedev, VFIO_DEVICE_TYPE_CCW, &vfio_ccw_ops,
+                     DEVICE(vcdev), true);
 }
 
 #ifdef CONFIG_IOMMUFD
hw/vfio/helpers.c +11 -0
index 3592c3d54e..6789870802 100644
@@ -652,3 +652,14 @@ void vfio_device_set_fd(VFIODevice *vbasedev, const char *str, Error **errp)
     }
     vbasedev->fd = fd;
 }
+
+void vfio_device_init(VFIODevice *vbasedev, int type, VFIODeviceOps *ops,
+                      DeviceState *dev, bool ram_discard)
+{
+    vbasedev->type = type;
+    vbasedev->ops = ops;
+    vbasedev->dev = dev;
+    vbasedev->fd = -1;
+
+    vbasedev->ram_block_discard_allowed = ram_discard;
+}
hw/vfio/pci.c +2 -4
index 87405584d7..1874ec1aba 100644
@@ -3327,10 +3327,8 @@ static void vfio_instance_init(Object *obj)
     vdev->host.slot = ~0U;
     vdev->host.function = ~0U;
 
-    vbasedev->type = VFIO_DEVICE_TYPE_PCI;
-    vbasedev->ops = &vfio_pci_ops;
-    vbasedev->dev = DEVICE(vdev);
-    vbasedev->fd = -1;
+    vfio_device_init(vbasedev, VFIO_DEVICE_TYPE_PCI, &vfio_pci_ops,
+                     DEVICE(vdev), false);
 
     vdev->nv_gpudirect_clique = 0xFF;
 
hw/vfio/platform.c +2 -4
index 506eb8193f..a8d9b7da63 100644
@@ -657,10 +657,8 @@ static void vfio_platform_instance_init(Object *obj)
     VFIOPlatformDevice *vdev = VFIO_PLATFORM_DEVICE(obj);
     VFIODevice *vbasedev = &vdev->vbasedev;
 
-    vbasedev->type = VFIO_DEVICE_TYPE_PLATFORM;
-    vbasedev->ops = &vfio_platform_ops;
-    vbasedev->dev = DEVICE(vdev);
-    vbasedev->fd = -1;
+    vfio_device_init(vbasedev, VFIO_DEVICE_TYPE_PLATFORM, &vfio_platform_ops,
+                     DEVICE(vdev), false);
 }
 
 #ifdef CONFIG_IOMMUFD
Signature · 1 line
2.34.1
#29 lore raw

PATCH v7 27/27 docs/devel: Add VFIO iommufd backend documentation

In reply to Zhenzhong Duan
---
 MAINTAINERS                    |   1 +
 docs/devel/index-internals.rst |   1 +
 docs/devel/vfio-iommufd.rst    | 166 +++++++++++++++++++++++++++++++++
 3 files changed, 168 insertions(+)
 create mode 100644 docs/devel/vfio-iommufd.rst
MAINTAINERS +1 -0
index ca70bb4e64..0ddb20a35f 100644
@@ -2176,6 +2176,7 @@ F: backends/iommufd.c
 F: include/sysemu/iommufd.h
 F: include/qemu/chardev_open.h
 F: util/chardev_open.c
+F: docs/devel/vfio-iommufd.rst
 
 vhost
 M: Michael S. Tsirkin <[email protected]>
docs/devel/index-internals.rst +1 -0
index 6f81df92bc..3def4a138b 100644
@@ -18,5 +18,6 @@ Details about QEMU's various subsystems including how to add features to them.
    s390-dasd-ipl
    tracing
    vfio-migration
+   vfio-iommufd
    writing-monitor-commands
    virtio-backends
docs/devel/vfio-iommufd.rst new file +166 -0

166 lines not on this page · raw message

Signature · 1 line
2.34.1
#30 lore raw
In reply to Zhenzhong Duan

Hello Zhenzhong

Quoted 40 lines · Zhenzhong Duan

Hi,

Thanks all for giving guides and comments on previous series, this is the remaining part of the iommufd support.

Besides suggested changes in v6, I'd like to highlight two changes for final review:
1. Instantiate can_be_deleted callback to fix race where iommufd object can be deleted before vfio device
2. After careful re-thinking, I'd like to follow Nicolin's suggestion in v5, remove is_ioas check which indeed looks heavy just for tracepoint. In fact we can get corresponding info by looking over trace context.

PATCH 1: Introduce iommufd object
PATCH 2-9: add IOMMUFD container and cdev support PATCH 10-17: fd passing for cdev and linking to IOMMUFD PATCH 18: make VFIOContainerBase parameter const PATCH 19-21: Compile out for IOMMUFD for arm, s390x and x86 PATCH 22-26: vfio device init code cleanup
PATCH 27: add iommufd doc

We have done wide test with different combinations, e.g:
- PCI device were tested
- FD passing and hot reset with some trick.
- device hotplug test with legacy and iommufd backends
- with or without vIOMMU for legacy and iommufd backends
- divices linked to different iommufds
- VFIO migration with a E800 net card(no dirty sync support) passthrough
- platform, ccw and ap were only compile-tested due to environment limit
- test mdev pass through with mtty and mix with real device and different BE
- test iommufd object hotplug/unplug and mix with vfio device plug/unplug

Given some iommufd kernel limitations, the iommufd backend is not yet fully on par with the legacy backend w.r.t. features like:
- p2p mappings (you will see related error traces)
- dirty page sync
- and etc.

Quoted 2 lines

qemu code: https://github.com/yiliu1765/qemu/commits/zhenzhong/iommufd_cdev_v7
Based on vfio-next, commit id: c487fb8a50

The series is pushed on top of vfio-next in the vfio-8.2 tree :

https://github.com/legoater/qemu/commits/vfio-8.2

with a little extra to deal with a PPC build failure.

Thanks,

C.

#31 lore raw
Quoted 51 lines

-----Original Message-----
From: Cédric Le Goater <[email protected]>
Sent: Wednesday, November 22, 2023 1:23 AM
Subject: Re: [PATCH v7 00/27] vfio: Adopt iommufd

Hello Zhenzhong

Quoted 33 lines · Zhenzhong Duan

Hi,

Thanks all for giving guides and comments on previous series, this is the remaining part of the iommufd support.

Besides suggested changes in v6, I'd like to highlight two changes for final review:
1. Instantiate can_be_deleted callback to fix race where iommufd object can be deleted before vfio device
2. After careful re-thinking, I'd like to follow Nicolin's suggestion in v5, remove is_ioas check which indeed looks heavy just for tracepoint. In fact we can get corresponding info by looking over trace context.

PATCH 1: Introduce iommufd object
PATCH 2-9: add IOMMUFD container and cdev support PATCH 10-17: fd passing for cdev and linking to IOMMUFD PATCH 18: make VFIOContainerBase parameter const PATCH 19-21: Compile out for IOMMUFD for arm, s390x and x86 PATCH 22-26: vfio device init code cleanup
PATCH 27: add iommufd doc

We have done wide test with different combinations, e.g:
- PCI device were tested
- FD passing and hot reset with some trick.
- device hotplug test with legacy and iommufd backends
- with or without vIOMMU for legacy and iommufd backends
- divices linked to different iommufds
- VFIO migration with a E800 net card(no dirty sync support) passthrough
- platform, ccw and ap were only compile-tested due to environment limit
- test mdev pass through with mtty and mix with real device and different BE
- test iommufd object hotplug/unplug and mix with vfio device plug/unplug

Quoted 8 lines

Given some iommufd kernel limitations, the iommufd backend is not yet fully on par with the legacy backend w.r.t. features like:
- p2p mappings (you will see related error traces)
- dirty page sync
- and etc.

qemu code:

Quoted 8 lines

https://github.com/yiliu1765/qemu/commits/zhenzhong/iommufd_cdev_v7

Quoted 1 line

Based on vfio-next, commit id: c487fb8a50

The series is pushed on top of vfio-next in the vfio-8.2 tree :

https://github.com/legoater/qemu/commits/vfio-8.2

with a little extra to deal with a PPC build failure.

Thanks Cédric. That's strange I didn't see this failure on my env which has CONFIG_VFIO_PCI enabled by default for PPC.

BRs.
Zhenzhong

#32 lore raw
Quoted 9 lines
Quoted 6 lines

The series is pushed on top of vfio-next in the vfio-8.2 tree :

https://github.com/legoater/qemu/commits/vfio-8.2

with a little extra to deal with a PPC build failure.

Thanks Cédric. That's strange I didn't see this failure on my env which has CONFIG_VFIO_PCI enabled by default for PPC.

The compile issue shows with --without-default-devices.

VFIO is always selected (see ppc/Kconfig) but VFIO_PCI is not when --without-default-devices is used. Hence the compile failure because of the common vfio-pci routines exported in pci.c.

Ideally, we should use an 'imply VFIO' in ppc/Kconfig because VFIO is not a required subsystem for the pseries machine. If that was the case, we wouldn't compile the VFIO EEH hooks defined in hw/ppc/spapr_pci_vfio.c :

  bool spapr_phb_eeh_available(SpaprPhbState *sphb);
  int spapr_phb_vfio_eeh_set_option(SpaprPhbState *sphb,
                                    unsigned int addr, int option);
  int spapr_phb_vfio_eeh_get_state(SpaprPhbState *sphb, int *state);
  int spapr_phb_vfio_eeh_reset(SpaprPhbState *sphb, int option);
  int spapr_phb_vfio_eeh_configure(SpaprPhbState *sphb);
  void spapr_phb_vfio_reset(DeviceState *qdev);

It is not that simple to fix. The simpler approach is to force compile of VFIO PCI in ppc/Kconfig with a 'select VFIO_PCI'. we should improve that.

Thanks,

C.

#33 lore raw
Quoted 18 lines

-----Original Message-----
From: Cédric Le Goater <[email protected]>
Sent: Wednesday, November 22, 2023 4:07 PM
Subject: Re: [PATCH v7 00/27] vfio: Adopt iommufd

Quoted 8 lines
Quoted 5 lines

The series is pushed on top of vfio-next in the vfio-8.2 tree :

https://github.com/legoater/qemu/commits/vfio-8.2

with a little extra to deal with a PPC build failure.

Thanks Cédric. That's strange I didn't see this failure on my env which has CONFIG_VFIO_PCI enabled by default for PPC.

Quoted 5 lines

The compile issue shows with --without-default-devices.

VFIO is always selected (see ppc/Kconfig) but VFIO_PCI is not when --without-default-devices is used. Hence the compile failure because of the common vfio-pci routines exported in pci.c.

Clear, thanks

Quoted 6 lines

Ideally, we should use an 'imply VFIO' in ppc/Kconfig because VFIO is not a required subsystem for the pseries machine. If that was the case, we wouldn't compile the VFIO EEH hooks defined in hw/ppc/spapr_pci_vfio.c :

Quoted 7 lines
  bool spapr_phb_eeh_available(SpaprPhbState *sphb);
  int spapr_phb_vfio_eeh_set_option(SpaprPhbState *sphb,
                                    unsigned int addr, int option);
  int spapr_phb_vfio_eeh_get_state(SpaprPhbState *sphb, int *state);
  int spapr_phb_vfio_eeh_reset(SpaprPhbState *sphb, int option);
  int spapr_phb_vfio_eeh_configure(SpaprPhbState *sphb);
  void spapr_phb_vfio_reset(DeviceState *qdev);

Indeed, I reproduced same after some try out.
Maybe need a stub file for those functions.

Quoted 4 lines

It is not that simple to fix. The simpler approach is to force compile of VFIO PCI in ppc/Kconfig with a 'select VFIO_PCI'. we should improve that.

Yes, not a blocking issue after your fix. I can have a try when I'm idle.

Thanks
Zhenzhong

Tested-by on the v7 series
#34 lore raw
In reply to Zhenzhong Duan
Quoted 2 lines · Zhenzhong Duan

qemu code: https://github.com/yiliu1765/qemu/commits/zhenzhong/iommufd_cdev_v7
Based on vfio-next, commit id: c487fb8a50

I've tested with an aarch64-softmmu build using both legacy VFIO passthrough and IOMMUFD+cdev, although this might be similar to what Eric tested.

Also, tried rebasing our nesting changes on top and ran some 2-stage translation sanity using this branch:
https://github.com/nicolinc/qemu/tree/wip/iommufd_nesting-11212023-cdev-v7
(Note that the nesting branch is WIP with no stability guarantee)

I'll do more tests with vSVA cases in the next days, yet FWIW:

#35 lore raw
Quoted 17 lines

-----Original Message-----
From: Nicolin Chen <[email protected]>
Sent: Wednesday, November 22, 2023 6:56 AM
Subject: Re: [PATCH v7 00/27] vfio: Adopt iommufd

Quoted 1 line · Zhenzhong Duan

qemu code:

https://github.com/yiliu1765/qemu/commits/zhenzhong/iommufd_cdev_v7

Quoted 1 line

Based on vfio-next, commit id: c487fb8a50

I've tested with an aarch64-softmmu build using both legacy VFIO passthrough and IOMMUFD+cdev, although this might be similar to what Eric tested.

Quoted 8 lines

Also, tried rebasing our nesting changes on top and ran some 2-stage translation sanity using this branch:
https://github.com/nicolinc/qemu/tree/wip/iommufd_nesting-11212023-cdev-v7
(Note that the nesting branch is WIP with no stability guarantee)

I'll do more tests with vSVA cases in the next days, yet FWIW:

Thanks Nicolin.

BRs.
Zhenzhong

#36 lore raw
In reply to Zhenzhong Duan
Quoted 33 lines · Zhenzhong Duan

Hi,

Thanks all for giving guides and comments on previous series, this is the remaining part of the iommufd support.

Besides suggested changes in v6, I'd like to highlight two changes for final review:
1. Instantiate can_be_deleted callback to fix race where iommufd object can be deleted before vfio device
2. After careful re-thinking, I'd like to follow Nicolin's suggestion in v5, remove is_ioas check which indeed looks heavy just for tracepoint. In fact we can get corresponding info by looking over trace context.

PATCH 1: Introduce iommufd object
PATCH 2-9: add IOMMUFD container and cdev support PATCH 10-17: fd passing for cdev and linking to IOMMUFD PATCH 18: make VFIOContainerBase parameter const PATCH 19-21: Compile out for IOMMUFD for arm, s390x and x86 PATCH 22-26: vfio device init code cleanup
PATCH 27: add iommufd doc

We have done wide test with different combinations, e.g:
- PCI device were tested
- FD passing and hot reset with some trick.
- device hotplug test with legacy and iommufd backends
- with or without vIOMMU for legacy and iommufd backends
- divices linked to different iommufds
- VFIO migration with a E800 net card(no dirty sync support) passthrough
- platform, ccw and ap were only compile-tested due to environment limit
- test mdev pass through with mtty and mix with real device and different BE
- test iommufd object hotplug/unplug and mix with vfio device plug/unplug

Quoted 4 lines

Given some iommufd kernel limitations, the iommufd backend is not yet fully on par with the legacy backend w.r.t. features like:
- p2p mappings (you will see related error traces)
- dirty page sync

Just as a quick update: I intend to follow-up with this (alongside my other debt) when I am back from vacation ~2weeks from now. The one thing needed before dirty tracking enabling is a userspace autodomains that's equivalent to the kernel.

I don't know what to do about mdevs tbh, considering there's no hw domain going on it's just telling iommufd that 'hey I am accessing these pages' (IIUC I could be missing something). Right now it just falls back to IOAS attach instead of hwpt-id attach if it all fails;

Here's a partial snip below that is trying to match kernel iommufd_device_auto_get_domain(). It's not that far from Zhenzhong v5 implementation, except that we handle the -EINVAL from the attach to allocate a new hwpt for said device, and if that fails then just bail out like the kernel.

static int iommufd_cdev_attach_container(VFIODevice *vbasedev,
VFIOIOMMUFDContainer *container, Error **errp)
{
- return iommufd_cdev_attach_ioas_hwpt(vbasedev, container->ioas_id, errp);
+ uint32_t pt_id;
+
+ if (!iommufd_cdev_autodomains_get(vbasedev, container, &pt_id, errp)) {
+ return 0;
+ }
+ QLIST_FOREACH(hwpt, &container->hwpt_list, next) {
+ ret = iommufd_cdev_attach_ioas_hwpt(vbasedev, hwpt->hwpt_id, &err);
+ if (ret) {
+ /* -EINVAL means the domain is incompatible with the device. */
+ if (ret == -EINVAL) {
+ continue;
+ }
+ return ret;
+ } else {

+            vbasedev->hwpt = hwpt;
+            *hwpt_id = hwpt->hwpt_id;
+            return 0;

+ }
+ }
+
+ ret = iommufd_backend_alloc_hwpt(iommufd, vbasedev->devid,
+ container->ioas_id, 0, 0, 0,
+ NULL, hwpt_id);
+ if (ret) {
+ error_setg_errno(errp, errno, "error alloc shadow hwpt");
+ return ret;
+ }
+

+    hwpt = g_malloc0(sizeof(*hwpt));
+    hwpt->hwpt_id = *hwpt_id;
+    QLIST_INIT(&hwpt->device_list);
+
+    ret = iommufd_cdev_attach_ioas_hwpt(vbasedev, hwpt->hwpt_id, &err);
+    if (ret) {
+        iommufd_backend_free_id(vbasedev->iommufd, hwpt->hwpt_id);
+        g_free(hwpt);
+        return ret;

+ }
+
+ QLIST_INSERT_HEAD(&container->hwpt_list, hwpt, next);
+ return 0;
+}
+
static int iommufd_cdev_attach_container(VFIODevice *vbasedev,
VFIOIOMMUFDContainer *container, Error **errp)
{
- return iommufd_cdev_attach_ioas_hwpt(vbasedev, container->ioas_id, errp);
+ uint32_t pt_id;
+
+ if (!iommufd_cdev_autodomains_get(vbasedev, container, &pt_id, errp)) {
+ return 0;
+ }
+
+ pt_id = container->ioas_id;
+ return iommufd_cdev_attach_ioas_hwpt(vbasedev, pt_id, errp);
}

#37 lore raw
In reply to Zhenzhong Duan
Quoted 13 lines · Zhenzhong Duan

Hi,

Thanks all for giving guides and comments on previous series, this is the remaining part of the iommufd support.

Besides suggested changes in v6, I'd like to highlight two changes for final review:
1. Instantiate can_be_deleted callback to fix race where iommufd object can be deleted before vfio device
2. After careful re-thinking, I'd like to follow Nicolin's suggestion in v5, remove is_ioas check which indeed looks heavy just for tracepoint. In fact we can get corresponding info by looking over trace context.

Quoted 7 lines

PATCH 1: Introduce iommufd object
PATCH 2-9: add IOMMUFD container and cdev support PATCH 10-17: fd passing for cdev and linking to IOMMUFD PATCH 18: make VFIOContainerBase parameter const PATCH 19-21: Compile out for IOMMUFD for arm, s390x and x86 PATCH 22-26: vfio device init code cleanup
PATCH 27: add iommufd doc

Applied to vfio-next.

Thanks,

C.