Skip to contentSkip to conversation

iommupt: Unmap and return the PFNs in one walk

PATCH New Fred Griffoul 1 participant 4 messages Nov 11

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

cover iommupt: Unmap and return the PFNs in one walk

From: Fred Griffoul <[email protected]>

When iommufd unmaps an area, it must unpin the user pages, but it keeps no list of their PFNs. It reads each one back from the IOMMU domain with iommu_iova_to_phys(), one CPU page at a time, then walks the page table again in iommu_unmap(). With 4 KiB pages, a 1 GiB IOPTE costs 262144 lookups before the unmap starts.

This series lets the iommupt unmap walk report the physical range of each IOPTE as it removes it, so iommufd unmaps and collects the PFNs in one walk. The walk also steps over holes, where iommu_unmap() stops at the first one.

Patch 1 adds iommu_unmap_sparse(), patch 2 uses it in iopt_area_unpin_domain(), and patch 3 adds a selftest for the areas that keep the per-page read-back.

An earlier series [1] proposed iova_to_phys_length() so that iommufd can read the PFNs back one IOPTE at a time instead of one page at a time. The unmap is still a second walk there. This series collects the PFNs in the unmap walk itself.

The series applies to iommu/next. I wrote parts of the code and the changelogs with Kiro, an AI coding assistant using Claude models, and used it to run the tests. I reviewed and tested all of it.

[1] https://lore.kernel.org/linux-iommu/[email protected]/

Fred Griffoul (3):
iommupt: Add iommu_unmap_sparse()
iommufd: Use iommu_unmap_sparse() to unpin domain pages iommufd/selftest: Unmap areas that start inside a CPU page

 drivers/iommu/generic_pt/iommu_pt.h       |  61 ++++++++-
 drivers/iommu/generic_pt/kunit_iommu_pt.h | 144 ++++++++++++++++++++++
 drivers/iommu/iommu-debug-pagealloc.c     |  13 ++
 drivers/iommu/iommu-priv.h                |  24 ++++
 drivers/iommu/iommu.c                     |  76 ++++++++++++
 drivers/iommu/iommufd/pages.c             |  98 ++++++++++++++-
 include/linux/generic_pt/iommu.h          |  24 ++++
 include/linux/iommu.h                     |  22 ++++
 tools/testing/selftests/iommu/iommufd.c   |  30 +++++
 9 files changed, 486 insertions(+), 6 deletions(-)

base-commit: 2cf4be57b301ed2d7af82e70cff5dfd96894d8de

Signature · 1 line
2.47.3
#1 lore raw

PATCH 1/3 iommupt: Add iommu_unmap_sparse()

From: Fred Griffoul <[email protected]>

iommu_unmap() stops at the first IOVA that is not mapped, and it does not report what it removed. A caller that needs the physical addresses has to look up each page with iommu_iova_to_phys() first, then walk the page table again to unmap.

Add iommu_unmap_sparse() for domains that use the generic page table (iommupt), which steps over holes. An optional record function receives the IOVA, physical address and size of each mapping before it is cleared, and can stop the walk by returning false, for example when the caller's storage is full. The walk also stops before a mapping that extends past the end of the range, and the function returns the number of bytes processed so the caller can resume from there. The device can still reach the memory until the IOTLB is flushed at the end of the call, so the record function must not free or unpin it.

With iommu.debug_pagealloc, account for each mapping as it is removed, not for the whole range up front, because the walk can stop before the end of the range.

---
 drivers/iommu/generic_pt/iommu_pt.h       |  61 ++++++++-
 drivers/iommu/generic_pt/kunit_iommu_pt.h | 144 ++++++++++++++++++++++
 drivers/iommu/iommu-debug-pagealloc.c     |  13 ++
 drivers/iommu/iommu-priv.h                |  24 ++++
 drivers/iommu/iommu.c                     |  76 ++++++++++++
 include/linux/generic_pt/iommu.h          |  24 ++++
 include/linux/iommu.h                     |  22 ++++
 7 files changed, 363 insertions(+), 1 deletion(-)
drivers/iommu/generic_pt/iommu_pt.h +60 -1
index 837d835e4fad8..780b813be3b31 100644
@@ -993,7 +993,13 @@ static int NS(map_range)(struct pt_iommu *iommu_table, dma_addr_t iova,
 
 struct pt_unmap_args {
 	struct iommupt_pending_gather pending;
+	iommu_unmap_record_t record;
+	void *priv;
+	/* With sparse, the IOVA of the entry that stopped the walk */
+	pt_vaddr_t stopped;
 	pt_vaddr_t unmapped;
+	/* Step over entries that are not present instead of stopping */
+	bool sparse;
 };
 
 static __maybe_unused int __unmap_range(struct pt_range *range, void *arg,
@@ -1030,7 +1036,9 @@ static __maybe_unused int __unmap_range(struct pt_range *range, void *arg,
 	}
 
 	do {
-		if (pts.type != PT_ENTRY_OA) {
+		if (pts.type == PT_ENTRY_EMPTY && unmap->sparse) {
+			pts.index++;
+		} else if (pts.type != PT_ENTRY_OA) {
 			bool fully_covered;
 
 			if (pts.type != PT_ENTRY_TABLE) {
@@ -1072,6 +1080,26 @@ static __maybe_unused int __unmap_range(struct pt_range *range, void *arg,
 			 * the length returned will be larger than requested.
 			 */
 			num_contig_lg2 = pt_entry_num_contig_lg2(&pts);
+			if (unmap->sparse) {
+				unsigned int oasz_lg2 = pt_entry_oa_lg2sz(&pts);
+
+				if (pts.index != start_index)
+					pt_index_to_va(&pts);
+				/*
+				 * Stop before an entry that ends past the range
+				 * or that @record does not take. The error only
+				 * ends the walk, at unmap->stopped.
+				 */
+				if (!pt_entry_fully_covered(&pts, oasz_lg2) ||
+				    (unmap->record &&
+				     !unmap->record(unmap->priv, range->va,
+						    pt_entry_oa(&pts),
+						    log2_to_int(oasz_lg2)))) {
+					unmap->stopped = range->va;
+					ret = -ENOSPC;
+					break;
+				}
+			}
 			pt_clear_entries(&pts, num_contig_lg2);
 			gather_add_leaf(&unmap->pending, &pts);
 			num_oas += log2_to_int(num_contig_lg2);
@@ -1115,6 +1143,36 @@ static size_t NS(unmap_range)(struct pt_iommu *iommu_table, dma_addr_t iova,
 	return unmap.unmapped;
 }
 
+static size_t
+NS(unmap_range_sparse)(struct pt_iommu *iommu_table, dma_addr_t iova,
+		       dma_addr_t len, iommu_unmap_record_t record, void *priv,
+		       struct iommu_iotlb_gather *iotlb_gather)
+{
+	struct pt_unmap_args unmap = {
+		.pending.iotlb_gather = iotlb_gather,
+		.pending.free_list =
+			IOMMU_PAGES_LIST_INIT(unmap.pending.free_list),
+		.record = record,
+		.priv = priv,
+		.stopped = iova,
+		.sparse = true,
+	};
+	struct pt_range range;
+	size_t processed;
+	int ret;
+
+	ret = make_range(common_from_iommu(iommu_table), &range, iova, len);
+	if (ret)
+		return 0;
+
+	ret = pt_walk_range(&range, __unmap_range, &unmap);
+	processed = ret ? unmap.stopped - (pt_vaddr_t)iova : len;
+
+	/* One invalidation for the processed range, holes included */
+	gather_range_pending(&unmap.pending, iommu_table, iova, processed);
+	return processed;
+}
+
 static void NS(get_info)(struct pt_iommu *iommu_table,
 			 struct pt_iommu_info *info)
 {
@@ -1168,6 +1226,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),
+	.unmap_range_sparse = NS(unmap_range_sparse),
 #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),
drivers/iommu/generic_pt/kunit_iommu_pt.h +144 -0

161 lines not on this page · raw message

drivers/iommu/iommu-debug-pagealloc.c +13 -0
index 80164df5bab10..976e7f73ea9b9 100644
@@ -108,6 +108,19 @@ void __iommu_debug_map(struct iommu_domain *domain, phys_addr_t phys, size_t siz
 		iommu_debug_inc_page(phys + off);
 }
 
+void __iommu_debug_unmap_phys(struct iommu_domain *domain, phys_addr_t phys,
+			      size_t size)
+{
+	size_t off, end;
+	size_t page_size = iommu_debug_page_size(domain);
+
+	if (WARN_ON(!phys || check_add_overflow(phys, size, &end)))
+		return;
+
+	for (off = 0; off < size; off += page_size)
+		iommu_debug_dec_page(phys + off);
+}
+
 static void __iommu_debug_update_iova(struct iommu_domain *domain,
 				      unsigned long iova, size_t size, bool inc)
 {
drivers/iommu/iommu-priv.h +24 -0
index 1f9f886b2c107..d6ad234637606 100644
@@ -79,6 +79,13 @@ void __iommu_debug_unmap_begin(struct iommu_domain *domain,
 			       unsigned long iova, size_t size);
 void __iommu_debug_unmap_end(struct iommu_domain *domain,
 			     unsigned long iova, size_t size, size_t unmapped);
+void __iommu_debug_unmap_phys(struct iommu_domain *domain, phys_addr_t phys,
+			      size_t size);
+
+static inline bool iommu_debug_enabled(void)
+{
+	return static_branch_unlikely(&iommu_debug_initialized);
+}
 
 static inline void iommu_debug_map(struct iommu_domain *domain,
 				   phys_addr_t phys, size_t size)
@@ -102,9 +109,26 @@ static inline void iommu_debug_unmap_end(struct iommu_domain *domain,
 		__iommu_debug_unmap_end(domain, iova, size, unmapped);
 }
 
+static inline void iommu_debug_unmap_phys(struct iommu_domain *domain,
+					  phys_addr_t phys, size_t size)
+{
+	if (iommu_debug_enabled())
+		__iommu_debug_unmap_phys(domain, phys, size);
+}
+
 void iommu_debug_init(void);
 
 #else
+static inline bool iommu_debug_enabled(void)
+{
+	return false;
+}
+
+static inline void iommu_debug_unmap_phys(struct iommu_domain *domain,
+					  phys_addr_t phys, size_t size)
+{
+}
+
 static inline void iommu_debug_map(struct iommu_domain *domain,
 				   phys_addr_t phys, size_t size)
 {
drivers/iommu/iommu.c +76 -0

82 lines not on this page · raw message

include/linux/generic_pt/iommu.h +24 -0
index 13ebb72a67de3..b8d37b12f5307 100644
@@ -137,6 +137,30 @@ struct pt_iommu_ops {
 			      dma_addr_t len,
 			      struct iommu_iotlb_gather *iotlb_gather);
 
+	/**
+	 * @unmap_range_sparse: Make a range of IOVA that may have holes empty
+	 * @iommu_table: Table to manipulate
+	 * @iova: IO virtual address to start
+	 * @len: Length of the range starting from @iova
+	 * @record: Optional function called with each entry before it is cleared
+	 * @priv: Argument passed to @record
+	 * @iotlb_gather: Gather struct that must be flushed on return
+	 *
+	 * Like unmap_range(), but entries that are not present are stepped
+	 * over, and an entry that extends past the end of the range stops the
+	 * walk instead of being removed. A false return from @record also stops
+	 * the walk before that entry.
+	 *
+	 * Context: The caller must hold a write range lock that includes
+	 * the whole range.
+	 *
+	 * Returns: Number of bytes processed, holes included.
+	 */
+	size_t (*unmap_range_sparse)(struct pt_iommu *iommu_table,
+				     dma_addr_t iova, dma_addr_t len,
+				     iommu_unmap_record_t record, void *priv,
+				     struct iommu_iotlb_gather *iotlb_gather);
+
 	/**
 	 * @set_dirty: Make the iova write dirty
 	 * @iommu_table: Table to manipulate
include/linux/iommu.h +22 -0
index ef5043752a365..a9a66b2df77c1 100644
@@ -340,6 +340,18 @@ struct iommu_pages_list {
 #define IOMMU_PAGES_LIST_INIT(name) \
 	((struct iommu_pages_list){ .pages = LIST_HEAD_INIT(name.pages) })
 
+/**
+ * typedef iommu_unmap_record_t - Records a mapping iommu_unmap_sparse() removes
+ * @priv: Argument given to iommu_unmap_sparse()
+ * @iova: IO virtual address of the mapping
+ * @paddr: Physical address of the mapping
+ * @size: Size of the mapping
+ *
+ * Returns: true to continue the walk, false to stop it before this mapping.
+ */
+typedef bool (*iommu_unmap_record_t)(void *priv, unsigned long iova,
+				     phys_addr_t paddr, size_t size);
+
 #ifdef CONFIG_IOMMU_API
 
 /**
@@ -955,6 +967,8 @@ extern size_t iommu_unmap(struct iommu_domain *domain, unsigned long iova,
 extern size_t iommu_unmap_fast(struct iommu_domain *domain,
 			       unsigned long iova, size_t size,
 			       struct iommu_iotlb_gather *iotlb_gather);
+size_t iommu_unmap_sparse(struct iommu_domain *domain, unsigned long iova,
+			  size_t size, iommu_unmap_record_t record, void *priv);
 extern ssize_t iommu_map_sg(struct iommu_domain *domain, unsigned long iova,
 			    struct scatterlist *sg, unsigned int nents,
 			    int prot, gfp_t gfp);
@@ -1291,6 +1305,14 @@ static inline size_t iommu_unmap_fast(struct iommu_domain *domain,
 	return 0;
 }
 
+static inline size_t iommu_unmap_sparse(struct iommu_domain *domain,
+					unsigned long iova, size_t size,
+					iommu_unmap_record_t record,
+					void *priv)
+{
+	return 0;
+}
+
 static inline ssize_t iommu_map_sg(struct iommu_domain *domain,
 				   unsigned long iova, struct scatterlist *sg,
 				   unsigned int nents, int prot, gfp_t gfp)
Signature · 1 line
2.47.3
#2 lore raw

PATCH 2/3 iommufd: Use iommu_unmap_sparse() to unpin domain pages

In reply to Fred Griffoul

From: Fred Griffoul <[email protected]>

iommufd keeps no copy of the PFNs it pinned for an area, so iopt_area_unpin_domain() reads each one back from the domain with iommu_iova_to_phys(), one CPU page at a time, and then unmaps the range in a second walk. With 4 KiB pages, a 1 GiB IOPTE costs 262144 lookups before the unmap starts.

Call iommu_unmap_sparse() instead, and add the PFNs of each IOPTE it removes to the pfn_batch, so one walk both unmaps the range and collects the PFNs. The last IOPTE removed can hold pages beyond the ones this pass unpins. The loop already handles that case: it keeps those pages in the batch and carries them over to the next pass.

Domains that do not use iommupt keep the per-page read-back, and so do areas whose IOVA or memory starts or ends inside a CPU page. Such areas exist only when the smallest page size of every domain in the IOAS is smaller than PAGE_SIZE.

---
 drivers/iommu/iommufd/pages.c | 98 +++++++++++++++++++++++++++++++++--
 1 file changed, 93 insertions(+), 5 deletions(-)
drivers/iommu/iommufd/pages.c +93 -5
index 2f6153108add7..c2a04a8845cc8 100644
@@ -468,6 +468,79 @@ static void batch_from_domain_continue(struct pfn_batch *batch,
 	batch->array_size = array_size;
 }
 
+struct batch_unmap {
+	struct pfn_batch *batch;
+	unsigned long first_iova;
+	unsigned long last_iova;
+};
+
+static bool batch_record_unmapped(void *priv, unsigned long iova,
+				  phys_addr_t paddr, size_t size)
+{
+	struct batch_unmap *unmap = priv;
+	unsigned long first, end;
+
+	/* Stop after the entry that holds the last page to unpin */
+	if (iova > unmap->last_iova)
+		return false;
+
+	/*
+	 * Count each CPU page once, from the entry that holds its first byte.
+	 * Pages before first_iova belong to an access and stay pinned.
+	 */
+	first = max(ALIGN(iova, PAGE_SIZE), unmap->first_iova);
+	end = ALIGN(iova + size, PAGE_SIZE);
+	if (first >= end)
+		return true;
+	return batch_add_pfn_num(unmap->batch, PHYS_PFN(paddr + (first - iova)),
+				 (end - first) >> PAGE_SHIFT, BATCH_CPU_MEMORY);
+}
+
+/* True if the area starts and ends on CPU pages, in both IOVA and memory */
+static bool iopt_area_pages_aligned(struct iopt_area *area)
+{
+	return !area->page_offset &&
+	       PAGE_ALIGNED(iopt_area_iova(area) |
+			    (iopt_area_last_iova(area) + 1));
+}
+
+/*
+ * Unmap from unmapped_index and collect the PFNs from start_index on into the
+ * batch in one walk. The walk ends after the entry that holds last_index, which
+ * can reach past last_index, or before an entry the batch has no room for.
+ * Returns the number of indexes unmapped, 0 if the caller has to read the PFNs
+ * back with batch_from_domain() instead.
+ */
+static unsigned long batch_unmap_from_domain(struct pfn_batch *batch,
+					     struct iommu_domain *domain,
+					     struct iopt_area *area,
+					     unsigned long unmapped_index,
+					     unsigned long start_index,
+					     unsigned long last_index,
+					     unsigned long real_last_index)
+{
+	unsigned long start = max(start_index, unmapped_index);
+	struct batch_unmap unmap = {
+		.batch = batch,
+		.first_iova = iopt_area_index_to_iova(area, start),
+		.last_iova = iopt_area_index_to_iova_last(area, last_index),
+	};
+	unsigned long iova = iopt_area_index_to_iova(area, unmapped_index);
+	unsigned long last =
+		iopt_area_index_to_iova_last(area, real_last_index);
+	size_t unmapped;
+
+	if (!iopt_area_pages_aligned(area))
+		return 0;
+
+	/* The range runs to the area end, batch_record_unmapped() stops it */
+	unmapped = iommu_unmap_sparse(domain, iova, last - iova + 1,
+				      batch_record_unmapped, &unmap);
+	if (IS_ENABLED(CONFIG_IOMMUFD_TEST))
+		WARN_ON(unmapped % PAGE_SIZE);
+	return unmapped >> PAGE_SHIFT;
+}
+
 /*
  * This is part of the VFIO compatibility support for VFIO_TYPE1_IOMMU. That
  * mode permits splitting a mapped area up, and then one of the splits is
@@ -1689,19 +1762,33 @@ iopt_area_unpin_domain(struct pfn_batch *batch, struct iopt_area *area,
 {
 	while (start_index <= last_index) {
 		unsigned long batch_last_index;
+		bool read_ahead = true;
 
 		if (*unmapped_end_index <= last_index) {
 			unsigned long start =
 				max(start_index, *unmapped_end_index);
+			unsigned long unmapped, batch_end;
 
 			if (IS_ENABLED(CONFIG_IOMMUFD_TEST) &&
 			    batch->total_pfns)
 				WARN_ON(*unmapped_end_index -
 						batch->total_pfns !=
 					start_index);
-			batch_from_domain(batch, domain, area, start,
-					  last_index);
-			batch_last_index = start_index + batch->total_pfns - 1;
+			unmapped = batch_unmap_from_domain(batch, domain, area,
+							   *unmapped_end_index,
+							   start_index,
+							   last_index,
+							   real_last_index);
+			if (unmapped) {
+				/* The walk ended on an entry boundary */
+				*unmapped_end_index += unmapped;
+				read_ahead = false;
+			} else {
+				batch_from_domain(batch, domain, area, start,
+						  last_index);
+			}
+			batch_end = start_index + batch->total_pfns - 1;
+			batch_last_index = min(batch_end, last_index);
 		} else {
 			batch_last_index = last_index;
 		}
@@ -1716,9 +1803,10 @@ iopt_area_unpin_domain(struct pfn_batch *batch, struct iopt_area *area,
 		 * middle of the domains we need to keep reading pfns until we
 		 * find a cut point to do the unmap. The pfns we read are
 		 * carried over and either skipped or integrated into the next
-		 * batch.
+		 * batch. batch_unmap_from_domain() already ends on an entry
+		 * boundary and needs no read-ahead.
 		 */
-		if (batch_last_index == last_index &&
+		if (read_ahead && batch_last_index == last_index &&
 		    last_index != real_last_index)
 			batch_from_domain_continue(batch, domain, area,
 						   last_index + 1,
Signature · 1 line
2.47.3
#3 lore raw

PATCH 3/3 iommufd/selftest: Unmap areas that start inside a CPU page

In reply to Fred Griffoul

From: Fred Griffoul <[email protected]>

On iommupt domains, iopt_area_unpin_domain() unmaps and collects PFNs in one walk, which needs IOPTEs that line up with CPU pages. The mock domain maps 2 KiB per IOPTE, so IOMMU_IOAS_MAP_FIXED_IOVA can place a user address with a 2 KiB offset at a CPU page aligned IOVA. Such an area must take the per-page read-back instead, or one of its pages stays pinned.

Map a buffer at each MOCK_PAGE_SIZE offset in its first CPU page, unmap it, and check that no page is left pinned.

---
 tools/testing/selftests/iommu/iommufd.c | 30 +++++++++++++++++++++++++
 1 file changed, 30 insertions(+)
tools/testing/selftests/iommu/iommufd.c +30 -0
index ca2b35e9d443a..14c8a12a3bc17 100644
@@ -1890,6 +1890,36 @@ TEST_F(iommufd_mock_domain, all_aligns)
 		close(mfd);
 }
 
+/*
+ * Map memory that starts inside a CPU page at a CPU page aligned IOVA, which
+ * the mock domain's MOCK_PAGE_SIZE IOPTEs allow, then unmap it and check that
+ * every page is unpinned.
+ */
+TEST_F(iommufd_mock_domain, fixed_iova_offsets)
+{
+	size_t buf_size = self->mmap_buf_size;
+	size_t length = buf_size - PAGE_SIZE;
+	unsigned int start;
+	uint8_t *buf;
+
+	if (variant->file)
+		SKIP(return, "Skipping file variant, the test maps anonymous memory");
+
+	buf = mmap(0, buf_size, PROT_READ | PROT_WRITE, self->mmap_flags, -1,
+		   0);
+	ASSERT_NE(MAP_FAILED, buf);
+	check_refs(buf, buf_size, 0);
+
+	for (start = 0; start < PAGE_SIZE; start += MOCK_PAGE_SIZE) {
+		test_ioctl_ioas_map_fixed(buf + start, length,
+					  MOCK_APERTURE_START);
+		check_mock_iova(buf + start, MOCK_APERTURE_START, length);
+		test_ioctl_ioas_unmap(MOCK_APERTURE_START, length);
+		check_refs(buf, buf_size, 0);
+	}
+	ASSERT_EQ(0, munmap(buf, buf_size));
+}
+
 TEST_F(iommufd_mock_domain, all_aligns_copy)
 {
 	size_t test_step = variant->hugepages ? self->mmap_buf_size / 16 :
Signature · 1 line
2.47.3