Skip to contentSkip to conversation

Use the generic iommu page table for SMMUv3

PATCH In review Jason Gunthorpe 2 participants 28 messages Nov 15 – Dec 4

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

v3 cover Use the generic iommu page table for SMMUv3

[ This is the last series to move SMMUv3 over to the generic page
table. The whole branch is here:
https://github.com/jgunthorpe/linux/commits/iommu_pt_arm64/
]

Introduce the generic page table for what the ARM spec calls VMSAv8-64 (ie the long 64 bit PTE page table, io-pgtable-arm.c) and use it for SMMUv3. ARM is by far the most complex page table of all the ones implemented, it has the most runtime behavior variations and a lot of features.

Like the othe architectures, the page table itself is supported by a kunit compare test that runs operations through both io-pgtable-arm.c and the new code then checks for identical PTEs. This is on the github link above but I don't intend to merge it.

The existing kunit tests for iommupt will automatically cover the new format as well.

This is the final series migrating the SMMUv3 driver over to use the new functions and remove io-pgtable-arm.c usage. In principle the other iommu drivers that use io-pgtable-arm could be converted someday as well.

Included is a mitigation for the CONT under invalidation errata, extended to work with paging domains.

v3:
- Rebase on v7.4-rc2
- Split the armv8 patch into three parts, generic, db, and iommu
- Clarify some comments, mark some more debug things as WARN_ON
- Use tgsz instead of granule for consistency
- Refactor checks into armv8pt_validate_features() and add more
- Drop PT_FEAT_ARMV8_AARCH32
- Fix make dirty logic
- Use arch/arm64 constants instead of copying for SVA
- Mitigate the CONT under invalidation errata
- Pull in the left over two patches from v9 of the precursor series:

     https://patch.msgid.link/r/[email protected]

v2: https://patch.msgid.link/r/[email protected]
- Rename granule_lg2sz to tgsz_lg2 to represent the ARM translation granule
v1: https://patch.msgid.link/r/[email protected]

Jason Gunthorpe (13):
iommu/arm-smmu-v3: Change how the tlbi describes the invalidation iommu/arm-smmu-v3: Support the DS expansion of range invalidation
SCALE
iommupt: Remove the sanity check for pt_num_items_lg2() at the top
level
iommupt/kunit: Do not test INCOHERENT on anything but x86 iommupt/kunit: Skip test configs without supported features iommupt/armv8: Add the 64 bit ARMv8 page table format iommupt/armv8: Add DBM support
iommupt/armv8: Implement the iommu specific components iommu/arm-smmu-v3: Remove io-pgtable-arm from sva.c iommu/arm-smmu-v3: Move the DMA API comment to flush_iotlb_all iommu/arm-smmu-v3: Support CONT in paging domains with errata iommu/arm-smmu-v3: Use the generic iommu page table
iommu: Remove pgsize from iommu_iotlb_gather

 drivers/iommu/arm/Kconfig                     |    4 +-
 .../iommu/arm/arm-smmu-v3/arm-smmu-v3-sva.c   |   44 +-
 .../iommu/arm/arm-smmu-v3/arm-smmu-v3-test.c  |   49 +-
 drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c   |  609 ++++++----
 drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h   |   49 +-
 drivers/iommu/generic_pt/.kunitconfig         |    1 +
 drivers/iommu/generic_pt/Kconfig              |   12 +
 drivers/iommu/generic_pt/fmt/Makefile         |    2 +
 drivers/iommu/generic_pt/fmt/armv8.h          | 1076 +++++++++++++++++
 drivers/iommu/generic_pt/fmt/defs_armv8.h     |   23 +
 drivers/iommu/generic_pt/fmt/iommu_armv8.c    |   13 +
 drivers/iommu/generic_pt/iommu_pt.h           |   14 -
 drivers/iommu/generic_pt/kunit_iommu.h        |   27 +-
 include/linux/generic_pt/common.h             |   38 +
 include/linux/generic_pt/iommu.h              |   72 ++
 include/linux/iommu.h                         |   62 +-
 16 files changed, 1738 insertions(+), 357 deletions(-)
 create mode 100644 drivers/iommu/generic_pt/fmt/armv8.h
 create mode 100644 drivers/iommu/generic_pt/fmt/defs_armv8.h
 create mode 100644 drivers/iommu/generic_pt/fmt/iommu_armv8.c

base-commit: 7475ea8b58616b33c04afb976cf0fbaad9dd63fb

Signature · 1 line
2.43.0
#1 lore raw

PATCH v3 1/13 iommu/arm-smmu-v3: Change how the tlbi describes the invalidation

The range-invalidation logic has long had a FIXME that there is not enough information to properly compute the range invalidation. There is also subtly not enough information to properly compute the single stride either.

Change tlbi to use the information format that iommupt is going to use for ARM. This prepares the invalidation code to support iommupt and fixes two small limitations with the current code.

iommupt is designed to accumulate all invalidation into a single gather, then the iommu driver should issue a small number of commands to execute the gather to control invalidation latency. This is in contrast to io-pgtable-arm.c which generates many gather flushes and direct walk cache flushes as it progresses.

To accommodate this the gather will accumulate "damage" in bitmaps, one for leaf changes and one for table changes. This is enough information for SMMUv3 to compute the proper stride for single invalidation and to generate ideal hints for range invalidation.

Change the inner workings of the tlbi process to directly use this new-style gather description with the idea that the iommupt conversion will just direct assign the gather fields to the tlbi.

Rework the three places creating the tlbi to express their needs in terms of the new bitmaps.

1) Simple iotlb invalidation always gets a single range of leaf levels, so it can set a single leaf bit

2) Walk invalidation is expected to clear the table, child tables, and all the leaves it could contain. Set a range of table bits and all the leaf bits.

There is a weakness in the existing io-pgtable where it double invalidates the leaves, once through the arm_smmu_tlb_inv_walk() then again through the gather. Since these are separate operations they are not capped by the invalidation count limits and a single unmap may end up doing thousands of tlbi commands. Eventually converting to iommupt's gather only approach will correct this.

3) SVA invalidation has no idea what the MM did, so it will set all the bits in the bitmaps.

This corrects another weakness where the range-invalidation logic was generating hints assuming the #2 rules which isn't correct for SVA.

---
 .../iommu/arm/arm-smmu-v3/arm-smmu-v3-sva.c   |  29 ++-
 drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c   | 193 +++++++++++++-----
 drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h   |  25 ++-
 3 files changed, 188 insertions(+), 59 deletions(-)
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3-sva.c +23 -6
index faeec656da9e7f..fdc6cb7a128037 100644
@@ -140,17 +140,34 @@ static void arm_smmu_mm_arch_invalidate_secondary_tlbs(struct mmu_notifier *mn,
 {
 	struct arm_smmu_domain *smmu_domain =
 		container_of(mn, struct arm_smmu_domain, mmu_notifier);
+	u8 tgsz_lg2 = smmu_domain->tgsz_lg2;
 	struct arm_smmu_tlbi tlbi = {
 		.tgsz_lg2 = smmu_domain->tgsz_lg2,
-		.iova = start,
+		.start = start,
+		.last = end - 1,
 		/*
-		 * The mm_types defines vm_end as the first byte after the end
-		 * address, different from IOMMU subsystem using the last
-		 * address of an address range.
+		 * No information comes from the mm, assume the worst case that
+		 * it changed every table level. The way this is hooked into the
+		 * mm is tricky, the range won't be expanded to include an
+		 * entire table level if one was removed like the iommu gather
+		 * does. Thus even if this is a 4k invalidation it may be
+		 * including any table level too.
 		 */
-		.size = end - start,
-		.iopte_size = PAGE_SIZE,
+		.table_levels_bitmap = 0xfe,
 	};
+	u8 pmd_lg2sz = arm_smmu_pt_level_to_lg2sz(tgsz_lg2, 1);
+
+	/*
+	 * If the size is small then we can infer the invalidation is PTE only
+	 * and set the PTE level only. Otherwise it could be some other
+	 * combination so just set them all. This allows range invalidation to
+	 * use TTL=3 in cases of PTE only changes. The mm must not try to
+	 * partially invalidate pmd/etc.
+	 */
+	if (end - start < BIT_U64(pmd_lg2sz))
+		tlbi.leaf_levels_bitmap = 1;
+	else
+		tlbi.leaf_levels_bitmap = 0xff;
 
 	arm_smmu_domain_tlbi(&tlbi, smmu_domain);
 }
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +145 -48

297 lines not on this page · raw message

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h +20 -5
index bb048e08d613d3..b08c112875d3b6 100644
@@ -830,17 +830,30 @@ static inline unsigned int arm_smmu_pt_lg2sz_to_level(unsigned int tgsz_lg2,
 }
 
 struct arm_smmu_tlbi {
-	unsigned long iova;
-	size_t size;
-	/* page or block size of the leaf iopte */
-	unsigned int iopte_size;
+	unsigned long start;
+	unsigned long last;
 	/* Base Translation Granule of the page table */
 	u8 tgsz_lg2;
-	bool leaf_only;
+	/*
+	 * Level bitmaps use iommupt numbering: bit 0 is the leaf-only level
+	 * (ARM level 3), bit 1 is the next level up (ARM level 2), etc. These
+	 * match the iommu_iotlb_gather.pt fields. Each set bit indicates a
+	 * change at that level. The contiguous hint has no effect on
+	 * invalidation processing because HW can ignore the hint.
+	 *
+	 * The pair selects the invalidation scope:
+	 *   table!=0, leaf==0 : walk cache only
+	 *   table==0, leaf!=0 : leaves only
+	 *   table!=0, leaf!=0 : walk cache + all leaves
+	 *   table==0, leaf==0 : illegal
+	 */
+	u8 leaf_levels_bitmap;
+	u8 table_levels_bitmap;
 
 	struct {
 		bool use_full_inv;
 		u16 num;
+		u8 stride_lg2;
 	} single;
 
 	struct {
@@ -1213,6 +1226,8 @@ static inline void arm_smmu_domain_inv(struct arm_smmu_domain *smmu_domain)
 {
 	/* Prefilled for invalidate all */
 	struct arm_smmu_tlbi tlbi = {
+		.start = 0,
+		.last = ULONG_MAX,
 		.tgsz_lg2 = smmu_domain->tgsz_lg2,
 		.single.use_full_inv = true,
 		.range.use_full_inv = true,
Signature · 1 line
2.43.0
#2 lore raw

PATCH v3 2/13 iommu/arm-smmu-v3: Support the DS expansion of range invalidation SCALE

In reply to Jason Gunthorpe

If DS is supported then SCALE can go up to 39. Compute a scale max that is compatible for the entire invs list.

Replace the has_range_inv in the invs list with a 0 range_inv_scale_max to mean range invalidation is unavailable.

---
 .../iommu/arm/arm-smmu-v3/arm-smmu-v3-test.c  |  4 ++--
 drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c   | 22 ++++++++++++++-----
 drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h   |  5 +++--
 3 files changed, 22 insertions(+), 9 deletions(-)
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3-test.c +2 -2
index 5a4e45e1512589..3a0fef761daea8 100644
@@ -647,7 +647,7 @@ static void arm_smmu_v3_invs_test_verify(struct kunit *test,
 {
 	KUNIT_ASSERT_EQ(test, invs->num_invs, num_invs);
 	KUNIT_EXPECT_EQ(test, invs->num_trashes, num_trashes);
-	KUNIT_EXPECT_TRUE(test, invs->has_range_inv);
+	KUNIT_EXPECT_EQ(test, invs->range_inv_scale_max, 31);
 	KUNIT_EXPECT_TRUE(test, invs->has_full_cont_range_inv);
 	while (num_invs--) {
 		KUNIT_EXPECT_EQ(test, invs->inv[num_invs].id, ids[num_invs]);
@@ -715,7 +715,7 @@ static void arm_smmu_v3_invs_test(struct kunit *test)
 	test_a = arm_smmu_invs_alloc(0);
 	KUNIT_ASSERT_NOT_ERR_OR_NULL(test, test_a);
 	KUNIT_EXPECT_EQ(test, test_a->num_invs, 0);
-	KUNIT_EXPECT_FALSE(test, test_a->has_range_inv);
+	KUNIT_EXPECT_EQ(test, test_a->range_inv_scale_max, 0);
 	KUNIT_EXPECT_FALSE(test, test_a->has_full_cont_range_inv);
 
 	/* Test1: merge invs1 (new array) */
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +17 -5
index 54178af99c9407..294f9645cdc3db 100644
@@ -1065,9 +1065,19 @@ static void arm_smmu_invs_update_caps(struct arm_smmu_invs *invs,
 		invs->has_ats = true;
 
 	if (inv->smmu->features & ARM_SMMU_FEAT_RANGE_INV) {
-		invs->has_range_inv = true;
+		unsigned int scale_max;
+
 		if (inv->smmu->options & ARM_SMMU_OPT_FULL_CONT_RANGE_INV)
 			invs->has_full_cont_range_inv = true;
+
+		/*
+		 * SCALE increases to 6 bits when SMMU_IDR5.DS == 1, values
+		 * above 39 are treated as 39 (H.a 4.4.1.1)
+		 */
+		scale_max = (inv->smmu->features & ARM_SMMU_FEAT_DS) ? 39 : 31;
+		if (!invs->range_inv_scale_max ||
+		    scale_max < invs->range_inv_scale_max)
+			invs->range_inv_scale_max = scale_max;
 	}
 }
 
@@ -2659,7 +2669,8 @@ static unsigned int arm_smmu_compute_range_ttl(u8 leaf_bitmap, u8 table_bitmap,
  * CONT is covered by one command.
  */
 static void arm_smmu_tlbi_calc_range(struct arm_smmu_tlbi *tlbi,
-				     bool single_range_inv)
+				     bool single_range_inv,
+				     unsigned int scale_max)
 {
 	u8 tgsz_lg2 = tlbi->tgsz_lg2;
 	unsigned int ttl = arm_smmu_compute_range_ttl(
@@ -2681,7 +2692,7 @@ static void arm_smmu_tlbi_calc_range(struct arm_smmu_tlbi *tlbi,
 	 * address beyond alignment to tg (so long as TTL=0).
 	 */
 	first.scale = arm_smmu_range_inv_calc_scale(num_tg);
-	if (first.scale > 31) {
+	if (first.scale > scale_max) {
 		/* Range too large for a single command do full invalidation */
 		tlbi->range.use_full_inv = true;
 		return;
@@ -2952,12 +2963,13 @@ void arm_smmu_domain_tlbi(struct arm_smmu_tlbi *tlbi,
 	 * The invs generation ensures this matches the instances being
 	 * invalidated.
 	 */
-	if (invs->has_range_inv) {
+	if (invs->range_inv_scale_max) {
 		if (!tlbi->range.use_full_inv) {
 			arm_smmu_tlbi_calc_range(
 				tlbi,
 				smmu_domain->stage == ARM_SMMU_DOMAIN_SVA &&
-					invs->has_full_cont_range_inv);
+					invs->has_full_cont_range_inv,
+				invs->range_inv_scale_max);
 		}
 	}
 
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h +3 -2
index b08c112875d3b6..7106bd3a8bd7f6 100644
@@ -765,9 +765,10 @@ static inline bool arm_smmu_inv_is_ats(const struct arm_smmu_inv *inv)
  *               Must not be greater than @num_invs
  * @rwlock: optional rwlock to fence ATS operations
  * @has_ats: flag if the array contains an INV_TYPE_ATS or INV_TYPE_ATS_FULL
- * @has_range_inv: flag if any entry's SMMU supports range invalidation
  * @has_full_cont_range_inv: flag if any entry's SMMU requires the CONT range
  *                           invalidation workaround
+ * @range_inv_scale_max: max SCALE usable by all range-capable SMMUs, or 0 if
+ *                       no SMMU supports range invalidation
  * @rcu: rcu head for kfree_rcu()
  * @inv: flexible invalidation array
  *
@@ -797,8 +798,8 @@ struct arm_smmu_invs {
 	size_t num_trashes;
 	rwlock_t rwlock;
 	bool has_ats;
-	bool has_range_inv;
 	bool has_full_cont_range_inv;
+	u8 range_inv_scale_max;
 	struct rcu_head rcu;
 	struct arm_smmu_inv inv[] __counted_by(max_invs);
 };
Signature · 1 line
2.43.0
#3 lore raw

PATCH v3 3/13 iommupt: Remove the sanity check for pt_num_items_lg2() at the top level

In reply to Jason Gunthorpe

This was ill conceived, the existing formats work OK because they happen to support pt_num_items_lg2() at the topk level. However the documentation is clear that is not permitted because ARMv8 has concatenated top levels and we do not want to calculate an exact pt_num_items_lg2() for the top level special case.

The logic to compute the number of items of the top level is shown in pt_top_memsize_lg2() which is:

	num_items_lg2 = common->max_vasz_lg2 - pt_table_item_lg2sz(&pts);

Which is pointless to try and sanity check.

---
 drivers/iommu/generic_pt/iommu_pt.h | 14 --------------
 1 file changed, 14 deletions(-)
drivers/iommu/generic_pt/iommu_pt.h +0 -14
index 837d835e4fad8e..0360a02479e3f6 100644
@@ -1193,20 +1193,6 @@ static int pt_init_common(struct pt_common *common)
 		     PT_FORCE_ENABLED_FEATURES))
 		return -EOPNOTSUPP;
 
-	/*
-	 * Check if the top level of the page table is too small to hold the
-	 * specified maxvasz.
-	 */
-	if (!pt_feature(common, PT_FEAT_DYNAMIC_TOP) &&
-	    top_range.top_level != PT_MAX_TOP_LEVEL) {
-		struct pt_state pts = { .range = &top_range,
-					.level = top_range.top_level };
-
-		if (common->max_vasz_lg2 >
-		    pt_num_items_lg2(&pts) + pt_table_item_lg2sz(&pts))
-			return -EOPNOTSUPP;
-	}
-
 	if (common->max_oasz_lg2 == 0)
 		common->max_oasz_lg2 = pt_max_oa_lg2(common);
 	else
Signature · 1 line
2.43.0
Reviewed-by on v3 3/13
#4 lore raw

Re: [PATCH v3 03/13] iommupt: Remove the sanity check for pt_num_items_lg2() at the top level

Quoted 2 lines · Jason Gunthorpe

This was ill conceived, the existing formats work OK because they happen to support pt_num_items_lg2() at the topk level. However the

"topk level" reads like a typo?

Quoted 7 lines

documentation is clear that is not permitted because ARMv8 has concatenated top levels and we do not want to calculate an exact pt_num_items_lg2() for the top level special case.

The logic to compute the number of items of the top level is shown in pt_top_memsize_lg2() which is:

Quoted 7 lines
	num_items_lg2 = common->max_vasz_lg2 - pt_table_item_lg2sz(&pts);

Which is pointless to try and sanity check.

#5 lore raw

PATCH v3 4/13 iommupt/kunit: Do not test INCOHERENT on anything but x86

In reply to Jason Gunthorpe

The use of the dma API on other arches inside iommu-pages can blow up with the fake struct device that kunit creates and result in crashes. x86 uses a direct arch cache flush function so doesn't have any restriction.

---
 drivers/iommu/generic_pt/kunit_iommu.h | 17 +++++++++++++++--
 1 file changed, 15 insertions(+), 2 deletions(-)
drivers/iommu/generic_pt/kunit_iommu.h +15 -2
index 22c9e4c4dd97cd..79d7f9c8e7868f 100644
@@ -16,6 +16,19 @@
 int pt_iommu_init(struct pt_iommu_table *fmt_table,
 		  const struct pt_iommu_table_cfg *cfg, gfp_t gfp);
 
+/*
+ * iommu_pages_flush_incoherent() uses clflush directly on x86 but falls back to
+ * dma_sync_single_for_device() elsewhere, which needs a real DMA device. The
+ * kunit's dummy_dev is a kunit_device_register() stub and cannot service the
+ * DMA API, so skip this feature in kunit on non-x86.
+ */
+#if IS_ENABLED(CONFIG_X86)
+#define KUNIT_PT_SUPPORTED_FEATURES PT_SUPPORTED_FEATURES
+#else
+#define KUNIT_PT_SUPPORTED_FEATURES \
+	(PT_SUPPORTED_FEATURES & ~BIT(PT_FEAT_DMA_INCOHERENT))
+#endif
+
 /* The format can provide a list of configurations it would like to test */
 #ifdef kunit_fmt_cfgs
 static const void *kunit_pt_gen_params_cfg(struct kunit *test, const void *prev,
@@ -125,10 +138,10 @@ static int pt_kunit_priv_init(struct kunit *test, struct kunit_iommu_priv *priv)
 	 * The format can set a list of features that the kunit_fmt_cfgs
 	 * controls, other features are default to on.
 	 */
-	priv->cfg.common.features |= PT_SUPPORTED_FEATURES &
+	priv->cfg.common.features |= KUNIT_PT_SUPPORTED_FEATURES &
 				     (~KUNIT_FMT_FEATURES);
 #else
-	priv->cfg.common.features = PT_SUPPORTED_FEATURES;
+	priv->cfg.common.features = KUNIT_PT_SUPPORTED_FEATURES;
 #endif
 
 	/* Defaults, for the kunit */
Signature · 1 line
2.43.0
Reviewed-by on v3 4/13
#6 lore raw

Re: [PATCH v3 04/13] iommupt/kunit: Do not test INCOHERENT on anything but x86

Quoted 6 lines · Jason Gunthorpe

The use of the dma API on other arches inside iommu-pages can blow up with the fake struct device that kunit creates and result in crashes. x86 uses a direct arch cache flush function so doesn't have any restriction.

#7 lore raw

PATCH v3 5/13 iommupt/kunit: Skip test configs without supported features

In reply to Jason Gunthorpe

Some of the tests configs can test features we don't currently enable, like TTBR1 on ARMv8. Instead of blowing up, skip the test. When CONFIG_DEBUG_GENERIC_PT is set all features are force enabled during the build so everything can be tested. That is the normal mode for the kunit.py runner.

---
 drivers/iommu/generic_pt/kunit_iommu.h | 10 ++++++++++
 1 file changed, 10 insertions(+)
drivers/iommu/generic_pt/kunit_iommu.h +10 -0
index 79d7f9c8e7868f..558e161eacb05f 100644
@@ -134,6 +134,16 @@ static int pt_kunit_priv_init(struct kunit *test, struct kunit_iommu_priv *priv)
 
 #ifdef kunit_fmt_cfgs
 	priv->cfg = kunit_fmt_cfgs[((uintptr_t)test->param_value) - 1];
+	/*
+	 * Without CONFIG_DEBUG_GENERIC_PT only the format's compiled-in
+	 * PT_SUPPORTED_FEATURES are available, so cfgs requesting bits outside
+	 * that set cannot be tested.
+	 */
+	if (priv->cfg.common.features & ~KUNIT_PT_SUPPORTED_FEATURES)
+		kunit_skip(
+			test,
+			"cfg requires features not built into this format (enable CONFIG_DEBUG_GENERIC_PT)");
+
 	/*
 	 * The format can set a list of features that the kunit_fmt_cfgs
 	 * controls, other features are default to on.
Signature · 1 line
2.43.0
#8 lore raw

Re: [PATCH v3 05/13] iommupt/kunit: Skip test configs without supported features

Quoted 19 lines · Jason Gunthorpe

Some of the tests configs can test features we don't currently enable, like TTBR1 on ARMv8. Instead of blowing up, skip the test. When CONFIG_DEBUG_GENERIC_PT is set all features are force enabled during the build so everything can be tested. That is the normal mode for the kunit.py runner.

---
 drivers/iommu/generic_pt/kunit_iommu.h | 10 ++++++++++
 1 file changed, 10 insertions(+)
drivers/iommu/generic_pt/kunit_iommu.h +0 -0
index 79d7f9c8e7868f..558e161eacb05f 100644
@@ -134,6 +134,16 @@ static int pt_kunit_priv_init(struct kunit *test, struct kunit_iommu_priv *priv)
 
 #ifdef kunit_fmt_cfgs

drivers/iommu/generic_pt/kunit_iommu.h static int pt_kunit_priv_init(struct kunit *test, struct kunit_iommu_priv *priv) · line 145

Quoted 10 lines
drivers/iommu/generic_pt/kunit_iommu.h +9 -0
 	priv->cfg = kunit_fmt_cfgs[((uintptr_t)test->param_value) - 1];
+	/*
+	 * Without CONFIG_DEBUG_GENERIC_PT only the format's compiled-in
+	 * PT_SUPPORTED_FEATURES are available, so cfgs requesting bits outside
+	 * that set cannot be tested.
+	 */
+	if (priv->cfg.common.features & ~KUNIT_PT_SUPPORTED_FEATURES)
+		kunit_skip(
+			test,
+			"cfg requires features not built into this format (enable CONFIG_DEBUG_GENERIC_PT)");

The patch looks fine.

But I tried iommu_pt_kunit_test on Grace with CONFIG_PAGE_SIZE_64KB and got this assertion:

------------------------------------------------------------
KTAP version 1
1..6
KTAP version 1
# Subtest: amdv1_mock_iommu_test
# module: kunit_iommu_mock
1..7
KTAP version 1
# Subtest: test_increase_level
ok 1 amdv1_mock_cfg_0
ok 2 amdv1_mock_cfg_1 # SKIP max_vasz_lg2 fits in starting level, no growth possible
# test_increase_level: pass:1 fail:0 skip:1 total:2
ok 1 test_increase_level
KTAP version 1
# Subtest: test_map_simple
ok 1 amdv1_mock_cfg_0
ok 2 amdv1_mock_cfg_1
# test_map_simple: pass:2 fail:0 skip:0 total:2
ok 2 test_map_simple
KTAP version 1
# Subtest: test_map_table_to_oa
# test_map_table_to_oa: Test should be marked slow (runtime: 4.997639265s)
# test_map_table_to_oa: ASSERTION FAILED at drivers/iommu/generic_pt/fmt/../kunit_iommu_pt.h:473
Expected priv->orig_nr_secondary_pagetable == global_node_page_state(NR_SECONDARY_PAGETABLE), but
priv->orig_nr_secondary_pagetable == 157 (0x9d) global_node_page_state(NR_SECONDARY_PAGETABLE) == 174 (0xae)
# test_map_table_to_oa: test aborted during cleanup. continuing without cleaning up
[...and all other tests continued but all failed...]
------------------------------------------------------------

I asked AI to fix the issue, and it came up with a patch (attached). I wonder if it makes sense to you.

Nicolin

From c7e0332ce5c2854e4ff23ac7cb024ad837d11986 Mon Sep 17 00:00:00 2001
From: Nicolin Chen <[email protected]>
Date: Tue, 24 Nov 2026 04:41:11 +0000
Subject: [PATCH] iommupt/kunit: Include per-CPU deltas in the leak check

The leak check reads NR_SECONDARY_PAGETABLE with global_node_page_state(). That only returns the global counter. Each CPU also keeps a small delta of page updates that is folded into the global counter only after it exceeds a threshold. So the value can be off by a few pages without any leak.

On an arm64 KVM guest with 64 KiB pages, test_map_simple frees every page but still sees 5 extra pages. The assertion fails in the exit callback and aborts the cleanup. Then the dummy device stays registered, and every later test case fails to init with -EBUSY.

Add pt_kunit_nr_secondary_pagetable(). It adds the per-CPU deltas of every node to the global counter. Use it for both the initial and the final read. The result is still a best-effort snapshot, because a concurrent fold can move a delta from a CPU to the global counter between the two reads.

Also change the assertion into an expectation. A mismatch still fails the test case, but the exit callback now finishes its cleanup. So a mismatch no longer breaks the test cases that run after it.

Fixes bc5233c0904e ("iommupt: Add a kunit test for the IOMMU implementation")
---
 drivers/iommu/generic_pt/kunit_iommu.h    |  2 +-
 drivers/iommu/generic_pt/kunit_iommu_pt.h | 29 +++++++++++++++++++----
 2 files changed, 26 insertions(+), 5 deletions(-)
drivers/iommu/generic_pt/kunit_iommu.h +1 -1
index 558e161eacb05..3c098be0d8f3f 100644
@@ -84,7 +84,7 @@ struct kunit_iommu_priv {
 	unsigned int largest_pgsz_lg2;
 	pt_oaddr_t test_oa;
 	pt_vaddr_t safe_pgsize_bitmap;
-	unsigned long orig_nr_secondary_pagetable;
+	long orig_nr_secondary_pagetable;
 
 };
 PT_IOMMU_CHECK_DOMAIN(struct kunit_iommu_priv, fmt_table.iommu, domain);
drivers/iommu/generic_pt/kunit_iommu_pt.h +25 -4
index 9fc71db74234d..29b882dd5b0ed 100644
@@ -438,6 +438,28 @@ static struct kunit_case iommu_test_cases[] = {
 	{},
 };
 
+/*
+ * global_node_page_state() only reads the global counter. Each CPU also keeps
+ * a small delta that might not be folded into the global counter yet. Add the
+ * deltas of every CPU on every node to get a closer count. This is still just
+ * a best-effort snapshot. A concurrent fold can move a delta between the reads.
+ */
+static long pt_kunit_nr_secondary_pagetable(void)
+{
+	const enum node_stat_item item = NR_SECONDARY_PAGETABLE;
+	long nr = atomic_long_read(&vm_node_stat[item]);
+	int nid, cpu;
+
+	for_each_online_node(nid) {
+		struct per_cpu_nodestat __percpu *stats =
+			NODE_DATA(nid)->per_cpu_nodestats;
+
+		for_each_online_cpu(cpu)
+			nr += per_cpu_ptr(stats, cpu)->vm_node_stat_diff[item];
+	}
+	return nr;
+}
+
 static int pt_kunit_iommu_init(struct kunit *test)
 {
 	struct kunit_iommu_priv *priv;
@@ -447,8 +469,7 @@ static int pt_kunit_iommu_init(struct kunit *test)
 	if (!priv)
 		return -ENOMEM;
 
-	priv->orig_nr_secondary_pagetable =
-		global_node_page_state(NR_SECONDARY_PAGETABLE);
+	priv->orig_nr_secondary_pagetable = pt_kunit_nr_secondary_pagetable();
 	ret = pt_kunit_priv_init(test, priv);
 	if (ret) {
 		kunit_kfree(test, priv);
@@ -470,8 +491,8 @@ static void pt_kunit_iommu_exit(struct kunit *test)
 	 * Look for memory leaks, assumes kunit is running isolated and nothing
 	 * else is using secondary page tables.
 	 */
-	KUNIT_ASSERT_EQ(test, priv->orig_nr_secondary_pagetable,
-			global_node_page_state(NR_SECONDARY_PAGETABLE));
+	KUNIT_EXPECT_EQ(test, priv->orig_nr_secondary_pagetable,
+			pt_kunit_nr_secondary_pagetable());
 	kunit_kfree(test, test->priv);
 }
 
Signature · 1 line
2.43.0
#9 lore raw

Re: [PATCH v3 05/13] iommupt/kunit: Skip test configs without supported features

Quoted 4 lines · Nicolin Chen

The leak check reads NR_SECONDARY_PAGETABLE with global_node_page_state(). That only returns the global counter. Each CPU also keeps a small delta of page updates that is folded into the global counter only after it exceeds a threshold. So the value can be off by a few pages without any leak.

There is a patch already in my tree to deal with this, this test only works when you use the kunit runner

Thanks,
Jason

#10 lore raw

Re: [PATCH v3 05/13] iommupt/kunit: Skip test configs without supported features

Quoted 9 lines · Jason Gunthorpe
Quoted 4 lines · Nicolin Chen

The leak check reads NR_SECONDARY_PAGETABLE with global_node_page_state(). That only returns the global counter. Each CPU also keeps a small delta of page updates that is folded into the global counter only after it exceeds a threshold. So the value can be off by a few pages without any leak.

There is a patch already in my tree to deal with this, this test only works when you use the kunit runner

6e8127719449e kunit: tool: catch warnings generated by the kernel

You mean this one? It doesn't fix the leak-check failure though.

The test can pass with a UML runner but fails running with arm64:

  $ ./tools/testing/kunit/kunit.py run \
        --kunitconfig=drivers/iommu/generic_pt
  Testing complete. Ran 482 tests: passed: 426, skipped: 56
  $ ./tools/testing/kunit/kunit.py run --arch=arm64 \
        --kunitconfig=drivers/iommu/generic_pt
  Testing complete. Ran 482 tests: passed: 3, failed: 478, skipped: 1

It's likely because UML has CONFIG_SMP=n, so global_node_page_state() is good enough.

If the test is supposed to run with the UML only, let's ignore the other case then.

Nicolin

#11 lore raw

Re: [PATCH v3 05/13] iommupt/kunit: Skip test configs without supported features

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

The leak check reads NR_SECONDARY_PAGETABLE with global_node_page_state(). That only returns the global counter. Each CPU also keeps a small delta of page updates that is folded into the global counter only after it exceeds a threshold. So the value can be off by a few pages without any leak.

Quoted 6 lines
Quoted 2 lines

There is a patch already in my tree to deal with this, this test only works when you use the kunit runner

6e8127719449e kunit: tool: catch warnings generated by the kernel

You mean this one? It doesn't fix the leak-check failure though.

Sorry, not my tree, Joerg picked it up:

https://git.kernel.org/pub/scm/linux/kernel/git/iommu/linux.git/commit/?id=d2eba9f4fa6319eac08608958d4f3a11d5240002

Jason

#12 lore raw

Re: [PATCH v3 05/13] iommupt/kunit: Skip test configs without supported features

Quoted 12 lines · Jason Gunthorpe
Quoted 11 lines · Nicolin Chen
Quoted 9 lines · Jason Gunthorpe
Quoted 4 lines · Nicolin Chen

The leak check reads NR_SECONDARY_PAGETABLE with global_node_page_state(). That only returns the global counter. Each CPU also keeps a small delta of page updates that is folded into the global counter only after it exceeds a threshold. So the value can be off by a few pages without any leak.

There is a patch already in my tree to deal with this, this test only works when you use the kunit runner

Quoted 7 lines
Quoted 3 lines

6e8127719449e kunit: tool: catch warnings generated by the kernel

You mean this one? It doesn't fix the leak-check failure though.

Sorry, not my tree, Joerg picked it up:

https://git.kernel.org/pub/scm/linux/kernel/git/iommu/linux.git/commit/?id=d2eba9f4fa6319eac08608958d4f3a11d5240002

That one works. Kunit runs fine with it.

Thanks
Nicolin

Reviewed-by on v3 5/13
#13 lore raw

Re: [PATCH v3 05/13] iommupt/kunit: Skip test configs without supported features

In reply to Jason Gunthorpe
Quoted 8 lines · Jason Gunthorpe

Some of the tests configs can test features we don't currently enable, like TTBR1 on ARMv8. Instead of blowing up, skip the test. When CONFIG_DEBUG_GENERIC_PT is set all features are force enabled during the build so everything can be tested. That is the normal mode for the kunit.py runner.

#14 lore raw

PATCH v3 6/13 iommupt/armv8: Add the 64 bit ARMv8 page table format

In reply to Jason Gunthorpe

The features, format and naming is taking from the ARMv8 VMSAv8-64 chapter. By far ARMv8 is the most complex format supported by generic page table, with the largest number of options and configurations.

ARMv8 uses almost all the features of the common implementation:

- Contiguous pages
- Leaf pages at many levels
- Variable starting top level
- Variable size top level supporting concatenated tables with a high order top table allocation
- Dirty tracking
- Low (TTB0) or high (TTB1) starting VA
- Software bits

Compared to the io-pgtable version this also implements the contiguous page hint, and supports dirty readback from the S2. It always will use S2 concatenation to avoid a table walk instead of only using it when required by the spec. This closer to the original io-pgtable version which tried to use it sometime when not mandatory. The cost is an increased case of high order allocations for the table top. When a S1 is supported by HW only VFIO creates S2s so a high order allocation failure is OK. If S2 is only supported then the iommu core will perform the S2's table top allocations during early boot, and that is OK too.

iommupt's incoherent flushing algorithm was modeled after the ARM io-pgtable version so there is no change here.

Additionaly it includes implementations for the LPA, LVA, and LPA2 features however they will be compiled off for the iommu build until a driver actually needs thems. With these features it can support the "level -1" to produce a 5 level table similar to x86, as well as all the different placements of OA bits defined by the spec.

This is supported by a compare test that creates parallel iommupt and io-pgtable instances with matching parameters and validates that every tree level is the "same" across several meaningful tests. It covers the S2 concatenated pages, the recent bugs found in the io-pgtable logic and a range of VA sizes.

Add the generic page table API component and generic definitions for ARMv8.

---
 drivers/iommu/generic_pt/fmt/armv8.h      | 485 ++++++++++++++++++++++
 drivers/iommu/generic_pt/fmt/defs_armv8.h |  23 +
 include/linux/generic_pt/common.h         |  36 ++
 3 files changed, 544 insertions(+)
 create mode 100644 drivers/iommu/generic_pt/fmt/armv8.h
 create mode 100644 drivers/iommu/generic_pt/fmt/defs_armv8.h
drivers/iommu/generic_pt/fmt/armv8.h new file +485 -0
new file mode 100644
index 00000000000000..68fedda41fc198
@@ -0,0 +1,485 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+/*
+ * Copyright (c) 2024-2026, NVIDIA CORPORATION & AFFILIATES
+ *
+ * The page table format described by ARM DDI 0487 L.b, Chapter D8
+ * "The AArch64 Virtual Memory System Architecture" (VMSAv8-64).
+ * With the right cfg this will also implement the VMSAv8-32 Long
+ * Descriptor format.
+ *
+ * This was called io-pgtable-arm.c and ARM_xx_LPAE_Sx.
+ *
+ * NOTE! The level numbering is consistent with the Generic Page Table API, but
+ * is reversed from what the ARM documents use.
+ *
+ *   generic_pt | ARM | 4K TG          | 16K TG        | 64K TG
+ *   -----------+-----+----------------+---------------+----------------
+ *   0          |   3 | 4KB (64KB)     | 16KB (2MB)    | 64KB (2MB)
+ *   1          |   2 | 2MB (32MB)     | 32MB (1GB)    | 512MB (16GB)
+ *   2          |   1 | 1GB (16GB)     | 64GB       NL2| 4TB (128TB) NL1
+ *   3          |   0 | 512GB (8TB) NL2| 128TB      NL | -
+ *   4          |  -1 | 256TB       NL | -             | -
+ * Supported contiguous size in brackets. NL = no leaf, this level can only
+ * be a table, never a block/page descriptor (see armv8pt_can_have_leaf()):
+ *   NL  = never a leaf, regardless of features
+ *   NL1 = leaf only with FEAT_LPA and not FEAT_LPA2, otherwise NL
+ *   NL2 = leaf only with FEAT_LPA2, otherwise NL
+ */
+#ifndef __GENERIC_PT_FMT_ARMV8_H
+#define __GENERIC_PT_FMT_ARMV8_H
+
+#include "defs_armv8.h"
+#include "../pt_defs.h"
+
+#include <asm/page.h>
+#include <linux/bitfield.h>
+#include <linux/bits.h>
+#include <linux/container_of.h>
+#include <linux/errno.h>
+#include <linux/limits.h>
+#include <linux/sizes.h>
+#include <linux/string.h>
+
+/*
+ * Aid for understanding how the spec numerology relates to the code. Note the
+ * expression "level > ARMLx" means any ARMLy such that level < x
+ */
+enum {
+	ARML3 = 0,
+	ARML2 = 1,
+	ARML1 = 2,
+	ARML0 = 3,
+	ARMLn1 = 4,
+};
+
+enum {
+	PT_MAX_TOP_LEVEL = PT_SUPPORTED_FEATURE(PT_FEAT_ARMV8_LPA2) ? ARMLn1 :
+								      ARML0,
+	PT_ITEM_WORD_SIZE = sizeof(u64),
+};
+
+enum {
+	PT_MAX_OUTPUT_ADDRESS_LG2 =
+		(PT_SUPPORTED_FEATURE(PT_FEAT_ARMV8_LPA2) |
+		 PT_SUPPORTED_FEATURE(PT_FEAT_ARMV8_LPA)) ? 52 : 48,
+	/* See armv8pt_iommu_fmt_init() */
+	PT_MAX_VA_ADDRESS_LG2 =
+		(PT_SUPPORTED_FEATURE(PT_FEAT_ARMV8_LPA2) |
+		 PT_SUPPORTED_FEATURE(PT_FEAT_ARMV8_LVA) |
+		 PT_SUPPORTED_FEATURE(PT_FEAT_ARMV8_LPA)) ? 52 : 48,
+
+	/*
+	 * D24.2.195 TTBR_ELx BADDR:
+	 *
+	 * Bits A[(x-1):0] of the stage 1 translation table base address are
+	 * zero. Address bit x is the minimum address bit required to align the
+	 * translation table to the size of the table. x is calculated based on
+	 * LOG2(StartTableSize), as described in VMSAv9-128. The smallest
+	 * permitted value of x is 5.
+	 *
+	 * R_KBLCR requires the table to be aligned to its own size.
+	 *
+	 * SMMU S2TTB additionally says: In addition, a 64-byte minimum
+	 * alignment on starting-level translation table addresses is imposed
+	 * when S2TG selects 64KB granules and the effective S2PS value
+	 * indicates 52-bit output. In this case bits [5:0] are treated as zero.
+	 */
+	PT_TOP_PHYS_MASK = GENMASK_ULL(51, 5),
+};
+
+/* Common PTE bits */
+enum {
+	ARMV8PT_FMT_VALID = BIT(0),
+	ARMV8PT_FMT_PAGE = BIT(1),
+	ARMV8PT_FMT_TABLE = BIT(1),
+	ARMV8PT_FMT_NS = BIT(5),
+	ARMV8PT_FMT_SH = GENMASK(9, 8),
+	ARMV8PT_FMT_AF = BIT(10),
+
+	/* 64K FEAT_LPA: OA[51:48] in bits[15:12], Figures D8-14/15 */
+	ARMV8PT_FMT_OA52_LPA = GENMASK_ULL(15, 12),
+	/* 4K/16K FEAT_LPA2 (DS=1): OA[51:50] in bits[9:8], Figures D8-14/15 */
+	ARMV8PT_FMT_OA52_LPA2 = GENMASK_ULL(9, 8),
+
+	ARMV8PT_FMT_CONTIG = BIT_ULL(52),
+	ARMV8PT_FMT_UXN = BIT_ULL(53),
+	ARMV8PT_FMT_PXN = BIT_ULL(54),
+	ARMV8PT_FMT_NSTABLE = BIT_ULL(63),
+};
+
+/* S1 PTE bits */
+enum {
+	ARMV8PT_FMT_ATTRINDX = GENMASK(4, 2),
+	ARMV8PT_FMT_AP = GENMASK(7, 6),
+	ARMV8PT_FMT_nG = BIT(11),
+};
+
+enum {
+	ARMV8PT_SH_IS = 3,
+	ARMV8PT_SH_OS = 2,
+
+	ARMV8PT_RGN_NC = 0,
+	ARMV8PT_RGN_WBWA = 1,
+
+	ARMV8PT_AP_UNPRIV = 1,
+	ARMV8PT_AP_RDONLY = 2,
+};
+
+enum {
+	ARMV8PT_MAIR_ITEM = GENMASK_U32(7, 0),
+
+	ARMV8PT_MAIR_ATTR_IDX_NC = 0,
+	ARMV8PT_MAIR_ATTR_IDX_CACHE = 1,
+	ARMV8PT_MAIR_ATTR_IDX_DEV = 2,
+	ARMV8PT_MAIR_ATTR_IDX_INC_OCACHE = 3,
+
+	ARMV8PT_MAIR_ATTR_NC = 0x44,
+	ARMV8PT_MAIR_ATTR_WBRWA = 0xff,
+	ARMV8PT_MAIR_ATTR_DEVICE = 0x04,
+	ARMV8PT_MAIR_ATTR_INC_OWBRWA = 0xf4,
+};
+
+/* S2 PTE bits */
+enum {
+	ARMV8PT_FMT_S2MEMATTR = GENMASK(5, 2),
+	ARMV8PT_FMT_S2AP = GENMASK(7, 6),
+};
+
+enum {
+	SZLG2_4K = 12,
+	SZLG2_16K = 14,
+	SZLG2_64K = 16,
+};
+
+enum {
+	/*
+	 * For !S2FWB these code to:
+	 *  1111 = Normal outer write back cacheable / Inner Write Back Cacheable
+	 *         Permit S1 to override
+	 *  0101 = Normal Non-cachable / Inner Non-cachable
+	 *  0001 = Device / Device-nGnRE
+	 * For S2FWB these code to:
+	 *  0110 Force Normal Write Back
+	 *  0101 Normal* is forced Normal-NC, Device unchanged
+	 *  0001 Force Device-nGnRE
+	 */
+	ARMV8PT_MEMATTR_FWB_WB = 6,
+	ARMV8PT_MEMATTR_OIWB = 0xf,
+	ARMV8PT_MEMATTR_NC = 5,
+	ARMV8PT_MEMATTR_DEV = 1,
+
+	ARMV8PT_S2AP_READ = 1,
+	ARMV8PT_S2AP_WRITE = 2,
+};
+
+#define common_to_armv8pt(common_ptr) \
+	container_of_const(common_ptr, struct pt_armv8, common)
+#define to_armv8pt(pts) common_to_armv8pt((pts)->range->common)
+
+/* Runtime granule accessors */
+static inline u8 armv8pt_tgsz_lg2(const struct pt_state *pts)
+{
+	return to_armv8pt(pts)->tgsz_lg2;
+}
+
+static inline u64 armv8pt_fmt_oa48(unsigned int tgsz_lg2)
+{
+	return GENMASK_ULL(47, tgsz_lg2);
+}
+
+/*
+ * The generic implementations cannot be used if PT_GRANULE_LG2SZ is dynamic.
+ */
+static inline unsigned int armv8pt_table_item_lg2sz(const struct pt_state *pts)
+{
+	unsigned int tgsz_lg2 = armv8pt_tgsz_lg2(pts);
+
+	return tgsz_lg2 + (tgsz_lg2 - ilog2(PT_ITEM_WORD_SIZE)) * pts->level;
+}
+#define pt_table_item_lg2sz armv8pt_table_item_lg2sz
+
+static inline unsigned int armv8pt_pgsz_lg2_to_level(struct pt_common *common,
+						     unsigned int pgsize_lg2)
+{
+	unsigned int tgsz_lg2 = common_to_armv8pt(common)->tgsz_lg2;
+
+	return (pgsize_lg2 - tgsz_lg2) / (tgsz_lg2 - ilog2(sizeof(u64)));
+}
+#define pt_pgsz_lg2_to_level armv8pt_pgsz_lg2_to_level
+
+static inline bool armv8pt_has_system_page_size(const struct pt_common *common)
+{
+	return common_to_armv8pt(common)->tgsz_lg2 == PAGE_SHIFT;
+}
+#define pt_has_system_page_size armv8pt_has_system_page_size
+
+static inline pt_oaddr_t armv8pt_oa(const struct pt_state *pts)
+{
+	unsigned int tgsz_lg2 = armv8pt_tgsz_lg2(pts);
+	u64 entry = pts->entry;
+	pt_oaddr_t oa;
+
+	if (pts_feature(pts, PT_FEAT_ARMV8_LPA2)) {
+		/* 4K/16K with DS=1: OA[49:granule] direct, OA[51:50] in [9:8] */
+		oa = entry & GENMASK_ULL(49, tgsz_lg2);
+		oa |= ((pt_oaddr_t)FIELD_GET(ARMV8PT_FMT_OA52_LPA2, entry))
+		      << 50;
+	} else {
+		oa = entry & GENMASK_ULL(47, tgsz_lg2);
+		if (PT_SUPPORTED_FEATURE(PT_FEAT_ARMV8_LPA) &&
+		    tgsz_lg2 == SZLG2_64K)
+			oa |= ((pt_oaddr_t)FIELD_GET(ARMV8PT_FMT_OA52_LPA,
+						     entry))
+			      << 48;
+	}
+	return oa;
+}
+
+static inline pt_oaddr_t armv8pt_table_pa(const struct pt_state *pts)
+{
+	return armv8pt_oa(pts);
+}
+#define pt_table_pa armv8pt_table_pa
+
+/*
+ * Return a block or page entry pointing at a physical address. Returns the
+ * address adjusted for the item in a contiguous case.
+ */
+static inline pt_oaddr_t armv8pt_item_oa(const struct pt_state *pts)
+{
+	return armv8pt_oa(pts);
+}
+#define pt_item_oa armv8pt_item_oa
+
+static inline bool armv8pt_can_have_leaf(const struct pt_state *pts)
+{
+	unsigned int tgsz_lg2 = armv8pt_tgsz_lg2(pts);
+
+	/*
+	 * Tables D8-16/17 (4K), D8-26/27 (16K), D8-35/36 (64K).
+	 *
+	 * When FEAT_LPA2, one additional level gains block descriptors:
+	 *   4K:  ARM level 0 (pt 3) gains 512GB blocks
+	 *   16K: ARM level 1 (pt 2) gains 64GB blocks
+	 * ARM Level -1 (pt 4) is always table-only.
+	 */
+	if (pts_feature(pts, PT_FEAT_ARMV8_LPA2)) {
+		if (tgsz_lg2 == SZLG2_4K && pts->level > ARML0)
+			return false;
+		if (tgsz_lg2 == SZLG2_16K && pts->level > ARML1)
+			return false;
+		if (tgsz_lg2 == SZLG2_64K && pts->level > ARML2)
+			return false;
+	} else {
+		if (tgsz_lg2 == SZLG2_4K && pts->level > ARML1)
+			return false;
+		if (tgsz_lg2 == SZLG2_16K && pts->level > ARML2)
+			return false;
+		if (tgsz_lg2 == SZLG2_64K &&
+		    pts->level > (pts_feature(pts, PT_FEAT_ARMV8_LPA) ? ARML1 :
+									ARML2))
+			return false;
+	}
+	return true;
+}
+#define pt_can_have_leaf armv8pt_can_have_leaf
+
+/* Number contiguous entries that ARMV8PT_FMT_CONTIG will join at this level */
+static inline unsigned short
+armv8pt_contig_count_lg2(const struct pt_state *pts)
+{
+	unsigned int tgsz_lg2 = armv8pt_tgsz_lg2(pts);
+
+	if (tgsz_lg2 == SZLG2_4K)
+		return ilog2(16); /* 64KB, 32MB, 16GB, 8TB */
+	else if (tgsz_lg2 == SZLG2_16K && pts->level == ARML2)
+		return ilog2(32); /* 1GB */
+	else if (tgsz_lg2 == SZLG2_16K && pts->level == ARML3)
+		return ilog2(128); /* 2MB */
+	else if (tgsz_lg2 == SZLG2_64K)
+		return ilog2(32); /* 2MB, 16GB, 128TB */
+	return ilog2(1);
+}
+#define pt_contig_count_lg2 armv8pt_contig_count_lg2
+
+static inline unsigned int
+armv8pt_entry_num_contig_lg2(const struct pt_state *pts)
+{
+	if (pts->entry & ARMV8PT_FMT_CONTIG)
+		return armv8pt_contig_count_lg2(pts);
+	return ilog2(1);
+}
+#define pt_entry_num_contig_lg2 armv8pt_entry_num_contig_lg2
+
+static inline pt_vaddr_t armv8pt_full_va_prefix(const struct pt_common *common)
+{
+	if (pt_feature(common, PT_FEAT_ARMV8_TTBR1))
+		return PT_VADDR_MAX;
+	return 0;
+}
+#define pt_full_va_prefix armv8pt_full_va_prefix
+
+static inline unsigned int armv8pt_num_items_lg2(const struct pt_state *pts)
+{
+	/*
+	 * It is not allowed to call pt_num_items_lg2() at the top level, this
+	 * API restriction is specifically an optimization avoid overheads
+	 * dealing with concatenated tables here.
+	 */
+	PT_WARN_ON(pts->level == pts->range->top_level);
+	return armv8pt_tgsz_lg2(pts) - ilog2(sizeof(u64));
+}
+#define pt_num_items_lg2 armv8pt_num_items_lg2
+
+static inline enum pt_entry_type armv8pt_load_entry_raw(struct pt_state *pts)
+{
+	const u64 *tablep = pt_cur_table(pts, u64) + pts->index;
+	u64 entry;
+
+	pts->entry = entry = READ_ONCE(*tablep);
+	if (!(entry & ARMV8PT_FMT_VALID))
+		return PT_ENTRY_EMPTY;
+	/* R_RWMFF/Table D8-48: ARM level 3 has only Page descriptors */
+	if (pts->level != ARML3 && (entry & ARMV8PT_FMT_TABLE))
+		return PT_ENTRY_TABLE;
+
+	/* Must be a block or page, don't check the page bit on level 0 */
+	return PT_ENTRY_OA;
+}
+#define pt_load_entry_raw armv8pt_load_entry_raw
+
+static inline void
+armv8pt_install_leaf_entry(struct pt_state *pts, pt_oaddr_t oa,
+			   unsigned int oasz_lg2,
+			   const struct pt_write_attrs *attrs)
+{
+	unsigned int isz_lg2 = pt_table_item_lg2sz(pts);
+	u64 *tablep = pt_cur_table(pts, u64);
+	u64 entry;
+
+	if (!pt_check_install_leaf_args(pts, oa, oasz_lg2))
+		return;
+
+	if (pts_feature(pts, PT_FEAT_ARMV8_LPA2))
+		entry = ARMV8PT_FMT_VALID |
+			(oa & GENMASK_ULL(49, armv8pt_tgsz_lg2(pts))) |
+			FIELD_PREP(ARMV8PT_FMT_OA52_LPA2, oa >> 50) |
+			attrs->descriptor_bits;
+	else {
+		entry = ARMV8PT_FMT_VALID |
+			(oa & GENMASK_ULL(47, armv8pt_tgsz_lg2(pts))) |
+			attrs->descriptor_bits;
+		/* 64K FEAT_LPA: OA[51:48] in [15:12] */
+		if (pts_feature(pts, PT_FEAT_ARMV8_LPA))
+			entry |= FIELD_PREP(ARMV8PT_FMT_OA52_LPA, oa >> 48);
+	}
+
+	/*
+	 * R_RWMFF/Table D8-48: at ARM level 3 the leaf is a Page descriptor
+	 * with bit[1]=1; at other levels it is a Block with bit[1]=0.
+	 */
+	if (pts->level == ARML3)
+		entry |= ARMV8PT_FMT_PAGE;
+
+	if (oasz_lg2 != isz_lg2) {
+		u64 *end;
+
+		entry |= ARMV8PT_FMT_CONTIG;
+		tablep += pts->index;
+		end = tablep + log2_to_int(armv8pt_contig_count_lg2(pts));
+		for (; tablep != end; tablep++) {
+			WRITE_ONCE(*tablep, entry);
+			entry += (u64)1 << isz_lg2;
+		}
+	} else {
+		WRITE_ONCE(tablep[pts->index], entry);
+	}
+	pts->entry = entry;
+}
+#define pt_install_leaf_entry armv8pt_install_leaf_entry
+
+static inline bool armv8pt_install_table(struct pt_state *pts,
+					 pt_oaddr_t table_pa,
+					 const struct pt_write_attrs *attrs)
+{
+	u64 entry;
+
+	if (pts_feature(pts, PT_FEAT_ARMV8_LPA2))
+		entry = ARMV8PT_FMT_VALID | ARMV8PT_FMT_TABLE |
+			(table_pa & GENMASK_ULL(49, armv8pt_tgsz_lg2(pts))) |
+			FIELD_PREP(ARMV8PT_FMT_OA52_LPA2, table_pa >> 50);
+	else {
+		entry = ARMV8PT_FMT_VALID | ARMV8PT_FMT_TABLE |
+			(table_pa & GENMASK_ULL(47, armv8pt_tgsz_lg2(pts)));
+		/* 64K FEAT_LPA: OA[51:48] in [15:12] */
+		if (pts_feature(pts, PT_FEAT_ARMV8_LPA))
+			entry |= FIELD_PREP(ARMV8PT_FMT_OA52_LPA,
+					    table_pa >> 48);
+	}
+
+	return pt_table_install64(pts, entry);
+}
+#define pt_install_table armv8pt_install_table
+
+static inline void armv8pt_attr_from_entry(const struct pt_state *pts,
+					   struct pt_write_attrs *attrs)
+{
+	u64 mask = ARMV8PT_FMT_AF | ARMV8PT_FMT_UXN | ARMV8PT_FMT_PXN |
+		   ARMV8PT_FMT_ATTRINDX | ARMV8PT_FMT_AP | ARMV8PT_FMT_nG |
+		   ARMV8PT_FMT_S2MEMATTR | ARMV8PT_FMT_S2AP;
+
+	/* Tables D8-52/53: with LPA2 bits [9:8] are OA[51:50], not SH */
+	if (!pts_feature(pts, PT_FEAT_ARMV8_LPA2))
+		mask |= ARMV8PT_FMT_SH;
+	attrs->descriptor_bits = pts->entry & mask;
+}
+#define pt_attr_from_entry armv8pt_attr_from_entry
+
+static inline void armv8pt_clear_entries(struct pt_state *pts,
+					 unsigned int num_contig_lg2)
+{
+	u64 *tablep = pt_cur_table(pts, u64) + pts->index;
+	u64 *end = tablep + log2_to_int(num_contig_lg2);
+
+	for (; tablep != end; tablep++)
+		WRITE_ONCE(*tablep, 0);
+}
+#define pt_clear_entries armv8pt_clear_entries
+
+static inline unsigned int armv8pt_max_sw_bit(struct pt_common *common)
+{
+	/*
+	 * Stage 2 bit [55] is the NS field in Realm state (Table D8-53),
+	 * so it cannot be used as a software bit for stage 2.
+	 */
+	if (pt_feature(common, PT_FEAT_ARMV8_S2))
+		return 2;
+	return 3;
+}
+#define pt_max_sw_bit armv8pt_max_sw_bit
+
+static inline u64 armv8pt_sw_bit(unsigned int bitnr)
+{
+	if (__builtin_constant_p(bitnr) && bitnr > 3)
+		BUILD_BUG();
+
+	/*
+	 * D8.3 Tables D8-50 through D8-53: Bits marked IGNORED in Table
+	 * descriptors and "Reserved for software use" in Block and Page
+	 * descriptors.
+	 *
+	 * Bits [58:56] are safe for all descriptor types at both stage 1
+	 * and stage 2.  Bit [55] is additionally available at stage 1
+	 * (Table D8-52).
+	 */
+	switch (bitnr) {
+	case 0 ... 2:
+		return BIT_ULL(56 + bitnr);
+	case 3:
+		return BIT_ULL(55);
+	default:
+		PT_WARN_ON(true);
+		return 0;
+	}
+}
+#define pt_sw_bit armv8pt_sw_bit
drivers/iommu/generic_pt/fmt/defs_armv8.h new file +23 -0
new file mode 100644
index 00000000000000..d6c74dc3b574cf
@@ -0,0 +1,23 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+/*
+ * Copyright (c) 2024-2026, NVIDIA CORPORATION & AFFILIATES
+ *
+ * VMSAv8-64 translation table in AArch64 mode
+ *
+ */
+#ifndef __GENERIC_PT_FMT_DEFS_ARMV8_H
+#define __GENERIC_PT_FMT_DEFS_ARMV8_H
+
+#include <linux/generic_pt/common.h>
+#include <linux/types.h>
+
+typedef u64 pt_vaddr_t;
+typedef u64 pt_oaddr_t;
+
+struct armv8pt_write_attrs {
+	u64 descriptor_bits;
+	gfp_t gfp;
+};
+#define pt_write_attrs armv8pt_write_attrs
+
+#endif
include/linux/generic_pt/common.h +36 -0
index 1b39b27f0cfa81..09f4767b4410a4 100644
@@ -162,6 +162,42 @@ enum {
 	PT_FEAT_AMDV1_FORCE_COHERENCE,
 };
 
+struct pt_armv8 {
+	struct pt_common common;
+	u8 tgsz_lg2;
+};
+
+enum {
+	/* Use the upper address space instead of lower */
+	PT_FEAT_ARMV8_TTBR1 = PT_FEAT_FMT_START,
+	/*
+	 * Large Physical Address Extension (for 64k):
+	 *  - HW must support a 4TB block descriptor
+	 *  - HW must decode the additional OA in PTE bits[15:12]
+	 */
+	PT_FEAT_ARMV8_LPA,
+	/*
+	 * Large Physical Address 2 Extension (for 4/16k):
+	 *  - HW must support TSZ=12 (52 bit VA)
+	 *  - HW must support a 5 level walk (table level -1), 4k only
+	 *  - HW must support 16 entries in ARM L0, 16k only
+	 *  - HW must support a 512GB block descriptor in 4k
+	 *                       64GB block descriptor in 16k
+	 *  - HW must decode the additional OA in PTE bits[9:8]
+	 *  - HW must support DS=1
+	 */
+	PT_FEAT_ARMV8_LPA2,
+	/*
+	 * Large Virtual Address Extension (for S1 64k):
+	 *  - HW must support S1.TSZ=12 (52 bit VA)
+	 */
+	PT_FEAT_ARMV8_LVA,
+	/* Use the Stage 2 format instead of Stage 1 */
+	PT_FEAT_ARMV8_S2,
+	/* For S2 uses the Force Write Back coding of the S2MEMATTR */
+	PT_FEAT_ARMV8_S2FWB,
+};
+
 struct pt_vtdss {
 	struct pt_common common;
 };
Signature · 1 line
2.43.0
#15 lore raw

Re: [PATCH v3 06/13] iommupt/armv8: Add the 64 bit ARMv8 page table format

drivers/iommu/generic_pt/fmt/armv8.h line 8

Quoted 10 lines · Jason Gunthorpe

+++ b/drivers/iommu/generic_pt/fmt/armv8.h

drivers/iommu/generic_pt/fmt/armv8.h new file +8 -0
@@ -0,0 +1,485 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+/*
+ * Copyright (c) 2024-2026, NVIDIA CORPORATION & AFFILIATES
+ *
+ * The page table format described by ARM DDI 0487 L.b, Chapter D8
+ * "The AArch64 Virtual Memory System Architecture" (VMSAv8-64).
+ * With the right cfg this will also implement the VMSAv8-32 Long
+ * Descriptor format.

Nit: M.d is the latest version. See if it's worth asking AI to update it and the session numbers in the file.

drivers/iommu/generic_pt/fmt/armv8.h line 41

Quoted 3 lines
drivers/iommu/generic_pt/fmt/armv8.h new file +3 -0
+#include <linux/limits.h>
+#include <linux/sizes.h>
+#include <linux/string.h>

It seems that these three headers aren't used.

Quoted 8 lines
drivers/iommu/generic_pt/fmt/armv8.h new file +8 -0
+enum {
+	PT_MAX_OUTPUT_ADDRESS_LG2 =
+		(PT_SUPPORTED_FEATURE(PT_FEAT_ARMV8_LPA2) |
+		 PT_SUPPORTED_FEATURE(PT_FEAT_ARMV8_LPA)) ? 52 : 48,
+	/* See armv8pt_iommu_fmt_init() */
+	PT_MAX_VA_ADDRESS_LG2 =
+		(PT_SUPPORTED_FEATURE(PT_FEAT_ARMV8_LPA2) |
+		 PT_SUPPORTED_FEATURE(PT_FEAT_ARMV8_LVA) |

drivers/iommu/generic_pt/fmt/armv8.h line 78

Quoted 10 lines
drivers/iommu/generic_pt/fmt/armv8.h new file +10 -0
+		 PT_SUPPORTED_FEATURE(PT_FEAT_ARMV8_LPA)) ? 52 : 48,
+
+	/*
+	 * D24.2.195 TTBR_ELx BADDR:
+	 *
+	 * Bits A[(x-1):0] of the stage 1 translation table base address are
+	 * zero. Address bit x is the minimum address bit required to align the
+	 * translation table to the size of the table. x is calculated based on
+	 * LOG2(StartTableSize), as described in VMSAv9-128. The smallest
+	 * permitted value of x is 5.

The spec (M.d) defines 6:
"
D24.2.208 TTBR0_EL1, Translation Table Base Register 0 (EL1)

BADDR[47:1], bits [47:1]

When TTBR0_EL1.BADDR represents a 52-bit addresses, all of the following apply:
- Bits A[51:48] of the stage 1 translation table base address bits are in register bits[5:2].
- Register bit[1] is RES0.
- The smallest permitted value of x is 6.
- When x>6, register bits[(x-1):6] are RES0.
".

EL2 and EL3 have the same piece.

drivers/iommu/generic_pt/fmt/armv8.h line 85

Quoted 6 lines
drivers/iommu/generic_pt/fmt/armv8.h new file +6 -0
+	 * R_KBLCR requires the table to be aligned to its own size.
+	 *
+	 * SMMU S2TTB additionally says: In addition, a 64-byte minimum
+	 * alignment on starting-level translation table addresses is imposed
+	 * when S2TG selects 64KB granules and the effective S2PS value
+	 * indicates 52-bit output. In this case bits [5:0] are treated as zero.

I think 6 also matches the R_KBLCR here for 64-bit alignment?

Review line 37

Quoted 2 lines
(quoted diff) +2 -0
+	 */
+	PT_TOP_PHYS_MASK = GENMASK_ULL(51, 5),

And here, should it be GENMASK_ULL(51, 6)?

drivers/iommu/generic_pt/fmt/armv8.h line 95

Quoted 8 lines
drivers/iommu/generic_pt/fmt/armv8.h new file +8 -0
+};
+
+/* Common PTE bits */
+enum {
+	ARMV8PT_FMT_VALID = BIT(0),
+	ARMV8PT_FMT_PAGE = BIT(1),
+	ARMV8PT_FMT_TABLE = BIT(1),
+	ARMV8PT_FMT_NS = BIT(5),

NS belongs to S1 only.

For S2, bit-5 is MemAttr[3], and bit-55 is Non-secure (NS).

drivers/iommu/generic_pt/fmt/armv8.h line 106

Quoted 11 lines
drivers/iommu/generic_pt/fmt/armv8.h new file +11 -0
+	ARMV8PT_FMT_SH = GENMASK(9, 8),
+	ARMV8PT_FMT_AF = BIT(10),
+
+	/* 64K FEAT_LPA: OA[51:48] in bits[15:12], Figures D8-14/15 */
+	ARMV8PT_FMT_OA52_LPA = GENMASK_ULL(15, 12),
+	/* 4K/16K FEAT_LPA2 (DS=1): OA[51:50] in bits[9:8], Figures D8-14/15 */
+	ARMV8PT_FMT_OA52_LPA2 = GENMASK_ULL(9, 8),
+
+	ARMV8PT_FMT_CONTIG = BIT_ULL(52),
+	ARMV8PT_FMT_UXN = BIT_ULL(53),
+	ARMV8PT_FMT_PXN = BIT_ULL(54),

The bits for UXN and PXN are swapped. And S2 doesn't define them as UXN and PXN but XN[1:0],

Perhaps move UXN/PXN to "S1 PTE bits" and add an ARMV8PT_FMT_S2NX to "S2 PTE bits"?

drivers/iommu/generic_pt/fmt/armv8.h line 107

Quoted 1 line
drivers/iommu/generic_pt/fmt/armv8.h new file +1 -0
+	ARMV8PT_FMT_NSTABLE = BIT_ULL(63),

This doesn't seem to be common but S1 only.

Bit-63 NSTABLE is only defined in
Table D8-50 Stage 1 VMSAv8-64 Table descriptor fields

not in
Table D8-51 Stage 2 VMSAv8-64 Table descriptor fields Table D8-52 Stage 1 VMSAv8-64 Block and Page descriptor fields Table D8-53 Stage 2 VMSAv8-64 Block and Page descriptor fields

Quoted 6 lines
drivers/iommu/generic_pt/fmt/armv8.h new file +6 -0
+/* Number contiguous entries that ARMV8PT_FMT_CONTIG will join at this level */
+static inline unsigned short
+armv8pt_contig_count_lg2(const struct pt_state *pts)
+{
+	unsigned int tgsz_lg2 = armv8pt_tgsz_lg2(pts);
+

drivers/iommu/generic_pt/fmt/armv8.h line 302

Quoted 10 lines
drivers/iommu/generic_pt/fmt/armv8.h new file +10 -0
+	if (tgsz_lg2 == SZLG2_4K)
+		return ilog2(16); /* 64KB, 32MB, 16GB, 8TB */
+	else if (tgsz_lg2 == SZLG2_16K && pts->level == ARML2)
+		return ilog2(32); /* 1GB */
+	else if (tgsz_lg2 == SZLG2_16K && pts->level == ARML3)
+		return ilog2(128); /* 2MB */
+	else if (tgsz_lg2 == SZLG2_64K)
+		return ilog2(32); /* 2MB, 16GB, 128TB */
+	return ilog2(1);
+}

In "D8.7.1 The Contiguous bit", I don't see the 8TB and 128TB being listed.

Also, should SZLG2_64K check level == ARML2 or ARML3?

drivers/iommu/generic_pt/fmt/armv8.h line 473

Quoted 13 lines
drivers/iommu/generic_pt/fmt/armv8.h new file +13 -0
+static inline u64 armv8pt_sw_bit(unsigned int bitnr)
+{
+	if (__builtin_constant_p(bitnr) && bitnr > 3)
+		BUILD_BUG();
+
+	/*
+	 * D8.3 Tables D8-50 through D8-53: Bits marked IGNORED in Table
+	 * descriptors and "Reserved for software use" in Block and Page
+	 * descriptors.
+	 *
+	 * Bits [58:56] are safe for all descriptor types at both stage 1
+	 * and stage 2.  Bit [55] is additionally available at stage 1
+	 * (Table D8-52).

Per Table D8-53 Stage 2 VMSAv8-64 Block and Page descriptor fields, bit-58 is only available for stage 2 when VTCR_EL2.AssuredOnly=0.

Nicolin

#16 lore raw

PATCH v3 7/13 iommupt/armv8: Add DBM support

In reply to Jason Gunthorpe

Provide the functions required to do dirty tracking with variations for S1 and S2 formats. This follows the same scheme as iopgtable where the table starts off dirty to avoid any HW updates, and once dirty tracking is started it will be cleaned.

---
 drivers/iommu/generic_pt/fmt/armv8.h | 102 ++++++++++++++++++++++++++-
 include/linux/generic_pt/common.h    |   2 +
 2 files changed, 101 insertions(+), 3 deletions(-)
drivers/iommu/generic_pt/fmt/armv8.h +99 -3
index 68fedda41fc198..f204f6906bb14f 100644
@@ -101,6 +101,7 @@ enum {
 	/* 4K/16K FEAT_LPA2 (DS=1): OA[51:50] in bits[9:8], Figures D8-14/15 */
 	ARMV8PT_FMT_OA52_LPA2 = GENMASK_ULL(9, 8),
 
+	ARMV8PT_FMT_DBM = BIT_ULL(51),
 	ARMV8PT_FMT_CONTIG = BIT_ULL(52),
 	ARMV8PT_FMT_UXN = BIT_ULL(53),
 	ARMV8PT_FMT_PXN = BIT_ULL(54),
@@ -424,9 +425,9 @@ static inline bool armv8pt_install_table(struct pt_state *pts,
 static inline void armv8pt_attr_from_entry(const struct pt_state *pts,
 					   struct pt_write_attrs *attrs)
 {
-	u64 mask = ARMV8PT_FMT_AF | ARMV8PT_FMT_UXN | ARMV8PT_FMT_PXN |
-		   ARMV8PT_FMT_ATTRINDX | ARMV8PT_FMT_AP | ARMV8PT_FMT_nG |
-		   ARMV8PT_FMT_S2MEMATTR | ARMV8PT_FMT_S2AP;
+	u64 mask = ARMV8PT_FMT_AF | ARMV8PT_FMT_DBM | ARMV8PT_FMT_UXN |
+		   ARMV8PT_FMT_PXN | ARMV8PT_FMT_ATTRINDX | ARMV8PT_FMT_AP |
+		   ARMV8PT_FMT_nG | ARMV8PT_FMT_S2MEMATTR | ARMV8PT_FMT_S2AP;
 
 	/* Tables D8-52/53: with LPA2 bits [9:8] are OA[51:50], not SH */
 	if (!pts_feature(pts, PT_FEAT_ARMV8_LPA2))
@@ -446,6 +447,101 @@ static inline void armv8pt_clear_entries(struct pt_state *pts,
 }
 #define pt_clear_entries armv8pt_clear_entries
 
+/*
+ * Call fn over all the items in an entry. If the entry is contiguous this
+ * iterates over the entire contiguous entry, including items preceding
+ * pts->va. always_inline avoids an indirect function call.
+ */
+static __always_inline bool armv8pt_reduce_contig(const struct pt_state *pts,
+						  bool (*fn)(u64 *tablep,
+							     u64 entry))
+{
+	u64 *tablep = pt_cur_table(pts, u64);
+
+	if (pts->entry & ARMV8PT_FMT_CONTIG) {
+		unsigned int num_contig_lg2 = armv8pt_contig_count_lg2(pts);
+		u64 *end;
+
+		tablep += log2_set_mod(pts->index, 0, num_contig_lg2);
+		end = tablep + log2_to_int(num_contig_lg2);
+		for (; tablep != end; tablep++)
+			if (fn(tablep, READ_ONCE(*tablep)))
+				return true;
+		return false;
+	}
+	return fn(tablep + pts->index, pts->entry);
+}
+
+static inline bool armv8pt_check_is_dirty_s1(u64 *tablep, u64 entry)
+{
+	return (entry & (ARMV8PT_FMT_DBM |
+			 FIELD_PREP(ARMV8PT_FMT_AP, ARMV8PT_AP_RDONLY))) ==
+	       ARMV8PT_FMT_DBM;
+}
+
+static bool armv8pt_clear_dirty_s1(u64 *tablep, u64 entry)
+{
+	WRITE_ONCE(*tablep,
+		   entry | FIELD_PREP(ARMV8PT_FMT_AP, ARMV8PT_AP_RDONLY));
+	return false;
+}
+
+static inline bool armv8pt_check_is_dirty_s2(u64 *tablep, u64 entry)
+{
+	const u64 DIRTY = ARMV8PT_FMT_DBM |
+			  FIELD_PREP(ARMV8PT_FMT_S2AP, ARMV8PT_S2AP_WRITE);
+
+	return (entry & DIRTY) == DIRTY;
+}
+
+static bool armv8pt_clear_dirty_s2(u64 *tablep, u64 entry)
+{
+	WRITE_ONCE(*tablep, entry & ~(u64)FIELD_PREP(ARMV8PT_FMT_S2AP,
+						     ARMV8PT_S2AP_WRITE));
+	return false;
+}
+
+static inline bool armv8pt_entry_is_write_dirty(const struct pt_state *pts)
+{
+	if (!pts_feature(pts, PT_FEAT_ARMV8_S2))
+		return armv8pt_reduce_contig(pts, armv8pt_check_is_dirty_s1);
+	else
+		return armv8pt_reduce_contig(pts, armv8pt_check_is_dirty_s2);
+}
+#define pt_entry_is_write_dirty armv8pt_entry_is_write_dirty
+
+static inline void armv8pt_entry_make_write_clean(struct pt_state *pts)
+{
+	if (!pts_feature(pts, PT_FEAT_ARMV8_S2))
+		armv8pt_reduce_contig(pts, armv8pt_clear_dirty_s1);
+	else
+		armv8pt_reduce_contig(pts, armv8pt_clear_dirty_s2);
+}
+#define pt_entry_make_write_clean armv8pt_entry_make_write_clean
+
+static inline bool armv8pt_entry_make_write_dirty(struct pt_state *pts)
+{
+	u64 *tablep = pt_cur_table(pts, u64) + pts->index;
+	u64 new = pts->entry;
+
+	if (!(pts->entry & ARMV8PT_FMT_DBM))
+		return false;
+
+	if (!pts_feature(pts, PT_FEAT_ARMV8_S2))
+		new &= ~FIELD_PREP(ARMV8PT_FMT_AP, ARMV8PT_AP_RDONLY);
+	else
+		new |= FIELD_PREP(ARMV8PT_FMT_S2AP, ARMV8PT_S2AP_WRITE);
+
+	return try_cmpxchg64(tablep, &pts->entry, new);
+}
+#define pt_entry_make_write_dirty armv8pt_entry_make_write_dirty
+
+static inline bool armv8pt_dirty_supported(struct pt_common *common)
+{
+	return pt_feature(common, PT_FEAT_ARMV8_DBM);
+}
+#define pt_dirty_supported armv8pt_dirty_supported
+
 static inline unsigned int armv8pt_max_sw_bit(struct pt_common *common)
 {
 	/*
include/linux/generic_pt/common.h +2 -0
index 09f4767b4410a4..b5a551a22fbc5e 100644
@@ -194,6 +194,8 @@ enum {
 	PT_FEAT_ARMV8_LVA,
 	/* Use the Stage 2 format instead of Stage 1 */
 	PT_FEAT_ARMV8_S2,
+	/* Use Dirty Bit Modifier, necessary for IOMMU dirty tracking */
+	PT_FEAT_ARMV8_DBM,
 	/* For S2 uses the Force Write Back coding of the S2MEMATTR */
 	PT_FEAT_ARMV8_S2FWB,
 };
Signature · 1 line
2.43.0
Reviewed-by on v3 7/13
#17 lore raw

Re: [PATCH v3 07/13] iommupt/armv8: Add DBM support

Quoted 6 lines · Jason Gunthorpe

Provide the functions required to do dirty tracking with variations for S1 and S2 formats. This follows the same scheme as iopgtable where the table starts off dirty to avoid any HW updates, and once dirty tracking is started it will be cleaned.

Two nits below, but they are ignorable.

drivers/iommu/generic_pt/fmt/armv8.h static inline void armv8pt_clear_entries(struct pt_state *pts, · line 487

Quoted 13 lines
drivers/iommu/generic_pt/fmt/armv8.h +13 -0
+static inline bool armv8pt_check_is_dirty_s1(u64 *tablep, u64 entry)
+{
+	return (entry & (ARMV8PT_FMT_DBM |
+			 FIELD_PREP(ARMV8PT_FMT_AP, ARMV8PT_AP_RDONLY))) ==
+	       ARMV8PT_FMT_DBM;
+}
+
+static bool armv8pt_clear_dirty_s1(u64 *tablep, u64 entry)
+{
+	WRITE_ONCE(*tablep,
+		   entry | FIELD_PREP(ARMV8PT_FMT_AP, ARMV8PT_AP_RDONLY));
+	return false;
+}

Could this be "inline", matching with armv8pt_check_is_dirty_s1?

Quoted 4 lines
drivers/iommu/generic_pt/fmt/armv8.h +4 -0
+static inline bool armv8pt_check_is_dirty_s2(u64 *tablep, u64 entry)
+{
+	const u64 DIRTY = ARMV8PT_FMT_DBM |
+			  FIELD_PREP(ARMV8PT_FMT_S2AP, ARMV8PT_S2AP_WRITE);

drivers/iommu/generic_pt/fmt/armv8.h static inline void armv8pt_clear_entries(struct pt_state *pts, · line 502

Quoted 10 lines
drivers/iommu/generic_pt/fmt/armv8.h +10 -0
+
+	return (entry & DIRTY) == DIRTY;
+}
+
+static bool armv8pt_clear_dirty_s2(u64 *tablep, u64 entry)
+{
+	WRITE_ONCE(*tablep, entry & ~(u64)FIELD_PREP(ARMV8PT_FMT_S2AP,
+						     ARMV8PT_S2AP_WRITE));
+	return false;
+}

Ditto

Nicolin

#18 lore raw

PATCH v3 8/13 iommupt/armv8: Implement the iommu specific components

In reply to Jason Gunthorpe

The iommu page table is built on top of the generic components, add the peices required to turn that on for ARMv8
- Makefile and kconfig
- pt_iommu_* functions for ARMv8, including the complicated initialization of the level and structure from a typical pt_iommu cfg
- pt_iommu_hw_info to return the field values program into the STE
- 12 kunit patterns covering a range of operating modes

Include an inline helper pt_iommu_armv8_choose_granule_lg2sz() that does similar to what iopgtbl does to select an appropriate translation granule size.

---
 drivers/iommu/generic_pt/.kunitconfig      |   1 +
 drivers/iommu/generic_pt/Kconfig           |  12 +
 drivers/iommu/generic_pt/fmt/Makefile      |   2 +
 drivers/iommu/generic_pt/fmt/armv8.h       | 495 +++++++++++++++++++++
 drivers/iommu/generic_pt/fmt/iommu_armv8.c |  13 +
 include/linux/generic_pt/iommu.h           |  72 +++
 6 files changed, 595 insertions(+)
 create mode 100644 drivers/iommu/generic_pt/fmt/iommu_armv8.c
drivers/iommu/generic_pt/.kunitconfig +1 -0
index a3da74328f12fc..f5832b8189d1e2 100644
@@ -4,6 +4,7 @@ CONFIG_GENERIC_PT=y
 CONFIG_DEBUG_GENERIC_PT=y
 CONFIG_IOMMU_PT=y
 CONFIG_IOMMU_PT_AMDV1=y
+CONFIG_IOMMU_PT_ARMV8=y
 CONFIG_IOMMU_PT_VTDSS=y
 CONFIG_IOMMU_PT_RISCV64=y
 CONFIG_IOMMU_PT_X86_64=y
drivers/iommu/generic_pt/Kconfig +12 -0
index 2a81dac960ac02..0a44608968f246 100644
@@ -42,6 +42,17 @@ config IOMMU_PT_AMDV1
 
 	  Selected automatically by an IOMMU driver that uses this format.
 
+config IOMMU_PT_ARMV8
+	tristate "IOMMU page table for 64 bit ARMv8"
+	depends on !GENERIC_ATOMIC64 # for cmpxchg64
+	help
+	  iommu_domain implementation for the ARMv8 VMSAv8-64 and the VMSAv8-32
+	  long descriptor pagetable format. This format supports both stage-1
+	  and stage-2, as well as address spaces up to 48-bits in size with
+	  4K, 16K, and 64K granule sizes.
+
+	  Selected automatically by an IOMMU driver that uses this format.
+
 config IOMMU_PT_VTDSS
        tristate "IOMMU page table for Intel VT-d Second Stage"
 	depends on !GENERIC_ATOMIC64 # for cmpxchg64
@@ -85,6 +96,7 @@ config IOMMU_PT_KUNIT_TEST
 	tristate "IOMMU Page Table KUnit Test" if !KUNIT_ALL_TESTS
 	depends on KUNIT
 	depends on IOMMU_PT_AMDV1 || !IOMMU_PT_AMDV1
+	depends on IOMMU_PT_ARMV8 || !IOMMU_PT_ARMV8
 	depends on IOMMU_PT_RISCV64 || !IOMMU_PT_RISCV64
 	depends on IOMMU_PT_X86_64 || !IOMMU_PT_X86_64
 	depends on IOMMU_PT_VTDSS || !IOMMU_PT_VTDSS
drivers/iommu/generic_pt/fmt/Makefile +2 -0
index a43f3b81d2dbc4..42e66ad940aebd 100644
@@ -3,6 +3,8 @@
 iommu_pt_fmt-$(CONFIG_IOMMU_PT_AMDV1) += amdv1
 iommu_pt_fmt-$(CONFIG_IOMMUFD_TEST) += mock
 
+iommu_pt_fmt-$(CONFIG_IOMMU_PT_ARMV8) += armv8
+
 iommu_pt_fmt-$(CONFIG_IOMMU_PT_VTDSS) += vtdss
 
 iommu_pt_fmt-$(CONFIG_IOMMU_PT_RISCV64) += riscv64
drivers/iommu/generic_pt/fmt/armv8.h +495 -0

498 lines not on this page · raw message

drivers/iommu/generic_pt/fmt/iommu_armv8.c new file +13 -0
new file mode 100644
index 00000000000000..95878105d35e18
@@ -0,0 +1,13 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * Copyright (c) 2024-2026, NVIDIA CORPORATION & AFFILIATES
+ */
+#define PT_FMT armv8
+#define PT_SUPPORTED_FEATURES                                  \
+	(BIT(PT_FEAT_DMA_INCOHERENT) | BIT(PT_FEAT_ARMV8_S2) | \
+	 BIT(PT_FEAT_ARMV8_LVA) |                              \
+	 BIT(PT_FEAT_ARMV8_DBM) | BIT(PT_FEAT_ARMV8_S2FWB) |  \
+	 BIT(PT_FEAT_DETAILED_GATHER))
+#define PT_FORCE_ENABLED_FEATURES BIT(PT_FEAT_DETAILED_GATHER)
+
+#include "iommu_template.h"
include/linux/generic_pt/iommu.h +72 -0

78 lines not on this page · raw message

Signature · 1 line
2.43.0
#19 lore raw

Re: [PATCH v3 08/13] iommupt/armv8: Implement the iommu specific components

Quoted 2 lines · Jason Gunthorpe

The iommu page table is built on top of the generic components, add the peices required to turn that on for ARMv8

s/peices/pieces

Quoted 8 lines

- Makefile and kconfig
- pt_iommu_* functions for ARMv8, including the complicated initialization of the level and structure from a typical pt_iommu cfg
- pt_iommu_hw_info to return the field values program into the STE
- 12 kunit patterns covering a range of operating modes

Include an inline helper pt_iommu_armv8_choose_granule_lg2sz() that does similar to what iopgtbl does to select an appropriate translation granule

s/iopgtbl/io-pgtble-arm

drivers/iommu/generic_pt/Kconfig config IOMMU_PT_AMDV1 · line 51

Quoted 7 lines
drivers/iommu/generic_pt/Kconfig +7 -0
+config IOMMU_PT_ARMV8
+	tristate "IOMMU page table for 64 bit ARMv8"
+	depends on !GENERIC_ATOMIC64 # for cmpxchg64
+	help
+	  iommu_domain implementation for the ARMv8 VMSAv8-64 and the VMSAv8-32
+	  long descriptor pagetable format. This format supports both stage-1
+	  and stage-2, as well as address spaces up to 48-bits in size with

I see this patch supports 52 bits.

Quoted 8 lines
drivers/iommu/generic_pt/fmt/armv8.h +8 -0
+static inline void armv8pt_s2_validate_level(unsigned int top_level,
+					     unsigned int tgsz_lg2,
+					     unsigned int vasz_lg2, bool lpa2)
+{
+	unsigned int max_top_level;
+
+	switch (tgsz_lg2) {
+	case SZLG2_4K:

drivers/iommu/generic_pt/fmt/armv8.h static inline u64 armv8pt_sw_bit(unsigned int bitnr) · line 723

Quoted 10 lines
drivers/iommu/generic_pt/fmt/armv8.h +10 -0
+		if (lpa2)
+			max_top_level =
+				vasz_lg2 >= 52 ?
+					ARMLn1 :
+					(vasz_lg2 >= 44 ? ARML0 : ARML1);
+		else
+			max_top_level = vasz_lg2 >= 44 ? ARML0 : ARML1;
+		break;
+	case SZLG2_16K: /* ARM level 1 requires PA >= 42 */
+		max_top_level = vasz_lg2 >= 42 ? ARML1 : ARML2;

max_top_level can be 0 in 16K when vasz_lg2 >= 52.

Quoted 3 lines
drivers/iommu/generic_pt/fmt/armv8.h +3 -0
+static inline int armv8pt_iommu_fmt_init(struct pt_iommu_armv8 *iommu_table,
+					 const struct pt_iommu_armv8_cfg *cfg)
+{

[...]

Quoted 16 lines
drivers/iommu/generic_pt/fmt/armv8.h +16 -0
+	/*
+	 * R_SRKBC: For the 4KB granule, an initial lookup level of 3 is
+	 * only supported if FEAT_TTST is implemented. See Table D8-9 and
+	 * Table D8-24. FEAT_TTST is not supported.
+	 */
+	if (pt_feature(&armv8pt->common, PT_FEAT_ARMV8_S2) &&
+	    tgsz_lg2 == SZLG2_4K && levels == 1)
+		return -EINVAL;
+
+	/*
+	 * D8.2.2: Always use the S2 concatenated tables feature (I_TDMHR)
+	 * to fold a top level of up to 16 tables into the next lower
+	 * level. Since FEAT_TTST is not supported single level cannot be
+	 * selected here either. Notice that there are a number of cases
+	 * in the spec that require concatenated tables (eg R_DXBSH),
+	 * since this always uses them it is OK. See commit 4dcac8407fe1

drivers/iommu/generic_pt/fmt/armv8.h static inline u64 armv8pt_sw_bit(unsigned int bitnr) · line 875

Quoted 10 lines
drivers/iommu/generic_pt/fmt/armv8.h +10 -0
+	 * ("iommu/io-pgtable-arm: Fix stage-2 concatenation with 16K")
+	 */
+	if (!pt_feature(&armv8pt->common, PT_FEAT_DYNAMIC_TOP) &&
+	    pt_feature(&armv8pt->common, PT_FEAT_ARMV8_S2) && levels > 1) {
+		unsigned int topsz_lg2 =
+			vasz_lg2 - (tgsz_lg2 + (tgsz_lg2 - ilog2(sizeof(u64))) *
+						       (levels - 1));
+		if (topsz_lg2 <= ilog2(16))
+			levels--;
+	}

Should we move the "levels == 1" test (R_SRKBC) after concatenation?

Quoted 5 lines
drivers/iommu/generic_pt/fmt/armv8.h +5 -0
+static inline void
+armv8pt_iommu_fmt_hw_info(struct pt_iommu_armv8 *table,
+			  const struct pt_range *top_range,
+			  struct pt_iommu_armv8_hw_info *info)
+{

[...]

Quoted 5 lines
drivers/iommu/generic_pt/fmt/armv8.h +5 -0
+	if (pt_feature(common, PT_FEAT_ARMV8_S2)) {
+		/*
+		 * STE S2SL0/S2SL2: Starting level in VTCR_EL2.SL0/SL2
+		 * encoding. Table from D24.2.210 SL0:
+		 *

drivers/iommu/generic_pt/fmt/armv8.h static inline u64 armv8pt_sw_bit(unsigned int bitnr) · line 963

Quoted 10 lines
drivers/iommu/generic_pt/fmt/armv8.h +10 -0
+		 * 4K:  top_level  ARMLx    S2SL0  S2SL2
+		 *      1          ARML2    0      0
+		 *      2          ARML1    1      0
+		 *      3          ARML0    2      0
+		 *      4          ARMLn1   0      1      (FEAT_LPA2)
+		 *
+		 * 16K/64K:
+		 *      0          ARML3    0
+		 *      1          ARML2    1
+		 *      2          ARML1    2

Is this missing (or on purpose):
* 3 ARML0 3 (16K; FEAT_LPA2)
?

drivers/iommu/generic_pt/fmt/armv8.h static inline u64 armv8pt_sw_bit(unsigned int bitnr) · line 971

Quoted 8 lines
drivers/iommu/generic_pt/fmt/armv8.h +8 -0
+		 */
+		info->s2.sl2 = 0;
+		if (tgsz_lg2 == SZLG2_4K) {
+			if (top_range->top_level == ARMLn1) {
+				info->s2.sl0 = 0;
+				info->s2.sl2 = 1;
+			} else {
+				info->s2.sl0 = top_range->top_level - 1;

Though it's not in the list above, top_level can be 0 (ARML3) for 4K, right? Would 0 - 1 underflow here?

Quoted 31 lines
drivers/iommu/generic_pt/fmt/armv8.h +31 -0
+#if defined(GENERIC_PT_KUNIT)
+static const struct pt_iommu_armv8_cfg armv8_kunit_fmt_cfgs[] = {
+	/*
+	 * See R_DXBSH: 16K granule + 48-bit S2 is required to start at level 1
+	 * with 2 concatenated tables.
+	 */
+	[4] = { .tgsz_lg2 = 14,
+		.common.features = BIT(PT_FEAT_ARMV8_S2),
+		.common.hw_max_oasz_lg2 = 48,
+		.common.hw_max_vasz_lg2 = 48 },
+	[5] = { .tgsz_lg2 = 14,
+		.common.features = BIT(PT_FEAT_ARMV8_TTBR1),
+		.common.hw_max_oasz_lg2 = 48,
+		.common.hw_max_vasz_lg2 = 48 },
+	/* 64K granule */
+	[6] = { .tgsz_lg2 = 16,
+		.common.features = BIT(PT_FEAT_ARMV8_DBM),
+		.common.hw_max_oasz_lg2 = 48,
+		.common.hw_max_vasz_lg2 = 48 },
+	[7] = { .tgsz_lg2 = 16,
+		.common.features = BIT(PT_FEAT_ARMV8_S2),
+		.common.hw_max_oasz_lg2 = 48,
+		.common.hw_max_vasz_lg2 = 48 },
+	[8] = { .tgsz_lg2 = 16,
+		.common.features = BIT(PT_FEAT_ARMV8_TTBR1),
+		.common.hw_max_oasz_lg2 = 48,
+		.common.hw_max_vasz_lg2 = 48 },
+	/* S2 concatenated table configurations at smaller IPA sizes */
+	[9] = { .tgsz_lg2 = 12,
+		.common.features = BIT(PT_FEAT_ARMV8_S2),
+		.common.hw_max_oasz_lg2 = 40,

drivers/iommu/generic_pt/fmt/armv8.h static inline u64 armv8pt_sw_bit(unsigned int bitnr) · line 1067

Quoted 10 lines
drivers/iommu/generic_pt/fmt/armv8.h +10 -0
+		.common.hw_max_vasz_lg2 = 40 },
+	[10] = { .tgsz_lg2 = 12,
+		 .common.features = BIT(PT_FEAT_ARMV8_S2),
+		 .common.hw_max_oasz_lg2 = 42,
+		 .common.hw_max_vasz_lg2 = 42 },
+	[11] = { .tgsz_lg2 = 14,
+		 .common.features = BIT(PT_FEAT_ARMV8_S2),
+		 .common.hw_max_oasz_lg2 = 40,
+		 .common.hw_max_vasz_lg2 = 40 },
+};

Would it be worth adding a 52-bit coverage with PT_FEAT_ARMV8_LPA2?

Nicolin

#20 lore raw

PATCH v3 9/13 iommu/arm-smmu-v3: Remove io-pgtable-arm from sva.c

In reply to Jason Gunthorpe

This is only being used to get some STE constants. Use the same constants from the arm architecture code in sysreg.h instead.

---
 drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3-sva.c | 15 ++++++++-------
 1 file changed, 8 insertions(+), 7 deletions(-)
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3-sva.c +8 -7
index fdc6cb7a128037..0ce720de6c92fa 100644
@@ -10,8 +10,9 @@
 #include <linux/slab.h>
 #include <kunit/visibility.h>
 
+#include <asm/sysreg.h>
+
 #include "arm-smmu-v3.h"
-#include "../../io-pgtable-arm.h"
 
 static void __maybe_unused
 arm_smmu_update_s1_domain_cd_entry(struct arm_smmu_domain *smmu_domain)
@@ -41,10 +42,10 @@ static u64 page_size_to_cd(void)
 	static_assert(PAGE_SIZE == SZ_4K || PAGE_SIZE == SZ_16K ||
 		      PAGE_SIZE == SZ_64K);
 	if (PAGE_SIZE == SZ_64K)
-		return ARM_LPAE_TCR_TG0_64K;
+		return TCR_EL1_TG0_64K;
 	if (PAGE_SIZE == SZ_16K)
-		return ARM_LPAE_TCR_TG0_16K;
-	return ARM_LPAE_TCR_TG0_4K;
+		return TCR_EL1_TG0_16K;
+	return TCR_EL1_TG0_4K;
 }
 
 VISIBLE_IF_KUNIT
@@ -85,10 +86,10 @@ void arm_smmu_make_sva_cd(struct arm_smmu_cd *target,
 				   64ULL - vabits_actual) |
 			FIELD_PREP(CTXDESC_CD_0_TCR_TG0, page_size_to_cd()) |
 			FIELD_PREP(CTXDESC_CD_0_TCR_IRGN0,
-				   ARM_LPAE_TCR_RGN_WBWA) |
+				   TCR_EL1_IRGN0_WBWA) |
 			FIELD_PREP(CTXDESC_CD_0_TCR_ORGN0,
-				   ARM_LPAE_TCR_RGN_WBWA) |
-			FIELD_PREP(CTXDESC_CD_0_TCR_SH0, ARM_LPAE_TCR_SH_IS));
+				   TCR_EL1_ORGN0_WBWA) |
+			FIELD_PREP(CTXDESC_CD_0_TCR_SH0, TCR_EL1_SH0_INNER));
 
 		target->data[1] = cpu_to_le64(virt_to_phys(mm->pgd) &
 					      CTXDESC_CD_1_TTB0_MASK);
Signature · 1 line
2.43.0
#22 lore raw

PATCH v3 10/13 iommu/arm-smmu-v3: Move the DMA API comment to flush_iotlb_all

In reply to Jason Gunthorpe

arm_smmu_tlb_inv_context() is the wrong flush_all for this comment, it is only called during io-pgtable destruction not during the dma-iommu operation. Move it to arm_smmu_flush_iotlb_all() which is the flush that is triggered by the dma-iommu lazy flush thread.

---
 drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c | 31 +++++++++++----------
 1 file changed, 16 insertions(+), 15 deletions(-)
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +16 -15
index 294f9645cdc3db..3eb61eb35d0b38 100644
@@ -2484,21 +2484,6 @@ static void arm_smmu_tlb_inv_context(void *cookie)
 {
 	struct arm_smmu_domain *smmu_domain = cookie;
 
-	/*
-	 * If the DMA API is running in non-strict mode then another CPU could
-	 * have changed the page table and not invoked any flush op. Instead the
-	 * other CPU will do an atomic_read() and this CPU will have done an
-	 * atomic_write(). That handshake is enough to acquire the page table
-	 * writes from the other CPU.
-	 *
-	 * All command execution has a dma_wmb() to release all the in-memory
-	 * structures written by this CPU, that barrier must also release the
-	 * writes acquired from all the other CPUs too.
-	 *
-	 * There are other barriers and atomics on this path, but the above is
-	 * the essential mechanism for ensuring that HW sees the page table
-	 * writes from another CPU before it executes the IOTLB invalidation.
-	 */
 	arm_smmu_domain_inv(smmu_domain);
 }
 
@@ -4309,6 +4294,22 @@ static void arm_smmu_flush_iotlb_all(struct iommu_domain *domain)
 {
 	struct arm_smmu_domain *smmu_domain = to_smmu_domain(domain);
 
+	/*
+	 * If the DMA API is running in non-strict mode then another CPU could
+	 * have changed the page table and not invoked any flush op. Instead the
+	 * other CPU will do an atomic_read() and this CPU will have done an
+	 * atomic_write(). That handshake is enough to acquire the page table
+	 * writes from the other CPU.
+	 *
+	 * All command execution has a dma_wmb() to release all the in-memory
+	 * structures written by this CPU, that barrier must also release the
+	 * writes acquired from all the other CPUs too.
+	 *
+	 * There are other barriers and atomics on this path, but the above is
+	 * the essential mechanism for ensuring that HW sees the page table
+	 * writes from another CPU before it executes the IOTLB invalidation.
+	 */
+
 	if (smmu_domain->smmu)
 		arm_smmu_tlb_inv_context(smmu_domain);
 }
Signature · 1 line
2.43.0
Reviewed-by on v3 10/13
#23 lore raw

Re: [PATCH v3 10/13] iommu/arm-smmu-v3: Move the DMA API comment to flush_iotlb_all

Quoted 7 lines · Jason Gunthorpe

arm_smmu_tlb_inv_context() is the wrong flush_all for this comment, it is only called during io-pgtable destruction not during the dma-iommu operation. Move it to arm_smmu_flush_iotlb_all() which is the flush that is triggered by the dma-iommu lazy flush thread.

#24 lore raw

PATCH v3 11/13 iommu/arm-smmu-v3: Support CONT in paging domains with errata

In reply to Jason Gunthorpe

The erratum (MMU-700: #3777127, S3: #3673557) deals with under invalidation of a CONT PTE grouping in the SMMU. The previous fix was simplified and just assumed the paging domains would never have CONT.

Extend that fix to support CONT in paging domains by making use of the leaf bitmap in the new gather.

If two range invalidations are generated then the middle overlap of the range invalidations may slice a CONT such that it will be under-invalidated for this errata. Search through all possible CONTs in the gather's range and find the largest CONT that could have been sliced.

First try to extend the existing trailing range invalidation to cover the CONT range also, if that isn't possible then issue a third range invalidation that just covers the CONT.

Since iommupt will record what leaf levels it is changing the search can be limited to the the CONT groupings that might have actually been effected, and this in turn reduces the required adjustment to the trailing range invalidation.

This allows all CONTs to work with HW that has the errata and requires at most three range invalidations per gather with no over invalidation.

---
 drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c | 165 ++++++++++++++++++--
 drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h |   2 +-
 2 files changed, 152 insertions(+), 15 deletions(-)
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +151 -14
index 3eb61eb35d0b38..c0daf5102d88a5 100644
@@ -24,6 +24,7 @@
 #include <linux/of.h>
 #include <linux/of_address.h>
 #include <linux/of_platform.h>
+#include <linux/overflow.h>
 #include <linux/pci.h>
 #include <linux/pci-ats.h>
 #include <linux/platform_device.h>
@@ -2516,9 +2517,24 @@ static u64 arm_smmu_range_inv_calc_num(u64 num_tg, unsigned int scale)
 	return DIV_ROUND_UP_ULL(num_tg, 1ULL << scale);
 }
 
+static u64
+arm_smmu_range_inv_last_tg(const struct arm_smmu_range_inv *range_inv)
+{
+	return range_inv->start_tg + (range_inv->num << range_inv->scale) - 1;
+}
+
+/* Range invalidation A encloses the range covered by range invalidation B */
+static bool arm_smmu_range_inv_encloses(const struct arm_smmu_range_inv *a,
+					const struct arm_smmu_range_inv *b)
+{
+	return a->start_tg <= b->start_tg &&
+	       arm_smmu_range_inv_last_tg(a) >= arm_smmu_range_inv_last_tg(b);
+}
+
 /*
  * Initialize the smallest range invalidation covering num_tg and ending at
- * last_tg.
+ * last_tg. Returns a range invalidation with num == 0 if it cannot be
+ * represented without wrapping.
  */
 static struct arm_smmu_range_inv arm_smmu_range_inv_init_end(u64 last_tg,
 							     u64 num_tg)
@@ -2530,7 +2546,9 @@ static struct arm_smmu_range_inv arm_smmu_range_inv_init_end(u64 last_tg,
 
 	range_inv.scale = arm_smmu_range_inv_calc_scale(num_tg);
 	range_inv.num = arm_smmu_range_inv_calc_num(num_tg, range_inv.scale);
-	range_inv.start_tg = last_tg - ((range_inv.num << range_inv.scale) - 1);
+	if (check_sub_overflow(last_tg, (range_inv.num << range_inv.scale) - 1,
+			       &range_inv.start_tg))
+		range_inv.num = 0;
 	return range_inv;
 }
 
@@ -2639,9 +2657,109 @@ static unsigned int arm_smmu_compute_range_ttl(u8 leaf_bitmap, u8 table_bitmap,
 	return ttl;
 }
 
+enum arm_smmu_range_inv_mode {
+	ARM_SMMU_RANGE_INV_NORMAL,
+	ARM_SMMU_RANGE_INV_SINGLE,
+	ARM_SMMU_RANGE_INV_CONT_ERRATA,
+};
+
+/* Number of contiguous entries grouped by CONT at an iommupt leaf level. */
+static unsigned int arm_smmu_tlbi_cont_count_lg2(u8 tgsz_lg2,
+						 unsigned int level)
+{
+	if (tgsz_lg2 == 12 && level <= 3)
+		return ilog2(16); /* 64KB, 32MB, 16GB, 8TB */
+	else if (tgsz_lg2 == 14 && level == 1)
+		return ilog2(32); /* 1GB */
+	else if (tgsz_lg2 == 14 && level == 0)
+		return ilog2(128); /* 2M */
+	else if (tgsz_lg2 == 16 && level <= 2)
+		return ilog2(32); /* 2MB, 16GB, 128TB */
+	return 0;
+}
+
 /*
- * Generate up to two range TLBI command payloads covering [start, last]. Sets
- * use_full_inv if the range is too large to represent.
+ * For the ARM_SMMU_OPT_FULL_CONT_RANGE_INV errata any CONT group must be fully
+ * enclosed by a single range invalidation. The algorithm using two range
+ * invalidations in arm_smmu_tlbi_calc_range() does not guarantee this. So if
+ * two range invalidations were produced we may need to extend the trailing
+ * range invalidation or add a third range invalidation to cover a sliced CONT.
+ * Search for the largest CONT that could have been sliced, extend the trailing
+ * range invalidation when that stays inside the gathered range, or queue an
+ * exact third range invalidation.
+ */
+static void arm_smmu_tlbi_cont_errata(struct arm_smmu_tlbi *tlbi,
+				      const struct arm_smmu_range_inv *first,
+				      struct arm_smmu_range_inv *trail,
+				      unsigned int scale_max, u8 ttl, u8 tg_enc)
+{
+	u8 leaf_levels = tlbi->leaf_levels_bitmap;
+	u64 range_start_tg = tlbi->start >> tlbi->tgsz_lg2;
+	u64 range_last_tg = tlbi->last >> tlbi->tgsz_lg2;
+
+	/* Table only invalidation cannot slice a CONT */
+	if (!leaf_levels)
+		return;
+
+	/*
+	 * Iterate through all the leaf levels that were changed, from highest
+	 * to lowest iommupt level. Check if a possible CONT at that level has
+	 * been sliced between the two range invalidations.
+	 */
+	while (leaf_levels) {
+		struct arm_smmu_range_inv cont = { .num = 1 };
+		unsigned int level = fls(leaf_levels) - 1;
+		struct arm_smmu_range_inv new_trail;
+		unsigned int cont_count_lg2;
+		u64 cont_last_tg;
+
+		leaf_levels &= ~BIT(level);
+		cont_count_lg2 =
+			arm_smmu_tlbi_cont_count_lg2(tlbi->tgsz_lg2, level);
+		if (!cont_count_lg2)
+			continue;
+
+		/* A NUM=0 range invalidation with this SCALE covers the entire CONT. */
+		cont.scale = (tlbi->tgsz_lg2 - 3) * level + cont_count_lg2;
+		if (WARN_ON(cont.scale > scale_max)) {
+			tlbi->range.use_full_inv = true;
+			return;
+		}
+
+		/*
+		 * If the CONT is fully covered by the other range
+		 * invalidations, or is outside the gather's range then it has
+		 * not been sliced.
+		 */
+		cont.start_tg =
+			round_down(trail->start_tg - 1, BIT_ULL(cont.scale));
+		cont_last_tg = arm_smmu_range_inv_last_tg(&cont);
+		if (cont.start_tg < range_start_tg ||
+		    cont_last_tg > range_last_tg ||
+		    arm_smmu_range_inv_encloses(first, &cont) ||
+		    arm_smmu_range_inv_encloses(trail, &cont))
+			continue;
+
+		/*
+		 * Extend the trailing range invalidation backwards to cover the
+		 * CONT. Rounding may move its start before the CONT, but it
+		 * must remain inside the gathered range.
+		 */
+		new_trail = arm_smmu_range_inv_init_end(
+			range_last_tg, range_last_tg - cont.start_tg + 1);
+		if (new_trail.num && new_trail.start_tg >= range_start_tg) {
+			*trail = new_trail;
+			return;
+		}
+
+		arm_smmu_tlbi_add_range_cmd(tlbi, &cont, ttl, tg_enc);
+		return;
+	}
+}
+
+/*
+ * Generate up to three range TLBI command payloads covering [start, last].
+ * Sets use_full_inv if the range is too large to represent.
  *
  * Normally the first range invalidation is the largest representable span which
  * does not exceed the requested range. If necessary, the second range
@@ -2652,10 +2770,16 @@ static unsigned int arm_smmu_compute_range_ttl(u8 leaf_bitmap, u8 table_bitmap,
  * For SVA on an invs containing an SMMU with ARM_SMMU_OPT_FULL_CONT_RANGE_INV,
  * produce only a single range invalidation and overinvalidate so any potential
  * CONT is covered by one command.
+ *
+ * For paging domains affected by ARM_SMMU_OPT_FULL_CONT_RANGE_INV, extend the
+ * normal trailing range invalidation to span a possible CONT group sliced at
+ * the seam. If extending it would invalidate outside the requested range, issue
+ * an exact extra range invalidation.
  */
-static void arm_smmu_tlbi_calc_range(struct arm_smmu_tlbi *tlbi,
-				     bool single_range_inv,
-				     unsigned int scale_max)
+static void
+arm_smmu_tlbi_calc_range(struct arm_smmu_tlbi *tlbi,
+			 enum arm_smmu_range_inv_mode range_inv_mode,
+			 unsigned int scale_max)
 {
 	u8 tgsz_lg2 = tlbi->tgsz_lg2;
 	unsigned int ttl = arm_smmu_compute_range_ttl(
@@ -2683,7 +2807,7 @@ static void arm_smmu_tlbi_calc_range(struct arm_smmu_tlbi *tlbi,
 		return;
 	}
 
-	if (single_range_inv) {
+	if (range_inv_mode == ARM_SMMU_RANGE_INV_SINGLE) {
 		/*
 		 * Produce a single invalidation by rounding up and disabling
 		 * the trailer.
@@ -2701,8 +2825,12 @@ static void arm_smmu_tlbi_calc_range(struct arm_smmu_tlbi *tlbi,
 	}
 	arm_smmu_tlbi_add_range_cmd(tlbi, &first, ttl, tg_enc);
 
-	if (trail.num)
+	if (trail.num) {
+		if (range_inv_mode == ARM_SMMU_RANGE_INV_CONT_ERRATA)
+			arm_smmu_tlbi_cont_errata(tlbi, &first, &trail,
+						  scale_max, ttl, tg_enc);
 		arm_smmu_tlbi_add_range_cmd(tlbi, &trail, ttl, tg_enc);
+	}
 }
 
 /*
@@ -2950,11 +3078,20 @@ void arm_smmu_domain_tlbi(struct arm_smmu_tlbi *tlbi,
 	 */
 	if (invs->range_inv_scale_max) {
 		if (!tlbi->range.use_full_inv) {
-			arm_smmu_tlbi_calc_range(
-				tlbi,
-				smmu_domain->stage == ARM_SMMU_DOMAIN_SVA &&
-					invs->has_full_cont_range_inv,
-				invs->range_inv_scale_max);
+			enum arm_smmu_range_inv_mode range_inv_mode =
+				ARM_SMMU_RANGE_INV_NORMAL;
+
+			if (invs->has_full_cont_range_inv) {
+				if (smmu_domain->stage == ARM_SMMU_DOMAIN_SVA)
+					range_inv_mode =
+						ARM_SMMU_RANGE_INV_SINGLE;
+				else
+					range_inv_mode =
+						ARM_SMMU_RANGE_INV_CONT_ERRATA;
+			}
+
+			arm_smmu_tlbi_calc_range(tlbi, range_inv_mode,
+						 invs->range_inv_scale_max);
 		}
 	}
 
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h +1 -1
index 7106bd3a8bd7f6..a59b17679e6716 100644
@@ -860,7 +860,7 @@ struct arm_smmu_tlbi {
 	struct {
 		bool use_full_inv;
 		u8 num_cmds;
-		struct arm_smmu_cmd cmds[2];
+		struct arm_smmu_cmd cmds[3];
 	} range;
 };
 
Signature · 1 line
2.43.0
#25 lore raw

PATCH v3 12/13 iommu/arm-smmu-v3: Use the generic iommu page table

In reply to Jason Gunthorpe

Switch to use the iommupt provided page table. This is fairly straightforward now since the page table construction and hwinfo are very similar to io-pgtable-arm.

The struct pt_iommu_armv8_hw_info is a direct replacement for 'tcr' and I have a kunit compare test validating that the fields have identical values for identical configurations.

Quirks are replaced by features
IO_PGTABLE_QUIRK_ARM_HD -> PT_FEAT_ARMV8_DBM IO_PGTABLE_QUIRK_ARM_S2FWB -> PT_FEAT_ARMV8_S2FWB

SMMU features are mapped to iommupt features:
ARM_SMMU_FEAT_COHERENCY -> PT_FEAT_DMA_INCOHERENT ARM_SMMU_FEAT_VAX -> PT_FEAT_ARMV8_LVA ARM_SMMU_FEAT_S2FWB -> PT_FEAT_ARMV8_S2FWB

Remove the iommu_flush_ops entirely, iommupt only uses gathers for invalidation. Wire the tlbi directly to the gather.

Remove the trampoline for map/unmap/iova/read_and_clear_dirt. iommupt directly provides the domain ops. Domain initialization is largely moved into iommupt common code.

Change the kunit to fully create a page table to generate the tcr bits for testing.

Compared to io-pgtable-arm iommupt has a number of key differences:
- CONT support
- Unmap yields a single gather which generates a single tlbi operation
* free_list is always used to free after invalidate
* walk cache and leaf invalidation are combined in cases without range invalidation instead of being duplicated
* the cutover to all-invalidate without range invalidation covers walk invalidation now too, umap -> single gather -> single all invalidate.
* Range invalidation flushes the walk cache and leafs together with a good TTL hint.
* Range invalidation always generates at most two commands from any gather.

---
 drivers/iommu/arm/Kconfig                     |   4 +-
 .../iommu/arm/arm-smmu-v3/arm-smmu-v3-test.c  |  45 +--
 drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c   | 260 +++++-------------
 drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h   |  17 +-
 4 files changed, 108 insertions(+), 218 deletions(-)
drivers/iommu/arm/Kconfig +3 -1
index 5fac08b89deea7..495b03ad3cf6c1 100644
@@ -77,7 +77,9 @@ config ARM_SMMU_V3
 	tristate "ARM Ltd. System MMU Version 3 (SMMUv3) Support"
 	depends on ARM64
 	select IOMMU_API
-	select IOMMU_IO_PGTABLE_LPAE
+	select GENERIC_PT
+	select IOMMU_PT
+	select IOMMU_PT_ARMV8
 	select GENERIC_MSI_IRQ
 	select IOMMUFD_DRIVER if IOMMUFD
 	help
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3-test.c +23 -22

80 lines not on this page · raw message

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +75 -185

436 lines not on this page · raw message

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h +7 -10
index a59b17679e6716..17ad696ed69305 100644
@@ -9,6 +9,7 @@
 #define _ARM_SMMU_V3_H
 
 #include <linux/bitfield.h>
+#include <linux/generic_pt/iommu.h>
 #include <linux/iommu.h>
 #include <linux/iommufd.h>
 #include <linux/kernel.h>
@@ -824,12 +825,6 @@ static inline unsigned int arm_smmu_pt_level_to_lg2sz(unsigned int tgsz_lg2,
 	return tgsz_lg2 + (tgsz_lg2 - ilog2(sizeof(u64))) * level;
 }
 
-static inline unsigned int arm_smmu_pt_lg2sz_to_level(unsigned int tgsz_lg2,
-						      unsigned int lg2sz)
-{
-	return (lg2sz - tgsz_lg2) / (tgsz_lg2 - ilog2(sizeof(u64)));
-}
-
 struct arm_smmu_tlbi {
 	unsigned long start;
 	unsigned long last;
@@ -1094,9 +1089,12 @@ enum arm_smmu_domain_stage {
 };
 
 struct arm_smmu_domain {
-	struct arm_smmu_device		*smmu;
+	union {
+		struct iommu_domain	domain;
+		struct pt_iommu_armv8	armv8pt;
+	};
 
-	struct io_pgtable_ops		*pgtbl_ops;
+	struct arm_smmu_device		*smmu;
 	atomic_t			nr_ats_masters;
 
 	enum arm_smmu_domain_stage	stage;
@@ -1105,8 +1103,6 @@ struct arm_smmu_domain {
 		struct arm_smmu_s2_cfg		s2_cfg;
 	};
 
-	struct iommu_domain		domain;
-
 	struct arm_smmu_invs __rcu	*invs;
 
 	/* List of struct arm_smmu_master_domain */
@@ -1118,6 +1114,7 @@ struct arm_smmu_domain {
 
 	struct mmu_notifier		mmu_notifier;
 };
+PT_IOMMU_CHECK_DOMAIN(struct arm_smmu_domain, armv8pt.iommu, domain);
 
 struct arm_smmu_nested_domain {
 	struct iommu_domain domain;
Signature · 1 line
2.43.0
#26 lore raw

PATCH v3 13/13 iommu: Remove pgsize from iommu_iotlb_gather

In reply to Jason Gunthorpe

SMMUv3 was the only user, remove it and iommu_iotlb_gather_add_range_pgsize() which is also unused now.

---
 include/linux/iommu.h | 62 +++++++++----------------------------------
 1 file changed, 13 insertions(+), 49 deletions(-)
include/linux/iommu.h +13 -49
index ef5043752a3651..339ea708f352fb 100644
@@ -361,29 +361,21 @@ struct iommu_iotlb_gather {
 	 */
 	unsigned long		end;
 
-	union {
+	struct {
 		/**
-		 * @pgsize: The interval at which to perform the flush, only
-		 *          used by arm-smmu-v3
+		 * @pt.leaf_levels_bitmap: Bitmap of generic_pt levels where
+		 * leaf entries were unmapped. Bit 0 means the leaf only level.
+		 * If 0 no leafs were unmapped.
 		 */
-		size_t pgsize;
-		struct {
-			/**
-			 * @pt.leaf_levels_bitmap: Bitmap of generic_pt
-			 * levels where leaf entries were unmapped. Bit 0
-			 * means the leaf only level. If 0 no leafs
-			 * were unmapped.
-			 */
-			u8 leaf_levels_bitmap;
-			/**
-			 * @pt.table_levels_bitmap: Bitmap of generic_pt levels
-			 * of table entries that were removed. Bit 0 is never
-			 * set, bit 1 means a table of all leafs was removed.
-			 * When freelist is empty this must be 0.
-			 */
-			u8 table_levels_bitmap;
-		} pt;
-	};
+		u8 leaf_levels_bitmap;
+		/**
+		 * @pt.table_levels_bitmap: Bitmap of generic_pt levels of table
+		 * entries that were removed. Bit 0 is never set, bit 1 means a
+		 * table of all leafs was removed. When freelist is empty this
+		 * must be 0.
+		 */
+		u8 table_levels_bitmap;
+	} pt;
 
 	/**
 	 * @freelist: Removed pages to free after sync, only used by
@@ -1062,34 +1054,6 @@ static inline void iommu_iotlb_gather_add_range(struct iommu_iotlb_gather *gathe
 		gather->end = end;
 }
 
-/**
- * iommu_iotlb_gather_add_page - Gather for page-based TLB invalidation
- * @domain: IOMMU domain to be invalidated
- * @gather: TLB gather data
- * @iova: start of page to invalidate
- * @size: size of page to invalidate
- *
- * Helper for IOMMU drivers to build invalidation commands based on individual
- * pages, or with page size/table level hints which cannot be gathered if they
- * differ.
- */
-static inline void iommu_iotlb_gather_add_page(struct iommu_domain *domain,
-					       struct iommu_iotlb_gather *gather,
-					       unsigned long iova, size_t size)
-{
-	/*
-	 * If the new page is disjoint from the current range or is mapped at
-	 * a different granularity, then sync the TLB so that the gather
-	 * structure can be rewritten.
-	 */
-	if ((gather->pgsize && gather->pgsize != size) ||
-	    iommu_iotlb_gather_is_disjoint(gather, iova, size))
-		iommu_iotlb_sync(domain, gather);
-
-	gather->pgsize = size;
-	iommu_iotlb_gather_add_range(gather, iova, size);
-}
-
 static inline bool iommu_iotlb_gather_queued(struct iommu_iotlb_gather *gather)
 {
 	return gather && gather->queued;
Signature · 1 line
2.43.0
Tested-by on the v3 series
#27 lore raw
In reply to Jason Gunthorpe
Quoted 11 lines · Jason Gunthorpe

v3:
- Rebase on v7.4-rc2
- Split the armv8 patch into three parts, generic, db, and iommu
- Clarify some comments, mark some more debug things as WARN_ON
- Use tgsz instead of granule for consistency
- Refactor checks into armv8pt_validate_features() and add more
- Drop PT_FEAT_ARMV8_AARCH32
- Fix make dirty logic
- Use arch/arm64 constants instead of copying for SVA
- Mitigate the CONT under invalidation errata
- Pull in the left over two patches from v9 of the precursor series:

Quoted 1 line
     https://patch.msgid.link/r/[email protected]

I've verified v3 with S1/S2/SVA sanity.