Skip to contentSkip to conversation

AMD IOMMU Updates for v7.5

GIT PULL New Vasant Hegde 2 participants 40 messages Dec 4 – Dec 5

Subsystems (2)
lore
Share & tools
lore

Vasant Hegde

author maintainer
#0 lore raw

Hi Joerg,

This series includes quite a few fixes and minor cleanups. Major changes:

- Move DTE lock from dev_data structure to pci segment so that we can have consistent locking mechanism while updating DTE.

- Fixes for init/teardown path specifically around interrupt allocation, protection domain ID free path, etc.

- RCU protectin for GA Log notifier, keep unobserved log overflow status bits and performance improvement in interrupt invalidation path. Disable GAPPI bit during boot to avoid unhandled interrupt issue when AVIC is enabled.

- Couple of fixes for PASID/PRI handling path.
Note that this addresses most of the issues in SVA path. I still have one more series to finish

This series is based on top of amd/amd-vi branch (commit b6a9fa34ce418). Please consider pulling these patches for v7.5.

The full series is also available on GitHub:
https://github.com/AMDESE/linux-iommu/tree/amd-vi/updates-7.5

Thanks
Vasant

Ankit Soni (2):
iommu/amd: Move page-table setup into init_pgtable_params() iommu/amd: Adhere to IVINFO[PAsize] for output address limits

Dheeraj Kumar Srivastava (1):
iommu/amd: Enhance "Command buffer timeout" error message

Guanghui Feng (2):
iommu/amd: Do not clear unobserved log overflow status bits iommu/amd: Reuse device data for IRTE cache invalidation

Li RongQing (1):
iommu/amd: RCU-protect iommu_ga_log_notifier

Naveen N Rao (AMD) (1):
iommu/amd: Explicitly disable GAPPI

Santosh Shukla (1):
iommu/amd: Restore an SVA PASID after PCI reset

Vasant Hegde (29):
iommu/amd: Continue the completion sequence in SNP kdump iommu/amd: Destroy protection domain IDs after the domains are freed iommu/amd: Unregister the IOMMUs before disabling them on init failure iommu/amd: Log error message when IOMMU interrupt setup failed iommu/amd: Remove the shared INTCAPXT domain only after its IRQs are freed iommu/amd: Serialize device-table writes with one per-segment lock iommu/amd: Identify a DTE entry by its DeviceID
iommu/amd: Drop the iommu_dev_data allocation for alias devices iommu/amd: Clear the event log entry after reporting an I/O page fault iommu/amd: Hold the device mutex across a page-fault report iommu/amd: Log raw event log
iommu/amd: Drop redundant flushes when the page table top changes iommu/amd: Fix page-counter drift in multi-level GCR3 table teardown iommu/amd: Do not allocate GCR3 tables when clearing a PASID iommu/amd: Allocate the completion sequence after queueing commands iommu/amd: Free the level-1 tables of a two-level GCR3 table iommu/amd: Update device attach state only after a successful attach iommu/amd: Write the DTE under the domain lock on attach and detach iommu/amd: Disable PRI before ATS and PASID
iommu/amd: Derive the PPR completion GN bit from the request iommu/amd: Complete a PPR from a device the IOMMU did not probe iommu/amd: Keep the GCR3 table while PASIDs are attached iommu/amd: Return -ENOMEM when SVA PASID allocation fails iommu/amd: Complete an aborted PPR group only on its last page iommu/amd: Discard partial page requests when the PPR log overflows iommu/amd: Allocate the GCR3 table from the device
iommu/amd: Drain the PPR log before detaching an SVA PASID iommu/amd: Drain the PPR log before removing a device from the IOPF queue iommu/amd: Don't detach SVA PASIDs from the mm release notifier

Wei Wang (1):
iommu/amd: Skip the southbridge IOAPIC PCI class check in guests

 drivers/iommu/amd/amd_iommu.h       |   9 +-
 drivers/iommu/amd/amd_iommu_types.h |  21 +-
 drivers/iommu/amd/init.c            | 229 +++++++++---
 drivers/iommu/amd/iommu.c           | 562 +++++++++++++++-------------
 drivers/iommu/amd/pasid.c           |  32 +-
 drivers/iommu/amd/ppr.c             |  92 ++++-
 6 files changed, 608 insertions(+), 337 deletions(-)
Signature · 1 line
2.31.1
author maintainer
#1 lore raw

PATCH 1/38 iommu/amd: Enhance "Command buffer timeout" error message

From: Dheeraj Kumar Srivastava <[email protected]>

Current IOMMU driver prints "Command buffer timeout" error message with insufficient information to further debug the issue.

Enhance the error message as follows:
1. Log the IOMMU PCI device ID in the error message.
2. With the "amd_iommu_dump=1" kernel command line option, dump the entire command buffer entries, including the Head and Tail offsets.

Consolidate the timeout logging and the command buffer dump into a single helper and use DO_ONCE_LITE() to dump the command buffer only once to avoid dmesg spam. While at it, apply the same reporting to the completion-wait timeout path as well.

---
 drivers/iommu/amd/iommu.c | 21 ++++++++++++---------
 1 file changed, 12 insertions(+), 9 deletions(-)
drivers/iommu/amd/iommu.c +12 -9
index 41ee4ad1dcf8..60aeb10362f2 100644
@@ -1209,6 +1209,16 @@ static void dump_command_buffer(struct amd_iommu *iommu)
 	}
 }
 
+static void report_command_buffer_timeout(struct amd_iommu *iommu, const char *reason)
+{
+	pr_err_ratelimited("IOMMU %04x:%02x:%02x.%01x: %s\n",
+			   iommu->pci_seg->id, PCI_BUS_NUM(iommu->devid),
+			   PCI_SLOT(iommu->devid), PCI_FUNC(iommu->devid), reason);
+
+	if (amd_iommu_dump)
+		DO_ONCE_LITE(dump_command_buffer, iommu);
+}
+
 static int wait_on_sem(struct amd_iommu *iommu, u64 data)
 {
 	int i = 0;
@@ -1224,14 +1234,7 @@ static int wait_on_sem(struct amd_iommu *iommu, u64 data)
 	}
 
 	if (i == LOOP_TIMEOUT) {
-
-		pr_alert("IOMMU %04x:%02x:%02x.%01x: Completion-Wait loop timed out\n",
-			 iommu->pci_seg->id, PCI_BUS_NUM(iommu->devid),
-			 PCI_SLOT(iommu->devid), PCI_FUNC(iommu->devid));
-
-		if (amd_iommu_dump)
-			DO_ONCE_LITE(dump_command_buffer, iommu);
-
+		report_command_buffer_timeout(iommu, "Completion-Wait loop timed out");
 		return -EIO;
 	}
 
@@ -1403,7 +1406,7 @@ static int __iommu_queue_command_sync(struct amd_iommu *iommu,
 		/* Skip udelay() the first time around */
 		if (count++) {
 			if (count == LOOP_TIMEOUT) {
-				pr_err("Command buffer timeout\n");
+				report_command_buffer_timeout(iommu, "Command buffer timeout");
 				return -EIO;
 			}
 
Signature · 1 line
2.31.1
author maintainer
#2 lore raw

PATCH 2/38 iommu/amd: Move page-table setup into init_pgtable_params()

In reply to Vasant Hegde

From: Ankit Soni <[email protected]>

early_amd_iommu_init() currently sets guest page-table level, host address size, and v1/v2 fallback inline after the IVHD walk. That clutters the function.

Move the page-table setup into a separate function. No functional change.

---
 drivers/iommu/amd/init.c | 88 +++++++++++++++++++++-------------------
 1 file changed, 47 insertions(+), 41 deletions(-)
drivers/iommu/amd/init.c +47 -41
index 58f63298493b..b63a5e69279e 100644
@@ -3303,6 +3303,52 @@ static void __init ivinfo_init(void *ivrs)
 	amd_iommu_ivinfo = *((u32 *)(ivrs + IOMMU_IVINFO_OFFSET));
 }
 
+static void __init init_pgtable_params(void)
+{
+	u8 vasize, efr_hats;
+
+	vasize = FIELD_GET(IOMMU_IVINFO_VASIZE, amd_iommu_ivinfo);
+	if (!vasize)
+		vasize = 64;
+
+	/* 5 level guest page table */
+	if (cpu_feature_enabled(X86_FEATURE_LA57) &&
+	    FIELD_GET(FEATURE_GATS, amd_iommu_efr) == GUEST_PGTABLE_5_LEVEL)
+		amd_iommu_gpt_level = PAGE_MODE_5_LEVEL;
+
+	efr_hats = FIELD_GET(FEATURE_HATS, amd_iommu_efr);
+	if (efr_hats != 0x3) {
+		/*
+		 * efr[HATS] bits specify the maximum host translation level
+		 * supported, with LEVEL 4 being initial max level.
+		 */
+		amd_iommu_hpt_vasize = min_t(unsigned int, vasize,
+					 (efr_hats + PAGE_MODE_4_LEVEL - 1) * 9 + 21);
+	} else {
+		pr_warn_once(FW_BUG "Disable host address translation due to invalid translation level (%#x).\n",
+			     efr_hats);
+		amd_iommu_hatdis = true;
+	}
+
+	if (amd_iommu_pgtable == PD_MODE_V2) {
+		if (!amd_iommu_v2_pgtbl_supported()) {
+			pr_warn("Cannot enable v2 page table for DMA-API. Fallback to v1.\n");
+			amd_iommu_pgtable = PD_MODE_V1;
+		}
+	}
+
+	if (amd_iommu_hatdis) {
+		/*
+		 * Host (v1) page table is not available. Attempt to use
+		 * Guest (v2) page table.
+		 */
+		if (amd_iommu_v2_pgtbl_supported())
+			amd_iommu_pgtable = PD_MODE_V2;
+		else
+			amd_iommu_pgtable = PD_MODE_NONE;
+	}
+}
+
 /*
  * This is the hardware init function for AMD IOMMU in the system.
  * This function is called either from amd_iommu_init or from the interrupt
@@ -3335,7 +3381,6 @@ static int __init early_amd_iommu_init(void)
 	struct acpi_table_header *ivrs_base;
 	int ret;
 	acpi_status status;
-	u8 efr_hats, max_vasize;
 
 	status = acpi_get_table("IVRS", 0, &ivrs_base);
 	if (status == AE_NOT_FOUND)
@@ -3362,10 +3407,6 @@ static int __init early_amd_iommu_init(void)
 
 	ivinfo_init(ivrs_base);
 
-	max_vasize = FIELD_GET(IOMMU_IVINFO_VASIZE, amd_iommu_ivinfo);
-	if (!max_vasize)
-		max_vasize = 64;
-
 	amd_iommu_target_ivhd_type = get_highest_supported_ivhd_type(ivrs_base);
 	DUMP_printk("Using IVHD type %#x\n", amd_iommu_target_ivhd_type);
 
@@ -3377,42 +3418,7 @@ static int __init early_amd_iommu_init(void)
 	if (ret)
 		goto out;
 
-	/* 5 level guest page table */
-	if (cpu_feature_enabled(X86_FEATURE_LA57) &&
-	    FIELD_GET(FEATURE_GATS, amd_iommu_efr) == GUEST_PGTABLE_5_LEVEL)
-		amd_iommu_gpt_level = PAGE_MODE_5_LEVEL;
-
-	efr_hats = FIELD_GET(FEATURE_HATS, amd_iommu_efr);
-	if (efr_hats != 0x3) {
-		/*
-		 * efr[HATS] bits specify the maximum host translation level
-		 * supported, with LEVEL 4 being initial max level.
-		 */
-		amd_iommu_hpt_vasize = min_t(unsigned int, max_vasize,
-					 (efr_hats + PAGE_MODE_4_LEVEL - 1) * 9 + 21);
-	} else {
-		pr_warn_once(FW_BUG "Disable host address translation due to invalid translation level (%#x).\n",
-			     efr_hats);
-		amd_iommu_hatdis = true;
-	}
-
-	if (amd_iommu_pgtable == PD_MODE_V2) {
-		if (!amd_iommu_v2_pgtbl_supported()) {
-			pr_warn("Cannot enable v2 page table for DMA-API. Fallback to v1.\n");
-			amd_iommu_pgtable = PD_MODE_V1;
-		}
-	}
-
-	if (amd_iommu_hatdis) {
-		/*
-		 * Host (v1) page table is not available. Attempt to use
-		 * Guest (v2) page table.
-		 */
-		if (amd_iommu_v2_pgtbl_supported())
-			amd_iommu_pgtable = PD_MODE_V2;
-		else
-			amd_iommu_pgtable = PD_MODE_NONE;
-	}
+	init_pgtable_params();
 
 	/* Disable any previously enabled IOMMUs */
 	if (!is_kdump_kernel())
Signature · 1 line
2.31.1
author maintainer
#3 lore raw

PATCH 3/38 iommu/amd: Adhere to IVINFO[PAsize] for output address limits

In reply to Vasant Hegde

From: Ankit Soni <[email protected]>

ACPI IVRS IVinfo reports the maximum physical address size (PAsize) supported by the IOMMU. The AMD IOMMU driver currently hardcodes 52 bits when configuring paging domains. On systems where firmware or a VM advertises a smaller limit, the driver may over-advertise capabilities and create domains outside the hardware's actual bounds.

---
 drivers/iommu/amd/amd_iommu.h       | 1 +
 drivers/iommu/amd/amd_iommu_types.h | 1 +
 drivers/iommu/amd/init.c            | 9 ++++++++-
 drivers/iommu/amd/iommu.c           | 4 ++--
 4 files changed, 12 insertions(+), 3 deletions(-)
drivers/iommu/amd/amd_iommu.h +1 -0
index 29355810db7c..315ec397333b 100644
@@ -45,6 +45,7 @@ extern int amd_iommu_guest_ir;
 extern enum protection_domain_mode amd_iommu_pgtable;
 extern int amd_iommu_gpt_level;
 extern u8 amd_iommu_hpt_vasize;
+extern u8 amd_iommu_pasize;
 extern unsigned long amd_iommu_pgsize_bitmap;
 extern bool amd_iommu_hatdis;
 
drivers/iommu/amd/amd_iommu_types.h +1 -0
index f98770db0090..dab2a423b296 100644
@@ -385,6 +385,7 @@
 #define IOMMU_IVINFO_EFRSUP     BIT(0)
 #define IOMMU_IVINFO_DMA_REMAP  BIT(1)
 #define IOMMU_IVINFO_VASIZE	GENMASK_ULL(21, 15)
+#define IOMMU_IVINFO_PASIZE	GENMASK_ULL(14, 8)
 
 /* IOMMU Feature Reporting Field (for IVHD type 10h */
 #define IOMMU_FEAT_GASUP_SHIFT	6
drivers/iommu/amd/init.c +8 -1
index b63a5e69279e..1a72e35cdafd 100644
@@ -157,6 +157,8 @@ bool amd_iommu_irq_remap __read_mostly;
 enum protection_domain_mode amd_iommu_pgtable = PD_MODE_V1;
 /* Virtual address size */
 u8 amd_iommu_hpt_vasize;
+/* Physical address size */
+u8 amd_iommu_pasize __ro_after_init;
 /* Guest page table level */
 int amd_iommu_gpt_level = PAGE_MODE_4_LEVEL;
 
@@ -3305,7 +3307,12 @@ static void __init ivinfo_init(void *ivrs)
 
 static void __init init_pgtable_params(void)
 {
-	u8 vasize, efr_hats;
+	u8 pasize, vasize, efr_hats;
+
+	pasize = FIELD_GET(IOMMU_IVINFO_PASIZE, amd_iommu_ivinfo);
+	if (!pasize)
+		pasize = 52;
+	amd_iommu_pasize = min_t(u8, pasize, 52);
 
 	vasize = FIELD_GET(IOMMU_IVINFO_VASIZE, amd_iommu_ivinfo);
 	if (!vasize)
drivers/iommu/amd/iommu.c +2 -2
index 60aeb10362f2..61b3191136e4 100644
@@ -2758,7 +2758,7 @@ static struct iommu_domain *amd_iommu_domain_alloc_paging_v1(struct device *dev,
 		cfg.common.features |= BIT(PT_FEAT_FLUSH_RANGE);
 
 	cfg.common.hw_max_vasz_lg2 = amd_iommu_hpt_vasize;
-	cfg.common.hw_max_oasz_lg2 = 52;
+	cfg.common.hw_max_oasz_lg2 = amd_iommu_pasize;
 	cfg.starting_level = 2;
 	domain->domain.ops = &amdv1_ops;
 
@@ -2833,7 +2833,7 @@ static struct iommu_domain *amd_iommu_domain_alloc_paging_v2(struct device *dev,
 		cfg.common.hw_max_vasz_lg2 = 47;
 		cfg.top_level = 3;
 	}
-	cfg.common.hw_max_oasz_lg2 = 52;
+	cfg.common.hw_max_oasz_lg2 = amd_iommu_pasize;
 	domain->domain.ops = &amdv2_ops;
 
 	ret = pt_iommu_x86_64_init(&domain->amdv2, &cfg, GFP_KERNEL);
Signature · 1 line
2.31.1
author maintainer
#4 lore raw

PATCH 4/38 iommu/amd: Do not clear unobserved log overflow status bits

In reply to Vasant Hegde

From: Guanghui Feng <[email protected]>

amd_iommu_handle_irq() clears the interrupt status with an unconditional writel(mask, MMIO_STATUS_OFFSET), where mask is int_mask | overflow_mask. If hardware sets a log overflow bit after the status register is sampled at the top of the loop but before that write, the write clears the freshly-set bit while the stale sampled status does not contain it, so overflow_handler() is skipped for an overflow that really happened.

This is fatal for the GA log: GALOverflow generates no interrupt of its own (MMIO Offset 2020h bit 9), amd_iommu_restart_ga_log() is the only recovery path, and per spec section 2.7.4 logging stays halted until GALogEn is toggled -- a bare W1C of GALOverflow is not part of that recovery. The GA log then stays halted, GAInt never re-asserts and the GA log interrupt line goes permanently silent, losing all AVIC non-running vCPU wakeups on that IOMMU.

Clear only the bits observed this round by writing status & mask. An overflow bit set concurrently is then left asserted and is re-observed by the existing ERBT1312 status read-back at the bottom of the loop, which re-enters the loop and runs overflow_handler().

The unconditional write has cleared an overflow bit since commit 5ce97f4ec5e0 ("iommu/amd: Recover from event log overflow"); commit af47b0a24058 ("iommu/amd: Handle GALog overflows") and commit 274c2218b8b2 ("iommu/amd: Handle PPR log overflow") later added the GA and PPR overflow bits to the same write.

Fixes 5ce97f4ec5e0 ("iommu/amd: Recover from event log overflow")
---
 drivers/iommu/amd/iommu.c | 14 ++++++++++++--
 1 file changed, 12 insertions(+), 2 deletions(-)
drivers/iommu/amd/iommu.c +12 -2
index 61b3191136e4..3b087c777121 100644
@@ -1117,8 +1117,18 @@ static void amd_iommu_handle_irq(void *data, const char *evt_type,
 	u32 mask = int_mask | overflow_mask;
 
 	while (status & mask) {
-		/* Enable interrupt sources again */
-		writel(mask, iommu->mmio_base + MMIO_STATUS_OFFSET);
+		/*
+		 * Clear only the status bits observed in this round.  The log
+		 * overflow bits are RW1C; clearing one unconditionally here
+		 * would drop an overflow that hardware set between the readl()
+		 * above and this write, without ever running overflow_handler().
+		 * Leaving such a bit asserted lets the existing ERBT1312
+		 * read-back below re-observe it and re-enter the loop so
+		 * overflow_handler() runs.  This matters most for the GA log,
+		 * whose GALOverflow bit generates no interrupt of its own, so a
+		 * dropped overflow can otherwise halt GA logging permanently.
+		 */
+		writel(status & mask, iommu->mmio_base + MMIO_STATUS_OFFSET);
 
 		if (int_handler) {
 			pr_devel("Processing IOMMU (ivhd%d) %s Log\n",
Signature · 1 line
2.31.1
author maintainer
#5 lore raw

PATCH 5/38 iommu/amd: RCU-protect iommu_ga_log_notifier

In reply to Vasant Hegde

From: Li RongQing <[email protected]>

iommu_poll_ga_log() accesses iommu_ga_log_notifier without an RCU read-side critical section, so synchronize_rcu() in the unregister path does not wait for an in-flight notifier callback.

Use rcu_assign_pointer() when updating the notifier and rcu_dereference() under rcu_read_lock() when invoking it. Load the pointer once so the NULL check and the call observe the same value.

---
 drivers/iommu/amd/iommu.c | 28 ++++++++++++++++------------
 1 file changed, 16 insertions(+), 12 deletions(-)
drivers/iommu/amd/iommu.c +16 -12
index 3b087c777121..6f1f27053703 100644
@@ -1035,11 +1035,11 @@ static void iommu_poll_events(struct amd_iommu *iommu)
 }
 
 #ifdef CONFIG_IRQ_REMAP
-static int (*iommu_ga_log_notifier)(u32);
+static int (__rcu *iommu_ga_log_notifier)(u32 ga_tag);
 
 int amd_iommu_register_ga_log_notifier(int (*notifier)(u32))
 {
-	iommu_ga_log_notifier = notifier;
+	rcu_assign_pointer(iommu_ga_log_notifier, notifier);
 
 	/*
 	 * Ensure all in-flight IRQ handlers run to completion before returning
@@ -1075,17 +1075,21 @@ static void iommu_poll_ga_log(struct amd_iommu *iommu)
 
 		/* Handle GA entry */
 		switch (GA_REQ_TYPE(log_entry)) {
-		case GA_GUEST_NR:
-			if (!iommu_ga_log_notifier)
-				break;
-
-			pr_debug("%s: devid=%#x, ga_tag=%#x\n",
-				 __func__, GA_DEVID(log_entry),
-				 GA_TAG(log_entry));
-
-			if (iommu_ga_log_notifier(GA_TAG(log_entry)) != 0)
-				pr_err("GA log notifier failed.\n");
+		case GA_GUEST_NR: {
+			int (*notifier)(u32 ga_tag);
+
+			rcu_read_lock();
+			notifier = rcu_dereference(iommu_ga_log_notifier);
+			if (notifier) {
+				pr_debug("%s: devid=%#x, ga_tag=%#x\n",
+					 __func__, GA_DEVID(log_entry),
+					 GA_TAG(log_entry));
+				if (notifier(GA_TAG(log_entry)))
+					pr_err("GA log notifier failed.\n");
+			}
+			rcu_read_unlock();
 			break;
+		}
 		default:
 			break;
 		}
Signature · 1 line
2.31.1
author maintainer
#6 lore raw

PATCH 6/38 iommu/amd: Reuse device data for IRTE cache invalidation

In reply to Vasant Hegde

From: Guanghui Feng <[email protected]>

The DMA alias invalidation path in iommu_flush_irt_and_complete() performs a linear search_dev_data() walk on every IRTE update. Nested VM entry and exit can switch multiple interrupt routes between guest and remapping modes, repeating this lookup for each posted interrupt. A reported workload with 4334 device entries shows median lookup latencies of 22-33 us per invocation, even when IRT caching is disabled and the lookup result is unused.

Save the allocation-time device data in struct amd_ir_data and thread it through all IRTE update paths:

- iommu_flush_irt_and_complete() accepts a dev_data parameter. When IRT caching is disabled it returns immediately without any lookup. When dev_data is NULL (IOAPIC/HPET allocated before PCI enumeration) it falls back to search_dev_data() so DMA-alias invalidation still works if the device is later probed.

- modify_irte_ga(), modify_irte() and free_irte() accept and forward dev_data.

- The amd_irte_ops callbacks (activate, deactivate, set_affinity) are extended to carry dev_data so that amd_ir_update_irte() and the irq_remapping activate/deactivate domain callbacks pass the cached pointer.

- amd_iommu_activate_guest_mode() and deactivate_guest_mode() pass ir_data->dev_data directly.

- amd_ir_set_vcpu_affinity() reuses ir_data->dev_data for the vCPU affinity capability check. This path is only reachable through irq_bypass producers (VFIO-PCI, vhost-vDPA), where device probe always precedes IRQ allocation, so dev_data is guaranteed non-NULL.

Device data is retained in the segment list across unplug and reused on reprobe, so the cached pointer remains valid throughout the IRQ lifetime. The PCI device is still resolved through dev_data->dev at flush time so that later device association is observed.

DMA-alias invalidation, command ordering, locking and completion waits are preserved when IRT caching is enabled.

Fixes 5aac28784dca ("iommu/amd: Invalidate IRT cache for DMA aliases")
---
 drivers/iommu/amd/amd_iommu_types.h | 10 ++--
 drivers/iommu/amd/iommu.c           | 76 +++++++++++++++++------------
 2 files changed, 51 insertions(+), 35 deletions(-)
drivers/iommu/amd/amd_iommu_types.h +7 -3
index dab2a423b296..1c1b39a74233 100644
@@ -1030,6 +1030,7 @@ struct irq_2_irte {
 
 struct amd_ir_data {
 	struct amd_iommu *iommu;
+	struct iommu_dev_data *dev_data;
 	struct irq_2_irte irq_2_irte;
 	struct msi_msg msi_entry;
 	void *entry;    /* Pointer to union irte or struct irte_ga */
@@ -1046,9 +1047,12 @@ struct amd_ir_data {
 
 struct amd_irte_ops {
 	void (*prepare)(void *, u32, bool, u8, u32, int);
-	void (*activate)(struct amd_iommu *iommu, void *, u16, u16);
-	void (*deactivate)(struct amd_iommu *iommu, void *, u16, u16);
-	void (*set_affinity)(struct amd_iommu *iommu, void *, u16, u16, u8, u32);
+	void (*activate)(struct amd_iommu *iommu, void *, u16, u16,
+			 struct iommu_dev_data *dev_data);
+	void (*deactivate)(struct amd_iommu *iommu, void *, u16, u16,
+			   struct iommu_dev_data *dev_data);
+	void (*set_affinity)(struct amd_iommu *iommu, void *, u16, u16, u8,
+			     u32, struct iommu_dev_data *dev_data);
 	void *(*get)(struct irq_remap_table *, int);
 	void (*set_allocated)(struct irq_remap_table *, int);
 	bool (*is_allocated)(struct irq_remap_table *, int);
drivers/iommu/amd/iommu.c +44 -32

227 lines not on this page · raw message

Signature · 1 line
2.31.1
author maintainer
#7 lore raw

PATCH 7/38 iommu/amd: Skip the southbridge IOAPIC PCI class check in guests

In reply to Vasant Hegde

From: Wei Wang <[email protected]>

Linux 7.3 hangs during boot in a VMware ESXi 7.0U3 guest with the virtual IOMMU enabled. IVRS reports 00:14.0 as the source ID for the southbridge IOAPIC, but reading the PCI class at that address returns 0xffff. The PCI class check therefore rejects a valid mapping, causing Linux to disable interrupt remapping.

On bare metal, the PCI class provides a sanity check that the source ID corresponds to a southbridge function. In a VM, the VMM typically supplies both the IVRS mapping and the source ID used by the emulated IOAPIC. That ID need not correspond to a guest-visible PCI function.

Skip the PCI class check when the CPU advertises a hypervisor. The driver still requires a source-ID mapping for each IOAPIC. With the check skipped, the guest boots with interrupt remapping enabled.

Fixes 16f52863b2ec ("iommu/amd: Dynamically verify Southbridge IOAPIC via PCI config space")
---
 drivers/iommu/amd/init.c | 8 ++++++++
 1 file changed, 8 insertions(+)
drivers/iommu/amd/init.c +8 -0
index 1a72e35cdafd..2172d96e536d 100644
@@ -3211,6 +3211,14 @@ static bool __init check_sb_ioapic(int devid)
 	u8 devfn = devid & 0xff;
 	u16 val;
 
+	/*
+	 * A virtual IOAPIC may use a source ID with no corresponding PCI
+	 * function. Skip the PCI class check in guests and accept the source
+	 * ID from IVRS.
+	 */
+	if (boot_cpu_has(X86_FEATURE_HYPERVISOR))
+		return true;
+
 	val = read_pci_config_16(bus, PCI_SLOT(devfn), PCI_FUNC(devfn),
 				 PCI_CLASS_DEVICE);
 
Signature · 1 line
2.31.1
author maintainer
#8 lore raw

PATCH 8/38 iommu/amd: Continue the completion sequence in SNP kdump

In reply to Vasant Hegde

SNP kdump remaps the previous kernel's completion-wait semaphore because the completion-store registers are locked. That page already holds the last sequence number the IOMMU stored, but cmd_sem_val starts at zero.

wait_on_sem() returns once the stored value is at least the target. Until the new counter catches up, every completion wait succeeds before the IOMMU has executed the command. That includes the cache flushes issued while the kdump kernel adopts the old device table.

When the old device table is reused, sample the semaphore after the command buffer is disabled. A completion wait fetched before that can still store a later sequence number. The old command buffer holds at most 512 commands, so continue that far past the sampled value.

Fixes d2a0cac10597 ("iommu/amd: move wait_on_sem() out of spinlock")
Cc Ankit Soni <[email protected]>
---
 drivers/iommu/amd/init.c | 14 ++++++++++++++
 1 file changed, 14 insertions(+)
drivers/iommu/amd/init.c +14 -0
index 2172d96e536d..482d8b6a631a 100644
@@ -3068,6 +3068,20 @@ static void early_enable_iommus(void)
 
 		for_each_iommu(iommu) {
 			iommu_disable_command_buffer(iommu);
+
+			/*
+			 * SNP reuses the previous kernel's completion
+			 * semaphore. wait_on_sem() returns once the stored
+			 * value is at least the target. A completion wait
+			 * fetched before CmdBufEn was cleared can still
+			 * store a later value, and the old command buffer
+			 * holds at most CMD_BUFFER_ENTRIES such commands.
+			 * Continue past that range. A new page reads as
+			 * zero, so this only skips those entries.
+			 */
+			iommu->cmd_sem_val = READ_ONCE(*iommu->cmd_sem) +
+					     CMD_BUFFER_ENTRIES;
+
 			iommu_disable_event_buffer(iommu);
 			iommu_disable_irtcachedis(iommu);
 			iommu_enable_command_buffer(iommu);
Signature · 1 line
2.31.1
author maintainer
#9 lore raw

PATCH 9/38 iommu/amd: Destroy protection domain IDs after the domains are freed

In reply to Vasant Hegde

free_dma_resources() destroyed the protection-domain IDA before free_iommu_resources() unregistered the IOMMU. Unregister frees the group default domains, and amd_iommu_domain_free() then calls ida_free() on an IDA that has already been destroyed. That warns for every domain ID released during init failure.

Move the destroy into free_iommu_resources(), after free_iommu_all() has unregistered the devices and the domains have released their IDs.

---
 drivers/iommu/amd/init.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/iommu/amd/init.c +1 -1
index 482d8b6a631a..e92bd59ca2a5 100644
@@ -3216,6 +3216,7 @@ static struct syscore amd_iommu_syscore = {
 static void __init free_iommu_resources(void)
 {
 	free_iommu_all();
+	amd_iommu_pdom_id_destroy();
 	free_pci_segments();
 }
 
@@ -3318,7 +3319,6 @@ static bool __init check_ioapic_information(void)
 
 static void __init free_dma_resources(void)
 {
-	amd_iommu_pdom_id_destroy();
 	free_unity_maps();
 }
 
Signature · 1 line
2.31.1
author maintainer
#10 lore raw

PATCH 10/38 iommu/amd: Unregister the IOMMUs before disabling them on init failure

In reply to Vasant Hegde

The init failure path disabled the IOMMUs and then called free_iommu_resources(), which unregisters each IOMMU. Unregistering releases the devices behind it and clearing a DTE queues an INVALIDATE_DEVTAB_ENTRY followed by a COMPLETION_WAIT. The command processor was already off, so every one of those waits spins for LOOP_TIMEOUT and reports:

Sample log:
AMD-Vi: IOMMU 0000:70:00.2: Completion-Wait loop timed out
AMD-Vi: CMD Buffer head=56 tail=58

Unregister the IOMMUs first, while they still process commands, then disable the hardware and free the resources.

---
 drivers/iommu/amd/init.c | 16 +++++++++++++---
 1 file changed, 13 insertions(+), 3 deletions(-)
drivers/iommu/amd/init.c +13 -3
index e92bd59ca2a5..1ab254391365 100644
@@ -1852,9 +1852,19 @@ static void __init free_pci_segments(void)
 	}
 }
 
-static void __init free_sysfs(struct amd_iommu *iommu)
+/*
+ * Unregistering an IOMMU releases the devices behind it and clearing a
+ * DTE queues an invalidation and waits for it to complete. The IOMMUs
+ * must still accept commands.
+ */
+static void __init unregister_iommus(void)
 {
-	if (iommu->iommu.dev) {
+	struct amd_iommu *iommu;
+
+	for_each_iommu(iommu) {
+		if (!iommu->iommu.dev)
+			continue;
+
 		iommu_device_unregister(&iommu->iommu);
 		iommu_device_sysfs_remove(&iommu->iommu);
 	}
@@ -1862,7 +1872,6 @@ static void __init free_sysfs(struct amd_iommu *iommu)
 
 static void __init free_iommu_one(struct amd_iommu *iommu)
 {
-	free_sysfs(iommu);
 	free_iommu_buffers(iommu);
 	amd_iommu_free_ppr_log(iommu);
 	free_ga_log(iommu);
@@ -3693,6 +3702,7 @@ static int __init state_next(void)
 	if (ret) {
 		free_dma_resources();
 		if (!irq_remapping_enabled) {
+			unregister_iommus();
 			disable_iommus();
 			free_iommu_resources();
 		} else {
Signature · 1 line
2.31.1
author maintainer
#11 lore raw

PATCH 11/38 iommu/amd: Log error message when IOMMU interrupt setup failed

In reply to Vasant Hegde

iommu_init_irq() returns -ENODEV when XT mode was not selected and the IOMMU has no MSI capability. MSI and INTCAPXT failures return their own errno. The caller records the error and tears the IOMMU down without saying which step failed.

Log the missing capability, and log the errno when interrupt allocation fails.

---
 drivers/iommu/amd/init.c | 16 +++++++++++-----
 1 file changed, 11 insertions(+), 5 deletions(-)
drivers/iommu/amd/init.c +11 -5
index 1ab254391365..0660604cf579 100644
@@ -2703,15 +2703,21 @@ static int iommu_init_irq(struct amd_iommu *iommu)
 	if (iommu->int_enabled)
 		goto enable_faults;
 
-	if (amd_iommu_xt_mode == IRQ_REMAP_X2APIC_MODE)
+	if (amd_iommu_xt_mode == IRQ_REMAP_X2APIC_MODE) {
 		ret = iommu_setup_intcapxt(iommu);
-	else if (iommu->dev->msi_cap)
+	} else if (iommu->dev->msi_cap) {
 		ret = iommu_setup_msi(iommu);
-	else
-		ret = -ENODEV;
+	} else {
+		pr_err("IOMMU%d: x2APIC is unavailable and the IOMMU has no MSI capability\n",
+		       iommu->index);
+		return -ENODEV;
+	}
 
-	if (ret)
+	if (ret) {
+		pr_err("IOMMU%d: failed to enable interrupts (%d)\n",
+		       iommu->index, ret);
 		return ret;
+	}
 
 	iommu->int_enabled = true;
 enable_faults:
Signature · 1 line
2.31.1
author maintainer
#12 lore raw

PATCH 12/38 iommu/amd: Remove the shared INTCAPXT domain only after its IRQs are freed

In reply to Vasant Hegde

__iommu_setup_intcapxt() called irq_domain_remove() when allocation or request_threaded_irq() failed. That domain is shared by every IOMMU and by the event, PPR, and GA interrupts. Removing it while another IRQ is still mapped trips the warning, and iommu_irqdomain keeps pointing at the freed domain.

Free only the IRQ whose request failed. Remember each requested IRQ and release it if a later interrupt fails or when the IOMMU is destroyed. Remove the domain, and clear iommu_irqdomain, once its last IRQ is gone.

---
 drivers/iommu/amd/amd_iommu_types.h |  3 ++
 drivers/iommu/amd/init.c            | 62 +++++++++++++++++++++++++----
 2 files changed, 58 insertions(+), 7 deletions(-)
drivers/iommu/amd/amd_iommu_types.h +3 -0
index 1c1b39a74233..51db65740e41 100644
@@ -687,18 +687,21 @@ struct amd_iommu {
 
 	/* Name for event log interrupt */
 	unsigned char evt_irq_name[16];
+	int evt_irq;
 
 	/* Base of the PPR log, if present */
 	u8 *ppr_log;
 
 	/* Name for PPR log interrupt */
 	unsigned char ppr_irq_name[16];
+	int ppr_irq;
 
 	/* Base of the GA log, if present */
 	u8 *ga_log;
 
 	/* Name for GA log interrupt */
 	unsigned char ga_irq_name[16];
+	int ga_irq;
 
 	/* Tail of the GA log, if present */
 	u8 *ga_log_tail;
drivers/iommu/amd/init.c +55 -7

111 lines not on this page · raw message

Signature · 1 line
2.31.1
author maintainer
#13 lore raw

PATCH 13/38 iommu/amd: Serialize device-table writes with one per-segment lock

In reply to Vasant Hegde

The DTE update lock (dte_lock) currently lives in iommu_dev_data structure. Because of this, dte[devid] can only be serialized when a corresponding dev_data object exists. This leads to inconsistent locking:

- The interrupt remapping path (set_dte_irq_entry()) skips the lock entirely when search_dev_data() returns NULL, leaving the DTE write unprotected.
- An alias ID has no device object of its own, so clone_alias() has to create a dev_data for alias devices purely to have a lock to hold before updating the DTE.

Move dte_lock to per PCI segment (amd_iommu_pci_seg). This guarantees that every code path holds the lock before updating DTE. A subsequent patch builds on this by removing the need to create dev_data objects solely for alias devices.

A DTE update is not a fast-path operation, so using a single per-PCI- segment lock instead of a per-device lock does not affect performance.

---
 drivers/iommu/amd/amd_iommu_types.h |  2 +-
 drivers/iommu/amd/init.c            |  1 +
 drivers/iommu/amd/iommu.c           | 22 ++++++++++------------
 3 files changed, 12 insertions(+), 13 deletions(-)
drivers/iommu/amd/amd_iommu_types.h +1 -1
index 51db65740e41..bbfc561d6abf 100644
@@ -567,6 +567,7 @@ struct amd_iommu_pci_seg {
 
 	/* List of all available dev_data structures */
 	struct llist_head dev_data_list;
+	spinlock_t dte_lock;		/* Device-table update lock */
 
 	/* PCI segment number */
 	u16 id;
@@ -807,7 +808,6 @@ struct devid_map {
 struct iommu_dev_data {
 	/*Protect against attach/detach races */
 	struct mutex mutex;
-	spinlock_t dte_lock;              /* DTE lock for 256-bit access */
 
 	struct list_head list;		  /* For domain->dev_list */
 	struct llist_node dev_data_list;  /* For global dev_data_list */
drivers/iommu/amd/init.c +1 -0
index 24bf65e35694..e020459513d8 100644
@@ -1803,6 +1803,7 @@ static struct amd_iommu_pci_seg *__init alloc_pci_segment(u16 id,
 
 	pci_seg->id = id;
 	init_llist_head(&pci_seg->dev_data_list);
+	spin_lock_init(&pci_seg->dte_lock);
 	INIT_LIST_HEAD(&pci_seg->unity_map);
 	list_add_tail(&pci_seg->list, &amd_iommu_pci_seg_list);
 
drivers/iommu/amd/iommu.c +10 -12
index 1840af314131..ce2e36dbc962 100644
@@ -121,7 +121,7 @@ static void write_dte_upper128(struct dev_table_entry *ptr, struct dev_table_ent
 	/*
 	 * Preserve DTE_DATA2_INTR_MASK. This needs to be
 	 * done here since it requires to be inside
-	 * spin_lock(&dev_data->dte_lock) context.
+	 * pci_seg->dte_lock context.
 	 */
 	new->data[2] &= ~DTE_DATA2_INTR_MASK;
 	new->data[2] |= old.data[2] & DTE_DATA2_INTR_MASK;
@@ -152,7 +152,7 @@ static void update_dte256(struct amd_iommu *iommu, struct iommu_dev_data *dev_da
 	struct dev_table_entry *dev_table = get_dev_table(iommu);
 	struct dev_table_entry *ptr = &dev_table[dev_data->devid];
 
-	spin_lock_irqsave(&dev_data->dte_lock, flags);
+	spin_lock_irqsave(&iommu->pci_seg->dte_lock, flags);
 
 	if (!(ptr->data[0] & DTE_FLAG_V)) {
 		/* Existing DTE is not valid. */
@@ -208,7 +208,7 @@ static void update_dte256(struct amd_iommu *iommu, struct iommu_dev_data *dev_da
 		write_dte_lower128(ptr, new);
 	}
 
-	spin_unlock_irqrestore(&dev_data->dte_lock, flags);
+	spin_unlock_irqrestore(&iommu->pci_seg->dte_lock, flags);
 }
 
 void amd_iommu_update_dte(struct amd_iommu *iommu,
@@ -230,10 +230,10 @@ static void get_dte256(struct amd_iommu *iommu, struct iommu_dev_data *dev_data,
 
 	ptr = &dev_table[dev_data->devid];
 
-	spin_lock_irqsave(&dev_data->dte_lock, flags);
+	spin_lock_irqsave(&iommu->pci_seg->dte_lock, flags);
 	dte->data128[0] = ptr->data128[0];
 	dte->data128[1] = ptr->data128[1];
-	spin_unlock_irqrestore(&dev_data->dte_lock, flags);
+	spin_unlock_irqrestore(&iommu->pci_seg->dte_lock, flags);
 }
 
 static inline bool pdom_is_v2_pgtbl_mode(struct protection_domain *pdom)
@@ -383,7 +383,6 @@ static struct iommu_dev_data *alloc_dev_data(struct amd_iommu *iommu, u16 devid)
 		return NULL;
 
 	mutex_init(&dev_data->mutex);
-	spin_lock_init(&dev_data->dte_lock);
 	dev_data->devid = devid;
 	ratelimit_default_init(&dev_data->rs);
 
@@ -3121,13 +3120,13 @@ static int amd_iommu_set_dirty_tracking(struct iommu_domain *domain,
 	}
 
 	list_for_each_entry(dev_data, &pdomain->dev_list, list) {
-		spin_lock(&dev_data->dte_lock);
 		iommu = get_amd_iommu_from_dev_data(dev_data);
+		spin_lock(&iommu->pci_seg->dte_lock);
 		dte = &get_dev_table(iommu)[dev_data->devid];
 		new = dte->data[0];
 		new = (enable ? new | DTE_FLAG_HAD : new & ~DTE_FLAG_HAD);
 		dte->data[0] = new;
-		spin_unlock(&dev_data->dte_lock);
+		spin_unlock(&iommu->pci_seg->dte_lock);
 
 		/* Flush device DTE */
 		device_flush_dte(dev_data);
@@ -3360,11 +3359,11 @@ static void set_dte_irq_entry(struct amd_iommu *iommu, u16 devid,
 			      struct irq_remap_table *table)
 {
 	u64 new;
+	unsigned long flags;
 	struct dev_table_entry *dte = &get_dev_table(iommu)[devid];
 	struct iommu_dev_data *dev_data = search_dev_data(iommu, devid);
 
-	if (dev_data)
-		spin_lock(&dev_data->dte_lock);
+	spin_lock_irqsave(&iommu->pci_seg->dte_lock, flags);
 
 	new = READ_ONCE(dte->data[2]);
 	new &= ~DTE_IRQ_PHYS_ADDR_MASK;
@@ -3374,8 +3373,7 @@ static void set_dte_irq_entry(struct amd_iommu *iommu, u16 devid,
 	new |= DTE_IRQ_REMAP_ENABLE;
 	WRITE_ONCE(dte->data[2], new);
 
-	if (dev_data)
-		spin_unlock(&dev_data->dte_lock);
+	spin_unlock_irqrestore(&iommu->pci_seg->dte_lock, flags);
 }
 
 static struct irq_remap_table *get_irq_table(struct amd_iommu *iommu, u16 devid)
Signature · 1 line
2.31.1
author maintainer
#14 lore raw

PATCH 14/38 iommu/amd: Identify a DTE entry by its DeviceID

In reply to Vasant Hegde

The DTE accessors update_dte256() and get_dte256() take a struct iommu_dev_data pointer purely to read ->devid when indexing into the device table. Now that the DTE lock lives in the per-PCI-segment structure rather than in iommu_dev_data, nothing in these helpers needs the dev_data object itself.

A DTE entry is fundamentally identified by its DeviceID, so pass the DeviceID directly instead of an iommu_dev_data. This removes the artificial requirement for callers to construct or look up a dev_data object just to program or read a DTE slot. ex, dump_dte_entry() no longer has to call find_dev_data() before dumping an entry.

Cc Suravee Suthikulpanit <[email protected]>
---
 drivers/iommu/amd/iommu.c | 31 +++++++++++++++----------------
 1 file changed, 15 insertions(+), 16 deletions(-)
drivers/iommu/amd/iommu.c +15 -16
index ce2e36dbc962..4c88c4aa2d24 100644
@@ -145,12 +145,12 @@ static void write_dte_lower128(struct dev_table_entry *ptr, struct dev_table_ent
  * This function is used only by code, which updates DMA translation part of the DTE.
  * So, only consider control bits related to DMA when updating the entry.
  */
-static void update_dte256(struct amd_iommu *iommu, struct iommu_dev_data *dev_data,
+static void update_dte256(struct amd_iommu *iommu, u16 devid,
 			  struct dev_table_entry *new)
 {
 	unsigned long flags;
 	struct dev_table_entry *dev_table = get_dev_table(iommu);
-	struct dev_table_entry *ptr = &dev_table[dev_data->devid];
+	struct dev_table_entry *ptr = &dev_table[devid];
 
 	spin_lock_irqsave(&iommu->pci_seg->dte_lock, flags);
 
@@ -158,12 +158,12 @@ static void update_dte256(struct amd_iommu *iommu, struct iommu_dev_data *dev_da
 		/* Existing DTE is not valid. */
 		write_dte_upper128(ptr, new);
 		write_dte_lower128(ptr, new);
-		iommu_flush_dte_sync(iommu, dev_data->devid);
+		iommu_flush_dte_sync(iommu, devid);
 	} else if (!(new->data[0] & DTE_FLAG_V)) {
 		/* Existing DTE is valid. New DTE is not valid.  */
 		write_dte_lower128(ptr, new);
 		write_dte_upper128(ptr, new);
-		iommu_flush_dte_sync(iommu, dev_data->devid);
+		iommu_flush_dte_sync(iommu, devid);
 	} else if (!FIELD_GET(DTE_FLAG_GV, ptr->data[0])) {
 		/*
 		 * Both DTEs are valid.
@@ -171,7 +171,7 @@ static void update_dte256(struct amd_iommu *iommu, struct iommu_dev_data *dev_da
 		 */
 		write_dte_upper128(ptr, new);
 		write_dte_lower128(ptr, new);
-		iommu_flush_dte_sync(iommu, dev_data->devid);
+		iommu_flush_dte_sync(iommu, devid);
 	} else if (!FIELD_GET(DTE_FLAG_GV, new->data[0])) {
 		/*
 		 * Both DTEs are valid.
@@ -180,7 +180,7 @@ static void update_dte256(struct amd_iommu *iommu, struct iommu_dev_data *dev_da
 		 */
 		write_dte_lower128(ptr, new);
 		write_dte_upper128(ptr, new);
-		iommu_flush_dte_sync(iommu, dev_data->devid);
+		iommu_flush_dte_sync(iommu, devid);
 	} else if (FIELD_GET(DTE_GPT_LEVEL_MASK, ptr->data[2]) !=
 		   FIELD_GET(DTE_GPT_LEVEL_MASK, new->data[2])) {
 		/*
@@ -193,12 +193,12 @@ static void update_dte256(struct amd_iommu *iommu, struct iommu_dev_data *dev_da
 
 		/* First disable DTE */
 		write_dte_lower128(ptr, &clear);
-		iommu_flush_dte_sync(iommu, dev_data->devid);
+		iommu_flush_dte_sync(iommu, devid);
 
 		/* Then update DTE */
 		write_dte_upper128(ptr, new);
 		write_dte_lower128(ptr, new);
-		iommu_flush_dte_sync(iommu, dev_data->devid);
+		iommu_flush_dte_sync(iommu, devid);
 	} else {
 		/*
 		 * Both DTEs are valid and have guest page table,
@@ -215,20 +215,20 @@ void amd_iommu_update_dte(struct amd_iommu *iommu,
 			     struct iommu_dev_data *dev_data,
 			     struct dev_table_entry *new)
 {
-	update_dte256(iommu, dev_data, new);
+	update_dte256(iommu, dev_data->devid, new);
 	clone_aliases(iommu, dev_data->dev);
 	device_flush_dte(dev_data);
 	iommu_completion_wait(iommu);
 }
 
-static void get_dte256(struct amd_iommu *iommu, struct iommu_dev_data *dev_data,
-		      struct dev_table_entry *dte)
+static void get_dte256(struct amd_iommu *iommu, u16 devid,
+		       struct dev_table_entry *dte)
 {
 	unsigned long flags;
 	struct dev_table_entry *ptr;
 	struct dev_table_entry *dev_table = get_dev_table(iommu);
 
-	ptr = &dev_table[dev_data->devid];
+	ptr = &dev_table[devid];
 
 	spin_lock_irqsave(&iommu->pci_seg->dte_lock, flags);
 	dte->data128[0] = ptr->data128[0];
@@ -431,7 +431,7 @@ static int clone_alias(struct pci_dev *pdev_origin, u16 alias, void *data)
 		ret = -EINVAL;
 		goto out;
 	}
-	get_dte256(iommu, dev_data, &new);
+	get_dte256(iommu, dev_data->devid, &new);
 
 	/* Setup alias */
 	alias_data = find_dev_data(iommu, alias);
@@ -440,7 +440,7 @@ static int clone_alias(struct pci_dev *pdev_origin, u16 alias, void *data)
 		ret = -EINVAL;
 		goto out;
 	}
-	update_dte256(iommu, alias_data, &new);
+	update_dte256(iommu, alias_data->devid, &new);
 
 	amd_iommu_set_rlookup_table(iommu, alias);
 out:
@@ -749,9 +749,8 @@ static void dump_dte_entry(struct amd_iommu *iommu, u16 devid)
 {
 	int i;
 	struct dev_table_entry dte;
-	struct iommu_dev_data *dev_data = find_dev_data(iommu, devid);
 
-	get_dte256(iommu, dev_data, &dte);
+	get_dte256(iommu, devid, &dte);
 
 	for (i = 0; i < 4; ++i)
 		pr_err("DTE[%d]: %016llx\n", i, dte.data[i]);
Signature · 1 line
2.31.1
author maintainer
#15 lore raw

PATCH 15/38 iommu/amd: Drop the iommu_dev_data allocation for alias devices

In reply to Vasant Hegde

A DMA alias is simply another DeviceID for a device the driver already tracks. The alias dev_data object is never attached to a domain and is never freed, so it serves no purpose beyond carrying a deviceID.

Now that the DTE helpers address a slot directly by DeviceID, get_dte256()/update_dte256() can read the source entry and write the alias entry using their DeviceIDs alone. Drop the dev_data lookup and the alias allocation.

No functional change intended.

Cc Suravee Suthikulpanit <[email protected]>
---
 drivers/iommu/amd/iommu.c | 27 ++++-----------------------
 1 file changed, 4 insertions(+), 23 deletions(-)
drivers/iommu/amd/iommu.c +4 -23
index 4c88c4aa2d24..3bf211107528 100644
@@ -82,7 +82,6 @@ static void amd_iommu_change_top(struct pt_iommu *iommu_table,
 
 static void iommu_flush_dte_sync(struct amd_iommu *iommu, u16 devid);
 
-static struct iommu_dev_data *find_dev_data(struct amd_iommu *iommu, u16 devid);
 static bool amd_iommu_enforce_cache_coherency(struct iommu_domain *domain);
 static int amd_iommu_set_dirty_tracking(struct iommu_domain *domain,
 					bool enable);
@@ -412,10 +411,8 @@ static int clone_alias(struct pci_dev *pdev_origin, u16 alias, void *data)
 {
 	struct dev_table_entry new;
 	struct amd_iommu *iommu;
-	struct iommu_dev_data *dev_data, *alias_data;
 	struct pci_dev *pdev = data;
 	u16 devid = pci_dev_id(pdev);
-	int ret = 0;
 
 	if (devid == alias)
 		return 0;
@@ -424,27 +421,11 @@ static int clone_alias(struct pci_dev *pdev_origin, u16 alias, void *data)
 	if (!iommu)
 		return 0;
 
-	/* Copy the data from pdev */
-	dev_data = dev_iommu_priv_get(&pdev->dev);
-	if (!dev_data) {
-		pr_err("%s : Failed to get dev_data for 0x%x\n", __func__, devid);
-		ret = -EINVAL;
-		goto out;
-	}
-	get_dte256(iommu, dev_data->devid, &new);
-
-	/* Setup alias */
-	alias_data = find_dev_data(iommu, alias);
-	if (!alias_data) {
-		pr_err("%s : Failed to get alias dev_data for 0x%x\n", __func__, alias);
-		ret = -EINVAL;
-		goto out;
-	}
-	update_dte256(iommu, alias_data->devid, &new);
-
+	get_dte256(iommu, devid, &new);
+	update_dte256(iommu, alias, &new);
 	amd_iommu_set_rlookup_table(iommu, alias);
-out:
-	return ret;
+
+	return 0;
 }
 
 static void clone_aliases(struct amd_iommu *iommu, struct device *dev)
Signature · 1 line
2.31.1
author maintainer
#16 lore raw

PATCH 16/38 iommu/amd: Clear the event log entry after reporting an I/O page fault

In reply to Vasant Hegde

The I/O page fault path returned early after reporting the fault, skipping the code that zeroes the slot. Make sure slot is cleared before returning.

---
 drivers/iommu/amd/iommu.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/iommu/amd/iommu.c +2 -1
index 3bf211107528..49bb0c23868d 100644
@@ -932,7 +932,7 @@ static void iommu_print_event(struct amd_iommu *iommu, void *__evt)
 
 	if (type == EVENT_TYPE_IO_FAULT) {
 		amd_iommu_report_page_fault(iommu, devid, pasid, address, flags);
-		return;
+		goto out;
 	}
 
 	switch (type) {
@@ -986,6 +986,7 @@ static void iommu_print_event(struct amd_iommu *iommu, void *__evt)
 			event[0], event[1], event[2], event[3]);
 	}
 
+out:
 	/*
 	 * To detect the hardware errata 732 we need to clear the
 	 * entry back to zero. This issue does not exist on SNP
Signature · 1 line
2.31.1
author maintainer
#17 lore raw

PATCH 17/38 iommu/amd: Hold the device mutex across a page-fault report

In reply to Vasant Hegde

amd_iommu_report_page_fault() read dev_data->domain outside any lock and then dereferenced it in report_iommu_fault(). detach_device() clears that pointer under dev_data->mutex and the domain is freed only after detach returns. Nothing prevented a concurrent detach from freeing the domain between the read and the report, leading to a potential use-after-free.

The fault runs in the threaded IRQ handler, which can sleep, so the same mutex can cover both the lookup and the report. Hold dev_data->mutex across reading dev_data->domain and calling report_iommu_fault(), so the domain cannot be detached and freed while it is in use.

---
 drivers/iommu/amd/iommu.c | 21 +++++++++++++++------
 1 file changed, 15 insertions(+), 6 deletions(-)
drivers/iommu/amd/iommu.c +15 -6
index 49bb0c23868d..b35001199d58 100644
@@ -836,8 +836,21 @@ static void amd_iommu_report_page_fault(struct amd_iommu *iommu,
 		 * prevent logging it.
 		 */
 		if (IS_IOMMU_MEM_TRANSACTION(flags)) {
+			struct protection_domain *domain;
+			int handled = -ENODEV;
+
+			mutex_lock(&dev_data->mutex);
+			domain = dev_data->domain;
+			if (domain)
+				handled = report_iommu_fault(&domain->domain,
+							     &pdev->dev, address,
+							     IS_WRITE_REQUEST(flags) ?
+							     IOMMU_FAULT_WRITE :
+							     IOMMU_FAULT_READ);
+			mutex_unlock(&dev_data->mutex);
+
 			/* Device not attached to domain properly */
-			if (dev_data->domain == NULL) {
+			if (!domain) {
 				pr_err_ratelimited("Event logged [Device not attached to domain properly]\n");
 				pr_err_ratelimited("  device=%04x:%02x:%02x.%x domain=0x%04x\n",
 						   iommu->pci_seg->id, PCI_BUS_NUM(devid), PCI_SLOT(devid),
@@ -845,11 +858,7 @@ static void amd_iommu_report_page_fault(struct amd_iommu *iommu,
 				goto out;
 			}
 
-			if (!report_iommu_fault(&dev_data->domain->domain,
-						&pdev->dev, address,
-						IS_WRITE_REQUEST(flags) ?
-							IOMMU_FAULT_WRITE :
-							IOMMU_FAULT_READ))
+			if (!handled)
 				goto out;
 		}
 
Signature · 1 line
2.31.1
author maintainer
#18 lore raw

PATCH 18/38 iommu/amd: Log raw event log

In reply to Vasant Hegde

Log the raw event entry unconditionally before processing/decoding the event. This is useful for debugging especially when decoded log doesn't decode all the fields like newly introduced fields.

---
 drivers/iommu/amd/iommu.c | 3 +++
 1 file changed, 3 insertions(+)
drivers/iommu/amd/iommu.c +3 -0
index b35001199d58..0cfaed36ce32 100644
@@ -939,6 +939,9 @@ static void iommu_print_event(struct amd_iommu *iommu, void *__evt)
 		goto retry;
 	}
 
+	dev_err_ratelimited(dev, "Raw event: evt[0]=0x%08x, evt[1]=0x%08x, evt[2]=0x%08x, evt[3]=0x%08x\n",
+			    event[0], event[1], event[2], event[3]);
+
 	if (type == EVENT_TYPE_IO_FAULT) {
 		amd_iommu_report_page_fault(iommu, devid, pasid, address, flags);
 		goto out;
Signature · 1 line
2.31.1
author maintainer
#19 lore raw

PATCH 19/38 iommu/amd: Drop redundant flushes when the page table top changes

In reply to Vasant Hegde

amd_iommu_change_top() updates each device's DTE via set_dte_entry(), which already clones the aliases, flushes the DTE and device IOTLB, and waits for completion. Hence remove redundant clone_aliases and dte flush from amd_iommu_change_top().

Cc Suravee Suthikulpanit <[email protected]>
---
 drivers/iommu/amd/iommu.c | 13 +++++--------
 1 file changed, 5 insertions(+), 8 deletions(-)
drivers/iommu/amd/iommu.c +5 -8
index 0cfaed36ce32..303cd218bc60 100644
@@ -2640,19 +2640,16 @@ static void amd_iommu_change_top(struct pt_iommu *iommu_table,
 
 	lockdep_assert_held(&pdom->lock);
 
-	/* Update the DTE for all devices attached to this domain */
+	/*
+	 * Update the DTE for all devices attached to this domain. This also
+	 * updates the aliases and flushes the DTEs.
+	 */
 	list_for_each_entry(dev_data, &pdom->dev_list, list) {
-		struct amd_iommu *iommu = rlookup_amd_iommu(dev_data->dev);
+		struct amd_iommu *iommu = get_amd_iommu_from_dev_data(dev_data);
 
 		/* Update the HW references with the new level and top ptr */
 		set_dte_entry(iommu, dev_data, top_paddr, top_level);
-		clone_aliases(iommu, dev_data->dev);
 	}
-
-	list_for_each_entry(dev_data, &pdom->dev_list, list)
-		device_flush_dte(dev_data);
-
-	domain_flush_complete(pdom);
 }
 
 /*
Signature · 1 line
2.31.1
author maintainer
#20 lore raw

PATCH 20/38 iommu/amd: Fix page-counter drift in multi-level GCR3 table teardown

In reply to Vasant Hegde

__get_gcr3_pte() allocates intermediate GCR3 tables with get_zeroed_page(), but free_gcr3_tbl_level1() releases them with iommu_free_pages(). iommu_free_pages() decrements NR_IOMMU_PAGES and NR_SECONDARY_PAGETABLE, but get_zeroed_page() never incremented those counters. So every teardown of a multi-level PASID (GCR3) table makes both counters drift negative.

Allocate the sub tables with iommu_alloc_pages_node_sz() on the IOMMU node. That matches the GCR3 root allocation, so the alloc and free paths are symmetric and the page counters stay balanced.

Fixes 75114cbaa136 ("iommu/amd: use page allocation function provided by iommu-pages.h")
---
 drivers/iommu/amd/iommu.c | 8 +++++---
 1 file changed, 5 insertions(+), 3 deletions(-)
drivers/iommu/amd/iommu.c +5 -3
index 303cd218bc60..f1aff2ce8058 100644
@@ -2019,7 +2019,7 @@ static int setup_gcr3_table(struct gcr3_tbl_info *gcr3_info,
 }
 
 static u64 *__get_gcr3_pte(struct gcr3_tbl_info *gcr3_info,
-			   ioasid_t pasid, bool alloc)
+			   ioasid_t pasid, bool alloc, int nid)
 {
 	int index;
 	u64 *pte;
@@ -2038,7 +2038,7 @@ static u64 *__get_gcr3_pte(struct gcr3_tbl_info *gcr3_info,
 			if (!alloc)
 				return NULL;
 
-			root = (void *)get_zeroed_page(GFP_ATOMIC);
+			root = iommu_alloc_pages_node_sz(nid, GFP_ATOMIC, SZ_4K);
 			if (root == NULL)
 				return NULL;
 
@@ -2057,9 +2057,11 @@ static int update_gcr3(struct iommu_dev_data *dev_data,
 		       ioasid_t pasid, unsigned long gcr3, bool set)
 {
 	struct gcr3_tbl_info *gcr3_info = &dev_data->gcr3_info;
+	struct amd_iommu *iommu = get_amd_iommu_from_dev_data(dev_data);
+	int nid = iommu ? dev_to_node(&iommu->dev->dev) : NUMA_NO_NODE;
 	u64 *pte;
 
-	pte = __get_gcr3_pte(gcr3_info, pasid, true);
+	pte = __get_gcr3_pte(gcr3_info, pasid, true, nid);
 	if (pte == NULL)
 		return -ENOMEM;
 
Signature · 1 line
2.31.1
author maintainer
#21 lore raw

PATCH 21/38 iommu/amd: Do not allocate GCR3 tables when clearing a PASID

In reply to Vasant Hegde

Allocate gcr3 intermediate tables only when installing an entry. A missing intermediate table means nothing was installed under it, so a clear simply succeeds.

Fixes e8e1aac33458 ("iommu/amd: Refactor helper function for setting / clearing GCR3")
Cc Suravee Suthikulpanit <[email protected]>
---
 drivers/iommu/amd/iommu.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/iommu/amd/iommu.c +2 -2
index f1aff2ce8058..cdbbf7cf18c6 100644
@@ -2061,9 +2061,9 @@ static int update_gcr3(struct iommu_dev_data *dev_data,
 	int nid = iommu ? dev_to_node(&iommu->dev->dev) : NUMA_NO_NODE;
 	u64 *pte;
 
-	pte = __get_gcr3_pte(gcr3_info, pasid, true, nid);
+	pte = __get_gcr3_pte(gcr3_info, pasid, set, nid);
 	if (pte == NULL)
-		return -ENOMEM;
+		return set ? -ENOMEM : 0;
 
 	if (set)
 		*pte = (gcr3 & PAGE_MASK) | GCR3_VALID;
Signature · 1 line
2.31.1
author maintainer
#22 lore raw

PATCH 22/38 iommu/amd: Allocate the completion sequence after queueing commands

In reply to Vasant Hegde

iommu_flush_irt_and_complete() reserves a completion-wait sequence number (via get_cmdsem_val()) before queueing the invalidate_irt commands. If one of those commands fails to queue, it returns early without ever queueing the completion wait that would store that sequence number.

Currently this is harmless, since iommu_completion_wait() is only called after some command has been queued. But allocating a sequence number and not using it may cause problems in the future.

Reserve and queue the completion wait only after the invalidate_irt commands are queued. Move the locked sequence allocation and queueing into a new __iommu_completion_wait() helper, called from both iommu_completion_wait() and iommu_flush_irt_and_complete(). The caller holds iommu->lock; the semaphore wait stays outside the lock.

---
 drivers/iommu/amd/iommu.c | 50 ++++++++++++++++++---------------------
 1 file changed, 23 insertions(+), 27 deletions(-)
drivers/iommu/amd/iommu.c +23 -27
index cdbbf7cf18c6..e67f7e2ed39e 100644
@@ -1453,24 +1453,11 @@ static int iommu_queue_command(struct amd_iommu *iommu, struct iommu_cmd *cmd)
 	return iommu_queue_command_sync(iommu, cmd, true);
 }
 
-static u64 get_cmdsem_val(struct amd_iommu *iommu)
-{
-	lockdep_assert_held(&iommu->lock);
-	return ++iommu->cmd_sem_val;
-}
-
-/*
- * This function queues a completion wait command into the command
- * buffer of an IOMMU
- */
-static int iommu_completion_wait(struct amd_iommu *iommu)
+static int __iommu_completion_wait(struct amd_iommu *iommu, u64 *data)
 {
 	struct iommu_cmd cmd;
-	unsigned long flags;
-	int ret;
-	u64 data;
 
-	raw_spin_lock_irqsave(&iommu->lock, flags);
+	lockdep_assert_held(&iommu->lock);
 
 	if (!iommu->need_sync) {
 		/*
@@ -1482,15 +1469,28 @@ static int iommu_completion_wait(struct amd_iommu *iommu)
 		 * command queued before this call (possibly on another CPU)
 		 * is guaranteed to have completed before returning.
 		 */
-		data = iommu->cmd_sem_val;
-		raw_spin_unlock_irqrestore(&iommu->lock, flags);
-		return wait_on_sem(iommu, data);
+		*data = iommu->cmd_sem_val;
+		return 0;
 	}
 
-	data = get_cmdsem_val(iommu);
-	build_completion_wait(&cmd, iommu, data);
+	*data = ++iommu->cmd_sem_val;
+	build_completion_wait(&cmd, iommu, *data);
+
+	return __iommu_queue_command_sync(iommu, &cmd, false);
+}
+
+/*
+ * This function queues a completion wait command into the command
+ * buffer of an IOMMU
+ */
+static int iommu_completion_wait(struct amd_iommu *iommu)
+{
+	unsigned long flags;
+	int ret;
+	u64 data;
 
-	ret = __iommu_queue_command_sync(iommu, &cmd, false);
+	raw_spin_lock_irqsave(&iommu->lock, flags);
+	ret = __iommu_completion_wait(iommu, &data);
 	raw_spin_unlock_irqrestore(&iommu->lock, flags);
 
 	if (ret)
@@ -3305,7 +3305,6 @@ static void iommu_flush_irt_and_complete(struct amd_iommu *iommu, u16 devid,
 	int ret;
 	u64 data;
 	unsigned long flags;
-	struct iommu_cmd cmd;
 	struct pci_dev *pdev = NULL;
 
 	if (iommu->irtcachedis_enabled)
@@ -3318,9 +3317,6 @@ static void iommu_flush_irt_and_complete(struct amd_iommu *iommu, u16 devid,
 		pdev = to_pci_dev(dev_data->dev);
 
 	raw_spin_lock_irqsave(&iommu->lock, flags);
-	data = get_cmdsem_val(iommu);
-	build_completion_wait(&cmd, iommu, data);
-
 	if (pdev)
 		ret = pci_for_each_dma_alias(pdev, iommu_flush_dev_irt, iommu);
 	else
@@ -3328,11 +3324,11 @@ static void iommu_flush_irt_and_complete(struct amd_iommu *iommu, u16 devid,
 	if (ret)
 		goto out_err;
 
-	ret = __iommu_queue_command_sync(iommu, &cmd, false);
+	ret = __iommu_completion_wait(iommu, &data);
 	if (ret)
 		goto out_err;
-	raw_spin_unlock_irqrestore(&iommu->lock, flags);
 
+	raw_spin_unlock_irqrestore(&iommu->lock, flags);
 	wait_on_sem(iommu, data);
 	return;
 
Signature · 1 line
2.31.1
author maintainer
#23 lore raw

PATCH 23/38 iommu/amd: Free the level-1 tables of a two-level GCR3 table

In reply to Vasant Hegde

free_gcr3_tbl_level2() frees the leaf tables under each level-1 table via free_gcr3_tbl_level1(), but never frees the level-1 tables themselves. So tearing down a two-level GCR3 table leaks every level-1 table.

This is not reachable today: PASIDs are limited to 16 bits (PASID_MASK), so setup_gcr3_table() only ever needs a single level above the leaves. Free the level-1 tables too, so the table can later be grown for 20-bit PASIDs without leaking.

---
 drivers/iommu/amd/iommu.c | 1 +
 1 file changed, 1 insertion(+)
drivers/iommu/amd/iommu.c +1 -0
index e67f7e2ed39e..ed4661accc97 100644
@@ -1951,6 +1951,7 @@ static void free_gcr3_tbl_level2(u64 *tbl)
 		ptr = iommu_phys_to_virt(tbl[i] & PAGE_MASK);
 
 		free_gcr3_tbl_level1(ptr);
+		iommu_free_pages(ptr);
 	}
 }
 
Signature · 1 line
2.31.1
author maintainer
#24 lore raw

PATCH 24/38 iommu/amd: Update device attach state only after a successful attach

In reply to Vasant Hegde

amd_iommu_attach_device() clears dev_data->defer_attach before it has validated or attempted anything, and recomputes dev_data->use_vapic from the new domain after attach_device() returns, whether or not the attach succeeded.

When the attach fails, the new domain is not installed. Clearing defer_attach then drops the deferred attach for a device that was never attached to the new domain, and use_vapic ends up describing a domain the device is not using.

Clear defer_attach and update use_vapic only once attach_device() succeeds. An early failure, such as the dirty tracking check or set_device_perfopt(), now leaves both fields untouched.

---
 drivers/iommu/amd/iommu.c | 8 +++++---
 1 file changed, 5 insertions(+), 3 deletions(-)
drivers/iommu/amd/iommu.c +5 -3
index ed4661accc97..5d34964169f8 100644
@@ -3034,8 +3034,6 @@ static int amd_iommu_attach_device(struct iommu_domain *dom, struct device *dev,
 	if (dev_data->domain == domain)
 		return 0;
 
-	dev_data->defer_attach = false;
-
 	/*
 	 * Restrict to devices with compatible IOMMU hardware support
 	 * when enforcement of dirty tracking is enabled.
@@ -3053,6 +3051,10 @@ static int amd_iommu_attach_device(struct iommu_domain *dom, struct device *dev,
 		detach_device(dev);
 
 	ret = attach_device(dev, domain);
+	if (ret)
+		return ret;
+
+	dev_data->defer_attach = false;
 
 #ifdef CONFIG_IRQ_REMAP
 	if (AMD_IOMMU_GUEST_IR_VAPIC(amd_iommu_guest_ir)) {
@@ -3063,7 +3065,7 @@ static int amd_iommu_attach_device(struct iommu_domain *dom, struct device *dev,
 	}
 #endif
 
-	return ret;
+	return 0;
 }
 
 static bool amd_iommu_capable(struct device *dev, enum iommu_cap cap)
Signature · 1 line
2.31.1
author maintainer
#25 lore raw

PATCH 25/38 iommu/amd: Write the DTE under the domain lock on attach and detach

In reply to Vasant Hegde

amd_iommu_change_top() and amd_iommu_set_dirty_tracking() rewrite the DTE of every device on the domain's dev_list while holding the domain lock. attach_device() adds the device to dev_list under that lock, but builds and writes its DTE after dropping it.

On concurrent update it's possible that it may end up writing old top or losing HAD bits.

detach_device() has the mirror problem: it clears the DTE before taking the domain lock, so a concurrent change_top() can make the DTE valid again before the device is removed from dev_list.

Hold the domain lock across both the dev_list update and the DTE write, in both the attach and detach paths. This follows the existing pdom->lock -> dte_lock -> iommu->lock ordering already used by change_top().

---
 drivers/iommu/amd/iommu.c | 15 +++++++++------
 1 file changed, 9 insertions(+), 6 deletions(-)
drivers/iommu/amd/iommu.c +9 -6
index 5d34964169f8..a0b296013c80 100644
@@ -2413,14 +2413,16 @@ static int attach_device(struct device *dev,
 	}
 
 skip_caps:
-	/* Update data structures */
-	dev_data->domain = domain;
+	/*
+	 * Build and write the DTE under the domain lock so a concurrent
+	 * change_top() or dirty tracking update cannot be overwritten with
+	 * stale values.
+	 */
 	spin_lock_irqsave(&domain->lock, flags);
+	dev_data->domain = domain;
 	list_add(&dev_data->list, &domain->dev_list);
-	spin_unlock_irqrestore(&domain->lock, flags);
-
-	/* Update device table */
 	dev_update_dte(dev_data, true);
+	spin_unlock_irqrestore(&domain->lock, flags);
 
 out:
 	mutex_unlock(&dev_data->mutex);
@@ -2458,11 +2460,12 @@ static void detach_device(struct device *dev)
 	if (dev_is_pci(dev))
 		pdev_disable_caps(to_pci_dev(dev));
 
+	spin_lock_irqsave(&domain->lock, flags);
+
 	/* Clear DTE and flush the entry */
 	dev_update_dte(dev_data, false);
 
 	/* Flush IOTLB and wait for the flushes to finish */
-	spin_lock_irqsave(&domain->lock, flags);
 	amd_iommu_domain_flush_all(domain);
 	list_del(&dev_data->list);
 	spin_unlock_irqrestore(&domain->lock, flags);
Signature · 1 line
2.31.1
author maintainer
#26 lore raw

PATCH 26/38 iommu/amd: Disable PRI before ATS and PASID

In reply to Vasant Hegde

pdev_enable_caps() enables the device capabilities in the order PASID, ATS, then PRI, but pdev_disable_caps() tore them down as ATS, PASID, then PRI -- not the reverse of enabling.

PRI sits on top of ATS: page requests are issued for failed ATS translations, and with PASID enabled both the requests and (when pri_tlp is set) the responses carry a PASID prefix. Disabling ATS and PASID first left PRI enabled on a function that could no longer issue or accept such transactions, while page requests might still be outstanding.

Disable the capabilities in the reverse order of enabling: PRI, then ATS, then PASID. This also keeps ATS disabled before PASID, as required by the PCIe specification.

Fixes eda8c2860ab6 ("iommu/amd: Enable device ATS/PASID/PRI capabilities independently")
---
 drivers/iommu/amd/iommu.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/iommu/amd/iommu.c +1 -1
index a0b296013c80..5a5cb12869a9 100644
@@ -656,9 +656,9 @@ static void pdev_enable_caps(struct pci_dev *pdev)
 
 static void pdev_disable_caps(struct pci_dev *pdev)
 {
+	pdev_disable_cap_pri(pdev);
 	pdev_disable_cap_ats(pdev);
 	pdev_disable_cap_pasid(pdev);
-	pdev_disable_cap_pri(pdev);
 }
 
 /*
Signature · 1 line
2.31.1
author maintainer
#27 lore raw

PATCH 27/38 iommu/amd: Derive the PPR completion GN bit from the request

In reply to Vasant Hegde

Current amd_iommu_complete_ppr() derived GN bit from page table mode. It also missed IOMMU passthrough mode which also supports PASID.

Pass GN in from the caller instead: amd_iommu_report_ppr_err() uses EVENT_FLAG_PPR_GN, the abort path copies PPR_FLAG_GN from the log entry, and amd_iommu_page_response() reads it back from IOMMU_FAULT_PAGE_REQUEST_PASID_VALID recorded when the fault was reported. Fold __amd_iommu_complete_ppr() into amd_iommu_complete_ppr() now that every caller supplies gn.

Fixes c94252cd5bbc ("iommu/amd: Fix GN bit setting in COMPLETE_PPR_REQUEST command")
---
 drivers/iommu/amd/amd_iommu.h |  3 ++-
 drivers/iommu/amd/iommu.c     | 19 +++----------------
 drivers/iommu/amd/ppr.c       | 14 ++++++++++----
 3 files changed, 15 insertions(+), 21 deletions(-)
drivers/iommu/amd/amd_iommu.h +2 -1
index 315ec397333b..44aebf1e6aee 100644
@@ -83,7 +83,8 @@ int __init amd_iommu_alloc_ppr_log(struct amd_iommu *iommu);
 void __init amd_iommu_free_ppr_log(struct amd_iommu *iommu);
 void amd_iommu_enable_ppr_log(struct amd_iommu *iommu);
 void amd_iommu_poll_ppr_log(struct amd_iommu *iommu);
-int amd_iommu_complete_ppr(struct device *dev, u32 pasid, int status, int tag);
+int amd_iommu_complete_ppr(struct device *dev, u32 pasid, int status, int tag,
+			   bool gn);
 
 /*
  * This function flushes all internal caches of
drivers/iommu/amd/iommu.c +3 -16
index 5a5cb12869a9..a6ed81c9725e 100644
@@ -90,9 +90,6 @@ static void clone_aliases(struct amd_iommu *iommu, struct device *dev);
 
 static int iommu_completion_wait(struct amd_iommu *iommu);
 
-static int __amd_iommu_complete_ppr(struct device *dev, u32 pasid,
-				    int status, int tag, bool gn);
-
 /****************************************************************************
  *
  * Helper functions
@@ -907,7 +904,7 @@ static void amd_iommu_report_ppr_err(struct amd_iommu *iommu, volatile u32 *even
 
 	gn = (flags & EVENT_FLAG_PPR_GN);
 
-	__amd_iommu_complete_ppr(&pdev->dev, pasid, IOMMU_PAGE_RESP_FAILURE, tag, gn);
+	amd_iommu_complete_ppr(&pdev->dev, pasid, IOMMU_PAGE_RESP_FAILURE, tag, gn);
 	pci_dev_put(pdev);
 }
 
@@ -1870,8 +1867,8 @@ static void dev_flush_pasid_all(struct iommu_dev_data *dev_data,
 	amd_iommu_dev_flush_pasid_pages(dev_data, pasid, 0, U64_MAX);
 }
 
-static int __amd_iommu_complete_ppr(struct device *dev, u32 pasid,
-				    int status, int tag, bool gn)
+int amd_iommu_complete_ppr(struct device *dev, u32 pasid, int status,
+			   int tag, bool gn)
 {
 	struct iommu_dev_data *dev_data;
 	struct amd_iommu *iommu;
@@ -1885,16 +1882,6 @@ static int __amd_iommu_complete_ppr(struct device *dev, u32 pasid,
 	return iommu_queue_command(iommu, &cmd);
 }
 
-int amd_iommu_complete_ppr(struct device *dev, u32 pasid, int status, int tag)
-{
-	struct iommu_dev_data *dev_data = dev_iommu_priv_get(dev);
-	bool gn;
-
-	gn = pdom_is_v2_pgtbl_mode(dev_data->domain);
-
-	return __amd_iommu_complete_ppr(dev, pasid, status, tag, gn);
-}
-
 /****************************************************************************
  *
  * The next functions belong to the domain allocation. A domain is
drivers/iommu/amd/ppr.c +10 -4
index 2039a9dd71ac..1181dc31795f 100644
@@ -144,8 +144,11 @@ static void iommu_call_iopf_notifier(struct amd_iommu *iommu, u64 *raw)
 		goto out;
 	}
 
-	event.fault.prm.flags |= IOMMU_FAULT_PAGE_RESPONSE_NEEDS_PASID;
-	event.fault.prm.flags |= IOMMU_FAULT_PAGE_REQUEST_PASID_VALID;
+	/* PPR_FLAG_GN means this request carries a valid PASID. */
+	if (PPR_FLAGS(raw[0]) & PPR_FLAG_GN) {
+		event.fault.prm.flags |= IOMMU_FAULT_PAGE_RESPONSE_NEEDS_PASID;
+		event.fault.prm.flags |= IOMMU_FAULT_PAGE_REQUEST_PASID_VALID;
+	}
 	if (PPR_TAG_LAST_PAGE(raw[0]))
 		event.fault.prm.flags |= IOMMU_FAULT_PAGE_REQUEST_LAST_PAGE;
 
@@ -157,7 +160,8 @@ static void iommu_call_iopf_notifier(struct amd_iommu *iommu, u64 *raw)
 out:
 	/* Nobody cared, abort */
 	amd_iommu_complete_ppr(&pdev->dev, PPR_PASID(raw[0]),
-			       IOMMU_PAGE_RESP_FAILURE, PPR_TAG(raw[0]));
+			       IOMMU_PAGE_RESP_FAILURE, PPR_TAG(raw[0]),
+			       PPR_FLAGS(raw[0]) & PPR_FLAG_GN);
 	pci_dev_put(pdev);
 }
 
@@ -241,7 +245,9 @@ void amd_iommu_iopf_uninit(struct amd_iommu *iommu)
 void amd_iommu_page_response(struct device *dev, struct iopf_fault *evt,
 			     struct iommu_page_response *resp)
 {
-	amd_iommu_complete_ppr(dev, resp->pasid, resp->code, resp->grpid);
+	bool gn = evt->fault.prm.flags & IOMMU_FAULT_PAGE_REQUEST_PASID_VALID;
+
+	amd_iommu_complete_ppr(dev, resp->pasid, resp->code, resp->grpid, gn);
 }
 
 int amd_iommu_iopf_add_device(struct amd_iommu *iommu,
Signature · 1 line
2.31.1
author maintainer
#28 lore raw

PATCH 28/38 iommu/amd: Complete a PPR from a device the IOMMU did not probe

In reply to Vasant Hegde

iommu_call_iopf_notifier() reads dev_data->max_pasids after looking up the PCI device. dev_iommu_priv_get() is NULL when probe failed, and the abort path then calls amd_iommu_complete_ppr(), which reads dev_data->devid and the device's IOMMU. A kdump kernel reuses the previous device table, so a device that failed probe can still have PPR set. The invalid-PPR event path has the same dependency.

COMPLETE_PPR needs the IOMMU that owns the log and the DeviceID from the entry. amd_iommu_complete_ppr() takes those directly. Report the fault only when the device was probed. Otherwise complete the last page of the group from that DeviceID. The invalid-PPR event path completes the same way and no longer looks the device up.

---
 drivers/iommu/amd/amd_iommu.h |  4 ++--
 drivers/iommu/amd/iommu.c     | 27 +++++----------------------
 drivers/iommu/amd/ppr.c       | 27 +++++++++++++++++++++++----
 3 files changed, 30 insertions(+), 28 deletions(-)
drivers/iommu/amd/amd_iommu.h +2 -2
index 44aebf1e6aee..b13eaa7620da 100644
@@ -83,8 +83,8 @@ int __init amd_iommu_alloc_ppr_log(struct amd_iommu *iommu);
 void __init amd_iommu_free_ppr_log(struct amd_iommu *iommu);
 void amd_iommu_enable_ppr_log(struct amd_iommu *iommu);
 void amd_iommu_poll_ppr_log(struct amd_iommu *iommu);
-int amd_iommu_complete_ppr(struct device *dev, u32 pasid, int status, int tag,
-			   bool gn);
+int amd_iommu_complete_ppr(struct amd_iommu *iommu, u16 devid, u32 pasid,
+			   int status, int tag, bool gn);
 
 /*
  * This function flushes all internal caches of
drivers/iommu/amd/iommu.c +5 -22
index a6ed81c9725e..9b82fe5c56b1 100644
@@ -877,7 +877,6 @@ static void amd_iommu_report_page_fault(struct amd_iommu *iommu,
 static void amd_iommu_report_ppr_err(struct amd_iommu *iommu, volatile u32 *event,
 				     u16 devid, u64 address, int flags)
 {
-	struct pci_dev *pdev;
 	struct device *dev = iommu->iommu.dev;
 	u32 pasid = PPR_PASID(*((u64 *)event));
 	int tag = event[1] & 0x03FF;
@@ -892,20 +891,9 @@ static void amd_iommu_report_ppr_err(struct amd_iommu *iommu, volatile u32 *even
 	if (flags & EVENT_FLAG_PPR_RX)
 		return;
 
-	pdev = pci_get_domain_bus_and_slot(iommu->pci_seg->id, PCI_BUS_NUM(devid),
-					   devid & 0xff);
-	if (!pdev)
-		return;
-
-	if (!dev_iommu_priv_get(&pdev->dev)) {
-		pci_dev_put(pdev);
-		return;
-	}
-
 	gn = (flags & EVENT_FLAG_PPR_GN);
-
-	amd_iommu_complete_ppr(&pdev->dev, pasid, IOMMU_PAGE_RESP_FAILURE, tag, gn);
-	pci_dev_put(pdev);
+	amd_iommu_complete_ppr(iommu, devid, pasid, IOMMU_PAGE_RESP_FAILURE,
+			       tag, gn);
 }
 
 static void iommu_print_event(struct amd_iommu *iommu, void *__evt)
@@ -1867,17 +1855,12 @@ static void dev_flush_pasid_all(struct iommu_dev_data *dev_data,
 	amd_iommu_dev_flush_pasid_pages(dev_data, pasid, 0, U64_MAX);
 }
 
-int amd_iommu_complete_ppr(struct device *dev, u32 pasid, int status,
-			   int tag, bool gn)
+int amd_iommu_complete_ppr(struct amd_iommu *iommu, u16 devid, u32 pasid,
+			   int status, int tag, bool gn)
 {
-	struct iommu_dev_data *dev_data;
-	struct amd_iommu *iommu;
 	struct iommu_cmd cmd;
 
-	dev_data = dev_iommu_priv_get(dev);
-	iommu    = get_amd_iommu_from_dev(dev);
-
-	build_complete_ppr(&cmd, dev_data->devid, pasid, status, tag, gn);
+	build_complete_ppr(&cmd, devid, pasid, status, tag, gn);
 
 	return iommu_queue_command(iommu, &cmd);
 }
drivers/iommu/amd/ppr.c +23 -4
index 1181dc31795f..7d660a81df3a 100644
@@ -116,10 +116,27 @@ static void iommu_call_iopf_notifier(struct amd_iommu *iommu, u64 *raw)
 		return;
 	}
 
+	/*
+	 * Probe never attached this device, or it is no longer on the
+	 * bus. A kdump kernel can reuse a DTE that still has PPR set.
+	 * The log entry carries the DeviceID, so complete the group
+	 * here and do not touch dev_data.
+	 */
 	pdev = pci_get_domain_bus_and_slot(iommu->pci_seg->id,
 					   PCI_BUS_NUM(devid), devid & 0xff);
-	if (!pdev)
+	dev_data = pdev ? dev_iommu_priv_get(&pdev->dev) : NULL;
+	if (!dev_data) {
+		pr_info_ratelimited("PPR for unprobed device: 0x%x\n", devid);
+
+		if (PPR_TAG_LAST_PAGE(raw[0])) {
+			amd_iommu_complete_ppr(iommu, devid, PPR_PASID(raw[0]),
+					       IOMMU_PAGE_RESP_FAILURE,
+					       PPR_TAG(raw[0]),
+					       PPR_FLAGS(raw[0]) & PPR_FLAG_GN);
+		}
+		pci_dev_put(pdev);
 		return;
+	}
 
 	if (!ppr_is_valid(iommu, raw))
 		goto out;
@@ -136,7 +153,6 @@ static void iommu_call_iopf_notifier(struct amd_iommu *iommu, u64 *raw)
 	 * PASID zero is used for requests from the I/O device without
 	 * a PASID
 	 */
-	dev_data = dev_iommu_priv_get(&pdev->dev);
 	if (event.fault.prm.pasid == 0 ||
 	    event.fault.prm.pasid >= dev_data->max_pasids) {
 		pr_info_ratelimited("Invalid PASID : 0x%x, device : 0x%x\n",
@@ -159,7 +175,7 @@ static void iommu_call_iopf_notifier(struct amd_iommu *iommu, u64 *raw)
 
 out:
 	/* Nobody cared, abort */
-	amd_iommu_complete_ppr(&pdev->dev, PPR_PASID(raw[0]),
+	amd_iommu_complete_ppr(iommu, devid, PPR_PASID(raw[0]),
 			       IOMMU_PAGE_RESP_FAILURE, PPR_TAG(raw[0]),
 			       PPR_FLAGS(raw[0]) & PPR_FLAG_GN);
 	pci_dev_put(pdev);
@@ -245,9 +261,12 @@ void amd_iommu_iopf_uninit(struct amd_iommu *iommu)
 void amd_iommu_page_response(struct device *dev, struct iopf_fault *evt,
 			     struct iommu_page_response *resp)
 {
+	struct iommu_dev_data *dev_data = dev_iommu_priv_get(dev);
 	bool gn = evt->fault.prm.flags & IOMMU_FAULT_PAGE_REQUEST_PASID_VALID;
 
-	amd_iommu_complete_ppr(dev, resp->pasid, resp->code, resp->grpid, gn);
+	amd_iommu_complete_ppr(get_amd_iommu_from_dev_data(dev_data),
+			       dev_data->devid, resp->pasid, resp->code,
+			       resp->grpid, gn);
 }
 
 int amd_iommu_iopf_add_device(struct amd_iommu *iommu,
Signature · 1 line
2.31.1
author maintainer
#29 lore raw

PATCH 29/38 iommu/amd: Restore an SVA PASID after PCI reset

In reply to Vasant Hegde

From: Santosh Shukla <[email protected]>

pci_dev_reset_iommu_done() re-attaches every PASID with old set to the group's blocking domain. iommu_sva_set_dev_pasid() rejects any old domain, so the core warns and the PASID stays unprogrammed until the device is unbound.

prepare() has already cleared the GCR3 entry and dropped the SVA tracking record. A blocking old domain is therefore a fresh attach. Replacing one attached domain with another still returns -EOPNOTSUPP.

Fixes c279e83953d9 ("iommu: Introduce pci_dev_reset_iommu_prepare/done()")
[Updated description - Vasant]
---
 drivers/iommu/amd/pasid.c | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)
drivers/iommu/amd/pasid.c +6 -1
index 40be5902087c..87fd2688574c 100644
@@ -109,7 +109,12 @@ static int iommu_sva_set_dev_pasid(struct iommu_domain *domain,
 	unsigned long flags;
 	int ret = -EINVAL;
 
-	if (old)
+	/*
+	 * pci_dev_reset_iommu_done() passes the blocking domain. prepare()
+	 * has already cleared this PASID, so program it again. Replacing
+	 * one attached domain with another is not supported.
+	 */
+	if (old && old->type != IOMMU_DOMAIN_BLOCKED)
 		return -EOPNOTSUPP;
 
 	/* PASID zero is used for requests from the I/O device without PASID */
Signature · 1 line
2.31.1
author maintainer
#30 lore raw

PATCH 30/38 iommu/amd: Keep the GCR3 table while PASIDs are attached

In reply to Vasant Hegde

pci_dev_reset_iommu_prepare() attaches the blocked domain before clearing the device's PASIDs. detach_device() frees the GCR3 table during that transition, so a later amd_iommu_clear_gcr3() dereferences a NULL root.

Do not free the GCR3 table while it still has attached PASIDs. The RID GCR3[0] entry is still cleared before detach, and setup_gcr3_table() reuses the retained table on re-attach. Free it from amd_iommu_release_device() instead, after the blocked-domain attach has cleared the DTE.

Fixes c9e8701132e6 ("iommu/amd: Setup GCR3 table in advance if domain is SVA capable")
---
 drivers/iommu/amd/iommu.c | 24 ++++++++++++++++++++----
 1 file changed, 20 insertions(+), 4 deletions(-)
drivers/iommu/amd/iommu.c +20 -4
index 9b82fe5c56b1..e2a22ef3a1dd 100644
@@ -1966,12 +1966,12 @@ static int setup_gcr3_table(struct gcr3_tbl_info *gcr3_info,
 	int nid = iommu ? dev_to_node(&iommu->dev->dev) : NUMA_NO_NODE;
 	int domid;
 
+	if (gcr3_info->gcr3_tbl)
+		return 0;
+
 	if (levels > amd_iommu_max_glx_val)
 		return -EINVAL;
 
-	if (gcr3_info->gcr3_tbl)
-		return -EBUSY;
-
 	/* Allocate per device domain ID */
 	domid = amd_iommu_pdom_id_alloc();
 	if (domid <= 0)
@@ -2264,7 +2264,7 @@ static void destroy_gcr3_table(struct iommu_dev_data *dev_data,
 	if (pdom_is_v2_pgtbl_mode(pdom))
 		update_gcr3(dev_data, 0, 0, false);
 
-	if (gcr3_info->gcr3_tbl == NULL)
+	if (gcr3_info->gcr3_tbl == NULL || gcr3_info->pasid_cnt)
 		return;
 
 	free_gcr3_table(gcr3_info);
@@ -2540,6 +2540,21 @@ static struct iommu_device *amd_iommu_probe_device(struct device *dev)
 	return iommu_dev;
 }
 
+static void amd_iommu_release_device(struct device *dev)
+{
+	struct iommu_dev_data *dev_data = dev_iommu_priv_get(dev);
+
+	/*
+	 * A device that requires direct mappings is released to the identity
+	 * domain, whose DTE can still point at the GCR3 table. Keep the table
+	 * in that case; a later probe reuses it.
+	 */
+	if (dev_data->domain)
+		return;
+
+	destroy_gcr3_table(dev_data, NULL);
+}
+
 static struct iommu_group *amd_iommu_device_group(struct device *dev)
 {
 	if (dev_is_pci(dev))
@@ -3244,6 +3259,7 @@ const struct iommu_ops amd_iommu_ops = {
 	.domain_alloc_paging_flags = amd_iommu_domain_alloc_paging_flags,
 	.domain_alloc_sva = amd_iommu_domain_alloc_sva,
 	.probe_device = amd_iommu_probe_device,
+	.release_device = amd_iommu_release_device,
 	.device_group = amd_iommu_device_group,
 	.get_resv_regions = amd_iommu_get_resv_regions,
 	.is_attach_deferred = amd_iommu_is_attach_deferred,
Signature · 1 line
2.31.1
author maintainer
#31 lore raw

PATCH 31/38 iommu/amd: Return -ENOMEM when SVA PASID allocation fails

In reply to Vasant Hegde

iommu_sva_set_dev_pasid() returns -EINVAL when the pdom_dev_data allocation fails. An invalid PASID or a disabled PASID is an invalid argument. Running out of memory is not, so return -ENOMEM and let the bind caller tell the two failures apart.

---
 drivers/iommu/amd/pasid.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/iommu/amd/pasid.c +1 -1
index 87fd2688574c..a5ca5c2b8241 100644
@@ -128,7 +128,7 @@ static int iommu_sva_set_dev_pasid(struct iommu_domain *domain,
 	/* Add PASID to protection domain pasid list */
 	pdom_dev_data = kzalloc_obj(*pdom_dev_data);
 	if (pdom_dev_data == NULL)
-		return ret;
+		return -ENOMEM;
 
 	pdom_dev_data->pasid = pasid;
 	pdom_dev_data->dev_data = dev_data;
Signature · 1 line
2.31.1
author maintainer
#32 lore raw

PATCH 32/38 iommu/amd: Complete an aborted PPR group only on its last page

In reply to Vasant Hegde

iommu_call_iopf_notifier() sends COMPLETE_PPR for every rejected request. A group of several pages then gets several responses for one group index. A response for an earlier page can complete a newer group that reused the index.

Respond only when the request is the last page of its group. A request that is not the last page needs no acknowledgement.

Fixes 978d626b8f1a ("iommu/amd: Add IO page fault notifier handler")
---
 drivers/iommu/amd/ppr.c | 15 +++++++++++----
 1 file changed, 11 insertions(+), 4 deletions(-)
drivers/iommu/amd/ppr.c +11 -4
index 7d660a81df3a..20ad2e46b240 100644
@@ -174,10 +174,17 @@ static void iommu_call_iopf_notifier(struct amd_iommu *iommu, u64 *raw)
 	return;
 
 out:
-	/* Nobody cared, abort */
-	amd_iommu_complete_ppr(iommu, devid, PPR_PASID(raw[0]),
-			       IOMMU_PAGE_RESP_FAILURE, PPR_TAG(raw[0]),
-			       PPR_FLAGS(raw[0]) & PPR_FLAG_GN);
+	/*
+	 * A page-request group is completed once. Responding to a page
+	 * that is not the last one sends another completion for the same
+	 * group index, which can complete a newer group that reused it.
+	 */
+	if (PPR_TAG_LAST_PAGE(raw[0])) {
+		amd_iommu_complete_ppr(iommu, devid, PPR_PASID(raw[0]),
+				       IOMMU_PAGE_RESP_FAILURE,
+				       PPR_TAG(raw[0]),
+				       PPR_FLAGS(raw[0]) & PPR_FLAG_GN);
+	}
 	pci_dev_put(pdev);
 }
 
Signature · 1 line
2.31.1
author maintainer
#33 lore raw

PATCH 33/38 iommu/amd: Discard partial page requests when the PPR log overflows

In reply to Vasant Hegde

An overflow drops requests that were not written into the log. The IRQ thread consumes what is still there and then restarts the log. A group whose last page was dropped stays on the device partial list. The next group that reuses the index is merged with those requests, and the partials remain until the device leaves the IOPF queue.

Discard the partials after the log has stopped and before it is enabled again. The handler has already polled every entry that survived.

Fixes 978d626b8f1a ("iommu/amd: Add IO page fault notifier handler")
---
 drivers/iommu/amd/ppr.c | 15 +++++++++++++++
 1 file changed, 15 insertions(+)
drivers/iommu/amd/ppr.c +15 -0
index 20ad2e46b240..795e31735fea 100644
@@ -59,6 +59,21 @@ void __init amd_iommu_free_ppr_log(struct amd_iommu *iommu)
  */
 void amd_iommu_restart_ppr_log(struct amd_iommu *iommu)
 {
+	u32 status;
+
+	/*
+	 * Overflow stops the log. The IRQ thread has already consumed
+	 * the entries that were written. A group whose last page was
+	 * dropped is still on the partial list; discard it before the
+	 * log restarts and another group reuses the index.
+	 */
+	status = readl(iommu->mmio_base + MMIO_STATUS_OFFSET);
+	if (status & MMIO_STATUS_PPR_RUN_MASK)
+		return;
+
+	if (iommu->iopf_queue)
+		iopf_queue_discard_partial(iommu->iopf_queue);
+
 	amd_iommu_restart_log(iommu, "PPR", CONTROL_PPRINT_EN,
 			      CONTROL_PPRLOG_EN, MMIO_STATUS_PPR_RUN_MASK,
 			      MMIO_STATUS_PPR_OVERFLOW_MASK);
Signature · 1 line
2.31.1
author maintainer
#34 lore raw

PATCH 34/38 iommu/amd: Allocate the GCR3 table from the device

In reply to Vasant Hegde

setup_gcr3_table() conflated allocating the per-device GCR3 table with programming the v2 RID GCR3[0] entry. Because the table can outlive the RID domain, split the two and change where the table is allocated based on the device's PASID capability:

- PASID-capable device: the GCR3 table is allocated once in amd_iommu_probe_device() and kept for the lifetime of the device. It is freed only in amd_iommu_release_device(), after the DTE has been cleared.

- Non-PASID device with a v2 page-table domain: the table is allocated on demand in attach_device() and freed in detach_device() when the domain is detached.

With allocation handled per the above, attach_device() only programs GCR3[0] (via set_default_gcr3_entry()) for a v2 domain. detach_device() clears GCR3[0] (via clear_default_gcr3_entry()) for a v2 domain and, for a non-PASID device, frees the table there. set_dte_entry() installs the GCR3 table in the DTE only for an SVA-capable domain.

Rename the helpers accordingly: setup_gcr3_table() becomes alloc_gcr3_table(), and init_gcr3_table()/destroy_gcr3_table() are replaced by the narrower set_default_gcr3_entry()/clear_default_gcr3_entry().

---
 drivers/iommu/amd/iommu.c | 109 +++++++++++++++++++++-----------------
 1 file changed, 59 insertions(+), 50 deletions(-)
drivers/iommu/amd/iommu.c +59 -50
index e2a22ef3a1dd..d2f31a29a704 100644
@@ -1959,11 +1959,14 @@ static int get_gcr3_levels(int pasids)
 	return levels ? (DIV_ROUND_UP(levels, 9) - 1) : levels;
 }
 
-static int setup_gcr3_table(struct gcr3_tbl_info *gcr3_info,
-			    struct amd_iommu *iommu, int pasids)
+static int alloc_gcr3_table(struct iommu_dev_data *dev_data,
+			    struct amd_iommu *iommu)
 {
+	struct gcr3_tbl_info *gcr3_info = &dev_data->gcr3_info;
+	int pasids = dev_data->max_pasids > 0 ? dev_data->max_pasids : 1;
 	int levels = get_gcr3_levels(pasids);
-	int nid = iommu ? dev_to_node(&iommu->dev->dev) : NUMA_NO_NODE;
+	int nid = iommu && iommu->dev ? dev_to_node(&iommu->dev->dev) :
+					NUMA_NO_NODE;
 	int domid;
 
 	if (gcr3_info->gcr3_tbl)
@@ -1981,6 +1984,7 @@ static int setup_gcr3_table(struct gcr3_tbl_info *gcr3_info,
 	gcr3_info->gcr3_tbl = iommu_alloc_pages_node_sz(nid, GFP_ATOMIC, SZ_4K);
 	if (gcr3_info->gcr3_tbl == NULL) {
 		amd_iommu_pdom_id_free(domid);
+		gcr3_info->domid = 0;
 		return -ENOMEM;
 	}
 
@@ -2172,7 +2176,12 @@ static void set_dte_entry(struct amd_iommu *iommu,
 	amd_iommu_make_clear_dte(dev_data, &new);
 
 	old_domid = READ_ONCE(dte->data[1]) & DTE_DOMID_MASK;
-	if (gcr3_info->gcr3_tbl)
+	/*
+	 * Update GCR3 related info if device is attached to PASID
+	 * capable domain
+	 */
+	if (pdom_is_sva_capable(domain) && gcr3_info->gcr3_tbl &&
+	    !(dev_data->perfopt && pdom_is_in_pt_mode(domain)))
 		set_dte_gcr3_table(dev_data, &new);
 	else if (domain->domain.type == IOMMU_DOMAIN_IDENTITY)
 		set_dte_passthrough(dev_data, domain, &new);
@@ -2216,58 +2225,27 @@ static void dev_update_dte(struct iommu_dev_data *dev_data, bool set)
 		clear_dte_entry(iommu, dev_data);
 }
 
-/*
- * If domain is SVA capable then initialize GCR3 table. Also if domain is
- * in v2 page table mode then update GCR3[0].
- */
-static int init_gcr3_table(struct iommu_dev_data *dev_data,
-			   struct protection_domain *pdom)
+/* Program GCR3[0], the RID page table. Only a v2 domain has one. */
+static int set_default_gcr3_entry(struct iommu_dev_data *dev_data,
+				  struct protection_domain *pdom)
 {
-	struct amd_iommu *iommu = get_amd_iommu_from_dev_data(dev_data);
-	int max_pasids = dev_data->max_pasids;
 	struct pt_iommu_x86_64_hw_info pt_info;
-	int ret = 0;
-
-	 /*
-	  * If domain is in pt mode then setup GCR3 table only if device
-	  * is PASID capable
-	  */
-	if (pdom_is_in_pt_mode(pdom) && !pdev_pasid_supported(dev_data))
-		return ret;
 
-	/*
-	 * By default, setup GCR3 table to support MAX PASIDs
-	 * supported by the device/IOMMU.
-	 */
-	ret = setup_gcr3_table(&dev_data->gcr3_info, iommu,
-			       max_pasids > 0 ?  max_pasids : 1);
-	if (ret)
-		return ret;
-
-	/* Setup GCR3[0] only if domain is setup with v2 page table mode */
 	if (!pdom_is_v2_pgtbl_mode(pdom))
-		return ret;
+		return 0;
 
 	pt_iommu_x86_64_hw_info(&pdom->amdv2, &pt_info);
-	ret = update_gcr3(dev_data, 0, __sme_set(pt_info.gcr3_pt), true);
-	if (ret)
-		free_gcr3_table(&dev_data->gcr3_info);
-
-	return ret;
+	return update_gcr3(dev_data, 0, __sme_set(pt_info.gcr3_pt), true);
 }
 
-static void destroy_gcr3_table(struct iommu_dev_data *dev_data,
-			       struct protection_domain *pdom)
+static void clear_default_gcr3_entry(struct iommu_dev_data *dev_data)
 {
 	struct gcr3_tbl_info *gcr3_info = &dev_data->gcr3_info;
 
-	if (pdom_is_v2_pgtbl_mode(pdom))
-		update_gcr3(dev_data, 0, 0, false);
-
-	if (gcr3_info->gcr3_tbl == NULL || gcr3_info->pasid_cnt)
+	if (gcr3_info->gcr3_tbl == NULL)
 		return;
 
-	free_gcr3_table(gcr3_info);
+	update_gcr3(dev_data, 0, 0, false);
 }
 
 static int pdom_attach_iommu(struct amd_iommu *iommu,
@@ -2358,9 +2336,18 @@ static int attach_device(struct device *dev,
 	if (dev_data->perfopt && pdom_is_in_pt_mode(domain))
 		goto skip_caps;
 
-	/* Setup GCR3 table */
-	if (pdom_is_sva_capable(domain)) {
-		ret = init_gcr3_table(dev_data, domain);
+	/*
+	 * A PASID-capable device already owns a table from probe. A paging
+	 * domain with v2 page table without PASID allocates one here.
+	 */
+	if (pdom_is_v2_pgtbl_mode(domain)) {
+		ret = alloc_gcr3_table(dev_data, iommu);
+		if (ret) {
+			pdom_detach_iommu(iommu, domain);
+			goto out;
+		}
+
+		ret = set_default_gcr3_entry(dev_data, domain);
 		if (ret) {
 			pdom_detach_iommu(iommu, domain);
 			goto out;
@@ -2440,9 +2427,17 @@ static void detach_device(struct device *dev)
 	list_del(&dev_data->list);
 	spin_unlock_irqrestore(&domain->lock, flags);
 
-	/* Clear GCR3 table */
-	if (pdom_is_sva_capable(domain))
-		destroy_gcr3_table(dev_data, domain);
+	/*
+	 * GCR3[0] belongs to the paging domain w/ v2 page table.
+	 * A device without PASID has no other entries, so the
+	 * table is freed with that domain.
+	 */
+	if (pdom_is_v2_pgtbl_mode(domain)) {
+		clear_default_gcr3_entry(dev_data);
+
+		if (!pdev_pasid_supported(dev_data))
+			free_gcr3_table(&dev_data->gcr3_info);
+	}
 
 	/* Update data structures */
 	dev_data->domain = NULL;
@@ -2537,6 +2532,17 @@ static struct iommu_device *amd_iommu_probe_device(struct device *dev)
 		return ERR_PTR(-ENODEV);
 	}
 
+	/*
+	 * PASID-capable devices own a GCR3 table for the life of the device.
+	 * A paging domain with v2 page table without PASID allocates one
+	 * later, from attach_device().
+	 */
+	if (pdev_pasid_supported(dev_data)) {
+		ret = alloc_gcr3_table(dev_data, iommu);
+		if (ret)
+			return ERR_PTR(ret);
+	}
+
 	return iommu_dev;
 }
 
@@ -2552,7 +2558,10 @@ static void amd_iommu_release_device(struct device *dev)
 	if (dev_data->domain)
 		return;
 
-	destroy_gcr3_table(dev_data, NULL);
+	WARN_ON(dev_data->gcr3_info.pasid_cnt);
+
+	if (dev_data->gcr3_info.gcr3_tbl)
+		free_gcr3_table(&dev_data->gcr3_info);
 }
 
 static struct iommu_group *amd_iommu_device_group(struct device *dev)
Signature · 1 line
2.31.1
author maintainer
#35 lore raw

PATCH 35/38 iommu/amd: Drain the PPR log before detaching an SVA PASID

In reply to Vasant Hegde

amd_iommu_remove_dev_pasid() can return while a page request for that PASID is still sitting in the hardware PPR log. The PPR thread may later enqueue that request after the core has already freed the PASID attach handle, and the IOPF worker then dereferences the freed handle -- a use-after-free.

The device driver issues a PASID stop before unbind, so no new request is generated for this PASID, but requests already posted remain in the log. Process those entries and then flush the IOPF workqueue so that queued work completes before the handle is freed.

Serialize PPR log consumption with a new per-IOMMU mutex (ppr_lock):
factor the existing poll into __amd_iommu_poll_ppr_log() under the lock, and have both the PPR thread and the drain path take it.

---
 drivers/iommu/amd/amd_iommu.h       |  1 +
 drivers/iommu/amd/amd_iommu_types.h |  2 ++
 drivers/iommu/amd/init.c            |  1 +
 drivers/iommu/amd/pasid.c           | 10 +++++++++-
 drivers/iommu/amd/ppr.c             | 29 ++++++++++++++++++++++++++++-
 5 files changed, 41 insertions(+), 2 deletions(-)
drivers/iommu/amd/amd_iommu.h +1 -0
index b13eaa7620da..e0cb8cbc6f36 100644
@@ -83,6 +83,7 @@ int __init amd_iommu_alloc_ppr_log(struct amd_iommu *iommu);
 void __init amd_iommu_free_ppr_log(struct amd_iommu *iommu);
 void amd_iommu_enable_ppr_log(struct amd_iommu *iommu);
 void amd_iommu_poll_ppr_log(struct amd_iommu *iommu);
+void amd_iommu_drain_ppr_log(struct iommu_dev_data *dev_data);
 int amd_iommu_complete_ppr(struct amd_iommu *iommu, u16 devid, u32 pasid,
 			   int status, int tag, bool gn);
 
drivers/iommu/amd/amd_iommu_types.h +2 -0
index bbfc561d6abf..ac34169b5913 100644
@@ -692,6 +692,8 @@ struct amd_iommu {
 
 	/* Base of the PPR log, if present */
 	u8 *ppr_log;
+	/* Serializes PPR log consumption */
+	struct mutex ppr_lock;
 
 	/* Name for PPR log interrupt */
 	unsigned char ppr_irq_name[16];
drivers/iommu/amd/init.c +1 -0
index e020459513d8..3a4624f5cc24 100644
@@ -1975,6 +1975,7 @@ static int __init init_iommu_one(struct amd_iommu *iommu, struct ivhd_header *h,
 	iommu->pci_seg = pci_seg;
 
 	raw_spin_lock_init(&iommu->lock);
+	mutex_init(&iommu->ppr_lock);
 	iommu->cmd_sem_val = 0;
 
 	/* Add IOMMU to internal data structures */
drivers/iommu/amd/pasid.c +9 -1
index a5ca5c2b8241..d0e2bf7921bf 100644
@@ -154,9 +154,10 @@ void amd_iommu_remove_dev_pasid(struct device *dev, ioasid_t pasid,
 				struct iommu_domain *domain)
 {
 	struct protection_domain *sva_pdom;
+	struct iommu_dev_data *dev_data = dev_iommu_priv_get(dev);
 	unsigned long flags;
 
-	if (!is_pasid_valid(dev_iommu_priv_get(dev), pasid))
+	if (!is_pasid_valid(dev_data, pasid))
 		return;
 
 	sva_pdom = to_pdomain(domain);
@@ -167,6 +168,13 @@ void amd_iommu_remove_dev_pasid(struct device *dev, ioasid_t pasid,
 	remove_pdom_dev_pasid(sva_pdom, dev, pasid);
 
 	spin_unlock_irqrestore(&sva_pdom->lock, flags);
+
+	/*
+	 * Queued faults reference the attach handle, which the caller
+	 * frees once this returns. Consume requests already in the log
+	 * and flush the work they queued.
+	 */
+	amd_iommu_drain_ppr_log(dev_data);
 }
 
 static void iommu_sva_domain_free(struct iommu_domain *domain)
drivers/iommu/amd/ppr.c +28 -1
index 795e31735fea..6d4b29905d40 100644
@@ -203,10 +203,12 @@ static void iommu_call_iopf_notifier(struct amd_iommu *iommu, u64 *raw)
 	pci_dev_put(pdev);
 }
 
-void amd_iommu_poll_ppr_log(struct amd_iommu *iommu)
+static void __amd_iommu_poll_ppr_log(struct amd_iommu *iommu)
 {
 	u32 head, tail;
 
+	lockdep_assert_held(&iommu->ppr_lock);
+
 	head = readl(iommu->mmio_base + MMIO_PPR_HEAD_OFFSET);
 	tail = readl(iommu->mmio_base + MMIO_PPR_TAIL_OFFSET);
 
@@ -250,6 +252,31 @@ void amd_iommu_poll_ppr_log(struct amd_iommu *iommu)
 	}
 }
 
+void amd_iommu_poll_ppr_log(struct amd_iommu *iommu)
+{
+	mutex_lock(&iommu->ppr_lock);
+	__amd_iommu_poll_ppr_log(iommu);
+	mutex_unlock(&iommu->ppr_lock);
+}
+
+/*
+ * Consume PPR requests already logged for this device, then flush the
+ * IOPF work they queued. The caller is releasing a PASID attach handle.
+ */
+void amd_iommu_drain_ppr_log(struct iommu_dev_data *dev_data)
+{
+	struct amd_iommu *iommu = get_amd_iommu_from_dev_data(dev_data);
+
+	if (!iommu->ppr_log || !dev_data->ppr)
+		return;
+
+	mutex_lock(&iommu->ppr_lock);
+	__amd_iommu_poll_ppr_log(iommu);
+	mutex_unlock(&iommu->ppr_lock);
+
+	iopf_queue_flush_dev(dev_data->dev);
+}
+
 /**************************************************************
  *
  * IOPF handling stuff
Signature · 1 line
2.31.1
author maintainer
#36 lore raw

PATCH 36/38 iommu/amd: Drain the PPR log before removing a device from the IOPF queue

In reply to Vasant Hegde

detach_device() flushes the software fault queue and removes the device from the IOPF queue before it clears the DTE. The DTE is what enables PPR, so the IOMMU can still log a page request after fault_param is gone. iommu_report_device_fault() warns when it finds a handler and no fault parameter.

Clear and invalidate the DTE first. A device on the IOPF queue then drains the PPR log and is removed from the queue. Disable the PCI capabilities after that, for every device, so PRI stays enabled until the logged requests have been answered.

---
 drivers/iommu/amd/iommu.c | 24 ++++++++++++------------
 1 file changed, 12 insertions(+), 12 deletions(-)
drivers/iommu/amd/iommu.c +12 -12
index d2f31a29a704..7203672f36cb 100644
@@ -2408,25 +2408,25 @@ static void detach_device(struct device *dev)
 	if (WARN_ON(!dev_data->domain))
 		goto out;
 
-	/* Remove IOPF handler */
+	/* Clear DTE and flush the entry */
+	spin_lock_irqsave(&domain->lock, flags);
+	dev_update_dte(dev_data, false);
+	amd_iommu_domain_flush_all(domain);
+	list_del(&dev_data->list);
+	spin_unlock_irqrestore(&domain->lock, flags);
+
+	/*
+	 * Stop new page requests, then finish the ones already logged.
+	 * Disable the PCI capabilities only after that, for every device.
+	 */
 	if (dev_data->ppr) {
-		iopf_queue_flush_dev(dev);
+		amd_iommu_drain_ppr_log(dev_data);
 		amd_iommu_iopf_remove_device(iommu, dev_data);
 	}
 
 	if (dev_is_pci(dev))
 		pdev_disable_caps(to_pci_dev(dev));
 
-	spin_lock_irqsave(&domain->lock, flags);
-
-	/* Clear DTE and flush the entry */
-	dev_update_dte(dev_data, false);
-
-	/* Flush IOTLB and wait for the flushes to finish */
-	amd_iommu_domain_flush_all(domain);
-	list_del(&dev_data->list);
-	spin_unlock_irqrestore(&domain->lock, flags);
-
 	/*
 	 * GCR3[0] belongs to the paging domain w/ v2 page table.
 	 * A device without PASID has no other entries, so the
Signature · 1 line
2.31.1
author maintainer
#37 lore raw

PATCH 37/38 iommu/amd: Don't detach SVA PASIDs from the mm release notifier

In reply to Vasant Hegde

sva_mn_release() runs when the mm page tables are about to be freed. It calls remove_dev_pasid(), which invokes amd_iommu_clear_gcr3() without the group mutex and trips its lockdep assertion. It also tears down the PASID attachment and driver metadata behind the IOMMU core's back.

Stop removing the attachment from the notifier. The notifier only has to keep the IOMMU from walking page tables that are about to be freed. Leave pasid_cnt and pdom_dev_data intact and let the normal core-driven detach take the group mutex, clear the entry and remove the attachment.

Do not clear the GCR3 entry in the notifier either. A cleared entry does not produce a recoverable page request, so a device that still issues PASID traffic would report an IOMMU error until amd_iommu_remove_dev_pasid() runs. Instead, allocate dummy page table root, shared by all IOMMUs. sva_mn_release() path replaces actual GCR3 pointer with dummy page table root. A walk through the root faults instead of following freed memory.

Fixes a5a91e54846d ("iommu/amd: Add SVA domain support")
Cc Liang Wendy <[email protected]>
Cc Jason Gunthorpe <[email protected]>
---
 drivers/iommu/amd/amd_iommu.h       |  4 ++++
 drivers/iommu/amd/amd_iommu_types.h |  2 --
 drivers/iommu/amd/init.c            | 11 ++++++++++
 drivers/iommu/amd/iommu.c           | 32 +++++++++++++++++++++++++++++
 drivers/iommu/amd/pasid.c           | 13 ++++++++----
 5 files changed, 56 insertions(+), 6 deletions(-)
drivers/iommu/amd/amd_iommu.h +4 -0
index e0cb8cbc6f36..76cb2f99f9c8 100644
@@ -77,6 +77,10 @@ void amd_iommu_iopf_remove_device(struct amd_iommu *iommu,
 int amd_iommu_set_gcr3(struct iommu_dev_data *dev_data,
 		       ioasid_t pasid, unsigned long gcr3);
 int amd_iommu_clear_gcr3(struct iommu_dev_data *dev_data, ioasid_t pasid);
+int amd_iommu_set_gcr3_fault_pgd(struct iommu_dev_data *dev_data,
+				 ioasid_t pasid);
+int __init amd_iommu_sva_fault_pgd_alloc(void);
+void __init amd_iommu_sva_fault_pgd_free(void);
 
 /* PPR */
 int __init amd_iommu_alloc_ppr_log(struct amd_iommu *iommu);
drivers/iommu/amd/amd_iommu_types.h +0 -2
index ac34169b5913..26c75b5289e8 100644
@@ -453,8 +453,6 @@ extern bool amdr_ivrs_remap_support;
 /* Making iterating over protection_domain->dev_data_list easier */
 #define for_each_pdom_dev_data(pdom_dev_data, pdom) \
 	list_for_each_entry(pdom_dev_data, &pdom->dev_data_list, list)
-#define for_each_pdom_dev_data_safe(pdom_dev_data, next, pdom) \
-	list_for_each_entry_safe((pdom_dev_data), (next), &pdom->dev_data_list, list)
 
 #define for_each_ivhd_dte_flags(entry) \
 	list_for_each_entry((entry), &amd_ivhd_dev_flags_list, list)
drivers/iommu/amd/init.c +11 -0
index 3a4624f5cc24..f8953a2bc1eb 100644
@@ -2451,6 +2451,16 @@ static int __init amd_iommu_init_pci(void)
 		iommu_set_cwwb_range(iommu);
 	}
 
+	/*
+	 * iommu_init_pci() populates amd_iommu_efr from the IOMMU, so check
+	 * PASID support only after it runs.
+	 */
+	if (amd_iommu_pasid_supported()) {
+		ret = amd_iommu_sva_fault_pgd_alloc();
+		if (ret)
+			goto out;
+	}
+
 	/*
 	 * Order is important here to make sure any unity map requirements are
 	 * fulfilled. The unity mappings are created and written to the device
@@ -3281,6 +3291,7 @@ static struct syscore amd_iommu_syscore = {
 static void __init free_iommu_resources(void)
 {
 	free_iommu_all();
+	amd_iommu_sva_fault_pgd_free();
 	amd_iommu_pdom_id_destroy();
 	free_pci_segments();
 }
drivers/iommu/amd/iommu.c +32 -0
index 7203672f36cb..517225edb257 100644
@@ -2065,6 +2065,38 @@ int amd_iommu_set_gcr3(struct iommu_dev_data *dev_data, ioasid_t pasid,
 	return ret;
 }
 
+/* Dummy page table root, used in sva_mn_release() path */
+static void *sva_fault_pgd;
+
+int __init amd_iommu_sva_fault_pgd_alloc(void)
+{
+	sva_fault_pgd = iommu_alloc_pages_node_sz(NUMA_NO_NODE, GFP_KERNEL,
+						  SZ_4K);
+	return sva_fault_pgd ? 0 : -ENOMEM;
+}
+
+void __init amd_iommu_sva_fault_pgd_free(void)
+{
+	if (sva_fault_pgd)
+		iommu_free_pages(sva_fault_pgd);
+
+	sva_fault_pgd = NULL;
+}
+
+/*
+ * Point a still-attached PASID at the permanent zero root.
+ * pasid_cnt stays put; amd_iommu_clear_gcr3() drops the slot on detach.
+ */
+int amd_iommu_set_gcr3_fault_pgd(struct iommu_dev_data *dev_data,
+				 ioasid_t pasid)
+{
+	if (WARN_ON_ONCE(!sva_fault_pgd))
+		return -ENODEV;
+
+	return update_gcr3(dev_data, pasid,
+			   iommu_virt_to_phys(sva_fault_pgd), true);
+}
+
 int amd_iommu_clear_gcr3(struct iommu_dev_data *dev_data, ioasid_t pasid)
 {
 	struct gcr3_tbl_info *gcr3_info = &dev_data->gcr3_info;
drivers/iommu/amd/pasid.c +9 -4
index d0e2bf7921bf..6d126246d850 100644
@@ -79,7 +79,7 @@ static void sva_arch_invalidate_secondary_tlbs(struct mmu_notifier *mn,
 
 static void sva_mn_release(struct mmu_notifier *mn, struct mm_struct *mm)
 {
-	struct pdom_dev_data *pdom_dev_data, *next;
+	struct pdom_dev_data *pdom_dev_data;
 	struct protection_domain *sva_pdom;
 	unsigned long flags;
 
@@ -87,9 +87,14 @@ static void sva_mn_release(struct mmu_notifier *mn, struct mm_struct *mm)
 
 	spin_lock_irqsave(&sva_pdom->lock, flags);
 
-	/* Assume dev_data_list contains same PASID with different devices */
-	for_each_pdom_dev_data_safe(pdom_dev_data, next, sva_pdom)
-		remove_dev_pasid(pdom_dev_data);
+	/*
+	 * The mm page tables are freed when this returns. Point each
+	 * still-attached PASID at the permanent zero root so a later
+	 * access faults instead of walking freed memory.
+	 */
+	for_each_pdom_dev_data(pdom_dev_data, sva_pdom)
+		amd_iommu_set_gcr3_fault_pgd(pdom_dev_data->dev_data,
+					     pdom_dev_data->pasid);
 
 	spin_unlock_irqrestore(&sva_pdom->lock, flags);
 }
Signature · 1 line
2.31.1
author maintainer
#38 lore raw

PATCH 38/38 iommu/amd: Explicitly disable GAPPI

In reply to Vasant Hegde

From: "Naveen N Rao (AMD)" <[email protected]>

Since commit b03500f03ea0 ("KVM: SVM: Generate GA log IRQs only if the associated vCPUs is blocking"), running a VM with AVIC enabled and a passed-through (VFIO) device can result in unexpected host interrupts with kernel log messages such as:
No irq handler for 99.39

Or worse, the host hangs, or panics with:

  Kernel panic - not syncing: Unexpected external interrupt 0x80

AMD IOMMU supports GAPPI mode (Guest APIC Physical Processor Interrupt) wherein device interrupts for vCPUs that are not running can result in host interrupts. More specifically, if IRTE[IsRun]=0 and IRTE[GALogIntr]=0, and if GAPPI mode is enabled, IOMMU sends a host interrupt to IRTE[destination] with vector number derived from the low byte of IRTE[GATag] (which KVM populates with the vCPU index).

Prior to the above commit, KVM never cleared IRTE[GALogIntr] and so device interrupts for non-running vCPUs always resulted in a GALog entry, with an optional GALog interrupt to the host. Since the above commit, KVM clears IRTE[GALogIntr] if the vCPU is scheduled out without blocking, which can trigger GAPPI interrupts if GAPPI mode is enabled.

GAPPI mode is controlled by GAPPIEn in the IOMMU Control register with a reset value of 0 and Linux never sets it. So, GAPPI mode is not enabled by default. However, enabling SEV-SNP in the BIOS sets GAPPIEn to 1 resulting in GAPPI mode being enabled on boot.

Fix this by disabling GAPPI mode in iommu_disable(). Disabling GAPPI mode in kdump path is left for the series that enables GAPPI, since GAPPI is never otherwise left enabled by Linux kernel today.

Fixes b03500f03ea0 ("KVM: SVM: Generate GA log IRQs only if the associated vCPUs is blocking")
---
 drivers/iommu/amd/amd_iommu_types.h | 1 +
 drivers/iommu/amd/init.c            | 3 +++
 2 files changed, 4 insertions(+)
drivers/iommu/amd/amd_iommu_types.h +1 -0
index 26c75b5289e8..30408756021a 100644
@@ -180,6 +180,7 @@
 #define CONTROL_EPH_EN		45
 #define CONTROL_XT_EN		50
 #define CONTROL_INTCAPXT_EN	51
+#define CONTROL_GAPPI_EN	55
 #define CONTROL_GCR3TRPMODE	58
 #define CONTROL_IRTCACHEDIS	59
 #define CONTROL_SNPAVIC_EN	61
drivers/iommu/amd/init.c +3 -0
index f8953a2bc1eb..84495fe8110a 100644
@@ -483,6 +483,9 @@ static void iommu_disable(struct amd_iommu *iommu)
 	iommu_feature_disable(iommu, CONTROL_GALOG_EN);
 	iommu_feature_disable(iommu, CONTROL_GAINT_EN);
 
+	/* Disable IOMMU GAPPI */
+	iommu_feature_disable(iommu, CONTROL_GAPPI_EN);
+
 	/* Disable IOMMU PPR logging */
 	iommu_feature_disable(iommu, CONTROL_PPRLOG_EN);
 	iommu_feature_disable(iommu, CONTROL_PPRINT_EN);
Signature · 1 line
2.31.1