Skip to contentSkip to conversation

vSMMUv3/pSMMUv3 2 stage VFIO integration

RFC Superseded Eric Auger 4 participants 37 messages Sep 21, 2018 – Nov 26, 2018

v2 of 9 Superseded Latest is v9 →

lore
Share & tools
lore

Eric Auger

author
#0 lore raw

v2 cover vSMMUv3/pSMMUv3 2 stage VFIO integration

Up to now vSMMUv3 has not been integrated with VFIO. VFIO integration requires to program the physical IOMMU consistently with the guest mappings. However, as opposed to VTD, SMMUv3 has no "Caching Mode" which allows easy trapping of guest mappings. This means the vSMMUV3 cannot use the same VFIO integration as VTD.

However SMMUv3 has 2 translation stages. This was devised with virtualization use case in mind where stage 1 is "owned" by the guest whereas the host uses stage 2 for VM isolation.

This series sets up this nested translation stage. It only works if there is one physical SMMUv3 used along with QEMU vSMMUv3 (in other words, it does not work if there is a physical SMMUv2).

The series uses a new kernel user API [1], still under definition.

- We force the host to use stage 2 instead of stage 1, when we detect a vSMMUV3 is behind a VFIO device. For a VFIO device without any virtual IOMMU, we still use stage 1 as many existing SMMUs expect this behavior.
- We introduce new IOTLB "config" notifiers, requested to notify changes in the config of a given iommu memory region. So now we have notifiers for IOTLB changes and config changes.
- vSMMUv3 calls config notifiers when STE (Stream Table Entries) are updated by the guest.
- We implement a specific UNMAP notifier that conveys guest IOTLB invalidations to the host
- We implement a new MAP notifiers only used for MSI IOVAs so that the host can build a nested stage translation for MSI IOVAs
- As the legacy MAP notifier is not called anymore, we must make sure stage 2 mappings are set. This is achieved through another memory listener.
- Physical SMMUs faults are reported to the guest via en eventfd mechanism and reinjected into this latter.

Note: some iommu memory notifier rework related patches are close to those previously published by Peter and Liu. I will be pleased to add their Signed-off-by if they agree/wish.

Note: The 2 first patches were sent separately in:
[PATCH 0/2] ARM SMMUv3: Fix event queue handling and memory region names
as they are fixes of current SMMU emulation code.

Best Regards

Eric

This series can be found at:
https://github.com/eauger/qemu/tree/v3.0.0_2stage-rfc-v2

Testing:
- For testing use my kernel branch
https://github.com/eauger/linux/tree/v4.19-rc4-2stage-rfc-v2 [1]
- Tested on Qualcomm HW with 1/2 assigned e1000e NICs. Hotplug was also tested OK.
- Known limitation:
- currently sending an NH_ASID command instead of NH_VA upon guest NH_VA. This may cause important perf downgrade. Propagating NH_VA does not work at the moment.

References:
- [1] [RFC v2 00/20] SMMUv3 Nested Stage Setup
(https://lkml.org/lkml/2018/9/18/1087)
The User API still is unstable and under discussion.

History:
v1 -> v2:
- Fixed dual assignment (asid now correctly propagated on TLB invalidations)
- Integrated fault reporting

Next Steps:
- Mature the user API with people involved in SVA work (KVM forum may be a good opportunity to meet)
- Submit the IOMMU cfg notifier changes and some VFIO changes separately, to progress independently on the kernel dependency

Eric Auger (28):
hw/arm/smmu-common: Fix the name of the iommu memory regions hw/arm/smmuv3: fix eventq recording and IRQ triggerring
update-linux-headers: Import iommu.h
linux-headers: Partial header update
memory: add IOMMU_ATTR_VFIO_NESTED IOMMU memory region attribute hw/arm/smmuv3: Implement get_attr API to report IOMMU_ATTR_VFIO_NESTED hw/vfio/common: Refactor container initialization hw/vfio/common: Force nested if iommu requires it
memory: Introduce IOMMUIOLTBNotifier
memory: rename memory_region notify_iommu, notify_one
memory: Add IOMMUConfigNotifier
memory: Add arch_id in IOTLBEntry
hw/arm/smmuv3: Store s1ctrptr in translation config data hw/arm/smmuv3: Implement dummy replay
hw/arm/smmuv3: Notify on config changes
hw/arm/smmuv3: Fill the IOTLBEntry arch_id on NH_VA invalidation hw/vfio/common: Introduce vfio_alloc_guest_iommu helper hw/vfio/common: Introduce vfio_dma_(un)map_ram_section helpers hw/vfio/common: Register specific nested mode notifiers and
memory_listener
hw/vfio/common: Register MAP notifier for MSI binding target/arm/kvm: Notifies IOMMU on MSI stage 1 binding vfio/pci: Always set up MSI route before enabling vectors hw/arm/smmuv3: Remove warning about unsupported MAP notifiers
memory: Introduce IOMMU_NOTIFIER_INIT_CFG IOMMU Config Notifier
memory: Introduce IOMMU Memory Region inject_faults API hw/vfio/common: Handle fault_handler
hw/arm/smmuv3: Init fault handling
hw/arm/smmuv3: Implement fault injection

 exec.c                          |  12 +-
 hw/arm/smmu-common.c            |  12 +-
 hw/arm/smmuv3-internal.h        |  26 +-
 hw/arm/smmuv3.c                 | 189 +++++++--
 hw/i386/intel_iommu.c           |  16 +-
 hw/misc/tz-mpc.c                |   8 +-
 hw/ppc/spapr_iommu.c            |   2 +-
 hw/s390x/s390-pci-inst.c        |   4 +-
 hw/vfio/common.c                | 666 ++++++++++++++++++++++++--------
 hw/vfio/pci.c                   |   1 +
 hw/vfio/trace-events            |   4 +-
 hw/virtio/vhost.c               |  12 +-
 include/exec/memory.h           | 140 +++++--
 include/hw/arm/smmu-common.h    |   1 +
 include/hw/vfio/vfio-common.h   |   1 +
 linux-headers/linux/iommu.h     | 237 ++++++++++++
 linux-headers/linux/vfio.h      |  48 +++
 memory.c                        |  66 +++-
 scripts/update-linux-headers.sh |   2 +-
 target/arm/kvm.c                |  46 +--
 20 files changed, 1206 insertions(+), 287 deletions(-)
 create mode 100644 linux-headers/linux/iommu.h
Signature · 1 line
2.17.1
author
#1 lore raw

RFC v2 1/28 hw/arm/smmu-common: Fix the name of the iommu memory regions

At the point smmu_find_add_as() gets called, the bus number might not be computed. Let's change the name of IOMMU memory region and just use the devfn and an incrementing index.

The name only is used for debug.

---
 hw/arm/smmu-common.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
hw/arm/smmu-common.c +3 -3
index 55c75d65d2..3f55cfd193 100644
@@ -311,6 +311,7 @@ static AddressSpace *smmu_find_add_as(PCIBus *bus, void *opaque, int devfn)
     SMMUState *s = opaque;
     SMMUPciBus *sbus = g_hash_table_lookup(s->smmu_pcibus_by_busptr, bus);
     SMMUDevice *sdev;
+    static uint index;
 
     if (!sbus) {
         sbus = g_malloc0(sizeof(SMMUPciBus) +
@@ -321,9 +322,8 @@ static AddressSpace *smmu_find_add_as(PCIBus *bus, void *opaque, int devfn)
 
     sdev = sbus->pbdev[devfn];
     if (!sdev) {
-        char *name = g_strdup_printf("%s-%d-%d",
-                                     s->mrtypename,
-                                     pci_bus_num(bus), devfn);
+        char *name = g_strdup_printf("%s-%d-%d", s->mrtypename, devfn, index++);
+
         sdev = sbus->pbdev[devfn] = g_new0(SMMUDevice, 1);
 
         sdev->smmu = s;
Signature · 1 line
2.17.1
author
#2 lore raw

RFC v2 2/28 hw/arm/smmuv3: fix eventq recording and IRQ triggerring

In reply to Eric Auger

The event queue management is broken today. Event records are not properly written as EVT_SET_* macro was not updating the actual event record. Also the event queue interrupt is not correctly triggered.

Fixes bb981004eaf4 ("hw/arm/smmuv3: Event queue recording helper")
---
 hw/arm/smmuv3-internal.h | 26 +++++++++++++-------------
 hw/arm/smmuv3.c          |  2 +-
 2 files changed, 14 insertions(+), 14 deletions(-)
hw/arm/smmuv3-internal.h +13 -13
index bab25d640e..19540f8f41 100644
@@ -442,17 +442,17 @@ typedef struct SMMUEventInfo {
 
 #define EVT_Q_OVERFLOW        (1 << 31)
 
-#define EVT_SET_TYPE(x, v)              deposit32((x)->word[0], 0 , 8 , v)
-#define EVT_SET_SSV(x, v)               deposit32((x)->word[0], 11, 1 , v)
-#define EVT_SET_SSID(x, v)              deposit32((x)->word[0], 12, 20, v)
-#define EVT_SET_SID(x, v)               ((x)->word[1] = v)
-#define EVT_SET_STAG(x, v)              deposit32((x)->word[2], 0 , 16, v)
-#define EVT_SET_STALL(x, v)             deposit32((x)->word[2], 31, 1 , v)
-#define EVT_SET_PNU(x, v)               deposit32((x)->word[3], 1 , 1 , v)
-#define EVT_SET_IND(x, v)               deposit32((x)->word[3], 2 , 1 , v)
-#define EVT_SET_RNW(x, v)               deposit32((x)->word[3], 3 , 1 , v)
-#define EVT_SET_S2(x, v)                deposit32((x)->word[3], 7 , 1 , v)
-#define EVT_SET_CLASS(x, v)             deposit32((x)->word[3], 8 , 2 , v)
+#define EVT_SET_TYPE(x, v)  ((x)->word[0] = deposit32((x)->word[0], 0 , 8 , v))
+#define EVT_SET_SSV(x, v)   ((x)->word[0] = deposit32((x)->word[0], 11, 1 , v))
+#define EVT_SET_SSID(x, v)  ((x)->word[0] = deposit32((x)->word[0], 12, 20, v))
+#define EVT_SET_SID(x, v)   ((x)->word[1] = v)
+#define EVT_SET_STAG(x, v)  ((x)->word[2] = deposit32((x)->word[2], 0 , 16, v))
+#define EVT_SET_STALL(x, v) ((x)->word[2] = deposit32((x)->word[2], 31, 1 , v))
+#define EVT_SET_PNU(x, v)   ((x)->word[3] = deposit32((x)->word[3], 1 , 1 , v))
+#define EVT_SET_IND(x, v)   ((x)->word[3] = deposit32((x)->word[3], 2 , 1 , v))
+#define EVT_SET_RNW(x, v)   ((x)->word[3] = deposit32((x)->word[3], 3 , 1 , v))
+#define EVT_SET_S2(x, v)    ((x)->word[3] = deposit32((x)->word[3], 7 , 1 , v))
+#define EVT_SET_CLASS(x, v) ((x)->word[3] = deposit32((x)->word[3], 8 , 2 , v))
 #define EVT_SET_ADDR(x, addr)                             \
     do {                                                  \
             (x)->word[5] = (uint32_t)(addr >> 32);        \
@@ -460,8 +460,8 @@ typedef struct SMMUEventInfo {
     } while (0)
 #define EVT_SET_ADDR2(x, addr)                            \
     do {                                                  \
-            deposit32((x)->word[7], 3, 29, addr >> 16);   \
-            deposit32((x)->word[7], 0, 16, addr & 0xffff);\
+            (x)->word[7] = deposit32((x)->word[7], 3, 29, addr >> 16);   \
+            (x)->word[7] = deposit32((x)->word[7], 0, 16, addr & 0xffff);\
     } while (0)
 
 void smmuv3_record_event(SMMUv3State *s, SMMUEventInfo *event);
hw/arm/smmuv3.c +1 -1
index bb6a24e9b8..8c4e99fecc 100644
@@ -136,7 +136,7 @@ static MemTxResult smmuv3_write_eventq(SMMUv3State *s, Evt *evt)
         return r;
     }
 
-    if (smmuv3_q_empty(q)) {
+    if (!smmuv3_q_empty(q)) {
         smmuv3_trigger_irq(s, SMMU_IRQ_EVTQ, 0);
     }
     return MEMTX_OK;
Signature · 1 line
2.17.1
author
#3 lore raw

RFC v2 3/28 update-linux-headers: Import iommu.h

In reply to Eric Auger

Update the script to import the new iommu.h uapi header.

---
 scripts/update-linux-headers.sh | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
scripts/update-linux-headers.sh +1 -1
index 0a964fe240..3f11e49758 100755
@@ -125,7 +125,7 @@ done
 
 rm -rf "$output/linux-headers/linux"
 mkdir -p "$output/linux-headers/linux"
-for header in kvm.h vfio.h vfio_ccw.h vhost.h \
+for header in kvm.h vfio.h iommu.h vfio_ccw.h vhost.h \
               psci.h psp-sev.h userfaultfd.h; do
     cp "$tmpdir/include/linux/$header" "$output/linux-headers/linux"
 done
Signature · 1 line
2.17.1
author
#4 lore raw

RFC v2 4/28 linux-headers: Partial header update

In reply to Eric Auger

This imports both the iommu.h and vfio.h headers found on branch
https://github.com/eauger/linux/tree/v4.19-rc4-2stage-rfc-v2
([RFC v2 00/20] SMMUv3 Nested Stage Setup)

---

v1 -> v2:
- addition of the default reporting API
- renamings
- CD removal from iommu_pasid_smmuv3

---
 linux-headers/linux/iommu.h | 237 ++++++++++++++++++++++++++++++++++++
 linux-headers/linux/vfio.h  |  48 ++++++++
 2 files changed, 285 insertions(+)
 create mode 100644 linux-headers/linux/iommu.h
linux-headers/linux/iommu.h new file +237 -0
new file mode 100644
index 0000000000..9d55e7d053
@@ -0,0 +1,237 @@
+/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */
+/*
+ * IOMMU user API definitions
+ *
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation.
+ */
+
+#ifndef _IOMMU_H
+#define _IOMMU_H
+
+#include <linux/types.h>
+
+/**
+ * SMMUv3 Stream Table Entry stage 1 related information
+ * @s1contextptr: Context Descriptor Table GPA
+ * @abort: shall the STE lead to abort
+ * @s1fmt: STE s1fmt field as set by the guest
+ * @s1cdmax: STE s1cdmax as set by the guest
+ * @s1dss: STE s1dss as set by the guest
+ * All field names match the smmu 3.0/3.1 spec (ARM IHI 0070A)
+ */
+struct iommu_pasid_smmuv3 {
+	__u64 s1contextptr;
+	__u8 bypass;
+	__u8 abort;
+	__u8 s1fmt;
+	__u8 s1cdmax;
+	__u8 s1dss;
+};
+
+/**
+ * PASID table data used to bind guest PASID table to the host IOMMU
+ * Note PASID table corresponds to the Context Table on ARM SMMUv3.
+ *
+ * @version: API version to prepare for future extensions
+ * @format: format of the PASID table
+ *
+ */
+struct iommu_pasid_table_config {
+#define PASID_TABLE_CFG_VERSION_1 1
+	__u32 version;
+#define IOMMU_PASID_FORMAT_SMMUV3	(1 << 0)
+	__u32 format;
+	union {
+		struct iommu_pasid_smmuv3 smmuv3;
+	};
+};
+
+/**
+ * enum iommu_inv_granularity - Generic invalidation granularity
+ * @IOMMU_INV_GRANU_DOMAIN_ALL_PASID:	TLB entries or PASID caches of all
+ *					PASIDs associated with a domain ID
+ * @IOMMU_INV_GRANU_PASID_SEL:		TLB entries or PASID cache associated
+ *					with a PASID and a domain
+ * @IOMMU_INV_GRANU_PAGE_PASID:		TLB entries of selected page range
+ *					within a PASID
+ *
+ * When an invalidation request is passed down to IOMMU to flush translation
+ * caches, it may carry different granularity levels, which can be specific
+ * to certain types of translation caches.
+ * This enum is a collection of granularities for all types of translation
+ * caches. The idea is to make it easy for IOMMU model specific driver to
+ * convert from generic to model specific value. Each IOMMU driver
+ * can enforce check based on its own conversion table. The conversion is
+ * based on 2D look-up with inputs as follows:
+ * - translation cache types
+ * - granularity
+ *
+ *             type |   DTLB    |    TLB    |   PASID   |
+ *  granule         |           |           |   cache   |
+ * -----------------+-----------+-----------+-----------+
+ *  DN_ALL_PASID    |   Y       |   Y       |   Y       |
+ *  PASID_SEL       |   Y       |   Y       |   Y       |
+ *  PAGE_PASID      |   Y       |   Y       |   N/A     |
+ *
+ */
+enum iommu_inv_granularity {
+	IOMMU_INV_GRANU_DOMAIN_ALL_PASID,
+	IOMMU_INV_GRANU_PASID_SEL,
+	IOMMU_INV_GRANU_PAGE_PASID,
+	IOMMU_INV_NR_GRANU,
+};
+
+/**
+ * enum iommu_inv_type - Generic translation cache types for invalidation
+ *
+ * @IOMMU_INV_TYPE_DTLB:	device IOTLB
+ * @IOMMU_INV_TYPE_TLB:		IOMMU paging structure cache
+ * @IOMMU_INV_TYPE_PASID:	PASID cache
+ * Invalidation requests sent to IOMMU for a given device need to indicate
+ * which type of translation cache to be operated on. Combined with enum
+ * iommu_inv_granularity, model specific driver can do a simple lookup to
+ * convert from generic to model specific value.
+ */
+enum iommu_inv_type {
+	IOMMU_INV_TYPE_DTLB,
+	IOMMU_INV_TYPE_TLB,
+	IOMMU_INV_TYPE_PASID,
+	IOMMU_INV_NR_TYPE
+};
+
+/**
+ * Translation cache invalidation header that contains mandatory meta data.
+ * @version:	info format version, expecting future extesions
+ * @type:	type of translation cache to be invalidated
+ */
+struct iommu_cache_invalidate_hdr {
+	__u32 version;
+#define TLB_INV_HDR_VERSION_1 1
+	enum iommu_inv_type type;
+};
+
+/**
+ * Translation cache invalidation information, contains generic IOMMU
+ * data which can be parsed based on model ID by model specific drivers.
+ * Since the invalidation of second level page tables are included in the
+ * unmap operation, this info is only applicable to the first level
+ * translation caches, i.e. DMA request with PASID.
+ *
+ * @granularity:	requested invalidation granularity, type dependent
+ * @size:		2^size of 4K pages, 0 for 4k, 9 for 2MB, etc.
+ * @nr_pages:		number of pages to invalidate
+ * @pasid:		processor address space ID value per PCI spec.
+ * @arch_id:		architecture dependent id characterizing a context
+ *			and tagging the caches, ie. domain Identfier on VTD,
+ *			asid on ARM SMMU
+ * @addr:		page address to be invalidated
+ * @flags		IOMMU_INVALIDATE_ADDR_LEAF: leaf paging entries
+ *			IOMMU_INVALIDATE_GLOBAL_PAGE: global pages
+ *
+ */
+struct iommu_cache_invalidate_info {
+	struct iommu_cache_invalidate_hdr	hdr;
+	enum iommu_inv_granularity	granularity;
+	__u32		flags;
+#define IOMMU_INVALIDATE_ADDR_LEAF	(1 << 0)
+#define IOMMU_INVALIDATE_GLOBAL_PAGE	(1 << 1)
+	__u8		size;
+	__u64		nr_pages;
+	__u32		pasid;
+	__u64		arch_id;
+	__u64		addr;
+};
+
+struct iommu_guest_msi_binding {
+	__u64		iova;
+	__u64		gpa;
+	__u32		granule;
+};
+
+/*  Generic fault types, can be expanded IRQ remapping fault */
+enum iommu_fault_type {
+	IOMMU_FAULT_DMA_UNRECOV = 1,	/* unrecoverable fault */
+	IOMMU_FAULT_PAGE_REQ,		/* page request fault */
+};
+
+enum iommu_fault_reason {
+	IOMMU_FAULT_REASON_UNKNOWN = 0,
+
+	/* IOMMU internal error, no specific reason to report out */
+	IOMMU_FAULT_REASON_INTERNAL,
+
+	/* Could not access the PASID table (fetch caused external abort) */
+	IOMMU_FAULT_REASON_PASID_FETCH,
+
+	/* could not access the device context (fetch caused external abort) */
+	IOMMU_FAULT_REASON_DEVICE_CONTEXT_FETCH,
+
+	/* pasid entry is invalid or has configuration errors */
+	IOMMU_FAULT_REASON_BAD_PASID_ENTRY,
+
+	/* device context entry is invalid or has configuration errors */
+	IOMMU_FAULT_REASON_BAD_DEVICE_CONTEXT_ENTRY,
+	/*
+	 * PASID is out of range (e.g. exceeds the maximum PASID
+	 * supported by the IOMMU) or disabled.
+	 */
+	IOMMU_FAULT_REASON_PASID_INVALID,
+
+	/* source id is out of range */
+	IOMMU_FAULT_REASON_SOURCEID_INVALID,
+
+	/*
+	 * An external abort occurred fetching (or updating) a translation
+	 * table descriptor
+	 */
+	IOMMU_FAULT_REASON_WALK_EABT,
+
+	/*
+	 * Could not access the page table entry (Bad address),
+	 * actual translation fault
+	 */
+	IOMMU_FAULT_REASON_PTE_FETCH,
+
+	/* Protection flag check failed */
+	IOMMU_FAULT_REASON_PERMISSION,
+
+	/* access flag check failed */
+	IOMMU_FAULT_REASON_ACCESS,
+
+	/* Output address of a translation stage caused Address Size fault */
+	IOMMU_FAULT_REASON_OOR_ADDRESS
+};
+
+/**
+ * struct iommu_fault - Generic fault data
+ *
+ * @type contains fault type
+ * @reason fault reasons if relevant outside IOMMU driver.
+ * IOMMU driver internal faults are not reported.
+ * @addr: tells the offending page address
+ * @fetch_addr: tells the address that caused an abort, if any
+ * @pasid: contains process address space ID, used in shared virtual memory
+ * @page_req_group_id: page request group index
+ * @last_req: last request in a page request group
+ * @pasid_valid: indicates if the PRQ has a valid PASID
+ * @prot: page access protection flag:
+ *	IOMMU_FAULT_READ, IOMMU_FAULT_WRITE
+ */
+
+struct iommu_fault {
+	__u32	type;   /* enum iommu_fault_type */
+	__u32	reason; /* enum iommu_fault_reason */
+	__u64	addr;
+	__u64	fetch_addr;
+	__u32	pasid;
+	__u32	page_req_group_id;
+	__u32	last_req;
+	__u32	pasid_valid;
+	__u32	prot;
+	__u32	access;
+};
+#endif /* _IOMMU_H */
+
linux-headers/linux/vfio.h +48 -0

60 lines not on this page · raw message

Signature · 1 line
2.17.1
author
#5 lore raw

RFC v2 5/28 memory: add IOMMU_ATTR_VFIO_NESTED IOMMU memory region attribute

In reply to Eric Auger

We introduce a new IOMMU Memory Region attribute, IOMMU_ATTR_VFIO_NESTED which tells whether the virtual IOMMU requires physical nested stages for VFIO integration. Intel virtual IOMMU supports Caching Mode and does not require 2 stages at physical level. However virtual ARM SMMU does not implement such caching mode and requires to use physical stage 1 for VFIO integration.

---
 include/exec/memory.h | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
include/exec/memory.h +2 -1
index eb4f2fb249..b6e59c139c 100644
@@ -209,7 +209,8 @@ struct MemoryRegionOps {
 };
 
 enum IOMMUMemoryRegionAttr {
-    IOMMU_ATTR_SPAPR_TCE_FD
+    IOMMU_ATTR_SPAPR_TCE_FD,
+    IOMMU_ATTR_VFIO_NESTED,
 };
 
 /**
Signature · 1 line
2.17.1
author
#6 lore raw

RFC v2 6/28 hw/arm/smmuv3: Implement get_attr API to report IOMMU_ATTR_VFIO_NESTED

In reply to Eric Auger

Virtual SMMUv3 requires physical nested stages for VFIO integration. Let's advertise this.

---
 hw/arm/smmuv3.c | 12 ++++++++++++
 1 file changed, 12 insertions(+)
hw/arm/smmuv3.c +12 -0
index 8c4e99fecc..d6895071a5 100644
@@ -1504,6 +1504,17 @@ static void smmuv3_notify_flag_changed(IOMMUMemoryRegion *iommu,
     }
 }
 
+static int smmuv3_get_attr(IOMMUMemoryRegion *iommu,
+                           enum IOMMUMemoryRegionAttr attr,
+                           void *data)
+{
+    if (attr == IOMMU_ATTR_VFIO_NESTED) {
+        *(bool *) data = true;
+        return 0;
+    }
+    return -EINVAL;
+}
+
 static void smmuv3_iommu_memory_region_class_init(ObjectClass *klass,
                                                   void *data)
 {
@@ -1511,6 +1522,7 @@ static void smmuv3_iommu_memory_region_class_init(ObjectClass *klass,
 
     imrc->translate = smmuv3_translate;
     imrc->notify_flag_changed = smmuv3_notify_flag_changed;
+    imrc->get_attr = smmuv3_get_attr;
 }
 
 static const TypeInfo smmuv3_type_info = {
Signature · 1 line
2.17.1
author
#7 lore raw

RFC v2 7/28 hw/vfio/common: Refactor container initialization

In reply to Eric Auger

To prepare for testing yet another extension, let's refactor the code. We introduce vfio_iommu_get_type() helper which selects the richest API (v2 first). Then vfio_init_container() does the SET_CONTAINER and SET_IOMMU ioctl calls. So we end up with a switch/case on the iommu_type which should be a little bit more readable when introducing the NESTING extension check. Also ioctl's get called once per iommu_type.

---
 hw/vfio/common.c | 102 ++++++++++++++++++++++++++++++-----------------
 1 file changed, 65 insertions(+), 37 deletions(-)
hw/vfio/common.c +65 -37
index 7c185e5a2e..53b8f773cc 100644
@@ -1036,12 +1036,58 @@ static void vfio_put_address_space(VFIOAddressSpace *space)
     }
 }
 
+/*
+ * vfio_iommu_get_type - selects the richest iommu_type (v2 first)
+ * nested only is selected if requested by @force_nested
+ */
+static int vfio_iommu_get_type(VFIOContainer *container,
+                               Error **errp)
+{
+    int fd = container->fd;
+
+    if (ioctl(fd, VFIO_CHECK_EXTENSION, VFIO_TYPE1v2_IOMMU)) {
+        return VFIO_TYPE1v2_IOMMU;
+    } else if (ioctl(fd, VFIO_CHECK_EXTENSION, VFIO_TYPE1_IOMMU)) {
+        return VFIO_TYPE1_IOMMU;
+    } else if (ioctl(fd, VFIO_CHECK_EXTENSION, VFIO_SPAPR_TCE_v2_IOMMU)) {
+        return VFIO_SPAPR_TCE_v2_IOMMU;
+    } else if (ioctl(fd, VFIO_CHECK_EXTENSION, VFIO_SPAPR_TCE_IOMMU)) {
+        return VFIO_SPAPR_TCE_IOMMU;
+    } else {
+        error_setg(errp, "No available IOMMU models");
+        return -EINVAL;
+    }
+}
+
+static int vfio_init_container(VFIOContainer *container, int group_fd,
+                               int iommu_type, Error **errp)
+{
+    int ret;
+
+    ret = ioctl(group_fd, VFIO_GROUP_SET_CONTAINER, &container->fd);
+    if (ret) {
+        error_setg_errno(errp, errno, "failed to set group container");
+        return -errno;
+    }
+
+    ret = ioctl(container->fd, VFIO_SET_IOMMU, iommu_type);
+    if (ret) {
+        error_setg_errno(errp, errno, "failed to set iommu for container");
+        return -errno;
+    }
+    container->iommu_type = iommu_type;
+    return 0;
+}
+
 static int vfio_connect_container(VFIOGroup *group, AddressSpace *as,
                                   Error **errp)
 {
     VFIOContainer *container;
     int ret, fd;
     VFIOAddressSpace *space;
+    int iommu_type;
+    bool v2 = false;
+
 
     space = vfio_get_address_space(as);
 
@@ -1101,23 +1147,20 @@ static int vfio_connect_container(VFIOGroup *group, AddressSpace *as,
     container->fd = fd;
     QLIST_INIT(&container->giommu_list);
     QLIST_INIT(&container->hostwin_list);
-    if (ioctl(fd, VFIO_CHECK_EXTENSION, VFIO_TYPE1_IOMMU) ||
-        ioctl(fd, VFIO_CHECK_EXTENSION, VFIO_TYPE1v2_IOMMU)) {
-        bool v2 = !!ioctl(fd, VFIO_CHECK_EXTENSION, VFIO_TYPE1v2_IOMMU);
+
+    iommu_type = vfio_iommu_get_type(container, errp);
+    if (iommu_type < 0) {
+            goto free_container_exit;
+    }
+
+    switch (iommu_type) {
+    case VFIO_TYPE1v2_IOMMU:
+    case VFIO_TYPE1_IOMMU:
+    {
         struct vfio_iommu_type1_info info;
 
-        ret = ioctl(group->fd, VFIO_GROUP_SET_CONTAINER, &fd);
+        ret = vfio_init_container(container, group->fd, iommu_type, errp);
         if (ret) {
-            error_setg_errno(errp, errno, "failed to set group container");
-            ret = -errno;
-            goto free_container_exit;
-        }
-
-        container->iommu_type = v2 ? VFIO_TYPE1v2_IOMMU : VFIO_TYPE1_IOMMU;
-        ret = ioctl(fd, VFIO_SET_IOMMU, container->iommu_type);
-        if (ret) {
-            error_setg_errno(errp, errno, "failed to set iommu for container");
-            ret = -errno;
             goto free_container_exit;
         }
 
@@ -1137,28 +1180,16 @@ static int vfio_connect_container(VFIOGroup *group, AddressSpace *as,
         }
         vfio_host_win_add(container, 0, (hwaddr)-1, info.iova_pgsizes);
         container->pgsizes = info.iova_pgsizes;
-    } else if (ioctl(fd, VFIO_CHECK_EXTENSION, VFIO_SPAPR_TCE_IOMMU) ||
-               ioctl(fd, VFIO_CHECK_EXTENSION, VFIO_SPAPR_TCE_v2_IOMMU)) {
+        break;
+    }
+    case VFIO_SPAPR_TCE_v2_IOMMU:
+        v2 = true;
+    case VFIO_SPAPR_TCE_IOMMU:
+    {
         struct vfio_iommu_spapr_tce_info info;
-        bool v2 = !!ioctl(fd, VFIO_CHECK_EXTENSION, VFIO_SPAPR_TCE_v2_IOMMU);
 
-        ret = ioctl(group->fd, VFIO_GROUP_SET_CONTAINER, &fd);
+        ret = vfio_init_container(container, group->fd, iommu_type, errp);
         if (ret) {
-            error_setg_errno(errp, errno, "failed to set group container");
-            ret = -errno;
-            goto free_container_exit;
-        }
-        container->iommu_type =
-            v2 ? VFIO_SPAPR_TCE_v2_IOMMU : VFIO_SPAPR_TCE_IOMMU;
-        ret = ioctl(fd, VFIO_SET_IOMMU, container->iommu_type);
-        if (ret) {
-            container->iommu_type = VFIO_SPAPR_TCE_IOMMU;
-            v2 = false;
-            ret = ioctl(fd, VFIO_SET_IOMMU, container->iommu_type);
-        }
-        if (ret) {
-            error_setg_errno(errp, errno, "failed to set iommu for container");
-            ret = -errno;
             goto free_container_exit;
         }
 
@@ -1222,10 +1253,7 @@ static int vfio_connect_container(VFIOGroup *group, AddressSpace *as,
                               info.dma32_window_size - 1,
                               0x1000);
         }
-    } else {
-        error_setg(errp, "No available IOMMU models");
-        ret = -EINVAL;
-        goto free_container_exit;
+    }
     }
 
     vfio_kvm_device_add_group(group);
Signature · 1 line
2.17.1
Reviewed-by on v2 7/28
#8 lore raw

Re: [Qemu-arm] [Qemu-devel] [RFC v2 07/28] hw/vfio/common: Refactor container initialization

Quoted 19 lines · On Fri, 21 Sep 2018 10:17:58 +0200 Eric Auger <[email protected]> wrote:

To prepare for testing yet another extension, let's refactor the code. We introduce vfio_iommu_get_type() helper which selects the richest API (v2 first). Then vfio_init_container() does the SET_CONTAINER and SET_IOMMU ioctl calls. So we end up with a switch/case on the iommu_type which should be a little bit more readable when introducing the NESTING extension check. Also ioctl's get called once per iommu_type.

---
 hw/vfio/common.c | 102 ++++++++++++++++++++++++++++++-----------------
 1 file changed, 65 insertions(+), 37 deletions(-)
hw/vfio/common.c +0 -0
index 7c185e5a2e..53b8f773cc 100644

hw/vfio/common.c static void vfio_put_address_space(VFIOAddressSpace *space) · line 1041

Quoted 6 lines
hw/vfio/common.c +3 -0
@@ -1036,12 +1036,58 @@ static void vfio_put_address_space(VFIOAddressSpace *space)
     }
 }
 
+/*
+ * vfio_iommu_get_type - selects the richest iommu_type (v2 first)
+ * nested only is selected if requested by @force_nested

It seems the second line belongs to patch 8.

Appart from that, this definitely makes the code more readable.

Quoted 135 lines
hw/vfio/common.c +62 -37
+ */
+static int vfio_iommu_get_type(VFIOContainer *container,
+                               Error **errp)
+{
+    int fd = container->fd;
+
+    if (ioctl(fd, VFIO_CHECK_EXTENSION, VFIO_TYPE1v2_IOMMU)) {
+        return VFIO_TYPE1v2_IOMMU;
+    } else if (ioctl(fd, VFIO_CHECK_EXTENSION, VFIO_TYPE1_IOMMU)) {
+        return VFIO_TYPE1_IOMMU;
+    } else if (ioctl(fd, VFIO_CHECK_EXTENSION, VFIO_SPAPR_TCE_v2_IOMMU)) {
+        return VFIO_SPAPR_TCE_v2_IOMMU;
+    } else if (ioctl(fd, VFIO_CHECK_EXTENSION, VFIO_SPAPR_TCE_IOMMU)) {
+        return VFIO_SPAPR_TCE_IOMMU;
+    } else {
+        error_setg(errp, "No available IOMMU models");
+        return -EINVAL;
+    }
+}
+
+static int vfio_init_container(VFIOContainer *container, int group_fd,
+                               int iommu_type, Error **errp)
+{
+    int ret;
+
+    ret = ioctl(group_fd, VFIO_GROUP_SET_CONTAINER, &container->fd);
+    if (ret) {
+        error_setg_errno(errp, errno, "failed to set group container");
+        return -errno;
+    }
+
+    ret = ioctl(container->fd, VFIO_SET_IOMMU, iommu_type);
+    if (ret) {
+        error_setg_errno(errp, errno, "failed to set iommu for container");
+        return -errno;
+    }
+    container->iommu_type = iommu_type;
+    return 0;
+}
+
 static int vfio_connect_container(VFIOGroup *group, AddressSpace *as,
                                   Error **errp)
 {
     VFIOContainer *container;
     int ret, fd;
     VFIOAddressSpace *space;
+    int iommu_type;
+    bool v2 = false;
+
 
     space = vfio_get_address_space(as);
 
@@ -1101,23 +1147,20 @@ static int vfio_connect_container(VFIOGroup *group, AddressSpace *as,
     container->fd = fd;
     QLIST_INIT(&container->giommu_list);
     QLIST_INIT(&container->hostwin_list);
-    if (ioctl(fd, VFIO_CHECK_EXTENSION, VFIO_TYPE1_IOMMU) ||
-        ioctl(fd, VFIO_CHECK_EXTENSION, VFIO_TYPE1v2_IOMMU)) {
-        bool v2 = !!ioctl(fd, VFIO_CHECK_EXTENSION, VFIO_TYPE1v2_IOMMU);
+
+    iommu_type = vfio_iommu_get_type(container, errp);
+    if (iommu_type < 0) {
+            goto free_container_exit;
+    }
+
+    switch (iommu_type) {
+    case VFIO_TYPE1v2_IOMMU:
+    case VFIO_TYPE1_IOMMU:
+    {
         struct vfio_iommu_type1_info info;
 
-        ret = ioctl(group->fd, VFIO_GROUP_SET_CONTAINER, &fd);
+        ret = vfio_init_container(container, group->fd, iommu_type, errp);
         if (ret) {
-            error_setg_errno(errp, errno, "failed to set group container");
-            ret = -errno;
-            goto free_container_exit;
-        }
-
-        container->iommu_type = v2 ? VFIO_TYPE1v2_IOMMU : VFIO_TYPE1_IOMMU;
-        ret = ioctl(fd, VFIO_SET_IOMMU, container->iommu_type);
-        if (ret) {
-            error_setg_errno(errp, errno, "failed to set iommu for container");
-            ret = -errno;
             goto free_container_exit;
         }
 
@@ -1137,28 +1180,16 @@ static int vfio_connect_container(VFIOGroup *group, AddressSpace *as,
         }
         vfio_host_win_add(container, 0, (hwaddr)-1, info.iova_pgsizes);
         container->pgsizes = info.iova_pgsizes;
-    } else if (ioctl(fd, VFIO_CHECK_EXTENSION, VFIO_SPAPR_TCE_IOMMU) ||
-               ioctl(fd, VFIO_CHECK_EXTENSION, VFIO_SPAPR_TCE_v2_IOMMU)) {
+        break;
+    }
+    case VFIO_SPAPR_TCE_v2_IOMMU:
+        v2 = true;
+    case VFIO_SPAPR_TCE_IOMMU:
+    {
         struct vfio_iommu_spapr_tce_info info;
-        bool v2 = !!ioctl(fd, VFIO_CHECK_EXTENSION, VFIO_SPAPR_TCE_v2_IOMMU);
 
-        ret = ioctl(group->fd, VFIO_GROUP_SET_CONTAINER, &fd);
+        ret = vfio_init_container(container, group->fd, iommu_type, errp);
         if (ret) {
-            error_setg_errno(errp, errno, "failed to set group container");
-            ret = -errno;
-            goto free_container_exit;
-        }
-        container->iommu_type =
-            v2 ? VFIO_SPAPR_TCE_v2_IOMMU : VFIO_SPAPR_TCE_IOMMU;
-        ret = ioctl(fd, VFIO_SET_IOMMU, container->iommu_type);
-        if (ret) {
-            container->iommu_type = VFIO_SPAPR_TCE_IOMMU;
-            v2 = false;
-            ret = ioctl(fd, VFIO_SET_IOMMU, container->iommu_type);
-        }
-        if (ret) {
-            error_setg_errno(errp, errno, "failed to set iommu for container");
-            ret = -errno;
             goto free_container_exit;
         }
 
@@ -1222,10 +1253,7 @@ static int vfio_connect_container(VFIOGroup *group, AddressSpace *as,
                               info.dma32_window_size - 1,
                               0x1000);
         }
-    } else {
-        error_setg(errp, "No available IOMMU models");
-        ret = -EINVAL;
-        goto free_container_exit;
+    }
     }
 
     vfio_kvm_device_add_group(group);
author
#9 lore raw

Re: [Qemu-arm] [Qemu-devel] [RFC v2 07/28] hw/vfio/common: Refactor container initialization

Hi Greg,

Quoted 25 lines · Greg Kurz
Quoted 22 lines · On Fri, 21 Sep 2018 10:17:58 +0200 Eric Auger <[email protected]> wrote:

To prepare for testing yet another extension, let's refactor the code. We introduce vfio_iommu_get_type() helper which selects the richest API (v2 first). Then vfio_init_container() does the SET_CONTAINER and SET_IOMMU ioctl calls. So we end up with a switch/case on the iommu_type which should be a little bit more readable when introducing the NESTING extension check. Also ioctl's get called once per iommu_type.

---
 hw/vfio/common.c | 102 ++++++++++++++++++++++++++++++-----------------
 1 file changed, 65 insertions(+), 37 deletions(-)
hw/vfio/common.c +0 -0
index 7c185e5a2e..53b8f773cc 100644
@@ -1036,12 +1036,58 @@ static void vfio_put_address_space(VFIOAddressSpace *space)
     }
 }
 
Quoted 5 lines

hw/vfio/common.c static void vfio_put_address_space(VFIOAddressSpace *space) · line 1041

Quoted 3 lines
hw/vfio/common.c +3 -0
+/*
+ * vfio_iommu_get_type - selects the richest iommu_type (v2 first)
+ * nested only is selected if requested by @force_nested

It seems the second line belongs to patch 8.

Yes it does. thanks for spotting that.

Quoted 4 lines

Appart from that, this definitely makes the code more readable.

I will send this patch separately.

Thanks

Eric

Quoted 138 lines
Quoted 136 lines
hw/vfio/common.c +62 -37
+ */
+static int vfio_iommu_get_type(VFIOContainer *container,
+                               Error **errp)
+{
+    int fd = container->fd;
+
+    if (ioctl(fd, VFIO_CHECK_EXTENSION, VFIO_TYPE1v2_IOMMU)) {
+        return VFIO_TYPE1v2_IOMMU;
+    } else if (ioctl(fd, VFIO_CHECK_EXTENSION, VFIO_TYPE1_IOMMU)) {
+        return VFIO_TYPE1_IOMMU;
+    } else if (ioctl(fd, VFIO_CHECK_EXTENSION, VFIO_SPAPR_TCE_v2_IOMMU)) {
+        return VFIO_SPAPR_TCE_v2_IOMMU;
+    } else if (ioctl(fd, VFIO_CHECK_EXTENSION, VFIO_SPAPR_TCE_IOMMU)) {
+        return VFIO_SPAPR_TCE_IOMMU;
+    } else {
+        error_setg(errp, "No available IOMMU models");
+        return -EINVAL;
+    }
+}
+
+static int vfio_init_container(VFIOContainer *container, int group_fd,
+                               int iommu_type, Error **errp)
+{
+    int ret;
+
+    ret = ioctl(group_fd, VFIO_GROUP_SET_CONTAINER, &container->fd);
+    if (ret) {
+        error_setg_errno(errp, errno, "failed to set group container");
+        return -errno;
+    }
+
+    ret = ioctl(container->fd, VFIO_SET_IOMMU, iommu_type);
+    if (ret) {
+        error_setg_errno(errp, errno, "failed to set iommu for container");
+        return -errno;
+    }
+    container->iommu_type = iommu_type;
+    return 0;
+}
+
 static int vfio_connect_container(VFIOGroup *group, AddressSpace *as,
                                   Error **errp)
 {
     VFIOContainer *container;
     int ret, fd;
     VFIOAddressSpace *space;
+    int iommu_type;
+    bool v2 = false;
+
 
     space = vfio_get_address_space(as);
 
@@ -1101,23 +1147,20 @@ static int vfio_connect_container(VFIOGroup *group, AddressSpace *as,
     container->fd = fd;
     QLIST_INIT(&container->giommu_list);
     QLIST_INIT(&container->hostwin_list);
-    if (ioctl(fd, VFIO_CHECK_EXTENSION, VFIO_TYPE1_IOMMU) ||
-        ioctl(fd, VFIO_CHECK_EXTENSION, VFIO_TYPE1v2_IOMMU)) {
-        bool v2 = !!ioctl(fd, VFIO_CHECK_EXTENSION, VFIO_TYPE1v2_IOMMU);
+
+    iommu_type = vfio_iommu_get_type(container, errp);
+    if (iommu_type < 0) {
+            goto free_container_exit;
+    }
+
+    switch (iommu_type) {
+    case VFIO_TYPE1v2_IOMMU:
+    case VFIO_TYPE1_IOMMU:
+    {
         struct vfio_iommu_type1_info info;
 
-        ret = ioctl(group->fd, VFIO_GROUP_SET_CONTAINER, &fd);
+        ret = vfio_init_container(container, group->fd, iommu_type, errp);
         if (ret) {
-            error_setg_errno(errp, errno, "failed to set group container");
-            ret = -errno;
-            goto free_container_exit;
-        }
-
-        container->iommu_type = v2 ? VFIO_TYPE1v2_IOMMU : VFIO_TYPE1_IOMMU;
-        ret = ioctl(fd, VFIO_SET_IOMMU, container->iommu_type);
-        if (ret) {
-            error_setg_errno(errp, errno, "failed to set iommu for container");
-            ret = -errno;
             goto free_container_exit;
         }
 
@@ -1137,28 +1180,16 @@ static int vfio_connect_container(VFIOGroup *group, AddressSpace *as,
         }
         vfio_host_win_add(container, 0, (hwaddr)-1, info.iova_pgsizes);
         container->pgsizes = info.iova_pgsizes;
-    } else if (ioctl(fd, VFIO_CHECK_EXTENSION, VFIO_SPAPR_TCE_IOMMU) ||
-               ioctl(fd, VFIO_CHECK_EXTENSION, VFIO_SPAPR_TCE_v2_IOMMU)) {
+        break;
+    }
+    case VFIO_SPAPR_TCE_v2_IOMMU:
+        v2 = true;
+    case VFIO_SPAPR_TCE_IOMMU:
+    {
         struct vfio_iommu_spapr_tce_info info;
-        bool v2 = !!ioctl(fd, VFIO_CHECK_EXTENSION, VFIO_SPAPR_TCE_v2_IOMMU);
 
-        ret = ioctl(group->fd, VFIO_GROUP_SET_CONTAINER, &fd);
+        ret = vfio_init_container(container, group->fd, iommu_type, errp);
         if (ret) {
-            error_setg_errno(errp, errno, "failed to set group container");
-            ret = -errno;
-            goto free_container_exit;
-        }
-        container->iommu_type =
-            v2 ? VFIO_SPAPR_TCE_v2_IOMMU : VFIO_SPAPR_TCE_IOMMU;
-        ret = ioctl(fd, VFIO_SET_IOMMU, container->iommu_type);
-        if (ret) {
-            container->iommu_type = VFIO_SPAPR_TCE_IOMMU;
-            v2 = false;
-            ret = ioctl(fd, VFIO_SET_IOMMU, container->iommu_type);
-        }
-        if (ret) {
-            error_setg_errno(errp, errno, "failed to set iommu for container");
-            ret = -errno;
             goto free_container_exit;
         }
 
@@ -1222,10 +1253,7 @@ static int vfio_connect_container(VFIOGroup *group, AddressSpace *as,
                               info.dma32_window_size - 1,
                               0x1000);
         }
-    } else {
-        error_setg(errp, "No available IOMMU models");
-        ret = -EINVAL;
-        goto free_container_exit;
+    }
     }
 
     vfio_kvm_device_add_group(group);
author
#10 lore raw

RFC v2 8/28 hw/vfio/common: Force nested if iommu requires it

In reply to Eric Auger

In case we detect the address space is translated by a virtual IOMMU which requires nested stages, let's set up the container with the VFIO_TYPE1_NESTING_IOMMU iommu_type.

---
 hw/vfio/common.c | 23 ++++++++++++++++++++---
 1 file changed, 20 insertions(+), 3 deletions(-)
hw/vfio/common.c +20 -3
index 53b8f773cc..1416892f1c 100644
@@ -1041,11 +1041,15 @@ static void vfio_put_address_space(VFIOAddressSpace *space)
  * nested only is selected if requested by @force_nested
  */
 static int vfio_iommu_get_type(VFIOContainer *container,
-                               Error **errp)
+                               bool force_nested, Error **errp)
 {
     int fd = container->fd;
 
-    if (ioctl(fd, VFIO_CHECK_EXTENSION, VFIO_TYPE1v2_IOMMU)) {
+    if (force_nested &&
+        ioctl(fd, VFIO_CHECK_EXTENSION, VFIO_TYPE1_NESTING_IOMMU)) {
+        /* NESTED implies v2 */
+        return VFIO_TYPE1_NESTING_IOMMU;
+    } else if (ioctl(fd, VFIO_CHECK_EXTENSION, VFIO_TYPE1v2_IOMMU)) {
         return VFIO_TYPE1v2_IOMMU;
     } else if (ioctl(fd, VFIO_CHECK_EXTENSION, VFIO_TYPE1_IOMMU)) {
         return VFIO_TYPE1_IOMMU;
@@ -1085,9 +1089,16 @@ static int vfio_connect_container(VFIOGroup *group, AddressSpace *as,
     VFIOContainer *container;
     int ret, fd;
     VFIOAddressSpace *space;
+    IOMMUMemoryRegion *iommu_mr;
     int iommu_type;
+    bool force_nested = false;
     bool v2 = false;
 
+    if (as != &address_space_memory && memory_region_is_iommu(as->root)) {
+        iommu_mr = IOMMU_MEMORY_REGION(as->root);
+        memory_region_iommu_get_attr(iommu_mr, IOMMU_ATTR_VFIO_NESTED,
+                                     (void *)&force_nested);
+    }
 
     space = vfio_get_address_space(as);
 
@@ -1148,12 +1159,18 @@ static int vfio_connect_container(VFIOGroup *group, AddressSpace *as,
     QLIST_INIT(&container->giommu_list);
     QLIST_INIT(&container->hostwin_list);
 
-    iommu_type = vfio_iommu_get_type(container, errp);
+    iommu_type = vfio_iommu_get_type(container, force_nested, errp);
     if (iommu_type < 0) {
             goto free_container_exit;
     }
 
+    if (force_nested && iommu_type != VFIO_TYPE1_NESTING_IOMMU) {
+            error_setg(errp, "nested mode requested by the virtual IOMMU "
+                       "but not supported by the vfio iommu");
+    }
+
     switch (iommu_type) {
+    case VFIO_TYPE1_NESTING_IOMMU:
     case VFIO_TYPE1v2_IOMMU:
     case VFIO_TYPE1_IOMMU:
     {
Signature · 1 line
2.17.1
author
#11 lore raw

RFC v2 9/28 memory: Introduce IOMMUIOLTBNotifier

In reply to Eric Auger

Current IOMMUNotifiers dedicate to IOTLB related notifications. We want to introduce notifiers for virtual IOMMU config changes. Let's create a new IOMMUIOLTBNotifier datatype. This paves the way to the introduction of an IOMMUConfigNotifier. IOMMUNotifier now has an iotlb_notifier field. We change all calling sites.

We also rename IOMMU_NOTIFIER_ALL into IOMMU_NOTIFIER_IOTLB_ALL

---
 exec.c                | 12 ++++++------
 hw/arm/smmu-common.c  |  4 ++--
 hw/i386/intel_iommu.c |  6 +++---
 hw/vfio/common.c      | 12 ++++++------
 hw/virtio/vhost.c     | 12 ++++++------
 include/exec/memory.h | 25 +++++++++++++++----------
 memory.c              | 10 +++++-----
 7 files changed, 43 insertions(+), 38 deletions(-)
exec.c +6 -6
index 6826c8337d..1411660289 100644
@@ -683,12 +683,12 @@ static void tcg_register_iommu_notifier(CPUState *cpu,
          * just register interest in the whole thing, on the assumption
          * that iommu reconfiguration will be rare.
          */
-        iommu_notifier_init(&notifier->n,
-                            tcg_iommu_unmap_notify,
-                            IOMMU_NOTIFIER_UNMAP,
-                            0,
-                            HWADDR_MAX,
-                            iommu_idx);
+        iommu_iotlb_notifier_init(&notifier->n,
+                                  tcg_iommu_unmap_notify,
+                                  IOMMU_NOTIFIER_UNMAP,
+                                  0,
+                                  HWADDR_MAX,
+                                  iommu_idx);
         memory_region_register_iommu_notifier(notifier->mr, &notifier->n);
     }
 
hw/arm/smmu-common.c +2 -2
index 3f55cfd193..ad6ef2135b 100644
@@ -391,9 +391,9 @@ static void smmu_unmap_notifier_range(IOMMUNotifier *n)
     IOMMUTLBEntry entry;
 
     entry.target_as = &address_space_memory;
-    entry.iova = n->start;
+    entry.iova = n->iotlb_notifier.start;
     entry.perm = IOMMU_NONE;
-    entry.addr_mask = n->end - n->start;
+    entry.addr_mask = n->iotlb_notifier.end - n->iotlb_notifier.start;
 
     memory_region_notify_one(n, &entry);
 }
hw/i386/intel_iommu.c +3 -3
index 3dfada19a6..0dbd9512f2 100644
@@ -2984,8 +2984,8 @@ static void vtd_address_space_unmap(VTDAddressSpace *as, IOMMUNotifier *n)
 {
     IOMMUTLBEntry entry;
     hwaddr size;
-    hwaddr start = n->start;
-    hwaddr end = n->end;
+    hwaddr start = n->iotlb_notifier.start;
+    hwaddr end = n->iotlb_notifier.end;
     IntelIOMMUState *s = as->iommu_state;
     DMAMap map;
 
@@ -3021,7 +3021,7 @@ static void vtd_address_space_unmap(VTDAddressSpace *as, IOMMUNotifier *n)
 
     entry.target_as = &address_space_memory;
     /* Adjust iova for the size */
-    entry.iova = n->start & ~(size - 1);
+    entry.iova = n->iotlb_notifier.start & ~(size - 1);
     /* This field is meaningless for unmap */
     entry.translated_addr = 0;
     entry.perm = IOMMU_NONE;
hw/vfio/common.c +6 -6
index 1416892f1c..19dfc279d6 100644
@@ -527,11 +527,11 @@ static void vfio_listener_region_add(MemoryListener *listener,
         llend = int128_sub(llend, int128_one());
         iommu_idx = memory_region_iommu_attrs_to_index(iommu_mr,
                                                        MEMTXATTRS_UNSPECIFIED);
-        iommu_notifier_init(&giommu->n, vfio_iommu_map_notify,
-                            IOMMU_NOTIFIER_ALL,
-                            section->offset_within_region,
-                            int128_get64(llend),
-                            iommu_idx);
+        iommu_iotlb_notifier_init(&giommu->n, vfio_iommu_map_notify,
+                                  IOMMU_NOTIFIER_IOTLB_ALL,
+                                  section->offset_within_region,
+                                  int128_get64(llend),
+                                  iommu_idx);
         QLIST_INSERT_HEAD(&container->giommu_list, giommu, giommu_next);
 
         memory_region_register_iommu_notifier(section->mr, &giommu->n);
@@ -625,7 +625,7 @@ static void vfio_listener_region_del(MemoryListener *listener,
 
         QLIST_FOREACH(giommu, &container->giommu_list, giommu_next) {
             if (MEMORY_REGION(giommu->iommu) == section->mr &&
-                giommu->n.start == section->offset_within_region) {
+                giommu->n.iotlb_notifier.start == section->offset_within_region) {
                 memory_region_unregister_iommu_notifier(section->mr,
                                                         &giommu->n);
                 QLIST_REMOVE(giommu, giommu_next);
hw/virtio/vhost.c +6 -6
index d4cb5894a8..c21b9b8be9 100644
@@ -677,11 +677,11 @@ static void vhost_iommu_region_add(MemoryListener *listener,
     end = int128_sub(end, int128_one());
     iommu_idx = memory_region_iommu_attrs_to_index(iommu_mr,
                                                    MEMTXATTRS_UNSPECIFIED);
-    iommu_notifier_init(&iommu->n, vhost_iommu_unmap_notify,
-                        IOMMU_NOTIFIER_UNMAP,
-                        section->offset_within_region,
-                        int128_get64(end),
-                        iommu_idx);
+    iommu_iotlb_notifier_init(&iommu->n, vhost_iommu_unmap_notify,
+                              IOMMU_NOTIFIER_UNMAP,
+                              section->offset_within_region,
+                              int128_get64(end),
+                              iommu_idx);
     iommu->mr = section->mr;
     iommu->iommu_offset = section->offset_within_address_space -
                           section->offset_within_region;
@@ -704,7 +704,7 @@ static void vhost_iommu_region_del(MemoryListener *listener,
 
     QLIST_FOREACH(iommu, &dev->iommu_list, iommu_next) {
         if (iommu->mr == section->mr &&
-            iommu->n.start == section->offset_within_region) {
+            iommu->n.iotlb_notifier.start == section->offset_within_region) {
             memory_region_unregister_iommu_notifier(iommu->mr,
                                                     &iommu->n);
             QLIST_REMOVE(iommu, iommu_next);
include/exec/memory.h +15 -10
index b6e59c139c..31fc859c6b 100644
@@ -86,18 +86,22 @@ typedef enum {
     IOMMU_NOTIFIER_MAP = 0x2,
 } IOMMUNotifierFlag;
 
-#define IOMMU_NOTIFIER_ALL (IOMMU_NOTIFIER_MAP | IOMMU_NOTIFIER_UNMAP)
+#define IOMMU_NOTIFIER_IOTLB_ALL (IOMMU_NOTIFIER_MAP | IOMMU_NOTIFIER_UNMAP)
 
 struct IOMMUNotifier;
 typedef void (*IOMMUNotify)(struct IOMMUNotifier *notifier,
                             IOMMUTLBEntry *data);
 
-struct IOMMUNotifier {
+typedef struct IOMMUIOLTBNotifier {
     IOMMUNotify notify;
-    IOMMUNotifierFlag notifier_flags;
     /* Notify for address space range start <= addr <= end */
     hwaddr start;
     hwaddr end;
+} IOMMUIOLTBNotifier;
+
+struct IOMMUNotifier {
+    IOMMUNotifierFlag notifier_flags;
+    IOMMUIOLTBNotifier iotlb_notifier;
     int iommu_idx;
     QLIST_ENTRY(IOMMUNotifier) node;
 };
@@ -126,15 +130,16 @@ typedef struct IOMMUNotifier IOMMUNotifier;
 /* RAM is a persistent kind memory */
 #define RAM_PMEM (1 << 5)
 
-static inline void iommu_notifier_init(IOMMUNotifier *n, IOMMUNotify fn,
-                                       IOMMUNotifierFlag flags,
-                                       hwaddr start, hwaddr end,
-                                       int iommu_idx)
+static inline void iommu_iotlb_notifier_init(IOMMUNotifier *n, IOMMUNotify fn,
+                                             IOMMUNotifierFlag flags,
+                                             hwaddr start, hwaddr end,
+                                             int iommu_idx)
 {
-    n->notify = fn;
+    assert(flags & IOMMU_NOTIFIER_MAP || flags & IOMMU_NOTIFIER_UNMAP);
     n->notifier_flags = flags;
-    n->start = start;
-    n->end = end;
+    n->iotlb_notifier.notify = fn;
+    n->iotlb_notifier.start = start;
+    n->iotlb_notifier.end = end;
     n->iommu_idx = iommu_idx;
 }
 
memory.c +5 -5
index 9b73892768..b7e2e43b68 100644
@@ -1800,7 +1800,7 @@ void memory_region_register_iommu_notifier(MemoryRegion *mr,
     /* We need to register for at least one bitfield */
     iommu_mr = IOMMU_MEMORY_REGION(mr);
     assert(n->notifier_flags != IOMMU_NOTIFIER_NONE);
-    assert(n->start <= n->end);
+    assert(n->iotlb_notifier.start <= n->iotlb_notifier.end);
     assert(n->iommu_idx >= 0 &&
            n->iommu_idx < memory_region_iommu_num_indexes(iommu_mr));
 
@@ -1836,7 +1836,7 @@ void memory_region_iommu_replay(IOMMUMemoryRegion *iommu_mr, IOMMUNotifier *n)
     for (addr = 0; addr < memory_region_size(mr); addr += granularity) {
         iotlb = imrc->translate(iommu_mr, addr, IOMMU_NONE, n->iommu_idx);
         if (iotlb.perm != IOMMU_NONE) {
-            n->notify(n, &iotlb);
+            n->iotlb_notifier.notify(n, &iotlb);
         }
 
         /* if (2^64 - MR size) < granularity, it's possible to get an
@@ -1879,8 +1879,8 @@ void memory_region_notify_one(IOMMUNotifier *notifier,
      * Skip the notification if the notification does not overlap
      * with registered range.
      */
-    if (notifier->start > entry->iova + entry->addr_mask ||
-        notifier->end < entry->iova) {
+    if (notifier->iotlb_notifier.start > entry->iova + entry->addr_mask ||
+        notifier->iotlb_notifier.end < entry->iova) {
         return;
     }
 
@@ -1891,7 +1891,7 @@ void memory_region_notify_one(IOMMUNotifier *notifier,
     }
 
     if (notifier->notifier_flags & request_flags) {
-        notifier->notify(notifier, entry);
+        notifier->iotlb_notifier.notify(notifier, entry);
     }
 }
 
Signature · 1 line
2.17.1
author
#12 lore raw

RFC v2 10/28 memory: rename memory_region notify_iommu, notify_one

In reply to Eric Auger

Le's rename those notification functions to clearly discriminate iotlb notifications from looming config notifications.

---
 hw/arm/smmu-common.c     |  2 +-
 hw/arm/smmuv3.c          |  2 +-
 hw/i386/intel_iommu.c    | 10 +++++-----
 hw/misc/tz-mpc.c         |  8 ++++----
 hw/ppc/spapr_iommu.c     |  2 +-
 hw/s390x/s390-pci-inst.c |  4 ++--
 include/exec/memory.h    | 20 ++++++++++----------
 memory.c                 | 12 ++++++------
 8 files changed, 30 insertions(+), 30 deletions(-)
hw/arm/smmu-common.c +1 -1
index ad6ef2135b..70b014e618 100644
@@ -395,7 +395,7 @@ static void smmu_unmap_notifier_range(IOMMUNotifier *n)
     entry.perm = IOMMU_NONE;
     entry.addr_mask = n->iotlb_notifier.end - n->iotlb_notifier.start;
 
-    memory_region_notify_one(n, &entry);
+    memory_region_iotlb_notify_one(n, &entry);
 }
 
 /* Unmap all notifiers attached to @mr */
hw/arm/smmuv3.c +1 -1
index d6895071a5..b8c41916aa 100644
@@ -822,7 +822,7 @@ static void smmuv3_notify_iova(IOMMUMemoryRegion *mr,
     entry.addr_mask = (1 << tt->granule_sz) - 1;
     entry.perm = IOMMU_NONE;
 
-    memory_region_notify_one(n, &entry);
+    memory_region_iotlb_notify_one(n, &entry);
 }
 
 /* invalidate an asid/iova tuple in all mr's */
hw/i386/intel_iommu.c +5 -5
index 0dbd9512f2..dfd3cae054 100644
@@ -1031,7 +1031,7 @@ static int vtd_dev_to_context_entry(IntelIOMMUState *s, uint8_t bus_num,
 static int vtd_sync_shadow_page_hook(IOMMUTLBEntry *entry,
                                      void *private)
 {
-    memory_region_notify_iommu((IOMMUMemoryRegion *)private, 0, *entry);
+    memory_region_iotlb_notify_iommu((IOMMUMemoryRegion *)private, 0, *entry);
     return 0;
 }
 
@@ -1592,7 +1592,7 @@ static void vtd_iotlb_page_invalidate_notify(IntelIOMMUState *s,
                     .addr_mask = size - 1,
                     .perm = IOMMU_NONE,
                 };
-                memory_region_notify_iommu(&vtd_as->iommu, 0, entry);
+                memory_region_iotlb_notify_iommu(&vtd_as->iommu, 0, entry);
             }
         }
     }
@@ -2031,7 +2031,7 @@ static bool vtd_process_device_iotlb_desc(IntelIOMMUState *s,
     entry.iova = addr;
     entry.perm = IOMMU_NONE;
     entry.translated_addr = 0;
-    memory_region_notify_iommu(&vtd_dev_as->iommu, 0, entry);
+    memory_region_iotlb_notify_iommu(&vtd_dev_as->iommu, 0, entry);
 
 done:
     return true;
@@ -3036,7 +3036,7 @@ static void vtd_address_space_unmap(VTDAddressSpace *as, IOMMUNotifier *n)
     map.size = entry.addr_mask;
     iova_tree_remove(as->iova_tree, &map);
 
-    memory_region_notify_one(n, &entry);
+    memory_region_iotlb_notify_one(n, &entry);
 }
 
 static void vtd_address_space_unmap_all(IntelIOMMUState *s)
@@ -3053,7 +3053,7 @@ static void vtd_address_space_unmap_all(IntelIOMMUState *s)
 
 static int vtd_replay_hook(IOMMUTLBEntry *entry, void *private)
 {
-    memory_region_notify_one((IOMMUNotifier *)private, entry);
+    memory_region_iotlb_notify_one((IOMMUNotifier *)private, entry);
     return 0;
 }
 
hw/misc/tz-mpc.c +4 -4
index e0c58ba37e..a585e7b475 100644
@@ -100,8 +100,8 @@ static void tz_mpc_iommu_notify(TZMPC *s, uint32_t lutidx,
         entry.translated_addr = addr;
 
         entry.perm = IOMMU_NONE;
-        memory_region_notify_iommu(&s->upstream, IOMMU_IDX_S, entry);
-        memory_region_notify_iommu(&s->upstream, IOMMU_IDX_NS, entry);
+        memory_region_iotlb_notify_iommu(&s->upstream, IOMMU_IDX_S, entry);
+        memory_region_iotlb_notify_iommu(&s->upstream, IOMMU_IDX_NS, entry);
 
         entry.perm = IOMMU_RW;
         if (block_is_ns) {
@@ -109,13 +109,13 @@ static void tz_mpc_iommu_notify(TZMPC *s, uint32_t lutidx,
         } else {
             entry.target_as = &s->downstream_as;
         }
-        memory_region_notify_iommu(&s->upstream, IOMMU_IDX_S, entry);
+        memory_region_iotlb_notify_iommu(&s->upstream, IOMMU_IDX_S, entry);
         if (block_is_ns) {
             entry.target_as = &s->downstream_as;
         } else {
             entry.target_as = &s->blocked_io_as;
         }
-        memory_region_notify_iommu(&s->upstream, IOMMU_IDX_NS, entry);
+        memory_region_iotlb_notify_iommu(&s->upstream, IOMMU_IDX_NS, entry);
     }
 }
 
hw/ppc/spapr_iommu.c +1 -1
index 1b0880ac9e..680fb6ad24 100644
@@ -429,7 +429,7 @@ static target_ulong put_tce_emu(sPAPRTCETable *tcet, target_ulong ioba,
     entry.translated_addr = tce & page_mask;
     entry.addr_mask = ~page_mask;
     entry.perm = spapr_tce_iommu_access_flags(tce);
-    memory_region_notify_iommu(&tcet->iommu, 0, entry);
+    memory_region_iotlb_notify_iommu(&tcet->iommu, 0, entry);
 
     return H_SUCCESS;
 }
hw/s390x/s390-pci-inst.c +2 -2
index 7b61367ee3..a5ad72d19c 100644
@@ -589,7 +589,7 @@ static void s390_pci_update_iotlb(S390PCIIOMMU *iommu, S390IOTLBEntry *entry)
             }
 
             notify.perm = IOMMU_NONE;
-            memory_region_notify_iommu(&iommu->iommu_mr, 0, notify);
+            memory_region_iotlb_notify_iommu(&iommu->iommu_mr, 0, notify);
             notify.perm = entry->perm;
         }
 
@@ -601,7 +601,7 @@ static void s390_pci_update_iotlb(S390PCIIOMMU *iommu, S390IOTLBEntry *entry)
         g_hash_table_replace(iommu->iotlb, &cache->iova, cache);
     }
 
-    memory_region_notify_iommu(&iommu->iommu_mr, 0, notify);
+    memory_region_iotlb_notify_iommu(&iommu->iommu_mr, 0, notify);
 }
 
 int rpcit_service_call(S390CPU *cpu, uint8_t r1, uint8_t r2, uintptr_t ra)
include/exec/memory.h +10 -10
index 31fc859c6b..5ef9bf6d21 100644
@@ -1024,10 +1024,10 @@ static inline IOMMUMemoryRegionClass *memory_region_get_iommu_class_nocheck(
 uint64_t memory_region_iommu_get_min_page_size(IOMMUMemoryRegion *iommu_mr);
 
 /**
- * memory_region_notify_iommu: notify a change in an IOMMU translation entry.
+ * memory_region_iotlb_notify_iommu: notify a change in an IOMMU translation
+ * entry.
  *
  * The notification type will be decided by entry.perm bits:
- *
  * - For UNMAP (cache invalidation) notifies: set entry.perm to IOMMU_NONE.
  * - For MAP (newly added entry) notifies: set entry.perm to the
  *   permission of the page (which is definitely !IOMMU_NONE).
@@ -1041,15 +1041,15 @@ uint64_t memory_region_iommu_get_min_page_size(IOMMUMemoryRegion *iommu_mr);
  *         replaces all old entries for the same virtual I/O address range.
  *         Deleted entries have .@perm == 0.
  */
-void memory_region_notify_iommu(IOMMUMemoryRegion *iommu_mr,
-                                int iommu_idx,
-                                IOMMUTLBEntry entry);
+void memory_region_iotlb_notify_iommu(IOMMUMemoryRegion *iommu_mr,
+                                      int iommu_idx,
+                                      IOMMUTLBEntry entry);
 
 /**
- * memory_region_notify_one: notify a change in an IOMMU translation
- *                           entry to a single notifier
+ * memory_region_iotlb_notify_one: notify a change in an IOMMU translation
+ *                                 entry to a single notifier
  *
- * This works just like memory_region_notify_iommu(), but it only
+ * This works just like memory_region_iotlb_notify_iommu(), but it only
  * notifies a specific notifier, not all of them.
  *
  * @notifier: the notifier to be notified
@@ -1057,8 +1057,8 @@ void memory_region_notify_iommu(IOMMUMemoryRegion *iommu_mr,
  *         replaces all old entries for the same virtual I/O address range.
  *         Deleted entries have .@perm == 0.
  */
-void memory_region_notify_one(IOMMUNotifier *notifier,
-                              IOMMUTLBEntry *entry);
+void memory_region_iotlb_notify_one(IOMMUNotifier *notifier,
+                                    IOMMUTLBEntry *entry);
 
 /**
  * memory_region_register_iommu_notifier: register a notifier for changes to
memory.c +6 -6
index b7e2e43b68..8ee5cbdbad 100644
@@ -1870,8 +1870,8 @@ void memory_region_unregister_iommu_notifier(MemoryRegion *mr,
     memory_region_update_iommu_notify_flags(iommu_mr);
 }
 
-void memory_region_notify_one(IOMMUNotifier *notifier,
-                              IOMMUTLBEntry *entry)
+void memory_region_iotlb_notify_one(IOMMUNotifier *notifier,
+                                    IOMMUTLBEntry *entry)
 {
     IOMMUNotifierFlag request_flags;
 
@@ -1895,9 +1895,9 @@ void memory_region_notify_one(IOMMUNotifier *notifier,
     }
 }
 
-void memory_region_notify_iommu(IOMMUMemoryRegion *iommu_mr,
-                                int iommu_idx,
-                                IOMMUTLBEntry entry)
+void memory_region_iotlb_notify_iommu(IOMMUMemoryRegion *iommu_mr,
+                                      int iommu_idx,
+                                      IOMMUTLBEntry entry)
 {
     IOMMUNotifier *iommu_notifier;
 
@@ -1905,7 +1905,7 @@ void memory_region_notify_iommu(IOMMUMemoryRegion *iommu_mr,
 
     IOMMU_NOTIFIER_FOREACH(iommu_notifier, iommu_mr) {
         if (iommu_notifier->iommu_idx == iommu_idx) {
-            memory_region_notify_one(iommu_notifier, &entry);
+            memory_region_iotlb_notify_one(iommu_notifier, &entry);
         }
     }
 }
Signature · 1 line
2.17.1
author
#13 lore raw

RFC v2 11/28 memory: Add IOMMUConfigNotifier

In reply to Eric Auger

With this patch, an IOMMUNotifier can now be either an IOTLB notifier or a config notifier. A config notifier is supposed to be called on guest translation config change. This gives host a chance to update the physical IOMMU configuration so that is consistent with the guest view.

The notifier is passed an IOMMUConfig. The first type of configuration introduced here consists in the PASID configuration.

We introduce the associated helpers, iommu_config_notifier_init, memory_region_config_notify_iommu

---

v1 -> v2:
- use pasid_table config
- pass IOMMUNotifierFlag flags to iommu_config_notifier_init to prepare for other config flags
- Introduce IOMMUConfig
- s/IOMMU_NOTIFIER_S1_CFG/IOMMU_NOTIFIER_PASID_CFG
- remove unused IOMMUStage1ConfigType

---
 hw/vfio/common.c      | 14 +++++++---
 include/exec/memory.h | 62 +++++++++++++++++++++++++++++++++++++++++--
 memory.c              | 34 ++++++++++++++++++++++--
 3 files changed, 102 insertions(+), 8 deletions(-)
hw/vfio/common.c +10 -4
index 19dfc279d6..5dcb502f42 100644
@@ -624,10 +624,16 @@ static void vfio_listener_region_del(MemoryListener *listener,
         VFIOGuestIOMMU *giommu;
 
         QLIST_FOREACH(giommu, &container->giommu_list, giommu_next) {
-            if (MEMORY_REGION(giommu->iommu) == section->mr &&
-                giommu->n.iotlb_notifier.start == section->offset_within_region) {
-                memory_region_unregister_iommu_notifier(section->mr,
-                                                        &giommu->n);
+            if (MEMORY_REGION(giommu->iommu) == section->mr) {
+                if (is_iommu_iotlb_notifier(&giommu->n) &&
+                    giommu->n.iotlb_notifier.start ==
+                        section->offset_within_region) {
+                    memory_region_unregister_iommu_notifier(section->mr,
+                                                            &giommu->n);
+                } else if (is_iommu_config_notifier(&giommu->n)) {
+                    memory_region_unregister_iommu_notifier(section->mr,
+                                                            &giommu->n);
+                }
                 QLIST_REMOVE(giommu, giommu_next);
                 g_free(giommu);
                 break;
include/exec/memory.h +60 -2

119 lines not on this page · raw message

memory.c +32 -2
index 8ee5cbdbad..2c320bc14b 100644
@@ -49,6 +49,8 @@ static GHashTable *flat_views;
 
 typedef struct AddrRange AddrRange;
 
+struct iommu_pasid_table_config;
+
 /*
  * Note that signed integers are needed for negative offsetting in aliases
  * (large MemoryRegion::alias_offset).
@@ -1800,7 +1802,9 @@ void memory_region_register_iommu_notifier(MemoryRegion *mr,
     /* We need to register for at least one bitfield */
     iommu_mr = IOMMU_MEMORY_REGION(mr);
     assert(n->notifier_flags != IOMMU_NOTIFIER_NONE);
-    assert(n->iotlb_notifier.start <= n->iotlb_notifier.end);
+    if (is_iommu_iotlb_notifier(n)) {
+        assert(n->iotlb_notifier.start <= n->iotlb_notifier.end);
+    }
     assert(n->iommu_idx >= 0 &&
            n->iommu_idx < memory_region_iommu_num_indexes(iommu_mr));
 
@@ -1870,6 +1874,13 @@ void memory_region_unregister_iommu_notifier(MemoryRegion *mr,
     memory_region_update_iommu_notify_flags(iommu_mr);
 }
 
+static void
+memory_region_config_notify_one(IOMMUNotifier *notifier,
+                                IOMMUConfig *cfg)
+{
+    notifier->config_notifier.notify(notifier, cfg);
+}
+
 void memory_region_iotlb_notify_one(IOMMUNotifier *notifier,
                                     IOMMUTLBEntry *entry)
 {
@@ -1904,12 +1915,31 @@ void memory_region_iotlb_notify_iommu(IOMMUMemoryRegion *iommu_mr,
     assert(memory_region_is_iommu(MEMORY_REGION(iommu_mr)));
 
     IOMMU_NOTIFIER_FOREACH(iommu_notifier, iommu_mr) {
-        if (iommu_notifier->iommu_idx == iommu_idx) {
+        if (iommu_notifier->iommu_idx == iommu_idx &&
+            is_iommu_iotlb_notifier(iommu_notifier)) {
             memory_region_iotlb_notify_one(iommu_notifier, &entry);
         }
     }
 }
 
+void memory_region_config_notify_iommu(IOMMUMemoryRegion *iommu_mr,
+                                       int iommu_idx,
+                                       IOMMUNotifierFlag flag,
+                                       IOMMUConfig *config)
+{
+    IOMMUNotifier *iommu_notifier;
+
+    assert(memory_region_is_iommu(MEMORY_REGION(iommu_mr)));
+
+    IOMMU_NOTIFIER_FOREACH(iommu_notifier, iommu_mr) {
+        if (iommu_notifier->iommu_idx == iommu_idx &&
+            is_iommu_config_notifier(iommu_notifier) &&
+            iommu_notifier->notifier_flags == flag) {
+            memory_region_config_notify_one(iommu_notifier, config);
+        }
+    }
+}
+
 int memory_region_iommu_get_attr(IOMMUMemoryRegion *iommu_mr,
                                  enum IOMMUMemoryRegionAttr attr,
                                  void *data)
Signature · 1 line
2.17.1
author
#14 lore raw

RFC v2 12/28 memory: Add arch_id in IOTLBEntry

In reply to Eric Auger

TLB entries are usually tagged with some ids such as the asid or pasid. When propagating an invalidation command from the guest to the host, we need to pass this id.

---
 include/exec/memory.h | 1 +
 1 file changed, 1 insertion(+)
include/exec/memory.h +1 -0
index d4486d4e6b..93150e1450 100644
@@ -75,6 +75,7 @@ struct IOMMUTLBEntry {
     hwaddr           translated_addr;
     hwaddr           addr_mask;  /* 0xfff = 4k translation */
     IOMMUAccessFlags perm;
+    uint32_t         arch_id; /* architecture specific ID tagging the TLB */
 };
 
 typedef struct IOMMUConfig {
Signature · 1 line
2.17.1
author
#15 lore raw

RFC v2 13/28 hw/arm/smmuv3: Store s1ctrptr in translation config data

In reply to Eric Auger

For VFIO integration we will need to pass the context descriptor table GPA to the host. So let's decode and store it.

---
 hw/arm/smmuv3.c              | 1 +
 include/hw/arm/smmu-common.h | 1 +
 2 files changed, 2 insertions(+)
hw/arm/smmuv3.c +1 -0
index b8c41916aa..afe1758830 100644
@@ -351,6 +351,7 @@ static int decode_ste(SMMUv3State *s, SMMUTransCfg *cfg,
                       "SMMUv3 S1 stalling fault model not allowed yet\n");
         goto bad_ste;
     }
+    cfg->s1ctxptr = STE_CTXPTR(ste);
     return 0;
 
 bad_ste:
include/hw/arm/smmu-common.h +1 -0
index b07cadd0ef..52073a23b4 100644
@@ -68,6 +68,7 @@ typedef struct SMMUTransCfg {
     uint8_t tbi;               /* Top Byte Ignore */
     uint16_t asid;
     SMMUTransTableInfo tt[2];
+    dma_addr_t s1ctxptr;
     uint32_t iotlb_hits;       /* counts IOTLB hits for this asid */
     uint32_t iotlb_misses;     /* counts IOTLB misses for this asid */
 } SMMUTransCfg;
Signature · 1 line
2.17.1
author
#16 lore raw

RFC v2 14/28 hw/arm/smmuv3: Implement dummy replay

In reply to Eric Auger

The default implementation of memory_region_iommu_replay() shall not be used as it forces the translation of the whole RAM range. The purpose of this function is to update the shadow page tables. However in case of nested stage, there is no shadow page table so we can simply return.

---
 hw/arm/smmuv3.c | 6 ++++++
 1 file changed, 6 insertions(+)
hw/arm/smmuv3.c +6 -0
index afe1758830..d609038724 100644
@@ -1516,6 +1516,11 @@ static int smmuv3_get_attr(IOMMUMemoryRegion *iommu,
     return -EINVAL;
 }
 
+static inline void
+smmuv3_replay(IOMMUMemoryRegion *iommu_mr, IOMMUNotifier *n)
+{
+}
+
 static void smmuv3_iommu_memory_region_class_init(ObjectClass *klass,
                                                   void *data)
 {
@@ -1524,6 +1529,7 @@ static void smmuv3_iommu_memory_region_class_init(ObjectClass *klass,
     imrc->translate = smmuv3_translate;
     imrc->notify_flag_changed = smmuv3_notify_flag_changed;
     imrc->get_attr = smmuv3_get_attr;
+    imrc->replay = smmuv3_replay;
 }
 
 static const TypeInfo smmuv3_type_info = {
Signature · 1 line
2.17.1
author
#17 lore raw

RFC v2 15/28 hw/arm/smmuv3: Notify on config changes

In reply to Eric Auger

In case IOMMU config notifiers are attached to the IOMMU memory region, we execute them, passing as argument the iommu_pasid_table_config struct updated with the new viommu translation config. Config notifiers are called on STE changes. At physical level, they translate into CMD_CFGI_STE_* commands.

---

v1 -> v2:
- do not notify anymore on CD change. Anyway the smmuv3 linux driver is not sending any CD invalidation commands. If we were to propagate CD invalidation commands, we would use the CACHE_INVALIDATE VFIO ioctl.
- notify a precise config flags to prepare for addition of new flags

---
 hw/arm/smmuv3.c | 61 +++++++++++++++++++++++++++++++++++--------------
 1 file changed, 44 insertions(+), 17 deletions(-)
hw/arm/smmuv3.c +44 -17
index d609038724..196835739f 100644
@@ -16,6 +16,8 @@
  * with this program; if not, see <http://www.gnu.org/licenses/>.
  */
 
+#include "linux/iommu.h"
+
 #include "qemu/osdep.h"
 #include "hw/boards.h"
 #include "sysemu/sysemu.h"
@@ -843,6 +845,46 @@ static void smmuv3_inv_notifiers_iova(SMMUState *s, int asid, dma_addr_t iova)
     }
 }
 
+static void smmuv3_notify_config_change(SMMUState *bs, uint32_t sid)
+{
+    IOMMUMemoryRegion *mr = smmu_iommu_mr(bs, sid);
+    SMMUEventInfo event = {.type = SMMU_EVT_NONE, .sid = sid};
+    SMMUTransCfg *cfg;
+    SMMUDevice *sdev;
+
+    if (!mr) {
+        return;
+    }
+
+    sdev = container_of(mr, SMMUDevice, iommu);
+
+    /* flush QEMU config cache */
+    smmuv3_flush_config(sdev);
+
+    if (mr->iommu_notify_flags & IOMMU_NOTIFIER_PASID_CFG) {
+        /* force a guest RAM config structure decoding */
+        cfg = smmuv3_get_config(sdev, &event);
+
+        if (cfg) {
+            IOMMUConfig *iommu_config = g_new0(IOMMUConfig, 1);
+
+            iommu_config->pasid_cfg.format = IOMMU_PASID_FORMAT_SMMUV3;
+            iommu_config->pasid_cfg.smmuv3.bypass =
+                cfg->disabled || cfg->bypassed;
+            iommu_config->pasid_cfg.smmuv3.abort = cfg->aborted;
+            iommu_config->pasid_cfg.smmuv3.s1contextptr = cfg->s1ctxptr;
+
+            memory_region_config_notify_iommu(mr, 0, IOMMU_NOTIFIER_PASID_CFG,
+                                              iommu_config);
+            g_free(iommu_config);
+        } else {
+            qemu_log_mask(LOG_GUEST_ERROR,
+                          "%s error decoding the configuration for iommu mr=%s\n",
+                         __func__, mr->parent_obj.name);
+        }
+    }
+}
+
 static int smmuv3_cmdq_consume(SMMUv3State *s)
 {
     SMMUState *bs = ARM_SMMU(s);
@@ -893,22 +935,14 @@ static int smmuv3_cmdq_consume(SMMUv3State *s)
         case SMMU_CMD_CFGI_STE:
         {
             uint32_t sid = CMD_SID(&cmd);
-            IOMMUMemoryRegion *mr = smmu_iommu_mr(bs, sid);
-            SMMUDevice *sdev;
 
             if (CMD_SSEC(&cmd)) {
                 cmd_error = SMMU_CERROR_ILL;
                 break;
             }
 
-            if (!mr) {
-                break;
-            }
-
             trace_smmuv3_cmdq_cfgi_ste(sid);
-            sdev = container_of(mr, SMMUDevice, iommu);
-            smmuv3_flush_config(sdev);
-
+            smmuv3_notify_config_change(bs, sid);
             break;
         }
         case SMMU_CMD_CFGI_STE_RANGE: /* same as SMMU_CMD_CFGI_ALL */
@@ -925,14 +959,7 @@ static int smmuv3_cmdq_consume(SMMUv3State *s)
             trace_smmuv3_cmdq_cfgi_ste_range(start, end);
 
             for (i = start; i <= end; i++) {
-                IOMMUMemoryRegion *mr = smmu_iommu_mr(bs, i);
-                SMMUDevice *sdev;
-
-                if (!mr) {
-                    continue;
-                }
-                sdev = container_of(mr, SMMUDevice, iommu);
-                smmuv3_flush_config(sdev);
+                smmuv3_notify_config_change(bs, i);
             }
             break;
         }
Signature · 1 line
2.17.1
author
#18 lore raw

RFC v2 16/28 hw/arm/smmuv3: Fill the IOTLBEntry arch_id on NH_VA invalidation

In reply to Eric Auger

When the guest invalidates one S1 entry, it passes the asid. When propagating this invalidation downto the host, the asid information also must be passed. So let's fill the arch_id field introduced for that purpose.

---
 hw/arm/smmuv3.c | 1 +
 1 file changed, 1 insertion(+)
hw/arm/smmuv3.c +1 -0
index 196835739f..1d8deae37f 100644
@@ -824,6 +824,7 @@ static void smmuv3_notify_iova(IOMMUMemoryRegion *mr,
     entry.iova = iova;
     entry.addr_mask = (1 << tt->granule_sz) - 1;
     entry.perm = IOMMU_NONE;
+    entry.arch_id = asid;
 
     memory_region_iotlb_notify_one(n, &entry);
 }
Signature · 1 line
2.17.1
author
#19 lore raw

RFC v2 17/28 hw/vfio/common: Introduce vfio_alloc_guest_iommu helper

In reply to Eric Auger

Soon this code will be called several times. So let's introduce an helper.

---
 hw/vfio/common.c | 25 ++++++++++++++++++++-----
 1 file changed, 20 insertions(+), 5 deletions(-)
hw/vfio/common.c +20 -5
index 5dcb502f42..ce13c102a5 100644
@@ -24,6 +24,7 @@
 #include <linux/kvm.h>
 #endif
 #include <linux/vfio.h>
+#include <linux/iommu.h>
 
 #include "hw/vfio/vfio-common.h"
 #include "hw/vfio/vfio.h"
@@ -401,6 +402,19 @@ out:
     rcu_read_unlock();
 }
 
+static VFIOGuestIOMMU *vfio_alloc_guest_iommu(VFIOContainer *container,
+                                              IOMMUMemoryRegion *iommu,
+                                              hwaddr offset)
+{
+    VFIOGuestIOMMU *giommu = g_new0(VFIOGuestIOMMU, 1);
+
+    giommu->container = container;
+    giommu->iommu = iommu;
+    giommu->iommu_offset = offset;
+    /* notifier will be registered separately */
+    return giommu;
+}
+
 static void vfio_listener_region_add(MemoryListener *listener,
                                      MemoryRegionSection *section)
 {
@@ -508,6 +522,7 @@ static void vfio_listener_region_add(MemoryListener *listener,
     if (memory_region_is_iommu(section->mr)) {
         VFIOGuestIOMMU *giommu;
         IOMMUMemoryRegion *iommu_mr = IOMMU_MEMORY_REGION(section->mr);
+        hwaddr offset;
         int iommu_idx;
 
         trace_vfio_listener_region_add_iommu(iova, end);
@@ -517,11 +532,11 @@ static void vfio_listener_region_add(MemoryListener *listener,
          * would be the right place to wire that up (tell the KVM
          * device emulation the VFIO iommu handles to use).
          */
-        giommu = g_malloc0(sizeof(*giommu));
-        giommu->iommu = iommu_mr;
-        giommu->iommu_offset = section->offset_within_address_space -
-                               section->offset_within_region;
-        giommu->container = container;
+
+        offset = section->offset_within_address_space -
+                    section->offset_within_region;
+        giommu = vfio_alloc_guest_iommu(container, iommu_mr, offset);
+
         llend = int128_add(int128_make64(section->offset_within_region),
                            section->size);
         llend = int128_sub(llend, int128_one());
Signature · 1 line
2.17.1
author
#20 lore raw

RFC v2 18/28 hw/vfio/common: Introduce vfio_dma_(un)map_ram_section helpers

In reply to Eric Auger

This code is going to be duplicated soon, so let's introduce an helper which dma (unp)maps a ram memory section.

No functional change.

---
 hw/vfio/common.c     | 198 ++++++++++++++++++++++++++-----------------
 hw/vfio/trace-events |   4 +-
 2 files changed, 123 insertions(+), 79 deletions(-)
hw/vfio/common.c +121 -77
index ce13c102a5..83f5f2263d 100644
@@ -415,13 +415,130 @@ static VFIOGuestIOMMU *vfio_alloc_guest_iommu(VFIOContainer *container,
     return giommu;
 }
 
+static int vfio_dma_map_ram_section(VFIOContainer *container,
+                                    MemoryRegionSection *section)
+{
+    VFIOHostDMAWindow *hostwin;
+    Int128 llend, llsize;
+    bool hostwin_found;
+    hwaddr iova, end;
+    void *vaddr;
+    int ret;
+
+    assert(memory_region_is_ram(section->mr));
+
+    iova = TARGET_PAGE_ALIGN(section->offset_within_address_space);
+    llend = int128_make64(section->offset_within_address_space);
+    llend = int128_add(llend, section->size);
+    llend = int128_and(llend, int128_exts64(TARGET_PAGE_MASK));
+    end = int128_get64(int128_sub(llend, int128_one()));
+
+    vaddr = memory_region_get_ram_ptr(section->mr) +
+            section->offset_within_region +
+            (iova - section->offset_within_address_space);
+
+    hostwin_found = false;
+    QLIST_FOREACH(hostwin, &container->hostwin_list, hostwin_next) {
+        if (hostwin->min_iova <= iova && end <= hostwin->max_iova) {
+            hostwin_found = true;
+            break;
+        }
+    }
+
+    if (!hostwin_found) {
+        error_report("vfio: IOMMU container %p can't map guest IOVA region"
+                     " 0x%"HWADDR_PRIx"..0x%"HWADDR_PRIx,
+                     container, iova, end);
+        return -EFAULT;
+    }
+
+    trace_vfio_dma_map_ram(iova, end, vaddr);
+
+    llsize = int128_sub(llend, int128_make64(iova));
+
+    if (memory_region_is_ram_device(section->mr)) {
+        hwaddr pgmask = (1ULL << ctz64(hostwin->iova_pgsizes)) - 1;
+
+        if ((iova & pgmask) || (int128_get64(llsize) & pgmask)) {
+            trace_vfio_listener_region_add_no_dma_map(
+                memory_region_name(section->mr),
+                section->offset_within_address_space,
+                int128_getlo(section->size),
+                pgmask + 1);
+            return 0;
+        }
+    }
+
+    ret = vfio_dma_map(container, iova, int128_get64(llsize),
+                       vaddr, section->readonly);
+    if (ret) {
+        error_report("vfio_dma_map(%p, 0x%"HWADDR_PRIx", "
+                     "0x%"HWADDR_PRIx", %p) = %d (%m)",
+                     container, iova, int128_get64(llsize), vaddr, ret);
+        if (memory_region_is_ram_device(section->mr)) {
+            /* Allow unexpected mappings not to be fatal for RAM devices */
+            return 0;
+        }
+        return -EINVAL;
+    }
+    return 0;
+}
+
+static void vfio_dma_unmap_ram_section(VFIOContainer *container,
+                                       MemoryRegionSection *section)
+{
+    Int128 llend, llsize;
+    hwaddr iova, end;
+    bool try_unmap = true;
+    int ret;
+
+    iova = TARGET_PAGE_ALIGN(section->offset_within_address_space);
+    llend = int128_make64(section->offset_within_address_space);
+    llend = int128_add(llend, section->size);
+    llend = int128_and(llend, int128_exts64(TARGET_PAGE_MASK));
+
+    if (int128_ge(int128_make64(iova), llend)) {
+        return;
+    }
+    end = int128_get64(int128_sub(llend, int128_one()));
+
+    llsize = int128_sub(llend, int128_make64(iova));
+
+    trace_vfio_dma_unmap_ram(iova, end);
+
+    if (memory_region_is_ram_device(section->mr)) {
+        hwaddr pgmask;
+        VFIOHostDMAWindow *hostwin;
+        bool hostwin_found = false;
+
+        QLIST_FOREACH(hostwin, &container->hostwin_list, hostwin_next) {
+            if (hostwin->min_iova <= iova && end <= hostwin->max_iova) {
+                hostwin_found = true;
+                break;
+            }
+        }
+        assert(hostwin_found); /* or region_add() would have failed */
+
+        pgmask = (1ULL << ctz64(hostwin->iova_pgsizes)) - 1;
+        try_unmap = !((iova & pgmask) || (int128_get64(llsize) & pgmask));
+    }
+
+    if (try_unmap) {
+        ret = vfio_dma_unmap(container, iova, int128_get64(llsize));
+        if (ret) {
+            error_report("vfio_dma_unmap(%p, 0x%"HWADDR_PRIx", "
+                         "0x%"HWADDR_PRIx") = %d (%m)",
+                         container, iova, int128_get64(llsize), ret);
+        }
+    }
+}
+
 static void vfio_listener_region_add(MemoryListener *listener,
                                      MemoryRegionSection *section)
 {
     VFIOContainer *container = container_of(listener, VFIOContainer, listener);
     hwaddr iova, end;
-    Int128 llend, llsize;
-    void *vaddr;
+    Int128 llend;
     int ret;
     VFIOHostDMAWindow *hostwin;
     bool hostwin_found;
@@ -556,41 +673,10 @@ static void vfio_listener_region_add(MemoryListener *listener,
     }
 
     /* Here we assume that memory_region_is_ram(section->mr)==true */
-
-    vaddr = memory_region_get_ram_ptr(section->mr) +
-            section->offset_within_region +
-            (iova - section->offset_within_address_space);
-
-    trace_vfio_listener_region_add_ram(iova, end, vaddr);
-
-    llsize = int128_sub(llend, int128_make64(iova));
-
-    if (memory_region_is_ram_device(section->mr)) {
-        hwaddr pgmask = (1ULL << ctz64(hostwin->iova_pgsizes)) - 1;
-
-        if ((iova & pgmask) || (int128_get64(llsize) & pgmask)) {
-            trace_vfio_listener_region_add_no_dma_map(
-                memory_region_name(section->mr),
-                section->offset_within_address_space,
-                int128_getlo(section->size),
-                pgmask + 1);
-            return;
-        }
-    }
-
-    ret = vfio_dma_map(container, iova, int128_get64(llsize),
-                       vaddr, section->readonly);
+    ret = vfio_dma_map_ram_section(container, section);
     if (ret) {
-        error_report("vfio_dma_map(%p, 0x%"HWADDR_PRIx", "
-                     "0x%"HWADDR_PRIx", %p) = %d (%m)",
-                     container, iova, int128_get64(llsize), vaddr, ret);
-        if (memory_region_is_ram_device(section->mr)) {
-            /* Allow unexpected mappings not to be fatal for RAM devices */
-            return;
-        }
         goto fail;
     }
-
     return;
 
 fail:
@@ -616,10 +702,6 @@ static void vfio_listener_region_del(MemoryListener *listener,
                                      MemoryRegionSection *section)
 {
     VFIOContainer *container = container_of(listener, VFIOContainer, listener);
-    hwaddr iova, end;
-    Int128 llend, llsize;
-    int ret;
-    bool try_unmap = true;
 
     if (vfio_listener_skipped_section(section)) {
         trace_vfio_listener_region_del_skip(
@@ -664,45 +746,7 @@ static void vfio_listener_region_del(MemoryListener *listener,
          */
     }
 
-    iova = TARGET_PAGE_ALIGN(section->offset_within_address_space);
-    llend = int128_make64(section->offset_within_address_space);
-    llend = int128_add(llend, section->size);
-    llend = int128_and(llend, int128_exts64(TARGET_PAGE_MASK));
-
-    if (int128_ge(int128_make64(iova), llend)) {
-        return;
-    }
-    end = int128_get64(int128_sub(llend, int128_one()));
-
-    llsize = int128_sub(llend, int128_make64(iova));
-
-    trace_vfio_listener_region_del(iova, end);
-
-    if (memory_region_is_ram_device(section->mr)) {
-        hwaddr pgmask;
-        VFIOHostDMAWindow *hostwin;
-        bool hostwin_found = false;
-
-        QLIST_FOREACH(hostwin, &container->hostwin_list, hostwin_next) {
-            if (hostwin->min_iova <= iova && end <= hostwin->max_iova) {
-                hostwin_found = true;
-                break;
-            }
-        }
-        assert(hostwin_found); /* or region_add() would have failed */
-
-        pgmask = (1ULL << ctz64(hostwin->iova_pgsizes)) - 1;
-        try_unmap = !((iova & pgmask) || (int128_get64(llsize) & pgmask));
-    }
-
-    if (try_unmap) {
-        ret = vfio_dma_unmap(container, iova, int128_get64(llsize));
-        if (ret) {
-            error_report("vfio_dma_unmap(%p, 0x%"HWADDR_PRIx", "
-                         "0x%"HWADDR_PRIx") = %d (%m)",
-                         container, iova, int128_get64(llsize), ret);
-        }
-    }
+    vfio_dma_unmap_ram_section(container, section);
 
     memory_region_unref(section->mr);
 
hw/vfio/trace-events +2 -2
index a85e8662ea..cee49ef124 100644
@@ -93,10 +93,10 @@ vfio_region_read(char *name, int index, uint64_t addr, unsigned size, uint64_t d
 vfio_iommu_map_notify(const char *op, uint64_t iova_start, uint64_t iova_end) "iommu %s @ 0x%"PRIx64" - 0x%"PRIx64
 vfio_listener_region_add_skip(uint64_t start, uint64_t end) "SKIPPING region_add 0x%"PRIx64" - 0x%"PRIx64
 vfio_listener_region_add_iommu(uint64_t start, uint64_t end) "region_add [iommu] 0x%"PRIx64" - 0x%"PRIx64
-vfio_listener_region_add_ram(uint64_t iova_start, uint64_t iova_end, void *vaddr) "region_add [ram] 0x%"PRIx64" - 0x%"PRIx64" [%p]"
+vfio_dma_map_ram(uint64_t iova_start, uint64_t iova_end, void *vaddr) "region_add [ram] 0x%"PRIx64" - 0x%"PRIx64" [%p]"
 vfio_listener_region_add_no_dma_map(const char *name, uint64_t iova, uint64_t size, uint64_t page_size) "Region \"%s\" 0x%"PRIx64" size=0x%"PRIx64" is not aligned to 0x%"PRIx64" and cannot be mapped for DMA"
 vfio_listener_region_del_skip(uint64_t start, uint64_t end) "SKIPPING region_del 0x%"PRIx64" - 0x%"PRIx64
-vfio_listener_region_del(uint64_t start, uint64_t end) "region_del 0x%"PRIx64" - 0x%"PRIx64
+vfio_dma_unmap_ram(uint64_t start, uint64_t end) "region_del 0x%"PRIx64" - 0x%"PRIx64
 vfio_disconnect_container(int fd) "close container->fd=%d"
 vfio_put_group(int fd) "close group->fd=%d"
 vfio_get_device(const char * name, unsigned int flags, unsigned int num_regions, unsigned int num_irqs) "Device %s flags: %u, regions: %u, irqs: %u"
Signature · 1 line
2.17.1
author
#21 lore raw

RFC v2 19/28 hw/vfio/common: Register specific nested mode notifiers and memory_listener

In reply to Eric Auger

In nested mode, legacy vfio_iommu_map_notify MAP/UNMAP notifier cannot be used anymore. Indeed there is no caching mode in place that allows to trap MAP events. Only configuration change and UNMAP events can be trapped. As such we register
- one configuration notifier, whose role is to propagate the configuration update downto the host
- one UNMAP notifier, whose role is to propagate the TLB invalidation at physical IOMMU level.

Those notifiers propagate the guest stage 1 mappings at physical level.

Also as there is no MAP event, the stage 2 mapping is not handled anymore by the vfio_iommu_map_notify notifier.

We register a prereg_listener whose role is to dma_(un)map the RAM memory regions. This programs the stage 2.

---

v1 -> v2:
- adapt to uapi changes
- pass the asid
- pass IOMMU_NOTIFIER_S1_CFG when initializing the config notifier

---
 hw/vfio/common.c | 167 ++++++++++++++++++++++++++++++++++++++---------
 1 file changed, 137 insertions(+), 30 deletions(-)
hw/vfio/common.c +137 -30
index 83f5f2263d..77bdb76ade 100644
@@ -349,6 +349,65 @@ static bool vfio_get_vaddr(IOMMUTLBEntry *iotlb, void **vaddr,
     return true;
 }
 
+/* Program the guest @cfg on physical IOMMU stage 1 (nested mode) */
+static void vfio_iommu_nested_notify(IOMMUNotifier *n,
+                                     IOMMUConfig *cfg)
+{
+    VFIOGuestIOMMU *giommu = container_of(n, VFIOGuestIOMMU, n);
+    VFIOContainer *container = giommu->container;
+    struct vfio_iommu_type1_bind_pasid_table info;
+    int ret;
+
+    info.argsz = sizeof(info);
+    info.flags = 0;
+    memcpy(&info.config, &cfg->pasid_cfg, sizeof(cfg->pasid_cfg));
+
+    ret = ioctl(container->fd, VFIO_IOMMU_BIND_PASID_TABLE, &info);
+    if (ret) {
+        error_report("%s: failed to pass S1 config to the host (%d)",
+                     __func__, ret);
+    }
+}
+
+/* Propagate a guest invalidation downto the physical IOMMU (nested mode) */
+static void vfio_iommu_unmap_notify(IOMMUNotifier *n, IOMMUTLBEntry *iotlb)
+{
+    VFIOGuestIOMMU *giommu = container_of(n, VFIOGuestIOMMU, n);
+    hwaddr start = iotlb->iova + giommu->iommu_offset;
+
+    VFIOContainer *container = giommu->container;
+    struct vfio_iommu_type1_cache_invalidate ustruct;
+    int ret;
+
+    assert(iotlb->perm == IOMMU_NONE);
+
+    ustruct.argsz = sizeof(ustruct);
+    ustruct.flags = 0;
+    ustruct.info.hdr.version = TLB_INV_HDR_VERSION_1;
+    ustruct.info.hdr.type = IOMMU_INV_TYPE_TLB;
+    ustruct.info.granularity = IOMMU_INV_NR_GRANU;
+    ustruct.info.flags = IOMMU_INVALIDATE_GLOBAL_PAGE;
+    /* 2^size of 4K pages, 0 for 4k, 9 for 2MB, etc. */
+    ustruct.info.size = ctz64(~iotlb->addr_mask) - 12;
+    /*
+     * TODO: at the moment we invalidate the whole ASID instead
+     * of invalidating the given nb_pages (nb_pages = 0):
+     * mask covering the whole GPA range is observed: in this case we shall
+     * invalidate the whole ASID (NH_ASID) and not induce storm of
+     * NH_VA commands.
+     */
+    ustruct.info.nr_pages = 0;
+    ustruct.info.addr = start;
+    ustruct.info.arch_id = iotlb->arch_id;
+
+    ret = ioctl(container->fd, VFIO_IOMMU_CACHE_INVALIDATE, &ustruct);
+    if (ret) {
+        error_report("%s: failed to invalidate CACHE for 0x%"PRIx64
+                     " mask=0x%"PRIx64" (%d)",
+                     __func__, start, iotlb->addr_mask, ret);
+    }
+}
+
 static void vfio_iommu_map_notify(IOMMUNotifier *n, IOMMUTLBEntry *iotlb)
 {
     VFIOGuestIOMMU *giommu = container_of(n, VFIOGuestIOMMU, n);
@@ -533,6 +592,32 @@ static void vfio_dma_unmap_ram_section(VFIOContainer *container,
     }
 }
 
+static void vfio_prereg_listener_region_add(MemoryListener *listener,
+                                            MemoryRegionSection *section)
+{
+    VFIOContainer *container =
+        container_of(listener, VFIOContainer, prereg_listener);
+
+    if (!memory_region_is_ram(section->mr)) {
+        return;
+    }
+
+    vfio_dma_map_ram_section(container, section);
+
+}
+static void vfio_prereg_listener_region_del(MemoryListener *listener,
+                                     MemoryRegionSection *section)
+{
+    VFIOContainer *container =
+        container_of(listener, VFIOContainer, prereg_listener);
+
+    if (!memory_region_is_ram(section->mr)) {
+        return;
+    }
+
+    vfio_dma_unmap_ram_section(container, section);
+}
+
 static void vfio_listener_region_add(MemoryListener *listener,
                                      MemoryRegionSection *section)
 {
@@ -541,7 +626,6 @@ static void vfio_listener_region_add(MemoryListener *listener,
     Int128 llend;
     int ret;
     VFIOHostDMAWindow *hostwin;
-    bool hostwin_found;
 
     if (vfio_listener_skipped_section(section)) {
         trace_vfio_listener_region_add_skip(
@@ -618,26 +702,10 @@ static void vfio_listener_region_add(MemoryListener *listener,
 #endif
     }
 
-    hostwin_found = false;
-    QLIST_FOREACH(hostwin, &container->hostwin_list, hostwin_next) {
-        if (hostwin->min_iova <= iova && end <= hostwin->max_iova) {
-            hostwin_found = true;
-            break;
-        }
-    }
-
-    if (!hostwin_found) {
-        error_report("vfio: IOMMU container %p can't map guest IOVA region"
-                     " 0x%"HWADDR_PRIx"..0x%"HWADDR_PRIx,
-                     container, iova, end);
-        ret = -EFAULT;
-        goto fail;
-    }
-
     memory_region_ref(section->mr);
 
     if (memory_region_is_iommu(section->mr)) {
-        VFIOGuestIOMMU *giommu;
+        VFIOGuestIOMMU *giommu = NULL;
         IOMMUMemoryRegion *iommu_mr = IOMMU_MEMORY_REGION(section->mr);
         hwaddr offset;
         int iommu_idx;
@@ -652,21 +720,40 @@ static void vfio_listener_region_add(MemoryListener *listener,
 
         offset = section->offset_within_address_space -
                     section->offset_within_region;
-        giommu = vfio_alloc_guest_iommu(container, iommu_mr, offset);
-
         llend = int128_add(int128_make64(section->offset_within_region),
                            section->size);
         llend = int128_sub(llend, int128_one());
         iommu_idx = memory_region_iommu_attrs_to_index(iommu_mr,
                                                        MEMTXATTRS_UNSPECIFIED);
-        iommu_iotlb_notifier_init(&giommu->n, vfio_iommu_map_notify,
-                                  IOMMU_NOTIFIER_IOTLB_ALL,
-                                  section->offset_within_region,
-                                  int128_get64(llend),
-                                  iommu_idx);
-        QLIST_INSERT_HEAD(&container->giommu_list, giommu, giommu_next);
 
-        memory_region_register_iommu_notifier(section->mr, &giommu->n);
+        if (container->iommu_type == VFIO_TYPE1_NESTING_IOMMU) {
+            /* Config notifier to propagate guest stage 1 config changes */
+            giommu = vfio_alloc_guest_iommu(container, iommu_mr, offset);
+            iommu_config_notifier_init(&giommu->n, vfio_iommu_nested_notify,
+                                       IOMMU_NOTIFIER_PASID_CFG, iommu_idx);
+            QLIST_INSERT_HEAD(&container->giommu_list, giommu, giommu_next);
+            memory_region_register_iommu_notifier(section->mr, &giommu->n);
+
+            /* IOTLB unmap notifier to propagate guest IOTLB invalidations */
+            giommu = vfio_alloc_guest_iommu(container, iommu_mr, offset);
+            iommu_iotlb_notifier_init(&giommu->n, vfio_iommu_unmap_notify,
+                                      IOMMU_NOTIFIER_UNMAP,
+                                      section->offset_within_region,
+                                      int128_get64(llend),
+                                      iommu_idx);
+            QLIST_INSERT_HEAD(&container->giommu_list, giommu, giommu_next);
+            memory_region_register_iommu_notifier(section->mr, &giommu->n);
+        } else {
+            /* MAP/UNMAP IOTLB notifier */
+            giommu = vfio_alloc_guest_iommu(container, iommu_mr, offset);
+            iommu_iotlb_notifier_init(&giommu->n, vfio_iommu_map_notify,
+                                      IOMMU_NOTIFIER_IOTLB_ALL,
+                                      section->offset_within_region,
+                                      int128_get64(llend),
+                                      iommu_idx);
+            QLIST_INSERT_HEAD(&container->giommu_list, giommu, giommu_next);
+            memory_region_register_iommu_notifier(section->mr, &giommu->n);
+        }
         memory_region_iommu_replay(giommu->iommu, &giommu->n);
 
         return;
@@ -679,7 +766,7 @@ static void vfio_listener_region_add(MemoryListener *listener,
     }
     return;
 
-fail:
+ fail:
     if (memory_region_is_ram_device(section->mr)) {
         error_report("failed to vfio_dma_map. pci p2p may not work");
         return;
@@ -763,15 +850,21 @@ static void vfio_listener_region_del(MemoryListener *listener,
     }
 }
 
-static const MemoryListener vfio_memory_listener = {
+static MemoryListener vfio_memory_listener = {
     .region_add = vfio_listener_region_add,
     .region_del = vfio_listener_region_del,
 };
 
+static MemoryListener vfio_memory_prereg_listener = {
+    .region_add = vfio_prereg_listener_region_add,
+    .region_del = vfio_prereg_listener_region_del,
+};
+
 static void vfio_listener_release(VFIOContainer *container)
 {
     memory_listener_unregister(&container->listener);
-    if (container->iommu_type == VFIO_SPAPR_TCE_v2_IOMMU) {
+    if (container->iommu_type == VFIO_SPAPR_TCE_v2_IOMMU ||
+        container->iommu_type == VFIO_TYPE1_NESTING_IOMMU) {
         memory_listener_unregister(&container->prereg_listener);
     }
 }
@@ -1262,6 +1355,20 @@ static int vfio_connect_container(VFIOGroup *group, AddressSpace *as,
         }
         vfio_host_win_add(container, 0, (hwaddr)-1, info.iova_pgsizes);
         container->pgsizes = info.iova_pgsizes;
+
+        if (container->iommu_type == VFIO_TYPE1_NESTING_IOMMU) {
+            container->prereg_listener = vfio_memory_prereg_listener;
+
+            memory_listener_register(&container->prereg_listener,
+                                     &address_space_memory);
+            if (container->error) {
+                memory_listener_unregister(&container->prereg_listener);
+                ret = container->error;
+                error_setg(errp,
+                    "RAM memory listener initialization failed for container");
+                goto free_container_exit;
+            }
+        }
         break;
     }
     case VFIO_SPAPR_TCE_v2_IOMMU:
Signature · 1 line
2.17.1
author
#22 lore raw

RFC v2 20/28 hw/vfio/common: Register MAP notifier for MSI binding

In reply to Eric Auger

Register a MAP notifier to propage MSI stage 1 bindings to the host. When the notifier gets called, we pass the guest stage 1 MSI binding to the host. The host can then build a S2 binding whose entry is the guest MSI doorbell GPA.

---
 hw/vfio/common.c | 29 +++++++++++++++++++++++++++++
 1 file changed, 29 insertions(+)
hw/vfio/common.c +29 -0
index 77bdb76ade..172ddd396f 100644
@@ -408,6 +408,26 @@ static void vfio_iommu_unmap_notify(IOMMUNotifier *n, IOMMUTLBEntry *iotlb)
     }
 }
 
+static void vfio_iommu_msi_map_notify(IOMMUNotifier *n, IOMMUTLBEntry *iotlb)
+{
+    VFIOGuestIOMMU *giommu = container_of(n, VFIOGuestIOMMU, n);
+    VFIOContainer *container = giommu->container;
+    struct vfio_iommu_type1_bind_guest_msi ustruct;
+    int ret;
+
+    ustruct.argsz = sizeof(struct vfio_iommu_type1_bind_guest_msi);
+    ustruct.flags = 0;
+    ustruct.binding.iova = iotlb->iova;
+    ustruct.binding.gpa = iotlb->translated_addr;
+    ustruct.binding.granule = ctz64(~iotlb->addr_mask);
+
+    ret = ioctl(container->fd, VFIO_IOMMU_BIND_MSI , &ustruct);
+    if (ret) {
+        error_report("%s: failed to pass MSI binding (%d)",
+                     __func__, ret);
+    }
+}
+
 static void vfio_iommu_map_notify(IOMMUNotifier *n, IOMMUTLBEntry *iotlb)
 {
     VFIOGuestIOMMU *giommu = container_of(n, VFIOGuestIOMMU, n);
@@ -743,6 +763,15 @@ static void vfio_listener_region_add(MemoryListener *listener,
                                       iommu_idx);
             QLIST_INSERT_HEAD(&container->giommu_list, giommu, giommu_next);
             memory_region_register_iommu_notifier(section->mr, &giommu->n);
+
+            giommu = vfio_alloc_guest_iommu(container, iommu_mr, offset);
+            iommu_iotlb_notifier_init(&giommu->n, vfio_iommu_msi_map_notify,
+                                      IOMMU_NOTIFIER_MAP,
+                                      section->offset_within_region,
+                                      int128_get64(llend),
+                                      iommu_idx);
+            QLIST_INSERT_HEAD(&container->giommu_list, giommu, giommu_next);
+            memory_region_register_iommu_notifier(section->mr, &giommu->n);
         } else {
             /* MAP/UNMAP IOTLB notifier */
             giommu = vfio_alloc_guest_iommu(container, iommu_mr, offset);
Signature · 1 line
2.17.1
author
#23 lore raw

RFC v2 21/28 target/arm/kvm: Notifies IOMMU on MSI stage 1 binding

In reply to Eric Auger

When the MSI route is setup, we know the MSI IOVA and the doorbell GPA . At that point we can communicate this guest stage 1 binding to the host. Then the host will be able to construct a stage 2 binding taking as input address the doorbell GPA.

We also directly use the iommu memory region translate() callback as the addr_mask is returned in IOTLB entry. address_space_translate does not return this information.

---

TODO: access to as->root field may be cleaned later on

---
 target/arm/kvm.c | 46 ++++++++++++++++++++--------------------------
 1 file changed, 20 insertions(+), 26 deletions(-)
target/arm/kvm.c +20 -26
index 65f867d569..6f905215b8 100644
@@ -661,41 +661,35 @@ int kvm_arch_fixup_msi_route(struct kvm_irq_routing_entry *route,
                              uint64_t address, uint32_t data, PCIDevice *dev)
 {
     AddressSpace *as = pci_device_iommu_address_space(dev);
-    hwaddr xlat, len, doorbell_gpa;
-    MemoryRegionSection mrs;
-    MemoryRegion *mr;
-    int ret = 1;
+    IOMMUMemoryRegionClass *imrc;
+    IOMMUMemoryRegion *iommu_mr;
+    IOMMUTLBEntry entry;
 
     if (as == &address_space_memory) {
         return 0;
     }
 
+    iommu_mr = IOMMU_MEMORY_REGION(as->root);
+    imrc = memory_region_get_iommu_class_nocheck(iommu_mr);
+
     /* MSI doorbell address is translated by an IOMMU */
 
     rcu_read_lock();
-    mr = address_space_translate(as, address, &xlat, &len, true,
-                                 MEMTXATTRS_UNSPECIFIED);
-    if (!mr) {
-        goto unlock;
-    }
-    mrs = memory_region_find(mr, xlat, 1);
-    if (!mrs.mr) {
-        goto unlock;
-    }
-
-    doorbell_gpa = mrs.offset_within_address_space;
-    memory_region_unref(mrs.mr);
-
-    route->u.msi.address_lo = doorbell_gpa;
-    route->u.msi.address_hi = doorbell_gpa >> 32;
-
-    trace_kvm_arm_fixup_msi_route(address, doorbell_gpa);
-
-    ret = 0;
-
-unlock:
+    entry = imrc->translate(iommu_mr, address, IOMMU_WO, 0);
     rcu_read_unlock();
-    return ret;
+
+    if (entry.perm == IOMMU_NONE) {
+        return -ENOENT;
+    }
+
+    route->u.msi.address_lo = entry.translated_addr;
+    route->u.msi.address_hi = entry.translated_addr >> 32;
+
+    memory_region_iotlb_notify_iommu(iommu_mr, 0, entry);
+
+    trace_kvm_arm_fixup_msi_route(address, entry.translated_addr);
+
+    return 0;
 }
 
 int kvm_arch_add_msi_route_post(struct kvm_irq_routing_entry *route,
Signature · 1 line
2.17.1
author
#24 lore raw

RFC v2 22/28 vfio/pci: Always set up MSI route before enabling vectors

In reply to Eric Auger

As we enable the vectors, we shall have an MSI route setup. The notification of the stage 1 binding is done on MSI route setup.

---
 hw/vfio/pci.c | 1 +
 1 file changed, 1 insertion(+)
hw/vfio/pci.c +1 -0
index 866f0deeb7..842b0921d4 100644
@@ -522,6 +522,7 @@ static int vfio_msix_vector_do_use(PCIDevice *pdev, unsigned int nr,
     if (vdev->nr_vectors < nr + 1) {
         vfio_disable_irqindex(&vdev->vbasedev, VFIO_PCI_MSIX_IRQ_INDEX);
         vdev->nr_vectors = nr + 1;
+        vfio_add_kvm_msi_virq(vdev, vector, nr, true);
         ret = vfio_enable_vectors(vdev, true);
         if (ret) {
             error_report("vfio: failed to enable vectors, %d", ret);
Signature · 1 line
2.17.1
author
#25 lore raw

RFC v2 23/28 hw/arm/smmuv3: Remove warning about unsupported MAP notifiers

In reply to Eric Auger

SMMUv3 now is integrated with VFIO by enable the 2 stages of the physical SMMUv3. This relies on a MAP notifier for MSI stage 1 binding notification. So let's remove this warning.

---
 hw/arm/smmuv3.c | 8 --------
 1 file changed, 8 deletions(-)
hw/arm/smmuv3.c +0 -8
index 1d8deae37f..c6dec63f07 100644
@@ -1504,14 +1504,6 @@ static void smmuv3_notify_flag_changed(IOMMUMemoryRegion *iommu,
     SMMUNotifierNode *node = NULL;
     SMMUNotifierNode *next_node = NULL;
 
-    if (new & IOMMU_NOTIFIER_MAP) {
-        int bus_num = pci_bus_num(sdev->bus);
-        PCIDevice *pcidev = pci_find_device(sdev->bus, bus_num, sdev->devfn);
-
-        warn_report("SMMUv3 does not support notification on MAP: "
-                     "device %s will not function properly", pcidev->name);
-    }
-
     if (old == IOMMU_NOTIFIER_NONE) {
         trace_smmuv3_notify_flag_add(iommu->parent_obj.name);
         node = g_malloc0(sizeof(*node));
Signature · 1 line
2.17.1
author
#26 lore raw

RFC v2 24/28 memory: Introduce IOMMU_NOTIFIER_INIT_CFG IOMMU Config Notifier

In reply to Eric Auger

This patch adds a new IOMMU config notifier. It aims at configuring the fault reporting from host to guest.

---

I acknowledge I am not a big fan of having a vfio uapi struct referenced in IOMMUConfig. However this config really sets something at VFIO layer. Also I may rename IOMMU_NOTIFIER_INIT_CFG into IOMMU_NOTIFIER_FAULT_CONFIG. Globally it is also questionnable at this stage if such a notifier really is requested. I devised that to allow the SMMU to pass a fifo size to the kernel. This size can be aligned to the size as seen/set by the guest. However for unrecoverable errors we may consider that having an arbitrary size determined by vfio/common.c can be sufficient?

---
 include/exec/memory.h | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)
include/exec/memory.h +6 -1
index 93150e1450..f54c39b248 100644
@@ -28,6 +28,7 @@
 #include "hw/qdev-core.h"
 #ifdef CONFIG_LINUX
 #include <linux/iommu.h>
+#include <linux/vfio.h>
 #endif
 
 #define RAM_ADDR_INVALID (~(ram_addr_t)0)
@@ -82,6 +83,7 @@ typedef struct IOMMUConfig {
     union {
 #ifdef __linux__
         struct iommu_pasid_table_config pasid_cfg;
+        struct vfio_iommu_type1_guest_fault_config fault_cfg;
 #endif
           };
 } IOMMUConfig;
@@ -98,10 +100,13 @@ typedef enum {
     IOMMU_NOTIFIER_MAP = 0x2,
     /* Notify stage 1 config changes */
     IOMMU_NOTIFIER_PASID_CFG = 0x4,
+    /* Notify IOMMU initial setup */
+    IOMMU_NOTIFIER_INIT_CFG = 0x8,
 } IOMMUNotifierFlag;
 
 #define IOMMU_NOTIFIER_IOTLB_ALL (IOMMU_NOTIFIER_MAP | IOMMU_NOTIFIER_UNMAP)
-#define IOMMU_NOTIFIER_CONFIG_ALL (IOMMU_NOTIFIER_PASID_CFG)
+#define IOMMU_NOTIFIER_CONFIG_ALL (IOMMU_NOTIFIER_PASID_CFG | \
+                                   IOMMU_NOTIFIER_INIT_CFG)
 
 struct IOMMUNotifier;
 struct IOMMUConfig;
Signature · 1 line
2.17.1
author
#27 lore raw

RFC v2 25/28 memory: Introduce IOMMU Memory Region inject_faults API

In reply to Eric Auger

This new API allows to inject @count iommu_faults into the IOMMU memory region.

---
 include/exec/memory.h | 26 ++++++++++++++++++++++++++
 memory.c              | 12 ++++++++++++
 2 files changed, 38 insertions(+)
include/exec/memory.h +26 -0
index f54c39b248..45bcca2081 100644
@@ -391,6 +391,20 @@ typedef struct IOMMUMemoryRegionClass {
      * @iommu: the IOMMUMemoryRegion
      */
     int (*num_indexes)(IOMMUMemoryRegion *iommu);
+
+#ifdef CONFIG_LINUX
+    /* Inject @count faults into the IOMMU memory region
+     *
+     * Optional method: if this method is not provided, then
+     * memory_region_injection_faults() will return -ENOENT
+     *
+     * @iommu: the IOMMU memory region to inject the faults in
+     * @count: number of faults to inject
+     * @buf: fault buffer
+     */
+    int (*inject_faults)(IOMMUMemoryRegion *iommu, int count,
+                         struct iommu_fault *buf);
+#endif
 } IOMMUMemoryRegionClass;
 
 typedef struct CoalescedMemoryRange CoalescedMemoryRange;
@@ -1203,6 +1217,18 @@ int memory_region_iommu_attrs_to_index(IOMMUMemoryRegion *iommu_mr,
  */
 int memory_region_iommu_num_indexes(IOMMUMemoryRegion *iommu_mr);
 
+#ifdef CONFIG_LINUX
+/**
+ * memory_region_inject_faults : inject @count faults stored in @buf
+ *
+ * @iommu_mr: the IOMMU memory region
+ * @count: number of faults to be injected
+ * @buf: buffer containing the faults
+ */
+int memory_region_inject_faults(IOMMUMemoryRegion *iommu_mr, int count,
+                                struct iommu_fault *buf);
+#endif
+
 /**
  * memory_region_name: get a memory region's name
  *
memory.c +12 -0
index 2c320bc14b..6ba8d31773 100644
@@ -1976,6 +1976,18 @@ int memory_region_iommu_num_indexes(IOMMUMemoryRegion *iommu_mr)
     return imrc->num_indexes(iommu_mr);
 }
 
+#ifdef CONFIG_LINUX
+int memory_region_inject_faults(IOMMUMemoryRegion *iommu_mr, int count,
+                                struct iommu_fault *buf)
+{
+    IOMMUMemoryRegionClass *imrc = IOMMU_MEMORY_REGION_GET_CLASS(iommu_mr);
+    if (!imrc->inject_faults) {
+        return -ENOENT;
+    }
+    return imrc->inject_faults(iommu_mr, count, buf);
+}
+#endif
+
 void memory_region_set_log(MemoryRegion *mr, bool log, unsigned client)
 {
     uint8_t mask = 1 << client;
Signature · 1 line
2.17.1
author
#28 lore raw

RFC v2 26/28 hw/vfio/common: Handle fault_handler

In reply to Eric Auger

We introduce a new IOMMU notifier, whose role is to register the fault notifier.

The patch also implements the userspace fault handler. When the eventfd is signalled, the fault handler injects the set of collected faults into the IOMMU memory region.

---
 hw/vfio/common.c              | 118 ++++++++++++++++++++++++++++++++++
 include/hw/vfio/vfio-common.h |   1 +
 2 files changed, 119 insertions(+)
hw/vfio/common.c +118 -0
index 172ddd396f..9548e962e5 100644
@@ -37,12 +37,16 @@
 #include "sysemu/kvm.h"
 #include "trace.h"
 #include "qapi/error.h"
+#include "qemu/event_notifier.h"
+#include "qemu/main-loop.h"
 
 struct vfio_group_head vfio_group_list =
     QLIST_HEAD_INITIALIZER(vfio_group_list);
 struct vfio_as_head vfio_address_spaces =
     QLIST_HEAD_INITIALIZER(vfio_address_spaces);
 
+#define MAX_QUERIED_FAULT_EVENTS 10
+
 #ifdef CONFIG_KVM
 /*
  * We have a single VFIO pseudo device per KVM VM.  Once created it lives
@@ -349,6 +353,111 @@ static bool vfio_get_vaddr(IOMMUTLBEntry *iotlb, void **vaddr,
     return true;
 }
 
+/*
+ * At the moment we retrieve MAX_QUERIED_FAULT_EVENTS events
+ * TODO: loop until the ioctl returns count = 0
+ */
+static void vfio_iommu_fault_handler(void *data)
+{
+    VFIOGuestIOMMU *giommu = (VFIOGuestIOMMU *)data;
+    IOMMUMemoryRegion *iommu = giommu->iommu;
+    struct vfio_iommu_type1_get_fault_events *ustruct;
+    size_t fault_buffer_size =
+        MAX_QUERIED_FAULT_EVENTS * sizeof(struct iommu_fault);
+    size_t argsz = sizeof(*ustruct) + fault_buffer_size;
+    int ret;
+
+    ustruct = g_malloc0(argsz);
+    ustruct->argsz = argsz;
+    ustruct->count = 0;
+
+    ret = ioctl(giommu->container->fd, VFIO_IOMMU_GET_FAULT_EVENTS, ustruct);
+    if (ret) {
+        error_report("%s: failed to get pending faults (%d)",
+                     __func__, ret);
+    }
+
+    assert(ustruct->count > 0);
+    memory_region_inject_faults(iommu, ustruct->count, ustruct->events);
+
+    g_free(ustruct);
+
+    ret = event_notifier_test_and_clear(giommu->fault_notifier);
+    if (!ret) {
+        error_report("Error when clearing fd=%d (ret = %d)",
+                     event_notifier_get_fd(giommu->fault_notifier), ret);
+    }
+}
+
+static void
+vfio_iommu_fault_handler_register(IOMMUNotifier *n, IOMMUConfig *cfg)
+
+{
+    VFIOGuestIOMMU *giommu = container_of(n, VFIOGuestIOMMU, n);
+    VFIOContainer *container = giommu->container;
+    struct vfio_iommu_type1_set_fault_eventfd info;
+    int ret;
+
+    info.argsz = sizeof(info);
+    info.flags = 0;
+
+    giommu->fault_notifier = g_malloc0(sizeof(EventNotifier));
+    ret = event_notifier_init(giommu->fault_notifier, 0);
+    if (ret) {
+        error_report("%s: failed to init fault eventfd (%d)",
+                     __func__, ret);
+        goto out;
+    }
+
+    info.eventfd = event_notifier_get_fd(giommu->fault_notifier);
+    qemu_set_fd_handler(info.eventfd, vfio_iommu_fault_handler, NULL, giommu);
+
+    memcpy(&info.config, &cfg->fault_cfg, sizeof(cfg->fault_cfg));
+
+    ret = ioctl(container->fd, VFIO_IOMMU_SET_FAULT_EVENTFD, &info);
+    if (ret) {
+        error_report("%s: failed to setup iommu fault propagation (%d)",
+                     __func__, ret);
+        goto cleanup;
+    }
+    return;
+cleanup:
+    qemu_set_fd_handler(info.eventfd, NULL, NULL, NULL);
+    event_notifier_cleanup(giommu->fault_notifier);
+out:
+    g_free(giommu->fault_notifier);
+}
+
+static void vfio_iommu_fault_handler_unregister(IOMMUNotifier *n)
+{
+    VFIOGuestIOMMU *giommu = container_of(n, VFIOGuestIOMMU, n);
+    VFIOContainer *container = giommu->container;
+    struct vfio_iommu_type1_set_fault_eventfd info;
+    int eventfd, ret;
+
+    if (!(n->notifier_flags & IOMMU_NOTIFIER_INIT_CFG) ||
+        !giommu->fault_notifier) {
+        return;
+    }
+
+    eventfd = event_notifier_get_fd(giommu->fault_notifier);
+    if (eventfd < 0) {
+        return;
+    }
+
+    info.argsz = sizeof(info);
+    info.flags = 0;
+    info.eventfd = -1;
+    ret = ioctl(container->fd, VFIO_IOMMU_SET_FAULT_EVENTFD, &info);
+    if (ret) {
+        error_report("%s: failed to stop iommu fault propagation (%d)",
+                     __func__, ret);
+    }
+    qemu_set_fd_handler(eventfd, NULL, NULL, NULL);
+    event_notifier_cleanup(giommu->fault_notifier);
+    g_free(giommu->fault_notifier);
+}
+
 /* Program the guest @cfg on physical IOMMU stage 1 (nested mode) */
 static void vfio_iommu_nested_notify(IOMMUNotifier *n,
                                      IOMMUConfig *cfg)
@@ -754,6 +863,14 @@ static void vfio_listener_region_add(MemoryListener *listener,
             QLIST_INSERT_HEAD(&container->giommu_list, giommu, giommu_next);
             memory_region_register_iommu_notifier(section->mr, &giommu->n);
 
+            /* Config notifier to register fault handler */
+            giommu = vfio_alloc_guest_iommu(container, iommu_mr, offset);
+            iommu_config_notifier_init(&giommu->n,
+                                       vfio_iommu_fault_handler_register,
+                                       IOMMU_NOTIFIER_INIT_CFG, iommu_idx);
+            QLIST_INSERT_HEAD(&container->giommu_list, giommu, giommu_next);
+            memory_region_register_iommu_notifier(section->mr, &giommu->n);
+
             /* IOTLB unmap notifier to propagate guest IOTLB invalidations */
             giommu = vfio_alloc_guest_iommu(container, iommu_mr, offset);
             iommu_iotlb_notifier_init(&giommu->n, vfio_iommu_unmap_notify,
@@ -846,6 +963,7 @@ static void vfio_listener_region_del(MemoryListener *listener,
                 } else if (is_iommu_config_notifier(&giommu->n)) {
                     memory_region_unregister_iommu_notifier(section->mr,
                                                             &giommu->n);
+                    vfio_iommu_fault_handler_unregister(&giommu->n);
                 }
                 QLIST_REMOVE(giommu, giommu_next);
                 g_free(giommu);
include/hw/vfio/vfio-common.h +1 -0
index 821def0565..db9cd93d77 100644
@@ -91,6 +91,7 @@ typedef struct VFIOGuestIOMMU {
     hwaddr iommu_offset;
     IOMMUNotifier n;
     QLIST_ENTRY(VFIOGuestIOMMU) giommu_next;
+    EventNotifier *fault_notifier;
 } VFIOGuestIOMMU;
 
 typedef struct VFIOHostDMAWindow {
Signature · 1 line
2.17.1
author
#29 lore raw

RFC v2 27/28 hw/arm/smmuv3: Init fault handling

In reply to Eric Auger

We configure the kernel fault event fifo when the guest sizes the event queue.

---

At the moment we arbitrarily cap the fifo size to 2^5 events

---
 hw/arm/smmuv3.c | 20 ++++++++++++++++++++
 1 file changed, 20 insertions(+)
hw/arm/smmuv3.c +20 -0
index c6dec63f07..ae27cfdfa0 100644
@@ -1066,6 +1066,25 @@ static int smmuv3_cmdq_consume(SMMUv3State *s)
     return 0;
 }
 
+static int smmuv3_init_fault_queues(SMMUv3State *s)
+{
+    SMMUState *base = &s->smmu_state;
+    SMMUNotifierNode *node;
+    IOMMUConfig config;
+    /* TODO: today we cap the shift to 5 to avoid the kfifo to become too big*/
+    int qs = MIN(5, s->eventq.log2size);
+
+    config.fault_cfg.qs = qs;
+
+    QLIST_FOREACH(node, &base->notifiers_list, next) {
+        IOMMUMemoryRegion *iommu_mr = &node->sdev->iommu;
+
+        memory_region_config_notify_iommu(iommu_mr, 0, IOMMU_NOTIFIER_INIT_CFG,
+                                          &config);
+    }
+    return 0;
+}
+
 static MemTxResult smmu_writell(SMMUv3State *s, hwaddr offset,
                                uint64_t data, MemTxAttrs attrs)
 {
@@ -1089,6 +1108,7 @@ static MemTxResult smmu_writell(SMMUv3State *s, hwaddr offset,
         if (s->eventq.log2size > SMMU_EVENTQS) {
             s->eventq.log2size = SMMU_EVENTQS;
         }
+        smmuv3_init_fault_queues(s);
         return MEMTX_OK;
     case A_EVENTQ_IRQ_CFG0:
         s->eventq_irq_cfg0 = data;
Signature · 1 line
2.17.1
author
#30 lore raw

RFC v2 28/28 hw/arm/smmuv3: Implement fault injection

In reply to Eric Auger

We convert iommu_fault structs received from the kernel into the data struct used by the emulation code and record the evnts into the virtual event queue.

---

Exhaustive mapping remains to be done

---
 hw/arm/smmuv3.c | 76 +++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 76 insertions(+)
hw/arm/smmuv3.c +76 -0
index ae27cfdfa0..7ecc6c9669 100644
@@ -1561,6 +1561,81 @@ smmuv3_replay(IOMMUMemoryRegion *iommu_mr, IOMMUNotifier *n)
 {
 }
 
+static inline int
+smmuv3_inject_faults(IOMMUMemoryRegion *iommu_mr, int count,
+                     struct iommu_fault *buf)
+{
+    SMMUDevice *sdev = container_of(iommu_mr, SMMUDevice, iommu);
+    SMMUv3State *s3 = sdev->smmu;
+    uint32_t sid = smmu_get_sid(sdev);
+    int i;
+
+    for (i = 0; i < count; i++) {
+        SMMUEventInfo info = {};
+
+        if (buf[i].type != IOMMU_FAULT_DMA_UNRECOV) {
+            continue;
+        }
+
+       info.sid = sid;
+
+        switch (buf[i].reason) {
+        case IOMMU_FAULT_REASON_UNKNOWN:
+        case IOMMU_FAULT_REASON_INTERNAL:
+            break;
+        case IOMMU_FAULT_REASON_PASID_FETCH:
+            info.type = SMMU_EVT_F_CD_FETCH;
+            break;
+        case IOMMU_FAULT_REASON_DEVICE_CONTEXT_FETCH:
+            info.type = SMMU_EVT_F_STE_FETCH;
+            info.u.f_cd_fetch.addr = buf[i].fetch_addr;
+            break;
+        case IOMMU_FAULT_REASON_BAD_PASID_ENTRY:
+            info.type = SMMU_EVT_C_BAD_CD;
+            /* TODO further fill info.u.c_bad_cd */
+            break;
+        case IOMMU_FAULT_REASON_BAD_DEVICE_CONTEXT_ENTRY:
+            info.type = SMMU_EVT_C_BAD_STE;
+            /* TODO further fill info.u.f_ste_fetch */
+            break;
+        case IOMMU_FAULT_REASON_PASID_INVALID:
+            info.type = SMMU_EVT_C_BAD_SUBSTREAMID;
+            /* TODO further fill info.u.c_bad_substream */
+            break;
+        case IOMMU_FAULT_REASON_SOURCEID_INVALID:
+            info.type = SMMU_EVT_C_BAD_STREAMID;
+            /* TODO further fill info.u.c_bad_streamid */
+            break;
+        case IOMMU_FAULT_REASON_WALK_EABT:
+            info.type = SMMU_EVT_F_WALK_EABT;
+            info.u.f_walk_eabt.addr = buf[i].addr;
+            info.u.f_walk_eabt.addr2 = buf[i].fetch_addr;
+            break;
+        case IOMMU_FAULT_REASON_PTE_FETCH:
+            info.type = SMMU_EVT_F_TRANSLATION;
+            info.u.f_translation.addr = buf[i].addr;
+            break;
+        case IOMMU_FAULT_REASON_PERMISSION:
+            info.type = SMMU_EVT_F_PERMISSION;
+            info.u.f_permission.addr = buf[i].addr;
+            break;
+        case IOMMU_FAULT_REASON_ACCESS:
+            info.type = SMMU_EVT_F_ACCESS;
+            info.u.f_access.addr = buf[i].addr;
+            break;
+        case IOMMU_FAULT_REASON_OOR_ADDRESS:
+            info.type = SMMU_EVT_F_ADDR_SIZE;
+            info.u.f_addr_size.addr = buf[i].addr;
+            break;
+        default:
+            break;
+        }
+
+        smmuv3_record_event(s3, &info);
+    }
+    return 0;
+}
+
 static void smmuv3_iommu_memory_region_class_init(ObjectClass *klass,
                                                   void *data)
 {
@@ -1570,6 +1645,7 @@ static void smmuv3_iommu_memory_region_class_init(ObjectClass *klass,
     imrc->notify_flag_changed = smmuv3_notify_flag_changed;
     imrc->get_attr = smmuv3_get_attr;
     imrc->replay = smmuv3_replay;
+    imrc->inject_faults = smmuv3_inject_faults;
 }
 
 static const TypeInfo smmuv3_type_info = {
Signature · 1 line
2.17.1
#31 lore raw
In reply to Eric Auger

Hi Eric,

Quoted 39 lines

From: Eric Auger [mailto:[email protected]]
Sent: Friday, September 21, 2018 4:18 PM
Subject: [RFC v2 00/28] vSMMUv3/pSMMUv3 2 stage VFIO integration

Up to now vSMMUv3 has not been integrated with VFIO. VFIO integration requires to program the physical IOMMU consistently with the guest mappings. However, as opposed to VTD, SMMUv3 has no "Caching Mode" which allows easy trapping of guest mappings. This means the vSMMUV3 cannot use the same VFIO integration as VTD.

However SMMUv3 has 2 translation stages. This was devised with virtualization use case in mind where stage 1 is "owned" by the guest whereas the host uses stage 2 for VM isolation.

This series sets up this nested translation stage. It only works if there is one physical SMMUv3 used along with QEMU vSMMUv3 (in other words, it does not work if there is a physical SMMUv2).

The series uses a new kernel user API [1], still under definition.

- We force the host to use stage 2 instead of stage 1, when we detect a vSMMUV3 is behind a VFIO device. For a VFIO device without any virtual IOMMU, we still use stage 1 as many existing SMMUs expect this behavior.
- We introduce new IOTLB "config" notifiers, requested to notify changes in the config of a given iommu memory region. So now we have notifiers for IOTLB changes and config changes.
- vSMMUv3 calls config notifiers when STE (Stream Table Entries) are updated by the guest.
- We implement a specific UNMAP notifier that conveys guest IOTLB invalidations to the host
- We implement a new MAP notifiers only used for MSI IOVAs so that the host can build a nested stage translation for MSI IOVAs
- As the legacy MAP notifier is not called anymore, we must make sure stage 2 mappings are set. This is achieved through another memory listener.
- Physical SMMUs faults are reported to the guest via en eventfd mechanism and reinjected into this latter.

Quoted 3 lines

Note: some iommu memory notifier rework related patches are close to those previously published by Peter and Liu. I will be pleased to add their Signed-off-by if they agree/wish.

Yeah, feel free to add mine if it's originated from our previous work.

BTW. Curiously, are you planning to implement all vIOMMU related operations through MemoryRegion notifiers? Honestly, I did it in such way in early RFC for vSVA work. However, we encountered two issues at that time. First, how to check whether the notifier should be registered. Second, there are cases in which the vfio_listener_region_add is not triggered but vIOMMU exists. Details can be got by the link below:
(http://lists.gnu.org/archive/html/qemu-devel/2018-03/msg00078.html)

As thus, we had some discussions in community. Last time, PCIPASIDOps was proposed. It is to add callbacks in PCIDevice. VFIO would register its implementations in vfio_realize(). Supposedly, pasid_table_bind, page_table_bind, sva_tlb_invalidation_passdown and other vIOMMU related operations can be done in such way. The sample patch below may show how it looks like. (the full patch is in my sandbox, planned to send out with Scalable Mode emulation patch).

Sample patch:
include/hw/pci/pci.h:
+typedef struct PCIPASIDOps PCIPASIDOps;
+struct PCIPASIDOps {
+ void (*pasid_bind_table)(PCIBus *bus, int32_t devfn,
+ struct pasid_table_config *ptbl_cfg);
+ void (*pasid_invalidate_extend_iotlb)(PCIBus *bus, int32_t devfn,
+ struct tlb_invalidate_info *inv_info);
+};

 @@ -350,6 +359,7 @@ struct PCIDevice {
      MSIVectorUseNotifier msix_vector_use_notifier;
      MSIVectorReleaseNotifier msix_vector_release_notifier;
      MSIVectorPollNotifier msix_vector_poll_notifier;

+ PCIPASIDOps *pasid_ops;
};

hw/pci/pci.c:
+void pci_setup_pasid_ops(PCIDevice *dev, PCIPASIDOps *ops)
+{
+ assert(ops && !dev->pasid_ops);
+ dev->pasid_ops = ops;
+}
+
+void pci_device_pasid_bind_table(PCIBus *bus, int32_t devfn,
+ struct pasid_table_config *ptbl_cfg)
+{
+ PCIDevice *dev;
+
+ if (!bus) {
+ return;
+ }
+
+ dev = bus->devices[devfn];
+ if (dev && dev->pasid_ops) {
+ dev->pasid_ops->pasid_bind_table(bus, devfn, ptbl_cfg);
+ }
+}

hw/vfio/pci.c:
+static PCIPASIDOps vfio_pci_pasid_ops = {
+ .pasid_bind_table = vfio_pci_device_pasid_bind_table,
+ .pasid_invalidate_extend_iotlb = vfio_pci_device_pasid_invalidate_eiotlb,
+};
+
static void vfio_realize(PCIDevice *pdev, Error **errp)

  {
      VFIOPCIDevice *vdev = DO_UPCAST(VFIOPCIDevice, pdev, pdev);
 @@ -3048,6 +3068,8 @@ static void vfio_realize(PCIDevice *pdev, Error **errp)
      vfio_register_req_notifier(vdev);
      vfio_setup_resetfn_quirk(vdev);

+ pci_setup_pasid_ops(pdev, &vfio_pci_pasid_ops);
+

      return;

Regards,
Yi Liu

author
#32 lore raw

Hi Yi,

Quoted 41 lines · Yi L

Hi Eric,

Quoted 39 lines

From: Eric Auger [mailto:[email protected]]
Sent: Friday, September 21, 2018 4:18 PM
Subject: [RFC v2 00/28] vSMMUv3/pSMMUv3 2 stage VFIO integration

Up to now vSMMUv3 has not been integrated with VFIO. VFIO integration requires to program the physical IOMMU consistently with the guest mappings. However, as opposed to VTD, SMMUv3 has no "Caching Mode" which allows easy trapping of guest mappings. This means the vSMMUV3 cannot use the same VFIO integration as VTD.

However SMMUv3 has 2 translation stages. This was devised with virtualization use case in mind where stage 1 is "owned" by the guest whereas the host uses stage 2 for VM isolation.

This series sets up this nested translation stage. It only works if there is one physical SMMUv3 used along with QEMU vSMMUv3 (in other words, it does not work if there is a physical SMMUv2).

The series uses a new kernel user API [1], still under definition.

- We force the host to use stage 2 instead of stage 1, when we detect a vSMMUV3 is behind a VFIO device. For a VFIO device without any virtual IOMMU, we still use stage 1 as many existing SMMUs expect this behavior.
- We introduce new IOTLB "config" notifiers, requested to notify changes in the config of a given iommu memory region. So now we have notifiers for IOTLB changes and config changes.
- vSMMUv3 calls config notifiers when STE (Stream Table Entries) are updated by the guest.
- We implement a specific UNMAP notifier that conveys guest IOTLB invalidations to the host
- We implement a new MAP notifiers only used for MSI IOVAs so that the host can build a nested stage translation for MSI IOVAs
- As the legacy MAP notifier is not called anymore, we must make sure stage 2 mappings are set. This is achieved through another memory listener.
- Physical SMMUs faults are reported to the guest via en eventfd mechanism and reinjected into this latter.

Quoted 5 lines
Quoted 3 lines

Note: some iommu memory notifier rework related patches are close to those previously published by Peter and Liu. I will be pleased to add their Signed-off-by if they agree/wish.

Yeah, feel free to add mine if it's originated from our previous work.

OK

Quoted 5 lines

BTW. Curiously, are you planning to implement all vIOMMU related operations through MemoryRegion notifiers? Honestly, I did it in such way in early RFC for vSVA work. However, we encountered two issues at that time. First, how to check whether the notifier should be registered.

On my side I think I resolved this by querying the iommu mr about the new IOMMU_ATTR_VFIO_NESTED IOMMU attribute in vfio_connect_container

See patches 5 and 6, 8

This tells me whether the nested mode must be setup and choose the right container->iommu_type which is then used in vfio_listener_region_add() to decide whether the specific notifiers mustd to be registered.

Quoted 3 lines

Second, there are cases in which the vfio_listener_region_add is not triggered but vIOMMU exists. Details can be got by the link below:
(http://lists.gnu.org/archive/html/qemu-devel/2018-03/msg00078.html)

Yes I remember this, due to the PT=1 case. On ARM we don't have this specificity hence this integration.

Quoted 8 lines

As thus, we had some discussions in community. Last time, PCIPASIDOps was proposed. It is to add callbacks in PCIDevice. VFIO would register its implementations in vfio_realize(). Supposedly, pasid_table_bind, page_table_bind, sva_tlb_invalidation_passdown and other vIOMMU related operations can be done in such way. The sample patch below may show how it looks like. (the full patch is in my sandbox, planned to send out with Scalable Mode emulation patch).

To be honest, I lost track of the series and did not see this PCIPASIDOps proposal. I will study whether this can fit my needs.

Thank you for the link!

Best Regards

Eric

Quoted 61 lines

Sample patch:
include/hw/pci/pci.h:
+typedef struct PCIPASIDOps PCIPASIDOps;
+struct PCIPASIDOps {
+ void (*pasid_bind_table)(PCIBus *bus, int32_t devfn,
+ struct pasid_table_config *ptbl_cfg);
+ void (*pasid_invalidate_extend_iotlb)(PCIBus *bus, int32_t devfn,
+ struct tlb_invalidate_info *inv_info);
+};

 @@ -350,6 +359,7 @@ struct PCIDevice {
      MSIVectorUseNotifier msix_vector_use_notifier;
      MSIVectorReleaseNotifier msix_vector_release_notifier;
      MSIVectorPollNotifier msix_vector_poll_notifier;

+ PCIPASIDOps *pasid_ops;
};

hw/pci/pci.c:
+void pci_setup_pasid_ops(PCIDevice *dev, PCIPASIDOps *ops)
+{
+ assert(ops && !dev->pasid_ops);
+ dev->pasid_ops = ops;
+}
+
+void pci_device_pasid_bind_table(PCIBus *bus, int32_t devfn,
+ struct pasid_table_config *ptbl_cfg)
+{
+ PCIDevice *dev;
+
+ if (!bus) {
+ return;
+ }
+
+ dev = bus->devices[devfn];
+ if (dev && dev->pasid_ops) {
+ dev->pasid_ops->pasid_bind_table(bus, devfn, ptbl_cfg);
+ }
+}

hw/vfio/pci.c:
+static PCIPASIDOps vfio_pci_pasid_ops = {
+ .pasid_bind_table = vfio_pci_device_pasid_bind_table,
+ .pasid_invalidate_extend_iotlb = vfio_pci_device_pasid_invalidate_eiotlb,
+};
+
static void vfio_realize(PCIDevice *pdev, Error **errp)

  {
      VFIOPCIDevice *vdev = DO_UPCAST(VFIOPCIDevice, pdev, pdev);
 @@ -3048,6 +3068,8 @@ static void vfio_realize(PCIDevice *pdev, Error **errp)
      vfio_register_req_notifier(vdev);
      vfio_setup_resetfn_quirk(vdev);

+ pci_setup_pasid_ops(pdev, &vfio_pci_pasid_ops);
+

      return;

Regards,
Yi Liu

#33 lore raw

Hi Eric,

Quoted 52 lines

From: Auger Eric [mailto:[email protected]]
Sent: Thursday, October 18, 2018 11:16 PM

Hi Yi,

Quoted 41 lines · Yi L

Hi Eric,

Quoted 39 lines

From: Eric Auger [mailto:[email protected]]
Sent: Friday, September 21, 2018 4:18 PM
Subject: [RFC v2 00/28] vSMMUv3/pSMMUv3 2 stage VFIO integration

Up to now vSMMUv3 has not been integrated with VFIO. VFIO integration requires to program the physical IOMMU consistently with the guest mappings. However, as opposed to VTD, SMMUv3 has no "Caching Mode" which allows easy trapping of guest mappings.
This means the vSMMUV3 cannot use the same VFIO integration as VTD.

However SMMUv3 has 2 translation stages. This was devised with virtualization use case in mind where stage 1 is "owned" by the guest whereas the host uses stage 2 for VM isolation.

This series sets up this nested translation stage. It only works if there is one physical SMMUv3 used along with QEMU vSMMUv3 (in other words, it does not work if there is a physical SMMUv2).

The series uses a new kernel user API [1], still under definition.

- We force the host to use stage 2 instead of stage 1, when we detect a vSMMUV3 is behind a VFIO device. For a VFIO device without any virtual IOMMU, we still use stage 1 as many existing SMMUs expect this behavior.
- We introduce new IOTLB "config" notifiers, requested to notify changes in the config of a given iommu memory region. So now we have notifiers for IOTLB changes and config changes.
- vSMMUv3 calls config notifiers when STE (Stream Table Entries) are updated by the guest.
- We implement a specific UNMAP notifier that conveys guest IOTLB invalidations to the host
- We implement a new MAP notifiers only used for MSI IOVAs so that the host can build a nested stage translation for MSI IOVAs
- As the legacy MAP notifier is not called anymore, we must make sure stage 2 mappings are set. This is achieved through another memory listener.
- Physical SMMUs faults are reported to the guest via en eventfd mechanism and reinjected into this latter.

Quoted 5 lines
Quoted 3 lines

Note: some iommu memory notifier rework related patches are close to those previously published by Peter and Liu. I will be pleased to add their Signed-off-by if they agree/wish.

Yeah, feel free to add mine if it's originated from our previous work.

Quoted 8 lines

OK

Quoted 5 lines

BTW. Curiously, are you planning to implement all vIOMMU related operations through MemoryRegion notifiers? Honestly, I did it in such way in early RFC for vSVA work. However, we encountered two issues at that time. First, how to check whether the notifier should be registered.

On my side I think I resolved this by querying the iommu mr about the new IOMMU_ATTR_VFIO_NESTED IOMMU attribute in vfio_connect_container

So it's to detect it by checking iommu mr? I think it is also similar to my early RFC.
https://patchwork.kernel.org/patch/9701003/

+ /* Check if vIOMMU exists */
+ QTAILQ_FOREACH(subregion, &as->root->subregions, subregions_link) {
+ if (memory_region_is_iommu(subregion)) {
+ IOMMUNotifier n1;
+
+ /*

+             FIXME: current iommu notifier is actually designed for
+             IOMMUTLB MAP/UNMAP. However, vIOMMU emulator may need
+             notifiers other than MAP/UNMAP, so it'll be better to
+             split the non-IOMMUTLB notifier from the current IOMMUTLB
+             notifier framewrok.
+             */
+            iommu_notifier_init(&n1, vfio_iommu_bind_pasid_tbl_notify,
+                                IOMMU_NOTIFIER_SVM_PASIDT_BIND,
+                                0,
+                                0);
+            vfio_register_notifier(group->container,
+                                   subregion,
+                                   0,
+                                   &n1);

+ }
+ }

For VT-d, we only have 1 iommu mr. But I was told ther may be multiple iommu mr on other platform. So I switched to use PCISVAOps. Thoughts?

Quoted 21 lines

See patches 5 and 6, 8

This tells me whether the nested mode must be setup and choose the right container->iommu_type which is then used in vfio_listener_region_add() to decide whether the specific notifiers mustd to be registered.

Quoted 3 lines

Second, there are cases in which the vfio_listener_region_add is not triggered but vIOMMU exists. Details can be got by the link below:
(http://lists.gnu.org/archive/html/qemu-devel/2018-03/msg00078.html)

Yes I remember this, due to the PT=1 case. On ARM we don't have this specificity hence this integration.

Quoted 8 lines

As thus, we had some discussions in community. Last time, PCIPASIDOps was proposed. It is to add callbacks in PCIDevice. VFIO would register its implementations in vfio_realize(). Supposedly, pasid_table_bind, page_table_bind, sva_tlb_invalidation_passdown and other vIOMMU related operations can be done in such way. The sample patch below may show how it looks like. (the full patch is in my sandbox, planned to send out with Scalable Mode emulation patch).

Quoted 2 lines

To be honest, I lost track of the series and did not see this PCIPASIDOps proposal. I will study whether this can fit my needs.

It's proposed in below link. The name at that time is PCISVAOps. I made it to be PCIPASIDOps to be more generic.

http://lists.gnu.org/archive/html/qemu-devel/2018-03/msg00081.html

Regards,
Yi Liu

#34 lore raw
In reply to Eric Auger
Quoted 14 lines

-----Original Message-----
From: Qemu-devel [mailto:qemu-devel- [email protected]] On Behalf Of Eric Auger
Sent: 21 September 2018 09:18
To: [email protected]; [email protected]; qemu- [email protected]; [email protected]; [email protected]
Cc: [email protected]; [email protected]; [email protected]; jean- [email protected]; [email protected]; [email protected]
Subject: [Qemu-devel] [RFC v2 00/28] vSMMUv3/pSMMUv3 2 stage VFIO integration

[...]

Quoted 12 lines

This series can be found at:
https://github.com/eauger/qemu/tree/v3.0.0_2stage-rfc-v2

Testing:
- For testing use my kernel branch
https://github.com/eauger/linux/tree/v4.19-rc4-2stage-rfc-v2 [1]
- Tested on Qualcomm HW with 1/2 assigned e1000e NICs. Hotplug was also tested OK.
- Known limitation:
- currently sending an NH_ASID command instead of NH_VA upon guest NH_VA. This may cause important perf downgrade. Propagating NH_VA does not work at the moment.

Hi Eric,

I had a go with this RFC on one of our platform and noted that when the Guest boots with ACPI , the ping doesn't work with the assigned ixgbevf NIC though the network device gets detected and added to the iommu group.

It's all fine when I boot the Guest with DT. Have you tested this with ACPI yet or am I missing anything obvious here?

Please let me know.

Thanks,
Shameer

Quoted 75 lines

References:
- [1] [RFC v2 00/20] SMMUv3 Nested Stage Setup
(https://lkml.org/lkml/2018/9/18/1087)
The User API still is unstable and under discussion.

History:
v1 -> v2:
- Fixed dual assignment (asid now correctly propagated on TLB invalidations)
- Integrated fault reporting

Next Steps:
- Mature the user API with people involved in SVA work (KVM forum may be a good opportunity to meet)
- Submit the IOMMU cfg notifier changes and some VFIO changes separately, to
progress independently on the kernel dependency

Eric Auger (28):
hw/arm/smmu-common: Fix the name of the iommu memory regions hw/arm/smmuv3: fix eventq recording and IRQ triggerring
update-linux-headers: Import iommu.h
linux-headers: Partial header update
memory: add IOMMU_ATTR_VFIO_NESTED IOMMU memory region attribute hw/arm/smmuv3: Implement get_attr API to report
IOMMU_ATTR_VFIO_NESTED
hw/vfio/common: Refactor container initialization hw/vfio/common: Force nested if iommu requires it
memory: Introduce IOMMUIOLTBNotifier
memory: rename memory_region notify_iommu, notify_one
memory: Add IOMMUConfigNotifier
memory: Add arch_id in IOTLBEntry
hw/arm/smmuv3: Store s1ctrptr in translation config data hw/arm/smmuv3: Implement dummy replay
hw/arm/smmuv3: Notify on config changes hw/arm/smmuv3: Fill the IOTLBEntry arch_id on NH_VA invalidation hw/vfio/common: Introduce vfio_alloc_guest_iommu helper hw/vfio/common: Introduce vfio_dma_(un)map_ram_section helpers hw/vfio/common: Register specific nested mode notifiers and
memory_listener
hw/vfio/common: Register MAP notifier for MSI binding target/arm/kvm: Notifies IOMMU on MSI stage 1 binding vfio/pci: Always set up MSI route before enabling vectors hw/arm/smmuv3: Remove warning about unsupported MAP notifiers
memory: Introduce IOMMU_NOTIFIER_INIT_CFG IOMMU Config Notifier
memory: Introduce IOMMU Memory Region inject_faults API hw/vfio/common: Handle fault_handler
hw/arm/smmuv3: Init fault handling
hw/arm/smmuv3: Implement fault injection

 exec.c                          |  12 +-
 hw/arm/smmu-common.c            |  12 +-
 hw/arm/smmuv3-internal.h        |  26 +-
 hw/arm/smmuv3.c                 | 189 +++++++--
 hw/i386/intel_iommu.c           |  16 +-
 hw/misc/tz-mpc.c                |   8 +-
 hw/ppc/spapr_iommu.c            |   2 +-
 hw/s390x/s390-pci-inst.c        |   4 +-
 hw/vfio/common.c                | 666 ++++++++++++++++++++++++--------
 hw/vfio/pci.c                   |   1 +
 hw/vfio/trace-events            |   4 +-
 hw/virtio/vhost.c               |  12 +-
 include/exec/memory.h           | 140 +++++--
 include/hw/arm/smmu-common.h    |   1 +
 include/hw/vfio/vfio-common.h   |   1 +
 linux-headers/linux/iommu.h     | 237 ++++++++++++
 linux-headers/linux/vfio.h      |  48 +++
 memory.c                        |  66 +++-
 scripts/update-linux-headers.sh |   2 +-
 target/arm/kvm.c                |  46 +--
 20 files changed, 1206 insertions(+), 287 deletions(-)
 create mode 100644 linux-headers/linux/iommu.h

--
2.17.1

author
#35 lore raw

Hi Shameer,

Quoted 30 lines · Shameerali Kolothum Thodi
Quoted 14 lines

-----Original Message-----
From: Qemu-devel [mailto:qemu-devel- [email protected]] On Behalf Of Eric Auger
Sent: 21 September 2018 09:18
To: [email protected]; [email protected]; qemu- [email protected]; [email protected]; [email protected]
Cc: [email protected]; [email protected]; [email protected]; jean- [email protected]; [email protected]; [email protected]
Subject: [Qemu-devel] [RFC v2 00/28] vSMMUv3/pSMMUv3 2 stage VFIO integration

[...]

Quoted 12 lines

This series can be found at:
https://github.com/eauger/qemu/tree/v3.0.0_2stage-rfc-v2

Testing:
- For testing use my kernel branch
https://github.com/eauger/linux/tree/v4.19-rc4-2stage-rfc-v2 [1]
- Tested on Qualcomm HW with 1/2 assigned e1000e NICs. Hotplug was also tested OK.
- Known limitation:
- currently sending an NH_ASID command instead of NH_VA upon guest NH_VA. This may cause important perf downgrade. Propagating NH_VA does not work at the moment.

Quoted 8 lines

Hi Eric,

I had a go with this RFC on one of our platform and noted that when the Guest boots with ACPI , the ping doesn't work with the assigned ixgbevf NIC though the network device gets detected and added to the iommu group.

It's all fine when I boot the Guest with DT. Have you tested this with ACPI yet or am I missing anything obvious here?

Thank you for reporting. You are not missing anything obvious: I can reproduce the issue as well on one of my platform. I will debug and come back to you as soon as possible.

Thanks

Eric

Quoted 83 lines

Please let me know.

Thanks,
Shameer

Quoted 75 lines

References:
- [1] [RFC v2 00/20] SMMUv3 Nested Stage Setup
(https://lkml.org/lkml/2018/9/18/1087)
The User API still is unstable and under discussion.

History:
v1 -> v2:
- Fixed dual assignment (asid now correctly propagated on TLB invalidations)
- Integrated fault reporting

Next Steps:
- Mature the user API with people involved in SVA work (KVM forum may be a good opportunity to meet)
- Submit the IOMMU cfg notifier changes and some VFIO changes separately, to
progress independently on the kernel dependency

Eric Auger (28):
hw/arm/smmu-common: Fix the name of the iommu memory regions hw/arm/smmuv3: fix eventq recording and IRQ triggerring
update-linux-headers: Import iommu.h
linux-headers: Partial header update
memory: add IOMMU_ATTR_VFIO_NESTED IOMMU memory region attribute hw/arm/smmuv3: Implement get_attr API to report
IOMMU_ATTR_VFIO_NESTED
hw/vfio/common: Refactor container initialization hw/vfio/common: Force nested if iommu requires it
memory: Introduce IOMMUIOLTBNotifier
memory: rename memory_region notify_iommu, notify_one
memory: Add IOMMUConfigNotifier
memory: Add arch_id in IOTLBEntry
hw/arm/smmuv3: Store s1ctrptr in translation config data hw/arm/smmuv3: Implement dummy replay
hw/arm/smmuv3: Notify on config changes hw/arm/smmuv3: Fill the IOTLBEntry arch_id on NH_VA invalidation hw/vfio/common: Introduce vfio_alloc_guest_iommu helper hw/vfio/common: Introduce vfio_dma_(un)map_ram_section helpers hw/vfio/common: Register specific nested mode notifiers and
memory_listener
hw/vfio/common: Register MAP notifier for MSI binding target/arm/kvm: Notifies IOMMU on MSI stage 1 binding vfio/pci: Always set up MSI route before enabling vectors hw/arm/smmuv3: Remove warning about unsupported MAP notifiers
memory: Introduce IOMMU_NOTIFIER_INIT_CFG IOMMU Config Notifier
memory: Introduce IOMMU Memory Region inject_faults API hw/vfio/common: Handle fault_handler
hw/arm/smmuv3: Init fault handling
hw/arm/smmuv3: Implement fault injection

 exec.c                          |  12 +-
 hw/arm/smmu-common.c            |  12 +-
 hw/arm/smmuv3-internal.h        |  26 +-
 hw/arm/smmuv3.c                 | 189 +++++++--
 hw/i386/intel_iommu.c           |  16 +-
 hw/misc/tz-mpc.c                |   8 +-
 hw/ppc/spapr_iommu.c            |   2 +-
 hw/s390x/s390-pci-inst.c        |   4 +-
 hw/vfio/common.c                | 666 ++++++++++++++++++++++++--------
 hw/vfio/pci.c                   |   1 +
 hw/vfio/trace-events            |   4 +-
 hw/virtio/vhost.c               |  12 +-
 include/exec/memory.h           | 140 +++++--
 include/hw/arm/smmu-common.h    |   1 +
 include/hw/vfio/vfio-common.h   |   1 +
 linux-headers/linux/iommu.h     | 237 ++++++++++++
 linux-headers/linux/vfio.h      |  48 +++
 memory.c                        |  66 +++-
 scripts/update-linux-headers.sh |   2 +-
 target/arm/kvm.c                |  46 +--
 20 files changed, 1206 insertions(+), 287 deletions(-)
 create mode 100644 linux-headers/linux/iommu.h

--
2.17.1

author
#36 lore raw
In reply to Shameerali Kolothum Thodi

Hi Shameer,

Quoted 30 lines · Shameerali Kolothum Thodi
Quoted 14 lines

-----Original Message-----
From: Qemu-devel [mailto:qemu-devel- [email protected]] On Behalf Of Eric Auger
Sent: 21 September 2018 09:18
To: [email protected]; [email protected]; qemu- [email protected]; [email protected]; [email protected]
Cc: [email protected]; [email protected]; [email protected]; jean- [email protected]; [email protected]; [email protected]
Subject: [Qemu-devel] [RFC v2 00/28] vSMMUv3/pSMMUv3 2 stage VFIO integration

[...]

Quoted 12 lines

This series can be found at:
https://github.com/eauger/qemu/tree/v3.0.0_2stage-rfc-v2

Testing:
- For testing use my kernel branch
https://github.com/eauger/linux/tree/v4.19-rc4-2stage-rfc-v2 [1]
- Tested on Qualcomm HW with 1/2 assigned e1000e NICs. Hotplug was also tested OK.
- Known limitation:
- currently sending an NH_ASID command instead of NH_VA upon guest NH_VA. This may cause important perf downgrade. Propagating NH_VA does not work at the moment.

Quoted 8 lines

Hi Eric,

I had a go with this RFC on one of our platform and noted that when the Guest boots with ACPI , the ping doesn't work with the assigned ixgbevf NIC though the network device gets detected and added to the iommu group.

It's all fine when I boot the Guest with DT. Have you tested this with ACPI yet or am I missing anything obvious here?

I just submitted the following QEMU patch:

[PATCH for-3.1] hw/arm/virt-acpi-build: Fix SMMUv3 ACPI integration

Please can you apply it and test it?

Thank you in advance

Best Regards

Eric

Quoted 83 lines

Please let me know.

Thanks,
Shameer

Quoted 75 lines

References:
- [1] [RFC v2 00/20] SMMUv3 Nested Stage Setup
(https://lkml.org/lkml/2018/9/18/1087)
The User API still is unstable and under discussion.

History:
v1 -> v2:
- Fixed dual assignment (asid now correctly propagated on TLB invalidations)
- Integrated fault reporting

Next Steps:
- Mature the user API with people involved in SVA work (KVM forum may be a good opportunity to meet)
- Submit the IOMMU cfg notifier changes and some VFIO changes separately, to
progress independently on the kernel dependency

Eric Auger (28):
hw/arm/smmu-common: Fix the name of the iommu memory regions hw/arm/smmuv3: fix eventq recording and IRQ triggerring
update-linux-headers: Import iommu.h
linux-headers: Partial header update
memory: add IOMMU_ATTR_VFIO_NESTED IOMMU memory region attribute hw/arm/smmuv3: Implement get_attr API to report
IOMMU_ATTR_VFIO_NESTED
hw/vfio/common: Refactor container initialization hw/vfio/common: Force nested if iommu requires it
memory: Introduce IOMMUIOLTBNotifier
memory: rename memory_region notify_iommu, notify_one
memory: Add IOMMUConfigNotifier
memory: Add arch_id in IOTLBEntry
hw/arm/smmuv3: Store s1ctrptr in translation config data hw/arm/smmuv3: Implement dummy replay
hw/arm/smmuv3: Notify on config changes hw/arm/smmuv3: Fill the IOTLBEntry arch_id on NH_VA invalidation hw/vfio/common: Introduce vfio_alloc_guest_iommu helper hw/vfio/common: Introduce vfio_dma_(un)map_ram_section helpers hw/vfio/common: Register specific nested mode notifiers and
memory_listener
hw/vfio/common: Register MAP notifier for MSI binding target/arm/kvm: Notifies IOMMU on MSI stage 1 binding vfio/pci: Always set up MSI route before enabling vectors hw/arm/smmuv3: Remove warning about unsupported MAP notifiers
memory: Introduce IOMMU_NOTIFIER_INIT_CFG IOMMU Config Notifier
memory: Introduce IOMMU Memory Region inject_faults API hw/vfio/common: Handle fault_handler
hw/arm/smmuv3: Init fault handling
hw/arm/smmuv3: Implement fault injection

 exec.c                          |  12 +-
 hw/arm/smmu-common.c            |  12 +-
 hw/arm/smmuv3-internal.h        |  26 +-
 hw/arm/smmuv3.c                 | 189 +++++++--
 hw/i386/intel_iommu.c           |  16 +-
 hw/misc/tz-mpc.c                |   8 +-
 hw/ppc/spapr_iommu.c            |   2 +-
 hw/s390x/s390-pci-inst.c        |   4 +-
 hw/vfio/common.c                | 666 ++++++++++++++++++++++++--------
 hw/vfio/pci.c                   |   1 +
 hw/vfio/trace-events            |   4 +-
 hw/virtio/vhost.c               |  12 +-
 include/exec/memory.h           | 140 +++++--
 include/hw/arm/smmu-common.h    |   1 +
 include/hw/vfio/vfio-common.h   |   1 +
 linux-headers/linux/iommu.h     | 237 ++++++++++++
 linux-headers/linux/vfio.h      |  48 +++
 memory.c                        |  66 +++-
 scripts/update-linux-headers.sh |   2 +-
 target/arm/kvm.c                |  46 +--
 20 files changed, 1206 insertions(+), 287 deletions(-)
 create mode 100644 linux-headers/linux/iommu.h

--
2.17.1