AI Trajectory


Trajectory: (Expand/Collapse All)
Seq Timestamp Type Name Duration
0/0 2026/10/15 03:44 flow patch-triage
3m Args:
null

Results:
{
  "EnableConfigs": [
    "BPF_SYSCALL",
    "BPF_JIT"
  ],
  "FocusSymbols": [
    "arena_vm_fault",
    "arena_free_pages",
    "arena_free_worker",
    "zap_pages",
    "arena_map_alloc",
    "arena_map_free",
    "arena_map_get_file",
    "bpf_arena_alloc_pages",
    "bpf_arena_free_pages",
    "range_tree_set_avail",
    "range_tree_set_unavail",
    "range_tree_make_avail",
    "range_tree_clear"
  ],
  "KMSANReasoning": "The patch series refactors concurrency management, page fault handling, and page freeing logic for BPF arena maps (BPF_MAP_TYPE_ARENA). Specifically, it introduces an anonymous backing file with address_space_operations for rmap-based page zapping (eliminating VMA list lock inversion), an atomic operation reference counter (arena_opref) and wait queue to synchronize faults against frees, range availability tracking in the range tree (range_node available flag, range_tree_set_unavail, range_tree_make_avail), folio locking during fault admission, and state flags for deferred free spans.\n\nPotential bugs introduced or affected by these changes are concurrency bugs, use-after-free (e.g. accessing freed pages or range/span nodes during races), invalid/double free, or deadlock/locking issues. These failure modes are reliably detected by standard KASAN and LOCKDEP configurations.\n\nKMSAN is not applicable here because:\n1. No uninitialized memory or kernel structures are copied or leaked to user space (arena_map_get_file creates a cloned struct file returned via FD_ADD as a standard file descriptor integer).\n2. All newly added or modified data structures (struct range_node, struct arena_free_span) have all their fields explicitly assigned upon allocation before insertion into rb-trees or lockless lists.\n3. No branching or conditional logic depends on uninitialized scalar variables or struct padding.\n4. Memory buffer bounds and lengths remain standard page-aligned calculations and do not expose uninitialized memory reads.\n\nBecause there are no uninitialized memory access risks that would evade KASAN and require KMSAN, a dedicated KMSAN fuzzing session is not warranted.",
  "NeedsKMSAN": false,
  "Reasoning": "The patch refactors the BPF arena memory management subsystem and its range tree tracking. It redesigns the concurrency control between page fault handling and page freeing/zapping by introducing an opref counter and waitqueue, utilizes the address space rmap tree lock for zapping user VMA mappings, adopts folio locking during fault admission, introduces state tracking for deferred freeing in the worker, and adds support for unavailable ranges in the range tree allocator. These changes modify reachable core BPF and memory management paths with complex concurrency and new assertions, making them high-priority targets for fuzzing.",
  "WorthFuzzing": true
}

1/1 2026/10/15 03:44 action read-patch-diff
0m Args:
null

Results:
{
  "PatchDiff": "commit 456b159a4993a650829f5000345b42c15f99ab55\nAuthor: syz-cluster \u003ctriage@syzkaller.com\u003e\nDate:   Thu Oct 15 03:44:37 2026 +0000\n\n    syz-cluster: applied patch under review\n\ndiff --git a/include/linux/bpf.h b/include/linux/bpf.h\nindex 54144372281cb..fd2986686d629 100644\n--- a/include/linux/bpf.h\n+++ b/include/linux/bpf.h\n@@ -89,6 +89,7 @@ struct bpf_map_ops {\n \t/* funcs callable from userspace (via syscall) */\n \tint (*map_alloc_check)(union bpf_attr *attr);\n \tstruct bpf_map *(*map_alloc)(union bpf_attr *attr);\n+\tstruct file *(*map_get_file)(struct bpf_map *map, int flags);\n \tvoid (*map_release)(struct bpf_map *map, struct file *map_file);\n \tvoid (*map_free)(struct bpf_map *map);\n \tvoid (*map_free_pre_rcu)(struct bpf_map *map);\ndiff --git a/kernel/bpf/arena.c b/kernel/bpf/arena.c\nindex 0ff707707da04..899ad275ac7f5 100644\n--- a/kernel/bpf/arena.c\n+++ b/kernel/bpf/arena.c\n@@ -1,15 +1,20 @@\n // SPDX-License-Identifier: GPL-2.0-only\n /* Copyright (c) 2024 Meta Platforms, Inc. and affiliates. */\n+#include \u003clinux/anon_inodes.h\u003e\n+#include \u003clinux/atomic.h\u003e\n+#include \u003clinux/bits.h\u003e\n #include \u003clinux/bpf.h\u003e\n #include \u003clinux/btf.h\u003e\n #include \u003clinux/cacheflush.h\u003e\n #include \u003clinux/err.h\u003e\n+#include \u003clinux/fs.h\u003e\n #include \u003clinux/irq_work.h\u003e\n #include \"linux/filter.h\"\n #include \u003clinux/llist.h\u003e\n #include \u003clinux/btf_ids.h\u003e\n #include \u003clinux/vmalloc.h\u003e\n #include \u003clinux/pagemap.h\u003e\n+#include \u003clinux/wait.h\u003e\n #include \u003casm/tlbflush.h\u003e\n #include \"range_tree.h\"\n \n@@ -53,17 +58,18 @@ struct bpf_arena {\n \tu64 user_vm_start;\n \tu64 user_vm_end;\n \tstruct vm_struct *kern_vm;\n+\tstruct file *file;\n \tstruct page *scratch_page;\n \tstruct range_tree rt;\n \t/* protects rt and nr_pages */\n \trqspinlock_t spinlock;\n+\tatomic_t opref;\n+\twait_queue_head_t opwait;\n \t/* number of pages currently populated in the arena */\n \tu64 nr_pages;\n \tstruct list_head vma_list;\n \t/* protects vma_list */\n \tstruct mutex lock;\n-\tu64 zap_gen;\n-\tstruct mutex zap_mutex;\n \tstruct irq_work     free_irq;\n \tstruct work_struct  free_work;\n \tstruct llist_head   free_spans;\n@@ -72,10 +78,48 @@ struct bpf_arena {\n static void arena_free_worker(struct work_struct *work);\n static void arena_free_irq(struct irq_work *iw);\n \n+/* Positive references admit frees, negative references admit faults. */\n+enum arena_opref {\n+\tARENA_OPREF_FREE = 1,\n+\tARENA_OPREF_FAULT = -1,\n+};\n+\n+static bool arena_opref_get(struct bpf_arena *arena, enum arena_opref ref)\n+{\n+\tint users = atomic_read(\u0026arena-\u003eopref);\n+\n+\tdo {\n+\t\tif (users \u0026\u0026 (users ^ ref) \u003c 0)\n+\t\t\treturn false;\n+\t} while (!atomic_try_cmpxchg_acquire(\u0026arena-\u003eopref, \u0026users, users + ref));\n+\treturn true;\n+}\n+\n+static void arena_opref_put(struct bpf_arena *arena, enum arena_opref ref)\n+{\n+\tif (atomic_fetch_sub_release(ref, \u0026arena-\u003eopref) == ref)\n+\t\twake_up_all(\u0026arena-\u003eopwait);\n+}\n+\n+/*\n+ * Zero flags denote an unstarted free. ZAPPED implies CLEARED, and FAILED\n+ * is a terminal pre-clear failure set alone. RESERVED tracks ownership\n+ * independently of cleanup progress.\n+ * Each span has a single owner until it is published on free_spans, so flag\n+ * updates do not need atomic bit operations.\n+ */\n+enum arena_free_span_flags {\n+\tARENA_FREE_SPAN_CLEARED = BIT(0),\t/* Kernel PTEs cleared */\n+\tARENA_FREE_SPAN_ZAPPED = BIT(1),\t/* Kernel TLB flushed and user mappings zapped */\n+\tARENA_FREE_SPAN_RESERVED = BIT(2),\t/* Owns an unavailable range */\n+\tARENA_FREE_SPAN_FAILED = BIT(3),\t/* Freeing operation cannot continue */\n+};\n+\n struct arena_free_span {\n \tstruct llist_node node;\n \tunsigned long uaddr;\n \tu32 page_cnt;\n+\tunsigned int flags;\n };\n \n u64 bpf_arena_get_kern_vm_start(struct bpf_arena *arena)\n@@ -201,6 +245,9 @@ static int apply_range_set_cb(pte_t *pte, unsigned long addr, void *data)\n \t\treturn -EBUSY;\n \tset_pte_at(\u0026init_mm, addr, pte, pteval);\n #endif\n+\tpage_folio(page)-\u003eindex = compute_pgoff(d-\u003earena,\n+\t\t\t\t\t\taddr - bpf_arena_get_kern_vm_start(d-\u003earena));\n+\tpage-\u003emapping = d-\u003earena-\u003efile-\u003ef_mapping;\n \tWARN_ON_ONCE(llist_del_first(d-\u003epages) != node);\n \td-\u003ei++;\n \tWRITE_ONCE(d-\u003earena-\u003enr_pages, d-\u003earena-\u003enr_pages + 1);\n@@ -268,6 +315,20 @@ static int populate_pgtable_except_pte(struct bpf_arena *arena)\n \t\t\t\t   SZ_4G + GUARD_SZ / 2, apply_range_set_cb, NULL);\n }\n \n+/* The backing file must not hold a map reference. */\n+static const struct file_operations arena_backing_fops = {};\n+\n+/* Arena pages are not page-cache entries and must not be evicted by MM. */\n+static bool arena_release_folio(struct folio *folio, gfp_t gfp)\n+{\n+\treturn false;\n+}\n+\n+static const struct address_space_operations arena_aops = {\n+\t.dirty_folio = noop_dirty_folio,\n+\t.release_folio = arena_release_folio,\n+};\n+\n static struct bpf_map *arena_map_alloc(union bpf_attr *attr)\n {\n \tstruct vm_struct *kern_vm;\n@@ -322,16 +383,26 @@ static struct bpf_map *arena_map_alloc(union bpf_attr *attr)\n \t\tgoto err_free_arena;\n \n \trange_tree_init(\u0026arena-\u003ert);\n-\terr = range_tree_set(\u0026arena-\u003ert, 0, attr-\u003emax_entries);\n+\terr = range_tree_set_avail(\u0026arena-\u003ert, 0, attr-\u003emax_entries);\n \tif (err)\n \t\tgoto err_free_scratch;\n \tmutex_init(\u0026arena-\u003elock);\n-\tmutex_init(\u0026arena-\u003ezap_mutex);\n \traw_res_spin_lock_init(\u0026arena-\u003espinlock);\n+\tatomic_set(\u0026arena-\u003eopref, 0);\n+\tinit_waitqueue_head(\u0026arena-\u003eopwait);\n \terr = populate_pgtable_except_pte(arena);\n \tif (err)\n \t\tgoto err_destroy_rt;\n \n+\tarena-\u003efile = anon_inode_create_getfile(\"bpf-map\", \u0026arena_backing_fops,\n+\t\t\t\t\t\tNULL, O_RDWR, NULL);\n+\tif (IS_ERR(arena-\u003efile)) {\n+\t\terr = PTR_ERR(arena-\u003efile);\n+\t\tgoto err_destroy_rt;\n+\t}\n+\tarena-\u003efile-\u003ef_mapping-\u003ea_ops = \u0026arena_aops;\n+\tmapping_set_release_always(arena-\u003efile-\u003ef_mapping);\n+\n \treturn \u0026arena-\u003emap;\n \n err_destroy_rt:\n@@ -345,6 +416,14 @@ static struct bpf_map *arena_map_alloc(union bpf_attr *attr)\n \treturn ERR_PTR(err);\n }\n \n+static void arena_put_page(struct page *page)\n+{\n+\tlock_page(page);\n+\tpage-\u003emapping = NULL;\n+\tunlock_page(page);\n+\t__free_page(page);\n+}\n+\n static int existing_page_cb(pte_t *ptep, unsigned long addr, void *data)\n {\n \tstruct bpf_arena *arena = data;\n@@ -368,13 +447,15 @@ static int existing_page_cb(pte_t *ptep, unsigned long addr, void *data)\n \t * the TLB entries can stick around and continue to permit access to\n \t * the freed page. So it all relies on 1.\n \t */\n-\t__free_page(page);\n+\tarena_put_page(page);\n \treturn 0;\n }\n \n static void arena_map_free(struct bpf_map *map)\n {\n \tstruct bpf_arena *arena = container_of(map, struct bpf_arena, map);\n+\tstruct llist_node *pos, *next;\n+\tstruct arena_free_span *s;\n \n \t/*\n \t * Check that user vma-s are not around when bpf map is freed.\n@@ -385,9 +466,18 @@ static void arena_map_free(struct bpf_map *map)\n \tif (WARN_ON_ONCE(!list_empty(\u0026arena-\u003evma_list)))\n \t\treturn;\n \n-\t/* Ensure no pending deferred frees */\n+\t/*\n+\t * No callers remain. Drain the IRQ callback, then stop the worker,\n+\t * including any attempts to requeue itself during teardown.\n+\t */\n \tirq_work_sync(\u0026arena-\u003efree_irq);\n-\tflush_work(\u0026arena-\u003efree_work);\n+\tdisable_work_sync(\u0026arena-\u003efree_work);\n+\n+\t/* Remaining mapped pages are reclaimed by the page-table walk below. */\n+\tllist_for_each_safe(pos, next, llist_del_all(\u0026arena-\u003efree_spans)) {\n+\t\ts = llist_entry(pos, struct arena_free_span, node);\n+\t\tkfree_nolock(s);\n+\t}\n \n \t/*\n \t * free_vm_area() calls remove_vm_area() that calls free_unmap_vmap_area().\n@@ -400,6 +490,7 @@ static void arena_map_free(struct bpf_map *map)\n \tfree_vm_area(arena-\u003ekern_vm);\n \trange_tree_destroy(\u0026arena-\u003ert);\n \t__free_page(arena-\u003escratch_page);\n+\tfput(arena-\u003efile);\n \tbpf_map_area_free(arena);\n }\n \n@@ -428,10 +519,8 @@ static u64 arena_map_mem_usage(const struct bpf_map *map)\n }\n \n struct vma_list {\n-\tstruct vm_area_struct *vma;\n \tstruct list_head head;\n \trefcount_t mmap_count;\n-\tu64 zap_gen;\n };\n \n static int remember_vma(struct bpf_arena *arena, struct vm_area_struct *vma)\n@@ -443,8 +532,6 @@ static int remember_vma(struct bpf_arena *arena, struct vm_area_struct *vma)\n \t\treturn -ENOMEM;\n \trefcount_set(\u0026vml-\u003emmap_count, 1);\n \tvma-\u003evm_private_data = vml;\n-\tvml-\u003evma = vma;\n-\tvml-\u003ezap_gen = 0;\n \tlist_add(\u0026vml-\u003ehead, \u0026arena-\u003evma_list);\n \treturn 0;\n }\n@@ -487,13 +574,22 @@ static vm_fault_t arena_vm_fault(struct vm_fault *vmf)\n \tstruct bpf_arena *arena = container_of(map, struct bpf_arena, map);\n \tstruct mem_cgroup *new_memcg, *old_memcg;\n \tLLIST_HEAD(pages);\n-\tstruct page *page, *new_page = NULL;\n \tstruct apply_range_data data;\n \tvm_fault_t fault_ret;\n+\tstruct page *page, *new_page = NULL;\n \tlong kbase, kaddr;\n \tunsigned long flags;\n \tint ret;\n \n+\tif (!arena_opref_get(arena, ARENA_OPREF_FAULT)) {\n+\t\tif (vmf-\u003eflags \u0026 FAULT_FLAG_ALLOW_RETRY)\n+\t\t\tgoto retry;\n+\t\t/* zap_pages() does not need the fault caller's mmap_lock. */\n+\t\twait_event(arena-\u003eopwait, arena_opref_get(arena, ARENA_OPREF_FAULT));\n+\t}\n+\t/* folio_lock_or_retry() may drop the VMA lock before we release opref. */\n+\tbpf_map_inc(map);\n+\n \tkbase = bpf_arena_get_kern_vm_start(arena);\n \tkaddr = kbase + (u32)(vmf-\u003eaddress);\n \n@@ -511,15 +607,15 @@ static vm_fault_t arena_vm_fault(struct vm_fault *vmf)\n \t\tbpf_map_memcg_exit(old_memcg, new_memcg);\n \t}\n \n-\tif (raw_res_spin_lock_irqsave(\u0026arena-\u003espinlock, flags)) {\n-\t\t/*\n-\t\t * A failed lock means a possible deadlock was detected. Don't\n-\t\t * return VM_FAULT_RETRY: this handler never took mmap_lock, but\n-\t\t * the fault path would re-take it on retry and deadlock. Fail.\n-\t\t */\n-\t\tif (new_page)\n-\t\t\tfree_pages_nolock(new_page, 0);\n-\t\treturn VM_FAULT_SIGBUS;\n+\tret = raw_res_spin_lock_irqsave(\u0026arena-\u003espinlock, flags);\n+\tif (ret) {\n+\t\t/* If we are deadlocking somehow, no way to ensure forward progress. */\n+\t\tif (ret == -EDEADLK) {\n+\t\t\tfault_ret = VM_FAULT_SIGBUS;\n+\t\t\tgoto out_err;\n+\t\t}\n+\n+\t\tgoto retry_admitted;\n \t}\n \n \tpage = vmalloc_to_page((void *)kaddr);\n@@ -547,8 +643,8 @@ static vm_fault_t arena_vm_fault(struct vm_fault *vmf)\n \n \tif (!new_page) {\n \t\t/*\n-\t\t * The probed page was freed meanwhile or preallocation failed;\n-\t\t * try the non-blocking allocator, we cannot sleep here.\n+\t\t * Preallocation failed; try the non-blocking allocator since\n+\t\t * we cannot sleep here.\n \t\t */\n \t\tnew_page = bpf_alloc_page(map-\u003enuma_node, false);\n \t\tif (!new_page) {\n@@ -558,7 +654,16 @@ static vm_fault_t arena_vm_fault(struct vm_fault *vmf)\n \t}\n \n \tret = range_tree_clear(\u0026arena-\u003ert, vmf-\u003epgoff, 1);\n-\tif (ret) {\n+\t/* If a range is unavailable, try again. */\n+\tif (ret == -EAGAIN) {\n+\t\t/* Non-retryable GUP callers recheck the PTE on NOPAGE. */\n+\t\tif (!(vmf-\u003eflags \u0026 FAULT_FLAG_ALLOW_RETRY)) {\n+\t\t\tfault_ret = VM_FAULT_NOPAGE;\n+\t\t\tgoto out_err_locked_memcg;\n+\t\t}\n+\t\traw_res_spin_unlock_irqrestore(\u0026arena-\u003espinlock, flags);\n+\t\tgoto retry_memcg;\n+\t} else if (ret) {\n \t\tfault_ret = VM_FAULT_SIGBUS;\n \t\tgoto out_err_locked_memcg;\n \t}\n@@ -570,7 +675,7 @@ static vm_fault_t arena_vm_fault(struct vm_fault *vmf)\n \tret = apply_to_page_range(\u0026init_mm, kaddr, PAGE_SIZE, apply_range_set_cb, \u0026data);\n \tif (ret) {\n \t\tllist_del_first(\u0026pages);\n-\t\trange_tree_set(\u0026arena-\u003ert, vmf-\u003epgoff, 1);\n+\t\trange_tree_set_avail(\u0026arena-\u003ert, vmf-\u003epgoff, 1);\n \t\tfault_ret = VM_FAULT_SIGBUS;\n \t\tgoto out_err_locked_memcg;\n \t}\n@@ -580,20 +685,52 @@ static vm_fault_t arena_vm_fault(struct vm_fault *vmf)\n \tpage = new_page;\n \tnew_page = NULL;\n out:\n-\tpage_ref_add(page, 1);\n+\t/* Hand fault admission over to the folio lock before returning to MM. */\n+\tget_page(page);\n \traw_res_spin_unlock_irqrestore(\u0026arena-\u003espinlock, flags);\n-\tif (new_page)\n+\n+\tif (new_page) {\n \t\tfree_pages_nolock(new_page, 0);\n-\tvmf-\u003epage = page;\n-\treturn 0;\n+\t\tnew_page = NULL;\n+\t}\n+\n+\tfault_ret = folio_lock_or_retry(page_folio(page), vmf);\n+\tif (fault_ret) {\n+\t\tput_page(page);\n+\t} else {\n+\t\tvmf-\u003epage = page;\n+\t\tfault_ret = VM_FAULT_LOCKED;\n+\t}\n+\tgoto out_put;\n \n out_err_locked_memcg:\n \tbpf_map_memcg_exit(old_memcg, new_memcg);\n out_err_locked:\n \traw_res_spin_unlock_irqrestore(\u0026arena-\u003espinlock, flags);\n+out_err:\n \tif (new_page)\n \t\tfree_pages_nolock(new_page, 0);\n+out_put:\n+\tarena_opref_put(arena, ARENA_OPREF_FAULT);\n+\tbpf_map_put(map);\n \treturn fault_ret;\n+\n+retry_memcg:\n+\tbpf_map_memcg_exit(old_memcg, new_memcg);\n+retry_admitted:\n+\tarena_opref_put(arena, ARENA_OPREF_FAULT);\n+\tbpf_map_put(map);\n+retry:\n+\tif (new_page)\n+\t\tfree_pages_nolock(new_page, 0);\n+\n+\tif (!(vmf-\u003eflags \u0026 FAULT_FLAG_ALLOW_RETRY))\n+\t\treturn VM_FAULT_SIGBUS;\n+\n+\tif (!(vmf-\u003eflags \u0026 FAULT_FLAG_RETRY_NOWAIT))\n+\t\trelease_fault_lock(vmf);\n+\n+\treturn VM_FAULT_RETRY;\n }\n \n static const struct vm_operations_struct arena_vm_ops = {\n@@ -638,6 +775,20 @@ static unsigned long arena_get_unmapped_area(struct file *filp, unsigned long ad\n \treturn round_up(ret, SZ_4G);\n }\n \n+static struct file *arena_map_get_file(struct bpf_map *map, int flags)\n+{\n+\tstruct bpf_arena *arena = container_of(map, struct bpf_arena, map);\n+\tstruct file *file;\n+\n+\tfile = alloc_file_clone(arena-\u003efile, flags \u0026 (O_ACCMODE | O_NONBLOCK),\n+\t\t\t\t\u0026bpf_map_fops);\n+\tif (!IS_ERR(file)) {\n+\t\tfile-\u003eprivate_data = map;\n+\t\tfile_set_fsnotify_mode(file, FMODE_NONOTIFY);\n+\t}\n+\treturn file;\n+}\n+\n static int arena_map_mmap(struct bpf_map *map, struct vm_area_struct *vma)\n {\n \tstruct bpf_arena *arena = container_of(map, struct bpf_arena, map);\n@@ -692,6 +843,7 @@ BTF_ID_LIST_SINGLE(bpf_arena_map_btf_ids, struct, bpf_arena)\n const struct bpf_map_ops arena_map_ops = {\n \t.map_meta_equal = bpf_map_meta_equal,\n \t.map_alloc = arena_map_alloc,\n+\t.map_get_file = arena_map_get_file,\n \t.map_free = arena_map_free,\n \t.map_direct_value_addr = arena_map_direct_value_addr,\n \t.map_mmap = arena_map_mmap,\n@@ -813,7 +965,7 @@ static long arena_alloc_pages(struct bpf_arena *arena, long uaddr, long page_cnt\n out_unmap:\n \t/* Error handling: Undo partial mappings. */\n \tflush_vmap_cache(kern_vm_start + uaddr32, mapped \u003c\u003c PAGE_SHIFT);\n-\trange_tree_set(\u0026arena-\u003ert, pgoff + mapped, page_cnt - mapped);\n+\trange_tree_set_avail(\u0026arena-\u003ert, pgoff + mapped, page_cnt - mapped);\n \traw_res_spin_unlock_irqrestore(\u0026arena-\u003espinlock, flags);\n \tif (mapped)\n \t\tarena_free_pages(arena, uaddr32, mapped, sleepable);\n@@ -835,65 +987,35 @@ static long arena_alloc_pages(struct bpf_arena *arena, long uaddr, long page_cnt\n  */\n static void zap_pages(struct bpf_arena *arena, long uaddr, long page_cnt)\n {\n+\tstruct address_space *mapping = arena-\u003efile-\u003ef_mapping;\n \tunsigned long size = (unsigned long)page_cnt \u003c\u003c PAGE_SHIFT;\n+\tpgoff_t first = compute_pgoff(arena, uaddr);\n+\tpgoff_t last = first + page_cnt - 1;\n \tstruct vm_area_struct *vma;\n-\tstruct mm_struct *mm;\n-\tstruct vma_list *vml;\n-\tunsigned long vm_start;\n-\tu64 my_gen;\n \n-\t/*\n-\t * Taking mmap_read_lock() under arena-\u003elock would deadlock against\n-\t * arena_vm_close(), which runs with mmap_write_lock held and then\n-\t * acquires arena-\u003elock. Drop arena-\u003elock for mmap_read_lock().\n-\t *\n-\t * Use per-call my_gen, recorded in vml-\u003ezap_gen, to remember which\n-\t * vmls this invocation has already processed across the lock drop.\n-\t * Hold zap_mutex around the whole walk so concurrent zap_pages()\n-\t * callers cannot overwrite each other's marks on shared vmls --\n-\t * otherwise call B's mark would make call A skip a vml that A has\n-\t * not yet zapped for A's uaddr range.\n-\t */\n-\tmutex_lock(\u0026arena-\u003ezap_mutex);\n-\tmutex_lock(\u0026arena-\u003elock);\n-\tmy_gen = ++arena-\u003ezap_gen;\n-\tfor (;;) {\n-\t\tmm = NULL;\n-\t\tlist_for_each_entry(vml, \u0026arena-\u003evma_list, head) {\n-\t\t\tif (vml-\u003ezap_gen \u003e= my_gen)\n-\t\t\t\tcontinue;\n-\t\t\tvml-\u003ezap_gen = my_gen;\n-\t\t\tif (!mmget_not_zero(vml-\u003evma-\u003evm_mm))\n-\t\t\t\tcontinue;\n-\t\t\tmm = vml-\u003evma-\u003evm_mm;\n-\t\t\tvm_start = vml-\u003evma-\u003evm_start;\n-\t\t\tbreak;\n-\t\t}\n-\t\tif (!mm)\n-\t\t\tbreak;\n-\t\tmutex_unlock(\u0026arena-\u003elock);\n-\n-\t\tmmap_read_lock(mm);\n-\t\t/*\n-\t\t * Re-resolve: while we waited the VMA could have been unmapped\n-\t\t * and a different mapping installed at the same address.\n-\t\t */\n-\t\tvma = find_vma(mm, vm_start);\n-\t\tif (vma \u0026\u0026 vma-\u003evm_start == vm_start \u0026\u0026\n-\t\t    vma-\u003evm_file \u0026\u0026 vma-\u003evm_file-\u003eprivate_data == \u0026arena-\u003emap)\n-\t\t\tzap_vma_range(vma, uaddr, size);\n-\t\tmmap_read_unlock(mm);\n-\t\tmmput(mm);\n-\n-\t\tmutex_lock(\u0026arena-\u003elock);\n+\t/* The mapping lock keeps VMAs stable without taking mmap_lock. */\n+\ti_mmap_lock_read(mapping);\n+\tmapping_rmap_tree_foreach(vma, mapping, first, last) {\n+\t\tif (vma-\u003evm_ops != \u0026arena_vm_ops ||\n+\t\t    vma-\u003evm_file-\u003eprivate_data != \u0026arena-\u003emap)\n+\t\t\tcontinue;\n+\t\tzap_vma_range(vma, uaddr, size);\n \t}\n-\tmutex_unlock(\u0026arena-\u003elock);\n-\tmutex_unlock(\u0026arena-\u003ezap_mutex);\n+\ti_mmap_unlock_read(mapping);\n+}\n+\n+static void wait_for_faults(struct llist_head *pages)\n+{\n+\tstruct page *page;\n+\n+\tllist_for_each_entry(page, pages-\u003efirst, pcp_llist)\n+\t\tfolio_wait_locked(page_folio(page));\n }\n \n static void arena_free_pages(struct bpf_arena *arena, long uaddr, long page_cnt, bool sleepable)\n {\n \tstruct mem_cgroup *new_memcg, *old_memcg;\n+\tstruct range_node *unavail_node = NULL;\n \tu64 full_uaddr, uaddr_end;\n \tlong kaddr, pgoff;\n \tstruct page *page;\n@@ -902,6 +1024,7 @@ static void arena_free_pages(struct bpf_arena *arena, long uaddr, long page_cnt,\n \tstruct arena_free_span *s;\n \tstruct clear_range_data cdata;\n \tunsigned long flags;\n+\tbool release_only = false;\n \tint ret = 0;\n \n \t/* only aligned lower 32-bit are relevant */\n@@ -921,14 +1044,28 @@ static void arena_free_pages(struct bpf_arena *arena, long uaddr, long page_cnt,\n \n \tif (!sleepable)\n \t\tgoto defer;\n+\tif (!arena_opref_get(arena, ARENA_OPREF_FREE))\n+\t\tgoto defer;\n \n \tret = raw_res_spin_lock_irqsave(\u0026arena-\u003espinlock, flags);\n \n \t/* Can't proceed without holding the spinlock so defer the free */\n \tif (ret)\n-\t\tgoto defer;\n+\t\tgoto defer_admitted;\n \n-\trange_tree_set(\u0026arena-\u003ert, pgoff, page_cnt);\n+\tunavail_node = range_tree_set_unavail(\u0026arena-\u003ert, pgoff, page_cnt);\n+\tif (IS_ERR(unavail_node)) {\n+\t\traw_res_spin_unlock_irqrestore(\u0026arena-\u003espinlock, flags);\n+\n+\t\t/* If overlapping free in progress or out of memory, defer. */\n+\t\tret = PTR_ERR(unavail_node);\n+\t\tif (ret == -ENOMEM || ret == -EAGAIN)\n+\t\t\tgoto defer_admitted;\n+\t\tWARN_ON_ONCE(ret);\n+\t\tarena_opref_put(arena, ARENA_OPREF_FREE);\n+\t\tbpf_map_memcg_exit(old_memcg, new_memcg);\n+\t\treturn;\n+\t}\n \n \tinit_llist_head(\u0026free_pages);\n \tcdata.arena = arena;\n@@ -940,6 +1077,8 @@ static void arena_free_pages(struct bpf_arena *arena, long uaddr, long page_cnt,\n \t/* drop the lock to do the tlb flush and zap pages */\n \traw_res_spin_unlock_irqrestore(\u0026arena-\u003espinlock, flags);\n \n+\twait_for_faults(\u0026free_pages);\n+\n \t/* ensure no stale TLB entries */\n \tflush_tlb_kernel_range(kaddr, kaddr + (page_cnt * PAGE_SIZE));\n \n@@ -956,25 +1095,58 @@ static void arena_free_pages(struct bpf_arena *arena, long uaddr, long page_cnt,\n \t\t\t * page_cnt is big it's faster to do the batched zap.\n \t\t\t */\n \t\t\tzap_pages(arena, full_uaddr, 1);\n-\t\t__free_page(page);\n+\t\tarena_put_page(page);\n \t}\n+\n+\tret = raw_res_spin_lock_irqsave(\u0026arena-\u003espinlock, flags);\n+\tif (ret) {\n+\t\trelease_only = true;\n+\t\tgoto defer_admitted;\n+\t}\n+\n+\tret = range_tree_make_avail(\u0026arena-\u003ert, pgoff, page_cnt);\n+\traw_res_spin_unlock_irqrestore(\u0026arena-\u003espinlock, flags);\n+\tWARN_ON_ONCE(ret);\n+\tarena_opref_put(arena, ARENA_OPREF_FREE);\n \tbpf_map_memcg_exit(old_memcg, new_memcg);\n \n \treturn;\n \n+defer_admitted:\n+\tarena_opref_put(arena, ARENA_OPREF_FREE);\n defer:\n \ts = kmalloc_nolock(sizeof(struct arena_free_span), __GFP_ACCOUNT, -1);\n \tbpf_map_memcg_exit(old_memcg, new_memcg);\n-\tif (!s)\n+\tif (!s) {\n \t\t/*\n-\t\t * If allocation fails in non-sleepable context, pages are intentionally left\n-\t\t * inaccessible (leaked) until the arena is destroyed. Cleanup or retries are not\n-\t\t * possible here, so we intentionally omit them for safety.\n+\t\t * Directly mark the region available. Unavailable regions must\n+\t\t * always be transient.\n+\t\t *\n+\t\t * Directly marking the node avialable is safe because unavailable nodes\n+\t\t * are not modified by the range tree code without a reference to the node.\n+\t\t * The unavailable -\u003e available op does not touch anything in the tree apart\n+\t\t * from the node so no need to take the lock.\n+\t\t *\n+\t\t * The downside is fragmentation in the tree, but this is a) safe and b) better\n+\t\t * than leaking the range.\n \t\t */\n+\t\tif (release_only)\n+\t\t\trange_node_mark_available(unavail_node);\n+\n+\t\t/*\n+\t\t * If we haven't even zapped the pages, intentionally leave them\n+\t\t * inaccessible (leaked) until the arena is destroyed. Cleanup or\n+\t\t * retries are not possible here.\n+\t\t */\n+\n \t\treturn;\n+\t}\n \n \ts-\u003epage_cnt = page_cnt;\n \ts-\u003euaddr = uaddr;\n+\ts-\u003eflags = release_only ? (ARENA_FREE_SPAN_CLEARED |\n+\t\t\t\t   ARENA_FREE_SPAN_ZAPPED |\n+\t\t\t\t   ARENA_FREE_SPAN_RESERVED) : 0;\n \tllist_add(\u0026s-\u003enode, \u0026arena-\u003efree_spans);\n \tirq_work_queue(\u0026arena-\u003efree_irq);\n }\n@@ -1023,6 +1195,7 @@ static void arena_free_worker(struct work_struct *work)\n \tstruct mem_cgroup *new_memcg, *old_memcg;\n \tstruct llist_node *list, *pos, *t;\n \tstruct arena_free_span *s;\n+\tstruct range_node *unavail_node;\n \tu64 arena_vm_start, user_vm_start;\n \tstruct llist_head free_pages;\n \tstruct clear_range_data cdata;\n@@ -1030,8 +1203,15 @@ static void arena_free_worker(struct work_struct *work)\n \tunsigned long full_uaddr;\n \tlong kaddr, page_cnt, pgoff;\n \tunsigned long flags;\n+\tbool retry = false;\n+\tint ret;\n \n+\tif (!arena_opref_get(arena, ARENA_OPREF_FREE)) {\n+\t\tschedule_work(work);\n+\t\treturn;\n+\t}\n \tif (raw_res_spin_lock_irqsave(\u0026arena-\u003espinlock, flags)) {\n+\t\tarena_opref_put(arena, ARENA_OPREF_FREE);\n \t\tschedule_work(work);\n \t\treturn;\n \t}\n@@ -1045,23 +1225,53 @@ static void arena_free_worker(struct work_struct *work)\n \tuser_vm_start = bpf_arena_get_user_vm_start(arena);\n \n \tlist = llist_del_all(\u0026arena-\u003efree_spans);\n-\tllist_for_each(pos, list) {\n+\tllist_for_each_safe(pos, t, list) {\n \t\ts = llist_entry(pos, struct arena_free_span, node);\n+\t\tif (s-\u003eflags)\n+\t\t\tcontinue;\n+\n \t\tpage_cnt = s-\u003epage_cnt;\n-\t\tkaddr = arena_vm_start + s-\u003euaddr;\n \t\tpgoff = compute_pgoff(arena, s-\u003euaddr);\n+\t\tkaddr = arena_vm_start + s-\u003euaddr;\n+\n+\t\t/*\n+\t\t * Marking the range tree unavailable is required to avoid\n+\t\t * reallocations through, e.g., minor page faults.\n+\t\t */\n+\t\tunavail_node = range_tree_set_unavail(\u0026arena-\u003ert, pgoff, page_cnt);\n+\t\tif (!IS_ERR(unavail_node)) {\n+\t\t\ts-\u003eflags |= ARENA_FREE_SPAN_RESERVED;\n+\t\t\tgoto clear_ptes;\n+\t\t}\n \n-\t\t/* clear ptes and collect pages in free_pages llist */\n+\t\tret = PTR_ERR(unavail_node);\n+\t\t/* Retry without starting teardown. */\n+\t\tif (ret == -EAGAIN || ret == -ENOMEM)\n+\t\t\tcontinue;\n+\n+\t\t/* Unexpected failures leave pages for map teardown. */\n+\t\tWARN_ON_ONCE(ret);\n+\n+\t\ts-\u003eflags = ARENA_FREE_SPAN_FAILED;\n+\t\tcontinue;\n+\n+clear_ptes:\n+\t\t/* clear ptes and mark the span as cleared. */\n \t\tapply_to_existing_page_range(\u0026init_mm, kaddr, page_cnt \u003c\u003c PAGE_SHIFT,\n \t\t\t\t\t     apply_range_clear_cb, \u0026cdata);\n-\n-\t\trange_tree_set(\u0026arena-\u003ert, pgoff, page_cnt);\n+\t\ts-\u003eflags |= ARENA_FREE_SPAN_CLEARED;\n \t}\n \traw_res_spin_unlock_irqrestore(\u0026arena-\u003espinlock, flags);\n \n-\t/* Iterate the list again without holding spinlock to do the tlb flush and zap_pages */\n+\twait_for_faults(\u0026free_pages);\n+\n+\t/* Remove stale translations before freeing the collected pages. */\n \tllist_for_each_safe(pos, t, list) {\n \t\ts = llist_entry(pos, struct arena_free_span, node);\n+\t\tif (!(s-\u003eflags \u0026 ARENA_FREE_SPAN_CLEARED) ||\n+\t\t    (s-\u003eflags \u0026 ARENA_FREE_SPAN_ZAPPED))\n+\t\t\tcontinue;\n+\n \t\tpage_cnt = s-\u003epage_cnt;\n \t\tfull_uaddr = clear_lo32(user_vm_start) + s-\u003euaddr;\n \t\tkaddr = arena_vm_start + s-\u003euaddr;\n@@ -1072,16 +1282,68 @@ static void arena_free_worker(struct work_struct *work)\n \t\t/* remove pages from user vmas */\n \t\tzap_pages(arena, full_uaddr, page_cnt);\n \n-\t\tkfree_nolock(s);\n+\t\t/*\n+\t\t * Used to avoid zapping twice if we fail the lock acquisition\n+\t\t * below and rerun the span through this function.\n+\t\t */\n+\t\ts-\u003eflags |= ARENA_FREE_SPAN_ZAPPED;\n \t}\n \n \t/* free all pages collected by apply_to_existing_page_range() in the first loop */\n \tllist_for_each_safe(pos, t, __llist_del_all(\u0026free_pages)) {\n \t\tpage = llist_entry(pos, struct page, pcp_llist);\n-\t\t__free_page(page);\n+\t\tarena_put_page(page);\n \t}\n \n+\tif (raw_res_spin_lock_irqsave(\u0026arena-\u003espinlock, flags)) {\n+\t\tllist_for_each_safe(pos, t, list) {\n+\t\t\ts = llist_entry(pos, struct arena_free_span, node);\n+\n+\t\t\t/* Only unstarted frees and reserved ranges need a retry. */\n+\t\t\tif (!s-\u003eflags || (s-\u003eflags \u0026 ARENA_FREE_SPAN_RESERVED)) {\n+\t\t\t\tllist_add(pos, \u0026arena-\u003efree_spans);\n+\t\t\t\tretry = true;\n+\t\t\t} else {\n+\t\t\t\tkfree_nolock(s);\n+\t\t\t}\n+\t\t}\n+\t\tgoto done;\n+\t}\n+\n+\tllist_for_each_safe(pos, t, list) {\n+\t\ts = llist_entry(pos, struct arena_free_span, node);\n+\n+\t\tif (s-\u003eflags \u0026 ARENA_FREE_SPAN_FAILED) {\n+\t\t\tkfree_nolock(s);\n+\t\t\tcontinue;\n+\t\t}\n+\n+\t\tif (!(s-\u003eflags \u0026 ARENA_FREE_SPAN_CLEARED)) {\n+\t\t\tllist_add(pos, \u0026arena-\u003efree_spans);\n+\t\t\tretry = true;\n+\t\t\tcontinue;\n+\t\t}\n+\n+\t\tif (s-\u003eflags \u0026 ARENA_FREE_SPAN_RESERVED) {\n+\t\t\tpage_cnt = s-\u003epage_cnt;\n+\t\t\tpgoff = compute_pgoff(arena, s-\u003euaddr);\n+\t\t\t/*\n+\t\t\t * This range tree operation does not allocate memory,\n+\t\t\t * so failures are actual bugs.\n+\t\t\t */\n+\t\t\tret = range_tree_make_avail(\u0026arena-\u003ert, pgoff, page_cnt);\n+\t\t\tWARN_ON_ONCE(ret);\n+\t\t}\n+\t\tkfree_nolock(s);\n+\t}\n+\traw_res_spin_unlock_irqrestore(\u0026arena-\u003espinlock, flags);\n+\n+done:\n+\tarena_opref_put(arena, ARENA_OPREF_FREE);\n \tbpf_map_memcg_exit(old_memcg, new_memcg);\n+\n+\tif (retry)\n+\t\tschedule_work(work);\n }\n \n static void arena_free_irq(struct irq_work *iw)\ndiff --git a/kernel/bpf/range_tree.c b/kernel/bpf/range_tree.c\nindex 2460e78d6a554..e46f3467c3a24 100644\n--- a/kernel/bpf/range_tree.c\n+++ b/kernel/bpf/range_tree.c\n@@ -3,6 +3,7 @@\n #include \u003clinux/interval_tree_generic.h\u003e\n #include \u003clinux/slab.h\u003e\n #include \u003clinux/bpf.h\u003e\n+#include \u003clinux/err.h\u003e\n #include \"range_tree.h\"\n \n /*\n@@ -39,8 +40,29 @@ struct range_node {\n \tu32 rn_start;\n \tu32 rn_last; /* inclusive */\n \tu32 __rn_subtree_last;\n+\tbool available; /* range is available for allocating. */\n };\n \n+/* Is the range available for merging? */\n+static inline bool range_available(struct range_node *rn)\n+{\n+\t/* Pairs with smp_store_release() in range_node_mark_available(). */\n+\treturn rn \u0026\u0026 smp_load_acquire(\u0026rn-\u003eavailable);\n+}\n+\n+/*\n+ * Mark a node as available. Designed to be used locklessly\n+ * as a last-ditch effort to avoid leaking unavailable range\n+ * tree nodes when all attempts to directly or indirectly\n+ * free an arena region has failed. See arena_free_pages()\n+ * for more info.\n+ */\n+void range_node_mark_available(struct range_node *rn)\n+{\n+\t/* Pairs with smp_load_acquire() in range_available(). */\n+\tsmp_store_release(\u0026rn-\u003eavailable, true);\n+}\n+\n static struct range_node *rb_to_range_node(struct rb_node *rb)\n {\n \treturn rb_entry(rb, struct range_node, rb_range_size);\n@@ -55,20 +77,30 @@ static u32 rn_size(struct range_node *rn)\n static inline struct range_node *__find_range(struct range_tree *rt, u32 len)\n {\n \tstruct rb_node *rb = rt-\u003erange_size_root.rb_root.rb_node;\n-\tstruct range_node *best = NULL;\n+\tstruct rb_node *best = NULL;\n+\tstruct range_node *rn;\n \n \twhile (rb) {\n-\t\tstruct range_node *rn = rb_to_range_node(rb);\n+\t\trn = rb_to_range_node(rb);\n \n \t\tif (len \u003c= rn_size(rn)) {\n-\t\t\tbest = rn;\n+\t\t\tbest = rb;\n \t\t\trb = rb-\u003erb_right;\n \t\t} else {\n \t\t\trb = rb-\u003erb_left;\n \t\t}\n \t}\n \n-\treturn best;\n+\t/* Filter unavailable ranges. */\n+\twhile (best) {\n+\t\trn = rb_to_range_node(best);\n+\t\tif (range_available(rn))\n+\t\t\treturn rn;\n+\n+\t\tbest = rb_prev(best);\n+\t}\n+\n+\treturn NULL;\n }\n \n s64 range_tree_find(struct range_tree *rt, u32 len)\n@@ -135,10 +167,19 @@ range_it_iter_first(struct range_tree *rt, u32 start, u32 last)\n /* Clear the range in this range tree */\n int range_tree_clear(struct range_tree *rt, u32 start, u32 len)\n {\n+\tu32 first = start;\n \tu32 last = start + len - 1;\n \tstruct range_node *new_rn;\n \tstruct range_node *rn;\n \n+\t/* Scan for unavailable ranges and try again if so. */\n+\twhile ((rn = range_it_iter_first(rt, first, last))) {\n+\t\tif (!range_available(rn))\n+\t\t\treturn -EAGAIN;\n+\n+\t\tfirst = rn-\u003ern_last + 1;\n+\t}\n+\n \twhile ((rn = range_it_iter_first(rt, start, last))) {\n \t\tif (rn-\u003ern_start \u003c start \u0026\u0026 rn-\u003ern_last \u003e last) {\n \t\t\tu32 old_last = rn-\u003ern_last;\n@@ -159,6 +200,7 @@ int range_tree_clear(struct range_tree *rt, u32 start, u32 len)\n \t\t\trange_it_insert(rn, rt);\n \n \t\t\t/* Add right-half range */\n+\t\t\tnew_rn-\u003eavailable = rn-\u003eavailable;\n \t\t\tnew_rn-\u003ern_start = last + 1;\n \t\t\tnew_rn-\u003ern_last = old_last;\n \t\t\trange_it_insert(new_rn, rt);\n@@ -186,66 +228,172 @@ int range_tree_clear(struct range_tree *rt, u32 start, u32 len)\n int is_range_tree_set(struct range_tree *rt, u32 start, u32 len)\n {\n \tu32 last = start + len - 1;\n-\tstruct range_node *left;\n+\tstruct range_node *rn;\n \n-\t/* Is this whole range set ? */\n-\tleft = range_it_iter_first(rt, start, last);\n-\tif (left \u0026\u0026 left-\u003ern_start \u003c= start \u0026\u0026 left-\u003ern_last \u003e= last)\n-\t\treturn 0;\n+\tfor ((rn = range_it_iter_first(rt, start, last)); rn != NULL;\n+\t\trn = __range_it_iter_next(rn, start, last)) {\n+\t\t/* Make sure the range covers the start */\n+\t\tif (rn-\u003ern_start \u003e start)\n+\t\t\treturn -ESRCH;\n+\n+\t\t/* If it covers the entire range we're done. */\n+\t\tif (rn-\u003ern_last \u003e= last)\n+\t\t\treturn 0;\n+\n+\t\tstart = rn-\u003ern_last + 1;\n+\t}\n+\n+\t/* No range to cover [start, last] */\n \treturn -ESRCH;\n }\n \n-/* Set the range in this range tree */\n-int range_tree_set(struct range_tree *rt, u32 start, u32 len)\n+/* Do we have adjacent ranges (and do not overlap with them)? */\n+static int range_get_adjacent(struct range_tree *rt, u32 start, u32 last,\n+\t\tstruct range_node **leftp, struct range_node **rightp)\n {\n-\tu32 last = start + len - 1;\n-\tstruct range_node *new_rn = NULL;\n \tstruct range_node *right;\n \tstruct range_node *left;\n-\tint err;\n \n-\t/* Is this whole range already set ? */\n-\tleft = range_it_iter_first(rt, start, last);\n-\tif (left \u0026\u0026 left-\u003ern_start \u003c= start \u0026\u0026 left-\u003ern_last \u003e= last)\n-\t\treturn 0;\n+\t/* Do we have a left-adjacent range ? */\n+\tleft = start ? range_it_iter_first(rt, start - 1, start - 1) : NULL;\n+\tif (left \u0026\u0026 left-\u003ern_last != start - 1)\n+\t\treturn -EFAULT;\n \n-\tleft = range_it_iter_first(rt, start - 1, start - 1);\n-\tright = range_it_iter_first(rt, last + 1, last + 1);\n-\tif (!left \u0026\u0026 !right) {\n-\t\tnew_rn = kmalloc_nolock(sizeof(struct range_node),\n-\t\t\t\t\t__GFP_ACCOUNT, NUMA_NO_NODE);\n-\t\tif (!new_rn)\n-\t\t\treturn -ENOMEM;\n-\t}\n+\t/* Do we have a right-adjacent range ? */\n+\tright = last != U32_MAX ? range_it_iter_first(rt, last + 1, last + 1) : NULL;\n+\tif (right \u0026\u0026 right-\u003ern_start != last + 1)\n+\t\treturn -EFAULT;\n \n-\t/* Clear out everything in the range we want to set. */\n-\terr = range_tree_clear(rt, start, len);\n-\tif (err)\n-\t\tgoto out_free_new;\n+\t*leftp = left;\n+\t*rightp = right;\n+\n+\treturn 0;\n+}\n \n-\tif (left \u0026\u0026 right) {\n+/*\n+ * Merge with adjacent available ranges if possible. The new [start, last]\n+ * has already been confirmed to be adjacent with left/right by the caller.\n+ */\n+static int range_tree_merge(struct range_tree *rt, u32 start, u32 last,\n+\t\tstruct range_node *left, struct range_node *right)\n+{\n+\tif (range_available(left) \u0026\u0026 range_available(right)) {\n \t\t/* Combine left and right adjacent ranges */\n \t\trange_it_remove(left, rt);\n \t\trange_it_remove(right, rt);\n \t\tleft-\u003ern_last = right-\u003ern_last;\n \t\trange_it_insert(left, rt);\n \t\tkfree_nolock(right);\n-\t} else if (left) {\n+\t} else if (range_available(left)) {\n \t\t/* Combine with the left range */\n \t\trange_it_remove(left, rt);\n \t\tleft-\u003ern_last = last;\n \t\trange_it_insert(left, rt);\n-\t} else if (right) {\n+\t} else if (range_available(right)) {\n \t\t/* Combine with the right range */\n \t\trange_it_remove(right, rt);\n \t\tright-\u003ern_start = start;\n \t\trange_it_insert(right, rt);\n \t} else {\n-\t\t/* No adjacent ranges; use the pre-allocated node */\n-\t\tnew_rn-\u003ern_start = start;\n-\t\tnew_rn-\u003ern_last = last;\n-\t\trange_it_insert(new_rn, rt);\n+\t\t/* No merge available. */\n+\t\treturn -ENOENT;\n \t}\n+\n+\treturn 0;\n+}\n+\n+/* Make a range available, possibly merging. */\n+int range_tree_make_avail(struct range_tree *rt, u32 start, u32 len)\n+{\n+\tu32 last = start + len - 1;\n+\tstruct range_node *rn;\n+\tstruct range_node *right;\n+\tstruct range_node *left;\n+\tint err;\n+\n+\t/*\n+\t * Confirm the range exists is unavailable,\n+\t * and fits the requested range exactly.\n+\t */\n+\trn = range_it_iter_first(rt, start, last);\n+\tif (!rn || rn-\u003eavailable)\n+\t\treturn -EINVAL;\n+\n+\tif (rn-\u003ern_start != start || rn-\u003ern_last != last)\n+\t\treturn -EINVAL;\n+\n+\terr = range_get_adjacent(rt, start, last, \u0026left, \u0026right);\n+\tif (err)\n+\t\treturn err;\n+\n+\t/* If no merging required, just make available. */\n+\tif (!range_available(left) \u0026\u0026 !range_available(right)) {\n+\t\trn-\u003eavailable = true;\n+\t\treturn 0;\n+\t}\n+\n+\t/* Can merge, remove the range already. */\n+\tstart = rn-\u003ern_start;\n+\tlast = rn-\u003ern_last;\n+\trange_it_remove(rn, rt);\n+\tkfree_nolock(rn);\n+\n+\treturn range_tree_merge(rt, start, last, left, right);\n+}\n+\n+/* Set the range in this range tree */\n+static int range_tree_set(struct range_tree *rt, u32 start, u32 len,\n+\t\t\t  bool available, struct range_node **new_rnp)\n+{\n+\tu32 last = start + len - 1;\n+\tstruct range_node *new_rn = NULL;\n+\tstruct range_node *right;\n+\tstruct range_node *left;\n+\tint err;\n+\n+\t/* Already available: nothing to change. */\n+\tleft = range_it_iter_first(rt, start, last);\n+\tif (available \u0026\u0026 range_available(left) \u0026\u0026\n+\t    left-\u003ern_start \u003c= start \u0026\u0026 left-\u003ern_last \u003e= last)\n+\t\treturn 0;\n+\n+\t/* Predict whether insertion needs a new node before clearing. */\n+\tleft = start ? range_it_iter_first(rt, start - 1, start - 1) : NULL;\n+\tright = last != U32_MAX ? range_it_iter_first(rt, last + 1, last + 1) : NULL;\n+\n+\t/* Unavailable ranges cannot merge. Allocate before changing the tree. */\n+\tif (!available ||\n+\t    (!range_available(left) \u0026\u0026 !range_available(right))) {\n+\t\tnew_rn = kmalloc_nolock(sizeof(*new_rn), __GFP_ACCOUNT,\n+\t\t\t\t\tNUMA_NO_NODE);\n+\t\tif (!new_rn)\n+\t\t\treturn -ENOMEM;\n+\t}\n+\n+\t/* Clear out everything in the range we want to set. */\n+\terr = range_tree_clear(rt, start, len);\n+\tif (err)\n+\t\tgoto out_free_new;\n+\n+\t/* Recompute adjacency: clearing may have trimmed or split nodes. */\n+\terr = range_get_adjacent(rt, start, last, \u0026left, \u0026right);\n+\tif (err)\n+\t\tgoto out_free_new;\n+\n+\tif (available \u0026\u0026\n+\t    (range_available(left) || range_available(right))) {\n+\t\terr = range_tree_merge(rt, start, last, left, right);\n+\t\tgoto out_free_new;\n+\t}\n+\n+\t/* No merge possible; transfer the reserved node to the tree. */\n+\tnew_rn-\u003eavailable = available;\n+\tnew_rn-\u003ern_start = start;\n+\tnew_rn-\u003ern_last = last;\n+\trange_it_insert(new_rn, rt);\n+\tif (new_rnp)\n+\t\t*new_rnp = new_rn;\n+\n \treturn 0;\n \n out_free_new:\n@@ -253,6 +401,24 @@ int range_tree_set(struct range_tree *rt, u32 start, u32 len)\n \treturn err;\n }\n \n+int range_tree_set_avail(struct range_tree *rt, u32 start, u32 len)\n+{\n+\treturn range_tree_set(rt, start, len, true, NULL);\n+}\n+\n+struct range_node *range_tree_set_unavail(struct range_tree *rt, u32 start, u32 len)\n+{\n+\tstruct range_node *rn = NULL;\n+\tint err;\n+\n+\terr = range_tree_set(rt, start, len, false, \u0026rn);\n+\tif (err)\n+\t\treturn ERR_PTR(err);\n+\tif (WARN_ON_ONCE(!rn))\n+\t\treturn ERR_PTR(-EINVAL);\n+\treturn rn;\n+}\n+\n void range_tree_destroy(struct range_tree *rt)\n {\n \tstruct range_node *rn;\ndiff --git a/kernel/bpf/range_tree.h b/kernel/bpf/range_tree.h\nindex ff0b9110eb715..4f9ea2acea290 100644\n--- a/kernel/bpf/range_tree.h\n+++ b/kernel/bpf/range_tree.h\n@@ -10,11 +10,16 @@ struct range_tree {\n \tstruct rb_root_cached range_size_root;\n };\n \n+struct range_node;\n+\n void range_tree_init(struct range_tree *rt);\n void range_tree_destroy(struct range_tree *rt);\n \n int range_tree_clear(struct range_tree *rt, u32 start, u32 len);\n-int range_tree_set(struct range_tree *rt, u32 start, u32 len);\n+int range_tree_set_avail(struct range_tree *rt, u32 start, u32 len);\n+struct range_node *range_tree_set_unavail(struct range_tree *rt, u32 start, u32 len);\n+void range_node_mark_available(struct range_node *rn);\n+int range_tree_make_avail(struct range_tree *rt, u32 start, u32 len);\n int is_range_tree_set(struct range_tree *rt, u32 start, u32 len);\n s64 range_tree_find(struct range_tree *rt, u32 len);\n \ndiff --git a/kernel/bpf/syscall.c b/kernel/bpf/syscall.c\nindex 654f896af265b..1a1cc305dabb9 100644\n--- a/kernel/bpf/syscall.c\n+++ b/kernel/bpf/syscall.c\n@@ -1209,6 +1209,8 @@ int bpf_map_new_fd(struct bpf_map *map, int flags)\n \tif (ret \u003c 0)\n \t\treturn ret;\n \n+\tif (map-\u003eops-\u003emap_get_file)\n+\t\treturn FD_ADD(flags | O_CLOEXEC, map-\u003eops-\u003emap_get_file(map, flags));\n \treturn anon_inode_getfd(\"bpf-map\", \u0026bpf_map_fops, map,\n \t\t\t\tflags | O_CLOEXEC);\n }\ndiff --git a/tools/testing/selftests/bpf/prog_tests/arena_race.c b/tools/testing/selftests/bpf/prog_tests/arena_race.c\nnew file mode 100644\nindex 0000000000000..301f4dff28f99\n--- /dev/null\n+++ b/tools/testing/selftests/bpf/prog_tests/arena_race.c\n@@ -0,0 +1,285 @@\n+// SPDX-License-Identifier: GPL-2.0\n+\n+#define _GNU_SOURCE\n+#include \u003csched.h\u003e\n+#include \u003csys/syscall.h\u003e\n+#include \u003ctest_progs.h\u003e\n+\n+#include \"arena_race.skel.h\"\n+\n+struct free_thread_ctx {\n+\tstruct arena_race *skel;\n+\tint err;\n+\t__u32 retval;\n+};\n+\n+struct fault_thread_ctx {\n+\t__u64 *addr;\n+\tint stop;\n+};\n+\n+static int run_prog(struct bpf_program *prog, const char *name)\n+{\n+\tLIBBPF_OPTS(bpf_test_run_opts, opts);\n+\tint err;\n+\n+\terr = bpf_prog_test_run_opts(bpf_program__fd(prog), \u0026opts);\n+\treturn ASSERT_OK(err, name) \u0026\u0026 ASSERT_OK(opts.retval, name) ? 0 : -1;\n+}\n+\n+/* Trigger the sleepable free page path. */\n+static void *run_free_thread(void *arg)\n+{\n+\tLIBBPF_OPTS(bpf_test_run_opts, opts);\n+\tstruct free_thread_ctx *ctx = arg;\n+\n+\tctx-\u003eskel-\u003ebss-\u003etarget_tid = sys_gettid();\n+\tctx-\u003eerr = bpf_prog_test_run_opts(\n+\t\tbpf_program__fd(ctx-\u003eskel-\u003eprogs.free_page), \u0026opts);\n+\tctx-\u003eretval = opts.retval;\n+\treturn NULL;\n+}\n+\n+/* Continuously fault in the address. */\n+static void *fault_reader_thread(void *arg)\n+{\n+\tstruct fault_thread_ctx *ctx = arg;\n+\t__u64 *addr;\n+\n+\twhile (!READ_ONCE(ctx-\u003estop)) {\n+\t\taddr = __atomic_load_n(\u0026ctx-\u003eaddr, __ATOMIC_ACQUIRE);\n+\t\t(void)READ_ONCE(*addr);\n+\t}\n+\treturn NULL;\n+}\n+\n+static int wait_for(int *p)\n+{\n+\t__u64 deadline = get_time_ns() + 5ULL * 1000 * 1000 * 1000;\n+\n+\twhile (!READ_ONCE(*p)) {\n+\t\tif (get_time_ns() \u003e deadline)\n+\t\t\treturn -ETIMEDOUT;\n+\t}\n+\treturn 0;\n+}\n+\n+static struct arena_race *setup_arena(__u64 **addr, bool trace_flush)\n+{\n+\tstruct arena_race *skel;\n+\tsize_t arena_sz;\n+\tchar *base;\n+\tint err;\n+\n+\tskel = arena_race__open();\n+\tif (!ASSERT_OK_PTR(skel, \"open\"))\n+\t\treturn NULL;\n+\terr = bpf_program__set_autoload(skel-\u003eprogs.trace_flush, trace_flush);\n+\tif (!ASSERT_OK(err, \"trace_flush_autoload\"))\n+\t\tgoto err_out;\n+\n+\terr = arena_race__load(skel);\n+\tif (!ASSERT_OK(err, \"load\"))\n+\t\tgoto err_out;\n+\terr = arena_race__attach(skel);\n+\tif (!ASSERT_OK(err, \"attach\"))\n+\t\tgoto err_out;\n+\n+\tif (run_prog(skel-\u003eprogs.alloc_old, \"alloc_old\"))\n+\t\tgoto err_out;\n+\tif (skel-\u003ebss-\u003eskip) {\n+\t\ttest__skip();\n+\t\tgoto err_out;\n+\t}\n+\n+\tbase = bpf_map__initial_value(skel-\u003emaps.arena, \u0026arena_sz);\n+\tif (!ASSERT_OK_PTR(base, \"arena_base\"))\n+\t\tgoto err_out;\n+\t*addr = (__u64 *)(base + getpagesize());\n+\tif (!ASSERT_EQ((unsigned long)skel-\u003ebss-\u003eptr, (unsigned long)*addr,\n+\t\t       \"arena_ptr\"))\n+\t\tgoto err_out;\n+\treturn skel;\n+\n+err_out:\n+\tarena_race__destroy(skel);\n+\treturn NULL;\n+}\n+\n+static void test_free_before_flush(bool deferred)\n+{\n+\tstruct free_thread_ctx ctx = {};\n+\tstruct arena_race *skel;\n+\tpthread_t thread;\n+\t__u64 *addr;\n+\tbool thread_created = false, flush_seen = false, completed = false;\n+\tint err;\n+\n+\tif (libbpf_find_vmlinux_btf_id(\"flush_tlb_kernel_range\",\n+\t\t\t\t\tBPF_TRACE_FENTRY) \u003c= 0) {\n+\t\tprintf(\"%s:SKIP: flush_tlb_kernel_range is not an fentry target\\n\",\n+\t\t       __func__);\n+\t\ttest__skip();\n+\t\treturn;\n+\t}\n+\n+\tskel = setup_arena(\u0026addr, true);\n+\tif (!skel)\n+\t\treturn;\n+\n+\t/* Pause during a TLB flush to widen the race window. */\n+\tskel-\u003ebss-\u003epause_on_flush = 1;\n+\n+\tif (deferred) {\n+\t\t/*\n+\t\t * Test the nonsleepable free path that gets\n+\t\t * deferred to a worker in the kernel. We do\n+\t\t * so by triggering the arena operation from\n+\t\t * a nonsleepable tracepoint context.\n+\t\t */\n+\t\tskel-\u003ebss-\u003etrigger_pid_tgid =\n+\t\t\t((__u64)getpid() \u003c\u003c 32) | (__u32)sys_gettid();\n+\t\tskel-\u003ebss-\u003etrigger_syscall = SYS_getpgid;\n+\t\tskel-\u003ebss-\u003edeferred_free = 1;\n+\t\tif (!ASSERT_GE(syscall(SYS_getpgid, 0), 0, \"deferred_free\"))\n+\t\t\tgoto release;\n+\t} else {\n+\t\t/*\n+\t\t * Test the sleepable arena free path through a\n+\t\t * syscall test prog.\n+\t\t */\n+\t\tctx.skel = skel;\n+\t\terr = pthread_create(\u0026thread, NULL, run_free_thread, \u0026ctx);\n+\t\tif (!ASSERT_OK(err, \"pthread_create\")) {\n+\t\t\tskel-\u003ebss-\u003erelease = 1;\n+\t\t\tgoto out;\n+\t\t}\n+\t\tthread_created = true;\n+\t}\n+\n+\t/* Wait until the worker thread triggers a flush. */\n+\terr = wait_for(\u0026skel-\u003ebss-\u003eflush_entered);\n+\tif (!ASSERT_OK(err, \"flush_entered\"))\n+\t\tgoto release;\n+\n+\tflush_seen = true;\n+\n+\t/* Force a reallocation during the flush. */\n+\trun_prog(skel-\u003eprogs.try_realloc, \"realloc_before_flush\");\n+\tASSERT_NULL(skel-\u003ebss-\u003erealloc_ptr, \"realloc_before_flush\");\n+\n+release:\n+\tskel-\u003ebss-\u003erelease = 1;\n+\tif (thread_created) {\n+\t\tASSERT_OK(pthread_join(thread, NULL), \"pthread_join\");\n+\t\tthread_created = false;\n+\t\tcompleted = ASSERT_OK(ctx.err, \"free_run\") \u0026\u0026\n+\t\t\t    ASSERT_OK(ctx.retval, \"free_retval\");\n+\t} else if (skel-\u003ebss-\u003etarget_tid) {\n+\t\terr = wait_for(\u0026skel-\u003ebss-\u003eworker_exited);\n+\t\tcompleted = ASSERT_OK(err, \"worker_exited\");\n+\t}\n+\tASSERT_FALSE(skel-\u003ebss-\u003etimed_out, \"flush_timed_out\");\n+\n+\tif (flush_seen \u0026\u0026 completed \u0026\u0026\n+\t    !run_prog(skel-\u003eprogs.try_realloc, \"realloc_after_flush\")) {\n+\t\tASSERT_EQ((unsigned long)skel-\u003ebss-\u003erealloc_ptr,\n+\t\t\t  (unsigned long)addr, \"realloc_after_flush\");\n+\t\tASSERT_EQ(*addr, skel-\u003erodata-\u003enew_marker, \"new_marker\");\n+\t}\n+out:\n+\tarena_race__destroy(skel);\n+}\n+\n+/*\n+ * Force a race between a faulting thread in userspace and a\n+ * free operation on the arena.\n+ */\n+static void test_fault_free_realloc(void)\n+{\n+\tstruct fault_thread_ctx fault = {};\n+\tstruct arena_race *skel;\n+\tpthread_t fault_thread;\n+\tbool fault_created = false;\n+\t__u64 *addr;\n+\t__u64 expected, value;\n+\tint err, i;\n+\n+\tskel = setup_arena(\u0026addr, false);\n+\tif (!skel)\n+\t\treturn;\n+\n+\tskel-\u003ebss-\u003erealloc_after_free = 1;\n+\n+\tfault.addr = addr;\n+\terr = pthread_create(\u0026fault_thread, NULL, fault_reader_thread, \u0026fault);\n+\tif (!ASSERT_OK(err, \"pthread_create_fault\"))\n+\t\tgoto out;\n+\tfault_created = true;\n+\n+\tfor (i = 0; i \u003c 1000; i++) {\n+\t\tLIBBPF_OPTS(bpf_test_run_opts, opts);\n+\n+\t\t/* Keep deferred frees from earlier iterations on separate slots. */\n+\t\tif (i) {\n+\t\t\tskel-\u003ebss-\u003epage_idx = i;\n+\t\t\tif (run_prog(skel-\u003eprogs.alloc_old, \"alloc_next\"))\n+\t\t\t\tgoto out;\n+\t\t\taddr = (__u64 *)(unsigned long)skel-\u003ebss-\u003eptr;\n+\t\t\t__atomic_store_n(\u0026fault.addr, addr, __ATOMIC_RELEASE);\n+\t\t}\n+\n+\t\terr = bpf_prog_test_run_opts(bpf_program__fd(skel-\u003eprogs.free_page),\n+\t\t\t\t\t     \u0026opts);\n+\t\tif (err) {\n+\t\t\tASSERT_OK(err, \"free_realloc\");\n+\t\t\tbreak;\n+\t\t}\n+\t\tif (opts.retval) {\n+\t\t\tASSERT_OK(opts.retval, \"free_realloc\");\n+\t\t\tbreak;\n+\t\t}\n+\t\t/* The reader may populate the slot first, or free may defer. */\n+\t\tif (!skel-\u003ebss-\u003erealloc_ptr)\n+\t\t\tcontinue;\n+\t\tvalue = *addr;\n+\t\texpected = skel-\u003ebss-\u003ecurrent_marker;\n+\t\tif (value != expected) {\n+\t\t\tASSERT_EQ(value, expected, \"marker_after_realloc\");\n+\t\t\tbreak;\n+\t\t}\n+\t}\n+\n+\tWRITE_ONCE(fault.stop, 1);\n+\tif (fault_created) {\n+\t\tASSERT_OK(pthread_join(fault_thread, NULL), \"pthread_join_fault\");\n+\t\tfault_created = false;\n+\t}\n+out:\n+\tWRITE_ONCE(fault.stop, 1);\n+\tif (fault_created)\n+\t\tpthread_join(fault_thread, NULL);\n+\tarena_race__destroy(skel);\n+}\n+\n+void serial_test_arena_race(void)\n+{\n+\tcpu_set_t cpuset;\n+\tint err;\n+\n+\terr = sched_getaffinity(0, sizeof(cpuset), \u0026cpuset);\n+\tif (!ASSERT_OK(err, \"sched_getaffinity\"))\n+\t\treturn;\n+\tif (CPU_COUNT(\u0026cpuset) \u003c 2) {\n+\t\tprintf(\"%s:SKIP: at least two runnable CPUs are required\\n\", __func__);\n+\t\ttest__skip();\n+\t\treturn;\n+\t}\n+\n+\tif (test__start_subtest(\"free_before_flush\"))\n+\t\ttest_free_before_flush(false);\n+\tif (test__start_subtest(\"deferred_free_before_flush\"))\n+\t\ttest_free_before_flush(true);\n+\tif (test__start_subtest(\"fault_free_realloc\"))\n+\t\ttest_fault_free_realloc();\n+}\ndiff --git a/tools/testing/selftests/bpf/progs/arena_race.c b/tools/testing/selftests/bpf/progs/arena_race.c\nnew file mode 100644\nindex 0000000000000..6d1675ba23957\n--- /dev/null\n+++ b/tools/testing/selftests/bpf/progs/arena_race.c\n@@ -0,0 +1,159 @@\n+// SPDX-License-Identifier: GPL-2.0\n+\n+#define BPF_NO_KFUNC_PROTOTYPES\n+#include \u003cvmlinux.h\u003e\n+#include \u003cbpf/bpf_helpers.h\u003e\n+#include \u003cbpf/bpf_tracing.h\u003e\n+#include \"bpf_experimental.h\"\n+#include \u003cbpf_arena_common.h\u003e\n+\n+const volatile __u64 old_marker = 0x1111222233334444ULL;\n+const volatile __u64 new_marker = 0x5555666677778888ULL;\n+\n+struct {\n+\t__uint(type, BPF_MAP_TYPE_ARENA);\n+\t__uint(map_flags, BPF_F_MMAPABLE);\n+\t__uint(max_entries, 1024);\n+#ifdef __TARGET_ARCH_arm64\n+\t__ulong(map_extra, 0x1ull \u003c\u003c 32);\n+#else\n+\t__ulong(map_extra, 0x1ull \u003c\u003c 44);\n+#endif\n+} arena SEC(\".maps\");\n+\n+bool skip;\n+int page_idx;\n+\n+void __arena *ptr;\n+void __arena *realloc_ptr;\n+bool realloc_after_free;\n+__u64 current_marker;\n+__u64 marker_seq;\n+\n+int target_tid;\n+int pause_on_flush;\n+int flush_entered;\n+int release;\n+int timed_out;\n+\n+__u64 trigger_pid_tgid;\n+long trigger_syscall;\n+int deferred_free;\n+int worker_armed;\n+int worker_exited;\n+\n+static __always_inline void wait_for_release(void)\n+{\n+\twhile (!*(volatile int *)\u0026release \u0026\u0026 can_loop)\n+\t\t;\n+\tif (!*(volatile int *)\u0026release)\n+\t\ttimed_out = 1;\n+}\n+\n+SEC(\"syscall\")\n+int alloc_old(void *ctx)\n+{\n+#if defined(__BPF_FEATURE_ADDR_SPACE_CAST) || defined(BPF_ARENA_FORCE_ASM)\n+\t__u64 __arena *p;\n+\tchar __arena *base = arena_base(\u0026arena);\n+\n+\trealloc_ptr = NULL;\n+\tptr = bpf_arena_alloc_pages(\u0026arena, base + (page_idx + 1) * __PAGE_SIZE, 1,\n+\t\t\t\t    NUMA_NO_NODE, 0);\n+\tif (!ptr)\n+\t\treturn 1;\n+\tp = (__u64 __arena *)ptr;\n+\t*p = old_marker;\n+\tcurrent_marker = old_marker;\n+#else\n+\tskip = true;\n+#endif\n+\treturn 0;\n+}\n+\n+SEC(\"syscall\")\n+int free_page(void *ctx)\n+{\n+#if defined(__BPF_FEATURE_ADDR_SPACE_CAST) || defined(BPF_ARENA_FORCE_ASM)\n+\t__u64 __arena *p;\n+\t__u64 marker;\n+\n+\tif (!ptr)\n+\t\treturn 1;\n+\tbpf_arena_free_pages(\u0026arena, ptr, 1);\n+\tif (!realloc_after_free)\n+\t\treturn 0;\n+\n+\tmarker = new_marker + ++marker_seq;\n+\trealloc_ptr = bpf_arena_alloc_pages(\u0026arena, ptr, 1, NUMA_NO_NODE, 0);\n+\tif (!realloc_ptr)\n+\t\treturn 0;\n+\tptr = realloc_ptr;\n+\tp = (__u64 __arena *)ptr;\n+\t*p = marker;\n+\tcurrent_marker = marker;\n+#endif\n+\treturn 0;\n+}\n+\n+SEC(\"syscall\")\n+int try_realloc(void *ctx)\n+{\n+#if defined(__BPF_FEATURE_ADDR_SPACE_CAST) || defined(BPF_ARENA_FORCE_ASM)\n+\t__u64 __arena *p;\n+\n+\trealloc_ptr = bpf_arena_alloc_pages(\u0026arena, ptr, 1, NUMA_NO_NODE, 0);\n+\tif (realloc_ptr) {\n+\t\tptr = realloc_ptr;\n+\t\tp = (__u64 __arena *)realloc_ptr;\n+\t\t*p = new_marker;\n+\t\tcurrent_marker = new_marker;\n+\t}\n+#endif\n+\treturn 0;\n+}\n+\n+SEC(\"tp_btf/sys_enter\")\n+int BPF_PROG(deferred_free_prog, struct pt_regs *regs, long id)\n+{\n+#if defined(__BPF_FEATURE_ADDR_SPACE_CAST) || defined(BPF_ARENA_FORCE_ASM)\n+\tif (!deferred_free || bpf_get_current_pid_tgid() != trigger_pid_tgid ||\n+\t    id != trigger_syscall)\n+\t\treturn 0;\n+\n+\tdeferred_free = 0;\n+\t/* The worker can run on another CPU before the kfunc returns. */\n+\tworker_armed = 1;\n+\tbpf_arena_free_pages(\u0026arena, ptr, 1);\n+#endif\n+\treturn 0;\n+}\n+\n+SEC(\"fentry/arena_free_worker\")\n+int BPF_PROG(trace_free_worker, struct work_struct *work)\n+{\n+\tif (worker_armed \u0026\u0026 !target_tid)\n+\t\ttarget_tid = (__u32)bpf_get_current_pid_tgid();\n+\treturn 0;\n+}\n+\n+SEC(\"fexit/arena_free_worker\")\n+int BPF_PROG(trace_free_worker_ret, struct work_struct *work)\n+{\n+\tif ((__u32)bpf_get_current_pid_tgid() == target_tid)\n+\t\tworker_exited = 1;\n+\treturn 0;\n+}\n+\n+SEC(\"?fentry/flush_tlb_kernel_range\")\n+int BPF_PROG(trace_flush, unsigned long start, unsigned long end)\n+{\n+\tif (!pause_on_flush ||\n+\t    (__u32)bpf_get_current_pid_tgid() != target_tid)\n+\t\treturn 0;\n+\tflush_entered = 1;\n+\twait_for_release();\n+\treturn 0;\n+}\n+\n+char _license[] SEC(\"license\") = \"GPL\";\n"
}

2/1 2026/10/15 03:44 agent patch-evaluator
1m Model:
core

Args:
null

Results:
{
  "EnableConfigs": [
    "BPF_SYSCALL",
    "BPF_JIT"
  ],
  "FocusSymbols": [
    "arena_vm_fault",
    "arena_free_pages",
    "arena_free_worker",
    "zap_pages",
    "arena_map_alloc",
    "arena_map_free",
    "arena_map_get_file",
    "bpf_arena_alloc_pages",
    "bpf_arena_free_pages",
    "range_tree_set_avail",
    "range_tree_set_unavail",
    "range_tree_make_avail",
    "range_tree_clear"
  ],
  "Reasoning": "The patch refactors the BPF arena memory management subsystem and its range tree tracking. It redesigns the concurrency control between page fault handling and page freeing/zapping by introducing an opref counter and waitqueue, utilizes the address space rmap tree lock for zapping user VMA mappings, adopts folio locking during fault admission, introduces state tracking for deferred freeing in the worker, and adds support for unavailable ranges in the range tree allocator. These changes modify reachable core BPF and memory management paths with complex concurrency and new assertions, making them high-priority targets for fuzzing.",
  "WorthFuzzing": true
}

Instruction:
You are an expert Linux kernel maintainer and security engineer.
Your job is to review a provided patch series and evaluate whether it warrants fuzzing with syzkaller.

IMPORTANT: The changes have ALREADY been applied and committed as the HEAD commit in
your workspace. Do NOT rely on internal assumptions. You must actively use your code access
tools to inspect the actual source code, callers, and surrounding context.

================================================================================
1. CORE TRIAGE PHILOSOPHY
================================================================================
The goal of patch fuzzing is to discover crashes, regressions, exposed latent bugs,
and newly triggered assertions introduced by the patch series.

- REACHABILITY IS THE PRIMARY GATE:
  Fuzzing can only discover bugs in code that can actually execute in standard virtualized
  environments (GCE or QEMU, utilizing software-emulated devices like USB gadgets, netdev, tun/tap).
  If the modified code is structurally unreachable (see Section 2), it MUST NOT be fuzzed,
  regardless of whether it adds assertions or complex logic.

- DO NOT BLINDLY TRUST "NO FUNCTIONAL CHANGE" (NFCI) OR "REFACTORING" CLAIMS:
  Patch authors routinely label changes as "cleanups", "refactorings", or state
  "No functional change intended". Do NOT take these claims at face value.
  Code refactorings that rearrange logic, introduce helper functions, or alter state management
  in core subsystems frequently introduce subtle semantic shifts or uncover latent kernel bugs.
  If reachable executable code is modified or refactored, it MUST be fuzzed.

- NEW OR MODIFIED ASSERTIONS IN REACHABLE CODE MUST BE FUZZED:
  When a patch introduces or modifies runtime checks or assertions (e.g., WARN_ON*, VM_WARN_ON*,
  BUG_ON*, lockdep_assert*) in reachable code paths, it enforces new or stricter invariants.
  Even if the author believes the invariant always holds, fuzzing is essential to verify whether
  an unusual sequence of operations can violate it.

================================================================================
2. WHEN TO RETURN WorthFuzzing=false (NEGATIVE CRITERIA)
================================================================================
Return WorthFuzzing=false ONLY IF all modified code falls strictly into one or more of these categories:

- Non-kernel and non-executable changes:
  * Modifications to Documentation/, comments, or spelling fixes.
  * User-space directories, self-tests, samples, or scripts (e.g., tools/, samples/, scripts/, usr/)
    that do not affect the compiled kernel image (vmlinux) or kernel modules.
  * Purely decorative logging (e.g., message strings in pr_err, printk, dev_info) or tracepoints
    that do not alter control flow or data structures.
  * Build system or Kconfig changes that do not alter compiled C logic.
- Structurally unreachable hardware:
  * Vendor-specific PCIe switches, SmartNICs, or GPU drivers (e.g., mlxsw, pds_core, qed,
    ionic, amdgpu) requiring physical ASIC/PCIe cards not emulated in standard QEMU.
- Unreachable execution paths:
  * Driver teardown callbacks (.remove, .shutdown, pci_unregister_driver) executed only during
    physical PCI hot-unplug or manual sysfs driver unbinding.
  * Code paths exclusive to architectures other than the target architecture.

================================================================================
3. WHEN TO RETURN WorthFuzzing=true (POSITIVE CRITERIA)
================================================================================
Return WorthFuzzing=true whenever the patch touches reachable executable code, including:
- Core Subsystems:
  * Any logic modifications in memory management (mm/), synchronization/locking (kernel/locking/),
    BPF, scheduler, core networking, VFS, or syscall handling.
- Refactorings and Code Cleanups:
  * Any restructuring of reachable data structures, helper abstractions, or algorithm flows.
- Runtime Assertions and Defensive Checks:
  * Any introduction or alteration of assertions (WARN_ON*, VM_WARN_ON*, BUG_ON*, etc.) in reachable paths.
- Reachable Drivers and Protocols:
  * Drivers accessible via virtual buses (virtio, USB gadget, loopback, netlink, binder, sockets, etc.).

================================================================================
4. EXTRACTING FocusSymbols (PREVENTING DILUTION)
================================================================================
When WorthFuzzing=true, you must extract specific kernel functions into FocusSymbols to guide the fuzzer:

- AVOID UBIQUITOUS LIFECYCLE HOT-PATHS:
  Do NOT list generic, ubiquitous functions called by almost every program in the corpus
  (including, but not limited to: general memory allocators and deallocators, page fault
  and trap handlers, or core synchronization primitives; this is not an exhaustive list).
  Listing ubiquitous functions causes the fuzzer to classify thousands of unrelated tests as "focused",
  which severely dilutes fuzzing effort away from the actual changes.

- TARGET SPECIFIC FEATURE LOGIC AND ENTRYPOINTS:
  List functions that specifically implement the logic being added or altered, or direct API entrypoints
  for the subsystem feature under review.

- HANDLING STATIC INLINE FUNCTIONS IN HEADERS (.h):
  Compiler-inlined static functions (such as static inlines in mm/*.h or include/linux/*.h) lack
  distinct symbol addresses in vmlinux and cannot be targeted directly by symbol coverage filters.
  If the changes are primarily in static inline helpers, identify non-static, feature-specific caller
  functions in .c files that exercise them (avoiding ubiquitous lifecycle wrappers).

================================================================================
5. IDENTIFYING EnableConfigs
================================================================================
Identify any specific CONFIG_ options required to properly compile and reach the modified code:
- Inspect Kconfig files and #ifdef guards; do not make assumptions.
- Check "depends on" lines in Kconfig to include any non-standard parent subsystem configs needed.
- Strip any 'CONFIG_' prefix (e.g., return "NET_IPV4" instead of "CONFIG_NET_IPV4").
Prefer calling several tools at the same time to save round-trips.


Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.

Prompt:
Target architecture: amd64

For your convenience, here is the diff of the changes:
commit 456b159a4993a650829f5000345b42c15f99ab55
Author: syz-cluster <triage@syzkaller.com>
Date:   Thu Oct 15 03:44:37 2026 +0000

    syz-cluster: applied patch under review

diff --git a/include/linux/bpf.h b/include/linux/bpf.h
index 54144372281cb..fd2986686d629 100644
--- a/include/linux/bpf.h
+++ b/include/linux/bpf.h
@@ -89,6 +89,7 @@ struct bpf_map_ops {
 	/* funcs callable from userspace (via syscall) */
 	int (*map_alloc_check)(union bpf_attr *attr);
 	struct bpf_map *(*map_alloc)(union bpf_attr *attr);
+	struct file *(*map_get_file)(struct bpf_map *map, int flags);
 	void (*map_release)(struct bpf_map *map, struct file *map_file);
 	void (*map_free)(struct bpf_map *map);
 	void (*map_free_pre_rcu)(struct bpf_map *map);
diff --git a/kernel/bpf/arena.c b/kernel/bpf/arena.c
index 0ff707707da04..899ad275ac7f5 100644
--- a/kernel/bpf/arena.c
+++ b/kernel/bpf/arena.c
@@ -1,15 +1,20 @@
 // SPDX-License-Identifier: GPL-2.0-only
 /* Copyright (c) 2024 Meta Platforms, Inc. and affiliates. */
+#include <linux/anon_inodes.h>
+#include <linux/atomic.h>
+#include <linux/bits.h>
 #include <linux/bpf.h>
 #include <linux/btf.h>
 #include <linux/cacheflush.h>
 #include <linux/err.h>
+#include <linux/fs.h>
 #include <linux/irq_work.h>
 #include "linux/filter.h"
 #include <linux/llist.h>
 #include <linux/btf_ids.h>
 #include <linux/vmalloc.h>
 #include <linux/pagemap.h>
+#include <linux/wait.h>
 #include <asm/tlbflush.h>
 #include "range_tree.h"
 
@@ -53,17 +58,18 @@ struct bpf_arena {
 	u64 user_vm_start;
 	u64 user_vm_end;
 	struct vm_struct *kern_vm;
+	struct file *file;
 	struct page *scratch_page;
 	struct range_tree rt;
 	/* protects rt and nr_pages */
 	rqspinlock_t spinlock;
+	atomic_t opref;
+	wait_queue_head_t opwait;
 	/* number of pages currently populated in the arena */
 	u64 nr_pages;
 	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;
@@ -72,10 +78,48 @@ struct bpf_arena {
 static void arena_free_worker(struct work_struct *work);
 static void arena_free_irq(struct irq_work *iw);
 
+/* Positive references admit frees, negative references admit faults. */
+enum arena_opref {
+	ARENA_OPREF_FREE = 1,
+	ARENA_OPREF_FAULT = -1,
+};
+
+static bool arena_opref_get(struct bpf_arena *arena, enum arena_opref ref)
+{
+	int users = atomic_read(&arena->opref);
+
+	do {
+		if (users && (users ^ ref) < 0)
+			return false;
+	} while (!atomic_try_cmpxchg_acquire(&arena->opref, &users, users + ref));
+	return true;
+}
+
+static void arena_opref_put(struct bpf_arena *arena, enum arena_opref ref)
+{
+	if (atomic_fetch_sub_release(ref, &arena->opref) == ref)
+		wake_up_all(&arena->opwait);
+}
+
+/*
+ * Zero flags denote an unstarted free. ZAPPED implies CLEARED, and FAILED
+ * is a terminal pre-clear failure set alone. RESERVED tracks ownership
+ * independently of cleanup progress.
+ * Each span has a single owner until it is published on free_spans, so flag
+ * updates do not need atomic bit operations.
+ */
+enum arena_free_span_flags {
+	ARENA_FREE_SPAN_CLEARED = BIT(0),	/* Kernel PTEs cleared */
+	ARENA_FREE_SPAN_ZAPPED = BIT(1),	/* Kernel TLB flushed and user mappings zapped */
+	ARENA_FREE_SPAN_RESERVED = BIT(2),	/* Owns an unavailable range */
+	ARENA_FREE_SPAN_FAILED = BIT(3),	/* Freeing operation cannot continue */
+};
+
 struct arena_free_span {
 	struct llist_node node;
 	unsigned long uaddr;
 	u32 page_cnt;
+	unsigned int flags;
 };
 
 u64 bpf_arena_get_kern_vm_start(struct bpf_arena *arena)
@@ -201,6 +245,9 @@ static int apply_range_set_cb(pte_t *pte, unsigned long addr, void *data)
 		return -EBUSY;
 	set_pte_at(&init_mm, addr, pte, pteval);
 #endif
+	page_folio(page)->index = compute_pgoff(d->arena,
+						addr - bpf_arena_get_kern_vm_start(d->arena));
+	page->mapping = d->arena->file->f_mapping;
 	WARN_ON_ONCE(llist_del_first(d->pages) != node);
 	d->i++;
 	WRITE_ONCE(d->arena->nr_pages, d->arena->nr_pages + 1);
@@ -268,6 +315,20 @@ static int populate_pgtable_except_pte(struct bpf_arena *arena)
 				   SZ_4G + GUARD_SZ / 2, apply_range_set_cb, NULL);
 }
 
+/* The backing file must not hold a map reference. */
+static const struct file_operations arena_backing_fops = {};
+
+/* Arena pages are not page-cache entries and must not be evicted by MM. */
+static bool arena_release_folio(struct folio *folio, gfp_t gfp)
+{
+	return false;
+}
+
+static const struct address_space_operations arena_aops = {
+	.dirty_folio = noop_dirty_folio,
+	.release_folio = arena_release_folio,
+};
+
 static struct bpf_map *arena_map_alloc(union bpf_attr *attr)
 {
 	struct vm_struct *kern_vm;
@@ -322,16 +383,26 @@ static struct bpf_map *arena_map_alloc(union bpf_attr *attr)
 		goto err_free_arena;
 
 	range_tree_init(&arena->rt);
-	err = range_tree_set(&arena->rt, 0, attr->max_entries);
+	err = range_tree_set_avail(&arena->rt, 0, attr->max_entries);
 	if (err)
 		goto err_free_scratch;
 	mutex_init(&arena->lock);
-	mutex_init(&arena->zap_mutex);
 	raw_res_spin_lock_init(&arena->spinlock);
+	atomic_set(&arena->opref, 0);
+	init_waitqueue_head(&arena->opwait);
 	err = populate_pgtable_except_pte(arena);
 	if (err)
 		goto err_destroy_rt;
 
+	arena->file = anon_inode_create_getfile("bpf-map", &arena_backing_fops,
+						NULL, O_RDWR, NULL);
+	if (IS_ERR(arena->file)) {
+		err = PTR_ERR(arena->file);
+		goto err_destroy_rt;
+	}
+	arena->file->f_mapping->a_ops = &arena_aops;
+	mapping_set_release_always(arena->file->f_mapping);
+
 	return &arena->map;
 
 err_destroy_rt:
@@ -345,6 +416,14 @@ static struct bpf_map *arena_map_alloc(union bpf_attr *attr)
 	return ERR_PTR(err);
 }
 
+static void arena_put_page(struct page *page)
+{
+	lock_page(page);
+	page->mapping = NULL;
+	unlock_page(page);
+	__free_page(page);
+}
+
 static int existing_page_cb(pte_t *ptep, unsigned long addr, void *data)
 {
 	struct bpf_arena *arena = data;
@@ -368,13 +447,15 @@ static int existing_page_cb(pte_t *ptep, unsigned long addr, void *data)
 	 * the TLB entries can stick around and continue to permit access to
 	 * the freed page. So it all relies on 1.
 	 */
-	__free_page(page);
+	arena_put_page(page);
 	return 0;
 }
 
 static void arena_map_free(struct bpf_map *map)
 {
 	struct bpf_arena *arena = container_of(map, struct bpf_arena, map);
+	struct llist_node *pos, *next;
+	struct arena_free_span *s;
 
 	/*
 	 * Check that user vma-s are not around when bpf map is freed.
@@ -385,9 +466,18 @@ static void arena_map_free(struct bpf_map *map)
 	if (WARN_ON_ONCE(!list_empty(&arena->vma_list)))
 		return;
 
-	/* Ensure no pending deferred frees */
+	/*
+	 * No callers remain. Drain the IRQ callback, then stop the worker,
+	 * including any attempts to requeue itself during teardown.
+	 */
 	irq_work_sync(&arena->free_irq);
-	flush_work(&arena->free_work);
+	disable_work_sync(&arena->free_work);
+
+	/* Remaining mapped pages are reclaimed by the page-table walk below. */
+	llist_for_each_safe(pos, next, llist_del_all(&arena->free_spans)) {
+		s = llist_entry(pos, struct arena_free_span, node);
+		kfree_nolock(s);
+	}
 
 	/*
 	 * free_vm_area() calls remove_vm_area() that calls free_unmap_vmap_area().
@@ -400,6 +490,7 @@ static void arena_map_free(struct bpf_map *map)
 	free_vm_area(arena->kern_vm);
 	range_tree_destroy(&arena->rt);
 	__free_page(arena->scratch_page);
+	fput(arena->file);
 	bpf_map_area_free(arena);
 }
 
@@ -428,10 +519,8 @@ static u64 arena_map_mem_usage(const struct bpf_map *map)
 }
 
 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)
@@ -443,8 +532,6 @@ static int remember_vma(struct bpf_arena *arena, struct vm_area_struct *vma)
 		return -ENOMEM;
 	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;
 }
@@ -487,13 +574,22 @@ static vm_fault_t arena_vm_fault(struct vm_fault *vmf)
 	struct bpf_arena *arena = container_of(map, struct bpf_arena, map);
 	struct mem_cgroup *new_memcg, *old_memcg;
 	LLIST_HEAD(pages);
-	struct page *page, *new_page = NULL;
 	struct apply_range_data data;
 	vm_fault_t fault_ret;
+	struct page *page, *new_page = NULL;
 	long kbase, kaddr;
 	unsigned long flags;
 	int ret;
 
+	if (!arena_opref_get(arena, ARENA_OPREF_FAULT)) {
+		if (vmf->flags & FAULT_FLAG_ALLOW_RETRY)
+			goto retry;
+		/* zap_pages() does not need the fault caller's mmap_lock. */
+		wait_event(arena->opwait, arena_opref_get(arena, ARENA_OPREF_FAULT));
+	}
+	/* folio_lock_or_retry() may drop the VMA lock before we release opref. */
+	bpf_map_inc(map);
+
 	kbase = bpf_arena_get_kern_vm_start(arena);
 	kaddr = kbase + (u32)(vmf->address);
 
@@ -511,15 +607,15 @@ static vm_fault_t arena_vm_fault(struct vm_fault *vmf)
 		bpf_map_memcg_exit(old_memcg, new_memcg);
 	}
 
-	if (raw_res_spin_lock_irqsave(&arena->spinlock, flags)) {
-		/*
-		 * A failed lock means a possible deadlock was detected. Don't
-		 * return VM_FAULT_RETRY: this handler never took mmap_lock, but
-		 * the fault path would re-take it on retry and deadlock. Fail.
-		 */
-		if (new_page)
-			free_pages_nolock(new_page, 0);
-		return VM_FAULT_SIGBUS;
+	ret = raw_res_spin_lock_irqsave(&arena->spinlock, flags);
+	if (ret) {
+		/* If we are deadlocking somehow, no way to ensure forward progress. */
+		if (ret == -EDEADLK) {
+			fault_ret = VM_FAULT_SIGBUS;
+			goto out_err;
+		}
+
+		goto retry_admitted;
 	}
 
 	page = vmalloc_to_page((void *)kaddr);
@@ -547,8 +643,8 @@ static vm_fault_t arena_vm_fault(struct vm_fault *vmf)
 
 	if (!new_page) {
 		/*
-		 * The probed page was freed meanwhile or preallocation failed;
-		 * try the non-blocking allocator, we cannot sleep here.
+		 * Preallocation failed; try the non-blocking allocator since
+		 * we cannot sleep here.
 		 */
 		new_page = bpf_alloc_page(map->numa_node, false);
 		if (!new_page) {
@@ -558,7 +654,16 @@ static vm_fault_t arena_vm_fault(struct vm_fault *vmf)
 	}
 
 	ret = range_tree_clear(&arena->rt, vmf->pgoff, 1);
-	if (ret) {
+	/* If a range is unavailable, try again. */
+	if (ret == -EAGAIN) {
+		/* Non-retryable GUP callers recheck the PTE on NOPAGE. */
+		if (!(vmf->flags & FAULT_FLAG_ALLOW_RETRY)) {
+			fault_ret = VM_FAULT_NOPAGE;
+			goto out_err_locked_memcg;
+		}
+		raw_res_spin_unlock_irqrestore(&arena->spinlock, flags);
+		goto retry_memcg;
+	} else if (ret) {
 		fault_ret = VM_FAULT_SIGBUS;
 		goto out_err_locked_memcg;
 	}
@@ -570,7 +675,7 @@ static vm_fault_t arena_vm_fault(struct vm_fault *vmf)
 	ret = apply_to_page_range(&init_mm, kaddr, PAGE_SIZE, apply_range_set_cb, &data);
 	if (ret) {
 		llist_del_first(&pages);
-		range_tree_set(&arena->rt, vmf->pgoff, 1);
+		range_tree_set_avail(&arena->rt, vmf->pgoff, 1);
 		fault_ret = VM_FAULT_SIGBUS;
 		goto out_err_locked_memcg;
 	}
@@ -580,20 +685,52 @@ static vm_fault_t arena_vm_fault(struct vm_fault *vmf)
 	page = new_page;
 	new_page = NULL;
 out:
-	page_ref_add(page, 1);
+	/* Hand fault admission over to the folio lock before returning to MM. */
+	get_page(page);
 	raw_res_spin_unlock_irqrestore(&arena->spinlock, flags);
-	if (new_page)
+
+	if (new_page) {
 		free_pages_nolock(new_page, 0);
-	vmf->page = page;
-	return 0;
+		new_page = NULL;
+	}
+
+	fault_ret = folio_lock_or_retry(page_folio(page), vmf);
+	if (fault_ret) {
+		put_page(page);
+	} else {
+		vmf->page = page;
+		fault_ret = VM_FAULT_LOCKED;
+	}
+	goto out_put;
 
 out_err_locked_memcg:
 	bpf_map_memcg_exit(old_memcg, new_memcg);
 out_err_locked:
 	raw_res_spin_unlock_irqrestore(&arena->spinlock, flags);
+out_err:
 	if (new_page)
 		free_pages_nolock(new_page, 0);
+out_put:
+	arena_opref_put(arena, ARENA_OPREF_FAULT);
+	bpf_map_put(map);
 	return fault_ret;
+
+retry_memcg:
+	bpf_map_memcg_exit(old_memcg, new_memcg);
+retry_admitted:
+	arena_opref_put(arena, ARENA_OPREF_FAULT);
+	bpf_map_put(map);
+retry:
+	if (new_page)
+		free_pages_nolock(new_page, 0);
+
+	if (!(vmf->flags & FAULT_FLAG_ALLOW_RETRY))
+		return VM_FAULT_SIGBUS;
+
+	if (!(vmf->flags & FAULT_FLAG_RETRY_NOWAIT))
+		release_fault_lock(vmf);
+
+	return VM_FAULT_RETRY;
 }
 
 static const struct vm_operations_struct arena_vm_ops = {
@@ -638,6 +775,20 @@ static unsigned long arena_get_unmapped_area(struct file *filp, unsigned long ad
 	return round_up(ret, SZ_4G);
 }
 
+static struct file *arena_map_get_file(struct bpf_map *map, int flags)
+{
+	struct bpf_arena *arena = container_of(map, struct bpf_arena, map);
+	struct file *file;
+
+	file = alloc_file_clone(arena->file, flags & (O_ACCMODE | O_NONBLOCK),
+				&bpf_map_fops);
+	if (!IS_ERR(file)) {
+		file->private_data = map;
+		file_set_fsnotify_mode(file, FMODE_NONOTIFY);
+	}
+	return file;
+}
+
 static int arena_map_mmap(struct bpf_map *map, struct vm_area_struct *vma)
 {
 	struct bpf_arena *arena = container_of(map, struct bpf_arena, map);
@@ -692,6 +843,7 @@ BTF_ID_LIST_SINGLE(bpf_arena_map_btf_ids, struct, bpf_arena)
 const struct bpf_map_ops arena_map_ops = {
 	.map_meta_equal = bpf_map_meta_equal,
 	.map_alloc = arena_map_alloc,
+	.map_get_file = arena_map_get_file,
 	.map_free = arena_map_free,
 	.map_direct_value_addr = arena_map_direct_value_addr,
 	.map_mmap = arena_map_mmap,
@@ -813,7 +965,7 @@ static long arena_alloc_pages(struct bpf_arena *arena, long uaddr, long page_cnt
 out_unmap:
 	/* Error handling: Undo partial mappings. */
 	flush_vmap_cache(kern_vm_start + uaddr32, mapped << PAGE_SHIFT);
-	range_tree_set(&arena->rt, pgoff + mapped, page_cnt - mapped);
+	range_tree_set_avail(&arena->rt, pgoff + mapped, page_cnt - mapped);
 	raw_res_spin_unlock_irqrestore(&arena->spinlock, flags);
 	if (mapped)
 		arena_free_pages(arena, uaddr32, mapped, sleepable);
@@ -835,65 +987,35 @@ 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)
 {
+	struct address_space *mapping = arena->file->f_mapping;
 	unsigned long size = (unsigned long)page_cnt << PAGE_SHIFT;
+	pgoff_t first = compute_pgoff(arena, uaddr);
+	pgoff_t last = first + page_cnt - 1;
 	struct vm_area_struct *vma;
-	struct mm_struct *mm;
-	struct vma_list *vml;
-	unsigned long vm_start;
-	u64 my_gen;
 
-	/*
-	 * 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);
+	/* The mapping lock keeps VMAs stable without taking mmap_lock. */
+	i_mmap_lock_read(mapping);
+	mapping_rmap_tree_foreach(vma, mapping, first, last) {
+		if (vma->vm_ops != &arena_vm_ops ||
+		    vma->vm_file->private_data != &arena->map)
+			continue;
+		zap_vma_range(vma, uaddr, size);
 	}
-	mutex_unlock(&arena->lock);
-	mutex_unlock(&arena->zap_mutex);
+	i_mmap_unlock_read(mapping);
+}
+
+static void wait_for_faults(struct llist_head *pages)
+{
+	struct page *page;
+
+	llist_for_each_entry(page, pages->first, pcp_llist)
+		folio_wait_locked(page_folio(page));
 }
 
 static void arena_free_pages(struct bpf_arena *arena, long uaddr, long page_cnt, bool sleepable)
 {
 	struct mem_cgroup *new_memcg, *old_memcg;
+	struct range_node *unavail_node = NULL;
 	u64 full_uaddr, uaddr_end;
 	long kaddr, pgoff;
 	struct page *page;
@@ -902,6 +1024,7 @@ static void arena_free_pages(struct bpf_arena *arena, long uaddr, long page_cnt,
 	struct arena_free_span *s;
 	struct clear_range_data cdata;
 	unsigned long flags;
+	bool release_only = false;
 	int ret = 0;
 
 	/* only aligned lower 32-bit are relevant */
@@ -921,14 +1044,28 @@ static void arena_free_pages(struct bpf_arena *arena, long uaddr, long page_cnt,
 
 	if (!sleepable)
 		goto defer;
+	if (!arena_opref_get(arena, ARENA_OPREF_FREE))
+		goto defer;
 
 	ret = raw_res_spin_lock_irqsave(&arena->spinlock, flags);
 
 	/* Can't proceed without holding the spinlock so defer the free */
 	if (ret)
-		goto defer;
+		goto defer_admitted;
 
-	range_tree_set(&arena->rt, pgoff, page_cnt);
+	unavail_node = range_tree_set_unavail(&arena->rt, pgoff, page_cnt);
+	if (IS_ERR(unavail_node)) {
+		raw_res_spin_unlock_irqrestore(&arena->spinlock, flags);
+
+		/* If overlapping free in progress or out of memory, defer. */
+		ret = PTR_ERR(unavail_node);
+		if (ret == -ENOMEM || ret == -EAGAIN)
+			goto defer_admitted;
+		WARN_ON_ONCE(ret);
+		arena_opref_put(arena, ARENA_OPREF_FREE);
+		bpf_map_memcg_exit(old_memcg, new_memcg);
+		return;
+	}
 
 	init_llist_head(&free_pages);
 	cdata.arena = arena;
@@ -940,6 +1077,8 @@ static void arena_free_pages(struct bpf_arena *arena, long uaddr, long page_cnt,
 	/* drop the lock to do the tlb flush and zap pages */
 	raw_res_spin_unlock_irqrestore(&arena->spinlock, flags);
 
+	wait_for_faults(&free_pages);
+
 	/* ensure no stale TLB entries */
 	flush_tlb_kernel_range(kaddr, kaddr + (page_cnt * PAGE_SIZE));
 
@@ -956,25 +1095,58 @@ static void arena_free_pages(struct bpf_arena *arena, long uaddr, long page_cnt,
 			 * page_cnt is big it's faster to do the batched zap.
 			 */
 			zap_pages(arena, full_uaddr, 1);
-		__free_page(page);
+		arena_put_page(page);
 	}
+
+	ret = raw_res_spin_lock_irqsave(&arena->spinlock, flags);
+	if (ret) {
+		release_only = true;
+		goto defer_admitted;
+	}
+
+	ret = range_tree_make_avail(&arena->rt, pgoff, page_cnt);
+	raw_res_spin_unlock_irqrestore(&arena->spinlock, flags);
+	WARN_ON_ONCE(ret);
+	arena_opref_put(arena, ARENA_OPREF_FREE);
 	bpf_map_memcg_exit(old_memcg, new_memcg);
 
 	return;
 
+defer_admitted:
+	arena_opref_put(arena, ARENA_OPREF_FREE);
 defer:
 	s = kmalloc_nolock(sizeof(struct arena_free_span), __GFP_ACCOUNT, -1);
 	bpf_map_memcg_exit(old_memcg, new_memcg);
-	if (!s)
+	if (!s) {
 		/*
-		 * If allocation fails in non-sleepable context, pages are intentionally left
-		 * inaccessible (leaked) until the arena is destroyed. Cleanup or retries are not
-		 * possible here, so we intentionally omit them for safety.
+		 * Directly mark the region available. Unavailable regions must
+		 * always be transient.
+		 *
+		 * Directly marking the node avialable is safe because unavailable nodes
+		 * are not modified by the range tree code without a reference to the node.
+		 * The unavailable -> available op does not touch anything in the tree apart
+		 * from the node so no need to take the lock.
+		 *
+		 * The downside is fragmentation in the tree, but this is a) safe and b) better
+		 * than leaking the range.
 		 */
+		if (release_only)
+			range_node_mark_available(unavail_node);
+
+		/*
+		 * If we haven't even zapped the pages, intentionally leave them
+		 * inaccessible (leaked) until the arena is destroyed. Cleanup or
+		 * retries are not possible here.
+		 */
+
 		return;
+	}
 
 	s->page_cnt = page_cnt;
 	s->uaddr = uaddr;
+	s->flags = release_only ? (ARENA_FREE_SPAN_CLEARED |
+				   ARENA_FREE_SPAN_ZAPPED |
+				   ARENA_FREE_SPAN_RESERVED) : 0;
 	llist_add(&s->node, &arena->free_spans);
 	irq_work_queue(&arena->free_irq);
 }
@@ -1023,6 +1195,7 @@ static void arena_free_worker(struct work_struct *work)
 	struct mem_cgroup *new_memcg, *old_memcg;
 	struct llist_node *list, *pos, *t;
 	struct arena_free_span *s;
+	struct range_node *unavail_node;
 	u64 arena_vm_start, user_vm_start;
 	struct llist_head free_pages;
 	struct clear_range_data cdata;
@@ -1030,8 +1203,15 @@ static void arena_free_worker(struct work_struct *work)
 	unsigned long full_uaddr;
 	long kaddr, page_cnt, pgoff;
 	unsigned long flags;
+	bool retry = false;
+	int ret;
 
+	if (!arena_opref_get(arena, ARENA_OPREF_FREE)) {
+		schedule_work(work);
+		return;
+	}
 	if (raw_res_spin_lock_irqsave(&arena->spinlock, flags)) {
+		arena_opref_put(arena, ARENA_OPREF_FREE);
 		schedule_work(work);
 		return;
 	}
@@ -1045,23 +1225,53 @@ static void arena_free_worker(struct work_struct *work)
 	user_vm_start = bpf_arena_get_user_vm_start(arena);
 
 	list = llist_del_all(&arena->free_spans);
-	llist_for_each(pos, list) {
+	llist_for_each_safe(pos, t, list) {
 		s = llist_entry(pos, struct arena_free_span, node);
+		if (s->flags)
+			continue;
+
 		page_cnt = s->page_cnt;
-		kaddr = arena_vm_start + s->uaddr;
 		pgoff = compute_pgoff(arena, s->uaddr);
+		kaddr = arena_vm_start + s->uaddr;
+
+		/*
+		 * Marking the range tree unavailable is required to avoid
+		 * reallocations through, e.g., minor page faults.
+		 */
+		unavail_node = range_tree_set_unavail(&arena->rt, pgoff, page_cnt);
+		if (!IS_ERR(unavail_node)) {
+			s->flags |= ARENA_FREE_SPAN_RESERVED;
+			goto clear_ptes;
+		}
 
-		/* clear ptes and collect pages in free_pages llist */
+		ret = PTR_ERR(unavail_node);
+		/* Retry without starting teardown. */
+		if (ret == -EAGAIN || ret == -ENOMEM)
+			continue;
+
+		/* Unexpected failures leave pages for map teardown. */
+		WARN_ON_ONCE(ret);
+
+		s->flags = ARENA_FREE_SPAN_FAILED;
+		continue;
+
+clear_ptes:
+		/* clear ptes and mark the span as cleared. */
 		apply_to_existing_page_range(&init_mm, kaddr, page_cnt << PAGE_SHIFT,
 					     apply_range_clear_cb, &cdata);
-
-		range_tree_set(&arena->rt, pgoff, page_cnt);
+		s->flags |= ARENA_FREE_SPAN_CLEARED;
 	}
 	raw_res_spin_unlock_irqrestore(&arena->spinlock, flags);
 
-	/* Iterate the list again without holding spinlock to do the tlb flush and zap_pages */
+	wait_for_faults(&free_pages);
+
+	/* Remove stale translations before freeing the collected pages. */
 	llist_for_each_safe(pos, t, list) {
 		s = llist_entry(pos, struct arena_free_span, node);
+		if (!(s->flags & ARENA_FREE_SPAN_CLEARED) ||
+		    (s->flags & ARENA_FREE_SPAN_ZAPPED))
+			continue;
+
 		page_cnt = s->page_cnt;
 		full_uaddr = clear_lo32(user_vm_start) + s->uaddr;
 		kaddr = arena_vm_start + s->uaddr;
@@ -1072,16 +1282,68 @@ static void arena_free_worker(struct work_struct *work)
 		/* remove pages from user vmas */
 		zap_pages(arena, full_uaddr, page_cnt);
 
-		kfree_nolock(s);
+		/*
+		 * Used to avoid zapping twice if we fail the lock acquisition
+		 * below and rerun the span through this function.
+		 */
+		s->flags |= ARENA_FREE_SPAN_ZAPPED;
 	}
 
 	/* free all pages collected by apply_to_existing_page_range() in the first loop */
 	llist_for_each_safe(pos, t, __llist_del_all(&free_pages)) {
 		page = llist_entry(pos, struct page, pcp_llist);
-		__free_page(page);
+		arena_put_page(page);
 	}
 
+	if (raw_res_spin_lock_irqsave(&arena->spinlock, flags)) {
+		llist_for_each_safe(pos, t, list) {
+			s = llist_entry(pos, struct arena_free_span, node);
+
+			/* Only unstarted frees and reserved ranges need a retry. */
+			if (!s->flags || (s->flags & ARENA_FREE_SPAN_RESERVED)) {
+				llist_add(pos, &arena->free_spans);
+				retry = true;
+			} else {
+				kfree_nolock(s);
+			}
+		}
+		goto done;
+	}
+
+	llist_for_each_safe(pos, t, list) {
+		s = llist_entry(pos, struct arena_free_span, node);
+
+		if (s->flags & ARENA_FREE_SPAN_FAILED) {
+			kfree_nolock(s);
+			continue;
+		}
+
+		if (!(s->flags & ARENA_FREE_SPAN_CLEARED)) {
+			llist_add(pos, &arena->free_spans);
+			retry = true;
+			continue;
+		}
+
+		if (s->flags & ARENA_FREE_SPAN_RESERVED) {
+			page_cnt = s->page_cnt;
+			pgoff = compute_pgoff(arena, s->uaddr);
+			/*
+			 * This range tree operation does not allocate memory,
+			 * so failures are actual bugs.
+			 */
+			ret = range_tree_make_avail(&arena->rt, pgoff, page_cnt);
+			WARN_ON_ONCE(ret);
+		}
+		kfree_nolock(s);
+	}
+	raw_res_spin_unlock_irqrestore(&arena->spinlock, flags);
+
+done:
+	arena_opref_put(arena, ARENA_OPREF_FREE);
 	bpf_map_memcg_exit(old_memcg, new_memcg);
+
+	if (retry)
+		schedule_work(work);
 }
 
 static void arena_free_irq(struct irq_work *iw)
diff --git a/kernel/bpf/range_tree.c b/kernel/bpf/range_tree.c
index 2460e78d6a554..e46f3467c3a24 100644
--- a/kernel/bpf/range_tree.c
+++ b/kernel/bpf/range_tree.c
@@ -3,6 +3,7 @@
 #include <linux/interval_tree_generic.h>
 #include <linux/slab.h>
 #include <linux/bpf.h>
+#include <linux/err.h>
 #include "range_tree.h"
 
 /*
@@ -39,8 +40,29 @@ struct range_node {
 	u32 rn_start;
 	u32 rn_last; /* inclusive */
 	u32 __rn_subtree_last;
+	bool available; /* range is available for allocating. */
 };
 
+/* Is the range available for merging? */
+static inline bool range_available(struct range_node *rn)
+{
+	/* Pairs with smp_store_release() in range_node_mark_available(). */
+	return rn && smp_load_acquire(&rn->available);
+}
+
+/*
+ * Mark a node as available. Designed to be used locklessly
+ * as a last-ditch effort to avoid leaking unavailable range
+ * tree nodes when all attempts to directly or indirectly
+ * free an arena region has failed. See arena_free_pages()
+ * for more info.
+ */
+void range_node_mark_available(struct range_node *rn)
+{
+	/* Pairs with smp_load_acquire() in range_available(). */
+	smp_store_release(&rn->available, true);
+}
+
 static struct range_node *rb_to_range_node(struct rb_node *rb)
 {
 	return rb_entry(rb, struct range_node, rb_range_size);
@@ -55,20 +77,30 @@ static u32 rn_size(struct range_node *rn)
 static inline struct range_node *__find_range(struct range_tree *rt, u32 len)
 {
 	struct rb_node *rb = rt->range_size_root.rb_root.rb_node;
-	struct range_node *best = NULL;
+	struct rb_node *best = NULL;
+	struct range_node *rn;
 
 	while (rb) {
-		struct range_node *rn = rb_to_range_node(rb);
+		rn = rb_to_range_node(rb);
 
 		if (len <= rn_size(rn)) {
-			best = rn;
+			best = rb;
 			rb = rb->rb_right;
 		} else {
 			rb = rb->rb_left;
 		}
 	}
 
-	return best;
+	/* Filter unavailable ranges. */
+	while (best) {
+		rn = rb_to_range_node(best);
+		if (range_available(rn))
+			return rn;
+
+		best = rb_prev(best);
+	}
+
+	return NULL;
 }
 
 s64 range_tree_find(struct range_tree *rt, u32 len)
@@ -135,10 +167,19 @@ range_it_iter_first(struct range_tree *rt, u32 start, u32 last)
 /* Clear the range in this range tree */
 int range_tree_clear(struct range_tree *rt, u32 start, u32 len)
 {
+	u32 first = start;
 	u32 last = start + len - 1;
 	struct range_node *new_rn;
 	struct range_node *rn;
 
+	/* Scan for unavailable ranges and try again if so. */
+	while ((rn = range_it_iter_first(rt, first, last))) {
+		if (!range_available(rn))
+			return -EAGAIN;
+
+		first = rn->rn_last + 1;
+	}
+
 	while ((rn = range_it_iter_first(rt, start, last))) {
 		if (rn->rn_start < start && rn->rn_last > last) {
 			u32 old_last = rn->rn_last;
@@ -159,6 +200,7 @@ int range_tree_clear(struct range_tree *rt, u32 start, u32 len)
 			range_it_insert(rn, rt);
 
 			/* Add right-half range */
+			new_rn->available = rn->available;
 			new_rn->rn_start = last + 1;
 			new_rn->rn_last = old_last;
 			range_it_insert(new_rn, rt);
@@ -186,66 +228,172 @@ int range_tree_clear(struct range_tree *rt, u32 start, u32 len)
 int is_range_tree_set(struct range_tree *rt, u32 start, u32 len)
 {
 	u32 last = start + len - 1;
-	struct range_node *left;
+	struct range_node *rn;
 
-	/* Is this whole range set ? */
-	left = range_it_iter_first(rt, start, last);
-	if (left && left->rn_start <= start && left->rn_last >= last)
-		return 0;
+	for ((rn = range_it_iter_first(rt, start, last)); rn != NULL;
+		rn = __range_it_iter_next(rn, start, last)) {
+		/* Make sure the range covers the start */
+		if (rn->rn_start > start)
+			return -ESRCH;
+
+		/* If it covers the entire range we're done. */
+		if (rn->rn_last >= last)
+			return 0;
+
+		start = rn->rn_last + 1;
+	}
+
+	/* No range to cover [start, last] */
 	return -ESRCH;
 }
 
-/* Set the range in this range tree */
-int range_tree_set(struct range_tree *rt, u32 start, u32 len)
+/* Do we have adjacent ranges (and do not overlap with them)? */
+static int range_get_adjacent(struct range_tree *rt, u32 start, u32 last,
+		struct range_node **leftp, struct range_node **rightp)
 {
-	u32 last = start + len - 1;
-	struct range_node *new_rn = NULL;
 	struct range_node *right;
 	struct range_node *left;
-	int err;
 
-	/* Is this whole range already set ? */
-	left = range_it_iter_first(rt, start, last);
-	if (left && left->rn_start <= start && left->rn_last >= last)
-		return 0;
+	/* Do we have a left-adjacent range ? */
+	left = start ? range_it_iter_first(rt, start - 1, start - 1) : NULL;
+	if (left && left->rn_last != start - 1)
+		return -EFAULT;
 
-	left = range_it_iter_first(rt, start - 1, start - 1);
-	right = range_it_iter_first(rt, last + 1, last + 1);
-	if (!left && !right) {
-		new_rn = kmalloc_nolock(sizeof(struct range_node),
-					__GFP_ACCOUNT, NUMA_NO_NODE);
-		if (!new_rn)
-			return -ENOMEM;
-	}
+	/* Do we have a right-adjacent range ? */
+	right = last != U32_MAX ? range_it_iter_first(rt, last + 1, last + 1) : NULL;
+	if (right && right->rn_start != last + 1)
+		return -EFAULT;
 
-	/* Clear out everything in the range we want to set. */
-	err = range_tree_clear(rt, start, len);
-	if (err)
-		goto out_free_new;
+	*leftp = left;
+	*rightp = right;
+
+	return 0;
+}
 
-	if (left && right) {
+/*
+ * Merge with adjacent available ranges if possible. The new [start, last]
+ * has already been confirmed to be adjacent with left/right by the caller.
+ */
+static int range_tree_merge(struct range_tree *rt, u32 start, u32 last,
+		struct range_node *left, struct range_node *right)
+{
+	if (range_available(left) && range_available(right)) {
 		/* Combine left and right adjacent ranges */
 		range_it_remove(left, rt);
 		range_it_remove(right, rt);
 		left->rn_last = right->rn_last;
 		range_it_insert(left, rt);
 		kfree_nolock(right);
-	} else if (left) {
+	} else if (range_available(left)) {
 		/* Combine with the left range */
 		range_it_remove(left, rt);
 		left->rn_last = last;
 		range_it_insert(left, rt);
-	} else if (right) {
+	} else if (range_available(right)) {
 		/* Combine with the right range */
 		range_it_remove(right, rt);
 		right->rn_start = start;
 		range_it_insert(right, rt);
 	} else {
-		/* No adjacent ranges; use the pre-allocated node */
-		new_rn->rn_start = start;
-		new_rn->rn_last = last;
-		range_it_insert(new_rn, rt);
+		/* No merge available. */
+		return -ENOENT;
 	}
+
+	return 0;
+}
+
+/* Make a range available, possibly merging. */
+int range_tree_make_avail(struct range_tree *rt, u32 start, u32 len)
+{
+	u32 last = start + len - 1;
+	struct range_node *rn;
+	struct range_node *right;
+	struct range_node *left;
+	int err;
+
+	/*
+	 * Confirm the range exists is unavailable,
+	 * and fits the requested range exactly.
+	 */
+	rn = range_it_iter_first(rt, start, last);
+	if (!rn || rn->available)
+		return -EINVAL;
+
+	if (rn->rn_start != start || rn->rn_last != last)
+		return -EINVAL;
+
+	err = range_get_adjacent(rt, start, last, &left, &right);
+	if (err)
+		return err;
+
+	/* If no merging required, just make available. */
+	if (!range_available(left) && !range_available(right)) {
+		rn->available = true;
+		return 0;
+	}
+
+	/* Can merge, remove the range already. */
+	start = rn->rn_start;
+	last = rn->rn_last;
+	range_it_remove(rn, rt);
+	kfree_nolock(rn);
+
+	return range_tree_merge(rt, start, last, left, right);
+}
+
+/* Set the range in this range tree */
+static int range_tree_set(struct range_tree *rt, u32 start, u32 len,
+			  bool available, struct range_node **new_rnp)
+{
+	u32 last = start + len - 1;
+	struct range_node *new_rn = NULL;
+	struct range_node *right;
+	struct range_node *left;
+	int err;
+
+	/* Already available: nothing to change. */
+	left = range_it_iter_first(rt, start, last);
+	if (available && range_available(left) &&
+	    left->rn_start <= start && left->rn_last >= last)
+		return 0;
+
+	/* Predict whether insertion needs a new node before clearing. */
+	left = start ? range_it_iter_first(rt, start - 1, start - 1) : NULL;
+	right = last != U32_MAX ? range_it_iter_first(rt, last + 1, last + 1) : NULL;
+
+	/* Unavailable ranges cannot merge. Allocate before changing the tree. */
+	if (!available ||
+	    (!range_available(left) && !range_available(right))) {
+		new_rn = kmalloc_nolock(sizeof(*new_rn), __GFP_ACCOUNT,
+					NUMA_NO_NODE);
+		if (!new_rn)
+			return -ENOMEM;
+	}
+
+	/* Clear out everything in the range we want to set. */
+	err = range_tree_clear(rt, start, len);
+	if (err)
+		goto out_free_new;
+
+	/* Recompute adjacency: clearing may have trimmed or split nodes. */
+	err = range_get_adjacent(rt, start, last, &left, &right);
+	if (err)
+		goto out_free_new;
+
+	if (available &&
+	    (range_available(left) || range_available(right))) {
+		err = range_tree_merge(rt, start, last, left, right);
+		goto out_free_new;
+	}
+
+	/* No merge possible; transfer the reserved node to the tree. */
+	new_rn->available = available;
+	new_rn->rn_start = start;
+	new_rn->rn_last = last;
+	range_it_insert(new_rn, rt);
+	if (new_rnp)
+		*new_rnp = new_rn;
+
 	return 0;
 
 out_free_new:
@@ -253,6 +401,24 @@ int range_tree_set(struct range_tree *rt, u32 start, u32 len)
 	return err;
 }
 
+int range_tree_set_avail(struct range_tree *rt, u32 start, u32 len)
+{
+	return range_tree_set(rt, start, len, true, NULL);
+}
+
+struct range_node *range_tree_set_unavail(struct range_tree *rt, u32 start, u32 len)
+{
+	struct range_node *rn = NULL;
+	int err;
+
+	err = range_tree_set(rt, start, len, false, &rn);
+	if (err)
+		return ERR_PTR(err);
+	if (WARN_ON_ONCE(!rn))
+		return ERR_PTR(-EINVAL);
+	return rn;
+}
+
 void range_tree_destroy(struct range_tree *rt)
 {
 	struct range_node *rn;
diff --git a/kernel/bpf/range_tree.h b/kernel/bpf/range_tree.h
index ff0b9110eb715..4f9ea2acea290 100644
--- a/kernel/bpf/range_tree.h
+++ b/kernel/bpf/range_tree.h
@@ -10,11 +10,16 @@ struct range_tree {
 	struct rb_root_cached range_size_root;
 };
 
+struct range_node;
+
 void range_tree_init(struct range_tree *rt);
 void range_tree_destroy(struct range_tree *rt);
 
 int range_tree_clear(struct range_tree *rt, u32 start, u32 len);
-int range_tree_set(struct range_tree *rt, u32 start, u32 len);
+int range_tree_set_avail(struct range_tree *rt, u32 start, u32 len);
+struct range_node *range_tree_set_unavail(struct range_tree *rt, u32 start, u32 len);
+void range_node_mark_available(struct range_node *rn);
+int range_tree_make_avail(struct range_tree *rt, u32 start, u32 len);
 int is_range_tree_set(struct range_tree *rt, u32 start, u32 len);
 s64 range_tree_find(struct range_tree *rt, u32 len);
 
diff --git a/kernel/bpf/syscall.c b/kernel/bpf/syscall.c
index 654f896af265b..1a1cc305dabb9 100644
--- a/kernel/bpf/syscall.c
+++ b/kernel/bpf/syscall.c
@@ -1209,6 +1209,8 @@ int bpf_map_new_fd(struct bpf_map *map, int flags)
 	if (ret < 0)
 		return ret;
 
+	if (map->ops->map_get_file)
+		return FD_ADD(flags | O_CLOEXEC, map->ops->map_get_file(map, flags));
 	return anon_inode_getfd("bpf-map", &bpf_map_fops, map,
 				flags | O_CLOEXEC);
 }
diff --git a/tools/testing/selftests/bpf/prog_tests/arena_race.c b/tools/testing/selftests/bpf/prog_tests/arena_race.c
new file mode 100644
index 0000000000000..301f4dff28f99
--- /dev/null
+++ b/tools/testing/selftests/bpf/prog_tests/arena_race.c
@@ -0,0 +1,285 @@
+// SPDX-License-Identifier: GPL-2.0
+
+#define _GNU_SOURCE
+#include <sched.h>
+#include <sys/syscall.h>
+#include <test_progs.h>
+
+#include "arena_race.skel.h"
+
+struct free_thread_ctx {
+	struct arena_race *skel;
+	int err;
+	__u32 retval;
+};
+
+struct fault_thread_ctx {
+	__u64 *addr;
+	int stop;
+};
+
+static int run_prog(struct bpf_program *prog, const char *name)
+{
+	LIBBPF_OPTS(bpf_test_run_opts, opts);
+	int err;
+
+	err = bpf_prog_test_run_opts(bpf_program__fd(prog), &opts);
+	return ASSERT_OK(err, name) && ASSERT_OK(opts.retval, name) ? 0 : -1;
+}
+
+/* Trigger the sleepable free page path. */
+static void *run_free_thread(void *arg)
+{
+	LIBBPF_OPTS(bpf_test_run_opts, opts);
+	struct free_thread_ctx *ctx = arg;
+
+	ctx->skel->bss->target_tid = sys_gettid();
+	ctx->err = bpf_prog_test_run_opts(
+		bpf_program__fd(ctx->skel->progs.free_page), &opts);
+	ctx->retval = opts.retval;
+	return NULL;
+}
+
+/* Continuously fault in the address. */
+static void *fault_reader_thread(void *arg)
+{
+	struct fault_thread_ctx *ctx = arg;
+	__u64 *addr;
+
+	while (!READ_ONCE(ctx->stop)) {
+		addr = __atomic_load_n(&ctx->addr, __ATOMIC_ACQUIRE);
+		(void)READ_ONCE(*addr);
+	}
+	return NULL;
+}
+
+static int wait_for(int *p)
+{
+	__u64 deadline = get_time_ns() + 5ULL * 1000 * 1000 * 1000;
+
+	while (!READ_ONCE(*p)) {
+		if (get_time_ns() > deadline)
+			return -ETIMEDOUT;
+	}
+	return 0;
+}
+
+static struct arena_race *setup_arena(__u64 **addr, bool trace_flush)
+{
+	struct arena_race *skel;
+	size_t arena_sz;
+	char *base;
+	int err;
+
+	skel = arena_race__open();
+	if (!ASSERT_OK_PTR(skel, "open"))
+		return NULL;
+	err = bpf_program__set_autoload(skel->progs.trace_flush, trace_flush);
+	if (!ASSERT_OK(err, "trace_flush_autoload"))
+		goto err_out;
+
+	err = arena_race__load(skel);
+	if (!ASSERT_OK(err, "load"))
+		goto err_out;
+	err = arena_race__attach(skel);
+	if (!ASSERT_OK(err, "attach"))
+		goto err_out;
+
+	if (run_prog(skel->progs.alloc_old, "alloc_old"))
+		goto err_out;
+	if (skel->bss->skip) {
+		test__skip();
+		goto err_out;
+	}
+
+	base = bpf_map__initial_value(skel->maps.arena, &arena_sz);
+	if (!ASSERT_OK_PTR(base, "arena_base"))
+		goto err_out;
+	*addr = (__u64 *)(base + getpagesize());
+	if (!ASSERT_EQ((unsigned long)skel->bss->ptr, (unsigned long)*addr,
+		       "arena_ptr"))
+		goto err_out;
+	return skel;
+
+err_out:
+	arena_race__destroy(skel);
+	return NULL;
+}
+
+static void test_free_before_flush(bool deferred)
+{
+	struct free_thread_ctx ctx = {};
+	struct arena_race *skel;
+	pthread_t thread;
+	__u64 *addr;
+	bool thread_created = false, flush_seen = false, completed = false;
+	int err;
+
+	if (libbpf_find_vmlinux_btf_id("flush_tlb_kernel_range",
+					BPF_TRACE_FENTRY) <= 0) {
+		printf("%s:SKIP: flush_tlb_kernel_range is not an fentry target\n",
+		       __func__);
+		test__skip();
+		return;
+	}
+
+	skel = setup_arena(&addr, true);
+	if (!skel)
+		return;
+
+	/* Pause during a TLB flush to widen the race window. */
+	skel->bss->pause_on_flush = 1;
+
+	if (deferred) {
+		/*
+		 * Test the nonsleepable free path that gets
+		 * deferred to a worker in the kernel. We do
+		 * so by triggering the arena operation from
+		 * a nonsleepable tracepoint context.
+		 */
+		skel->bss->trigger_pid_tgid =
+			((__u64)getpid() << 32) | (__u32)sys_gettid();
+		skel->bss->trigger_syscall = SYS_getpgid;
+		skel->bss->deferred_free = 1;
+		if (!ASSERT_GE(syscall(SYS_getpgid, 0), 0, "deferred_free"))
+			goto release;
+	} else {
+		/*
+		 * Test the sleepable arena free path through a
+		 * syscall test prog.
+		 */
+		ctx.skel = skel;
+		err = pthread_create(&thread, NULL, run_free_thread, &ctx);
+		if (!ASSERT_OK(err, "pthread_create")) {
+			skel->bss->release = 1;
+			goto out;
+		}
+		thread_created = true;
+	}
+
+	/* Wait until the worker thread triggers a flush. */
+	err = wait_for(&skel->bss->flush_entered);
+	if (!ASSERT_OK(err, "flush_entered"))
+		goto release;
+
+	flush_seen = true;
+
+	/* Force a reallocation during the flush. */
+	run_prog(skel->progs.try_realloc, "realloc_before_flush");
+	ASSERT_NULL(skel->bss->realloc_ptr, "realloc_before_flush");
+
+release:
+	skel->bss->release = 1;
+	if (thread_created) {
+		ASSERT_OK(pthread_join(thread, NULL), "pthread_join");
+		thread_created = false;
+		completed = ASSERT_OK(ctx.err, "free_run") &&
+			    ASSERT_OK(ctx.retval, "free_retval");
+	} else if (skel->bss->target_tid) {
+		err = wait_for(&skel->bss->worker_exited);
+		completed = ASSERT_OK(err, "worker_exited");
+	}
+	ASSERT_FALSE(skel->bss->timed_out, "flush_timed_out");
+
+	if (flush_seen && completed &&
+	    !run_prog(skel->progs.try_realloc, "realloc_after_flush")) {
+		ASSERT_EQ((unsigned long)skel->bss->realloc_ptr,
+			  (unsigned long)addr, "realloc_after_flush");
+		ASSERT_EQ(*addr, skel->rodata->new_marker, "new_marker");
+	}
+out:
+	arena_race__destroy(skel);
+}
+
+/*
+ * Force a race between a faulting thread in userspace and a
+ * free operation on the arena.
+ */
+static void test_fault_free_realloc(void)
+{
+	struct fault_thread_ctx fault = {};
+	struct arena_race *skel;
+	pthread_t fault_thread;
+	bool fault_created = false;
+	__u64 *addr;
+	__u64 expected, value;
+	int err, i;
+
+	skel = setup_arena(&addr, false);
+	if (!skel)
+		return;
+
+	skel->bss->realloc_after_free = 1;
+
+	fault.addr = addr;
+	err = pthread_create(&fault_thread, NULL, fault_reader_thread, &fault);
+	if (!ASSERT_OK(err, "pthread_create_fault"))
+		goto out;
+	fault_created = true;
+
+	for (i = 0; i < 1000; i++) {
+		LIBBPF_OPTS(bpf_test_run_opts, opts);
+
+		/* Keep deferred frees from earlier iterations on separate slots. */
+		if (i) {
+			skel->bss->page_idx = i;
+			if (run_prog(skel->progs.alloc_old, "alloc_next"))
+				goto out;
+			addr = (__u64 *)(unsigned long)skel->bss->ptr;
+			__atomic_store_n(&fault.addr, addr, __ATOMIC_RELEASE);
+		}
+
+		err = bpf_prog_test_run_opts(bpf_program__fd(skel->progs.free_page),
+					     &opts);
+		if (err) {
+			ASSERT_OK(err, "free_realloc");
+			break;
+		}
+		if (opts.retval) {
+			ASSERT_OK(opts.retval, "free_realloc");
+			break;
+		}
+		/* The reader may populate the slot first, or free may defer. */
+		if (!skel->bss->realloc_ptr)
+			continue;
+		value = *addr;
+		expected = skel->bss->current_marker;
+		if (value != expected) {
+			ASSERT_EQ(value, expected, "marker_after_realloc");
+			break;
+		}
+	}
+
+	WRITE_ONCE(fault.stop, 1);
+	if (fault_created) {
+		ASSERT_OK(pthread_join(fault_thread, NULL), "pthread_join_fault");
+		fault_created = false;
+	}
+out:
+	WRITE_ONCE(fault.stop, 1);
+	if (fault_created)
+		pthread_join(fault_thread, NULL);
+	arena_race__destroy(skel);
+}
+
+void serial_test_arena_race(void)
+{
+	cpu_set_t cpuset;
+	int err;
+
+	err = sched_getaffinity(0, sizeof(cpuset), &cpuset);
+	if (!ASSERT_OK(err, "sched_getaffinity"))
+		return;
+	if (CPU_COUNT(&cpuset) < 2) {
+		printf("%s:SKIP: at least two runnable CPUs are required\n", __func__);
+		test__skip();
+		return;
+	}
+
+	if (test__start_subtest("free_before_flush"))
+		test_free_before_flush(false);
+	if (test__start_subtest("deferred_free_before_flush"))
+		test_free_before_flush(true);
+	if (test__start_subtest("fault_free_realloc"))
+		test_fault_free_realloc();
+}
diff --git a/tools/testing/selftests/bpf/progs/arena_race.c b/tools/testing/selftests/bpf/progs/arena_race.c
new file mode 100644
index 0000000000000..6d1675ba23957
--- /dev/null
+++ b/tools/testing/selftests/bpf/progs/arena_race.c
@@ -0,0 +1,159 @@
+// SPDX-License-Identifier: GPL-2.0
+
+#define BPF_NO_KFUNC_PROTOTYPES
+#include <vmlinux.h>
+#include <bpf/bpf_helpers.h>
+#include <bpf/bpf_tracing.h>
+#include "bpf_experimental.h"
+#include <bpf_arena_common.h>
+
+const volatile __u64 old_marker = 0x1111222233334444ULL;
+const volatile __u64 new_marker = 0x5555666677778888ULL;
+
+struct {
+	__uint(type, BPF_MAP_TYPE_ARENA);
+	__uint(map_flags, BPF_F_MMAPABLE);
+	__uint(max_entries, 1024);
+#ifdef __TARGET_ARCH_arm64
+	__ulong(map_extra, 0x1ull << 32);
+#else
+	__ulong(map_extra, 0x1ull << 44);
+#endif
+} arena SEC(".maps");
+
+bool skip;
+int page_idx;
+
+void __arena *ptr;
+void __arena *realloc_ptr;
+bool realloc_after_free;
+__u64 current_marker;
+__u64 marker_seq;
+
+int target_tid;
+int pause_on_flush;
+int flush_entered;
+int release;
+int timed_out;
+
+__u64 trigger_pid_tgid;
+long trigger_syscall;
+int deferred_free;
+int worker_armed;
+int worker_exited;
+
+static __always_inline void wait_for_release(void)
+{
+	while (!*(volatile int *)&release && can_loop)
+		;
+	if (!*(volatile int *)&release)
+		timed_out = 1;
+}
+
+SEC("syscall")
+int alloc_old(void *ctx)
+{
+#if defined(__BPF_FEATURE_ADDR_SPACE_CAST) || defined(BPF_ARENA_FORCE_ASM)
+	__u64 __arena *p;
+	char __arena *base = arena_base(&arena);
+
+	realloc_ptr = NULL;
+	ptr = bpf_arena_alloc_pages(&arena, base + (page_idx + 1) * __PAGE_SIZE, 1,
+				    NUMA_NO_NODE, 0);
+	if (!ptr)
+		return 1;
+	p = (__u64 __arena *)ptr;
+	*p = old_marker;
+	current_marker = old_marker;
+#else
+	skip = true;
+#endif
+	return 0;
+}
+
+SEC("syscall")
+int free_page(void *ctx)
+{
+#if defined(__BPF_FEATURE_ADDR_SPACE_CAST) || defined(BPF_ARENA_FORCE_ASM)
+	__u64 __arena *p;
+	__u64 marker;
+
+	if (!ptr)
+		return 1;
+	bpf_arena_free_pages(&arena, ptr, 1);
+	if (!realloc_after_free)
+		return 0;
+
+	marker = new_marker + ++marker_seq;
+	realloc_ptr = bpf_arena_alloc_pages(&arena, ptr, 1, NUMA_NO_NODE, 0);
+	if (!realloc_ptr)
+		return 0;
+	ptr = realloc_ptr;
+	p = (__u64 __arena *)ptr;
+	*p = marker;
+	current_marker = marker;
+#endif
+	return 0;
+}
+
+SEC("syscall")
+int try_realloc(void *ctx)
+{
+#if defined(__BPF_FEATURE_ADDR_SPACE_CAST) || defined(BPF_ARENA_FORCE_ASM)
+	__u64 __arena *p;
+
+	realloc_ptr = bpf_arena_alloc_pages(&arena, ptr, 1, NUMA_NO_NODE, 0);
+	if (realloc_ptr) {
+		ptr = realloc_ptr;
+		p = (__u64 __arena *)realloc_ptr;
+		*p = new_marker;
+		current_marker = new_marker;
+	}
+#endif
+	return 0;
+}
+
+SEC("tp_btf/sys_enter")
+int BPF_PROG(deferred_free_prog, struct pt_regs *regs, long id)
+{
+#if defined(__BPF_FEATURE_ADDR_SPACE_CAST) || defined(BPF_ARENA_FORCE_ASM)
+	if (!deferred_free || bpf_get_current_pid_tgid() != trigger_pid_tgid ||
+	    id != trigger_syscall)
+		return 0;
+
+	deferred_free = 0;
+	/* The worker can run on another CPU before the kfunc returns. */
+	worker_armed = 1;
+	bpf_arena_free_pages(&arena, ptr, 1);
+#endif
+	return 0;
+}
+
+SEC("fentry/arena_free_worker")
+int BPF_PROG(trace_free_worker, struct work_struct *work)
+{
+	if (worker_armed && !target_tid)
+		target_tid = (__u32)bpf_get_current_pid_tgid();
+	return 0;
+}
+
+SEC("fexit/arena_free_worker")
+int BPF_PROG(trace_free_worker_ret, struct work_struct *work)
+{
+	if ((__u32)bpf_get_current_pid_tgid() == target_tid)
+		worker_exited = 1;
+	return 0;
+}
+
+SEC("?fentry/flush_tlb_kernel_range")
+int BPF_PROG(trace_flush, unsigned long start, unsigned long end)
+{
+	if (!pause_on_flush ||
+	    (__u32)bpf_get_current_pid_tgid() != target_tid)
+		return 0;
+	flush_entered = 1;
+	wait_for_release();
+	return 0;
+}
+
+char _license[] SEC("license") = "GPL";

3/2 2026/10/15 03:44 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 22166
							output: 31
							thoughts: 403
						

Thoughts:
**Analyzing the Patch for Fuzzing Potential**

Okay, let's dive into this. The request is straightforward: assess this patch series and determine if it's a good candidate for syzkaller fuzzing. Right, let's get to the code.

Looking at the patch, the file touches are interesting. I see changes across several areas: `include/linux/bpf.h` with the addition of `map_get_file`, which could be significant. Then, the real meat is in `kernel/bpf/arena.c`. We're talking substantial modifications to arena memory management: synchronization primitives, range tree operations, backing file/anonymous inode handling, the mapping lock, and those key page fault handler (`arena_vm_fault`) and page freeing functions (`arena_free_pages`, `arena_free_worker`). This screams memory management, which is always a prime target for fuzzing. `kernel/bpf/range_tree.c` and `.h` also jump out, as range trees are often complex and error-prone. And finally, `kernel/bpf/syscall.c` calls `map_get_file`. There are also self-tests in `tools/testing/selftests/bpf/...`.

So, it's pretty clear this is squarely within the Linux kernel's BPF subsystem. This involves kernel-core code, dealing with the relatively new BPF arena feature and how it interacts with the syscall interface. The fact that the code impacts functionality reachable via syscalls - arena maps, `mmap` calls, page faults, and free operations via kfuncs or prog execution – is a big red flag.

Hold on. Before I get too excited, let's make sure this is even *fuzzable* in standard environments. Is it accessible in QEMU, GCE, and on amd64 architectures? Checking the location, `kernel/bpf/arena.c`, it definitely looks like it is. Now I need to quickly check those Kconfig options to be sure BPF arena is properly enabled. Okay, let's see what's what...



4/2 2026/10/15 03:44 tool grepper
0m Error:
no matches

Args:
{
  "Expression": "BPF_ARENA",
  "PathPrefixes": [
    "kernel/bpf/"
  ]
}

Results:
{
  "error": "no matches"
}

5/2 2026/10/15 03:44 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 23062
							output: 29
							thoughts: 21
						

Thoughts:
Okay, let's dive into this. Here's my thought process on dissecting how `arena.c` is compiled within the `kernel/bpf/Makefile`:

**Deconstructing the `arena.c` Compilation in the BPF Kernel**

Alright, my immediate thought is to trace the compilation process of `arena.c` within the BPF kernel's build system. I need to figure out how the build system handles this specific file. Let's see how they handle it, what flags are passed, any special considerations for BPF context... Is it linked in as part of a larger object, or treated as an individual component? And of course, I'm thinking about optimization flags, debug symbols, and potential inclusion paths. I expect they are leveraging the `Makefile` structure for optimal BPF code generation. I'm looking for anything unusual or custom beyond the typical kernel compilation procedures. I need to understand if there are any specific BPF-related compiler flags being leveraged, or if it is integrated into the larger build process.



6/2 2026/10/15 03:45 tool grepper
0m Args:
{
  "Expression": "arena\\.o",
  "PathPrefixes": [
    "kernel/bpf/"
  ]
}

Results:
{
  "Output": "kernel/bpf/Makefile=19=ifeq ($(CONFIG_MMU)$(CONFIG_64BIT),yy)\nkernel/bpf/Makefile:20:obj-$(CONFIG_BPF_SYSCALL) += arena.o range_tree.o\nkernel/bpf/Makefile-21-endif\n"
}

7/2 2026/10/15 03:45 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 23414
							output: 35
							thoughts: 172
						

Thoughts:
**BPF Kernel Configuration for Fuzzing**

Okay, here's what's running through my mind. I see this `kernel/bpf/Makefile` snippet:

```makefile
ifeq ($(CONFIG_MMU)$(CONFIG_64BIT),yy)
obj-$(CONFIG_BPF_SYSCALL) += arena.o range_tree.o
endif
```

Right away, I recognize that this points to the importance of `CONFIG_BPF_SYSCALL`. Since my focus is on fuzzing, I'm thinking, "Is `CONFIG_BPF_SYSCALL` standard in syzkaller fuzzing?" Yes, absolutely. It's a huge target for vulnerability research. And, given that this Makefile checks for both `CONFIG_MMU` and `CONFIG_64BIT`, I know this applies to amd64, which is a key architecture, as that is 64-bit and uses an MMU. Makes sense.

I need to understand the connection to the `arena` BPF map type. So, my next step is to dig into the kernel source, specifically `kernel/bpf/arena.c` or any other relevant files, to see how `BPF_MAP_TYPE_ARENA` is implemented and used.



8/2 2026/10/15 03:45 tool grepper
0m Args:
{
  "Expression": "BPF_MAP_TYPE_ARENA",
  "PathPrefixes": [
    "kernel/bpf/"
  ]
}

Results:
{
  "Output": "kernel/bpf/arena.c=130=u64 bpf_arena_get_user_vm_start(struct bpf_arena *arena)\n--\nkernel/bpf/arena.c-136- * bpf_arena_map_kern_vm_start - kern_vm_start lookup by struct bpf_map *\nkernel/bpf/arena.c:137: * @map: a BPF_MAP_TYPE_ARENA map\nkernel/bpf/arena.c-138- *\n--\nkernel/bpf/arena.c=1358=__bpf_kfunc void *bpf_arena_alloc_pages(void *p__map, void *addr__ign, u32 page_cnt,\n--\nkernel/bpf/arena.c-1363-\nkernel/bpf/arena.c:1364:\tif (map-\u003emap_type != BPF_MAP_TYPE_ARENA || flags || !page_cnt)\nkernel/bpf/arena.c-1365-\t\treturn NULL;\n--\nkernel/bpf/arena.c=1370=void *bpf_arena_alloc_pages_non_sleepable(void *p__map, void *addr__ign, u32 page_cnt,\n--\nkernel/bpf/arena.c-1375-\nkernel/bpf/arena.c:1376:\tif (map-\u003emap_type != BPF_MAP_TYPE_ARENA || flags || !page_cnt)\nkernel/bpf/arena.c-1377-\t\treturn NULL;\n--\nkernel/bpf/arena.c=1382=void *bpf_arena_alloc_pages_sleepable(void *p__map, void *addr__ign, u32 page_cnt,\n--\nkernel/bpf/arena.c-1387-\nkernel/bpf/arena.c:1388:\tif (map-\u003emap_type != BPF_MAP_TYPE_ARENA || flags || !page_cnt)\nkernel/bpf/arena.c-1389-\t\treturn NULL;\n--\nkernel/bpf/arena.c=1394=__bpf_kfunc void bpf_arena_free_pages(void *p__map, void *ptr__ign, u32 page_cnt)\n--\nkernel/bpf/arena.c-1398-\nkernel/bpf/arena.c:1399:\tif (map-\u003emap_type != BPF_MAP_TYPE_ARENA || !page_cnt || !ptr__ign)\nkernel/bpf/arena.c-1400-\t\treturn;\n--\nkernel/bpf/arena.c=1404=void bpf_arena_free_pages_non_sleepable(void *p__map, void *ptr__ign, u32 page_cnt)\n--\nkernel/bpf/arena.c-1408-\nkernel/bpf/arena.c:1409:\tif (map-\u003emap_type != BPF_MAP_TYPE_ARENA || !page_cnt || !ptr__ign)\nkernel/bpf/arena.c-1410-\t\treturn;\n--\nkernel/bpf/arena.c=1414=__bpf_kfunc int bpf_arena_reserve_pages(void *p__map, void *ptr__ign, u32 page_cnt)\n--\nkernel/bpf/arena.c-1418-\nkernel/bpf/arena.c:1419:\tif (map-\u003emap_type != BPF_MAP_TYPE_ARENA)\nkernel/bpf/arena.c-1420-\t\treturn -EINVAL;\n--\nkernel/bpf/syscall.c=250=static int bpf_map_update_value(struct bpf_map *map, struct file *map_file,\n--\nkernel/bpf/syscall.c-258-\t} else if (map-\u003emap_type == BPF_MAP_TYPE_CPUMAP ||\nkernel/bpf/syscall.c:259:\t\t   map-\u003emap_type == BPF_MAP_TYPE_ARENA ||\nkernel/bpf/syscall.c-260-\t\t   map-\u003emap_type == BPF_MAP_TYPE_STRUCT_OPS) {\n--\nkernel/bpf/syscall.c=1403=static int map_create_alloc(union bpf_attr *attr, bpfptr_t uattr, struct bpf_verifier_log *log,\n--\nkernel/bpf/syscall.c-1440-\tif (attr-\u003emap_type != BPF_MAP_TYPE_BLOOM_FILTER \u0026\u0026\nkernel/bpf/syscall.c:1441:\t    attr-\u003emap_type != BPF_MAP_TYPE_ARENA \u0026\u0026\nkernel/bpf/syscall.c-1442-\t    attr-\u003emap_type != BPF_MAP_TYPE_RHASH \u0026\u0026\n--\nkernel/bpf/syscall.c-1536-\tcase BPF_MAP_TYPE_CPUMAP:\nkernel/bpf/syscall.c:1537:\tcase BPF_MAP_TYPE_ARENA:\nkernel/bpf/syscall.c-1538-\tcase BPF_MAP_TYPE_INSN_ARRAY:\n--\nkernel/bpf/verifier.c=18731=static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)\n--\nkernel/bpf/verifier.c-18815-\t    insn-\u003esrc_reg == BPF_PSEUDO_MAP_IDX_VALUE) {\nkernel/bpf/verifier.c:18816:\t\tif (map-\u003emap_type == BPF_MAP_TYPE_ARENA) {\nkernel/bpf/verifier.c-18817-\t\t\t__mark_reg_unknown(env, dst_reg);\n--\nkernel/bpf/verifier.c=20586=static int check_map_prog_compatibility(struct bpf_verifier_env *env,\n--\nkernel/bpf/verifier.c-20651-\t\tcase BPF_MAP_TYPE_STACK:\nkernel/bpf/verifier.c:20652:\t\tcase BPF_MAP_TYPE_ARENA:\nkernel/bpf/verifier.c-20653-\t\tcase BPF_MAP_TYPE_INSN_ARRAY:\n--\nkernel/bpf/verifier.c-20667-\nkernel/bpf/verifier.c:20668:\tif (map-\u003emap_type == BPF_MAP_TYPE_ARENA) {\nkernel/bpf/verifier.c-20669-\t\tif (env-\u003eprog-\u003eaux-\u003earena) {\n"
}

9/2 2026/10/15 03:45 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 25552
							output: 34
							thoughts: 941
						

Thoughts:
**Deep Dive into BPF Arena Memory Management Patch**

Okay, let's break this down. This patch is a substantial modification to BPF arena memory management. It's touching some really core pieces: BPF maps, memory management, and synchronization. The implications of these changes are substantial.

Firstly, the introduction of `map_get_file` within `struct bpf_map_ops` and its implementation, `arena_map_get_file`, are key. By associating the arena map with a file (specifically, a clone of `arena->file`), we're hooking it directly into the file system infrastructure, which is a departure from the generic anon inode approach. This means the arena's pages are now tied to `arena->file->f_mapping` with `arena_aops` which creates a much more direct interaction with the MM.

Secondly, setting `page_folio(page)->index` and linking `page->mapping` to the arena's file mapping during page setup is quite significant. This tightens the coupling between pages and the file's mapping, indicating a reliance on the file system's capabilities for memory management within the BPF arena.

The introduction of `arena_put_page()` hints at a change in how pages are released. The locking, nulling the mapping, and subsequent freeing with `__free_page` needs careful examination. It’s critical to understand the synchronization here.

The rework of synchronization within `arena_vm_fault()` is where things get interesting. The use of `arena->opref` for tracking concurrent operations (freeing versus faulting), `opwait`, and `folio_lock_or_retry()` suggests a shift towards more robust concurrency handling. Replacing the old generation-based `zap_pages()` with `i_mmap_lock_read` and `mapping_rmap_tree_foreach()` using the rmap is a notable change and probably much more robust in terms of dealing with MM operations. Understanding the implications of handling `VM_FAULT_LOCKED`, `VM_FAULT_NOPAGE`, and `VM_FAULT_RETRY` is essential.

In `arena_free_pages()` and `arena_free_worker()`, the coordination with `wait_for_faults(&free_pages)` and the introduction of unavailable ranges in the range tree represent a complex state management scheme. The new state machine for spans, using `flags` such as `ARENA_FREE_SPAN_CLEARED`, `ARENA_FREE_SPAN_ZAPPED`, etc., points to intricate concurrency and error handling strategies. Requeuing, error handling, and `disable_work_sync` all add to the complexity. This is all about getting those pages unmapped and free.

Finally, the added `WARN_ON_ONCE` statements, specifically in `arena_free_pages`, `arena_free_worker`, and `range_tree_set_unavail`, act as important assertions. They highlight potential error conditions that the developers found important to track, and need further investigation.

Overall, the patch deeply intertwines with core mm-interaction, locking, and synchronization. It's a complex dance between memory management, BPF maps, folio locking, page faults, and workqueues. The concurrency between `mmap`, page faults, and page frees (both sleepable and deferred) is a key area to scrutinize. The new primitives introduced, like `opref`, `opwait`, the range tree unavailable states, and folio locking are prime targets for in-depth analysis. Given the BPF's user-space accessibility via `bpf(BPF_MAP_CREATE, ...)` and `mmap()` (which trigger page faults) and BPF programs freeing pages, this looks like a prime candidate for thorough fuzzing and testing. We need to check the Kconfig as well, specifically the `CONFIG_MMU` and `CONFIG_64BIT` requirements.



10/2 2026/10/15 03:45 tool grepper
0m Args:
{
  "Expression": "BPF_SYSCALL",
  "PathPrefixes": [
    "kernel/bpf/Kconfig"
  ]
}

Results:
{
  "Output": "kernel/bpf/Kconfig=29=menu \"BPF subsystem\"\nkernel/bpf/Kconfig-30-\nkernel/bpf/Kconfig:31:config BPF_SYSCALL\nkernel/bpf/Kconfig-32-\tbool \"Enable bpf() system call\"\n--\nkernel/bpf/Kconfig=62=config BPF_JIT_ALWAYS_ON\nkernel/bpf/Kconfig-63-\tbool \"Permanently enable BPF JIT and remove BPF interpreter\"\nkernel/bpf/Kconfig:64:\tdepends on BPF_SYSCALL \u0026\u0026 HAVE_EBPF_JIT \u0026\u0026 BPF_JIT\nkernel/bpf/Kconfig-65-\thelp\n--\nkernel/bpf/Kconfig=77=config BPF_UNPRIV_DEFAULT_OFF\n--\nkernel/bpf/Kconfig-79-\tdefault y\nkernel/bpf/Kconfig:80:\tdepends on BPF_SYSCALL\nkernel/bpf/Kconfig-81-\thelp\n--\nkernel/bpf/Kconfig=94=config BPF_CRYPTO\nkernel/bpf/Kconfig-95-\tdef_bool y\nkernel/bpf/Kconfig:96:\tdepends on BPF_SYSCALL\nkernel/bpf/Kconfig-97-\tselect CRYPTO_LIB_AES_CBC\n--\nkernel/bpf/Kconfig=105=config BPF_LSM\n--\nkernel/bpf/Kconfig-107-\tdepends on BPF_EVENTS\nkernel/bpf/Kconfig:108:\tdepends on BPF_SYSCALL\nkernel/bpf/Kconfig-109-\tdepends on SECURITY\n"
}

11/2 2026/10/15 03:45 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 27781
							output: 27
							thoughts: 41
						

Thoughts:
Okay, let's break this down.

**Investigating Dependencies and Configuration Requirements**

Alright, before I dive too deep into this particular module, I want to confirm something crucial for its integration: Does the `arena` or `range_tree` module have any hidden dependencies or specific configuration flags that need to be enabled before I can properly work with it? It's easy to overlook these subtle dependencies, and they can lead to headaches later.

So, the next logical step is to perform a quick search. I'll use `grep` to quickly scan the `kernel/bpf/Kconfig` file for anything related to "arena". That file is the central source of truth for kernel configuration options, so if there's a dependency lurking, it'll most likely be documented there. Hopefully, this will give me a clear picture of its configuration landscape. From there, I can ensure that the configuration is accurate.



12/2 2026/10/15 03:45 tool grepper
0m Args:
{
  "Expression": "arena",
  "PathPrefixes": [
    "kernel/bpf/"
  ]
}

Results:
{
  "Output": "\nFull output is too long, showing 200 out of 1471 lines.\nUse more precise expression or PathPrefixes if possible.\n\nNumber of matching lines per file (11 files in total):\nkernel/bpf/Makefile:1\nkernel/bpf/arena.c:328\nkernel/bpf/bpf_struct_ops.c:19\nkernel/bpf/btf.c:16\nkernel/bpf/core.c:10\nkernel/bpf/fixups.c:9\nkernel/bpf/log.c:1\nkernel/bpf/range_tree.c:3\nkernel/bpf/syscall.c:1\nkernel/bpf/trampoline.c:7\nkernel/bpf/verifier.c:82\n\nkernel/bpf/Makefile=19=ifeq ($(CONFIG_MMU)$(CONFIG_64BIT),yy)\nkernel/bpf/Makefile:20:obj-$(CONFIG_BPF_SYSCALL) += arena.o range_tree.o\nkernel/bpf/Makefile-21-endif\n--\nkernel/bpf/arena.c-21-/*\nkernel/bpf/arena.c:22: * bpf_arena is a sparsely populated shared memory region between bpf program and\nkernel/bpf/arena.c-23- * user space process.\n--\nkernel/bpf/arena.c-27- * kern_vm_start ffffc90001e69000 // picked by get_vm_area()\nkernel/bpf/arena.c:28: * For user space all pointers within the arena are normal 8-byte addresses.\nkernel/bpf/arena.c-29- * In this example 7f7d26200000 is the address of the first page (pgoff=0).\n--\nkernel/bpf/arena.c-35- *\nkernel/bpf/arena.c:36: * BPF JITs generate the following code to access arena:\nkernel/bpf/arena.c-37- *   mov eax, eax  // eax has lower 32-bit of user pointer\n--\nkernel/bpf/arena.c-44- * into kernel and user vma.\nkernel/bpf/arena.c:45: * bpf program can allocate a page via bpf_arena_alloc_pages() kfunc\nkernel/bpf/arena.c-46- * which will insert it into kernel vm_area.\n--\nkernel/bpf/arena.c-53-\nkernel/bpf/arena.c:54:static void arena_free_pages(struct bpf_arena *arena, long uaddr, long page_cnt, bool sleepable);\nkernel/bpf/arena.c-55-\nkernel/bpf/arena.c:56:struct bpf_arena {\nkernel/bpf/arena.c-57-\tstruct bpf_map map;\n--\nkernel/bpf/arena.c-67-\twait_queue_head_t opwait;\nkernel/bpf/arena.c:68:\t/* number of pages currently populated in the arena */\nkernel/bpf/arena.c-69-\tu64 nr_pages;\n--\nkernel/bpf/arena.c-77-\nkernel/bpf/arena.c:78:static void arena_free_worker(struct work_struct *work);\nkernel/bpf/arena.c:79:static void arena_free_irq(struct irq_work *iw);\nkernel/bpf/arena.c-80-\nkernel/bpf/arena.c-81-/* Positive references admit frees, negative references admit faults. */\nkernel/bpf/arena.c:82:enum arena_opref {\nkernel/bpf/arena.c-83-\tARENA_OPREF_FREE = 1,\n--\nkernel/bpf/arena.c-86-\nkernel/bpf/arena.c:87:static bool arena_opref_get(struct bpf_arena *arena, enum arena_opref ref)\nkernel/bpf/arena.c-88-{\nkernel/bpf/arena.c:89:\tint users = atomic_read(\u0026arena-\u003eopref);\nkernel/bpf/arena.c-90-\n--\nkernel/bpf/arena.c-93-\t\t\treturn false;\nkernel/bpf/arena.c:94:\t} while (!atomic_try_cmpxchg_acquire(\u0026arena-\u003eopref, \u0026users, users + ref));\nkernel/bpf/arena.c-95-\treturn true;\n--\nkernel/bpf/arena.c-97-\nkernel/bpf/arena.c:98:static void arena_opref_put(struct bpf_arena *arena, enum arena_opref ref)\nkernel/bpf/arena.c-99-{\nkernel/bpf/arena.c:100:\tif (atomic_fetch_sub_release(ref, \u0026arena-\u003eopref) == ref)\nkernel/bpf/arena.c:101:\t\twake_up_all(\u0026arena-\u003eopwait);\nkernel/bpf/arena.c-102-}\n--\nkernel/bpf/arena.c-110- */\nkernel/bpf/arena.c:111:enum arena_free_span_flags {\nkernel/bpf/arena.c-112-\tARENA_FREE_SPAN_CLEARED = BIT(0),\t/* Kernel PTEs cleared */\n--\nkernel/bpf/arena.c-117-\nkernel/bpf/arena.c:118:struct arena_free_span {\nkernel/bpf/arena.c-119-\tstruct llist_node node;\n--\nkernel/bpf/arena.c-124-\nkernel/bpf/arena.c:125:u64 bpf_arena_get_kern_vm_start(struct bpf_arena *arena)\nkernel/bpf/arena.c-126-{\nkernel/bpf/arena.c:127:\treturn arena ? (u64) (long) arena-\u003ekern_vm-\u003eaddr + GUARD_SZ / 2 : 0;\nkernel/bpf/arena.c-128-}\nkernel/bpf/arena.c-129-\nkernel/bpf/arena.c:130:u64 bpf_arena_get_user_vm_start(struct bpf_arena *arena)\nkernel/bpf/arena.c-131-{\nkernel/bpf/arena.c:132:\treturn arena ? arena-\u003euser_vm_start : 0;\nkernel/bpf/arena.c-133-}\n--\nkernel/bpf/arena.c-135-/**\nkernel/bpf/arena.c:136: * bpf_arena_map_kern_vm_start - kern_vm_start lookup by struct bpf_map *\nkernel/bpf/arena.c-137- * @map: a BPF_MAP_TYPE_ARENA map\n--\nkernel/bpf/arena.c-140- */\nkernel/bpf/arena.c:141:u64 bpf_arena_map_kern_vm_start(struct bpf_map *map)\nkernel/bpf/arena.c-142-{\nkernel/bpf/arena.c:143:\treturn bpf_arena_get_kern_vm_start(container_of(map, struct bpf_arena, map));\nkernel/bpf/arena.c-144-}\n--\nkernel/bpf/arena.c-146-/**\nkernel/bpf/arena.c:147: * bpf_prog_arena - return the bpf_map of the arena referenced by @prog\nkernel/bpf/arena.c-148- * @prog: a loaded BPF program\nkernel/bpf/arena.c-149- *\nkernel/bpf/arena.c:150: * The verifier enforces at most one arena per program and stores it in\nkernel/bpf/arena.c:151: * prog-\u003eaux-\u003earena. Return that arena's underlying bpf_map, or NULL if\nkernel/bpf/arena.c:152: * @prog does not reference an arena.\nkernel/bpf/arena.c-153- */\nkernel/bpf/arena.c:154:struct bpf_map *bpf_prog_arena(struct bpf_prog *prog)\nkernel/bpf/arena.c-155-{\nkernel/bpf/arena.c:156:\tstruct bpf_arena *arena = prog-\u003eaux-\u003earena;\nkernel/bpf/arena.c-157-\nkernel/bpf/arena.c:158:\treturn arena ? \u0026arena-\u003emap : NULL;\nkernel/bpf/arena.c-159-}\nkernel/bpf/arena.c-160-\nkernel/bpf/arena.c:161:static long arena_map_peek_elem(struct bpf_map *map, void *value)\nkernel/bpf/arena.c-162-{\n--\nkernel/bpf/arena.c-165-\nkernel/bpf/arena.c:166:static long arena_map_push_elem(struct bpf_map *map, void *value, u64 flags)\nkernel/bpf/arena.c-167-{\n--\nkernel/bpf/arena.c-170-\nkernel/bpf/arena.c:171:static long arena_map_pop_elem(struct bpf_map *map, void *value)\nkernel/bpf/arena.c-172-{\n--\nkernel/bpf/arena.c-175-\nkernel/bpf/arena.c:176:static long arena_map_delete_elem(struct bpf_map *map, void *value)\nkernel/bpf/arena.c-177-{\n--\nkernel/bpf/arena.c-180-\nkernel/bpf/arena.c:181:static int arena_map_get_next_key(struct bpf_map *map, void *key, void *next_key)\nkernel/bpf/arena.c-182-{\n--\nkernel/bpf/arena.c-185-\nkernel/bpf/arena.c:186:static long compute_pgoff(struct bpf_arena *arena, long uaddr)\nkernel/bpf/arena.c-187-{\nkernel/bpf/arena.c:188:\treturn (u32)(uaddr - (u32)arena-\u003euser_vm_start) \u003e\u003e PAGE_SHIFT;\nkernel/bpf/arena.c-189-}\n--\nkernel/bpf/arena.c=191=struct apply_range_data {\nkernel/bpf/arena.c:192:\tstruct bpf_arena *arena;\nkernel/bpf/arena.c-193-\tstruct llist_head *pages;\n--\nkernel/bpf/arena.c=197=struct clear_range_data {\nkernel/bpf/arena.c:198:\tstruct bpf_arena *arena;\nkernel/bpf/arena.c-199-\tstruct llist_head *free_pages;\n--\nkernel/bpf/arena.c=202=static int apply_range_set_cb(pte_t *pte, unsigned long addr, void *data)\n--\nkernel/bpf/arena.c-232-\t\t\tcontinue;\nkernel/bpf/arena.c:233:\t\tif (WARN_ON_ONCE(pte_page(old) != d-\u003earena-\u003escratch_page))\nkernel/bpf/arena.c-234-\t\t\treturn -EBUSY;\n--\nkernel/bpf/arena.c-240-\t * Without ptep_try_set() there is no atomic installer, but such arches\nkernel/bpf/arena.c:241:\t * also do not wire up bpf_arena_handle_page_fault(), so no scratch page\nkernel/bpf/arena.c-242-\t * is ever installed and the slot is always none here.\n--\nkernel/bpf/arena.c-247-#endif\nkernel/bpf/arena.c:248:\tpage_folio(page)-\u003eindex = compute_pgoff(d-\u003earena,\nkernel/bpf/arena.c:249:\t\t\t\t\t\taddr - bpf_arena_get_kern_vm_start(d-\u003earena));\nkernel/bpf/arena.c:250:\tpage-\u003emapping = d-\u003earena-\u003efile-\u003ef_mapping;\nkernel/bpf/arena.c-251-\tWARN_ON_ONCE(llist_del_first(d-\u003epages) != node);\nkernel/bpf/arena.c-252-\td-\u003ei++;\nkernel/bpf/arena.c:253:\tWRITE_ONCE(d-\u003earena-\u003enr_pages, d-\u003earena-\u003enr_pages + 1);\nkernel/bpf/arena.c-254-\treturn 0;\n--\nkernel/bpf/arena.c=262=static int apply_range_clear_cb(pte_t *pte, unsigned long addr, void *data)\n--\nkernel/bpf/arena.c-280-\t/*\nkernel/bpf/arena.c:281:\t * Skip the per-arena scratch page. A kernel fault on an unallocated uaddr\nkernel/bpf/arena.c:282:\t * scratches its PTE. A later bpf_arena_free_pages() over that range walks\nkernel/bpf/arena.c-283-\t * here. Without the skip, scratch_page would be freed.\nkernel/bpf/arena.c-284-\t */\nkernel/bpf/arena.c:285:\tif (page == d-\u003earena-\u003escratch_page)\nkernel/bpf/arena.c-286-\t\treturn 0;\n--\nkernel/bpf/arena.c-288-\t__llist_add(\u0026page-\u003epcp_llist, d-\u003efree_pages);\nkernel/bpf/arena.c:289:\tWRITE_ONCE(d-\u003earena-\u003enr_pages, d-\u003earena-\u003enr_pages - 1);\nkernel/bpf/arena.c-290-\treturn 0;\n--\nkernel/bpf/arena.c=293=static int apply_range_set_scratch_cb(pte_t *pte, unsigned long addr, void *data)\n--\nkernel/bpf/arena.c-310-\nkernel/bpf/arena.c:311:static int populate_pgtable_except_pte(struct bpf_arena *arena)\nkernel/bpf/arena.c-312-{\nkernel/bpf/arena.c-313-\t/* Populate intermediates for the recovery range (4 GiB + upper half-guard). */\nkernel/bpf/arena.c:314:\treturn apply_to_page_range(\u0026init_mm, bpf_arena_get_kern_vm_start(arena),\nkernel/bpf/arena.c-315-\t\t\t\t   SZ_4G + GUARD_SZ / 2, apply_range_set_cb, NULL);\n--\nkernel/bpf/arena.c-318-/* The backing file must not hold a map reference. */\nkernel/bpf/arena.c:319:static const struct file_operations arena_backing_fops = {};\nkernel/bpf/arena.c-320-\nkernel/bpf/arena.c-321-/* Arena pages are not page-cache entries and must not be evicted by MM. */\nkernel/bpf/arena.c:322:static bool arena_release_folio(struct folio *folio, gfp_t gfp)\nkernel/bpf/arena.c-323-{\n--\nkernel/bpf/arena.c-326-\nkernel/bpf/arena.c:327:static const struct address_space_operations arena_aops = {\nkernel/bpf/arena.c-328-\t.dirty_folio = noop_dirty_folio,\nkernel/bpf/arena.c:329:\t.release_folio = arena_release_folio,\nkernel/bpf/arena.c-330-};\nkernel/bpf/arena.c-331-\nkernel/bpf/arena.c:332:static struct bpf_map *arena_map_alloc(union bpf_attr *attr)\nkernel/bpf/arena.c-333-{\n--\nkernel/bpf/arena.c-335-\tint numa_node = bpf_map_attr_numa_node(attr);\nkernel/bpf/arena.c:336:\tstruct bpf_arena *arena;\nkernel/bpf/arena.c-337-\tu64 vm_range;\n--\nkernel/bpf/arena.c-339-\nkernel/bpf/arena.c:340:\tif (!bpf_jit_supports_arena())\nkernel/bpf/arena.c-341-\t\treturn ERR_PTR(-EOPNOTSUPP);\n--\nkernel/bpf/arena.c-365-\nkernel/bpf/arena.c:366:\tarena = bpf_map_area_alloc(sizeof(*arena), numa_node);\n\n"
}

13/2 2026/10/15 03:45 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 32309
							output: 36
							thoughts: 48
						

Thoughts:
Here's my analysis of the provided code snippet:

**Diving into BPF JIT Arena Support**

Okay, so I see this line, line 340, staring me in the face: `if (!bpf_jit_supports_arena()) return ERR_PTR(-EOPNOTSUPP);`. Immediately, my brain kicks into gear. This is a critical check for BPF JIT functionality – clearly, something relies on the arena feature. The negative return suggests an unsupported operation if the arena isn't available.

My first thought? We need to understand what `bpf_jit_supports_arena()` *actually* does. What's it testing? Is this feature essential for *all* JIT operations, or just certain optimizations, code paths or maybe specific hardware? I want to know the *why* behind this check. I'm going to track down the implementation of that function right now. I need to know the conditions under which it returns true or false, and what's at stake if it returns false. Is there a fallback mechanism? Could we, perhaps, emulate this arena functionality? Is there a performance hit if we don't have it? My mind is already sketching out a mental map of dependencies. This is a potential performance bottleneck, or, at the very least, a significant feature gate. I need to understand its implications for the overall BPF JIT design. Right, time to dig deeper!



14/2 2026/10/15 03:45 tool grepper
0m Args:
{
  "Expression": "bpf_jit_supports_arena",
  "PathPrefixes": [
    "arch/",
    "kernel/"
  ]
}

Results:
{
  "Output": "arch/arm64/net/bpf_jit_comp.c=2472=bool bpf_jit_supports_stack_args(void)\n--\narch/arm64/net/bpf_jit_comp.c-2476-\narch/arm64/net/bpf_jit_comp.c:2477:bool bpf_jit_supports_arena_args(void)\narch/arm64/net/bpf_jit_comp.c-2478-{\n--\narch/arm64/net/bpf_jit_comp.c=3408=bool bpf_jit_supports_exceptions(void)\n--\narch/arm64/net/bpf_jit_comp.c-3417-\narch/arm64/net/bpf_jit_comp.c:3418:bool bpf_jit_supports_arena(void)\narch/arm64/net/bpf_jit_comp.c-3419-{\n--\narch/arm64/net/bpf_jit_comp.c-3422-\narch/arm64/net/bpf_jit_comp.c:3423:bool bpf_jit_supports_arena_scalar(void)\narch/arm64/net/bpf_jit_comp.c-3424-{\n--\narch/loongarch/net/bpf_jit.c=2432=bool bpf_jit_bypass_spec_v4(void)\n--\narch/loongarch/net/bpf_jit.c-2436-\narch/loongarch/net/bpf_jit.c:2437:bool bpf_jit_supports_arena(void)\narch/loongarch/net/bpf_jit.c-2438-{\n--\narch/mips/net/bpf_jit_comp32.c=229=static void emit_mov_r64(struct jit_context *ctx, const u8 dst[],\n--\narch/mips/net/bpf_jit_comp32.c-245-\t\t * offsets; defined exceptions require\narch/mips/net/bpf_jit_comp32.c:246:\t\t * bpf_jit_supports_percpu_insn() or bpf_jit_supports_arena(),\narch/mips/net/bpf_jit_comp32.c-247-\t\t * neither implemented by MIPS.\n--\narch/mips/net/bpf_jit_comp64.c=152=static void emit_mov_r64(struct jit_context *ctx, u8 dst, u8 src, s16 off)\n--\narch/mips/net/bpf_jit_comp64.c-165-\t\t * offsets; defined exceptions require\narch/mips/net/bpf_jit_comp64.c:166:\t\t * bpf_jit_supports_percpu_insn() or bpf_jit_supports_arena(),\narch/mips/net/bpf_jit_comp64.c-167-\t\t * neither implemented by MIPS.\n--\narch/powerpc/net/bpf_jit_comp.c=535=bool bpf_jit_supports_fsession(void)\n--\narch/powerpc/net/bpf_jit_comp.c-545-\narch/powerpc/net/bpf_jit_comp.c:546:bool bpf_jit_supports_arena(void)\narch/powerpc/net/bpf_jit_comp.c-547-{\n--\narch/riscv/net/bpf_jit_comp64.c=2232=bool bpf_jit_supports_ptr_xchg(void)\n--\narch/riscv/net/bpf_jit_comp64.c-2236-\narch/riscv/net/bpf_jit_comp64.c:2237:bool bpf_jit_supports_arena(void)\narch/riscv/net/bpf_jit_comp64.c-2238-{\n--\narch/s390/net/bpf_jit_comp.c=3075=bool bpf_jit_supports_subprog_tailcalls(void)\n--\narch/s390/net/bpf_jit_comp.c-3079-\narch/s390/net/bpf_jit_comp.c:3080:bool bpf_jit_supports_arena(void)\narch/s390/net/bpf_jit_comp.c-3081-{\n--\narch/x86/net/bpf_jit_comp.c=4519=bool bpf_jit_supports_stack_args(void)\n--\narch/x86/net/bpf_jit_comp.c-4523-\narch/x86/net/bpf_jit_comp.c:4524:bool bpf_jit_supports_arena_args(void)\narch/x86/net/bpf_jit_comp.c-4525-{\n--\narch/x86/net/bpf_jit_comp.c=4624=void bpf_arch_poke_desc_update(struct bpf_jit_poke_descriptor *poke,\n--\narch/x86/net/bpf_jit_comp.c-4671-\narch/x86/net/bpf_jit_comp.c:4672:bool bpf_jit_supports_arena(void)\narch/x86/net/bpf_jit_comp.c-4673-{\n--\narch/x86/net/bpf_jit_comp.c-4676-\narch/x86/net/bpf_jit_comp.c:4677:bool bpf_jit_supports_arena_scalar(void)\narch/x86/net/bpf_jit_comp.c-4678-{\n--\nkernel/bpf/arena.c=332=static struct bpf_map *arena_map_alloc(union bpf_attr *attr)\n--\nkernel/bpf/arena.c-339-\nkernel/bpf/arena.c:340:\tif (!bpf_jit_supports_arena())\nkernel/bpf/arena.c-341-\t\treturn ERR_PTR(-EOPNOTSUPP);\n--\nkernel/bpf/core.c=3423=bool __weak bpf_jit_supports_stack_args(void)\n--\nkernel/bpf/core.c-3427-\nkernel/bpf/core.c:3428:bool __weak bpf_jit_supports_arena_args(void)\nkernel/bpf/core.c-3429-{\n--\nkernel/bpf/core.c=3433=bool __weak bpf_jit_supports_far_kfunc_call(void)\n--\nkernel/bpf/core.c-3437-\nkernel/bpf/core.c:3438:bool __weak bpf_jit_supports_arena(void)\nkernel/bpf/core.c-3439-{\n--\nkernel/bpf/core.c-3443-/* Whether JIT takes BPF_REG_AX as the address of arena access */\nkernel/bpf/core.c:3444:bool __weak bpf_jit_supports_arena_scalar(void)\nkernel/bpf/core.c-3445-{\n--\nkernel/bpf/syscall.c=2955=static int bpf_prog_load(union bpf_attr *attr, bpfptr_t uattr, struct bpf_log_attr *attr_log)\n--\nkernel/bpf/syscall.c-2980-\nkernel/bpf/syscall.c:2981:\tif ((attr-\u003eprog_flags \u0026 BPF_F_ARENA_SCALAR) \u0026\u0026 !bpf_jit_supports_arena_scalar())\nkernel/bpf/syscall.c-2982-\t\treturn -EOPNOTSUPP;\n--\nkernel/bpf/verifier.c=13651=get_kfunc_arg_type(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,\n--\nkernel/bpf/verifier.c-13789-\telse if (is_kfunc_arg_arena(meta-\u003ebtf, \u0026args[arg])) {\nkernel/bpf/verifier.c:13790:\t\tif (!bpf_jit_supports_arena_args()) {\nkernel/bpf/verifier.c-13791-\t\t\tverbose(env, \"JIT does not support kfunc %s() with arena pointer arguments\\n\",\n--\nkernel/bpf/verifier.c=20586=static int check_map_prog_compatibility(struct bpf_verifier_env *env,\n--\nkernel/bpf/verifier.c-20680-\t\t}\nkernel/bpf/verifier.c:20681:\t\tif (!bpf_jit_supports_arena()) {\nkernel/bpf/verifier.c-20682-\t\t\tverbose(env, \"JIT doesn't support arena\\n\");\n--\nkernel/bpf/verifier.c=21677=static int check_struct_ops_btf_id(struct bpf_verifier_env *env)\n--\nkernel/bpf/verifier.c-21766-\t\tif (base_type(info-\u003ereg_type) == PTR_TO_ARENA) {\nkernel/bpf/verifier.c:21767:\t\t\tif (!bpf_jit_supports_arena_args()) {\nkernel/bpf/verifier.c-21768-\t\t\t\tverbose(env, \"JIT does not support arena arguments\\n\");\n"
}

15/2 2026/10/15 03:45 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 35129
							output: 45
							thoughts: 77
						

Thoughts:
Here's my summary, as though I were thinking through the problem:

**Digging into the BPF JIT Support**

Alright, I need to understand the arena support within the x86 BPF JIT compiler. My instinct is to head straight to the source. Specifically, I want to examine the implementation of `bpf_jit_supports_arena()`. The most likely place to find this is in `arch/x86/net/bpf_jit_comp.c`, and I'm guessing line 4672 is a good place to start – it's often where function definitions live or where related logic begins. Let me just quickly use `read-file` to get the context around that line to confirm my initial assumption. That's where the information I need resides.



16/2 2026/10/15 03:45 tool read-file
0m Args:
{
  "File": "arch/x86/net/bpf_jit_comp.c",
  "FirstLine": 4665,
  "LineCount": 25
}

Results:
{
  "Contents": "4665:\t\t\tt = old_addr ? BPF_MOD_JUMP : BPF_MOD_NOP;\n4666:\t\t\tret = __bpf_arch_text_poke(poke-\u003etailcall_target,\n4667:\t\t\t\t\t\t   t, BPF_MOD_NOP, old_addr, NULL);\n4668:\t\t\tBUG_ON(ret \u003c 0);\n4669:\t\t}\n4670:\t}\n4671:\t\n4672:\tbool bpf_jit_supports_arena(void)\n4673:\t{\n4674:\t\treturn true;\n4675:\t}\n4676:\t\n4677:\tbool bpf_jit_supports_arena_scalar(void)\n4678:\t{\n4679:\t\treturn true;\n4680:\t}\n4681:\t\n4682:\tbool bpf_jit_supports_insn(struct bpf_insn *insn, bool in_arena)\n4683:\t{\n4684:\t\tif (!in_arena)\n4685:\t\t\treturn true;\n4686:\t\tswitch (insn-\u003ecode) {\n4687:\t\tcase BPF_STX | BPF_ATOMIC | BPF_W:\n4688:\t\tcase BPF_STX | BPF_ATOMIC | BPF_DW:\n4689:\t\t\tif (insn-\u003eimm == (BPF_AND | BPF_FETCH) ||\n"
}

17/2 2026/10/15 03:45 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 35812
							output: 35
							thoughts: 49
						

Thoughts:
Here's my summary, as though I'm thinking through this process:

**Investigating BPF JIT Compilation on x86**

Okay, so I'm looking into the BPF JIT compilation process on x86. The obvious starting point is `arch/x86/net/bpf_jit_comp.c`, because that's the likely source code for the JIT compiler itself when `CONFIG_BPF_JIT` is enabled. Now, the next logical step is to see how this particular file is built and incorporated into the kernel. Where would that information reside? That's right, the `Makefile` in the same directory, which is `arch/x86/net/Makefile`. I need to peek at that to understand the build process.



18/2 2026/10/15 03:45 tool grepper
0m Args:
{
  "Expression": "bpf_jit_comp",
  "PathPrefixes": [
    "arch/x86/net/"
  ]
}

Results:
{
  "Output": "arch/x86/net/Makefile=6=ifeq ($(CONFIG_X86_32),y)\narch/x86/net/Makefile:7:        obj-$(CONFIG_BPF_JIT) += bpf_jit_comp32.o\narch/x86/net/Makefile-8-else\narch/x86/net/Makefile:9:        obj-$(CONFIG_BPF_JIT) += bpf_jit_comp.o bpf_timed_may_goto.o\narch/x86/net/Makefile-10-endif\n"
}

19/2 2026/10/15 03:45 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 36212
							output: 20
							thoughts: 104
						

Thoughts:
Okay, here's my assessment of the situation:

**Investigating BPF JIT Compilation Support**

Right, so, I see that `bpf_jit_comp.c` has a function, `bpf_jit_supports_arena()`, which is returning true on x86_64. This is a good starting point. My next step is to nail down the *why* - what are the configuration settings driving this behavior? My initial hunch is that `CONFIG_BPF_JIT` and `CONFIG_BPF_SYSCALL` are the crucial flags that are enabling the JIT compilation. I need to confirm this. I'll need to dig into the kernel's Kconfig files to confirm my thoughts. I'll start looking in `init/Kconfig`, then branch out to `arch/x86/Kconfig` and `kernel/bpf/Kconfig`, as these would be the most likely locations for those settings. That should give me the configuration context I need.



20/2 2026/10/15 03:45 tool grepper
0m Args:
{
  "Expression": "config BPF_JIT"
}

Results:
{
  "Output": "kernel/bpf/Kconfig=31=config BPF_SYSCALL\n--\nkernel/bpf/Kconfig-45-\nkernel/bpf/Kconfig:46:config BPF_JIT\nkernel/bpf/Kconfig-47-\tbool \"Enable BPF Just In Time compiler\"\n--\nkernel/bpf/Kconfig-61-\nkernel/bpf/Kconfig:62:config BPF_JIT_ALWAYS_ON\nkernel/bpf/Kconfig-63-\tbool \"Permanently enable BPF JIT and remove BPF interpreter\"\n--\nkernel/bpf/Kconfig-72-\nkernel/bpf/Kconfig:73:config BPF_JIT_DEFAULT_ON\nkernel/bpf/Kconfig-74-\tdef_bool ARCH_WANT_DEFAULT_BPF_JIT || BPF_JIT_ALWAYS_ON\n--\nkernel/bpf/Kconfig=105=config BPF_LSM\n--\nkernel/bpf/Kconfig-116-\nkernel/bpf/Kconfig:117:config BPF_JIT_KASAN\nkernel/bpf/Kconfig-118-\tbool\n"
}

21/2 2026/10/15 03:45 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 36850
							output: 50
							thoughts: 1189
						

Thoughts:
**Focusing on BPF Arena Fuzzing Targets**

Okay, let's break this down. My goal is to identify the most promising targets for fuzzing a recent BPF arena patch. I'm focusing specifically on the areas that have been modified or introduced and are likely to be reached via fuzzing.

First, I confirmed the configuration dependencies. `arena.o` and `range_tree.o` require both `BPF_SYSCALL` and, crucially, `BPF_JIT`. The `bpf_jit_supports_arena()` function, which gates arena support, depends on the JIT configuration. So, both need to be active.

Now, why am I confident this is worth the effort? Several factors jump out:

1.  **Core Kernel Modification:** The patch dives deep, directly modifying code in `kernel/bpf/arena.c` and `kernel/bpf/range_tree.c`.
2.  **Concurrency Changes:** It touches concurrency with `opref`, `opwait`, folio locking, rmap tree traversal, and span state flags. That's a classic area for race conditions.
3.  **Memory Lifecycle:** This alters memory allocation/freeing, page mapping pointers, and page table updates, all areas where subtle errors can lead to crashes or vulnerabilities.
4.  **Defensive Programming:** It adds defensive checks and `WARN_ON_ONCE` assertions, suggesting the developers anticipated potential issues and added protections.
5.  **Reachable Surfaces:** Everything here is directly reachable through `bpf()` system calls (`BPF_MAP_CREATE` with `BPF_MAP_TYPE_ARENA`), `mmap()`, memory access triggering page faults, and `bpf_arena_alloc_pages` / `bpf_arena_free_pages` / map destruction.

Now for the key part: pinpointing specific fuzzing targets. I'm looking for functions that were added or substantially changed by the patch. Here's what I've identified:

In `kernel/bpf/arena.c`:

*   `arena_opref_get`, `arena_opref_put`
*   `arena_backing_fops`
*   `arena_release_folio`
*   `arena_map_alloc`, `arena_put_page`, `arena_map_free`, `arena_map_get_file`, `arena_map_mmap`
*   `arena_vm_fault`
*   `zap_pages`, `wait_for_faults`
*   `arena_free_pages`, `arena_free_worker`
*   `bpf_arena_free_pages`, `bpf_arena_alloc_pages`, `bpf_arena_reserve_pages`

In `kernel/bpf/range_tree.c`:

*   `range_node_mark_available`
*   `range_tree_make_avail`
*   `range_tree_set_avail`
*   `range_tree_set_unavail`
*   `range_tree_clear`
*   `range_get_adjacent`, `range_tree_merge`, `range_tree_set`

In `kernel/bpf/syscall.c`:

*   `bpf_map_new_fd` (modified to call `map->ops->map_get_file`)

Now, a crucial question: which of these are actually *visible* to me? Static functions are usually local to the compilation unit. They won't be in the vmlinux symbol table unless they are inlined. So I need to determine which of the `arena_*` functions (like `arena_vm_fault`, `arena_free_pages`, and `arena_free_worker`) are actually available to be targeted.



22/2 2026/10/15 03:45 tool grepper
0m Args:
{
  "Expression": "^static (vm_fault_t|void|long|int|struct|bool).*arena_",
  "PathPrefixes": [
    "kernel/bpf/arena.c"
  ]
}

Results:
{
  "Output": "kernel/bpf/arena.c-53-\nkernel/bpf/arena.c:54:static void arena_free_pages(struct bpf_arena *arena, long uaddr, long page_cnt, bool sleepable);\nkernel/bpf/arena.c-55-\nkernel/bpf/arena.c=56=struct bpf_arena {\n--\nkernel/bpf/arena.c-77-\nkernel/bpf/arena.c:78:static void arena_free_worker(struct work_struct *work);\nkernel/bpf/arena.c:79:static void arena_free_irq(struct irq_work *iw);\nkernel/bpf/arena.c-80-\n--\nkernel/bpf/arena.c=82=enum arena_opref {\n--\nkernel/bpf/arena.c-86-\nkernel/bpf/arena.c:87:static bool arena_opref_get(struct bpf_arena *arena, enum arena_opref ref)\nkernel/bpf/arena.c-88-{\n--\nkernel/bpf/arena.c-97-\nkernel/bpf/arena.c:98:static void arena_opref_put(struct bpf_arena *arena, enum arena_opref ref)\nkernel/bpf/arena.c-99-{\n--\nkernel/bpf/arena.c=154=struct bpf_map *bpf_prog_arena(struct bpf_prog *prog)\n--\nkernel/bpf/arena.c-160-\nkernel/bpf/arena.c:161:static long arena_map_peek_elem(struct bpf_map *map, void *value)\nkernel/bpf/arena.c-162-{\n--\nkernel/bpf/arena.c-165-\nkernel/bpf/arena.c:166:static long arena_map_push_elem(struct bpf_map *map, void *value, u64 flags)\nkernel/bpf/arena.c-167-{\n--\nkernel/bpf/arena.c-170-\nkernel/bpf/arena.c:171:static long arena_map_pop_elem(struct bpf_map *map, void *value)\nkernel/bpf/arena.c-172-{\n--\nkernel/bpf/arena.c-175-\nkernel/bpf/arena.c:176:static long arena_map_delete_elem(struct bpf_map *map, void *value)\nkernel/bpf/arena.c-177-{\n--\nkernel/bpf/arena.c-180-\nkernel/bpf/arena.c:181:static int arena_map_get_next_key(struct bpf_map *map, void *key, void *next_key)\nkernel/bpf/arena.c-182-{\n--\nkernel/bpf/arena.c=319=static const struct file_operations arena_backing_fops = {};\n--\nkernel/bpf/arena.c-321-/* Arena pages are not page-cache entries and must not be evicted by MM. */\nkernel/bpf/arena.c:322:static bool arena_release_folio(struct folio *folio, gfp_t gfp)\nkernel/bpf/arena.c-323-{\n--\nkernel/bpf/arena.c=327=static const struct address_space_operations arena_aops = {\n--\nkernel/bpf/arena.c-331-\nkernel/bpf/arena.c:332:static struct bpf_map *arena_map_alloc(union bpf_attr *attr)\nkernel/bpf/arena.c-333-{\n--\nkernel/bpf/arena.c-418-\nkernel/bpf/arena.c:419:static void arena_put_page(struct page *page)\nkernel/bpf/arena.c-420-{\n--\nkernel/bpf/arena.c=427=static int existing_page_cb(pte_t *ptep, unsigned long addr, void *data)\n--\nkernel/bpf/arena.c-453-\nkernel/bpf/arena.c:454:static void arena_map_free(struct bpf_map *map)\nkernel/bpf/arena.c-455-{\n--\nkernel/bpf/arena.c-496-\nkernel/bpf/arena.c:497:static void *arena_map_lookup_elem(struct bpf_map *map, void *key)\nkernel/bpf/arena.c-498-{\n--\nkernel/bpf/arena.c-501-\nkernel/bpf/arena.c:502:static long arena_map_update_elem(struct bpf_map *map, void *key,\nkernel/bpf/arena.c-503-\t\t\t\t  void *value, u64 flags)\n--\nkernel/bpf/arena.c-507-\nkernel/bpf/arena.c:508:static int arena_map_check_btf(struct bpf_map *map, const struct btf *btf,\nkernel/bpf/arena.c-509-\t\t\t       const struct btf_type *key_type, const struct btf_type *value_type)\n--\nkernel/bpf/arena.c=526=static int remember_vma(struct bpf_arena *arena, struct vm_area_struct *vma)\n--\nkernel/bpf/arena.c-538-\nkernel/bpf/arena.c:539:static void arena_vm_open(struct vm_area_struct *vma)\nkernel/bpf/arena.c-540-{\n--\nkernel/bpf/arena.c-545-\nkernel/bpf/arena.c:546:static int arena_vm_may_split(struct vm_area_struct *vma, unsigned long addr)\nkernel/bpf/arena.c-547-{\n--\nkernel/bpf/arena.c-550-\nkernel/bpf/arena.c:551:static int arena_vm_mremap(struct vm_area_struct *vma)\nkernel/bpf/arena.c-552-{\n--\nkernel/bpf/arena.c-555-\nkernel/bpf/arena.c:556:static void arena_vm_close(struct vm_area_struct *vma)\nkernel/bpf/arena.c-557-{\n--\nkernel/bpf/arena.c-570-\nkernel/bpf/arena.c:571:static vm_fault_t arena_vm_fault(struct vm_fault *vmf)\nkernel/bpf/arena.c-572-{\n--\nkernel/bpf/arena.c=744=static unsigned long arena_get_unmapped_area(struct file *filp, unsigned long addr,\n--\nkernel/bpf/arena.c-777-\nkernel/bpf/arena.c:778:static struct file *arena_map_get_file(struct bpf_map *map, int flags)\nkernel/bpf/arena.c-779-{\n--\nkernel/bpf/arena.c-791-\nkernel/bpf/arena.c:792:static int arena_map_mmap(struct bpf_map *map, struct vm_area_struct *vma)\nkernel/bpf/arena.c-793-{\n--\nkernel/bpf/arena.c-831-\nkernel/bpf/arena.c:832:static int arena_map_direct_value_addr(const struct bpf_map *map, u64 *imm, u32 off)\nkernel/bpf/arena.c-833-{\n--\nkernel/bpf/arena.c=863=static u64 clear_lo32(u64 val)\n--\nkernel/bpf/arena.c-867-\nkernel/bpf/arena.c:868:static int arena_adjust_tree(struct bpf_arena *arena, long uaddr, long page_cnt, long *pgoff)\nkernel/bpf/arena.c-869-{\n--\nkernel/bpf/arena.c-892- */\nkernel/bpf/arena.c:893:static long arena_alloc_pages(struct bpf_arena *arena, long uaddr, long page_cnt, int node_id,\nkernel/bpf/arena.c-894-\t\t\t      bool sleepable)\n--\nkernel/bpf/arena.c=1007=static void wait_for_faults(struct llist_head *pages)\n--\nkernel/bpf/arena.c-1014-\nkernel/bpf/arena.c:1015:static void arena_free_pages(struct bpf_arena *arena, long uaddr, long page_cnt, bool sleepable)\nkernel/bpf/arena.c-1016-{\n--\nkernel/bpf/arena.c-1157- */\nkernel/bpf/arena.c:1158:static int arena_reserve_pages(struct bpf_arena *arena, long uaddr, u32 page_cnt)\nkernel/bpf/arena.c-1159-{\n--\nkernel/bpf/arena.c-1191-\nkernel/bpf/arena.c:1192:static void arena_free_worker(struct work_struct *work)\nkernel/bpf/arena.c-1193-{\n--\nkernel/bpf/arena.c-1348-\nkernel/bpf/arena.c:1349:static void arena_free_irq(struct irq_work *iw)\nkernel/bpf/arena.c-1350-{\n--\nkernel/bpf/arena.c=1444=late_initcall(kfunc_init);\nkernel/bpf/arena.c-1445-\nkernel/bpf/arena.c:1446:static void __bpf_prog_report_arena_violation(struct bpf_prog *prog, bool write,\nkernel/bpf/arena.c-1447-\t\t\t\t\t      unsigned long addr, unsigned long fault_ip)\n"
}

23/2 2026/10/15 03:45 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 41456
							output: 18
							thoughts: 392
						

Thoughts:
**Analyzing BPF Arena and Range Tree Usage**

Okay, let's dive into the code. My initial focus is on `kernel/bpf/arena.c` and `kernel/bpf/range_tree.c`. It looks like these files are central to the BPF memory management within the kernel. I need to get a clear picture of what's been changed and how they interact.

In `arena.c`, I'm seeing significant modifications to several key functions. `arena_vm_fault`, the VM fault handler, has been substantially altered. `arena_free_pages`, which is fundamental to freeing arena pages, has also undergone substantial changes, along with `arena_free_worker`, the deferred work item. I also see that `zap_pages` is updated to utilize rmap walk. The allocation and freeing functions, `arena_map_alloc` and `arena_map_free`, have been modified to include backing file creation with `anon_inode`, and cleanup operations such as disabling work synchronization, kfree spans, and fput the backing file, respectively. There's also a new `arena_map_get_file` callback added to map operations. Furthermore, the `bpf_arena_alloc_pages` and `bpf_arena_free_pages` kfuncs are interesting, as they're the direct interface for BPF programs and syscalls to interact with the arena.

Now, turning to `range_tree.c`, I'm noting the presence of functions like `range_tree_set_avail`, `range_tree_set_unavail`, `range_tree_make_avail`, `range_node_mark_available`, and `range_tree_clear`. I'll need to understand their purpose within this arena context.

I'm now going to cross-reference the usage of those exported functions in `range_tree.c` which include `range_tree_clear`, `range_tree_set_avail`, `range_tree_set_unavail`, `range_node_mark_available`, `range_tree_make_avail`, and `range_tree_find`. Okay, this looks like a very targeted use case; the range tree is *only* used within `kernel/bpf/arena.c`. This strongly suggests that the range tree is tightly coupled with the arena memory management. It's not a generic data structure. I'll need to explore that coupling to understand the changes fully. It looks like my next step will be a deep dive into how `range_tree.c` implements its functions to service arena's memory needs.



24/2 2026/10/15 03:45 tool grepper
0m Args:
{
  "Expression": "range_tree_"
}

Results:
{
  "Output": "kernel/bpf/arena.c=332=static struct bpf_map *arena_map_alloc(union bpf_attr *attr)\n--\nkernel/bpf/arena.c-384-\nkernel/bpf/arena.c:385:\trange_tree_init(\u0026arena-\u003ert);\nkernel/bpf/arena.c:386:\terr = range_tree_set_avail(\u0026arena-\u003ert, 0, attr-\u003emax_entries);\nkernel/bpf/arena.c-387-\tif (err)\n--\nkernel/bpf/arena.c-408-err_destroy_rt:\nkernel/bpf/arena.c:409:\trange_tree_destroy(\u0026arena-\u003ert);\nkernel/bpf/arena.c-410-err_free_scratch:\n--\nkernel/bpf/arena.c=454=static void arena_map_free(struct bpf_map *map)\n--\nkernel/bpf/arena.c-490-\tfree_vm_area(arena-\u003ekern_vm);\nkernel/bpf/arena.c:491:\trange_tree_destroy(\u0026arena-\u003ert);\nkernel/bpf/arena.c-492-\t__free_page(arena-\u003escratch_page);\n--\nkernel/bpf/arena.c=571=static vm_fault_t arena_vm_fault(struct vm_fault *vmf)\n--\nkernel/bpf/arena.c-655-\nkernel/bpf/arena.c:656:\tret = range_tree_clear(\u0026arena-\u003ert, vmf-\u003epgoff, 1);\nkernel/bpf/arena.c-657-\t/* If a range is unavailable, try again. */\n--\nkernel/bpf/arena.c-677-\t\tllist_del_first(\u0026pages);\nkernel/bpf/arena.c:678:\t\trange_tree_set_avail(\u0026arena-\u003ert, vmf-\u003epgoff, 1);\nkernel/bpf/arena.c-679-\t\tfault_ret = VM_FAULT_SIGBUS;\n--\nkernel/bpf/arena.c=868=static int arena_adjust_tree(struct bpf_arena *arena, long uaddr, long page_cnt, long *pgoff)\n--\nkernel/bpf/arena.c-873-\tif (uaddr) {\nkernel/bpf/arena.c:874:\t\tret = is_range_tree_set(\u0026arena-\u003ert, *pgoff, page_cnt);\nkernel/bpf/arena.c-875-\t\tif (ret)\nkernel/bpf/arena.c-876-\t\t\treturn ret;\nkernel/bpf/arena.c:877:\t\treturn range_tree_clear(\u0026arena-\u003ert, *pgoff, page_cnt);\nkernel/bpf/arena.c-878-\t}\nkernel/bpf/arena.c-879-\nkernel/bpf/arena.c:880:\tret = range_tree_find(\u0026arena-\u003ert, page_cnt);\nkernel/bpf/arena.c-881-\tif (ret \u003c 0)\n--\nkernel/bpf/arena.c-885-\nkernel/bpf/arena.c:886:\treturn range_tree_clear(\u0026arena-\u003ert, *pgoff, page_cnt);\nkernel/bpf/arena.c-887-}\n--\nkernel/bpf/arena.c=893=static long arena_alloc_pages(struct bpf_arena *arena, long uaddr, long page_cnt, int node_id,\n--\nkernel/bpf/arena.c-967-\tflush_vmap_cache(kern_vm_start + uaddr32, mapped \u003c\u003c PAGE_SHIFT);\nkernel/bpf/arena.c:968:\trange_tree_set_avail(\u0026arena-\u003ert, pgoff + mapped, page_cnt - mapped);\nkernel/bpf/arena.c-969-\traw_res_spin_unlock_irqrestore(\u0026arena-\u003espinlock, flags);\n--\nkernel/bpf/arena.c=1015=static void arena_free_pages(struct bpf_arena *arena, long uaddr, long page_cnt, bool sleepable)\n--\nkernel/bpf/arena.c-1055-\nkernel/bpf/arena.c:1056:\tunavail_node = range_tree_set_unavail(\u0026arena-\u003ert, pgoff, page_cnt);\nkernel/bpf/arena.c-1057-\tif (IS_ERR(unavail_node)) {\n--\nkernel/bpf/arena.c-1106-\nkernel/bpf/arena.c:1107:\tret = range_tree_make_avail(\u0026arena-\u003ert, pgoff, page_cnt);\nkernel/bpf/arena.c-1108-\traw_res_spin_unlock_irqrestore(\u0026arena-\u003espinlock, flags);\n--\nkernel/bpf/arena.c=1158=static int arena_reserve_pages(struct bpf_arena *arena, long uaddr, u32 page_cnt)\n--\nkernel/bpf/arena.c-1176-\t/* Cannot guard already allocated pages. */\nkernel/bpf/arena.c:1177:\tret = is_range_tree_set(\u0026arena-\u003ert, pgoff, page_cnt);\nkernel/bpf/arena.c-1178-\tif (ret) {\n--\nkernel/bpf/arena.c-1184-\tbpf_map_memcg_enter(\u0026arena-\u003emap, \u0026old_memcg, \u0026new_memcg);\nkernel/bpf/arena.c:1185:\tret = range_tree_clear(\u0026arena-\u003ert, pgoff, page_cnt);\nkernel/bpf/arena.c-1186-\tbpf_map_memcg_exit(old_memcg, new_memcg);\n--\nkernel/bpf/arena.c=1192=static void arena_free_worker(struct work_struct *work)\n--\nkernel/bpf/arena.c-1240-\t\t */\nkernel/bpf/arena.c:1241:\t\tunavail_node = range_tree_set_unavail(\u0026arena-\u003ert, pgoff, page_cnt);\nkernel/bpf/arena.c-1242-\t\tif (!IS_ERR(unavail_node)) {\n--\nkernel/bpf/arena.c-1333-\t\t\t */\nkernel/bpf/arena.c:1334:\t\t\tret = range_tree_make_avail(\u0026arena-\u003ert, pgoff, page_cnt);\nkernel/bpf/arena.c-1335-\t\t\tWARN_ON_ONCE(ret);\n--\nkernel/bpf/range_tree.c-16- * range less or equal requested size.\nkernel/bpf/range_tree.c:17: * range_tree_clear/set() clears or sets a range of bits in this bitmap. The\nkernel/bpf/range_tree.c-18- * adjacent ranges are merged or split at the same time.\n--\nkernel/bpf/range_tree.c-27- * At init time:\nkernel/bpf/range_tree.c:28: *   range_tree_set(rt, 0, max);\nkernel/bpf/range_tree.c-29- * Then:\nkernel/bpf/range_tree.c:30: *   start = range_tree_find(rt, len);\nkernel/bpf/range_tree.c-31- *   if (start \u003e= 0)\nkernel/bpf/range_tree.c:32: *     range_tree_clear(rt, start, len);\nkernel/bpf/range_tree.c-33- * to find free range and mark slots as allocated and later:\nkernel/bpf/range_tree.c:34: *   range_tree_set(rt, start, len);\nkernel/bpf/range_tree.c-35- * to mark as unallocated after use.\n--\nkernel/bpf/range_tree.c=77=static inline struct range_node *__find_range(struct range_tree *rt, u32 len)\n--\nkernel/bpf/range_tree.c-105-\nkernel/bpf/range_tree.c:106:s64 range_tree_find(struct range_tree *rt, u32 len)\nkernel/bpf/range_tree.c-107-{\n--\nkernel/bpf/range_tree.c=162=range_it_iter_first(struct range_tree *rt, u32 start, u32 last)\n--\nkernel/bpf/range_tree.c-167-/* Clear the range in this range tree */\nkernel/bpf/range_tree.c:168:int range_tree_clear(struct range_tree *rt, u32 start, u32 len)\nkernel/bpf/range_tree.c-169-{\n--\nkernel/bpf/range_tree.c-227-/* Is the whole range set ? */\nkernel/bpf/range_tree.c:228:int is_range_tree_set(struct range_tree *rt, u32 start, u32 len)\nkernel/bpf/range_tree.c-229-{\n--\nkernel/bpf/range_tree.c=251=static int range_get_adjacent(struct range_tree *rt, u32 start, u32 last,\n--\nkernel/bpf/range_tree.c-276- */\nkernel/bpf/range_tree.c:277:static int range_tree_merge(struct range_tree *rt, u32 start, u32 last,\nkernel/bpf/range_tree.c-278-\t\tstruct range_node *left, struct range_node *right)\n--\nkernel/bpf/range_tree.c-305-/* Make a range available, possibly merging. */\nkernel/bpf/range_tree.c:306:int range_tree_make_avail(struct range_tree *rt, u32 start, u32 len)\nkernel/bpf/range_tree.c-307-{\n--\nkernel/bpf/range_tree.c-340-\nkernel/bpf/range_tree.c:341:\treturn range_tree_merge(rt, start, last, left, right);\nkernel/bpf/range_tree.c-342-}\n--\nkernel/bpf/range_tree.c-344-/* Set the range in this range tree */\nkernel/bpf/range_tree.c:345:static int range_tree_set(struct range_tree *rt, u32 start, u32 len,\nkernel/bpf/range_tree.c-346-\t\t\t  bool available, struct range_node **new_rnp)\n--\nkernel/bpf/range_tree.c-373-\t/* Clear out everything in the range we want to set. */\nkernel/bpf/range_tree.c:374:\terr = range_tree_clear(rt, start, len);\nkernel/bpf/range_tree.c-375-\tif (err)\n--\nkernel/bpf/range_tree.c-384-\t    (range_available(left) || range_available(right))) {\nkernel/bpf/range_tree.c:385:\t\terr = range_tree_merge(rt, start, last, left, right);\nkernel/bpf/range_tree.c-386-\t\tgoto out_free_new;\n--\nkernel/bpf/range_tree.c-403-\nkernel/bpf/range_tree.c:404:int range_tree_set_avail(struct range_tree *rt, u32 start, u32 len)\nkernel/bpf/range_tree.c-405-{\nkernel/bpf/range_tree.c:406:\treturn range_tree_set(rt, start, len, true, NULL);\nkernel/bpf/range_tree.c-407-}\nkernel/bpf/range_tree.c-408-\nkernel/bpf/range_tree.c:409:struct range_node *range_tree_set_unavail(struct range_tree *rt, u32 start, u32 len)\nkernel/bpf/range_tree.c-410-{\n--\nkernel/bpf/range_tree.c-413-\nkernel/bpf/range_tree.c:414:\terr = range_tree_set(rt, start, len, false, \u0026rn);\nkernel/bpf/range_tree.c-415-\tif (err)\n--\nkernel/bpf/range_tree.c-421-\nkernel/bpf/range_tree.c:422:void range_tree_destroy(struct range_tree *rt)\nkernel/bpf/range_tree.c-423-{\n--\nkernel/bpf/range_tree.c-431-\nkernel/bpf/range_tree.c:432:void range_tree_init(struct range_tree *rt)\nkernel/bpf/range_tree.c-433-{\n--\nkernel/bpf/range_tree.h=13=struct range_node;\nkernel/bpf/range_tree.h-14-\nkernel/bpf/range_tree.h:15:void range_tree_init(struct range_tree *rt);\nkernel/bpf/range_tree.h:16:void range_tree_destroy(struct range_tree *rt);\nkernel/bpf/range_tree.h-17-\nkernel/bpf/range_tree.h:18:int range_tree_clear(struct range_tree *rt, u32 start, u32 len);\nkernel/bpf/range_tree.h:19:int range_tree_set_avail(struct range_tree *rt, u32 start, u32 len);\nkernel/bpf/range_tree.h:20:struct range_node *range_tree_set_unavail(struct range_tree *rt, u32 start, u32 len);\nkernel/bpf/range_tree.h-21-void range_node_mark_available(struct range_node *rn);\nkernel/bpf/range_tree.h:22:int range_tree_make_avail(struct range_tree *rt, u32 start, u32 len);\nkernel/bpf/range_tree.h:23:int is_range_tree_set(struct range_tree *rt, u32 start, u32 len);\nkernel/bpf/range_tree.h:24:s64 range_tree_find(struct range_tree *rt, u32 len);\nkernel/bpf/range_tree.h-25-\n"
}

25/2 2026/10/15 03:46 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 46123
							output: 47
							thoughts: 177
						

Thoughts:
**Analyzing Memory Management Functions**

Alright, let's take a look at this. I see a cluster of functions here that immediately jump out at me as related to memory management, specifically within an arena-based system. We've got: `arena_vm_fault`, likely handling page faults; `arena_free_pages`, and `arena_free_worker`, suggesting freeing operations and potentially a background worker thread; functions for allocation, like `arena_map_alloc`, `arena_map_free`, and `arena_map_get_file`, which looks like they interact with a mapping structure; and of course `zap_pages`, a lower-level page clearing function. Then, the `range_tree` family: `range_tree_set_avail`, `range_tree_set_unavail`, `range_tree_make_avail`, `range_tree_clear`, and `range_node_mark_available` are all tell-tale signs of a range-based allocator, probably managing page availability within this arena. The presence of `bpf_arena_alloc_pages` and `bpf_arena_free_pages` in particular, suggests that the BPF subsystem is also using this arena-based memory allocation strategy.

Okay, my immediate instinct is to confirm that these `bpf_arena` functions are truly part of the BPF arena implementation. I'll need to verify if these symbols, `bpf_arena_alloc_pages` and `bpf_arena_free_pages`, are actually defined within `kernel/bpf/arena.c`. That's the next logical step.



26/2 2026/10/15 03:46 tool grepper
0m Args:
{
  "Expression": "^(__bpf_kfunc|void \\*|void).*bpf_arena_",
  "PathPrefixes": [
    "kernel/bpf/arena.c"
  ]
}

Results:
{
  "Output": "kernel/bpf/arena.c=1356=__bpf_kfunc_start_defs();\nkernel/bpf/arena.c-1357-\nkernel/bpf/arena.c:1358:__bpf_kfunc void *bpf_arena_alloc_pages(void *p__map, void *addr__ign, u32 page_cnt,\nkernel/bpf/arena.c-1359-\t\t\t\t\tint node_id, u64 flags)\n--\nkernel/bpf/arena.c-1369-\nkernel/bpf/arena.c:1370:void *bpf_arena_alloc_pages_non_sleepable(void *p__map, void *addr__ign, u32 page_cnt,\nkernel/bpf/arena.c-1371-\t\t\t\t\t  int node_id, u64 flags)\n--\nkernel/bpf/arena.c-1381-\nkernel/bpf/arena.c:1382:void *bpf_arena_alloc_pages_sleepable(void *p__map, void *addr__ign, u32 page_cnt,\nkernel/bpf/arena.c-1383-\t\t\t\t      int node_id, u64 flags)\n--\nkernel/bpf/arena.c-1393-\nkernel/bpf/arena.c:1394:__bpf_kfunc void bpf_arena_free_pages(void *p__map, void *ptr__ign, u32 page_cnt)\nkernel/bpf/arena.c-1395-{\n--\nkernel/bpf/arena.c-1403-\nkernel/bpf/arena.c:1404:void bpf_arena_free_pages_non_sleepable(void *p__map, void *ptr__ign, u32 page_cnt)\nkernel/bpf/arena.c-1405-{\n--\nkernel/bpf/arena.c-1413-\nkernel/bpf/arena.c:1414:__bpf_kfunc int bpf_arena_reserve_pages(void *p__map, void *ptr__ign, u32 page_cnt)\nkernel/bpf/arena.c-1415-{\n"
}

27/2 2026/10/15 03:46 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 47252
							output: 35
							thoughts: 586
						

Thoughts:
**My Assessment of Relevant BPF Arena Functions**

Okay, let's break this down. My initial assessment identifies several key functions related to the BPF arena implementation. Specifically, I see `bpf_arena_alloc_pages` and `bpf_arena_free_pages` as exported kfuncs, the `arena_vm_fault` as the fault handler, and `arena_free_worker` as the workqueue function. Also, `arena_free_pages` looks like an internal helper for freeing pages. Then there's the mapping functions: `arena_map_alloc`, `arena_map_free`, `arena_map_get_file`, along with `zap_pages` and the range tree functions `range_tree_set_avail`, `range_tree_set_unavail`, `range_tree_make_avail`, and `range_tree_clear`.

Now, I'm considering if `bpf_map_new_fd` should be a focus. While it's called on every BPF map creation, making it relatively ubiquitous, it calls `map_get_file` internally. However, `arena_map_get_file` seems to be the arena-specific implementation, which is more relevant to this specific area of interest.

Let's review the guidelines in Section 4 to make sure this meets the criteria. The guideline "AVOID UBIQUITOUS LIFECYCLE HOT-PATHS" advises against including very generic functions. Thankfully, `arena_vm_fault` is specific to arena VMAs; it's not a general page fault handler, so it should be fine. The guideline "TARGET SPECIFIC FEATURE LOGIC AND ENTRYPOINTS" favors listing functions that implement specific logic or are direct entrypoints for the subsystem. The list of functions that seem to meet this requirement are: `arena_vm_fault`, `arena_free_pages`, `arena_free_worker`, `zap_pages`, `arena_map_alloc`, `arena_map_free`, `arena_map_get_file`, `bpf_arena_alloc_pages`, `bpf_arena_free_pages`, `range_tree_set_avail`, `range_tree_set_unavail`, `range_tree_make_avail`, and `range_tree_clear`.

Finally, configuration. I need to make sure I haven't missed any required configurations. The obvious ones are `BPF_SYSCALL` and `BPF_JIT`. Let me check includes/uses in `kernel/bpf/arena.c`: it includes `anon_inodes.h`, which is selected by `CONFIG_ANON_INODES`, which itself is selected by `BPF_SYSCALL`. I'll want to verify this using the Kconfig select statements for `BPF_SYSCALL`.



28/2 2026/10/15 03:46 tool grepper
0m Args:
{
  "Expression": "config BPF_SYSCALL",
  "PathPrefixes": [
    "kernel/bpf/Kconfig"
  ]
}

Results:
{
  "Output": "kernel/bpf/Kconfig=29=menu \"BPF subsystem\"\nkernel/bpf/Kconfig-30-\nkernel/bpf/Kconfig:31:config BPF_SYSCALL\nkernel/bpf/Kconfig-32-\tbool \"Enable bpf() system call\"\n"
}

29/2 2026/10/15 03:46 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 48562
							output: 34
							thoughts: 34
						

Thoughts:
Okay, here's my interpretation of that thought process, tailored for an expert audience, and written in the first person:

**Investigating BPF_SYSCALL in the Kernel Configuration**

Alright, I need to get a handle on how `BPF_SYSCALL` is handled in the kernel config. My focus is on understanding its dependencies and selections within the broader BPF context. I'm thinking I should jump into the `kernel/bpf/Kconfig` file, specifically around line 31. That area should give me a solid overview of what `BPF_SYSCALL` either *selects* or *depends on*. This investigation should help me to understand any potential build-time implications or prerequisites for enabling this specific BPF syscall feature.



30/2 2026/10/15 03:46 tool read-file
0m Args:
{
  "File": "kernel/bpf/Kconfig",
  "FirstLine": 30,
  "LineCount": 35
}

Results:
{
  "Contents": "  30:\t\n  31:\tconfig BPF_SYSCALL\n  32:\t\tbool \"Enable bpf() system call\"\n  33:\t\tselect BPF\n  34:\t\tselect IRQ_WORK\n  35:\t\tselect NEED_TASKS_RCU\n  36:\t\tselect TASKS_TRACE_RCU\n  37:\t\tselect BINARY_PRINTF\n  38:\t\tselect NET_SOCK_MSG if NET\n  39:\t\tselect NET_XGRESS if NET\n  40:\t\tselect PAGE_POOL if NET\n  41:\t\tdefault n\n  42:\t\thelp\n  43:\t\t  Enable the bpf() system call that allows to manipulate BPF programs\n  44:\t\t  and maps via file descriptors.\n  45:\t\n  46:\tconfig BPF_JIT\n  47:\t\tbool \"Enable BPF Just In Time compiler\"\n  48:\t\tdepends on BPF\n  49:\t\tdepends on HAVE_CBPF_JIT || HAVE_EBPF_JIT\n  50:\t\tselect EXECMEM\n  51:\t\thelp\n  52:\t\t  BPF programs are normally handled by a BPF interpreter. This option\n  53:\t\t  allows the kernel to generate native code when a program is loaded\n  54:\t\t  into the kernel. This will significantly speed-up processing of BPF\n  55:\t\t  programs.\n  56:\t\n  57:\t\t  Note, an admin should enable this feature changing:\n  58:\t\t  /proc/sys/net/core/bpf_jit_enable\n  59:\t\t  /proc/sys/net/core/bpf_jit_harden   (optional)\n  60:\t\t  /proc/sys/net/core/bpf_jit_kallsyms (optional)\n  61:\t\n  62:\tconfig BPF_JIT_ALWAYS_ON\n  63:\t\tbool \"Permanently enable BPF JIT and remove BPF interpreter\"\n  64:\t\tdepends on BPF_SYSCALL \u0026\u0026 HAVE_EBPF_JIT \u0026\u0026 BPF_JIT\n"
}

31/2 2026/10/15 03:46 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 49314
							output: 19
							thoughts: 18
						

Thoughts:
Okay, here's my take on those thoughts, tailored for an expert audience, presented in the first person:

**Investigating the Implementation of `ANON_INODES`**

Right, so `ANON_INODES`... that's always a point of interest. My immediate thought is, "Who's actually making the call on how this is handled?" Is it the kernel itself, the filesystem driver, some configuration option, or perhaps a higher-level abstraction layer that's responsible for the selection or definition of it? I need to quickly identify the authority and control-flow involved. This will be the key to understanding its full lifecycle and any potential vulnerabilities or performance implications. Understanding the "who" is fundamental for going deeper.



32/2 2026/10/15 03:46 tool grepper
0m Error:
no matches

Args:
{
  "Expression": "config ANON_INODES"
}

Results:
{
  "error": "no matches"
}

33/2 2026/10/15 03:46 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 49520
							output: 19
							thoughts: 22
						

Thoughts:
Okay, let's see...

**Checking the Source for `anon_inode`**

Right, where are we with this? I need to understand where `anon_inode` is defined and how it's used. Since it's filesystem-related, the most logical first place to look is within the `fs` directory. Given the project structure, I'm thinking the build configuration files are going to be key to finding what I'm looking for - so, `Makefile` and `Kconfig` files are the place to start digging. Let's see if either of those files holds any clues about `anon_inode`. My instincts tell me that either one of these will lead me down the right path.



34/2 2026/10/15 03:46 tool grepper
0m Args:
{
  "Expression": "anon_inodes\\.o"
}

Results:
{
  "Output": "fs/Makefile=25=obj-$(CONFIG_EPOLL)\t\t+= eventpoll.o\nfs/Makefile:26:obj-y\t\t\t\t+= anon_inodes.o\nfs/Makefile-27-obj-$(CONFIG_SIGNALFD)\t\t+= signalfd.o\n"
}

35/2 2026/10/15 03:46 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 49786
							output: 279
							thoughts: 459
						

Thoughts:
**My Assessment of the BPF Arena Patch**

Okay, so `anon_inodes.o` being `obj-y` tells me that `CONFIG_BPF_SYSCALL` and `CONFIG_BPF_JIT` are the primary configurations required for this patch. Given that we're likely on an amd64 system, `CONFIG_64BIT` and `CONFIG_MMU` are a given. So, `BPF_SYSCALL` and `BPF_JIT` are the crucial configs we need to enable.

Now, let's look at the parameters for `set-results`. We need:

*   `WorthFuzzing`: True, obviously.
*   `EnableConfigs`: `["BPF_SYSCALL", "BPF_JIT"]` - those are the configs. Check.
*   `FocusSymbols`: I've got a good list of critical symbols: `arena_vm_fault`, `arena_free_pages`, `arena_free_worker`, `zap_pages`, `arena_map_alloc`, `arena_map_free`, `arena_map_get_file`, `bpf_arena_alloc_pages`, `bpf_arena_free_pages`, `range_tree_set_avail`, `range_tree_set_unavail`, `range_tree_make_avail`, `range_tree_clear` - these seem to cover the core areas. Check.
*   `Reasoning`: The patch itself modifies the BPF arena's implementation, involving address space mapping and the underlying range tree allocator. It looks like it introduces a new synchronization mechanism (`opref` tracking and waitqueue), switches user mapping invalidation to rmap walk, incorporates folio locking, and adds state tracking and retry logic for deferred span freeing, and updates the range tree to support tracking unavailable ranges. This definitely hits a complex area with concurrency and locking interactions within the core memory management and BPF code, which justifies fuzzing. Check.

Let me take another quick glance. Alright, everything looks correct and complete. The configuration and reasoning are all solid. We're good to go. Time to call `set-results`.



36/2 2026/10/15 03:46 tool set-results
0m Args:
{
  "EnableConfigs": [
    "BPF_SYSCALL",
    "BPF_JIT"
  ],
  "FocusSymbols": [
    "arena_vm_fault",
    "arena_free_pages",
    "arena_free_worker",
    "zap_pages",
    "arena_map_alloc",
    "arena_map_free",
    "arena_map_get_file",
    "bpf_arena_alloc_pages",
    "bpf_arena_free_pages",
    "range_tree_set_avail",
    "range_tree_set_unavail",
    "range_tree_make_avail",
    "range_tree_clear"
  ],
  "Reasoning": "The patch refactors the BPF arena memory management subsystem and its range tree tracking. It redesigns the concurrency control between page fault handling and page freeing/zapping by introducing an opref counter and waitqueue, utilizes the address space rmap tree lock for zapping user VMA mappings, adopts folio locking during fault admission, introduces state tracking for deferred freeing in the worker, and adds support for unavailable ranges in the range tree allocator. These changes modify reachable core BPF and memory management paths with complex concurrency and new assertions, making them high-priority targets for fuzzing.",
  "WorthFuzzing": true
}

Results:
{
  "EnableConfigs": [
    "BPF_SYSCALL",
    "BPF_JIT"
  ],
  "FocusSymbols": [
    "arena_vm_fault",
    "arena_free_pages",
    "arena_free_worker",
    "zap_pages",
    "arena_map_alloc",
    "arena_map_free",
    "arena_map_get_file",
    "bpf_arena_alloc_pages",
    "bpf_arena_free_pages",
    "range_tree_set_avail",
    "range_tree_set_unavail",
    "range_tree_make_avail",
    "range_tree_clear"
  ],
  "Reasoning": "The patch refactors the BPF arena memory management subsystem and its range tree tracking. It redesigns the concurrency control between page fault handling and page freeing/zapping by introducing an opref counter and waitqueue, utilizes the address space rmap tree lock for zapping user VMA mappings, adopts folio locking during fault admission, introduces state tracking for deferred freeing in the worker, and adds support for unavailable ranges in the range tree allocator. These changes modify reachable core BPF and memory management paths with complex concurrency and new assertions, making them high-priority targets for fuzzing.",
  "WorthFuzzing": true
}

37/1 2026/10/15 03:46 action If
1m Args:
{
  "WorthFuzzing": true
}

Results:
null

38/2 2026/10/15 03:46 agent kmsan-evaluator
1m Model:
core

Args:
null

Results:
{
  "KMSANReasoning": "The patch series refactors concurrency management, page fault handling, and page freeing logic for BPF arena maps (BPF_MAP_TYPE_ARENA). Specifically, it introduces an anonymous backing file with address_space_operations for rmap-based page zapping (eliminating VMA list lock inversion), an atomic operation reference counter (arena_opref) and wait queue to synchronize faults against frees, range availability tracking in the range tree (range_node available flag, range_tree_set_unavail, range_tree_make_avail), folio locking during fault admission, and state flags for deferred free spans.\n\nPotential bugs introduced or affected by these changes are concurrency bugs, use-after-free (e.g. accessing freed pages or range/span nodes during races), invalid/double free, or deadlock/locking issues. These failure modes are reliably detected by standard KASAN and LOCKDEP configurations.\n\nKMSAN is not applicable here because:\n1. No uninitialized memory or kernel structures are copied or leaked to user space (arena_map_get_file creates a cloned struct file returned via FD_ADD as a standard file descriptor integer).\n2. All newly added or modified data structures (struct range_node, struct arena_free_span) have all their fields explicitly assigned upon allocation before insertion into rb-trees or lockless lists.\n3. No branching or conditional logic depends on uninitialized scalar variables or struct padding.\n4. Memory buffer bounds and lengths remain standard page-aligned calculations and do not expose uninitialized memory reads.\n\nBecause there are no uninitialized memory access risks that would evade KASAN and require KMSAN, a dedicated KMSAN fuzzing session is not warranted.",
  "NeedsKMSAN": false
}

Instruction:
You are an expert Linux kernel security engineer specializing in kernel memory
error detectors (KASAN and KMSAN). Your job is to review the provided patch series and
determine if the code changes justify spawning a dedicated KMSAN (KernelMemorySanitizer)
fuzzing session in addition to standard KASAN fuzzing.

CRITICAL DISTINCTION BETWEEN KASAN AND KMSAN:
- Standard KASAN kernel builds (upstream-apparmor-kasan.config) already enable
  a comprehensive suite of debugging tools and sanitizers, including KASAN
  (out-of-bounds accesses, use-after-free, double free, invalid free), LOCKDEP
  (locking bugs and deadlocks), UB-sanitizers, and memory corruption checks.
- KMSAN (KernelMemorySanitizer) detects reads of UNINITIALIZED memory (stack, heap,
  or page allocations) and kernel-to-user memory info-leaks.

Rule: THERE IS NO SENSE IN RUNNING A KMSAN SESSION IF A BUG CAN BE CAUGHT BY KASAN,
LOCKDEP, OR OTHER STANDARD BUG DETECTORS.
A dedicated KMSAN fuzzing session incurs significant resource costs. You must ONLY
set NeedsKMSAN=true if the code changes introduce or expose UNINITIALIZED MEMORY risks
that are detected ONLY by KMSAN.

Look holistically at the patch series and surrounding code. Even if no direct
uninitialized field accesses or new buffer allocations are added in the diff itself,
a patch may alter control flow, bounds checking, or data length calculations in ways
that change how the rest of the code operates on existing buffers (e.g. allowing
uninitialized stack/heap memory to be read, copied to user space, or used in control
flow). Do not hesitate to use your code access tools to inspect the surrounding code,
called functions, and callers.

Set NeedsKMSAN=true ONLY IF the patch introduces or modifies:
1. Kernel structures sent to user space (via copy_to_user, put_user, netlink skb
   attributes, ioctl output arguments, socket options, or BPF buffers) where fields
   or structure padding might not be fully initialized/zeroed.
2. Conditional logic or branching that depends on potentially uninitialized variables
   or struct fields.
3. Allocation or initialization of complex data structures where uninitialized fields
   could be read later in reachable code paths.
4. Bounds checks, lengths, or logic in a way that allows surrounding code to access
   uninitialized bytes of existing buffers.

Set NeedsKMSAN=false IF:
- The code changes primarily risk out-of-bounds access, array overflows, NULL pointer
  dereferences, locking deadlocks, or use-after-free bugs (these are already caught
  by KASAN, LOCKDEP, or standard bug detectors).
- All stack/heap structures touched or introduced by the patch are fully zeroed
  or initialized (e.g. using = {0}, memset, kzalloc) before being read or copied.
- The patch does not introduce any risk of uninitialized memory usage or info-leaks.

Use your code access tools to inspect the surrounding code if necessary, then provide
detailed KMSANReasoning contrasting KASAN vs KMSAN applicability for this patch.
Prefer calling several tools at the same time to save round-trips.


Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.

Prompt:
Target architecture: amd64

For your convenience, here is the diff of the changes:
commit 456b159a4993a650829f5000345b42c15f99ab55
Author: syz-cluster <triage@syzkaller.com>
Date:   Thu Oct 15 03:44:37 2026 +0000

    syz-cluster: applied patch under review

diff --git a/include/linux/bpf.h b/include/linux/bpf.h
index 54144372281cb..fd2986686d629 100644
--- a/include/linux/bpf.h
+++ b/include/linux/bpf.h
@@ -89,6 +89,7 @@ struct bpf_map_ops {
 	/* funcs callable from userspace (via syscall) */
 	int (*map_alloc_check)(union bpf_attr *attr);
 	struct bpf_map *(*map_alloc)(union bpf_attr *attr);
+	struct file *(*map_get_file)(struct bpf_map *map, int flags);
 	void (*map_release)(struct bpf_map *map, struct file *map_file);
 	void (*map_free)(struct bpf_map *map);
 	void (*map_free_pre_rcu)(struct bpf_map *map);
diff --git a/kernel/bpf/arena.c b/kernel/bpf/arena.c
index 0ff707707da04..899ad275ac7f5 100644
--- a/kernel/bpf/arena.c
+++ b/kernel/bpf/arena.c
@@ -1,15 +1,20 @@
 // SPDX-License-Identifier: GPL-2.0-only
 /* Copyright (c) 2024 Meta Platforms, Inc. and affiliates. */
+#include <linux/anon_inodes.h>
+#include <linux/atomic.h>
+#include <linux/bits.h>
 #include <linux/bpf.h>
 #include <linux/btf.h>
 #include <linux/cacheflush.h>
 #include <linux/err.h>
+#include <linux/fs.h>
 #include <linux/irq_work.h>
 #include "linux/filter.h"
 #include <linux/llist.h>
 #include <linux/btf_ids.h>
 #include <linux/vmalloc.h>
 #include <linux/pagemap.h>
+#include <linux/wait.h>
 #include <asm/tlbflush.h>
 #include "range_tree.h"
 
@@ -53,17 +58,18 @@ struct bpf_arena {
 	u64 user_vm_start;
 	u64 user_vm_end;
 	struct vm_struct *kern_vm;
+	struct file *file;
 	struct page *scratch_page;
 	struct range_tree rt;
 	/* protects rt and nr_pages */
 	rqspinlock_t spinlock;
+	atomic_t opref;
+	wait_queue_head_t opwait;
 	/* number of pages currently populated in the arena */
 	u64 nr_pages;
 	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;
@@ -72,10 +78,48 @@ struct bpf_arena {
 static void arena_free_worker(struct work_struct *work);
 static void arena_free_irq(struct irq_work *iw);
 
+/* Positive references admit frees, negative references admit faults. */
+enum arena_opref {
+	ARENA_OPREF_FREE = 1,
+	ARENA_OPREF_FAULT = -1,
+};
+
+static bool arena_opref_get(struct bpf_arena *arena, enum arena_opref ref)
+{
+	int users = atomic_read(&arena->opref);
+
+	do {
+		if (users && (users ^ ref) < 0)
+			return false;
+	} while (!atomic_try_cmpxchg_acquire(&arena->opref, &users, users + ref));
+	return true;
+}
+
+static void arena_opref_put(struct bpf_arena *arena, enum arena_opref ref)
+{
+	if (atomic_fetch_sub_release(ref, &arena->opref) == ref)
+		wake_up_all(&arena->opwait);
+}
+
+/*
+ * Zero flags denote an unstarted free. ZAPPED implies CLEARED, and FAILED
+ * is a terminal pre-clear failure set alone. RESERVED tracks ownership
+ * independently of cleanup progress.
+ * Each span has a single owner until it is published on free_spans, so flag
+ * updates do not need atomic bit operations.
+ */
+enum arena_free_span_flags {
+	ARENA_FREE_SPAN_CLEARED = BIT(0),	/* Kernel PTEs cleared */
+	ARENA_FREE_SPAN_ZAPPED = BIT(1),	/* Kernel TLB flushed and user mappings zapped */
+	ARENA_FREE_SPAN_RESERVED = BIT(2),	/* Owns an unavailable range */
+	ARENA_FREE_SPAN_FAILED = BIT(3),	/* Freeing operation cannot continue */
+};
+
 struct arena_free_span {
 	struct llist_node node;
 	unsigned long uaddr;
 	u32 page_cnt;
+	unsigned int flags;
 };
 
 u64 bpf_arena_get_kern_vm_start(struct bpf_arena *arena)
@@ -201,6 +245,9 @@ static int apply_range_set_cb(pte_t *pte, unsigned long addr, void *data)
 		return -EBUSY;
 	set_pte_at(&init_mm, addr, pte, pteval);
 #endif
+	page_folio(page)->index = compute_pgoff(d->arena,
+						addr - bpf_arena_get_kern_vm_start(d->arena));
+	page->mapping = d->arena->file->f_mapping;
 	WARN_ON_ONCE(llist_del_first(d->pages) != node);
 	d->i++;
 	WRITE_ONCE(d->arena->nr_pages, d->arena->nr_pages + 1);
@@ -268,6 +315,20 @@ static int populate_pgtable_except_pte(struct bpf_arena *arena)
 				   SZ_4G + GUARD_SZ / 2, apply_range_set_cb, NULL);
 }
 
+/* The backing file must not hold a map reference. */
+static const struct file_operations arena_backing_fops = {};
+
+/* Arena pages are not page-cache entries and must not be evicted by MM. */
+static bool arena_release_folio(struct folio *folio, gfp_t gfp)
+{
+	return false;
+}
+
+static const struct address_space_operations arena_aops = {
+	.dirty_folio = noop_dirty_folio,
+	.release_folio = arena_release_folio,
+};
+
 static struct bpf_map *arena_map_alloc(union bpf_attr *attr)
 {
 	struct vm_struct *kern_vm;
@@ -322,16 +383,26 @@ static struct bpf_map *arena_map_alloc(union bpf_attr *attr)
 		goto err_free_arena;
 
 	range_tree_init(&arena->rt);
-	err = range_tree_set(&arena->rt, 0, attr->max_entries);
+	err = range_tree_set_avail(&arena->rt, 0, attr->max_entries);
 	if (err)
 		goto err_free_scratch;
 	mutex_init(&arena->lock);
-	mutex_init(&arena->zap_mutex);
 	raw_res_spin_lock_init(&arena->spinlock);
+	atomic_set(&arena->opref, 0);
+	init_waitqueue_head(&arena->opwait);
 	err = populate_pgtable_except_pte(arena);
 	if (err)
 		goto err_destroy_rt;
 
+	arena->file = anon_inode_create_getfile("bpf-map", &arena_backing_fops,
+						NULL, O_RDWR, NULL);
+	if (IS_ERR(arena->file)) {
+		err = PTR_ERR(arena->file);
+		goto err_destroy_rt;
+	}
+	arena->file->f_mapping->a_ops = &arena_aops;
+	mapping_set_release_always(arena->file->f_mapping);
+
 	return &arena->map;
 
 err_destroy_rt:
@@ -345,6 +416,14 @@ static struct bpf_map *arena_map_alloc(union bpf_attr *attr)
 	return ERR_PTR(err);
 }
 
+static void arena_put_page(struct page *page)
+{
+	lock_page(page);
+	page->mapping = NULL;
+	unlock_page(page);
+	__free_page(page);
+}
+
 static int existing_page_cb(pte_t *ptep, unsigned long addr, void *data)
 {
 	struct bpf_arena *arena = data;
@@ -368,13 +447,15 @@ static int existing_page_cb(pte_t *ptep, unsigned long addr, void *data)
 	 * the TLB entries can stick around and continue to permit access to
 	 * the freed page. So it all relies on 1.
 	 */
-	__free_page(page);
+	arena_put_page(page);
 	return 0;
 }
 
 static void arena_map_free(struct bpf_map *map)
 {
 	struct bpf_arena *arena = container_of(map, struct bpf_arena, map);
+	struct llist_node *pos, *next;
+	struct arena_free_span *s;
 
 	/*
 	 * Check that user vma-s are not around when bpf map is freed.
@@ -385,9 +466,18 @@ static void arena_map_free(struct bpf_map *map)
 	if (WARN_ON_ONCE(!list_empty(&arena->vma_list)))
 		return;
 
-	/* Ensure no pending deferred frees */
+	/*
+	 * No callers remain. Drain the IRQ callback, then stop the worker,
+	 * including any attempts to requeue itself during teardown.
+	 */
 	irq_work_sync(&arena->free_irq);
-	flush_work(&arena->free_work);
+	disable_work_sync(&arena->free_work);
+
+	/* Remaining mapped pages are reclaimed by the page-table walk below. */
+	llist_for_each_safe(pos, next, llist_del_all(&arena->free_spans)) {
+		s = llist_entry(pos, struct arena_free_span, node);
+		kfree_nolock(s);
+	}
 
 	/*
 	 * free_vm_area() calls remove_vm_area() that calls free_unmap_vmap_area().
@@ -400,6 +490,7 @@ static void arena_map_free(struct bpf_map *map)
 	free_vm_area(arena->kern_vm);
 	range_tree_destroy(&arena->rt);
 	__free_page(arena->scratch_page);
+	fput(arena->file);
 	bpf_map_area_free(arena);
 }
 
@@ -428,10 +519,8 @@ static u64 arena_map_mem_usage(const struct bpf_map *map)
 }
 
 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)
@@ -443,8 +532,6 @@ static int remember_vma(struct bpf_arena *arena, struct vm_area_struct *vma)
 		return -ENOMEM;
 	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;
 }
@@ -487,13 +574,22 @@ static vm_fault_t arena_vm_fault(struct vm_fault *vmf)
 	struct bpf_arena *arena = container_of(map, struct bpf_arena, map);
 	struct mem_cgroup *new_memcg, *old_memcg;
 	LLIST_HEAD(pages);
-	struct page *page, *new_page = NULL;
 	struct apply_range_data data;
 	vm_fault_t fault_ret;
+	struct page *page, *new_page = NULL;
 	long kbase, kaddr;
 	unsigned long flags;
 	int ret;
 
+	if (!arena_opref_get(arena, ARENA_OPREF_FAULT)) {
+		if (vmf->flags & FAULT_FLAG_ALLOW_RETRY)
+			goto retry;
+		/* zap_pages() does not need the fault caller's mmap_lock. */
+		wait_event(arena->opwait, arena_opref_get(arena, ARENA_OPREF_FAULT));
+	}
+	/* folio_lock_or_retry() may drop the VMA lock before we release opref. */
+	bpf_map_inc(map);
+
 	kbase = bpf_arena_get_kern_vm_start(arena);
 	kaddr = kbase + (u32)(vmf->address);
 
@@ -511,15 +607,15 @@ static vm_fault_t arena_vm_fault(struct vm_fault *vmf)
 		bpf_map_memcg_exit(old_memcg, new_memcg);
 	}
 
-	if (raw_res_spin_lock_irqsave(&arena->spinlock, flags)) {
-		/*
-		 * A failed lock means a possible deadlock was detected. Don't
-		 * return VM_FAULT_RETRY: this handler never took mmap_lock, but
-		 * the fault path would re-take it on retry and deadlock. Fail.
-		 */
-		if (new_page)
-			free_pages_nolock(new_page, 0);
-		return VM_FAULT_SIGBUS;
+	ret = raw_res_spin_lock_irqsave(&arena->spinlock, flags);
+	if (ret) {
+		/* If we are deadlocking somehow, no way to ensure forward progress. */
+		if (ret == -EDEADLK) {
+			fault_ret = VM_FAULT_SIGBUS;
+			goto out_err;
+		}
+
+		goto retry_admitted;
 	}
 
 	page = vmalloc_to_page((void *)kaddr);
@@ -547,8 +643,8 @@ static vm_fault_t arena_vm_fault(struct vm_fault *vmf)
 
 	if (!new_page) {
 		/*
-		 * The probed page was freed meanwhile or preallocation failed;
-		 * try the non-blocking allocator, we cannot sleep here.
+		 * Preallocation failed; try the non-blocking allocator since
+		 * we cannot sleep here.
 		 */
 		new_page = bpf_alloc_page(map->numa_node, false);
 		if (!new_page) {
@@ -558,7 +654,16 @@ static vm_fault_t arena_vm_fault(struct vm_fault *vmf)
 	}
 
 	ret = range_tree_clear(&arena->rt, vmf->pgoff, 1);
-	if (ret) {
+	/* If a range is unavailable, try again. */
+	if (ret == -EAGAIN) {
+		/* Non-retryable GUP callers recheck the PTE on NOPAGE. */
+		if (!(vmf->flags & FAULT_FLAG_ALLOW_RETRY)) {
+			fault_ret = VM_FAULT_NOPAGE;
+			goto out_err_locked_memcg;
+		}
+		raw_res_spin_unlock_irqrestore(&arena->spinlock, flags);
+		goto retry_memcg;
+	} else if (ret) {
 		fault_ret = VM_FAULT_SIGBUS;
 		goto out_err_locked_memcg;
 	}
@@ -570,7 +675,7 @@ static vm_fault_t arena_vm_fault(struct vm_fault *vmf)
 	ret = apply_to_page_range(&init_mm, kaddr, PAGE_SIZE, apply_range_set_cb, &data);
 	if (ret) {
 		llist_del_first(&pages);
-		range_tree_set(&arena->rt, vmf->pgoff, 1);
+		range_tree_set_avail(&arena->rt, vmf->pgoff, 1);
 		fault_ret = VM_FAULT_SIGBUS;
 		goto out_err_locked_memcg;
 	}
@@ -580,20 +685,52 @@ static vm_fault_t arena_vm_fault(struct vm_fault *vmf)
 	page = new_page;
 	new_page = NULL;
 out:
-	page_ref_add(page, 1);
+	/* Hand fault admission over to the folio lock before returning to MM. */
+	get_page(page);
 	raw_res_spin_unlock_irqrestore(&arena->spinlock, flags);
-	if (new_page)
+
+	if (new_page) {
 		free_pages_nolock(new_page, 0);
-	vmf->page = page;
-	return 0;
+		new_page = NULL;
+	}
+
+	fault_ret = folio_lock_or_retry(page_folio(page), vmf);
+	if (fault_ret) {
+		put_page(page);
+	} else {
+		vmf->page = page;
+		fault_ret = VM_FAULT_LOCKED;
+	}
+	goto out_put;
 
 out_err_locked_memcg:
 	bpf_map_memcg_exit(old_memcg, new_memcg);
 out_err_locked:
 	raw_res_spin_unlock_irqrestore(&arena->spinlock, flags);
+out_err:
 	if (new_page)
 		free_pages_nolock(new_page, 0);
+out_put:
+	arena_opref_put(arena, ARENA_OPREF_FAULT);
+	bpf_map_put(map);
 	return fault_ret;
+
+retry_memcg:
+	bpf_map_memcg_exit(old_memcg, new_memcg);
+retry_admitted:
+	arena_opref_put(arena, ARENA_OPREF_FAULT);
+	bpf_map_put(map);
+retry:
+	if (new_page)
+		free_pages_nolock(new_page, 0);
+
+	if (!(vmf->flags & FAULT_FLAG_ALLOW_RETRY))
+		return VM_FAULT_SIGBUS;
+
+	if (!(vmf->flags & FAULT_FLAG_RETRY_NOWAIT))
+		release_fault_lock(vmf);
+
+	return VM_FAULT_RETRY;
 }
 
 static const struct vm_operations_struct arena_vm_ops = {
@@ -638,6 +775,20 @@ static unsigned long arena_get_unmapped_area(struct file *filp, unsigned long ad
 	return round_up(ret, SZ_4G);
 }
 
+static struct file *arena_map_get_file(struct bpf_map *map, int flags)
+{
+	struct bpf_arena *arena = container_of(map, struct bpf_arena, map);
+	struct file *file;
+
+	file = alloc_file_clone(arena->file, flags & (O_ACCMODE | O_NONBLOCK),
+				&bpf_map_fops);
+	if (!IS_ERR(file)) {
+		file->private_data = map;
+		file_set_fsnotify_mode(file, FMODE_NONOTIFY);
+	}
+	return file;
+}
+
 static int arena_map_mmap(struct bpf_map *map, struct vm_area_struct *vma)
 {
 	struct bpf_arena *arena = container_of(map, struct bpf_arena, map);
@@ -692,6 +843,7 @@ BTF_ID_LIST_SINGLE(bpf_arena_map_btf_ids, struct, bpf_arena)
 const struct bpf_map_ops arena_map_ops = {
 	.map_meta_equal = bpf_map_meta_equal,
 	.map_alloc = arena_map_alloc,
+	.map_get_file = arena_map_get_file,
 	.map_free = arena_map_free,
 	.map_direct_value_addr = arena_map_direct_value_addr,
 	.map_mmap = arena_map_mmap,
@@ -813,7 +965,7 @@ static long arena_alloc_pages(struct bpf_arena *arena, long uaddr, long page_cnt
 out_unmap:
 	/* Error handling: Undo partial mappings. */
 	flush_vmap_cache(kern_vm_start + uaddr32, mapped << PAGE_SHIFT);
-	range_tree_set(&arena->rt, pgoff + mapped, page_cnt - mapped);
+	range_tree_set_avail(&arena->rt, pgoff + mapped, page_cnt - mapped);
 	raw_res_spin_unlock_irqrestore(&arena->spinlock, flags);
 	if (mapped)
 		arena_free_pages(arena, uaddr32, mapped, sleepable);
@@ -835,65 +987,35 @@ 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)
 {
+	struct address_space *mapping = arena->file->f_mapping;
 	unsigned long size = (unsigned long)page_cnt << PAGE_SHIFT;
+	pgoff_t first = compute_pgoff(arena, uaddr);
+	pgoff_t last = first + page_cnt - 1;
 	struct vm_area_struct *vma;
-	struct mm_struct *mm;
-	struct vma_list *vml;
-	unsigned long vm_start;
-	u64 my_gen;
 
-	/*
-	 * 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);
+	/* The mapping lock keeps VMAs stable without taking mmap_lock. */
+	i_mmap_lock_read(mapping);
+	mapping_rmap_tree_foreach(vma, mapping, first, last) {
+		if (vma->vm_ops != &arena_vm_ops ||
+		    vma->vm_file->private_data != &arena->map)
+			continue;
+		zap_vma_range(vma, uaddr, size);
 	}
-	mutex_unlock(&arena->lock);
-	mutex_unlock(&arena->zap_mutex);
+	i_mmap_unlock_read(mapping);
+}
+
+static void wait_for_faults(struct llist_head *pages)
+{
+	struct page *page;
+
+	llist_for_each_entry(page, pages->first, pcp_llist)
+		folio_wait_locked(page_folio(page));
 }
 
 static void arena_free_pages(struct bpf_arena *arena, long uaddr, long page_cnt, bool sleepable)
 {
 	struct mem_cgroup *new_memcg, *old_memcg;
+	struct range_node *unavail_node = NULL;
 	u64 full_uaddr, uaddr_end;
 	long kaddr, pgoff;
 	struct page *page;
@@ -902,6 +1024,7 @@ static void arena_free_pages(struct bpf_arena *arena, long uaddr, long page_cnt,
 	struct arena_free_span *s;
 	struct clear_range_data cdata;
 	unsigned long flags;
+	bool release_only = false;
 	int ret = 0;
 
 	/* only aligned lower 32-bit are relevant */
@@ -921,14 +1044,28 @@ static void arena_free_pages(struct bpf_arena *arena, long uaddr, long page_cnt,
 
 	if (!sleepable)
 		goto defer;
+	if (!arena_opref_get(arena, ARENA_OPREF_FREE))
+		goto defer;
 
 	ret = raw_res_spin_lock_irqsave(&arena->spinlock, flags);
 
 	/* Can't proceed without holding the spinlock so defer the free */
 	if (ret)
-		goto defer;
+		goto defer_admitted;
 
-	range_tree_set(&arena->rt, pgoff, page_cnt);
+	unavail_node = range_tree_set_unavail(&arena->rt, pgoff, page_cnt);
+	if (IS_ERR(unavail_node)) {
+		raw_res_spin_unlock_irqrestore(&arena->spinlock, flags);
+
+		/* If overlapping free in progress or out of memory, defer. */
+		ret = PTR_ERR(unavail_node);
+		if (ret == -ENOMEM || ret == -EAGAIN)
+			goto defer_admitted;
+		WARN_ON_ONCE(ret);
+		arena_opref_put(arena, ARENA_OPREF_FREE);
+		bpf_map_memcg_exit(old_memcg, new_memcg);
+		return;
+	}
 
 	init_llist_head(&free_pages);
 	cdata.arena = arena;
@@ -940,6 +1077,8 @@ static void arena_free_pages(struct bpf_arena *arena, long uaddr, long page_cnt,
 	/* drop the lock to do the tlb flush and zap pages */
 	raw_res_spin_unlock_irqrestore(&arena->spinlock, flags);
 
+	wait_for_faults(&free_pages);
+
 	/* ensure no stale TLB entries */
 	flush_tlb_kernel_range(kaddr, kaddr + (page_cnt * PAGE_SIZE));
 
@@ -956,25 +1095,58 @@ static void arena_free_pages(struct bpf_arena *arena, long uaddr, long page_cnt,
 			 * page_cnt is big it's faster to do the batched zap.
 			 */
 			zap_pages(arena, full_uaddr, 1);
-		__free_page(page);
+		arena_put_page(page);
 	}
+
+	ret = raw_res_spin_lock_irqsave(&arena->spinlock, flags);
+	if (ret) {
+		release_only = true;
+		goto defer_admitted;
+	}
+
+	ret = range_tree_make_avail(&arena->rt, pgoff, page_cnt);
+	raw_res_spin_unlock_irqrestore(&arena->spinlock, flags);
+	WARN_ON_ONCE(ret);
+	arena_opref_put(arena, ARENA_OPREF_FREE);
 	bpf_map_memcg_exit(old_memcg, new_memcg);
 
 	return;
 
+defer_admitted:
+	arena_opref_put(arena, ARENA_OPREF_FREE);
 defer:
 	s = kmalloc_nolock(sizeof(struct arena_free_span), __GFP_ACCOUNT, -1);
 	bpf_map_memcg_exit(old_memcg, new_memcg);
-	if (!s)
+	if (!s) {
 		/*
-		 * If allocation fails in non-sleepable context, pages are intentionally left
-		 * inaccessible (leaked) until the arena is destroyed. Cleanup or retries are not
-		 * possible here, so we intentionally omit them for safety.
+		 * Directly mark the region available. Unavailable regions must
+		 * always be transient.
+		 *
+		 * Directly marking the node avialable is safe because unavailable nodes
+		 * are not modified by the range tree code without a reference to the node.
+		 * The unavailable -> available op does not touch anything in the tree apart
+		 * from the node so no need to take the lock.
+		 *
+		 * The downside is fragmentation in the tree, but this is a) safe and b) better
+		 * than leaking the range.
 		 */
+		if (release_only)
+			range_node_mark_available(unavail_node);
+
+		/*
+		 * If we haven't even zapped the pages, intentionally leave them
+		 * inaccessible (leaked) until the arena is destroyed. Cleanup or
+		 * retries are not possible here.
+		 */
+
 		return;
+	}
 
 	s->page_cnt = page_cnt;
 	s->uaddr = uaddr;
+	s->flags = release_only ? (ARENA_FREE_SPAN_CLEARED |
+				   ARENA_FREE_SPAN_ZAPPED |
+				   ARENA_FREE_SPAN_RESERVED) : 0;
 	llist_add(&s->node, &arena->free_spans);
 	irq_work_queue(&arena->free_irq);
 }
@@ -1023,6 +1195,7 @@ static void arena_free_worker(struct work_struct *work)
 	struct mem_cgroup *new_memcg, *old_memcg;
 	struct llist_node *list, *pos, *t;
 	struct arena_free_span *s;
+	struct range_node *unavail_node;
 	u64 arena_vm_start, user_vm_start;
 	struct llist_head free_pages;
 	struct clear_range_data cdata;
@@ -1030,8 +1203,15 @@ static void arena_free_worker(struct work_struct *work)
 	unsigned long full_uaddr;
 	long kaddr, page_cnt, pgoff;
 	unsigned long flags;
+	bool retry = false;
+	int ret;
 
+	if (!arena_opref_get(arena, ARENA_OPREF_FREE)) {
+		schedule_work(work);
+		return;
+	}
 	if (raw_res_spin_lock_irqsave(&arena->spinlock, flags)) {
+		arena_opref_put(arena, ARENA_OPREF_FREE);
 		schedule_work(work);
 		return;
 	}
@@ -1045,23 +1225,53 @@ static void arena_free_worker(struct work_struct *work)
 	user_vm_start = bpf_arena_get_user_vm_start(arena);
 
 	list = llist_del_all(&arena->free_spans);
-	llist_for_each(pos, list) {
+	llist_for_each_safe(pos, t, list) {
 		s = llist_entry(pos, struct arena_free_span, node);
+		if (s->flags)
+			continue;
+
 		page_cnt = s->page_cnt;
-		kaddr = arena_vm_start + s->uaddr;
 		pgoff = compute_pgoff(arena, s->uaddr);
+		kaddr = arena_vm_start + s->uaddr;
+
+		/*
+		 * Marking the range tree unavailable is required to avoid
+		 * reallocations through, e.g., minor page faults.
+		 */
+		unavail_node = range_tree_set_unavail(&arena->rt, pgoff, page_cnt);
+		if (!IS_ERR(unavail_node)) {
+			s->flags |= ARENA_FREE_SPAN_RESERVED;
+			goto clear_ptes;
+		}
 
-		/* clear ptes and collect pages in free_pages llist */
+		ret = PTR_ERR(unavail_node);
+		/* Retry without starting teardown. */
+		if (ret == -EAGAIN || ret == -ENOMEM)
+			continue;
+
+		/* Unexpected failures leave pages for map teardown. */
+		WARN_ON_ONCE(ret);
+
+		s->flags = ARENA_FREE_SPAN_FAILED;
+		continue;
+
+clear_ptes:
+		/* clear ptes and mark the span as cleared. */
 		apply_to_existing_page_range(&init_mm, kaddr, page_cnt << PAGE_SHIFT,
 					     apply_range_clear_cb, &cdata);
-
-		range_tree_set(&arena->rt, pgoff, page_cnt);
+		s->flags |= ARENA_FREE_SPAN_CLEARED;
 	}
 	raw_res_spin_unlock_irqrestore(&arena->spinlock, flags);
 
-	/* Iterate the list again without holding spinlock to do the tlb flush and zap_pages */
+	wait_for_faults(&free_pages);
+
+	/* Remove stale translations before freeing the collected pages. */
 	llist_for_each_safe(pos, t, list) {
 		s = llist_entry(pos, struct arena_free_span, node);
+		if (!(s->flags & ARENA_FREE_SPAN_CLEARED) ||
+		    (s->flags & ARENA_FREE_SPAN_ZAPPED))
+			continue;
+
 		page_cnt = s->page_cnt;
 		full_uaddr = clear_lo32(user_vm_start) + s->uaddr;
 		kaddr = arena_vm_start + s->uaddr;
@@ -1072,16 +1282,68 @@ static void arena_free_worker(struct work_struct *work)
 		/* remove pages from user vmas */
 		zap_pages(arena, full_uaddr, page_cnt);
 
-		kfree_nolock(s);
+		/*
+		 * Used to avoid zapping twice if we fail the lock acquisition
+		 * below and rerun the span through this function.
+		 */
+		s->flags |= ARENA_FREE_SPAN_ZAPPED;
 	}
 
 	/* free all pages collected by apply_to_existing_page_range() in the first loop */
 	llist_for_each_safe(pos, t, __llist_del_all(&free_pages)) {
 		page = llist_entry(pos, struct page, pcp_llist);
-		__free_page(page);
+		arena_put_page(page);
 	}
 
+	if (raw_res_spin_lock_irqsave(&arena->spinlock, flags)) {
+		llist_for_each_safe(pos, t, list) {
+			s = llist_entry(pos, struct arena_free_span, node);
+
+			/* Only unstarted frees and reserved ranges need a retry. */
+			if (!s->flags || (s->flags & ARENA_FREE_SPAN_RESERVED)) {
+				llist_add(pos, &arena->free_spans);
+				retry = true;
+			} else {
+				kfree_nolock(s);
+			}
+		}
+		goto done;
+	}
+
+	llist_for_each_safe(pos, t, list) {
+		s = llist_entry(pos, struct arena_free_span, node);
+
+		if (s->flags & ARENA_FREE_SPAN_FAILED) {
+			kfree_nolock(s);
+			continue;
+		}
+
+		if (!(s->flags & ARENA_FREE_SPAN_CLEARED)) {
+			llist_add(pos, &arena->free_spans);
+			retry = true;
+			continue;
+		}
+
+		if (s->flags & ARENA_FREE_SPAN_RESERVED) {
+			page_cnt = s->page_cnt;
+			pgoff = compute_pgoff(arena, s->uaddr);
+			/*
+			 * This range tree operation does not allocate memory,
+			 * so failures are actual bugs.
+			 */
+			ret = range_tree_make_avail(&arena->rt, pgoff, page_cnt);
+			WARN_ON_ONCE(ret);
+		}
+		kfree_nolock(s);
+	}
+	raw_res_spin_unlock_irqrestore(&arena->spinlock, flags);
+
+done:
+	arena_opref_put(arena, ARENA_OPREF_FREE);
 	bpf_map_memcg_exit(old_memcg, new_memcg);
+
+	if (retry)
+		schedule_work(work);
 }
 
 static void arena_free_irq(struct irq_work *iw)
diff --git a/kernel/bpf/range_tree.c b/kernel/bpf/range_tree.c
index 2460e78d6a554..e46f3467c3a24 100644
--- a/kernel/bpf/range_tree.c
+++ b/kernel/bpf/range_tree.c
@@ -3,6 +3,7 @@
 #include <linux/interval_tree_generic.h>
 #include <linux/slab.h>
 #include <linux/bpf.h>
+#include <linux/err.h>
 #include "range_tree.h"
 
 /*
@@ -39,8 +40,29 @@ struct range_node {
 	u32 rn_start;
 	u32 rn_last; /* inclusive */
 	u32 __rn_subtree_last;
+	bool available; /* range is available for allocating. */
 };
 
+/* Is the range available for merging? */
+static inline bool range_available(struct range_node *rn)
+{
+	/* Pairs with smp_store_release() in range_node_mark_available(). */
+	return rn && smp_load_acquire(&rn->available);
+}
+
+/*
+ * Mark a node as available. Designed to be used locklessly
+ * as a last-ditch effort to avoid leaking unavailable range
+ * tree nodes when all attempts to directly or indirectly
+ * free an arena region has failed. See arena_free_pages()
+ * for more info.
+ */
+void range_node_mark_available(struct range_node *rn)
+{
+	/* Pairs with smp_load_acquire() in range_available(). */
+	smp_store_release(&rn->available, true);
+}
+
 static struct range_node *rb_to_range_node(struct rb_node *rb)
 {
 	return rb_entry(rb, struct range_node, rb_range_size);
@@ -55,20 +77,30 @@ static u32 rn_size(struct range_node *rn)
 static inline struct range_node *__find_range(struct range_tree *rt, u32 len)
 {
 	struct rb_node *rb = rt->range_size_root.rb_root.rb_node;
-	struct range_node *best = NULL;
+	struct rb_node *best = NULL;
+	struct range_node *rn;
 
 	while (rb) {
-		struct range_node *rn = rb_to_range_node(rb);
+		rn = rb_to_range_node(rb);
 
 		if (len <= rn_size(rn)) {
-			best = rn;
+			best = rb;
 			rb = rb->rb_right;
 		} else {
 			rb = rb->rb_left;
 		}
 	}
 
-	return best;
+	/* Filter unavailable ranges. */
+	while (best) {
+		rn = rb_to_range_node(best);
+		if (range_available(rn))
+			return rn;
+
+		best = rb_prev(best);
+	}
+
+	return NULL;
 }
 
 s64 range_tree_find(struct range_tree *rt, u32 len)
@@ -135,10 +167,19 @@ range_it_iter_first(struct range_tree *rt, u32 start, u32 last)
 /* Clear the range in this range tree */
 int range_tree_clear(struct range_tree *rt, u32 start, u32 len)
 {
+	u32 first = start;
 	u32 last = start + len - 1;
 	struct range_node *new_rn;
 	struct range_node *rn;
 
+	/* Scan for unavailable ranges and try again if so. */
+	while ((rn = range_it_iter_first(rt, first, last))) {
+		if (!range_available(rn))
+			return -EAGAIN;
+
+		first = rn->rn_last + 1;
+	}
+
 	while ((rn = range_it_iter_first(rt, start, last))) {
 		if (rn->rn_start < start && rn->rn_last > last) {
 			u32 old_last = rn->rn_last;
@@ -159,6 +200,7 @@ int range_tree_clear(struct range_tree *rt, u32 start, u32 len)
 			range_it_insert(rn, rt);
 
 			/* Add right-half range */
+			new_rn->available = rn->available;
 			new_rn->rn_start = last + 1;
 			new_rn->rn_last = old_last;
 			range_it_insert(new_rn, rt);
@@ -186,66 +228,172 @@ int range_tree_clear(struct range_tree *rt, u32 start, u32 len)
 int is_range_tree_set(struct range_tree *rt, u32 start, u32 len)
 {
 	u32 last = start + len - 1;
-	struct range_node *left;
+	struct range_node *rn;
 
-	/* Is this whole range set ? */
-	left = range_it_iter_first(rt, start, last);
-	if (left && left->rn_start <= start && left->rn_last >= last)
-		return 0;
+	for ((rn = range_it_iter_first(rt, start, last)); rn != NULL;
+		rn = __range_it_iter_next(rn, start, last)) {
+		/* Make sure the range covers the start */
+		if (rn->rn_start > start)
+			return -ESRCH;
+
+		/* If it covers the entire range we're done. */
+		if (rn->rn_last >= last)
+			return 0;
+
+		start = rn->rn_last + 1;
+	}
+
+	/* No range to cover [start, last] */
 	return -ESRCH;
 }
 
-/* Set the range in this range tree */
-int range_tree_set(struct range_tree *rt, u32 start, u32 len)
+/* Do we have adjacent ranges (and do not overlap with them)? */
+static int range_get_adjacent(struct range_tree *rt, u32 start, u32 last,
+		struct range_node **leftp, struct range_node **rightp)
 {
-	u32 last = start + len - 1;
-	struct range_node *new_rn = NULL;
 	struct range_node *right;
 	struct range_node *left;
-	int err;
 
-	/* Is this whole range already set ? */
-	left = range_it_iter_first(rt, start, last);
-	if (left && left->rn_start <= start && left->rn_last >= last)
-		return 0;
+	/* Do we have a left-adjacent range ? */
+	left = start ? range_it_iter_first(rt, start - 1, start - 1) : NULL;
+	if (left && left->rn_last != start - 1)
+		return -EFAULT;
 
-	left = range_it_iter_first(rt, start - 1, start - 1);
-	right = range_it_iter_first(rt, last + 1, last + 1);
-	if (!left && !right) {
-		new_rn = kmalloc_nolock(sizeof(struct range_node),
-					__GFP_ACCOUNT, NUMA_NO_NODE);
-		if (!new_rn)
-			return -ENOMEM;
-	}
+	/* Do we have a right-adjacent range ? */
+	right = last != U32_MAX ? range_it_iter_first(rt, last + 1, last + 1) : NULL;
+	if (right && right->rn_start != last + 1)
+		return -EFAULT;
 
-	/* Clear out everything in the range we want to set. */
-	err = range_tree_clear(rt, start, len);
-	if (err)
-		goto out_free_new;
+	*leftp = left;
+	*rightp = right;
+
+	return 0;
+}
 
-	if (left && right) {
+/*
+ * Merge with adjacent available ranges if possible. The new [start, last]
+ * has already been confirmed to be adjacent with left/right by the caller.
+ */
+static int range_tree_merge(struct range_tree *rt, u32 start, u32 last,
+		struct range_node *left, struct range_node *right)
+{
+	if (range_available(left) && range_available(right)) {
 		/* Combine left and right adjacent ranges */
 		range_it_remove(left, rt);
 		range_it_remove(right, rt);
 		left->rn_last = right->rn_last;
 		range_it_insert(left, rt);
 		kfree_nolock(right);
-	} else if (left) {
+	} else if (range_available(left)) {
 		/* Combine with the left range */
 		range_it_remove(left, rt);
 		left->rn_last = last;
 		range_it_insert(left, rt);
-	} else if (right) {
+	} else if (range_available(right)) {
 		/* Combine with the right range */
 		range_it_remove(right, rt);
 		right->rn_start = start;
 		range_it_insert(right, rt);
 	} else {
-		/* No adjacent ranges; use the pre-allocated node */
-		new_rn->rn_start = start;
-		new_rn->rn_last = last;
-		range_it_insert(new_rn, rt);
+		/* No merge available. */
+		return -ENOENT;
 	}
+
+	return 0;
+}
+
+/* Make a range available, possibly merging. */
+int range_tree_make_avail(struct range_tree *rt, u32 start, u32 len)
+{
+	u32 last = start + len - 1;
+	struct range_node *rn;
+	struct range_node *right;
+	struct range_node *left;
+	int err;
+
+	/*
+	 * Confirm the range exists is unavailable,
+	 * and fits the requested range exactly.
+	 */
+	rn = range_it_iter_first(rt, start, last);
+	if (!rn || rn->available)
+		return -EINVAL;
+
+	if (rn->rn_start != start || rn->rn_last != last)
+		return -EINVAL;
+
+	err = range_get_adjacent(rt, start, last, &left, &right);
+	if (err)
+		return err;
+
+	/* If no merging required, just make available. */
+	if (!range_available(left) && !range_available(right)) {
+		rn->available = true;
+		return 0;
+	}
+
+	/* Can merge, remove the range already. */
+	start = rn->rn_start;
+	last = rn->rn_last;
+	range_it_remove(rn, rt);
+	kfree_nolock(rn);
+
+	return range_tree_merge(rt, start, last, left, right);
+}
+
+/* Set the range in this range tree */
+static int range_tree_set(struct range_tree *rt, u32 start, u32 len,
+			  bool available, struct range_node **new_rnp)
+{
+	u32 last = start + len - 1;
+	struct range_node *new_rn = NULL;
+	struct range_node *right;
+	struct range_node *left;
+	int err;
+
+	/* Already available: nothing to change. */
+	left = range_it_iter_first(rt, start, last);
+	if (available && range_available(left) &&
+	    left->rn_start <= start && left->rn_last >= last)
+		return 0;
+
+	/* Predict whether insertion needs a new node before clearing. */
+	left = start ? range_it_iter_first(rt, start - 1, start - 1) : NULL;
+	right = last != U32_MAX ? range_it_iter_first(rt, last + 1, last + 1) : NULL;
+
+	/* Unavailable ranges cannot merge. Allocate before changing the tree. */
+	if (!available ||
+	    (!range_available(left) && !range_available(right))) {
+		new_rn = kmalloc_nolock(sizeof(*new_rn), __GFP_ACCOUNT,
+					NUMA_NO_NODE);
+		if (!new_rn)
+			return -ENOMEM;
+	}
+
+	/* Clear out everything in the range we want to set. */
+	err = range_tree_clear(rt, start, len);
+	if (err)
+		goto out_free_new;
+
+	/* Recompute adjacency: clearing may have trimmed or split nodes. */
+	err = range_get_adjacent(rt, start, last, &left, &right);
+	if (err)
+		goto out_free_new;
+
+	if (available &&
+	    (range_available(left) || range_available(right))) {
+		err = range_tree_merge(rt, start, last, left, right);
+		goto out_free_new;
+	}
+
+	/* No merge possible; transfer the reserved node to the tree. */
+	new_rn->available = available;
+	new_rn->rn_start = start;
+	new_rn->rn_last = last;
+	range_it_insert(new_rn, rt);
+	if (new_rnp)
+		*new_rnp = new_rn;
+
 	return 0;
 
 out_free_new:
@@ -253,6 +401,24 @@ int range_tree_set(struct range_tree *rt, u32 start, u32 len)
 	return err;
 }
 
+int range_tree_set_avail(struct range_tree *rt, u32 start, u32 len)
+{
+	return range_tree_set(rt, start, len, true, NULL);
+}
+
+struct range_node *range_tree_set_unavail(struct range_tree *rt, u32 start, u32 len)
+{
+	struct range_node *rn = NULL;
+	int err;
+
+	err = range_tree_set(rt, start, len, false, &rn);
+	if (err)
+		return ERR_PTR(err);
+	if (WARN_ON_ONCE(!rn))
+		return ERR_PTR(-EINVAL);
+	return rn;
+}
+
 void range_tree_destroy(struct range_tree *rt)
 {
 	struct range_node *rn;
diff --git a/kernel/bpf/range_tree.h b/kernel/bpf/range_tree.h
index ff0b9110eb715..4f9ea2acea290 100644
--- a/kernel/bpf/range_tree.h
+++ b/kernel/bpf/range_tree.h
@@ -10,11 +10,16 @@ struct range_tree {
 	struct rb_root_cached range_size_root;
 };
 
+struct range_node;
+
 void range_tree_init(struct range_tree *rt);
 void range_tree_destroy(struct range_tree *rt);
 
 int range_tree_clear(struct range_tree *rt, u32 start, u32 len);
-int range_tree_set(struct range_tree *rt, u32 start, u32 len);
+int range_tree_set_avail(struct range_tree *rt, u32 start, u32 len);
+struct range_node *range_tree_set_unavail(struct range_tree *rt, u32 start, u32 len);
+void range_node_mark_available(struct range_node *rn);
+int range_tree_make_avail(struct range_tree *rt, u32 start, u32 len);
 int is_range_tree_set(struct range_tree *rt, u32 start, u32 len);
 s64 range_tree_find(struct range_tree *rt, u32 len);
 
diff --git a/kernel/bpf/syscall.c b/kernel/bpf/syscall.c
index 654f896af265b..1a1cc305dabb9 100644
--- a/kernel/bpf/syscall.c
+++ b/kernel/bpf/syscall.c
@@ -1209,6 +1209,8 @@ int bpf_map_new_fd(struct bpf_map *map, int flags)
 	if (ret < 0)
 		return ret;
 
+	if (map->ops->map_get_file)
+		return FD_ADD(flags | O_CLOEXEC, map->ops->map_get_file(map, flags));
 	return anon_inode_getfd("bpf-map", &bpf_map_fops, map,
 				flags | O_CLOEXEC);
 }
diff --git a/tools/testing/selftests/bpf/prog_tests/arena_race.c b/tools/testing/selftests/bpf/prog_tests/arena_race.c
new file mode 100644
index 0000000000000..301f4dff28f99
--- /dev/null
+++ b/tools/testing/selftests/bpf/prog_tests/arena_race.c
@@ -0,0 +1,285 @@
+// SPDX-License-Identifier: GPL-2.0
+
+#define _GNU_SOURCE
+#include <sched.h>
+#include <sys/syscall.h>
+#include <test_progs.h>
+
+#include "arena_race.skel.h"
+
+struct free_thread_ctx {
+	struct arena_race *skel;
+	int err;
+	__u32 retval;
+};
+
+struct fault_thread_ctx {
+	__u64 *addr;
+	int stop;
+};
+
+static int run_prog(struct bpf_program *prog, const char *name)
+{
+	LIBBPF_OPTS(bpf_test_run_opts, opts);
+	int err;
+
+	err = bpf_prog_test_run_opts(bpf_program__fd(prog), &opts);
+	return ASSERT_OK(err, name) && ASSERT_OK(opts.retval, name) ? 0 : -1;
+}
+
+/* Trigger the sleepable free page path. */
+static void *run_free_thread(void *arg)
+{
+	LIBBPF_OPTS(bpf_test_run_opts, opts);
+	struct free_thread_ctx *ctx = arg;
+
+	ctx->skel->bss->target_tid = sys_gettid();
+	ctx->err = bpf_prog_test_run_opts(
+		bpf_program__fd(ctx->skel->progs.free_page), &opts);
+	ctx->retval = opts.retval;
+	return NULL;
+}
+
+/* Continuously fault in the address. */
+static void *fault_reader_thread(void *arg)
+{
+	struct fault_thread_ctx *ctx = arg;
+	__u64 *addr;
+
+	while (!READ_ONCE(ctx->stop)) {
+		addr = __atomic_load_n(&ctx->addr, __ATOMIC_ACQUIRE);
+		(void)READ_ONCE(*addr);
+	}
+	return NULL;
+}
+
+static int wait_for(int *p)
+{
+	__u64 deadline = get_time_ns() + 5ULL * 1000 * 1000 * 1000;
+
+	while (!READ_ONCE(*p)) {
+		if (get_time_ns() > deadline)
+			return -ETIMEDOUT;
+	}
+	return 0;
+}
+
+static struct arena_race *setup_arena(__u64 **addr, bool trace_flush)
+{
+	struct arena_race *skel;
+	size_t arena_sz;
+	char *base;
+	int err;
+
+	skel = arena_race__open();
+	if (!ASSERT_OK_PTR(skel, "open"))
+		return NULL;
+	err = bpf_program__set_autoload(skel->progs.trace_flush, trace_flush);
+	if (!ASSERT_OK(err, "trace_flush_autoload"))
+		goto err_out;
+
+	err = arena_race__load(skel);
+	if (!ASSERT_OK(err, "load"))
+		goto err_out;
+	err = arena_race__attach(skel);
+	if (!ASSERT_OK(err, "attach"))
+		goto err_out;
+
+	if (run_prog(skel->progs.alloc_old, "alloc_old"))
+		goto err_out;
+	if (skel->bss->skip) {
+		test__skip();
+		goto err_out;
+	}
+
+	base = bpf_map__initial_value(skel->maps.arena, &arena_sz);
+	if (!ASSERT_OK_PTR(base, "arena_base"))
+		goto err_out;
+	*addr = (__u64 *)(base + getpagesize());
+	if (!ASSERT_EQ((unsigned long)skel->bss->ptr, (unsigned long)*addr,
+		       "arena_ptr"))
+		goto err_out;
+	return skel;
+
+err_out:
+	arena_race__destroy(skel);
+	return NULL;
+}
+
+static void test_free_before_flush(bool deferred)
+{
+	struct free_thread_ctx ctx = {};
+	struct arena_race *skel;
+	pthread_t thread;
+	__u64 *addr;
+	bool thread_created = false, flush_seen = false, completed = false;
+	int err;
+
+	if (libbpf_find_vmlinux_btf_id("flush_tlb_kernel_range",
+					BPF_TRACE_FENTRY) <= 0) {
+		printf("%s:SKIP: flush_tlb_kernel_range is not an fentry target\n",
+		       __func__);
+		test__skip();
+		return;
+	}
+
+	skel = setup_arena(&addr, true);
+	if (!skel)
+		return;
+
+	/* Pause during a TLB flush to widen the race window. */
+	skel->bss->pause_on_flush = 1;
+
+	if (deferred) {
+		/*
+		 * Test the nonsleepable free path that gets
+		 * deferred to a worker in the kernel. We do
+		 * so by triggering the arena operation from
+		 * a nonsleepable tracepoint context.
+		 */
+		skel->bss->trigger_pid_tgid =
+			((__u64)getpid() << 32) | (__u32)sys_gettid();
+		skel->bss->trigger_syscall = SYS_getpgid;
+		skel->bss->deferred_free = 1;
+		if (!ASSERT_GE(syscall(SYS_getpgid, 0), 0, "deferred_free"))
+			goto release;
+	} else {
+		/*
+		 * Test the sleepable arena free path through a
+		 * syscall test prog.
+		 */
+		ctx.skel = skel;
+		err = pthread_create(&thread, NULL, run_free_thread, &ctx);
+		if (!ASSERT_OK(err, "pthread_create")) {
+			skel->bss->release = 1;
+			goto out;
+		}
+		thread_created = true;
+	}
+
+	/* Wait until the worker thread triggers a flush. */
+	err = wait_for(&skel->bss->flush_entered);
+	if (!ASSERT_OK(err, "flush_entered"))
+		goto release;
+
+	flush_seen = true;
+
+	/* Force a reallocation during the flush. */
+	run_prog(skel->progs.try_realloc, "realloc_before_flush");
+	ASSERT_NULL(skel->bss->realloc_ptr, "realloc_before_flush");
+
+release:
+	skel->bss->release = 1;
+	if (thread_created) {
+		ASSERT_OK(pthread_join(thread, NULL), "pthread_join");
+		thread_created = false;
+		completed = ASSERT_OK(ctx.err, "free_run") &&
+			    ASSERT_OK(ctx.retval, "free_retval");
+	} else if (skel->bss->target_tid) {
+		err = wait_for(&skel->bss->worker_exited);
+		completed = ASSERT_OK(err, "worker_exited");
+	}
+	ASSERT_FALSE(skel->bss->timed_out, "flush_timed_out");
+
+	if (flush_seen && completed &&
+	    !run_prog(skel->progs.try_realloc, "realloc_after_flush")) {
+		ASSERT_EQ((unsigned long)skel->bss->realloc_ptr,
+			  (unsigned long)addr, "realloc_after_flush");
+		ASSERT_EQ(*addr, skel->rodata->new_marker, "new_marker");
+	}
+out:
+	arena_race__destroy(skel);
+}
+
+/*
+ * Force a race between a faulting thread in userspace and a
+ * free operation on the arena.
+ */
+static void test_fault_free_realloc(void)
+{
+	struct fault_thread_ctx fault = {};
+	struct arena_race *skel;
+	pthread_t fault_thread;
+	bool fault_created = false;
+	__u64 *addr;
+	__u64 expected, value;
+	int err, i;
+
+	skel = setup_arena(&addr, false);
+	if (!skel)
+		return;
+
+	skel->bss->realloc_after_free = 1;
+
+	fault.addr = addr;
+	err = pthread_create(&fault_thread, NULL, fault_reader_thread, &fault);
+	if (!ASSERT_OK(err, "pthread_create_fault"))
+		goto out;
+	fault_created = true;
+
+	for (i = 0; i < 1000; i++) {
+		LIBBPF_OPTS(bpf_test_run_opts, opts);
+
+		/* Keep deferred frees from earlier iterations on separate slots. */
+		if (i) {
+			skel->bss->page_idx = i;
+			if (run_prog(skel->progs.alloc_old, "alloc_next"))
+				goto out;
+			addr = (__u64 *)(unsigned long)skel->bss->ptr;
+			__atomic_store_n(&fault.addr, addr, __ATOMIC_RELEASE);
+		}
+
+		err = bpf_prog_test_run_opts(bpf_program__fd(skel->progs.free_page),
+					     &opts);
+		if (err) {
+			ASSERT_OK(err, "free_realloc");
+			break;
+		}
+		if (opts.retval) {
+			ASSERT_OK(opts.retval, "free_realloc");
+			break;
+		}
+		/* The reader may populate the slot first, or free may defer. */
+		if (!skel->bss->realloc_ptr)
+			continue;
+		value = *addr;
+		expected = skel->bss->current_marker;
+		if (value != expected) {
+			ASSERT_EQ(value, expected, "marker_after_realloc");
+			break;
+		}
+	}
+
+	WRITE_ONCE(fault.stop, 1);
+	if (fault_created) {
+		ASSERT_OK(pthread_join(fault_thread, NULL), "pthread_join_fault");
+		fault_created = false;
+	}
+out:
+	WRITE_ONCE(fault.stop, 1);
+	if (fault_created)
+		pthread_join(fault_thread, NULL);
+	arena_race__destroy(skel);
+}
+
+void serial_test_arena_race(void)
+{
+	cpu_set_t cpuset;
+	int err;
+
+	err = sched_getaffinity(0, sizeof(cpuset), &cpuset);
+	if (!ASSERT_OK(err, "sched_getaffinity"))
+		return;
+	if (CPU_COUNT(&cpuset) < 2) {
+		printf("%s:SKIP: at least two runnable CPUs are required\n", __func__);
+		test__skip();
+		return;
+	}
+
+	if (test__start_subtest("free_before_flush"))
+		test_free_before_flush(false);
+	if (test__start_subtest("deferred_free_before_flush"))
+		test_free_before_flush(true);
+	if (test__start_subtest("fault_free_realloc"))
+		test_fault_free_realloc();
+}
diff --git a/tools/testing/selftests/bpf/progs/arena_race.c b/tools/testing/selftests/bpf/progs/arena_race.c
new file mode 100644
index 0000000000000..6d1675ba23957
--- /dev/null
+++ b/tools/testing/selftests/bpf/progs/arena_race.c
@@ -0,0 +1,159 @@
+// SPDX-License-Identifier: GPL-2.0
+
+#define BPF_NO_KFUNC_PROTOTYPES
+#include <vmlinux.h>
+#include <bpf/bpf_helpers.h>
+#include <bpf/bpf_tracing.h>
+#include "bpf_experimental.h"
+#include <bpf_arena_common.h>
+
+const volatile __u64 old_marker = 0x1111222233334444ULL;
+const volatile __u64 new_marker = 0x5555666677778888ULL;
+
+struct {
+	__uint(type, BPF_MAP_TYPE_ARENA);
+	__uint(map_flags, BPF_F_MMAPABLE);
+	__uint(max_entries, 1024);
+#ifdef __TARGET_ARCH_arm64
+	__ulong(map_extra, 0x1ull << 32);
+#else
+	__ulong(map_extra, 0x1ull << 44);
+#endif
+} arena SEC(".maps");
+
+bool skip;
+int page_idx;
+
+void __arena *ptr;
+void __arena *realloc_ptr;
+bool realloc_after_free;
+__u64 current_marker;
+__u64 marker_seq;
+
+int target_tid;
+int pause_on_flush;
+int flush_entered;
+int release;
+int timed_out;
+
+__u64 trigger_pid_tgid;
+long trigger_syscall;
+int deferred_free;
+int worker_armed;
+int worker_exited;
+
+static __always_inline void wait_for_release(void)
+{
+	while (!*(volatile int *)&release && can_loop)
+		;
+	if (!*(volatile int *)&release)
+		timed_out = 1;
+}
+
+SEC("syscall")
+int alloc_old(void *ctx)
+{
+#if defined(__BPF_FEATURE_ADDR_SPACE_CAST) || defined(BPF_ARENA_FORCE_ASM)
+	__u64 __arena *p;
+	char __arena *base = arena_base(&arena);
+
+	realloc_ptr = NULL;
+	ptr = bpf_arena_alloc_pages(&arena, base + (page_idx + 1) * __PAGE_SIZE, 1,
+				    NUMA_NO_NODE, 0);
+	if (!ptr)
+		return 1;
+	p = (__u64 __arena *)ptr;
+	*p = old_marker;
+	current_marker = old_marker;
+#else
+	skip = true;
+#endif
+	return 0;
+}
+
+SEC("syscall")
+int free_page(void *ctx)
+{
+#if defined(__BPF_FEATURE_ADDR_SPACE_CAST) || defined(BPF_ARENA_FORCE_ASM)
+	__u64 __arena *p;
+	__u64 marker;
+
+	if (!ptr)
+		return 1;
+	bpf_arena_free_pages(&arena, ptr, 1);
+	if (!realloc_after_free)
+		return 0;
+
+	marker = new_marker + ++marker_seq;
+	realloc_ptr = bpf_arena_alloc_pages(&arena, ptr, 1, NUMA_NO_NODE, 0);
+	if (!realloc_ptr)
+		return 0;
+	ptr = realloc_ptr;
+	p = (__u64 __arena *)ptr;
+	*p = marker;
+	current_marker = marker;
+#endif
+	return 0;
+}
+
+SEC("syscall")
+int try_realloc(void *ctx)
+{
+#if defined(__BPF_FEATURE_ADDR_SPACE_CAST) || defined(BPF_ARENA_FORCE_ASM)
+	__u64 __arena *p;
+
+	realloc_ptr = bpf_arena_alloc_pages(&arena, ptr, 1, NUMA_NO_NODE, 0);
+	if (realloc_ptr) {
+		ptr = realloc_ptr;
+		p = (__u64 __arena *)realloc_ptr;
+		*p = new_marker;
+		current_marker = new_marker;
+	}
+#endif
+	return 0;
+}
+
+SEC("tp_btf/sys_enter")
+int BPF_PROG(deferred_free_prog, struct pt_regs *regs, long id)
+{
+#if defined(__BPF_FEATURE_ADDR_SPACE_CAST) || defined(BPF_ARENA_FORCE_ASM)
+	if (!deferred_free || bpf_get_current_pid_tgid() != trigger_pid_tgid ||
+	    id != trigger_syscall)
+		return 0;
+
+	deferred_free = 0;
+	/* The worker can run on another CPU before the kfunc returns. */
+	worker_armed = 1;
+	bpf_arena_free_pages(&arena, ptr, 1);
+#endif
+	return 0;
+}
+
+SEC("fentry/arena_free_worker")
+int BPF_PROG(trace_free_worker, struct work_struct *work)
+{
+	if (worker_armed && !target_tid)
+		target_tid = (__u32)bpf_get_current_pid_tgid();
+	return 0;
+}
+
+SEC("fexit/arena_free_worker")
+int BPF_PROG(trace_free_worker_ret, struct work_struct *work)
+{
+	if ((__u32)bpf_get_current_pid_tgid() == target_tid)
+		worker_exited = 1;
+	return 0;
+}
+
+SEC("?fentry/flush_tlb_kernel_range")
+int BPF_PROG(trace_flush, unsigned long start, unsigned long end)
+{
+	if (!pause_on_flush ||
+	    (__u32)bpf_get_current_pid_tgid() != target_tid)
+		return 0;
+	flush_entered = 1;
+	wait_for_release();
+	return 0;
+}
+
+char _license[] SEC("license") = "GPL";

39/3 2026/10/15 03:46 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 21378
							output: 38
							thoughts: 1189
						

Thoughts:
**KMSAN Evaluation: BPF Arena Patch**

Okay, let's break this down. I need to determine if this patch warrants a dedicated KMSAN fuzzing session. The guiding principle is clear: if KASAN or other standard detectors can catch it, we *don't* need KMSAN. KMSAN is a resource hog, so we only deploy it when dealing with *uninitialized memory* risks that *only* KMSAN detects.

First, I need to understand what this patch actually *does*. It touches `include/linux/bpf.h`, adding a `map_get_file` operation to `bpf_map_ops`. The core of the changes seem to be in `kernel/bpf/arena.c`, where they're introducing a backing file for `bpf_arena`, replacing some locking and iterating with rmap/address_space operations to address race conditions. There are also updates to `kernel/bpf/range_tree.c`, introducing an `available` flag to `range_node` within a `range_tree` structure, and associated functions for manipulating the range tree. `kernel/bpf/syscall.c` utilizes `map->ops->map_get_file` if it's defined, and there's a selftest in `arena_race.c`.

Now, the crucial part: does this introduce or modify something that could lead to uninitialized memory reads or information leaks? The documentation sets a clear precedent. We need to be on the lookout for structures sent to userspace, conditional logic using uninitialized variables, allocation of complex structures with potential uninitialized fields, or vulnerabilities related to bounds checks where uninitialized bytes can be accessed. If all structures are zeroed or initialized, then it should be marked as false.

So, let's dive into the code itself. The introduction of `struct range_node` and its `available` flag in `range_tree.c` draws my attention. The definition of the structure itself doesn't inherently scream "KMSAN risk" – it's a collection of integers and a boolean. But now I need to trace the allocation and usage of this structure. Let's start with how it's allocated, specifically in `range_tree_clear` where I've noted a potential area of concern. It looks like `new_rn` is allocated, with some fields explicitly set in `range_tree_clear`. Let me read the source file itself to check how `new_rn` is allocated. Let's get the code using `read-file` and check.



40/3 2026/10/15 03:46 tool read-file
0m Args:
{
  "File": "kernel/bpf/range_tree.c",
  "FirstLine": 140,
  "LineCount": 80
}

Results:
{
  "Contents": " 140:\t\n 141:\tINTERVAL_TREE_DEFINE(struct range_node, rn_rbnode, u32,\n 142:\t\t\t     __rn_subtree_last, START, LAST,\n 143:\t\t\t     static inline __maybe_unused,\n 144:\t\t\t     __range_it)\n 145:\t\n 146:\tstatic inline __maybe_unused void\n 147:\trange_it_insert(struct range_node *rn, struct range_tree *rt)\n 148:\t{\n 149:\t\t__range_size_insert(rn, \u0026rt-\u003erange_size_root);\n 150:\t\t__range_it_insert(rn, \u0026rt-\u003eit_root);\n 151:\t}\n 152:\t\n 153:\tstatic inline __maybe_unused void\n 154:\trange_it_remove(struct range_node *rn, struct range_tree *rt)\n 155:\t{\n 156:\t\trb_erase_cached(\u0026rn-\u003erb_range_size, \u0026rt-\u003erange_size_root);\n 157:\t\tRB_CLEAR_NODE(\u0026rn-\u003erb_range_size);\n 158:\t\t__range_it_remove(rn, \u0026rt-\u003eit_root);\n 159:\t}\n 160:\t\n 161:\tstatic inline __maybe_unused struct range_node *\n 162:\trange_it_iter_first(struct range_tree *rt, u32 start, u32 last)\n 163:\t{\n 164:\t\treturn __range_it_iter_first(\u0026rt-\u003eit_root, start, last);\n 165:\t}\n 166:\t\n 167:\t/* Clear the range in this range tree */\n 168:\tint range_tree_clear(struct range_tree *rt, u32 start, u32 len)\n 169:\t{\n 170:\t\tu32 first = start;\n 171:\t\tu32 last = start + len - 1;\n 172:\t\tstruct range_node *new_rn;\n 173:\t\tstruct range_node *rn;\n 174:\t\n 175:\t\t/* Scan for unavailable ranges and try again if so. */\n 176:\t\twhile ((rn = range_it_iter_first(rt, first, last))) {\n 177:\t\t\tif (!range_available(rn))\n 178:\t\t\t\treturn -EAGAIN;\n 179:\t\n 180:\t\t\tfirst = rn-\u003ern_last + 1;\n 181:\t\t}\n 182:\t\n 183:\t\twhile ((rn = range_it_iter_first(rt, start, last))) {\n 184:\t\t\tif (rn-\u003ern_start \u003c start \u0026\u0026 rn-\u003ern_last \u003e last) {\n 185:\t\t\t\tu32 old_last = rn-\u003ern_last;\n 186:\t\n 187:\t\t\t\t/*\n 188:\t\t\t\t * Pre-allocate the right-half node before modifying\n 189:\t\t\t\t * the tree. If allocation fails we return -ENOMEM\n 190:\t\t\t\t * without altering the range tree.\n 191:\t\t\t\t */\n 192:\t\t\t\tnew_rn = kmalloc_nolock(sizeof(struct range_node),\n 193:\t\t\t\t\t\t\t__GFP_ACCOUNT, NUMA_NO_NODE);\n 194:\t\t\t\tif (!new_rn)\n 195:\t\t\t\t\treturn -ENOMEM;\n 196:\t\n 197:\t\t\t\t/* Overlaps with the entire clearing range */\n 198:\t\t\t\trange_it_remove(rn, rt);\n 199:\t\t\t\trn-\u003ern_last = start - 1;\n 200:\t\t\t\trange_it_insert(rn, rt);\n 201:\t\n 202:\t\t\t\t/* Add right-half range */\n 203:\t\t\t\tnew_rn-\u003eavailable = rn-\u003eavailable;\n 204:\t\t\t\tnew_rn-\u003ern_start = last + 1;\n 205:\t\t\t\tnew_rn-\u003ern_last = old_last;\n 206:\t\t\t\trange_it_insert(new_rn, rt);\n 207:\t\t\t} else if (rn-\u003ern_start \u003c start) {\n 208:\t\t\t\t/* Overlaps with the left side of the clearing range */\n 209:\t\t\t\trange_it_remove(rn, rt);\n 210:\t\t\t\trn-\u003ern_last = start - 1;\n 211:\t\t\t\trange_it_insert(rn, rt);\n 212:\t\t\t} else if (rn-\u003ern_last \u003e last) {\n 213:\t\t\t\t/* Overlaps with the right side of the clearing range */\n 214:\t\t\t\trange_it_remove(rn, rt);\n 215:\t\t\t\trn-\u003ern_start = last + 1;\n 216:\t\t\t\trange_it_insert(rn, rt);\n 217:\t\t\t\tbreak;\n 218:\t\t\t} else {\n 219:\t\t\t\t/* in the middle of the clearing range */\n"
}

41/3 2026/10/15 03:46 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 24447
							output: 38
							thoughts: 242
						

Thoughts:
**Analyzing Range Tree Insertion**

Okay, here we go, digging into this range tree implementation. Line 192 immediately caught my eye: `new_rn = kmalloc_nolock(sizeof(struct range_node), __GFP_ACCOUNT, NUMA_NO_NODE);`. Right, they're using `kmalloc_nolock` – that's something to keep in mind, potential locking implications there. Then, I see the subsequent field assignments to `new_rn`: `new_rn->available = rn->available;`, `new_rn->rn_start = last + 1;`, `new_rn->rn_last = old_last;`, followed by `range_it_insert(new_rn, rt);`.

My immediate question is: does `range_it_insert` handle initializing the red-black tree node fields? Things like `rb_range_size`, `rb_range_it`, and `__rn_subtree_last` are crucial for the tree's structure and operations. Ah, yes! A quick mental check… the code suggests `__range_size_insert` and `__range_it_insert` *do* indeed set up the necessary linkages for the rb_node. Okay, that's good.

But, I must not forget another function to consider. `range_tree_set` is still a mystery. I should read through it in `kernel/bpf/range_tree.c`, lines 340-420. Time to understand the broader context and how `range_tree_set` plays into this whole insertion mechanism. This is a crucial area to analyze.



42/3 2026/10/15 03:46 tool read-file
0m Args:
{
  "File": "kernel/bpf/range_tree.c",
  "FirstLine": 340,
  "LineCount": 80
}

Results:
{
  "Contents": " 340:\t\n 341:\t\treturn range_tree_merge(rt, start, last, left, right);\n 342:\t}\n 343:\t\n 344:\t/* Set the range in this range tree */\n 345:\tstatic int range_tree_set(struct range_tree *rt, u32 start, u32 len,\n 346:\t\t\t\t  bool available, struct range_node **new_rnp)\n 347:\t{\n 348:\t\tu32 last = start + len - 1;\n 349:\t\tstruct range_node *new_rn = NULL;\n 350:\t\tstruct range_node *right;\n 351:\t\tstruct range_node *left;\n 352:\t\tint err;\n 353:\t\n 354:\t\t/* Already available: nothing to change. */\n 355:\t\tleft = range_it_iter_first(rt, start, last);\n 356:\t\tif (available \u0026\u0026 range_available(left) \u0026\u0026\n 357:\t\t    left-\u003ern_start \u003c= start \u0026\u0026 left-\u003ern_last \u003e= last)\n 358:\t\t\treturn 0;\n 359:\t\n 360:\t\t/* Predict whether insertion needs a new node before clearing. */\n 361:\t\tleft = start ? range_it_iter_first(rt, start - 1, start - 1) : NULL;\n 362:\t\tright = last != U32_MAX ? range_it_iter_first(rt, last + 1, last + 1) : NULL;\n 363:\t\n 364:\t\t/* Unavailable ranges cannot merge. Allocate before changing the tree. */\n 365:\t\tif (!available ||\n 366:\t\t    (!range_available(left) \u0026\u0026 !range_available(right))) {\n 367:\t\t\tnew_rn = kmalloc_nolock(sizeof(*new_rn), __GFP_ACCOUNT,\n 368:\t\t\t\t\t\tNUMA_NO_NODE);\n 369:\t\t\tif (!new_rn)\n 370:\t\t\t\treturn -ENOMEM;\n 371:\t\t}\n 372:\t\n 373:\t\t/* Clear out everything in the range we want to set. */\n 374:\t\terr = range_tree_clear(rt, start, len);\n 375:\t\tif (err)\n 376:\t\t\tgoto out_free_new;\n 377:\t\n 378:\t\t/* Recompute adjacency: clearing may have trimmed or split nodes. */\n 379:\t\terr = range_get_adjacent(rt, start, last, \u0026left, \u0026right);\n 380:\t\tif (err)\n 381:\t\t\tgoto out_free_new;\n 382:\t\n 383:\t\tif (available \u0026\u0026\n 384:\t\t    (range_available(left) || range_available(right))) {\n 385:\t\t\terr = range_tree_merge(rt, start, last, left, right);\n 386:\t\t\tgoto out_free_new;\n 387:\t\t}\n 388:\t\n 389:\t\t/* No merge possible; transfer the reserved node to the tree. */\n 390:\t\tnew_rn-\u003eavailable = available;\n 391:\t\tnew_rn-\u003ern_start = start;\n 392:\t\tnew_rn-\u003ern_last = last;\n 393:\t\trange_it_insert(new_rn, rt);\n 394:\t\tif (new_rnp)\n 395:\t\t\t*new_rnp = new_rn;\n 396:\t\n 397:\t\treturn 0;\n 398:\t\n 399:\tout_free_new:\n 400:\t\tkfree_nolock(new_rn);\n 401:\t\treturn err;\n 402:\t}\n 403:\t\n 404:\tint range_tree_set_avail(struct range_tree *rt, u32 start, u32 len)\n 405:\t{\n 406:\t\treturn range_tree_set(rt, start, len, true, NULL);\n 407:\t}\n 408:\t\n 409:\tstruct range_node *range_tree_set_unavail(struct range_tree *rt, u32 start, u32 len)\n 410:\t{\n 411:\t\tstruct range_node *rn = NULL;\n 412:\t\tint err;\n 413:\t\n 414:\t\terr = range_tree_set(rt, start, len, false, \u0026rn);\n 415:\t\tif (err)\n 416:\t\t\treturn ERR_PTR(err);\n 417:\t\tif (WARN_ON_ONCE(!rn))\n 418:\t\t\treturn ERR_PTR(-EINVAL);\n 419:\t\treturn rn;\n"
}

43/3 2026/10/15 03:46 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 26330
							output: 37
							thoughts: 204
						

Thoughts:
Here's my thought process, breaking down the code segment:

**Analyzing Range Tree Set Insertion**

Okay, so I'm looking at the `range_tree_set` function and the insertion logic. First things first, it seems like we're allocating a new range node, `new_rn`, using `kmalloc_nolock`. That allocation is important, and I'm noting the flags used, especially `__GFP_ACCOUNT` and `NUMA_NO_NODE`. I also see that afterwards, the code correctly initializes several fields of `new_rn`: `available`, `rn_start`, and `rn_last`. Then, it calls `range_it_insert(new_rn, rt);` to perform the actual insertion into the tree.

Now, my immediate concern is, are we absolutely sure that `range_it_insert` or any of the underlying interval tree or red-black tree operations *don't* access any of those uninitialized `new_rn` fields *before* we've set them? This is a classic potential race condition or use-before-initialization bug scenario. Let's see... I'll check `__range_size_insert` and `__range_it_insert` to make sure nothing weird is happening.

Right, so `INTERVAL_TREE_DEFINE` is where `__range_it_insert` gets defined. Good, let's see what that looks like. Okay, I see in `INTERVAL_TREE_DEFINE`, `node->__rn_subtree_last = ...`. That's part of the node structure, so it's a field! That's concerning. That is happening. I need to see how the implementation looks.

Let's quickly check `__range_size_insert` to be sure there's nothing in there that is relevant.



44/3 2026/10/15 03:47 tool grepper
0m Args:
{
  "Expression": "__range_size_insert",
  "PathPrefixes": [
    "kernel/bpf/range_tree.c"
  ]
}

Results:
{
  "Output": "kernel/bpf/range_tree.c=106=s64 range_tree_find(struct range_tree *rt, u32 len)\n--\nkernel/bpf/range_tree.c-116-/* Insert the range into rbtree sorted by the range size */\nkernel/bpf/range_tree.c:117:static inline void __range_size_insert(struct range_node *rn,\nkernel/bpf/range_tree.c-118-\t\t\t\t       struct rb_root_cached *root)\n--\nkernel/bpf/range_tree.c=147=range_it_insert(struct range_node *rn, struct range_tree *rt)\nkernel/bpf/range_tree.c-148-{\nkernel/bpf/range_tree.c:149:\t__range_size_insert(rn, \u0026rt-\u003erange_size_root);\nkernel/bpf/range_tree.c-150-\t__range_it_insert(rn, \u0026rt-\u003eit_root);\n"
}

45/3 2026/10/15 03:47 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 27225
							output: 38
							thoughts: 26
						

Thoughts:
Okay, here's my interpretation of what's going through my mind as I approach this code snippet, tailored for a fellow expert:

**Diving into `range_tree.c`**

Alright, time to get my hands dirty. Lines 110-140 in `kernel/bpf/range_tree.c` – that's where the action is, apparently. Let's see... range trees, classic. I'm already picturing the balanced tree structure in my head, likely either an RB-Tree or something similar for efficient lookups and insertions. I wonder if they're optimizing for space or for retrieval, let's see which functions are used. I bet they're handling a specific data structure, maybe representing memory regions, network addresses, or some sort of interval data. Okay, let's start reading and see if the naming conventions give away any clues as to the actual data. Hopefully, they use descriptive variable names, but you never know. I'm expecting to see operations for insertion, deletion, and searching – the bread and butter of range trees. And of course, how they are handling contention, which is important to consider. Alright, deep breath, let's start decoding the logic.



46/3 2026/10/15 03:47 tool read-file
0m Args:
{
  "File": "kernel/bpf/range_tree.c",
  "FirstLine": 110,
  "LineCount": 35
}

Results:
{
  "Contents": " 110:\t\trn = __find_range(rt, len);\n 111:\t\tif (!rn)\n 112:\t\t\treturn -ENOENT;\n 113:\t\treturn rn-\u003ern_start;\n 114:\t}\n 115:\t\n 116:\t/* Insert the range into rbtree sorted by the range size */\n 117:\tstatic inline void __range_size_insert(struct range_node *rn,\n 118:\t\t\t\t\t       struct rb_root_cached *root)\n 119:\t{\n 120:\t\tstruct rb_node **link = \u0026root-\u003erb_root.rb_node, *rb = NULL;\n 121:\t\tu64 size = rn_size(rn);\n 122:\t\tbool leftmost = true;\n 123:\t\n 124:\t\twhile (*link) {\n 125:\t\t\trb = *link;\n 126:\t\t\tif (size \u003e rn_size(rb_to_range_node(rb))) {\n 127:\t\t\t\tlink = \u0026rb-\u003erb_left;\n 128:\t\t\t} else {\n 129:\t\t\t\tlink = \u0026rb-\u003erb_right;\n 130:\t\t\t\tleftmost = false;\n 131:\t\t\t}\n 132:\t\t}\n 133:\t\n 134:\t\trb_link_node(\u0026rn-\u003erb_range_size, rb, link);\n 135:\t\trb_insert_color_cached(\u0026rn-\u003erb_range_size, root, leftmost);\n 136:\t}\n 137:\t\n 138:\t#define START(node) ((node)-\u003ern_start)\n 139:\t#define LAST(node)  ((node)-\u003ern_last)\n 140:\t\n 141:\tINTERVAL_TREE_DEFINE(struct range_node, rn_rbnode, u32,\n 142:\t\t\t     __rn_subtree_last, START, LAST,\n 143:\t\t\t     static inline __maybe_unused,\n 144:\t\t\t     __range_it)\n"
}

47/3 2026/10/15 03:47 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 28085
							output: 37
							thoughts: 834
						

Thoughts:
**Analyzing BPF Arena Memory Management**

Okay, so I'm diving into this BPF arena memory management and need to trace data initialization to make sure nothing fishy is going on. First, I see `rb_link_node` setting `parent` and nulling out `rb_left` and `rb_right` on the RB-tree node, and initializing `__rb_parent_color`. And then `rn_size` uses the `rn_last` and `rn_start` values to calculate size, which suggests proper initialization of those members.

But wait, I need to zoom out a bit. What about `arena_free_span`? Where is that allocated and initialized? Let's go to `arena_free_span`'s definition in `kernel/bpf/arena.c`: it has a `llist_node`, `uaddr`, `page_cnt` and `flags` members. Now, I see it's allocated in `arena_free_pages()` via `kmalloc_nolock`. Okay, and right after that I see the `page_cnt`, `uaddr`, and `flags` fields are initialized. Also, `llist_add` is used, which means that `s->node` is set as well. So far, all the fields in `struct arena_free_span` are properly initialized.

Now the million-dollar question: Are any of these structures, or their members, getting copied to user space? I need to check `bpf_map_new_fd`. Okay, it calls `map->ops->map_get_file`. Let's look at `arena_map_get_file` - I see that it uses `alloc_file_clone` to create a `struct file *`. I know that creates a duplicate file and returns a `struct file *`. But how was `arena->file` created in the first place? Ah, `arena->file = anon_inode_create_getfile`. So, we clone a file and then return it. Then `bpf_map_new_fd` calls `FD_ADD` with that file pointer. I need to trace this `FD_ADD` call to see how file descriptors work.



48/3 2026/10/15 03:47 tool grepper
0m Args:
{
  "Expression": "bpf_map_new_fd",
  "PathPrefixes": [
    "kernel/bpf/syscall.c"
  ]
}

Results:
{
  "Output": "kernel/bpf/syscall.c=1192=const struct file_operations bpf_map_fops = {\n--\nkernel/bpf/syscall.c-1203-\nkernel/bpf/syscall.c:1204:int bpf_map_new_fd(struct bpf_map *map, int flags)\nkernel/bpf/syscall.c-1205-{\n--\nkernel/bpf/syscall.c=1651=static int map_create(union bpf_attr *attr, bpfptr_t uattr, struct bpf_common_attr *attr_common,\n--\nkernel/bpf/syscall.c-1693-\nkernel/bpf/syscall.c:1694:\terr = bpf_map_new_fd(map, f_flags);\nkernel/bpf/syscall.c-1695-\tif (err \u003c 0) {\n--\nkernel/bpf/syscall.c=4967=static int bpf_map_get_fd_by_id(const union bpf_attr *attr)\n--\nkernel/bpf/syscall.c-4995-\nkernel/bpf/syscall.c:4996:\tfd = bpf_map_new_fd(map, f_flags);\nkernel/bpf/syscall.c-4997-\tif (fd \u003c 0)\n"
}

49/3 2026/10/15 03:47 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 29780
							output: 37
							thoughts: 22
						

Thoughts:
Okay, let's dive into this code.

**Diving into `bpf_map_new_fd`**

Alright, I'm going to take a look at `bpf_map_new_fd`, specifically around line 1204. I need to understand how the file descriptor for a BPF map is created and what's going on behind the scenes. This function is critical for how our BPF programs interact with the kernel-managed map data structures, so a solid grasp of its workings is essential. I need to figure out the map's lifecycle and how this function fits into the overall scheme of BPF program-map interaction. I'm expecting to see things like map creation arguments, resource allocation, and, of course, the actual file descriptor creation. I anticipate encountering some intricate interactions, likely involving system calls. I'll need to dissect the logic to identify any potential performance bottlenecks or subtle security implications within this crucial section of code.



50/3 2026/10/15 03:47 tool read-file
0m Args:
{
  "File": "kernel/bpf/syscall.c",
  "FirstLine": 1200,
  "LineCount": 25
}

Results:
{
  "Contents": "1200:\t\t.poll\t\t= bpf_map_poll,\n1201:\t\t.get_unmapped_area = bpf_get_unmapped_area,\n1202:\t};\n1203:\t\n1204:\tint bpf_map_new_fd(struct bpf_map *map, int flags)\n1205:\t{\n1206:\t\tint ret;\n1207:\t\n1208:\t\tret = security_bpf_map(map, OPEN_FMODE(flags));\n1209:\t\tif (ret \u003c 0)\n1210:\t\t\treturn ret;\n1211:\t\n1212:\t\tif (map-\u003eops-\u003emap_get_file)\n1213:\t\t\treturn FD_ADD(flags | O_CLOEXEC, map-\u003eops-\u003emap_get_file(map, flags));\n1214:\t\treturn anon_inode_getfd(\"bpf-map\", \u0026bpf_map_fops, map,\n1215:\t\t\t\t\tflags | O_CLOEXEC);\n1216:\t}\n1217:\t\n1218:\tint bpf_get_file_flag(int flags)\n1219:\t{\n1220:\t\tif ((flags \u0026 BPF_F_RDONLY) \u0026\u0026 (flags \u0026 BPF_F_WRONLY))\n1221:\t\t\treturn -EINVAL;\n1222:\t\tif (flags \u0026 BPF_F_RDONLY)\n1223:\t\t\treturn O_RDONLY;\n1224:\t\tif (flags \u0026 BPF_F_WRONLY)\n"
}

51/3 2026/10/15 03:47 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 30458
							output: 19
							thoughts: 27
						

Thoughts:
Here's my thought process, as requested:

**Deconstructing `FD_ADD`**

Okay, `FD_ADD`. That rings a bell, probably something related to file descriptors, but I need to be precise. Let's not make assumptions. I'll need to dig into the definition to be absolutely certain. The most direct approach is a quick `grep` for `FD_ADD` in the relevant codebase or include files. That should reveal what the macro expands to, assuming it *is* a macro. If that doesn't yield results, I'll need to double check the definitions. This is all about eliminating uncertainty and confirming my understanding of that macro's function within the broader context.



52/3 2026/10/15 03:47 tool grepper
0m Args:
{
  "Expression": "#define FD_ADD"
}

Results:
{
  "Output": "include/linux/file.h=171=static inline int class_fd_prepare_lock_err(const struct fd_prepare *fdf)\n--\ninclude/linux/file.h-251- */\ninclude/linux/file.h:252:#define FD_ADD(_fd_flags, _file_owned) \\\ninclude/linux/file.h-253-\t__FD_ADD(__UNIQUE_ID(fd_prepare), _fd_flags, _file_owned)\n"
}

53/3 2026/10/15 03:47 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 30781
							output: 32
							thoughts: 844
						

Thoughts:
**Analyzing the BPF Arena Patch Series**

Okay, so I've just had `FD_ADD` install a file in the user file descriptor table, returning the new FD integer. Now, let's dive into this patch series. My goal is to understand what problem this is actually solving and how the solution works, with a keen eye for potential vulnerabilities, especially memory leaks.

This patch series is focused on the `bpf_arena` mechanism. Essentially, `bpf_arena` manages memory pages that can be brought in via user-space memory accesses using `arena_vm_fault`, or allocated through BPF programs using `bpf_arena_alloc_pages`. Pages can also be freed via `bpf_arena_free_pages`.

Previously, `zap_pages` was the mechanism for freeing pages. It did this by iterating through `arena->vma_list` and calling `zap_vma_range`. However, to avoid deadlocks with `arena_vm_close` (which takes an `mmap_write_lock` then `arena->lock`), `zap_pages` dropped `arena->lock`, took an `mmap_read_lock`, and used `vml->zap_gen` and so on.

The problems that resulted from this old way were many, including races, such as:

*   Freeing arena pages concurrently with TLB flushes or user accesses.
*   Faulting and freeing pages at the same time.
*   Reallocating a page while a deferred or concurrent free was still in progress, before the TLB flush was done.

The patch series is designed to tackle these race conditions by implementing the following changes:

1.  Associating `arena->file` with an anonymous inode and address_space. This change allows pages to be mapped, so that `folio->index` and `folio->mapping` are set, allowing `zap_pages` to use `i_mmap_lock_read(mapping)` and `mapping_rmap_tree_foreach(...)` instead of manually tracking VMAs with `arena->vma_list`.
2.  Using `arena_opref` to coordinate faults and frees, differentiating between `ARENA_OPREF_FAULT` and `ARENA_OPREF_FREE`.
3.  Employing `folio_lock_or_retry()` during fault operations and `wait_for_faults` during frees to synchronize the faulting folios.
4.  Introducing a range tree. This tree marks ranges as "unavailable" during free operations using `range_tree_set_unavail`, preventing concurrent faults or reallocations from re-using the range until kernel PTEs are cleared, the TLB is flushed, and user mappings are removed (`range_tree_make_avail`).
5.  In `arena_map_free`, draining IRQ work and the workqueue safely to free any remaining spans and pages.

Now, let's meticulously examine whether any uninitialized memory could be inadvertently read or leaked. Here's what I'm looking at:

*   Does this patch send any kernel structures to user space? The only data returned is an `fd` (an int) by `bpf_map_new_fd`. In `arena_vm_fault`, the patch sets `vmf->page = page; fault_ret = VM_FAULT_LOCKED;`.

*   I'm now diving into the page fault handling in `arena_vm_fault`. Specifically:

    ```c
	page = vmalloc_to_page((void *)kaddr);
	if (page) {
		/*
		 * If page is present that means user vma was zapped
		 * and page was not freed. It's still in vmalloc space.
		 * Same condition as if (zap_pages) was not called for this page.
		 */
		goto out;
	}

	if (!new_page) {
		/*
		 * Preallocation failed; try the non-blocking allocator since
		 * we cannot sleep here.
		 */
		new_page = bpf_alloc_page(map->numa_node, false);
		if (!new_page) {
			fault_ret = VM_FAULT_OOM;
			goto out_err_locked_memcg;
		}
	}
    ```

    Aha! The critical point is `bpf_alloc_page`. Is the memory zero-initialized by the `bpf_alloc_page` function? That's the key question. I need to know exactly how `bpf_alloc_page` behaves to determine if we have a potential vulnerability.



54/3 2026/10/15 03:47 tool grepper
0m Args:
{
  "Expression": "bpf_alloc_page",
  "PathPrefixes": [
    "kernel/bpf/"
  ]
}

Results:
{
  "Output": "kernel/bpf/arena.c=332=static struct bpf_map *arena_map_alloc(union bpf_attr *attr)\n--\nkernel/bpf/arena.c-380-\nkernel/bpf/arena.c:381:\tarena-\u003escratch_page = bpf_alloc_page(NUMA_NO_NODE, true);\nkernel/bpf/arena.c-382-\tif (!arena-\u003escratch_page)\n--\nkernel/bpf/arena.c=571=static vm_fault_t arena_vm_fault(struct vm_fault *vmf)\n--\nkernel/bpf/arena.c-648-\t\t */\nkernel/bpf/arena.c:649:\t\tnew_page = bpf_alloc_page(map-\u003enuma_node, false);\nkernel/bpf/arena.c-650-\t\tif (!new_page) {\n--\nkernel/bpf/arena.c=893=static long arena_alloc_pages(struct bpf_arena *arena, long uaddr, long page_cnt, int node_id,\n--\nkernel/bpf/arena.c-925-\nkernel/bpf/arena.c:926:\tret = bpf_alloc_pages(node_id, page_cnt, \u0026pages, sleepable);\nkernel/bpf/arena.c-927-\tif (ret)\n--\nkernel/bpf/syscall.c=599=static bool can_alloc_pages(void)\n--\nkernel/bpf/syscall.c-604-\nkernel/bpf/syscall.c:605:struct page *bpf_alloc_page(int nid, bool sleepable)\nkernel/bpf/syscall.c-606-{\n--\nkernel/bpf/syscall.c=616=void bpf_free_pages(struct llist_head *pages)\n--\nkernel/bpf/syscall.c-625-\nkernel/bpf/syscall.c:626:int bpf_alloc_pages(int nid, unsigned long nr_pages,\nkernel/bpf/syscall.c-627-\t\t    struct llist_head *pages, bool sleepable)\n--\nkernel/bpf/syscall.c-632-\tfor (i = 0; i \u003c nr_pages; i++) {\nkernel/bpf/syscall.c:633:\t\tpg = bpf_alloc_page(nid, sleepable);\nkernel/bpf/syscall.c-634-\t\tif (!pg)\n"
}

55/3 2026/10/15 03:47 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 33290
							output: 36
							thoughts: 23
						

Thoughts:
Okay, let's dive into this. Here's my thought process on dissecting `bpf_alloc_page`:

**Diving into `bpf_alloc_page` in `kernel/bpf/syscall.c`**

Alright, I need to understand how the kernel handles page allocation within the BPF subsystem. My first instinct is to locate the `bpf_alloc_page` function within `kernel/bpf/syscall.c`. I expect to find the low-level memory allocation logic there, the core building block for BPF's memory management. I'm keen to examine the nuances of this allocation, particularly within the context of BPF's security constraints and potential for sandboxing. I'll be looking for how they ensure isolation, prevent memory corruption, and deal with resource limits. I suspect this function holds the key to how BPF programs access, create and manage their memory maps. I anticipate seeing specific checks and guards implemented within this allocation routine to prevent any form of exploitation.



56/3 2026/10/15 03:47 tool read-file
0m Args:
{
  "File": "kernel/bpf/syscall.c",
  "FirstLine": 600,
  "LineCount": 20
}

Results:
{
  "Contents": " 600:\t{\n 601:\t\treturn preempt_count() == 0 \u0026\u0026 !irqs_disabled() \u0026\u0026\n 602:\t\t\t!IS_ENABLED(CONFIG_PREEMPT_RT);\n 603:\t}\n 604:\t\n 605:\tstruct page *bpf_alloc_page(int nid, bool sleepable)\n 606:\t{\n 607:\t\tif (!sleepable || !can_alloc_pages())\n 608:\t\t\treturn alloc_pages_nolock(__GFP_ACCOUNT, nid, 0);\n 609:\t\n 610:\t\treturn alloc_pages_node(nid,\n 611:\t\t\t\t\tGFP_KERNEL | __GFP_ZERO | __GFP_ACCOUNT\n 612:\t\t\t\t\t| __GFP_NOWARN | __GFP_RETRY_MAYFAIL,\n 613:\t\t\t\t\t0);\n 614:\t}\n 615:\t\n 616:\tvoid bpf_free_pages(struct llist_head *pages)\n 617:\t{\n 618:\t\tstruct llist_node *node;\n 619:\t\tstruct page *page, *tmp;\n"
}

57/3 2026/10/15 03:47 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 33866
							output: 20
							thoughts: 26
						

Thoughts:
Here's my attempt at summarizing the thought process, tailored for an expert audience:

**Investigating `alloc_pages_nolock`**

Hold on a second. I need to make sure I'm crystal clear on this `alloc_pages_nolock` function. My intuition is telling me there might be a subtle nuance that I'm overlooking, especially considering the lack of a lock. Time to dive into the definition and the context of its use, really understand what that function is up to. I need to refresh my understanding of its non-locking behaviour. Gotta make sure I'm not missing something critical when considering this path.



58/3 2026/10/15 03:47 tool grepper
0m Args:
{
  "Expression": "alloc_pages_nolock"
}

Results:
{
  "Output": "include/linux/gfp.h=25=static inline bool gfpflags_allow_spinning(const gfp_t gfp_flags)\n--\ninclude/linux/gfp.h-30-\t * All GFP_* flags including GFP_NOWAIT use one or both flags.\ninclude/linux/gfp.h:31:\t * alloc_pages_nolock() is the only API that doesn't specify either flag.\ninclude/linux/gfp.h-32-\t *\n--\ninclude/linux/gfp.h-36-\t * on any locks (i.e. only trylocks). There is no high level\ninclude/linux/gfp.h:37:\t * GFP_$FOO flag for this use in alloc_pages_nolock() as the\ninclude/linux/gfp.h-38-\t * regular page allocator doesn't fully support this\n--\ninclude/linux/gfp.h=309=static inline struct page *alloc_page_vma_noprof(gfp_t gfp,\n--\ninclude/linux/gfp.h-317-\ninclude/linux/gfp.h:318:struct page *alloc_pages_nolock_noprof(gfp_t gfp_flags, int nid, unsigned int order);\ninclude/linux/gfp.h:319:#define alloc_pages_nolock(...)\t\t\talloc_hooks(alloc_pages_nolock_noprof(__VA_ARGS__))\ninclude/linux/gfp.h-320-\n--\nkernel/bpf/syscall.c=605=struct page *bpf_alloc_page(int nid, bool sleepable)\n--\nkernel/bpf/syscall.c-607-\tif (!sleepable || !can_alloc_pages())\nkernel/bpf/syscall.c:608:\t\treturn alloc_pages_nolock(__GFP_ACCOUNT, nid, 0);\nkernel/bpf/syscall.c-609-\n--\nmm/page_alloc.c=5343=static inline bool alloc_nolock_allowed(void)\n--\nmm/page_alloc.c-5355-/*\nmm/page_alloc.c:5356: * GFP flags to set for ALLOC_NOLOCK i.e. alloc_pages_nolock().\nmm/page_alloc.c-5357- *\n--\nmm/page_alloc.c-5363- *\nmm/page_alloc.c:5364: * Specify __GFP_NOWARN since failing alloc_pages_nolock() is not a reason\nmm/page_alloc.c-5365- * to warn. Also warn would trigger printk() which is unsafe from\n--\nmm/page_alloc.c-5373- * Though __GFP_NOMEMALLOC is not checked in the code path below,\nmm/page_alloc.c:5374: * specify it here to highlight that alloc_pages_nolock()\nmm/page_alloc.c-5375- * doesn't want to deplete reserves.\n--\nmm/page_alloc.c=5569=EXPORT_SYMBOL(__free_pages);\n--\nmm/page_alloc.c-5572- * Can be called while holding raw_spin_lock or from IRQ and NMI for any\nmm/page_alloc.c:5573: * page type (not only those that came from alloc_pages_nolock)\nmm/page_alloc.c-5574- */\n--\nmm/page_alloc.c=8041=struct page *alloc_frozen_pages_nolock_noprof(gfp_t gfp_flags, int nid, unsigned int order)\n--\nmm/page_alloc.c-8048-/**\nmm/page_alloc.c:8049: * alloc_pages_nolock - opportunistic reentrant allocation from any context\nmm/page_alloc.c-8050- * @gfp_flags: GFP flags. Only __GFP_ACCOUNT, plus some flags that get set\n--\nmm/page_alloc.c-8056- * call from any context where RCU is watching (from atomic, NMI, and also\nmm/page_alloc.c:8057: * reentrant allocator -\u003e tracepoint -\u003e alloc_pages_nolock_noprof).\nmm/page_alloc.c-8058- * Allocation is best effort and to be expected to fail easily so nobody should\n--\nmm/page_alloc.c-8064- */\nmm/page_alloc.c:8065:struct page *alloc_pages_nolock_noprof(gfp_t gfp_flags, int nid, unsigned int order)\nmm/page_alloc.c-8066-{\n--\nmm/page_alloc.c-8073-}\nmm/page_alloc.c:8074:EXPORT_SYMBOL_GPL(alloc_pages_nolock_noprof);\n--\nmm/page_owner.c=316=void __reset_page_owner(struct page *page, unsigned short order)\n--\nmm/page_owner.c-334-\t * to prevent issues in stack_depot_save().\nmm/page_owner.c:335:\t * This is similar to alloc_pages_nolock() gfp flags, but only used\nmm/page_owner.c-336-\t * to signal stack_depot to avoid spin_locks.\n"
}

59/3 2026/10/15 03:47 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 35366
							output: 19
							thoughts: 1680
						

Thoughts:
**Deep Dive into the BPF Arena Patch**

Okay, so `bpf_alloc_page` *wasn't* introduced here, that's good to know. I need to focus on what *this* patch did to `arena.c`. Let me reconstruct the changes step by step.

Right, the key changes in `kernel/bpf/arena.c` are: First, they've added `arena->file` to the `bpf_arena` struct and initialized it using `anon_inode_create_getfile`. That's a new backing file for the arena. Then, a few atomics and a wait queue (`opref` and `opwait`) were added. There are functions to manage an operation reference count, `arena_opref_get` and `arena_opref_put`.

They've also added flags to `struct arena_free_span`. Interesting. In `apply_range_set_cb`, there is a significant change in how the page is mapped, specifically its index and mapping. The `arena_release_folio` function now just returns false. The arena's address space operations have been updated, with `noop_dirty_folio` and `arena_release_folio`.

`arena_put_page` now sets `page->mapping` to NULL, locks and unlocks the page, and then frees it. `arena_map_free` now disables a work queue and frees the backing file.

`arena_vm_fault` uses `arena_opref_get` and `arena_opref_put` and now interacts with `bpf_map_inc` and `bpf_map_put`. The fault handling seems to have some retries in it due to the `range_tree_clear` returning `-EAGAIN`. Also, there's a `get_page` call and folio locking.

`arena_map_get_file` is the interesting part, which appears to allocate a file clone of the arena's file and sets its private data. The file mode is nonotify.

Other new functions like `zap_pages`, `wait_for_faults`, `arena_free_pages`, and `arena_free_worker` have been introduced. `arena_free_pages` uses the opref count and some range tree manipulation. They are also waiting on faults and setting flags on spans. `arena_free_worker` seems to manage the actual freeing of memory, calling the same functions.

Now to `range_tree.c`. A `bool available` flag has been added to `struct range_node`. Functions `range_available`, `range_node_mark_available`, and `__find_range` check this availability. `range_tree_clear` returns -EAGAIN if a range isn't available, and splits of nodes maintain availability. `range_tree_clear` also calls `kfree_nolock(new_rn)`. The `range_tree_set` function's behavior with availability and merging is also noteworthy. The `range_tree_merge` calls are conditional on `range_available`.

Now, are any of those structs uninitialized? Let's check.

For `range_node`, all the fields seem to be initialized before the node is used. That's good. And the `range_node` struct is entirely internal, so no user-space exposure. Same goes for `arena_free_span` - all fields are explicitly set, and it's internal. `arena_map_alloc` has a couple of atomic and waitqueue initializations and sets `arena->file`. `arena_map_get_file` does some setup on the file clone, and then returns it. But does `alloc_file_clone` leave fields uninitialized? This needs more investigation.



60/3 2026/10/15 03:47 tool grepper
0m Args:
{
  "Expression": "alloc_file_clone"
}

Results:
{
  "Output": "Documentation/filesystems/porting.rst=780=so the caller needs to drop the inode reference it held.\nDocumentation/filesystems/porting.rst:781:alloc_file_clone(file, flags, ops) does not affect any caller's references.\nDocumentation/filesystems/porting.rst-782-On success you get a new struct file sharing the mount/dentry with the\n--\nfs/file_table.c=469=EXPORT_SYMBOL_GPL(alloc_file_pseudo_noaccount);\nfs/file_table.c-470-\nfs/file_table.c:471:struct file *alloc_file_clone(struct file *base, int flags,\nfs/file_table.c-472-\t\t\t\tconst struct file_operations *fops)\n--\nfs/pipe.c=1007=int create_pipe_files(struct file **res, int flags)\n--\nfs/pipe.c-1036-\nfs/pipe.c:1037:\tres[0] = alloc_file_clone(f, O_RDONLY | (flags \u0026 O_NONBLOCK),\nfs/pipe.c-1038-\t\t\t\t  \u0026pipeanon_fops);\n--\ninclude/linux/file.h=28=extern struct file *alloc_file_pseudo_noaccount(struct inode *, struct vfsmount *,\ninclude/linux/file.h-29-\tconst char *, int flags, const struct file_operations *);\ninclude/linux/file.h:30:extern struct file *alloc_file_clone(struct file *, int flags,\ninclude/linux/file.h-31-\tconst struct file_operations *);\n--\nipc/shm.c=1521=long do_shmat(int shmid, char __user *shmaddr, int shmflg,\n--\nipc/shm.c-1628-\nipc/shm.c:1629:\tfile = alloc_file_clone(base, f_flags,\nipc/shm.c-1630-\t\t\t  is_file_hugepages(base) ?\n--\nkernel/bpf/arena.c=778=static struct file *arena_map_get_file(struct bpf_map *map, int flags)\n--\nkernel/bpf/arena.c-782-\nkernel/bpf/arena.c:783:\tfile = alloc_file_clone(arena-\u003efile, flags \u0026 (O_ACCMODE | O_NONBLOCK),\nkernel/bpf/arena.c-784-\t\t\t\t\u0026bpf_map_fops);\n"
}

61/3 2026/10/15 03:47 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 38521
							output: 382
							thoughts: 3074
						

Thoughts:
**KMSAN Assessment: Concurrency Bug Fix in BPF Arena**

Okay, so I've been tasked with evaluating this patch series. My initial thought is to determine if this requires KMSAN, given the changes to `alloc_file_clone` and specifically how the BPF arena functions. The key question I'm asking myself: Could these changes introduce any uninitialized memory issues?

I've carefully examined `arena_vm_fault` because it's the critical piece here, the code that maps pages into userspace.  It looks like this patch is changing how pages are acquired in `arena_vm_fault`, going from a direct `page_ref_add` and simple return to using `get_page` and `folio_lock_or_retry`. Before I was concerned about changes to page allocation, but after reviewing `bpf_alloc_page`, which remains untouched, it's clear this isn't about *new* allocation bugs. The core functionality – allocating a `new_page` if needed or using a page already in vmalloc – is fundamentally unchanged. The changes only relate to the reference counting and locking around the pages. The addition of mapping to `arena->file->f_mapping` for reverse mapping and page cache is important for VMA integration but not directly a source of uninitialized memory.

So, let's look at the "rules".

1.  **Kernel structures sent to userspace:**  There's no `copy_to_user`, no netlink, no ioctl output, nothing that directly puts kernel memory into user space, not even an `fd` that's passed. So, no.

2.  **Conditional logic based on potentially uninitialized variables:**  I've checked every single variable in the patch. I've looked at all the new or modified functions and they all appear initialized. I've double checked `atomic_read` and ensured that `arena->opref` is initialized with `atomic_set`. The `range_node` available flags look good too. Everything seems properly initialized, from `arena_free_span` to `struct range_node` itself.

3.  **Allocation of complex data structures:** The allocation and initialization of `struct arena_free_span`, `range_node` and `struct bpf_arena` all are initialized before being used. This isn't KMSAN territory.

4.  **Bounds checks, lengths, or logic that allows access to uninitialized bytes of existing buffers:** This patch seems to be focused on *concurrency* in the BPF arena and not memory corruption. I can see the changes deal with synchronization, with atomic operations and locking. But, the real bug risks here are race conditions, use-after-free, double frees, and locking issues, not uninitialized memory.

Based on these points, *this patch series does NOT introduce any uninitialized memory risks.*  Therefore, KMSAN is **not** needed. These changes are focused on correctness and concurrency, which are already covered by KASAN and LOCKDEP. This is a fix for race conditions, use-after-free, double-free, and locking bugs. KASAN is the appropriate tool here.



62/3 2026/10/15 03:48 tool set-results
0m Args:
{
  "KMSANReasoning": "The patch series refactors concurrency management, page fault handling, and page freeing logic for BPF arena maps (BPF_MAP_TYPE_ARENA). Specifically, it introduces an anonymous backing file with address_space_operations for rmap-based page zapping (eliminating VMA list lock inversion), an atomic operation reference counter (arena_opref) and wait queue to synchronize faults against frees, range availability tracking in the range tree (range_node available flag, range_tree_set_unavail, range_tree_make_avail), folio locking during fault admission, and state flags for deferred free spans.\n\nPotential bugs introduced or affected by these changes are concurrency bugs, use-after-free (e.g. accessing freed pages or range/span nodes during races), invalid/double free, or deadlock/locking issues. These failure modes are reliably detected by standard KASAN and LOCKDEP configurations.\n\nKMSAN is not applicable here because:\n1. No uninitialized memory or kernel structures are copied or leaked to user space (arena_map_get_file creates a cloned struct file returned via FD_ADD as a standard file descriptor integer).\n2. All newly added or modified data structures (struct range_node, struct arena_free_span) have all their fields explicitly assigned upon allocation before insertion into rb-trees or lockless lists.\n3. No branching or conditional logic depends on uninitialized scalar variables or struct padding.\n4. Memory buffer bounds and lengths remain standard page-aligned calculations and do not expose uninitialized memory reads.\n\nBecause there are no uninitialized memory access risks that would evade KASAN and require KMSAN, a dedicated KMSAN fuzzing session is not warranted.",
  "NeedsKMSAN": false
}

Results:
{
  "KMSANReasoning": "The patch series refactors concurrency management, page fault handling, and page freeing logic for BPF arena maps (BPF_MAP_TYPE_ARENA). Specifically, it introduces an anonymous backing file with address_space_operations for rmap-based page zapping (eliminating VMA list lock inversion), an atomic operation reference counter (arena_opref) and wait queue to synchronize faults against frees, range availability tracking in the range tree (range_node available flag, range_tree_set_unavail, range_tree_make_avail), folio locking during fault admission, and state flags for deferred free spans.\n\nPotential bugs introduced or affected by these changes are concurrency bugs, use-after-free (e.g. accessing freed pages or range/span nodes during races), invalid/double free, or deadlock/locking issues. These failure modes are reliably detected by standard KASAN and LOCKDEP configurations.\n\nKMSAN is not applicable here because:\n1. No uninitialized memory or kernel structures are copied or leaked to user space (arena_map_get_file creates a cloned struct file returned via FD_ADD as a standard file descriptor integer).\n2. All newly added or modified data structures (struct range_node, struct arena_free_span) have all their fields explicitly assigned upon allocation before insertion into rb-trees or lockless lists.\n3. No branching or conditional logic depends on uninitialized scalar variables or struct padding.\n4. Memory buffer bounds and lengths remain standard page-aligned calculations and do not expose uninitialized memory reads.\n\nBecause there are no uninitialized memory access risks that would evade KASAN and require KMSAN, a dedicated KMSAN fuzzing session is not warranted.",
  "NeedsKMSAN": false
}

LLM Calls Summary:
Total Calls Total Tokens Avg Tokens Total Duration (Seconds) Avg Duration (Seconds)
Tool Calls Summary:
Total Calls Total Duration (Seconds) Avg Duration (Seconds)