Skip to contentSkip to conversation

bpf: Take mmap_lock in zap_pages()

PATCH Applied Alexei Starovoitov 5 participants 10 messages May 28 – Jun 4

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

PATCH 1/1 bpf: Take mmap_lock in zap_pages()

From: Alexei Starovoitov <[email protected]>

zap_vma_range() requires the owning mm's mmap_lock to be held.

Taking mmap_read_lock under arena->lock would AB-BA against arena_vm_close() and arena_map_mmap(), both of which run with mmap_write_lock held and then acquire arena->lock. Instead drop arena->lock, mmget_not_zero() the vma's mm, take mmap_read_lock, and re-resolve the vma via find_vma() since it may have been unmapped or replaced while waiting.

Track processed vmls with a per-call generation in vml->zap_gen and serialize zap_pages() callers with a new arena->zap_mutex so concurrent callers on different uaddr ranges do not mark each other's vmls processed before the zap is done.

Fixes 317460317a02 ("bpf: Introduce bpf_arena.")
---
 kernel/bpf/arena.c | 61 +++++++++++++++++++++++++++++++++++++++++++---
 1 file changed, 57 insertions(+), 4 deletions(-)
kernel/bpf/arena.c +57 -4
index 1727503b25d8..9b2dea229b38 100644
@@ -60,6 +60,8 @@ struct bpf_arena {
 	struct list_head vma_list;
 	/* protects vma_list */
 	struct mutex lock;
+	u64 zap_gen;
+	struct mutex zap_mutex;
 	struct irq_work     free_irq;
 	struct work_struct  free_work;
 	struct llist_head   free_spans;
@@ -289,6 +291,7 @@ static struct bpf_map *arena_map_alloc(union bpf_attr *attr)
 	if (err)
 		goto err_free_scratch;
 	mutex_init(&arena->lock);
+	mutex_init(&arena->zap_mutex);
 	raw_res_spin_lock_init(&arena->spinlock);
 	err = populate_pgtable_except_pte(arena);
 	if (err)
@@ -391,6 +394,7 @@ struct vma_list {
 	struct vm_area_struct *vma;
 	struct list_head head;
 	refcount_t mmap_count;
+	u64 zap_gen;
 };
 
 static int remember_vma(struct bpf_arena *arena, struct vm_area_struct *vma)
@@ -403,6 +407,7 @@ static int remember_vma(struct bpf_arena *arena, struct vm_area_struct *vma)
 	refcount_set(&vml->mmap_count, 1);
 	vma->vm_private_data = vml;
 	vml->vma = vma;
+	vml->zap_gen = 0;
 	list_add(&vml->head, &arena->vma_list);
 	return 0;
 }
@@ -746,12 +751,60 @@ static long arena_alloc_pages(struct bpf_arena *arena, long uaddr, long page_cnt
  */
 static void zap_pages(struct bpf_arena *arena, long uaddr, long page_cnt)
 {
+	unsigned long size = (unsigned long)page_cnt << PAGE_SHIFT;
+	struct vm_area_struct *vma;
+	struct mm_struct *mm;
 	struct vma_list *vml;
+	unsigned long vm_start;
+	u64 my_gen;
 
-	guard(mutex)(&arena->lock);
-	/* iterate link list under lock */
-	list_for_each_entry(vml, &arena->vma_list, head)
-		zap_vma_range(vml->vma, uaddr, PAGE_SIZE * page_cnt);
+	/*
+	 * Taking mmap_read_lock() under arena->lock would deadlock against
+	 * arena_vm_close(), which runs with mmap_write_lock held and then
+	 * acquires arena->lock. Drop arena->lock for mmap_read_lock().
+	 *
+	 * Use per-call my_gen, recorded in vml->zap_gen, to remember which
+	 * vmls this invocation has already processed across the lock drop.
+	 * Hold zap_mutex around the whole walk so concurrent zap_pages()
+	 * callers cannot overwrite each other's marks on shared vmls --
+	 * otherwise call B's mark would make call A skip a vml that A has
+	 * not yet zapped for A's uaddr range.
+	 */
+	mutex_lock(&arena->zap_mutex);
+	mutex_lock(&arena->lock);
+	my_gen = ++arena->zap_gen;
+	for (;;) {
+		mm = NULL;
+		list_for_each_entry(vml, &arena->vma_list, head) {
+			if (vml->zap_gen >= my_gen)
+				continue;
+			vml->zap_gen = my_gen;
+			if (!mmget_not_zero(vml->vma->vm_mm))
+				continue;
+			mm = vml->vma->vm_mm;
+			vm_start = vml->vma->vm_start;
+			break;
+		}
+		if (!mm)
+			break;
+		mutex_unlock(&arena->lock);
+
+		mmap_read_lock(mm);
+		/*
+		 * Re-resolve: while we waited the VMA could have been unmapped
+		 * and a different mapping installed at the same address.
+		 */
+		vma = find_vma(mm, vm_start);
+		if (vma && vma->vm_start == vm_start &&
+		    vma->vm_file && vma->vm_file->private_data == &arena->map)
+			zap_vma_range(vma, uaddr, size);
+		mmap_read_unlock(mm);
+		mmput(mm);
+
+		mutex_lock(&arena->lock);
+	}
+	mutex_unlock(&arena->lock);
+	mutex_unlock(&arena->zap_mutex);
 }
 
 static void arena_free_pages(struct bpf_arena *arena, long uaddr, long page_cnt, bool sleepable)
Signature · 1 line
2.53.0-Meta
#1 lore raw
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:

New issues:
- [High] zap_pages() can enter an infinite loop if userspace continuously mmaps and munmaps the arena, stalling the thread indefinitely.

Pre-existing issues:
- [Critical] zap_pages() can pass an address range to zap_vma_range() that exceeds the boundaries of the VMA, causing the kernel to unmap memory belonging to adjacent mappings. --

commit 5e7dd96eaa4e65e290f989d52d5ebe8450def72a
Author: Alexei Starovoitov <[email protected]>

bpf: Take mmap_lock in zap_pages()

This commit addresses an AB-BA deadlock between arena->lock and mmap_lock in zap_pages() by dropping arena->lock before acquiring mmap_read_lock(). It introduces a zap_gen counter and a zap_mutex to track processed VMAs and serialize callers while the lock is dropped.

Quoted 4 lines
kernel/bpf/arena.c +0 -0
index 1727503b25d84..9b2dea229b385 100644

[ ... ]

Quoted 3 lines
kernel/bpf/arena.c +0 -0
@@ -746,12 +751,60 @@ static long arena_alloc_pages(struct bpf_arena *arena, long uaddr, long page_cnt
 static void zap_pages(struct bpf_arena *arena, long uaddr, long page_cnt)
 {

[ ... ]

Quoted 8 lines
kernel/bpf/arena.c +8 -0
+	mutex_lock(&arena->zap_mutex);
+	mutex_lock(&arena->lock);
+	my_gen = ++arena->zap_gen;
+	for (;;) {
+		mm = NULL;
+		list_for_each_entry(vml, &arena->vma_list, head) {
+			if (vml->zap_gen >= my_gen)
+				continue;

kernel/bpf/arena.c static long arena_alloc_pages(struct bpf_arena *arena, long uaddr, long page_cnt · line 790

Quoted 10 lines
kernel/bpf/arena.c +10 -0
+			vml->zap_gen = my_gen;
+			if (!mmget_not_zero(vml->vma->vm_mm))
+				continue;
+			mm = vml->vma->vm_mm;
+			vm_start = vml->vma->vm_start;
+			break;
+		}
+		if (!mm)
+			break;
+		mutex_unlock(&arena->lock);

[Severity: High]
Can this loop run indefinitely if userspace continuously mmaps and munmaps the arena?

Since remember_vma() unconditionally sets vml->zap_gen = 0 and adds the new VMA to the vma_list, concurrent mmap() and munmap() calls could repeatedly inject new VMAs with a zap_gen of 0 while the lock is dropped. This might cause the loop to repeatedly process these new VMAs and stall the thread.

kernel/bpf/arena.c static long arena_alloc_pages(struct bpf_arena *arena, long uaddr, long page_cnt · line 800

Quoted 10 lines
kernel/bpf/arena.c +10 -0
+
+		mmap_read_lock(mm);
+		/*
+		 * Re-resolve: while we waited the VMA could have been unmapped
+		 * and a different mapping installed at the same address.
+		 */
+		vma = find_vma(mm, vm_start);
+		if (vma && vma->vm_start == vm_start &&
+		    vma->vm_file && vma->vm_file->private_data == &arena->map)
+			zap_vma_range(vma, uaddr, size);

[Severity: Critical]
This is a pre-existing issue, but could this unmap memory belonging to adjacent mappings if the VMA was partially unmapped?

The uaddr and size variables appear to be bounded by the global arena->user_vm_start and arena->user_vm_end. If userspace partially unmaps the arena using munmap(), the vma->vm_start or vma->vm_end shrinks, but the global arena bounds remain unchanged.

Since zap_vma_range() relies on the caller to provide a range fully contained within the VMA, passing an un-shrunk uaddr and size could exceed the current bounds of the VMA and inadvertently unmap adjacent userspace mappings.

Quoted 8 lines
kernel/bpf/arena.c +7 -0
+		mmap_read_unlock(mm);
+		mmput(mm);
+
+		mutex_lock(&arena->lock);
+	}
+	mutex_unlock(&arena->lock);
+	mutex_unlock(&arena->zap_mutex);
 }
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
#2 lore raw
Quoted 52 lines · On Thu, May 28, 2026 at 4:11 PM <[email protected]> wrote:

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:

New issues:
- [High] zap_pages() can enter an infinite loop if userspace continuously mmaps and munmaps the arena, stalling the thread indefinitely.

Pre-existing issues:
- [Critical] zap_pages() can pass an address range to zap_vma_range() that exceeds the boundaries of the VMA, causing the kernel to unmap memory belonging to adjacent mappings. --

commit 5e7dd96eaa4e65e290f989d52d5ebe8450def72a
Author: Alexei Starovoitov <[email protected]>

bpf: Take mmap_lock in zap_pages()

This commit addresses an AB-BA deadlock between arena->lock and mmap_lock in zap_pages() by dropping arena->lock before acquiring mmap_read_lock(). It introduces a zap_gen counter and a zap_mutex to track processed VMAs and serialize callers while the lock is dropped.

Quoted 4 lines
kernel/bpf/arena.c +0 -0
index 1727503b25d84..9b2dea229b385 100644

[ ... ]

Quoted 3 lines
kernel/bpf/arena.c +0 -0
@@ -746,12 +751,60 @@ static long arena_alloc_pages(struct bpf_arena *arena, long uaddr, long page_cnt
 static void zap_pages(struct bpf_arena *arena, long uaddr, long page_cnt)
 {

[ ... ]

Quoted 8 lines
kernel/bpf/arena.c +8 -0
+     mutex_lock(&arena->zap_mutex);
+     mutex_lock(&arena->lock);
+     my_gen = ++arena->zap_gen;
+     for (;;) {
+             mm = NULL;
+             list_for_each_entry(vml, &arena->vma_list, head) {
+                     if (vml->zap_gen >= my_gen)
+                             continue;

kernel/bpf/arena.c static long arena_alloc_pages(struct bpf_arena *arena, long uaddr, long page_cnt · line 790

Quoted 10 lines
kernel/bpf/arena.c +10 -0
+                     vml->zap_gen = my_gen;
+                     if (!mmget_not_zero(vml->vma->vm_mm))
+                             continue;
+                     mm = vml->vma->vm_mm;
+                     vm_start = vml->vma->vm_start;
+                     break;
+             }
+             if (!mm)
+                     break;
+             mutex_unlock(&arena->lock);
Quoted 8 lines

[Severity: High]
Can this loop run indefinitely if userspace continuously mmaps and munmaps the arena?

Since remember_vma() unconditionally sets vml->zap_gen = 0 and adds the new VMA to the vma_list, concurrent mmap() and munmap() calls could repeatedly inject new VMAs with a zap_gen of 0 while the lock is dropped. This might cause the loop to repeatedly process these new VMAs and stall the thread.

Nope. Cannot happen.

Quoted 20 lines

kernel/bpf/arena.c static long arena_alloc_pages(struct bpf_arena *arena, long uaddr, long page_cnt · line 800

Quoted 10 lines
kernel/bpf/arena.c +10 -0
+
+             mmap_read_lock(mm);
+             /*
+              * Re-resolve: while we waited the VMA could have been unmapped
+              * and a different mapping installed at the same address.
+              */
+             vma = find_vma(mm, vm_start);
+             if (vma && vma->vm_start == vm_start &&
+                 vma->vm_file && vma->vm_file->private_data == &arena->map)
+                     zap_vma_range(vma, uaddr, size);

[Severity: Critical]
This is a pre-existing issue, but could this unmap memory belonging to adjacent mappings if the VMA was partially unmapped?

The uaddr and size variables appear to be bounded by the global arena->user_vm_start and arena->user_vm_end. If userspace partially unmaps the arena using munmap(), the vma->vm_start or vma->vm_end shrinks, but the global arena bounds remain unchanged.

Quoted 4 lines

Since zap_vma_range() relies on the caller to provide a range fully contained within the VMA, passing an un-shrunk uaddr and size could exceed the current bounds of the VMA and inadvertently unmap adjacent userspace mappings.

Nope. Not an issue.

#3 lore raw
In reply to Alexei Starovoitov
Quoted 76 lines · Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

zap_vma_range() requires the owning mm's mmap_lock to be held.

Taking mmap_read_lock under arena->lock would AB-BA against arena_vm_close() and arena_map_mmap(), both of which run with mmap_write_lock held and then acquire arena->lock. Instead drop arena->lock, mmget_not_zero() the vma's mm, take mmap_read_lock, and re-resolve the vma via find_vma() since it may have been unmapped or replaced while waiting.

Track processed vmls with a per-call generation in vml->zap_gen and serialize zap_pages() callers with a new arena->zap_mutex so concurrent callers on different uaddr ranges do not mark each other's vmls processed before the zap is done.

Fixes 317460317a02 ("bpf: Introduce bpf_arena.")
---
 kernel/bpf/arena.c | 61 +++++++++++++++++++++++++++++++++++++++++++---
 1 file changed, 57 insertions(+), 4 deletions(-)
kernel/bpf/arena.c +11 -4
index 1727503b25d8..9b2dea229b38 100644
@@ -60,6 +60,8 @@ struct bpf_arena {
 	struct list_head vma_list;
 	/* protects vma_list */
 	struct mutex lock;
+	u64 zap_gen;
+	struct mutex zap_mutex;
 	struct irq_work     free_irq;
 	struct work_struct  free_work;
 	struct llist_head   free_spans;
@@ -289,6 +291,7 @@ static struct bpf_map *arena_map_alloc(union bpf_attr *attr)
 	if (err)
 		goto err_free_scratch;
 	mutex_init(&arena->lock);
+	mutex_init(&arena->zap_mutex);
 	raw_res_spin_lock_init(&arena->spinlock);
 	err = populate_pgtable_except_pte(arena);
 	if (err)
@@ -391,6 +394,7 @@ struct vma_list {
 	struct vm_area_struct *vma;
 	struct list_head head;
 	refcount_t mmap_count;
+	u64 zap_gen;
 };
 
 static int remember_vma(struct bpf_arena *arena, struct vm_area_struct *vma)
@@ -403,6 +407,7 @@ static int remember_vma(struct bpf_arena *arena, struct vm_area_struct *vma)
 	refcount_set(&vml->mmap_count, 1);
 	vma->vm_private_data = vml;
 	vml->vma = vma;
+	vml->zap_gen = 0;
 	list_add(&vml->head, &arena->vma_list);
 	return 0;
 }
@@ -746,12 +751,60 @@ static long arena_alloc_pages(struct bpf_arena *arena, long uaddr, long page_cnt
  */
 static void zap_pages(struct bpf_arena *arena, long uaddr, long page_cnt)
 {
+	unsigned long size = (unsigned long)page_cnt << PAGE_SHIFT;
+	struct vm_area_struct *vma;
+	struct mm_struct *mm;
 	struct vma_list *vml;
+	unsigned long vm_start;
+	u64 my_gen;
 
-	guard(mutex)(&arena->lock);
-	/* iterate link list under lock */
-	list_for_each_entry(vml, &arena->vma_list, head)
-		zap_vma_range(vml->vma, uaddr, PAGE_SIZE * page_cnt);
+	/*

kernel/bpf/arena.c static long arena_alloc_pages(struct bpf_arena *arena, long uaddr, long page_cnt · line 771

Quoted 10 lines
kernel/bpf/arena.c +10 -0
+	 * Taking mmap_read_lock() under arena->lock would deadlock against
+	 * arena_vm_close(), which runs with mmap_write_lock held and then
+	 * acquires arena->lock. Drop arena->lock for mmap_read_lock().
+	 *
+	 * Use per-call my_gen, recorded in vml->zap_gen, to remember which
+	 * vmls this invocation has already processed across the lock drop.
+	 * Hold zap_mutex around the whole walk so concurrent zap_pages()
+	 * callers cannot overwrite each other's marks on shared vmls --
+	 * otherwise call B's mark would make call A skip a vml that A has
+	 * not yet zapped for A's uaddr range.

One thing I'm fuzzy on: If the vml gens are to mediate between zap_pages calls on the same arena, doesn't the zap_mutex already serialize those calls? In that case, since zap_gen is only used for zap_pages(), do we actually need gen counting?

Quoted 39 lines
kernel/bpf/arena.c +36 -0
+	 */
+	mutex_lock(&arena->zap_mutex);
+	mutex_lock(&arena->lock);
+	my_gen = ++arena->zap_gen;
+	for (;;) {
+		mm = NULL;
+		list_for_each_entry(vml, &arena->vma_list, head) {
+			if (vml->zap_gen >= my_gen)
+				continue;
+			vml->zap_gen = my_gen;
+			if (!mmget_not_zero(vml->vma->vm_mm))
+				continue;
+			mm = vml->vma->vm_mm;
+			vm_start = vml->vma->vm_start;
+			break;
+		}
+		if (!mm)
+			break;
+		mutex_unlock(&arena->lock);
+
+		mmap_read_lock(mm);
+		/*
+		 * Re-resolve: while we waited the VMA could have been unmapped
+		 * and a different mapping installed at the same address.
+		 */
+		vma = find_vma(mm, vm_start);
+		if (vma && vma->vm_start == vm_start &&
+		    vma->vm_file && vma->vm_file->private_data == &arena->map)
+			zap_vma_range(vma, uaddr, size);
+		mmap_read_unlock(mm);
+		mmput(mm);
+
+		mutex_lock(&arena->lock);
+	}
+	mutex_unlock(&arena->lock);
+	mutex_unlock(&arena->zap_mutex);
 }
 
 static void arena_free_pages(struct bpf_arena *arena, long uaddr, long page_cnt, bool sleepable)
#4 lore raw
Quoted 85 lines · Emil Tsalapatis
Quoted 83 lines · Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

zap_vma_range() requires the owning mm's mmap_lock to be held.

Taking mmap_read_lock under arena->lock would AB-BA against arena_vm_close() and arena_map_mmap(), both of which run with mmap_write_lock held and then acquire arena->lock. Instead drop arena->lock, mmget_not_zero() the vma's mm, take mmap_read_lock, and re-resolve the vma via find_vma() since it may have been unmapped or replaced while waiting.

Track processed vmls with a per-call generation in vml->zap_gen and serialize zap_pages() callers with a new arena->zap_mutex so concurrent callers on different uaddr ranges do not mark each other's vmls processed before the zap is done.

Fixes 317460317a02 ("bpf: Introduce bpf_arena.")
---
 kernel/bpf/arena.c | 61 +++++++++++++++++++++++++++++++++++++++++++---
 1 file changed, 57 insertions(+), 4 deletions(-)
kernel/bpf/arena.c +18 -4
index 1727503b25d8..9b2dea229b38 100644
@@ -60,6 +60,8 @@ struct bpf_arena {
      struct list_head vma_list;
      /* protects vma_list */
      struct mutex lock;
+     u64 zap_gen;
+     struct mutex zap_mutex;
      struct irq_work     free_irq;
      struct work_struct  free_work;
      struct llist_head   free_spans;
@@ -289,6 +291,7 @@ static struct bpf_map *arena_map_alloc(union bpf_attr *attr)
      if (err)
              goto err_free_scratch;
      mutex_init(&arena->lock);
+     mutex_init(&arena->zap_mutex);
      raw_res_spin_lock_init(&arena->spinlock);
      err = populate_pgtable_except_pte(arena);
      if (err)
@@ -391,6 +394,7 @@ struct vma_list {
      struct vm_area_struct *vma;
      struct list_head head;
      refcount_t mmap_count;
+     u64 zap_gen;
 };
 
 static int remember_vma(struct bpf_arena *arena, struct vm_area_struct *vma)
@@ -403,6 +407,7 @@ static int remember_vma(struct bpf_arena *arena, struct vm_area_struct *vma)
      refcount_set(&vml->mmap_count, 1);
      vma->vm_private_data = vml;
      vml->vma = vma;
+     vml->zap_gen = 0;
      list_add(&vml->head, &arena->vma_list);
      return 0;
 }
@@ -746,12 +751,60 @@ static long arena_alloc_pages(struct bpf_arena *arena, long uaddr, long page_cnt
  */
 static void zap_pages(struct bpf_arena *arena, long uaddr, long page_cnt)
 {
+     unsigned long size = (unsigned long)page_cnt << PAGE_SHIFT;
+     struct vm_area_struct *vma;
+     struct mm_struct *mm;
      struct vma_list *vml;
+     unsigned long vm_start;
+     u64 my_gen;
 
-     guard(mutex)(&arena->lock);
-     /* iterate link list under lock */
-     list_for_each_entry(vml, &arena->vma_list, head)
-             zap_vma_range(vml->vma, uaddr, PAGE_SIZE * page_cnt);
+     /*
+      * Taking mmap_read_lock() under arena->lock would deadlock against
+      * arena_vm_close(), which runs with mmap_write_lock held and then
+      * acquires arena->lock. Drop arena->lock for mmap_read_lock().
+      *
+      * Use per-call my_gen, recorded in vml->zap_gen, to remember which
+      * vmls this invocation has already processed across the lock drop.
+      * Hold zap_mutex around the whole walk so concurrent zap_pages()
Quoted 8 lines

kernel/bpf/arena.c static long arena_alloc_pages(struct bpf_arena *arena, long uaddr, long page_cnt · line 771

Quoted 3 lines
kernel/bpf/arena.c +3 -0
+      * callers cannot overwrite each other's marks on shared vmls --
+      * otherwise call B's mark would make call A skip a vml that A has
+      * not yet zapped for A's uaddr range.

One thing I'm fuzzy on: If the vml gens are to mediate between zap_pages calls on the same arena, doesn't the zap_mutex already serialize those calls? In that case, since zap_gen is only used for zap_pages(), do we actually need gen counting?

hmm. Good question!
That was an evolution of the patch over several revisions. The algorithm can be changed to:

        mutex_lock(&arena->lock);
-       my_gen = ++arena->zap_gen;
+       list_for_each_entry(vml, &arena->vma_list, head)
+               vml->zapped = false;
        for (;;) {
                mm = NULL;
                list_for_each_entry(vml, &arena->vma_list, head) {
-                       if (vml->zap_gen >= my_gen)
+                       if (vml->zapped)
                                continue;

- vml->zap_gen = my_gen;
+ vml->zapped = true;

which I think is less pretty since an extra walk of the list is needed. We cannot remove zap_gen completely, since arena_vm_close() can list_del() it. So vml->zapped or some kinda marker under arena->lock is still needed.

Another option would be to move processed vml-s into stack local link list:
grab the element from arena->vma_list under arena->zap_mutex, processed it without holding arena->lock, and then at the end add it back to arena->vma_list.
Feels more convoluted.

reviewer Reviewed-by
#5 lore raw
Quoted 111 lines · Alexei Starovoitov
Quoted 85 lines · Emil Tsalapatis
Quoted 83 lines · Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

zap_vma_range() requires the owning mm's mmap_lock to be held.

Taking mmap_read_lock under arena->lock would AB-BA against arena_vm_close() and arena_map_mmap(), both of which run with mmap_write_lock held and then acquire arena->lock. Instead drop arena->lock, mmget_not_zero() the vma's mm, take mmap_read_lock, and re-resolve the vma via find_vma() since it may have been unmapped or replaced while waiting.

Track processed vmls with a per-call generation in vml->zap_gen and serialize zap_pages() callers with a new arena->zap_mutex so concurrent callers on different uaddr ranges do not mark each other's vmls processed before the zap is done.

Fixes 317460317a02 ("bpf: Introduce bpf_arena.")
---
 kernel/bpf/arena.c | 61 +++++++++++++++++++++++++++++++++++++++++++---
 1 file changed, 57 insertions(+), 4 deletions(-)
kernel/bpf/arena.c +18 -4
index 1727503b25d8..9b2dea229b38 100644
@@ -60,6 +60,8 @@ struct bpf_arena {
      struct list_head vma_list;
      /* protects vma_list */
      struct mutex lock;
+     u64 zap_gen;
+     struct mutex zap_mutex;
      struct irq_work     free_irq;
      struct work_struct  free_work;
      struct llist_head   free_spans;
@@ -289,6 +291,7 @@ static struct bpf_map *arena_map_alloc(union bpf_attr *attr)
      if (err)
              goto err_free_scratch;
      mutex_init(&arena->lock);
+     mutex_init(&arena->zap_mutex);
      raw_res_spin_lock_init(&arena->spinlock);
      err = populate_pgtable_except_pte(arena);
      if (err)
@@ -391,6 +394,7 @@ struct vma_list {
      struct vm_area_struct *vma;
      struct list_head head;
      refcount_t mmap_count;
+     u64 zap_gen;
 };
 
 static int remember_vma(struct bpf_arena *arena, struct vm_area_struct *vma)
@@ -403,6 +407,7 @@ static int remember_vma(struct bpf_arena *arena, struct vm_area_struct *vma)
      refcount_set(&vml->mmap_count, 1);
      vma->vm_private_data = vml;
      vml->vma = vma;
+     vml->zap_gen = 0;
      list_add(&vml->head, &arena->vma_list);
      return 0;
 }
@@ -746,12 +751,60 @@ static long arena_alloc_pages(struct bpf_arena *arena, long uaddr, long page_cnt
  */
 static void zap_pages(struct bpf_arena *arena, long uaddr, long page_cnt)
 {
+     unsigned long size = (unsigned long)page_cnt << PAGE_SHIFT;
+     struct vm_area_struct *vma;
+     struct mm_struct *mm;
      struct vma_list *vml;
+     unsigned long vm_start;
+     u64 my_gen;
 
-     guard(mutex)(&arena->lock);
-     /* iterate link list under lock */
-     list_for_each_entry(vml, &arena->vma_list, head)
-             zap_vma_range(vml->vma, uaddr, PAGE_SIZE * page_cnt);
+     /*
+      * Taking mmap_read_lock() under arena->lock would deadlock against
+      * arena_vm_close(), which runs with mmap_write_lock held and then
+      * acquires arena->lock. Drop arena->lock for mmap_read_lock().
+      *
+      * Use per-call my_gen, recorded in vml->zap_gen, to remember which
+      * vmls this invocation has already processed across the lock drop.
+      * Hold zap_mutex around the whole walk so concurrent zap_pages()
Quoted 8 lines

kernel/bpf/arena.c static long arena_alloc_pages(struct bpf_arena *arena, long uaddr, long page_cnt · line 771

Quoted 3 lines
kernel/bpf/arena.c +3 -0
+      * callers cannot overwrite each other's marks on shared vmls --
+      * otherwise call B's mark would make call A skip a vml that A has
+      * not yet zapped for A's uaddr range.

One thing I'm fuzzy on: If the vml gens are to mediate between zap_pages calls on the same arena, doesn't the zap_mutex already serialize those calls? In that case, since zap_gen is only used for zap_pages(), do we actually need gen counting?

hmm. Good question!
That was an evolution of the patch over several revisions. The algorithm can be changed to:

        mutex_lock(&arena->lock);
(quoted diff) +4 -3
-       my_gen = ++arena->zap_gen;
+       list_for_each_entry(vml, &arena->vma_list, head)
+               vml->zapped = false;
        for (;;) {
                mm = NULL;
                list_for_each_entry(vml, &arena->vma_list, head) {
-                       if (vml->zap_gen >= my_gen)
+                       if (vml->zapped)
                                continue;
-                       vml->zap_gen = my_gen;
+                       vml->zapped = true;
Quoted 4 lines

which I think is less pretty since an extra walk of the list is needed. We cannot remove zap_gen completely, since arena_vm_close() can list_del() it. So vml->zapped or some kinda marker under arena->lock is still needed.

Right, the list may change out from under us while we've dropped the arena lock so we are restarting from the very beginning each time. In that case zap_gen is the best way to handle this.

I can't see any weird races/edge conditions otherwise. There's no race between zappers because of the lock. So the only race is with calls that modify the address space of the task. These are
- Process exit: Handled by the reference to the mm. If we grab a reference address space teardown can't start. If we don't, we do not need to do anything.
- munmap(): When we drop the lock, either
a) the munmap will win the mmap lock race, take the arena lock, and take over zapping the entry (and calling arena_vm_close()), in which case the vma lookup fails, or
b) We win the race and complete without issue - the unmap will just clean the VMA since there's no pages to zap
- mmap() on top of an arena mapping that causes implicit munmap():
Same as case 2, zapping and unmapping is in the same critical section so if we can't find the mapping anymore the operation successfully zapped it.

Quoted 5 lines

Another option would be to move processed vml-s into stack local link list:
grab the element from arena->vma_list under arena->zap_mutex, processed it without holding arena->lock, and then at the end add it back to arena->vma_list.
Feels more convoluted.

#6 lore raw
In reply to Alexei Starovoitov
Quoted 11 lines
kernel/bpf/arena.c +5 -4
-	guard(mutex)(&arena->lock);
-	/* iterate link list under lock */
-	list_for_each_entry(vml, &arena->vma_list, head)
-		zap_vma_range(vml->vma, uaddr, PAGE_SIZE * page_cnt);
+	/*
+	 * Taking mmap_read_lock() under arena->lock would deadlock against
+	 * arena_vm_close(), which runs with mmap_write_lock held and then
+	 * acquires arena->lock. Drop arena->lock for mmap_read_lock().
+	 *

kernel/bpf/arena.c static long arena_alloc_pages(struct bpf_arena *arena, long uaddr, long page_cnt · line 775

Quoted 10 lines
kernel/bpf/arena.c +10 -0
+	 * Use per-call my_gen, recorded in vml->zap_gen, to remember which
+	 * vmls this invocation has already processed across the lock drop.
+	 * Hold zap_mutex around the whole walk so concurrent zap_pages()
+	 * callers cannot overwrite each other's marks on shared vmls --
+	 * otherwise call B's mark would make call A skip a vml that A has
+	 * not yet zapped for A's uaddr range.
+	 */
+	mutex_lock(&arena->zap_mutex);
+	mutex_lock(&arena->lock);
+	my_gen = ++arena->zap_gen;

I was confused by that as well, good that we can get rid of it.

kernel/bpf/arena.c static long arena_alloc_pages(struct bpf_arena *arena, long uaddr, long page_cnt · line 783

Quoted 8 lines
kernel/bpf/arena.c +8 -0
+	for (;;) {
+		mm = NULL;
+		list_for_each_entry(vml, &arena->vma_list, head) {
+			if (vml->zap_gen >= my_gen)
+				continue;
+			vml->zap_gen = my_gen;
+			if (!mmget_not_zero(vml->vma->vm_mm))
+				continue;

Given that we still have a VMA with a valid MM pointer, I'd assume an unconditional mmget() should just be alright here.

Or am I missing something?

Signature · 3 lines
Cheers,

David
#7 lore raw
Quoted 23 lines · David Hildenbrand (Arm)
Quoted 12 lines
kernel/bpf/arena.c +5 -4
-     guard(mutex)(&arena->lock);
-     /* iterate link list under lock */
-     list_for_each_entry(vml, &arena->vma_list, head)
-             zap_vma_range(vml->vma, uaddr, PAGE_SIZE * page_cnt);
+     /*
+      * Taking mmap_read_lock() under arena->lock would deadlock against
+      * arena_vm_close(), which runs with mmap_write_lock held and then
+      * acquires arena->lock. Drop arena->lock for mmap_read_lock().
+      *

kernel/bpf/arena.c static long arena_alloc_pages(struct bpf_arena *arena, long uaddr, long page_cnt · line 775

Quoted 10 lines
kernel/bpf/arena.c +10 -0
+      * Use per-call my_gen, recorded in vml->zap_gen, to remember which
+      * vmls this invocation has already processed across the lock drop.
+      * Hold zap_mutex around the whole walk so concurrent zap_pages()
+      * callers cannot overwrite each other's marks on shared vmls --
+      * otherwise call B's mark would make call A skip a vml that A has
+      * not yet zapped for A's uaddr range.
+      */
+     mutex_lock(&arena->zap_mutex);
+     mutex_lock(&arena->lock);
+     my_gen = ++arena->zap_gen;
Quoted 1 line

I was confused by that as well, good that we can get rid of it.

get rid of it? As I explained to Emil, zap_gen is needed.

Quoted 9 lines

kernel/bpf/arena.c static long arena_alloc_pages(struct bpf_arena *arena, long uaddr, long page_cnt · line 783

Quoted 8 lines
kernel/bpf/arena.c +8 -0
+     for (;;) {
+             mm = NULL;
+             list_for_each_entry(vml, &arena->vma_list, head) {
+                     if (vml->zap_gen >= my_gen)
+                             continue;
+                     vml->zap_gen = my_gen;
+                     if (!mmget_not_zero(vml->vma->vm_mm))
+                             continue;
Quoted 4 lines

Given that we still have a VMA with a valid MM pointer, I'd assume an unconditional mmget() should just be alright here.

Or am I missing something?

exit_mmap() -> vma_close() -> arena_vm_close() will remove vml after dropping mm_users to zero.
But parallel zap_pages could have accessed valid vma and mm pointers from vml list, but vma->vm_mm->mm_users could be zero.

#8 lore raw
Quoted 24 lines · Alexei Starovoitov
Quoted 23 lines · David Hildenbrand (Arm)
Quoted 22 lines
kernel/bpf/arena.c +15 -4
-     guard(mutex)(&arena->lock);
-     /* iterate link list under lock */
-     list_for_each_entry(vml, &arena->vma_list, head)
-             zap_vma_range(vml->vma, uaddr, PAGE_SIZE * page_cnt);
+     /*
+      * Taking mmap_read_lock() under arena->lock would deadlock against
+      * arena_vm_close(), which runs with mmap_write_lock held and then
+      * acquires arena->lock. Drop arena->lock for mmap_read_lock().
+      *
+      * Use per-call my_gen, recorded in vml->zap_gen, to remember which
+      * vmls this invocation has already processed across the lock drop.
+      * Hold zap_mutex around the whole walk so concurrent zap_pages()
+      * callers cannot overwrite each other's marks on shared vmls --
+      * otherwise call B's mark would make call A skip a vml that A has
+      * not yet zapped for A's uaddr range.
+      */
+     mutex_lock(&arena->zap_mutex);
+     mutex_lock(&arena->lock);
+     my_gen = ++arena->zap_gen;
Quoted 3 lines
Quoted 1 line

I was confused by that as well, good that we can get rid of it.

get rid of it? As I explained to Emil, zap_gen is needed.

Oh, I misunderstood your reply.

Quoted 13 lines
Quoted 13 lines

kernel/bpf/arena.c static long arena_alloc_pages(struct bpf_arena *arena, long uaddr, long page_cnt · line 783

Quoted 9 lines
kernel/bpf/arena.c +8 -0
+     for (;;) {
+             mm = NULL;
+             list_for_each_entry(vml, &arena->vma_list, head) {
+                     if (vml->zap_gen >= my_gen)
+                             continue;
+                     vml->zap_gen = my_gen;
+                     if (!mmget_not_zero(vml->vma->vm_mm))
+                             continue;

Given that we still have a VMA with a valid MM pointer, I'd assume an unconditional mmget() should just be alright here.

Quoted 6 lines
Quoted 1 line

Or am I missing something?

exit_mmap() -> vma_close() -> arena_vm_close() will remove vml after dropping mm_users to zero.
But parallel zap_pages could have accessed valid vma and mm pointers from vml list, but vma->vm_mm->mm_users could be zero.

Ah yes, the usual mmget vs. mmgrab confusion on my side.

Make sense then, thanks!

Signature · 3 lines
Cheers,

David
#9 lore raw
In reply to Alexei Starovoitov
This patch was applied to bpf/bpf-next.git (master) by Alexei Starovoitov <[email protected]>:

Hello:

This patch was applied to bpf/bpf-next.git (master) by Alexei Starovoitov <[email protected]>:

Quoted 4 lines · On Thu, 28 May 2026 15:20:14 -0700 you wrote:

From: Alexei Starovoitov <[email protected]>

zap_vma_range() requires the owning mm's mmap_lock to be held.

Quoted 8 lines

Taking mmap_read_lock under arena->lock would AB-BA against arena_vm_close() and arena_map_mmap(), both of which run with mmap_write_lock held and then acquire arena->lock. Instead drop arena->lock, mmget_not_zero() the vma's mm, take mmap_read_lock, and re-resolve the vma via find_vma() since it may have been unmapped or replaced while waiting.

[...]

Here is the summary with links:
- [bpf-next] bpf: Take mmap_lock in zap_pages()

    https://git.kernel.org/bpf/bpf-next/c/80b89d0226a0

You are awesome, thank you!

Signature · 2 lines
Deet-doot-dot, I am a bot.
https://korg.docs.kernel.org/patchwork/pwbot.html