Skip to contentSkip to conversation

iommupt: Introduce IO page table shrinker

RFC PATCH In review Pranjal Shrivastava 4 participants 11 messages Oct 1 – Nov 9

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

cover iommupt: Introduce IO page table shrinker

Introduce a lockless, deferred reclamation framework for IOMMU page tables built on the generic_pt library. As VMMs and userspace drivers map and unmap large, sparse IOVA regions through VFIO and iommufd, page table directories are often left allocated but completely empty. generic_pt frees a table when a single unmap covers it entirely, but tables that empty through a series of partial unmaps stay allocated until the domain is destroyed. Under memory pressure, this *stranded* memory cannot be reclaimed and has resulted in OOMs.

This series refcounts leaf directories natively in struct ioptdesc and registers a domain-aware MM shrinker that prunes empty directories under system memory pressure.

This is an RFC to align on the design. It has known issues, listed below, and is not intended for merging as-is.

Design
======
- Refcounting: the __page_refcount of a leaf directory's struct ioptdesc counts its valid leaf entries, plus one for the table itself. Map takes a reference with atomic_inc_not_zero() before installing a leaf, and unmap drops it after clearing one. Leaf entries are counted only in the table that holds them, so map and unmap never update refcounts on the shared tables above it.
- Queueing: when the refcount drops to 1, the directory is empty and is logged with its IOVA into a per-domain xarray (reclaim_list). Only non-DMA domains are queued.
- Claim: under memory pressure, the shrinker walks the queued directories and claims each with atomic_cmpxchg(refcount, 1, 0). A map that finds the refcount at 0 fails atomic_inc_not_zero() and retries, so it never reuses a claimed directory.
- Sever: a format-agnostic top-down walk (sever_branch) clears the parent slot with cmpxchg, severing the dead branch from the live tree.
- Free: the domain's IOTLB is flushed so the IOMMU drops any cached pointers to the severed tables. A single synchronize_srcu() then waits for in-flight map walkers before the pages are freed.

The cost is one atomic operation per leaf entry on map and unmap, plus an xarray insert when a directory becomes empty.

Known issues
============
These are understood and will be addressed in the next version:

- Map vs. shrinker retry: on a claimed directory, map returns -EAGAIN, which __map_range() already uses to re-descend into the cached table pointer, i.e. the dead directory. It needs a distinct error and a retry from the top.
- Unmap vs. shrinker hand-off: an unmap that fully covers a queued directory, or a large-page map over an empty range, frees it directly while the xarray still references it.
- xarray keys: the key is the IOVA where the emptying unmap started, so a directory can be queued under several keys and nr_reclaimable over-counts. Keying by the table's PFN makes entries unique.
- A failed sever leaves the refcount at 0 instead of restoring it to 1. The top-level table, which has no parent, should never be queued.
- iommufd allocates paging domains without iommu_domain_init(), so their reclaim_list is not initialised.
- Combined with the observability series, pages must be uncharged from their domain at sever time, as they are freed after the domain may be gone.

Open questions
==============
- Leaf directories with child tables: a leaf directory above the last level (e.g. one holding a 2M leaf) can gain a child table, which is not counted, and could then be reclaimed while the child is live. Should child tables be counted at install, or counting be restricted to last-level directories?
- SRCU in reclaim context: the shrinker can run from direct reclaim inside a map's SRCU read section, where synchronize_srcu() would wait on itself. Should the free be deferred (work item / call_srcu), or is a different scheme preferred?
- IOTLB flush granularity: flush_iotlb_all() is used after severing. Would a range-based paging-structure flush be preferred?
- DMA-API domains are excluded since their unmap can run in IRQ context. Should the per-leaf atomics also be skipped for them?

Upcoming Work / Roadmap
=======================
An IO page table observability series, which attributes page table memory to its domain and exposes it via fdinfo, is posted separately as an RFC. The two series are independent; this one applies on v7.3-rc5 by itself.

There's an alignment session at Linux Plumbers Conference 2026 for these [1].

[1] https://lpc.events/event/20/contributions/2624/

Pranjal Shrivastava (5):
iommu: Add reclaim_list xarray to struct iommu_domain
iommupt: Implement refcounting logic for Leaf entries
iommupt: Add lockless sever_branch helper
iommupt: Introduce lockless page table shrinker
iommupt: Return real page count to the shrinker core

 drivers/iommu/Makefile              |   2 +-
 drivers/iommu/generic_pt/iommu_pt.h |  81 ++++++++++++++++-
 drivers/iommu/generic_pt/shrinker.c | 135 ++++++++++++++++++++++++++++
 drivers/iommu/iommu.c               |   2 +
 include/linux/generic_pt/iommu.h    |  29 ++++++
 include/linux/iommu.h               |   3 +
 6 files changed, 249 insertions(+), 3 deletions(-)
 create mode 100644 drivers/iommu/generic_pt/shrinker.c

base-commit: 72d3fcf802c45d00b300f25b848a93c3a2bd7c7e

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

RFC PATCH 1/5 iommu: Add reclaim_list xarray to struct iommu_domain

Introduce struct xarray reclaim_list to struct iommu_domain. This will serve as the O(1) storage where the fast path stores empty directories by their associated IOVA. IOVA is required by the shrinker to perform a top-down tree walk to safely locate and prune the parent pointer. While xa_store requires a localized spinlock, this path is only triggered when a directory reaches a completely empty state, keeping the vast majority of mapping operations lock-free.

---
 drivers/iommu/iommu.c | 2 ++
 include/linux/iommu.h | 3 +++
 2 files changed, 5 insertions(+)
drivers/iommu/iommu.c +2 -0
index cd1bca7ede9a..5d814854d825 100644
@@ -2074,6 +2074,7 @@ static void iommu_domain_init(struct iommu_domain *domain, unsigned int type,
 	domain->owner = ops;
 	if (!domain->ops)
 		domain->ops = ops->default_domain_ops;
+	xa_init(&domain->reclaim_list);
 }
 
 static struct iommu_domain *
@@ -2126,6 +2127,7 @@ EXPORT_SYMBOL_GPL(iommu_paging_domain_alloc_flags);
 
 void iommu_domain_free(struct iommu_domain *domain)
 {
+	xa_destroy(&domain->reclaim_list);
 	switch (domain->cookie_type) {
 	case IOMMU_COOKIE_DMA_IOVA:
 		iommu_put_dma_cookie(domain);
include/linux/iommu.h +3 -0
index ac43b8b93f14..b9611631ea80 100644
@@ -14,6 +14,7 @@
 #include <linux/err.h>
 #include <linux/of.h>
 #include <linux/iova_bitmap.h>
+#include <linux/xarray.h>
 #include <uapi/linux/iommufd.h>
 
 #define IOMMU_READ	(1 << 0)
@@ -249,6 +250,8 @@ struct iommu_domain {
 			struct list_head next;
 		};
 	};
+
+	struct xarray reclaim_list;
 };
 
 static inline bool iommu_is_dma_domain(struct iommu_domain *domain)
Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#2 lore raw

RFC PATCH 2/5 iommupt: Implement refcounting logic for Leaf entries

In reply to Pranjal Shrivastava

Implement a lockless state machine using the ioptdesc's __page_refcount field. During an unmap, the driver executes atomic_sub_return() when clearing a leaf PTE. If the refcount drops to the baseline state (1), the directory is completely empty and its pointer is stored to the domain's reclaim_list Xarray.

To protect against a concurrent background Shrinker pruning a directory while a map thread is actively populating it, the map thread must acquire a reference using atomic_inc_not_zero() before installing a new leaf. If the acquisition fails, the page has been marked dead (0) by the Shrinker. The map thread cleanly returns -EAGAIN, forcing the walker to loop and re-allocate a fresh directory.

Only non-DMA domains are queued: DMA API unmaps can run in IRQ context and the reclaim_list lock is not IRQ safe.

---
 drivers/iommu/generic_pt/iommu_pt.h | 26 ++++++++++++++++++++++++++
 1 file changed, 26 insertions(+)
drivers/iommu/generic_pt/iommu_pt.h +26 -0
index 07ec2b3ab986..c3d09b746eec 100644
@@ -621,6 +621,13 @@ static int __map_range_leaf(struct pt_range *range, void *arg,
 			PT_WARN_ON(compute_best_pgsize(&pts, oa) !=
 				   leaf_pgsize_lg2);
 		}
+
+		/* If refcount = 0, shrinker killed the page, retry map */
+		if (!atomic_inc_not_zero(&virt_to_ioptdesc(pts.table)->__page_refcount)) {
+			ret = -EAGAIN;
+			break;
+		}
+
 		pt_install_leaf_entry(&pts, oa, leaf_pgsize_lg2, &map->attrs);
 
 		oa += log2_to_int(leaf_pgsize_lg2);
@@ -754,6 +761,11 @@ static __always_inline int __do_map_single_page(struct pt_range *range,
 	if (pts.level == 0) {
 		if (pts.type != PT_ENTRY_EMPTY)
 			return -EADDRINUSE;
+
+		/* If refcount = 0, shrinker killed the page, retry map */
+		if (!atomic_inc_not_zero(&virt_to_ioptdesc(pts.table)->__page_refcount))
+			return -EAGAIN;
+
 		pt_install_leaf_entry(&pts, map->oa, PAGE_SHIFT,
 				      &map->attrs);
 		/* No flush, not used when incoherent */
@@ -1087,6 +1099,20 @@ static __maybe_unused int __unmap_range(struct pt_range *range, void *arg,
 			 */
 			num_contig_lg2 = pt_entry_num_contig_lg2(&pts);
 			pt_clear_entries(&pts, num_contig_lg2);
+
+			/* Drop refcount and add to reclaim_list for the last ref */
+			/*
+			 * DMA API unmaps can run in IRQ context and the reclaim_list
+			 * lock is not IRQ safe, so only queue for non-DMA domains.
+			 */
+			if (atomic_dec_return(&virt_to_ioptdesc(pts.table)->__page_refcount) == 1 &&
+			    !iommu_is_dma_domain(&iommu_from_common(range->common)->domain)) {
+				struct pt_iommu *iommu = iommu_from_common(range->common);
+
+				xa_store(&iommu->domain.reclaim_list, range->va,
+					 virt_to_ioptdesc(pts.table), GFP_ATOMIC);
+			}
+
 			gather_add_leaf(&unmap->pending, &pts);
 			num_oas += log2_to_int(num_contig_lg2);
 			if (pts.index < flush_start_index)
Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#3 lore raw

RFC PATCH 3/5 iommupt: Add lockless sever_branch helper

In reply to Pranjal Shrivastava

Introduce a new sever_branch pt_iommu_op. This helper performs a top-down walk to locate the target parent slot and safely executes a lockless cmpxchg to 0x0. Because generic_pt abstracts all hardware PTEs as u64, this safely utilizes the existing pt_table_install64 to cleanly sever the branch regardless of the underlying IOMMU format.

---
 drivers/iommu/generic_pt/iommu_pt.h | 40 +++++++++++++++++++++++++++++
 include/linux/generic_pt/iommu.h    | 14 ++++++++++
 2 files changed, 54 insertions(+)
drivers/iommu/generic_pt/iommu_pt.h +40 -0
index c3d09b746eec..868242eb2d55 100644
@@ -1155,6 +1155,45 @@ static size_t NS(unmap_range)(struct pt_iommu *iommu_table, dma_addr_t iova,
 	return unmap.unmapped;
 }
 
+struct pt_sever_args {
+	phys_addr_t expected_phys;
+	bool success;
+};
+
+static int __sever_branch(struct pt_range *range, void *arg,
+			  unsigned int level, struct pt_table_p *table)
+{
+	struct pt_state pts = pt_init(range, level, table);
+	struct pt_sever_args *sever = arg;
+
+	switch (pt_load_single_entry(&pts)) {
+	case PT_ENTRY_TABLE:
+		if (virt_to_phys(pt_table_ptr(&pts)) == sever->expected_phys) {
+			sever->success = pt_table_install64(&pts, 0x0);
+			return 1; /* Stop walking */
+		}
+		return pt_descend(&pts, arg, __sever_branch);
+	default:
+		break;
+	}
+	return 0;
+}
+
+static bool NS(sever_branch)(struct pt_iommu *iommu_table, dma_addr_t iova,
+			     phys_addr_t expected_phys)
+{
+	struct pt_range range;
+	struct pt_sever_args sever = { .expected_phys = expected_phys, .success = false };
+	int ret;
+
+	ret = make_range(common_from_iommu(iommu_table), &range, iova, 1);
+	if (ret)
+		return false;
+
+	pt_walk_range(&range, __sever_branch, &sever);
+	return sever.success;
+}
+
 static void NS(get_info)(struct pt_iommu *iommu_table,
 			 struct pt_iommu_info *info)
 {
@@ -1208,6 +1247,7 @@ static void NS(deinit)(struct pt_iommu *iommu_table)
 static const struct pt_iommu_ops NS(ops) = {
 	.map_range = NS(map_range),
 	.unmap_range = NS(unmap_range),
+	.sever_branch = NS(sever_branch),
 #if IS_ENABLED(CONFIG_IOMMUFD_DRIVER) && defined(pt_entry_is_write_dirty) && \
 	IS_ENABLED(CONFIG_IOMMUFD_TEST) && defined(pt_entry_make_write_dirty)
 	.set_dirty = NS(set_dirty),
include/linux/generic_pt/iommu.h +14 -0
index dd0edd02a48a..d1ade1767a9a 100644
@@ -137,6 +137,20 @@ struct pt_iommu_ops {
 			      dma_addr_t len,
 			      struct iommu_iotlb_gather *iotlb_gather);
 
+	/**
+	 * @sever_branch: Locklessly sever an empty page table branch
+	 * @iommu_table: Table to manipulate
+	 * @iova: IO virtual address associated with the branch
+	 * @expected_phys: Expected physical address of the child directory
+	 *
+	 * Context: Executed locklessly by a background Shrinker.
+	 * Uses cmpxchg to write 0x0 to the parent slot.
+	 *
+	 * Returns: true if successfully severed, false if aborted.
+	 */
+	bool (*sever_branch)(struct pt_iommu *iommu_table, dma_addr_t iova,
+			     phys_addr_t expected_phys);
+
 	/**
 	 * @set_dirty: Make the iova write dirty
 	 * @iommu_table: Table to manipulate
Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#4 lore raw

RFC PATCH 4/5 iommupt: Introduce lockless page table shrinker

In reply to Pranjal Shrivastava

Under system memory pressure, intermediate IOMMU page table directories that were left stranded by sparse unmaps consume valuable RAM. Introduce an IO Page Table Shrinker to reclaim such memory.

The shrinker locklessly harvests empty directories from the per-domain Xarrays, severs them from the page table tree using the format-agnostic sever_branch helper. It employs a single, global synchronize_srcu grace period before freeing the memory to protect against concurrent maps. SRCU is an appropriate choice because the allocation during map may sleep

After severing, flush the domain's IOTLB so the IOMMU drops any cached pointers to the severed tables before they are freed.

---
 drivers/iommu/Makefile              |   2 +-
 drivers/iommu/generic_pt/iommu_pt.h |  16 +++-
 drivers/iommu/generic_pt/shrinker.c | 136 ++++++++++++++++++++++++++++
 include/linux/generic_pt/iommu.h    |  10 ++
 4 files changed, 160 insertions(+), 4 deletions(-)
 create mode 100644 drivers/iommu/generic_pt/shrinker.c
drivers/iommu/Makefile +1 -1
index 2f05725eaab1..ad30c4b7566e 100644
@@ -3,7 +3,7 @@ obj-y += arm/ iommufd/
 obj-$(CONFIG_AMD_IOMMU) += amd/
 obj-$(CONFIG_INTEL_IOMMU) += intel/
 obj-$(CONFIG_RISCV_IOMMU) += riscv/
-obj-$(CONFIG_GENERIC_PT) += generic_pt/fmt/
+obj-$(CONFIG_GENERIC_PT) += generic_pt/fmt/ generic_pt/shrinker.o
 obj-$(CONFIG_HYPERV) += hyperv/
 obj-$(CONFIG_IOMMU_API) += iommu.o
 obj-$(CONFIG_IOMMU_SUPPORT) += iommu-pages.o
drivers/iommu/generic_pt/iommu_pt.h +13 -3
index 868242eb2d55..e5ee419f2f0b 100644
@@ -916,7 +916,7 @@ static int check_map_range(struct pt_iommu *iommu_table, struct pt_range *range,
 static int do_map(struct pt_range *range, struct pt_common *common,
 		  bool single_page, struct pt_iommu_map_args *map)
 {
-	int ret;
+	int ret, idx;
 
 	/*
 	 * The __map_single_page() fast path does not support DMA_INCOHERENT
@@ -924,17 +924,21 @@ static int do_map(struct pt_range *range, struct pt_common *common,
 	 */
 	if (single_page && !pt_feature(common, PT_FEAT_DMA_INCOHERENT)) {
 
+		idx = srcu_read_lock(&generic_pt_srcu);
 		ret = pt_walk_range(range, __map_single_page, map);
+		srcu_read_unlock(&generic_pt_srcu, idx);
 		if (ret != -EAGAIN)
 			return ret;
 		/* EAGAIN falls through to the full path */
 	}
 
 	do {
+		idx = srcu_read_lock(&generic_pt_srcu);
 		if (map->leaf_level == range->top_level)
 			ret = pt_walk_range(range, __map_range_leaf, map);
 		else
 			ret = pt_walk_range(range, __map_range, map);
+		srcu_read_unlock(&generic_pt_srcu, idx);
 	} while (ret == -EAGAIN);
 	return ret;
 }
@@ -1142,13 +1146,15 @@ static size_t NS(unmap_range)(struct pt_iommu *iommu_table, dma_addr_t iova,
 			unmap.pending.free_list),
 	};
 	struct pt_range range;
-	int ret;
+	int ret, idx;
 
 	ret = make_range(common_from_iommu(iommu_table), &range, iova, len);
 	if (ret)
 		return 0;
 
+	idx = srcu_read_lock(&generic_pt_srcu);
 	pt_walk_range(&range, __unmap_range, &unmap);
+	srcu_read_unlock(&generic_pt_srcu, idx);
 
 	gather_range_pending(&unmap.pending, iommu_table, iova, unmap.unmapped);
 
@@ -1170,7 +1176,8 @@ static int __sever_branch(struct pt_range *range, void *arg,
 	case PT_ENTRY_TABLE:
 		if (virt_to_phys(pt_table_ptr(&pts)) == sever->expected_phys) {
 			sever->success = pt_table_install64(&pts, 0x0);
-			return 1; /* Stop walking */
+			/* Stop walking */
+			return 1;
 		}
 		return pt_descend(&pts, arg, __sever_branch);
 	default:
@@ -1231,6 +1238,8 @@ static void NS(deinit)(struct pt_iommu *iommu_table)
 			collect.pending.free_list),
 	};
 
+	generic_pt_shrinker_remove(iommu_table);
+
 	iommu_pages_list_add(&collect.pending.free_list, range.top_table);
 	pt_walk_range(&range, __collect_tables, &collect);
 
@@ -1407,6 +1416,7 @@ int pt_iommu_init(struct pt_iommu_table *fmt_table,
 
 	/* Must be last, see pt_iommu_deinit() */
 	iommu_table->ops = &NS(ops);
+	generic_pt_shrinker_add(iommu_table);
 	return 0;
 }
 EXPORT_SYMBOL_NS_GPL(pt_iommu_init, "GENERIC_PT_IOMMU");
drivers/iommu/generic_pt/shrinker.c new file +136 -0

136 lines not on this page · raw message

include/linux/generic_pt/iommu.h +10 -0
index d1ade1767a9a..95bf9d4f0b6e 100644
@@ -64,8 +64,18 @@ struct pt_iommu {
 	 * page table which must have dma ops that perform cache flushing.
 	 */
 	struct device *iommu_device;
+
+	/**
+	 * @shrinker_list: Node for the generic_pt global shrinker list
+	 */
+	struct list_head shrinker_list;
 };
 
+extern struct srcu_struct generic_pt_srcu;
+
+void generic_pt_shrinker_add(struct pt_iommu *iommu);
+void generic_pt_shrinker_remove(struct pt_iommu *iommu);
+
 static inline struct pt_iommu *iommupt_from_domain(struct iommu_domain *domain)
 {
 	if (!IS_ENABLED(CONFIG_IOMMU_PT) || !domain->is_iommupt)
Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#5 lore raw

RFC PATCH 5/5 iommupt: Return real page count to the shrinker core

In reply to Pranjal Shrivastava

Update the count op to return real nr_pages that can be reclaimed.

---
 drivers/iommu/generic_pt/iommu_pt.h | 1 +
 drivers/iommu/generic_pt/shrinker.c | 9 ++++-----
 include/linux/generic_pt/iommu.h    | 5 +++++
 3 files changed, 10 insertions(+), 5 deletions(-)
drivers/iommu/generic_pt/iommu_pt.h +1 -0
index e5ee419f2f0b..4386caf3f713 100644
@@ -1115,6 +1115,7 @@ static __maybe_unused int __unmap_range(struct pt_range *range, void *arg,
 
 				xa_store(&iommu->domain.reclaim_list, range->va,
 					 virt_to_ioptdesc(pts.table), GFP_ATOMIC);
+				atomic_long_inc(&iommu->nr_reclaimable);
 			}
 
 			gather_add_leaf(&unmap->pending, &pts);
drivers/iommu/generic_pt/shrinker.c +4 -5
index 66169fb5db71..a27e171b5e80 100644
@@ -43,11 +43,7 @@ static unsigned long generic_pt_shrinker_count(struct shrinker *shrink,
 
 	mutex_lock(&generic_pt_domains_list_lock);
 	list_for_each_entry(iommu, &generic_pt_domains_list, shrinker_list) {
-		struct iommu_domain *domain = &iommu->domain;
-
-		/* TODO: Return real nr_pages here! */
-		if (!xa_empty(&domain->reclaim_list))
-			count += 1;
+		count += atomic_long_read(&iommu->nr_reclaimable);
 	}
 	mutex_unlock(&generic_pt_domains_list_lock);
 
@@ -78,15 +74,18 @@ static unsigned long generic_pt_shrinker_scan(struct shrinker *shrink,
 				if (iommu->ops->sever_branch(iommu, iova, virt_to_phys(virt))) {
 					/* Successfully severed, queue for freeing */
 					xa_erase(&domain->reclaim_list, iova);
+					atomic_long_dec(&iommu->nr_reclaimable);
 					iommu_pages_list_add(&free_list, virt);
 					freed_count++;
 				} else {
 					/* We raced with map, abort pruning */
 					xa_erase(&domain->reclaim_list, iova);
+					atomic_long_dec(&iommu->nr_reclaimable);
 				}
 			} else {
 				/* Not empty anymore, remove from list */
 				xa_erase(&domain->reclaim_list, iova);
+				atomic_long_dec(&iommu->nr_reclaimable);
 			}
 		}
 
include/linux/generic_pt/iommu.h +5 -0
index 95bf9d4f0b6e..3c94745bded0 100644
@@ -69,6 +69,11 @@ struct pt_iommu {
 	 * @shrinker_list: Node for the generic_pt global shrinker list
 	 */
 	struct list_head shrinker_list;
+
+	/**
+	 * @nr_reclaimable: Count of empty directories waiting in reclaim_list
+	 */
+	atomic_long_t nr_reclaimable;
 };
 
 extern struct srcu_struct generic_pt_srcu;
Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#6 lore raw
In reply to Pranjal Shrivastava
Quoted 9 lines · Pranjal Shrivastava

Introduce a lockless, deferred reclamation framework for IOMMU page tables built on the generic_pt library. As VMMs and userspace drivers map and unmap large, sparse IOVA regions through VFIO and iommufd, page table directories are often left allocated but completely empty. generic_pt frees a table when a single unmap covers it entirely, but tables that empty through a series of partial unmaps stay allocated until the domain is destroyed. Under memory pressure, this *stranded* memory cannot be reclaimed and has resulted in OOMs.

Quoted 3 lines

This series refcounts leaf directories natively in struct ioptdesc and registers a domain-aware MM shrinker that prunes empty directories under system memory pressure.

We had talked about doing it this way

But I had proposed a different, and possibly simpler, solution that addresses *just* the iommufd use case.

After unmapping something have iommufd compute the gap in IOVA that contains what was unmapped and then issue a 'clean(gap)' operation to generic_pt.

This is the same operation as unmap, except we know now that the gap has no PTEs so all it does is clean up the table pointers.

This requires no special refcounting or anything difficult beyond some locking in iommufd to hold the gap stable while we clean it.

Would it work for you? It seems substantially simpler, but I never tried to implement it.

An alternative version is closer to what you have here, somehow connect iommufd to the shrinker and have it lock and walk the gaps cleaning them on shrink requests?

iommufd has no trouble walking the gaps in the interval tree, there is a helper that does that computation.

Jason

#7 lore raw
Quoted 23 lines · Jason Gunthorpe
Quoted 9 lines · Pranjal Shrivastava

Introduce a lockless, deferred reclamation framework for IOMMU page tables built on the generic_pt library. As VMMs and userspace drivers map and unmap large, sparse IOVA regions through VFIO and iommufd, page table directories are often left allocated but completely empty. generic_pt frees a table when a single unmap covers it entirely, but tables that empty through a series of partial unmaps stay allocated until the domain is destroyed. Under memory pressure, this *stranded* memory cannot be reclaimed and has resulted in OOMs.

Quoted 3 lines

This series refcounts leaf directories natively in struct ioptdesc and registers a domain-aware MM shrinker that prunes empty directories under system memory pressure.

We had talked about doing it this way

But I had proposed a different, and possibly simpler, solution that addresses *just* the iommufd use case.

After unmapping something have iommufd compute the gap in IOVA that contains what was unmapped and then issue a 'clean(gap)' operation to generic_pt.

Quoted 9 lines

This is the same operation as unmap, except we know now that the gap has no PTEs so all it does is clean up the table pointers.

This requires no special refcounting or anything difficult beyond some locking in iommufd to hold the gap stable while we clean it.

Would it work for you? It seems substantially simpler, but I never tried to implement it.

I was tempted to use the interval trees too, but I started thinking about:

a) Locking: For the gap to stay stable while we clean it, we'd need to add some kind of serialization either through iova_rwsem or a dedicated gap_lock to prevent a concurrent map to allocate IOVA from that gap. Thus, every unmap pays for clean under the lock. I haven't perf-ed it yet, but I'm not sure whether users/Guests using virtio-iommu, where any guest DMA unmap becomes an unmap on the host, would regress.

b) Other users of IOMMU API (unmanaged domain) like the type 1 (which was the one hurting our systems) and other in-tree drivers that use an unmanaged domain and call iommu_map()/iommu_unmap() with their own IOVA allocator. One of the goals was to avoid enabling the user-space or in-kernel IOVA allocation (ab)users to cause OOMs via IOPT allocation.

Quoted 4 lines

An alternative version is closer to what you have here, somehow connect iommufd to the shrinker and have it lock and walk the gaps cleaning them on shrink requests?

I like this one better than cleaning on every unmap, since it keeps the cost off the map/unmap path and only does work under memory pressure. Although, it doesn't help type1 or the in-tree iommu_map() users.

Would you consider those users worth covering, or would you rather they track their own holes and call clean() themselves? Happy to dig into this at the LPC session too.

Thanks,
Praan

#8 lore raw
Quoted 55 lines · Pranjal Shrivastava
Quoted 23 lines · Jason Gunthorpe
Quoted 9 lines · Pranjal Shrivastava

Introduce a lockless, deferred reclamation framework for IOMMU page tables built on the generic_pt library. As VMMs and userspace drivers map and unmap large, sparse IOVA regions through VFIO and iommufd, page table directories are often left allocated but completely empty. generic_pt frees a table when a single unmap covers it entirely, but tables that empty through a series of partial unmaps stay allocated until the domain is destroyed. Under memory pressure, this *stranded* memory cannot be reclaimed and has resulted in OOMs.

Quoted 3 lines

This series refcounts leaf directories natively in struct ioptdesc and registers a domain-aware MM shrinker that prunes empty directories under system memory pressure.

We had talked about doing it this way

But I had proposed a different, and possibly simpler, solution that addresses *just* the iommufd use case.

After unmapping something have iommufd compute the gap in IOVA that contains what was unmapped and then issue a 'clean(gap)' operation to generic_pt.

Quoted 9 lines

This is the same operation as unmap, except we know now that the gap has no PTEs so all it does is clean up the table pointers.

This requires no special refcounting or anything difficult beyond some locking in iommufd to hold the gap stable while we clean it.

Would it work for you? It seems substantially simpler, but I never tried to implement it.

I was tempted to use the interval trees too, but I started thinking about:

a) Locking: For the gap to stay stable while we clean it, we'd need to add some kind of serialization either through iova_rwsem or a dedicated gap_lock to prevent a concurrent map to allocate IOVA from that gap. Thus, every unmap pays for clean under the lock. I haven't perf-ed it yet, but I'm not sure whether users/Guests using virtio-iommu, where any guest DMA unmap becomes an unmap on the host, would regress.

b) Other users of IOMMU API (unmanaged domain) like the type 1 (which was the one hurting our systems) and other in-tree drivers that use an unmanaged domain and call iommu_map()/iommu_unmap() with their own IOVA allocator. One of the goals was to avoid enabling the user-space or in-kernel IOVA allocation (ab)users to cause OOMs via IOPT allocation.

Quoted 4 lines

An alternative version is closer to what you have here, somehow connect iommufd to the shrinker and have it lock and walk the gaps cleaning them on shrink requests?

Quoted 8 lines

I like this one better than cleaning on every unmap, since it keeps the cost off the map/unmap path and only does work under memory pressure. Although, it doesn't help type1 or the in-tree iommu_map() users.

Would you consider those users worth covering, or would you rather they track their own holes and call clean() themselves? Happy to dig into this at the LPC session too.

I believe there is a value in supporting other users beyond IOMMUFD/VFIO (eg. DMA domains) or even outside of iommupt, I haven't investigated this, but it's worth looking into either integrating the "iommupt clean(gap)" idea in the IOVA allocator or more generally rely on refcounting + shrinker (or other method).
That’s probably a lot of investigation, so I am happy to help if needed in looking into any approach.

Thanks,
Mostafa

Quoted 3 lines

Thanks,
Praan

#9 lore raw
Quoted 5 lines · Mostafa Saleh

I believe there is a value in supporting other users beyond IOMMUFD/VFIO (eg. DMA domains) or even outside of iommupt, I haven't investigated this, but it's worth looking into either integrating the "iommupt clean(gap)" idea in the IOVA allocator or more generally rely on refcounting + shrinker (or other method).

The main point is to avoid the refcounting because that is going to be a perf negative for everyone..

I think most people should be able to do a clean call, and if it is routed as a generic domain function that would be fine too

Jason

syzbot Tested-by [email protected] on the v1 series
#10 lore raw
In reply to Pranjal Shrivastava
syzbot ci has tested the following series

syzbot ci has tested the following series

[v1] iommupt: Introduce IO page table shrinker
https://lore.kernel.org/all/[email protected]
* [RFC PATCH 1/5] iommu: Add reclaim_list xarray to struct iommu_domain
* [RFC PATCH 2/5] iommupt: Implement refcounting logic for Leaf entries
* [RFC PATCH 3/5] iommupt: Add lockless sever_branch helper
* [RFC PATCH 4/5] iommupt: Introduce lockless page table shrinker
* [RFC PATCH 5/5] iommupt: Return real page count to the shrinker core

and found the following issues:
* BUG: spinlock bad magic in xa_destroy
* INFO: trying to register non-static key in xa_destroy
* INFO: trying to register non-static key in xa_store

Full report is available here:
https://ci.syzbot.org/series/792388cb-7e39-4d83-8008-54d31031a227

***

BUG: spinlock bad magic in xa_destroy
tree:      axboe
URL:       https://kernel.googlesource.com/pub/scm/linux/kernel/git/axboe/linux.git
base:      72d3fcf802c45d00b300f25b848a93c3a2bd7c7e
arch:      amd64
compiler:  Debian clang version 22.1.8 (++20260613092233+e80beda6e255-1~exp1~20260613092250.77), Debian LLD 22.1.8
config:    https://ci.syzbot.org/builds/40ee62cc-4991-4840-96ac-e3f70bd4b70b/config
syz repro: https://ci.syzbot.org/findings/96c389a5-7ad8-436e-87ca-df20279f6360/syz_repro

iommufd_mock iommufd_mock0: Adding to iommu group 0

BUG: spinlock bad magic on CPU#1, syz.2.19/5813
 lock: mock_blocking_domain+0x70/0xe0 selftest.c:-1, .magic: 00000000, .owner: <none>/-1, .owner_cpu: 0
CPU: 1 UID: 0 PID: 5813 Comm: syz.2.19 Not tainted syzkaller #0 PREEMPT(full) 
Hardware name: QEMU Standard PC (Q35 + ICH9, 2009), BIOS 1.16.2-debian-1.16.2-1 04/01/2014
Call Trace:
 <TASK>
 dump_stack_lvl+0xe8/0x150 lib/dump_stack.c:120
 spin_bug kernel/locking/spinlock_debug.c:78 [inline]
 debug_spin_lock_before kernel/locking/spinlock_debug.c:86 [inline]
 do_raw_spin_lock+0x1e5/0x2f0 kernel/locking/spinlock_debug.c:115
 __raw_spin_lock_irqsave include/linux/spinlock_api_smp.h:156 [inline]
 _raw_spin_lock_irqsave+0x4c/0x60 kernel/locking/spinlock.c:181
 xa_destroy+0x59/0x2e0 lib/xarray.c:2393
 iommu_domain_free+0x25/0x170 drivers/iommu/iommu.c:2130
 iommu_deinit_device+0x353/0x5d0 drivers/iommu/iommu.c:600
 __iommu_group_remove_device+0x1dd/0x270 drivers/iommu/iommu.c:764
 iommu_release_device drivers/iommu/iommu.c:783 [inline]
 iommu_bus_notifier+0x6d/0x2c0 drivers/iommu/iommu.c:1826
 notifier_call_chain+0x1a5/0x3d0 kernel/notifier.c:85
 blocking_notifier_call_chain+0x6a/0x90 kernel/notifier.c:380
 bus_notify+0x143/0x180 drivers/base/bus.c:1086
 device_del+0x740/0x8f0 drivers/base/core.c:3982
 device_unregister+0x21/0xf0 drivers/base/core.c:4006
 mock_dev_destroy drivers/iommu/iommufd/selftest.c:1042 [inline]
 iommufd_test_mock_domain drivers/iommu/iommufd/selftest.c:1108 [inline]
 iommufd_test+0x3e03/0x6360 drivers/iommu/iommufd/selftest.c:2109
 iommufd_fops_ioctl+0x465/0x600 drivers/iommu/iommufd/main.c:556
 vfs_ioctl fs/ioctl.c:51 [inline]
 __do_sys_ioctl fs/ioctl.c:597 [inline]
 __se_sys_ioctl+0xfc/0x170 fs/ioctl.c:583
 do_syscall_x64 arch/x86/entry/syscall_64.c:61 [inline]
 do_syscall_64+0x166/0x520 arch/x86/entry/syscall_64.c:84
 entry_SYSCALL_64_after_hwframe+0x77/0x7f
RIP: 0033:0x7f9ceff9e159
Code: ff c3 66 2e 0f 1f 84 00 00 00 00 00 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 e8 ff ff ff f7 d8 64 89 01 48
RSP: 002b:00007f9cf0ea9028 EFLAGS: 00000246 ORIG_RAX: 0000000000000010
RAX: ffffffffffffffda RBX: 00007f9cf0225fa0 RCX: 00007f9ceff9e159
RDX: 0000200000000100 RSI: 0000000000003ba0 RDI: 0000000000000003
RBP: 00007f9cf003506b R08: 0000000000000000 R09: 0000000000000000
R10: 0000000000000000 R11: 0000000000000246 R12: 0000000000000000
R13: 00007f9cf0226038 R14: 00007f9cf0225fa0 R15: 00007ffe0de56058
 </TASK>

***

INFO: trying to register non-static key in xa_destroy

tree:      axboe
URL:       https://kernel.googlesource.com/pub/scm/linux/kernel/git/axboe/linux.git
base:      72d3fcf802c45d00b300f25b848a93c3a2bd7c7e
arch:      amd64
compiler:  Debian clang version 22.1.8 (++20260613092233+e80beda6e255-1~exp1~20260613092250.77), Debian LLD 22.1.8
config:    https://ci.syzbot.org/builds/40ee62cc-4991-4840-96ac-e3f70bd4b70b/config

iommufd_mock iommufd_mock0: Adding to iommu group 0
INFO: trying to register non-static key.
The code is fine but needs lockdep annotation, or maybe you didn't initialize this object before use? turning off the locking correctness validator.

CPU: 1 UID: 0 PID: 5775 Comm: syz.2.31 Not tainted syzkaller #0 PREEMPT(full) 
Hardware name: QEMU Standard PC (Q35 + ICH9, 2009), BIOS 1.16.2-debian-1.16.2-1 04/01/2014
Call Trace:
 <TASK>
 dump_stack_lvl+0xe8/0x150
 assign_lock_key+0x133/0x150
 register_lock_class+0xcc/0x2e0
 __lock_acquire+0x10c/0x2de0
 lock_acquire+0x115/0x350
 _raw_spin_lock_irqsave+0x40/0x60
 xa_destroy+0x59/0x2e0
 iommu_domain_free+0x25/0x170
 iommufd_hwpt_nested_destroy+0x4d/0x1a0
 iommufd_object_remove+0x35a/0x4c0
 iommufd_fops_ioctl+0x465/0x600
 __se_sys_ioctl+0xfc/0x170
 do_syscall_64+0x166/0x520
 entry_SYSCALL_64_after_hwframe+0x77/0x7f
RIP: 0033:0x7f593cf9e159
Code: ff c3 66 2e 0f 1f 84 00 00 00 00 00 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 e8 ff ff ff f7 d8 64 89 01 48
RSP: 002b:00007f593df41028 EFLAGS: 00000246 ORIG_RAX: 0000000000000010
RAX: ffffffffffffffda RBX: 00007f593d225fa0 RCX: 00007f593cf9e159
RDX: 0000200000000300 RSI: 0000000000003b80 RDI: 0000000000000003
RBP: 00007f593d03506b R08: 0000000000000000 R09: 0000000000000000
R10: 0000000000000000 R11: 0000000000000246 R12: 0000000000000000
R13: 00007f593d226038 R14: 00007f593d225fa0 R15: 00007ffe5c49ab68
 </TASK>

***

INFO: trying to register non-static key in xa_store

tree:      axboe
URL:       https://kernel.googlesource.com/pub/scm/linux/kernel/git/axboe/linux.git
base:      72d3fcf802c45d00b300f25b848a93c3a2bd7c7e
arch:      amd64
compiler:  Debian clang version 22.1.8 (++20260613092233+e80beda6e255-1~exp1~20260613092250.77), Debian LLD 22.1.8
config:    https://ci.syzbot.org/builds/40ee62cc-4991-4840-96ac-e3f70bd4b70b/config

INFO: trying to register non-static key.
The code is fine but needs lockdep annotation, or maybe you didn't initialize this object before use? turning off the locking correctness validator.

CPU: 0 UID: 0 PID: 6433 Comm: syz.2.305 Not tainted syzkaller #0 PREEMPT(full) 
Hardware name: QEMU Standard PC (Q35 + ICH9, 2009), BIOS 1.16.2-debian-1.16.2-1 04/01/2014
Call Trace:
 <TASK>
 dump_stack_lvl+0xe8/0x150
 assign_lock_key+0x133/0x150
 register_lock_class+0xcc/0x2e0
 __lock_acquire+0x10c/0x2de0
 lock_acquire+0x115/0x350
 _raw_spin_lock+0x2e/0x40
 xa_store+0x23/0x50
 __unmap_range+0x748/0x1190
 __unmap_range+0xbed/0x1190
 __unmap_range+0xbed/0x1190
 amdv1_mock_unmap_range+0x418/0x5e0
 __iommu_unmap+0x138/0x740
 iommu_unmap+0x114/0x200
 iopt_area_unmap_domain_range+0x279/0x310
 __iopt_area_unfill_domain+0x8a2/0xf30
 iopt_table_remove_domain+0x7e8/0xa90
 iommufd_hwpt_paging_destroy+0x1c1/0x2f0
 iommufd_object_remove+0x35a/0x4c0
 iommufd_hw_pagetable_detach+0x564/0x6a0
 iommufd_device_detach+0x1c/0x80
 iommufd_selftest_destroy+0xae/0x130
 iommufd_fops_release+0x186/0x3b0
 __fput+0x418/0xa50
 task_work_run+0x1d9/0x270
 exit_to_user_mode_loop+0x204/0x770
 do_syscall_64+0x328/0x520
 entry_SYSCALL_64_after_hwframe+0x77/0x7f
RIP: 0033:0x7fed0639e159
Code: ff c3 66 2e 0f 1f 84 00 00 00 00 00 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 e8 ff ff ff f7 d8 64 89 01 48
RSP: 002b:00007fff16748678 EFLAGS: 00000246 ORIG_RAX: 00000000000001b4
RAX: 0000000000000000 RBX: 00007fff16748760 RCX: 00007fed0639e159
RDX: 0000000000000000 RSI: 000000000000001e RDI: 0000000000000003
RBP: 000000000001312c R08: 0000000000000001 R09: 0000000000000000
R10: 0000001b31420000 R11: 0000000000000246 R12: 00007fff167487a0
R13: 00007fed06625fac R14: 0000000000013174 R15: 00007fed06625fa0
 </TASK>

***

If these findings have caused you to resend the series or submit a separate fix, please add the following tag to your commit message:

---
This report is generated by a bot. It may contain errors. syzbot ci engineers can be reached at [email protected].

To test a fix for this bug, please reply with #syz test (on a separate line) and attach the patch to the email.

Notes:
- The patch will be applied on top of the tested series (as an incremental fix).
- To test a new version of the whole series, please send it directly to [email protected].
- Arguments like custom git repos and branches are not supported.