[PATCH] iommufd: Unmap the failing batch before releasing its pins

From: Qihang

Date: Wed Nov 18 2026 - 11:40:40 EST


iopt_area_fill_domains() maps the PFNs of one batch into every domain
and only then moves on to the next batch. If batch_to_domain() fails
for one domain after an earlier domain has already installed the batch,
the unwind path calls pfn_reader_release_pins() at the top of
out_unmap. That unpins the pages of the failing batch while the
domains that did install it still translate those IOVAs, and only the
loop below removes those mappings. For the duration of that loop a
device can DMA to a page that is no longer pinned, so it can be freed
and reused while the translation remains live.

The release also cannot simply be delayed to pfn_reader_destroy():
the last domain in the unwind loop is the only one that unpins, and
the unpin ends in update_unpinned(). When an earlier batch was fully
installed before the failure, pages->npinned still counts the pins
the reader holds, while pages->last_npinned still has its pre-fill
value, so update_unpinned() warns about npinned being above
last_npinned.

Release the pins inside the else branch of the last domain instead,
right before iopt_area_unfill_partial_domain(). No domain maps the
failing batch by then: the earlier domains were just unmapped by this
loop, the failing domain rolled back its partial mapping in
batch_to_domain(), and the later domains never installed the batch.
The release also precedes the last domain's unpin and its
update_unpinned(), so the pin accounting stays consistent. The
single-domain variant iopt_area_fill_domain() already unwinds in this
order.

Fixes: 8d160cd4d506 ("iommufd: Algorithms for PFN storage")
Cc: stable@xxxxxxxxxxxxxxx
Signed-off-by: Qihang <q.h.hack.winter@xxxxxxxxx>
---
drivers/iommu/iommufd/pages.c | 13 ++++++++++++-
1 file changed, 12 insertions(+), 1 deletion(-)

diff --git a/drivers/iommu/iommufd/pages.c b/drivers/iommu/iommufd/pages.c
index 2f6153108add..a99f4efbffd9 100644
--- a/drivers/iommu/iommufd/pages.c
+++ b/drivers/iommu/iommufd/pages.c
@@ -1962,7 +1962,6 @@
return 0;

out_unmap:
- pfn_reader_release_pins(&pfns);
xa_for_each(&area->iopt->domains, unmap_index, domain) {
unsigned long end_index;

@@ -1982,6 +1981,18 @@
area, domain, iopt_area_index(area),
end_index - 1);
} else {
+ /*
+ * The last domain is the only one that unpins, so the
+ * reader's pins must be released before the unpin and
+ * its update_unpinned(): npinned still counts them
+ * while last_npinned predates the fill. No domain maps
+ * the failing batch any more: the earlier domains
+ * were just unmapped by this loop, the failing domain
+ * rolled back its partial mapping in
+ * batch_to_domain(), and the later domains never
+ * installed it.
+ */
+ pfn_reader_release_pins(&pfns);
iopt_area_unfill_partial_domain(area, pages, domain,
end_index);
}
--
2.54.0 (Apple Git-157)