[PATCH 1/2] iommu: Avoid using the list iterator past the loop in iommu_insert_resv_region()
From: Maoyi Xie
Date: Thu Jun 04 2026 - 01:20:20 EST
iommu_insert_resv_region() walks @regions to find the insertion point.
When no element compares greater, the list_for_each_entry() iterator ends
up one past the last entry, so &iter->list aliases the list head through
container_of() offset cancellation and the following list_add_tail() still
targets the tail. The result is correct, but using the iterator after the
loop is undefined per the list_for_each_entry() contract.
The loop only needs a list_head to use as the insertion point, not the
entry itself, so iterate with list_for_each() and keep the typed
list_entry() dereference inside the loop body. No functional change.
Suggested-by: Robin Murphy <robin.murphy@xxxxxxx>
Signed-off-by: Maoyi Xie <maoyixie.tju@xxxxxxxxx>
---
drivers/iommu/iommu.c | 7 +++++--
1 file changed, 5 insertions(+), 2 deletions(-)
diff --git a/drivers/iommu/iommu.c b/drivers/iommu/iommu.c
index 61c12ba78206..f9f53db9696f 100644
--- a/drivers/iommu/iommu.c
+++ b/drivers/iommu/iommu.c
@@ -862,6 +862,7 @@ static int iommu_insert_resv_region(struct iommu_resv_region *new,
struct list_head *regions)
{
struct iommu_resv_region *iter, *tmp, *nr, *top;
+ struct list_head *pos;
LIST_HEAD(stack);
nr = iommu_alloc_resv_region(new->start, new->length,
@@ -870,12 +871,14 @@ static int iommu_insert_resv_region(struct iommu_resv_region *new,
return -ENOMEM;
/* First add the new element based on start address sorting */
- list_for_each_entry(iter, regions, list) {
+ list_for_each(pos, regions) {
+ iter = list_entry(pos, struct iommu_resv_region, list);
+
if (nr->start < iter->start ||
(nr->start == iter->start && nr->type <= iter->type))
break;
}
- list_add_tail(&nr->list, &iter->list);
+ list_add_tail(&nr->list, pos);
/* Merge overlapping segments of type nr->type in @regions, if any */
list_for_each_entry_safe(iter, tmp, regions, list) {
--
2.34.1