[PATCH 1/2] mm: nommu: fix the error path when vma_iter_prealloc() fails
From: Hajime Tazaki
Date: Tue Jul 07 2026 - 19:51:57 EST
When vma_iter_prealloc() fails in do_mmap(), it jumps to error_just_free
without updating ret to -ENOMEM, meaning do_mmap() will return 0 on
failure.
Additionally, this error path unconditionally frees the region struct.
Since the region was already added to the global nommu_region_tree via
add_nommu_region(), leaving it makes a potential dangling pointer in
the tree and may cause a use-after-free on the next tree walk.
This commit fixes those issues by introducing new jump
label, error_vma_iter_prealloc, to correctly handle the error case of
vma_iter_prealloc(), and move the region updates after the place that
the allocation is finished.
Those issues are discovered by Sashiko, linked below.
Link: https://sashiko.dev/#/patchset/20260702012830.667205-1-thehajime%40gmail.com
Signed-off-by: Hajime Tazaki <thehajime@xxxxxxxxx>
---
mm/nommu.c | 11 +++++++++--
1 file changed, 9 insertions(+), 2 deletions(-)
diff --git a/mm/nommu.c b/mm/nommu.c
index 815ebefddfae..ad619611e83f 100644
--- a/mm/nommu.c
+++ b/mm/nommu.c
@@ -1181,7 +1181,6 @@ unsigned long do_mmap(struct file *file,
ret = do_mmap_private(vma, region, len, capabilities);
if (ret < 0)
goto error_just_free;
- add_nommu_region(region);
/* clear anonymous mappings that don't ask for uninitialized data */
if (!vma->vm_file &&
@@ -1199,7 +1198,9 @@ unsigned long do_mmap(struct file *file,
BUG_ON(!vma->vm_region);
vma_iter_config(&vmi, vma->vm_start, vma->vm_end);
if (vma_iter_prealloc(&vmi, vma))
- goto error_just_free;
+ goto error_vma_iter_prealloc;
+
+ add_nommu_region(region);
setup_vma_to_mm(vma, current->mm);
current->mm->map_count++;
@@ -1235,6 +1236,12 @@ unsigned long do_mmap(struct file *file,
ret = -EINVAL;
goto error;
+error_vma_iter_prealloc:
+ up_write(&nommu_region_sem);
+ pr_warn("Failed vma_iter_prealloc()\n");
+ ret = -ENOMEM;
+ goto error;
+
error_getting_vma:
kmem_cache_free(vm_region_jar, region);
pr_warn("Allocation of vma for %lu byte allocation from process %d failed\n",
--
2.43.0