Skip to contentSkip to conversation

iommu/arm-smmu-v3: Implement Runtime/System Sleep ops

PATCH In review Pranjal Shrivastava 11 participants 71 messages Sep 29 – Nov 18

Subsystems (8)
lore
Share & tools
lore
#0 lore raw

v11 cover iommu/arm-smmu-v3: Implement Runtime/System Sleep ops

As arm-smmu-v3 rapidly finds its way into SoCs designed for hand-held devices, power management capabilities, similar to its predecessors, are crucial for these applications. This series introduces power management support for the arm-smmu-v3 driver.

Design
======
The arm-smmu-v3 primarily operates with in-memory data structures through HW registers pointing to these data structures. The proposed design makes use of this fact for implementing suspend and resume ops, centered around a software gate embedded in the command queue.

1. CMDQ Gate (CMDQ_PROD_STOP_FLAG)
To safely manage runtime PM without regressing performance on high core count servers or systems not opting for runtime power management, this series introduces a CMDQ_PROD_STOP_FLAG (bit 30) in the command queue's producer index. The flag acts as a Point of Commitment in the cmpxchg loop of arm_smmu_cmdq_issue_cmdlist(), ensuring no new indices are reserved once suspension begins.

2. Suspend / Resume Flow
The suspend operation follows a multi-stage quiesce sequence:
a. Stop Traffic: Sets SMMUEN=0 and GBPA=Abort to halt new transactions. b. Gate CMDQ: Sets the CMDQ_PROD_STOP_FLAG to block new submissions. c. Command Flush: Waits for any in-flight "owner" threads to commit
their reserved indices to hardware.
d. SW Quiesce: Waits for all concurrent threads to release the shared

     cmdq->lock, ensuring no CPUs are left polling CONS register.

e. HW Drain: Polls the CMDQ until all committed commands are consumed. f. IRQ Quiesce: Disables hardware IRQs and waits for racing handlers to
complete via synchronize_irq()

Entering the suspend sequence implies that the device has no active clients. In v8, a surgical state-correction is added to runtime_suspend:
if draining fails, the software trackers (cons and owner_prod) are forced to align with the masked producer index. This voids any stale commands for the next session and prevents deadlocks or spurious executions upon resumption.

The resume operation clears the STOP_FLAG & performs a full device reset via arm_smmu_device_reset(), which re-initializes the HW using the SW-copies maintained by the driver and clears all cached configurations.

3. Guarding Hardware Access and Elision
The driver ensures the SMMU is active before hardware access via arm_smmu_rpm_get() and arm_smmu_rpm_put() helpers. To maintain code clarity, invalidation call-sites no longer perform manual elision checks; instead, elision is authoritative within the CMDQ submission path.

The renamed helper, arm_smmu_is_active(), is preserved only for critical diagnostic (ATC), early-drop (Page Response), and gerror short-circuits. For ATC invalidations, devlinks must guarantee the SMMU is active if the endpoint is active; a WARN_ON_ONCE() catches inconsistencies.

4. Implementation-Specific Quiescing (Tegra VCMDQ) Implementation-specific gating and draining are consolidated into a unified quiesce_and_drain_queues callback. The tegra241-cmdqv driver is updated to gate all active local virtual queues (VINTF0) before draining.

5. Interrupt Re-config
a. Wired irqs: The series refactors arm_smmu_setup_irqs to allow separate installation of handlers, aiding in correct re-initialization.

b. MSIs: The genirq/msi core caches the msi_msg in irq_chip_write_msi_msg() and provides msi_device_domain_restore_msi_msgs(), which arm_smmu_resume_msis() invokes during resume.

c. GERROR: Late-breaking global errors are captured and handled immediately after SMMU disablement during suspend to ensure no diagnostic information is lost.

Scalability and Performance
===========================
A key design goal of this series is to ensure that high-performance systems (typically servers) that do not enable runtime PM are not penalized. By embedding a stop flag in the command queue's producer index and designing RPM helpers to perform only read-only checks when RPM is disabled, command submission on these systems incurs negligible overhead. Power-managed systems only utilize runtime PM atomics as necessary, ensuring that scalability is maintained across all hardware classes.

Sashiko Reviews and Documentation
=================================
The series was run through Sashiko locally. In response to the review feedback, extensive verbose comments have been added across the series to thoroughly document hardware/software synchronization invariants, memory ordering dependencies (Point of Commitment, dma_wmb vs. smp_mb), and devlink power guarantees. Several edge-case race conditions, unmasking bugs, and resource leak paths were also addressed.

[v11]
- Replaced platform_device_msi_rewrite() and driver-side msi_msg caching with generic genirq/msi core support as suggested and provided by tglx (Thomas Gleixner):
* Cache desc->msg in irq_chip_write_msi_msg() and document why the assignment in __pci_write_msi_msg() remains for direct callers.
* Provide msi_device_domain_restore_msi_msgs() in kernel/irq/msi.c.
* Update arm_smmu_resume_msis() to call msi_device_domain_restore_msi_msgs() and drop manual msi_msg caching from arm_smmu_write_msi_msg().
- Rebased onto v7.3-rc4.

[v10]
- https://lore.kernel.org/all/[email protected]/
- Picked up common drain helpers from Nicolin's PRI series v3 [1].
- Introduced platform_device_msi_rewrite() in platform/msi core (suggested by Jason).
- Fixed the stale interrupt issue caused by calling arm_smmu_setup_irqs() early in probe (as reported by Sashiko in v9) by passing a bool to arm_smmu_device_reset() to ensure irqs aren't set-up again on resume.
- Fixed a CMDQ gate bypass race where threads waking from poll_until_not_full() could commit commands after STOP_FLAG was asserted
- Fixed a masking issue in __arm_smmu_cmdq_issue_cmdlist() & tegra241-cmdqv
- Added tegra241_vcmdq_wait_quiescent() to wait for in-flight owner threads
- Fixed VCMDQ drain loop error handling to continue draining remaining queues rather than abandoning them on timeout (pointed by Sashiko in v9)
- Explicitly zeroed *_IRQ_CFG0 registers during resume as they reset to unknown values.
- Cleared ARM_SMMU_FEAT_MSI on MSI setup fallback to avoid spurious MSI rewrites on resume.
- Retitled GERROR patch to "Factor out arm_smmu_handle_gerror()" for clarity
- Handled devlink creation failure in arm_smmu_probe_device()
- Added checks for the retval of arm_smmu_rpm_get() in arm_smmu_disable_action() & arm_smmu_device_shutdown()
- Clarified rationale for asynchronous put in teardown and shutdown paths where hardware has already been explicitly disabled.
- Documented safety of eliding ATC invalidations during suspend based on PCIe link power states and devlink guarantees per Jason's comment.
- Fixed stack timer lifecycle in KUnit tests using timer_setup_on_stack() and timer_destroy_on_stack(), and resolved mock register endianness.
- Added extensive verbose comments across the patches explaining locking, synchronization invariants, and devlink power guarantees based on local Sashiko review.
- Collected Reviewed-by tags from Jason Gunthorpe.
- Rebased onto latest arm/smmu/updates
[1] https://lore.kernel.org/all/[email protected]/

[v9]
- https://lore.kernel.org/all/[email protected]/
- Replaced atomic_fetch_or_relaxed() with atomic_fetch_or() for correct ordering while asserting the STOP_FLAG
- Moved arm_smmu_drain_queues() after the cmdq->lock wait loop in runtime_suspend() as per feedback in v8.
- Refactored suspend sequence to use arm_smmu_disable_irqs() and synchronize_irq() for safe GERROR handling.
- Fixed an off-by-one error in suspend polling timeouts.
- Dropped arm_smmu_cmdq_can_elide() check from inv_range
- Renamed arm_smmu_cmdq_can_elide() to arm_smmu_is_active().
- Removed redundant bitwise masking from owner_prod reads.
- Added comments to explain locking, gating and elision better.
- Added comments to explain secondary cmdq draining and gating.
- Rebased on arm/smmu/updates

[v8]
- https://lore.kernel.org/all/[email protected]/
- Centralized elision logic: dropped redundant checks from invalidation call-sites; elision is now authoritative within the CMDQ layer.
- Renamed elision helper to arm_smmu_cmdq_can_elide() and preserved it only for diagnostic/safety paths (ATC, GERROR, Page Response).
- Consolidated implementation-specific gating and draining into a unified quiesce_and_drain_queues callback.
- Updated tegra241-cmdqv to gate virtual queues before draining, addressing non-deterministic timeouts from guest-side submissions.
- Re-ordered probe sequence to enable pm_runtime only at the end, aligning with SMMUv2 and simplifying error paths.
- Refactored KUnit tests for better, addressed Nicolin's comments & added a multi-threaded kthread race test.
- Refactored RPM helpers to use early-return patterns for improved clarity.
- Collected R-bs from Nicolin.

[v7]
- https://lore.kernel.org/all/[email protected]/
- Rebased on the latest arm/smmu/updates branch (which has the removal of struct arm_smmu_cmdq_ent merged)
- Converted manual cmpxchg loops in suspend/resume to use atomics
- Re-worked to elide invalidations solely based on the CMDQ_PROD_STOP_FLAG via arm_smmu_can_elide(), dropping any need for pm_runtime_get_if_active
- Added an smp_mb() fence in the reset sequence to ensure that the SMMU acquires all RAM updates made by newly un-gated threads before SMMUEN=1
- Implemented bitwise masking for the PROD register to prevent software metadata (STOP_FLAG) bits from being written to physical hardware.
- Introduced a KUnit test suite to verify the CMDQ gating algorithm

[v6]
- https://lore.kernel.org/all/[email protected]/
- Replaced the atomic nr_cmdq_users counter with CMDQ_PROD_STOP_FLAG to eliminate atomic overhead on high-core count servers.
- Implemented a 5-step quiesce sequence in runtime_suspend including pipeline flushes and software completion barriers.
- Introduced arm_smmu_rpm_get_if_active() to elide TLB/CFG/ATC invalidations when the SMMU is suspended.
- Added WARN_ON_ONCE() in invalidation paths to detect inconsistent power states for active endpoints.
- Refined batch submission in __arm_smmu_domain_inv_range() to ensure clean state when dropping batches.
- Refactored GERROR handling for better integration with suspend.
- Added Suggested-by tags for Daniel Mentz.

[v5]
- https://lore.kernel.org/all/[email protected]/
- Refactored GERROR handling into a helper function and invoked it during runtime suspend after disabling the SMMU to capture any late-breaking gerrors as suggested by Jason.
- Updated arm_smmu_page_response to be power-state aware and drop page faults received while suspended.
- Included a patch from Ashish to correctly restore PROD and CONS indices for tegra241-cmdqv after a hardware reset.
- Collected Reviewed-bys from Mostafa and Nicolin.

[v4]
- https://lore.kernel.org/all/[email protected]/
- Dropped the pm_runtime_get_if_not_suspended() API in favor of a simpler, driver-specific biased counter (nr_cmdq_users) to manage runtime PM state.
- Reworked the suspend callback to poll on the biased counter before disabling the SMMU.
- Addressed comments for the MSI refactor.

[v3]
- https://lore.kernel.org/all/[email protected]/
- Introduced pm_runtime_get_if_not_suspended API to avoid races due to bouncing RPM states while eliding TLBIs as pointed out by Daniel.
- Addressed Nicolin's comments regarding msi_resume and CMDQV flush
- Addressed Daniel's comments about CMDQ locking and draining
- Addressed issues related to draining the evtq and priq
- Dropped the code to identify and track user-space attachments

[v2]
- https://lore.kernel.org/all/[email protected]/
- Introduced arm_smmu_rpm_get_if_active for eliding TLBIs & CFGIs
- Updated the rpm helper invocation strategy.
- Drained all queues in suspend callback (including tegra241-cmdv)
- Cache and restore msi_msg instead of free-ing realloc-ing on resume
- Added support to identify and track user-space attachments
- Fixed the setup_irqs as per Nicolin & Mostafa's suggestions
- Used force_runtime_suspend/resume instead as per Mostafa's suggestion.
- Added "Reviewed-by" line from Mostafa on an unchanged patch

[v1]
- https://lore.kernel.org/all/[email protected]/

Ashish Mhetre (1):
iommu/tegra241-cmdqv: Restore PROD and CONS after resume

Nicolin Chen (2):
iommu/arm-smmu-v3: Add Q_POS() macro iommu/arm-smmu-v3: Add arm_smmu_drain_queue() helper

Pranjal Shrivastava (12):
iommu/arm-smmu-v3: Refactor arm_smmu_setup_irqs iommu/tegra241-cmdqv: Add a helper to drain VCMDQs iommu/arm-smmu-v3: Add a helper to drain cmd queues genirq/msi: Cache MSI message in irq_chip_write_msi_msg() iommu/arm-smmu-v3: Restore MSI config on resume iommu/arm-smmu-v3: Factor out arm_smmu_handle_gerror() iommu/arm-smmu-v3: Add CMDQ_PROD_STOP_FLAG to gate CMDQ submissions iommu/tegra241-cmdqv: Add a helper to quiesce VCMDQs iommu/arm-smmu-v3: Implement pm_runtime & system sleep ops iommu/arm-smmu-v3: Enable pm_runtime and setup devlinks iommu/arm-smmu-v3: Invoke pm_runtime before hw access iommu/arm-smmu-v3: Add KUnit unit tests for Runtime PM

Thomas Gleixner (1):
genirq/msi: Provide msi_device_domain_restore_msi_msgs()

 .../arm/arm-smmu-v3/arm-smmu-v3-iommufd.c     |  20 +-
 .../iommu/arm/arm-smmu-v3/arm-smmu-v3-test.c  | 215 ++++++
 drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c   | 702 +++++++++++++++++-
 drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h   |  29 +
 .../iommu/arm/arm-smmu-v3/tegra241-cmdqv.c    | 128 ++++
 drivers/pci/msi/msi.c                         |   6 +
 include/linux/msi.h                           |   2 +
 kernel/irq/msi.c                              |  46 ++
 8 files changed, 1109 insertions(+), 39 deletions(-)

base-commit: 93f51579e7df248780214094418f205253383cc5

Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#1 lore raw

PATCH v11 1/16 iommu/arm-smmu-v3: Refactor arm_smmu_setup_irqs

Refactor arm_smmu_setup_irqs by splitting it into two parts, one for registering interrupt handlers and the other one for enabling interrupt generation in the hardware. This refactor helps in re-initialization of hardware interrupts as part of a subsequent patch that enables runtime power management for the arm-smmu-v3 driver.

Additionally, pass a 'resume' flag to arm_smmu_device_reset() to skip registering IRQ handlers again during resume. On probe, handlers are registered after queues are configured but before enabling translation.

---
 drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c | 75 +++++++++++++++------
 1 file changed, 56 insertions(+), 19 deletions(-)
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +56 -19
index 5732f3ba0122..270e6617a19a 100644
@@ -4756,14 +4756,55 @@ static void arm_smmu_setup_unique_irqs(struct arm_smmu_device *smmu)
 	}
 }
 
+static void arm_smmu_enable_irqs(struct arm_smmu_device *smmu)
+{
+	int ret;
+	u32 irqen_flags = IRQ_CTRL_EVTQ_IRQEN | IRQ_CTRL_GERROR_IRQEN;
+
+	if (smmu->features & ARM_SMMU_FEAT_PRI)
+		irqen_flags |= IRQ_CTRL_PRIQ_IRQEN;
+
+	/*
+	 * Enable interrupt generation on the SMMU.
+	 * As per the ARM SMMUv3 spec section 6.3.17 (SMMU_IRQ_CTRL):
+	 *
+	 * Completion of an Update of x_IRQEN from 0 to 1 guarantees that the
+	 * MSI configuration in SMMU_x_IRQ_CFG{0,1,2} will be used for all
+	 * future MSIs generated from source x. All wired or MSI interrupts
+	 * that are triggered from a source relate to occurrences that happened
+	 * after the completion of the Update that enabled the source. It is
+	 * not permitted to trigger an interrupt that relates to an occurrence
+	 * that happened before the source was enabled, even if the source was
+	 * previously enabled at the time of the occurrence.
+	 */
+	ret = arm_smmu_write_reg_sync(smmu, irqen_flags,
+				      ARM_SMMU_IRQ_CTRL, ARM_SMMU_IRQ_CTRLACK);
+	if (ret)
+		dev_warn(smmu->dev, "failed to enable irqs\n");
+}
+
+static int arm_smmu_disable_irqs(struct arm_smmu_device *smmu)
+{
+	return arm_smmu_write_reg_sync(smmu, 0, ARM_SMMU_IRQ_CTRL,
+				       ARM_SMMU_IRQ_CTRLACK);
+}
+
 static int arm_smmu_setup_irqs(struct arm_smmu_device *smmu)
 {
 	int ret, irq;
-	u32 irqen_flags = IRQ_CTRL_EVTQ_IRQEN | IRQ_CTRL_GERROR_IRQEN;
 
-	/* Disable IRQs first */
-	ret = arm_smmu_write_reg_sync(smmu, 0, ARM_SMMU_IRQ_CTRL,
-				      ARM_SMMU_IRQ_CTRLACK);
+	/*
+	 * Disable IRQs first as required by the Arm SMMUv3 spec.
+	 * As per the ARM SMMUv3 spec section 6.3.17 (SMMU_IRQ_CTRL):
+	 *
+	 * An Update of x_IRQEN from 1 to 0 completes when all prior MSIs have
+	 * completed. An MSI has completed when it is visible to its
+	 * Shareability domain, or when it has aborted, and the abort is
+	 * recorded in the appropriate SMMU_(*_)GERROR bit. Completion of this
+	 * Update guarantees that no new MSI writes or wired edge events from
+	 * source x become visible until the source is re-enabled.
+	 */
+	ret = arm_smmu_disable_irqs(smmu);
 	if (ret) {
 		dev_err(smmu->dev, "failed to disable irqs\n");
 		return ret;
@@ -4785,15 +4826,6 @@ static int arm_smmu_setup_irqs(struct arm_smmu_device *smmu)
 	} else
 		arm_smmu_setup_unique_irqs(smmu);
 
-	if (smmu->features & ARM_SMMU_FEAT_PRI)
-		irqen_flags |= IRQ_CTRL_PRIQ_IRQEN;
-
-	/* Enable interrupt generation on the SMMU */
-	ret = arm_smmu_write_reg_sync(smmu, irqen_flags,
-				      ARM_SMMU_IRQ_CTRL, ARM_SMMU_IRQ_CTRLACK);
-	if (ret)
-		dev_warn(smmu->dev, "failed to enable irqs\n");
-
 	return 0;
 }
 
@@ -4841,7 +4873,7 @@ static void arm_smmu_write_strtab(struct arm_smmu_device *smmu)
 	writel_relaxed(reg, smmu->base + ARM_SMMU_STRTAB_BASE_CFG);
 }
 
-static int arm_smmu_device_reset(struct arm_smmu_device *smmu)
+static int arm_smmu_device_reset(struct arm_smmu_device *smmu, bool resume)
 {
 	int ret;
 	u32 reg, enables;
@@ -4943,12 +4975,17 @@ static int arm_smmu_device_reset(struct arm_smmu_device *smmu)
 		}
 	}
 
-	ret = arm_smmu_setup_irqs(smmu);
-	if (ret) {
-		dev_err(smmu->dev, "failed to setup irqs\n");
-		return ret;
+	if (!resume) {
+		ret = arm_smmu_setup_irqs(smmu);
+		if (ret) {
+			dev_err(smmu->dev, "failed to setup irqs\n");
+			return ret;
+		}
 	}
 
+	/* Enable interrupt generation on the SMMU */
+	arm_smmu_enable_irqs(smmu);
+
 	if (is_kdump_kernel())
 		enables &= ~(CR0_EVTQEN | CR0_PRIQEN);
 
@@ -5594,7 +5631,7 @@ static int arm_smmu_device_probe(struct platform_device *pdev)
 	arm_smmu_rmr_install_bypass_ste(smmu);
 
 	/* Reset the device */
-	ret = arm_smmu_device_reset(smmu);
+	ret = arm_smmu_device_reset(smmu, false);
 	if (ret) {
 		arm_smmu_device_disable(smmu);
 		return ret;
Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#2 lore raw

Re: [PATCH v11 01/16] iommu/arm-smmu-v3: Refactor arm_smmu_setup_irqs

Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 6 lines

Refactor arm_smmu_setup_irqs by splitting it into two parts, one for registering interrupt handlers and the other one for enabling interrupt generation in the hardware. This refactor helps in re-initialization of hardware interrupts as part of a subsequent patch that enables runtime power management for the arm-smmu-v3 driver.

Quoted 8 lines

Additionally, pass a 'resume' flag to arm_smmu_device_reset() to skip registering IRQ handlers again during resume. On probe, handlers are registered after queues are configured but before enabling translation.

Sashiko has reviewed this patch and found no issues. It looks great!

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
maintainer
#3 lore raw

Re: [PATCH v11 01/16] iommu/arm-smmu-v3: Refactor arm_smmu_setup_irqs

In reply to Pranjal Shrivastava

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c static int arm_smmu_device_probe(struct platform_device *pdev) · line 5634

Quoted 6 lines · Pranjal Shrivastava
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +1 -1
@@ -5594,7 +5631,7 @@ static int arm_smmu_device_probe(struct platform_device *pdev)
 	arm_smmu_rmr_install_bypass_ste(smmu);
 
 	/* Reset the device */
-	ret = arm_smmu_device_reset(smmu);
+	ret = arm_smmu_device_reset(smmu, false);

It's a minor thing, but I have an irrational dislike of 'bool' paramaters because they're so opaque at the callsite. One way to tidy if up would be to rename arm_smmu_device_reset() to __arm_smmu_device_reset() and then have wrapper functions around that (e.g. arm_smmu_device_reset_resume()) but I actually wonder wheter you need the bool at all. Why can't you figure out the resume state from the 'struct device' instead?

Will

#4 lore raw

PATCH v11 2/16 iommu/arm-smmu-v3: Add Q_POS() macro

In reply to Pranjal Shrivastava

From: Nicolin Chen <[email protected]>

A queue position, the wrap bit combined with the index, is Q_WRP | Q_IDX. It is a (max_n_shift + 1)-bit value that wraps at twice the queue capacity. queue_inc_cons(), queue_sync_cons_ovf(), and queue_inc_prod_n() currently compute such positions by open-coding the two macros at each call site.

Add a Q_POS() macro and switch the open-coded sites to it.

A subsequent change will apply Q_POS() to a position difference, to count the entries that a queue pointer moved past.

No functional change intended.

Assisted-by Claude:claude-fable-5
---
 drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c | 11 +++++------
 drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h |  2 ++
 2 files changed, 7 insertions(+), 6 deletions(-)
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +5 -6
index 270e6617a19a..06b7de2e6e4b 100644
@@ -181,8 +181,8 @@ static void queue_sync_cons_out(struct arm_smmu_queue *q)
 
 static void queue_inc_cons(struct arm_smmu_ll_queue *q)
 {
-	u32 cons = (Q_WRP(q, q->cons) | Q_IDX(q, q->cons)) + 1;
-	q->cons = Q_OVF(q->cons) | Q_WRP(q, cons) | Q_IDX(q, cons);
+	u32 cons = Q_POS(q, q->cons) + 1;
+	q->cons = Q_OVF(q->cons) | Q_POS(q, cons);
 }
 
 static void queue_sync_cons_ovf(struct arm_smmu_queue *q)
@@ -192,8 +192,7 @@ static void queue_sync_cons_ovf(struct arm_smmu_queue *q)
 	if (likely(Q_OVF(llq->prod) == Q_OVF(llq->cons)))
 		return;
 
-	llq->cons = Q_OVF(llq->prod) | Q_WRP(llq, llq->cons) |
-		      Q_IDX(llq, llq->cons);
+	llq->cons = Q_OVF(llq->prod) | Q_POS(llq, llq->cons);
 	queue_sync_cons_out(q);
 }
 
@@ -218,8 +217,8 @@ static int queue_sync_prod_in(struct arm_smmu_queue *q)
 
 static u32 queue_inc_prod_n(struct arm_smmu_ll_queue *q, int n)
 {
-	u32 prod = (Q_WRP(q, q->prod) | Q_IDX(q, q->prod)) + n;
-	return Q_OVF(q->prod) | Q_WRP(q, prod) | Q_IDX(q, prod);
+	u32 prod = Q_POS(q, q->prod) + n;
+	return Q_OVF(q->prod) | Q_POS(q, prod);
 }
 
 static void queue_poll_init(struct arm_smmu_device *smmu,
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h +2 -0
index dd2fee2f560e..84e618a7fa9e 100644
@@ -187,6 +187,8 @@ struct arm_vsmmu;
 
 #define Q_IDX(llq, p)			((p) & ((1 << (llq)->max_n_shift) - 1))
 #define Q_WRP(llq, p)			((p) & (1 << (llq)->max_n_shift))
+/* A position is Q_WRP | Q_IDX, wrapping at twice the queue capacity */
+#define Q_POS(llq, p)			(Q_WRP(llq, p) | Q_IDX(llq, p))
 #define Q_OVERFLOW_FLAG			(1U << 31)
 #define Q_OVF(p)			((p) & Q_OVERFLOW_FLAG)
 #define Q_ENT(q, p)			((q)->base +			\
Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#5 lore raw

Re: [PATCH v11 02/16] iommu/arm-smmu-v3: Add Q_POS() macro

Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 9 lines

From: Nicolin Chen <[email protected]>

A queue position, the wrap bit combined with the index, is Q_WRP | Q_IDX. It is a (max_n_shift + 1)-bit value that wraps at twice the queue capacity. queue_inc_cons(), queue_sync_cons_ovf(), and queue_inc_prod_n() currently compute such positions by open-coding the two macros at each call site.

Add a Q_POS() macro and switch the open-coded sites to it.

Quoted 8 lines

A subsequent change will apply Q_POS() to a position difference, to count the entries that a queue pointer moved past.

No functional change intended.

Assisted-by Claude:claude-fable-5

Sashiko has reviewed this patch and found no issues. It looks great!

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
#6 lore raw

PATCH v11 3/16 iommu/arm-smmu-v3: Add arm_smmu_drain_queue() helper

In reply to Pranjal Shrivastava

From: Nicolin Chen <[email protected]>

Add a counting-based arm_smmu_drain_queue() helper, to replace queue specific polling loops. Its until_empty mode serves the suspend and runtime PM routines that would drain the CMDQ. Any timed-out drain fires a WARN_ON as well, since reaching the timeout would take some stuck consumer in any realistic case.

The existing queue_poll() API is not reusable for such a drain: it is the atomic busy-wait for the command issuing paths, and it assumes a hardware consumer making progress. A drain caller is sleepable, in contrast, while the EVTQ/PRIQ consumer is a threaded IRQ handler that needs the CPU: such a busy wait would starve the handler throughout an entire timeout, whenever the waiter and the handler shared one CPU on a non-preemptible kernel. So, this new sleeping helper is marked with a might_sleep() as well, given that an atomic-context misuse would otherwise hide behind an empty queue.

Note that a drained event is dequeued, but not necessarily handled, since queue_remove_raw() moves the MMIO CONS before the threaded IRQ handler gets to push the event onto the IOPF workqueue. A subsequent change will invoke synchronize_irq() and iopf_queue_flush_dev() to close that gap, and it will act on the errno of a timed-out drain too.

Assisted-by Claude:claude-fable-5
---
 drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c | 81 +++++++++++++++++++++
 1 file changed, 81 insertions(+)
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +81 -0
index 06b7de2e6e4b..84b56849f6dc 100644
@@ -948,6 +948,87 @@ static int arm_smmu_cmdq_batch_submit(struct arm_smmu_device *smmu,
 					   cmds->num, true);
 }
 
+/**
+ * arm_smmu_drain_queue - Drain an SMMU queue
+ * @smmu: the SMMU device
+ * @q: the queue to drain
+ * @until_empty: target selection
+ *
+ * With @until_empty == true (for CMDQ), exit once the queue is observed empty:
+ *
+ *   cons0                cons                                prod
+ *     |                   |                                   |
+ *  ---+###################+=====================+=============+--->
+ *                         |<--------- undrained==0? --------->|
+ *
+ * With @until_empty == false (for EVTQ/PRIQ), exit once "drained" reaches its
+ * target: "pending" (i.e. prod0 - cons0, frozen at the entry time):
+ *
+ *   cons0                cons                 prod0         (prod)
+ *     |<---- drained ---->|                     |             |
+ *  ---+###################+=====================+=============+--->
+ *     |<--------------- pending --------------->|
+ *
+ * Note that a drained entry is dequeued, but not necessarily handled: the
+ * EVTQ/PRIQ callers must follow up with a synchronize_irq() to wait for the
+ * threaded IRQ handler to finish handling the dequeued entries.
+ *
+ * Context: Process context; may sleep.
+ * Return: 0 on success or a negative errno on timeout.
+ */
+static int __maybe_unused arm_smmu_drain_queue(struct arm_smmu_device *smmu,
+					       struct arm_smmu_queue *q,
+					       bool until_empty)
+{
+	ktime_t timeout = ktime_add_us(ktime_get(), ARM_SMMU_POLL_TIMEOUT_US);
+	u32 cons, prod, prev, undrained;
+	u32 drained = 0, pending;
+
+	might_sleep();
+
+	cons = readl_relaxed(q->cons_reg);
+	prod = readl_relaxed(q->prod_reg);
+	/* The exit target: the number of entries in the queue at entry */
+	pending = Q_POS(&q->llq, prod - cons);
+
+	while (true) {
+		/* Accumulate the entries consumed since the last poll */
+		prev = cons;
+		cons = readl_relaxed(q->cons_reg);
+		drained += Q_POS(&q->llq, cons - prev);
+
+		prod = readl_relaxed(q->prod_reg);
+		undrained = Q_POS(&q->llq, prod - cons);
+
+		/* Exit on an empty queue, regardless of until_empty */
+		if (!undrained)
+			return 0;
+
+		/* Snapshot mode: exit once the pending entries are drained */
+		if (!until_empty && drained >= pending)
+			return 0;
+
+		/*
+		 * A timeout means the consumer might be stuck. In theory, if it
+		 * moves 2 * qsize entries or more within a single poll interval
+		 * Q_POS() would wrap and undercount drained: that could trigger
+		 * a spurious warning too, if the queue was never once observed
+		 * empty. Yet, that much consumption in such a short interval is
+		 * unrealistic. WARN it only, as a stuck consumer is a real bug.
+		 */
+		if (WARN_ON(ktime_compare(ktime_get(), timeout) > 0))
+			break;
+
+		/* The consumer might be a threaded IRQ handler. Yield to it */
+		usleep_range(100, 200);
+	}
+
+	dev_warn_ratelimited(smmu->dev,
+			     "queue drain timed out at prod=0x%x cons=0x%x\n",
+			     prod, cons);
+	return -ETIMEDOUT;
+}
+
 static void arm_smmu_page_response(struct device *dev, struct iopf_fault *unused,
 				   struct iommu_page_response *resp)
 {
Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#7 lore raw

Re: [PATCH v11 03/16] iommu/arm-smmu-v3: Add arm_smmu_drain_queue() helper

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] iommu: missing final condition check in arm_smmu_drain_queue() polling loop --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] iommu: missing final condition check in arm_smmu_drain_queue() polling loop --

commit d3de0e0ff6c17b4b4b52184a4e8af1a09c29b369
Author: Nicolin Chen <[email protected]>

iommu/arm-smmu-v3: Add arm_smmu_drain_queue() helper

This commit adds a sleepable, counting-based arm_smmu_drain_queue() helper to replace queue specific polling loops. Its until_empty mode serves suspend and runtime PM routines that drain the CMDQ.

Quoted 4 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +0 -0
index 06b7de2e6e4b6..84b56849f6dc4 100644

[ ... ]

Quoted 1 line
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +0 -0
@@ -948,6 +948,87 @@ static int arm_smmu_cmdq_batch_submit(struct arm_smmu_device *smmu,

[ ... ]

Quoted 17 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +17 -0
+	while (true) {
+		/* Accumulate the entries consumed since the last poll */
+		prev = cons;
+		cons = readl_relaxed(q->cons_reg);
+		drained += Q_POS(&q->llq, cons - prev);
+
+		prod = readl_relaxed(q->prod_reg);
+		undrained = Q_POS(&q->llq, prod - cons);
+
+		/* Exit on an empty queue, regardless of until_empty */
+		if (!undrained)
+			return 0;
+
+		/* Snapshot mode: exit once the pending entries are drained */
+		if (!until_empty && drained >= pending)
+			return 0;
+

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c static int arm_smmu_cmdq_batch_submit(struct arm_smmu_device *smmu, · line 1020

Quoted 10 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +10 -0
+		/*
+		 * A timeout means the consumer might be stuck. In theory, if it
+		 * moves 2 * qsize entries or more within a single poll interval
+		 * Q_POS() would wrap and undercount drained: that could trigger
+		 * a spurious warning too, if the queue was never once observed
+		 * empty. Yet, that much consumption in such a short interval is
+		 * unrealistic. WARN it only, as a stuck consumer is a real bug.
+		 */
+		if (WARN_ON(ktime_compare(ktime_get(), timeout) > 0))
+			break;

[Severity: Medium]
Is there a missing final condition re-evaluation after the timeout check in arm_smmu_drain_queue()?

If the thread executing this loop is preempted for more than the timeout duration immediately before the ktime_get() check:

arm_smmu_drain_queue()

    if (!undrained)
        return 0;
    
    [ ... thread preempted by hypervisor for >1 second ... ]
    
    if (WARN_ON(ktime_compare(ktime_get(), timeout) > 0))
        break;

Could this sequence result in a spurious timeout?

Even if the queue was fully drained while the thread was scheduled out, when the thread resumes it will immediately evaluate the timeout as exceeded without checking the queue state one last time.

This would trigger a WARN_ON stack trace and return -ETIMEDOUT, which could then cause caller operations like PM suspend to fail.

Quoted 10 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +10 -0
+
+		/* The consumer might be a threaded IRQ handler. Yield to it */
+		usleep_range(100, 200);
+	}
+
+	dev_warn_ratelimited(smmu->dev,
+			     "queue drain timed out at prod=0x%x cons=0x%x\n",
+			     prod, cons);
+	return -ETIMEDOUT;
+}
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
#8 lore raw

Re: [PATCH v11 03/16] iommu/arm-smmu-v3: Add arm_smmu_drain_queue() helper

In reply to Pranjal Shrivastava
Quoted 4 lines · Pranjal Shrivastava

+/**
+ * arm_smmu_drain_queue - Drain an SMMU queue
+ * @smmu: the SMMU device
+ * @q: the queue to drain

Quoted 8 lines

+ * @until_empty: target selection
+ *
+ * With @until_empty == true (for CMDQ), exit once the queue is observed empty:
+ *
+ * cons0 cons prod
+ * | | |
+ * ---+###################+=====================+=============+--->
+ * |<--------- undrained==0? --------->|

Jason gave some remarks against this API:
https://lore.kernel.org/linux-iommu/179018862538.3334538.17643821143626392419.b4-review@b4/

So, my PRI series would drop this patch. I suspect that it still has some value for the RPM/CMDQ case, compared to a busy-waiting alternative. Yet, it probably should be simplified for CMDQ case only.

In RPM case, the "prod" would be fixed/stable right? IOW, there should be no new commands added to the cmdq, so it only needs to wait for cons == prod?

Nicolin

#9 lore raw

Re: [PATCH v11 03/16] iommu/arm-smmu-v3: Add arm_smmu_drain_queue() helper

Quoted 14 lines · Nicolin Chen
Quoted 4 lines · Pranjal Shrivastava

+/**
+ * arm_smmu_drain_queue - Drain an SMMU queue
+ * @smmu: the SMMU device
+ * @q: the queue to drain

Quoted 8 lines

+ * @until_empty: target selection
+ *
+ * With @until_empty == true (for CMDQ), exit once the queue is observed empty:
+ *
+ * cons0 cons prod
+ * | | |
+ * ---+###################+=====================+=============+--->
+ * |<--------- undrained==0? --------->|

Quoted 3 lines

Jason gave some remarks against this API:
https://lore.kernel.org/linux-iommu/179018862538.3334538.17643821143626392419.b4-review@b4/

I see!

Quoted 9 lines

So, my PRI series would drop this patch. I suspect that it still has some value for the RPM/CMDQ case, compared to a busy-waiting alternative. Yet, it probably should be simplified for CMDQ case only.

In RPM case, the "prod" would be fixed/stable right? IOW, there should be no new commands added to the cmdq, so it only needs to wait for cons == prod?

Yes, that's correct. By the time we drain, the STOP_FLAG is set and we've waited for owner_prod to reach the target & cmdq->lock to drop.. so PROD is stable and only the HW moves CONS (same for the lvcmdqs).

I'll simplify this to just serve the CMDQ in v12, maybe just a sleeping readl_relaxed_poll_timeout() on CONS until it matches PROD..? I'll think try to see if I could repurpose this too.

Thanks,
Praan

#10 lore raw

PATCH v11 4/16 iommu/tegra241-cmdqv: Add a helper to drain VCMDQs

In reply to Pranjal Shrivastava

The tegra241-cmdqv driver supports vCMDQs which need to be drained before suspending the SMMU. The current driver implementation only uses VINTF0 for vCMDQs owned by the kernel which need to be drained. Add a helper that drains all the enabled vCMDQs under VINTF0.

Add a drain_queues function ptr to arm_smmu_impl_ops to drain implementation specified queues, and export arm_smmu_drain_queue().

---
 drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c   |  5 +-
 drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h   |  4 ++
 .../iommu/arm/arm-smmu-v3/tegra241-cmdqv.c    | 49 +++++++++++++++++++
 3 files changed, 55 insertions(+), 3 deletions(-)
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +2 -3
index 84b56849f6dc..d809b625f7fb 100644
@@ -976,9 +976,8 @@ static int arm_smmu_cmdq_batch_submit(struct arm_smmu_device *smmu,
  * Context: Process context; may sleep.
  * Return: 0 on success or a negative errno on timeout.
  */
-static int __maybe_unused arm_smmu_drain_queue(struct arm_smmu_device *smmu,
-					       struct arm_smmu_queue *q,
-					       bool until_empty)
+int arm_smmu_drain_queue(struct arm_smmu_device *smmu,
+			 struct arm_smmu_queue *q, bool until_empty)
 {
 	ktime_t timeout = ktime_add_us(ktime_get(), ARM_SMMU_POLL_TIMEOUT_US);
 	u32 cons, prod, prev, undrained;
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h +4 -0
index 84e618a7fa9e..deefb17e31eb 100644
@@ -891,6 +891,7 @@ struct arm_smmu_impl_ops {
 	size_t (*get_viommu_size)(enum iommu_viommu_type viommu_type);
 	int (*vsmmu_init)(struct arm_vsmmu *vsmmu,
 			  const struct iommu_user_data *user_data);
+	int (*drain_queues)(struct arm_smmu_device *smmu);
 };
 
 /* An SMMUv3 instance */
@@ -1174,6 +1175,9 @@ int arm_smmu_init_one_queue(struct arm_smmu_device *smmu,
 int arm_smmu_cmdq_init(struct arm_smmu_device *smmu,
 		       struct arm_smmu_cmdq *cmdq);
 
+int arm_smmu_drain_queue(struct arm_smmu_device *smmu,
+			 struct arm_smmu_queue *q, bool until_empty);
+
 static inline bool arm_smmu_master_canwbs(struct arm_smmu_master *master)
 {
 	return dev_iommu_fwspec_get(master->dev)->flags &
drivers/iommu/arm/arm-smmu-v3/tegra241-cmdqv.c +49 -0

61 lines not on this page · raw message

Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#11 lore raw

Re: [PATCH v11 04/16] iommu/tegra241-cmdqv: Add a helper to drain VCMDQs

Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 10 lines

The tegra241-cmdqv driver supports vCMDQs which need to be drained before suspending the SMMU. The current driver implementation only uses VINTF0 for vCMDQs owned by the kernel which need to be drained. Add a helper that drains all the enabled vCMDQs under VINTF0.

Add a drain_queues function ptr to arm_smmu_impl_ops to drain implementation specified queues, and export arm_smmu_drain_queue().

Sashiko has reviewed this patch and found no issues. It looks great!

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
#12 lore raw

PATCH v11 5/16 iommu/arm-smmu-v3: Add a helper to drain cmd queues

In reply to Pranjal Shrivastava

Before we suspend SMMU, we want to ensure that all commands (especially ATC_INV) have been flushed by the CMDQ, i.e. the CMDQs are empty. Add arm_smmu_drain_cmdqs() that drains the command queue using the arm_smmu_drain_queue() helper.

---
 drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c | 27 +++++++++++++++++++++
 1 file changed, 27 insertions(+)
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +27 -0
index d809b625f7fb..dc2fc02b5163 100644
@@ -1028,6 +1028,33 @@ int arm_smmu_drain_queue(struct arm_smmu_device *smmu,
 	return -ETIMEDOUT;
 }
 
+/*
+ * Lockless, the caller must ensure that no concurrent command submissions
+ * can happen (such as during suspend where clients are already quiesced).
+ * Polling until PROD == CONS ensures all pending commands in the queue have
+ * been consumed by the hardware.
+ */
+static int __maybe_unused arm_smmu_drain_cmdqs(struct arm_smmu_device *smmu)
+{
+	int ret, err;
+
+	/*
+	 * We skip cmdq locking here since this helper is only called
+	 * from contexts (like suspend) where the caller has already
+	 * ensured that new command submissions are fully closed.
+	 */
+	ret = arm_smmu_drain_queue(smmu, &smmu->cmdq.q, true);
+
+	/* Drain all implementation-specific queues */
+	if (smmu->impl_ops && smmu->impl_ops->drain_queues) {
+		err = smmu->impl_ops->drain_queues(smmu);
+		if (err)
+			ret = err;
+	}
+
+	return ret;
+}
+
 static void arm_smmu_page_response(struct device *dev, struct iopf_fault *unused,
 				   struct iommu_page_response *resp)
 {
Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#13 lore raw

Re: [PATCH v11 05/16] iommu/arm-smmu-v3: Add a helper to drain cmd queues

Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 8 lines

Before we suspend SMMU, we want to ensure that all commands (especially ATC_INV) have been flushed by the CMDQ, i.e. the CMDQs are empty. Add arm_smmu_drain_cmdqs() that drains the command queue using the arm_smmu_drain_queue() helper.

Sashiko has reviewed this patch and found no issues. It looks great!

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=5
#14 lore raw

PATCH v11 6/16 iommu/tegra241-cmdqv: Restore PROD and CONS after resume

In reply to Pranjal Shrivastava

From: Ashish Mhetre <[email protected]>

PROD and CONS indices for vcmdqs are getting set to 0 after resume. Because of this the vcmdq is not consuming commands after resume. Fix this by restoring PROD and CONS indices after resume from saved pointers.

---
 drivers/iommu/arm/arm-smmu-v3/tegra241-cmdqv.c | 10 ++++++++++
 1 file changed, 10 insertions(+)
drivers/iommu/arm/arm-smmu-v3/tegra241-cmdqv.c +10 -0
index a394bf0f487f..c7989fcd2c62 100644
@@ -567,6 +567,16 @@ static int tegra241_vcmdq_hw_init(struct tegra241_vcmdq *vcmdq)
 	/* Configure and enable VCMDQ */
 	writeq_relaxed(vcmdq->cmdq.q.q_base, REG_VCMDQ_PAGE1(vcmdq, BASE));
 
+	/*
+	 * HW Registers reset to 0 when power-cycled. Restore them from their
+	 * SW copies to prevent executing stale/ghost commands after resume.
+	 * Note on RPM: Power-cycles can never happen when VCMDQs are assigned
+	 * to the Guests since the relevant frameworks (IOMMUFD / VFIO) hold
+	 * active PM references preventing suspend while VMs are active.
+	 */
+	writel_relaxed(vcmdq->cmdq.q.llq.prod, REG_VCMDQ_PAGE0(vcmdq, PROD));
+	writel_relaxed(vcmdq->cmdq.q.llq.cons, REG_VCMDQ_PAGE0(vcmdq, CONS));
+
 	ret = vcmdq_write_config(vcmdq, VCMDQ_EN);
 	if (ret) {
 		dev_err(vcmdq->cmdqv->dev,
Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#15 lore raw

Re: [PATCH v11 06/16] iommu/tegra241-cmdqv: Restore PROD and CONS after resume

Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 10 lines

From: Ashish Mhetre <[email protected]>

PROD and CONS indices for vcmdqs are getting set to 0 after resume. Because of this the vcmdq is not consuming commands after resume. Fix this by restoring PROD and CONS indices after resume from saved pointers.

Sashiko has reviewed this patch and found no issues. It looks great!

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=6
#16 lore raw

PATCH v11 7/16 genirq/msi: Cache MSI message in irq_chip_write_msi_msg()

In reply to Pranjal Shrivastava

Currently, PCI MSI caches the composed MSI message into the MSI descriptor inside __pci_write_msi_msg(), whereas platform MSI and other device MSI domains do not cache the message in the core, forcing individual drivers to manually copy the message into desc->msg if they need to restore it across power transitions.

Cache desc->msg in irq_chip_write_msi_msg() before invoking the chip callback so all hierarchical MSI domains automatically record the latest message. Document why the redundant assignment in __pci_write_msi_msg() must remain for direct callers outside the irq_chip hierarchy.

---
 drivers/pci/msi/msi.c | 6 ++++++
 kernel/irq/msi.c      | 9 +++++++++
 2 files changed, 15 insertions(+)
drivers/pci/msi/msi.c +6 -0
index 80a9db417dc8..f7bedc31d486 100644
@@ -257,6 +257,12 @@ void __pci_write_msi_msg(struct msi_desc *entry, struct msi_msg *msg)
 		pci_write_msg_msi(dev, entry, msg);
 	}
 
+	/*
+	 * Although irq_chip_write_msi_msg() already caches the message,
+	 * keep the assignment here for callers that invoke
+	 * __pci_write_msi_msg() or pci_write_msi_msg() directly outside
+	 * the irq_chip hierarchy.
+	 */
 	entry->msg = *msg;
 
 	if (entry->write_msi_msg)
kernel/irq/msi.c +9 -0
index fb5f372215bf..df460a574d80 100644
@@ -634,6 +634,15 @@ static unsigned int msi_domain_get_hwsize(struct device *dev, unsigned int domid
 static inline void irq_chip_write_msi_msg(struct irq_data *data,
 					  struct msi_msg *msg)
 {
+	struct msi_desc *desc = irq_data_get_msi_desc(data);
+
+	/*
+	 * PCI Multi-MSI shares a single descriptor across all vectors and
+	 * the device stores only the base message. Cache the message of the
+	 * first interrupt only, so that sub-vectors cannot overwrite it.
+	 */
+	if (desc->irq == data->irq)
+		desc->msg = *msg;
 	data->chip->irq_write_msi_msg(data, msg);
 }
 
Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#17 lore raw

Re: [PATCH v11 07/16] genirq/msi: Cache MSI message in irq_chip_write_msi_msg()

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Critical] irq: NULL pointer dereference in irq_chip_write_msi_msg() --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Critical] irq: NULL pointer dereference in irq_chip_write_msi_msg()
--

commit 98ab4cb46e40acf3e5ccb95b4213b5490ae2ff8a
Author: Pranjal Shrivastava <[email protected]>

genirq/msi: Cache MSI message in irq_chip_write_msi_msg()

Currently, PCI MSI caches the composed MSI message into the MSI descriptor inside __pci_write_msi_msg(). This patch caches the message directly in irq_chip_write_msi_msg() so that all hierarchical MSI domains automatically record the latest message.

Quoted 6 lines
kernel/irq/msi.c +0 -0
index fb5f372215bf2..df460a574d800 100644
@@ -634,6 +634,15 @@ static unsigned int msi_domain_get_hwsize(struct device *dev, unsigned int domid
 static inline void irq_chip_write_msi_msg(struct irq_data *data,

kernel/irq/msi.c static unsigned int msi_domain_get_hwsize(struct device *dev, unsigned int domid · line 644

Quoted 10 lines
kernel/irq/msi.c +8 -0
 					  struct msi_msg *msg)
 {
+	struct msi_desc *desc = irq_data_get_msi_desc(data);
+
+	/*
+	 * PCI Multi-MSI shares a single descriptor across all vectors and
+	 * the device stores only the base message. Cache the message of the
+	 * first interrupt only, so that sub-vectors cannot overwrite it.
+	 */
+	if (desc->irq == data->irq)

[Severity: Critical]
Does this code cause a NULL pointer dereference for domains without an msi_desc object?

Looking at irq_chip_write_msi_msg() in kernel/irq/msi.c, architecture-specific domains like the x86 HPET (hpet_msi_domain_info) and DMAR (dmar_msi_domain_info) utilize generic MSI domain operations but do not allocate an msi_desc object for their interrupts.

When an interrupt from these domains is activated or its affinity is updated, calls like msi_domain_activate() or msi_domain_set_affinity() invoke irq_chip_write_msi_msg().

Because irq_data_get_msi_desc(data) returns NULL for these interrupts, checking desc->irq unconditionally could lead to a fatal dereference during boot.

I checked the follow-up patches in the series and it appears a check for desc is not introduced in any subsequent patch, so this regression remains present in the final series state.

Should this be updated to check if desc is valid first?

Quoted 3 lines
kernel/irq/msi.c +1 -0
+		desc->msg = *msg;
 	data->chip->irq_write_msi_msg(data, msg);
 }
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=7
maintainer
#18 lore raw

Re: [PATCH v11 07/16] genirq/msi: Cache MSI message in irq_chip_write_msi_msg()

In reply to Pranjal Shrivastava
Quoted 45 lines · Pranjal Shrivastava

Currently, PCI MSI caches the composed MSI message into the MSI descriptor inside __pci_write_msi_msg(), whereas platform MSI and other device MSI domains do not cache the message in the core, forcing individual drivers to manually copy the message into desc->msg if they need to restore it across power transitions.

Cache desc->msg in irq_chip_write_msi_msg() before invoking the chip callback so all hierarchical MSI domains automatically record the latest message. Document why the redundant assignment in __pci_write_msi_msg() must remain for direct callers outside the irq_chip hierarchy.

---
 drivers/pci/msi/msi.c | 6 ++++++
 kernel/irq/msi.c      | 9 +++++++++
 2 files changed, 15 insertions(+)
drivers/pci/msi/msi.c +6 -0
index 80a9db417dc8..f7bedc31d486 100644
@@ -257,6 +257,12 @@ void __pci_write_msi_msg(struct msi_desc *entry, struct msi_msg *msg)
 		pci_write_msg_msi(dev, entry, msg);
 	}
 
+	/*
+	 * Although irq_chip_write_msi_msg() already caches the message,
+	 * keep the assignment here for callers that invoke
+	 * __pci_write_msi_msg() or pci_write_msi_msg() directly outside
+	 * the irq_chip hierarchy.
+	 */
 	entry->msg = *msg;
 
 	if (entry->write_msi_msg)
kernel/irq/msi.c +1 -0
index fb5f372215bf..df460a574d80 100644
@@ -634,6 +634,15 @@ static unsigned int msi_domain_get_hwsize(struct device *dev, unsigned int domid
 static inline void irq_chip_write_msi_msg(struct irq_data *data,
 					  struct msi_msg *msg)
 {
+	struct msi_desc *desc = irq_data_get_msi_desc(data);

kernel/irq/msi.c static unsigned int msi_domain_get_hwsize(struct device *dev, unsigned int domid · line 647

Quoted 10 lines
kernel/irq/msi.c +8 -0
+
+	/*
+	 * PCI Multi-MSI shares a single descriptor across all vectors and
+	 * the device stores only the base message. Cache the message of the
+	 * first interrupt only, so that sub-vectors cannot overwrite it.
+	 */
+	if (desc->irq == data->irq)
+		desc->msg = *msg;
 	data->chip->irq_write_msi_msg(data, msg);
 }

Sashiko reported correctly:

Quoted 3 lines

[Severity: Critical]
Does this code cause a NULL pointer dereference for domains without an msi_desc object?

So this needs to be:

	if (desc && desc->irq == data->irq)
		desc->msg = *msg;

Did not think about that, but that also means that this patch was not tested on any recent (less than 10 years old) Intel x86 platform or a x86 VM exposing HPET...

Thanks,

tglx

#19 lore raw

Re: [PATCH v11 07/16] genirq/msi: Cache MSI message in irq_chip_write_msi_msg()

Quoted 63 lines · Thomas Gleixner
Quoted 45 lines · Pranjal Shrivastava

Currently, PCI MSI caches the composed MSI message into the MSI descriptor inside __pci_write_msi_msg(), whereas platform MSI and other device MSI domains do not cache the message in the core, forcing individual drivers to manually copy the message into desc->msg if they need to restore it across power transitions.

Cache desc->msg in irq_chip_write_msi_msg() before invoking the chip callback so all hierarchical MSI domains automatically record the latest message. Document why the redundant assignment in __pci_write_msi_msg() must remain for direct callers outside the irq_chip hierarchy.

---
 drivers/pci/msi/msi.c | 6 ++++++
 kernel/irq/msi.c      | 9 +++++++++
 2 files changed, 15 insertions(+)
drivers/pci/msi/msi.c +6 -0
index 80a9db417dc8..f7bedc31d486 100644
@@ -257,6 +257,12 @@ void __pci_write_msi_msg(struct msi_desc *entry, struct msi_msg *msg)
 		pci_write_msg_msi(dev, entry, msg);
 	}
 
+	/*
+	 * Although irq_chip_write_msi_msg() already caches the message,
+	 * keep the assignment here for callers that invoke
+	 * __pci_write_msi_msg() or pci_write_msi_msg() directly outside
+	 * the irq_chip hierarchy.
+	 */
 	entry->msg = *msg;
 
 	if (entry->write_msi_msg)
kernel/irq/msi.c +1 -0
index fb5f372215bf..df460a574d80 100644
@@ -634,6 +634,15 @@ static unsigned int msi_domain_get_hwsize(struct device *dev, unsigned int domid
 static inline void irq_chip_write_msi_msg(struct irq_data *data,
 					  struct msi_msg *msg)
 {
+	struct msi_desc *desc = irq_data_get_msi_desc(data);

kernel/irq/msi.c static unsigned int msi_domain_get_hwsize(struct device *dev, unsigned int domid · line 647

Quoted 10 lines
kernel/irq/msi.c +8 -0
+
+	/*
+	 * PCI Multi-MSI shares a single descriptor across all vectors and
+	 * the device stores only the base message. Cache the message of the
+	 * first interrupt only, so that sub-vectors cannot overwrite it.
+	 */
+	if (desc->irq == data->irq)
+		desc->msg = *msg;
 	data->chip->irq_write_msi_msg(data, msg);
 }

Sashiko reported correctly:

Quoted 3 lines

[Severity: Critical]
Does this code cause a NULL pointer dereference for domains without an msi_desc object?

Quoted 9 lines

So this needs to be:

	if (desc && desc->irq == data->irq)
		desc->msg = *msg;

Did not think about that, but that also means that this patch was not tested on any recent (less than 10 years old) Intel x86 platform or a x86 VM exposing HPET...

Ack, I'll fix that, and yes, I've tested this on arm64 platforms only. I'll pick up a recent Intel x86 platform as well, to test this.

Quoted 5 lines

Thanks,

tglx

Thanks,
Praan

Acked-by on v11 7/16
#20 lore raw

Re: [PATCH v11 07/16] genirq/msi: Cache MSI message in irq_chip_write_msi_msg()

In reply to Pranjal Shrivastava
Quoted 6 lines · Pranjal Shrivastava

Currently, PCI MSI caches the composed MSI message into the MSI descriptor inside __pci_write_msi_msg(), whereas platform MSI and other device MSI domains do not cache the message in the core, forcing individual drivers to manually copy the message into desc->msg if they need to restore it across power transitions.

Quoted 8 lines

Cache desc->msg in irq_chip_write_msi_msg() before invoking the chip callback so all hierarchical MSI domains automatically record the latest message. Document why the redundant assignment in __pci_write_msi_msg() must remain for direct callers outside the irq_chip hierarchy.

With the fix testing Thomas proposed:

Quoted 45 lines
---
 drivers/pci/msi/msi.c | 6 ++++++
 kernel/irq/msi.c      | 9 +++++++++
 2 files changed, 15 insertions(+)
drivers/pci/msi/msi.c +6 -0
index 80a9db417dc8..f7bedc31d486 100644
@@ -257,6 +257,12 @@ void __pci_write_msi_msg(struct msi_desc *entry, struct msi_msg *msg)
 		pci_write_msg_msi(dev, entry, msg);
 	}
 
+	/*
+	 * Although irq_chip_write_msi_msg() already caches the message,
+	 * keep the assignment here for callers that invoke
+	 * __pci_write_msi_msg() or pci_write_msi_msg() directly outside
+	 * the irq_chip hierarchy.
+	 */
 	entry->msg = *msg;
 
 	if (entry->write_msi_msg)
kernel/irq/msi.c +9 -0
index fb5f372215bf..df460a574d80 100644
@@ -634,6 +634,15 @@ static unsigned int msi_domain_get_hwsize(struct device *dev, unsigned int domid
 static inline void irq_chip_write_msi_msg(struct irq_data *data,
 					  struct msi_msg *msg)
 {
+	struct msi_desc *desc = irq_data_get_msi_desc(data);
+
+	/*
+	 * PCI Multi-MSI shares a single descriptor across all vectors and
+	 * the device stores only the base message. Cache the message of the
+	 * first interrupt only, so that sub-vectors cannot overwrite it.
+	 */
+	if (desc->irq == data->irq)
+		desc->msg = *msg;
 	data->chip->irq_write_msi_msg(data, msg);
 }
 
Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#21 lore raw

PATCH v11 8/16 genirq/msi: Provide msi_device_domain_restore_msi_msgs()

In reply to Pranjal Shrivastava

From: Thomas Gleixner <[email protected]>

Devices that provide the message store for MSI interrupts in their own hardware registers often lose that register state across power transitions (such as runtime suspend or system sleep) and need to restore the cached MSI messages upon resume.

Provide msi_device_domain_restore_msi_msgs() to iterate over all associated MSI descriptors in a device's MSI domain under proper descriptor and irq_desc locking and rewrite the cached MSI messages via the irq_chip hierarchy.

[praan: Use scoped_irqdesc_get_and_buslock(), fix the xarray range bound
and write the commit message]

---
 include/linux/msi.h |  2 ++
 kernel/irq/msi.c    | 37 +++++++++++++++++++++++++++++++++++++
 2 files changed, 39 insertions(+)
include/linux/msi.h +2 -0
index a4613de11960..44d551e85abd 100644
@@ -669,6 +669,8 @@ void msi_domain_free_irqs_all(struct device *dev, unsigned int domid);
 
 struct msi_domain_info *msi_get_domain_info(struct irq_domain *domain);
 
+void msi_device_domain_restore_msi_msgs(struct device *dev, unsigned int domid);
+
 /* Per device platform MSI */
 int platform_device_msi_init_and_alloc_irqs(struct device *dev, unsigned int nvec,
 					    irq_write_msi_msg_t write_msi_msg);
kernel/irq/msi.c +37 -0
index df460a574d80..8fb855b5e09f 100644
@@ -1784,3 +1784,40 @@ bool msi_device_has_isolated_msi(struct device *dev)
 	return arch_is_isolated_msi();
 }
 EXPORT_SYMBOL_GPL(msi_device_has_isolated_msi);
+
+/**
+ * msi_device_domain_restore_msi_msgs - Restore MSI messages for a device domain
+ * @dev:	The device to restore MSI messages for
+ * @domid:	The id of the interrupt domain to restore
+ */
+void msi_device_domain_restore_msi_msgs(struct device *dev, unsigned int domid)
+{
+	if (!dev->msi.data)
+		return;
+
+	guard(msi_descs_lock)(dev);
+	struct irq_domain *domain = msi_get_device_domain(dev, domid);
+
+	if (!domain || !irq_domain_is_msi_device(domain))
+		return;
+
+	struct xarray *xa = &dev->msi.data->__domains[domid].store;
+	struct msi_domain_info *info = domain->host_data;
+	struct msi_desc *msi_desc;
+	unsigned long idx;
+
+	xa_for_each_range(xa, idx, msi_desc, 0, info->hwsize - 1) {
+		/* Only handle MSI entries which have an interrupt associated */
+		if (!msi_desc_match(msi_desc, MSI_DESC_ASSOCIATED))
+			continue;
+
+		scoped_irqdesc_get_and_buslock(msi_desc->irq, 0) {
+			struct irq_data *data = irq_desc_get_irq_data(scoped_irqdesc);
+			struct msi_msg msg = msi_desc->msg;
+
+			if (data->chip)
+				irq_chip_write_msi_msg(data, &msg);
+		}
+	}
+}
+EXPORT_SYMBOL_GPL(msi_device_domain_restore_msi_msgs);
Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#22 lore raw

Re: [PATCH v11 08/16] genirq/msi: Provide msi_device_domain_restore_msi_msgs()

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Critical] irq/msi: NULL pointer dereference in msi_device_domain_restore_msi_msgs --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Critical] irq/msi: NULL pointer dereference in msi_device_domain_restore_msi_msgs --

commit 095b22d878464bc6c7b357c12fc988c69e1487d7
Author: Thomas Gleixner <[email protected]>

genirq/msi: Provide msi_device_domain_restore_msi_msgs()

This commit provides msi_device_domain_restore_msi_msgs() to iterate over MSI descriptors and rewrite cached MSI messages for devices that lose register state during power transitions. It iterates over the associated MSI descriptors in the device's MSI domain and rewrites the messages via the irq_chip hierarchy.

Quoted 4 lines
kernel/irq/msi.c +0 -0
index df460a574d800..8fb855b5e09f3 100644

[ ... ]

kernel/irq/msi.c bool msi_device_has_isolated_msi(struct device *dev) · line 1819

Quoted 11 lines
kernel/irq/msi.c +11 -0
+	xa_for_each_range(xa, idx, msi_desc, 0, info->hwsize - 1) {
+		/* Only handle MSI entries which have an interrupt associated */
+		if (!msi_desc_match(msi_desc, MSI_DESC_ASSOCIATED))
+			continue;
+
+		scoped_irqdesc_get_and_buslock(msi_desc->irq, 0) {
+			struct irq_data *data = irq_desc_get_irq_data(scoped_irqdesc);
+			struct msi_msg msg = msi_desc->msg;
+
+			if (data->chip)
+				irq_chip_write_msi_msg(data, &msg);

[Severity: Critical]
Will this result in a NULL pointer dereference in hierarchical IRQ domains?

Since irq_desc_get_irq_data() retrieves the top-level irq_data, data->chip points to the top-level irq_chip. In hierarchical IRQ domains, the top-level irq_chip typically does not implement the irq_write_msi_msg callback.

When this top-level irq_data is passed to irq_chip_write_msi_msg(), it will dereference a NULL function pointer:

kernel/irq/msi.c:irq_chip_write_msi_msg() {
    ...
    data->chip->irq_write_msi_msg(data, msg);
}

Should this code retrieve the specific irq_data for the MSI domain that actually implements the write_msi_msg callback, rather than using the top-level irq_data?

Quoted 4 lines
kernel/irq/msi.c +4 -0
+		}
+	}
+}
+EXPORT_SYMBOL_GPL(msi_device_domain_restore_msi_msgs);
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=8
maintainer
#23 lore raw

Re: [PATCH v11 08/16] genirq/msi: Provide msi_device_domain_restore_msi_msgs()

In reply to Pranjal Shrivastava
Quoted 19 lines · Pranjal Shrivastava
kernel/irq/msi.c +19 -0
+void msi_device_domain_restore_msi_msgs(struct device *dev, unsigned int domid)
+{
+	if (!dev->msi.data)
+		return;
+
+	guard(msi_descs_lock)(dev);
+	struct irq_domain *domain = msi_get_device_domain(dev, domid);
+
+	if (!domain || !irq_domain_is_msi_device(domain))
+		return;
+
+	struct xarray *xa = &dev->msi.data->__domains[domid].store;
+	struct msi_domain_info *info = domain->host_data;
+	struct msi_desc *msi_desc;
+	unsigned long idx;
+
+	xa_for_each_range(xa, idx, msi_desc, 0, info->hwsize - 1) {
+		/* Only handle MSI entries which have an interrupt associated */
+		if (!msi_desc_match(msi_desc, MSI_DESC_ASSOCIATED))

kernel/irq/msi.c bool msi_device_has_isolated_msi(struct device *dev) · line 1821

Quoted 10 lines
kernel/irq/msi.c +10 -0
+			continue;
+
+		scoped_irqdesc_get_and_buslock(msi_desc->irq, 0) {
+			struct irq_data *data = irq_desc_get_irq_data(scoped_irqdesc);
+			struct msi_msg msg = msi_desc->msg;
+
+			if (data->chip)
+				irq_chip_write_msi_msg(data, &msg);
+		}
+	}

In this case sashiko is wrong:

Quoted 9 lines

[Severity: Critical]
Will this result in a NULL pointer dereference in hierarchical IRQ domains?

Since irq_desc_get_irq_data() retrieves the top-level irq_data, data->chip points to the top-level irq_chip. In hierarchical IRQ domains, the top-level irq_chip typically does not implement the irq_write_msi_msg callback.

When this top-level irq_data is passed to irq_chip_write_msi_msg(), it will dereference a NULL function pointer:

All MSI top level (device) domains implement the irq_write_msi_msg() callback. That's the whole point of the top level MSI domain as that's the one which has access to the device and the associated message store.

Thanks,

tglx

#24 lore raw

Re: [PATCH v11 08/16] genirq/msi: Provide msi_device_domain_restore_msi_msgs()

Quoted 40 lines · Thomas Gleixner
Quoted 19 lines · Pranjal Shrivastava
kernel/irq/msi.c +19 -0
+void msi_device_domain_restore_msi_msgs(struct device *dev, unsigned int domid)
+{
+	if (!dev->msi.data)
+		return;
+
+	guard(msi_descs_lock)(dev);
+	struct irq_domain *domain = msi_get_device_domain(dev, domid);
+
+	if (!domain || !irq_domain_is_msi_device(domain))
+		return;
+
+	struct xarray *xa = &dev->msi.data->__domains[domid].store;
+	struct msi_domain_info *info = domain->host_data;
+	struct msi_desc *msi_desc;
+	unsigned long idx;
+
+	xa_for_each_range(xa, idx, msi_desc, 0, info->hwsize - 1) {
+		/* Only handle MSI entries which have an interrupt associated */
+		if (!msi_desc_match(msi_desc, MSI_DESC_ASSOCIATED))

kernel/irq/msi.c bool msi_device_has_isolated_msi(struct device *dev) · line 1821

Quoted 10 lines
kernel/irq/msi.c +10 -0
+			continue;
+
+		scoped_irqdesc_get_and_buslock(msi_desc->irq, 0) {
+			struct irq_data *data = irq_desc_get_irq_data(scoped_irqdesc);
+			struct msi_msg msg = msi_desc->msg;
+
+			if (data->chip)
+				irq_chip_write_msi_msg(data, &msg);
+		}
+	}

In this case sashiko is wrong:

Quoted 7 lines

[Severity: Critical]
Will this result in a NULL pointer dereference in hierarchical IRQ domains?

Since irq_desc_get_irq_data() retrieves the top-level irq_data, data->chip points to the top-level irq_chip. In hierarchical IRQ domains, the top-level irq_chip typically does not implement the irq_write_msi_msg callback.

Quoted 7 lines
Quoted 2 lines

When this top-level irq_data is passed to irq_chip_write_msi_msg(), it will dereference a NULL function pointer:

All MSI top level (device) domains implement the irq_write_msi_msg() callback. That's the whole point of the top level MSI domain as that's the one which has access to the device and the associated message store.

Ack, I can try folding this into a comment to avoid sashiko reporting this multiple time in the v12.

Thanks,
Praan

#25 lore raw

PATCH v11 9/16 iommu/arm-smmu-v3: Restore MSI config on resume

In reply to Pranjal Shrivastava

The SMMU's MSI configuration registers (*_IRQ_CFGn) containing target address, data and memory attributes lose their state when the SMMU is powered down.

Introduce arm_smmu_resume_msis() to zero the *_IRQ_CFG0 registers (which reset to unknown values) and restore the cached MSI messages across the device's MSI domain via msi_device_domain_restore_msi_msgs().

In addition, clear ARM_SMMU_FEAT_MSI if MSI setup fails and the driver falls back to wired IRQs, preventing spurious MSI resume attempts.

---
 drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c | 13 +++++++++++++
 1 file changed, 13 insertions(+)
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +13 -0
index dc2fc02b5163..7347d3ecdae8 100644
@@ -4779,6 +4779,19 @@ static void arm_smmu_write_msi_msg(struct msi_desc *desc, struct msi_msg *msg)
 	writel_relaxed(ARM_SMMU_MEMATTR_DEVICE_nGnRE, smmu->base + cfg[2]);
 }
 
+static void __maybe_unused arm_smmu_resume_msis(struct arm_smmu_device *smmu)
+{
+	/* Clear the MSI address regs as they reset to unknown value */
+	writeq_relaxed(0, smmu->base + ARM_SMMU_GERROR_IRQ_CFG0);
+	writeq_relaxed(0, smmu->base + ARM_SMMU_EVTQ_IRQ_CFG0);
+
+	if (smmu->features & ARM_SMMU_FEAT_PRI)
+		writeq_relaxed(0, smmu->base + ARM_SMMU_PRIQ_IRQ_CFG0);
+
+	/* No-op if no MSI device domain was instantiated (e.g. wired IRQs) */
+	msi_device_domain_restore_msi_msgs(smmu->dev, MSI_DEFAULT_DOMAIN);
+}
+
 static void arm_smmu_setup_msis(struct arm_smmu_device *smmu)
 {
 	int ret, nvec = ARM_SMMU_MAX_MSIS;
Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#26 lore raw

Re: [PATCH v11 09/16] iommu/arm-smmu-v3: Restore MSI config on resume

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] arm-smmu-v3: Meaningful code and commit message mismatch for ARM_SMMU_FEAT_MSI --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] arm-smmu-v3: Meaningful code and commit message mismatch for ARM_SMMU_FEAT_MSI --

commit 1bda20db5a1330cc7b28d06643bb07428e7318f4
Author: Pranjal Shrivastava <[email protected]>

iommu/arm-smmu-v3: Restore MSI config on resume

The SMMU's MSI configuration registers (*_IRQ_CFGn) containing target address, data and memory attributes lose their state when the SMMU is powered down. This commit introduces arm_smmu_resume_msis() to zero the registers and restore cached MSI messages. It also states it clears ARM_SMMU_FEAT_MSI on setup failure to prevent spurious resume attempts.

Quoted 2 lines

In addition, clear ARM_SMMU_FEAT_MSI if MSI setup fails and the driver falls back to wired IRQs, preventing spurious MSI resume attempts.

[Severity: Medium]
The commit message mentions clearing ARM_SMMU_FEAT_MSI on MSI setup failure, but the code to do this appears to be missing from the patch.

Looking at arm_smmu_setup_msis(), the flag is left set when falling back to wired IRQs:

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c:arm_smmu_setup_msis() {
    ...
	if (!dev->msi.domain) {
		dev_info(smmu->dev, "msi_domain absent - falling back to wired irqs\n");
		return;
	}
    ...
	ret = platform_device_msi_init_and_alloc_irqs(dev, nvec, arm_smmu_write_msi_msg);
	if (ret) {
		dev_warn(dev, "failed to allocate MSIs - falling back to wired irqs\n");
		return;
	}
    ...
}

Was the code to clear ARM_SMMU_FEAT_MSI accidentally dropped from this patch?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=9
maintainer
#27 lore raw

Re: [PATCH v11 09/16] iommu/arm-smmu-v3: Restore MSI config on resume

In reply to Pranjal Shrivastava
Quoted 24 lines · Pranjal Shrivastava

The SMMU's MSI configuration registers (*_IRQ_CFGn) containing target address, data and memory attributes lose their state when the SMMU is powered down.

Introduce arm_smmu_resume_msis() to zero the *_IRQ_CFG0 registers (which reset to unknown values) and restore the cached MSI messages across the device's MSI domain via msi_device_domain_restore_msi_msgs().

In addition, clear ARM_SMMU_FEAT_MSI if MSI setup fails and the driver falls back to wired IRQs, preventing spurious MSI resume attempts.

---
 drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c | 13 +++++++++++++
 1 file changed, 13 insertions(+)
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +0 -0
index dc2fc02b5163..7347d3ecdae8 100644
@@ -4779,6 +4779,19 @@ static void arm_smmu_write_msi_msg(struct msi_desc *desc, struct msi_msg *msg)
 	writel_relaxed(ARM_SMMU_MEMATTR_DEVICE_nGnRE, smmu->base + cfg[2]);

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c static void arm_smmu_write_msi_msg(struct msi_desc *desc, struct msi_msg *msg) · line 4789

Quoted 10 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +8 -0
 }
 
+static void __maybe_unused arm_smmu_resume_msis(struct arm_smmu_device *smmu)
+{
+	/* Clear the MSI address regs as they reset to unknown value */
+	writeq_relaxed(0, smmu->base + ARM_SMMU_GERROR_IRQ_CFG0);
+	writeq_relaxed(0, smmu->base + ARM_SMMU_EVTQ_IRQ_CFG0);
+
+	if (smmu->features & ARM_SMMU_FEAT_PRI)
+		writeq_relaxed(0, smmu->base + ARM_SMMU_PRIQ_IRQ_CFG0);

Please can you factor this out into a separate function (e.g. arm_smmu_reset_msis()) that can also be called from setup_msis()?

Will

#28 lore raw

PATCH v11 10/16 iommu/arm-smmu-v3: Factor out arm_smmu_handle_gerror()

In reply to Pranjal Shrivastava

The GERROR register's state might be lost when the SMMU is powered down during runtime suspend, requiring the suspend sequence to handle any pending errors before the hardware state is lost.

Refactor the gerror handling logic into a helper function. Subsequent patches will invoke it from the runtime suspend callback after disabling the SMMU, ensuring that any late-breaking gerrors are logged and ack'ed before the hardware state is lost.

---
 drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c | 11 +++++++++--
 1 file changed, 9 insertions(+), 2 deletions(-)
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +9 -2
index 7347d3ecdae8..a123810fac57 100644
@@ -2406,10 +2406,10 @@ static irqreturn_t arm_smmu_priq_thread(int irq, void *dev)
 
 static int arm_smmu_device_disable(struct arm_smmu_device *smmu);
 
-static irqreturn_t arm_smmu_gerror_handler(int irq, void *dev)
+/* Lockless; must ensure that there are no concurrent callers */
+static irqreturn_t arm_smmu_handle_gerror(struct arm_smmu_device *smmu)
 {
 	u32 gerror, gerrorn, active;
-	struct arm_smmu_device *smmu = dev;
 
 	gerror = readl_relaxed(smmu->base + ARM_SMMU_GERROR);
 	gerrorn = readl_relaxed(smmu->base + ARM_SMMU_GERRORN);
@@ -2452,6 +2452,13 @@ static irqreturn_t arm_smmu_gerror_handler(int irq, void *dev)
 	return IRQ_HANDLED;
 }
 
+static irqreturn_t arm_smmu_gerror_handler(int irq, void *dev)
+{
+	struct arm_smmu_device *smmu = dev;
+
+	return arm_smmu_handle_gerror(smmu);
+}
+
 static irqreturn_t arm_smmu_combined_irq_thread(int irq, void *dev)
 {
 	struct arm_smmu_device *smmu = dev;
Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#29 lore raw

Re: [PATCH v11 10/16] iommu/arm-smmu-v3: Factor out arm_smmu_handle_gerror()

Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 9 lines

The GERROR register's state might be lost when the SMMU is powered down during runtime suspend, requiring the suspend sequence to handle any pending errors before the hardware state is lost.

Refactor the gerror handling logic into a helper function. Subsequent patches will invoke it from the runtime suspend callback after disabling the SMMU, ensuring that any late-breaking gerrors are logged and ack'ed before the hardware state is lost.

Quoted 4 lines

Sashiko has reviewed this patch and found no issues. It looks great!

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=10
#30 lore raw

Re: [PATCH v11 10/16] iommu/arm-smmu-v3: Factor out arm_smmu_handle_gerror()

In reply to Pranjal Shrivastava
Quoted 8 lines · Pranjal Shrivastava

The GERROR register's state might be lost when the SMMU is powered down during runtime suspend, requiring the suspend sequence to handle any pending errors before the hardware state is lost.

Refactor the gerror handling logic into a helper function. Subsequent patches will invoke it from the runtime suspend callback after disabling the SMMU, ensuring that any late-breaking gerrors are logged and ack'ed before the hardware state is lost.

CMDQV has a separate IRQ, so I think it likely needs a counterpart.

I have a similar patch in one of my series:
https://lore.kernel.org/linux-iommu/16ae24cc2a002802b990afa1a69fe4ceab1e0da2.1790188510.git.nicolinc@nvidia.com/

Mine only handles CMDQ error though..

Nicolin

#31 lore raw

Re: [PATCH v11 10/16] iommu/arm-smmu-v3: Factor out arm_smmu_handle_gerror()

Quoted 10 lines · Nicolin Chen
Quoted 8 lines · Pranjal Shrivastava

The GERROR register's state might be lost when the SMMU is powered down during runtime suspend, requiring the suspend sequence to handle any pending errors before the hardware state is lost.

Refactor the gerror handling logic into a helper function. Subsequent patches will invoke it from the runtime suspend callback after disabling the SMMU, ensuring that any late-breaking gerrors are logged and ack'ed before the hardware state is lost.

Quoted 7 lines

CMDQV has a separate IRQ, so I think it likely needs a counterpart.

I have a similar patch in one of my series:
https://lore.kernel.org/linux-iommu/16ae24cc2a002802b990afa1a69fe4ceab1e0da2.1790188510.git.nicolinc@nvidia.com/

Mine only handles CMDQ error though..

I'll add a counterpart to arm_smmu_handle_gerror() in v12, I'll factor out the body of tegra241_cmdqv_isr() into something like tegra241_cmdqv_handle_errors() (bailing out early if VINTF_ERR_MAP is clear, so we don't warn on every suspend). The new impl->suspend op would call it after draining the lvcmdqs, with cmdqv->irq disabled around it, right before hw_deinit(vintf0).

Since yours is for the CMD_SYNC timeout path, I'll keep this independent? WDYT?

Praan

#32 lore raw

Re: [PATCH v11 10/16] iommu/arm-smmu-v3: Factor out arm_smmu_handle_gerror()

Quoted 26 lines · Pranjal Shrivastava
Quoted 10 lines · Nicolin Chen
Quoted 8 lines · Pranjal Shrivastava

The GERROR register's state might be lost when the SMMU is powered down during runtime suspend, requiring the suspend sequence to handle any pending errors before the hardware state is lost.

Refactor the gerror handling logic into a helper function. Subsequent patches will invoke it from the runtime suspend callback after disabling the SMMU, ensuring that any late-breaking gerrors are logged and ack'ed before the hardware state is lost.

Quoted 7 lines

CMDQV has a separate IRQ, so I think it likely needs a counterpart.

I have a similar patch in one of my series:
https://lore.kernel.org/linux-iommu/16ae24cc2a002802b990afa1a69fe4ceab1e0da2.1790188510.git.nicolinc@nvidia.com/

Mine only handles CMDQ error though..

I'll add a counterpart to arm_smmu_handle_gerror() in v12, I'll factor out the body of tegra241_cmdqv_isr() into something like tegra241_cmdqv_handle_errors() (bailing out early if VINTF_ERR_MAP is clear, so we don't warn on every suspend). The new impl->suspend op would call it after draining the lvcmdqs, with cmdqv->irq disabled around it, right before hw_deinit(vintf0).

Quoted 2 lines

Since yours is for the CMD_SYNC timeout path, I'll keep this independent? WDYT?

I'm fine with the independent function for now.

Nicolin

#33 lore raw

Re: [PATCH v11 10/16] iommu/arm-smmu-v3: Factor out arm_smmu_handle_gerror()

In reply to Nicolin Chen
Quoted 10 lines · Nicolin Chen
Quoted 8 lines · Pranjal Shrivastava

The GERROR register's state might be lost when the SMMU is powered down during runtime suspend, requiring the suspend sequence to handle any pending errors before the hardware state is lost.

Refactor the gerror handling logic into a helper function. Subsequent patches will invoke it from the runtime suspend callback after disabling the SMMU, ensuring that any late-breaking gerrors are logged and ack'ed before the hardware state is lost.

Quoted 5 lines

CMDQV has a separate IRQ, so I think it likely needs a counterpart.

I have a similar patch in one of my series:
https://lore.kernel.org/linux-iommu/16ae24cc2a002802b990afa1a69fe4ceab1e0da2.1790188510.git.nicolinc@nvidia.com/

On a different note, I should look at that series, I think there were multiple things that were fixed/addreseds in that series. I'll try to take a look soon.

Thanks,
Praan

maintainer
#34 lore raw

Re: [PATCH v11 10/16] iommu/arm-smmu-v3: Factor out arm_smmu_handle_gerror()

In reply to Pranjal Shrivastava
Quoted 22 lines · Pranjal Shrivastava

The GERROR register's state might be lost when the SMMU is powered down during runtime suspend, requiring the suspend sequence to handle any pending errors before the hardware state is lost.

Refactor the gerror handling logic into a helper function. Subsequent patches will invoke it from the runtime suspend callback after disabling the SMMU, ensuring that any late-breaking gerrors are logged and ack'ed before the hardware state is lost.

---
 drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c | 11 +++++++++--
 1 file changed, 9 insertions(+), 2 deletions(-)
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +0 -0
index 7347d3ecdae8..a123810fac57 100644

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c static irqreturn_t arm_smmu_priq_thread(int irq, void *dev) · line 2409

Quoted 5 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +1 -1
@@ -2406,10 +2406,10 @@ static irqreturn_t arm_smmu_priq_thread(int irq, void *dev)
 
 static int arm_smmu_device_disable(struct arm_smmu_device *smmu);
 
-static irqreturn_t arm_smmu_gerror_handler(int irq, void *dev)
+/* Lockless; must ensure that there are no concurrent callers */

This comment doesn't add an awful lot imo. You could probably say the same about many kernel functions and this isn't exposed outside of the file...

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c static irqreturn_t arm_smmu_gerror_handler(int irq, void *dev) · line 2453

Quoted 10 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +1 -1
+static irqreturn_t arm_smmu_handle_gerror(struct arm_smmu_device *smmu)
 {
 	u32 gerror, gerrorn, active;
-	struct arm_smmu_device *smmu = dev;
 
 	gerror = readl_relaxed(smmu->base + ARM_SMMU_GERROR);
 	gerrorn = readl_relaxed(smmu->base + ARM_SMMU_GERRORN);
@@ -2452,6 +2452,13 @@ static irqreturn_t arm_smmu_gerror_handler(int irq, void *dev)
 	return IRQ_HANDLED;
 }

I think it's a bit weird to return an irqreturn_t from a function that is now going to be called outside of irq context. Also, it looks like you end up calling this later on after you have drained the cmdq, which makes me a little worried about the case when we can end up calling __arm_smmu_cmdq_skip_err().

Will

#35 lore raw

PATCH v11 11/16 iommu/arm-smmu-v3: Add CMDQ_PROD_STOP_FLAG to gate CMDQ submissions

In reply to Pranjal Shrivastava

Introduce a new bit flag, CMDQ_PROD_STOP_FLAG (bit 30), in the command queue's producer index to safely gate command submissions during device suspension.

The flag embeds the suspend state directly into the existing global state The flag is checked in the cmpxchg loop in arm_smmu_cmdq_issue_cmdlist(), which acts as a Point of Commitment, ensuring that no indices are reserved or committed once the SMMU begins suspending.

This prevents a situation of "abandoned batches" where indices are incremented but commands are never written, which would otherwise lead to timeout during the drain poll.

Update queue_inc_prod_n() to preserve this flag during index calculations, ensuring that any in-flight commands that successfully passed the point of commitment can proceed to completion while the flag remains set.

---
 drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c | 35 +++++++++++++++++++--
 drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h |  5 +++
 2 files changed, 38 insertions(+), 2 deletions(-)
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +33 -2
index a123810fac57..7f89e2306942 100644
@@ -218,7 +218,8 @@ static int queue_sync_prod_in(struct arm_smmu_queue *q)
 static u32 queue_inc_prod_n(struct arm_smmu_ll_queue *q, int n)
 {
 	u32 prod = Q_POS(q, q->prod) + n;
-	return Q_OVF(q->prod) | Q_POS(q, prod);
+
+	return Q_OVF(q->prod) | Q_STOP(q->prod) | Q_POS(q, prod);
 }
 
 static void queue_poll_init(struct arm_smmu_device *smmu,
@@ -726,13 +727,42 @@ int __arm_smmu_cmdq_issue_cmdlist(struct arm_smmu_device *smmu,
 	do {
 		u64 old;
 
+		/*
+		 * If the SMMU is suspended/suspending, any new CMDs are elided.
+		 * This loop is the Point of Commitment. If we haven't cmpxchg'd
+		 * our new indices yet, we can safely bail. Once the indices are
+		 * committed, we MUST write valid commands to those slots to
+		 * avoid indefinite polling in the drain function.
+		 */
+		if (Q_STOP(llq.prod)) {
+			local_irq_restore(flags);
+			return 0;
+		}
+
 		while (!queue_has_space(&llq, n + sync)) {
 			local_irq_restore(flags);
+
+			/* Avoid waiting for space if the SMMU is suspending */
+			if (Q_STOP(READ_ONCE(cmdq->q.llq.prod)))
+				return 0;
+
 			if (arm_smmu_cmdq_poll_until_not_full(smmu, cmdq, &llq))
 				dev_err_ratelimited(smmu->dev, "CMDQ timeout\n");
 			local_irq_save(flags);
 		}
 
+		/*
+		 * If we exited the polling loop because the queue finally
+		 * has space, but the STOP_FLAG was set during the poll,
+		 * we must abort immediately. If we proceed, we will
+		 * commit new commands beyond the Point of Commitment while
+		 * the SMMU is suspending.
+		 */
+		if (Q_STOP(llq.prod)) {
+			local_irq_restore(flags);
+			return 0;
+		}
+
 		head.cons = llq.cons;
 		head.prod = queue_inc_prod_n(&llq, n + sync) |
 					     CMDQ_PROD_OWNED_FLAG;
@@ -779,7 +809,8 @@ int __arm_smmu_cmdq_issue_cmdlist(struct arm_smmu_device *smmu,
 		/* b. Stop gathering work by clearing the owned flag */
 		prod = atomic_fetch_andnot_relaxed(CMDQ_PROD_OWNED_FLAG,
 						   &cmdq->q.llq.atomic.prod);
-		prod &= ~CMDQ_PROD_OWNED_FLAG;
+		/* Strip all metadata flags */
+		prod &= CMDQ_PROD_IDX_MASK;
 
 		/*
 		 * c. Wait for any gathered work to be written to the queue.
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h +5 -0
index deefb17e31eb..794b258550dd 100644
@@ -394,6 +394,11 @@ static inline unsigned int arm_smmu_cdtab_l2_idx(unsigned int ssid)
 #define CMDQ_ERR_CERROR_ATC_INV_IDX	3
 
 #define CMDQ_PROD_OWNED_FLAG		Q_OVERFLOW_FLAG
+#define CMDQ_PROD_STOP_FLAG		(1U << 30)
+#define Q_STOP(p)			((p) & CMDQ_PROD_STOP_FLAG)
+
+/* Mask out software-only metadata flags to get the pure queue index/wrap bits */
+#define CMDQ_PROD_IDX_MASK		~(CMDQ_PROD_STOP_FLAG | CMDQ_PROD_OWNED_FLAG)
 
 struct arm_smmu_cmd {
 	u64 data[CMDQ_ENT_DWORDS];
Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#36 lore raw

Re: [PATCH v11 11/16] iommu/arm-smmu-v3: Add CMDQ_PROD_STOP_FLAG to gate CMDQ submissions

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] iommu/arm-smmu-v3: memory corruption from dropped ATC_INV when SMMU is suspended --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] iommu/arm-smmu-v3: memory corruption from dropped ATC_INV when SMMU is suspended --

commit 1d62496e7c0326798403d88bba79adbf58c43810
Author: Pranjal Shrivastava <[email protected]>

iommu/arm-smmu-v3: Add CMDQ_PROD_STOP_FLAG to gate CMDQ submissions

This commit introduces a CMDQ_PROD_STOP_FLAG to safely gate command queue submissions during device suspension. It checks this flag in the cmpxchg loop to avoid abandoning batches and indefinite polling during drains.

Quoted 3 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +0 -0

[ ... ]

Quoted 5 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +1 -0
@@ -726,13 +727,42 @@ int __arm_smmu_cmdq_issue_cmdlist(struct arm_smmu_device *smmu,
 	do {
 		u64 old;
 
+		/*

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c int __arm_smmu_cmdq_issue_cmdlist(struct arm_smmu_device *smmu, · line 740

Quoted 10 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +10 -0
+		 * If the SMMU is suspended/suspending, any new CMDs are elided.
+		 * This loop is the Point of Commitment. If we haven't cmpxchg'd
+		 * our new indices yet, we can safely bail. Once the indices are
+		 * committed, we MUST write valid commands to those slots to
+		 * avoid indefinite polling in the drain function.
+		 */
+		if (Q_STOP(llq.prod)) {
+			local_irq_restore(flags);
+			return 0;
+		}

[Severity: High]
Can this early return cause memory corruption by silently dropping ATC invalidations?

When the SMMU suspends, Q_STOP(llq.prod) becomes true. If a driver or background thread then calls dma_unmap() to free a buffer while a PCIe endpoint (with ATS enabled) is suspended to a state like D0, the SMMU driver will observe the stop flag here in __arm_smmu_cmdq_issue_cmdlist().

By bailing out and returning 0 (success) without actually submitting the CMDQ_OP_ATC_INV command to the hardware, the IOMMU core is misled into freeing the memory while the PCIe endpoint's Address Translation Cache (ATC) retains the stale translation. When the PCI device resumes, or if it issues a TLP while in D0, it could use the stale ATC entry to access the now-freed memory, bypassing IOMMU protections.

Are we assuming endpoint drivers clear their own ATC or that a hardware reset handles it? Client endpoint drivers typically lack an API to manually clear the ATC, and SMMU hardware resets do not broadcast ATC invalidations to endpoints.

[ ... ]

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=11
#37 lore raw

Re: [PATCH v11 11/16] iommu/arm-smmu-v3: Add CMDQ_PROD_STOP_FLAG to gate CMDQ submissions

In reply to Pranjal Shrivastava
Quoted 5 lines · Pranjal Shrivastava
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +1 -0
@@ -726,13 +727,42 @@ int __arm_smmu_cmdq_issue_cmdlist(struct arm_smmu_device *smmu,
 	do {
 		u64 old;
 
+		/*

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c int __arm_smmu_cmdq_issue_cmdlist(struct arm_smmu_device *smmu, · line 740

Quoted 10 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +10 -0
+		 * If the SMMU is suspended/suspending, any new CMDs are elided.
+		 * This loop is the Point of Commitment. If we haven't cmpxchg'd
+		 * our new indices yet, we can safely bail. Once the indices are
+		 * committed, we MUST write valid commands to those slots to
+		 * avoid indefinite polling in the drain function.
+		 */
+		if (Q_STOP(llq.prod)) {
+			local_irq_restore(flags);
+			return 0;
+		}

Sashiko pointed out this:
"
Can this early return cause memory corruption by silently dropping ATC invalidations?

When the SMMU suspends, Q_STOP(llq.prod) becomes true. If a driver or background thread then calls dma_unmap() to free a buffer while a PCIe endpoint (with ATS enabled) is suspended to a state like D0, the SMMU driver will observe the stop flag here in __arm_smmu_cmdq_issue_cmdlist().

By bailing out and returning 0 (success) without actually submitting the CMDQ_OP_ATC_INV command to the hardware, the IOMMU core is misled into freeing the memory while the PCIe endpoint's Address Translation Cache (ATC) retains the stale translation. When the PCI device resumes, or if it issues a TLP while in D0, it could use the stale ATC entry to access the now-freed memory, bypassing IOMMU protections.

Are we assuming endpoint drivers clear their own ATC or that a hardware reset handles it? Client endpoint drivers typically lack an API to manually clear the ATC, and SMMU hardware resets do not broadcast ATC invalidations to endpoints.
"

We may get away from the TLB maintenance. But ATC can be the case broken by the stop flag?

Nicolin

#38 lore raw

Re: [PATCH v11 11/16] iommu/arm-smmu-v3: Add CMDQ_PROD_STOP_FLAG to gate CMDQ submissions

Quoted 34 lines · Nicolin Chen
Quoted 5 lines · Pranjal Shrivastava
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +1 -0
@@ -726,13 +727,42 @@ int __arm_smmu_cmdq_issue_cmdlist(struct arm_smmu_device *smmu,
 	do {
 		u64 old;
 
+		/*

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c int __arm_smmu_cmdq_issue_cmdlist(struct arm_smmu_device *smmu, · line 740

Quoted 10 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +10 -0
+		 * If the SMMU is suspended/suspending, any new CMDs are elided.
+		 * This loop is the Point of Commitment. If we haven't cmpxchg'd
+		 * our new indices yet, we can safely bail. Once the indices are
+		 * committed, we MUST write valid commands to those slots to
+		 * avoid indefinite polling in the drain function.
+		 */
+		if (Q_STOP(llq.prod)) {
+			local_irq_restore(flags);
+			return 0;
+		}

Sashiko pointed out this:
"
Can this early return cause memory corruption by silently dropping ATC invalidations?

When the SMMU suspends, Q_STOP(llq.prod) becomes true. If a driver or background thread then calls dma_unmap() to free a buffer while a PCIe endpoint (with ATS enabled) is suspended to a state like D0, the SMMU driver will observe the stop flag here in __arm_smmu_cmdq_issue_cmdlist().

By bailing out and returning 0 (success) without actually submitting the CMDQ_OP_ATC_INV command to the hardware, the IOMMU core is misled into freeing the memory while the PCIe endpoint's Address Translation Cache (ATC) retains the stale translation. When the PCI device resumes, or if it issues a TLP while in D0, it could use the stale ATC entry to access the now-freed memory, bypassing IOMMU protections.

Quoted 9 lines

Are we assuming endpoint drivers clear their own ATC or that a hardware reset handles it? Client endpoint drivers typically lack an API to manually clear the ATC, and SMMU hardware resets do not broadcast ATC invalidations to endpoints.
"

We may get away from the TLB maintenance. But ATC can be the case broken by the stop flag?

Not really, I guess Sashiko missed the comment in a later patch. This was discussed with Jason in v9 [1].

The key thing is that ATC_INVs can't be issued by the time we set this flag anyway.. if we're in the suspend callback, the PCIe EP is already suspended, so none of the ATC invalidation TLPs would be responded to.

I'd addressed this in the RPM patch with a comment right above this check:

* Note that eliding ATC invalidations (CMDQ_OP_ATC_INV) is safe
* because client PCIe endpoints are guaranteed to be suspended
* (via device links) before the SMMU is suspended. With the PCIe
* links in a low-power state, no new TLPs can be transmitted.
* It is strictly the responsibility of the client/endpoint driver
* to quiesce DMA and ensure that the ATC state is cleared across
* power state transitions.

i.e. we only start eliding once *all* consumers are RPM suspended, so the "endpoint in D0" scenario can't happen.. and a suspended PCIe function shouldn't be issuing translated requests anyway.

So we can't issue ATC_INVs during suspend (the EP is already down), nor during resume (the SMMU resumes *before* the EP is made active). The EP can't use its ATC while suspended, and if it loses power/resets on the way back to D0 (from D3cold, or D3hot with No_Soft_Reset=0), it comes back with an empty ATC.. same assumption the PCI reset path makes today (pci_dev_reset_iommu_prepare()).

I can add a pointer in this patch's comment to the RPM patch to make that clearer.

[1] https://lore.kernel.org/all/[email protected]/

Thanks,
Praan

#39 lore raw

Re: [PATCH v11 11/16] iommu/arm-smmu-v3: Add CMDQ_PROD_STOP_FLAG to gate CMDQ submissions

Quoted 11 lines · Pranjal Shrivastava
Quoted 3 lines · Nicolin Chen

We may get away from the TLB maintenance. But ATC can be the case broken by the stop flag?

Not really, I guess Sashiko missed the comment in a later patch. This was discussed with Jason in v9 [1].

The key thing is that ATC_INVs can't be issued by the time we set this flag anyway.. if we're in the suspend callback, the PCIe EP is already suspended, so none of the ATC invalidation TLPs would be responded to.

Okay.

Quoted 10 lines

I'd addressed this in the RPM patch with a comment right above this check:

* Note that eliding ATC invalidations (CMDQ_OP_ATC_INV) is safe
* because client PCIe endpoints are guaranteed to be suspended
* (via device links) before the SMMU is suspended. With the PCIe
* links in a low-power state, no new TLPs can be transmitted.
* It is strictly the responsibility of the client/endpoint driver
* to quiesce DMA and ensure that the ATC state is cleared across
* power state transitions.

Quoted 3 lines

i.e. we only start eliding once *all* consumers are RPM suspended, so the "endpoint in D0" scenario can't happen.. and a suspended PCIe function shouldn't be issuing translated requests anyway.

Maybe move it to this PATCH-11?

Quoted 6 lines

So we can't issue ATC_INVs during suspend (the EP is already down), nor during resume (the SMMU resumes *before* the EP is made active). The EP can't use its ATC while suspended, and if it loses power/resets on the way back to D0 (from D3cold, or D3hot with No_Soft_Reset=0), it comes back with an empty ATC.. same assumption the PCI reset path makes today (pci_dev_reset_iommu_prepare()).

In that case, would the STOP flag be too late? It's only set in the middle of the SMMU suspend. So, an ATC command (via doamin invalidation) might be issued prior to the Point of Commitment, which will be timed out due to the unresponding EP?

Nicolin

#40 lore raw

Re: [PATCH v11 11/16] iommu/arm-smmu-v3: Add CMDQ_PROD_STOP_FLAG to gate CMDQ submissions

Quoted 11 lines · Nicolin Chen
Quoted 6 lines

So we can't issue ATC_INVs during suspend (the EP is already down), nor during resume (the SMMU resumes *before* the EP is made active). The EP can't use its ATC while suspended, and if it loses power/resets on the way back to D0 (from D3cold, or D3hot with No_Soft_Reset=0), it comes back with an empty ATC.. same assumption the PCI reset path makes today (pci_dev_reset_iommu_prepare()).

In that case, would the STOP flag be too late? It's only set in the middle of the SMMU suspend. So, an ATC command (via doamin invalidation) might be issued prior to the Point of Commitment, which will be timed out due to the unresponding EP?

How can you ever fix that?

How does power management really work, is it expected that the end device is already quieted by its driver?

Could the first step in power management install a blocked STE? Then we don't have to worry about ATC desync and that automatically stops generating new ATC invalidations if we go and detact the domains too

Maybe I'm wondering if power management should involve the core code so it detaches all the domains from the device, setups up blocking and then the iommu itself could power ofF?

Jason

#41 lore raw

Re: [PATCH v11 11/16] iommu/arm-smmu-v3: Add CMDQ_PROD_STOP_FLAG to gate CMDQ submissions

Quoted 9 lines · Jason Gunthorpe
Quoted 7 lines · Nicolin Chen
Quoted 6 lines

So we can't issue ATC_INVs during suspend (the EP is already down), nor during resume (the SMMU resumes *before* the EP is made active). The EP can't use its ATC while suspended, and if it loses power/resets on the way back to D0 (from D3cold, or D3hot with No_Soft_Reset=0), it comes back with an empty ATC.. same assumption the PCI reset path makes today (pci_dev_reset_iommu_prepare()).

Quoted 6 lines
Quoted 4 lines

In that case, would the STOP flag be too late? It's only set in the middle of the SMMU suspend. So, an ATC command (via doamin invalidation) might be issued prior to the Point of Commitment, which will be timed out due to the unresponding EP?

How can you ever fix that?

The unfortunate reality is that this gap exists in the kernel even today.. upstream SMMUv3 has no RPM, so it's always on, while the EPs can runtime suspend independently. So an ATC_INV can already be issued to an EP that has suspended. I'd argue RPM improves this slightly, since once the STOP flag is set everything is elided, so the window closes at SMMU suspend instead of never.

Quoted 4 lines

How does power management really work, is it expected that the end device is already quieted by its driver?

Yes, power management would topo-sort all dependencies and invoke suspend callbacks accordingly, i.e. in our case the suspend callbacks of all SMMU clients would be called before the SMMU's suspend callback.

Quoted 4 lines

Could the first step in power management install a blocked STE? Then we don't have to worry about ATC desync and that automatically stops generating new ATC invalidations if we go and detact the domains too

Partially.. at SMMU suspend we set GBPA to abort and clear SMMUEN, so nothing gets through while the SMMU is off. But that's global and only happens after all EPs are down, it doesn't stop ATC_INVs in the window Nicolin pointed out.

One way to ensure the ATC state is relying on the PCIe spec to lose ATC content during D0 entry from D3cold, or D3hot with No_Soft_Reset=0).

Another way to enforce this, is to *somehow* ask the endpoint drivers disable ATS during *their* suspend, i.e. in the EP's driver's suspend they could call pci_disable_ats or a better suited helper from pci core and the in the pm_resume / rpm_resume they could call it's equivalent pci_enable_ats, counterpart ensuring a clean ATS state. Or maybe the pci_dev_reset_iommu_prepare/done() pair (with slight refactoring) in EP's suspend/resume?

I could mention this explicitly in some comments or dev_warn if any of the masters have ATS state as ON during suspend?

LMK what you guys think of that?

Quoted 3 lines

Maybe I'm wondering if power management should involve the core code so it detaches all the domains from the device, setups up blocking and then the iommu itself could power ofF?

I'm slightly against the blocking domain attach because it's a reasonable ask for the client drivers to be able to dma_map / unmap when they're suspended, given that most of the modern IOMMU state is in-memory and the only HW state is some sort of TLB/ATC maintenance. We can map/unmap when the IOMMU is off and just ensure a clean cache state.

Drivers often want to pre-map everything, power ON just to run their workload, power off and then unmap.

That said, I agree it would be nice to have the core code handle power management, which can be one of the next steps. (it would be complicated to see how or what each IOMMU might have to handle for power mangement in a generic way).

Quoted 1 line

Jason

Thanks,
Praan

#42 lore raw

Re: [PATCH v11 11/16] iommu/arm-smmu-v3: Add CMDQ_PROD_STOP_FLAG to gate CMDQ submissions

Quoted 15 lines · Pranjal Shrivastava
Quoted 14 lines · Jason Gunthorpe
Quoted 11 lines · Nicolin Chen
Quoted 6 lines

So we can't issue ATC_INVs during suspend (the EP is already down), nor during resume (the SMMU resumes *before* the EP is made active). The EP can't use its ATC while suspended, and if it loses power/resets on the way back to D0 (from D3cold, or D3hot with No_Soft_Reset=0), it comes back with an empty ATC.. same assumption the PCI reset path makes today (pci_dev_reset_iommu_prepare()).

In that case, would the STOP flag be too late? It's only set in the middle of the SMMU suspend. So, an ATC command (via doamin invalidation) might be issued prior to the Point of Commitment, which will be timed out due to the unresponding EP?

Quoted 8 lines
Quoted 1 line

How can you ever fix that?

The unfortunate reality is that this gap exists in the kernel even today.. upstream SMMUv3 has no RPM, so it's always on, while the EPs can runtime suspend independently. So an ATC_INV can already be issued to an EP that has suspended. I'd argue RPM improves this slightly, since once the STOP flag is set everything is elided, so the window closes at SMMU suspend instead of never.

That doesn't sound very convincing though...

Quoted 7 lines
Quoted 3 lines

How does power management really work, is it expected that the end device is already quieted by its driver?

Yes, power management would topo-sort all dependencies and invoke suspend callbacks accordingly, i.e. in our case the suspend callbacks of all SMMU clients would be called before the SMMU's suspend callback.

If that's guaranteed, we should probably -EBUSY the suspend if one STE isn't aborted.

Quoted 10 lines
Quoted 4 lines

Could the first step in power management install a blocked STE? Then we don't have to worry about ATC desync and that automatically stops generating new ATC invalidations if we go and detact the domains too

Partially.. at SMMU suspend we set GBPA to abort and clear SMMUEN, so nothing gets through while the SMMU is off. But that's global and only happens after all EPs are down, it doesn't stop ATC_INVs in the window Nicolin pointed out.

Quoted 8 lines

One way to ensure the ATC state is relying on the PCIe spec to lose ATC content during D0 entry from D3cold, or D3hot with No_Soft_Reset=0).

Another way to enforce this, is to *somehow* ask the endpoint drivers disable ATS during *their* suspend, i.e. in the EP's driver's suspend they could call pci_disable_ats or a better suited helper from pci core and the in the pm_resume / rpm_resume they could call it's equivalent pci_enable_ats, counterpart ensuring a clean ATS state. Or maybe the

pci_enable/disable_ats is used by IOMMU drivers only.

Quoted 2 lines

pci_dev_reset_iommu_prepare/done() pair (with slight refactoring) in EP's suspend/resume?

That sounds right to me, though a different API for suspend/resume will be required. And call them in pci_pm_runtime_suspend/resume() maybe.

Jason, how do you think about this?

Quoted 9 lines

I could mention this explicitly in some comments or dev_warn if any of the masters have ATS state as ON during suspend?

LMK what you guys think of that?

Quoted 3 lines

Maybe I'm wondering if power management should involve the core code so it detaches all the domains from the device, setups up blocking and then the iommu itself could power ofF?

Quoted 7 lines

I'm slightly against the blocking domain attach because it's a reasonable ask for the client drivers to be able to dma_map / unmap when they're suspended, given that most of the modern IOMMU state is in-memory and the only HW state is some sort of TLB/ATC maintenance. We can map/unmap when the IOMMU is off and just ensure a clean cache state. Drivers often want to pre-map everything, power ON just to run their workload, power off and then unmap.

If it's about mapping, it shouldn't be a problem: while a device is in suspend state, iommu_group->domain would point to the DMA domain. This is similar to the resetting flow that only sets gdev->blocked.

Nicolin

#43 lore raw

Re: [PATCH v11 11/16] iommu/arm-smmu-v3: Add CMDQ_PROD_STOP_FLAG to gate CMDQ submissions

Quoted 8 lines · Nicolin Chen
Quoted 2 lines

pci_dev_reset_iommu_prepare/done() pair (with slight refactoring) in EP's suspend/resume?

That sounds right to me, though a different API for suspend/resume will be required. And call them in pci_pm_runtime_suspend/resume() maybe.

Jason, how do you think about this?

Maybe lets just start by refusing power management when ATS is on? For PCIe devices too?

It isn't just ARM that has this issue, every iommu is busted if you suspend the PCI device while an ATS domain is still active..

Jason

#44 lore raw

Re: [PATCH v11 11/16] iommu/arm-smmu-v3: Add CMDQ_PROD_STOP_FLAG to gate CMDQ submissions

Quoted 8 lines · Jason Gunthorpe
Quoted 7 lines · Nicolin Chen
Quoted 2 lines

pci_dev_reset_iommu_prepare/done() pair (with slight refactoring) in EP's suspend/resume?

That sounds right to me, though a different API for suspend/resume will be required. And call them in pci_pm_runtime_suspend/resume() maybe.

Quoted 7 lines
Quoted 1 line

Jason, how do you think about this?

Maybe lets just start by refusing power management when ATS is on? For PCIe devices too?

It isn't just ARM that has this issue, every iommu is busted if you suspend the PCI device while an ATS domain is still active..

So, should we put that refuse guard in pci_pm_runtime_suspend()?

I am thinking about splitting the iommu and pci patches out of my smmmuv3_atc_timeout series. They could be get merged alone.

Then, we add a new API for pci_pm_runtime_suspend/resume() with a new BLOCKED_SUSPEND reason in the list:
https://lore.kernel.org/linux-iommu/bf5ccc916593357c640cd7fcdffabfb46fdf4c64.1790188510.git.nicolinc@nvidia.com/

Nicolin

#45 lore raw

Re: [PATCH v11 11/16] iommu/arm-smmu-v3: Add CMDQ_PROD_STOP_FLAG to gate CMDQ submissions

Quoted 17 lines · Nicolin Chen
Quoted 8 lines · Jason Gunthorpe
Quoted 7 lines · Nicolin Chen
Quoted 2 lines

pci_dev_reset_iommu_prepare/done() pair (with slight refactoring) in EP's suspend/resume?

That sounds right to me, though a different API for suspend/resume will be required. And call them in pci_pm_runtime_suspend/resume() maybe.

Quoted 7 lines
Quoted 1 line

Jason, how do you think about this?

Maybe lets just start by refusing power management when ATS is on? For PCIe devices too?

It isn't just ARM that has this issue, every iommu is busted if you suspend the PCI device while an ATS domain is still active..

Quoted 7 lines

So, should we put that refuse guard in pci_pm_runtime_suspend()?

I am thinking about splitting the iommu and pci patches out of my smmmuv3_atc_timeout series. They could be get merged alone.

Then, we add a new API for pci_pm_runtime_suspend/resume() with a new BLOCKED_SUSPEND reason in the list:

The guard doesn't sound too bad, but what if we refactor the reset APIs instead and use them from the PCI core to disable ATS + flush the ATC right before the EP suspends, as discussed earlier? That'd fix it for every IOMMU without taking PM away from anyone.

FWIW, AFAICT VT-d and AMD-Vi already enable ATS for ATS-capable devices attached to the default DMA domain, so a blanket refusal might end up disabling RPM for some internal devices (e.g. dGPUs / NVMe) that rely on it today.

On the PCI side, I could roughly:

- Base on Nicolin's split out iommu/pci patches (blocked reason list)
- Add a suspend flavour of pci_dev_reset_iommu_prepare/done() with a BLOCKED_SUSPEND reason, i.e. RID/PASIDs parked on the blocking domain, group->domain retained (so dma_map/unmap keep working), ATS-capable devices only
- Call prepare() in pci_pm_runtime_suspend() after the driver's callback but before D3, and done() in pci_pm_runtime_resume() after D0 + pci_restore_state() but before the driver's callback. Same for the system sleep (noirq) paths
- Keep the guard only as a fallback, i.e. -EBUSY the suspend if prepare() fails

That flushes the ATC while the EP can still respond and stops any new ATC_INVs to it. On the SMMU side, we'd then never see a suspended ATS master with ATS still enabled, so a WARN_ON_ONCE() at suspend would do.

WDYT?

Thanks,
Praan

#46 lore raw

Re: [PATCH v11 11/16] iommu/arm-smmu-v3: Add CMDQ_PROD_STOP_FLAG to gate CMDQ submissions

In reply to Nicolin Chen
Quoted 18 lines · Nicolin Chen
Quoted 17 lines · Pranjal Shrivastava
Quoted 15 lines · Jason Gunthorpe
Quoted 11 lines · Nicolin Chen
Quoted 6 lines

So we can't issue ATC_INVs during suspend (the EP is already down), nor during resume (the SMMU resumes *before* the EP is made active). The EP can't use its ATC while suspended, and if it loses power/resets on the way back to D0 (from D3cold, or D3hot with No_Soft_Reset=0), it comes back with an empty ATC.. same assumption the PCI reset path makes today (pci_dev_reset_iommu_prepare()).

In that case, would the STOP flag be too late? It's only set in the middle of the SMMU suspend. So, an ATC command (via doamin invalidation) might be issued prior to the Point of Commitment, which will be timed out due to the unresponding EP?

How can you ever fix that?

Quoted 9 lines
Quoted 6 lines

The unfortunate reality is that this gap exists in the kernel even today.. upstream SMMUv3 has no RPM, so it's always on, while the EPs can runtime suspend independently. So an ATC_INV can already be issued to an EP that has suspended. I'd argue RPM improves this slightly, since once the STOP flag is set everything is elided, so the window closes at SMMU suspend instead of never.

That doesn't sound very convincing though...

All I'm saying is that today, EPs can get suspended without the SMMU ever knowing, making the SMMU aware of it helps with that.. although I agree we need a policy here.

Quoted 11 lines
Quoted 7 lines
Quoted 3 lines

How does power management really work, is it expected that the end device is already quieted by its driver?

Yes, power management would topo-sort all dependencies and invoke suspend callbacks accordingly, i.e. in our case the suspend callbacks of all SMMU clients would be called before the SMMU's suspend callback.

If that's guaranteed, we should probably -EBUSY the suspend if one STE isn't aborted.

That'd only work for (ATS-enabled) PCI devices.. for platform devices, the STE stays as is across RPM by design (no ATC, and the TLB/CFG state is covered by the invalidate-all on resume).

Quoted 13 lines
Quoted 13 lines
Quoted 4 lines

Could the first step in power management install a blocked STE? Then we don't have to worry about ATC desync and that automatically stops generating new ATC invalidations if we go and detact the domains too

Partially.. at SMMU suspend we set GBPA to abort and clear SMMUEN, so nothing gets through while the SMMU is off. But that's global and only happens after all EPs are down, it doesn't stop ATC_INVs in the window Nicolin pointed out.

One way to ensure the ATC state is relying on the PCIe spec to lose ATC content during D0 entry from D3cold, or D3hot with No_Soft_Reset=0).

Quoted 8 lines
Quoted 5 lines

Another way to enforce this, is to *somehow* ask the endpoint drivers disable ATS during *their* suspend, i.e. in the EP's driver's suspend they could call pci_disable_ats or a better suited helper from pci core and the in the pm_resume / rpm_resume they could call it's equivalent pci_enable_ats, counterpart ensuring a clean ATS state. Or maybe the

pci_enable/disable_ats is used by IOMMU drivers only.

Can't the PCI core call it too? I agree the endpoint drivers may not be aware of ATS, but there should be some way for us to flush + disable the ATC after the EP driver's suspend & before the EP sleeps (and so before the SMMU's suspend is called)?

Quoted 7 lines
Quoted 2 lines

pci_dev_reset_iommu_prepare/done() pair (with slight refactoring) in EP's suspend/resume?

That sounds right to me, though a different API for suspend/resume will be required. And call them in pci_pm_runtime_suspend/resume() maybe.

Ack.

Praan

maintainer
#47 lore raw

Re: [PATCH v11 11/16] iommu/arm-smmu-v3: Add CMDQ_PROD_STOP_FLAG to gate CMDQ submissions

In reply to Pranjal Shrivastava
Quoted 8 lines · Pranjal Shrivastava

Introduce a new bit flag, CMDQ_PROD_STOP_FLAG (bit 30), in the command queue's producer index to safely gate command submissions during device suspension.

The flag embeds the suspend state directly into the existing global state The flag is checked in the cmpxchg loop in arm_smmu_cmdq_issue_cmdlist(), which acts as a Point of Commitment, ensuring that no indices are reserved or committed once the SMMU begins suspending.

I'm not familiar with the term "Point of Commitment". Is that something you came up with? Without a general definition, I think I'd prefer to avoid using it, especially as it sounds like something to do with the Arm memory system (where we already have architectural terms such as "Point of Coherency".

Quoted 46 lines

This prevents a situation of "abandoned batches" where indices are incremented but commands are never written, which would otherwise lead to timeout during the drain poll.

Update queue_inc_prod_n() to preserve this flag during index calculations, ensuring that any in-flight commands that successfully passed the point of commitment can proceed to completion while the flag remains set.

---
 drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c | 35 +++++++++++++++++++--
 drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h |  5 +++
 2 files changed, 38 insertions(+), 2 deletions(-)
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +13 -1
index a123810fac57..7f89e2306942 100644
@@ -218,7 +218,8 @@ static int queue_sync_prod_in(struct arm_smmu_queue *q)
 static u32 queue_inc_prod_n(struct arm_smmu_ll_queue *q, int n)
 {
 	u32 prod = Q_POS(q, q->prod) + n;
-	return Q_OVF(q->prod) | Q_POS(q, prod);
+
+	return Q_OVF(q->prod) | Q_STOP(q->prod) | Q_POS(q, prod);
 }
 
 static void queue_poll_init(struct arm_smmu_device *smmu,
@@ -726,13 +727,42 @@ int __arm_smmu_cmdq_issue_cmdlist(struct arm_smmu_device *smmu,
 	do {
 		u64 old;
 
+		/*
+		 * If the SMMU is suspended/suspending, any new CMDs are elided.
+		 * This loop is the Point of Commitment. If we haven't cmpxchg'd
+		 * our new indices yet, we can safely bail. Once the indices are
+		 * committed, we MUST write valid commands to those slots to
+		 * avoid indefinite polling in the drain function.
+		 */
+		if (Q_STOP(llq.prod)) {
+			local_irq_restore(flags);
+			return 0;
+		}

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c int __arm_smmu_cmdq_issue_cmdlist(struct arm_smmu_device *smmu, · line 750

Quoted 10 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +6 -0
+
 		while (!queue_has_space(&llq, n + sync)) {
 			local_irq_restore(flags);
+
+			/* Avoid waiting for space if the SMMU is suspending */
+			if (Q_STOP(READ_ONCE(cmdq->q.llq.prod)))
+				return 0;
+
 			if (arm_smmu_cmdq_poll_until_not_full(smmu, cmdq, &llq))
 				dev_err_ratelimited(smmu->dev, "CMDQ timeout\n");

It's a bit grotty to have the extra READ_ONCE() here. Why not make arm_smmu_cmdq_poll_until_not_full() return if the stop bit is set?

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h static inline unsigned int arm_smmu_cdtab_l2_idx(unsigned int ssid) · line 397

Quoted 9 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h +1 -0
index deefb17e31eb..794b258550dd 100644
@@ -394,6 +394,11 @@ static inline unsigned int arm_smmu_cdtab_l2_idx(unsigned int ssid)
 #define CMDQ_ERR_CERROR_ATC_INV_IDX	3
 
 #define CMDQ_PROD_OWNED_FLAG		Q_OVERFLOW_FLAG
+#define CMDQ_PROD_STOP_FLAG		(1U << 30)

I'm unsure about this. Bit 30 of the cmdq prod register is RES0, so it's plausible that the architecture allocates that bit for something in future. For example, if the index field was extended, then I think that would cause problems for the driver.

Do we have to put the stop flag in the producer value, or can it just be a flag elsewhere in memory?

Will

reviewer
#48 lore raw

Re: [PATCH v11 11/16] iommu/arm-smmu-v3: Add CMDQ_PROD_STOP_FLAG to gate CMDQ submissions

Quoted 91 lines · Will Deacon
Quoted 8 lines · Pranjal Shrivastava

Introduce a new bit flag, CMDQ_PROD_STOP_FLAG (bit 30), in the command queue's producer index to safely gate command submissions during device suspension.

The flag embeds the suspend state directly into the existing global state The flag is checked in the cmpxchg loop in arm_smmu_cmdq_issue_cmdlist(), which acts as a Point of Commitment, ensuring that no indices are reserved or committed once the SMMU begins suspending.

I'm not familiar with the term "Point of Commitment". Is that something you came up with? Without a general definition, I think I'd prefer to avoid using it, especially as it sounds like something to do with the Arm memory system (where we already have architectural terms such as "Point of Coherency".

Quoted 46 lines

This prevents a situation of "abandoned batches" where indices are incremented but commands are never written, which would otherwise lead to timeout during the drain poll.

Update queue_inc_prod_n() to preserve this flag during index calculations, ensuring that any in-flight commands that successfully passed the point of commitment can proceed to completion while the flag remains set.

---
  drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c | 35 +++++++++++++++++++--
  drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h |  5 +++
  2 files changed, 38 insertions(+), 2 deletions(-)
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +13 -1
index a123810fac57..7f89e2306942 100644
@@ -218,7 +218,8 @@ static int queue_sync_prod_in(struct arm_smmu_queue *q)
  static u32 queue_inc_prod_n(struct arm_smmu_ll_queue *q, int n)
  {
  	u32 prod = Q_POS(q, q->prod) + n;
-	return Q_OVF(q->prod) | Q_POS(q, prod);
+
+	return Q_OVF(q->prod) | Q_STOP(q->prod) | Q_POS(q, prod);
  }
 
  static void queue_poll_init(struct arm_smmu_device *smmu,
@@ -726,13 +727,42 @@ int __arm_smmu_cmdq_issue_cmdlist(struct arm_smmu_device *smmu,
  	do {
  		u64 old;
 
+		/*
+		 * If the SMMU is suspended/suspending, any new CMDs are elided.
+		 * This loop is the Point of Commitment. If we haven't cmpxchg'd
+		 * our new indices yet, we can safely bail. Once the indices are
+		 * committed, we MUST write valid commands to those slots to
+		 * avoid indefinite polling in the drain function.
+		 */
+		if (Q_STOP(llq.prod)) {
+			local_irq_restore(flags);
+			return 0;
+		}

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c int __arm_smmu_cmdq_issue_cmdlist(struct arm_smmu_device *smmu, · line 750

Quoted 10 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +6 -0
+
  		while (!queue_has_space(&llq, n + sync)) {
  			local_irq_restore(flags);
+
+			/* Avoid waiting for space if the SMMU is suspending */
+			if (Q_STOP(READ_ONCE(cmdq->q.llq.prod)))
+				return 0;
+
  			if (arm_smmu_cmdq_poll_until_not_full(smmu, cmdq, &llq))
  				dev_err_ratelimited(smmu->dev, "CMDQ timeout\n");

It's a bit grotty to have the extra READ_ONCE() here. Why not make arm_smmu_cmdq_poll_until_not_full() return if the stop bit is set?

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h static inline unsigned int arm_smmu_cdtab_l2_idx(unsigned int ssid) · line 397

Quoted 9 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h +1 -0
index deefb17e31eb..794b258550dd 100644
@@ -394,6 +394,11 @@ static inline unsigned int arm_smmu_cdtab_l2_idx(unsigned int ssid)
  #define CMDQ_ERR_CERROR_ATC_INV_IDX	3
 
  #define CMDQ_PROD_OWNED_FLAG		Q_OVERFLOW_FLAG
+#define CMDQ_PROD_STOP_FLAG		(1U << 30)

I'm unsure about this. Bit 30 of the cmdq prod register is RES0, so it's plausible that the architecture allocates that bit for something in future. For example, if the index field was extended, then I think that would cause problems for the driver.

Quoted 2 lines

Do we have to put the stop flag in the producer value, or can it just be a flag elsewhere in memory?

Logically, it feels like this should happen earlier in the process anyway - if we're entering a state where we don't want to accept _any_ new command submissions, then surely arm_smmu_get_cmdq() should just start saying "No, there is no valid queue to submit this command." to everything?

Thanks,
Robin.

#49 lore raw

Re: [PATCH v11 11/16] iommu/arm-smmu-v3: Add CMDQ_PROD_STOP_FLAG to gate CMDQ submissions

Quoted 88 lines · Robin Murphy
Quoted 87 lines · Will Deacon
Quoted 8 lines · Pranjal Shrivastava

Introduce a new bit flag, CMDQ_PROD_STOP_FLAG (bit 30), in the command queue's producer index to safely gate command submissions during device suspension.

The flag embeds the suspend state directly into the existing global state The flag is checked in the cmpxchg loop in arm_smmu_cmdq_issue_cmdlist(), which acts as a Point of Commitment, ensuring that no indices are reserved or committed once the SMMU begins suspending.

I'm not familiar with the term "Point of Commitment". Is that something you came up with? Without a general definition, I think I'd prefer to avoid using it, especially as it sounds like something to do with the Arm memory system (where we already have architectural terms such as "Point of Coherency".

Quoted 44 lines

This prevents a situation of "abandoned batches" where indices are incremented but commands are never written, which would otherwise lead to timeout during the drain poll.

Update queue_inc_prod_n() to preserve this flag during index calculations, ensuring that any in-flight commands that successfully passed the point of commitment can proceed to completion while the flag remains set.

---
  drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c | 35 +++++++++++++++++++--
  drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h |  5 +++
  2 files changed, 38 insertions(+), 2 deletions(-)
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +13 -1
index a123810fac57..7f89e2306942 100644
@@ -218,7 +218,8 @@ static int queue_sync_prod_in(struct arm_smmu_queue *q)
  static u32 queue_inc_prod_n(struct arm_smmu_ll_queue *q, int n)
  {
  	u32 prod = Q_POS(q, q->prod) + n;
-	return Q_OVF(q->prod) | Q_POS(q, prod);
+
+	return Q_OVF(q->prod) | Q_STOP(q->prod) | Q_POS(q, prod);
  }
  static void queue_poll_init(struct arm_smmu_device *smmu,
@@ -726,13 +727,42 @@ int __arm_smmu_cmdq_issue_cmdlist(struct arm_smmu_device *smmu,
  	do {
  		u64 old;
+		/*
+		 * If the SMMU is suspended/suspending, any new CMDs are elided.
+		 * This loop is the Point of Commitment. If we haven't cmpxchg'd
+		 * our new indices yet, we can safely bail. Once the indices are
+		 * committed, we MUST write valid commands to those slots to
+		 * avoid indefinite polling in the drain function.
+		 */
+		if (Q_STOP(llq.prod)) {
+			local_irq_restore(flags);
+			return 0;
+		}

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c int __arm_smmu_cmdq_issue_cmdlist(struct arm_smmu_device *smmu, · line 749

Quoted 10 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +6 -0
+
  		while (!queue_has_space(&llq, n + sync)) {
  			local_irq_restore(flags);
+
+			/* Avoid waiting for space if the SMMU is suspending */
+			if (Q_STOP(READ_ONCE(cmdq->q.llq.prod)))
+				return 0;
+
  			if (arm_smmu_cmdq_poll_until_not_full(smmu, cmdq, &llq))
  				dev_err_ratelimited(smmu->dev, "CMDQ timeout\n");

It's a bit grotty to have the extra READ_ONCE() here. Why not make arm_smmu_cmdq_poll_until_not_full() return if the stop bit is set?

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h static inline unsigned int arm_smmu_cdtab_l2_idx(unsigned int ssid) · line 396

Quoted 8 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h +1 -0
index deefb17e31eb..794b258550dd 100644
@@ -394,6 +394,11 @@ static inline unsigned int arm_smmu_cdtab_l2_idx(unsigned int ssid)
  #define CMDQ_ERR_CERROR_ATC_INV_IDX	3
  #define CMDQ_PROD_OWNED_FLAG		Q_OVERFLOW_FLAG
+#define CMDQ_PROD_STOP_FLAG		(1U << 30)

I'm unsure about this. Bit 30 of the cmdq prod register is RES0, so it's plausible that the architecture allocates that bit for something in future. For example, if the index field was extended, then I think that would cause problems for the driver.

Quoted 8 lines
Quoted 2 lines

Do we have to put the stop flag in the producer value, or can it just be a flag elsewhere in memory?

Logically, it feels like this should happen earlier in the process anyway - if we're entering a state where we don't want to accept _any_ new command submissions, then surely arm_smmu_get_cmdq() should just start saying "No, there is no valid queue to submit this command." to everything?

We can do that as well, but it can only be an early-out.. the STOP_FLAG may not be set when arm_smmu_get_cmdq() looks at it, but get set right after, before we reserve our slots in arm_smmu_cmdq_issue_cmdlist(). So we'd still need the check at the point where we actually commit, i.e. the cmpxchg on llq.prod.

Thanks,
Praan

#50 lore raw

Re: [PATCH v11 11/16] iommu/arm-smmu-v3: Add CMDQ_PROD_STOP_FLAG to gate CMDQ submissions

In reply to Will Deacon
Quoted 67 lines · Will Deacon
Quoted 8 lines · Pranjal Shrivastava

Introduce a new bit flag, CMDQ_PROD_STOP_FLAG (bit 30), in the command queue's producer index to safely gate command submissions during device suspension.

The flag embeds the suspend state directly into the existing global state The flag is checked in the cmpxchg loop in arm_smmu_cmdq_issue_cmdlist(), which acts as a Point of Commitment, ensuring that no indices are reserved or committed once the SMMU begins suspending.

I'm not familiar with the term "Point of Commitment". Is that something you came up with? Without a general definition, I think I'd prefer to avoid using it, especially as it sounds like something to do with the Arm memory system (where we already have architectural terms such as "Point of Coherency".

Quoted 51 lines

This prevents a situation of "abandoned batches" where indices are incremented but commands are never written, which would otherwise lead to timeout during the drain poll.

Update queue_inc_prod_n() to preserve this flag during index calculations, ensuring that any in-flight commands that successfully passed the point of commitment can proceed to completion while the flag remains set.

---
 drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c | 35 +++++++++++++++++++--
 drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h |  5 +++
 2 files changed, 38 insertions(+), 2 deletions(-)
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +16 -1
index a123810fac57..7f89e2306942 100644
@@ -218,7 +218,8 @@ static int queue_sync_prod_in(struct arm_smmu_queue *q)
 static u32 queue_inc_prod_n(struct arm_smmu_ll_queue *q, int n)
 {
 	u32 prod = Q_POS(q, q->prod) + n;
-	return Q_OVF(q->prod) | Q_POS(q, prod);
+
+	return Q_OVF(q->prod) | Q_STOP(q->prod) | Q_POS(q, prod);
 }
 
 static void queue_poll_init(struct arm_smmu_device *smmu,
@@ -726,13 +727,42 @@ int __arm_smmu_cmdq_issue_cmdlist(struct arm_smmu_device *smmu,
 	do {
 		u64 old;
 
+		/*
+		 * If the SMMU is suspended/suspending, any new CMDs are elided.
+		 * This loop is the Point of Commitment. If we haven't cmpxchg'd
+		 * our new indices yet, we can safely bail. Once the indices are
+		 * committed, we MUST write valid commands to those slots to
+		 * avoid indefinite polling in the drain function.
+		 */
+		if (Q_STOP(llq.prod)) {
+			local_irq_restore(flags);
+			return 0;
+		}
+
 		while (!queue_has_space(&llq, n + sync)) {
 			local_irq_restore(flags);
+
+			/* Avoid waiting for space if the SMMU is suspending */
Quoted 9 lines

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c int __arm_smmu_cmdq_issue_cmdlist(struct arm_smmu_device *smmu, · line 750

Quoted 5 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +3 -0
+			if (Q_STOP(READ_ONCE(cmdq->q.llq.prod)))
+				return 0;
+
 			if (arm_smmu_cmdq_poll_until_not_full(smmu, cmdq, &llq))
 				dev_err_ratelimited(smmu->dev, "CMDQ timeout\n");

It's a bit grotty to have the extra READ_ONCE() here. Why not make arm_smmu_cmdq_poll_until_not_full() return if the stop bit is set?

Sure, it already refreshes llq on every iteration, so I'll make it bail out on Q_STOP(llq->prod) and have the caller loop on !Q_STOP(llq.prod) && !queue_has_space(), leaving a single STOP check right before the cmpxchg.

Quoted 15 lines

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h static inline unsigned int arm_smmu_cdtab_l2_idx(unsigned int ssid) · line 397

Quoted 9 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h +1 -0
index deefb17e31eb..794b258550dd 100644
@@ -394,6 +394,11 @@ static inline unsigned int arm_smmu_cdtab_l2_idx(unsigned int ssid)
 #define CMDQ_ERR_CERROR_ATC_INV_IDX	3
 
 #define CMDQ_PROD_OWNED_FLAG		Q_OVERFLOW_FLAG
+#define CMDQ_PROD_STOP_FLAG		(1U << 30)

I'm unsure about this. Bit 30 of the cmdq prod register is RES0, so it's plausible that the architecture allocates that bit for something in future. For example, if the index field was extended, then I think that would cause problems for the driver.

Quoted 3 lines

Do we have to put the stop flag in the producer value, or can it just be a flag elsewhere in memory?

Fair point, but the flag is SW-only, i.e. it's always stripped via CMDQ_PROD_IDX_MASK before anything reaches the HW and only ever tested via Q_STOP(). It's the same deal as CMDQ_PROD_OWNED_FLAG, which already uses bit 31 (also RES0 in SMMU_CMDQ_PROD, IHI0070 section 6.3.27) as a SW-only marker in llq.prod.

Keeping it in prod is what makes the check + slot reservation atomic in the cmpxchg.. with a separate flag, a CPU could check it, then suspend sets it and samples the target, and the CPU would still reserve slots beyond that target.

Thanks,
Praan

#51 lore raw

Re: [PATCH v11 11/16] iommu/arm-smmu-v3: Add CMDQ_PROD_STOP_FLAG to gate CMDQ submissions

Quoted 10 lines · Pranjal Shrivastava
Quoted 8 lines · Will Deacon
Quoted 7 lines · Pranjal Shrivastava
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h +0 -0
index deefb17e31eb..794b258550dd 100644
@@ -394,6 +394,11 @@ static inline unsigned int arm_smmu_cdtab_l2_idx(unsigned int ssid)
 #define CMDQ_ERR_CERROR_ATC_INV_IDX        3
 
Quoted 7 lines
Quoted 7 lines

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h static inline unsigned int arm_smmu_cdtab_l2_idx(unsigned int ssid) · line 397

Quoted 2 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h +1 -0
 #define CMDQ_PROD_OWNED_FLAG               Q_OVERFLOW_FLAG
+#define CMDQ_PROD_STOP_FLAG                (1U << 30)

I'm unsure about this. Bit 30 of the cmdq prod register is RES0, so it's plausible that the architecture allocates that bit for something in future. For example, if the index field was extended, then I think that would cause problems for the driver.

Let's cross that bridge when we come to it. I think that for the driver's internal llq.prod, we can deviate from the layout that the architecture defines for SMMU_CMDQ_PROD, and as Pranjal pointed out, we are already doing that. If the architecture eventually consumes the current RES0 bits, we could save them in a separate variable and only overlay them when writing to SMMU_CMDQ_PROD. If the index field is extended, we could artificially limit the index width in this driver or transition to a 64-bit type for llq.prod. Also, it appears unlikely for the index field to be extended beyond 24 bits, because SMMU_CMDQ_CONS allocates bits [30:24] for SMMU_CMDQ_CONS.ERR

Quoted 11 lines
Quoted 4 lines

Do we have to put the stop flag in the producer value, or can it just be a flag elsewhere in memory?

Fair point, but the flag is SW-only, i.e. it's always stripped via CMDQ_PROD_IDX_MASK before anything reaches the HW and only ever tested via Q_STOP(). It's the same deal as CMDQ_PROD_OWNED_FLAG, which already uses bit 31 (also RES0 in SMMU_CMDQ_PROD, IHI0070 section 6.3.27) as a SW-only marker in llq.prod.

Quoted 4 lines

Keeping it in prod is what makes the check + slot reservation atomic in the cmpxchg.. with a separate flag, a CPU could check it, then suspend sets it and samples the target, and the CPU would still reserve slots beyond that target.

I think that the suspend thread needs to ensure that potential users of the command queue either (a) observe the stop flag (or some variant of it) or (b) are accounted for such that the suspend thread can wait for them to conclude their command queue operations. For this type of synchronization, I believe we do need some variable that both the suspend thread and the command queue users access with cmpxchg or a similar operation. I guess that in some alternative design, we could use a combination of refcount_inc_not_zero in the command queue user threads and refcount_dec_if_one in the suspend thread, and I believe one of Pranjal's earlier patches used a similar method. The beauty of the current proposal is that we re-use existing synchronization primitives and don't introduce any new variables that we need to access using cmpxchg.

#52 lore raw

Re: [PATCH v11 11/16] iommu/arm-smmu-v3: Add CMDQ_PROD_STOP_FLAG to gate CMDQ submissions

In reply to Will Deacon
Quoted 10 lines · Will Deacon
Quoted 8 lines · Pranjal Shrivastava

Introduce a new bit flag, CMDQ_PROD_STOP_FLAG (bit 30), in the command queue's producer index to safely gate command submissions during device suspension.

The flag embeds the suspend state directly into the existing global state The flag is checked in the cmpxchg loop in arm_smmu_cmdq_issue_cmdlist(), which acts as a Point of Commitment, ensuring that no indices are reserved or committed once the SMMU begins suspending.

Quoted 6 lines

I'm not familiar with the term "Point of Commitment". Is that something you came up with? Without a general definition, I think I'd prefer to avoid using it, especially as it sounds like something to do with the Arm memory system (where we already have architectural terms such as "Point of Coherency".

Ack. I'll re-word this to avoid confusion.

Thanks,
Praan

#53 lore raw

Re: [PATCH v11 11/16] iommu/arm-smmu-v3: Add CMDQ_PROD_STOP_FLAG to gate CMDQ submissions

In reply to Pranjal Shrivastava
Quoted 42 lines · Pranjal Shrivastava

Introduce a new bit flag, CMDQ_PROD_STOP_FLAG (bit 30), in the command queue's producer index to safely gate command submissions during device suspension.

The flag embeds the suspend state directly into the existing global state The flag is checked in the cmpxchg loop in arm_smmu_cmdq_issue_cmdlist(), which acts as a Point of Commitment, ensuring that no indices are reserved or committed once the SMMU begins suspending.

This prevents a situation of "abandoned batches" where indices are incremented but commands are never written, which would otherwise lead to timeout during the drain poll.

Update queue_inc_prod_n() to preserve this flag during index calculations, ensuring that any in-flight commands that successfully passed the point of commitment can proceed to completion while the flag remains set.

---
  drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c | 35 +++++++++++++++++++--
  drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h |  5 +++
  2 files changed, 38 insertions(+), 2 deletions(-)
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +2 -1
index a123810fac57..7f89e2306942 100644
@@ -218,7 +218,8 @@ static int queue_sync_prod_in(struct arm_smmu_queue *q)
  static u32 queue_inc_prod_n(struct arm_smmu_ll_queue *q, int n)
  {
  	u32 prod = Q_POS(q, q->prod) + n;
-	return Q_OVF(q->prod) | Q_POS(q, prod);
+
+	return Q_OVF(q->prod) | Q_STOP(q->prod) | Q_POS(q, prod);
  }
 
  static void queue_poll_init(struct arm_smmu_device *smmu,
@@ -726,13 +727,42 @@ int __arm_smmu_cmdq_issue_cmdlist(struct arm_smmu_device *smmu,
  	do {

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c int __arm_smmu_cmdq_issue_cmdlist(struct arm_smmu_device *smmu, · line 737

Quoted 10 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +8 -0
  		u64 old;
 
+		/*
+		 * If the SMMU is suspended/suspending, any new CMDs are elided.
+		 * This loop is the Point of Commitment. If we haven't cmpxchg'd
+		 * our new indices yet, we can safely bail. Once the indices are
+		 * committed, we MUST write valid commands to those slots to
+		 * avoid indefinite polling in the drain function.
+		 */
+		if (Q_STOP(llq.prod)) {

I know that there has already been other comments on this "stop" flag and whether to use it in this way... but, if CONFIG_PM is unset, could Q_STOP() ever return true?

And it would be nice to not add extra logic in this loop. It is very timing sensitive, and adding extra checks can increase the chance that the cmpxchg fails (bad for performance).

Quoted 57 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +23 -1
+			local_irq_restore(flags);
+			return 0;
+		}
+
  		while (!queue_has_space(&llq, n + sync)) {
  			local_irq_restore(flags);
+
+			/* Avoid waiting for space if the SMMU is suspending */
+			if (Q_STOP(READ_ONCE(cmdq->q.llq.prod)))
+				return 0;
+
  			if (arm_smmu_cmdq_poll_until_not_full(smmu, cmdq, &llq))
  				dev_err_ratelimited(smmu->dev, "CMDQ timeout\n");
  			local_irq_save(flags);
  		}
 
+		/*
+		 * If we exited the polling loop because the queue finally
+		 * has space, but the STOP_FLAG was set during the poll,
+		 * we must abort immediately. If we proceed, we will
+		 * commit new commands beyond the Point of Commitment while
+		 * the SMMU is suspending.
+		 */
+		if (Q_STOP(llq.prod)) {
+			local_irq_restore(flags);
+			return 0;
+		}
+
  		head.cons = llq.cons;
  		head.prod = queue_inc_prod_n(&llq, n + sync) |
  					     CMDQ_PROD_OWNED_FLAG;
@@ -779,7 +809,8 @@ int __arm_smmu_cmdq_issue_cmdlist(struct arm_smmu_device *smmu,
  		/* b. Stop gathering work by clearing the owned flag */
  		prod = atomic_fetch_andnot_relaxed(CMDQ_PROD_OWNED_FLAG,
  						   &cmdq->q.llq.atomic.prod);
-		prod &= ~CMDQ_PROD_OWNED_FLAG;
+		/* Strip all metadata flags */
+		prod &= CMDQ_PROD_IDX_MASK;
 
  		/*
  		 * c. Wait for any gathered work to be written to the queue.
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h +5 -0
index deefb17e31eb..794b258550dd 100644
@@ -394,6 +394,11 @@ static inline unsigned int arm_smmu_cdtab_l2_idx(unsigned int ssid)
  #define CMDQ_ERR_CERROR_ATC_INV_IDX	3
 
  #define CMDQ_PROD_OWNED_FLAG		Q_OVERFLOW_FLAG
+#define CMDQ_PROD_STOP_FLAG		(1U << 30)
+#define Q_STOP(p)			((p) & CMDQ_PROD_STOP_FLAG)
+
+/* Mask out software-only metadata flags to get the pure queue index/wrap bits */
+#define CMDQ_PROD_IDX_MASK		~(CMDQ_PROD_STOP_FLAG | CMDQ_PROD_OWNED_FLAG)
 
  struct arm_smmu_cmd {
  	u64 data[CMDQ_ENT_DWORDS];
#54 lore raw

PATCH v11 12/16 iommu/tegra241-cmdqv: Add a helper to quiesce VCMDQs

In reply to Pranjal Shrivastava

The tegra241-cmdqv driver supports vCMDQs which need to be quiesced using the STOP_FLAG. The current driver implementation only uses VINTF0 for vCMDQs owned by the kernel which need to be stopped. Add a helper that sets the CMDQ_PROD_STOP_FLAG on these vCMDQs.

Consolidate this logic by renaming the implementation hook to quiesce_and_drain_queues and ensuring that the tegra241-cmdqv driver gates all active local virtual queues before starting the drain loop. Additionally, clear the STOP_FLAG in tegra241_vcmdq_hw_init() as a part of tegra241_cmdqv_hw_reset().

---
 drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c   |  4 +-
 drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h   |  2 +-
 .../iommu/arm/arm-smmu-v3/tegra241-cmdqv.c    | 77 ++++++++++++++++++-
 3 files changed, 76 insertions(+), 7 deletions(-)
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +2 -2
index 7f89e2306942..89a4e756ff17 100644
@@ -1077,8 +1077,8 @@ static int __maybe_unused arm_smmu_drain_cmdqs(struct arm_smmu_device *smmu)
 	ret = arm_smmu_drain_queue(smmu, &smmu->cmdq.q, true);
 
 	/* Drain all implementation-specific queues */
-	if (smmu->impl_ops && smmu->impl_ops->drain_queues) {
-		err = smmu->impl_ops->drain_queues(smmu);
+	if (smmu->impl_ops && smmu->impl_ops->quiesce_and_drain_queues) {
+		err = smmu->impl_ops->quiesce_and_drain_queues(smmu);
 		if (err)
 			ret = err;
 	}
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h +1 -1
index 794b258550dd..0a841441cc44 100644
@@ -896,7 +896,7 @@ struct arm_smmu_impl_ops {
 	size_t (*get_viommu_size)(enum iommu_viommu_type viommu_type);
 	int (*vsmmu_init)(struct arm_vsmmu *vsmmu,
 			  const struct iommu_user_data *user_data);
-	int (*drain_queues)(struct arm_smmu_device *smmu);
+	int (*quiesce_and_drain_queues)(struct arm_smmu_device *smmu);
 };
 
 /* An SMMUv3 instance */
drivers/iommu/arm/arm-smmu-v3/tegra241-cmdqv.c +73 -4

125 lines not on this page · raw message

Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#55 lore raw

Re: [PATCH v11 12/16] iommu/tegra241-cmdqv: Add a helper to quiesce VCMDQs

Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 5 lines

The tegra241-cmdqv driver supports vCMDQs which need to be quiesced using the STOP_FLAG. The current driver implementation only uses VINTF0 for vCMDQs owned by the kernel which need to be stopped. Add a helper that sets the CMDQ_PROD_STOP_FLAG on these vCMDQs.

Quoted 8 lines

Consolidate this logic by renaming the implementation hook to quiesce_and_drain_queues and ensuring that the tegra241-cmdqv driver gates all active local virtual queues before starting the drain loop. Additionally, clear the STOP_FLAG in tegra241_vcmdq_hw_init() as a part of tegra241_cmdqv_hw_reset().

Sashiko has reviewed this patch and found no issues. It looks great!

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=12
#56 lore raw

Re: [PATCH v11 12/16] iommu/tegra241-cmdqv: Add a helper to quiesce VCMDQs

In reply to Pranjal Shrivastava
Quoted 10 lines · Pranjal Shrivastava

The tegra241-cmdqv driver supports vCMDQs which need to be quiesced using the STOP_FLAG. The current driver implementation only uses VINTF0 for vCMDQs owned by the kernel which need to be stopped. Add a helper that sets the CMDQ_PROD_STOP_FLAG on these vCMDQs.

Consolidate this logic by renaming the implementation hook to quiesce_and_drain_queues and ensuring that the tegra241-cmdqv driver gates all active local virtual queues before starting the drain loop. Additionally, clear the STOP_FLAG in tegra241_vcmdq_hw_init() as a part of tegra241_cmdqv_hw_reset().

This whole suspend routine is missing the CMDQV flags.

vintf->enabled and vcmdq->enabled must be cleared when the system does suspend, via tegra241_vintf_hw_deinit(vintf0).

So, instead of quiesce_and_drain_queues, perhaps we need a suspend callback that:
- set stop flags to all lvcmdqs
- wait for all lvcmdqs being drained
- hw_deinit vintf0 and its lvcmdqs

drivers/iommu/arm/arm-smmu-v3/tegra241-cmdqv.c static int tegra241_vcmdq_hw_init(struct tegra241_vcmdq *vcmdq) · line 637

Quoted 8 lines
drivers/iommu/arm/arm-smmu-v3/tegra241-cmdqv.c +0 -1
@@ -566,7 +632,6 @@ static int tegra241_vcmdq_hw_init(struct tegra241_vcmdq *vcmdq)
 
 	/* Configure and enable VCMDQ */
 	writeq_relaxed(vcmdq->cmdq.q.q_base, REG_VCMDQ_PAGE1(vcmdq, BASE));
-
 	/*
 	 * HW Registers reset to 0 when power-cycled. Restore them from their
 	 * SW copies to prevent executing stale/ghost commands after resume.

Meaningless line removal.

Nicolin

#57 lore raw

Re: [PATCH v11 12/16] iommu/tegra241-cmdqv: Add a helper to quiesce VCMDQs

Quoted 14 lines · Nicolin Chen
Quoted 10 lines · Pranjal Shrivastava

The tegra241-cmdqv driver supports vCMDQs which need to be quiesced using the STOP_FLAG. The current driver implementation only uses VINTF0 for vCMDQs owned by the kernel which need to be stopped. Add a helper that sets the CMDQ_PROD_STOP_FLAG on these vCMDQs.

Consolidate this logic by renaming the implementation hook to quiesce_and_drain_queues and ensuring that the tegra241-cmdqv driver gates all active local virtual queues before starting the drain loop. Additionally, clear the STOP_FLAG in tegra241_vcmdq_hw_init() as a part of tegra241_cmdqv_hw_reset().

This whole suspend routine is missing the CMDQV flags.

Quoted 9 lines

vintf->enabled and vcmdq->enabled must be cleared when the system does suspend, via tegra241_vintf_hw_deinit(vintf0).

So, instead of quiesce_and_drain_queues, perhaps we need a suspend callback that:
- set stop flags to all lvcmdqs
- wait for all lvcmdqs being drained
- hw_deinit vintf0 and its lvcmdqs

Interesting. I had thought about that but Ashish was able to test a previous series (which def didn't de-init vintf0 & lvcmdqs in it) so I dropped that thought..

Looking at it again though, leaving the enabled flags stale is actually worse than I thought.. on resume, the CFGI_ALL / TLBI_*_ALL issued by arm_smmu_device_reset() go through get_secondary_cmdq(), which still sees vintf0 & its lvcmdqs as enabled and hands back an lvcmdq with the STOP_FLAG still set.. so those invalidations get silently elided until impl->device_reset re-inits vintf0 (after SMMUEN=1). Thanks for catching this!

I'm planning to add an impl->suspend op now.. that will cover this, and also the late breaking IRQ changes you're referring to in the other thread. Roughly:
- set STOP_FLAG on all lvcmdqs
- wait for owners & drain all lvcmdqs
- handle any pending CMDQV errors
- tegra241_vintf_hw_deinit(vintf0)

I'll call it from arm_smmu_runtime_suspend() before gating the main CMDQ, so the CMD_SYNC in tegra241_vcmdq_hw_flush_timeout() still goes through and any late cmd simply falls back to smmu->cmdq.

(Will drop the extra line removal as well).

Thanks,
Praan

#58 lore raw

Re: [PATCH v11 12/16] iommu/tegra241-cmdqv: Add a helper to quiesce VCMDQs

Quoted 11 lines · Pranjal Shrivastava

I'm planning to add an impl->suspend op now.. that will cover this, and also the late breaking IRQ changes you're referring to in the other thread. Roughly:
- set STOP_FLAG on all lvcmdqs
- wait for owners & drain all lvcmdqs
- handle any pending CMDQV errors
- tegra241_vintf_hw_deinit(vintf0)

I'll call it from arm_smmu_runtime_suspend() before gating the main CMDQ, so the CMD_SYNC in tegra241_vcmdq_hw_flush_timeout() still goes through and any late cmd simply falls back to smmu->cmdq.

That sounds good to me.

Nicolin

#59 lore raw

PATCH v11 13/16 iommu/arm-smmu-v3: Implement pm_runtime & system sleep ops

In reply to Pranjal Shrivastava

Implement pm_runtime and system sleep ops for arm-smmu-v3.

The suspend callback configures the SMMU to abort transactions, disables the main translation unit and then drains the command queue. A software gate (STOP_FLAG) quiesces submissions before power-off. Since devlinks ensure client devices are suspended before the SMMU, no client DMA can occur, making EVTQ/PRIQ IRQ synchronization during suspend unnecessary. Prod indices for EVTQ/PRIQ are synchronized via queue_sync_prod_in() to retain unread entries across power cycles.

The resume callback restores the MSI configuration and performs a full device reset via arm_smmu_device_reset to bring the SMMU back to an operational state. The MSIs are cached during the msi_write and are restored during the resume operation by using the helper. The STOP_FLAG is cleared only after the CMDQ is enabled in hardware.

Standard SET_RUNTIME_PM_OPS() and SET_SYSTEM_SLEEP_PM_OPS() macros are used to define dev_pm_ops, safely evaluating to NO_OPs when CONFIG_PM is disabled. The new RPM helpers are marked __maybe_unused to keep intermediate commits clean until invoked by respective handlers in the subsequent patches.

---
 drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c | 255 +++++++++++++++++++-
 drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h |  15 ++
 2 files changed, 265 insertions(+), 5 deletions(-)
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +250 -5
index 89a4e756ff17..e127e3be3a6b 100644
@@ -29,6 +29,7 @@
 #include <linux/platform_device.h>
 #include <linux/sort.h>
 #include <linux/string_choices.h>
+#include <linux/pm_runtime.h>
 #include <kunit/visibility.h>
 #include <uapi/linux/iommufd.h>
 
@@ -119,6 +120,45 @@ static const char * const event_class_str[] = {
 static int arm_smmu_alloc_cd_tables(struct arm_smmu_master *master);
 static bool arm_smmu_ats_supported(struct arm_smmu_master *master);
 
+/* Runtime PM helpers */
+__maybe_unused static int arm_smmu_rpm_get(struct arm_smmu_device *smmu)
+{
+	int ret;
+
+	if (!pm_runtime_enabled(smmu->dev))
+		return 0;
+
+	ret = pm_runtime_resume_and_get(smmu->dev);
+	if (ret < 0) {
+		dev_err(smmu->dev, "failed to resume device: %d\n", ret);
+		return ret;
+	}
+
+	return 0;
+}
+
+__maybe_unused static bool arm_smmu_rpm_get_if_active(struct arm_smmu_device *smmu)
+{
+	if (!pm_runtime_enabled(smmu->dev))
+		return true;
+
+	return pm_runtime_get_if_active(smmu->dev) > 0;
+}
+
+__maybe_unused static void arm_smmu_rpm_put(struct arm_smmu_device *smmu)
+{
+	int ret;
+
+	if (!pm_runtime_enabled(smmu->dev))
+		return;
+
+	ret = pm_runtime_put_autosuspend(smmu->dev);
+
+	/* -EAGAIN & -EBUSY aren't failures */
+	if (ret < 0 && ret != -EAGAIN && ret != -EBUSY)
+		dev_err(smmu->dev, "failed to suspend device: %d\n", ret);
+}
+
 static void parse_driver_options(struct arm_smmu_device *smmu)
 {
 	int i = 0;
@@ -729,10 +769,66 @@ int __arm_smmu_cmdq_issue_cmdlist(struct arm_smmu_device *smmu,
 
 		/*
 		 * If the SMMU is suspended/suspending, any new CMDs are elided.
-		 * This loop is the Point of Commitment. If we haven't cmpxchg'd
-		 * our new indices yet, we can safely bail. Once the indices are
-		 * committed, we MUST write valid commands to those slots to
-		 * avoid indefinite polling in the drain function.
+		 *
+		 * Note that eliding ATC invalidations (CMDQ_OP_ATC_INV) is safe
+		 * because client PCIe endpoints are guaranteed to be suspended
+		 * (via device links) before the SMMU is suspended. With the PCIe
+		 * links in a low-power state, no new TLPs can be transmitted.
+		 * It is strictly the responsibility of the client/endpoint driver
+		 * to quiesce DMA and ensure that the ATC state is cleared across
+		 * power state transitions.
+		 *
+		 * This loop acts as the Point of Commitment.
+		 * The CMDQ_PROD_STOP_FLAG ensures that no new commands are
+		 * committed once the SMMU begins to suspend. The synchronization
+		 * relies on the following observability invariants:
+		 *
+		 * 1. Other CPUs observe the STOP_FLAG only *after* the SMMU is
+		 *    disabled. This is enforced in arm_smmu_runtime_suspend()
+		 *    by using a fully ordered atomic_fetch_or() to set the flag,
+		 *    guaranteeing that SMMUEN=0 (with ABORT set) at the time of
+		 *    observation which ensures no in-memory structures are
+		 *    accessed by the SMMU (IHI0070 spec section 6.3.9.6).
+		 *
+		 * 2. Other CPUs observe the cleared STOP_FLAG before the SMMU
+		 *    is re-enabled. During resume, arm_smmu_device_reset()
+		 *    issues CFGI_ALL and TLBI_ALL commands *after* clearing the
+		 *    STOP_FLAG and before setting SMMUEN=1. The implicit
+		 *    dma_wmb() executed while submitting these commands ensures
+		 *    the cleared STOP_FLAG is visible to all other agents.
+		 *    Thus, any transition from a set STOP_FLAG to SMMUEN=1
+		 *    involves an invalidate-all operation prior to setting SMMUEN=1.
+		 *
+		 * Hence, if a CPU observes the STOP_FLAG, it is assured that:
+		 *  (a) Txns are blocked + No in-memory structures are accessed
+		 *  (b) If the SMMU is ever re-enabled, an invalidate-all is
+		 *      performed prior to it being enabled during reset.
+		 *
+		 * Note: The smp_mb() in arm_smmu_domain_inv_range() orders the
+		 * PTE update before the STOP_FLAG read, which ensures that if
+		 * CPU1 reads the STOP_FLAG and decides to elide the command,
+		 * the PTE update is already globally visible.
+		 *
+		 *  [CPU0]                            | [CPU1]
+		 *  arm_smmu_runtime_suspend() {      | [PTE update]
+		 *    SMMUEN = 0;                     | arm_smmu_domain_inv_range() {
+		 *    // set STOP_FLAG                |   smp_mb();
+		 *    target = atomic_fetch_or();     |   arm_smmu_cmdq_issue_cmdlist() {
+		 *    while (owner != target)         |     // read STOP_FLAG
+		 *      // wait for completion        |     Q_STOP(llq.prod);
+		 *    arm_smmu_drain_cmdqs();         |     // reserve indices
+		 *  }                                 |     cmpxchg(&cmdq->q.llq.atomic.prod);
+		 *  ...                               |     queue_write();
+		 *  arm_smmu_device_reset() {         |   }
+		 *    // clear STOP_FLAG              | }
+		 *    atomic_andnot();                |
+		 *    [Invalidate all TLB & CFG]      |
+		 *    SMMUEN = 1;                     |
+		 *  }                                 |
+		 *
+		 * If CPU1 hasn't cmpxchg'd its new indices yet, it observes the STOP_FLAG
+		 * and safely bails. Once the indices are committed, CPU1 MUST write valid
+		 * commands to those slots to avoid indefinite polling in CPU0's drain path.
 		 */
 		if (Q_STOP(llq.prod)) {
 			local_irq_restore(flags);
@@ -5068,7 +5164,8 @@ static int arm_smmu_device_reset(struct arm_smmu_device *smmu, bool resume)
 
 	/* Command queue */
 	writeq_relaxed(smmu->cmdq.q.q_base, smmu->base + ARM_SMMU_CMDQ_BASE);
-	writel_relaxed(smmu->cmdq.q.llq.prod, smmu->base + ARM_SMMU_CMDQ_PROD);
+	writel_relaxed(smmu->cmdq.q.llq.prod & CMDQ_PROD_IDX_MASK,
+		       smmu->base + ARM_SMMU_CMDQ_PROD);
 	writel_relaxed(smmu->cmdq.q.llq.cons, smmu->base + ARM_SMMU_CMDQ_CONS);
 
 	enables = CR0_CMDQEN;
@@ -5079,6 +5176,9 @@ static int arm_smmu_device_reset(struct arm_smmu_device *smmu, bool resume)
 		return ret;
 	}
 
+	/* Clear the STOP_FLAG to resume CMDQ submissions */
+	atomic_andnot(CMDQ_PROD_STOP_FLAG, &smmu->cmdq.q.llq.atomic.prod);
+
 	/* Invalidate any cached configuration */
 	arm_smmu_cmdq_issue_cmd_with_sync(smmu, arm_smmu_make_cmd_cfgi_all());
 
@@ -5830,6 +5930,150 @@ static void arm_smmu_device_shutdown(struct platform_device *pdev)
 	arm_smmu_device_disable(smmu);
 }
 
+static int __maybe_unused arm_smmu_runtime_suspend(struct device *dev)
+{
+	struct arm_smmu_device *smmu = dev_get_drvdata(dev);
+	struct arm_smmu_cmdq *cmdq = &smmu->cmdq;
+	int timeout = ARM_SMMU_SUSPEND_TIMEOUT_US;
+	u32 enables, target;
+	int ret;
+
+	/* Abort all transactions before disable to avoid spurious bypass */
+	arm_smmu_update_gbpa(smmu, GBPA_ABORT, 0);
+
+	/*
+	 * Disable the SMMU via CR0.EN and all queues except CMDQ.
+	 *
+	 * Note on EVTQ/PRIQ: Due to device links between client devices and
+	 * the SMMU, all masters are already runtime suspended and quiescent.
+	 * As client DMA is stopped, no new translation faults (EVTQ) or
+	 * Page Requests (PRIQ) can be generated, making it safe to disable
+	 * these queues without an explicit drain.
+	 */
+	enables = CR0_CMDQEN;
+	ret = arm_smmu_write_reg_sync(smmu, enables, ARM_SMMU_CR0, ARM_SMMU_CR0ACK);
+	if (ret) {
+		/* GBPA comes into effect when CR0.SMMUEN = 0, no rollback needed */
+		dev_err(smmu->dev, "failed to disable SMMU\n");
+		return ret;
+	}
+
+	/*
+	 * At this point the SMMU is completely disabled and won't access
+	 * any translation/config structures, even speculative accesses
+	 * aren't performed as per the IHI0070 spec (section 6.3.9.6).
+	 */
+
+	/*
+	 * Mark the primary CMDQ to stop and get the target index before the stop.
+	 *
+	 * Note that the primary CMDQ's STOP_FLAG acts as a proxy for the SMMU's
+	 * global power state. Because all queues are gated synchronously during
+	 * suspend, checking the primary queue's flag is sufficient.
+	 */
+	target = atomic_fetch_or(CMDQ_PROD_STOP_FLAG, &cmdq->q.llq.atomic.prod);
+	target &= CMDQ_PROD_IDX_MASK;
+
+
+	/* Wait for the last committed owner to reach the hardware */
+	while (atomic_read(&cmdq->owner_prod) != target && timeout) {
+		udelay(1);
+		timeout--;
+	}
+
+	/*
+	 * Entering suspend implies no active clients. A timeout here
+	 * indicates a fatal CMDQ lockup or hardware stall. We proceed
+	 * anyway to prioritize memory safety (avoiding stale TLBs)
+	 */
+	if (!timeout)
+		dev_err(smmu->dev, "cmdq owner wait timeout, (check runtime PM + devlinks)\n");
+
+	/* Wait for cmdq->lock == 0 to ensure last CMDQ_CONS_REG is written */
+	timeout = ARM_SMMU_SUSPEND_TIMEOUT_US;
+	while (atomic_read(&cmdq->lock) != 0 && timeout) {
+		udelay(1);
+		timeout--;
+	}
+
+	/* Timing out here implies misconfigured Runtime PM or broken devlinks */
+	if (!timeout)
+		dev_err(smmu->dev, "cmdq lock != 0, forcing suspend. Polling CPUs may fault.\n");
+
+	/* Drain the CMDQs */
+	ret = arm_smmu_drain_cmdqs(smmu);
+	if (ret)
+		dev_warn(smmu->dev, "failed to drain queues, forcing suspend\n");
+
+	/* Disable the SMMU */
+	arm_smmu_device_disable(smmu);
+
+	/* Disable IRQ generation */
+	arm_smmu_disable_irqs(smmu);
+
+	/* Wait for pending gerror handlers */
+	synchronize_irq(smmu->combined_irq ? smmu->combined_irq : smmu->gerr_irq);
+
+	/* Handle any pending gerrors before powering down */
+	arm_smmu_handle_gerror(smmu);
+
+	/* Sync prod pointer for EVTQ and PRIQ to avoid clobbering unread entries on resume */
+	if (queue_sync_prod_in(&smmu->evtq.q) == -EOVERFLOW)
+		dev_warn(smmu->dev, "EVTQ overflow detected during suspend\n");
+
+	if (smmu->features & ARM_SMMU_FEAT_PRI) {
+		if (queue_sync_prod_in(&smmu->priq.q) == -EOVERFLOW)
+			dev_warn(smmu->dev, "PRIQ overflow detected during suspend\n");
+	}
+
+	/* Avoid consuming stale commands on resume if we timed-out */
+	cmdq->q.llq.cons = cmdq->q.llq.prod & CMDQ_PROD_IDX_MASK;
+
+	dev_dbg(dev, "suspended smmu\n");
+
+	return 0;
+}
+
+static int __maybe_unused arm_smmu_runtime_resume(struct device *dev)
+{
+	struct arm_smmu_device *smmu = dev_get_drvdata(dev);
+	int ret;
+
+	/* Re-configure MSIs */
+	arm_smmu_resume_msis(smmu);
+
+	/* Clears the CMDQ_PROD_STOP_FLAG as well */
+	ret = arm_smmu_device_reset(smmu, true);
+	if (ret)
+		dev_err(dev, "failed to reset during resume operation: %d\n", ret);
+
+	dev_dbg(dev, "resumed smmu\n");
+
+	return ret;
+}
+
+static int __maybe_unused arm_smmu_pm_suspend(struct device *dev)
+{
+	if (pm_runtime_suspended(dev))
+		return 0;
+
+	return arm_smmu_runtime_suspend(dev);
+}
+
+static int __maybe_unused arm_smmu_pm_resume(struct device *dev)
+{
+	if (pm_runtime_suspended(dev))
+		return 0;
+
+	return arm_smmu_runtime_resume(dev);
+}
+
+static const struct dev_pm_ops arm_smmu_pm_ops = {
+	SET_SYSTEM_SLEEP_PM_OPS(arm_smmu_pm_suspend, arm_smmu_pm_resume)
+	SET_RUNTIME_PM_OPS(arm_smmu_runtime_suspend,
+			   arm_smmu_runtime_resume, NULL)
+};
+
 static const struct of_device_id arm_smmu_of_match[] = {
 	{ .compatible = "arm,smmu-v3", },
 	{ },
@@ -5846,6 +6090,7 @@ static struct platform_driver arm_smmu_driver = {
 	.driver	= {
 		.name			= "arm-smmu-v3",
 		.of_match_table		= arm_smmu_of_match,
+		.pm                     = &arm_smmu_pm_ops,
 		.suppress_bind_attrs	= true,
 	},
 	.probe	= arm_smmu_device_probe,
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h +15 -0
index 0a841441cc44..d0a3d497915c 100644
@@ -663,11 +663,14 @@ arm_smmu_make_cmd_tlbi(enum arm_smmu_cmdq_opcode op, u16 asid, u16 vmid)
 
 /* High-level queue structures */
 #define ARM_SMMU_POLL_TIMEOUT_US	1000000 /* 1s! */
+#define ARM_SMMU_SUSPEND_TIMEOUT_US	1000000	/* 1s! */
 #define ARM_SMMU_POLL_SPIN_COUNT	10
 
 #define MSI_IOVA_BASE			0x8000000
 #define MSI_IOVA_LENGTH			0x100000
 
+#define RPM_AUTOSUSPEND_DELAY_MS	15
+
 struct arm_smmu_ll_queue {
 	union {
 		u64			val;
@@ -1234,6 +1237,18 @@ int arm_smmu_cmdq_issue_cmdlist(struct arm_smmu_device *smmu,
 				bool sync);
 bool arm_smmu_erratum_repeat_tlbi_cfgi(void);
 
+/*
+ * Lockless pre-check to test if the SMMU is actively powered.
+ * Races with concurrent suspend are benign: the cmpxchg loop in
+ * arm_smmu_cmdq_issue_cmdlist() acts as the true commit point.
+ * If we lose the race, that loop observes Q_STOP == 1 and safely
+ * drops the command. If we win, the suspend thread waits for us.
+ */
+static inline bool arm_smmu_is_active(struct arm_smmu_device *smmu)
+{
+	return !Q_STOP(READ_ONCE(smmu->cmdq.q.llq.prod));
+}
+
 #ifdef CONFIG_ARM_SMMU_V3_SVA
 bool arm_smmu_sva_supported(struct arm_smmu_device *smmu);
 void arm_smmu_sva_notifier_synchronize(void);
Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#60 lore raw

Re: [PATCH v11 13/16] iommu/arm-smmu-v3: Implement pm_runtime & system sleep ops

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [Medium] iommu/arm-smmu-v3: invalid synchronize_irq(0) call when gerror IRQ is absent - [Low]…

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [Medium] iommu/arm-smmu-v3: invalid synchronize_irq(0) call when gerror IRQ is absent
- [Low] iommu/arm-smmu-v3: dead code via unconditional pm_ops assignment
--

commit f1b9ff2a5159bd528e9134e997eee772c624264d
Author: Pranjal Shrivastava <[email protected]>

iommu/arm-smmu-v3: Implement pm_runtime & system sleep ops

This commit implements pm_runtime and system sleep operations for the arm-smmu-v3 driver. It adds suspend and resume callbacks that coordinate command queue draining and device resets to manage power state transitions.

Quoted 4 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +0 -0
index 89a4e756ff174..e127e3be3a6ba 100644

[ ... ]

Quoted 7 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +3 -0
@@ -5830,6 +5930,150 @@ static void arm_smmu_device_shutdown(struct platform_device *pdev)
 	arm_smmu_device_disable(smmu);
 }
 
+static int __maybe_unused arm_smmu_runtime_suspend(struct device *dev)
+{
+	struct arm_smmu_device *smmu = dev_get_drvdata(dev);

[ ... ]

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c static void arm_smmu_device_shutdown(struct platform_device *pdev) · line 6015

Quoted 5 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +5 -0
+	/* Disable IRQ generation */
+	arm_smmu_disable_irqs(smmu);
+
+	/* Wait for pending gerror handlers */
+	synchronize_irq(smmu->combined_irq ? smmu->combined_irq : smmu->gerr_irq);

[Severity: Medium]
Is there a risk of calling synchronize_irq(0) here if both smmu->combined_irq and smmu->gerr_irq are 0?

If the device firmware configuration lacks a combined IRQ and a gerror IRQ, and MSI allocation fails or falls back to wired interrupts, both variables would be initialized to 0. This evaluates to synchronize_irq(0), leading to an erroneous synchronization on an unrelated system interrupt (like a timer mapped to IRQ 0). Could this statement verify that the resulting IRQ is non-zero before invoking synchronize_irq()?

Quoted 3 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +3 -0
+
+	/* Handle any pending gerrors before powering down */
+	arm_smmu_handle_gerror(smmu);

[ ... ]

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c static struct platform_driver arm_smmu_driver = { · line 6093

Quoted 5 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +1 -0
@@ -5846,6 +6090,7 @@ static struct platform_driver arm_smmu_driver = {
 	.driver	= {
 		.name			= "arm-smmu-v3",
 		.of_match_table		= arm_smmu_of_match,
+		.pm                     = &arm_smmu_pm_ops,

[Severity: Low]
Does this code leave dead functions compiled into the binary when CONFIG_PM is disabled?

Assigning the arm_smmu_pm_ops structure unconditionally instead of wrapping it in pm_ptr() prevents the compiler from discarding the unused suspend and resume functions. Should this be wrapped as pm_ptr(&arm_smmu_pm_ops) to avoid dead code bloat?

Quoted 3 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +0 -0
 		.suppress_bind_attrs	= true,
 	},
 	.probe	= arm_smmu_device_probe,
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=13
#61 lore raw

Re: [PATCH v11 13/16] iommu/arm-smmu-v3: Implement pm_runtime & system sleep ops

In reply to Pranjal Shrivastava

Just some small things from a quick scan:

Quoted 5 lines · Pranjal Shrivastava
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h +0 -0
index 0a841441cc44..d0a3d497915c 100644
@@ -663,11 +663,14 @@ arm_smmu_make_cmd_tlbi(enum arm_smmu_cmdq_opcode op, u16 asid, u16 vmid)

[...]

Quoted 10 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h +3 -0
+#define RPM_AUTOSUSPEND_DELAY_MS	15
+
 struct arm_smmu_ll_queue {
 	union {
 		u64			val;
@@ -1234,6 +1237,18 @@ int arm_smmu_cmdq_issue_cmdlist(struct arm_smmu_device *smmu,
 				bool sync);
 bool arm_smmu_erratum_repeat_tlbi_cfgi(void);
 
+/*

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h int arm_smmu_cmdq_issue_cmdlist(struct arm_smmu_device *smmu, · line 1250

Quoted 10 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h +10 -0
+ * Lockless pre-check to test if the SMMU is actively powered.
+ * Races with concurrent suspend are benign: the cmpxchg loop in
+ * arm_smmu_cmdq_issue_cmdlist() acts as the true commit point.
+ * If we lose the race, that loop observes Q_STOP == 1 and safely
+ * drops the command. If we win, the suspend thread waits for us.
+ */
+static inline bool arm_smmu_is_active(struct arm_smmu_device *smmu)
+{
+	return !Q_STOP(READ_ONCE(smmu->cmdq.q.llq.prod));
+}

Move these to the patch that uses it?

Quoted 44 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +29 -0
index 89a4e756ff17..e127e3be3a6b 100644
@@ -29,6 +29,7 @@
 #include <linux/platform_device.h>
 #include <linux/sort.h>
 #include <linux/string_choices.h>
+#include <linux/pm_runtime.h>
 #include <kunit/visibility.h>
 #include <uapi/linux/iommufd.h>
 
@@ -119,6 +120,45 @@ static const char * const event_class_str[] = {
 static int arm_smmu_alloc_cd_tables(struct arm_smmu_master *master);
 static bool arm_smmu_ats_supported(struct arm_smmu_master *master);
 
+/* Runtime PM helpers */
+__maybe_unused static int arm_smmu_rpm_get(struct arm_smmu_device *smmu)
+{
+	int ret;
+
+	if (!pm_runtime_enabled(smmu->dev))
+		return 0;
+
+	ret = pm_runtime_resume_and_get(smmu->dev);
+	if (ret < 0) {
+		dev_err(smmu->dev, "failed to resume device: %d\n", ret);
+		return ret;
+	}
+
+	return 0;
+}
+
+__maybe_unused static bool arm_smmu_rpm_get_if_active(struct arm_smmu_device *smmu)
+{
+	if (!pm_runtime_enabled(smmu->dev))
+		return true;
+
+	return pm_runtime_get_if_active(smmu->dev) > 0;
+}
+
+__maybe_unused static void arm_smmu_rpm_put(struct arm_smmu_device *smmu)
+{
+	int ret;

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c static const char * const event_class_str[] = { · line 160

Quoted 10 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +10 -0
+
+	if (!pm_runtime_enabled(smmu->dev))
+		return;
+
+	ret = pm_runtime_put_autosuspend(smmu->dev);
+
+	/* -EAGAIN & -EBUSY aren't failures */
+	if (ret < 0 && ret != -EAGAIN && ret != -EBUSY)
+		dev_err(smmu->dev, "failed to suspend device: %d\n", ret);
+}

Ditto

Quoted 1 line
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +1 -0
+static int __maybe_unused arm_smmu_runtime_suspend(struct device *dev)

[...]

Quoted 14 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +14 -0
+	/* Wait for the last committed owner to reach the hardware */
+	while (atomic_read(&cmdq->owner_prod) != target && timeout) {
+		udelay(1);
+		timeout--;
+	}
+
+	/*
+	 * Entering suspend implies no active clients. A timeout here
+	 * indicates a fatal CMDQ lockup or hardware stall. We proceed
+	 * anyway to prioritize memory safety (avoiding stale TLBs)
+	 */
+	if (!timeout)
+		dev_err(smmu->dev, "cmdq owner wait timeout, (check runtime PM + devlinks)\n");
+

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c static void arm_smmu_device_shutdown(struct platform_device *pdev) · line 6001

Quoted 10 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +10 -0
+	/* Wait for cmdq->lock == 0 to ensure last CMDQ_CONS_REG is written */
+	timeout = ARM_SMMU_SUSPEND_TIMEOUT_US;
+	while (atomic_read(&cmdq->lock) != 0 && timeout) {
+		udelay(1);
+		timeout--;
+	}
+
+	/* Timing out here implies misconfigured Runtime PM or broken devlinks */
+	if (!timeout)
+		dev_err(smmu->dev, "cmdq lock != 0, forcing suspend. Polling CPUs may fault.\n");

Maybe a small helper that takes: read pointer, target, print?

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c static void arm_smmu_device_shutdown(struct platform_device *pdev) · line 6015

Quoted 2 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +2 -0
+	/* Wait for pending gerror handlers */
+	synchronize_irq(smmu->combined_irq ? smmu->combined_irq : smmu->gerr_irq);

Both might be 0?

Nicolin

maintainer
#62 lore raw

Re: [PATCH v11 13/16] iommu/arm-smmu-v3: Implement pm_runtime & system sleep ops

In reply to Pranjal Shrivastava
Quoted 42 lines · Pranjal Shrivastava

Implement pm_runtime and system sleep ops for arm-smmu-v3.

The suspend callback configures the SMMU to abort transactions, disables the main translation unit and then drains the command queue. A software gate (STOP_FLAG) quiesces submissions before power-off. Since devlinks ensure client devices are suspended before the SMMU, no client DMA can occur, making EVTQ/PRIQ IRQ synchronization during suspend unnecessary. Prod indices for EVTQ/PRIQ are synchronized via queue_sync_prod_in() to retain unread entries across power cycles.

The resume callback restores the MSI configuration and performs a full device reset via arm_smmu_device_reset to bring the SMMU back to an operational state. The MSIs are cached during the msi_write and are restored during the resume operation by using the helper. The STOP_FLAG is cleared only after the CMDQ is enabled in hardware.

Standard SET_RUNTIME_PM_OPS() and SET_SYSTEM_SLEEP_PM_OPS() macros are used to define dev_pm_ops, safely evaluating to NO_OPs when CONFIG_PM is disabled. The new RPM helpers are marked __maybe_unused to keep intermediate commits clean until invoked by respective handlers in the subsequent patches.

---
 drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c | 255 +++++++++++++++++++-
 drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h |  15 ++
 2 files changed, 265 insertions(+), 5 deletions(-)
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +1 -0
index 89a4e756ff17..e127e3be3a6b 100644
@@ -29,6 +29,7 @@
 #include <linux/platform_device.h>
 #include <linux/sort.h>
 #include <linux/string_choices.h>
+#include <linux/pm_runtime.h>
 #include <kunit/visibility.h>
 #include <uapi/linux/iommufd.h>
 

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c static const char * const event_class_str[] = { · line 124

Quoted 5 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +2 -0
@@ -119,6 +120,45 @@ static const char * const event_class_str[] = {
 static int arm_smmu_alloc_cd_tables(struct arm_smmu_master *master);
 static bool arm_smmu_ats_supported(struct arm_smmu_master *master);
 
+/* Runtime PM helpers */
+__maybe_unused static int arm_smmu_rpm_get(struct arm_smmu_device *smmu)

Just guard all this on CONFIG_PM instead of adding __maybe_unused? That way, the server folks don't even have to build this stuff.

Quoted 122 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +99 -5
+{
+	int ret;
+
+	if (!pm_runtime_enabled(smmu->dev))
+		return 0;
+
+	ret = pm_runtime_resume_and_get(smmu->dev);
+	if (ret < 0) {
+		dev_err(smmu->dev, "failed to resume device: %d\n", ret);
+		return ret;
+	}
+
+	return 0;
+}
+
+__maybe_unused static bool arm_smmu_rpm_get_if_active(struct arm_smmu_device *smmu)
+{
+	if (!pm_runtime_enabled(smmu->dev))
+		return true;
+
+	return pm_runtime_get_if_active(smmu->dev) > 0;
+}
+
+__maybe_unused static void arm_smmu_rpm_put(struct arm_smmu_device *smmu)
+{
+	int ret;
+
+	if (!pm_runtime_enabled(smmu->dev))
+		return;
+
+	ret = pm_runtime_put_autosuspend(smmu->dev);
+
+	/* -EAGAIN & -EBUSY aren't failures */
+	if (ret < 0 && ret != -EAGAIN && ret != -EBUSY)
+		dev_err(smmu->dev, "failed to suspend device: %d\n", ret);
+}
+
 static void parse_driver_options(struct arm_smmu_device *smmu)
 {
 	int i = 0;
@@ -729,10 +769,66 @@ int __arm_smmu_cmdq_issue_cmdlist(struct arm_smmu_device *smmu,
 
 		/*
 		 * If the SMMU is suspended/suspending, any new CMDs are elided.
-		 * This loop is the Point of Commitment. If we haven't cmpxchg'd
-		 * our new indices yet, we can safely bail. Once the indices are
-		 * committed, we MUST write valid commands to those slots to
-		 * avoid indefinite polling in the drain function.
+		 *
+		 * Note that eliding ATC invalidations (CMDQ_OP_ATC_INV) is safe
+		 * because client PCIe endpoints are guaranteed to be suspended
+		 * (via device links) before the SMMU is suspended. With the PCIe
+		 * links in a low-power state, no new TLPs can be transmitted.
+		 * It is strictly the responsibility of the client/endpoint driver
+		 * to quiesce DMA and ensure that the ATC state is cleared across
+		 * power state transitions.
+		 *
+		 * This loop acts as the Point of Commitment.
+		 * The CMDQ_PROD_STOP_FLAG ensures that no new commands are
+		 * committed once the SMMU begins to suspend. The synchronization
+		 * relies on the following observability invariants:
+		 *
+		 * 1. Other CPUs observe the STOP_FLAG only *after* the SMMU is
+		 *    disabled. This is enforced in arm_smmu_runtime_suspend()
+		 *    by using a fully ordered atomic_fetch_or() to set the flag,
+		 *    guaranteeing that SMMUEN=0 (with ABORT set) at the time of
+		 *    observation which ensures no in-memory structures are
+		 *    accessed by the SMMU (IHI0070 spec section 6.3.9.6).
+		 *
+		 * 2. Other CPUs observe the cleared STOP_FLAG before the SMMU
+		 *    is re-enabled. During resume, arm_smmu_device_reset()
+		 *    issues CFGI_ALL and TLBI_ALL commands *after* clearing the
+		 *    STOP_FLAG and before setting SMMUEN=1. The implicit
+		 *    dma_wmb() executed while submitting these commands ensures
+		 *    the cleared STOP_FLAG is visible to all other agents.
+		 *    Thus, any transition from a set STOP_FLAG to SMMUEN=1
+		 *    involves an invalidate-all operation prior to setting SMMUEN=1.
+		 *
+		 * Hence, if a CPU observes the STOP_FLAG, it is assured that:
+		 *  (a) Txns are blocked + No in-memory structures are accessed
+		 *  (b) If the SMMU is ever re-enabled, an invalidate-all is
+		 *      performed prior to it being enabled during reset.
+		 *
+		 * Note: The smp_mb() in arm_smmu_domain_inv_range() orders the
+		 * PTE update before the STOP_FLAG read, which ensures that if
+		 * CPU1 reads the STOP_FLAG and decides to elide the command,
+		 * the PTE update is already globally visible.
+		 *
+		 *  [CPU0]                            | [CPU1]
+		 *  arm_smmu_runtime_suspend() {      | [PTE update]
+		 *    SMMUEN = 0;                     | arm_smmu_domain_inv_range() {
+		 *    // set STOP_FLAG                |   smp_mb();
+		 *    target = atomic_fetch_or();     |   arm_smmu_cmdq_issue_cmdlist() {
+		 *    while (owner != target)         |     // read STOP_FLAG
+		 *      // wait for completion        |     Q_STOP(llq.prod);
+		 *    arm_smmu_drain_cmdqs();         |     // reserve indices
+		 *  }                                 |     cmpxchg(&cmdq->q.llq.atomic.prod);
+		 *  ...                               |     queue_write();
+		 *  arm_smmu_device_reset() {         |   }
+		 *    // clear STOP_FLAG              | }
+		 *    atomic_andnot();                |
+		 *    [Invalidate all TLB & CFG]      |
+		 *    SMMUEN = 1;                     |
+		 *  }                                 |
+		 *
+		 * If CPU1 hasn't cmpxchg'd its new indices yet, it observes the STOP_FLAG
+		 * and safely bails. Once the indices are committed, CPU1 MUST write valid
+		 * commands to those slots to avoid indefinite polling in CPU0's drain path.
 		 */
 		if (Q_STOP(llq.prod)) {
 			local_irq_restore(flags);
@@ -5068,7 +5164,8 @@ static int arm_smmu_device_reset(struct arm_smmu_device *smmu, bool resume)
 
 	/* Command queue */
 	writeq_relaxed(smmu->cmdq.q.q_base, smmu->base + ARM_SMMU_CMDQ_BASE);
-	writel_relaxed(smmu->cmdq.q.llq.prod, smmu->base + ARM_SMMU_CMDQ_PROD);
+	writel_relaxed(smmu->cmdq.q.llq.prod & CMDQ_PROD_IDX_MASK,
+		       smmu->base + ARM_SMMU_CMDQ_PROD);
 	writel_relaxed(smmu->cmdq.q.llq.cons, smmu->base + ARM_SMMU_CMDQ_CONS);
 
 	enables = CR0_CMDQEN;

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c static int arm_smmu_device_reset(struct arm_smmu_device *smmu, bool resume) · line 5180

Quoted 5 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +2 -0
@@ -5079,6 +5176,9 @@ static int arm_smmu_device_reset(struct arm_smmu_device *smmu, bool resume)
 		return ret;
 	}
 
+	/* Clear the STOP_FLAG to resume CMDQ submissions */
+	atomic_andnot(CMDQ_PROD_STOP_FLAG, &smmu->cmdq.q.llq.atomic.prod);

Presumably this needs to be ordered after the prior MMIO accesses? I think we're probably missing some barriers with the code as you have it here.

Quoted 39 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +32 -0
+
 	/* Invalidate any cached configuration */
 	arm_smmu_cmdq_issue_cmd_with_sync(smmu, arm_smmu_make_cmd_cfgi_all());
 
@@ -5830,6 +5930,150 @@ static void arm_smmu_device_shutdown(struct platform_device *pdev)
 	arm_smmu_device_disable(smmu);
 }
 
+static int __maybe_unused arm_smmu_runtime_suspend(struct device *dev)
+{
+	struct arm_smmu_device *smmu = dev_get_drvdata(dev);
+	struct arm_smmu_cmdq *cmdq = &smmu->cmdq;
+	int timeout = ARM_SMMU_SUSPEND_TIMEOUT_US;
+	u32 enables, target;
+	int ret;
+
+	/* Abort all transactions before disable to avoid spurious bypass */
+	arm_smmu_update_gbpa(smmu, GBPA_ABORT, 0);
+
+	/*
+	 * Disable the SMMU via CR0.EN and all queues except CMDQ.
+	 *
+	 * Note on EVTQ/PRIQ: Due to device links between client devices and
+	 * the SMMU, all masters are already runtime suspended and quiescent.
+	 * As client DMA is stopped, no new translation faults (EVTQ) or
+	 * Page Requests (PRIQ) can be generated, making it safe to disable
+	 * these queues without an explicit drain.
+	 */
+	enables = CR0_CMDQEN;
+	ret = arm_smmu_write_reg_sync(smmu, enables, ARM_SMMU_CR0, ARM_SMMU_CR0ACK);
+	if (ret) {
+		/* GBPA comes into effect when CR0.SMMUEN = 0, no rollback needed */
+		dev_err(smmu->dev, "failed to disable SMMU\n");
+		return ret;
+	}
+
+	/*
+	 * At this point the SMMU is completely disabled and won't access
+	 * any translation/config structures, even speculative accesses

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c static void arm_smmu_device_shutdown(struct platform_device *pdev) · line 5973

Quoted 10 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +10 -0
+	 * aren't performed as per the IHI0070 spec (section 6.3.9.6).
+	 */
+
+	/*
+	 * Mark the primary CMDQ to stop and get the target index before the stop.
+	 *
+	 * Note that the primary CMDQ's STOP_FLAG acts as a proxy for the SMMU's
+	 * global power state. Because all queues are gated synchronously during
+	 * suspend, checking the primary queue's flag is sufficient.
+	 */

Strictly speaking, I think you need an mb() here.

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c static void arm_smmu_device_shutdown(struct platform_device *pdev) · line 5974

Quoted 1 line
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +1 -0
+	target = atomic_fetch_or(CMDQ_PROD_STOP_FLAG, &cmdq->q.llq.atomic.prod);

Then this could be atomic_fetch_or_relaxed()...

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c static void arm_smmu_device_shutdown(struct platform_device *pdev) · line 5976

Quoted 2 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +2 -0
+	target &= CMDQ_PROD_IDX_MASK;
+

... and you can use smp_mb__after_atomic() here so that we don't read owner_prod early.

Quoted 7 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +7 -0
+	/* Wait for the last committed owner to reach the hardware */
+	while (atomic_read(&cmdq->owner_prod) != target && timeout) {
+		udelay(1);
+		timeout--;
+	}
+
+	/*

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c static void arm_smmu_device_shutdown(struct platform_device *pdev) · line 5994

Quoted 10 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +10 -0
+	 * Entering suspend implies no active clients. A timeout here
+	 * indicates a fatal CMDQ lockup or hardware stall. We proceed
+	 * anyway to prioritize memory safety (avoiding stale TLBs)
+	 */
+	if (!timeout)
+		dev_err(smmu->dev, "cmdq owner wait timeout, (check runtime PM + devlinks)\n");
+
+	/* Wait for cmdq->lock == 0 to ensure last CMDQ_CONS_REG is written */
+	timeout = ARM_SMMU_SUSPEND_TIMEOUT_US;
+	while (atomic_read(&cmdq->lock) != 0 && timeout) {

This probably needs to be ordered after the read of owner_prod, so I would add an smp_rmb() before the loop.

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c static void arm_smmu_device_shutdown(struct platform_device *pdev) · line 6003

Quoted 9 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +9 -0
+		udelay(1);
+		timeout--;
+	}
+
+	/* Timing out here implies misconfigured Runtime PM or broken devlinks */
+	if (!timeout)
+		dev_err(smmu->dev, "cmdq lock != 0, forcing suspend. Polling CPUs may fault.\n");
+
+	/* Drain the CMDQs */

Probably need another mb() here so that we don't start looking at the hardware registers until we know that the producer threads have gone away?

Quoted 17 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +17 -0
+	ret = arm_smmu_drain_cmdqs(smmu);
+	if (ret)
+		dev_warn(smmu->dev, "failed to drain queues, forcing suspend\n");
+
+	/* Disable the SMMU */
+	arm_smmu_device_disable(smmu);
+
+	/* Disable IRQ generation */
+	arm_smmu_disable_irqs(smmu);
+
+	/* Wait for pending gerror handlers */
+	synchronize_irq(smmu->combined_irq ? smmu->combined_irq : smmu->gerr_irq);
+
+	/* Handle any pending gerrors before powering down */
+	arm_smmu_handle_gerror(smmu);
+
+	/* Sync prod pointer for EVTQ and PRIQ to avoid clobbering unread entries on resume */

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c static void arm_smmu_device_shutdown(struct platform_device *pdev) · line 6030

Quoted 10 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +10 -0
+	if (queue_sync_prod_in(&smmu->evtq.q) == -EOVERFLOW)
+		dev_warn(smmu->dev, "EVTQ overflow detected during suspend\n");
+
+	if (smmu->features & ARM_SMMU_FEAT_PRI) {
+		if (queue_sync_prod_in(&smmu->priq.q) == -EOVERFLOW)
+			dev_warn(smmu->dev, "PRIQ overflow detected during suspend\n");
+	}
+
+	/* Avoid consuming stale commands on resume if we timed-out */
+	cmdq->q.llq.cons = cmdq->q.llq.prod & CMDQ_PROD_IDX_MASK;

What is the problem with consuming stale commands in this case?

Quoted 24 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h +4 -0
index 0a841441cc44..d0a3d497915c 100644
@@ -663,11 +663,14 @@ arm_smmu_make_cmd_tlbi(enum arm_smmu_cmdq_opcode op, u16 asid, u16 vmid)
 
 /* High-level queue structures */
 #define ARM_SMMU_POLL_TIMEOUT_US	1000000 /* 1s! */
+#define ARM_SMMU_SUSPEND_TIMEOUT_US	1000000	/* 1s! */
 #define ARM_SMMU_POLL_SPIN_COUNT	10
 
 #define MSI_IOVA_BASE			0x8000000
 #define MSI_IOVA_LENGTH			0x100000
 
+#define RPM_AUTOSUSPEND_DELAY_MS	15
+
 struct arm_smmu_ll_queue {
 	union {
 		u64			val;
@@ -1234,6 +1237,18 @@ int arm_smmu_cmdq_issue_cmdlist(struct arm_smmu_device *smmu,
 				bool sync);
 bool arm_smmu_erratum_repeat_tlbi_cfgi(void);
 
+/*

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h int arm_smmu_cmdq_issue_cmdlist(struct arm_smmu_device *smmu, · line 1250

Quoted 10 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h +10 -0
+ * Lockless pre-check to test if the SMMU is actively powered.
+ * Races with concurrent suspend are benign: the cmpxchg loop in
+ * arm_smmu_cmdq_issue_cmdlist() acts as the true commit point.
+ * If we lose the race, that loop observes Q_STOP == 1 and safely
+ * drops the command. If we win, the suspend thread waits for us.
+ */
+static inline bool arm_smmu_is_active(struct arm_smmu_device *smmu)
+{
+	return !Q_STOP(READ_ONCE(smmu->cmdq.q.llq.prod));
+}

Why does this need to be in the header?

Will

#63 lore raw

PATCH v11 14/16 iommu/arm-smmu-v3: Enable pm_runtime and setup devlinks

In reply to Pranjal Shrivastava

Enable PM runtime for SMMUs having a power-domain during smmu probe. Add a devlink between the clients and SMMU device. The absence of a power domain effectively disables runtime power management.

Additionally, handle runtime PM teardown in arm_smmu_disable_action() and skip MMIO accesses during teardown and shutdown if the SMMU is already runtime suspended, as translation is already disabled and the hardware is in a low-power state.

---
 drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c | 49 +++++++++++++++++++--
 1 file changed, 46 insertions(+), 3 deletions(-)
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +46 -3
index e127e3be3a6b..2a1b5ce6ff1c 100644
@@ -4511,8 +4511,28 @@ static struct iommu_device *arm_smmu_probe_device(struct device *dev)
 	if (ret)
 		goto err_disable_pasid;
 
+	/*
+	 * If linking fails on an RPM-enabled SMMU, abort probe to prevent
+	 * DMA transactions while the SMMU is autosuspended. Otherwise, warn
+	 * and continue since the SMMU is always powered.
+	 */
+	if (!device_link_add(dev, smmu->dev,
+			     DL_FLAG_PM_RUNTIME | DL_FLAG_AUTOREMOVE_SUPPLIER)) {
+		if (pm_runtime_enabled(smmu->dev)) {
+			dev_err(smmu->dev, "failed to add devlink to %s\n",
+				dev_name(dev));
+			ret = -ENOMEM;
+			goto err_free_cd_tables;
+		}
+
+		dev_warn(smmu->dev, "failed to add devlink to %s\n", dev_name(dev));
+	}
+
 	return &smmu->iommu;
 
+err_free_cd_tables:
+	if (arm_smmu_cdtab_allocated(&master->cd_table))
+		arm_smmu_free_cd_tables(master);
 err_disable_pasid:
 	arm_smmu_disable_pasid(master);
 	arm_smmu_remove_master(master);
@@ -5097,9 +5117,17 @@ static void arm_smmu_disable_action(void *data)
 {
 	struct arm_smmu_device *smmu = data;
 
-	if (smmu->impl_ops && smmu->impl_ops->device_disable)
-		smmu->impl_ops->device_disable(smmu);
-	arm_smmu_device_disable(smmu);
+	/* If the SMMU is already suspended, nothing to do */
+	if (!pm_runtime_suspended(smmu->dev)) {
+		if (smmu->impl_ops && smmu->impl_ops->device_disable)
+			smmu->impl_ops->device_disable(smmu);
+		arm_smmu_device_disable(smmu);
+	}
+
+	if (pm_runtime_enabled(smmu->dev)) {
+		pm_runtime_dont_use_autosuspend(smmu->dev);
+		pm_runtime_disable(smmu->dev);
+	}
 }
 
 static void arm_smmu_write_strtab(struct arm_smmu_device *smmu)
@@ -5912,6 +5940,17 @@ static int arm_smmu_device_probe(struct platform_device *pdev)
 		return ret;
 	}
 
+	/*
+	 * Safe to enable RPM here as client devices cannot be probed
+	 * before this probe function successfully returns.
+	 */
+	if (dev->pm_domain) {
+		pm_runtime_set_active(dev);
+		pm_runtime_use_autosuspend(dev);
+		pm_runtime_set_autosuspend_delay(dev, RPM_AUTOSUSPEND_DELAY_MS);
+		pm_runtime_enable(dev);
+	}
+
 	return 0;
 }
 
@@ -5927,6 +5966,10 @@ static void arm_smmu_device_shutdown(struct platform_device *pdev)
 {
 	struct arm_smmu_device *smmu = platform_get_drvdata(pdev);
 
+	/* If the SMMU is already suspended, nothing to do */
+	if (pm_runtime_suspended(&pdev->dev))
+		return;
+
 	arm_smmu_device_disable(smmu);
 }
 
Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#64 lore raw

Re: [PATCH v11 14/16] iommu/arm-smmu-v3: Enable pm_runtime and setup devlinks

Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 4 lines

Enable PM runtime for SMMUs having a power-domain during smmu probe. Add a devlink between the clients and SMMU device. The absence of a power domain effectively disables runtime power management.

Quoted 8 lines

Additionally, handle runtime PM teardown in arm_smmu_disable_action() and skip MMIO accesses during teardown and shutdown if the SMMU is already runtime suspended, as translation is already disabled and the hardware is in a low-power state.

Sashiko has reviewed this patch and found no issues. It looks great!

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=14
#65 lore raw

PATCH v11 15/16 iommu/arm-smmu-v3: Invoke pm_runtime before hw access

In reply to Pranjal Shrivastava

Invoke the pm_runtime helpers at all places before accessing the hw. The idea is to invoke runtime_pm helpers at common points which are used by exposed ops or interrupt handlers. TLB and CFG invalidations are elided if the SMMU is suspended by observing the CMDQ_PROD_STOP_FLAG.

In the threaded interrupt handlers (EVTQ/PRIQ), arm_smmu_rpm_get_if_active() is used to avoid sleeping and deadlocking against synchronize_irq() during suspend. Because device links guarantee client devices remain suspended and cannot issue DMA until the SMMU has fully transitioned to RPM_ACTIVE, no client-generated events can be received or dropped during transient states like RPM_RESUMING.

---
 .../arm/arm-smmu-v3/arm-smmu-v3-iommufd.c     |  20 ++-
 drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c   | 163 +++++++++++++++++-
 drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h   |   3 +
 3 files changed, 175 insertions(+), 11 deletions(-)
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3-iommufd.c +16 -4
index 25982bdbcbd9..7150b9c497a4 100644
@@ -15,17 +15,28 @@ void *arm_smmu_hw_info(struct device *dev, u32 *length,
 	struct iommu_hw_info_arm_smmuv3 *info;
 	u32 __iomem *base_idr;
 	unsigned int i;
+	int ret;
+
+	ret = arm_smmu_rpm_get(master->smmu);
+	if (ret < 0)
+		return ERR_PTR(-EIO);
 
 	if (*type != IOMMU_HW_INFO_TYPE_DEFAULT &&
 	    *type != IOMMU_HW_INFO_TYPE_ARM_SMMUV3) {
-		if (!impl_ops || !impl_ops->hw_info)
-			return ERR_PTR(-EOPNOTSUPP);
-		return impl_ops->hw_info(master->smmu, length, type);
+		void *ret_ptr = ERR_PTR(-EOPNOTSUPP);
+
+		if (impl_ops && impl_ops->hw_info)
+			ret_ptr = impl_ops->hw_info(master->smmu, length, type);
+
+		arm_smmu_rpm_put(master->smmu);
+		return ret_ptr;
 	}
 
 	info = kzalloc_obj(*info);
-	if (!info)
+	if (!info) {
+		arm_smmu_rpm_put(master->smmu);
 		return ERR_PTR(-ENOMEM);
+	}
 
 	base_idr = master->smmu->base + ARM_SMMU_IDR0;
 	for (i = 0; i <= 5; i++)
@@ -39,6 +50,7 @@ void *arm_smmu_hw_info(struct device *dev, u32 *length,
 	*length = sizeof(*info);
 	*type = IOMMU_HW_INFO_TYPE_ARM_SMMUV3;
 
+	arm_smmu_rpm_put(master->smmu);
 	return info;
 }
 
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +156 -7

282 lines not on this page · raw message

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h +3 -0
index d0a3d497915c..a018913d3bb8 100644
@@ -1249,6 +1249,9 @@ static inline bool arm_smmu_is_active(struct arm_smmu_device *smmu)
 	return !Q_STOP(READ_ONCE(smmu->cmdq.q.llq.prod));
 }
 
+int arm_smmu_rpm_get(struct arm_smmu_device *smmu);
+void arm_smmu_rpm_put(struct arm_smmu_device *smmu);
+
 #ifdef CONFIG_ARM_SMMU_V3_SVA
 bool arm_smmu_sva_supported(struct arm_smmu_device *smmu);
 void arm_smmu_sva_notifier_synchronize(void);
Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#66 lore raw

Re: [PATCH v11 15/16] iommu/arm-smmu-v3: Invoke pm_runtime before hw access

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [High] pm: power domain leak in arm_smmu_disable_action() - [High] irq: CPU livelock in threaded queues…

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [High] pm: power domain leak in arm_smmu_disable_action()
- [High] irq: CPU livelock in threaded queues due to uncleared events
--

commit 13dd005a8c8b5e0160d4c5b2b42bd2a26eae301e
Author: Pranjal Shrivastava <[email protected]>

iommu/arm-smmu-v3: Invoke pm_runtime before hw access

This commit introduces pm_runtime helpers before accessing hardware across the driver to avoid sleeping and deadlocking during transient power states. It uses lockless checks and non-sleeping runtime PM gets in threaded interrupts, and explicitly manages PM state around device disable paths.

Quoted 4 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +0 -0
index 2a1b5ce6ff1cf..89ffa83464780 100644

[ ... ]

Quoted 1 line
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +0 -0
@@ -2460,6 +2478,40 @@ static irqreturn_t arm_smmu_evtq_thread(int irq, void *dev)

[ ... ]

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c static irqreturn_t arm_smmu_evtq_thread(int irq, void *dev) · line 2513

Quoted 4 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +4 -0
+	if (!arm_smmu_rpm_get_if_active(smmu)) {
+		dev_warn_ratelimited(smmu->dev, "client device is suspended, dropping event\n");
+		return IRQ_HANDLED;
+	}

[Severity: High]
Can this cause an interrupt livelock?

If arm_smmu_rpm_get_if_active() observes the RPM_SUSPENDING state, it returns false, which means this returns IRQ_HANDLED without dequeueing the event or updating the hardware CONS pointer.

Because the event is left in the queue, won't the SMMU hardware continue to assert the level-triggered wired interrupt line, resulting in an infinite CPU loop that deadlocks the suspend sequence?

Quoted 2 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +0 -0
 	do {
 		while (!queue_remove_raw(q, evt)) {

[ ... ]

Quoted 1 line
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +0 -0
@@ -2518,6 +2571,18 @@ static irqreturn_t arm_smmu_priq_thread(int irq, void *dev)

[ ... ]

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c static irqreturn_t arm_smmu_priq_thread(int irq, void *dev) · line 2584

Quoted 4 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +4 -0
+	if (!arm_smmu_rpm_get_if_active(smmu)) {
+		dev_warn_ratelimited(smmu->dev, "client device is suspended, dropping page request\n");
+		return IRQ_HANDLED;
+	}

[Severity: High]
Similar to the evtq thread above, does returning IRQ_HANDLED here without consuming the hardware queue entries leave the interrupt line asserted? Could this lead to a CPU livelock during transient power states?

Quoted 2 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +0 -0
 	do {
 		while (!queue_remove_raw(q, evt))

[ ... ]

Quoted 8 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +1 -0
@@ -5116,14 +5227,37 @@ static int arm_smmu_device_disable(struct arm_smmu_device *smmu)
 static void arm_smmu_disable_action(void *data)
 {
 	struct arm_smmu_device *smmu = data;
+	int ret;
 
 	/* If the SMMU is already suspended, nothing to do */
 	if (!pm_runtime_suspended(smmu->dev)) {

[ ... ]

Quoted 13 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +12 -0
 		arm_smmu_device_disable(smmu);
+
+		/*
+		 * A PM ref was only acquired via arm_smmu_rpm_get() to
+		 * guarantee power for the MMIO register writes in
+		 * arm_smmu_device_disable().
+		 *
+		 * Drop the PM ref, we intentionally do NOT invoke a
+		 * synchronous put/suspend here since the HW was already
+		 * disabled above. Calling put_sync would invoke
+		 * arm_smmu_runtime_suspend(), redundantly attempting to
+		 * do the same. Any pending autosuspend timer is cleanly
+		 * cancelled by pm_runtime_disable() immediately below.

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c static int arm_smmu_device_disable(struct arm_smmu_device *smmu)

Quoted 10 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +4 -0
+		 * The core code ensures the power management here.
+		 */
+		arm_smmu_rpm_put(smmu);
 	}
 
+disable_pm:
 	if (pm_runtime_enabled(smmu->dev)) {
 		pm_runtime_dont_use_autosuspend(smmu->dev);
 		pm_runtime_disable(smmu->dev);
 	}

[Severity: High]
Does this sequence strand the attached PM domain in the ON state?

The code calls an asynchronous put (arm_smmu_rpm_put() invokes pm_runtime_put_autosuspend()) immediately before calling pm_runtime_disable(). Disabling runtime PM while a device is active cancels any pending autosuspend work and freezes the power state as RPM_ACTIVE.

Subsequent driver core calls to pm_runtime_put_sync() would then see disable_depth > 0 and fail with -EACCES without suspending the device, resulting in a permanent PM domain power leak preventing deep SOC idle states.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=15
#67 lore raw

PATCH v11 16/16 iommu/arm-smmu-v3: Add KUnit unit tests for Runtime PM

In reply to Pranjal Shrivastava

Introduce kunit selftests to verify the Runtime PM elision gating, post-suspend elisions and progress on resumption under active invalidation load. Simulate concurrent HW suspension using a timer. Mock all HW registers and CMDQ buffers by allocating them on RAM. Make the mock CMDQ self-consuming to avoid hitting queue_full scenarios.

---
 .../iommu/arm/arm-smmu-v3/arm-smmu-v3-test.c  | 215 ++++++++++++++++++
 drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c   |   1 +
 2 files changed, 216 insertions(+)
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3-test.c +215 -0
index add671363c82..97c1e907717d 100644
@@ -3,6 +3,10 @@
  * Copyright 2024 Google LLC.
  */
 #include <kunit/test.h>
+#include <linux/delay.h>
+#include <linux/kthread.h>
+#include <linux/sched.h>
+#include <linux/timer.h>
 #include <linux/io-pgtable.h>
 
 #include "arm-smmu-v3.h"
@@ -771,6 +775,215 @@ static void arm_smmu_v3_invs_test(struct kunit *test)
 	kfree(test_b);
 }
 
+struct arm_smmu_mock_cmdq {
+	/*
+	 * Mock register in RAM. Typed as __le32 to match writel_relaxed()
+	 * endianness without calling readl_* accessors directly on RAM.
+	 */
+	__le32 mock_prod_reg;
+};
+
+/* Helper to allocate a self-consuming mock cmdq */
+static void arm_smmu_v3_test_init_mock_cmdq(struct kunit *test,
+					    struct arm_smmu_device *smmu,
+					    struct arm_smmu_mock_cmdq *mock)
+{
+	struct arm_smmu_cmdq *cmdq = &smmu->cmdq;
+	unsigned long *mock_valid_map;
+	u64 *mock_base;
+
+	mock_base = kunit_kzalloc(test, 1024 * sizeof(struct arm_smmu_cmd), GFP_KERNEL);
+	mock_valid_map = kunit_kzalloc(test, BITS_TO_LONGS(1024) * sizeof(long), GFP_KERNEL);
+
+	KUNIT_ASSERT_NOT_NULL(test, mock_base);
+	KUNIT_ASSERT_NOT_NULL(test, mock_valid_map);
+
+	smmu->features = 0;
+	/* 1024 entries */
+	cmdq->q.llq.max_n_shift = 10;
+	cmdq->q.ent_dwords = CMDQ_ENT_DWORDS;
+	cmdq->q.base = (__le64 *)mock_base;
+	cmdq->valid_map = (atomic_long_t *)mock_valid_map;
+
+	/* Self-Consuming, prod == cons always ensures queue empty */
+	cmdq->q.prod_reg = (__force void __iomem *)&mock->mock_prod_reg;
+	cmdq->q.cons_reg = (__force void __iomem *)&mock->mock_prod_reg;
+
+	atomic_set(&cmdq->q.llq.atomic.prod, 0);
+	atomic_set(&cmdq->q.llq.atomic.cons, 0);
+	atomic_set(&cmdq->owner_prod, 0);
+	mock->mock_prod_reg = cpu_to_le32(0);
+}
+
+struct arm_smmu_test_timer_context {
+	struct arm_smmu_device *smmu;
+	struct timer_list timer;
+	bool suspended;
+};
+
+static void arm_smmu_v3_test_rpm_timer_callback(struct timer_list *t)
+{
+	struct arm_smmu_test_timer_context *ctx =
+		timer_container_of(ctx, t, timer);
+	struct arm_smmu_cmdq *cmdq = &ctx->smmu->cmdq;
+
+	/* Simulate a concurrent suspend event interrupting the invalidations */
+	atomic_or(CMDQ_PROD_STOP_FLAG, &cmdq->q.llq.atomic.prod);
+	WRITE_ONCE(ctx->suspended, true);
+}
+
+/*
+ * Verify SMMU PM Runtime gating, elision, and post-suspend resumption
+ * safety sequentially under active stress.
+ */
+static void arm_smmu_v3_rpm_test_stress_race(struct kunit *test)
+{
+	struct arm_smmu_cmd cmd = arm_smmu_make_cmd_cfgi_all();
+	struct arm_smmu_test_timer_context timer_ctx = {0};
+	struct arm_smmu_device mock_smmu = smmu;
+	struct arm_smmu_cmdq *cmdq = &mock_smmu.cmdq;
+	struct arm_smmu_mock_cmdq mock = {0};
+	u32 stopped_prod;
+	int i;
+
+	arm_smmu_v3_test_init_mock_cmdq(test, &mock_smmu, &mock);
+
+	timer_ctx.smmu = &mock_smmu;
+
+	timer_setup_on_stack(&timer_ctx.timer, arm_smmu_v3_test_rpm_timer_callback, 0);
+	mod_timer(&timer_ctx.timer, jiffies + msecs_to_jiffies(10));
+
+	/* Execute the unmap storm until the timer triggers */
+	while (!READ_ONCE(timer_ctx.suspended)) {
+		if (arm_smmu_cmdq_issue_cmdlist(&mock_smmu, cmdq, &cmd, 1, false))
+			break;
+		usleep_range(50, 100);
+	}
+
+	timer_shutdown_sync(&timer_ctx.timer);
+	timer_destroy_on_stack(&timer_ctx.timer);
+
+	/* Establish the post-storm prod_reg index */
+	stopped_prod = le32_to_cpu(mock.mock_prod_reg);
+
+	/*
+	 * Attempt multiple unmaps while the SMMU is disabled (STOP_GATE is set)
+	 * Every single invalidation must get elided and return 0. The prod_reg
+	 * shall remain completely frozen after all of these submissions.
+	 */
+	for (i = 0; i < 1000; i++) {
+		if (arm_smmu_cmdq_issue_cmdlist(&mock_smmu, cmdq, &cmd, 1, false))
+			break;
+	}
+	KUNIT_EXPECT_EQ(test, stopped_prod, le32_to_cpu(mock.mock_prod_reg));
+
+	/*
+	 * Clear the STOP_FLAG (resume the SMMU). A new invalidation must
+	 * now successfully commit prod_idx & move the prod_reg by exactly 1.
+	 */
+	atomic_andnot(CMDQ_PROD_STOP_FLAG, &cmdq->q.llq.atomic.prod);
+	KUNIT_EXPECT_EQ(test, 0, arm_smmu_cmdq_issue_cmdlist(&mock_smmu, cmdq, &cmd, 1, false));
+	KUNIT_EXPECT_EQ(test, Q_POS(&cmdq->q.llq, stopped_prod + 1),
+			le32_to_cpu(mock.mock_prod_reg));
+}
+
+struct arm_smmu_test_kthread_context {
+	struct arm_smmu_device *smmu;
+	int error;
+};
+
+static int arm_smmu_v3_test_kthread_worker(void *data)
+{
+	struct arm_smmu_cmd cmd = arm_smmu_make_cmd_cfgi_all();
+	struct arm_smmu_test_kthread_context *ctx = data;
+	struct arm_smmu_cmdq *cmdq = &ctx->smmu->cmdq;
+
+	while (!kthread_should_stop()) {
+		if (arm_smmu_cmdq_issue_cmdlist(ctx->smmu, cmdq, &cmd, 1, false))
+			WRITE_ONCE(ctx->error, 1);
+		usleep_range(50, 100);
+	}
+	return 0;
+}
+
+KUNIT_DEFINE_ACTION_WRAPPER(kunit_action_kthread_stop, kthread_stop, struct task_struct *);
+
+static void arm_smmu_v3_rpm_test_kthread_race(struct kunit *test)
+{
+	struct arm_smmu_test_kthread_context *ctx;
+	struct arm_smmu_device *mock_smmu;
+	struct arm_smmu_mock_cmdq *mock;
+	struct task_struct *thread1, *thread2;
+	u32 stopped_prod;
+	int i;
+
+	ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL);
+	mock_smmu = kunit_kzalloc(test, sizeof(*mock_smmu), GFP_KERNEL);
+	mock = kunit_kzalloc(test, sizeof(*mock), GFP_KERNEL);
+	KUNIT_ASSERT_NOT_NULL(test, ctx);
+	KUNIT_ASSERT_NOT_NULL(test, mock_smmu);
+	KUNIT_ASSERT_NOT_NULL(test, mock);
+
+	*mock_smmu = smmu;
+	ctx->smmu = mock_smmu;
+	arm_smmu_v3_test_init_mock_cmdq(test, mock_smmu, mock);
+
+	thread1 = kthread_run(arm_smmu_v3_test_kthread_worker, ctx, "smmu_w1");
+	if (IS_ERR(thread1)) {
+		KUNIT_FAIL(test, "Failed to spawn kthread 1\n");
+		return;
+	}
+	if (kunit_add_action_or_reset(test, kunit_action_kthread_stop, thread1)) {
+		KUNIT_FAIL(test, "Failed to register cleanup for kthread 1\n");
+		return;
+	}
+
+	thread2 = kthread_run(arm_smmu_v3_test_kthread_worker, ctx, "smmu_w2");
+	if (IS_ERR(thread2)) {
+		KUNIT_FAIL(test, "Failed to spawn kthread 2\n");
+		return;
+	}
+	if (kunit_add_action_or_reset(test, kunit_action_kthread_stop, thread2)) {
+		KUNIT_FAIL(test, "Failed to register cleanup for kthread 2\n");
+		return;
+	}
+
+	/* Wait for worker threads to start and issue initial commands */
+	for (i = 0; i < 20; i++) {
+		if (le32_to_cpu(READ_ONCE(mock->mock_prod_reg)) > 0)
+			break;
+		usleep_range(1000, 2000);
+	}
+	KUNIT_EXPECT_GT(test, le32_to_cpu(READ_ONCE(mock->mock_prod_reg)), 0);
+
+	/* Gate the CMDQ */
+	atomic_or(CMDQ_PROD_STOP_FLAG, &mock_smmu->cmdq.q.llq.atomic.prod);
+
+	/* Wait for in-flight submissions to settle */
+	for (i = 0; i < 50; i++) {
+		stopped_prod = le32_to_cpu(READ_ONCE(mock->mock_prod_reg));
+		usleep_range(1000, 2000);
+		if (stopped_prod == le32_to_cpu(READ_ONCE(mock->mock_prod_reg)))
+			break;
+	}
+
+	usleep_range(1000, 2000);
+	KUNIT_EXPECT_EQ(test, stopped_prod, le32_to_cpu(READ_ONCE(mock->mock_prod_reg)));
+
+	/* Open the gate and wait for worker threads to resume */
+	atomic_andnot(CMDQ_PROD_STOP_FLAG, &mock_smmu->cmdq.q.llq.atomic.prod);
+	for (i = 0; i < 20; i++) {
+		if (le32_to_cpu(READ_ONCE(mock->mock_prod_reg)) != stopped_prod)
+			break;
+		usleep_range(1000, 2000);
+	}
+	KUNIT_EXPECT_NE(test, stopped_prod, le32_to_cpu(READ_ONCE(mock->mock_prod_reg)));
+
+	kunit_release_action(test, kunit_action_kthread_stop, thread2);
+	kunit_release_action(test, kunit_action_kthread_stop, thread1);
+	KUNIT_EXPECT_EQ(test, 0, READ_ONCE(ctx->error));
+}
+
 static struct kunit_case arm_smmu_v3_test_cases[] = {
 	KUNIT_CASE(arm_smmu_v3_write_ste_test_bypass_to_abort),
 	KUNIT_CASE(arm_smmu_v3_write_ste_test_abort_to_bypass),
@@ -797,6 +1010,8 @@ static struct kunit_case arm_smmu_v3_test_cases[] = {
 	KUNIT_CASE(arm_smmu_v3_write_cd_test_sva_clear),
 	KUNIT_CASE(arm_smmu_v3_write_cd_test_sva_release),
 	KUNIT_CASE(arm_smmu_v3_invs_test),
+	KUNIT_CASE(arm_smmu_v3_rpm_test_stress_race),
+	KUNIT_CASE(arm_smmu_v3_rpm_test_kthread_race),
 	{},
 };
 
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +1 -0
index 89ffa8346478..62fc758d8044 100644
@@ -991,6 +991,7 @@ int arm_smmu_cmdq_issue_cmdlist(struct arm_smmu_device *smmu,
 
 	return ret;
 }
+EXPORT_SYMBOL_IF_KUNIT(arm_smmu_cmdq_issue_cmdlist);
 
 static int arm_smmu_cmdq_issue_cmd_p(struct arm_smmu_device *smmu,
 				     struct arm_smmu_cmd *cmd, bool sync)
Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#68 lore raw

Re: [PATCH v11 16/16] iommu/arm-smmu-v3: Add KUnit unit tests for Runtime PM

Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 7 lines

Introduce kunit selftests to verify the Runtime PM elision gating, post-suspend elisions and progress on resumption under active invalidation load. Simulate concurrent HW suspension using a timer. Mock all HW registers and CMDQ buffers by allocating them on RAM. Make the mock CMDQ self-consuming to avoid hitting queue_full scenarios.

Sashiko has reviewed this patch and found no issues. It looks great!

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=16
#69 lore raw

Re: [PATCH v11 16/16] iommu/arm-smmu-v3: Add KUnit unit tests for Runtime PM

In reply to Pranjal Shrivastava

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3-test.c line 8

Quoted 4 lines · Pranjal Shrivastava

#include <kunit/test.h>

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3-test.c +3 -0
+#include <linux/delay.h>
+#include <linux/kthread.h>
+#include <linux/sched.h>

kthread is used here, so sched is not necessary?

Quoted 23 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3-test.c +23 -0
+struct arm_smmu_mock_cmdq {
+	/*
+	 * Mock register in RAM. Typed as __le32 to match writel_relaxed()
+	 * endianness without calling readl_* accessors directly on RAM.
+	 */
+	__le32 mock_prod_reg;
+};
+
+/* Helper to allocate a self-consuming mock cmdq */
+static void arm_smmu_v3_test_init_mock_cmdq(struct kunit *test,
+					    struct arm_smmu_device *smmu,
+					    struct arm_smmu_mock_cmdq *mock)
+{
+	struct arm_smmu_cmdq *cmdq = &smmu->cmdq;
+	unsigned long *mock_valid_map;
+	u64 *mock_base;
+
+	mock_base = kunit_kzalloc(test, 1024 * sizeof(struct arm_smmu_cmd), GFP_KERNEL);
+	mock_valid_map = kunit_kzalloc(test, BITS_TO_LONGS(1024) * sizeof(long), GFP_KERNEL);
+
+	KUNIT_ASSERT_NOT_NULL(test, mock_base);
+	KUNIT_ASSERT_NOT_NULL(test, mock_valid_map);
+

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3-test.c static void arm_smmu_v3_invs_test(struct kunit *test) · line 810

Quoted 10 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3-test.c +10 -0
+	smmu->features = 0;
+	/* 1024 entries */
+	cmdq->q.llq.max_n_shift = 10;
+	cmdq->q.ent_dwords = CMDQ_ENT_DWORDS;
+	cmdq->q.base = (__le64 *)mock_base;
+	cmdq->valid_map = (atomic_long_t *)mock_valid_map;
+
+	/* Self-Consuming, prod == cons always ensures queue empty */
+	cmdq->q.prod_reg = (__force void __iomem *)&mock->mock_prod_reg;
+	cmdq->q.cons_reg = (__force void __iomem *)&mock->mock_prod_reg;

Is it really necessary to return mock->mock_prod_reg?

mock_base and mock_valid_map are working well here.

Couldn't mock_prod_reg be allocated here, then the caller just uses cmdq->q.prod_reg?

E.g.

static inline u32 arm_smmu_v3_test_read_prod(struct arm_smmu_cmdq *cmdq)

{
      return le32_to_cpu(READ_ONCE(*(__le32 __force *)cmdq->q.prod_reg));
}
Quoted 5 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3-test.c +5 -0
+struct arm_smmu_test_timer_context {
+	struct arm_smmu_device *smmu;
+	struct timer_list timer;
+	bool suspended;
+};

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3-test.c static void arm_smmu_v3_invs_test(struct kunit *test) · line 832

Quoted 10 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3-test.c +10 -0
+
+static void arm_smmu_v3_test_rpm_timer_callback(struct timer_list *t)
+{
+	struct arm_smmu_test_timer_context *ctx =
+		timer_container_of(ctx, t, timer);
+	struct arm_smmu_cmdq *cmdq = &ctx->smmu->cmdq;
+
+	/* Simulate a concurrent suspend event interrupting the invalidations */
+	atomic_or(CMDQ_PROD_STOP_FLAG, &cmdq->q.llq.atomic.prod);
+	WRITE_ONCE(ctx->suspended, true);

Both STOP and suspended flags are set at the same time, seemingly a bit redundant to me..

Quoted 4 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3-test.c +4 -0
+struct arm_smmu_test_kthread_context {
+	struct arm_smmu_device *smmu;
+	int error;
+};

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3-test.c static void arm_smmu_v3_invs_test(struct kunit *test) · line 903

Quoted 10 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3-test.c +10 -0
+
+static int arm_smmu_v3_test_kthread_worker(void *data)
+{
+	struct arm_smmu_cmd cmd = arm_smmu_make_cmd_cfgi_all();
+	struct arm_smmu_test_kthread_context *ctx = data;
+	struct arm_smmu_cmdq *cmdq = &ctx->smmu->cmdq;
+
+	while (!kthread_should_stop()) {
+		if (arm_smmu_cmdq_issue_cmdlist(ctx->smmu, cmdq, &cmd, 1, false))
+			WRITE_ONCE(ctx->error, 1);

With "sync=false", arm_smmu_cmdq_issue_cmdlist cannot fail. I don't see any "sync=true" call site in this patch. But even there was one, would the mock cmdq ever time out?

So, error (and arm_smmu_test_kthread_context) seems useless?

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3-test.c static void arm_smmu_v3_invs_test(struct kunit *test) · line 921

Quoted 11 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3-test.c +11 -0
+static void arm_smmu_v3_rpm_test_kthread_race(struct kunit *test)
+{
+	struct arm_smmu_test_kthread_context *ctx;
+	struct arm_smmu_device *mock_smmu;
+	struct arm_smmu_mock_cmdq *mock;
+	struct task_struct *thread1, *thread2;
+	u32 stopped_prod;
+	int i;
+
+	ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL);
+	mock_smmu = kunit_kzalloc(test, sizeof(*mock_smmu), GFP_KERNEL);

The other function simply does:

	struct arm_smmu_device mock_smmu = smmu;

Review

Quoted 2 lines
(quoted diff) +2 -0
+	/* Wait for worker threads to start and issue initial commands */
+	for (i = 0; i < 20; i++) {

I am a bit confused by the number in the for loop: it's 20 here...

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3-test.c static void arm_smmu_v3_invs_test(struct kunit *test) · line 963

Quoted 7 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3-test.c +7 -0
+	KUNIT_EXPECT_GT(test, le32_to_cpu(READ_ONCE(mock->mock_prod_reg)), 0);
+
+	/* Gate the CMDQ */
+	atomic_or(CMDQ_PROD_STOP_FLAG, &mock_smmu->cmdq.q.llq.atomic.prod);
+
+	/* Wait for in-flight submissions to settle */
+	for (i = 0; i < 50; i++) {

... but it's 50 here. Mind elaborating?

Nicolin

Tested-by on the v11 series
#70 lore raw
In reply to Pranjal Shrivastava

Hi Pranjal,

Tested the system sleep ops on RK3588 (Orange Pi 5), MMU600_PHP, no power domain in DT, with USB3 and GMAC translated:
- s2idle x3: OK.
- deep suspend x3: the SMMU loses its state (CR0, GBPA, STRTAB_BASE read 0 at resume); your resume path restores it, USB3 and Ethernet work, no errors. Without it the SMMU would resume in bypass.

Not tested: runtime PM, MSI restore, CMDQV.

Arun