Skip to contentSkip to conversation

iommu/dma: Don't free under/oversized IOVA ranges

PATCH New Matt Vollrath 1 participant 1 message Oct 1

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

PATCH 1/1 iommu/dma: Don't free under/oversized IOVA ranges

When unmapping DMA from a translating IOMMU, the range unmapped by the IOMMU page table may not match the size specified in the request. An unmapped length of 0 suggests that either the request was rejected by the IOMMU or the IOVA did not exist in the page table. A size mismatch suggests that either the unmap was partially successful or the request was made with an incorrect IOVA and/or size.

Because the return value of iommu_unmap_fast() is already in hand in __iommu_dma_unmap(), hardening is cheap.

In the case of an unmapped length of 0, skip the IOTLB sync (because there is nothing to sync) and skip freeing of the unmapped IOVA which would corrupt the IOVA allocator state.

In the case of size mismatch, flush the IOTLB synchronously and intentionally leak the IOVA allocation if it existed. A potential leak of a valid IOVA is more predictable than potentially corrupting the IOVA allocator state. The existing WARN_ON() is preserved.

The intention is to prevent failure cascades from intermittent driver bugs. If one bad unmap causes a future mapping error (because the allocator cache believed that an IOVA was free), then we are at the mercy of the driver's map error handling.

Assisted-by Claude:claude-opus-5-5

---
This was tested with QEMU 8.2 against virtio-iommu and emulation of:
* VT-d
* AMD-Vi
* SMMUv3
* s390 zPCI

---
 drivers/iommu/dma-iommu.c | 17 ++++++++++++++++-
 1 file changed, 16 insertions(+), 1 deletion(-)
drivers/iommu/dma-iommu.c +16 -1
index 58c624513cd4..029ccc3b55cf 100644
@@ -836,7 +836,22 @@ static void __iommu_dma_unmap(struct device *dev, dma_addr_t dma_addr,
 	iotlb_gather.queued = READ_ONCE(cookie->fq_domain);
 
 	unmapped = iommu_unmap_fast(domain, dma_addr, size, &iotlb_gather);
-	WARN_ON(unmapped != size);
+	if (WARN_ON(unmapped != size)) {
+		if (unmapped) {
+			/*
+			 * If we changed the page table, we must sync IOTLB.
+			 * Freeing the IOVA could corrupt the allocator,
+			 *   so leak it instead.
+			 */
+			if (iotlb_gather.queued) {
+				iommu_flush_iotlb_all(domain);
+				iommu_put_pages_list(&iotlb_gather.freelist);
+			} else {
+				iommu_iotlb_sync(domain, &iotlb_gather);
+			}
+		}
+		return;
+	}
 
 	if (!iotlb_gather.queued)
 		iommu_iotlb_sync(domain, &iotlb_gather);

base-commit: cec2dc7663e7182c311162163d71b1bbdfdbf09b

Signature · 1 line
2.43.0