Skip to contentSkip to conversation

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

PATCH Superseded Pranjal Shrivastava 4 participants 40 messages Jul 28 – Aug 30

Subsystems (4)

v9 of 11 Superseded Latest is v11 →

lore
Share & tools
lore
#0 lore raw

v9 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 series caches the msi_msg and restores it during resume via a new arm_smmu_resume_msis() helper.

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.

[v9]
- 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

Pranjal Shrivastava (11):
iommu/arm-smmu-v3: Refactor arm_smmu_setup_irqs iommu/arm-smmu-v3: Add a helper to drain cmd queues iommu/tegra241-cmdqv: Add a helper to drain VCMDQs iommu/arm-smmu-v3: Cache and restore MSI config iommu/arm-smmu-v3: Handle gerror during suspend 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

 .../arm/arm-smmu-v3/arm-smmu-v3-iommufd.c     |  20 +-
 .../iommu/arm/arm-smmu-v3/arm-smmu-v3-test.c  | 171 ++++++
 drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c   | 518 +++++++++++++++++-
 drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h   |  27 +
 .../iommu/arm/arm-smmu-v3/tegra241-cmdqv.c    |  73 +++
 5 files changed, 780 insertions(+), 29 deletions(-)

base-commit: a86c36163c9722545d27e92bdad8418fdcaa8b1d

Signature · 1 line
2.55.0.487.gaf234c4eb3-goog
#1 lore raw

PATCH v9 1/12 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.

---
 drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c | 47 +++++++++++++--------
 1 file changed, 30 insertions(+), 17 deletions(-)
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +30 -17
index 3a9cbd7d8a00..a11f5bcbe77d 100644
@@ -4749,14 +4749,32 @@ 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;
+
+	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);
+	ret = arm_smmu_disable_irqs(smmu);
 	if (ret) {
 		dev_err(smmu->dev, "failed to disable irqs\n");
 		return ret;
@@ -4778,15 +4796,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;
 }
 
@@ -4936,11 +4945,8 @@ 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;
-	}
+	/* Enable interrupt generation on the SMMU */
+	arm_smmu_enable_irqs(smmu);
 
 	if (is_kdump_kernel())
 		enables &= ~(CR0_EVTQEN | CR0_PRIQEN);
@@ -5576,6 +5582,13 @@ static int arm_smmu_device_probe(struct platform_device *pdev)
 	/* Check for RMRs and install bypass STEs if any */
 	arm_smmu_rmr_install_bypass_ste(smmu);
 
+	/* Setup interrupt handlers */
+	ret = arm_smmu_setup_irqs(smmu);
+	if (ret) {
+		dev_err(smmu->dev, "failed to setup irqs\n");
+		return ret;
+	}
+
 	/* Reset the device */
 	ret = arm_smmu_device_reset(smmu);
 	if (ret) {
Signature · 1 line
2.55.0.487.gaf234c4eb3-goog
Reviewed-by on v9 1/12
#2 lore raw

Re: [PATCH v9 01/12] iommu/arm-smmu-v3: Refactor arm_smmu_setup_irqs

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

Quoted 8 lines

[ ... 84 lines skipped ... ]

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +7 -0
+	/* Setup interrupt handlers */
+	ret = arm_smmu_setup_irqs(smmu);
+	if (ret) {
+		dev_err(smmu->dev, "failed to setup irqs\n");
+		return ret;
+	}
+

The sashiko remark makes sense to me, we should not enable interrupts until everything has been initialized and things are ready to go. So this is better done after the device reset call, which is the thing that is setting up the queue pointers in HW..

I'm not sure what to make of the MSI register ordering around kdump comment.. Nicolin?

But the refactoing looks fine to me

Signature · 1 line
Jason
#3 lore raw

Re: [PATCH v9 01/12] iommu/arm-smmu-v3: Refactor arm_smmu_setup_irqs

Quoted 14 lines · Jason Gunthorpe

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

Quoted 8 lines

[ ... 84 lines skipped ... ]

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +7 -0
+	/* Setup interrupt handlers */
+	ret = arm_smmu_setup_irqs(smmu);
+	if (ret) {
+		dev_err(smmu->dev, "failed to setup irqs\n");
+		return ret;
+	}
+

The sashiko remark makes sense to me, we should not enable interrupts until everything has been initialized and things are ready to go. So this is better done after the device reset call, which is the thing that is setting up the queue pointers in HW..

Quoted 3 lines

I'm not sure what to make of the MSI register ordering around kdump comment.. Nicolin?

Ack. I agree with Sashiko's remarks, we'd need to call this within device_reset right before the SMMU is enabled (same place as today). I factored this out to avoid setting up irq handlers multiple times across a suspend / resume cycle (for e.g. we can't request_irq multiple times for the same irq). Otherwise, we'd have to de-register IRQ handlers in the suspend callback. Maybe we could do this ONCE based on some smmu->inited bool?

Quoted 4 lines

But the refactoing looks fine to me

Thanks,
Praan

#4 lore raw

Re: [PATCH v9 01/12] iommu/arm-smmu-v3: Refactor arm_smmu_setup_irqs

Quoted 19 lines · Pranjal Shrivastava
Quoted 14 lines · Jason Gunthorpe

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

Quoted 8 lines

[ ... 84 lines skipped ... ]

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +7 -0
+	/* Setup interrupt handlers */
+	ret = arm_smmu_setup_irqs(smmu);
+	if (ret) {
+		dev_err(smmu->dev, "failed to setup irqs\n");
+		return ret;
+	}
+

The sashiko remark makes sense to me, we should not enable interrupts until everything has been initialized and things are ready to go. So this is better done after the device reset call, which is the thing that is setting up the queue pointers in HW..

Quoted 3 lines

I'm not sure what to make of the MSI register ordering around kdump comment.. Nicolin?

Quoted 7 lines

Ack. I agree with Sashiko's remarks, we'd need to call this within device_reset right before the SMMU is enabled (same place as today). I factored this out to avoid setting up irq handlers multiple times across a suspend / resume cycle (for e.g. we can't request_irq multiple times for the same irq). Otherwise, we'd have to de-register IRQ handlers in the suspend callback. Maybe we could do this ONCE based on some smmu->inited bool?

Yea, setting MSI while IRQ and CMDQ are enabled might be an issue.

FWIW, my kdump series disables EVTQ and PRIQ, so the concern would only apply to GERROR.

Nicolin

#5 lore raw

Re: [PATCH v9 01/12] iommu/arm-smmu-v3: Refactor arm_smmu_setup_irqs

Quoted 28 lines · Nicolin Chen
Quoted 19 lines · Pranjal Shrivastava
Quoted 14 lines · Jason Gunthorpe

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

Quoted 8 lines

[ ... 84 lines skipped ... ]

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +7 -0
+	/* Setup interrupt handlers */
+	ret = arm_smmu_setup_irqs(smmu);
+	if (ret) {
+		dev_err(smmu->dev, "failed to setup irqs\n");
+		return ret;
+	}
+

The sashiko remark makes sense to me, we should not enable interrupts until everything has been initialized and things are ready to go. So this is better done after the device reset call, which is the thing that is setting up the queue pointers in HW..

Quoted 3 lines

I'm not sure what to make of the MSI register ordering around kdump comment.. Nicolin?

Quoted 7 lines

Ack. I agree with Sashiko's remarks, we'd need to call this within device_reset right before the SMMU is enabled (same place as today). I factored this out to avoid setting up irq handlers multiple times across a suspend / resume cycle (for e.g. we can't request_irq multiple times for the same irq). Otherwise, we'd have to de-register IRQ handlers in the suspend callback. Maybe we could do this ONCE based on some smmu->inited bool?

Quoted 5 lines

Yea, setting MSI while IRQ and CMDQ are enabled might be an issue.

FWIW, my kdump series disables EVTQ and PRIQ, so the concern would only apply to GERROR.

Hmm, I guess I'll move it into the reset handler with some smmu->inited? The other thing could be somehow masking all interrupts till we *really* enable the SMMU.

Which one sounds better to you? Any preference?
(Will / Jason / Mostafa / Daniel?)

Thanks,
Praan

#6 lore raw

PATCH v9 2/12 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 a helper function that polls till the queues are dained.

---
 drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c | 45 +++++++++++++++++++++
 drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h |  3 ++
 2 files changed, 48 insertions(+)
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +45 -0
index a11f5bcbe77d..08b83f211ab3 100644
@@ -949,6 +949,51 @@ static int arm_smmu_cmdq_batch_submit(struct arm_smmu_device *smmu,
 					   cmds->num, true);
 }
 
+/*
+ * Currently, only used for CMDQ.
+ * TODO: Update to handle PRIQ & EVTQ when PRI support is added
+ */
+int arm_smmu_queue_poll_until_empty(struct arm_smmu_device *smmu,
+				    struct arm_smmu_queue *q)
+{
+	struct arm_smmu_queue_poll qp;
+	struct arm_smmu_ll_queue *llq = &q->llq;
+	int ret = 0;
+
+	queue_poll_init(smmu, &qp);
+
+	/*
+	 * The events are only generated when CMDQ becomes non-full.
+	 * Thus, wfe can't be used here, mark it false explicitly.
+	 */
+	qp.wfe = false;
+
+	do {
+		WRITE_ONCE(llq->cons, readl_relaxed(q->cons_reg));
+		if (queue_empty(llq))
+			break;
+
+		ret = queue_poll(&qp);
+
+	} while (!ret);
+
+	return ret;
+}
+
+static int arm_smmu_drain_queues(struct arm_smmu_device *smmu)
+{
+	int ret;
+
+	/*
+	 * We skip the 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_queue_poll_until_empty(smmu, &smmu->cmdq.q);
+
+	return ret;
+}
+
 static void arm_smmu_page_response(struct device *dev, struct iopf_fault *unused,
 				   struct iommu_page_response *resp)
 {
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h +3 -0
index 43f4d24e7847..00ad2e0c257b 100644
@@ -1167,6 +1167,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_queue_poll_until_empty(struct arm_smmu_device *smmu,
+				    struct arm_smmu_queue *q);
+
 static inline bool arm_smmu_master_canwbs(struct arm_smmu_master *master)
 {
 	return dev_iommu_fwspec_get(master->dev)->flags &
Signature · 1 line
2.55.0.487.gaf234c4eb3-goog
Reviewed-by on v9 2/12
#7 lore raw

Re: [PATCH v9 02/12] iommu/arm-smmu-v3: Add a helper to drain cmd queues

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

Quoted 2 lines

[ ... 36 lines skipped ... ]

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +1 -0
+		if (queue_empty(llq))

[Severity: High]
Does polling for an empty CMDQ actually guarantee that commands have completed?

queue_empty() relies on the SMMU consumer register equaling the producer pointer. However, for CMD_SYNC, the SMMU advances the consumer register immediately upon consumption, not upon completion. Suspending the SMMU while commands like ATC_INV are still in-flight could abort them, leaving stale translations in the device ATC and causing submitters to time out.

This seems broadly wrong, but it doesn't seem explained very well, maybe put a comment above the function something like

The caller must have ensured that no concurrent command submission can happen. Thus the entry at the PROD must be a CMD_SYNC due to how all submitters generate commands. Waiting for PROD==CONS guarentees completion of the sync and all prior work and thus idle HW.

I don't think the other substantive remarks are valid.

The Werror thing is right, every patch should compile alone without warnings. Sometimes people add __maybe_unused to accomplish this..

Quoted 1 line

[ ... 19 lines skipped ... ]

[Severity: High]
Does this logic miss commands routed to secondary queues?

The driver supports routing commands, specifically ATC_INV, to secondary queues (like the Tegra241 CMDQV virtual queues) via get_secondary_cmdq(). By strictly hardcoding the poll to smmu->cmdq.q, we ignore secondary queues. If the SMMU suspends while ATC_INV commands are processing there, they could be dropped.

Yes, I think the ordering is wrong, to keep them as different patches

iommu/tegra241-cmdqv: Add a helper to drain VCMDQs

Should come first, adding the op callback, then this patch would have the hunk completing the function so the newly introduced function works completely.

Otherwise the approach looks OK to me

Signature · 1 line
Jason
#8 lore raw

Re: [PATCH v9 02/12] iommu/arm-smmu-v3: Add a helper to drain cmd queues

Quoted 20 lines · Jason Gunthorpe

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

Quoted 2 lines

[ ... 36 lines skipped ... ]

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +1 -0
+		if (queue_empty(llq))

[Severity: High]
Does polling for an empty CMDQ actually guarantee that commands have completed?

queue_empty() relies on the SMMU consumer register equaling the producer pointer. However, for CMD_SYNC, the SMMU advances the consumer register immediately upon consumption, not upon completion. Suspending the SMMU while commands like ATC_INV are still in-flight could abort them, leaving stale translations in the device ATC and causing submitters to time out.

This seems broadly wrong, but it doesn't seem explained very well, maybe put a comment above the function something like

The caller must have ensured that no concurrent command submission can happen. Thus the entry at the PROD must be a CMD_SYNC due to how all submitters generate commands. Waiting for PROD==CONS guarentees completion of the sync and all prior work and thus idle HW.

Quoted 5 lines

I don't think the other substantive remarks are valid.

The Werror thing is right, every patch should compile alone without warnings. Sometimes people add __maybe_unused to accomplish this..

Ack. I plan to add __maybe_unused here.

Quoted 10 lines
Quoted 1 line

[ ... 19 lines skipped ... ]

[Severity: High]
Does this logic miss commands routed to secondary queues?

The driver supports routing commands, specifically ATC_INV, to secondary queues (like the Tegra241 CMDQV virtual queues) via get_secondary_cmdq(). By strictly hardcoding the poll to smmu->cmdq.q, we ignore secondary queues. If the SMMU suspends while ATC_INV commands are processing there, they could be dropped.

Quoted 8 lines

Yes, I think the ordering is wrong, to keep them as different patches

iommu/tegra241-cmdqv: Add a helper to drain VCMDQs

Should come first, adding the op callback, then this patch would have the hunk completing the function so the newly introduced function works completely.

Ack, I'll re-order the patches.

Quoted 3 lines

Otherwise the approach looks OK to me

Thanks,
Praan

#9 lore raw

Re: [PATCH v9 02/12] iommu/arm-smmu-v3: Add a helper to drain cmd queues

Quoted 21 lines · Pranjal Shrivastava
Quoted 20 lines · Jason Gunthorpe

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

Quoted 2 lines

[ ... 36 lines skipped ... ]

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +1 -0
+		if (queue_empty(llq))

[Severity: High]
Does polling for an empty CMDQ actually guarantee that commands have completed?

queue_empty() relies on the SMMU consumer register equaling the producer pointer. However, for CMD_SYNC, the SMMU advances the consumer register immediately upon consumption, not upon completion. Suspending the SMMU while commands like ATC_INV are still in-flight could abort them, leaving stale translations in the device ATC and causing submitters to time out.

This seems broadly wrong, but it doesn't seem explained very well, maybe put a comment above the function something like

The caller must have ensured that no concurrent command submission can happen. Thus the entry at the PROD must be a CMD_SYNC due to how all submitters generate commands. Waiting for PROD==CONS guarentees completion of the sync and all prior work and thus idle HW.

Quoted 7 lines
Quoted 5 lines

I don't think the other substantive remarks are valid.

The Werror thing is right, every patch should compile alone without warnings. Sometimes people add __maybe_unused to accomplish this..

Ack. I plan to add __maybe_unused here.

Maybe it's time to use the shared helper in both of our series?

I plan to send PRI-v3 on rc1 (likely next week) with this:
https://github.com/nicolinc/iommufd/commit/d10325ff40fd45c476bc98d484d8dd2cdc7fdf95

I think this series can take it (and its parent Q_POS as well), as we discussed in the other mail.

Nicolin

#10 lore raw

Re: [PATCH v9 02/12] iommu/arm-smmu-v3: Add a helper to drain cmd queues

Quoted 30 lines · Nicolin Chen
Quoted 21 lines · Pranjal Shrivastava
Quoted 20 lines · Jason Gunthorpe

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

Quoted 2 lines

[ ... 36 lines skipped ... ]

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +1 -0
+		if (queue_empty(llq))

[Severity: High]
Does polling for an empty CMDQ actually guarantee that commands have completed?

queue_empty() relies on the SMMU consumer register equaling the producer pointer. However, for CMD_SYNC, the SMMU advances the consumer register immediately upon consumption, not upon completion. Suspending the SMMU while commands like ATC_INV are still in-flight could abort them, leaving stale translations in the device ATC and causing submitters to time out.

This seems broadly wrong, but it doesn't seem explained very well, maybe put a comment above the function something like

The caller must have ensured that no concurrent command submission can happen. Thus the entry at the PROD must be a CMD_SYNC due to how all submitters generate commands. Waiting for PROD==CONS guarentees completion of the sync and all prior work and thus idle HW.

Quoted 7 lines
Quoted 5 lines

I don't think the other substantive remarks are valid.

The Werror thing is right, every patch should compile alone without warnings. Sometimes people add __maybe_unused to accomplish this..

Ack. I plan to add __maybe_unused here.

Quoted 8 lines

Maybe it's time to use the shared helper in both of our series?

I plan to send PRI-v3 on rc1 (likely next week) with this:
https://github.com/nicolinc/iommufd/commit/d10325ff40fd45c476bc98d484d8dd2cdc7fdf95

I think this series can take it (and its parent Q_POS as well), as we discussed in the other mail.

Ack. I agree, I can pick up Q_POS & the common drain helper here.

Quoted 1 line

Nicolin

Thanks,
Praan

#11 lore raw

PATCH v9 3/12 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 another function ptr to arm_smmu_impl_ops to drain implementation specified queues and call it within arm_smmu_drain_queues.

---
 drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c   |  7 ++++
 drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h   |  1 +
 .../iommu/arm/arm-smmu-v3/tegra241-cmdqv.c    | 35 +++++++++++++++++++
 3 files changed, 43 insertions(+)
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +7 -0
index 08b83f211ab3..96ca4a024cdd 100644
@@ -991,6 +991,13 @@ static int arm_smmu_drain_queues(struct arm_smmu_device *smmu)
 	 */
 	ret = arm_smmu_queue_poll_until_empty(smmu, &smmu->cmdq.q);
 
+	if (ret)
+		goto out;
+
+	/* Drain all implementation-specific queues */
+	if (smmu->impl_ops && smmu->impl_ops->drain_queues)
+		ret = smmu->impl_ops->drain_queues(smmu);
+out:
 	return ret;
 }
 
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h +1 -0
index 00ad2e0c257b..adfcbb654673 100644
@@ -886,6 +886,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 */
drivers/iommu/arm/arm-smmu-v3/tegra241-cmdqv.c +35 -0
index 6644075c1431..f62e9bdabf8a 100644
@@ -447,6 +447,40 @@ tegra241_cmdqv_get_cmdq(struct arm_smmu_device *smmu,
 	return &vcmdq->cmdq;
 }
 
+static int tegra241_cmdqv_drain_vintf0_lvcmdqs(struct arm_smmu_device *smmu)
+{
+	struct tegra241_cmdqv *cmdqv =
+		container_of(smmu, struct tegra241_cmdqv, smmu);
+	struct tegra241_vintf *vintf = cmdqv->vintfs[0];
+	int ret = 0;
+	u16 lidx;
+
+	/*
+	 * Kernel only uses VINTF0. Return if it's disabled.
+	 * Note: Lockless reads of the enabled flags are safe here.
+	 * VINTF0 is initialized during probe() (before Runtime PM is
+	 * enabled) and de-initialized during remove() (after the driver
+	 * core has called pm_runtime_disable()). Thus, this drain helper,
+	 * running only in runtime_suspend(), cannot race against VINTF0
+	 * creation or destruction.
+	 */
+	if (!READ_ONCE(vintf->enabled))
+		return 0;
+
+	for (lidx = 0; lidx < cmdqv->num_lvcmdqs_per_vintf; lidx++) {
+		struct tegra241_vcmdq *vcmdq = vintf->lvcmdqs[lidx];
+
+		if (!vcmdq || !READ_ONCE(vcmdq->enabled))
+			continue;
+
+		ret = arm_smmu_queue_poll_until_empty(smmu, &vcmdq->cmdq.q);
+		if (ret)
+			break;
+	}
+
+	return ret;
+}
+
 /* HW Reset Functions */
 
 /*
@@ -905,6 +939,7 @@ static struct arm_smmu_impl_ops tegra241_cmdqv_impl_ops = {
 	.device_reset = tegra241_cmdqv_hw_reset,
 	.device_disable = tegra241_cmdqv_hw_disable,
 	.device_remove = tegra241_cmdqv_remove,
+	.drain_queues = tegra241_cmdqv_drain_vintf0_lvcmdqs,
 	/* For user-space use */
 	.hw_info = tegra241_cmdqv_hw_info,
 	.get_viommu_size = tegra241_cmdqv_get_vintf_size,
Signature · 1 line
2.55.0.487.gaf234c4eb3-goog
#12 lore raw

PATCH v9 4/12 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 | 7 +++++++
 1 file changed, 7 insertions(+)
drivers/iommu/arm/arm-smmu-v3/tegra241-cmdqv.c +7 -0
index f62e9bdabf8a..8ecd2052b6dd 100644
@@ -553,6 +553,13 @@ 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.
+	 */
+	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.55.0.487.gaf234c4eb3-goog
#13 lore raw

PATCH v9 5/12 iommu/arm-smmu-v3: Cache and restore MSI config

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. We'll need to cache and restore their contents to ensure that MSIs work after the system resumes.

To address this, cache the original msi_msg within the msi_desc when the configuration is first written by arm_smmu_write_msi_msg. This primarily includes the target address and data since the memory attributes are fixed.

Introduce a new helper arm_smmu_resume_msis which will later be called during the driver's resume callback. The helper would retrieve the cached MSI message for each relevant interrupt (evtq, gerr, priq) via get_cached_msi_msg & re-config the registers via arm_smmu_write_msi_msg.

---
 drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c | 37 +++++++++++++++++++++
 1 file changed, 37 insertions(+)
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +37 -0
index 96ca4a024cdd..03b80ab0a59b 100644
@@ -4710,6 +4710,9 @@ static void arm_smmu_write_msi_msg(struct msi_desc *desc, struct msi_msg *msg)
 	struct arm_smmu_device *smmu = dev_get_drvdata(dev);
 	phys_addr_t *cfg = arm_smmu_msi_cfg[desc->msi_index];
 
+	/* Cache the msi_msg for resume */
+	desc->msg = *msg;
+
 	doorbell = (((u64)msg->address_hi) << 32) | msg->address_lo;
 	doorbell &= MSI_CFG0_ADDR_MASK;
 
@@ -4718,6 +4721,40 @@ 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 arm_smmu_resume_msi(struct arm_smmu_device *smmu,
+				unsigned int irq, const char *name)
+{
+	struct msi_desc *desc;
+	struct msi_msg msg;
+
+	if (!irq)
+		return;
+
+	desc = irq_get_msi_desc(irq);
+	if (!desc) {
+		dev_err(smmu->dev, "Failed to resume msi: %s", name);
+		return;
+	}
+
+	get_cached_msi_msg(irq, &msg);
+	arm_smmu_write_msi_msg(desc, &msg);
+}
+
+static void arm_smmu_resume_msis(struct arm_smmu_device *smmu)
+{
+	if (!(smmu->features & ARM_SMMU_FEAT_MSI))
+		return;
+
+	if (!dev_get_msi_domain(smmu->dev))
+		return;
+
+	arm_smmu_resume_msi(smmu, smmu->gerr_irq, "gerror");
+	arm_smmu_resume_msi(smmu, smmu->evtq.q.irq, "evtq");
+
+	if (smmu->features & ARM_SMMU_FEAT_PRI)
+		arm_smmu_resume_msi(smmu, smmu->priq.q.irq, "priq");
+}
+
 static void arm_smmu_setup_msis(struct arm_smmu_device *smmu)
 {
 	int ret, nvec = ARM_SMMU_MAX_MSIS;
Signature · 1 line
2.55.0.487.gaf234c4eb3-goog
#14 lore raw

Re: [PATCH v9 05/12] iommu/arm-smmu-v3: Cache and restore MSI config

Quoted 9 lines

[ ... 37 lines skipped ... ]

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +8 -0
+static void arm_smmu_resume_msi(struct arm_smmu_device *smmu,
+				unsigned int irq, const char *name)
+{
+	struct msi_desc *desc;
+	struct msi_msg msg;
+
+	if (!irq)
+		return;

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 4741

Quoted 10 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +10 -0
+
+	desc = irq_get_msi_desc(irq);
+	if (!desc) {
+		dev_err(smmu->dev, "Failed to resume msi: %s", name);
+		return;
+	}
+
+	get_cached_msi_msg(irq, &msg);
+	arm_smmu_write_msi_msg(desc, &msg);
+}

I'd really rather the irq core do this than open coding it like this, it should be fairly common for any driver doing power management and platform_device_msi stuff?

So maybe:

        platform_device_msi_rewrite(dev, irq, arm_smmu_write_msi_msg);

?

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 4749

Quoted 10 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +8 -0
+
+static void arm_smmu_resume_msis(struct arm_smmu_device *smmu)
+{
 
 
+	if (!(smmu->features & ARM_SMMU_FEAT_MSI))
+		return;
+
+	if (!dev_get_msi_domain(smmu->dev))
+		return;

[Severity: Medium]
Will this correctly detect if we have fallen back to wired irqs?

When setting up MSIs, if the allocation fails, the driver gracefully falls back to wired irqs without clearing the MSI feature flag:

 arm_smmu_setup_msis() {
     ...
     ret = platform_device_msi_init_and_alloc_irqs(...)
     if (ret) {
         dev_warn(dev, "failed to allocate MSIs - falling back to wired irqs\n");
         return;
     }
     ...

}

Does this mean the resume checks here will still pass during a fallback, causing irq_get_msi_desc() to return NULL and trigger a spurious dev_err() for each irq on every resume?

Seems believable..

Signature · 1 line
Jason
#15 lore raw

Re: [PATCH v9 05/12] iommu/arm-smmu-v3: Cache and restore MSI config

Quoted 24 lines · Jason Gunthorpe
Quoted 9 lines

[ ... 37 lines skipped ... ]

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +8 -0
+static void arm_smmu_resume_msi(struct arm_smmu_device *smmu,
+				unsigned int irq, const char *name)
+{
+	struct msi_desc *desc;
+	struct msi_msg msg;
+
+	if (!irq)
+		return;

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 4741

Quoted 10 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +10 -0
+
+	desc = irq_get_msi_desc(irq);
+	if (!desc) {
+		dev_err(smmu->dev, "Failed to resume msi: %s", name);
+		return;
+	}
+
+	get_cached_msi_msg(irq, &msg);
+	arm_smmu_write_msi_msg(desc, &msg);
+}

I'd really rather the irq core do this than open coding it like this, it should be fairly common for any driver doing power management and platform_device_msi stuff?

Quoted 5 lines

So maybe:

        platform_device_msi_rewrite(dev, irq, arm_smmu_write_msi_msg);

?

I guess it does make sense to add another irq core helper like:

void platform_device_msi_rewrite(struct device *dev, unsigned int irq,
irq_write_msi_msg_t write_msi_msg)

{
    struct msi_desc *desc = irq_get_msi_desc(irq);
    struct msi_msg msg;

    if (!desc)
        return;

    __get_cached_msi_msg(desc, &msg);
    write_msi_msg(desc, &msg);
}

EXPORT_SYMBOL_GPL(platform_device_msi_rewrite);

Quoted 16 lines

[Severity: Medium]
Will this correctly detect if we have fallen back to wired irqs?

When setting up MSIs, if the allocation fails, the driver gracefully falls back to wired irqs without clearing the MSI feature flag:

 arm_smmu_setup_msis() {
     ...
     ret = platform_device_msi_init_and_alloc_irqs(...)
     if (ret) {
         dev_warn(dev, "failed to allocate MSIs - falling back to wired irqs\n");
         return;
     }
     ...
Quoted 7 lines

}

Does this mean the resume checks here will still pass during a fallback, causing irq_get_msi_desc() to return NULL and trigger a spurious dev_err() for each irq on every resume?

Seems believable..

Ack. Yes, I think in this case we should be ideally clearing that
feature: smmu->features &= ~ARM_SMMU_FEAT_MSI; before return.

Thanks,
Praan

#16 lore raw

PATCH v9 6/12 iommu/arm-smmu-v3: Handle gerror during suspend

In reply to Pranjal Shrivastava

The GERROR register's state might be lost when the SMMU is powered down during runtime suspend. Handle any pending errors before suspending.

Refactor the gerror handling logic into a helper function and invoke it from the runtime suspend callback after disabling the SMMU. This ensures 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 03b80ab0a59b..2a976f210d9b 100644
@@ -2352,10 +2352,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);
@@ -2398,6 +2398,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.55.0.487.gaf234c4eb3-goog
Reviewed-by on v9 6/12
#17 lore raw

Re: [PATCH v9 06/12] iommu/arm-smmu-v3: Handle gerror during suspend

Quoted 7 lines

The GERROR register's state might be lost when the SMMU is powered down during runtime suspend. Handle any pending errors before suspending.

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

The commit message isn't clear, this is just a refactoring patch it does not "Handle gerror during suspend"

But the refactoring is fine

Though sashiko seems right about the pre-existing bug.

Signature · 1 line
Jason
#18 lore raw

Re: [PATCH v9 06/12] iommu/arm-smmu-v3: Handle gerror during suspend

Quoted 8 lines · Jason Gunthorpe
Quoted 7 lines

The GERROR register's state might be lost when the SMMU is powered down during runtime suspend. Handle any pending errors before suspending.

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

Quoted 9 lines

The commit message isn't clear, this is just a refactoring patch it does not "Handle gerror during suspend"

But the refactoring is fine

Though sashiko seems right about the pre-existing bug.

Yes, we recently fixed the pre-existing bug with this:
https://git.kernel.org/pub/scm/linux/kernel/git/iommu/linux.git/commit/?id=eced8058c82a

Thanks
Praan

#19 lore raw

PATCH v9 7/12 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 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 | 20 +++++++++++++++++++-
 drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h |  5 +++++
 2 files changed, 24 insertions(+), 1 deletion(-)
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +19 -1
index 2a976f210d9b..8809757ebee8 100644
@@ -219,7 +219,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);
+
+	return Q_OVF(q->prod) | Q_STOP(q->prod) | Q_WRP(q, prod) | Q_IDX(q, prod);
 }
 
 static void queue_poll_init(struct arm_smmu_device *smmu,
@@ -727,8 +728,25 @@ 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);
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h +5 -0
index adfcbb654673..40b889998d5b 100644
@@ -389,6 +389,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.55.0.487.gaf234c4eb3-goog
#20 lore raw

Re: [PATCH v9 07/12] iommu/arm-smmu-v3: Add CMDQ_PROD_STOP_FLAG to gate CMDQ submissions

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

Quoted 11 lines

[ ... 52 lines skipped ... ]

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +5 -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);

[Severity: Critical]
Can this loop bypass the Q_STOP check if a suspend happens concurrently?

If a thread enters the while loop because there's no space, and a concurrent task sets the CMDQ_PROD_STOP_FLAG while space becomes available:

1. arm_smmu_cmdq_poll_until_not_full() updates llq.val with the latest global state, which now includes the newly set STOP_FLAG in llq.prod.
2. The loop condition !queue_has_space(&llq, n + sync) now evaluates to false, causing the thread to exit the inner loop.
3. This bypasses the Q_STOP(READ_ONCE(cmdq->q.llq.prod)) check inside the loop, as well as the Q_STOP(llq.prod) check at the top of the do-while loop.

The thread would then successfully cmpxchg the new producer index with the STOP_FLAG set.

Make sense to me, having arm_smmu_cmdq_poll_until_not_full() reload the llq and then not loop again from the top skips the Q_STOP flag.

Signature · 1 line
Jason
#21 lore raw

Re: [PATCH v9 07/12] iommu/arm-smmu-v3: Add CMDQ_PROD_STOP_FLAG to gate CMDQ submissions

Quoted 25 lines · Jason Gunthorpe

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

Quoted 11 lines

[ ... 52 lines skipped ... ]

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +5 -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);

[Severity: Critical]
Can this loop bypass the Q_STOP check if a suspend happens concurrently?

If a thread enters the while loop because there's no space, and a concurrent task sets the CMDQ_PROD_STOP_FLAG while space becomes available:

1. arm_smmu_cmdq_poll_until_not_full() updates llq.val with the latest global state, which now includes the newly set STOP_FLAG in llq.prod.
2. The loop condition !queue_has_space(&llq, n + sync) now evaluates to false, causing the thread to exit the inner loop.
3. This bypasses the Q_STOP(READ_ONCE(cmdq->q.llq.prod)) check inside the loop, as well as the Q_STOP(llq.prod) check at the top of the do-while loop.

Quoted 7 lines

The thread would then successfully cmpxchg the new producer index with the STOP_FLAG set.

Make sense to me, having arm_smmu_cmdq_poll_until_not_full() reload the llq and then not loop again from the top skips the Q_STOP flag.

Right. I guess we should check the condition again after exiting the loop or add the point of commitment to this space loop somehow. I'll take care of this.

Thanks,
Praan

#22 lore raw

PATCH v9 8/12 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 as well. 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 the vCMDQs as well.

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    | 37 +++++++++++++++++--
 3 files changed, 37 insertions(+), 6 deletions(-)
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +2 -2
index 8809757ebee8..49e15d062dd5 100644
@@ -1013,8 +1013,8 @@ static int arm_smmu_drain_queues(struct arm_smmu_device *smmu)
 		goto out;
 
 	/* Drain all implementation-specific queues */
-	if (smmu->impl_ops && smmu->impl_ops->drain_queues)
-		ret = smmu->impl_ops->drain_queues(smmu);
+	if (smmu->impl_ops && smmu->impl_ops->quiesce_and_drain_queues)
+		ret = smmu->impl_ops->quiesce_and_drain_queues(smmu);
 out:
 	return ret;
 }
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h +1 -1
index 40b889998d5b..cc25f307a9e4 100644
@@ -891,7 +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);
+	int (*quiesce_and_drain_queues)(struct arm_smmu_device *smmu);
 };
 
 /* An SMMUv3 instance */
drivers/iommu/arm/arm-smmu-v3/tegra241-cmdqv.c +34 -3
index 8ecd2052b6dd..32139797c19b 100644
@@ -447,6 +447,26 @@ tegra241_cmdqv_get_cmdq(struct arm_smmu_device *smmu,
 	return &vcmdq->cmdq;
 }
 
+static void tegra241_cmdqv_quiesce_vintf0_lvcmdqs(struct arm_smmu_device *smmu)
+{
+	struct tegra241_cmdqv *cmdqv =
+		container_of(smmu, struct tegra241_cmdqv, smmu);
+	struct tegra241_vintf *vintf = cmdqv->vintfs[0];
+	u16 lidx;
+
+	if (!READ_ONCE(vintf->enabled))
+		return;
+
+	for (lidx = 0; lidx < cmdqv->num_lvcmdqs_per_vintf; lidx++) {
+		struct tegra241_vcmdq *vcmdq = vintf->lvcmdqs[lidx];
+
+		if (!vcmdq || !READ_ONCE(vcmdq->enabled))
+			continue;
+
+		atomic_or(CMDQ_PROD_STOP_FLAG, &vcmdq->cmdq.q.llq.atomic.prod);
+	}
+}
+
 static int tegra241_cmdqv_drain_vintf0_lvcmdqs(struct arm_smmu_device *smmu)
 {
 	struct tegra241_cmdqv *cmdqv =
@@ -467,6 +487,14 @@ static int tegra241_cmdqv_drain_vintf0_lvcmdqs(struct arm_smmu_device *smmu)
 	if (!READ_ONCE(vintf->enabled))
 		return 0;
 
+	/*
+	 * Gate all vCMDQs by setting the STOP_FLAG in a separate,
+	 * initial loop to ensure no new commands can be submitted
+	 * to any secondary queue while we are waiting to drain them.
+	 */
+	tegra241_cmdqv_quiesce_vintf0_lvcmdqs(smmu);
+
+	/* Now that all queues are safely gated, drain them sequentially. */
 	for (lidx = 0; lidx < cmdqv->num_lvcmdqs_per_vintf; lidx++) {
 		struct tegra241_vcmdq *vcmdq = vintf->lvcmdqs[lidx];
 
@@ -552,14 +580,17 @@ 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.
 	 */
-	writel_relaxed(vcmdq->cmdq.q.llq.prod, REG_VCMDQ_PAGE0(vcmdq, PROD));
+	writel_relaxed(vcmdq->cmdq.q.llq.prod & CMDQ_PROD_IDX_MASK,
+		       REG_VCMDQ_PAGE0(vcmdq, PROD));
 	writel_relaxed(vcmdq->cmdq.q.llq.cons, REG_VCMDQ_PAGE0(vcmdq, CONS));
 
+	/* Clear the CMDQ_PROD_STOP_FLAG */
+	atomic_andnot(CMDQ_PROD_STOP_FLAG, &vcmdq->cmdq.q.llq.atomic.prod);
+
 	ret = vcmdq_write_config(vcmdq, VCMDQ_EN);
 	if (ret) {
 		dev_err(vcmdq->cmdqv->dev,
@@ -946,7 +977,7 @@ static struct arm_smmu_impl_ops tegra241_cmdqv_impl_ops = {
 	.device_reset = tegra241_cmdqv_hw_reset,
 	.device_disable = tegra241_cmdqv_hw_disable,
 	.device_remove = tegra241_cmdqv_remove,
-	.drain_queues = tegra241_cmdqv_drain_vintf0_lvcmdqs,
+	.quiesce_and_drain_queues = tegra241_cmdqv_drain_vintf0_lvcmdqs,
 	/* For user-space use */
 	.hw_info = tegra241_cmdqv_hw_info,
 	.get_viommu_size = tegra241_cmdqv_get_vintf_size,
Signature · 1 line
2.55.0.487.gaf234c4eb3-goog
#23 lore raw

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

Quoted 6 lines

[ ... 73 lines skipped ... ]

drivers/iommu/arm/arm-smmu-v3/tegra241-cmdqv.c +1 -0
@@ -467,6 +487,14 @@ static int tegra241_cmdqv_drain_vintf0_lvcmdqs(struct arm_smmu_device *smmu)
 	if (!READ_ONCE(vintf->enabled))
 		return 0;
 
+	/*

drivers/iommu/arm/arm-smmu-v3/tegra241-cmdqv.c static int tegra241_cmdqv_drain_vintf0_lvcmdqs(struct arm_smmu_device *smmu) · line 500

Quoted 10 lines
drivers/iommu/arm/arm-smmu-v3/tegra241-cmdqv.c +7 -0
+	 * Gate all vCMDQs by setting the STOP_FLAG in a separate,
+	 * initial loop to ensure no new commands can be submitted
+	 * to any secondary queue while we are waiting to drain them.
+	 */
+	tegra241_cmdqv_quiesce_vintf0_lvcmdqs(smmu);
+
+	/* Now that all queues are safely gated, drain them sequentially. */
 	for (lidx = 0; lidx < cmdqv->num_lvcmdqs_per_vintf; lidx++) {
 		struct tegra241_vcmdq *vcmdq = vintf->lvcmdqs[lidx];
 

[Severity: High]
If arm_smmu_queue_poll_until_empty() fails during this sequential drain, it returns an error without clearing the CMDQ_PROD_STOP_FLAG that was just set on all queues:

Make sense to me, the earlier patch added:

		ret = arm_smmu_queue_poll_until_empty(smmu, &vcmdq->cmdq.q);
		if (ret)
			break;
Signature · 1 line
Jason
#24 lore raw

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

Quoted 22 lines · Jason Gunthorpe
Quoted 6 lines

[ ... 73 lines skipped ... ]

drivers/iommu/arm/arm-smmu-v3/tegra241-cmdqv.c +1 -0
@@ -467,6 +487,14 @@ static int tegra241_cmdqv_drain_vintf0_lvcmdqs(struct arm_smmu_device *smmu)
 	if (!READ_ONCE(vintf->enabled))
 		return 0;
 
+	/*

drivers/iommu/arm/arm-smmu-v3/tegra241-cmdqv.c static int tegra241_cmdqv_drain_vintf0_lvcmdqs(struct arm_smmu_device *smmu) · line 500

Quoted 10 lines
drivers/iommu/arm/arm-smmu-v3/tegra241-cmdqv.c +7 -0
+	 * Gate all vCMDQs by setting the STOP_FLAG in a separate,
+	 * initial loop to ensure no new commands can be submitted
+	 * to any secondary queue while we are waiting to drain them.
+	 */
+	tegra241_cmdqv_quiesce_vintf0_lvcmdqs(smmu);
+
+	/* Now that all queues are safely gated, drain them sequentially. */
 	for (lidx = 0; lidx < cmdqv->num_lvcmdqs_per_vintf; lidx++) {
 		struct tegra241_vcmdq *vcmdq = vintf->lvcmdqs[lidx];
 

[Severity: High]
If arm_smmu_queue_poll_until_empty() fails during this sequential drain, it returns an error without clearing the CMDQ_PROD_STOP_FLAG that was just set on all queues:

Quoted 6 lines

Make sense to me, the earlier patch added:

		ret = arm_smmu_queue_poll_until_empty(smmu, &vcmdq->cmdq.q);
		if (ret)
			break;

Yes, I plan to treat this the same as the primary CMDQ and move on instead of break; I'll address this in v10.

Thanks,
Praan

#25 lore raw

PATCH v9 9/12 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 new transactions, disables the main translation unit and then drains the command queue to ensure completion of any in-flight commands. A software gate (STOP_FLAG) and synchronization barriers are used to quiesce the command submission pipeline and ensure state consistency before power-off.

To prevent software metadata flags from leaking into physical registers or polluting the tracking pointer, a newly introduced bitmask (CMDQ_PROD_IDX_MASK) is applied to all register writes and tracking updates.

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.

---
 drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c | 233 +++++++++++++++++++-
 drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h |  15 ++
 2 files changed, 242 insertions(+), 6 deletions(-)
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +227 -6
index 49e15d062dd5..5f0e01dc4f6a 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;
@@ -730,10 +770,58 @@ 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.
+		 *
+		 * 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_queues();        |     // 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);
@@ -798,7 +886,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.
@@ -4995,7 +5084,8 @@ static int arm_smmu_device_reset(struct arm_smmu_device *smmu)
 
 	/* 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;
@@ -5006,6 +5096,9 @@ static int arm_smmu_device_reset(struct arm_smmu_device *smmu)
 		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());
 
@@ -5746,6 +5839,133 @@ 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 */
+	enables = CR0_CMDQEN;
+	ret = arm_smmu_write_reg_sync(smmu, enables, ARM_SMMU_CR0, ARM_SMMU_CR0ACK);
+	if (ret) {
+		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_queues(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);
+
+	/* Avoid consuming stale commands if we timed-out to drain the queues */
+	if (ret || !timeout)
+		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);
+	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", },
 	{ },
@@ -5762,6 +5982,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 cc25f307a9e4..24b9969b0b90 100644
@@ -658,11 +658,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;
@@ -1227,6 +1230,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.55.0.487.gaf234c4eb3-goog
#26 lore raw

Re: [PATCH v9 09/12] iommu/arm-smmu-v3: Implement pm_runtime & system sleep ops

Quoted 7 lines

[ ... 80 lines skipped ... ]

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +0 -2
@@ -730,10 +770,58 @@ 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

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

Quoted 10 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +8 -2
-		 * committed, we MUST write valid commands to those slots to
-		 * avoid indefinite polling in the drain function.
+		 *
+		 * 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()

[Severity: Critical]
If an ATC invalidation (CMDQ_OP_ATC_INV) is issued (e.g., during iommu_unmap from a background thread) while the SMMU is suspended, the command appears to be silently dropped here.

Since ATC caches inside PCIe endpoints might not be globally invalidated during resume, could the endpoint retain stale ATC entries upon wake-up? Would this allow the endpoint to DMA into freed memory?

I agree.. I think there are only two options?
1) After GBPA=Abort ATS requests are blocked, so you could full invalidate all the device ATC's and now it is safe to ignore ATC_INV
2) Just don't perform suspend once ATS is activated

Signature · 1 line
Jason
#27 lore raw

Re: [PATCH v9 09/12] iommu/arm-smmu-v3: Implement pm_runtime & system sleep ops

Quoted 27 lines · Jason Gunthorpe
Quoted 7 lines

[ ... 80 lines skipped ... ]

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +0 -2
@@ -730,10 +770,58 @@ 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

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

Quoted 10 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +8 -2
-		 * committed, we MUST write valid commands to those slots to
-		 * avoid indefinite polling in the drain function.
+		 *
+		 * 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()

[Severity: Critical]
If an ATC invalidation (CMDQ_OP_ATC_INV) is issued (e.g., during iommu_unmap from a background thread) while the SMMU is suspended, the command appears to be silently dropped here.

Since ATC caches inside PCIe endpoints might not be globally invalidated during resume, could the endpoint retain stale ATC entries upon wake-up? Would this allow the endpoint to DMA into freed memory?

Quoted 5 lines

I agree.. I think there are only two options?
1) After GBPA=Abort ATS requests are blocked, so you could full invalidate all the device ATC's and now it is safe to ignore ATC_INV
2) Just don't perform suspend once ATS is activated

This is a little tricky, I'm leaning towards 1) since edge devices can have ATS enabled

However, the EP might've entered it's low power state by the time we reach smmu's suspend. I'm not sure if we should be waking up the EP for ATC INV All (or if it would even wake up in such a case?)

Praan

#28 lore raw

Re: [PATCH v9 09/12] iommu/arm-smmu-v3: Implement pm_runtime & system sleep ops

Quoted 8 lines · Pranjal Shrivastava
Quoted 5 lines

I agree.. I think there are only two options?
1) After GBPA=Abort ATS requests are blocked, so you could full invalidate all the device ATC's and now it is safe to ignore ATC_INV
2) Just don't perform suspend once ATS is activated

This is a little tricky, I'm leaning towards 1) since edge devices can have ATS enabled

Oh really? Surprising..

Quoted 3 lines

However, the EP might've entered it's low power state by the time we reach smmu's suspend. I'm not sure if we should be waking up the EP for ATC INV All (or if it would even wake up in such a case?)

Is its power down explicit? Could the PM stuff trigger wiping the ATC and blocking DMA for a single device before allowing it to power down?

Jason

#29 lore raw

Re: [PATCH v9 09/12] iommu/arm-smmu-v3: Implement pm_runtime & system sleep ops

Quoted 11 lines · Jason Gunthorpe
Quoted 8 lines · Pranjal Shrivastava
Quoted 5 lines

I agree.. I think there are only two options?
1) After GBPA=Abort ATS requests are blocked, so you could full invalidate all the device ATC's and now it is safe to ignore ATC_INV
2) Just don't perform suspend once ATS is activated

This is a little tricky, I'm leaning towards 1) since edge devices can have ATS enabled

Quoted 9 lines

Oh really? Surprising..

Quoted 3 lines

However, the EP might've entered it's low power state by the time we reach smmu's suspend. I'm not sure if we should be waking up the EP for ATC INV All (or if it would even wake up in such a case?)

Is its power down explicit? Could the PM stuff trigger wiping the ATC and blocking DMA for a single device before allowing it to power down?

The power down is explicit, due to devlinks, the PCIe driver's suspend op (runtime / system) is called before the SMMU's suspend. I'm relying on PCIe driver's op to clear ATC and everything else before powering down

Basically, what I mean is it should be the PCIe device's responsibility to clear ATC in this case because by the time we come to IOMMU's suspend, the PCIe device would be powered down anyway and I'm not sure if issuing an ATS INV request TLP would wake up the endpoint.

IIUC, if the link is in L1 / L2 then TLP tranmission is disabled, and to bring it back to L0 we might have to call into the PCIe subsystem *somehow*.

One thing we can do is shout in the dmesg with a dev_warn if rpm & ATS both are enabled saying the PCIe driver is responsible for clearing out it's ATC during suspend since SMMU's suspend runs after the dev is down.

Thanks,
Praan

#30 lore raw

Re: [PATCH v9 09/12] iommu/arm-smmu-v3: Implement pm_runtime & system sleep ops

Quoted 18 lines · Pranjal Shrivastava
Quoted 17 lines · Jason Gunthorpe
Quoted 8 lines · Pranjal Shrivastava
Quoted 5 lines

I agree.. I think there are only two options?
1) After GBPA=Abort ATS requests are blocked, so you could full invalidate all the device ATC's and now it is safe to ignore ATC_INV
2) Just don't perform suspend once ATS is activated

This is a little tricky, I'm leaning towards 1) since edge devices can have ATS enabled

Oh really? Surprising..

Quoted 3 lines

However, the EP might've entered it's low power state by the time we reach smmu's suspend. I'm not sure if we should be waking up the EP for ATC INV All (or if it would even wake up in such a case?)

Quoted 7 lines
Quoted 3 lines

Is its power down explicit? Could the PM stuff trigger wiping the ATC and blocking DMA for a single device before allowing it to power down?

The power down is explicit, due to devlinks, the PCIe driver's suspend op (runtime / system) is called before the SMMU's suspend. I'm relying on PCIe driver's op to clear ATC and everything else before powering down

So maybe everything is OK and it just need some commenting to define this split up?

IIRC there is a PCI spec thing that says the ATC is cleared on certain config cycles?

Jason

#31 lore raw

Re: [PATCH v9 09/12] iommu/arm-smmu-v3: Implement pm_runtime & system sleep ops

Quoted 23 lines · Jason Gunthorpe
Quoted 22 lines · Pranjal Shrivastava
Quoted 20 lines · Jason Gunthorpe
Quoted 8 lines · Pranjal Shrivastava
Quoted 5 lines

I agree.. I think there are only two options?
1) After GBPA=Abort ATS requests are blocked, so you could full invalidate all the device ATC's and now it is safe to ignore ATC_INV
2) Just don't perform suspend once ATS is activated

This is a little tricky, I'm leaning towards 1) since edge devices can have ATS enabled

Oh really? Surprising..

Quoted 3 lines

However, the EP might've entered it's low power state by the time we reach smmu's suspend. I'm not sure if we should be waking up the EP for ATC INV All (or if it would even wake up in such a case?)

Is its power down explicit? Could the PM stuff trigger wiping the ATC and blocking DMA for a single device before allowing it to power down?

Quoted 7 lines
Quoted 3 lines

The power down is explicit, due to devlinks, the PCIe driver's suspend op (runtime / system) is called before the SMMU's suspend. I'm relying on PCIe driver's op to clear ATC and everything else before powering down

So maybe everything is OK and it just need some commenting to define this split up?

Yes, we can add a comment and a small dev_warn when ATS is enabled with rpm clearly mentioning the reason for any unwanted aliasing (if observed)

Quoted 3 lines

IIRC there is a PCI spec thing that says the ATC is cleared on certain config cycles?

Yes, IRC, D3Cold would clear everything anyway, and D3Hot -> D0 with soft-reset also lands in uninitialized. I'd have to check for D3Hot -> D0 without soft-reset. However, for this discussion I think we agree hhat it's not the IOMMU's responsibility to handle the PCIe ATC state.

Thanks,
Praan

#32 lore raw

PATCH v9 10/12 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.

---
 drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c | 10 ++++++++++
 1 file changed, 10 insertions(+)
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +10 -0
index 5f0e01dc4f6a..1253065b6db4 100644
@@ -4431,6 +4431,9 @@ static struct iommu_device *arm_smmu_probe_device(struct device *dev)
 	if (ret)
 		goto err_disable_pasid;
 
+	device_link_add(dev, smmu->dev,
+			DL_FLAG_PM_RUNTIME | DL_FLAG_AUTOREMOVE_SUPPLIER);
+
 	return &smmu->iommu;
 
 err_disable_pasid:
@@ -5821,6 +5824,13 @@ static int arm_smmu_device_probe(struct platform_device *pdev)
 		return ret;
 	}
 
+	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;
 }
 
Signature · 1 line
2.55.0.487.gaf234c4eb3-goog
#33 lore raw

PATCH v9 11/12 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.

---
 .../arm/arm-smmu-v3/arm-smmu-v3-iommufd.c     |  20 ++-
 drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c   | 123 +++++++++++++++++-
 drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h   |   3 +
 3 files changed, 135 insertions(+), 11 deletions(-)
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3-iommufd.c +16 -4
index 76333091ec15..6b0b021df82c 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 +116 -7

235 lines not on this page · raw message

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h +3 -0
index 24b9969b0b90..15b5d5fad627 100644
@@ -1242,6 +1242,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.55.0.487.gaf234c4eb3-goog
#34 lore raw

Re: [PATCH v9 11/12] iommu/arm-smmu-v3: Invoke pm_runtime before hw access

Quoted 25 lines · Pranjal Shrivastava
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +21 -0
@@ -2386,6 +2407,34 @@ static irqreturn_t arm_smmu_evtq_thread(int irq, void *dev)
        static DEFINE_RATELIMIT_STATE(rs, DEFAULT_RATELIMIT_INTERVAL,
                                      DEFAULT_RATELIMIT_BURST);
 
+       /*
+        * Use a non-sleeping get to avoid a circular dependency deadlock
+        * with arm_smmu_runtime_suspend().
+        *
+        * When using a combined_irq, the suspend thread waits for pending
+        * threaded handlers to complete. If the IRQ thread blocks waiting
+        * for the PM core, it creates a deadlock:
+        *
+        *  [Suspend Thread]                  | [IRQ Thread]
+        *  pm_runtime_suspend()              |
+        *    state = RPM_SUSPENDING;         |
+        *                                    | IRQ fires
+        *                                    | arm_smmu_rpm_get()
+        *                                    |   sleeps (waiting for suspend)
+        *  arm_smmu_runtime_suspend()        |
+        *    ...                             |
+        *    synchronize_irq()               |
+        *      sleeps (waiting for IRQ)      |
+        *
+        *           <==== DEADLOCK ====>
+        *

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

Quoted 10 lines
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +7 -0
+        * A non-sleeping get allows the thread to instantly drop the event
+        * if the device is suspending, safely bypassing the synchronize_irq()
+        * deadlock.
+        */
+       if (!arm_smmu_rpm_get_if_active(smmu))
+               return IRQ_NONE;
+
        do {
                while (!queue_remove_raw(q, evt)) {
                        arm_smmu_decode_event(smmu, evt, &event);

Sashiko has the following concern:

Quoted 11 lines

Does returning IRQ_NONE here during transient PM states cause an interrupt storm or data loss?
If the device is in a transient state (like RPM_SUSPENDING), this lockless check returns false and the thread aborts without acknowledging the hardware interrupt. For a level-triggered interrupt, this could cause an infinite interrupt storm since the line is unmasked on thread exit. Additionally, can aborting early here cause pending events to be permanently erased on resume?
Because the thread aborts without updating the software llq.prod index via queue_sync_prod_in(), the stale pointer will be written back to the hardware EVTQ_PROD register during arm_smmu_device_reset() on resume.

I tend to agree with the concern about the stale producer index. Should we call queue_sync_prod_in(&smmu->evtq.q) in arm_smmu_runtime_suspend() after disabling the event queue? Also, how about printing a warning and returning IRQ_HANDLED if arm_smmu_rpm_get_if_active(smmu) returns false here?

#35 lore raw

PATCH v9 12/12 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  | 171 ++++++++++++++++++
 drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c   |   1 +
 2 files changed, 172 insertions(+)
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3-test.c +171 -0
index add671363c82..2654bd497fd3 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,171 @@ static void arm_smmu_v3_invs_test(struct kunit *test)
 	kfree(test_b);
 }
 
+struct arm_smmu_mock_cmdq {
+	u32 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 u32 __iomem *)&mock->mock_prod_reg;
+	cmdq->q.cons_reg = (__force u32 __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 = 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(&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_delete_sync(&timer_ctx.timer);
+
+	/* Establish the post-storm prod_reg index */
+	stopped_prod = 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, 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, stopped_prod + 1, 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;
+}
+
+static void arm_smmu_v3_rpm_test_kthread_race(struct kunit *test)
+{
+	struct arm_smmu_test_kthread_context ctx = {0};
+	struct arm_smmu_device mock_smmu = smmu;
+	struct arm_smmu_mock_cmdq mock = {0};
+	struct task_struct *thread1, *thread2;
+	u32 stopped_prod;
+
+	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");
+	thread2 = kthread_run(arm_smmu_v3_test_kthread_worker, &ctx, "smmu_w2");
+	if (IS_ERR(thread1) || IS_ERR(thread2)) {
+		if (!IS_ERR(thread1))
+			kthread_stop(thread1);
+		if (!IS_ERR(thread2))
+			kthread_stop(thread2);
+		return;
+	}
+
+	usleep_range(1000, 2000);
+
+	/* Gate the CMDQ */
+	atomic_or(CMDQ_PROD_STOP_FLAG, &mock_smmu.cmdq.q.llq.atomic.prod);
+	stopped_prod = mock.mock_prod_reg;
+
+	usleep_range(1000, 2000);
+	KUNIT_EXPECT_EQ(test, stopped_prod, mock.mock_prod_reg);
+
+	/* Open the gate */
+	atomic_andnot(CMDQ_PROD_STOP_FLAG, &mock_smmu.cmdq.q.llq.atomic.prod);
+	usleep_range(1000, 2000);
+	KUNIT_EXPECT_NE(test, stopped_prod, mock.mock_prod_reg);
+
+	kthread_stop(thread1);
+	kthread_stop(thread2);
+	KUNIT_EXPECT_EQ(test, 0, 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 +966,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 97e7284fcfcc..9106ffb75f7a 100644
@@ -935,6 +935,7 @@ int __arm_smmu_cmdq_issue_cmdlist(struct arm_smmu_device *smmu,
 	local_irq_restore(flags);
 	return ret;
 }
+EXPORT_SYMBOL_IF_KUNIT(arm_smmu_cmdq_issue_cmdlist);
 
 bool arm_smmu_erratum_repeat_tlbi_cfgi(void)
 {
Signature · 1 line
2.55.0.487.gaf234c4eb3-goog
#36 lore raw
In reply to Pranjal Shrivastava
Quoted 6 lines · Pranjal Shrivastava

[v9]
- 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

Quoted 8 lines

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

There are alot of scary looking sashiko remarks, are you planning to resend this with some of them addressed?

Jason

#37 lore raw
Quoted 17 lines · Jason Gunthorpe
Quoted 6 lines · Pranjal Shrivastava

[v9]
- 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

Quoted 8 lines

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

Quoted 3 lines

There are alot of scary looking sashiko remarks, are you planning to resend this with some of them addressed?

Yes, I was first hoping to discuss them on the list! Thanks a lot for initiating that discussion :)

[BTW, I'm interested to know if you used some tool to pull in sashiko feedback in your replies, such a tool seems helpful!]

Thanks,
Praan

#38 lore raw
Quoted 22 lines · Pranjal Shrivastava
Quoted 17 lines · Jason Gunthorpe
Quoted 6 lines · Pranjal Shrivastava

[v9]
- 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

Quoted 8 lines

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

Quoted 3 lines

There are alot of scary looking sashiko remarks, are you planning to resend this with some of them addressed?

Quoted 5 lines

Yes, I was first hoping to discuss them on the list! Thanks a lot for initiating that discussion :)

[BTW, I'm interested to know if you used some tool to pull in sashiko feedback in your replies, such a tool seems helpful!]

I have been testing 'b4 review tui' to help my workflow. I have too many patches to review and I'm trying to move them all into b4 and out of my scattered mail boxes.

If you setup sashiko.dev integration:

[b4]
sashiko-url = https://sashiko.dev

Then when you load a series it just automagically shows the sashiko stuff (press f to expand them) and you can easially quote them when replying.

It can be a bit rough to ge there though, you have to get a series applied to make it to that screen, so eg, the whitespace damage here made that a pain.

However.. I had AI make an AI instruction for another AI to use AI to to automagically fix git am conflicts to get *something* so I can use the tool..

But I like that the patches end up applied on a check out branch and I can poke around with my editor too..

Jason

#39 lore raw
Quoted 46 lines · Jason Gunthorpe
Quoted 22 lines · Pranjal Shrivastava
Quoted 17 lines · Jason Gunthorpe
Quoted 6 lines · Pranjal Shrivastava

[v9]
- 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

Quoted 8 lines

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

Quoted 3 lines

There are alot of scary looking sashiko remarks, are you planning to resend this with some of them addressed?

Quoted 5 lines

Yes, I was first hoping to discuss them on the list! Thanks a lot for initiating that discussion :)

[BTW, I'm interested to know if you used some tool to pull in sashiko feedback in your replies, such a tool seems helpful!]

I have been testing 'b4 review tui' to help my workflow. I have too many patches to review and I'm trying to move them all into b4 and out of my scattered mail boxes.

If you setup sashiko.dev integration:

[b4]
sashiko-url = https://sashiko.dev

Then when you load a series it just automagically shows the sashiko stuff (press f to expand them) and you can easially quote them when replying.

It can be a bit rough to ge there though, you have to get a series applied to make it to that screen, so eg, the whitespace damage here made that a pain.

Quoted 7 lines

However.. I had AI make an AI instruction for another AI to use AI to to automagically fix git am conflicts to get *something* so I can use the tool..

But I like that the patches end up applied on a check out branch and I can poke around with my editor too..

Ack. That sounds interesting, I'll try it out! And sorry for the whitespace issue, the --fix-inplace is notorious,

Thanks for sharing this!
- Praan