AI Trajectory


Trajectory: (Expand/Collapse All)
Seq Timestamp Type Name Duration
0/0 2026/11/25 13:48 flow patch-triage
16m Args:
null

Results:
{
  "EnableConfigs": [
    "SLUB",
    "RUST"
  ],
  "FocusSymbols": [
    "kmem_cache_prefill_sheaf",
    "kmem_cache_return_sheaf",
    "kmem_cache_refill_sheaf",
    "kmem_cache_alloc_from_sheaf_noprof",
    "radix_tree_node_ctor",
    "rust_helper_xas_result",
    "rust_helper_xa_zero_to_null",
    "rust_helper_xas_error"
  ],
  "KMSANReasoning": "The patch series introduces Rust abstractions for SLUB allocator sheaves (`rust/kernel/mm/sheaf.rs`) and XArray entry/preallocation operations (`rust/kernel/xarray.rs`, `rust/kernel/xarray/entry.rs`), along with exporting several existing SLUB sheaf functions in `mm/slub.c` and updating `radix_tree_init` to configure sheaf capacity.\n\nKMSAN is not required for the following reasons:\n1. No user-space copy boundaries (such as `copy_to_user`, ioctl outputs, netlink attributes, or BPF buffers) are introduced or modified.\n2. All data structures initialized in both C and Rust are fully initialized before use: `struct kmem_cache_args` is zero-initialized, `struct xa_state` explicitly sets all fields, and `radix_tree_node` / `XArrayNode` instances are explicitly zeroed via `radix_tree_node_ctor` (`memset(node, 0, sizeof(*node))`).\n3. Any potential bugs in this patch series involve reference counting, lock guard behavior, lifetime/ownership conversions (`into_ptr`, `static_from_ptr`), or slab management, which fall squarely under KASAN, LOCKDEP, and standard kernel debugging facilities rather than KMSAN uninitialized memory detection.",
  "NeedsKMSAN": false,
  "Reasoning": "The patch series modifies core memory management and data structure logic. It configures the global radix_tree_node_cachep with sheaf capacity support (.sheaf_capacity = 64), which alters SLUB fast-path allocation and freeing behavior (percpu sheaves) for all radix tree and XArray nodes across the kernel. It also exports the SLUB sheaf management API, moves XArray helpers to public headers, and adds Rust abstractions for SLUB sheaves and XArray entry operations. These changes touch reachable core paths and warrant fuzzing.",
  "WorthFuzzing": true
}

1/1 2026/11/25 13:48 action read-patch-diff
0m Args:
null

Results:
{
  "PatchDiff": "commit 8f525438224f17da9edd0c9c7e7da757f585c4fb\nAuthor: syz-cluster \u003ctriage@syzkaller.com\u003e\nDate:   Wed Nov 25 13:48:27 2026 +0000\n\n    syz-cluster: applied patch under review\n\ndiff --git a/MAINTAINERS b/MAINTAINERS\nindex 222b7fc2c3aab8..845503be1f289b 100644\n--- a/MAINTAINERS\n+++ b/MAINTAINERS\n@@ -30500,6 +30500,7 @@ B:\thttps://github.com/Rust-for-Linux/linux/issues\n C:\thttps://rust-for-linux.zulipchat.com\n T:\tgit https://github.com/Rust-for-Linux/linux.git xarray-next\n F:\trust/kernel/xarray.rs\n+F:\trust/kernel/xarray/\n \n XBOX DVD IR REMOTE\n M:\tBenjamin Valentin \u003cbenpicco@googlemail.com\u003e\ndiff --git a/include/linux/radix-tree.h b/include/linux/radix-tree.h\nindex 057edc4cbb6ef2..ac5fc299399cfb 100644\n--- a/include/linux/radix-tree.h\n+++ b/include/linux/radix-tree.h\n@@ -470,4 +470,7 @@ static __always_inline void __rcu **radix_tree_next_slot(void __rcu **slot,\n \t     slot = radix_tree_next_slot(slot, iter,\t\t\t\\\n \t\t\t\tRADIX_TREE_ITER_TAGGED | tag))\n \n+\n+void radix_tree_node_ctor(void *arg);\n+\n #endif /* _LINUX_RADIX_TREE_H */\ndiff --git a/include/linux/xarray.h b/include/linux/xarray.h\nindex be850174e802e6..db2520864aaa7f 100644\n--- a/include/linux/xarray.h\n+++ b/include/linux/xarray.h\n@@ -191,6 +191,17 @@ static inline bool xa_is_zero(const void *entry)\n \treturn unlikely(entry == XA_ZERO_ENTRY);\n }\n \n+/**\n+ * xa_zero_to_null() - Convert an internal zero entry into a NULL pointer.\n+ * @entry: XArray entry.\n+ *\n+ * Return: %NULL if @entry is a zero entry, @entry otherwise.\n+ */\n+static inline void *xa_zero_to_null(void *entry)\n+{\n+\treturn xa_is_zero(entry) ? NULL : entry;\n+}\n+\n /**\n  * xa_is_err() - Report whether an XArray operation returned an error\n  * @entry: Result from calling an XArray function\n@@ -1437,6 +1448,21 @@ static inline int xas_error(const struct xa_state *xas)\n \treturn xa_err(xas-\u003exa_node);\n }\n \n+/**\n+ * xas_result() - Extract the result of an XArray operation.\n+ * @xas: XArray operation state.\n+ * @curr: Entry returned by the operation.\n+ *\n+ * Return: @curr if the operation succeeded, the error encoded in @xas\n+ * otherwise.\n+ */\n+static inline void *xas_result(struct xa_state *xas, void *curr)\n+{\n+\tif (xas_error(xas))\n+\t\tcurr = xas-\u003exa_node;\n+\treturn curr;\n+}\n+\n /**\n  * xas_set_err() - Note an error in the xa_state.\n  * @xas: XArray operation state.\ndiff --git a/lib/radix-tree.c b/lib/radix-tree.c\nindex 976b9bd02a1b5d..ddd67ce672f5c4 100644\n--- a/lib/radix-tree.c\n+++ b/lib/radix-tree.c\n@@ -33,6 +33,7 @@\n  * Radix tree node cache.\n  */\n struct kmem_cache *radix_tree_node_cachep;\n+EXPORT_SYMBOL(radix_tree_node_cachep);\n \n /*\n  * The radix tree is variable-height, so an insert operation not only has\n@@ -1566,14 +1567,14 @@ void idr_destroy(struct idr *idr)\n }\n EXPORT_SYMBOL(idr_destroy);\n \n-static void\n-radix_tree_node_ctor(void *arg)\n+void radix_tree_node_ctor(void *arg)\n {\n \tstruct radix_tree_node *node = arg;\n \n \tmemset(node, 0, sizeof(*node));\n \tINIT_LIST_HEAD(\u0026node-\u003eprivate_list);\n }\n+EXPORT_SYMBOL(radix_tree_node_ctor);\n \n static int radix_tree_cpu_dead(unsigned int cpu)\n {\n@@ -1598,10 +1599,16 @@ void __init radix_tree_init(void)\n \tBUILD_BUG_ON(RADIX_TREE_MAX_TAGS + __GFP_BITS_SHIFT \u003e 32);\n \tBUILD_BUG_ON(ROOT_IS_IDR \u0026 ~GFP_ZONEMASK);\n \tBUILD_BUG_ON(XA_CHUNK_SIZE \u003e 255);\n-\tradix_tree_node_cachep = kmem_cache_create(\"radix_tree_node\",\n-\t\t\tsizeof(struct radix_tree_node), 0,\n-\t\t\tSLAB_PANIC | SLAB_RECLAIM_ACCOUNT,\n-\t\t\tradix_tree_node_ctor);\n+\n+\tstruct kmem_cache_args args = {\n+\t\t.ctor = radix_tree_node_ctor,\n+\t\t.sheaf_capacity = 64,\n+\t};\n+\n+\tradix_tree_node_cachep = kmem_cache_create(\n+\t\t\"radix_tree_node\", sizeof(struct radix_tree_node), \u0026args,\n+\t\tSLAB_PANIC | SLAB_RECLAIM_ACCOUNT);\n+\n \tret = cpuhp_setup_state_nocalls(CPUHP_RADIX_DEAD, \"lib/radix:dead\",\n \t\t\t\t\tNULL, radix_tree_cpu_dead);\n \tWARN_ON(ret \u003c 0);\ndiff --git a/lib/xarray.c b/lib/xarray.c\nindex bfe7bef80f34eb..49fbec5f6c38e8 100644\n--- a/lib/xarray.c\n+++ b/lib/xarray.c\n@@ -437,11 +437,6 @@ static unsigned long max_index(void *entry)\n \treturn (XA_CHUNK_SIZE \u003c\u003c xa_to_node(entry)-\u003eshift) - 1;\n }\n \n-static inline void *xa_zero_to_null(void *entry)\n-{\n-\treturn xa_is_zero(entry) ? NULL : entry;\n-}\n-\n static void xas_shrink(struct xa_state *xas)\n {\n \tstruct xarray *xa = xas-\u003exa;\n@@ -1627,13 +1622,6 @@ void *xa_load(struct xarray *xa, unsigned long index)\n }\n EXPORT_SYMBOL(xa_load);\n \n-static void *xas_result(struct xa_state *xas, void *curr)\n-{\n-\tif (xas_error(xas))\n-\t\tcurr = xas-\u003exa_node;\n-\treturn curr;\n-}\n-\n /**\n  * __xa_erase() - Erase this entry from the XArray while locked.\n  * @xa: XArray.\ndiff --git a/mm/slub.c b/mm/slub.c\nindex cd671b93471918..21811b9ff791f4 100644\n--- a/mm/slub.c\n+++ b/mm/slub.c\n@@ -5292,6 +5292,7 @@ kmem_cache_prefill_sheaf(struct kmem_cache *s, gfp_t gfp, unsigned int size)\n \n \treturn sheaf;\n }\n+EXPORT_SYMBOL(kmem_cache_prefill_sheaf);\n \n /*\n  * Use this to return a sheaf obtained by kmem_cache_prefill_sheaf()\n@@ -5347,6 +5348,7 @@ void kmem_cache_return_sheaf(struct kmem_cache *s, gfp_t gfp,\n \tbarn_put_full_sheaf(barn, sheaf);\n \tstat(s, BARN_PUT);\n }\n+EXPORT_SYMBOL(kmem_cache_return_sheaf);\n \n /*\n  * Refill a sheaf previously returned by kmem_cache_prefill_sheaf to at least\n@@ -5402,6 +5404,7 @@ int kmem_cache_refill_sheaf(struct kmem_cache *s, gfp_t gfp,\n \t*sheafp = sheaf;\n \treturn 0;\n }\n+EXPORT_SYMBOL(kmem_cache_refill_sheaf);\n \n /*\n  * Allocate from a sheaf obtained by kmem_cache_prefill_sheaf()\n@@ -5440,6 +5443,7 @@ kmem_cache_alloc_from_sheaf_noprof(struct kmem_cache *s, gfp_t gfp,\n \n \treturn ret;\n }\n+EXPORT_SYMBOL(kmem_cache_alloc_from_sheaf_noprof);\n \n unsigned int kmem_cache_sheaf_size(struct slab_sheaf *sheaf)\n {\ndiff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h\nindex 3791af0aadc73e..fb76a2d30449a1 100644\n--- a/rust/bindings/bindings_helper.h\n+++ b/rust/bindings/bindings_helper.h\n@@ -127,9 +127,20 @@ const blk_features_t RUST_CONST_HELPER_BLK_FEAT_ROTATIONAL = BLK_FEAT_ROTATIONAL\n const fop_flags_t RUST_CONST_HELPER_FOP_UNSIGNED_OFFSET = FOP_UNSIGNED_OFFSET;\n \n const xa_mark_t RUST_CONST_HELPER_XA_PRESENT = XA_PRESENT;\n+const xa_mark_t RUST_CONST_HELPER_XA_FREE_MARK = XA_FREE_MARK;\n \n const gfp_t RUST_CONST_HELPER_XA_FLAGS_ALLOC = XA_FLAGS_ALLOC;\n const gfp_t RUST_CONST_HELPER_XA_FLAGS_ALLOC1 = XA_FLAGS_ALLOC1;\n+/*\n+ * `XAS_RESTART` is `((struct xa_node *)3UL)` -- a sentinel pointer value, not\n+ * an address. Cast to `size_t` so bindgen emits a plain `usize` constant; for\n+ * pointer-typed macro values bindgen otherwise generates a `pub static mut`,\n+ * see https://github.com/rust-lang/rust-bindgen/issues/3347.\n+ */\n+const size_t RUST_CONST_HELPER_XAS_RESTART = (size_t)XAS_RESTART;\n+const size_t RUST_CONST_HELPER_XA_CHUNK_SHIFT = XA_CHUNK_SHIFT;\n+const size_t RUST_CONST_HELPER_XA_CHUNK_SIZE = XA_CHUNK_SIZE;\n+extern struct kmem_cache *radix_tree_node_cachep;\n \n const vm_flags_t RUST_CONST_HELPER_VM_MERGEABLE = VM_MERGEABLE;\n const vm_flags_t RUST_CONST_HELPER_VM_READ = VM_READ;\ndiff --git a/rust/helpers/xarray.c b/rust/helpers/xarray.c\nindex 08979b3043410f..d7548a17ae0d06 100644\n--- a/rust/helpers/xarray.c\n+++ b/rust/helpers/xarray.c\n@@ -26,3 +26,18 @@ __rust_helper void rust_helper_xa_unlock(struct xarray *xa)\n {\n \treturn xa_unlock(xa);\n }\n+\n+__rust_helper void *rust_helper_xas_result(struct xa_state *xas, void *curr)\n+{\n+\treturn xas_result(xas, curr);\n+}\n+\n+__rust_helper void *rust_helper_xa_zero_to_null(void *entry)\n+{\n+\treturn xa_zero_to_null(entry);\n+}\n+\n+__rust_helper int rust_helper_xas_error(const struct xa_state *xas)\n+{\n+\treturn xas_error(xas);\n+}\ndiff --git a/rust/kernel/mm.rs b/rust/kernel/mm.rs\nindex 58bc1793fdaf5e..c1920f04917093 100644\n--- a/rust/kernel/mm.rs\n+++ b/rust/kernel/mm.rs\n@@ -18,6 +18,7 @@\n };\n use core::{ops::Deref, ptr::NonNull};\n \n+pub mod sheaf;\n pub mod virt;\n use virt::VmaRef;\n \ndiff --git a/rust/kernel/mm/sheaf.rs b/rust/kernel/mm/sheaf.rs\nnew file mode 100644\nindex 00000000000000..9afbac20241868\n--- /dev/null\n+++ b/rust/kernel/mm/sheaf.rs\n@@ -0,0 +1,762 @@\n+// SPDX-License-Identifier: GPL-2.0\n+\n+//! Slub allocator sheaf abstraction.\n+//!\n+//! Sheaves are percpu array-based caching layers for the slub allocator.\n+//! They provide a mechanism for pre-allocating objects that can later\n+//! be retrieved without risking allocation failure, making them useful in\n+//! contexts where memory allocation must be guaranteed to succeed.\n+//!\n+//! The term \"sheaf\" is the english word for a bundle of straw. In this context\n+//! it means a bundle of pre-allocated objects. A per-NUMA-node cache of sheaves\n+//! is called a \"barn\". Because you store your sheafs in barns.\n+//!\n+//! # Use cases\n+//!\n+//! Sheaves are particularly useful when:\n+//!\n+//! - Allocations must be guaranteed to succeed in a restricted context (e.g.,\n+//!   while holding locks or in atomic context).\n+//! - Multiple allocations need to be performed as a batch operation.\n+//! - Fast-path allocation performance is critical, as sheaf allocations avoid\n+//!   atomic operations by using local locks with preemption disabled. Note\n+//!   that the abstraction adds reference counting on top of this for dynamic\n+//!   caches, see [`Sheaf`].\n+//!\n+//! # Architecture\n+//!\n+//! The sheaf system supports two modes of operation:\n+//!\n+//! - **Static caches**: [`KMemCache`] represents a cache that is never\n+//!   destroyed, typically one created by C code at kernel boot time. These\n+//!   have `'static` lifetime and produce [`StaticSheaf`] instances.\n+//! - **Dynamic caches**: [`KMemCacheHandle`] owns a cache created through\n+//!   this abstraction. These are reference-counted, destroyed when the last\n+//!   reference is dropped, and produce [`DynamicSheaf`] instances.\n+//!\n+//! Both modes use the same core types:\n+//!\n+//! - [`Sheaf`]: A pre-filled container of objects from a specific cache.\n+//! - [`SBox`]: An owned allocation from a sheaf, similar to a `Box`.\n+//!\n+//! # Example\n+//!\n+//! Using a dynamically created cache:\n+//!\n+//! ```\n+//! use kernel::c_str;\n+//! use kernel::mm::sheaf::{KMemCacheHandle, KMemCacheInit, Sheaf, SBox};\n+//! use kernel::prelude::*;\n+//!\n+//! struct MyObject {\n+//!     value: u32,\n+//! }\n+//!\n+//! impl KMemCacheInit\u003cMyObject\u003e for MyObject {\n+//!     fn init() -\u003e impl Init\u003cMyObject\u003e {\n+//!         init!(MyObject { value: 0 })\n+//!     }\n+//! }\n+//!\n+//! // Create a cache with a sheaf capacity of at least 16 objects.\n+//! let cache = KMemCacheHandle::\u003cMyObject\u003e::new(c_str!(\"my_cache\"), 16)?;\n+//!\n+//! // Pre-fill a sheaf with 8 objects.\n+//! let mut sheaf = cache.as_arc_borrow().sheaf(8, GFP_KERNEL)?;\n+//!\n+//! // Allocations from the sheaf are guaranteed to succeed until empty.\n+//! let obj = sheaf.alloc().unwrap();\n+//!\n+//! // Return the sheaf when done, attempting to refill it.\n+//! sheaf.return_refill(GFP_KERNEL);\n+//! # Ok::\u003c(), Error\u003e(())\n+//! ```\n+//!\n+//! # Constraints\n+//!\n+//! - Sheaves are slower when `CONFIG_SLUB_TINY` is enabled, or when slab\n+//!   debugging (`slab_debug`) is enabled for the cache, due to cpu sheaves\n+//!   being disabled. All prefilled sheaves become \"oversize\" and go through a\n+//!   slower allocation path.\n+//! - The sheaf capacity of a cache is decided at cache creation time. The\n+//!   capacity requested when creating the cache is a minimum. The allocator\n+//!   calculates a capacity based on the object size and uses the larger of the\n+//!   two.\n+\n+use core::{\n+    convert::Infallible,\n+    marker::PhantomData,\n+    ops::{Deref, DerefMut},\n+    ptr::NonNull,\n+};\n+\n+use kernel::prelude::*;\n+\n+use crate::{\n+    sync::{Arc, ArcBorrow},\n+    types::Opaque,\n+};\n+\n+/// A slab cache with sheaf support.\n+///\n+/// This type is a transparent wrapper around a kernel `kmem_cache`. It can be\n+/// used with caches created either by C code or via [`KMemCacheHandle`].\n+///\n+/// When a reference to this type has `'static` lifetime (i.e., `\u0026'static\n+/// KMemCache\u003cT\u003e`), it represents a cache that is never destroyed, typically\n+/// one created by C code at boot time. Such references produce\n+/// [`StaticSheaf`] instances via [`sheaf`].\n+///\n+/// [`sheaf`]: KMemCache::sheaf\n+///\n+/// # Type parameter\n+///\n+/// - `T`: The type of objects managed by this cache. Must implement\n+///   [`KMemCacheInit`] to provide initialization logic for allocations.\n+#[repr(transparent)]\n+pub struct KMemCache\u003cT: KMemCacheInit\u003cT\u003e\u003e {\n+    inner: Opaque\u003cbindings::kmem_cache\u003e,\n+    _p: PhantomData\u003cT\u003e,\n+}\n+\n+// SAFETY: The C `kmem_cache` is internally synchronized and has no thread\n+// affinity, so a `KMemCache\u003cT\u003e` may be sent to another thread if the objects\n+// it manages can.\n+unsafe impl\u003cT: KMemCacheInit\u003cT\u003e + Send\u003e Send for KMemCache\u003cT\u003e {}\n+\n+// SAFETY: All operations available through `\u0026KMemCache\u003cT\u003e` (creating sheaves\n+// and allocating objects) are internally synchronized by the C side, so the\n+// cache may be used from multiple threads concurrently if the objects it\n+// manages can be sent between threads.\n+unsafe impl\u003cT: KMemCacheInit\u003cT\u003e + Send\u003e Sync for KMemCache\u003cT\u003e {}\n+\n+impl\u003cT: KMemCacheInit\u003cT\u003e\u003e KMemCache\u003cT\u003e {\n+    /// Creates a pre-filled sheaf from this cache.\n+    ///\n+    /// Allocates a sheaf and pre-fills it with `size` objects. Once created,\n+    /// allocations from the sheaf via [`Sheaf::alloc`] are guaranteed to\n+    /// succeed until the sheaf is depleted.\n+    ///\n+    /// # Arguments\n+    ///\n+    /// - `size`: The number of objects to pre-allocate. Must not be zero. If\n+    ///   `size` exceeds the sheaf capacity of the cache, an \"oversize\" sheaf\n+    ///   is allocated. Oversize sheaves are slower to create, and they are\n+    ///   flushed and freed rather than cached for reuse when returned.\n+    /// - `gfp`: Allocation flags controlling how memory is obtained. Use\n+    ///   [`GFP_KERNEL`] for normal allocations that may sleep, or\n+    ///   [`GFP_NOWAIT`] for non-blocking allocations.\n+    ///\n+    /// # Errors\n+    ///\n+    /// Returns [`ENOMEM`] if the sheaf or its objects could not be allocated,\n+    /// or if `size` is zero.\n+    #[inline]\n+    pub fn sheaf(\n+        \u0026'static self,\n+        size: usize,\n+        gfp: kernel::alloc::Flags,\n+    ) -\u003e Result\u003cSheaf\u003c'static, T, Static\u003e\u003e {\n+        // SAFETY: `self.as_raw()` returns a valid cache pointer, and `size`\n+        // has been validated to fit in a `c_uint`.\n+        let ptr = unsafe {\n+            bindings::kmem_cache_prefill_sheaf(self.inner.get(), gfp.as_raw(), size.try_into()?)\n+        };\n+\n+        // INVARIANT: `ptr` was returned by `kmem_cache_prefill_sheaf` and is\n+        // non-null (checked below). `cache` is the cache from which this sheaf\n+        // was created. `dropped` is false since the sheaf has not been returned.\n+        Ok(Sheaf {\n+            sheaf: NonNull::new(ptr).ok_or(ENOMEM)?,\n+            // SAFETY: `self` is a valid reference, so the pointer is non-null.\n+            cache: CacheRef::Static(unsafe {\n+                NonNull::new_unchecked((\u0026raw const *self).cast_mut())\n+            }),\n+            dropped: false,\n+            _p: PhantomData,\n+        })\n+    }\n+\n+    #[inline]\n+    fn as_raw(\u0026self) -\u003e *mut bindings::kmem_cache {\n+        self.inner.get()\n+    }\n+\n+    /// Creates a reference to a [`KMemCache`] from a raw pointer.\n+    ///\n+    /// This is useful for wrapping a C-initialized static `kmem_cache`, such as\n+    /// the global `radix_tree_node_cachep` used by XArrays.\n+    ///\n+    /// # Safety\n+    ///\n+    /// - `ptr` must be a valid pointer to a `kmem_cache` that was created for\n+    ///   objects of type `T`.\n+    /// - The cache must remain valid for the lifetime `'a`.\n+    /// - The caller must ensure that the cache was configured appropriately for\n+    ///   the type `T`, including proper size and alignment.\n+    pub unsafe fn from_raw\u003c'a\u003e(ptr: *mut bindings::kmem_cache) -\u003e \u0026'a Self {\n+        // SAFETY: The caller guarantees that `ptr` is a valid pointer to a\n+        // `kmem_cache` created for objects of type `T`, that it remains valid\n+        // for lifetime `'a`, and that the cache is properly configured for `T`.\n+        unsafe { \u0026*ptr.cast::\u003cSelf\u003e() }\n+    }\n+}\n+\n+/// A slab cache with sheaf support.\n+///\n+/// This type wraps a kernel `kmem_cache` configured with a sheaf capacity,\n+/// enabling pre-allocation of objects via [`Sheaf`].\n+///\n+/// For now, this type only exists for sheaf management.\n+///\n+/// # Type parameter\n+///\n+/// - `T`: The type of objects managed by this cache. Must implement\n+///   [`KMemCacheInit`] to provide initialization logic for new allocations.\n+///\n+/// # Context\n+///\n+/// Dropping the last reference to a `KMemCacheHandle` destroys the cache via\n+/// `kmem_cache_destroy`, which may sleep. [`SBox`] instances allocated from\n+/// the handle each hold a reference, so the last reference may be dropped\n+/// when an [`SBox`] is dropped. The last reference must not be dropped from a\n+/// context where sleeping is not allowed.\n+///\n+/// A [`Sheaf`] created from the handle also holds a reference, but dropping\n+/// a [`Sheaf`] never drops the last one. See the `# Lifecycle` section of\n+/// [`Sheaf`].\n+///\n+/// # Invariants\n+///\n+/// - `cache` is a valid pointer to a `kmem_cache` created with\n+///   `__kmem_cache_create_args`.\n+/// - The cache is valid for the lifetime of this struct.\n+#[repr(transparent)]\n+pub struct KMemCacheHandle\u003cT: KMemCacheInit\u003cT\u003e\u003e {\n+    cache: NonNull\u003cKMemCache\u003cT\u003e\u003e,\n+}\n+\n+// SAFETY: `KMemCacheHandle\u003cT\u003e` owns a `kmem_cache`, which is internally\n+// synchronized and has no thread affinity. The cache may be destroyed from a\n+// thread other than the one that created it.\n+unsafe impl\u003cT: KMemCacheInit\u003cT\u003e + Send\u003e Send for KMemCacheHandle\u003cT\u003e {}\n+\n+// SAFETY: All operations available through `\u0026KMemCacheHandle\u003cT\u003e` are\n+// internally synchronized by the C side, so the cache may be used from\n+// multiple threads concurrently if the objects it manages can be sent between\n+// threads.\n+unsafe impl\u003cT: KMemCacheInit\u003cT\u003e + Send\u003e Sync for KMemCacheHandle\u003cT\u003e {}\n+\n+impl\u003cT: KMemCacheInit\u003cT\u003e\u003e KMemCacheHandle\u003cT\u003e {\n+    /// Creates a new slab cache with sheaf support.\n+    ///\n+    /// Creates a kernel slab cache for objects of type `T` with at least the\n+    /// specified sheaf capacity. The cache uses the provided `name` for\n+    /// identification in `/sys/kernel/slab/` and debugging output.\n+    ///\n+    /// # Arguments\n+    ///\n+    /// - `name`: A string identifying the cache. This name appears in sysfs and\n+    ///   debugging output.\n+    /// - `sheaf_capacity`: The minimum number of objects a regular sheaf from\n+    ///   this cache can hold. The allocator calculates a capacity based on the\n+    ///   object size and uses the larger of the two, so a value of zero\n+    ///   selects the calculated capacity. Set this to the largest `size` that\n+    ///   is expected to be passed to [`sheaf`](Self::sheaf) to avoid oversize\n+    ///   sheaves. The value is ignored when `CONFIG_SLUB_TINY` is enabled or\n+    ///   when slab debugging (`slab_debug`) is enabled for the cache.\n+    ///\n+    /// # Errors\n+    ///\n+    /// Returns an error if:\n+    ///\n+    /// - The cache could not be created due to memory pressure.\n+    /// - The size of `T` cannot be represented as a `c_uint`.\n+    pub fn new(name: \u0026CStr, sheaf_capacity: u32) -\u003e Result\u003cArc\u003cSelf\u003e\u003e\n+    where\n+        T: KMemCacheInit\u003cT\u003e,\n+    {\n+        let flags = 0;\n+        let mut args: bindings::kmem_cache_args = pin_init::zeroed();\n+        args.sheaf_capacity = sheaf_capacity;\n+\n+        // With an alignment of zero, the slab allocator only guarantees\n+        // `ARCH_SLAB_MINALIGN`, which may be smaller than the alignment of `T`.\n+        args.align = core::mem::align_of::\u003cT\u003e().try_into()?;\n+\n+        // NOTE: We are not initializing at object allocation time, because\n+        // there is no matching teardown function on the C side machinery.\n+        args.ctor = None;\n+\n+        // SAFETY: `name` is a valid C string, `args` is properly initialized,\n+        // and the size of `T` has been validated to fit in a `c_uint`.\n+        let ptr = unsafe {\n+            bindings::__kmem_cache_create_args(\n+                name.as_char_ptr(),\n+                core::mem::size_of::\u003cT\u003e().try_into()?,\n+                \u0026mut args,\n+                flags,\n+            )\n+        };\n+\n+        // INVARIANT: `ptr` was returned by `__kmem_cache_create_args` and is\n+        // non-null (checked below). The cache is valid until\n+        // `kmem_cache_destroy` is called in `Drop`.\n+        Ok(Arc::new(\n+            Self {\n+                cache: NonNull::new(ptr.cast()).ok_or(ENOMEM)?,\n+            },\n+            GFP_KERNEL,\n+        )?)\n+    }\n+\n+    /// Creates a pre-filled sheaf from this cache.\n+    ///\n+    /// Allocates a sheaf and pre-fills it with `size` objects. Once created,\n+    /// allocations from the sheaf via [`Sheaf::alloc`] are guaranteed to\n+    /// succeed until the sheaf is depleted.\n+    ///\n+    /// # Arguments\n+    ///\n+    /// - `size`: The number of objects to pre-allocate. Must not be zero. If\n+    ///   `size` exceeds the sheaf capacity of the cache, an \"oversize\" sheaf\n+    ///   is allocated. Oversize sheaves are slower to create, and they are\n+    ///   flushed and freed rather than cached for reuse when returned.\n+    /// - `gfp`: Allocation flags controlling how memory is obtained. Use\n+    ///   [`GFP_KERNEL`] for normal allocations that may sleep, or\n+    ///   [`GFP_NOWAIT`] for non-blocking allocations.\n+    ///\n+    /// # Errors\n+    ///\n+    /// Returns [`ENOMEM`] if the sheaf or its objects could not be allocated,\n+    /// or if `size` is zero.\n+    #[inline]\n+    pub fn sheaf\u003c'a\u003e(\n+        self: ArcBorrow\u003c'a, Self\u003e,\n+        size: usize,\n+        gfp: kernel::alloc::Flags,\n+    ) -\u003e Result\u003cSheaf\u003c'a, T, Dynamic\u003e\u003e {\n+        // SAFETY: `self.as_raw()` returns a valid cache pointer, and `size`\n+        // has been validated to fit in a `c_uint`.\n+        let ptr = unsafe {\n+            bindings::kmem_cache_prefill_sheaf(self.as_raw(), gfp.as_raw(), size.try_into()?)\n+        };\n+\n+        // INVARIANT: `ptr` was returned by `kmem_cache_prefill_sheaf` and is\n+        // non-null (checked below). `cache` is the cache from which this sheaf\n+        // was created. `dropped` is false since the sheaf has not been returned.\n+        Ok(Sheaf {\n+            sheaf: NonNull::new(ptr).ok_or(ENOMEM)?,\n+            cache: CacheRef::Arc(self.into()),\n+            dropped: false,\n+            _p: PhantomData,\n+        })\n+    }\n+\n+    #[inline]\n+    fn as_raw(\u0026self) -\u003e *mut bindings::kmem_cache {\n+        self.cache.as_ptr().cast()\n+    }\n+}\n+\n+impl\u003cT: KMemCacheInit\u003cT\u003e\u003e Drop for KMemCacheHandle\u003cT\u003e {\n+    fn drop(\u0026mut self) {\n+        // SAFETY: `self.as_raw()` returns a valid cache pointer that was\n+        // created by `__kmem_cache_create_args`. As all objects allocated from\n+        // this hold a reference on `self`, they must have been dropped for this\n+        // `drop` method to execute.\n+        unsafe { bindings::kmem_cache_destroy(self.as_raw()) };\n+    }\n+}\n+\n+/// Trait for types that can be initialized in a slab cache.\n+///\n+/// This trait provides the initialization logic for objects allocated from a\n+/// [`KMemCache`]. The initializer is called when objects are allocated from a\n+/// sheaf via [`Sheaf::alloc`].\n+///\n+/// # Implementation\n+///\n+/// Implementors must provide [`init`](KMemCacheInit::init), which returns an\n+/// infallible initializer for the type.\n+///\n+/// # Example\n+///\n+/// ```\n+/// use kernel::mm::sheaf::KMemCacheInit;\n+/// use kernel::prelude::*;\n+///\n+/// struct MyData {\n+///     counter: u32,\n+///     name: [u8; 16],\n+/// }\n+///\n+/// impl KMemCacheInit\u003cMyData\u003e for MyData {\n+///     fn init() -\u003e impl Init\u003cMyData\u003e {\n+///         init!(MyData {\n+///             counter: 0,\n+///             name: [0; 16],\n+///         })\n+///     }\n+/// }\n+/// ```\n+pub trait KMemCacheInit\u003cT\u003e {\n+    /// Returns an initializer for creating new objects of type `T`.\n+    ///\n+    /// The initializer is applied to newly allocated objects when they are allocated from a sheaf\n+    /// via [`Sheaf::alloc`]. The initializer should set all fields to their default or initial\n+    /// values.\n+    fn init() -\u003e impl Init\u003cT, Infallible\u003e;\n+}\n+\n+/// Marker type for sheaves from static caches.\n+///\n+/// Used as a type parameter for [`Sheaf`] to indicate the sheaf was created\n+/// from a `\u0026'static KMemCache\u003cT\u003e`.\n+pub enum Static {}\n+\n+/// Marker type for sheaves from dynamic caches.\n+///\n+/// Used as a type parameter for [`Sheaf`] to indicate the sheaf was created\n+/// from a [`KMemCacheHandle`] via [`ArcBorrow`].\n+pub enum Dynamic {}\n+\n+/// A sheaf from a static cache.\n+///\n+/// This is a [`Sheaf`] backed by a `\u0026'static KMemCache\u003cT\u003e`.\n+pub type StaticSheaf\u003c'a, T\u003e = Sheaf\u003c'a, T, Static\u003e;\n+\n+/// A sheaf from a dynamic cache.\n+///\n+/// This is a [`Sheaf`] backed by a reference-counted [`KMemCacheHandle`].\n+pub type DynamicSheaf\u003c'a, T\u003e = Sheaf\u003c'a, T, Dynamic\u003e;\n+\n+/// A pre-filled container of slab objects.\n+///\n+/// A sheaf holds a set of pre-allocated objects from a [`KMemCache`].\n+/// Allocations from a sheaf are guaranteed to succeed until the sheaf is\n+/// depleted, making sheaves useful in contexts where allocation failure is\n+/// not acceptable.\n+///\n+/// Sheaves provide faster allocation than direct allocation because they use\n+/// local locks with preemption disabled rather than atomic operations. Note\n+/// that each [`SBox`] allocated from a [`DynamicSheaf`] holds a reference to\n+/// the [`KMemCacheHandle`] the sheaf was created from, to keep the cache\n+/// alive until the object is freed. [`Sheaf::alloc`] thus increments the\n+/// reference count of the handle, and dropping the [`SBox`] decrements it.\n+/// Both are atomic operations on a counter that is shared by all users of the\n+/// cache.\n+///\n+/// This does not apply to a [`StaticSheaf`]. A static cache is never\n+/// destroyed, so objects allocated from it do not hold a reference and no\n+/// reference counting takes place.\n+///\n+/// # Type parameters\n+///\n+/// - `'a`: The lifetime of the cache reference the sheaf was created from.\n+///   The cache is guaranteed to outlive `'a`.\n+/// - `T`: The type of objects in this sheaf.\n+/// - `A`: Either [`Static`] or [`Dynamic`], indicating whether the backing\n+///   cache is a static reference or a reference-counted handle.\n+///\n+/// For convenience, [`StaticSheaf`] and [`DynamicSheaf`] type aliases are\n+/// provided.\n+///\n+/// # Lifecycle\n+///\n+/// Sheaves are created via [`KMemCache::sheaf`] or [`KMemCacheHandle::sheaf`]\n+/// and should be returned to the allocator when no longer needed via\n+/// [`Sheaf::return_refill`]. If a sheaf is simply dropped, it is returned with\n+/// `GFP_NOWAIT` flags, which may result in the sheaf being flushed and freed\n+/// rather than being cached for reuse.\n+///\n+/// A sheaf created from a [`KMemCacheHandle`] holds a reference to the\n+/// handle. Dropping the sheaf never drops the last reference to the handle,\n+/// and thus never destroys the cache: [`KMemCacheHandle::sheaf`] ties the\n+/// lifetime `'a` of the sheaf to the [`ArcBorrow`] it is called on, so the\n+/// reference the [`ArcBorrow`] was created from outlives the sheaf. A sheaf\n+/// can therefore be dropped in a context where sleeping is not allowed. Note\n+/// that this does not extend to [`SBox`] instances allocated from the sheaf.\n+///\n+/// # Invariants\n+///\n+/// - `sheaf` is a valid pointer to a `slab_sheaf` obtained from\n+///   `kmem_cache_prefill_sheaf`.\n+/// - `cache` is the cache from which this sheaf was created.\n+/// - `dropped` tracks whether the sheaf has been explicitly returned.\n+pub struct Sheaf\u003c'a, T: KMemCacheInit\u003cT\u003e, A\u003e {\n+    sheaf: NonNull\u003cbindings::slab_sheaf\u003e,\n+    cache: CacheRef\u003cT\u003e,\n+    dropped: bool,\n+    _p: PhantomData\u003c(\u0026'a KMemCache\u003cT\u003e, A)\u003e,\n+}\n+\n+// SAFETY: A prefilled sheaf is exclusively owned by the caller and has no\n+// affinity to the CPU or thread that created it: `kmem_cache_alloc_from_sheaf`\n+// does not touch percpu state, and `kmem_cache_return_sheaf` reattaches the\n+// sheaf to the CPU that is current at return time. Thus the sheaf may be sent\n+// to another thread if the objects it manages can.\n+unsafe impl\u003cT: KMemCacheInit\u003cT\u003e + Send, A\u003e Send for Sheaf\u003c'_, T, A\u003e {}\n+\n+// NOTE: `Sheaf` is deliberately not `Sync`. The C side mutates sheaf state\n+// without synchronization, relying on the caller's exclusive ownership. The\n+// mutable receivers of the methods on `Sheaf` enforce this exclusivity.\n+\n+impl\u003c'a, T: KMemCacheInit\u003cT\u003e, A\u003e Sheaf\u003c'a, T, A\u003e {\n+    #[inline]\n+    fn as_raw(\u0026self) -\u003e *mut bindings::slab_sheaf {\n+        self.sheaf.as_ptr()\n+    }\n+\n+    /// Return the sheaf and try to refill using `flags`.\n+    ///\n+    /// If the sheaf cannot simply become the percpu spare sheaf, but there's\n+    /// space for a full sheaf in the barn, we try to refill the sheaf back to\n+    /// the cache's sheaf_capacity to avoid handling partially full sheaves.\n+    ///\n+    /// If the refill fails because gfp is e.g. GFP_NOWAIT, or the barn is full,\n+    /// the sheaf is instead flushed and freed.\n+    #[inline]\n+    pub fn return_refill(mut self, flags: kernel::alloc::Flags) {\n+        self.dropped = true;\n+        // SAFETY: `self.cache.as_raw()` and `self.as_raw()` return valid\n+        // pointers to the cache and sheaf respectively.\n+        unsafe {\n+            bindings::kmem_cache_return_sheaf(self.cache.as_raw(), flags.as_raw(), self.as_raw())\n+        };\n+        drop(self);\n+    }\n+\n+    /// Refills the sheaf to at least the specified size.\n+    ///\n+    /// Replenishes the sheaf by preallocating objects until it contains at\n+    /// least `size` objects. If the sheaf already contains `size` or more\n+    /// objects, this is a no-op. In practice, the sheaf is refilled to its\n+    /// full capacity.\n+    ///\n+    /// # Arguments\n+    ///\n+    /// - `flags`: Allocation flags controlling how memory is obtained.\n+    /// - `size`: The minimum number of objects the sheaf should contain after\n+    ///   refilling. If `size` exceeds the cache's `sheaf_capacity`, the sheaf\n+    ///   may be replaced with a larger one.\n+    ///\n+    /// # Errors\n+    ///\n+    /// Returns an error if the objects could not be allocated. If refilling\n+    /// fails, the existing sheaf is left intact.\n+    pub fn refill(\u0026mut self, flags: kernel::alloc::Flags, size: usize) -\u003e Result {\n+        // SAFETY: `self.cache.as_raw()` returns a valid cache pointer and\n+        // `\u0026raw mut self.sheaf` points to a valid sheaf per the type invariants.\n+        kernel::error::to_result(unsafe {\n+            bindings::kmem_cache_refill_sheaf(\n+                self.cache.as_raw(),\n+                flags.as_raw(),\n+                (\u0026raw mut (self.sheaf)).cast(),\n+                size.try_into()?,\n+            )\n+        })\n+    }\n+\n+    /// Allocates an object from the sheaf.\n+    ///\n+    /// Returns a new [`SBox`] containing an initialized object, or [`None`]\n+    /// if the sheaf is depleted. Allocations are guaranteed to succeed as\n+    /// long as the sheaf contains pre-allocated objects.\n+    ///\n+    /// The `gfp` flags passed to `kmem_cache_alloc_from_sheaf` are set to zero,\n+    /// meaning no additional flags like `__GFP_ZERO` or `__GFP_ACCOUNT` are\n+    /// applied.\n+    ///\n+    /// The returned `T` is initialized as part of this function.\n+    pub fn alloc(\u0026mut self) -\u003e Option\u003cSBox\u003cT\u003e\u003e {\n+        // SAFETY: `self.cache.as_raw()` and `self.as_raw()` return valid\n+        // pointers. The function returns NULL when the sheaf is empty.\n+        let ptr = unsafe {\n+            bindings::kmem_cache_alloc_from_sheaf_noprof(self.cache.as_raw(), 0, self.as_raw())\n+        };\n+\n+        let ptr = NonNull::new(ptr.cast::\u003cT\u003e())?;\n+\n+        // SAFETY:\n+        // - `ptr` is a valid, non-null pointer as it was just returned by the\n+        //   cache.\n+        // - The initializer is infallible, so an error is never returned.\n+        unsafe { T::init().__init(ptr.as_ptr()) }.expect(\"Initializer is infallible\");\n+\n+        // INVARIANT: `ptr` was returned by `kmem_cache_alloc_from_sheaf_noprof`\n+        // and initialized above. `cache` is the cache from which this object\n+        // was allocated. The object remains valid until freed in `Drop`.\n+        Some(SBox {\n+            ptr,\n+            cache: self.cache.clone(),\n+        })\n+    }\n+}\n+\n+impl\u003c'a, T: KMemCacheInit\u003cT\u003e, A\u003e Drop for Sheaf\u003c'a, T, A\u003e {\n+    fn drop(\u0026mut self) {\n+        if !self.dropped {\n+            // SAFETY: `self.cache.as_raw()` and `self.as_raw()` return valid\n+            // pointers. Using `GFP_NOWAIT` because the drop may occur in a\n+            // context where sleeping is not permitted.\n+            unsafe {\n+                bindings::kmem_cache_return_sheaf(\n+                    self.cache.as_raw(),\n+                    GFP_NOWAIT.as_raw(),\n+                    self.as_raw(),\n+                )\n+            };\n+        }\n+    }\n+}\n+\n+/// Internal reference to a cache, either static or reference-counted.\n+///\n+/// # Invariants\n+///\n+/// - For `CacheRef::Static`: the `NonNull` points to a valid `KMemCache\u003cT\u003e`\n+///   with `'static` lifetime, derived from a `\u0026'static KMemCache\u003cT\u003e` reference.\n+enum CacheRef\u003cT: KMemCacheInit\u003cT\u003e\u003e {\n+    /// A reference-counted handle to a dynamically created cache.\n+    Arc(Arc\u003cKMemCacheHandle\u003cT\u003e\u003e),\n+    /// A pointer to a static lifetime cache.\n+    Static(NonNull\u003cKMemCache\u003cT\u003e\u003e),\n+}\n+\n+impl\u003cT: KMemCacheInit\u003cT\u003e\u003e Clone for CacheRef\u003cT\u003e {\n+    fn clone(\u0026self) -\u003e Self {\n+        match self {\n+            Self::Arc(arg0) =\u003e Self::Arc(arg0.clone()),\n+            Self::Static(arg0) =\u003e Self::Static(*arg0),\n+        }\n+    }\n+}\n+\n+impl\u003cT: KMemCacheInit\u003cT\u003e\u003e CacheRef\u003cT\u003e {\n+    #[inline]\n+    fn as_raw(\u0026self) -\u003e *mut bindings::kmem_cache {\n+        match self {\n+            CacheRef::Arc(handle) =\u003e handle.as_raw(),\n+            // SAFETY: By type invariant, `ptr` points to a valid `KMemCache\u003cT\u003e`\n+            // with `'static` lifetime.\n+            CacheRef::Static(ptr) =\u003e unsafe { ptr.as_ref() }.as_raw(),\n+        }\n+    }\n+}\n+\n+/// An owned allocation from a cache sheaf.\n+///\n+/// `SBox` is similar to `Box` but is backed by a slab cache allocation obtained\n+/// through a [`Sheaf`]. It provides owned access to an initialized object and\n+/// ensures the object is properly freed back to the cache when dropped.\n+///\n+/// The contained `T` is initialized when the `SBox` is returned from alloc and\n+/// dropped when the `SBox` is dropped.\n+///\n+/// An `SBox` allocated from a [`KMemCacheHandle`] backed sheaf holds a\n+/// reference to the handle. Dropping the `SBox` may thus drop the last\n+/// reference to the handle and destroy the cache, which may sleep. See the\n+/// `# Context` section of [`KMemCacheHandle`].\n+///\n+/// # Invariants\n+///\n+/// - `ptr` points to a valid, initialized object of type `T`.\n+/// - `cache` is the cache from which this object was allocated.\n+/// - The object remains valid for the lifetime of the `SBox`.\n+pub struct SBox\u003cT: KMemCacheInit\u003cT\u003e\u003e {\n+    ptr: NonNull\u003cT\u003e,\n+    cache: CacheRef\u003cT\u003e,\n+}\n+\n+// SAFETY: `SBox\u003cT\u003e` owns a `T`. Sheaf allocated objects are ordinary slab\n+// objects that may be freed from any thread, so an `SBox\u003cT\u003e` may be sent to\n+// another thread if `T` can.\n+unsafe impl\u003cT: KMemCacheInit\u003cT\u003e + Send\u003e Send for SBox\u003cT\u003e {}\n+\n+// SAFETY: `SBox\u003cT\u003e` has no interior mutability, so sharing `\u0026SBox\u003cT\u003e` between\n+// threads only shares `\u0026T`.\n+unsafe impl\u003cT: KMemCacheInit\u003cT\u003e + Sync\u003e Sync for SBox\u003cT\u003e {}\n+\n+impl\u003cT: KMemCacheInit\u003cT\u003e\u003e SBox\u003cT\u003e {\n+    /// Consumes the `SBox` and returns the raw pointer to the contained value.\n+    ///\n+    /// The caller becomes responsible for freeing the memory. The object is not\n+    /// dropped and remains initialized. Use [`static_from_ptr`] to reconstruct\n+    /// an `SBox` from the pointer.\n+    ///\n+    /// This method is only intended for objects allocated from a static cache.\n+    /// Calling it on an `SBox` backed by a [`KMemCacheHandle`] leaks a\n+    /// reference on the handle, preventing the cache from ever being\n+    /// destroyed, as [`static_from_ptr`] cannot restore the reference.\n+    ///\n+    /// [`static_from_ptr`]: SBox::static_from_ptr\n+    pub fn into_ptr(self) -\u003e *mut T {\n+        debug_assert!(matches!(self.cache, CacheRef::Static(_)));\n+        let ptr = self.ptr.as_ptr();\n+        core::mem::forget(self);\n+        ptr\n+    }\n+\n+    /// Reconstructs an `SBox` from a raw pointer and cache.\n+    ///\n+    /// This is intended for use with objects that were previously converted to\n+    /// raw pointers via [`into_ptr`], typically for passing through C code.\n+    ///\n+    /// [`into_ptr`]: SBox::into_ptr\n+    ///\n+    /// # Safety\n+    ///\n+    /// - `cache` must be a valid pointer to the `kmem_cache` from which `value`\n+    ///   was allocated.\n+    /// - `cache` must be a statically allocated cache that is never destroyed.\n+    /// - `value` must be a valid pointer to an initialized `T` that was\n+    ///   allocated from `cache`.\n+    /// - The caller must ensure that no other `SBox` or reference exists for\n+    ///   `value`.\n+    pub unsafe fn static_from_ptr(cache: *mut bindings::kmem_cache, value: *mut T) -\u003e Self {\n+        // INVARIANT: The caller guarantees `value` points to a valid,\n+        // initialized `T` allocated from `cache`.\n+        Self {\n+            // SAFETY: By function safety requirements, `value` is not null.\n+            ptr: unsafe { NonNull::new_unchecked(value) },\n+            cache: CacheRef::Static(\n+                // SAFETY: By function safety requirements, `cache` is not null.\n+                unsafe { NonNull::new_unchecked(cache.cast()) },\n+            ),\n+        }\n+    }\n+}\n+\n+impl\u003cT: KMemCacheInit\u003cT\u003e\u003e Deref for SBox\u003cT\u003e {\n+    type Target = T;\n+\n+    #[inline]\n+    fn deref(\u0026self) -\u003e \u0026Self::Target {\n+        // SAFETY: `ptr` is valid and properly aligned per the type invariants.\n+        unsafe { self.ptr.as_ref() }\n+    }\n+}\n+\n+impl\u003cT: KMemCacheInit\u003cT\u003e\u003e DerefMut for SBox\u003cT\u003e {\n+    #[inline]\n+    fn deref_mut(\u0026mut self) -\u003e \u0026mut Self::Target {\n+        // SAFETY: `ptr` is valid and properly aligned per the type invariants,\n+        // and we have exclusive access via `\u0026mut self`.\n+        unsafe { self.ptr.as_mut() }\n+    }\n+}\n+\n+impl\u003cT: KMemCacheInit\u003cT\u003e\u003e Drop for SBox\u003cT\u003e {\n+    fn drop(\u0026mut self) {\n+        // SAFETY: By type invariant, `ptr` points to a valid and initialized\n+        // object. We do not touch `ptr` after returning it to the cache.\n+        unsafe { core::ptr::drop_in_place(self.ptr.as_ptr()) };\n+\n+        // SAFETY: `self.ptr` was allocated from `self.cache` via\n+        // `kmem_cache_alloc_from_sheaf_noprof` and is valid.\n+        unsafe {\n+            bindings::kmem_cache_free(self.cache.as_raw(), self.ptr.as_ptr().cast());\n+        }\n+    }\n+}\ndiff --git a/rust/kernel/xarray.rs b/rust/kernel/xarray.rs\nindex 987c9c0c219891..20792b09c12662 100644\n--- a/rust/kernel/xarray.rs\n+++ b/rust/kernel/xarray.rs\n@@ -4,20 +4,101 @@\n //!\n //! C header: [`include/linux/xarray.h`](srctree/include/linux/xarray.h)\n \n-use crate::{\n+use core::{\n+    convert::Infallible,\n+    iter,\n+    marker::PhantomData,\n+    pin::Pin,\n+    ptr::{\n+        null_mut,\n+        NonNull, //\n+    },\n+};\n+pub use entry::{\n+    Entry,\n+    OccupiedEntry,\n+    VacantEntry, //\n+};\n+use kernel::{\n     alloc,\n     bindings,\n     build_assert::build_assert,\n-    error::{Error, Result},\n+    error::{\n+        code::*,\n+        to_result,\n+        Error,\n+        Result, //\n+    },\n     ffi::c_void,\n+    fmt,\n+    mm::sheaf::{\n+        KMemCache,\n+        SBox,\n+        StaticSheaf, //\n+    },\n     types::{\n         ForeignOwnable,\n         NotThreadSafe,\n         Opaque, //\n     }, //\n };\n-use core::{iter, marker::PhantomData, pin::Pin, ptr::NonNull};\n-use pin_init::{pin_data, pin_init, pinned_drop, PinInit};\n+use pin_init::{\n+    init,\n+    pin_data,\n+    pin_init,\n+    pinned_drop,\n+    Init,\n+    PinInit, //\n+};\n+\n+/// Sheaf of preallocated [`XArray`] nodes.\n+pub type XArraySheaf\u003c'a\u003e = StaticSheaf\u003c'a, XArrayNode\u003e;\n+\n+/// Returns a reference to the global XArray node cache.\n+///\n+/// This provides access to the kernel's `radix_tree_node_cachep`, which is the\n+/// slab cache used for allocating internal XArray nodes. This cache can be used\n+/// to create sheaves for preallocating XArray nodes.\n+pub fn xarray_kmem_cache() -\u003e \u0026'static KMemCache\u003cXArrayNode\u003e {\n+    // SAFETY: `radix_tree_node_cachep` is a valid, statically initialized\n+    // kmem_cache that remains valid for the lifetime of the kernel. The cache\n+    // is configured for `xa_node` objects which match our `XArrayNode` type.\n+    unsafe { KMemCache::from_raw(bindings::radix_tree_node_cachep) }\n+}\n+\n+/// An preallocated XArray node.\n+///\n+/// This represents a single preallocated internal node for an XArray.\n+///\n+/// This type is `#[repr(transparent)]` as it is cast to and from pointers to\n+/// the inner [`bindings::xa_node`].\n+#[repr(transparent)]\n+pub struct XArrayNode {\n+    node: Opaque\u003cbindings::xa_node\u003e,\n+}\n+\n+// SAFETY: A preallocated `xa_node` is opaque storage for the C XArray\n+// implementation, which moves nodes between CPUs freely. It is not tied to\n+// the thread that allocated it.\n+unsafe impl Send for XArrayNode {}\n+\n+impl kernel::mm::sheaf::KMemCacheInit\u003cXArrayNode\u003e for XArrayNode {\n+    fn init() -\u003e impl Init\u003cSelf, Infallible\u003e {\n+        init!(Self {\n+            // SAFETY:\n+            // - This initialization cannot fail and will never return `Err`.\n+            // - The xa_node does not move during initialization.\n+            node \u003c- unsafe {\n+                pin_init::init_from_closure(\n+                    |place: *mut Opaque\u003cbindings::xa_node\u003e| -\u003e Result\u003c(), Infallible\u003e {\n+                        bindings::radix_tree_node_ctor(place.cast::\u003cc_void\u003e());\n+                        Ok(())\n+                    },\n+                )\n+            }\n+        })\n+    }\n+}\n \n /// An array which efficiently maps sparse integer indices to owned objects.\n ///\n@@ -50,7 +131,10 @@\n /// *guard.get_mut(0).unwrap() = 0xffff;\n /// assert_eq!(guard.get(0).copied(), Some(0xffff));\n ///\n-/// assert_eq!(guard.store(0, beef, GFP_KERNEL)?.as_deref().copied(), Some(0xffff));\n+/// assert_eq!(\n+///     guard.store(0, beef, GFP_KERNEL)?.as_deref().copied(),\n+///     Some(0xffff)\n+/// );\n /// assert_eq!(guard.get(0).copied(), Some(0xbeef));\n ///\n /// guard.remove(0);\n@@ -112,15 +196,22 @@ fn iter(\u0026self) -\u003e impl Iterator\u003cItem = NonNull\u003cc_void\u003e\u003e + '_ {\n         let mut index = 0;\n \n         // SAFETY: `self.xa` is always valid by the type invariant.\n-        iter::once(unsafe {\n-            bindings::xa_find(self.xa.get(), \u0026mut index, usize::MAX, bindings::XA_PRESENT)\n-        })\n-        .chain(iter::from_fn(move || {\n-            // SAFETY: `self.xa` is always valid by the type invariant.\n-            Some(unsafe {\n-                bindings::xa_find_after(self.xa.get(), \u0026mut index, usize::MAX, bindings::XA_PRESENT)\n-            })\n-        }))\n+        Iterator::chain(\n+            iter::once(unsafe {\n+                bindings::xa_find(self.xa.get(), \u0026mut index, usize::MAX, bindings::XA_PRESENT)\n+            }),\n+            iter::from_fn(move || {\n+                // SAFETY: `self.xa` is always valid by the type invariant.\n+                Some(unsafe {\n+                    bindings::xa_find_after(\n+                        self.xa.get(),\n+                        \u0026mut index,\n+                        usize::MAX,\n+                        bindings::XA_PRESENT,\n+                    )\n+                })\n+            }),\n+        )\n         .map_while(|ptr| NonNull::new(ptr.cast()))\n     }\n \n@@ -141,7 +232,6 @@ pub fn try_lock(\u0026self) -\u003e Option\u003cGuard\u003c'_, T\u003e\u003e {\n     pub fn lock(\u0026self) -\u003e Guard\u003c'_, T\u003e {\n         // SAFETY: `self.xa` is always valid by the type invariant.\n         unsafe { bindings::xa_lock(self.xa.get()) };\n-\n         Guard {\n             xa: self,\n             _not_send: NotThreadSafe,\n@@ -152,6 +242,21 @@ pub fn lock(\u0026self) -\u003e Guard\u003c'_, T\u003e {\n /// A lock guard.\n ///\n /// The lock is unlocked when the guard goes out of scope.\n+///\n+/// # Temporary lock drops\n+///\n+/// Unlike a typical Rust lock guard, holding a `Guard` does not guarantee\n+/// continuous mutual exclusion for its entire lifetime: [`store`] may drop and\n+/// reacquire the lock to allocate memory when called with blocking allocation\n+/// flags. Other threads may lock and modify the array in that window, so a\n+/// sequence of operations on the guard that spans such a call is not atomic.\n+///\n+/// To modify the array without dropping the lock, use the entry API with\n+/// preallocated memory, see [`entry`] and [`insert_entry`].\n+///\n+/// [`store`]: Guard::store\n+/// [`entry`]: Guard::entry\n+/// [`insert_entry`]: Guard::insert_entry\n #[must_use = \"the lock unlocks immediately when the guard is unused\"]\n pub struct Guard\u003c'a, T: ForeignOwnable\u003e {\n     xa: \u0026'a XArray\u003cT\u003e,\n@@ -177,6 +282,15 @@ pub struct StoreError\u003cT\u003e {\n     pub value: T,\n }\n \n+impl\u003cT\u003e fmt::Debug for StoreError\u003cT\u003e {\n+    #[inline]\n+    fn fmt(\u0026self, f: \u0026mut fmt::Formatter\u003c'_\u003e) -\u003e fmt::Result {\n+        f.debug_struct(\"StoreError\")\n+            .field(\"error\", \u0026self.error)\n+            .finish()\n+    }\n+}\n+\n impl\u003cT\u003e From\u003cStoreError\u003cT\u003e\u003e for Error {\n     #[inline]\n     fn from(value: StoreError\u003cT\u003e) -\u003e Self {\n@@ -185,30 +299,194 @@ fn from(value: StoreError\u003cT\u003e) -\u003e Self {\n }\n \n impl\u003c'a, T: ForeignOwnable\u003e Guard\u003c'a, T\u003e {\n-    fn load\u003cF, U\u003e(\u0026self, index: usize, f: F) -\u003e Option\u003cU\u003e\n-    where\n-        F: FnOnce(NonNull\u003cc_void\u003e) -\u003e U,\n-    {\n-        // SAFETY: `self.xa.xa` is always valid by the type invariant.\n-        let ptr = unsafe { bindings::xa_load(self.xa.xa.get(), index) };\n-        let ptr = NonNull::new(ptr.cast())?;\n-        Some(f(ptr))\n+    #[inline]\n+    fn load(\u0026self, index: usize) -\u003e Option\u003cNonNull\u003cc_void\u003e\u003e {\n+        XArrayState::new(self, index).load()\n     }\n \n     /// Provides a reference to the element at the given index.\n+    ///\n+    /// # Examples\n+    ///\n+    /// ```\n+    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray}};\n+    /// let xa = KBox::pin_init(XArray::\u003cKBox\u003cu32\u003e\u003e::new(AllocKind::Alloc1), GFP_KERNEL)?;\n+    /// let mut guard = xa.lock();\n+    ///\n+    /// // Expanding an empty `Alloc1` array stores an internal zero entry at\n+    /// // index 0. It must not be visible through the API.\n+    /// guard.store(5, KBox::new(0xcafeu32, GFP_ATOMIC)?, GFP_ATOMIC)?;\n+    /// assert_eq!(guard.get(0), None);\n+    /// assert_eq!(guard.find_next(0).map(|(i, v)| (i, *v)), Some((5, 0xcafe)));\n+    ///\n+    /// # Ok::\u003c(), kernel::error::Error\u003e(())\n+    /// ```\n+    #[inline]\n     pub fn get(\u0026self, index: usize) -\u003e Option\u003cT::Borrowed\u003c'_\u003e\u003e {\n-        self.load(index, |ptr| {\n-            // SAFETY: `ptr` came from `T::into_foreign`.\n-            unsafe { T::borrow(ptr.as_ptr()) }\n-        })\n+        let ptr = self.load(index)?;\n+        // SAFETY: `ptr` came from `T::into_foreign`.\n+        Some(unsafe { T::borrow(ptr.as_ptr()) })\n     }\n \n     /// Provides a mutable reference to the element at the given index.\n+    #[inline]\n     pub fn get_mut(\u0026mut self, index: usize) -\u003e Option\u003cT::BorrowedMut\u003c'_\u003e\u003e {\n-        self.load(index, |ptr| {\n+        let ptr = self.load(index)?;\n+        // SAFETY: `ptr` came from `T::into_foreign`.\n+        Some(unsafe { T::borrow_mut(ptr.as_ptr()) })\n+    }\n+\n+    /// Gets an entry for the specified index, which can be vacant or occupied.\n+    ///\n+    /// # Examples\n+    ///\n+    /// ```\n+    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray, Entry}};\n+    /// let mut xa = KBox::pin_init(XArray::\u003cKBox\u003cu32\u003e\u003e::new(AllocKind::Alloc), GFP_KERNEL)?;\n+    /// let mut guard = xa.lock();\n+    ///\n+    /// assert!(guard.get(42).is_none());\n+    ///\n+    /// match guard.entry(42) {\n+    ///     Entry::Vacant(entry) =\u003e {\n+    ///         entry.insert(KBox::new(0x1337u32, GFP_ATOMIC)?, None)?;\n+    ///     }\n+    ///     Entry::Occupied(_) =\u003e unreachable!(\"We did not insert an entry yet\"),\n+    /// }\n+    ///\n+    /// assert_eq!(guard.get(42), Some(\u00260x1337));\n+    ///\n+    /// # Ok::\u003c(), kernel::error::Error\u003e(())\n+    /// ```\n+    pub fn entry\u003c'b\u003e(\u0026'b mut self, index: usize) -\u003e Entry\u003c'a, 'b, T\u003e {\n+        match self.load(index) {\n+            None =\u003e Entry::Vacant(VacantEntry::new(self, index)),\n+            Some(ptr) =\u003e Entry::Occupied(OccupiedEntry::new(self, index, ptr)),\n+        }\n+    }\n+\n+    #[inline]\n+    fn load_next(\u0026self, index: usize) -\u003e Option\u003c(usize, NonNull\u003cc_void\u003e)\u003e {\n+        XArrayState::new(self, index).load_next(usize::MAX)\n+    }\n+\n+    /// Finds the next element starting from the given index.\n+    ///\n+    /// # Examples\n+    ///\n+    /// ```\n+    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray}};\n+    /// let mut xa = KBox::pin_init(XArray::\u003cKBox\u003cu32\u003e\u003e::new(AllocKind::Alloc), GFP_KERNEL)?;\n+    /// let mut guard = xa.lock();\n+    ///\n+    /// guard.store(10, KBox::new(10u32, GFP_ATOMIC)?, GFP_ATOMIC)?;\n+    /// guard.store(20, KBox::new(20u32, GFP_ATOMIC)?, GFP_ATOMIC)?;\n+    ///\n+    /// if let Some((found_index, value)) = guard.find_next(11) {\n+    ///     assert_eq!(found_index, 20);\n+    ///     assert_eq!(*value, 20);\n+    /// }\n+    ///\n+    /// if let Some((found_index, value)) = guard.find_next(5) {\n+    ///     assert_eq!(found_index, 10);\n+    ///     assert_eq!(*value, 10);\n+    /// }\n+    ///\n+    /// # Ok::\u003c(), kernel::error::Error\u003e(())\n+    /// ```\n+    #[inline]\n+    pub fn find_next(\u0026self, index: usize) -\u003e Option\u003c(usize, T::Borrowed\u003c'_\u003e)\u003e {\n+        self.load_next(index)\n             // SAFETY: `ptr` came from `T::into_foreign`.\n-            unsafe { T::borrow_mut(ptr.as_ptr()) }\n-        })\n+            .map(|(index, ptr)| (index, unsafe { T::borrow(ptr.as_ptr()) }))\n+    }\n+\n+    /// Finds the next element starting from the given index, returning a mutable reference.\n+    ///\n+    /// # Examples\n+    ///\n+    /// ```\n+    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray}};\n+    /// let mut xa = KBox::pin_init(XArray::\u003cKBox\u003cu32\u003e\u003e::new(AllocKind::Alloc), GFP_KERNEL)?;\n+    /// let mut guard = xa.lock();\n+    ///\n+    /// guard.store(10, KBox::new(10u32, GFP_ATOMIC)?, GFP_ATOMIC)?;\n+    /// guard.store(20, KBox::new(20u32, GFP_ATOMIC)?, GFP_ATOMIC)?;\n+    ///\n+    /// if let Some((found_index, mut_value)) = guard.find_next_mut(5) {\n+    ///     assert_eq!(found_index, 10);\n+    ///     *mut_value = 0x99;\n+    /// }\n+    ///\n+    /// assert_eq!(guard.get(10).copied(), Some(0x99));\n+    ///\n+    /// # Ok::\u003c(), kernel::error::Error\u003e(())\n+    /// ```\n+    #[inline]\n+    pub fn find_next_mut(\u0026mut self, index: usize) -\u003e Option\u003c(usize, T::BorrowedMut\u003c'_\u003e)\u003e {\n+        self.load_next(index)\n+            // SAFETY: `ptr` came from `T::into_foreign`.\n+            .map(move |(index, ptr)| (index, unsafe { T::borrow_mut(ptr.as_ptr()) }))\n+    }\n+\n+    /// Finds the next occupied entry starting from the given index.\n+    ///\n+    /// # Examples\n+    ///\n+    /// ```\n+    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray}};\n+    /// let mut xa = KBox::pin_init(XArray::\u003cKBox\u003cu32\u003e\u003e::new(AllocKind::Alloc), GFP_KERNEL)?;\n+    /// let mut guard = xa.lock();\n+    ///\n+    /// guard.store(10, KBox::new(10u32, GFP_ATOMIC)?, GFP_ATOMIC)?;\n+    /// guard.store(20, KBox::new(20u32, GFP_ATOMIC)?, GFP_ATOMIC)?;\n+    ///\n+    /// if let Some(entry) = guard.find_next_entry(5) {\n+    ///     assert_eq!(entry.index(), 10);\n+    ///     let value = entry.remove();\n+    ///     assert_eq!(*value, 10);\n+    /// }\n+    ///\n+    /// assert_eq!(guard.get(10), None);\n+    ///\n+    /// # Ok::\u003c(), kernel::error::Error\u003e(())\n+    /// ```\n+    pub fn find_next_entry\u003c'b\u003e(\u0026'b mut self, index: usize) -\u003e Option\u003cOccupiedEntry\u003c'a, 'b, T\u003e\u003e {\n+        let mut state = XArrayState::new(self, index);\n+        let (_, ptr) = state.load_next(usize::MAX)?;\n+        Some(OccupiedEntry { state, ptr })\n+    }\n+\n+    /// Finds the next occupied entry starting at the given index, wrapping around.\n+    ///\n+    /// Searches for an entry starting at `index` up to the maximum index. If no entry\n+    /// is found, wraps around and searches from index 0 up to `index`.\n+    ///\n+    /// # Examples\n+    ///\n+    /// ```\n+    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray}};\n+    /// let mut xa = KBox::pin_init(XArray::\u003cKBox\u003cu32\u003e\u003e::new(AllocKind::Alloc), GFP_KERNEL)?;\n+    /// let mut guard = xa.lock();\n+    ///\n+    /// guard.store(100, KBox::new(42u32, GFP_ATOMIC)?, GFP_ATOMIC)?;\n+    /// let entry = guard.find_next_entry_circular(101);\n+    /// assert_eq!(entry.map(|e| e.index()), Some(100));\n+    ///\n+    /// # Ok::\u003c(), kernel::error::Error\u003e(())\n+    /// ```\n+    pub fn find_next_entry_circular\u003c'b\u003e(\n+        \u0026'b mut self,\n+        index: usize,\n+    ) -\u003e Option\u003cOccupiedEntry\u003c'a, 'b, T\u003e\u003e {\n+        let mut state = XArrayState::new(self, index);\n+\n+        let (_, ptr) = state.load_next(usize::MAX).or_else(|| {\n+            state.restart_at(0);\n+            state.load_next(index)\n+        })?;\n+\n+        Some(OccupiedEntry { state, ptr })\n     }\n \n     /// Removes and returns the element at the given index.\n@@ -226,7 +504,12 @@ pub fn remove(\u0026mut self, index: usize) -\u003e Option\u003cT\u003e {\n \n     /// Stores an element at the given index.\n     ///\n-    /// May drop the lock if needed to allocate memory, and then reacquire it afterwards.\n+    /// If `gfp` contains blocking allocation flags, this method may drop the\n+    /// lock to allocate memory and reacquire it afterwards. Other threads may\n+    /// lock and modify the array in that window, so callers must not rely on\n+    /// this method being atomic with respect to other operations on the\n+    /// guard. To store without dropping the lock, use [`Guard::insert_entry`]\n+    /// with preallocated memory.\n     ///\n     /// On success, returns the element which was previously at the given index.\n     ///\n@@ -273,8 +556,268 @@ pub fn store(\n             Ok(unsafe { T::try_from_foreign(old) })\n         }\n     }\n+\n+    /// Inserts a value and returns an occupied entry for further operations.\n+    ///\n+    /// If a value is already present, the operation fails.\n+    ///\n+    /// This method will not drop the XArray lock. If memory allocation is\n+    /// required for the operation to succeed, the user should supply memory\n+    /// through the `preload` argument.\n+    ///\n+    /// # Examples\n+    ///\n+    /// ```\n+    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray}};\n+    /// let mut xa = KBox::pin_init(XArray::\u003cKBox\u003cu32\u003e\u003e::new(AllocKind::Alloc), GFP_KERNEL)?;\n+    /// let mut guard = xa.lock();\n+    ///\n+    /// assert_eq!(guard.get(42), None);\n+    ///\n+    /// let value = KBox::new(0x1337u32, GFP_ATOMIC)?;\n+    /// let entry = guard.insert_entry(42, value, None)?;\n+    /// let borrowed = entry.into_mut();\n+    /// assert_eq!(borrowed, \u00260x1337);\n+    ///\n+    /// # Ok::\u003c(), kernel::error::Error\u003e(())\n+    /// ```\n+    pub fn insert_entry\u003c'b\u003e(\n+        \u0026'b mut self,\n+        index: usize,\n+        value: T,\n+        preload: Option\u003c\u0026mut XArraySheaf\u003c'_\u003e\u003e,\n+    ) -\u003e Result\u003cOccupiedEntry\u003c'a, 'b, T\u003e, StoreError\u003cT\u003e\u003e {\n+        match self.entry(index) {\n+            Entry::Vacant(entry) =\u003e entry.insert_entry(value, preload),\n+            Entry::Occupied(_) =\u003e Err(StoreError {\n+                error: EBUSY,\n+                value,\n+            }),\n+        }\n+    }\n+}\n+\n+/// Internal state for XArray iteration and entry operations.\n+///\n+/// `R` is the borrow held on the guard: either `\u0026Guard` for read-only callers\n+/// or `\u0026mut Guard` for entry-style APIs that need to surrender the borrow back\n+/// via [`XArrayState::into_guard`].\n+///\n+/// # Invariants\n+///\n+/// - `state` is always a valid `bindings::xa_state`.\n+/// - `state.xa` aliases the xarray reachable through `guard`.\n+pub(crate) struct XArrayState\u003cR\u003e {\n+    guard: R,\n+    state: bindings::xa_state,\n+}\n+\n+impl\u003cR\u003e Drop for XArrayState\u003cR\u003e {\n+    fn drop(\u0026mut self) {\n+        free_xa_alloc(\u0026mut self.state);\n+    }\n+}\n+\n+fn free_xa_alloc(state: \u0026mut bindings::xa_state) {\n+    if !state.xa_alloc.is_null() {\n+        // SAFETY:\n+        // - `xa_alloc` is only set via `SBox::into_ptr()` in `insert()` where\n+        //   the node comes from an `XArraySheaf` backed by `radix_tree_node_cachep`.\n+        // - `xa_alloc` points to a valid, initialized `XArrayNode`.\n+        // - The caller has exclusive ownership of `xa_alloc`, and no other\n+        //   `SBox` or reference exists for this value.\n+        drop(unsafe {\n+            SBox::\u003cXArrayNode\u003e::static_from_ptr(\n+                bindings::radix_tree_node_cachep,\n+                state.xa_alloc.cast(),\n+            )\n+        });\n+        state.xa_alloc = null_mut();\n+    }\n+}\n+\n+impl\u003c'a, R, T\u003e XArrayState\u003cR\u003e\n+where\n+    T: ForeignOwnable + 'a,\n+    R: core::ops::Deref\u003cTarget = Guard\u003c'a, T\u003e\u003e,\n+{\n+    #[inline]\n+    fn new(guard: R, index: usize) -\u003e Self {\n+        let xa_ptr = guard.xa.xa.get();\n+        // INVARIANT: `state` is initialized to a valid `xa_state` whose `xa` field aliases the\n+        // xarray reachable through `guard`.\n+        Self {\n+            guard,\n+            state: bindings::xa_state {\n+                xa: xa_ptr,\n+                xa_index: index,\n+                xa_shift: 0,\n+                xa_sibs: 0,\n+                xa_offset: 0,\n+                xa_pad: 0,\n+                xa_node: bindings::XAS_RESTART as *mut bindings::xa_node,\n+                xa_alloc: null_mut(),\n+                xa_update: None,\n+                xa_lru: null_mut(),\n+            },\n+        }\n+    }\n+\n+    #[inline]\n+    fn load(\u0026mut self) -\u003e Option\u003cNonNull\u003cc_void\u003e\u003e {\n+        // SAFETY: `self.state` is a valid `xa_state` by the type invariant. By the same\n+        // invariant, `self.state.xa` aliases the xarray reachable through `self.guard`, whose\n+        // lock we hold.\n+        let ptr = unsafe { bindings::xas_load(\u0026raw mut self.state) };\n+\n+        // Unlike the normal API, `xas_load` does not filter out internal entries. Arrays\n+        // created with [`AllocKind::Alloc1`] store `XA_ZERO_ENTRY` at index 0 when they are\n+        // expanded from empty, so convert zero entries to `NULL` like `xa_load` does. Retry\n+        // entries cannot be observed here because they require concurrent modification of the\n+        // array, and we hold the lock.\n+        //\n+        // SAFETY: `xa_zero_to_null` only inspects the value of `ptr`.\n+        NonNull::new(unsafe { bindings::xa_zero_to_null(ptr) }.cast())\n+    }\n+\n+    fn load_next(\u0026mut self, max: usize) -\u003e Option\u003c(usize, NonNull\u003cc_void\u003e)\u003e {\n+        loop {\n+            // SAFETY: `self.state` is a valid `xa_state` by the type invariant. By the same\n+            // invariant, `self.state.xa` aliases the xarray reachable through `self.guard`,\n+            // whose lock we hold.\n+            let ptr = unsafe { bindings::xas_find(\u0026raw mut self.state, max) };\n+            if ptr.is_null() {\n+                break None;\n+            }\n+\n+            // Unlike the normal API, `xas_find` does not filter out internal entries. Arrays\n+            // created with [`AllocKind::Alloc1`] store `XA_ZERO_ENTRY` at index 0 when they\n+            // are expanded from empty. Skip zero entries and continue the search, like the\n+            // `xas_retry` loop in `xa_find` does. Retry entries cannot be observed here\n+            // because they require concurrent modification of the array, and we hold the\n+            // lock.\n+            //\n+            // SAFETY: `xa_zero_to_null` only inspects the value of `ptr`.\n+            if let Some(ptr) = NonNull::new(unsafe { bindings::xa_zero_to_null(ptr) }) {\n+                break Some((self.state.xa_index, ptr));\n+            }\n+        }\n+    }\n+\n+    #[inline]\n+    fn status(\u0026self) -\u003e Result {\n+        // SAFETY: `self.state` is a valid `xa_state` by the type invariant.\n+        to_result(unsafe { bindings::xas_error(\u0026self.state) })\n+    }\n+\n+    /// Resets the state so the next operation walks the tree from the root,\n+    /// starting at `index`.\n+    fn restart_at(\u0026mut self, index: usize) {\n+        self.state.xa_index = index;\n+        self.state.xa_node = bindings::XAS_RESTART as *mut bindings::xa_node;\n+    }\n+}\n+\n+// Operations that modify the array require exclusive access to the guard, so\n+// they are only implemented for `XArrayState\u003c\u0026mut Guard\u003e`.\n+impl\u003c'a, 'b, T: ForeignOwnable\u003e XArrayState\u003c\u0026'b mut Guard\u003c'a, T\u003e\u003e {\n+    /// Stores `new` at the index of this state, returning the previous entry.\n+    ///\n+    /// The slot at the index of this state must be occupied. Storing to an\n+    /// occupied slot is a simple pointer swap that cannot fail, by design of\n+    /// the xarray data structure.\n+    fn replace(\u0026mut self, new: *mut c_void) -\u003e *mut c_void {\n+        // SAFETY: `self.state` is a valid `xa_state` by the type invariant. By the same\n+        // invariant, `self.state.xa` aliases the xarray reachable through `self.guard`, whose\n+        // lock we hold.\n+        let old = unsafe {\n+            bindings::xas_result(\n+                \u0026raw mut self.state,\n+                bindings::xa_zero_to_null(bindings::xas_store(\u0026raw mut self.state, new)),\n+            )\n+        };\n+\n+        // SAFETY: `old` is a valid return value from `xas_result`.\n+        let errno = unsafe { bindings::xa_err(old) };\n+\n+        // NOTE: Storing to an occupied slot never fails. This is by design of\n+        // the xarray data structure. If a slot is occupied, a store is a\n+        // simple pointer swap.\n+        debug_assert!(errno == 0);\n+\n+        old\n+    }\n+\n+    fn insert(\n+        \u0026mut self,\n+        value: T,\n+        mut preload: Option\u003c\u0026mut XArraySheaf\u003c'_\u003e\u003e,\n+    ) -\u003e Result\u003c*mut c_void, StoreError\u003cT\u003e\u003e {\n+        build_assert!(\n+            T::FOREIGN_ALIGN \u003e= 4,\n+            \"pointers stored in XArray must be 4-byte aligned\"\n+        );\n+        let new = T::into_foreign(value).cast();\n+\n+        loop {\n+            // SAFETY: `self.state` is a valid `xa_state` by the type invariant. By the same\n+            // invariant, `self.state.xa` aliases the xarray reachable through `self.guard`,\n+            // whose lock we hold. `new` came from `T::into_foreign`.\n+            unsafe { bindings::xas_store(\u0026mut self.state, new) };\n+\n+            // All arrays created by this abstraction have `XA_FLAGS_TRACK_FREE` set, so the\n+            // free mark must be cleared for a newly occupied index, as `__xa_store` does.\n+            // This is a no-op if the store above failed.\n+            //\n+            // SAFETY: `self.state` is a valid `xa_state` by the type invariant, and we hold\n+            // the lock on the xarray it refers to.\n+            unsafe { bindings::xas_clear_mark(\u0026self.state, bindings::XA_FREE_MARK) };\n+\n+            match self.status() {\n+                Ok(()) =\u003e break Ok(new),\n+                Err(ENOMEM) =\u003e {\n+                    debug_assert!(self.state.xa_alloc.is_null());\n+                    let node = match preload.as_mut().map(|sheaf| sheaf.alloc().ok_or(ENOMEM)) {\n+                        None =\u003e break Err(ENOMEM),\n+                        Some(Err(e)) =\u003e break Err(e),\n+                        Some(Ok(node)) =\u003e node,\n+                    };\n+\n+                    self.state.xa_alloc = node.into_ptr().cast();\n+\n+                    // On allocation failure, `xas_store` leaves `XA_ERROR(-ENOMEM)` in\n+                    // `self.state.xa_node`, which makes further operations on the state fail\n+                    // immediately without consuming `xa_alloc`. Reset the state so the retry\n+                    // walks the tree again, as `xas_nomem` does.\n+                    self.restart_at(self.state.xa_index);\n+                    continue;\n+                }\n+                Err(e) =\u003e break Err(e),\n+            }\n+        }\n+        .map_err(|error| {\n+            // SAFETY: `new` came from `T::into_foreign` and `xas_store` does not take\n+            // ownership of the value on error.\n+            let value = unsafe { T::from_foreign(new) };\n+            StoreError { value, error }\n+        })\n+    }\n+\n+    /// Consumes `self`, releases any preallocated node held in `xa_alloc`, and\n+    /// returns the inner `\u0026mut Guard`.\n+    #[inline]\n+    pub(crate) fn into_guard(self) -\u003e \u0026'b mut Guard\u003c'a, T\u003e {\n+        // Suppress the `Drop` impl so we can move `guard` out by hand.\n+        let mut this = core::mem::ManuallyDrop::new(self);\n+        free_xa_alloc(\u0026mut this.state);\n+        // SAFETY: `ManuallyDrop` prevents `Drop::drop` from running, so this is the only place\n+        // that consumes `guard`. `state` has no other resources after `free_xa_alloc`.\n+        unsafe { core::ptr::read(\u0026this.guard) }\n+    }\n }\n \n+mod entry;\n+\n // SAFETY: `XArray\u003cT\u003e` has no shared mutable state so it is `Send` iff `T` is `Send`.\n unsafe impl\u003cT: ForeignOwnable + Send\u003e Send for XArray\u003cT\u003e {}\n \ndiff --git a/rust/kernel/xarray/entry.rs b/rust/kernel/xarray/entry.rs\nnew file mode 100644\nindex 00000000000000..3d004f6f8c6cd4\n--- /dev/null\n+++ b/rust/kernel/xarray/entry.rs\n@@ -0,0 +1,381 @@\n+// SPDX-License-Identifier: GPL-2.0\n+\n+use super::{\n+    Guard,\n+    StoreError,\n+    XArraySheaf,\n+    XArrayState, //\n+};\n+use core::ptr::NonNull;\n+use kernel::{\n+    build_assert::build_assert,\n+    prelude::*,\n+    types::ForeignOwnable, //\n+};\n+\n+/// Represents either a vacant or occupied entry in an XArray.\n+pub enum Entry\u003c'a, 'b, T: ForeignOwnable\u003e {\n+    /// A vacant entry that can have a value inserted.\n+    Vacant(VacantEntry\u003c'a, 'b, T\u003e),\n+    /// An occupied entry containing a value.\n+    Occupied(OccupiedEntry\u003c'a, 'b, T\u003e),\n+}\n+\n+impl\u003cT: ForeignOwnable\u003e Entry\u003c'_, '_, T\u003e {\n+    /// Returns true if this entry is occupied.\n+    ///\n+    /// # Examples\n+    ///\n+    /// ```\n+    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray, Entry}};\n+    /// let mut xa = KBox::pin_init(XArray::\u003cKBox\u003cu32\u003e\u003e::new(AllocKind::Alloc), GFP_KERNEL)?;\n+    /// let mut guard = xa.lock();\n+    ///\n+    /// let entry = guard.entry(42);\n+    /// assert_eq!(entry.is_occupied(), false);\n+    /// drop(entry);\n+    ///\n+    /// guard.store(42, KBox::new(0x1337u32, GFP_ATOMIC)?, GFP_ATOMIC)?;\n+    /// let entry = guard.entry(42);\n+    /// assert_eq!(entry.is_occupied(), true);\n+    ///\n+    /// # Ok::\u003c(), kernel::error::Error\u003e(())\n+    /// ```\n+    #[inline]\n+    pub fn is_occupied(\u0026self) -\u003e bool {\n+        matches!(self, Entry::Occupied(_))\n+    }\n+}\n+\n+/// A view into a vacant entry in an XArray.\n+pub struct VacantEntry\u003c'a, 'b, T: ForeignOwnable\u003e {\n+    state: XArrayState\u003c\u0026'b mut Guard\u003c'a, T\u003e\u003e,\n+}\n+\n+impl\u003c'a, 'b, T\u003e VacantEntry\u003c'a, 'b, T\u003e\n+where\n+    T: ForeignOwnable,\n+{\n+    pub(crate) fn new(guard: \u0026'b mut Guard\u003c'a, T\u003e, index: usize) -\u003e Self {\n+        Self {\n+            state: XArrayState::new(guard, index),\n+        }\n+    }\n+\n+    /// Consumes the entry and returns a mutable reference to the underlying\n+    /// guard.\n+    ///\n+    /// This releases the slot reservation but retains the lock guard so the\n+    /// caller can perform further operations on the array.\n+    #[inline]\n+    pub fn into_guard(self) -\u003e \u0026'b mut Guard\u003c'a, T\u003e {\n+        self.state.into_guard()\n+    }\n+\n+    /// Inserts a value into this vacant entry.\n+    ///\n+    /// Returns a reference to the newly inserted value.\n+    ///\n+    /// - This method will fail if the nodes on the path to the index\n+    ///   represented by this entry are not present in the XArray and no memory\n+    ///   is available via the `preload` argument.\n+    /// - This method will not drop the XArray lock.\n+    ///\n+    ///\n+    /// # Examples\n+    ///\n+    /// ```\n+    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray, Entry}};\n+    /// let mut xa = KBox::pin_init(XArray::\u003cKBox\u003cu32\u003e\u003e::new(AllocKind::Alloc), GFP_KERNEL)?;\n+    /// let mut guard = xa.lock();\n+    ///\n+    /// assert_eq!(guard.get(42), None);\n+    ///\n+    /// if let Entry::Vacant(entry) = guard.entry(42) {\n+    ///     let value = KBox::new(0x1337u32, GFP_ATOMIC)?;\n+    ///     let borrowed = entry.insert(value, None)?;\n+    ///     assert_eq!(*borrowed, 0x1337);\n+    /// }\n+    ///\n+    /// assert_eq!(guard.get(42).copied(), Some(0x1337));\n+    ///\n+    /// # Ok::\u003c(), kernel::error::Error\u003e(())\n+    /// ```\n+    pub fn insert(\n+        mut self,\n+        value: T,\n+        preload: Option\u003c\u0026mut XArraySheaf\u003c'_\u003e\u003e,\n+    ) -\u003e Result\u003cT::BorrowedMut\u003c'b\u003e, StoreError\u003cT\u003e\u003e {\n+        let new = self.state.insert(value, preload)?;\n+\n+        // SAFETY: `new` came from `T::into_foreign`. The entry has exclusive\n+        // ownership of `new` as it holds a mutable reference to `Guard`.\n+        Ok(unsafe { T::borrow_mut(new) })\n+    }\n+\n+    /// Inserts a value and returns an occupied entry representing the newly inserted value.\n+    ///\n+    /// - This method will fail if the nodes on the path to the index\n+    ///   represented by this entry are not present in the XArray and no memory\n+    ///   is available via the `preload` argument.\n+    /// - This method will not drop the XArray lock.\n+    ///\n+    /// # Examples\n+    ///\n+    /// ```\n+    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray, Entry}};\n+    /// let mut xa = KBox::pin_init(XArray::\u003cKBox\u003cu32\u003e\u003e::new(AllocKind::Alloc), GFP_KERNEL)?;\n+    /// let mut guard = xa.lock();\n+    ///\n+    /// assert_eq!(guard.get(42), None);\n+    ///\n+    /// if let Entry::Vacant(entry) = guard.entry(42) {\n+    ///     let value = KBox::new(0x1337u32, GFP_ATOMIC)?;\n+    ///     let occupied = entry.insert_entry(value, None)?;\n+    ///     assert_eq!(occupied.index(), 42);\n+    /// }\n+    ///\n+    /// assert_eq!(guard.get(42).copied(), Some(0x1337));\n+    ///\n+    /// # Ok::\u003c(), kernel::error::Error\u003e(())\n+    /// ```\n+    pub fn insert_entry(\n+        mut self,\n+        value: T,\n+        preload: Option\u003c\u0026mut XArraySheaf\u003c'_\u003e\u003e,\n+    ) -\u003e Result\u003cOccupiedEntry\u003c'a, 'b, T\u003e, StoreError\u003cT\u003e\u003e {\n+        let new = self.state.insert(value, preload)?;\n+\n+        Ok(OccupiedEntry::\u003c'a, 'b, T\u003e {\n+            state: self.state,\n+            // SAFETY: `new` came from `T::into_foreign` and is guaranteed non-null.\n+            ptr: unsafe { core::ptr::NonNull::new_unchecked(new) },\n+        })\n+    }\n+\n+    /// Returns the index of this vacant entry.\n+    ///\n+    /// # Examples\n+    ///\n+    /// ```\n+    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray, Entry}};\n+    /// let mut xa = KBox::pin_init(XArray::\u003cKBox\u003cu32\u003e\u003e::new(AllocKind::Alloc), GFP_KERNEL)?;\n+    /// let mut guard = xa.lock();\n+    ///\n+    /// assert_eq!(guard.get(42), None);\n+    ///\n+    /// if let Entry::Vacant(entry) = guard.entry(42) {\n+    ///     assert_eq!(entry.index(), 42);\n+    /// }\n+    ///\n+    /// # Ok::\u003c(), kernel::error::Error\u003e(())\n+    /// ```\n+    #[inline]\n+    pub fn index(\u0026self) -\u003e usize {\n+        self.state.state.xa_index\n+    }\n+}\n+\n+/// A view into an occupied entry in an XArray.\n+pub struct OccupiedEntry\u003c'a, 'b, T: ForeignOwnable\u003e {\n+    pub(crate) state: XArrayState\u003c\u0026'b mut Guard\u003c'a, T\u003e\u003e,\n+    pub(crate) ptr: NonNull\u003cc_void\u003e,\n+}\n+\n+impl\u003c'a, 'b, T\u003e OccupiedEntry\u003c'a, 'b, T\u003e\n+where\n+    T: ForeignOwnable,\n+{\n+    pub(crate) fn new(guard: \u0026'b mut Guard\u003c'a, T\u003e, index: usize, ptr: NonNull\u003cc_void\u003e) -\u003e Self {\n+        Self {\n+            state: XArrayState::new(guard, index),\n+            ptr,\n+        }\n+    }\n+\n+    /// Consumes the entry and returns a mutable reference to the underlying\n+    /// guard.\n+    ///\n+    /// This releases the borrow on the entry's slot but retains the lock\n+    /// guard so the caller can perform further operations on the array.\n+    #[inline]\n+    pub fn into_guard(self) -\u003e \u0026'b mut Guard\u003c'a, T\u003e {\n+        self.state.into_guard()\n+    }\n+\n+    /// Removes the value from this occupied entry and returns it, consuming the entry.\n+    ///\n+    /// # Examples\n+    ///\n+    /// ```\n+    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray, Entry}};\n+    /// let mut xa = KBox::pin_init(XArray::\u003cKBox\u003cu32\u003e\u003e::new(AllocKind::Alloc), GFP_KERNEL)?;\n+    /// let mut guard = xa.lock();\n+    ///\n+    /// guard.store(42, KBox::new(0x1337u32, GFP_ATOMIC)?, GFP_ATOMIC)?;\n+    /// assert_eq!(guard.get(42).copied(), Some(0x1337));\n+    ///\n+    /// if let Entry::Occupied(entry) = guard.entry(42) {\n+    ///     let value = entry.remove();\n+    ///     assert_eq!(*value, 0x1337);\n+    /// }\n+    ///\n+    /// assert_eq!(guard.get(42), None);\n+    ///\n+    /// # Ok::\u003c(), kernel::error::Error\u003e(())\n+    /// ```\n+    pub fn remove(mut self) -\u003e T {\n+        let ptr = self.state.replace(core::ptr::null_mut());\n+\n+        // SAFETY:\n+        // - `ptr` came from `T::into_foreign`.\n+        // - As this method takes self by value, the lifetimes of any [`T::Borrowed`] and\n+        //   [`T::BorrowedMut`] we have created must have ended.\n+        unsafe { T::from_foreign(ptr.cast()) }\n+    }\n+\n+    /// Returns the index of this occupied entry.\n+    ///\n+    /// # Examples\n+    ///\n+    /// ```\n+    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray, Entry}};\n+    /// let mut xa = KBox::pin_init(XArray::\u003cKBox\u003cu32\u003e\u003e::new(AllocKind::Alloc), GFP_KERNEL)?;\n+    /// let mut guard = xa.lock();\n+    ///\n+    /// guard.store(42, KBox::new(0x1337u32, GFP_ATOMIC)?, GFP_ATOMIC)?;\n+    ///\n+    /// if let Entry::Occupied(entry) = guard.entry(42) {\n+    ///     assert_eq!(entry.index(), 42);\n+    /// }\n+    ///\n+    /// # Ok::\u003c(), kernel::error::Error\u003e(())\n+    /// ```\n+    #[inline]\n+    pub fn index(\u0026self) -\u003e usize {\n+        self.state.state.xa_index\n+    }\n+\n+    /// Replaces the value in this occupied entry and returns the old value.\n+    ///\n+    /// # Examples\n+    ///\n+    /// ```\n+    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray, Entry}};\n+    /// let mut xa = KBox::pin_init(XArray::\u003cKBox\u003cu32\u003e\u003e::new(AllocKind::Alloc), GFP_KERNEL)?;\n+    /// let mut guard = xa.lock();\n+    ///\n+    /// guard.store(42, KBox::new(0x1337u32, GFP_ATOMIC)?, GFP_ATOMIC)?;\n+    ///\n+    /// if let Entry::Occupied(mut entry) = guard.entry(42) {\n+    ///     let new_value = KBox::new(0x9999u32, GFP_ATOMIC)?;\n+    ///     let old_value = entry.insert(new_value);\n+    ///     assert_eq!(*old_value, 0x1337);\n+    /// }\n+    ///\n+    /// assert_eq!(guard.get(42).copied(), Some(0x9999));\n+    ///\n+    /// # Ok::\u003c(), kernel::error::Error\u003e(())\n+    /// ```\n+    pub fn insert(\u0026mut self, value: T) -\u003e T {\n+        build_assert!(\n+            T::FOREIGN_ALIGN \u003e= 4,\n+            \"pointers stored in XArray must be 4-byte aligned\"\n+        );\n+        let new = T::into_foreign(value).cast();\n+        // SAFETY: `new` came from `T::into_foreign` and is guaranteed non-null.\n+        self.ptr = unsafe { NonNull::new_unchecked(new) };\n+\n+        let old = self.state.replace(new);\n+\n+        // SAFETY:\n+        // - `old` came from `T::into_foreign`.\n+        // - As this method takes `self` by mutable reference, the lifetimes of any\n+        //   [`T::Borrowed`] and [`T::BorrowedMut`] we have created must have ended.\n+        unsafe { T::from_foreign(old) }\n+    }\n+\n+    /// Converts this occupied entry into a mutable reference to the value in the slot represented\n+    /// by the entry.\n+    ///\n+    /// # Examples\n+    ///\n+    /// ```\n+    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray, Entry}};\n+    /// let mut xa = KBox::pin_init(XArray::\u003cKBox\u003cu32\u003e\u003e::new(AllocKind::Alloc), GFP_KERNEL)?;\n+    /// let mut guard = xa.lock();\n+    ///\n+    /// guard.store(42, KBox::new(0x1337u32, GFP_ATOMIC)?, GFP_ATOMIC)?;\n+    ///\n+    /// if let Entry::Occupied(entry) = guard.entry(42) {\n+    ///     let value_ref = entry.into_mut();\n+    ///     *value_ref = 0x9999;\n+    /// }\n+    ///\n+    /// assert_eq!(guard.get(42).copied(), Some(0x9999));\n+    ///\n+    /// # Ok::\u003c(), kernel::error::Error\u003e(())\n+    /// ```\n+    #[inline]\n+    pub fn into_mut(self) -\u003e T::BorrowedMut\u003c'b\u003e {\n+        // SAFETY: `ptr` came from `T::into_foreign`.\n+        unsafe { T::borrow_mut(self.ptr.as_ptr()) }\n+    }\n+\n+    /// Swaps the value in this entry with the provided value.\n+    ///\n+    /// Returns the old value that was in the entry.\n+    ///\n+    /// # Examples\n+    ///\n+    /// ```\n+    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray, Entry}};\n+    /// let mut xa = KBox::pin_init(XArray::\u003cKBox\u003cu32\u003e\u003e::new(AllocKind::Alloc), GFP_KERNEL)?;\n+    /// let mut guard = xa.lock();\n+    ///\n+    /// guard.store(42, KBox::new(100u32, GFP_ATOMIC)?, GFP_ATOMIC)?;\n+    ///\n+    /// if let Entry::Occupied(mut entry) = guard.entry(42) {\n+    ///     let mut other = 200u32;\n+    ///     entry.swap(\u0026mut other);\n+    ///     assert_eq!(other, 100);\n+    ///     assert_eq!(*entry, 200);\n+    /// }\n+    ///\n+    /// # Ok::\u003c(), kernel::error::Error\u003e(())\n+    /// ```\n+    pub fn swap\u003cU\u003e(\u0026mut self, other: \u0026mut U)\n+    where\n+        T: ForeignOwnable\u003cBorrowed\u003c'b\u003e = \u0026'b U, BorrowedMut\u003c'b\u003e = \u0026'b mut U\u003e + 'b,\n+        U: 'b,\n+    {\n+        use core::ops::DerefMut;\n+        core::mem::swap(self.deref_mut(), other);\n+    }\n+}\n+\n+impl\u003c'a, 'b, T, U\u003e core::ops::Deref for OccupiedEntry\u003c'a, 'b, T\u003e\n+where\n+    T: ForeignOwnable\u003cBorrowed\u003c'b\u003e = \u0026'b U, BorrowedMut\u003c'b\u003e = \u0026'b mut U\u003e + 'b,\n+    U: 'b,\n+{\n+    type Target = U;\n+\n+    #[inline]\n+    fn deref(\u0026self) -\u003e \u0026Self::Target {\n+        // SAFETY: `ptr` came from `T::into_foreign`.\n+        unsafe { T::borrow(self.ptr.as_ptr()) }\n+    }\n+}\n+\n+impl\u003c'a, 'b, T, U\u003e core::ops::DerefMut for OccupiedEntry\u003c'a, 'b, T\u003e\n+where\n+    T: ForeignOwnable\u003cBorrowed\u003c'b\u003e = \u0026'b U, BorrowedMut\u003c'b\u003e = \u0026'b mut U\u003e + 'b,\n+    U: 'b,\n+{\n+    #[inline]\n+    fn deref_mut(\u0026mut self) -\u003e \u0026mut Self::Target {\n+        // SAFETY: `ptr` came from `T::into_foreign`.\n+        unsafe { T::borrow_mut(self.ptr.as_ptr()) }\n+    }\n+}\n"
}

2/1 2026/11/25 13:48 agent patch-evaluator
15m Model:
core

Args:
null

Results:
{
  "EnableConfigs": [
    "SLUB",
    "RUST"
  ],
  "FocusSymbols": [
    "kmem_cache_prefill_sheaf",
    "kmem_cache_return_sheaf",
    "kmem_cache_refill_sheaf",
    "kmem_cache_alloc_from_sheaf_noprof",
    "radix_tree_node_ctor",
    "rust_helper_xas_result",
    "rust_helper_xa_zero_to_null",
    "rust_helper_xas_error"
  ],
  "Reasoning": "The patch series modifies core memory management and data structure logic. It configures the global radix_tree_node_cachep with sheaf capacity support (.sheaf_capacity = 64), which alters SLUB fast-path allocation and freeing behavior (percpu sheaves) for all radix tree and XArray nodes across the kernel. It also exports the SLUB sheaf management API, moves XArray helpers to public headers, and adds Rust abstractions for SLUB sheaves and XArray entry operations. These changes touch reachable core paths and warrant 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 8f525438224f17da9edd0c9c7e7da757f585c4fb
Author: syz-cluster <triage@syzkaller.com>
Date:   Wed Nov 25 13:48:27 2026 +0000

    syz-cluster: applied patch under review

diff --git a/MAINTAINERS b/MAINTAINERS
index 222b7fc2c3aab8..845503be1f289b 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -30500,6 +30500,7 @@ B:	https://github.com/Rust-for-Linux/linux/issues
 C:	https://rust-for-linux.zulipchat.com
 T:	git https://github.com/Rust-for-Linux/linux.git xarray-next
 F:	rust/kernel/xarray.rs
+F:	rust/kernel/xarray/
 
 XBOX DVD IR REMOTE
 M:	Benjamin Valentin <benpicco@googlemail.com>
diff --git a/include/linux/radix-tree.h b/include/linux/radix-tree.h
index 057edc4cbb6ef2..ac5fc299399cfb 100644
--- a/include/linux/radix-tree.h
+++ b/include/linux/radix-tree.h
@@ -470,4 +470,7 @@ static __always_inline void __rcu **radix_tree_next_slot(void __rcu **slot,
 	     slot = radix_tree_next_slot(slot, iter,			\
 				RADIX_TREE_ITER_TAGGED | tag))
 
+
+void radix_tree_node_ctor(void *arg);
+
 #endif /* _LINUX_RADIX_TREE_H */
diff --git a/include/linux/xarray.h b/include/linux/xarray.h
index be850174e802e6..db2520864aaa7f 100644
--- a/include/linux/xarray.h
+++ b/include/linux/xarray.h
@@ -191,6 +191,17 @@ static inline bool xa_is_zero(const void *entry)
 	return unlikely(entry == XA_ZERO_ENTRY);
 }
 
+/**
+ * xa_zero_to_null() - Convert an internal zero entry into a NULL pointer.
+ * @entry: XArray entry.
+ *
+ * Return: %NULL if @entry is a zero entry, @entry otherwise.
+ */
+static inline void *xa_zero_to_null(void *entry)
+{
+	return xa_is_zero(entry) ? NULL : entry;
+}
+
 /**
  * xa_is_err() - Report whether an XArray operation returned an error
  * @entry: Result from calling an XArray function
@@ -1437,6 +1448,21 @@ static inline int xas_error(const struct xa_state *xas)
 	return xa_err(xas->xa_node);
 }
 
+/**
+ * xas_result() - Extract the result of an XArray operation.
+ * @xas: XArray operation state.
+ * @curr: Entry returned by the operation.
+ *
+ * Return: @curr if the operation succeeded, the error encoded in @xas
+ * otherwise.
+ */
+static inline void *xas_result(struct xa_state *xas, void *curr)
+{
+	if (xas_error(xas))
+		curr = xas->xa_node;
+	return curr;
+}
+
 /**
  * xas_set_err() - Note an error in the xa_state.
  * @xas: XArray operation state.
diff --git a/lib/radix-tree.c b/lib/radix-tree.c
index 976b9bd02a1b5d..ddd67ce672f5c4 100644
--- a/lib/radix-tree.c
+++ b/lib/radix-tree.c
@@ -33,6 +33,7 @@
  * Radix tree node cache.
  */
 struct kmem_cache *radix_tree_node_cachep;
+EXPORT_SYMBOL(radix_tree_node_cachep);
 
 /*
  * The radix tree is variable-height, so an insert operation not only has
@@ -1566,14 +1567,14 @@ void idr_destroy(struct idr *idr)
 }
 EXPORT_SYMBOL(idr_destroy);
 
-static void
-radix_tree_node_ctor(void *arg)
+void radix_tree_node_ctor(void *arg)
 {
 	struct radix_tree_node *node = arg;
 
 	memset(node, 0, sizeof(*node));
 	INIT_LIST_HEAD(&node->private_list);
 }
+EXPORT_SYMBOL(radix_tree_node_ctor);
 
 static int radix_tree_cpu_dead(unsigned int cpu)
 {
@@ -1598,10 +1599,16 @@ void __init radix_tree_init(void)
 	BUILD_BUG_ON(RADIX_TREE_MAX_TAGS + __GFP_BITS_SHIFT > 32);
 	BUILD_BUG_ON(ROOT_IS_IDR & ~GFP_ZONEMASK);
 	BUILD_BUG_ON(XA_CHUNK_SIZE > 255);
-	radix_tree_node_cachep = kmem_cache_create("radix_tree_node",
-			sizeof(struct radix_tree_node), 0,
-			SLAB_PANIC | SLAB_RECLAIM_ACCOUNT,
-			radix_tree_node_ctor);
+
+	struct kmem_cache_args args = {
+		.ctor = radix_tree_node_ctor,
+		.sheaf_capacity = 64,
+	};
+
+	radix_tree_node_cachep = kmem_cache_create(
+		"radix_tree_node", sizeof(struct radix_tree_node), &args,
+		SLAB_PANIC | SLAB_RECLAIM_ACCOUNT);
+
 	ret = cpuhp_setup_state_nocalls(CPUHP_RADIX_DEAD, "lib/radix:dead",
 					NULL, radix_tree_cpu_dead);
 	WARN_ON(ret < 0);
diff --git a/lib/xarray.c b/lib/xarray.c
index bfe7bef80f34eb..49fbec5f6c38e8 100644
--- a/lib/xarray.c
+++ b/lib/xarray.c
@@ -437,11 +437,6 @@ static unsigned long max_index(void *entry)
 	return (XA_CHUNK_SIZE << xa_to_node(entry)->shift) - 1;
 }
 
-static inline void *xa_zero_to_null(void *entry)
-{
-	return xa_is_zero(entry) ? NULL : entry;
-}
-
 static void xas_shrink(struct xa_state *xas)
 {
 	struct xarray *xa = xas->xa;
@@ -1627,13 +1622,6 @@ void *xa_load(struct xarray *xa, unsigned long index)
 }
 EXPORT_SYMBOL(xa_load);
 
-static void *xas_result(struct xa_state *xas, void *curr)
-{
-	if (xas_error(xas))
-		curr = xas->xa_node;
-	return curr;
-}
-
 /**
  * __xa_erase() - Erase this entry from the XArray while locked.
  * @xa: XArray.
diff --git a/mm/slub.c b/mm/slub.c
index cd671b93471918..21811b9ff791f4 100644
--- a/mm/slub.c
+++ b/mm/slub.c
@@ -5292,6 +5292,7 @@ kmem_cache_prefill_sheaf(struct kmem_cache *s, gfp_t gfp, unsigned int size)
 
 	return sheaf;
 }
+EXPORT_SYMBOL(kmem_cache_prefill_sheaf);
 
 /*
  * Use this to return a sheaf obtained by kmem_cache_prefill_sheaf()
@@ -5347,6 +5348,7 @@ void kmem_cache_return_sheaf(struct kmem_cache *s, gfp_t gfp,
 	barn_put_full_sheaf(barn, sheaf);
 	stat(s, BARN_PUT);
 }
+EXPORT_SYMBOL(kmem_cache_return_sheaf);
 
 /*
  * Refill a sheaf previously returned by kmem_cache_prefill_sheaf to at least
@@ -5402,6 +5404,7 @@ int kmem_cache_refill_sheaf(struct kmem_cache *s, gfp_t gfp,
 	*sheafp = sheaf;
 	return 0;
 }
+EXPORT_SYMBOL(kmem_cache_refill_sheaf);
 
 /*
  * Allocate from a sheaf obtained by kmem_cache_prefill_sheaf()
@@ -5440,6 +5443,7 @@ kmem_cache_alloc_from_sheaf_noprof(struct kmem_cache *s, gfp_t gfp,
 
 	return ret;
 }
+EXPORT_SYMBOL(kmem_cache_alloc_from_sheaf_noprof);
 
 unsigned int kmem_cache_sheaf_size(struct slab_sheaf *sheaf)
 {
diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h
index 3791af0aadc73e..fb76a2d30449a1 100644
--- a/rust/bindings/bindings_helper.h
+++ b/rust/bindings/bindings_helper.h
@@ -127,9 +127,20 @@ const blk_features_t RUST_CONST_HELPER_BLK_FEAT_ROTATIONAL = BLK_FEAT_ROTATIONAL
 const fop_flags_t RUST_CONST_HELPER_FOP_UNSIGNED_OFFSET = FOP_UNSIGNED_OFFSET;
 
 const xa_mark_t RUST_CONST_HELPER_XA_PRESENT = XA_PRESENT;
+const xa_mark_t RUST_CONST_HELPER_XA_FREE_MARK = XA_FREE_MARK;
 
 const gfp_t RUST_CONST_HELPER_XA_FLAGS_ALLOC = XA_FLAGS_ALLOC;
 const gfp_t RUST_CONST_HELPER_XA_FLAGS_ALLOC1 = XA_FLAGS_ALLOC1;
+/*
+ * `XAS_RESTART` is `((struct xa_node *)3UL)` -- a sentinel pointer value, not
+ * an address. Cast to `size_t` so bindgen emits a plain `usize` constant; for
+ * pointer-typed macro values bindgen otherwise generates a `pub static mut`,
+ * see https://github.com/rust-lang/rust-bindgen/issues/3347.
+ */
+const size_t RUST_CONST_HELPER_XAS_RESTART = (size_t)XAS_RESTART;
+const size_t RUST_CONST_HELPER_XA_CHUNK_SHIFT = XA_CHUNK_SHIFT;
+const size_t RUST_CONST_HELPER_XA_CHUNK_SIZE = XA_CHUNK_SIZE;
+extern struct kmem_cache *radix_tree_node_cachep;
 
 const vm_flags_t RUST_CONST_HELPER_VM_MERGEABLE = VM_MERGEABLE;
 const vm_flags_t RUST_CONST_HELPER_VM_READ = VM_READ;
diff --git a/rust/helpers/xarray.c b/rust/helpers/xarray.c
index 08979b3043410f..d7548a17ae0d06 100644
--- a/rust/helpers/xarray.c
+++ b/rust/helpers/xarray.c
@@ -26,3 +26,18 @@ __rust_helper void rust_helper_xa_unlock(struct xarray *xa)
 {
 	return xa_unlock(xa);
 }
+
+__rust_helper void *rust_helper_xas_result(struct xa_state *xas, void *curr)
+{
+	return xas_result(xas, curr);
+}
+
+__rust_helper void *rust_helper_xa_zero_to_null(void *entry)
+{
+	return xa_zero_to_null(entry);
+}
+
+__rust_helper int rust_helper_xas_error(const struct xa_state *xas)
+{
+	return xas_error(xas);
+}
diff --git a/rust/kernel/mm.rs b/rust/kernel/mm.rs
index 58bc1793fdaf5e..c1920f04917093 100644
--- a/rust/kernel/mm.rs
+++ b/rust/kernel/mm.rs
@@ -18,6 +18,7 @@
 };
 use core::{ops::Deref, ptr::NonNull};
 
+pub mod sheaf;
 pub mod virt;
 use virt::VmaRef;
 
diff --git a/rust/kernel/mm/sheaf.rs b/rust/kernel/mm/sheaf.rs
new file mode 100644
index 00000000000000..9afbac20241868
--- /dev/null
+++ b/rust/kernel/mm/sheaf.rs
@@ -0,0 +1,762 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Slub allocator sheaf abstraction.
+//!
+//! Sheaves are percpu array-based caching layers for the slub allocator.
+//! They provide a mechanism for pre-allocating objects that can later
+//! be retrieved without risking allocation failure, making them useful in
+//! contexts where memory allocation must be guaranteed to succeed.
+//!
+//! The term "sheaf" is the english word for a bundle of straw. In this context
+//! it means a bundle of pre-allocated objects. A per-NUMA-node cache of sheaves
+//! is called a "barn". Because you store your sheafs in barns.
+//!
+//! # Use cases
+//!
+//! Sheaves are particularly useful when:
+//!
+//! - Allocations must be guaranteed to succeed in a restricted context (e.g.,
+//!   while holding locks or in atomic context).
+//! - Multiple allocations need to be performed as a batch operation.
+//! - Fast-path allocation performance is critical, as sheaf allocations avoid
+//!   atomic operations by using local locks with preemption disabled. Note
+//!   that the abstraction adds reference counting on top of this for dynamic
+//!   caches, see [`Sheaf`].
+//!
+//! # Architecture
+//!
+//! The sheaf system supports two modes of operation:
+//!
+//! - **Static caches**: [`KMemCache`] represents a cache that is never
+//!   destroyed, typically one created by C code at kernel boot time. These
+//!   have `'static` lifetime and produce [`StaticSheaf`] instances.
+//! - **Dynamic caches**: [`KMemCacheHandle`] owns a cache created through
+//!   this abstraction. These are reference-counted, destroyed when the last
+//!   reference is dropped, and produce [`DynamicSheaf`] instances.
+//!
+//! Both modes use the same core types:
+//!
+//! - [`Sheaf`]: A pre-filled container of objects from a specific cache.
+//! - [`SBox`]: An owned allocation from a sheaf, similar to a `Box`.
+//!
+//! # Example
+//!
+//! Using a dynamically created cache:
+//!
+//! ```
+//! use kernel::c_str;
+//! use kernel::mm::sheaf::{KMemCacheHandle, KMemCacheInit, Sheaf, SBox};
+//! use kernel::prelude::*;
+//!
+//! struct MyObject {
+//!     value: u32,
+//! }
+//!
+//! impl KMemCacheInit<MyObject> for MyObject {
+//!     fn init() -> impl Init<MyObject> {
+//!         init!(MyObject { value: 0 })
+//!     }
+//! }
+//!
+//! // Create a cache with a sheaf capacity of at least 16 objects.
+//! let cache = KMemCacheHandle::<MyObject>::new(c_str!("my_cache"), 16)?;
+//!
+//! // Pre-fill a sheaf with 8 objects.
+//! let mut sheaf = cache.as_arc_borrow().sheaf(8, GFP_KERNEL)?;
+//!
+//! // Allocations from the sheaf are guaranteed to succeed until empty.
+//! let obj = sheaf.alloc().unwrap();
+//!
+//! // Return the sheaf when done, attempting to refill it.
+//! sheaf.return_refill(GFP_KERNEL);
+//! # Ok::<(), Error>(())
+//! ```
+//!
+//! # Constraints
+//!
+//! - Sheaves are slower when `CONFIG_SLUB_TINY` is enabled, or when slab
+//!   debugging (`slab_debug`) is enabled for the cache, due to cpu sheaves
+//!   being disabled. All prefilled sheaves become "oversize" and go through a
+//!   slower allocation path.
+//! - The sheaf capacity of a cache is decided at cache creation time. The
+//!   capacity requested when creating the cache is a minimum. The allocator
+//!   calculates a capacity based on the object size and uses the larger of the
+//!   two.
+
+use core::{
+    convert::Infallible,
+    marker::PhantomData,
+    ops::{Deref, DerefMut},
+    ptr::NonNull,
+};
+
+use kernel::prelude::*;
+
+use crate::{
+    sync::{Arc, ArcBorrow},
+    types::Opaque,
+};
+
+/// A slab cache with sheaf support.
+///
+/// This type is a transparent wrapper around a kernel `kmem_cache`. It can be
+/// used with caches created either by C code or via [`KMemCacheHandle`].
+///
+/// When a reference to this type has `'static` lifetime (i.e., `&'static
+/// KMemCache<T>`), it represents a cache that is never destroyed, typically
+/// one created by C code at boot time. Such references produce
+/// [`StaticSheaf`] instances via [`sheaf`].
+///
+/// [`sheaf`]: KMemCache::sheaf
+///
+/// # Type parameter
+///
+/// - `T`: The type of objects managed by this cache. Must implement
+///   [`KMemCacheInit`] to provide initialization logic for allocations.
+#[repr(transparent)]
+pub struct KMemCache<T: KMemCacheInit<T>> {
+    inner: Opaque<bindings::kmem_cache>,
+    _p: PhantomData<T>,
+}
+
+// SAFETY: The C `kmem_cache` is internally synchronized and has no thread
+// affinity, so a `KMemCache<T>` may be sent to another thread if the objects
+// it manages can.
+unsafe impl<T: KMemCacheInit<T> + Send> Send for KMemCache<T> {}
+
+// SAFETY: All operations available through `&KMemCache<T>` (creating sheaves
+// and allocating objects) are internally synchronized by the C side, so the
+// cache may be used from multiple threads concurrently if the objects it
+// manages can be sent between threads.
+unsafe impl<T: KMemCacheInit<T> + Send> Sync for KMemCache<T> {}
+
+impl<T: KMemCacheInit<T>> KMemCache<T> {
+    /// Creates a pre-filled sheaf from this cache.
+    ///
+    /// Allocates a sheaf and pre-fills it with `size` objects. Once created,
+    /// allocations from the sheaf via [`Sheaf::alloc`] are guaranteed to
+    /// succeed until the sheaf is depleted.
+    ///
+    /// # Arguments
+    ///
+    /// - `size`: The number of objects to pre-allocate. Must not be zero. If
+    ///   `size` exceeds the sheaf capacity of the cache, an "oversize" sheaf
+    ///   is allocated. Oversize sheaves are slower to create, and they are
+    ///   flushed and freed rather than cached for reuse when returned.
+    /// - `gfp`: Allocation flags controlling how memory is obtained. Use
+    ///   [`GFP_KERNEL`] for normal allocations that may sleep, or
+    ///   [`GFP_NOWAIT`] for non-blocking allocations.
+    ///
+    /// # Errors
+    ///
+    /// Returns [`ENOMEM`] if the sheaf or its objects could not be allocated,
+    /// or if `size` is zero.
+    #[inline]
+    pub fn sheaf(
+        &'static self,
+        size: usize,
+        gfp: kernel::alloc::Flags,
+    ) -> Result<Sheaf<'static, T, Static>> {
+        // SAFETY: `self.as_raw()` returns a valid cache pointer, and `size`
+        // has been validated to fit in a `c_uint`.
+        let ptr = unsafe {
+            bindings::kmem_cache_prefill_sheaf(self.inner.get(), gfp.as_raw(), size.try_into()?)
+        };
+
+        // INVARIANT: `ptr` was returned by `kmem_cache_prefill_sheaf` and is
+        // non-null (checked below). `cache` is the cache from which this sheaf
+        // was created. `dropped` is false since the sheaf has not been returned.
+        Ok(Sheaf {
+            sheaf: NonNull::new(ptr).ok_or(ENOMEM)?,
+            // SAFETY: `self` is a valid reference, so the pointer is non-null.
+            cache: CacheRef::Static(unsafe {
+                NonNull::new_unchecked((&raw const *self).cast_mut())
+            }),
+            dropped: false,
+            _p: PhantomData,
+        })
+    }
+
+    #[inline]
+    fn as_raw(&self) -> *mut bindings::kmem_cache {
+        self.inner.get()
+    }
+
+    /// Creates a reference to a [`KMemCache`] from a raw pointer.
+    ///
+    /// This is useful for wrapping a C-initialized static `kmem_cache`, such as
+    /// the global `radix_tree_node_cachep` used by XArrays.
+    ///
+    /// # Safety
+    ///
+    /// - `ptr` must be a valid pointer to a `kmem_cache` that was created for
+    ///   objects of type `T`.
+    /// - The cache must remain valid for the lifetime `'a`.
+    /// - The caller must ensure that the cache was configured appropriately for
+    ///   the type `T`, including proper size and alignment.
+    pub unsafe fn from_raw<'a>(ptr: *mut bindings::kmem_cache) -> &'a Self {
+        // SAFETY: The caller guarantees that `ptr` is a valid pointer to a
+        // `kmem_cache` created for objects of type `T`, that it remains valid
+        // for lifetime `'a`, and that the cache is properly configured for `T`.
+        unsafe { &*ptr.cast::<Self>() }
+    }
+}
+
+/// A slab cache with sheaf support.
+///
+/// This type wraps a kernel `kmem_cache` configured with a sheaf capacity,
+/// enabling pre-allocation of objects via [`Sheaf`].
+///
+/// For now, this type only exists for sheaf management.
+///
+/// # Type parameter
+///
+/// - `T`: The type of objects managed by this cache. Must implement
+///   [`KMemCacheInit`] to provide initialization logic for new allocations.
+///
+/// # Context
+///
+/// Dropping the last reference to a `KMemCacheHandle` destroys the cache via
+/// `kmem_cache_destroy`, which may sleep. [`SBox`] instances allocated from
+/// the handle each hold a reference, so the last reference may be dropped
+/// when an [`SBox`] is dropped. The last reference must not be dropped from a
+/// context where sleeping is not allowed.
+///
+/// A [`Sheaf`] created from the handle also holds a reference, but dropping
+/// a [`Sheaf`] never drops the last one. See the `# Lifecycle` section of
+/// [`Sheaf`].
+///
+/// # Invariants
+///
+/// - `cache` is a valid pointer to a `kmem_cache` created with
+///   `__kmem_cache_create_args`.
+/// - The cache is valid for the lifetime of this struct.
+#[repr(transparent)]
+pub struct KMemCacheHandle<T: KMemCacheInit<T>> {
+    cache: NonNull<KMemCache<T>>,
+}
+
+// SAFETY: `KMemCacheHandle<T>` owns a `kmem_cache`, which is internally
+// synchronized and has no thread affinity. The cache may be destroyed from a
+// thread other than the one that created it.
+unsafe impl<T: KMemCacheInit<T> + Send> Send for KMemCacheHandle<T> {}
+
+// SAFETY: All operations available through `&KMemCacheHandle<T>` are
+// internally synchronized by the C side, so the cache may be used from
+// multiple threads concurrently if the objects it manages can be sent between
+// threads.
+unsafe impl<T: KMemCacheInit<T> + Send> Sync for KMemCacheHandle<T> {}
+
+impl<T: KMemCacheInit<T>> KMemCacheHandle<T> {
+    /// Creates a new slab cache with sheaf support.
+    ///
+    /// Creates a kernel slab cache for objects of type `T` with at least the
+    /// specified sheaf capacity. The cache uses the provided `name` for
+    /// identification in `/sys/kernel/slab/` and debugging output.
+    ///
+    /// # Arguments
+    ///
+    /// - `name`: A string identifying the cache. This name appears in sysfs and
+    ///   debugging output.
+    /// - `sheaf_capacity`: The minimum number of objects a regular sheaf from
+    ///   this cache can hold. The allocator calculates a capacity based on the
+    ///   object size and uses the larger of the two, so a value of zero
+    ///   selects the calculated capacity. Set this to the largest `size` that
+    ///   is expected to be passed to [`sheaf`](Self::sheaf) to avoid oversize
+    ///   sheaves. The value is ignored when `CONFIG_SLUB_TINY` is enabled or
+    ///   when slab debugging (`slab_debug`) is enabled for the cache.
+    ///
+    /// # Errors
+    ///
+    /// Returns an error if:
+    ///
+    /// - The cache could not be created due to memory pressure.
+    /// - The size of `T` cannot be represented as a `c_uint`.
+    pub fn new(name: &CStr, sheaf_capacity: u32) -> Result<Arc<Self>>
+    where
+        T: KMemCacheInit<T>,
+    {
+        let flags = 0;
+        let mut args: bindings::kmem_cache_args = pin_init::zeroed();
+        args.sheaf_capacity = sheaf_capacity;
+
+        // With an alignment of zero, the slab allocator only guarantees
+        // `ARCH_SLAB_MINALIGN`, which may be smaller than the alignment of `T`.
+        args.align = core::mem::align_of::<T>().try_into()?;
+
+        // NOTE: We are not initializing at object allocation time, because
+        // there is no matching teardown function on the C side machinery.
+        args.ctor = None;
+
+        // SAFETY: `name` is a valid C string, `args` is properly initialized,
+        // and the size of `T` has been validated to fit in a `c_uint`.
+        let ptr = unsafe {
+            bindings::__kmem_cache_create_args(
+                name.as_char_ptr(),
+                core::mem::size_of::<T>().try_into()?,
+                &mut args,
+                flags,
+            )
+        };
+
+        // INVARIANT: `ptr` was returned by `__kmem_cache_create_args` and is
+        // non-null (checked below). The cache is valid until
+        // `kmem_cache_destroy` is called in `Drop`.
+        Ok(Arc::new(
+            Self {
+                cache: NonNull::new(ptr.cast()).ok_or(ENOMEM)?,
+            },
+            GFP_KERNEL,
+        )?)
+    }
+
+    /// Creates a pre-filled sheaf from this cache.
+    ///
+    /// Allocates a sheaf and pre-fills it with `size` objects. Once created,
+    /// allocations from the sheaf via [`Sheaf::alloc`] are guaranteed to
+    /// succeed until the sheaf is depleted.
+    ///
+    /// # Arguments
+    ///
+    /// - `size`: The number of objects to pre-allocate. Must not be zero. If
+    ///   `size` exceeds the sheaf capacity of the cache, an "oversize" sheaf
+    ///   is allocated. Oversize sheaves are slower to create, and they are
+    ///   flushed and freed rather than cached for reuse when returned.
+    /// - `gfp`: Allocation flags controlling how memory is obtained. Use
+    ///   [`GFP_KERNEL`] for normal allocations that may sleep, or
+    ///   [`GFP_NOWAIT`] for non-blocking allocations.
+    ///
+    /// # Errors
+    ///
+    /// Returns [`ENOMEM`] if the sheaf or its objects could not be allocated,
+    /// or if `size` is zero.
+    #[inline]
+    pub fn sheaf<'a>(
+        self: ArcBorrow<'a, Self>,
+        size: usize,
+        gfp: kernel::alloc::Flags,
+    ) -> Result<Sheaf<'a, T, Dynamic>> {
+        // SAFETY: `self.as_raw()` returns a valid cache pointer, and `size`
+        // has been validated to fit in a `c_uint`.
+        let ptr = unsafe {
+            bindings::kmem_cache_prefill_sheaf(self.as_raw(), gfp.as_raw(), size.try_into()?)
+        };
+
+        // INVARIANT: `ptr` was returned by `kmem_cache_prefill_sheaf` and is
+        // non-null (checked below). `cache` is the cache from which this sheaf
+        // was created. `dropped` is false since the sheaf has not been returned.
+        Ok(Sheaf {
+            sheaf: NonNull::new(ptr).ok_or(ENOMEM)?,
+            cache: CacheRef::Arc(self.into()),
+            dropped: false,
+            _p: PhantomData,
+        })
+    }
+
+    #[inline]
+    fn as_raw(&self) -> *mut bindings::kmem_cache {
+        self.cache.as_ptr().cast()
+    }
+}
+
+impl<T: KMemCacheInit<T>> Drop for KMemCacheHandle<T> {
+    fn drop(&mut self) {
+        // SAFETY: `self.as_raw()` returns a valid cache pointer that was
+        // created by `__kmem_cache_create_args`. As all objects allocated from
+        // this hold a reference on `self`, they must have been dropped for this
+        // `drop` method to execute.
+        unsafe { bindings::kmem_cache_destroy(self.as_raw()) };
+    }
+}
+
+/// Trait for types that can be initialized in a slab cache.
+///
+/// This trait provides the initialization logic for objects allocated from a
+/// [`KMemCache`]. The initializer is called when objects are allocated from a
+/// sheaf via [`Sheaf::alloc`].
+///
+/// # Implementation
+///
+/// Implementors must provide [`init`](KMemCacheInit::init), which returns an
+/// infallible initializer for the type.
+///
+/// # Example
+///
+/// ```
+/// use kernel::mm::sheaf::KMemCacheInit;
+/// use kernel::prelude::*;
+///
+/// struct MyData {
+///     counter: u32,
+///     name: [u8; 16],
+/// }
+///
+/// impl KMemCacheInit<MyData> for MyData {
+///     fn init() -> impl Init<MyData> {
+///         init!(MyData {
+///             counter: 0,
+///             name: [0; 16],
+///         })
+///     }
+/// }
+/// ```
+pub trait KMemCacheInit<T> {
+    /// Returns an initializer for creating new objects of type `T`.
+    ///
+    /// The initializer is applied to newly allocated objects when they are allocated from a sheaf
+    /// via [`Sheaf::alloc`]. The initializer should set all fields to their default or initial
+    /// values.
+    fn init() -> impl Init<T, Infallible>;
+}
+
+/// Marker type for sheaves from static caches.
+///
+/// Used as a type parameter for [`Sheaf`] to indicate the sheaf was created
+/// from a `&'static KMemCache<T>`.
+pub enum Static {}
+
+/// Marker type for sheaves from dynamic caches.
+///
+/// Used as a type parameter for [`Sheaf`] to indicate the sheaf was created
+/// from a [`KMemCacheHandle`] via [`ArcBorrow`].
+pub enum Dynamic {}
+
+/// A sheaf from a static cache.
+///
+/// This is a [`Sheaf`] backed by a `&'static KMemCache<T>`.
+pub type StaticSheaf<'a, T> = Sheaf<'a, T, Static>;
+
+/// A sheaf from a dynamic cache.
+///
+/// This is a [`Sheaf`] backed by a reference-counted [`KMemCacheHandle`].
+pub type DynamicSheaf<'a, T> = Sheaf<'a, T, Dynamic>;
+
+/// A pre-filled container of slab objects.
+///
+/// A sheaf holds a set of pre-allocated objects from a [`KMemCache`].
+/// Allocations from a sheaf are guaranteed to succeed until the sheaf is
+/// depleted, making sheaves useful in contexts where allocation failure is
+/// not acceptable.
+///
+/// Sheaves provide faster allocation than direct allocation because they use
+/// local locks with preemption disabled rather than atomic operations. Note
+/// that each [`SBox`] allocated from a [`DynamicSheaf`] holds a reference to
+/// the [`KMemCacheHandle`] the sheaf was created from, to keep the cache
+/// alive until the object is freed. [`Sheaf::alloc`] thus increments the
+/// reference count of the handle, and dropping the [`SBox`] decrements it.
+/// Both are atomic operations on a counter that is shared by all users of the
+/// cache.
+///
+/// This does not apply to a [`StaticSheaf`]. A static cache is never
+/// destroyed, so objects allocated from it do not hold a reference and no
+/// reference counting takes place.
+///
+/// # Type parameters
+///
+/// - `'a`: The lifetime of the cache reference the sheaf was created from.
+///   The cache is guaranteed to outlive `'a`.
+/// - `T`: The type of objects in this sheaf.
+/// - `A`: Either [`Static`] or [`Dynamic`], indicating whether the backing
+///   cache is a static reference or a reference-counted handle.
+///
+/// For convenience, [`StaticSheaf`] and [`DynamicSheaf`] type aliases are
+/// provided.
+///
+/// # Lifecycle
+///
+/// Sheaves are created via [`KMemCache::sheaf`] or [`KMemCacheHandle::sheaf`]
+/// and should be returned to the allocator when no longer needed via
+/// [`Sheaf::return_refill`]. If a sheaf is simply dropped, it is returned with
+/// `GFP_NOWAIT` flags, which may result in the sheaf being flushed and freed
+/// rather than being cached for reuse.
+///
+/// A sheaf created from a [`KMemCacheHandle`] holds a reference to the
+/// handle. Dropping the sheaf never drops the last reference to the handle,
+/// and thus never destroys the cache: [`KMemCacheHandle::sheaf`] ties the
+/// lifetime `'a` of the sheaf to the [`ArcBorrow`] it is called on, so the
+/// reference the [`ArcBorrow`] was created from outlives the sheaf. A sheaf
+/// can therefore be dropped in a context where sleeping is not allowed. Note
+/// that this does not extend to [`SBox`] instances allocated from the sheaf.
+///
+/// # Invariants
+///
+/// - `sheaf` is a valid pointer to a `slab_sheaf` obtained from
+///   `kmem_cache_prefill_sheaf`.
+/// - `cache` is the cache from which this sheaf was created.
+/// - `dropped` tracks whether the sheaf has been explicitly returned.
+pub struct Sheaf<'a, T: KMemCacheInit<T>, A> {
+    sheaf: NonNull<bindings::slab_sheaf>,
+    cache: CacheRef<T>,
+    dropped: bool,
+    _p: PhantomData<(&'a KMemCache<T>, A)>,
+}
+
+// SAFETY: A prefilled sheaf is exclusively owned by the caller and has no
+// affinity to the CPU or thread that created it: `kmem_cache_alloc_from_sheaf`
+// does not touch percpu state, and `kmem_cache_return_sheaf` reattaches the
+// sheaf to the CPU that is current at return time. Thus the sheaf may be sent
+// to another thread if the objects it manages can.
+unsafe impl<T: KMemCacheInit<T> + Send, A> Send for Sheaf<'_, T, A> {}
+
+// NOTE: `Sheaf` is deliberately not `Sync`. The C side mutates sheaf state
+// without synchronization, relying on the caller's exclusive ownership. The
+// mutable receivers of the methods on `Sheaf` enforce this exclusivity.
+
+impl<'a, T: KMemCacheInit<T>, A> Sheaf<'a, T, A> {
+    #[inline]
+    fn as_raw(&self) -> *mut bindings::slab_sheaf {
+        self.sheaf.as_ptr()
+    }
+
+    /// Return the sheaf and try to refill using `flags`.
+    ///
+    /// If the sheaf cannot simply become the percpu spare sheaf, but there's
+    /// space for a full sheaf in the barn, we try to refill the sheaf back to
+    /// the cache's sheaf_capacity to avoid handling partially full sheaves.
+    ///
+    /// If the refill fails because gfp is e.g. GFP_NOWAIT, or the barn is full,
+    /// the sheaf is instead flushed and freed.
+    #[inline]
+    pub fn return_refill(mut self, flags: kernel::alloc::Flags) {
+        self.dropped = true;
+        // SAFETY: `self.cache.as_raw()` and `self.as_raw()` return valid
+        // pointers to the cache and sheaf respectively.
+        unsafe {
+            bindings::kmem_cache_return_sheaf(self.cache.as_raw(), flags.as_raw(), self.as_raw())
+        };
+        drop(self);
+    }
+
+    /// Refills the sheaf to at least the specified size.
+    ///
+    /// Replenishes the sheaf by preallocating objects until it contains at
+    /// least `size` objects. If the sheaf already contains `size` or more
+    /// objects, this is a no-op. In practice, the sheaf is refilled to its
+    /// full capacity.
+    ///
+    /// # Arguments
+    ///
+    /// - `flags`: Allocation flags controlling how memory is obtained.
+    /// - `size`: The minimum number of objects the sheaf should contain after
+    ///   refilling. If `size` exceeds the cache's `sheaf_capacity`, the sheaf
+    ///   may be replaced with a larger one.
+    ///
+    /// # Errors
+    ///
+    /// Returns an error if the objects could not be allocated. If refilling
+    /// fails, the existing sheaf is left intact.
+    pub fn refill(&mut self, flags: kernel::alloc::Flags, size: usize) -> Result {
+        // SAFETY: `self.cache.as_raw()` returns a valid cache pointer and
+        // `&raw mut self.sheaf` points to a valid sheaf per the type invariants.
+        kernel::error::to_result(unsafe {
+            bindings::kmem_cache_refill_sheaf(
+                self.cache.as_raw(),
+                flags.as_raw(),
+                (&raw mut (self.sheaf)).cast(),
+                size.try_into()?,
+            )
+        })
+    }
+
+    /// Allocates an object from the sheaf.
+    ///
+    /// Returns a new [`SBox`] containing an initialized object, or [`None`]
+    /// if the sheaf is depleted. Allocations are guaranteed to succeed as
+    /// long as the sheaf contains pre-allocated objects.
+    ///
+    /// The `gfp` flags passed to `kmem_cache_alloc_from_sheaf` are set to zero,
+    /// meaning no additional flags like `__GFP_ZERO` or `__GFP_ACCOUNT` are
+    /// applied.
+    ///
+    /// The returned `T` is initialized as part of this function.
+    pub fn alloc(&mut self) -> Option<SBox<T>> {
+        // SAFETY: `self.cache.as_raw()` and `self.as_raw()` return valid
+        // pointers. The function returns NULL when the sheaf is empty.
+        let ptr = unsafe {
+            bindings::kmem_cache_alloc_from_sheaf_noprof(self.cache.as_raw(), 0, self.as_raw())
+        };
+
+        let ptr = NonNull::new(ptr.cast::<T>())?;
+
+        // SAFETY:
+        // - `ptr` is a valid, non-null pointer as it was just returned by the
+        //   cache.
+        // - The initializer is infallible, so an error is never returned.
+        unsafe { T::init().__init(ptr.as_ptr()) }.expect("Initializer is infallible");
+
+        // INVARIANT: `ptr` was returned by `kmem_cache_alloc_from_sheaf_noprof`
+        // and initialized above. `cache` is the cache from which this object
+        // was allocated. The object remains valid until freed in `Drop`.
+        Some(SBox {
+            ptr,
+            cache: self.cache.clone(),
+        })
+    }
+}
+
+impl<'a, T: KMemCacheInit<T>, A> Drop for Sheaf<'a, T, A> {
+    fn drop(&mut self) {
+        if !self.dropped {
+            // SAFETY: `self.cache.as_raw()` and `self.as_raw()` return valid
+            // pointers. Using `GFP_NOWAIT` because the drop may occur in a
+            // context where sleeping is not permitted.
+            unsafe {
+                bindings::kmem_cache_return_sheaf(
+                    self.cache.as_raw(),
+                    GFP_NOWAIT.as_raw(),
+                    self.as_raw(),
+                )
+            };
+        }
+    }
+}
+
+/// Internal reference to a cache, either static or reference-counted.
+///
+/// # Invariants
+///
+/// - For `CacheRef::Static`: the `NonNull` points to a valid `KMemCache<T>`
+///   with `'static` lifetime, derived from a `&'static KMemCache<T>` reference.
+enum CacheRef<T: KMemCacheInit<T>> {
+    /// A reference-counted handle to a dynamically created cache.
+    Arc(Arc<KMemCacheHandle<T>>),
+    /// A pointer to a static lifetime cache.
+    Static(NonNull<KMemCache<T>>),
+}
+
+impl<T: KMemCacheInit<T>> Clone for CacheRef<T> {
+    fn clone(&self) -> Self {
+        match self {
+            Self::Arc(arg0) => Self::Arc(arg0.clone()),
+            Self::Static(arg0) => Self::Static(*arg0),
+        }
+    }
+}
+
+impl<T: KMemCacheInit<T>> CacheRef<T> {
+    #[inline]
+    fn as_raw(&self) -> *mut bindings::kmem_cache {
+        match self {
+            CacheRef::Arc(handle) => handle.as_raw(),
+            // SAFETY: By type invariant, `ptr` points to a valid `KMemCache<T>`
+            // with `'static` lifetime.
+            CacheRef::Static(ptr) => unsafe { ptr.as_ref() }.as_raw(),
+        }
+    }
+}
+
+/// An owned allocation from a cache sheaf.
+///
+/// `SBox` is similar to `Box` but is backed by a slab cache allocation obtained
+/// through a [`Sheaf`]. It provides owned access to an initialized object and
+/// ensures the object is properly freed back to the cache when dropped.
+///
+/// The contained `T` is initialized when the `SBox` is returned from alloc and
+/// dropped when the `SBox` is dropped.
+///
+/// An `SBox` allocated from a [`KMemCacheHandle`] backed sheaf holds a
+/// reference to the handle. Dropping the `SBox` may thus drop the last
+/// reference to the handle and destroy the cache, which may sleep. See the
+/// `# Context` section of [`KMemCacheHandle`].
+///
+/// # Invariants
+///
+/// - `ptr` points to a valid, initialized object of type `T`.
+/// - `cache` is the cache from which this object was allocated.
+/// - The object remains valid for the lifetime of the `SBox`.
+pub struct SBox<T: KMemCacheInit<T>> {
+    ptr: NonNull<T>,
+    cache: CacheRef<T>,
+}
+
+// SAFETY: `SBox<T>` owns a `T`. Sheaf allocated objects are ordinary slab
+// objects that may be freed from any thread, so an `SBox<T>` may be sent to
+// another thread if `T` can.
+unsafe impl<T: KMemCacheInit<T> + Send> Send for SBox<T> {}
+
+// SAFETY: `SBox<T>` has no interior mutability, so sharing `&SBox<T>` between
+// threads only shares `&T`.
+unsafe impl<T: KMemCacheInit<T> + Sync> Sync for SBox<T> {}
+
+impl<T: KMemCacheInit<T>> SBox<T> {
+    /// Consumes the `SBox` and returns the raw pointer to the contained value.
+    ///
+    /// The caller becomes responsible for freeing the memory. The object is not
+    /// dropped and remains initialized. Use [`static_from_ptr`] to reconstruct
+    /// an `SBox` from the pointer.
+    ///
+    /// This method is only intended for objects allocated from a static cache.
+    /// Calling it on an `SBox` backed by a [`KMemCacheHandle`] leaks a
+    /// reference on the handle, preventing the cache from ever being
+    /// destroyed, as [`static_from_ptr`] cannot restore the reference.
+    ///
+    /// [`static_from_ptr`]: SBox::static_from_ptr
+    pub fn into_ptr(self) -> *mut T {
+        debug_assert!(matches!(self.cache, CacheRef::Static(_)));
+        let ptr = self.ptr.as_ptr();
+        core::mem::forget(self);
+        ptr
+    }
+
+    /// Reconstructs an `SBox` from a raw pointer and cache.
+    ///
+    /// This is intended for use with objects that were previously converted to
+    /// raw pointers via [`into_ptr`], typically for passing through C code.
+    ///
+    /// [`into_ptr`]: SBox::into_ptr
+    ///
+    /// # Safety
+    ///
+    /// - `cache` must be a valid pointer to the `kmem_cache` from which `value`
+    ///   was allocated.
+    /// - `cache` must be a statically allocated cache that is never destroyed.
+    /// - `value` must be a valid pointer to an initialized `T` that was
+    ///   allocated from `cache`.
+    /// - The caller must ensure that no other `SBox` or reference exists for
+    ///   `value`.
+    pub unsafe fn static_from_ptr(cache: *mut bindings::kmem_cache, value: *mut T) -> Self {
+        // INVARIANT: The caller guarantees `value` points to a valid,
+        // initialized `T` allocated from `cache`.
+        Self {
+            // SAFETY: By function safety requirements, `value` is not null.
+            ptr: unsafe { NonNull::new_unchecked(value) },
+            cache: CacheRef::Static(
+                // SAFETY: By function safety requirements, `cache` is not null.
+                unsafe { NonNull::new_unchecked(cache.cast()) },
+            ),
+        }
+    }
+}
+
+impl<T: KMemCacheInit<T>> Deref for SBox<T> {
+    type Target = T;
+
+    #[inline]
+    fn deref(&self) -> &Self::Target {
+        // SAFETY: `ptr` is valid and properly aligned per the type invariants.
+        unsafe { self.ptr.as_ref() }
+    }
+}
+
+impl<T: KMemCacheInit<T>> DerefMut for SBox<T> {
+    #[inline]
+    fn deref_mut(&mut self) -> &mut Self::Target {
+        // SAFETY: `ptr` is valid and properly aligned per the type invariants,
+        // and we have exclusive access via `&mut self`.
+        unsafe { self.ptr.as_mut() }
+    }
+}
+
+impl<T: KMemCacheInit<T>> Drop for SBox<T> {
+    fn drop(&mut self) {
+        // SAFETY: By type invariant, `ptr` points to a valid and initialized
+        // object. We do not touch `ptr` after returning it to the cache.
+        unsafe { core::ptr::drop_in_place(self.ptr.as_ptr()) };
+
+        // SAFETY: `self.ptr` was allocated from `self.cache` via
+        // `kmem_cache_alloc_from_sheaf_noprof` and is valid.
+        unsafe {
+            bindings::kmem_cache_free(self.cache.as_raw(), self.ptr.as_ptr().cast());
+        }
+    }
+}
diff --git a/rust/kernel/xarray.rs b/rust/kernel/xarray.rs
index 987c9c0c219891..20792b09c12662 100644
--- a/rust/kernel/xarray.rs
+++ b/rust/kernel/xarray.rs
@@ -4,20 +4,101 @@
 //!
 //! C header: [`include/linux/xarray.h`](srctree/include/linux/xarray.h)
 
-use crate::{
+use core::{
+    convert::Infallible,
+    iter,
+    marker::PhantomData,
+    pin::Pin,
+    ptr::{
+        null_mut,
+        NonNull, //
+    },
+};
+pub use entry::{
+    Entry,
+    OccupiedEntry,
+    VacantEntry, //
+};
+use kernel::{
     alloc,
     bindings,
     build_assert::build_assert,
-    error::{Error, Result},
+    error::{
+        code::*,
+        to_result,
+        Error,
+        Result, //
+    },
     ffi::c_void,
+    fmt,
+    mm::sheaf::{
+        KMemCache,
+        SBox,
+        StaticSheaf, //
+    },
     types::{
         ForeignOwnable,
         NotThreadSafe,
         Opaque, //
     }, //
 };
-use core::{iter, marker::PhantomData, pin::Pin, ptr::NonNull};
-use pin_init::{pin_data, pin_init, pinned_drop, PinInit};
+use pin_init::{
+    init,
+    pin_data,
+    pin_init,
+    pinned_drop,
+    Init,
+    PinInit, //
+};
+
+/// Sheaf of preallocated [`XArray`] nodes.
+pub type XArraySheaf<'a> = StaticSheaf<'a, XArrayNode>;
+
+/// Returns a reference to the global XArray node cache.
+///
+/// This provides access to the kernel's `radix_tree_node_cachep`, which is the
+/// slab cache used for allocating internal XArray nodes. This cache can be used
+/// to create sheaves for preallocating XArray nodes.
+pub fn xarray_kmem_cache() -> &'static KMemCache<XArrayNode> {
+    // SAFETY: `radix_tree_node_cachep` is a valid, statically initialized
+    // kmem_cache that remains valid for the lifetime of the kernel. The cache
+    // is configured for `xa_node` objects which match our `XArrayNode` type.
+    unsafe { KMemCache::from_raw(bindings::radix_tree_node_cachep) }
+}
+
+/// An preallocated XArray node.
+///
+/// This represents a single preallocated internal node for an XArray.
+///
+/// This type is `#[repr(transparent)]` as it is cast to and from pointers to
+/// the inner [`bindings::xa_node`].
+#[repr(transparent)]
+pub struct XArrayNode {
+    node: Opaque<bindings::xa_node>,
+}
+
+// SAFETY: A preallocated `xa_node` is opaque storage for the C XArray
+// implementation, which moves nodes between CPUs freely. It is not tied to
+// the thread that allocated it.
+unsafe impl Send for XArrayNode {}
+
+impl kernel::mm::sheaf::KMemCacheInit<XArrayNode> for XArrayNode {
+    fn init() -> impl Init<Self, Infallible> {
+        init!(Self {
+            // SAFETY:
+            // - This initialization cannot fail and will never return `Err`.
+            // - The xa_node does not move during initialization.
+            node <- unsafe {
+                pin_init::init_from_closure(
+                    |place: *mut Opaque<bindings::xa_node>| -> Result<(), Infallible> {
+                        bindings::radix_tree_node_ctor(place.cast::<c_void>());
+                        Ok(())
+                    },
+                )
+            }
+        })
+    }
+}
 
 /// An array which efficiently maps sparse integer indices to owned objects.
 ///
@@ -50,7 +131,10 @@
 /// *guard.get_mut(0).unwrap() = 0xffff;
 /// assert_eq!(guard.get(0).copied(), Some(0xffff));
 ///
-/// assert_eq!(guard.store(0, beef, GFP_KERNEL)?.as_deref().copied(), Some(0xffff));
+/// assert_eq!(
+///     guard.store(0, beef, GFP_KERNEL)?.as_deref().copied(),
+///     Some(0xffff)
+/// );
 /// assert_eq!(guard.get(0).copied(), Some(0xbeef));
 ///
 /// guard.remove(0);
@@ -112,15 +196,22 @@ fn iter(&self) -> impl Iterator<Item = NonNull<c_void>> + '_ {
         let mut index = 0;
 
         // SAFETY: `self.xa` is always valid by the type invariant.
-        iter::once(unsafe {
-            bindings::xa_find(self.xa.get(), &mut index, usize::MAX, bindings::XA_PRESENT)
-        })
-        .chain(iter::from_fn(move || {
-            // SAFETY: `self.xa` is always valid by the type invariant.
-            Some(unsafe {
-                bindings::xa_find_after(self.xa.get(), &mut index, usize::MAX, bindings::XA_PRESENT)
-            })
-        }))
+        Iterator::chain(
+            iter::once(unsafe {
+                bindings::xa_find(self.xa.get(), &mut index, usize::MAX, bindings::XA_PRESENT)
+            }),
+            iter::from_fn(move || {
+                // SAFETY: `self.xa` is always valid by the type invariant.
+                Some(unsafe {
+                    bindings::xa_find_after(
+                        self.xa.get(),
+                        &mut index,
+                        usize::MAX,
+                        bindings::XA_PRESENT,
+                    )
+                })
+            }),
+        )
         .map_while(|ptr| NonNull::new(ptr.cast()))
     }
 
@@ -141,7 +232,6 @@ pub fn try_lock(&self) -> Option<Guard<'_, T>> {
     pub fn lock(&self) -> Guard<'_, T> {
         // SAFETY: `self.xa` is always valid by the type invariant.
         unsafe { bindings::xa_lock(self.xa.get()) };
-
         Guard {
             xa: self,
             _not_send: NotThreadSafe,
@@ -152,6 +242,21 @@ pub fn lock(&self) -> Guard<'_, T> {
 /// A lock guard.
 ///
 /// The lock is unlocked when the guard goes out of scope.
+///
+/// # Temporary lock drops
+///
+/// Unlike a typical Rust lock guard, holding a `Guard` does not guarantee
+/// continuous mutual exclusion for its entire lifetime: [`store`] may drop and
+/// reacquire the lock to allocate memory when called with blocking allocation
+/// flags. Other threads may lock and modify the array in that window, so a
+/// sequence of operations on the guard that spans such a call is not atomic.
+///
+/// To modify the array without dropping the lock, use the entry API with
+/// preallocated memory, see [`entry`] and [`insert_entry`].
+///
+/// [`store`]: Guard::store
+/// [`entry`]: Guard::entry
+/// [`insert_entry`]: Guard::insert_entry
 #[must_use = "the lock unlocks immediately when the guard is unused"]
 pub struct Guard<'a, T: ForeignOwnable> {
     xa: &'a XArray<T>,
@@ -177,6 +282,15 @@ pub struct StoreError<T> {
     pub value: T,
 }
 
+impl<T> fmt::Debug for StoreError<T> {
+    #[inline]
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        f.debug_struct("StoreError")
+            .field("error", &self.error)
+            .finish()
+    }
+}
+
 impl<T> From<StoreError<T>> for Error {
     #[inline]
     fn from(value: StoreError<T>) -> Self {
@@ -185,30 +299,194 @@ fn from(value: StoreError<T>) -> Self {
 }
 
 impl<'a, T: ForeignOwnable> Guard<'a, T> {
-    fn load<F, U>(&self, index: usize, f: F) -> Option<U>
-    where
-        F: FnOnce(NonNull<c_void>) -> U,
-    {
-        // SAFETY: `self.xa.xa` is always valid by the type invariant.
-        let ptr = unsafe { bindings::xa_load(self.xa.xa.get(), index) };
-        let ptr = NonNull::new(ptr.cast())?;
-        Some(f(ptr))
+    #[inline]
+    fn load(&self, index: usize) -> Option<NonNull<c_void>> {
+        XArrayState::new(self, index).load()
     }
 
     /// Provides a reference to the element at the given index.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray}};
+    /// let xa = KBox::pin_init(XArray::<KBox<u32>>::new(AllocKind::Alloc1), GFP_KERNEL)?;
+    /// let mut guard = xa.lock();
+    ///
+    /// // Expanding an empty `Alloc1` array stores an internal zero entry at
+    /// // index 0. It must not be visible through the API.
+    /// guard.store(5, KBox::new(0xcafeu32, GFP_ATOMIC)?, GFP_ATOMIC)?;
+    /// assert_eq!(guard.get(0), None);
+    /// assert_eq!(guard.find_next(0).map(|(i, v)| (i, *v)), Some((5, 0xcafe)));
+    ///
+    /// # Ok::<(), kernel::error::Error>(())
+    /// ```
+    #[inline]
     pub fn get(&self, index: usize) -> Option<T::Borrowed<'_>> {
-        self.load(index, |ptr| {
-            // SAFETY: `ptr` came from `T::into_foreign`.
-            unsafe { T::borrow(ptr.as_ptr()) }
-        })
+        let ptr = self.load(index)?;
+        // SAFETY: `ptr` came from `T::into_foreign`.
+        Some(unsafe { T::borrow(ptr.as_ptr()) })
     }
 
     /// Provides a mutable reference to the element at the given index.
+    #[inline]
     pub fn get_mut(&mut self, index: usize) -> Option<T::BorrowedMut<'_>> {
-        self.load(index, |ptr| {
+        let ptr = self.load(index)?;
+        // SAFETY: `ptr` came from `T::into_foreign`.
+        Some(unsafe { T::borrow_mut(ptr.as_ptr()) })
+    }
+
+    /// Gets an entry for the specified index, which can be vacant or occupied.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray, Entry}};
+    /// let mut xa = KBox::pin_init(XArray::<KBox<u32>>::new(AllocKind::Alloc), GFP_KERNEL)?;
+    /// let mut guard = xa.lock();
+    ///
+    /// assert!(guard.get(42).is_none());
+    ///
+    /// match guard.entry(42) {
+    ///     Entry::Vacant(entry) => {
+    ///         entry.insert(KBox::new(0x1337u32, GFP_ATOMIC)?, None)?;
+    ///     }
+    ///     Entry::Occupied(_) => unreachable!("We did not insert an entry yet"),
+    /// }
+    ///
+    /// assert_eq!(guard.get(42), Some(&0x1337));
+    ///
+    /// # Ok::<(), kernel::error::Error>(())
+    /// ```
+    pub fn entry<'b>(&'b mut self, index: usize) -> Entry<'a, 'b, T> {
+        match self.load(index) {
+            None => Entry::Vacant(VacantEntry::new(self, index)),
+            Some(ptr) => Entry::Occupied(OccupiedEntry::new(self, index, ptr)),
+        }
+    }
+
+    #[inline]
+    fn load_next(&self, index: usize) -> Option<(usize, NonNull<c_void>)> {
+        XArrayState::new(self, index).load_next(usize::MAX)
+    }
+
+    /// Finds the next element starting from the given index.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray}};
+    /// let mut xa = KBox::pin_init(XArray::<KBox<u32>>::new(AllocKind::Alloc), GFP_KERNEL)?;
+    /// let mut guard = xa.lock();
+    ///
+    /// guard.store(10, KBox::new(10u32, GFP_ATOMIC)?, GFP_ATOMIC)?;
+    /// guard.store(20, KBox::new(20u32, GFP_ATOMIC)?, GFP_ATOMIC)?;
+    ///
+    /// if let Some((found_index, value)) = guard.find_next(11) {
+    ///     assert_eq!(found_index, 20);
+    ///     assert_eq!(*value, 20);
+    /// }
+    ///
+    /// if let Some((found_index, value)) = guard.find_next(5) {
+    ///     assert_eq!(found_index, 10);
+    ///     assert_eq!(*value, 10);
+    /// }
+    ///
+    /// # Ok::<(), kernel::error::Error>(())
+    /// ```
+    #[inline]
+    pub fn find_next(&self, index: usize) -> Option<(usize, T::Borrowed<'_>)> {
+        self.load_next(index)
             // SAFETY: `ptr` came from `T::into_foreign`.
-            unsafe { T::borrow_mut(ptr.as_ptr()) }
-        })
+            .map(|(index, ptr)| (index, unsafe { T::borrow(ptr.as_ptr()) }))
+    }
+
+    /// Finds the next element starting from the given index, returning a mutable reference.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray}};
+    /// let mut xa = KBox::pin_init(XArray::<KBox<u32>>::new(AllocKind::Alloc), GFP_KERNEL)?;
+    /// let mut guard = xa.lock();
+    ///
+    /// guard.store(10, KBox::new(10u32, GFP_ATOMIC)?, GFP_ATOMIC)?;
+    /// guard.store(20, KBox::new(20u32, GFP_ATOMIC)?, GFP_ATOMIC)?;
+    ///
+    /// if let Some((found_index, mut_value)) = guard.find_next_mut(5) {
+    ///     assert_eq!(found_index, 10);
+    ///     *mut_value = 0x99;
+    /// }
+    ///
+    /// assert_eq!(guard.get(10).copied(), Some(0x99));
+    ///
+    /// # Ok::<(), kernel::error::Error>(())
+    /// ```
+    #[inline]
+    pub fn find_next_mut(&mut self, index: usize) -> Option<(usize, T::BorrowedMut<'_>)> {
+        self.load_next(index)
+            // SAFETY: `ptr` came from `T::into_foreign`.
+            .map(move |(index, ptr)| (index, unsafe { T::borrow_mut(ptr.as_ptr()) }))
+    }
+
+    /// Finds the next occupied entry starting from the given index.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray}};
+    /// let mut xa = KBox::pin_init(XArray::<KBox<u32>>::new(AllocKind::Alloc), GFP_KERNEL)?;
+    /// let mut guard = xa.lock();
+    ///
+    /// guard.store(10, KBox::new(10u32, GFP_ATOMIC)?, GFP_ATOMIC)?;
+    /// guard.store(20, KBox::new(20u32, GFP_ATOMIC)?, GFP_ATOMIC)?;
+    ///
+    /// if let Some(entry) = guard.find_next_entry(5) {
+    ///     assert_eq!(entry.index(), 10);
+    ///     let value = entry.remove();
+    ///     assert_eq!(*value, 10);
+    /// }
+    ///
+    /// assert_eq!(guard.get(10), None);
+    ///
+    /// # Ok::<(), kernel::error::Error>(())
+    /// ```
+    pub fn find_next_entry<'b>(&'b mut self, index: usize) -> Option<OccupiedEntry<'a, 'b, T>> {
+        let mut state = XArrayState::new(self, index);
+        let (_, ptr) = state.load_next(usize::MAX)?;
+        Some(OccupiedEntry { state, ptr })
+    }
+
+    /// Finds the next occupied entry starting at the given index, wrapping around.
+    ///
+    /// Searches for an entry starting at `index` up to the maximum index. If no entry
+    /// is found, wraps around and searches from index 0 up to `index`.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray}};
+    /// let mut xa = KBox::pin_init(XArray::<KBox<u32>>::new(AllocKind::Alloc), GFP_KERNEL)?;
+    /// let mut guard = xa.lock();
+    ///
+    /// guard.store(100, KBox::new(42u32, GFP_ATOMIC)?, GFP_ATOMIC)?;
+    /// let entry = guard.find_next_entry_circular(101);
+    /// assert_eq!(entry.map(|e| e.index()), Some(100));
+    ///
+    /// # Ok::<(), kernel::error::Error>(())
+    /// ```
+    pub fn find_next_entry_circular<'b>(
+        &'b mut self,
+        index: usize,
+    ) -> Option<OccupiedEntry<'a, 'b, T>> {
+        let mut state = XArrayState::new(self, index);
+
+        let (_, ptr) = state.load_next(usize::MAX).or_else(|| {
+            state.restart_at(0);
+            state.load_next(index)
+        })?;
+
+        Some(OccupiedEntry { state, ptr })
     }
 
     /// Removes and returns the element at the given index.
@@ -226,7 +504,12 @@ pub fn remove(&mut self, index: usize) -> Option<T> {
 
     /// Stores an element at the given index.
     ///
-    /// May drop the lock if needed to allocate memory, and then reacquire it afterwards.
+    /// If `gfp` contains blocking allocation flags, this method may drop the
+    /// lock to allocate memory and reacquire it afterwards. Other threads may
+    /// lock and modify the array in that window, so callers must not rely on
+    /// this method being atomic with respect to other operations on the
+    /// guard. To store without dropping the lock, use [`Guard::insert_entry`]
+    /// with preallocated memory.
     ///
     /// On success, returns the element which was previously at the given index.
     ///
@@ -273,8 +556,268 @@ pub fn store(
             Ok(unsafe { T::try_from_foreign(old) })
         }
     }
+
+    /// Inserts a value and returns an occupied entry for further operations.
+    ///
+    /// If a value is already present, the operation fails.
+    ///
+    /// This method will not drop the XArray lock. If memory allocation is
+    /// required for the operation to succeed, the user should supply memory
+    /// through the `preload` argument.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray}};
+    /// let mut xa = KBox::pin_init(XArray::<KBox<u32>>::new(AllocKind::Alloc), GFP_KERNEL)?;
+    /// let mut guard = xa.lock();
+    ///
+    /// assert_eq!(guard.get(42), None);
+    ///
+    /// let value = KBox::new(0x1337u32, GFP_ATOMIC)?;
+    /// let entry = guard.insert_entry(42, value, None)?;
+    /// let borrowed = entry.into_mut();
+    /// assert_eq!(borrowed, &0x1337);
+    ///
+    /// # Ok::<(), kernel::error::Error>(())
+    /// ```
+    pub fn insert_entry<'b>(
+        &'b mut self,
+        index: usize,
+        value: T,
+        preload: Option<&mut XArraySheaf<'_>>,
+    ) -> Result<OccupiedEntry<'a, 'b, T>, StoreError<T>> {
+        match self.entry(index) {
+            Entry::Vacant(entry) => entry.insert_entry(value, preload),
+            Entry::Occupied(_) => Err(StoreError {
+                error: EBUSY,
+                value,
+            }),
+        }
+    }
+}
+
+/// Internal state for XArray iteration and entry operations.
+///
+/// `R` is the borrow held on the guard: either `&Guard` for read-only callers
+/// or `&mut Guard` for entry-style APIs that need to surrender the borrow back
+/// via [`XArrayState::into_guard`].
+///
+/// # Invariants
+///
+/// - `state` is always a valid `bindings::xa_state`.
+/// - `state.xa` aliases the xarray reachable through `guard`.
+pub(crate) struct XArrayState<R> {
+    guard: R,
+    state: bindings::xa_state,
+}
+
+impl<R> Drop for XArrayState<R> {
+    fn drop(&mut self) {
+        free_xa_alloc(&mut self.state);
+    }
+}
+
+fn free_xa_alloc(state: &mut bindings::xa_state) {
+    if !state.xa_alloc.is_null() {
+        // SAFETY:
+        // - `xa_alloc` is only set via `SBox::into_ptr()` in `insert()` where
+        //   the node comes from an `XArraySheaf` backed by `radix_tree_node_cachep`.
+        // - `xa_alloc` points to a valid, initialized `XArrayNode`.
+        // - The caller has exclusive ownership of `xa_alloc`, and no other
+        //   `SBox` or reference exists for this value.
+        drop(unsafe {
+            SBox::<XArrayNode>::static_from_ptr(
+                bindings::radix_tree_node_cachep,
+                state.xa_alloc.cast(),
+            )
+        });
+        state.xa_alloc = null_mut();
+    }
+}
+
+impl<'a, R, T> XArrayState<R>
+where
+    T: ForeignOwnable + 'a,
+    R: core::ops::Deref<Target = Guard<'a, T>>,
+{
+    #[inline]
+    fn new(guard: R, index: usize) -> Self {
+        let xa_ptr = guard.xa.xa.get();
+        // INVARIANT: `state` is initialized to a valid `xa_state` whose `xa` field aliases the
+        // xarray reachable through `guard`.
+        Self {
+            guard,
+            state: bindings::xa_state {
+                xa: xa_ptr,
+                xa_index: index,
+                xa_shift: 0,
+                xa_sibs: 0,
+                xa_offset: 0,
+                xa_pad: 0,
+                xa_node: bindings::XAS_RESTART as *mut bindings::xa_node,
+                xa_alloc: null_mut(),
+                xa_update: None,
+                xa_lru: null_mut(),
+            },
+        }
+    }
+
+    #[inline]
+    fn load(&mut self) -> Option<NonNull<c_void>> {
+        // SAFETY: `self.state` is a valid `xa_state` by the type invariant. By the same
+        // invariant, `self.state.xa` aliases the xarray reachable through `self.guard`, whose
+        // lock we hold.
+        let ptr = unsafe { bindings::xas_load(&raw mut self.state) };
+
+        // Unlike the normal API, `xas_load` does not filter out internal entries. Arrays
+        // created with [`AllocKind::Alloc1`] store `XA_ZERO_ENTRY` at index 0 when they are
+        // expanded from empty, so convert zero entries to `NULL` like `xa_load` does. Retry
+        // entries cannot be observed here because they require concurrent modification of the
+        // array, and we hold the lock.
+        //
+        // SAFETY: `xa_zero_to_null` only inspects the value of `ptr`.
+        NonNull::new(unsafe { bindings::xa_zero_to_null(ptr) }.cast())
+    }
+
+    fn load_next(&mut self, max: usize) -> Option<(usize, NonNull<c_void>)> {
+        loop {
+            // SAFETY: `self.state` is a valid `xa_state` by the type invariant. By the same
+            // invariant, `self.state.xa` aliases the xarray reachable through `self.guard`,
+            // whose lock we hold.
+            let ptr = unsafe { bindings::xas_find(&raw mut self.state, max) };
+            if ptr.is_null() {
+                break None;
+            }
+
+            // Unlike the normal API, `xas_find` does not filter out internal entries. Arrays
+            // created with [`AllocKind::Alloc1`] store `XA_ZERO_ENTRY` at index 0 when they
+            // are expanded from empty. Skip zero entries and continue the search, like the
+            // `xas_retry` loop in `xa_find` does. Retry entries cannot be observed here
+            // because they require concurrent modification of the array, and we hold the
+            // lock.
+            //
+            // SAFETY: `xa_zero_to_null` only inspects the value of `ptr`.
+            if let Some(ptr) = NonNull::new(unsafe { bindings::xa_zero_to_null(ptr) }) {
+                break Some((self.state.xa_index, ptr));
+            }
+        }
+    }
+
+    #[inline]
+    fn status(&self) -> Result {
+        // SAFETY: `self.state` is a valid `xa_state` by the type invariant.
+        to_result(unsafe { bindings::xas_error(&self.state) })
+    }
+
+    /// Resets the state so the next operation walks the tree from the root,
+    /// starting at `index`.
+    fn restart_at(&mut self, index: usize) {
+        self.state.xa_index = index;
+        self.state.xa_node = bindings::XAS_RESTART as *mut bindings::xa_node;
+    }
+}
+
+// Operations that modify the array require exclusive access to the guard, so
+// they are only implemented for `XArrayState<&mut Guard>`.
+impl<'a, 'b, T: ForeignOwnable> XArrayState<&'b mut Guard<'a, T>> {
+    /// Stores `new` at the index of this state, returning the previous entry.
+    ///
+    /// The slot at the index of this state must be occupied. Storing to an
+    /// occupied slot is a simple pointer swap that cannot fail, by design of
+    /// the xarray data structure.
+    fn replace(&mut self, new: *mut c_void) -> *mut c_void {
+        // SAFETY: `self.state` is a valid `xa_state` by the type invariant. By the same
+        // invariant, `self.state.xa` aliases the xarray reachable through `self.guard`, whose
+        // lock we hold.
+        let old = unsafe {
+            bindings::xas_result(
+                &raw mut self.state,
+                bindings::xa_zero_to_null(bindings::xas_store(&raw mut self.state, new)),
+            )
+        };
+
+        // SAFETY: `old` is a valid return value from `xas_result`.
+        let errno = unsafe { bindings::xa_err(old) };
+
+        // NOTE: Storing to an occupied slot never fails. This is by design of
+        // the xarray data structure. If a slot is occupied, a store is a
+        // simple pointer swap.
+        debug_assert!(errno == 0);
+
+        old
+    }
+
+    fn insert(
+        &mut self,
+        value: T,
+        mut preload: Option<&mut XArraySheaf<'_>>,
+    ) -> Result<*mut c_void, StoreError<T>> {
+        build_assert!(
+            T::FOREIGN_ALIGN >= 4,
+            "pointers stored in XArray must be 4-byte aligned"
+        );
+        let new = T::into_foreign(value).cast();
+
+        loop {
+            // SAFETY: `self.state` is a valid `xa_state` by the type invariant. By the same
+            // invariant, `self.state.xa` aliases the xarray reachable through `self.guard`,
+            // whose lock we hold. `new` came from `T::into_foreign`.
+            unsafe { bindings::xas_store(&mut self.state, new) };
+
+            // All arrays created by this abstraction have `XA_FLAGS_TRACK_FREE` set, so the
+            // free mark must be cleared for a newly occupied index, as `__xa_store` does.
+            // This is a no-op if the store above failed.
+            //
+            // SAFETY: `self.state` is a valid `xa_state` by the type invariant, and we hold
+            // the lock on the xarray it refers to.
+            unsafe { bindings::xas_clear_mark(&self.state, bindings::XA_FREE_MARK) };
+
+            match self.status() {
+                Ok(()) => break Ok(new),
+                Err(ENOMEM) => {
+                    debug_assert!(self.state.xa_alloc.is_null());
+                    let node = match preload.as_mut().map(|sheaf| sheaf.alloc().ok_or(ENOMEM)) {
+                        None => break Err(ENOMEM),
+                        Some(Err(e)) => break Err(e),
+                        Some(Ok(node)) => node,
+                    };
+
+                    self.state.xa_alloc = node.into_ptr().cast();
+
+                    // On allocation failure, `xas_store` leaves `XA_ERROR(-ENOMEM)` in
+                    // `self.state.xa_node`, which makes further operations on the state fail
+                    // immediately without consuming `xa_alloc`. Reset the state so the retry
+                    // walks the tree again, as `xas_nomem` does.
+                    self.restart_at(self.state.xa_index);
+                    continue;
+                }
+                Err(e) => break Err(e),
+            }
+        }
+        .map_err(|error| {
+            // SAFETY: `new` came from `T::into_foreign` and `xas_store` does not take
+            // ownership of the value on error.
+            let value = unsafe { T::from_foreign(new) };
+            StoreError { value, error }
+        })
+    }
+
+    /// Consumes `self`, releases any preallocated node held in `xa_alloc`, and
+    /// returns the inner `&mut Guard`.
+    #[inline]
+    pub(crate) fn into_guard(self) -> &'b mut Guard<'a, T> {
+        // Suppress the `Drop` impl so we can move `guard` out by hand.
+        let mut this = core::mem::ManuallyDrop::new(self);
+        free_xa_alloc(&mut this.state);
+        // SAFETY: `ManuallyDrop` prevents `Drop::drop` from running, so this is the only place
+        // that consumes `guard`. `state` has no other resources after `free_xa_alloc`.
+        unsafe { core::ptr::read(&this.guard) }
+    }
 }
 
+mod entry;
+
 // SAFETY: `XArray<T>` has no shared mutable state so it is `Send` iff `T` is `Send`.
 unsafe impl<T: ForeignOwnable + Send> Send for XArray<T> {}
 
diff --git a/rust/kernel/xarray/entry.rs b/rust/kernel/xarray/entry.rs
new file mode 100644
index 00000000000000..3d004f6f8c6cd4
--- /dev/null
+++ b/rust/kernel/xarray/entry.rs
@@ -0,0 +1,381 @@
+// SPDX-License-Identifier: GPL-2.0
+
+use super::{
+    Guard,
+    StoreError,
+    XArraySheaf,
+    XArrayState, //
+};
+use core::ptr::NonNull;
+use kernel::{
+    build_assert::build_assert,
+    prelude::*,
+    types::ForeignOwnable, //
+};
+
+/// Represents either a vacant or occupied entry in an XArray.
+pub enum Entry<'a, 'b, T: ForeignOwnable> {
+    /// A vacant entry that can have a value inserted.
+    Vacant(VacantEntry<'a, 'b, T>),
+    /// An occupied entry containing a value.
+    Occupied(OccupiedEntry<'a, 'b, T>),
+}
+
+impl<T: ForeignOwnable> Entry<'_, '_, T> {
+    /// Returns true if this entry is occupied.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray, Entry}};
+    /// let mut xa = KBox::pin_init(XArray::<KBox<u32>>::new(AllocKind::Alloc), GFP_KERNEL)?;
+    /// let mut guard = xa.lock();
+    ///
+    /// let entry = guard.entry(42);
+    /// assert_eq!(entry.is_occupied(), false);
+    /// drop(entry);
+    ///
+    /// guard.store(42, KBox::new(0x1337u32, GFP_ATOMIC)?, GFP_ATOMIC)?;
+    /// let entry = guard.entry(42);
+    /// assert_eq!(entry.is_occupied(), true);
+    ///
+    /// # Ok::<(), kernel::error::Error>(())
+    /// ```
+    #[inline]
+    pub fn is_occupied(&self) -> bool {
+        matches!(self, Entry::Occupied(_))
+    }
+}
+
+/// A view into a vacant entry in an XArray.
+pub struct VacantEntry<'a, 'b, T: ForeignOwnable> {
+    state: XArrayState<&'b mut Guard<'a, T>>,
+}
+
+impl<'a, 'b, T> VacantEntry<'a, 'b, T>
+where
+    T: ForeignOwnable,
+{
+    pub(crate) fn new(guard: &'b mut Guard<'a, T>, index: usize) -> Self {
+        Self {
+            state: XArrayState::new(guard, index),
+        }
+    }
+
+    /// Consumes the entry and returns a mutable reference to the underlying
+    /// guard.
+    ///
+    /// This releases the slot reservation but retains the lock guard so the
+    /// caller can perform further operations on the array.
+    #[inline]
+    pub fn into_guard(self) -> &'b mut Guard<'a, T> {
+        self.state.into_guard()
+    }
+
+    /// Inserts a value into this vacant entry.
+    ///
+    /// Returns a reference to the newly inserted value.
+    ///
+    /// - This method will fail if the nodes on the path to the index
+    ///   represented by this entry are not present in the XArray and no memory
+    ///   is available via the `preload` argument.
+    /// - This method will not drop the XArray lock.
+    ///
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray, Entry}};
+    /// let mut xa = KBox::pin_init(XArray::<KBox<u32>>::new(AllocKind::Alloc), GFP_KERNEL)?;
+    /// let mut guard = xa.lock();
+    ///
+    /// assert_eq!(guard.get(42), None);
+    ///
+    /// if let Entry::Vacant(entry) = guard.entry(42) {
+    ///     let value = KBox::new(0x1337u32, GFP_ATOMIC)?;
+    ///     let borrowed = entry.insert(value, None)?;
+    ///     assert_eq!(*borrowed, 0x1337);
+    /// }
+    ///
+    /// assert_eq!(guard.get(42).copied(), Some(0x1337));
+    ///
+    /// # Ok::<(), kernel::error::Error>(())
+    /// ```
+    pub fn insert(
+        mut self,
+        value: T,
+        preload: Option<&mut XArraySheaf<'_>>,
+    ) -> Result<T::BorrowedMut<'b>, StoreError<T>> {
+        let new = self.state.insert(value, preload)?;
+
+        // SAFETY: `new` came from `T::into_foreign`. The entry has exclusive
+        // ownership of `new` as it holds a mutable reference to `Guard`.
+        Ok(unsafe { T::borrow_mut(new) })
+    }
+
+    /// Inserts a value and returns an occupied entry representing the newly inserted value.
+    ///
+    /// - This method will fail if the nodes on the path to the index
+    ///   represented by this entry are not present in the XArray and no memory
+    ///   is available via the `preload` argument.
+    /// - This method will not drop the XArray lock.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray, Entry}};
+    /// let mut xa = KBox::pin_init(XArray::<KBox<u32>>::new(AllocKind::Alloc), GFP_KERNEL)?;
+    /// let mut guard = xa.lock();
+    ///
+    /// assert_eq!(guard.get(42), None);
+    ///
+    /// if let Entry::Vacant(entry) = guard.entry(42) {
+    ///     let value = KBox::new(0x1337u32, GFP_ATOMIC)?;
+    ///     let occupied = entry.insert_entry(value, None)?;
+    ///     assert_eq!(occupied.index(), 42);
+    /// }
+    ///
+    /// assert_eq!(guard.get(42).copied(), Some(0x1337));
+    ///
+    /// # Ok::<(), kernel::error::Error>(())
+    /// ```
+    pub fn insert_entry(
+        mut self,
+        value: T,
+        preload: Option<&mut XArraySheaf<'_>>,
+    ) -> Result<OccupiedEntry<'a, 'b, T>, StoreError<T>> {
+        let new = self.state.insert(value, preload)?;
+
+        Ok(OccupiedEntry::<'a, 'b, T> {
+            state: self.state,
+            // SAFETY: `new` came from `T::into_foreign` and is guaranteed non-null.
+            ptr: unsafe { core::ptr::NonNull::new_unchecked(new) },
+        })
+    }
+
+    /// Returns the index of this vacant entry.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray, Entry}};
+    /// let mut xa = KBox::pin_init(XArray::<KBox<u32>>::new(AllocKind::Alloc), GFP_KERNEL)?;
+    /// let mut guard = xa.lock();
+    ///
+    /// assert_eq!(guard.get(42), None);
+    ///
+    /// if let Entry::Vacant(entry) = guard.entry(42) {
+    ///     assert_eq!(entry.index(), 42);
+    /// }
+    ///
+    /// # Ok::<(), kernel::error::Error>(())
+    /// ```
+    #[inline]
+    pub fn index(&self) -> usize {
+        self.state.state.xa_index
+    }
+}
+
+/// A view into an occupied entry in an XArray.
+pub struct OccupiedEntry<'a, 'b, T: ForeignOwnable> {
+    pub(crate) state: XArrayState<&'b mut Guard<'a, T>>,
+    pub(crate) ptr: NonNull<c_void>,
+}
+
+impl<'a, 'b, T> OccupiedEntry<'a, 'b, T>
+where
+    T: ForeignOwnable,
+{
+    pub(crate) fn new(guard: &'b mut Guard<'a, T>, index: usize, ptr: NonNull<c_void>) -> Self {
+        Self {
+            state: XArrayState::new(guard, index),
+            ptr,
+        }
+    }
+
+    /// Consumes the entry and returns a mutable reference to the underlying
+    /// guard.
+    ///
+    /// This releases the borrow on the entry's slot but retains the lock
+    /// guard so the caller can perform further operations on the array.
+    #[inline]
+    pub fn into_guard(self) -> &'b mut Guard<'a, T> {
+        self.state.into_guard()
+    }
+
+    /// Removes the value from this occupied entry and returns it, consuming the entry.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray, Entry}};
+    /// let mut xa = KBox::pin_init(XArray::<KBox<u32>>::new(AllocKind::Alloc), GFP_KERNEL)?;
+    /// let mut guard = xa.lock();
+    ///
+    /// guard.store(42, KBox::new(0x1337u32, GFP_ATOMIC)?, GFP_ATOMIC)?;
+    /// assert_eq!(guard.get(42).copied(), Some(0x1337));
+    ///
+    /// if let Entry::Occupied(entry) = guard.entry(42) {
+    ///     let value = entry.remove();
+    ///     assert_eq!(*value, 0x1337);
+    /// }
+    ///
+    /// assert_eq!(guard.get(42), None);
+    ///
+    /// # Ok::<(), kernel::error::Error>(())
+    /// ```
+    pub fn remove(mut self) -> T {
+        let ptr = self.state.replace(core::ptr::null_mut());
+
+        // SAFETY:
+        // - `ptr` came from `T::into_foreign`.
+        // - As this method takes self by value, the lifetimes of any [`T::Borrowed`] and
+        //   [`T::BorrowedMut`] we have created must have ended.
+        unsafe { T::from_foreign(ptr.cast()) }
+    }
+
+    /// Returns the index of this occupied entry.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray, Entry}};
+    /// let mut xa = KBox::pin_init(XArray::<KBox<u32>>::new(AllocKind::Alloc), GFP_KERNEL)?;
+    /// let mut guard = xa.lock();
+    ///
+    /// guard.store(42, KBox::new(0x1337u32, GFP_ATOMIC)?, GFP_ATOMIC)?;
+    ///
+    /// if let Entry::Occupied(entry) = guard.entry(42) {
+    ///     assert_eq!(entry.index(), 42);
+    /// }
+    ///
+    /// # Ok::<(), kernel::error::Error>(())
+    /// ```
+    #[inline]
+    pub fn index(&self) -> usize {
+        self.state.state.xa_index
+    }
+
+    /// Replaces the value in this occupied entry and returns the old value.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray, Entry}};
+    /// let mut xa = KBox::pin_init(XArray::<KBox<u32>>::new(AllocKind::Alloc), GFP_KERNEL)?;
+    /// let mut guard = xa.lock();
+    ///
+    /// guard.store(42, KBox::new(0x1337u32, GFP_ATOMIC)?, GFP_ATOMIC)?;
+    ///
+    /// if let Entry::Occupied(mut entry) = guard.entry(42) {
+    ///     let new_value = KBox::new(0x9999u32, GFP_ATOMIC)?;
+    ///     let old_value = entry.insert(new_value);
+    ///     assert_eq!(*old_value, 0x1337);
+    /// }
+    ///
+    /// assert_eq!(guard.get(42).copied(), Some(0x9999));
+    ///
+    /// # Ok::<(), kernel::error::Error>(())
+    /// ```
+    pub fn insert(&mut self, value: T) -> T {
+        build_assert!(
+            T::FOREIGN_ALIGN >= 4,
+            "pointers stored in XArray must be 4-byte aligned"
+        );
+        let new = T::into_foreign(value).cast();
+        // SAFETY: `new` came from `T::into_foreign` and is guaranteed non-null.
+        self.ptr = unsafe { NonNull::new_unchecked(new) };
+
+        let old = self.state.replace(new);
+
+        // SAFETY:
+        // - `old` came from `T::into_foreign`.
+        // - As this method takes `self` by mutable reference, the lifetimes of any
+        //   [`T::Borrowed`] and [`T::BorrowedMut`] we have created must have ended.
+        unsafe { T::from_foreign(old) }
+    }
+
+    /// Converts this occupied entry into a mutable reference to the value in the slot represented
+    /// by the entry.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray, Entry}};
+    /// let mut xa = KBox::pin_init(XArray::<KBox<u32>>::new(AllocKind::Alloc), GFP_KERNEL)?;
+    /// let mut guard = xa.lock();
+    ///
+    /// guard.store(42, KBox::new(0x1337u32, GFP_ATOMIC)?, GFP_ATOMIC)?;
+    ///
+    /// if let Entry::Occupied(entry) = guard.entry(42) {
+    ///     let value_ref = entry.into_mut();
+    ///     *value_ref = 0x9999;
+    /// }
+    ///
+    /// assert_eq!(guard.get(42).copied(), Some(0x9999));
+    ///
+    /// # Ok::<(), kernel::error::Error>(())
+    /// ```
+    #[inline]
+    pub fn into_mut(self) -> T::BorrowedMut<'b> {
+        // SAFETY: `ptr` came from `T::into_foreign`.
+        unsafe { T::borrow_mut(self.ptr.as_ptr()) }
+    }
+
+    /// Swaps the value in this entry with the provided value.
+    ///
+    /// Returns the old value that was in the entry.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray, Entry}};
+    /// let mut xa = KBox::pin_init(XArray::<KBox<u32>>::new(AllocKind::Alloc), GFP_KERNEL)?;
+    /// let mut guard = xa.lock();
+    ///
+    /// guard.store(42, KBox::new(100u32, GFP_ATOMIC)?, GFP_ATOMIC)?;
+    ///
+    /// if let Entry::Occupied(mut entry) = guard.entry(42) {
+    ///     let mut other = 200u32;
+    ///     entry.swap(&mut other);
+    ///     assert_eq!(other, 100);
+    ///     assert_eq!(*entry, 200);
+    /// }
+    ///
+    /// # Ok::<(), kernel::error::Error>(())
+    /// ```
+    pub fn swap<U>(&mut self, other: &mut U)
+    where
+        T: ForeignOwnable<Borrowed<'b> = &'b U, BorrowedMut<'b> = &'b mut U> + 'b,
+        U: 'b,
+    {
+        use core::ops::DerefMut;
+        core::mem::swap(self.deref_mut(), other);
+    }
+}
+
+impl<'a, 'b, T, U> core::ops::Deref for OccupiedEntry<'a, 'b, T>
+where
+    T: ForeignOwnable<Borrowed<'b> = &'b U, BorrowedMut<'b> = &'b mut U> + 'b,
+    U: 'b,
+{
+    type Target = U;
+
+    #[inline]
+    fn deref(&self) -> &Self::Target {
+        // SAFETY: `ptr` came from `T::into_foreign`.
+        unsafe { T::borrow(self.ptr.as_ptr()) }
+    }
+}
+
+impl<'a, 'b, T, U> core::ops::DerefMut for OccupiedEntry<'a, 'b, T>
+where
+    T: ForeignOwnable<Borrowed<'b> = &'b U, BorrowedMut<'b> = &'b mut U> + 'b,
+    U: 'b,
+{
+    #[inline]
+    fn deref_mut(&mut self) -> &mut Self::Target {
+        // SAFETY: `ptr` came from `T::into_foreign`.
+        unsafe { T::borrow_mut(self.ptr.as_ptr()) }
+    }
+}

3/2 2026/11/25 13:48 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 28362
							output: 18
							thoughts: 941
						

Thoughts:
**Kernel Patch Evaluation for Syzkaller Fuzzing**

Okay, let's take a look at this patch series and decide if it's a good candidate for fuzzing with syzkaller. First, I need to understand what's actually changed.

Right off the bat, I see a few key areas that are touched. We have changes to `MAINTAINERS`, which is generally innocuous but points towards the scope of the changes. The addition of `rust/kernel/xarray/` is the first real signal. We also have changes to header files, including `radix-tree.h` and `xarray.h`. In particular, the new `radix_tree_node_ctor` and inline helpers `xa_zero_to_null()` and `xas_result()` are interesting.

Looking closer, `lib/radix-tree.c` sees the most action. `radix_tree_node_cachep` is now exported, and `radix_tree_node_ctor` is no longer static.  The `radix_tree_init` function now specifies a `.sheaf_capacity = 64`. This is a significant detail. The `xarray.c` file is mostly cleaned up of the helper functions that were moved. The changes to `mm/slub.c` are minor, and the changes to the rust bindings are as expected. Finally, in the Rust code, we see sheaves support and an entry API (`VacantEntry`, `OccupiedEntry`, etc.) for XArray.

Now the million-dollar question: Does syzkaller actually *fuzz* Rust kernel code?  And who's using Rust XArray or sheaf?  I need to figure out the scope of these changes. I'll search the codebase to see who is using `rust/kernel/xarray` or `sheaf`. I need to figure out if there are any Rust drivers or modules, to understand how this is used.

I also need to focus on this change in `lib/radix-tree.c`:  The `.sheaf_capacity = 64` configuration of `radix_tree_node_cachep` is a significant change! The radix tree and xarray are fundamental data structures in the C kernel. We're talking about page cache, file descriptors, IDR - pretty much everywhere! I need to understand the impact of the new `sheaf_capacity`.

Let's check what setting `.sheaf_capacity = 64` does to `radix_tree_node_cachep` using a codebase search. That will tell me if the change is a potential attack vector.



4/2 2026/11/25 13:48 tool grepper
0m Args:
{
  "Expression": "sheaf_capacity"
}

Results:
{
  "Output": "\nFull output is too long, showing 200 out of 260 lines.\nUse more precise expression or PathPrefixes if possible.\n\nNumber of matching lines per file (10 files in total):\ninclude/linux/slab.h:3\nlib/maple_tree.c:1\nlib/radix-tree.c:1\nmm/slab.h:2\nmm/slab_common.c:1\nmm/slub.c:32\nmm/vma_init.c:1\nrust/kernel/mm/sheaf.rs:5\ntools/include/linux/slab.h:3\ntools/testing/shared/linux.c:2\n\ninclude/linux/slab.h=297=struct kmem_cache_args {\n--\ninclude/linux/slab.h-356-\t/**\ninclude/linux/slab.h:357:\t * @sheaf_capacity: Enable sheaves of given capacity for the cache.\ninclude/linux/slab.h-358-\t *\n--\ninclude/linux/slab.h-380-\t *\ninclude/linux/slab.h:381:\t * When slub_debug is enabled for the cache, the sheaf_capacity argument\ninclude/linux/slab.h-382-\t * is ignored.\n--\ninclude/linux/slab.h-385-\t */\ninclude/linux/slab.h:386:\tunsigned int sheaf_capacity;\ninclude/linux/slab.h-387-};\n--\nlib/maple_tree.c=5743=void __init maple_tree_init(void)\n--\nlib/maple_tree.c-5746-\t\t.align  = sizeof(struct maple_node),\nlib/maple_tree.c:5747:\t\t.sheaf_capacity = 32,\nlib/maple_tree.c-5748-\t};\n--\nlib/radix-tree.c=1595=void __init radix_tree_init(void)\n--\nlib/radix-tree.c-1604-\t\t.ctor = radix_tree_node_ctor,\nlib/radix-tree.c:1605:\t\t.sheaf_capacity = 64,\nlib/radix-tree.c-1606-\t};\n--\nmm/slab.h=226=struct kmem_cache {\n--\nmm/slab.h-234-\tunsigned int offset;\t\t/* Free pointer offset */\nmm/slab.h:235:\tunsigned int sheaf_capacity;\nmm/slab.h-236-\tstruct kmem_cache_order_objects oo;\n--\nmm/slab.h=288=static inline bool cache_has_sheaves(struct kmem_cache *s)\n--\nmm/slab.h-290-\t/* Test CONFIG_SLUB_TINY for code elimination purposes */\nmm/slab.h:291:\treturn !IS_ENABLED(CONFIG_SLUB_TINY) \u0026\u0026 s-\u003esheaf_capacity;\nmm/slab.h-292-}\n--\nmm/slab_common.c=318=struct kmem_cache *__kmem_cache_create_args(const char *name,\n--\nmm/slab_common.c-346-\t */\nmm/slab_common.c:347:\tif (args-\u003esheaf_capacity)\nmm/slab_common.c-348-\t\tflags |= SLAB_NO_MERGE;\n--\nmm/slub.c=2866=static inline struct slab_sheaf *alloc_empty_sheaf(struct kmem_cache *s,\n--\nmm/slub.c-2873-\nmm/slub.c:2874:\treturn __alloc_empty_sheaf(s, gfp, alloc_flags, s-\u003esheaf_capacity);\nmm/slub.c-2875-}\n--\nmm/slub.c=2908=static int refill_sheaf(struct kmem_cache *s, struct slab_sheaf *sheaf,\n--\nmm/slub.c-2910-{\nmm/slub.c:2911:\tint to_fill = s-\u003esheaf_capacity - sheaf-\u003esize;\nmm/slub.c-2912-\tint filled;\n--\nmm/slub.c=5111=EXPORT_SYMBOL(kmem_cache_alloc_node_noprof);\n--\nmm/slub.c-5118- *\nmm/slub.c:5119: * Returns true if the sheaf is now full, at s-\u003esheaf_capacity.\nmm/slub.c-5120- * Returns false if the sheaf is still not full.\n--\nmm/slub.c=5122=static bool refill_sheaf_from_barn(struct kmem_cache *s,\n--\nmm/slub.c-5143-\t */\nmm/slub.c:5144:\twhile (sheaf-\u003esize \u003c s-\u003esheaf_capacity) {\nmm/slub.c-5145-\t\tsrc = barn-\u003esheaf_partial;\n--\nmm/slub.c-5155-\nmm/slub.c:5156:\t\tto_move = min(s-\u003esheaf_capacity - sheaf-\u003esize, src-\u003esize);\nmm/slub.c-5157-\t\tsrc-\u003esize -= to_move;\n--\nmm/slub.c-5177-\nmm/slub.c:5178:\tif (sheaf-\u003esize \u003c s-\u003esheaf_capacity)\nmm/slub.c-5179-\t\treturn false;\n--\nmm/slub.c=5223=kmem_cache_prefill_sheaf(struct kmem_cache *s, gfp_t gfp, unsigned int size)\n--\nmm/slub.c-5231-\nmm/slub.c:5232:\tif (unlikely(size \u003e s-\u003esheaf_capacity)) {\nmm/slub.c-5233-\n--\nmm/slub.c-5281-\tif (sheaf) {\nmm/slub.c:5282:\t\tsheaf-\u003ecapacity = s-\u003esheaf_capacity;\nmm/slub.c-5283-\t\tsheaf-\u003epfmemalloc = false;\n--\nmm/slub.c=5295=EXPORT_SYMBOL(kmem_cache_prefill_sheaf);\n--\nmm/slub.c-5301- * for a full sheaf in the barn, we try to refill the sheaf back to the cache's\nmm/slub.c:5302: * sheaf_capacity to avoid handling partially full sheaves.\nmm/slub.c-5303- *\n--\nmm/slub.c=5307=void kmem_cache_return_sheaf(struct kmem_cache *s, gfp_t gfp,\n--\nmm/slub.c-5312-\nmm/slub.c:5313:\tif (unlikely((sheaf-\u003ecapacity != s-\u003esheaf_capacity)\nmm/slub.c-5314-\t\t     || sheaf-\u003epfmemalloc)) {\n--\nmm/slub.c=5366=int kmem_cache_refill_sheaf(struct kmem_cache *s, gfp_t gfp,\n--\nmm/slub.c-5382-\tif (likely(sheaf-\u003ecapacity \u003e= size)) {\nmm/slub.c:5383:\t\tif (likely(sheaf-\u003ecapacity == s-\u003esheaf_capacity))\nmm/slub.c-5384-\t\t\treturn __prefill_sheaf_pfmemalloc(s, sheaf, gfp);\n--\nmm/slub.c=5969=static void __pcs_install_empty_sheaf(struct kmem_cache *s,\n--\nmm/slub.c-5985-\t */\nmm/slub.c:5986:\tif (pcs-\u003emain-\u003esize \u003c s-\u003esheaf_capacity) {\nmm/slub.c-5987-\t\tbarn_put_empty_sheaf(barn, empty);\n--\nmm/slub.c-5991-\t/* Also unlikely for the same reason */\nmm/slub.c:5992:\tif (pcs-\u003espare-\u003esize \u003c s-\u003esheaf_capacity) {\nmm/slub.c-5993-\t\tswap(pcs-\u003emain, pcs-\u003espare);\n--\nmm/slub.c=6016=__pcs_replace_full_main(struct kmem_cache *s, struct slub_percpu_sheaves *pcs,\n--\nmm/slub.c-6049-\nmm/slub.c:6050:\tif (pcs-\u003espare-\u003esize \u003c s-\u003esheaf_capacity) {\nmm/slub.c-6051-\t\tswap(pcs-\u003emain, pcs-\u003espare);\n--\nmm/slub.c-6117-\t */\nmm/slub.c:6118:\tif (pcs-\u003emain-\u003esize == s-\u003esheaf_capacity)\nmm/slub.c-6119-\t\tgoto restart;\n--\nmm/slub.c=6140=bool free_to_pcs(struct kmem_cache *s, void *object, bool allow_spin)\n--\nmm/slub.c-6148-\nmm/slub.c:6149:\tif (unlikely(pcs-\u003emain-\u003esize == s-\u003esheaf_capacity)) {\nmm/slub.c-6150-\n--\nmm/slub.c=6237=bool __kfree_rcu_sheaf(struct kmem_cache *s, void *obj, unsigned int free_flags)\n--\nmm/slub.c-6313-\nmm/slub.c:6314:\tif (likely(rcu_sheaf-\u003esize \u003c s-\u003esheaf_capacity)) {\nmm/slub.c-6315-\t\trcu_sheaf = NULL;\n--\nmm/slub.c=6414=static unsigned int __free_to_pcs_batch(struct kmem_cache *s, size_t size, void **p)\n--\nmm/slub.c-6425-\nmm/slub.c:6426:\tif (likely(pcs-\u003emain-\u003esize \u003c s-\u003esheaf_capacity))\nmm/slub.c-6427-\t\tgoto do_free;\n--\nmm/slub.c-6442-\nmm/slub.c:6443:\tif (pcs-\u003espare-\u003esize \u003c s-\u003esheaf_capacity) {\nmm/slub.c-6444-\t\tswap(pcs-\u003emain, pcs-\u003espare);\n--\nmm/slub.c-6458-\tmain = pcs-\u003emain;\nmm/slub.c:6459:\tbatch = min(size, s-\u003esheaf_capacity - main-\u003esize);\nmm/slub.c-6460-\n--\nmm/slub.c=7833=static int init_percpu_sheaves(struct kmem_cache *s)\n--\nmm/slub.c-7846-\t\t * Bootstrap sheaf has zero size so fast-path allocation fails.\nmm/slub.c:7847:\t\t * It has also size == s-\u003esheaf_capacity, so fast-path free\nmm/slub.c-7848-\t\t * fails. In the slow paths we recognize the situation by\nmm/slub.c:7849:\t\t * checking s-\u003esheaf_capacity. This allows fast paths to assume\nmm/slub.c-7850-\t\t * s-\u003ecpu_sheaves and pcs-\u003emain always exists and are valid.\n--\nmm/slub.c-7862-\t\t */\nmm/slub.c:7863:\t\tif (!s-\u003esheaf_capacity)\nmm/slub.c-7864-\t\t\tpcs-\u003emain = \u0026bootstrap_sheaf;\n--\nmm/slub.c=7959=static int init_kmem_cache_nodes(struct kmem_cache *s)\n--\nmm/slub.c-7997-\nmm/slub.c:7998:static unsigned int calculate_sheaf_capacity(struct kmem_cache *s,\nmm/slub.c-7999-\t\t\t\t\t     struct kmem_cache_args *args)\n--\nmm/slub.c-8041-\t */\nmm/slub.c:8042:\treturn max(capacity, args-\u003esheaf_capacity);\nmm/slub.c-8043-}\n--\nmm/slub.c=8049=static int calculate_sizes(struct kmem_cache_args *args, struct kmem_cache *s)\n--\nmm/slub.c-8193-\tif (!is_kmalloc_cache(s))\nmm/slub.c:8194:\t\ts-\u003esheaf_capacity = calculate_sheaf_capacity(s, args);\nmm/slub.c-8195-\n--\nmm/slub.c=8701=static void __init bootstrap_cache_sheaves(struct kmem_cache *s)\n--\nmm/slub.c-8709-\nmm/slub.c:8710:\tcapacity = calculate_sheaf_capacity(s, \u0026empty_args);\nmm/slub.c-8711-\n--\nmm/slub.c-8751-\nmm/slub.c:8752:\ts-\u003esheaf_capacity = capacity;\nmm/slub.c-8753-}\n--\nmm/slub.c=9333=SLAB_ATTR_RO(order);\nmm/slub.c-9334-\nmm/slub.c:9335:static ssize_t sheaf_capacity_show(struct kmem_cache *s, char *buf)\nmm/slub.c-9336-{\nmm/slub.c:9337:\treturn sysfs_emit(buf, \"%u\\n\", s-\u003esheaf_capacity);\nmm/slub.c-9338-}\nmm/slub.c:9339:SLAB_ATTR_RO(sheaf_capacity);\nmm/slub.c-9340-\n--\nmm/slub.c=9675=static const struct attribute *const slab_attrs[] = {\n--\nmm/slub.c-9679-\t\u0026order_attr.attr,\n\n"
}

5/2 2026/11/25 13:49 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 33505
							output: 35
							thoughts: 101
						

Thoughts:
Okay, here's my assessment of what I'm seeing:

**Per-CPU Sheaf Capacity in the Slab Allocator**

Interesting. I'm taking a look at the memory management code, specifically within `mm/slub.c`. And it seems like `args->sheaf_capacity` is the key to enabling per-CPU sheaves for the cache. That's a crucial optimization for reducing contention. Now, let me verify the context. I need to cross-reference with `mm/slab_common.c` to fully understand how `sheaf_capacity` fits into the overall slab allocation scheme. I'm going to scan around line 347 in `mm/slab_common.c`, and specifically around line 8040 of `mm/slub.c`, to get the complete picture and its impact on performance and memory management. This should clarify how the per-CPU sheaves are sized and how they interact with the global slab caches.



6/2 2026/11/25 13:49 tool read-file
0m Args:
{
  "File": "mm/slab_common.c",
  "FirstLine": 340,
  "LineCount": 30
}

Results:
{
  "Contents": " 340:\t\tflags \u0026= ~SLAB_DEBUG_FLAGS;\n 341:\t#endif\n 342:\t\n 343:\t\t/*\n 344:\t\t * Caches with specific capacity are special enough. It's simpler to\n 345:\t\t * make them unmergeable.\n 346:\t\t */\n 347:\t\tif (args-\u003esheaf_capacity)\n 348:\t\t\tflags |= SLAB_NO_MERGE;\n 349:\t\n 350:\t\tmutex_lock(\u0026slab_mutex);\n 351:\t\n 352:\t\terr = kmem_cache_sanity_check(name, object_size);\n 353:\t\tif (err) {\n 354:\t\t\tgoto out_unlock;\n 355:\t\t}\n 356:\t\n 357:\t\tif (flags \u0026 ~SLAB_FLAGS_PERMITTED) {\n 358:\t\t\terr = -EINVAL;\n 359:\t\t\tgoto out_unlock;\n 360:\t\t}\n 361:\t\n 362:\t\t/*\n 363:\t\t * For now we assume any cache can be used with __GFP_ACCOUNT and thus\n 364:\t\t * may need to store objcg pointers for objects\n 365:\t\t */\n 366:\t\tif (!mem_cgroup_kmem_disabled())\n 367:\t\t\tflags |= SLAB_MAY_ACCOUNT;\n 368:\t\n 369:\t\t/* Fail closed on bad usersize of useroffset values. */\n"
}

7/2 2026/11/25 13:49 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 34253
							output: 35
							thoughts: 253
						

Thoughts:
**Analyzing the Radix Tree Node Cache Initialization**

Okay, hold on a second! Before diving into *this* patch, I need to rewind and understand what `radix_tree_init` was doing *prior* to this change. My gut tells me something significant shifted here.

Let's see, the code snippet from `lib/radix-tree.c` shows the old initialization, which looks quite straightforward. It was creating a `kmem_cache` named "radix_tree_node" using `kmem_cache_create`. Nothing too complex there. Now, the new code has this `kmem_cache_args` struct and that `sheaf_capacity` parameter, a parameter I don't recall seeing before.

This change is definitely worth taking a closer look at, as it could be impacting performance in some way.

Now, let's look at the definition of `kmem_cache_create` itself. I need to refresh my understanding of how this function works, specifically how `kmem_cache_args` is used. That means digging into `include/linux/slab.h` right now. I suspect the changes in this initialization are going to be key to whatever improvements were intended.



8/2 2026/11/25 13:50 tool grepper
0m Args:
{
  "Expression": "kmem_cache_create\\(",
  "PathPrefixes": [
    "include/linux/slab.h"
  ]
}

Results:
{
  "Output": "include/linux/slab.h=26=enum _slab_flag_bits {\n--\ninclude/linux/slab.h-75-/*\ninclude/linux/slab.h:76: * Flags to pass to kmem_cache_create().\ninclude/linux/slab.h-77- * The ones marked DEBUG need CONFIG_SLUB_DEBUG enabled, otherwise are no-op\n--\ninclude/linux/slab.h-104-#define SLAB_STORE_USER\t\t__SLAB_FLAG_BIT(_SLAB_STORE_USER)\ninclude/linux/slab.h:105:/* Panic if kmem_cache_create() fails */\ninclude/linux/slab.h-106-#define SLAB_PANIC\t\t__SLAB_FLAG_BIT(_SLAB_PANIC)\n--\ninclude/linux/slab.h-159- * locks must be initialized after each and every kmem_struct_alloc().\ninclude/linux/slab.h:160: * Alternatively, make the ctor passed to kmem_cache_create() initialize\ninclude/linux/slab.h-161- * the locks at page-allocation time, as is done in __i915_request_ctor(),\n--\ninclude/linux/slab.h=283=bool slab_is_available(void);\n--\ninclude/linux/slab.h-285-/**\ninclude/linux/slab.h:286: * struct kmem_cache_args - Less common arguments for kmem_cache_create()\ninclude/linux/slab.h-287- *\n--\ninclude/linux/slab.h-293- *\ninclude/linux/slab.h:294: * When %NULL args is passed to kmem_cache_create(), it is equivalent to all\ninclude/linux/slab.h-295- * fields unused.\n--\ninclude/linux/slab.h=393=static inline struct kmem_cache *\ninclude/linux/slab.h:394:__kmem_cache_create(const char *name, unsigned int size, unsigned int align,\ninclude/linux/slab.h-395-\t\t    slab_flags_t flags, void (*ctor)(void *))\n--\ninclude/linux/slab.h-416- * This is a legacy wrapper, new code should use either KMEM_CACHE_USERCOPY()\ninclude/linux/slab.h:417: * if whitelisting a single field is sufficient, or kmem_cache_create() with\ninclude/linux/slab.h-418- * the necessary parameters passed via the args parameter (see\n--\ninclude/linux/slab.h=441=__kmem_cache_default_args(const char *name, unsigned int size,\n--\ninclude/linux/slab.h-464- * The new variant has 4 parameters:\ninclude/linux/slab.h:465: * ``kmem_cache_create(name, object_size, args, flags)``\ninclude/linux/slab.h-466- *\n--\ninclude/linux/slab.h-469- * The legacy variant has 5 parameters:\ninclude/linux/slab.h:470: * ``kmem_cache_create(name, object_size, align, flags, ctor)``\ninclude/linux/slab.h-471- *\n--\ninclude/linux/slab.h-478- */\ninclude/linux/slab.h:479:#define kmem_cache_create(__name, __object_size, __args, ...)           \\\ninclude/linux/slab.h-480-\t_Generic((__args),                                              \\\n"
}

9/2 2026/11/25 13:50 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 35681
							output: 34
							thoughts: 251
						

Thoughts:
**Analyzing the Radix Tree Node Cache Creation**

Okay, here's an interesting shift. I'm seeing that the `kmem_cache_create` call for the `radix_tree_node_cachep` has been updated. The previous version relied on the older, 5-parameter signature. Now, it's using the 4-parameter variant, which is more recent.

Specifically, I see this: the old:

Has been refactored to:

With this associated struct initialization:

Right, the key change is this `.sheaf_capacity = 64`. My mind immediately jumps to how this affects slab allocation, especially concerning per-CPU sheaves. I need to understand what setting a `sheaf_capacity` of 64 actually *means* in the context of `kmem_cache_create`. I need to dig into the details of the slab allocator, specifically `mm/slub.c`. I need to figure out the implications for allocation size, CPU affinity, and how the cache is organized. I'm going to look at the `calculate_sizes` function, and how percpu sheaves are used when the `sheaf_capacity` value is set. That's the key to understanding this.


10/2 2026/11/25 13:50 tool grepper
0m Args:
{
  "Expression": "init_percpu_sheaves",
  "PathPrefixes": [
    "mm/slub.c"
  ]
}

Results:
{
  "Output": "mm/slub.c=7818=static inline int alloc_kmem_cache_stats(struct kmem_cache *s)\n--\nmm/slub.c-7832-\nmm/slub.c:7833:static int init_percpu_sheaves(struct kmem_cache *s)\nmm/slub.c-7834-{\n--\nmm/slub.c=8673=static struct kmem_cache * __init bootstrap(struct kmem_cache *static_cache)\n--\nmm/slub.c-8696-/*\nmm/slub.c:8697: * Finish the sheaves initialization done normally by init_percpu_sheaves() and\nmm/slub.c-8698- * init_kmem_cache_nodes(). For normal kmalloc caches we have to bootstrap it\n--\nmm/slub.c=8844=int do_kmem_cache_create(struct kmem_cache *s, const char *name,\n--\nmm/slub.c-8916-\nmm/slub.c:8917:\terr = init_percpu_sheaves(s);\nmm/slub.c-8918-\tif (err)\n"
}

11/2 2026/11/25 13:50 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 36546
							output: 35
							thoughts: 25
						

Thoughts:
Okay, let's dive into this. Here's my take on those lines of code:

**Analyzing `mm/slub.c` – Delving into the Details Around Allocation and Freeing**

Alright, I'm heading over to `mm/slub.c` to refresh my memory, specifically around lines 7833-7870. I'm focusing on the allocation/free path in the SLUB allocator. I'm probably looking at this section because I need to understand either its performance characteristics or a potential bug report regarding this area. Perhaps there's a suspected memory leak or corruption, or maybe there is a problem concerning its scalability. I know that this part of the code is critical to understanding SLUB's internal workings. I expect that I'm going to see some of the core functions related to managing the slab caches, particularly the interaction between the CPU and memory. I'll be looking for the `kmem_cache_alloc` and `kmem_cache_free` code paths, which would allow me to see how the allocation/deallocation process works. I'll pay close attention to the lock usage and how it is meant to avoid contention between cores and their allocations. I anticipate the details of how the allocator interacts with the underlying page allocator, and how this relates to NUMA nodes or other hardware considerations. This section should give me a good handle on memory management within the SLUB allocator. I'll begin to understand any context switches, etc.



12/2 2026/11/25 13:51 tool read-file
0m Args:
{
  "File": "mm/slub.c",
  "FirstLine": 7833,
  "LineCount": 45
}

Results:
{
  "Contents": "7833:\tstatic int init_percpu_sheaves(struct kmem_cache *s)\n7834:\t{\n7835:\t\tstatic struct slab_sheaf bootstrap_sheaf = {};\n7836:\t\tint cpu;\n7837:\t\n7838:\t\tfor_each_possible_cpu(cpu) {\n7839:\t\t\tstruct slub_percpu_sheaves *pcs;\n7840:\t\n7841:\t\t\tpcs = per_cpu_ptr(s-\u003ecpu_sheaves, cpu);\n7842:\t\n7843:\t\t\tlocal_trylock_init(\u0026pcs-\u003elock);\n7844:\t\n7845:\t\t\t/*\n7846:\t\t\t * Bootstrap sheaf has zero size so fast-path allocation fails.\n7847:\t\t\t * It has also size == s-\u003esheaf_capacity, so fast-path free\n7848:\t\t\t * fails. In the slow paths we recognize the situation by\n7849:\t\t\t * checking s-\u003esheaf_capacity. This allows fast paths to assume\n7850:\t\t\t * s-\u003ecpu_sheaves and pcs-\u003emain always exists and are valid.\n7851:\t\t\t * It's also safe to share the single static bootstrap_sheaf\n7852:\t\t\t * with zero-sized objects array as it's never modified.\n7853:\t\t\t *\n7854:\t\t\t * Bootstrap_sheaf also has NULL pointer to kmem_cache so we\n7855:\t\t\t * recognize it and not attempt to free it when destroying the\n7856:\t\t\t * cache.\n7857:\t\t\t *\n7858:\t\t\t * We keep bootstrap_sheaf for kmem_cache and kmem_cache_node,\n7859:\t\t\t * caches with debug enabled, and all caches with SLUB_TINY.\n7860:\t\t\t * For kmalloc caches it's used temporarily during the initial\n7861:\t\t\t * bootstrap.\n7862:\t\t\t */\n7863:\t\t\tif (!s-\u003esheaf_capacity)\n7864:\t\t\t\tpcs-\u003emain = \u0026bootstrap_sheaf;\n7865:\t\t\telse\n7866:\t\t\t\tpcs-\u003emain = alloc_empty_sheaf(s, GFP_KERNEL, SLAB_ALLOC_DEFAULT);\n7867:\t\n7868:\t\t\tif (!pcs-\u003emain)\n7869:\t\t\t\treturn -ENOMEM;\n7870:\t\t}\n7871:\t\n7872:\t\treturn 0;\n7873:\t}\n7874:\t\n7875:\tstatic struct kmem_cache *kmem_cache_node;\n7876:\t\n7877:\t/*\n"
}

13/2 2026/11/25 13:51 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 37602
							output: 29
							thoughts: 64
						

Thoughts:
Here's my analysis of this situation:

**Investigating the Impact of Non-Zero `sheaf_capacity` on Cache Behavior**

Okay, so the fact that `s->sheaf_capacity` is *not* zero – that's the key. That has implications for how memory is managed, specifically within caches. My immediate thought is, "How does this nonzero capacity affect allocations and frees within a cache?" That's where the interesting stuff happens. I need to understand what this nonzero value *means* in the context of allocation strategies.

To get the full picture, I need to look at the code. Specifically, I need to zero in on how the `cache_has_sheaves(s)` function is used. So, the next logical step is to dive into `mm/slub.c` and search for that function. From there, I can trace the control flow and understand how `sheaf_capacity` interacts with the allocation and freeing mechanisms of the SLUB allocator. That's the crucial link I need to understand the behavior of the cache under these conditions.



14/2 2026/11/25 13:51 tool grepper
0m Args:
{
  "Expression": "cache_has_sheaves",
  "PathPrefixes": [
    "mm/"
  ]
}

Results:
{
  "Output": "mm/slab.h=226=struct kmem_cache {\n--\nmm/slab.h-287- */\nmm/slab.h:288:static inline bool cache_has_sheaves(struct kmem_cache *s)\nmm/slab.h-289-{\n--\nmm/slab_common.c=2195=void kvfree_rcu_barrier_on_cache(struct kmem_cache *s)\n--\nmm/slab_common.c-2199-\nmm/slab_common.c:2200:\tif (cache_has_sheaves(s)) {\nmm/slab_common.c-2201-\t\tcpus_read_lock();\n--\nmm/slub.c=3126=static void pcs_destroy(struct kmem_cache *s)\n--\nmm/slub.c-3137-\t/* pcs-\u003emain can only point to the bootstrap sheaf, nothing to free */\nmm/slub.c:3138:\tif (!cache_has_sheaves(s))\nmm/slub.c-3139-\t\tgoto free_pcs;\n--\nmm/slub.c=4078=static bool has_pcs_used(int cpu, struct kmem_cache *s)\n--\nmm/slub.c-4081-\nmm/slub.c:4082:\tif (!cache_has_sheaves(s))\nmm/slub.c-4083-\t\treturn false;\n--\nmm/slub.c=4095=static void flush_cpu_sheaves(struct work_struct *w)\n--\nmm/slub.c-4103-\nmm/slub.c:4104:\tif (cache_has_sheaves(s))\nmm/slub.c-4105-\t\tpcs_flush_all(s);\n--\nmm/slub.c=4216=void flush_all_rcu_sheaves(void)\n--\nmm/slub.c-4225-\tlist_for_each_entry(s, \u0026slab_caches, list) {\nmm/slub.c:4226:\t\tif (!cache_has_sheaves(s))\nmm/slub.c-4227-\t\t\tcontinue;\n--\nmm/slub.c=4237=static int slub_cpu_setup(unsigned int cpu)\n--\nmm/slub.c-4260-\t\t */\nmm/slub.c:4261:\t\tif (!cache_has_sheaves(s) || get_barn_node(s, nid))\nmm/slub.c-4262-\t\t\tcontinue;\n--\nmm/slub.c=4286=static int slub_cpu_dead(unsigned int cpu)\n--\nmm/slub.c-4291-\tlist_for_each_entry(s, \u0026slab_caches, list) {\nmm/slub.c:4292:\t\tif (cache_has_sheaves(s))\nmm/slub.c-4293-\t\t\t__pcs_flush_all_cpu(s, cpu);\n--\nmm/slub.c=4751=__pcs_replace_empty_main(struct kmem_cache *s, struct slub_percpu_sheaves *pcs,\n--\nmm/slub.c-4761-\t/* Bootstrap or debug cache, back off */\nmm/slub.c:4762:\tif (unlikely(!cache_has_sheaves(s))) {\nmm/slub.c-4763-\t\tlocal_unlock(\u0026s-\u003ecpu_sheaves-\u003elock);\n--\nmm/slub.c=4917=unsigned int alloc_from_pcs_bulk(struct kmem_cache *s, size_t size, void **p)\n--\nmm/slub.c-4934-\nmm/slub.c:4935:\t\tif (unlikely(!cache_has_sheaves(s))) {\nmm/slub.c-4936-\t\t\tlocal_unlock(\u0026s-\u003ecpu_sheaves-\u003elock);\n--\nmm/slub.c=6016=__pcs_replace_full_main(struct kmem_cache *s, struct slub_percpu_sheaves *pcs,\n--\nmm/slub.c-6026-\t/* Bootstrap or debug cache, back off */\nmm/slub.c:6027:\tif (unlikely(!cache_has_sheaves(s))) {\nmm/slub.c-6028-\t\tlocal_unlock(\u0026s-\u003ecpu_sheaves-\u003elock);\n--\nmm/slub.c=6237=bool __kfree_rcu_sheaf(struct kmem_cache *s, void *obj, unsigned int free_flags)\n--\nmm/slub.c-6258-\t\t/* Bootstrap or debug cache, fall back */\nmm/slub.c:6259:\t\tif (unlikely(!cache_has_sheaves(s))) {\nmm/slub.c-6260-\t\t\tlocal_unlock(\u0026s-\u003ecpu_sheaves-\u003elock);\n--\nmm/slub.c=7362=void kmem_cache_free_bulk(struct kmem_cache *s, size_t size, void **p)\n--\nmm/slub.c-7370-\t */\nmm/slub.c:7371:\tif (s \u0026\u0026 cache_has_sheaves(s)) {\nmm/slub.c-7372-\t\tfree_to_pcs_bulk(s, size, p);\n--\nmm/slub.c=7959=static int init_kmem_cache_nodes(struct kmem_cache *s)\n--\nmm/slub.c-7979-\nmm/slub.c:7980:\tif (slab_state == DOWN || !cache_has_sheaves(s))\nmm/slub.c-7981-\t\treturn 1;\n--\nmm/slub.c=8272=int __kmem_cache_shutdown(struct kmem_cache *s)\n--\nmm/slub.c-8279-\t/* we might have rcu sheaves in flight */\nmm/slub.c:8280:\tif (cache_has_sheaves(s))\nmm/slub.c-8281-\t\trcu_barrier();\n--\nmm/slub.c=8578=static int slab_mem_going_online_callback(int nid)\n--\nmm/slub.c-8599-\nmm/slub.c:8600:\t\tif (cache_has_sheaves(s) \u0026\u0026 !get_barn_node(s, nid)) {\nmm/slub.c-8601-\n--\nmm/slub.c=8701=static void __init bootstrap_cache_sheaves(struct kmem_cache *s)\n--\nmm/slub.c-8707-\nmm/slub.c:8708:\tVM_WARN_ON_ONCE(cache_has_sheaves(s));\nmm/slub.c-8709-\n--\nmm/slub.c=8755=static void __init bootstrap_kmalloc_sheaves(void)\n--\nmm/slub.c-8763-\t\t\t/* Do not bootstrap twice when caches are aliased */\nmm/slub.c:8764:\t\t\tif (s \u0026\u0026 !cache_has_sheaves(s))\nmm/slub.c-8765-\t\t\t\tbootstrap_cache_sheaves(s);\n"
}

15/2 2026/11/25 13:51 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 39813
							output: 38
							thoughts: 70
						

Thoughts:
**Investigating Sheaf Capacity and Allocation Behavior**

Okay, so I need to understand how `s->sheaf_capacity` is influencing memory allocation and deallocation within the SLUB allocator. My immediate thought is to trace the behavior during allocations and frees when this specific capacity is configured. I want to see precisely where the system checks the sheaves in relation to `slab_alloc` and `kmem_cache_alloc`. Time to dig in!

My next step is to use `grep` to quickly identify all instances where the code interacts with potential sheaf-related variables. I'll search the `mm/slub.c` file specifically for references to `pcs` (presumably a related struct or variable) and `s->cpu_sheaves`. That should give me a good overview of the relevant code sections I need to examine more closely. This should illuminate any conditional logic, especially around the use or potential misuse of the capacity setting. Let's see what we find.



16/2 2026/11/25 13:51 tool grepper
0m Args:
{
  "Expression": "alloc_from_pcs|free_to_pcs",
  "PathPrefixes": [
    "mm/slub.c"
  ]
}

Results:
{
  "Output": "mm/slub.c=4863=static __fastpath_inline\nmm/slub.c:4864:void *alloc_from_pcs(struct kmem_cache *s, gfp_t gfp, unsigned int alloc_flags, int node)\nmm/slub.c-4865-{\n--\nmm/slub.c=4916=static __fastpath_inline\nmm/slub.c:4917:unsigned int alloc_from_pcs_bulk(struct kmem_cache *s, size_t size, void **p)\nmm/slub.c-4918-{\n--\nmm/slub.c=5006=static __fastpath_inline void *slab_alloc_node(struct kmem_cache *s,\n--\nmm/slub.c-5020-\nmm/slub.c:5021:\tobject = alloc_from_pcs(s, gfpflags, ac-\u003ealloc_flags, node);\nmm/slub.c-5022-\n--\nmm/slub.c=5565=static void *__kmalloc_nolock_noprof(DECL_TOKEN_PARAMS(size, token), gfp_t gfp_flags,\n--\nmm/slub.c-5604-\nmm/slub.c:5605:\tret = alloc_from_pcs(s, gfp_flags, ac-\u003ealloc_flags, node);\nmm/slub.c-5606-\tif (ret)\n--\nmm/slub.c=6139=static __fastpath_inline\nmm/slub.c:6140:bool free_to_pcs(struct kmem_cache *s, void *object, bool allow_spin)\nmm/slub.c-6141-{\n--\nmm/slub.c=6237=bool __kfree_rcu_sheaf(struct kmem_cache *s, void *obj, unsigned int free_flags)\n--\nmm/slub.c-6355-\nmm/slub.c:6356:static __always_inline bool can_free_to_pcs(struct slab *slab)\nmm/slub.c-6357-{\n--\nmm/slub.c-6413- */\nmm/slub.c:6414:static unsigned int __free_to_pcs_batch(struct kmem_cache *s, size_t size, void **p)\nmm/slub.c-6415-{\n--\nmm/slub.c-6477- * Bulk free objects to the percpu sheaves.\nmm/slub.c:6478: * Unlike free_to_pcs() this includes the calls to all necessary hooks\nmm/slub.c-6479- * and the fallback to freeing to slab pages.\nmm/slub.c-6480- */\nmm/slub.c:6481:static void free_to_pcs_bulk(struct kmem_cache *s, size_t size, void **p)\nmm/slub.c-6482-{\n--\nmm/slub.c-6505-\nmm/slub.c:6506:\t\tif (unlikely(!can_free_to_pcs(slab))) {\nmm/slub.c-6507-\t\t\tif (i != remote_nr)\n--\nmm/slub.c-6518-\twhile (size) {\nmm/slub.c:6519:\t\tunsigned int batch_freed = __free_to_pcs_batch(s, size, p);\nmm/slub.c-6520-\n--\nmm/slub.c=6628=void slab_free(struct kmem_cache *s, struct slab *slab, void *object,\n--\nmm/slub.c-6636-\nmm/slub.c:6637:\tif (likely(can_free_to_pcs(slab)) \u0026\u0026 likely(free_to_pcs(s, object, true)))\nmm/slub.c-6638-\t\treturn;\n--\nmm/slub.c=6940=void kfree_nolock(const void *object)\n--\nmm/slub.c-6986-\nmm/slub.c:6987:\tif (likely(can_free_to_pcs(slab)) \u0026\u0026 likely(free_to_pcs(s, x, false)))\nmm/slub.c-6988-\t\treturn;\n--\nmm/slub.c=7362=void kmem_cache_free_bulk(struct kmem_cache *s, size_t size, void **p)\n--\nmm/slub.c-7371-\tif (s \u0026\u0026 cache_has_sheaves(s)) {\nmm/slub.c:7372:\t\tfree_to_pcs_bulk(s, size, p);\nmm/slub.c-7373-\t\treturn;\n--\nmm/slub.c=7609=bool kmem_cache_alloc_bulk_noprof(struct kmem_cache *s, gfp_t flags,\n--\nmm/slub.c-7639-\nmm/slub.c:7640:\ti = alloc_from_pcs_bulk(s, size, p);\nmm/slub.c-7641-\tif (i \u003c size) {\n"
}

17/2 2026/11/25 13:51 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 41470
							output: 35
							thoughts: 373
						

Thoughts:
**My Immediate Reactions to the Per-CPU Sheaves Change in SLUB**

Okay, hold on a second... LOOK AT THAT! I'm digging into `mm/slub.c` and specifically `slab_alloc_node` and `slab_free`. I see that when a cache has `sheaf_capacity` set, we're leveraging `alloc_from_pcs` and `free_to_pcs` *every single time* for allocations and frees. That's the key.

Now, my mind immediately jumps to `radix_tree_node_cachep`. It's used for allocating both `radix_tree_node` and `xa_node` structures! The implications are significant, it's hitting me now, so every single time the kernel allocates or deallocates a node in a radix tree or XArray... that's *everywhere*! Think page cache, those nodes in file descriptors, idr, bpf, ipc, pid, so much!

And the penny drops: this wasn't always the case. Previously, `radix_tree_node_cachep` *didn't* have `.sheaf_capacity` set. It was zero, so `cache_has_sheaves(s)` was false, and the fast per-CPU sheaves path wasn't used.

But *now* that `.sheaf_capacity` is set to 64, every single allocation and deallocation involving radix trees and XArrays throughout the entire kernel is hitting the per-CPU sheaves (PCS) fast path in SLUB! That's a huge potential performance gain. I need to dig into `alloc_from_pcs` now...



18/2 2026/11/25 13:52 tool read-file
0m Args:
{
  "File": "mm/slub.c",
  "FirstLine": 4863,
  "LineCount": 55
}

Results:
{
  "Contents": "4863:\tstatic __fastpath_inline\n4864:\tvoid *alloc_from_pcs(struct kmem_cache *s, gfp_t gfp, unsigned int alloc_flags, int node)\n4865:\t{\n4866:\t\tstruct slub_percpu_sheaves *pcs;\n4867:\t\tbool node_requested;\n4868:\t\tvoid *object;\n4869:\t\n4870:\t\tnode_requested = IS_ENABLED(CONFIG_NUMA) \u0026\u0026 node != NUMA_NO_NODE;\n4871:\t\n4872:\t\t/*\n4873:\t\t * We assume the percpu sheaves contain only local objects although it's\n4874:\t\t * not completely guaranteed, so we verify later.\n4875:\t\t */\n4876:\t\tif (unlikely(node_requested \u0026\u0026 node != numa_mem_id())) {\n4877:\t\t\tstat(s, ALLOC_NODE_MISMATCH);\n4878:\t\t\treturn NULL;\n4879:\t\t}\n4880:\t\n4881:\t\tif (!local_trylock(\u0026s-\u003ecpu_sheaves-\u003elock))\n4882:\t\t\treturn NULL;\n4883:\t\n4884:\t\tpcs = this_cpu_ptr(s-\u003ecpu_sheaves);\n4885:\t\n4886:\t\tif (unlikely(pcs-\u003emain-\u003esize == 0)) {\n4887:\t\t\tpcs = __pcs_replace_empty_main(s, pcs, gfp, alloc_flags);\n4888:\t\t\tif (unlikely(!pcs))\n4889:\t\t\t\treturn NULL;\n4890:\t\t}\n4891:\t\n4892:\t\tobject = pcs-\u003emain-\u003eobjects[pcs-\u003emain-\u003esize - 1];\n4893:\t\n4894:\t\tif (unlikely(node_requested)) {\n4895:\t\t\t/*\n4896:\t\t\t * Verify that the object was from the node we want. This could\n4897:\t\t\t * be false because of cpu migration during an unlocked part of\n4898:\t\t\t * the current allocation or previous freeing process.\n4899:\t\t\t */\n4900:\t\t\tif (page_to_nid(virt_to_page(object)) != node) {\n4901:\t\t\t\tlocal_unlock(\u0026s-\u003ecpu_sheaves-\u003elock);\n4902:\t\t\t\tstat(s, ALLOC_NODE_MISMATCH);\n4903:\t\t\t\treturn NULL;\n4904:\t\t\t}\n4905:\t\t}\n4906:\t\n4907:\t\tpcs-\u003emain-\u003esize--;\n4908:\t\n4909:\t\tlocal_unlock(\u0026s-\u003ecpu_sheaves-\u003elock);\n4910:\t\n4911:\t\tstat(s, ALLOC_FASTPATH);\n4912:\t\n4913:\t\treturn object;\n4914:\t}\n4915:\t\n4916:\tstatic __fastpath_inline\n4917:\tunsigned int alloc_from_pcs_bulk(struct kmem_cache *s, size_t size, void **p)\n"
}

19/2 2026/11/25 13:52 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 43041
							output: 26
							thoughts: 801
						

Thoughts:
**My Analysis of the Per-CPU Sheaf Changes**

Okay, here's what I've got so far. I'm looking at this change, and the key thing that jumps out is the impact on per-CPU sheaves and SLUB. It's clear that the code now handles `s->sheaf_capacity` being 0 differently. Before, particularly with `radix_tree_node_cachep`, `pcs->main` was pointing to `bootstrap_sheaf`, which had a `size == 0`. So, the check within `__pcs_replace_empty_main` `(!cache_has_sheaves(s))` would always fail because the cache *didn't* have sheaves. This meant it would bail out and fall back to the standard slab allocation.

Now, with this patch, `radix_tree_node_cachep` *does* have a `sheaf_capacity = 64`. This means `cache_has_sheaves(s)` is true! That's the critical point – `radix_tree_node_cachep` is now *actually* using per-CPU sheaves within SLUB! And the `free_to_pcs` path is now working as expected for `radix_tree_node_cachep`.

But hold on, let's look at the broader implications of the entire patch. It's not just a single line change; there's a wider scope here:

1.  **`radix_tree_init`:** The `.sheaf_capacity` is set, and important symbols like `radix_tree_node_cachep` and `radix_tree_node_ctor` are exported. This tells me it's not just an internal change.
2.  **`lib/xarray.c` / `include/linux/xarray.h`:**  Moving `xa_zero_to_null` and `xas_result` as static inline functions to the header file is interesting. It indicates potentially tighter integration or optimization around XArrays.
3.  **`mm/slub.c`:** Several SLUB-related functions are exported: `kmem_cache_prefill_sheaf`, `kmem_cache_return_sheaf`, `kmem_cache_refill_sheaf`, and `kmem_cache_alloc_from_sheaf_noprof`. This reinforces the per-CPU sheaf focus. It's making these functions accessible externally.
4.  **`rust/` directory:**  *Whoa*, there's a whole Rust ecosystem popping up here! It introduces a raft of new code: bindings, helper wrappers, a `sheaf` module, and an `xarray` module with Rust structures like `KMemCache`, `Sheaf`, `XArrayNode`, `Guard`, `XArrayState`, and different types of `Entry` (Vacant, Occupied). This is the big question for me, does the Rust code *do* anything *right now*? Is this just laying the groundwork, or is there active use of this Rust code in the running kernel?

I need to confirm if Rust-based code is currently reachable or utilized in the kernel or syzkaller. I need to check who's using `rust/kernel/xarray.rs` and verify the kernel or syzkaller's Rust enablement status. This is the crucial missing piece.



20/2 2026/11/25 13:52 tool grepper
0m Args:
{
  "Expression": "xarray::",
  "PathPrefixes": [
    "rust/"
  ]
}

Results:
{
  "Output": "rust/kernel/xarray.rs=86=    fn init() -\u003e impl Init\u003cSelf, Infallible\u003e {\n--\nrust/kernel/xarray.rs-116-/// use kernel::alloc::KBox;\nrust/kernel/xarray.rs:117:/// use kernel::xarray::{AllocKind, XArray};\nrust/kernel/xarray.rs-118-///\n--\nrust/kernel/xarray.rs=303=    fn load(\u0026self, index: usize) -\u003e Option\u003cNonNull\u003cc_void\u003e\u003e {\n--\nrust/kernel/xarray.rs-311-    /// ```\nrust/kernel/xarray.rs:312:    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray}};\nrust/kernel/xarray.rs-313-    /// let xa = KBox::pin_init(XArray::\u003cKBox\u003cu32\u003e\u003e::new(AllocKind::Alloc1), GFP_KERNEL)?;\n--\nrust/kernel/xarray.rs=333=    pub fn get_mut(\u0026mut self, index: usize) -\u003e Option\u003cT::BorrowedMut\u003c'_\u003e\u003e {\n--\nrust/kernel/xarray.rs-343-    /// ```\nrust/kernel/xarray.rs:344:    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray, Entry}};\nrust/kernel/xarray.rs-345-    /// let mut xa = KBox::pin_init(XArray::\u003cKBox\u003cu32\u003e\u003e::new(AllocKind::Alloc), GFP_KERNEL)?;\n--\nrust/kernel/xarray.rs=369=    fn load_next(\u0026self, index: usize) -\u003e Option\u003c(usize, NonNull\u003cc_void\u003e)\u003e {\n--\nrust/kernel/xarray.rs-377-    /// ```\nrust/kernel/xarray.rs:378:    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray}};\nrust/kernel/xarray.rs-379-    /// let mut xa = KBox::pin_init(XArray::\u003cKBox\u003cu32\u003e\u003e::new(AllocKind::Alloc), GFP_KERNEL)?;\n--\nrust/kernel/xarray.rs=398=    pub fn find_next(\u0026self, index: usize) -\u003e Option\u003c(usize, T::Borrowed\u003c'_\u003e)\u003e {\n--\nrust/kernel/xarray.rs-408-    /// ```\nrust/kernel/xarray.rs:409:    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray}};\nrust/kernel/xarray.rs-410-    /// let mut xa = KBox::pin_init(XArray::\u003cKBox\u003cu32\u003e\u003e::new(AllocKind::Alloc), GFP_KERNEL)?;\n--\nrust/kernel/xarray.rs=426=    pub fn find_next_mut(\u0026mut self, index: usize) -\u003e Option\u003c(usize, T::BorrowedMut\u003c'_\u003e)\u003e {\n--\nrust/kernel/xarray.rs-436-    /// ```\nrust/kernel/xarray.rs:437:    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray}};\nrust/kernel/xarray.rs-438-    /// let mut xa = KBox::pin_init(XArray::\u003cKBox\u003cu32\u003e\u003e::new(AllocKind::Alloc), GFP_KERNEL)?;\n--\nrust/kernel/xarray.rs=454=    pub fn find_next_entry\u003c'b\u003e(\u0026'b mut self, index: usize) -\u003e Option\u003cOccupiedEntry\u003c'a, 'b, T\u003e\u003e {\n--\nrust/kernel/xarray.rs-467-    /// ```\nrust/kernel/xarray.rs:468:    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray}};\nrust/kernel/xarray.rs-469-    /// let mut xa = KBox::pin_init(XArray::\u003cKBox\u003cu32\u003e\u003e::new(AllocKind::Alloc), GFP_KERNEL)?;\n--\nrust/kernel/xarray.rs=517=    pub fn store(\n--\nrust/kernel/xarray.rs-570-    /// ```\nrust/kernel/xarray.rs:571:    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray}};\nrust/kernel/xarray.rs-572-    /// let mut xa = KBox::pin_init(XArray::\u003cKBox\u003cu32\u003e\u003e::new(AllocKind::Alloc), GFP_KERNEL)?;\n--\nrust/kernel/xarray/entry.rs=24=impl\u003cT: ForeignOwnable\u003e Entry\u003c'_, '_, T\u003e {\n--\nrust/kernel/xarray/entry.rs-29-    /// ```\nrust/kernel/xarray/entry.rs:30:    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray, Entry}};\nrust/kernel/xarray/entry.rs-31-    /// let mut xa = KBox::pin_init(XArray::\u003cKBox\u003cu32\u003e\u003e::new(AllocKind::Alloc), GFP_KERNEL)?;\n--\nrust/kernel/xarray/entry.rs=71=    pub fn into_guard(self) -\u003e \u0026'b mut Guard\u003c'a, T\u003e {\n--\nrust/kernel/xarray/entry.rs-87-    /// ```\nrust/kernel/xarray/entry.rs:88:    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray, Entry}};\nrust/kernel/xarray/entry.rs-89-    /// let mut xa = KBox::pin_init(XArray::\u003cKBox\u003cu32\u003e\u003e::new(AllocKind::Alloc), GFP_KERNEL)?;\n--\nrust/kernel/xarray/entry.rs=104=    pub fn insert(\n--\nrust/kernel/xarray/entry.rs-125-    /// ```\nrust/kernel/xarray/entry.rs:126:    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray, Entry}};\nrust/kernel/xarray/entry.rs-127-    /// let mut xa = KBox::pin_init(XArray::\u003cKBox\u003cu32\u003e\u003e::new(AllocKind::Alloc), GFP_KERNEL)?;\n--\nrust/kernel/xarray/entry.rs=142=    pub fn insert_entry(\n--\nrust/kernel/xarray/entry.rs-160-    /// ```\nrust/kernel/xarray/entry.rs:161:    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray, Entry}};\nrust/kernel/xarray/entry.rs-162-    /// let mut xa = KBox::pin_init(XArray::\u003cKBox\u003cu32\u003e\u003e::new(AllocKind::Alloc), GFP_KERNEL)?;\n--\nrust/kernel/xarray/entry.rs=202=    pub fn into_guard(self) -\u003e \u0026'b mut Guard\u003c'a, T\u003e {\n--\nrust/kernel/xarray/entry.rs-210-    /// ```\nrust/kernel/xarray/entry.rs:211:    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray, Entry}};\nrust/kernel/xarray/entry.rs-212-    /// let mut xa = KBox::pin_init(XArray::\u003cKBox\u003cu32\u003e\u003e::new(AllocKind::Alloc), GFP_KERNEL)?;\n--\nrust/kernel/xarray/entry.rs=227=    pub fn remove(mut self) -\u003e T {\n--\nrust/kernel/xarray/entry.rs-241-    /// ```\nrust/kernel/xarray/entry.rs:242:    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray, Entry}};\nrust/kernel/xarray/entry.rs-243-    /// let mut xa = KBox::pin_init(XArray::\u003cKBox\u003cu32\u003e\u003e::new(AllocKind::Alloc), GFP_KERNEL)?;\n--\nrust/kernel/xarray/entry.rs=255=    pub fn index(\u0026self) -\u003e usize {\n--\nrust/kernel/xarray/entry.rs-263-    /// ```\nrust/kernel/xarray/entry.rs:264:    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray, Entry}};\nrust/kernel/xarray/entry.rs-265-    /// let mut xa = KBox::pin_init(XArray::\u003cKBox\u003cu32\u003e\u003e::new(AllocKind::Alloc), GFP_KERNEL)?;\n--\nrust/kernel/xarray/entry.rs=280=    pub fn insert(\u0026mut self, value: T) -\u003e T {\n--\nrust/kernel/xarray/entry.rs-303-    /// ```\nrust/kernel/xarray/entry.rs:304:    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray, Entry}};\nrust/kernel/xarray/entry.rs-305-    /// let mut xa = KBox::pin_init(XArray::\u003cKBox\u003cu32\u003e\u003e::new(AllocKind::Alloc), GFP_KERNEL)?;\n--\nrust/kernel/xarray/entry.rs=320=    pub fn into_mut(self) -\u003e T::BorrowedMut\u003c'b\u003e {\n--\nrust/kernel/xarray/entry.rs-331-    /// ```\nrust/kernel/xarray/entry.rs:332:    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray, Entry}};\nrust/kernel/xarray/entry.rs-333-    /// let mut xa = KBox::pin_init(XArray::\u003cKBox\u003cu32\u003e\u003e::new(AllocKind::Alloc), GFP_KERNEL)?;\n"
}

21/2 2026/11/25 13:52 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 46936
							output: 25
							thoughts: 15
						

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

**Investigating Rust Dependencies**

Right, let me quickly scan through the Rust codebase and determine if `xarray` or `sheaf` are being leveraged anywhere else. It’s important to identify all instances, not just the immediately obvious usage. We need to be thorough. I'll mentally note any modules or functions that might be relevant for deeper investigation. This is the first step in understanding the scope of potential impacts if we change either of these libraries. Any alternative implementations? Compatibility issues? A comprehensive dependency check is paramount before making any assumptions. Gotta be proactive about potential ripple effects.



22/2 2026/11/25 13:53 tool grepper
0m Args:
{
  "Expression": "kernel::mm::sheaf|kernel::xarray"
}

Results:
{
  "Output": "rust/kernel/mm/sheaf.rs-47-//! use kernel::c_str;\nrust/kernel/mm/sheaf.rs:48://! use kernel::mm::sheaf::{KMemCacheHandle, KMemCacheInit, Sheaf, SBox};\nrust/kernel/mm/sheaf.rs-49-//! use kernel::prelude::*;\n--\nrust/kernel/mm/sheaf.rs=363=    fn drop(\u0026mut self) {\n--\nrust/kernel/mm/sheaf.rs-385-/// ```\nrust/kernel/mm/sheaf.rs:386:/// use kernel::mm::sheaf::KMemCacheInit;\nrust/kernel/mm/sheaf.rs-387-/// use kernel::prelude::*;\n--\nrust/kernel/xarray.rs=83=unsafe impl Send for XArrayNode {}\nrust/kernel/xarray.rs-84-\nrust/kernel/xarray.rs:85:impl kernel::mm::sheaf::KMemCacheInit\u003cXArrayNode\u003e for XArrayNode {\nrust/kernel/xarray.rs-86-    fn init() -\u003e impl Init\u003cSelf, Infallible\u003e {\n--\nrust/kernel/xarray.rs-116-/// use kernel::alloc::KBox;\nrust/kernel/xarray.rs:117:/// use kernel::xarray::{AllocKind, XArray};\nrust/kernel/xarray.rs-118-///\n"
}

23/2 2026/11/25 13:53 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 47484
							output: 19
							thoughts: 33
						

Thoughts:
Here's my thought process, as if I were considering those ideas:

**Investigating Potential Dependencies: xarray and Sheaf**

Okay, before diving too deep, I need to take a quick step back and map the potential impact of changes I'm considering. The key here is to determine *who* might be using these specific data structures. My initial target is `kernel::xarray` and `kernel::mm::sheaf`. These are core components, so any modifications could have wide-ranging effects.

First, I need to check the obvious places. I'll search for direct dependencies on these in the driver code, the filesystem code, and, of course, within the Rust kernel code itself. I will start with a grep to search these areas for any uses of `kernel::xarray` or `kernel::mm::sheaf`. I am looking for the common usages, struct member definitions, function parameters, and direct instantiations. I'll need to look at both the kernel space and any associated user space interactions if possible.

My approach will be methodical. It's about minimizing the risk of a regression. Understanding the *current* usage is paramount. The goal is to fully understand the scope of influence before I go further. I have to avoid making assumptions, and ensure I am not accidentally breaking something that is not immediately obvious.



24/2 2026/11/25 13:53 tool grepper
0m Args:
{
  "Expression": "xarray::XArray"
}

Results:
{
  "Output": "no matches"
}

25/2 2026/11/25 13:53 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 47832
							output: 23
							thoughts: 762
						

Thoughts:
**Analyzing the Radix Tree and XArray Changes**

Okay, hold on a second! Even if the `rust/kernel/xarray` implementation isn't directly used by any in-tree drivers yet, I need to understand the implications of these C code modifications. This is crucial! Let's dive in and examine the C changes very carefully.

First, in `lib/radix-tree.c`, I see a significant change in the `radix_tree_init` function. Specifically, the creation of `radix_tree_node_cachep` is modified to include a `kmem_cache_args` structure. This structure introduces `.sheaf_capacity = 64`.

Next, I see some inline functions, `xa_zero_to_null` and `xas_result`, are introduced in `include/linux/xarray.h`. These look like small utility functions, nothing too alarming on their own.

Then, there's the header file `include/linux/radix-tree.h`, which just declares `void radix_tree_node_ctor(void *arg);`. That's a constructor for the radix tree node, which I expected to be there.

Finally, in `mm/slub.c` I see some exports of functions like `kmem_cache_prefill_sheaf`, `kmem_cache_return_sheaf`, and others related to SLUB sheaf management. That's interesting, but not immediately a "problem".

Wait a minute... back to `radix_tree_init`. Every single kernel boot calls that function, right? Now, by specifying `.sheaf_capacity = 64` when creating `radix_tree_node_cachep`, what's *actually* happening in the kernel? Aha! Every single `radix_tree_node` allocation throughout the *entire* kernel now utilizes SLUB's sheaf caching layer! Is that reachable? Is this something that's actually *used*? YES! `radix_tree_node_cachep` is used *whenever* a radix tree or xarray in the kernel grows and needs a new node! This change has the potential to impact many areas of the kernel! So when does xarray allocate a node? This is where I need to dig deeper. I need to trace where `radix_tree_node_cachep` is used. This is significant.



26/2 2026/11/25 13:53 tool grepper
0m Args:
{
  "Expression": "radix_tree_node_cachep"
}

Results:
{
  "Output": "lib/radix-tree.c-34- */\nlib/radix-tree.c:35:struct kmem_cache *radix_tree_node_cachep;\nlib/radix-tree.c:36:EXPORT_SYMBOL(radix_tree_node_cachep);\nlib/radix-tree.c-37-\n--\nlib/radix-tree.c=234=radix_tree_node_alloc(gfp_t gfp_mask, struct radix_tree_node *parent,\n--\nlib/radix-tree.c-253-\t\t */\nlib/radix-tree.c:254:\t\tret = kmem_cache_alloc(radix_tree_node_cachep,\nlib/radix-tree.c-255-\t\t\t\t       gfp_mask | __GFP_NOWARN);\n--\nlib/radix-tree.c-276-\t}\nlib/radix-tree.c:277:\tret = kmem_cache_alloc(radix_tree_node_cachep, gfp_mask);\nlib/radix-tree.c-278-out:\n--\nlib/radix-tree.c=291=void radix_tree_node_rcu_free(struct rcu_head *head)\n--\nlib/radix-tree.c-304-\nlib/radix-tree.c:305:\tkmem_cache_free(radix_tree_node_cachep, node);\nlib/radix-tree.c-306-}\n--\nlib/radix-tree.c=323=static __must_check int __radix_tree_preload(gfp_t gfp_mask, unsigned nr)\n--\nlib/radix-tree.c-338-\t\tlocal_unlock(\u0026radix_tree_preloads.lock);\nlib/radix-tree.c:339:\t\tnode = kmem_cache_alloc(radix_tree_node_cachep, gfp_mask);\nlib/radix-tree.c-340-\t\tif (node == NULL)\n--\nlib/radix-tree.c-348-\t\t} else {\nlib/radix-tree.c:349:\t\t\tkmem_cache_free(radix_tree_node_cachep, node);\nlib/radix-tree.c-350-\t\t}\n--\nlib/radix-tree.c=1579=static int radix_tree_cpu_dead(unsigned int cpu)\n--\nlib/radix-tree.c-1588-\t\trtp-\u003enodes = node-\u003eparent;\nlib/radix-tree.c:1589:\t\tkmem_cache_free(radix_tree_node_cachep, node);\nlib/radix-tree.c-1590-\t\trtp-\u003enr--;\n--\nlib/radix-tree.c=1595=void __init radix_tree_init(void)\n--\nlib/radix-tree.c-1607-\nlib/radix-tree.c:1608:\tradix_tree_node_cachep = kmem_cache_create(\nlib/radix-tree.c-1609-\t\t\"radix_tree_node\", sizeof(struct radix_tree_node), \u0026args,\n--\nlib/radix-tree.h=5=struct rcu_head;\nlib/radix-tree.h-6-\nlib/radix-tree.h:7:extern struct kmem_cache *radix_tree_node_cachep;\nlib/radix-tree.h-8-extern void radix_tree_node_rcu_free(struct rcu_head *head);\n--\nlib/xarray.c=301=bool xas_nomem(struct xa_state *xas, gfp_t gfp)\n--\nlib/xarray.c-308-\t\tgfp |= __GFP_ACCOUNT;\nlib/xarray.c:309:\txas-\u003exa_alloc = kmem_cache_alloc_lru(radix_tree_node_cachep, xas-\u003exa_lru, gfp);\nlib/xarray.c-310-\tif (!xas-\u003exa_alloc)\n--\nlib/xarray.c=328=static bool __xas_nomem(struct xa_state *xas, gfp_t gfp)\n--\nlib/xarray.c-340-\t\txas_unlock_type(xas, lock_type);\nlib/xarray.c:341:\t\txas-\u003exa_alloc = kmem_cache_alloc_lru(radix_tree_node_cachep, xas-\u003exa_lru, gfp);\nlib/xarray.c-342-\t\txas_lock_type(xas, lock_type);\nlib/xarray.c-343-\t} else {\nlib/xarray.c:344:\t\txas-\u003exa_alloc = kmem_cache_alloc_lru(radix_tree_node_cachep, xas-\u003exa_lru, gfp);\nlib/xarray.c-345-\t}\n--\nlib/xarray.c=362=static void *xas_alloc(struct xa_state *xas, unsigned int shift)\n--\nlib/xarray.c-377-\nlib/xarray.c:378:\t\tnode = kmem_cache_alloc_lru(radix_tree_node_cachep, xas-\u003exa_lru, gfp);\nlib/xarray.c-379-\t\tif (!node) {\n--\nlib/xarray.c=1040=void xas_split_alloc(struct xa_state *xas, void *entry, unsigned int order,\n--\nlib/xarray.c-1056-\nlib/xarray.c:1057:\t\tnode = kmem_cache_alloc_lru(radix_tree_node_cachep, xas-\u003exa_lru, gfp);\nlib/xarray.c-1058-\t\tif (!node)\n--\nlib/xarray.c=1173=void xas_try_split(struct xa_state *xas, void *entry, unsigned int order)\n--\nlib/xarray.c-1211-\t\tif (!child) {\nlib/xarray.c:1212:\t\t\tchild = kmem_cache_alloc_lru(radix_tree_node_cachep,\nlib/xarray.c-1213-\t\t\t\t\t\t     xas-\u003exa_lru, gfp);\n--\nrust/bindings/bindings_helper.h=142=const size_t RUST_CONST_HELPER_XA_CHUNK_SIZE = XA_CHUNK_SIZE;\nrust/bindings/bindings_helper.h:143:extern struct kmem_cache *radix_tree_node_cachep;\nrust/bindings/bindings_helper.h-144-\n--\nrust/kernel/mm/sheaf.rs=181=    fn as_raw(\u0026self) -\u003e *mut bindings::kmem_cache {\n--\nrust/kernel/mm/sheaf.rs-187-    /// This is useful for wrapping a C-initialized static `kmem_cache`, such as\nrust/kernel/mm/sheaf.rs:188:    /// the global `radix_tree_node_cachep` used by XArrays.\nrust/kernel/mm/sheaf.rs-189-    ///\n--\nrust/kernel/xarray.rs-58-///\nrust/kernel/xarray.rs:59:/// This provides access to the kernel's `radix_tree_node_cachep`, which is the\nrust/kernel/xarray.rs-60-/// slab cache used for allocating internal XArray nodes. This cache can be used\n--\nrust/kernel/xarray.rs=62=pub fn xarray_kmem_cache() -\u003e \u0026'static KMemCache\u003cXArrayNode\u003e {\nrust/kernel/xarray.rs:63:    // SAFETY: `radix_tree_node_cachep` is a valid, statically initialized\nrust/kernel/xarray.rs-64-    // kmem_cache that remains valid for the lifetime of the kernel. The cache\nrust/kernel/xarray.rs-65-    // is configured for `xa_node` objects which match our `XArrayNode` type.\nrust/kernel/xarray.rs:66:    unsafe { KMemCache::from_raw(bindings::radix_tree_node_cachep) }\nrust/kernel/xarray.rs-67-}\n--\nrust/kernel/xarray.rs=621=fn free_xa_alloc(state: \u0026mut bindings::xa_state) {\n--\nrust/kernel/xarray.rs-624-        // - `xa_alloc` is only set via `SBox::into_ptr()` in `insert()` where\nrust/kernel/xarray.rs:625:        //   the node comes from an `XArraySheaf` backed by `radix_tree_node_cachep`.\nrust/kernel/xarray.rs-626-        // - `xa_alloc` points to a valid, initialized `XArrayNode`.\n--\nrust/kernel/xarray.rs-630-            SBox::\u003cXArrayNode\u003e::static_from_ptr(\nrust/kernel/xarray.rs:631:                bindings::radix_tree_node_cachep,\nrust/kernel/xarray.rs-632-                state.xa_alloc.cast(),\n"
}

27/2 2026/11/25 13:53 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 51446
							output: 32
							thoughts: 338
						

Thoughts:
**Analyzing Radix Tree Node Allocation**

Okay, here's what's going on. I see that `radix_tree_node_cachep` is *everywhere* in the standard XArray and Radix Tree allocation paths within the C Linux kernel. Specifically, it's used in `radix_tree_node_alloc`, `radix_tree_node_rcu_free`, `__radix_tree_preload`, and the `xas_*` functions for memory management: `xas_nomem`, `__xas_nomem`, `xas_alloc`, `xas_split_alloc`, and `xas_try_split`. Makes perfect sense; it's the core of how these trees manage their node memory.

And, if I'm reading this correctly, `radix_tree_init()` sets up `radix_tree_node_cachep` using a `kmem_cache_args` struct. The configuration includes a constructor `radix_tree_node_ctor` and a `sheaf_capacity` of 64.  Then, `kmem_cache_create` is called to actually create the cache. The flags `SLAB_PANIC` and `SLAB_RECLAIM_ACCOUNT` are also there, which are important for stability and accounting.

Now, the important question is: what actually happens when `kmem_cache_alloc_lru(radix_tree_node_cachep, ...)` or just `kmem_cache_alloc(radix_tree_node_cachep, ...)` is called? I need to understand how those functions interact with the SLUB allocator to really grasp what's happening. I'm going to head over to `mm/slub.c` to examine the implementation of `kmem_cache_alloc` and `kmem_cache_alloc_lru`. That's where the magic happens.



28/2 2026/11/25 13:54 tool grepper
0m Args:
{
  "Expression": "kmem_cache_alloc_lru",
  "PathPrefixes": [
    "mm/"
  ]
}

Results:
{
  "Output": "mm/slub.c=5053=EXPORT_SYMBOL(kmem_cache_alloc_noprof);\nmm/slub.c-5054-\nmm/slub.c:5055:void *kmem_cache_alloc_lru_noprof(struct kmem_cache *s, struct list_lru *lru,\nmm/slub.c-5056-\t\t\t   gfp_t gfpflags)\n--\nmm/slub.c-5071-}\nmm/slub.c:5072:EXPORT_SYMBOL(kmem_cache_alloc_lru_noprof);\nmm/slub.c-5073-\n"
}

29/2 2026/11/25 13:54 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 52407
							output: 35
							thoughts: 36
						

Thoughts:
Okay, let's dive into this. Here's my thought process on the matter:

**Delving into SLUB Allocation: A Deep Dive**

Alright, time to get my hands dirty. I need to understand how these SLUB allocators work at a granular level. The first function I'm going to examine is `kmem_cache_alloc_lru_noprof`. I know this is a key entry point, and the 'noprof' suggests we're dealing with an allocation path that skips profiling overhead – likely a performance-critical path. I need to see how the LRU element fits in to this, or if it really does... I guess this is where it differs.

From there I'll follow the trail into `slab_alloc_node` in `mm/slub.c`. This is where the core allocation logic resides, handling the per-node allocation. I expect this function will illuminate the actual mechanics of picking a slab, finding a free object within it, and any necessary cache management along the way. I'm especially interested in the synchronization primitives used and the overall data structures involved: the slab caches, slabs, objects. I'm going to have to watch out for allocation strategies here: are they using per-CPU lists, per-node lists, or something else entirely? And what kind of lock contention might I expect?

This should give me a solid picture of the SLUB allocation flow, hopefully enough to have a solid answer.



30/2 2026/11/25 13:55 tool read-file
0m Args:
{
  "File": "mm/slub.c",
  "FirstLine": 5000,
  "LineCount": 75
}

Results:
{
  "Contents": "5000:\t *\n5001:\t * The fastpath works by first checking if the lockless freelist can be used.\n5002:\t * If not then __slab_alloc is called for slow processing.\n5003:\t *\n5004:\t * Otherwise we can simply pick the next object from the lockless free list.\n5005:\t */\n5006:\tstatic __fastpath_inline void *slab_alloc_node(struct kmem_cache *s,\n5007:\t\t\tgfp_t gfpflags, int node, const struct slab_alloc_context *ac)\n5008:\t{\n5009:\t\tvoid *object;\n5010:\t\n5011:\t\ts = slab_pre_alloc_hook(s, gfpflags);\n5012:\t\tif (unlikely(!s))\n5013:\t\t\treturn NULL;\n5014:\t\n5015:\t\tobject = kfence_alloc(s, ac-\u003eorig_size, gfpflags);\n5016:\t\tif (unlikely(object))\n5017:\t\t\tgoto out;\n5018:\t\n5019:\t\tnode = apply_strict_numa_policy(node);\n5020:\t\n5021:\t\tobject = alloc_from_pcs(s, gfpflags, ac-\u003ealloc_flags, node);\n5022:\t\n5023:\t\tif (unlikely(!object))\n5024:\t\t\tobject = ___slab_alloc(s, gfpflags, node, ac);\n5025:\t\n5026:\t\tmaybe_wipe_obj_freeptr(s, object);\n5027:\t\n5028:\tout:\n5029:\t\t/*\n5030:\t\t * In case this fails due to memcg_slab_post_alloc_hook(),\n5031:\t\t * object is set to NULL\n5032:\t\t */\n5033:\t\tslab_post_alloc_hook(s, gfpflags, 1, \u0026object, ac);\n5034:\t\n5035:\t\treturn object;\n5036:\t}\n5037:\t\n5038:\tvoid *kmem_cache_alloc_noprof(struct kmem_cache *s, gfp_t gfpflags)\n5039:\t{\n5040:\t\tvoid *ret;\n5041:\t\tconst struct slab_alloc_context ac = {\n5042:\t\t\t.caller_addr = _RET_IP_,\n5043:\t\t\t.orig_size = s-\u003eobject_size,\n5044:\t\t\t.alloc_flags = SLAB_ALLOC_DEFAULT,\n5045:\t\t};\n5046:\t\n5047:\t\tret = slab_alloc_node(s, gfpflags, NUMA_NO_NODE, \u0026ac);\n5048:\t\n5049:\t\ttrace_kmem_cache_alloc(_RET_IP_, ret, s, gfpflags, NUMA_NO_NODE);\n5050:\t\n5051:\t\treturn ret;\n5052:\t}\n5053:\tEXPORT_SYMBOL(kmem_cache_alloc_noprof);\n5054:\t\n5055:\tvoid *kmem_cache_alloc_lru_noprof(struct kmem_cache *s, struct list_lru *lru,\n5056:\t\t\t\t   gfp_t gfpflags)\n5057:\t{\n5058:\t\tvoid *ret;\n5059:\t\tconst struct slab_alloc_context ac = {\n5060:\t\t\t.caller_addr = _RET_IP_,\n5061:\t\t\t.orig_size = s-\u003eobject_size,\n5062:\t\t\t.alloc_flags = SLAB_ALLOC_DEFAULT,\n5063:\t\t\t.lru = lru,\n5064:\t\t};\n5065:\t\n5066:\t\tret = slab_alloc_node(s, gfpflags, NUMA_NO_NODE, \u0026ac);\n5067:\t\n5068:\t\ttrace_kmem_cache_alloc(_RET_IP_, ret, s, gfpflags, NUMA_NO_NODE);\n5069:\t\n5070:\t\treturn ret;\n5071:\t}\n5072:\tEXPORT_SYMBOL(kmem_cache_alloc_lru_noprof);\n5073:\t\n5074:\tbool kmem_cache_charge(void *objp, gfp_t gfpflags)\n"
}

31/2 2026/11/25 13:55 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 53949
							output: 21
							thoughts: 1724
						

Thoughts:
**Diving Deep into the `radix_tree_node_cachep` Transformation**

Okay, so I'm looking at this change to `radix_tree_node_cachep` and it's hitting me right in the sweet spot of my expertise. I'm seeing that the introduction of `sheaf_capacity = 64` is *way* more impactful than it might initially seem. Before this change, allocations and frees of `radix_tree_node` (that crucial building block for radix trees and xarrays) were chugging through the standard SLUB slowpath via `___slab_alloc` and `__slab_free`. Now, with sheaves enabled, everything goes through `alloc_from_pcs` and `free_to_pcs`.

This is *massive*. Radix trees and xarrays are everywhere in the kernel, constantly being allocated and freed. The page cache, file I/O, process creation, networking – it's all touching these structures. Now, they're all directly benefiting from per-CPU caching.

Wait, the Rust side! It's clear that this is where this change originates from, with the `XArraySheaf` and `kmem_cache_prefill_sheaf` call requiring `sheaf_capacity`. The `radix_tree_node_ctor` was exported and  `sheaf_capacity = 64` was set, explicitly for the Rust XArray preallocation. If `s->sheaf_capacity == 0`, every sheaf prefill would be considered oversize!

But let's not lose sight of the bigger picture. This impacts the *entire* kernel. Any operation involving xarrays or radix trees will now utilize per-CPU caching, a big win.

And the RCU implications? It's intriguing. I see that RCU freeing uses `kmem_cache_free` through `radix_tree_node_rcu_free`. This means that `radix_tree_node`s freed via RCU are now being placed into the per-CPU sheaves through `free_to_pcs`. That node can then likely be immediately reallocated by `alloc_from_pcs` on that CPU, after the RCU grace period. This will dramatically improve performance for the kernel.

What about direct calls to `kmem_cache_free`?  Well, `__radix_tree_preload`, `radix_tree_cpu_dead`, and the Rust `SBox::drop` are all using it. This confirms a significant shift in memory management for these structures.

And the initialization itself, `radix_tree_init()`, confirms that this is happening early in boot.

This change is a fundamental shift in how the kernel handles these critical data structures. It's a performance upgrade that's more significant than I initially appreciated.



32/2 2026/11/25 13:55 tool grepper
0m Args:
{
  "Expression": "radix_tree_init\\("
}

Results:
{
  "Output": "include/linux/radix-tree.h=241=int radix_tree_maybe_preload(gfp_t gfp_mask);\ninclude/linux/radix-tree.h:242:void radix_tree_init(void);\ninclude/linux/radix-tree.h-243-void *radix_tree_tag_set(struct radix_tree_root *,\n--\ninit/main.c=1044=void start_kernel(void)\n--\ninit/main.c-1123-\t\tlocal_irq_disable();\ninit/main.c:1124:\tradix_tree_init();\ninit/main.c-1125-\n--\nlib/radix-tree.c=1579=static int radix_tree_cpu_dead(unsigned int cpu)\n--\nlib/radix-tree.c-1594-\nlib/radix-tree.c:1595:void __init radix_tree_init(void)\nlib/radix-tree.c-1596-{\n--\ntools/testing/radix-tree/idr-test.c=621=int __weak main(void)\n--\ntools/testing/radix-tree/idr-test.c-623-\trcu_register_thread();\ntools/testing/radix-tree/idr-test.c:624:\tradix_tree_init();\ntools/testing/radix-tree/idr-test.c-625-\tidr_checks();\n--\ntools/testing/radix-tree/main.c=284=int main(int argc, char **argv)\n--\ntools/testing/radix-tree/main.c-304-\trcu_register_thread();\ntools/testing/radix-tree/main.c:305:\tradix_tree_init();\ntools/testing/radix-tree/main.c-306-\n--\ntools/testing/radix-tree/multiorder.c=286=int __weak main(int argc, char **argv)\n--\ntools/testing/radix-tree/multiorder.c-295-\trcu_register_thread();\ntools/testing/radix-tree/multiorder.c:296:\tradix_tree_init();\ntools/testing/radix-tree/multiorder.c-297-\tmultiorder_checks();\n--\ntools/testing/radix-tree/xarray.c=19=int __weak main(void)\n--\ntools/testing/radix-tree/xarray.c-21-\trcu_register_thread();\ntools/testing/radix-tree/xarray.c:22:\tradix_tree_init();\ntools/testing/radix-tree/xarray.c-23-\txarray_tests();\n"
}

33/2 2026/11/25 13:55 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 57005
							output: 35
							thoughts: 159
						

Thoughts:
**Initial Observations and Comparison of Radix and Maple Trees**

Okay, first things first. I've noticed `radix_tree_init()` is being called pretty early – right from `start_kernel()`! That's a key point to remember. And now I see that the `radix_tree_node_cachep` has a `.sheaf_capacity` of 64. Interesting.

Now, I'm getting curious about the relationship here. Did the maple tree code undergo a similar change recently? It's worth comparing the approaches. Let's dig into `lib/maple_tree.c`. Ah, there it is: `maple_tree_init()` has a `.sheaf_capacity` of 32. Okay, so different capacities.

I need to understand what triggered the change for the maple tree, so let's use `git log` and search for "sheaf_capacity" in that file. That should point me to the commit(s) where `.sheaf_capacity = 32` was introduced. Or, if `git` doesn't give me what I need, maybe grepping will help. This comparison will hopefully illuminate the rationale behind the sheaf mechanism in the maple tree and provide context for the radix tree's behavior. This is an important detail for performance and memory optimization.



34/2 2026/11/25 13:56 tool grepper
0m Args:
{
  "Expression": "maple_tree_init",
  "PathPrefixes": [
    "lib/maple_tree.c"
  ]
}

Results:
{
  "Output": "lib/maple_tree.c=5721=bool mas_nomem_nofail(struct ma_state *mas, unsigned long index,\n--\nlib/maple_tree.c-5742-\nlib/maple_tree.c:5743:void __init maple_tree_init(void)\nlib/maple_tree.c-5744-{\n"
}

35/2 2026/11/25 13:56 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 57589
							output: 37
							thoughts: 22
						

Thoughts:
Here's a summary of my thought process, as requested:

**Diving into `lib/maple_tree.c`**

Okay, time to get to the heart of the matter. I need to understand how this code is behaving, and my gut feeling points me towards a specific section. Let's start with `lib/maple_tree.c`, specifically around line 5743. I'm assuming that this area might be related to the issue I'm investigating. I'll need to carefully parse the surrounding code to grasp the context and logic being implemented there.



36/2 2026/11/25 13:56 tool read-file
0m Args:
{
  "File": "lib/maple_tree.c",
  "FirstLine": 5740,
  "LineCount": 25
}

Results:
{
  "Contents": "5740:\t\treturn true;\n5741:\t}\n5742:\t\n5743:\tvoid __init maple_tree_init(void)\n5744:\t{\n5745:\t\tstruct kmem_cache_args args = {\n5746:\t\t\t.align  = sizeof(struct maple_node),\n5747:\t\t\t.sheaf_capacity = 32,\n5748:\t\t};\n5749:\t\n5750:\t\tmaple_node_cache = kmem_cache_create(\"maple_node\",\n5751:\t\t\t\tsizeof(struct maple_node), \u0026args,\n5752:\t\t\t\tSLAB_PANIC);\n5753:\t}\n5754:\t\n5755:\t/**\n5756:\t * mtree_load() - Load a value stored in a maple tree\n5757:\t * @mt: The maple tree\n5758:\t * @index: The index to load\n5759:\t *\n5760:\t * Return: the entry or %NULL\n5761:\t */\n5762:\tvoid *mtree_load(struct maple_tree *mt, unsigned long index)\n5763:\t{\n5764:\t\tMA_STATE(mas, mt, index, index);\n"
}

37/2 2026/11/25 13:56 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 58118
							output: 18
							thoughts: 87
						

Thoughts:
Okay, let's dive into this Rust kernel code. My immediate focus is on understanding its integration, so I'm starting with `rust/kernel/xarray.rs` and `rust/kernel/mm/sheaf.rs`. My initial question is fundamental: **How deeply is Rust integrated? Is this a fully baked feature, or an experimental add-on?**

I'm thinking, "Is Rust's use conditional? Let's check the standard kernel configurations for `CONFIG_RUST`." That will give me a first indication. Then, I need to look for examples of how Rust is actually *being* used. I'll scan the `samples/rust/` directory, or the `rust/` directory to see what dependencies, tests, or drivers are implemented in Rust. That will show me the real scope of its application. It is important to see the 'where' it is being used, for example, is it just in a corner, or spread throughout.



38/2 2026/11/25 13:56 tool grepper
0m Args:
{
  "Expression": "depends on RUST"
}

Results:
{
  "Output": "arch/Kconfig=990=config HAVE_CFI_ICALL_NORMALIZE_INTEGERS_RUSTC\n--\narch/Kconfig-994-\t# With GCOV/KASAN we need this fix: https://github.com/rust-lang/rust/pull/129373\narch/Kconfig:995:\tdepends on RUSTC_LLVM_VERSION \u003e= 190103 || \\\narch/Kconfig-996-\t\t(!GCOV_KERNEL \u0026\u0026 !KASAN_GENERIC \u0026\u0026 !KASAN_SW_TAGS)\n--\narch/loongarch/Kconfig=344=config RUSTC_HAS_ANNOTATE_TABLEJUMP\narch/loongarch/Kconfig:345:\tdepends on RUST\narch/loongarch/Kconfig-346-\tdef_bool $(rustc-option,-Cllvm-args=--loongarch-annotate-tablejump)\n--\ndrivers/android/Kconfig=4=config ANDROID_BINDER_IPC_RUST\n--\ndrivers/android/Kconfig-7-\tdepends on NET\ndrivers/android/Kconfig:8:\tdepends on RUST\ndrivers/android/Kconfig-9-\tdefault n\n--\ndrivers/base/firmware_loader/Kconfig=38=config RUST_FW_LOADER_ABSTRACTIONS\ndrivers/base/firmware_loader/Kconfig-39-\tbool \"Rust Firmware Loader abstractions\"\ndrivers/base/firmware_loader/Kconfig:40:\tdepends on RUST\ndrivers/base/firmware_loader/Kconfig-41-\tselect FW_LOADER\n--\ndrivers/block/rnull/Kconfig=5=config BLK_DEV_RUST_NULL\ndrivers/block/rnull/Kconfig-6-\ttristate \"Rust null block driver (Experimental)\"\ndrivers/block/rnull/Kconfig:7:\tdepends on RUST \u0026\u0026 CONFIGFS_FS\ndrivers/block/rnull/Kconfig-8-\thelp\n--\ndrivers/fwctl/Kconfig=13=config RUST_FWCTL_ABSTRACTIONS\ndrivers/fwctl/Kconfig-14-\tbool \"Rust fwctl abstractions\"\ndrivers/fwctl/Kconfig:15:\tdepends on RUST \u0026\u0026 FWCTL=y\ndrivers/fwctl/Kconfig-16-\thelp\n--\ndrivers/gpu/drm/nova/Kconfig=1=config DRM_NOVA\n--\ndrivers/gpu/drm/nova/Kconfig-5-\tdepends on PCI\ndrivers/gpu/drm/nova/Kconfig:6:\tdepends on RUST\ndrivers/gpu/drm/nova/Kconfig-7-\tdepends on !CPU_BIG_ENDIAN\n--\ndrivers/gpu/drm/tyr/Kconfig=3=config DRM_TYR\n--\ndrivers/gpu/drm/tyr/Kconfig-5-\tdepends on DRM=y\ndrivers/gpu/drm/tyr/Kconfig:6:\tdepends on RUST\ndrivers/gpu/drm/tyr/Kconfig-7-\tdepends on ARM || ARM64 || COMPILE_TEST\n--\ndrivers/gpu/nova-core/Kconfig=1=config NOVA_CORE\n--\ndrivers/gpu/nova-core/Kconfig-4-\tdepends on PCI\ndrivers/gpu/nova-core/Kconfig:5:\tdepends on RUST\ndrivers/gpu/nova-core/Kconfig-6-\tdepends on !CPU_BIG_ENDIAN\n--\ndrivers/net/phy/Kconfig=65=config RUST_PHYLIB_ABSTRACTIONS\ndrivers/net/phy/Kconfig-66-        bool \"Rust PHYLIB abstractions support\"\ndrivers/net/phy/Kconfig:67:        depends on RUST\ndrivers/net/phy/Kconfig-68-        depends on PHYLIB=y\n--\ndrivers/net/phy/Kconfig=145=config AMCC_QT2025_PHY\ndrivers/net/phy/Kconfig-146-\ttristate \"AMCC QT2025 PHY\"\ndrivers/net/phy/Kconfig:147:\tdepends on RUST_PHYLIB_ABSTRACTIONS\ndrivers/net/phy/Kconfig:148:\tdepends on RUST_FW_LOADER_ABSTRACTIONS\ndrivers/net/phy/Kconfig-149-\thelp\n--\ndrivers/net/phy/Kconfig=160=config AX88796B_RUST_PHY\ndrivers/net/phy/Kconfig-161-\tbool \"Rust reference driver for Asix PHYs\"\ndrivers/net/phy/Kconfig:162:\tdepends on RUST_PHYLIB_ABSTRACTIONS \u0026\u0026 AX88796B_PHY\ndrivers/net/phy/Kconfig-163-\thelp\n--\ndrivers/pwm/Kconfig=773=config PWM_TH1520\n--\ndrivers/pwm/Kconfig-775-\tdepends on ARCH_THEAD || COMPILE_TEST\ndrivers/pwm/Kconfig:776:\tdepends on RUST\ndrivers/pwm/Kconfig-777-\tdepends on HAS_IOMEM \u0026\u0026 COMMON_CLK\n--\ndrivers/pwm/Kconfig=843=config PWM_XILINX\n--\ndrivers/pwm/Kconfig-858-\tbool\ndrivers/pwm/Kconfig:859:\tdepends on RUST\ndrivers/pwm/Kconfig-860-\thelp\n--\ndrivers/tty/serdev/Kconfig=12=config RUST_SERIAL_DEV_BUS_ABSTRACTIONS\ndrivers/tty/serdev/Kconfig-13-\tbool \"Rust Serial device bus abstractions\"\ndrivers/tty/serdev/Kconfig:14:\tdepends on RUST\ndrivers/tty/serdev/Kconfig-15-\tselect SERIAL_DEV_BUS\n--\ninit/Kconfig=2059=config RUST\n--\ninit/Kconfig-2061-\tdepends on HAVE_RUST\ninit/Kconfig:2062:\tdepends on RUST_IS_AVAILABLE\ninit/Kconfig-2063-\tselect EXTENDED_MODVERSIONS if MODVERSIONS\n--\ninit/Kconfig=2087=config RUSTC_VERSION_TEXT\ninit/Kconfig-2088-\tstring\ninit/Kconfig:2089:\tdepends on RUST\ninit/Kconfig-2090-\tdefault \"$(RUSTC_VERSION_TEXT)\"\n--\ninit/Kconfig=2094=config BINDGEN_VERSION_TEXT\ninit/Kconfig-2095-\tstring\ninit/Kconfig:2096:\tdepends on RUST\ninit/Kconfig-2097-\tdefault \"$(shell,$(BINDGEN) --version 2\u003e/dev/null)\"\n--\nlib/Kconfig.debug=2691=config FIND_BIT_BENCHMARK_RUST\nlib/Kconfig.debug-2692-\ttristate \"Test find_bit functions in Rust\"\nlib/Kconfig.debug:2693:\tdepends on RUST\nlib/Kconfig.debug-2694-\thelp\n--\nlib/Kconfig.debug=3616=config RUST_DEBUG_ASSERTIONS\nlib/Kconfig.debug-3617-\tbool \"Debug assertions\"\nlib/Kconfig.debug:3618:\tdepends on RUST\nlib/Kconfig.debug-3619-\thelp\n--\nlib/Kconfig.debug=3631=config RUST_OVERFLOW_CHECKS\n--\nlib/Kconfig.debug-3633-\tdefault y\nlib/Kconfig.debug:3634:\tdepends on RUST\nlib/Kconfig.debug-3635-\thelp\n--\nlib/Kconfig.debug=3646=config RUST_BUILD_ASSERT_ALLOW\nlib/Kconfig.debug-3647-\tbool \"Allow unoptimized build-time assertions\"\nlib/Kconfig.debug:3648:\tdepends on RUST\nlib/Kconfig.debug-3649-\thelp\n--\nlib/Kconfig.debug=3662=config RUST_KERNEL_DOCTESTS\nlib/Kconfig.debug-3663-\tbool \"Doctests for the `kernel` crate\" if !KUNIT_ALL_TESTS\nlib/Kconfig.debug:3664:\tdepends on RUST \u0026\u0026 KUNIT=y\nlib/Kconfig.debug-3665-\tdefault KUNIT_ALL_TESTS\n--\nlib/Kconfig.debug=3675=config RUST_INLINE_HELPERS\nlib/Kconfig.debug-3676-\tbool \"Inline C helpers into Rust code (EXPERIMENTAL)\"\nlib/Kconfig.debug:3677:\tdepends on RUST \u0026\u0026 RUSTC_CLANG_LLVM_COMPATIBLE\nlib/Kconfig.debug-3678-\tdepends on EXPERT\n--\nsamples/rust/Kconfig=3=menuconfig SAMPLES_RUST\nsamples/rust/Kconfig-4-\tbool \"Rust samples\"\nsamples/rust/Kconfig:5:\tdepends on RUST\nsamples/rust/Kconfig-6-\thelp\n--\nsecurity/Kconfig.hardening=254=config RUST_BITMAP_HARDENED\nsecurity/Kconfig.hardening-255-\tbool \"Check integrity of bitmap Rust API\"\nsecurity/Kconfig.hardening:256:\tdepends on RUST\nsecurity/Kconfig.hardening-257-\thelp\n"
}

39/2 2026/11/25 13:56 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 60718
							output: 33
							thoughts: 47
						

Thoughts:
Okay, here's my summary, considering my expertise:

**Binder IPC and Data Structures - A Quick Check**

Right, before diving too deep, I need to take a mental step back. Let's make absolutely sure we're on the right track. My immediate thought is, "Wait, before committing to a particular direction, a sanity check is needed!" Specifically, I need to verify how `ANDROID_BINDER_IPC_RUST` handles its data structures. Does the Rust implementation, at this point, employ `XArray` or `sheaf`? Those are the two primary candidates in this area. A quick scan of the code should provide the answer, and hopefully, that’ll give me the information I require to progress to the next stage. So, I must investigate!



40/2 2026/11/25 13:57 tool grepper
0m Args:
{
  "Expression": "XArray|xarray|sheaf",
  "PathPrefixes": [
    "drivers/android/"
  ]
}

Results:
{
  "Output": "drivers/android/binder/rust_binderfs.c-30-#include \u003clinux/user_namespace.h\u003e\ndrivers/android/binder/rust_binderfs.c:31:#include \u003clinux/xarray.h\u003e\ndrivers/android/binder/rust_binderfs.c-32-#include \u003cuapi/asm-generic/errno-base.h\u003e\n"
}

41/2 2026/11/25 13:57 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 61061
							output: 22
							thoughts: 25
						

Thoughts:
Here's my thought process, as if I were considering this myself:

**Investigating Binder Driver Rust Code**

Okay, so I need to get a handle on the Rust code within the Android driver framework. My initial thought is to dive right into the `drivers/android/binder/` directory. That's the logical starting point for anything related to Binder, and it's where I'd expect the core Rust implementation to reside, if there is one. The real question is, what Rust files have been added into `drivers/android/`? Need to start checking.



42/2 2026/11/25 13:57 tool codesearch-dir-index
0m Args:
{
  "Dir": "drivers/android/"
}

Results:
{
  "Files": null,
  "Subdirs": [
    "binder"
  ]
}

43/2 2026/11/25 13:57 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 61248
							output: 23
							thoughts: 14
						

Thoughts:
Here's my take on those thoughts, tailored for an expert audience:

**Diving into the Android Binder Implementation**

Okay, so I'm thinking, "Let's crack open the `drivers/android/binder` directory." I want to get a solid handle on how the Binder IPC mechanism is implemented at the kernel level. Specifically, I'm interested in the intricacies of the driver itself – what the code is *really* doing under the hood. I expect to find the core data structures for managing transactions, handles, and object lifetimes. I'm keen to see how they've handled the complexities of managing process boundaries and security context within the kernel. I'm probably going to be looking for clues on how the driver handles memory management, especially shared memory regions, and potential race conditions in a multi-threaded, inter-process environment. I'm hoping I can identify the key entry points for system calls like `binder_transaction`, `binder_ioctl`, and `binder_alloc`, and see how they are implemented. I'm also really curious to examine the code related to handle tracking, object lifetime management, and any related locking mechanisms used to ensure data integrity and prevent concurrency issues. Time to dig in!



44/2 2026/11/25 13:58 tool codesearch-dir-index
0m Args:
{
  "Dir": "drivers/android/binder"
}

Results:
{
  "Files": [
    "allocation.rs",
    "context.rs",
    "debug.rs",
    "deferred_close.rs",
    "defs.rs",
    "error.rs",
    "freeze.rs",
    "netlink.rs",
    "node.rs",
    "page_range.rs",
    "process.rs",
    "rust_binder.h",
    "rust_binder_events.c",
    "rust_binder_events.h",
    "rust_binder_internal.h",
    "rust_binder_main.rs",
    "rust_binderfs.c",
    "stats.rs",
    "thread.rs",
    "trace.rs",
    "transaction.rs"
  ],
  "Subdirs": [
    "node",
    "range_alloc"
  ]
}

45/2 2026/11/25 13:58 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 61717
							output: 29
							thoughts: 18
						

Thoughts:
Okay, here's my summarized thought process, presented as if I'm thinking it:

**Digging into the Android Binder Drivers**

Alright, time to get to work. I need to get my hands dirty. My instinct is telling me to go straight to the Android Binder drivers, specifically within the `drivers/android/binder/` directory. Seems like a good place to start. What am I looking for? Right, I'm thinking I'll start with a straightforward approach. Let's start with a `grep` search. And, I know exactly what I'm searching for: `xarray`. Let's see what that turns up. This feels like a good initial approach. I'll get a quick and dirty idea of where `xarray` shows up in this part of the kernel. Should be interesting.



46/2 2026/11/25 13:58 tool grepper
0m Args:
{
  "Expression": "xarray",
  "PathPrefixes": [
    "drivers/android/binder/"
  ]
}

Results:
{
  "Output": "drivers/android/binder/rust_binderfs.c-30-#include \u003clinux/user_namespace.h\u003e\ndrivers/android/binder/rust_binderfs.c:31:#include \u003clinux/xarray.h\u003e\ndrivers/android/binder/rust_binderfs.c-32-#include \u003cuapi/asm-generic/errno-base.h\u003e\n"
}

47/2 2026/11/25 13:58 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 62036
							output: 23
							thoughts: 35
						

Thoughts:
Okay, let's break this down.

**Initial Assessment of the Code Patch**

Alright, before I dive into the nitty-gritty of this patch, my first instinct is to get a handle on *why* it exists in the first place. You can't properly understand the *what* without understanding the *why*. So, the immediate next step is to get some context. I need to see what motivated this change. I'm going to reach for the commit history, most likely using `git log -n 5` (or a similar command) to check the most recent few entries. Hopefully, the commit message provides a clear explanation of the problem this patch addresses, the reasoning behind the solution, and possibly any relevant references or discussions. That context is absolutely crucial before I make any judgements. I need to understand the intent and the historical rationale before getting into the weeds.



48/2 2026/11/25 13:59 tool grepper
0m Args:
{
  "Expression": "syz-cluster: applied patch under review"
}

Results:
{
  "Output": "no matches"
}

49/2 2026/11/25 13:59 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 62293
							output: 35
							thoughts: 2333
						

Thoughts:
**Patch Analysis: Radix Tree/Xarray and SLUB Sheaf Optimization**

Okay, let's dive into this patch. First, I need to understand what's changed. The git log isn't immediately available, but the diff gives me the core information: a change to the MAINTAINERS file and, more importantly, modifications to radix-tree, xarray, and SLUB code, as well as some Rust bindings. This is definitely worth a closer look.

Now, let's consult the guidelines. The philosophy is clear: reachability is king, and don't blindly trust NFCI (no functional change) claims. Reachable, executable code changes? They get fuzzed. Non-kernel changes or unreachable hardware? Not fuzzed. Refactorings that touch reachable code? They *must* be fuzzed.

Looking at the patch itself, this definitely qualifies. `lib/radix-tree.c` is being modified. The `radix_tree_init()` function is now configuring the `radix_tree_node_cachep` with `.sheaf_capacity = 64`. Aha! This is interesting:  This means all allocations and frees to the radix tree and xarray nodes are now executed via SLUB percpu sheaves fastpaths (`alloc_from_pcs` and `free_to_pcs`) rather than the previous slab freelist path.  Radix trees and XArrays are crucial data structures in the kernel, underpinning page cache, file descriptors, and IPC. Moreover, the addition of prefill and refill methods (`kmem_cache_prefill_sheaf`, `kmem_cache_return_sheaf`, `kmem_cache_refill_sheaf`, `kmem_cache_alloc_from_sheaf_noprof`) is significant, along with inlining `xa_zero_to_null` and `xas_result`. And the Rust part is also very interesting, as the patch adds sheaf abstraction and xarray entry API and preallocation support.

Absolutely, WorthFuzzing is TRUE. We are modifying core subsystems (`mm/slub.c`, `lib/radix-tree.c`, `lib/xarray.c`, `include/linux/xarray.h`), and the refactoring is substantial.

Now comes the crucial part: selecting the `FocusSymbols`. We need to avoid ubiquitous lifecycle functions like general memory allocators. Instead, we need to target specific feature logic and entry points. Static inlines are tricky, but we can target the non-static callers.

Let's go function by function. In `lib/radix-tree.c`, `radix_tree_node_ctor`, `radix_tree_init`, `radix_tree_node_alloc`, `radix_tree_node_rcu_free`, and `__radix_tree_preload` have been modified/added. Now, which of these are the key entry points? The `init` function is only called once at boot, so likely not. The alloc and free functions, and the ctor/dtor functions are likely candidates. In `lib/xarray.c`, `xas_nomem`, `xas_alloc`, `xas_split_alloc`, and `xas_try_split` are potentially interesting, since the patch is also modifying the xarray fast paths. In `mm/slub.c`, the sheaf-related functions (`kmem_cache_prefill_sheaf`, `kmem_cache_return_sheaf`, `kmem_cache_refill_sheaf`, `kmem_cache_alloc_from_sheaf_noprof`), are crucial. `alloc_from_pcs` and `free_to_pcs` are static inline functions.

Now, which of these are too ubiquitous? `kmem_cache_alloc` and `kmem_cache_free` are definitely out, as we must avoid general memory allocators. We will focus on the others.

`radix_tree_node_ctor` is interesting, now that it's exported and non-static. It's a constructor for the slab objects. And the RCU callback, `radix_tree_node_rcu_free` should be included. `xas_alloc` and `xas_nomem` are also highly relevant. Every time the xarray grows or new levels are allocated, these functions are called.

The sheaf functions in `mm/slub.c` are not ubiquitous, especially as they were introduced in this patch. These functions specifically handle the optimization. The Rust helpers are also of interest.

Therefore, the `FocusSymbols` should be: `radix_tree_node_ctor`, `radix_tree_node_rcu_free`, `xas_nomem`, `


50/2 2026/11/25 13:59 tool read-file
0m Args:
{
  "File": "mm/slub.c",
  "FirstLine": 5280,
  "LineCount": 40
}

Results:
{
  "Contents": "5280:\t\n5281:\t\tif (sheaf) {\n5282:\t\t\tsheaf-\u003ecapacity = s-\u003esheaf_capacity;\n5283:\t\t\tsheaf-\u003epfmemalloc = false;\n5284:\t\n5285:\t\t\tif (sheaf-\u003esize \u003c size \u0026\u0026\n5286:\t\t\t    __prefill_sheaf_pfmemalloc(s, sheaf, gfp)) {\n5287:\t\t\t\tsheaf_flush_unused(s, sheaf);\n5288:\t\t\t\tfree_empty_sheaf(s, sheaf);\n5289:\t\t\t\tsheaf = NULL;\n5290:\t\t\t}\n5291:\t\t}\n5292:\t\n5293:\t\treturn sheaf;\n5294:\t}\n5295:\tEXPORT_SYMBOL(kmem_cache_prefill_sheaf);\n5296:\t\n5297:\t/*\n5298:\t * Use this to return a sheaf obtained by kmem_cache_prefill_sheaf()\n5299:\t *\n5300:\t * If the sheaf cannot simply become the percpu spare sheaf, but there's space\n5301:\t * for a full sheaf in the barn, we try to refill the sheaf back to the cache's\n5302:\t * sheaf_capacity to avoid handling partially full sheaves.\n5303:\t *\n5304:\t * If the refill fails because gfp is e.g. GFP_NOWAIT, or the barn is full, the\n5305:\t * sheaf is instead flushed and freed.\n5306:\t */\n5307:\tvoid kmem_cache_return_sheaf(struct kmem_cache *s, gfp_t gfp,\n5308:\t\t\t\t     struct slab_sheaf *sheaf)\n5309:\t{\n5310:\t\tstruct slub_percpu_sheaves *pcs;\n5311:\t\tstruct node_barn *barn;\n5312:\t\n5313:\t\tif (unlikely((sheaf-\u003ecapacity != s-\u003esheaf_capacity)\n5314:\t\t\t     || sheaf-\u003epfmemalloc)) {\n5315:\t\t\tsheaf_flush_unused(s, sheaf);\n5316:\t\t\tfree_empty_sheaf(s, sheaf);\n5317:\t\t\treturn;\n5318:\t\t}\n5319:\t\n"
}

51/2 2026/11/25 13:59 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 66298
							output: 35
							thoughts: 27
						

Thoughts:
Here's a summary of my thought process:

**Diving into the Slub Allocator**

Okay, so we're seeing an issue, and my initial instinct is to drill down into the SLUB allocator. Specifically, I'm thinking, given the nature of the problem, that the code responsible for managing the memory slabs might be the culprit. Let's start with a focused inspection. Line 5400 through 5450 in `mm/slub.c` is the region I'm targeting first. That area often deals with allocation, freeing, or slab manipulation. I need to refresh my mental map of how that section operates and see if anything jumps out that could correlate with the observed behavior. My focus is on anything that could cause a leak, corruption, or unexpected interaction with other parts of the system. Let's see if something reveals itself.



52/2 2026/11/25 14:00 tool read-file
0m Args:
{
  "File": "mm/slub.c",
  "FirstLine": 5400,
  "LineCount": 50
}

Results:
{
  "Contents": "5400:\t\tif (!sheaf)\n5401:\t\t\treturn -ENOMEM;\n5402:\t\n5403:\t\tkmem_cache_return_sheaf(s, gfp, *sheafp);\n5404:\t\t*sheafp = sheaf;\n5405:\t\treturn 0;\n5406:\t}\n5407:\tEXPORT_SYMBOL(kmem_cache_refill_sheaf);\n5408:\t\n5409:\t/*\n5410:\t * Allocate from a sheaf obtained by kmem_cache_prefill_sheaf()\n5411:\t *\n5412:\t * Guaranteed not to fail as many allocations as was the requested size.\n5413:\t * After the sheaf is emptied, it fails - no fallback to the slab cache itself.\n5414:\t *\n5415:\t * The gfp parameter is meant only to specify __GFP_ZERO or __GFP_ACCOUNT\n5416:\t * memcg charging is forced over limit if necessary, to avoid failure.\n5417:\t *\n5418:\t * It is possible that the allocation comes from kfence and then the sheaf\n5419:\t * size is not decreased.\n5420:\t */\n5421:\tvoid *\n5422:\tkmem_cache_alloc_from_sheaf_noprof(struct kmem_cache *s, gfp_t gfp,\n5423:\t\t\t\t\t   struct slab_sheaf *sheaf)\n5424:\t{\n5425:\t\tvoid *ret = NULL;\n5426:\t\tconst struct slab_alloc_context ac = {\n5427:\t\t\t.orig_size = s-\u003eobject_size,\n5428:\t\t\t.alloc_flags = SLAB_ALLOC_DEFAULT,\n5429:\t\t};\n5430:\t\n5431:\t\tif (sheaf-\u003esize == 0)\n5432:\t\t\tgoto out;\n5433:\t\n5434:\t\tret = kfence_alloc(s, s-\u003eobject_size, gfp);\n5435:\t\n5436:\t\tif (likely(!ret))\n5437:\t\t\tret = sheaf-\u003eobjects[--sheaf-\u003esize];\n5438:\t\n5439:\t\t/* add __GFP_NOFAIL to force successful memcg charging */\n5440:\t\tslab_post_alloc_hook(s, gfp | __GFP_NOFAIL, 1, \u0026ret, \u0026ac);\n5441:\tout:\n5442:\t\ttrace_kmem_cache_alloc(_RET_IP_, ret, s, gfp, NUMA_NO_NODE);\n5443:\t\n5444:\t\treturn ret;\n5445:\t}\n5446:\tEXPORT_SYMBOL(kmem_cache_alloc_from_sheaf_noprof);\n5447:\t\n5448:\tunsigned int kmem_cache_sheaf_size(struct slab_sheaf *sheaf)\n5449:\t{\n"
}

53/2 2026/11/25 14:00 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 67326
							output: 33
							thoughts: 905
						

Thoughts:
**Focusing on Target Symbols for Fuzzing**

Okay, so I need to figure out what symbols are relevant for fuzzing, specifically related to this sheaf implementation. First, I need to know which Rust symbols are even generated in `rust/kernel/xarray.rs` or `rust/helpers/xarray.c`. I already know about these C functions from `rust/helpers/xarray.c`: `rust_helper_xas_result`, `rust_helper_xa_zero_to_null`, and `rust_helper_xas_error`. But, I also need to consider that Rust functions will have their own mangled symbol names like `_RNv...` or `kernel::xarray::...`. Can Syzkaller even focus on those or am I stuck with C symbols?

I need to make sure I'm following Syzkaller's guidelines for `FocusSymbols`. It's crucial to avoid generic, ubiquitous functions. Things like allocators, deallocators, page fault handlers, and core synchronization primitives are a no-go. I want to target the specific feature logic and API entrypoints of this sheaf implementation.

So, let's look at the C functions that specifically implement the logic: `kmem_cache_prefill_sheaf`, `kmem_cache_return_sheaf`, `kmem_cache_refill_sheaf`, `kmem_cache_alloc_from_sheaf_noprof`, `radix_tree_node_ctor`, and the Rust helpers.

Hmm, what about `kmem_cache_create`? That's too generic, part of the lifecycle, I'll pass on that. `kmem_cache_sheaf_size`... nah, wasn't modified, so it's not the target. What about `refill_sheaf` or `refill_sheaf_from_barn`? I'd better check if `refill_sheaf` is static. Yep, it is. But, `kmem_cache_prefill_sheaf`, `kmem_cache_return_sheaf`, `kmem_cache_refill_sheaf`, and `kmem_cache_alloc_from_sheaf_noprof` are global exported functions – they are the *exact* C API entrypoints for sheaves. And `radix_tree_node_ctor` is the radix tree constructor, which was made non-static and exported. Good.

Okay, now for `EnableConfigs` and Kconfig requirements. I'm going to check if `sheaf` requires `CONFIG_SLUB`. Let's look at `cache_has_sheaves` in `mm/slab.h`. Seems like I should check if `SLUB_TINY` is enabled. It looks like it is not, but I should check. Looks like SLUB is the default. Right, SLAB was removed long ago. And it looks like the tiny version disables cpu sheaves! Hmm, let me grep for `config SLUB` in `init/Kconfig` or `mm/Kconfig` to be absolutely sure.



54/2 2026/11/25 14:00 tool grepper
0m Args:
{
  "Expression": "config SLUB\\b",
  "PathPrefixes": [
    "mm/",
    "init/"
  ]
}

Results:
{
  "Output": "mm/Kconfig=162=menu \"Slab allocator options\"\nmm/Kconfig-163-\nmm/Kconfig:164:config SLUB\nmm/Kconfig-165-\tdef_bool y\n"
}

55/2 2026/11/25 14:00 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 68999
							output: 28
							thoughts: 111
						

Thoughts:
**Considering the Rust Implementation**

Okay, so I'm seeing a patch that's clearly touching the Rust side of things. Specifically, it's modifying a few files within the `rust/` directory. I see:

*   `rust/bindings/bindings_helper.h`
*   `rust/helpers/xarray.c`
*   `rust/kernel/mm.rs`
*   `rust/kernel/mm/sheaf.rs`
*   `rust/kernel/xarray/entry.rs`

My immediate thought is, "What about `CONFIG_RUST`?" This is going to be a critical dependency. Given that it's altering these files, I need to check the `init/Kconfig` file to confirm that `CONFIG_RUST` is correctly enabled or disabled or otherwise addressed to ensure that this patch is correctly configured within the build system. Let me get right on that.


56/2 2026/11/25 14:01 tool grepper
0m Args:
{
  "Expression": "config RUST\\b",
  "PathPrefixes": [
    "init/"
  ]
}

Results:
{
  "Output": "init/Kconfig=2053=config PROFILING\n--\ninit/Kconfig-2058-\ninit/Kconfig:2059:config RUST\ninit/Kconfig-2060-\tbool \"Rust support\"\n"
}

57/2 2026/11/25 14:01 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 69409
							output: 31
							thoughts: 64
						

Thoughts:
**Investigating Radix Tree and Xarray Configuration**

Alright, let's get down to brass tacks. I need to figure out if there are any *specific* configuration options, like kernel parameters or build flags, that would directly influence the behavior of the radix tree or xarray implementations. It's crucial for understanding the system's performance characteristics. My initial assumption is that these are core kernel components, so they might not be configurable in the same way as, say, a loadable module.

Okay, let's confirm that hypothesis. I’ve checked the kernel source and can confirm that the radix tree and xarray implementations are baked into the kernel core unconditionally. The code lives right there in `lib/radix-tree.c` and `lib/xarray.c`. This strongly suggests there's no runtime configuration for these structures.

To be absolutely certain, I'll quickly check `lib/Makefile`. This will confirm if there are any conditional compilation rules or build-time options that would suggest a configurable nature, even if the result is that the build is always done. That should provide a definitive answer.



58/2 2026/11/25 14:01 tool grepper
0m Args:
{
  "Expression": "radix-tree|xarray",
  "PathPrefixes": [
    "lib/Makefile"
  ]
}

Results:
{
  "Output": "lib/Makefile=36=lib-y := ctype.o string.o vsprintf.o cmdline.o \\\nlib/Makefile:37:\t rbtree.o radix-tree.o timerqueue.o xarray.o \\\nlib/Makefile-38-\t maple_tree.o idr.o extable.o irq_regs.o argv_split.o \\\n--\nlib/Makefile=55=obj-y += bcd.o sort.o parser.o debug_locks.o random32.o \\\n--\nlib/Makefile-60-\t once.o refcount.o rcuref.o usercopy.o errseq.o bucket_locks.o \\\nlib/Makefile:61:\t generic-radix-tree.o bitmap-str.o\nlib/Makefile-62-obj-y += string_helpers.o\n--\nlib/Makefile=92=endif\nlib/Makefile-93-\nlib/Makefile:94:obj-$(CONFIG_TEST_XARRAY) += test_xarray.o\nlib/Makefile-95-obj-$(CONFIG_TEST_MAPLE_TREE) += test_maple_tree.o\n"
}

59/2 2026/11/25 14:01 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 70025
							output: 28
							thoughts: 125
						

Thoughts:
Okay, let me think this through.

**Analyzing the Kernel's Memory Management Components**

Right, so `radix-tree.o` and `xarray.o` are core parts of `lib-y`, built right into the kernel's core library. That's a given. And I know that `mm/slub.c` is enabled depending on `CONFIG_SLUB`. No surprises there. The interesting bit, as I recall, is how the Rust abstractions for these, specifically `rust/kernel/mm/sheaf.rs` and `rust/kernel/xarray.rs`, get compiled. That's the key. They are compiled when `CONFIG_RUST=y`, which makes perfect sense. Now, just to be absolutely certain, is that the only config option that drives their inclusion? I want to make sure I haven't missed a dependency or a hidden conditional. I should probably check the `rust/Makefile` or `rust/kernel/Makefile` to see exactly how the `rust/kernel/` directory and its contents are built. I need to confirm the build process to solidify this understanding.



60/2 2026/11/25 14:02 tool grepper
0m Args:
{
  "Expression": "sheaf|xarray",
  "PathPrefixes": [
    "rust/"
  ]
}

Results:
{
  "Output": "\nFull output is too long, showing 200 out of 540 lines.\nUse more precise expression or PathPrefixes if possible.\n\nNumber of matching lines per file (8 files in total):\nrust/bindings/bindings_helper.h:1\nrust/helpers/helpers.c:1\nrust/helpers/xarray.c:5\nrust/kernel/lib.rs:1\nrust/kernel/mm.rs:1\nrust/kernel/mm/sheaf.rs:112\nrust/kernel/xarray.rs:25\nrust/kernel/xarray/entry.rs:9\n\nrust/bindings/bindings_helper.h-97-#include \u003clinux/workqueue.h\u003e\nrust/bindings/bindings_helper.h:98:#include \u003clinux/xarray.h\u003e\nrust/bindings/bindings_helper.h-99-#include \u003cnet/genetlink.h\u003e\n--\nrust/helpers/helpers.c-110-#include \"workqueue.c\"\nrust/helpers/helpers.c:111:#include \"xarray.c\"\n--\nrust/helpers/xarray.c-2-\nrust/helpers/xarray.c:3:#include \u003clinux/xarray.h\u003e\nrust/helpers/xarray.c-4-\nrust/helpers/xarray.c=5=__rust_helper int rust_helper_xa_err(void *entry)\n--\nrust/helpers/xarray.c-9-\nrust/helpers/xarray.c:10:__rust_helper void rust_helper_xa_init_flags(struct xarray *xa, gfp_t flags)\nrust/helpers/xarray.c-11-{\n--\nrust/helpers/xarray.c-14-\nrust/helpers/xarray.c:15:__rust_helper int rust_helper_xa_trylock(struct xarray *xa)\nrust/helpers/xarray.c-16-{\n--\nrust/helpers/xarray.c-19-\nrust/helpers/xarray.c:20:__rust_helper void rust_helper_xa_lock(struct xarray *xa)\nrust/helpers/xarray.c-21-{\n--\nrust/helpers/xarray.c-24-\nrust/helpers/xarray.c:25:__rust_helper void rust_helper_xa_unlock(struct xarray *xa)\nrust/helpers/xarray.c-26-{\n--\nrust/kernel/lib.rs-150-pub mod workqueue;\nrust/kernel/lib.rs:151:pub mod xarray;\nrust/kernel/lib.rs-152-\n--\nrust/kernel/mm.rs-20-\nrust/kernel/mm.rs:21:pub mod sheaf;\nrust/kernel/mm.rs-22-pub mod virt;\n--\nrust/kernel/mm/sheaf.rs-2-\nrust/kernel/mm/sheaf.rs:3://! Slub allocator sheaf abstraction.\nrust/kernel/mm/sheaf.rs-4-//!\n--\nrust/kernel/mm/sheaf.rs-9-//!\nrust/kernel/mm/sheaf.rs:10://! The term \"sheaf\" is the english word for a bundle of straw. In this context\nrust/kernel/mm/sheaf.rs-11-//! it means a bundle of pre-allocated objects. A per-NUMA-node cache of sheaves\nrust/kernel/mm/sheaf.rs:12://! is called a \"barn\". Because you store your sheafs in barns.\nrust/kernel/mm/sheaf.rs-13-//!\n--\nrust/kernel/mm/sheaf.rs-20-//! - Multiple allocations need to be performed as a batch operation.\nrust/kernel/mm/sheaf.rs:21://! - Fast-path allocation performance is critical, as sheaf allocations avoid\nrust/kernel/mm/sheaf.rs-22-//!   atomic operations by using local locks with preemption disabled. Note\n--\nrust/kernel/mm/sheaf.rs-27-//!\nrust/kernel/mm/sheaf.rs:28://! The sheaf system supports two modes of operation:\nrust/kernel/mm/sheaf.rs-29-//!\n--\nrust/kernel/mm/sheaf.rs-39-//! - [`Sheaf`]: A pre-filled container of objects from a specific cache.\nrust/kernel/mm/sheaf.rs:40://! - [`SBox`]: An owned allocation from a sheaf, similar to a `Box`.\nrust/kernel/mm/sheaf.rs-41-//!\n--\nrust/kernel/mm/sheaf.rs-47-//! use kernel::c_str;\nrust/kernel/mm/sheaf.rs:48://! use kernel::mm::sheaf::{KMemCacheHandle, KMemCacheInit, Sheaf, SBox};\nrust/kernel/mm/sheaf.rs-49-//! use kernel::prelude::*;\n--\nrust/kernel/mm/sheaf.rs-60-//!\nrust/kernel/mm/sheaf.rs:61://! // Create a cache with a sheaf capacity of at least 16 objects.\nrust/kernel/mm/sheaf.rs-62-//! let cache = KMemCacheHandle::\u003cMyObject\u003e::new(c_str!(\"my_cache\"), 16)?;\nrust/kernel/mm/sheaf.rs-63-//!\nrust/kernel/mm/sheaf.rs:64://! // Pre-fill a sheaf with 8 objects.\nrust/kernel/mm/sheaf.rs:65://! let mut sheaf = cache.as_arc_borrow().sheaf(8, GFP_KERNEL)?;\nrust/kernel/mm/sheaf.rs-66-//!\nrust/kernel/mm/sheaf.rs:67://! // Allocations from the sheaf are guaranteed to succeed until empty.\nrust/kernel/mm/sheaf.rs:68://! let obj = sheaf.alloc().unwrap();\nrust/kernel/mm/sheaf.rs-69-//!\nrust/kernel/mm/sheaf.rs:70://! // Return the sheaf when done, attempting to refill it.\nrust/kernel/mm/sheaf.rs:71://! sheaf.return_refill(GFP_KERNEL);\nrust/kernel/mm/sheaf.rs-72-//! # Ok::\u003c(), Error\u003e(())\n--\nrust/kernel/mm/sheaf.rs-80-//!   slower allocation path.\nrust/kernel/mm/sheaf.rs:81://! - The sheaf capacity of a cache is decided at cache creation time. The\nrust/kernel/mm/sheaf.rs-82-//!   capacity requested when creating the cache is a minimum. The allocator\n--\nrust/kernel/mm/sheaf.rs-99-\nrust/kernel/mm/sheaf.rs:100:/// A slab cache with sheaf support.\nrust/kernel/mm/sheaf.rs-101-///\n--\nrust/kernel/mm/sheaf.rs-107-/// one created by C code at boot time. Such references produce\nrust/kernel/mm/sheaf.rs:108:/// [`StaticSheaf`] instances via [`sheaf`].\nrust/kernel/mm/sheaf.rs-109-///\nrust/kernel/mm/sheaf.rs:110:/// [`sheaf`]: KMemCache::sheaf\nrust/kernel/mm/sheaf.rs-111-///\n--\nrust/kernel/mm/sheaf.rs=133=impl\u003cT: KMemCacheInit\u003cT\u003e\u003e KMemCache\u003cT\u003e {\nrust/kernel/mm/sheaf.rs:134:    /// Creates a pre-filled sheaf from this cache.\nrust/kernel/mm/sheaf.rs-135-    ///\nrust/kernel/mm/sheaf.rs:136:    /// Allocates a sheaf and pre-fills it with `size` objects. Once created,\nrust/kernel/mm/sheaf.rs:137:    /// allocations from the sheaf via [`Sheaf::alloc`] are guaranteed to\nrust/kernel/mm/sheaf.rs:138:    /// succeed until the sheaf is depleted.\nrust/kernel/mm/sheaf.rs-139-    ///\n--\nrust/kernel/mm/sheaf.rs-142-    /// - `size`: The number of objects to pre-allocate. Must not be zero. If\nrust/kernel/mm/sheaf.rs:143:    ///   `size` exceeds the sheaf capacity of the cache, an \"oversize\" sheaf\nrust/kernel/mm/sheaf.rs-144-    ///   is allocated. Oversize sheaves are slower to create, and they are\n--\nrust/kernel/mm/sheaf.rs-151-    ///\nrust/kernel/mm/sheaf.rs:152:    /// Returns [`ENOMEM`] if the sheaf or its objects could not be allocated,\nrust/kernel/mm/sheaf.rs-153-    /// or if `size` is zero.\nrust/kernel/mm/sheaf.rs-154-    #[inline]\nrust/kernel/mm/sheaf.rs:155:    pub fn sheaf(\nrust/kernel/mm/sheaf.rs-156-        \u0026'static self,\n--\nrust/kernel/mm/sheaf.rs-162-        let ptr = unsafe {\nrust/kernel/mm/sheaf.rs:163:            bindings::kmem_cache_prefill_sheaf(self.inner.get(), gfp.as_raw(), size.try_into()?)\nrust/kernel/mm/sheaf.rs-164-        };\nrust/kernel/mm/sheaf.rs-165-\nrust/kernel/mm/sheaf.rs:166:        // INVARIANT: `ptr` was returned by `kmem_cache_prefill_sheaf` and is\nrust/kernel/mm/sheaf.rs:167:        // non-null (checked below). `cache` is the cache from which this sheaf\nrust/kernel/mm/sheaf.rs:168:        // was created. `dropped` is false since the sheaf has not been returned.\nrust/kernel/mm/sheaf.rs-169-        Ok(Sheaf {\nrust/kernel/mm/sheaf.rs:170:            sheaf: NonNull::new(ptr).ok_or(ENOMEM)?,\nrust/kernel/mm/sheaf.rs-171-            // SAFETY: `self` is a valid reference, so the pointer is non-null.\n--\nrust/kernel/mm/sheaf.rs=197=    pub unsafe fn from_raw\u003c'a\u003e(ptr: *mut bindings::kmem_cache) -\u003e \u0026'a Self {\n--\nrust/kernel/mm/sheaf.rs-204-\nrust/kernel/mm/sheaf.rs:205:/// A slab cache with sheaf support.\nrust/kernel/mm/sheaf.rs-206-///\nrust/kernel/mm/sheaf.rs:207:/// This type wraps a kernel `kmem_cache` configured with a sheaf capacity,\nrust/kernel/mm/sheaf.rs-208-/// enabling pre-allocation of objects via [`Sheaf`].\nrust/kernel/mm/sheaf.rs-209-///\nrust/kernel/mm/sheaf.rs:210:/// For now, this type only exists for sheaf management.\nrust/kernel/mm/sheaf.rs-211-///\n--\nrust/kernel/mm/sheaf.rs=250=impl\u003cT: KMemCacheInit\u003cT\u003e\u003e KMemCacheHandle\u003cT\u003e {\nrust/kernel/mm/sheaf.rs:251:    /// Creates a new slab cache with sheaf support.\nrust/kernel/mm/sheaf.rs-252-    ///\nrust/kernel/mm/sheaf.rs-253-    /// Creates a kernel slab cache for objects of type `T` with at least the\nrust/kernel/mm/sheaf.rs:254:    /// specified sheaf capacity. The cache uses the provided `name` for\nrust/kernel/mm/sheaf.rs-255-    /// identification in `/sys/kernel/slab/` and debugging output.\n--\nrust/kernel/mm/sheaf.rs-260-    ///   debugging output.\nrust/kernel/mm/sheaf.rs:261:    /// - `sheaf_capacity`: The minimum number of objects a regular sheaf from\nrust/kernel/mm/sheaf.rs-262-    ///   this cache can hold. The allocator calculates a capacity based on the\n--\nrust/kernel/mm/sheaf.rs-264-    ///   selects the calculated capacity. Set this to the largest `size` that\nrust/kernel/mm/sheaf.rs:265:    ///   is expected to be passed to [`sheaf`](Self::sheaf) to avoid oversize\nrust/kernel/mm/sheaf.rs-266-    ///   sheaves. The value is ignored when `CONFIG_SLUB_TINY` is enabled or\n--\nrust/kernel/mm/sheaf.rs-274-    /// - The size of `T` cannot be represented as a `c_uint`.\nrust/kernel/mm/sheaf.rs:275:    pub fn new(name: \u0026CStr, sheaf_capacity: u32) -\u003e Result\u003cArc\u003cSelf\u003e\u003e\nrust/kernel/mm/sheaf.rs-276-    where\n--\nrust/kernel/mm/sheaf.rs-280-        let mut args: bindings::kmem_cache_args = pin_init::zeroed();\nrust/kernel/mm/sheaf.rs:281:        args.sheaf_capacity = sheaf_capacity;\nrust/kernel/mm/sheaf.rs-282-\n--\nrust/kernel/mm/sheaf.rs-312-\nrust/kernel/mm/sheaf.rs:313:    /// Creates a pre-filled sheaf from this cache.\nrust/kernel/mm/sheaf.rs-314-    ///\nrust/kernel/mm/sheaf.rs:315:    /// Allocates a sheaf and pre-fills it with `size` objects. Once created,\nrust/kernel/mm/sheaf.rs:316:    /// allocations from the sheaf via [`Sheaf::alloc`] are guaranteed to\nrust/kernel/mm/sheaf.rs:317:    /// succeed until the sheaf is depleted.\nrust/kernel/mm/sheaf.rs-318-    ///\n--\nrust/kernel/mm/sheaf.rs-321-    /// - `size`: The number of objects to pre-allocate. Must not be zero. If\nrust/kernel/mm/sheaf.rs:322:    ///   `size` exceeds the sheaf capacity of the cache, an \"oversize\" sheaf\nrust/kernel/mm/sheaf.rs-323-    ///   is allocated. Oversize sheaves are slower to create, and they are\n--\nrust/kernel/mm/sheaf.rs-330-    ///\nrust/kernel/mm/sheaf.rs:331:    /// Returns [`ENOMEM`] if the sheaf or its objects could not be allocated,\nrust/kernel/mm/sheaf.rs-332-    /// or if `size` is zero.\nrust/kernel/mm/sheaf.rs-333-    #[inline]\nrust/kernel/mm/sheaf.rs:334:    pub fn sheaf\u003c'a\u003e(\nrust/kernel/mm/sheaf.rs-335-        self: ArcBorrow\u003c'a, Self\u003e,\n--\nrust/kernel/mm/sheaf.rs-341-        let ptr = unsafe {\nrust/kernel/mm/sheaf.rs:342:            bindings::kmem_cache_prefill_sheaf(self.as_raw(), gfp.as_raw(), size.try_into()?)\nrust/kernel/mm/sheaf.rs-343-        };\nrust/kernel/mm/sheaf.rs-344-\nrust/kernel/mm/sheaf.rs:345:        // INVARIANT: `ptr` was returned by `kmem_cache_prefill_sheaf` and is\nrust/kernel/mm/sheaf.rs:346:        // non-null (checked below). `cache` is the cache from which this sheaf\nrust/kernel/mm/sheaf.rs:347:        // was created. `dropped` is false since the sheaf has not been returned.\nrust/kernel/mm/sheaf.rs-348-        Ok(Sheaf {\nrust/kernel/mm/sheaf.rs:349:            sheaf: NonNull::new(ptr).ok_or(ENOMEM)?,\nrust/kernel/mm/sheaf.rs-350-            cache: CacheRef::Arc(self.into()),\n--\nrust/kernel/mm/sheaf.rs=363=    fn drop(\u0026mut self) {\n--\nrust/kernel/mm/sheaf.rs-375-/// [`KMemCache`]. The initializer is called when objects are allocated from a\nrust/kernel/mm/sheaf.rs:376:/// sheaf via [`Sheaf::alloc`].\nrust/kernel/mm/sheaf.rs-377-///\n--\nrust/kernel/mm/sheaf.rs-385-/// ```\nrust/kernel/mm/sheaf.rs:386:/// use kernel::mm::sheaf::KMemCacheInit;\nrust/kernel/mm/sheaf.rs-387-/// use kernel::prelude::*;\n--\nrust/kernel/mm/sheaf.rs=403=pub trait KMemCacheInit\u003cT\u003e {\n--\nrust/kernel/mm/sheaf.rs-405-    ///\nrust/kernel/mm/sheaf.rs:406:    /// The initializer is applied to newly allocated objects when they are allocated from a sheaf\nrust/kernel/mm/sheaf.rs-407-    /// via [`Sheaf::alloc`]. The initializer should set all fields to their default or initial\n--\n\n"
}

61/2 2026/11/25 14:02 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 74779
							output: 18
							thoughts: 59
						

Thoughts:
Here's my thought process, as it stands:

**Navigating the Kconfig Labyrinth**

Okay, so we're looking at some memory allocation stuff, and the system seems to be using SLUB. First thing's first, I need to verify which SLUB configuration options are set. Specifically, I'm trying to figure out if we're dealing with `SLUB_CPU_SHEAVES` or something similar related to sheaves. My gut tells me there might be a separate config related to sheaves within SLUB, but I need to confirm. Time to dive into the Kconfig files. The plan is simple, a quick `grep` for `SHEAF` and `SHEAVES` across the relevant Kconfig files should pinpoint the exact configuration option if it exists. Let's see what we find.



62/2 2026/11/25 14:03 tool grepper
0m Args:
{
  "Expression": "config.*SHEAF"
}

Results:
{
  "Output": "no matches"
}

63/2 2026/11/25 14:03 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 75041
							output: 250
							thoughts: 907
						

Thoughts:
**Sheaf Allocation and Rust Integration: Configuration and Focus for Fuzzing**

Okay, let's break this down systematically. I need to figure out the right settings for fuzzing, given the changes related to the sheaf allocation API and Rust integration. First, I confirmed that `SLUB_TINY` disables sheaves entirely. This means sheaves rely on the standard `SLUB` allocator and that `!SLUB_TINY` is a hard requirement. I also established that `CONFIG_RUST` is necessary, obviously, since it supports compilation of the Rust abstractions in `rust/`.

Next, I delved into the specific symbols involved. I identified several functions in `mm/slub.c` that are tied directly to the sheaf allocation logic: `kmem_cache_prefill_sheaf`, `kmem_cache_return_sheaf`, `kmem_cache_refill_sheaf`, and `kmem_cache_alloc_from_sheaf_noprof`. These are all part of the SLUB implementation for managing sheaves. Additionally, I found `radix_tree_node_ctor` in `lib/radix-tree.c`, which is the constructor for radix tree nodes. The XArray helper functions, such as `rust_helper_xas_result`, `rust_helper_xa_zero_to_null`, and `rust_helper_xas_error` in `rust/helpers/xarray.c` are also crucial.

I double-checked if there were any other code changes in the radix tree or xarray code: I noted that `xa_zero_to_null` and `xas_result` were moved to `include/linux/xarray.h` as static inline functions and that `radix_tree_node_ctor` was un-static'd and exported, and also that `radix_tree_init` was updated to set `.sheaf_capacity = 64`. Also, I re-confirmed that the aforementioned sheaf-related SLUB functions were exported with `EXPORT_SYMBOL`.

The crucial point here is that these aren't *ubiquitous* kernel functions. They are specific components of these specific features: the SLUB sheaf API, the radix tree node constructor, and the Rust xarray helpers. Therefore, focusing fuzzing on these functions makes sense and provides the basis of the `FocusSymbols`.

Finally, I verified the required parameters for `set-results`. The verdict is "WorthFuzzing: true." The relevant `EnableConfigs` are "SLUB" and "RUST" and the `FocusSymbols` are, as noted above: `kmem_cache_prefill_sheaf`, `kmem_cache_return_sheaf`, `kmem_cache_refill_sheaf`, `kmem_cache_alloc_from_sheaf_noprof`, `radix_tree_node_ctor`, `rust_helper_xas_result`, `rust_helper_xa_zero_to_null`, and `rust_helper_xas_error`. Everything checks out; I'm ready to call `set-results`.



64/2 2026/11/25 14:03 tool set-results
0m Args:
{
  "EnableConfigs": [
    "SLUB",
    "RUST"
  ],
  "FocusSymbols": [
    "kmem_cache_prefill_sheaf",
    "kmem_cache_return_sheaf",
    "kmem_cache_refill_sheaf",
    "kmem_cache_alloc_from_sheaf_noprof",
    "radix_tree_node_ctor",
    "rust_helper_xas_result",
    "rust_helper_xa_zero_to_null",
    "rust_helper_xas_error"
  ],
  "Reasoning": "The patch series modifies core memory management and data structure logic. It configures the global radix_tree_node_cachep with sheaf capacity support (.sheaf_capacity = 64), which alters SLUB fast-path allocation and freeing behavior (percpu sheaves) for all radix tree and XArray nodes across the kernel. It also exports the SLUB sheaf management API, moves XArray helpers to public headers, and adds Rust abstractions for SLUB sheaves and XArray entry operations. These changes touch reachable core paths and warrant fuzzing.",
  "WorthFuzzing": true
}

Results:
{
  "EnableConfigs": [
    "SLUB",
    "RUST"
  ],
  "FocusSymbols": [
    "kmem_cache_prefill_sheaf",
    "kmem_cache_return_sheaf",
    "kmem_cache_refill_sheaf",
    "kmem_cache_alloc_from_sheaf_noprof",
    "radix_tree_node_ctor",
    "rust_helper_xas_result",
    "rust_helper_xa_zero_to_null",
    "rust_helper_xas_error"
  ],
  "Reasoning": "The patch series modifies core memory management and data structure logic. It configures the global radix_tree_node_cachep with sheaf capacity support (.sheaf_capacity = 64), which alters SLUB fast-path allocation and freeing behavior (percpu sheaves) for all radix tree and XArray nodes across the kernel. It also exports the SLUB sheaf management API, moves XArray helpers to public headers, and adds Rust abstractions for SLUB sheaves and XArray entry operations. These changes touch reachable core paths and warrant fuzzing.",
  "WorthFuzzing": true
}

65/1 2026/11/25 14:03 action If
1m Args:
{
  "WorthFuzzing": true
}

Results:
null

66/2 2026/11/25 14:03 agent kmsan-evaluator
1m Model:
core

Args:
null

Results:
{
  "KMSANReasoning": "The patch series introduces Rust abstractions for SLUB allocator sheaves (`rust/kernel/mm/sheaf.rs`) and XArray entry/preallocation operations (`rust/kernel/xarray.rs`, `rust/kernel/xarray/entry.rs`), along with exporting several existing SLUB sheaf functions in `mm/slub.c` and updating `radix_tree_init` to configure sheaf capacity.\n\nKMSAN is not required for the following reasons:\n1. No user-space copy boundaries (such as `copy_to_user`, ioctl outputs, netlink attributes, or BPF buffers) are introduced or modified.\n2. All data structures initialized in both C and Rust are fully initialized before use: `struct kmem_cache_args` is zero-initialized, `struct xa_state` explicitly sets all fields, and `radix_tree_node` / `XArrayNode` instances are explicitly zeroed via `radix_tree_node_ctor` (`memset(node, 0, sizeof(*node))`).\n3. Any potential bugs in this patch series involve reference counting, lock guard behavior, lifetime/ownership conversions (`into_ptr`, `static_from_ptr`), or slab management, which fall squarely under KASAN, LOCKDEP, and standard kernel debugging facilities rather than KMSAN uninitialized memory detection.",
  "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 8f525438224f17da9edd0c9c7e7da757f585c4fb
Author: syz-cluster <triage@syzkaller.com>
Date:   Wed Nov 25 13:48:27 2026 +0000

    syz-cluster: applied patch under review

diff --git a/MAINTAINERS b/MAINTAINERS
index 222b7fc2c3aab8..845503be1f289b 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -30500,6 +30500,7 @@ B:	https://github.com/Rust-for-Linux/linux/issues
 C:	https://rust-for-linux.zulipchat.com
 T:	git https://github.com/Rust-for-Linux/linux.git xarray-next
 F:	rust/kernel/xarray.rs
+F:	rust/kernel/xarray/
 
 XBOX DVD IR REMOTE
 M:	Benjamin Valentin <benpicco@googlemail.com>
diff --git a/include/linux/radix-tree.h b/include/linux/radix-tree.h
index 057edc4cbb6ef2..ac5fc299399cfb 100644
--- a/include/linux/radix-tree.h
+++ b/include/linux/radix-tree.h
@@ -470,4 +470,7 @@ static __always_inline void __rcu **radix_tree_next_slot(void __rcu **slot,
 	     slot = radix_tree_next_slot(slot, iter,			\
 				RADIX_TREE_ITER_TAGGED | tag))
 
+
+void radix_tree_node_ctor(void *arg);
+
 #endif /* _LINUX_RADIX_TREE_H */
diff --git a/include/linux/xarray.h b/include/linux/xarray.h
index be850174e802e6..db2520864aaa7f 100644
--- a/include/linux/xarray.h
+++ b/include/linux/xarray.h
@@ -191,6 +191,17 @@ static inline bool xa_is_zero(const void *entry)
 	return unlikely(entry == XA_ZERO_ENTRY);
 }
 
+/**
+ * xa_zero_to_null() - Convert an internal zero entry into a NULL pointer.
+ * @entry: XArray entry.
+ *
+ * Return: %NULL if @entry is a zero entry, @entry otherwise.
+ */
+static inline void *xa_zero_to_null(void *entry)
+{
+	return xa_is_zero(entry) ? NULL : entry;
+}
+
 /**
  * xa_is_err() - Report whether an XArray operation returned an error
  * @entry: Result from calling an XArray function
@@ -1437,6 +1448,21 @@ static inline int xas_error(const struct xa_state *xas)
 	return xa_err(xas->xa_node);
 }
 
+/**
+ * xas_result() - Extract the result of an XArray operation.
+ * @xas: XArray operation state.
+ * @curr: Entry returned by the operation.
+ *
+ * Return: @curr if the operation succeeded, the error encoded in @xas
+ * otherwise.
+ */
+static inline void *xas_result(struct xa_state *xas, void *curr)
+{
+	if (xas_error(xas))
+		curr = xas->xa_node;
+	return curr;
+}
+
 /**
  * xas_set_err() - Note an error in the xa_state.
  * @xas: XArray operation state.
diff --git a/lib/radix-tree.c b/lib/radix-tree.c
index 976b9bd02a1b5d..ddd67ce672f5c4 100644
--- a/lib/radix-tree.c
+++ b/lib/radix-tree.c
@@ -33,6 +33,7 @@
  * Radix tree node cache.
  */
 struct kmem_cache *radix_tree_node_cachep;
+EXPORT_SYMBOL(radix_tree_node_cachep);
 
 /*
  * The radix tree is variable-height, so an insert operation not only has
@@ -1566,14 +1567,14 @@ void idr_destroy(struct idr *idr)
 }
 EXPORT_SYMBOL(idr_destroy);
 
-static void
-radix_tree_node_ctor(void *arg)
+void radix_tree_node_ctor(void *arg)
 {
 	struct radix_tree_node *node = arg;
 
 	memset(node, 0, sizeof(*node));
 	INIT_LIST_HEAD(&node->private_list);
 }
+EXPORT_SYMBOL(radix_tree_node_ctor);
 
 static int radix_tree_cpu_dead(unsigned int cpu)
 {
@@ -1598,10 +1599,16 @@ void __init radix_tree_init(void)
 	BUILD_BUG_ON(RADIX_TREE_MAX_TAGS + __GFP_BITS_SHIFT > 32);
 	BUILD_BUG_ON(ROOT_IS_IDR & ~GFP_ZONEMASK);
 	BUILD_BUG_ON(XA_CHUNK_SIZE > 255);
-	radix_tree_node_cachep = kmem_cache_create("radix_tree_node",
-			sizeof(struct radix_tree_node), 0,
-			SLAB_PANIC | SLAB_RECLAIM_ACCOUNT,
-			radix_tree_node_ctor);
+
+	struct kmem_cache_args args = {
+		.ctor = radix_tree_node_ctor,
+		.sheaf_capacity = 64,
+	};
+
+	radix_tree_node_cachep = kmem_cache_create(
+		"radix_tree_node", sizeof(struct radix_tree_node), &args,
+		SLAB_PANIC | SLAB_RECLAIM_ACCOUNT);
+
 	ret = cpuhp_setup_state_nocalls(CPUHP_RADIX_DEAD, "lib/radix:dead",
 					NULL, radix_tree_cpu_dead);
 	WARN_ON(ret < 0);
diff --git a/lib/xarray.c b/lib/xarray.c
index bfe7bef80f34eb..49fbec5f6c38e8 100644
--- a/lib/xarray.c
+++ b/lib/xarray.c
@@ -437,11 +437,6 @@ static unsigned long max_index(void *entry)
 	return (XA_CHUNK_SIZE << xa_to_node(entry)->shift) - 1;
 }
 
-static inline void *xa_zero_to_null(void *entry)
-{
-	return xa_is_zero(entry) ? NULL : entry;
-}
-
 static void xas_shrink(struct xa_state *xas)
 {
 	struct xarray *xa = xas->xa;
@@ -1627,13 +1622,6 @@ void *xa_load(struct xarray *xa, unsigned long index)
 }
 EXPORT_SYMBOL(xa_load);
 
-static void *xas_result(struct xa_state *xas, void *curr)
-{
-	if (xas_error(xas))
-		curr = xas->xa_node;
-	return curr;
-}
-
 /**
  * __xa_erase() - Erase this entry from the XArray while locked.
  * @xa: XArray.
diff --git a/mm/slub.c b/mm/slub.c
index cd671b93471918..21811b9ff791f4 100644
--- a/mm/slub.c
+++ b/mm/slub.c
@@ -5292,6 +5292,7 @@ kmem_cache_prefill_sheaf(struct kmem_cache *s, gfp_t gfp, unsigned int size)
 
 	return sheaf;
 }
+EXPORT_SYMBOL(kmem_cache_prefill_sheaf);
 
 /*
  * Use this to return a sheaf obtained by kmem_cache_prefill_sheaf()
@@ -5347,6 +5348,7 @@ void kmem_cache_return_sheaf(struct kmem_cache *s, gfp_t gfp,
 	barn_put_full_sheaf(barn, sheaf);
 	stat(s, BARN_PUT);
 }
+EXPORT_SYMBOL(kmem_cache_return_sheaf);
 
 /*
  * Refill a sheaf previously returned by kmem_cache_prefill_sheaf to at least
@@ -5402,6 +5404,7 @@ int kmem_cache_refill_sheaf(struct kmem_cache *s, gfp_t gfp,
 	*sheafp = sheaf;
 	return 0;
 }
+EXPORT_SYMBOL(kmem_cache_refill_sheaf);
 
 /*
  * Allocate from a sheaf obtained by kmem_cache_prefill_sheaf()
@@ -5440,6 +5443,7 @@ kmem_cache_alloc_from_sheaf_noprof(struct kmem_cache *s, gfp_t gfp,
 
 	return ret;
 }
+EXPORT_SYMBOL(kmem_cache_alloc_from_sheaf_noprof);
 
 unsigned int kmem_cache_sheaf_size(struct slab_sheaf *sheaf)
 {
diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h
index 3791af0aadc73e..fb76a2d30449a1 100644
--- a/rust/bindings/bindings_helper.h
+++ b/rust/bindings/bindings_helper.h
@@ -127,9 +127,20 @@ const blk_features_t RUST_CONST_HELPER_BLK_FEAT_ROTATIONAL = BLK_FEAT_ROTATIONAL
 const fop_flags_t RUST_CONST_HELPER_FOP_UNSIGNED_OFFSET = FOP_UNSIGNED_OFFSET;
 
 const xa_mark_t RUST_CONST_HELPER_XA_PRESENT = XA_PRESENT;
+const xa_mark_t RUST_CONST_HELPER_XA_FREE_MARK = XA_FREE_MARK;
 
 const gfp_t RUST_CONST_HELPER_XA_FLAGS_ALLOC = XA_FLAGS_ALLOC;
 const gfp_t RUST_CONST_HELPER_XA_FLAGS_ALLOC1 = XA_FLAGS_ALLOC1;
+/*
+ * `XAS_RESTART` is `((struct xa_node *)3UL)` -- a sentinel pointer value, not
+ * an address. Cast to `size_t` so bindgen emits a plain `usize` constant; for
+ * pointer-typed macro values bindgen otherwise generates a `pub static mut`,
+ * see https://github.com/rust-lang/rust-bindgen/issues/3347.
+ */
+const size_t RUST_CONST_HELPER_XAS_RESTART = (size_t)XAS_RESTART;
+const size_t RUST_CONST_HELPER_XA_CHUNK_SHIFT = XA_CHUNK_SHIFT;
+const size_t RUST_CONST_HELPER_XA_CHUNK_SIZE = XA_CHUNK_SIZE;
+extern struct kmem_cache *radix_tree_node_cachep;
 
 const vm_flags_t RUST_CONST_HELPER_VM_MERGEABLE = VM_MERGEABLE;
 const vm_flags_t RUST_CONST_HELPER_VM_READ = VM_READ;
diff --git a/rust/helpers/xarray.c b/rust/helpers/xarray.c
index 08979b3043410f..d7548a17ae0d06 100644
--- a/rust/helpers/xarray.c
+++ b/rust/helpers/xarray.c
@@ -26,3 +26,18 @@ __rust_helper void rust_helper_xa_unlock(struct xarray *xa)
 {
 	return xa_unlock(xa);
 }
+
+__rust_helper void *rust_helper_xas_result(struct xa_state *xas, void *curr)
+{
+	return xas_result(xas, curr);
+}
+
+__rust_helper void *rust_helper_xa_zero_to_null(void *entry)
+{
+	return xa_zero_to_null(entry);
+}
+
+__rust_helper int rust_helper_xas_error(const struct xa_state *xas)
+{
+	return xas_error(xas);
+}
diff --git a/rust/kernel/mm.rs b/rust/kernel/mm.rs
index 58bc1793fdaf5e..c1920f04917093 100644
--- a/rust/kernel/mm.rs
+++ b/rust/kernel/mm.rs
@@ -18,6 +18,7 @@
 };
 use core::{ops::Deref, ptr::NonNull};
 
+pub mod sheaf;
 pub mod virt;
 use virt::VmaRef;
 
diff --git a/rust/kernel/mm/sheaf.rs b/rust/kernel/mm/sheaf.rs
new file mode 100644
index 00000000000000..9afbac20241868
--- /dev/null
+++ b/rust/kernel/mm/sheaf.rs
@@ -0,0 +1,762 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Slub allocator sheaf abstraction.
+//!
+//! Sheaves are percpu array-based caching layers for the slub allocator.
+//! They provide a mechanism for pre-allocating objects that can later
+//! be retrieved without risking allocation failure, making them useful in
+//! contexts where memory allocation must be guaranteed to succeed.
+//!
+//! The term "sheaf" is the english word for a bundle of straw. In this context
+//! it means a bundle of pre-allocated objects. A per-NUMA-node cache of sheaves
+//! is called a "barn". Because you store your sheafs in barns.
+//!
+//! # Use cases
+//!
+//! Sheaves are particularly useful when:
+//!
+//! - Allocations must be guaranteed to succeed in a restricted context (e.g.,
+//!   while holding locks or in atomic context).
+//! - Multiple allocations need to be performed as a batch operation.
+//! - Fast-path allocation performance is critical, as sheaf allocations avoid
+//!   atomic operations by using local locks with preemption disabled. Note
+//!   that the abstraction adds reference counting on top of this for dynamic
+//!   caches, see [`Sheaf`].
+//!
+//! # Architecture
+//!
+//! The sheaf system supports two modes of operation:
+//!
+//! - **Static caches**: [`KMemCache`] represents a cache that is never
+//!   destroyed, typically one created by C code at kernel boot time. These
+//!   have `'static` lifetime and produce [`StaticSheaf`] instances.
+//! - **Dynamic caches**: [`KMemCacheHandle`] owns a cache created through
+//!   this abstraction. These are reference-counted, destroyed when the last
+//!   reference is dropped, and produce [`DynamicSheaf`] instances.
+//!
+//! Both modes use the same core types:
+//!
+//! - [`Sheaf`]: A pre-filled container of objects from a specific cache.
+//! - [`SBox`]: An owned allocation from a sheaf, similar to a `Box`.
+//!
+//! # Example
+//!
+//! Using a dynamically created cache:
+//!
+//! ```
+//! use kernel::c_str;
+//! use kernel::mm::sheaf::{KMemCacheHandle, KMemCacheInit, Sheaf, SBox};
+//! use kernel::prelude::*;
+//!
+//! struct MyObject {
+//!     value: u32,
+//! }
+//!
+//! impl KMemCacheInit<MyObject> for MyObject {
+//!     fn init() -> impl Init<MyObject> {
+//!         init!(MyObject { value: 0 })
+//!     }
+//! }
+//!
+//! // Create a cache with a sheaf capacity of at least 16 objects.
+//! let cache = KMemCacheHandle::<MyObject>::new(c_str!("my_cache"), 16)?;
+//!
+//! // Pre-fill a sheaf with 8 objects.
+//! let mut sheaf = cache.as_arc_borrow().sheaf(8, GFP_KERNEL)?;
+//!
+//! // Allocations from the sheaf are guaranteed to succeed until empty.
+//! let obj = sheaf.alloc().unwrap();
+//!
+//! // Return the sheaf when done, attempting to refill it.
+//! sheaf.return_refill(GFP_KERNEL);
+//! # Ok::<(), Error>(())
+//! ```
+//!
+//! # Constraints
+//!
+//! - Sheaves are slower when `CONFIG_SLUB_TINY` is enabled, or when slab
+//!   debugging (`slab_debug`) is enabled for the cache, due to cpu sheaves
+//!   being disabled. All prefilled sheaves become "oversize" and go through a
+//!   slower allocation path.
+//! - The sheaf capacity of a cache is decided at cache creation time. The
+//!   capacity requested when creating the cache is a minimum. The allocator
+//!   calculates a capacity based on the object size and uses the larger of the
+//!   two.
+
+use core::{
+    convert::Infallible,
+    marker::PhantomData,
+    ops::{Deref, DerefMut},
+    ptr::NonNull,
+};
+
+use kernel::prelude::*;
+
+use crate::{
+    sync::{Arc, ArcBorrow},
+    types::Opaque,
+};
+
+/// A slab cache with sheaf support.
+///
+/// This type is a transparent wrapper around a kernel `kmem_cache`. It can be
+/// used with caches created either by C code or via [`KMemCacheHandle`].
+///
+/// When a reference to this type has `'static` lifetime (i.e., `&'static
+/// KMemCache<T>`), it represents a cache that is never destroyed, typically
+/// one created by C code at boot time. Such references produce
+/// [`StaticSheaf`] instances via [`sheaf`].
+///
+/// [`sheaf`]: KMemCache::sheaf
+///
+/// # Type parameter
+///
+/// - `T`: The type of objects managed by this cache. Must implement
+///   [`KMemCacheInit`] to provide initialization logic for allocations.
+#[repr(transparent)]
+pub struct KMemCache<T: KMemCacheInit<T>> {
+    inner: Opaque<bindings::kmem_cache>,
+    _p: PhantomData<T>,
+}
+
+// SAFETY: The C `kmem_cache` is internally synchronized and has no thread
+// affinity, so a `KMemCache<T>` may be sent to another thread if the objects
+// it manages can.
+unsafe impl<T: KMemCacheInit<T> + Send> Send for KMemCache<T> {}
+
+// SAFETY: All operations available through `&KMemCache<T>` (creating sheaves
+// and allocating objects) are internally synchronized by the C side, so the
+// cache may be used from multiple threads concurrently if the objects it
+// manages can be sent between threads.
+unsafe impl<T: KMemCacheInit<T> + Send> Sync for KMemCache<T> {}
+
+impl<T: KMemCacheInit<T>> KMemCache<T> {
+    /// Creates a pre-filled sheaf from this cache.
+    ///
+    /// Allocates a sheaf and pre-fills it with `size` objects. Once created,
+    /// allocations from the sheaf via [`Sheaf::alloc`] are guaranteed to
+    /// succeed until the sheaf is depleted.
+    ///
+    /// # Arguments
+    ///
+    /// - `size`: The number of objects to pre-allocate. Must not be zero. If
+    ///   `size` exceeds the sheaf capacity of the cache, an "oversize" sheaf
+    ///   is allocated. Oversize sheaves are slower to create, and they are
+    ///   flushed and freed rather than cached for reuse when returned.
+    /// - `gfp`: Allocation flags controlling how memory is obtained. Use
+    ///   [`GFP_KERNEL`] for normal allocations that may sleep, or
+    ///   [`GFP_NOWAIT`] for non-blocking allocations.
+    ///
+    /// # Errors
+    ///
+    /// Returns [`ENOMEM`] if the sheaf or its objects could not be allocated,
+    /// or if `size` is zero.
+    #[inline]
+    pub fn sheaf(
+        &'static self,
+        size: usize,
+        gfp: kernel::alloc::Flags,
+    ) -> Result<Sheaf<'static, T, Static>> {
+        // SAFETY: `self.as_raw()` returns a valid cache pointer, and `size`
+        // has been validated to fit in a `c_uint`.
+        let ptr = unsafe {
+            bindings::kmem_cache_prefill_sheaf(self.inner.get(), gfp.as_raw(), size.try_into()?)
+        };
+
+        // INVARIANT: `ptr` was returned by `kmem_cache_prefill_sheaf` and is
+        // non-null (checked below). `cache` is the cache from which this sheaf
+        // was created. `dropped` is false since the sheaf has not been returned.
+        Ok(Sheaf {
+            sheaf: NonNull::new(ptr).ok_or(ENOMEM)?,
+            // SAFETY: `self` is a valid reference, so the pointer is non-null.
+            cache: CacheRef::Static(unsafe {
+                NonNull::new_unchecked((&raw const *self).cast_mut())
+            }),
+            dropped: false,
+            _p: PhantomData,
+        })
+    }
+
+    #[inline]
+    fn as_raw(&self) -> *mut bindings::kmem_cache {
+        self.inner.get()
+    }
+
+    /// Creates a reference to a [`KMemCache`] from a raw pointer.
+    ///
+    /// This is useful for wrapping a C-initialized static `kmem_cache`, such as
+    /// the global `radix_tree_node_cachep` used by XArrays.
+    ///
+    /// # Safety
+    ///
+    /// - `ptr` must be a valid pointer to a `kmem_cache` that was created for
+    ///   objects of type `T`.
+    /// - The cache must remain valid for the lifetime `'a`.
+    /// - The caller must ensure that the cache was configured appropriately for
+    ///   the type `T`, including proper size and alignment.
+    pub unsafe fn from_raw<'a>(ptr: *mut bindings::kmem_cache) -> &'a Self {
+        // SAFETY: The caller guarantees that `ptr` is a valid pointer to a
+        // `kmem_cache` created for objects of type `T`, that it remains valid
+        // for lifetime `'a`, and that the cache is properly configured for `T`.
+        unsafe { &*ptr.cast::<Self>() }
+    }
+}
+
+/// A slab cache with sheaf support.
+///
+/// This type wraps a kernel `kmem_cache` configured with a sheaf capacity,
+/// enabling pre-allocation of objects via [`Sheaf`].
+///
+/// For now, this type only exists for sheaf management.
+///
+/// # Type parameter
+///
+/// - `T`: The type of objects managed by this cache. Must implement
+///   [`KMemCacheInit`] to provide initialization logic for new allocations.
+///
+/// # Context
+///
+/// Dropping the last reference to a `KMemCacheHandle` destroys the cache via
+/// `kmem_cache_destroy`, which may sleep. [`SBox`] instances allocated from
+/// the handle each hold a reference, so the last reference may be dropped
+/// when an [`SBox`] is dropped. The last reference must not be dropped from a
+/// context where sleeping is not allowed.
+///
+/// A [`Sheaf`] created from the handle also holds a reference, but dropping
+/// a [`Sheaf`] never drops the last one. See the `# Lifecycle` section of
+/// [`Sheaf`].
+///
+/// # Invariants
+///
+/// - `cache` is a valid pointer to a `kmem_cache` created with
+///   `__kmem_cache_create_args`.
+/// - The cache is valid for the lifetime of this struct.
+#[repr(transparent)]
+pub struct KMemCacheHandle<T: KMemCacheInit<T>> {
+    cache: NonNull<KMemCache<T>>,
+}
+
+// SAFETY: `KMemCacheHandle<T>` owns a `kmem_cache`, which is internally
+// synchronized and has no thread affinity. The cache may be destroyed from a
+// thread other than the one that created it.
+unsafe impl<T: KMemCacheInit<T> + Send> Send for KMemCacheHandle<T> {}
+
+// SAFETY: All operations available through `&KMemCacheHandle<T>` are
+// internally synchronized by the C side, so the cache may be used from
+// multiple threads concurrently if the objects it manages can be sent between
+// threads.
+unsafe impl<T: KMemCacheInit<T> + Send> Sync for KMemCacheHandle<T> {}
+
+impl<T: KMemCacheInit<T>> KMemCacheHandle<T> {
+    /// Creates a new slab cache with sheaf support.
+    ///
+    /// Creates a kernel slab cache for objects of type `T` with at least the
+    /// specified sheaf capacity. The cache uses the provided `name` for
+    /// identification in `/sys/kernel/slab/` and debugging output.
+    ///
+    /// # Arguments
+    ///
+    /// - `name`: A string identifying the cache. This name appears in sysfs and
+    ///   debugging output.
+    /// - `sheaf_capacity`: The minimum number of objects a regular sheaf from
+    ///   this cache can hold. The allocator calculates a capacity based on the
+    ///   object size and uses the larger of the two, so a value of zero
+    ///   selects the calculated capacity. Set this to the largest `size` that
+    ///   is expected to be passed to [`sheaf`](Self::sheaf) to avoid oversize
+    ///   sheaves. The value is ignored when `CONFIG_SLUB_TINY` is enabled or
+    ///   when slab debugging (`slab_debug`) is enabled for the cache.
+    ///
+    /// # Errors
+    ///
+    /// Returns an error if:
+    ///
+    /// - The cache could not be created due to memory pressure.
+    /// - The size of `T` cannot be represented as a `c_uint`.
+    pub fn new(name: &CStr, sheaf_capacity: u32) -> Result<Arc<Self>>
+    where
+        T: KMemCacheInit<T>,
+    {
+        let flags = 0;
+        let mut args: bindings::kmem_cache_args = pin_init::zeroed();
+        args.sheaf_capacity = sheaf_capacity;
+
+        // With an alignment of zero, the slab allocator only guarantees
+        // `ARCH_SLAB_MINALIGN`, which may be smaller than the alignment of `T`.
+        args.align = core::mem::align_of::<T>().try_into()?;
+
+        // NOTE: We are not initializing at object allocation time, because
+        // there is no matching teardown function on the C side machinery.
+        args.ctor = None;
+
+        // SAFETY: `name` is a valid C string, `args` is properly initialized,
+        // and the size of `T` has been validated to fit in a `c_uint`.
+        let ptr = unsafe {
+            bindings::__kmem_cache_create_args(
+                name.as_char_ptr(),
+                core::mem::size_of::<T>().try_into()?,
+                &mut args,
+                flags,
+            )
+        };
+
+        // INVARIANT: `ptr` was returned by `__kmem_cache_create_args` and is
+        // non-null (checked below). The cache is valid until
+        // `kmem_cache_destroy` is called in `Drop`.
+        Ok(Arc::new(
+            Self {
+                cache: NonNull::new(ptr.cast()).ok_or(ENOMEM)?,
+            },
+            GFP_KERNEL,
+        )?)
+    }
+
+    /// Creates a pre-filled sheaf from this cache.
+    ///
+    /// Allocates a sheaf and pre-fills it with `size` objects. Once created,
+    /// allocations from the sheaf via [`Sheaf::alloc`] are guaranteed to
+    /// succeed until the sheaf is depleted.
+    ///
+    /// # Arguments
+    ///
+    /// - `size`: The number of objects to pre-allocate. Must not be zero. If
+    ///   `size` exceeds the sheaf capacity of the cache, an "oversize" sheaf
+    ///   is allocated. Oversize sheaves are slower to create, and they are
+    ///   flushed and freed rather than cached for reuse when returned.
+    /// - `gfp`: Allocation flags controlling how memory is obtained. Use
+    ///   [`GFP_KERNEL`] for normal allocations that may sleep, or
+    ///   [`GFP_NOWAIT`] for non-blocking allocations.
+    ///
+    /// # Errors
+    ///
+    /// Returns [`ENOMEM`] if the sheaf or its objects could not be allocated,
+    /// or if `size` is zero.
+    #[inline]
+    pub fn sheaf<'a>(
+        self: ArcBorrow<'a, Self>,
+        size: usize,
+        gfp: kernel::alloc::Flags,
+    ) -> Result<Sheaf<'a, T, Dynamic>> {
+        // SAFETY: `self.as_raw()` returns a valid cache pointer, and `size`
+        // has been validated to fit in a `c_uint`.
+        let ptr = unsafe {
+            bindings::kmem_cache_prefill_sheaf(self.as_raw(), gfp.as_raw(), size.try_into()?)
+        };
+
+        // INVARIANT: `ptr` was returned by `kmem_cache_prefill_sheaf` and is
+        // non-null (checked below). `cache` is the cache from which this sheaf
+        // was created. `dropped` is false since the sheaf has not been returned.
+        Ok(Sheaf {
+            sheaf: NonNull::new(ptr).ok_or(ENOMEM)?,
+            cache: CacheRef::Arc(self.into()),
+            dropped: false,
+            _p: PhantomData,
+        })
+    }
+
+    #[inline]
+    fn as_raw(&self) -> *mut bindings::kmem_cache {
+        self.cache.as_ptr().cast()
+    }
+}
+
+impl<T: KMemCacheInit<T>> Drop for KMemCacheHandle<T> {
+    fn drop(&mut self) {
+        // SAFETY: `self.as_raw()` returns a valid cache pointer that was
+        // created by `__kmem_cache_create_args`. As all objects allocated from
+        // this hold a reference on `self`, they must have been dropped for this
+        // `drop` method to execute.
+        unsafe { bindings::kmem_cache_destroy(self.as_raw()) };
+    }
+}
+
+/// Trait for types that can be initialized in a slab cache.
+///
+/// This trait provides the initialization logic for objects allocated from a
+/// [`KMemCache`]. The initializer is called when objects are allocated from a
+/// sheaf via [`Sheaf::alloc`].
+///
+/// # Implementation
+///
+/// Implementors must provide [`init`](KMemCacheInit::init), which returns an
+/// infallible initializer for the type.
+///
+/// # Example
+///
+/// ```
+/// use kernel::mm::sheaf::KMemCacheInit;
+/// use kernel::prelude::*;
+///
+/// struct MyData {
+///     counter: u32,
+///     name: [u8; 16],
+/// }
+///
+/// impl KMemCacheInit<MyData> for MyData {
+///     fn init() -> impl Init<MyData> {
+///         init!(MyData {
+///             counter: 0,
+///             name: [0; 16],
+///         })
+///     }
+/// }
+/// ```
+pub trait KMemCacheInit<T> {
+    /// Returns an initializer for creating new objects of type `T`.
+    ///
+    /// The initializer is applied to newly allocated objects when they are allocated from a sheaf
+    /// via [`Sheaf::alloc`]. The initializer should set all fields to their default or initial
+    /// values.
+    fn init() -> impl Init<T, Infallible>;
+}
+
+/// Marker type for sheaves from static caches.
+///
+/// Used as a type parameter for [`Sheaf`] to indicate the sheaf was created
+/// from a `&'static KMemCache<T>`.
+pub enum Static {}
+
+/// Marker type for sheaves from dynamic caches.
+///
+/// Used as a type parameter for [`Sheaf`] to indicate the sheaf was created
+/// from a [`KMemCacheHandle`] via [`ArcBorrow`].
+pub enum Dynamic {}
+
+/// A sheaf from a static cache.
+///
+/// This is a [`Sheaf`] backed by a `&'static KMemCache<T>`.
+pub type StaticSheaf<'a, T> = Sheaf<'a, T, Static>;
+
+/// A sheaf from a dynamic cache.
+///
+/// This is a [`Sheaf`] backed by a reference-counted [`KMemCacheHandle`].
+pub type DynamicSheaf<'a, T> = Sheaf<'a, T, Dynamic>;
+
+/// A pre-filled container of slab objects.
+///
+/// A sheaf holds a set of pre-allocated objects from a [`KMemCache`].
+/// Allocations from a sheaf are guaranteed to succeed until the sheaf is
+/// depleted, making sheaves useful in contexts where allocation failure is
+/// not acceptable.
+///
+/// Sheaves provide faster allocation than direct allocation because they use
+/// local locks with preemption disabled rather than atomic operations. Note
+/// that each [`SBox`] allocated from a [`DynamicSheaf`] holds a reference to
+/// the [`KMemCacheHandle`] the sheaf was created from, to keep the cache
+/// alive until the object is freed. [`Sheaf::alloc`] thus increments the
+/// reference count of the handle, and dropping the [`SBox`] decrements it.
+/// Both are atomic operations on a counter that is shared by all users of the
+/// cache.
+///
+/// This does not apply to a [`StaticSheaf`]. A static cache is never
+/// destroyed, so objects allocated from it do not hold a reference and no
+/// reference counting takes place.
+///
+/// # Type parameters
+///
+/// - `'a`: The lifetime of the cache reference the sheaf was created from.
+///   The cache is guaranteed to outlive `'a`.
+/// - `T`: The type of objects in this sheaf.
+/// - `A`: Either [`Static`] or [`Dynamic`], indicating whether the backing
+///   cache is a static reference or a reference-counted handle.
+///
+/// For convenience, [`StaticSheaf`] and [`DynamicSheaf`] type aliases are
+/// provided.
+///
+/// # Lifecycle
+///
+/// Sheaves are created via [`KMemCache::sheaf`] or [`KMemCacheHandle::sheaf`]
+/// and should be returned to the allocator when no longer needed via
+/// [`Sheaf::return_refill`]. If a sheaf is simply dropped, it is returned with
+/// `GFP_NOWAIT` flags, which may result in the sheaf being flushed and freed
+/// rather than being cached for reuse.
+///
+/// A sheaf created from a [`KMemCacheHandle`] holds a reference to the
+/// handle. Dropping the sheaf never drops the last reference to the handle,
+/// and thus never destroys the cache: [`KMemCacheHandle::sheaf`] ties the
+/// lifetime `'a` of the sheaf to the [`ArcBorrow`] it is called on, so the
+/// reference the [`ArcBorrow`] was created from outlives the sheaf. A sheaf
+/// can therefore be dropped in a context where sleeping is not allowed. Note
+/// that this does not extend to [`SBox`] instances allocated from the sheaf.
+///
+/// # Invariants
+///
+/// - `sheaf` is a valid pointer to a `slab_sheaf` obtained from
+///   `kmem_cache_prefill_sheaf`.
+/// - `cache` is the cache from which this sheaf was created.
+/// - `dropped` tracks whether the sheaf has been explicitly returned.
+pub struct Sheaf<'a, T: KMemCacheInit<T>, A> {
+    sheaf: NonNull<bindings::slab_sheaf>,
+    cache: CacheRef<T>,
+    dropped: bool,
+    _p: PhantomData<(&'a KMemCache<T>, A)>,
+}
+
+// SAFETY: A prefilled sheaf is exclusively owned by the caller and has no
+// affinity to the CPU or thread that created it: `kmem_cache_alloc_from_sheaf`
+// does not touch percpu state, and `kmem_cache_return_sheaf` reattaches the
+// sheaf to the CPU that is current at return time. Thus the sheaf may be sent
+// to another thread if the objects it manages can.
+unsafe impl<T: KMemCacheInit<T> + Send, A> Send for Sheaf<'_, T, A> {}
+
+// NOTE: `Sheaf` is deliberately not `Sync`. The C side mutates sheaf state
+// without synchronization, relying on the caller's exclusive ownership. The
+// mutable receivers of the methods on `Sheaf` enforce this exclusivity.
+
+impl<'a, T: KMemCacheInit<T>, A> Sheaf<'a, T, A> {
+    #[inline]
+    fn as_raw(&self) -> *mut bindings::slab_sheaf {
+        self.sheaf.as_ptr()
+    }
+
+    /// Return the sheaf and try to refill using `flags`.
+    ///
+    /// If the sheaf cannot simply become the percpu spare sheaf, but there's
+    /// space for a full sheaf in the barn, we try to refill the sheaf back to
+    /// the cache's sheaf_capacity to avoid handling partially full sheaves.
+    ///
+    /// If the refill fails because gfp is e.g. GFP_NOWAIT, or the barn is full,
+    /// the sheaf is instead flushed and freed.
+    #[inline]
+    pub fn return_refill(mut self, flags: kernel::alloc::Flags) {
+        self.dropped = true;
+        // SAFETY: `self.cache.as_raw()` and `self.as_raw()` return valid
+        // pointers to the cache and sheaf respectively.
+        unsafe {
+            bindings::kmem_cache_return_sheaf(self.cache.as_raw(), flags.as_raw(), self.as_raw())
+        };
+        drop(self);
+    }
+
+    /// Refills the sheaf to at least the specified size.
+    ///
+    /// Replenishes the sheaf by preallocating objects until it contains at
+    /// least `size` objects. If the sheaf already contains `size` or more
+    /// objects, this is a no-op. In practice, the sheaf is refilled to its
+    /// full capacity.
+    ///
+    /// # Arguments
+    ///
+    /// - `flags`: Allocation flags controlling how memory is obtained.
+    /// - `size`: The minimum number of objects the sheaf should contain after
+    ///   refilling. If `size` exceeds the cache's `sheaf_capacity`, the sheaf
+    ///   may be replaced with a larger one.
+    ///
+    /// # Errors
+    ///
+    /// Returns an error if the objects could not be allocated. If refilling
+    /// fails, the existing sheaf is left intact.
+    pub fn refill(&mut self, flags: kernel::alloc::Flags, size: usize) -> Result {
+        // SAFETY: `self.cache.as_raw()` returns a valid cache pointer and
+        // `&raw mut self.sheaf` points to a valid sheaf per the type invariants.
+        kernel::error::to_result(unsafe {
+            bindings::kmem_cache_refill_sheaf(
+                self.cache.as_raw(),
+                flags.as_raw(),
+                (&raw mut (self.sheaf)).cast(),
+                size.try_into()?,
+            )
+        })
+    }
+
+    /// Allocates an object from the sheaf.
+    ///
+    /// Returns a new [`SBox`] containing an initialized object, or [`None`]
+    /// if the sheaf is depleted. Allocations are guaranteed to succeed as
+    /// long as the sheaf contains pre-allocated objects.
+    ///
+    /// The `gfp` flags passed to `kmem_cache_alloc_from_sheaf` are set to zero,
+    /// meaning no additional flags like `__GFP_ZERO` or `__GFP_ACCOUNT` are
+    /// applied.
+    ///
+    /// The returned `T` is initialized as part of this function.
+    pub fn alloc(&mut self) -> Option<SBox<T>> {
+        // SAFETY: `self.cache.as_raw()` and `self.as_raw()` return valid
+        // pointers. The function returns NULL when the sheaf is empty.
+        let ptr = unsafe {
+            bindings::kmem_cache_alloc_from_sheaf_noprof(self.cache.as_raw(), 0, self.as_raw())
+        };
+
+        let ptr = NonNull::new(ptr.cast::<T>())?;
+
+        // SAFETY:
+        // - `ptr` is a valid, non-null pointer as it was just returned by the
+        //   cache.
+        // - The initializer is infallible, so an error is never returned.
+        unsafe { T::init().__init(ptr.as_ptr()) }.expect("Initializer is infallible");
+
+        // INVARIANT: `ptr` was returned by `kmem_cache_alloc_from_sheaf_noprof`
+        // and initialized above. `cache` is the cache from which this object
+        // was allocated. The object remains valid until freed in `Drop`.
+        Some(SBox {
+            ptr,
+            cache: self.cache.clone(),
+        })
+    }
+}
+
+impl<'a, T: KMemCacheInit<T>, A> Drop for Sheaf<'a, T, A> {
+    fn drop(&mut self) {
+        if !self.dropped {
+            // SAFETY: `self.cache.as_raw()` and `self.as_raw()` return valid
+            // pointers. Using `GFP_NOWAIT` because the drop may occur in a
+            // context where sleeping is not permitted.
+            unsafe {
+                bindings::kmem_cache_return_sheaf(
+                    self.cache.as_raw(),
+                    GFP_NOWAIT.as_raw(),
+                    self.as_raw(),
+                )
+            };
+        }
+    }
+}
+
+/// Internal reference to a cache, either static or reference-counted.
+///
+/// # Invariants
+///
+/// - For `CacheRef::Static`: the `NonNull` points to a valid `KMemCache<T>`
+///   with `'static` lifetime, derived from a `&'static KMemCache<T>` reference.
+enum CacheRef<T: KMemCacheInit<T>> {
+    /// A reference-counted handle to a dynamically created cache.
+    Arc(Arc<KMemCacheHandle<T>>),
+    /// A pointer to a static lifetime cache.
+    Static(NonNull<KMemCache<T>>),
+}
+
+impl<T: KMemCacheInit<T>> Clone for CacheRef<T> {
+    fn clone(&self) -> Self {
+        match self {
+            Self::Arc(arg0) => Self::Arc(arg0.clone()),
+            Self::Static(arg0) => Self::Static(*arg0),
+        }
+    }
+}
+
+impl<T: KMemCacheInit<T>> CacheRef<T> {
+    #[inline]
+    fn as_raw(&self) -> *mut bindings::kmem_cache {
+        match self {
+            CacheRef::Arc(handle) => handle.as_raw(),
+            // SAFETY: By type invariant, `ptr` points to a valid `KMemCache<T>`
+            // with `'static` lifetime.
+            CacheRef::Static(ptr) => unsafe { ptr.as_ref() }.as_raw(),
+        }
+    }
+}
+
+/// An owned allocation from a cache sheaf.
+///
+/// `SBox` is similar to `Box` but is backed by a slab cache allocation obtained
+/// through a [`Sheaf`]. It provides owned access to an initialized object and
+/// ensures the object is properly freed back to the cache when dropped.
+///
+/// The contained `T` is initialized when the `SBox` is returned from alloc and
+/// dropped when the `SBox` is dropped.
+///
+/// An `SBox` allocated from a [`KMemCacheHandle`] backed sheaf holds a
+/// reference to the handle. Dropping the `SBox` may thus drop the last
+/// reference to the handle and destroy the cache, which may sleep. See the
+/// `# Context` section of [`KMemCacheHandle`].
+///
+/// # Invariants
+///
+/// - `ptr` points to a valid, initialized object of type `T`.
+/// - `cache` is the cache from which this object was allocated.
+/// - The object remains valid for the lifetime of the `SBox`.
+pub struct SBox<T: KMemCacheInit<T>> {
+    ptr: NonNull<T>,
+    cache: CacheRef<T>,
+}
+
+// SAFETY: `SBox<T>` owns a `T`. Sheaf allocated objects are ordinary slab
+// objects that may be freed from any thread, so an `SBox<T>` may be sent to
+// another thread if `T` can.
+unsafe impl<T: KMemCacheInit<T> + Send> Send for SBox<T> {}
+
+// SAFETY: `SBox<T>` has no interior mutability, so sharing `&SBox<T>` between
+// threads only shares `&T`.
+unsafe impl<T: KMemCacheInit<T> + Sync> Sync for SBox<T> {}
+
+impl<T: KMemCacheInit<T>> SBox<T> {
+    /// Consumes the `SBox` and returns the raw pointer to the contained value.
+    ///
+    /// The caller becomes responsible for freeing the memory. The object is not
+    /// dropped and remains initialized. Use [`static_from_ptr`] to reconstruct
+    /// an `SBox` from the pointer.
+    ///
+    /// This method is only intended for objects allocated from a static cache.
+    /// Calling it on an `SBox` backed by a [`KMemCacheHandle`] leaks a
+    /// reference on the handle, preventing the cache from ever being
+    /// destroyed, as [`static_from_ptr`] cannot restore the reference.
+    ///
+    /// [`static_from_ptr`]: SBox::static_from_ptr
+    pub fn into_ptr(self) -> *mut T {
+        debug_assert!(matches!(self.cache, CacheRef::Static(_)));
+        let ptr = self.ptr.as_ptr();
+        core::mem::forget(self);
+        ptr
+    }
+
+    /// Reconstructs an `SBox` from a raw pointer and cache.
+    ///
+    /// This is intended for use with objects that were previously converted to
+    /// raw pointers via [`into_ptr`], typically for passing through C code.
+    ///
+    /// [`into_ptr`]: SBox::into_ptr
+    ///
+    /// # Safety
+    ///
+    /// - `cache` must be a valid pointer to the `kmem_cache` from which `value`
+    ///   was allocated.
+    /// - `cache` must be a statically allocated cache that is never destroyed.
+    /// - `value` must be a valid pointer to an initialized `T` that was
+    ///   allocated from `cache`.
+    /// - The caller must ensure that no other `SBox` or reference exists for
+    ///   `value`.
+    pub unsafe fn static_from_ptr(cache: *mut bindings::kmem_cache, value: *mut T) -> Self {
+        // INVARIANT: The caller guarantees `value` points to a valid,
+        // initialized `T` allocated from `cache`.
+        Self {
+            // SAFETY: By function safety requirements, `value` is not null.
+            ptr: unsafe { NonNull::new_unchecked(value) },
+            cache: CacheRef::Static(
+                // SAFETY: By function safety requirements, `cache` is not null.
+                unsafe { NonNull::new_unchecked(cache.cast()) },
+            ),
+        }
+    }
+}
+
+impl<T: KMemCacheInit<T>> Deref for SBox<T> {
+    type Target = T;
+
+    #[inline]
+    fn deref(&self) -> &Self::Target {
+        // SAFETY: `ptr` is valid and properly aligned per the type invariants.
+        unsafe { self.ptr.as_ref() }
+    }
+}
+
+impl<T: KMemCacheInit<T>> DerefMut for SBox<T> {
+    #[inline]
+    fn deref_mut(&mut self) -> &mut Self::Target {
+        // SAFETY: `ptr` is valid and properly aligned per the type invariants,
+        // and we have exclusive access via `&mut self`.
+        unsafe { self.ptr.as_mut() }
+    }
+}
+
+impl<T: KMemCacheInit<T>> Drop for SBox<T> {
+    fn drop(&mut self) {
+        // SAFETY: By type invariant, `ptr` points to a valid and initialized
+        // object. We do not touch `ptr` after returning it to the cache.
+        unsafe { core::ptr::drop_in_place(self.ptr.as_ptr()) };
+
+        // SAFETY: `self.ptr` was allocated from `self.cache` via
+        // `kmem_cache_alloc_from_sheaf_noprof` and is valid.
+        unsafe {
+            bindings::kmem_cache_free(self.cache.as_raw(), self.ptr.as_ptr().cast());
+        }
+    }
+}
diff --git a/rust/kernel/xarray.rs b/rust/kernel/xarray.rs
index 987c9c0c219891..20792b09c12662 100644
--- a/rust/kernel/xarray.rs
+++ b/rust/kernel/xarray.rs
@@ -4,20 +4,101 @@
 //!
 //! C header: [`include/linux/xarray.h`](srctree/include/linux/xarray.h)
 
-use crate::{
+use core::{
+    convert::Infallible,
+    iter,
+    marker::PhantomData,
+    pin::Pin,
+    ptr::{
+        null_mut,
+        NonNull, //
+    },
+};
+pub use entry::{
+    Entry,
+    OccupiedEntry,
+    VacantEntry, //
+};
+use kernel::{
     alloc,
     bindings,
     build_assert::build_assert,
-    error::{Error, Result},
+    error::{
+        code::*,
+        to_result,
+        Error,
+        Result, //
+    },
     ffi::c_void,
+    fmt,
+    mm::sheaf::{
+        KMemCache,
+        SBox,
+        StaticSheaf, //
+    },
     types::{
         ForeignOwnable,
         NotThreadSafe,
         Opaque, //
     }, //
 };
-use core::{iter, marker::PhantomData, pin::Pin, ptr::NonNull};
-use pin_init::{pin_data, pin_init, pinned_drop, PinInit};
+use pin_init::{
+    init,
+    pin_data,
+    pin_init,
+    pinned_drop,
+    Init,
+    PinInit, //
+};
+
+/// Sheaf of preallocated [`XArray`] nodes.
+pub type XArraySheaf<'a> = StaticSheaf<'a, XArrayNode>;
+
+/// Returns a reference to the global XArray node cache.
+///
+/// This provides access to the kernel's `radix_tree_node_cachep`, which is the
+/// slab cache used for allocating internal XArray nodes. This cache can be used
+/// to create sheaves for preallocating XArray nodes.
+pub fn xarray_kmem_cache() -> &'static KMemCache<XArrayNode> {
+    // SAFETY: `radix_tree_node_cachep` is a valid, statically initialized
+    // kmem_cache that remains valid for the lifetime of the kernel. The cache
+    // is configured for `xa_node` objects which match our `XArrayNode` type.
+    unsafe { KMemCache::from_raw(bindings::radix_tree_node_cachep) }
+}
+
+/// An preallocated XArray node.
+///
+/// This represents a single preallocated internal node for an XArray.
+///
+/// This type is `#[repr(transparent)]` as it is cast to and from pointers to
+/// the inner [`bindings::xa_node`].
+#[repr(transparent)]
+pub struct XArrayNode {
+    node: Opaque<bindings::xa_node>,
+}
+
+// SAFETY: A preallocated `xa_node` is opaque storage for the C XArray
+// implementation, which moves nodes between CPUs freely. It is not tied to
+// the thread that allocated it.
+unsafe impl Send for XArrayNode {}
+
+impl kernel::mm::sheaf::KMemCacheInit<XArrayNode> for XArrayNode {
+    fn init() -> impl Init<Self, Infallible> {
+        init!(Self {
+            // SAFETY:
+            // - This initialization cannot fail and will never return `Err`.
+            // - The xa_node does not move during initialization.
+            node <- unsafe {
+                pin_init::init_from_closure(
+                    |place: *mut Opaque<bindings::xa_node>| -> Result<(), Infallible> {
+                        bindings::radix_tree_node_ctor(place.cast::<c_void>());
+                        Ok(())
+                    },
+                )
+            }
+        })
+    }
+}
 
 /// An array which efficiently maps sparse integer indices to owned objects.
 ///
@@ -50,7 +131,10 @@
 /// *guard.get_mut(0).unwrap() = 0xffff;
 /// assert_eq!(guard.get(0).copied(), Some(0xffff));
 ///
-/// assert_eq!(guard.store(0, beef, GFP_KERNEL)?.as_deref().copied(), Some(0xffff));
+/// assert_eq!(
+///     guard.store(0, beef, GFP_KERNEL)?.as_deref().copied(),
+///     Some(0xffff)
+/// );
 /// assert_eq!(guard.get(0).copied(), Some(0xbeef));
 ///
 /// guard.remove(0);
@@ -112,15 +196,22 @@ fn iter(&self) -> impl Iterator<Item = NonNull<c_void>> + '_ {
         let mut index = 0;
 
         // SAFETY: `self.xa` is always valid by the type invariant.
-        iter::once(unsafe {
-            bindings::xa_find(self.xa.get(), &mut index, usize::MAX, bindings::XA_PRESENT)
-        })
-        .chain(iter::from_fn(move || {
-            // SAFETY: `self.xa` is always valid by the type invariant.
-            Some(unsafe {
-                bindings::xa_find_after(self.xa.get(), &mut index, usize::MAX, bindings::XA_PRESENT)
-            })
-        }))
+        Iterator::chain(
+            iter::once(unsafe {
+                bindings::xa_find(self.xa.get(), &mut index, usize::MAX, bindings::XA_PRESENT)
+            }),
+            iter::from_fn(move || {
+                // SAFETY: `self.xa` is always valid by the type invariant.
+                Some(unsafe {
+                    bindings::xa_find_after(
+                        self.xa.get(),
+                        &mut index,
+                        usize::MAX,
+                        bindings::XA_PRESENT,
+                    )
+                })
+            }),
+        )
         .map_while(|ptr| NonNull::new(ptr.cast()))
     }
 
@@ -141,7 +232,6 @@ pub fn try_lock(&self) -> Option<Guard<'_, T>> {
     pub fn lock(&self) -> Guard<'_, T> {
         // SAFETY: `self.xa` is always valid by the type invariant.
         unsafe { bindings::xa_lock(self.xa.get()) };
-
         Guard {
             xa: self,
             _not_send: NotThreadSafe,
@@ -152,6 +242,21 @@ pub fn lock(&self) -> Guard<'_, T> {
 /// A lock guard.
 ///
 /// The lock is unlocked when the guard goes out of scope.
+///
+/// # Temporary lock drops
+///
+/// Unlike a typical Rust lock guard, holding a `Guard` does not guarantee
+/// continuous mutual exclusion for its entire lifetime: [`store`] may drop and
+/// reacquire the lock to allocate memory when called with blocking allocation
+/// flags. Other threads may lock and modify the array in that window, so a
+/// sequence of operations on the guard that spans such a call is not atomic.
+///
+/// To modify the array without dropping the lock, use the entry API with
+/// preallocated memory, see [`entry`] and [`insert_entry`].
+///
+/// [`store`]: Guard::store
+/// [`entry`]: Guard::entry
+/// [`insert_entry`]: Guard::insert_entry
 #[must_use = "the lock unlocks immediately when the guard is unused"]
 pub struct Guard<'a, T: ForeignOwnable> {
     xa: &'a XArray<T>,
@@ -177,6 +282,15 @@ pub struct StoreError<T> {
     pub value: T,
 }
 
+impl<T> fmt::Debug for StoreError<T> {
+    #[inline]
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        f.debug_struct("StoreError")
+            .field("error", &self.error)
+            .finish()
+    }
+}
+
 impl<T> From<StoreError<T>> for Error {
     #[inline]
     fn from(value: StoreError<T>) -> Self {
@@ -185,30 +299,194 @@ fn from(value: StoreError<T>) -> Self {
 }
 
 impl<'a, T: ForeignOwnable> Guard<'a, T> {
-    fn load<F, U>(&self, index: usize, f: F) -> Option<U>
-    where
-        F: FnOnce(NonNull<c_void>) -> U,
-    {
-        // SAFETY: `self.xa.xa` is always valid by the type invariant.
-        let ptr = unsafe { bindings::xa_load(self.xa.xa.get(), index) };
-        let ptr = NonNull::new(ptr.cast())?;
-        Some(f(ptr))
+    #[inline]
+    fn load(&self, index: usize) -> Option<NonNull<c_void>> {
+        XArrayState::new(self, index).load()
     }
 
     /// Provides a reference to the element at the given index.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray}};
+    /// let xa = KBox::pin_init(XArray::<KBox<u32>>::new(AllocKind::Alloc1), GFP_KERNEL)?;
+    /// let mut guard = xa.lock();
+    ///
+    /// // Expanding an empty `Alloc1` array stores an internal zero entry at
+    /// // index 0. It must not be visible through the API.
+    /// guard.store(5, KBox::new(0xcafeu32, GFP_ATOMIC)?, GFP_ATOMIC)?;
+    /// assert_eq!(guard.get(0), None);
+    /// assert_eq!(guard.find_next(0).map(|(i, v)| (i, *v)), Some((5, 0xcafe)));
+    ///
+    /// # Ok::<(), kernel::error::Error>(())
+    /// ```
+    #[inline]
     pub fn get(&self, index: usize) -> Option<T::Borrowed<'_>> {
-        self.load(index, |ptr| {
-            // SAFETY: `ptr` came from `T::into_foreign`.
-            unsafe { T::borrow(ptr.as_ptr()) }
-        })
+        let ptr = self.load(index)?;
+        // SAFETY: `ptr` came from `T::into_foreign`.
+        Some(unsafe { T::borrow(ptr.as_ptr()) })
     }
 
     /// Provides a mutable reference to the element at the given index.
+    #[inline]
     pub fn get_mut(&mut self, index: usize) -> Option<T::BorrowedMut<'_>> {
-        self.load(index, |ptr| {
+        let ptr = self.load(index)?;
+        // SAFETY: `ptr` came from `T::into_foreign`.
+        Some(unsafe { T::borrow_mut(ptr.as_ptr()) })
+    }
+
+    /// Gets an entry for the specified index, which can be vacant or occupied.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray, Entry}};
+    /// let mut xa = KBox::pin_init(XArray::<KBox<u32>>::new(AllocKind::Alloc), GFP_KERNEL)?;
+    /// let mut guard = xa.lock();
+    ///
+    /// assert!(guard.get(42).is_none());
+    ///
+    /// match guard.entry(42) {
+    ///     Entry::Vacant(entry) => {
+    ///         entry.insert(KBox::new(0x1337u32, GFP_ATOMIC)?, None)?;
+    ///     }
+    ///     Entry::Occupied(_) => unreachable!("We did not insert an entry yet"),
+    /// }
+    ///
+    /// assert_eq!(guard.get(42), Some(&0x1337));
+    ///
+    /// # Ok::<(), kernel::error::Error>(())
+    /// ```
+    pub fn entry<'b>(&'b mut self, index: usize) -> Entry<'a, 'b, T> {
+        match self.load(index) {
+            None => Entry::Vacant(VacantEntry::new(self, index)),
+            Some(ptr) => Entry::Occupied(OccupiedEntry::new(self, index, ptr)),
+        }
+    }
+
+    #[inline]
+    fn load_next(&self, index: usize) -> Option<(usize, NonNull<c_void>)> {
+        XArrayState::new(self, index).load_next(usize::MAX)
+    }
+
+    /// Finds the next element starting from the given index.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray}};
+    /// let mut xa = KBox::pin_init(XArray::<KBox<u32>>::new(AllocKind::Alloc), GFP_KERNEL)?;
+    /// let mut guard = xa.lock();
+    ///
+    /// guard.store(10, KBox::new(10u32, GFP_ATOMIC)?, GFP_ATOMIC)?;
+    /// guard.store(20, KBox::new(20u32, GFP_ATOMIC)?, GFP_ATOMIC)?;
+    ///
+    /// if let Some((found_index, value)) = guard.find_next(11) {
+    ///     assert_eq!(found_index, 20);
+    ///     assert_eq!(*value, 20);
+    /// }
+    ///
+    /// if let Some((found_index, value)) = guard.find_next(5) {
+    ///     assert_eq!(found_index, 10);
+    ///     assert_eq!(*value, 10);
+    /// }
+    ///
+    /// # Ok::<(), kernel::error::Error>(())
+    /// ```
+    #[inline]
+    pub fn find_next(&self, index: usize) -> Option<(usize, T::Borrowed<'_>)> {
+        self.load_next(index)
             // SAFETY: `ptr` came from `T::into_foreign`.
-            unsafe { T::borrow_mut(ptr.as_ptr()) }
-        })
+            .map(|(index, ptr)| (index, unsafe { T::borrow(ptr.as_ptr()) }))
+    }
+
+    /// Finds the next element starting from the given index, returning a mutable reference.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray}};
+    /// let mut xa = KBox::pin_init(XArray::<KBox<u32>>::new(AllocKind::Alloc), GFP_KERNEL)?;
+    /// let mut guard = xa.lock();
+    ///
+    /// guard.store(10, KBox::new(10u32, GFP_ATOMIC)?, GFP_ATOMIC)?;
+    /// guard.store(20, KBox::new(20u32, GFP_ATOMIC)?, GFP_ATOMIC)?;
+    ///
+    /// if let Some((found_index, mut_value)) = guard.find_next_mut(5) {
+    ///     assert_eq!(found_index, 10);
+    ///     *mut_value = 0x99;
+    /// }
+    ///
+    /// assert_eq!(guard.get(10).copied(), Some(0x99));
+    ///
+    /// # Ok::<(), kernel::error::Error>(())
+    /// ```
+    #[inline]
+    pub fn find_next_mut(&mut self, index: usize) -> Option<(usize, T::BorrowedMut<'_>)> {
+        self.load_next(index)
+            // SAFETY: `ptr` came from `T::into_foreign`.
+            .map(move |(index, ptr)| (index, unsafe { T::borrow_mut(ptr.as_ptr()) }))
+    }
+
+    /// Finds the next occupied entry starting from the given index.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray}};
+    /// let mut xa = KBox::pin_init(XArray::<KBox<u32>>::new(AllocKind::Alloc), GFP_KERNEL)?;
+    /// let mut guard = xa.lock();
+    ///
+    /// guard.store(10, KBox::new(10u32, GFP_ATOMIC)?, GFP_ATOMIC)?;
+    /// guard.store(20, KBox::new(20u32, GFP_ATOMIC)?, GFP_ATOMIC)?;
+    ///
+    /// if let Some(entry) = guard.find_next_entry(5) {
+    ///     assert_eq!(entry.index(), 10);
+    ///     let value = entry.remove();
+    ///     assert_eq!(*value, 10);
+    /// }
+    ///
+    /// assert_eq!(guard.get(10), None);
+    ///
+    /// # Ok::<(), kernel::error::Error>(())
+    /// ```
+    pub fn find_next_entry<'b>(&'b mut self, index: usize) -> Option<OccupiedEntry<'a, 'b, T>> {
+        let mut state = XArrayState::new(self, index);
+        let (_, ptr) = state.load_next(usize::MAX)?;
+        Some(OccupiedEntry { state, ptr })
+    }
+
+    /// Finds the next occupied entry starting at the given index, wrapping around.
+    ///
+    /// Searches for an entry starting at `index` up to the maximum index. If no entry
+    /// is found, wraps around and searches from index 0 up to `index`.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray}};
+    /// let mut xa = KBox::pin_init(XArray::<KBox<u32>>::new(AllocKind::Alloc), GFP_KERNEL)?;
+    /// let mut guard = xa.lock();
+    ///
+    /// guard.store(100, KBox::new(42u32, GFP_ATOMIC)?, GFP_ATOMIC)?;
+    /// let entry = guard.find_next_entry_circular(101);
+    /// assert_eq!(entry.map(|e| e.index()), Some(100));
+    ///
+    /// # Ok::<(), kernel::error::Error>(())
+    /// ```
+    pub fn find_next_entry_circular<'b>(
+        &'b mut self,
+        index: usize,
+    ) -> Option<OccupiedEntry<'a, 'b, T>> {
+        let mut state = XArrayState::new(self, index);
+
+        let (_, ptr) = state.load_next(usize::MAX).or_else(|| {
+            state.restart_at(0);
+            state.load_next(index)
+        })?;
+
+        Some(OccupiedEntry { state, ptr })
     }
 
     /// Removes and returns the element at the given index.
@@ -226,7 +504,12 @@ pub fn remove(&mut self, index: usize) -> Option<T> {
 
     /// Stores an element at the given index.
     ///
-    /// May drop the lock if needed to allocate memory, and then reacquire it afterwards.
+    /// If `gfp` contains blocking allocation flags, this method may drop the
+    /// lock to allocate memory and reacquire it afterwards. Other threads may
+    /// lock and modify the array in that window, so callers must not rely on
+    /// this method being atomic with respect to other operations on the
+    /// guard. To store without dropping the lock, use [`Guard::insert_entry`]
+    /// with preallocated memory.
     ///
     /// On success, returns the element which was previously at the given index.
     ///
@@ -273,8 +556,268 @@ pub fn store(
             Ok(unsafe { T::try_from_foreign(old) })
         }
     }
+
+    /// Inserts a value and returns an occupied entry for further operations.
+    ///
+    /// If a value is already present, the operation fails.
+    ///
+    /// This method will not drop the XArray lock. If memory allocation is
+    /// required for the operation to succeed, the user should supply memory
+    /// through the `preload` argument.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray}};
+    /// let mut xa = KBox::pin_init(XArray::<KBox<u32>>::new(AllocKind::Alloc), GFP_KERNEL)?;
+    /// let mut guard = xa.lock();
+    ///
+    /// assert_eq!(guard.get(42), None);
+    ///
+    /// let value = KBox::new(0x1337u32, GFP_ATOMIC)?;
+    /// let entry = guard.insert_entry(42, value, None)?;
+    /// let borrowed = entry.into_mut();
+    /// assert_eq!(borrowed, &0x1337);
+    ///
+    /// # Ok::<(), kernel::error::Error>(())
+    /// ```
+    pub fn insert_entry<'b>(
+        &'b mut self,
+        index: usize,
+        value: T,
+        preload: Option<&mut XArraySheaf<'_>>,
+    ) -> Result<OccupiedEntry<'a, 'b, T>, StoreError<T>> {
+        match self.entry(index) {
+            Entry::Vacant(entry) => entry.insert_entry(value, preload),
+            Entry::Occupied(_) => Err(StoreError {
+                error: EBUSY,
+                value,
+            }),
+        }
+    }
+}
+
+/// Internal state for XArray iteration and entry operations.
+///
+/// `R` is the borrow held on the guard: either `&Guard` for read-only callers
+/// or `&mut Guard` for entry-style APIs that need to surrender the borrow back
+/// via [`XArrayState::into_guard`].
+///
+/// # Invariants
+///
+/// - `state` is always a valid `bindings::xa_state`.
+/// - `state.xa` aliases the xarray reachable through `guard`.
+pub(crate) struct XArrayState<R> {
+    guard: R,
+    state: bindings::xa_state,
+}
+
+impl<R> Drop for XArrayState<R> {
+    fn drop(&mut self) {
+        free_xa_alloc(&mut self.state);
+    }
+}
+
+fn free_xa_alloc(state: &mut bindings::xa_state) {
+    if !state.xa_alloc.is_null() {
+        // SAFETY:
+        // - `xa_alloc` is only set via `SBox::into_ptr()` in `insert()` where
+        //   the node comes from an `XArraySheaf` backed by `radix_tree_node_cachep`.
+        // - `xa_alloc` points to a valid, initialized `XArrayNode`.
+        // - The caller has exclusive ownership of `xa_alloc`, and no other
+        //   `SBox` or reference exists for this value.
+        drop(unsafe {
+            SBox::<XArrayNode>::static_from_ptr(
+                bindings::radix_tree_node_cachep,
+                state.xa_alloc.cast(),
+            )
+        });
+        state.xa_alloc = null_mut();
+    }
+}
+
+impl<'a, R, T> XArrayState<R>
+where
+    T: ForeignOwnable + 'a,
+    R: core::ops::Deref<Target = Guard<'a, T>>,
+{
+    #[inline]
+    fn new(guard: R, index: usize) -> Self {
+        let xa_ptr = guard.xa.xa.get();
+        // INVARIANT: `state` is initialized to a valid `xa_state` whose `xa` field aliases the
+        // xarray reachable through `guard`.
+        Self {
+            guard,
+            state: bindings::xa_state {
+                xa: xa_ptr,
+                xa_index: index,
+                xa_shift: 0,
+                xa_sibs: 0,
+                xa_offset: 0,
+                xa_pad: 0,
+                xa_node: bindings::XAS_RESTART as *mut bindings::xa_node,
+                xa_alloc: null_mut(),
+                xa_update: None,
+                xa_lru: null_mut(),
+            },
+        }
+    }
+
+    #[inline]
+    fn load(&mut self) -> Option<NonNull<c_void>> {
+        // SAFETY: `self.state` is a valid `xa_state` by the type invariant. By the same
+        // invariant, `self.state.xa` aliases the xarray reachable through `self.guard`, whose
+        // lock we hold.
+        let ptr = unsafe { bindings::xas_load(&raw mut self.state) };
+
+        // Unlike the normal API, `xas_load` does not filter out internal entries. Arrays
+        // created with [`AllocKind::Alloc1`] store `XA_ZERO_ENTRY` at index 0 when they are
+        // expanded from empty, so convert zero entries to `NULL` like `xa_load` does. Retry
+        // entries cannot be observed here because they require concurrent modification of the
+        // array, and we hold the lock.
+        //
+        // SAFETY: `xa_zero_to_null` only inspects the value of `ptr`.
+        NonNull::new(unsafe { bindings::xa_zero_to_null(ptr) }.cast())
+    }
+
+    fn load_next(&mut self, max: usize) -> Option<(usize, NonNull<c_void>)> {
+        loop {
+            // SAFETY: `self.state` is a valid `xa_state` by the type invariant. By the same
+            // invariant, `self.state.xa` aliases the xarray reachable through `self.guard`,
+            // whose lock we hold.
+            let ptr = unsafe { bindings::xas_find(&raw mut self.state, max) };
+            if ptr.is_null() {
+                break None;
+            }
+
+            // Unlike the normal API, `xas_find` does not filter out internal entries. Arrays
+            // created with [`AllocKind::Alloc1`] store `XA_ZERO_ENTRY` at index 0 when they
+            // are expanded from empty. Skip zero entries and continue the search, like the
+            // `xas_retry` loop in `xa_find` does. Retry entries cannot be observed here
+            // because they require concurrent modification of the array, and we hold the
+            // lock.
+            //
+            // SAFETY: `xa_zero_to_null` only inspects the value of `ptr`.
+            if let Some(ptr) = NonNull::new(unsafe { bindings::xa_zero_to_null(ptr) }) {
+                break Some((self.state.xa_index, ptr));
+            }
+        }
+    }
+
+    #[inline]
+    fn status(&self) -> Result {
+        // SAFETY: `self.state` is a valid `xa_state` by the type invariant.
+        to_result(unsafe { bindings::xas_error(&self.state) })
+    }
+
+    /// Resets the state so the next operation walks the tree from the root,
+    /// starting at `index`.
+    fn restart_at(&mut self, index: usize) {
+        self.state.xa_index = index;
+        self.state.xa_node = bindings::XAS_RESTART as *mut bindings::xa_node;
+    }
+}
+
+// Operations that modify the array require exclusive access to the guard, so
+// they are only implemented for `XArrayState<&mut Guard>`.
+impl<'a, 'b, T: ForeignOwnable> XArrayState<&'b mut Guard<'a, T>> {
+    /// Stores `new` at the index of this state, returning the previous entry.
+    ///
+    /// The slot at the index of this state must be occupied. Storing to an
+    /// occupied slot is a simple pointer swap that cannot fail, by design of
+    /// the xarray data structure.
+    fn replace(&mut self, new: *mut c_void) -> *mut c_void {
+        // SAFETY: `self.state` is a valid `xa_state` by the type invariant. By the same
+        // invariant, `self.state.xa` aliases the xarray reachable through `self.guard`, whose
+        // lock we hold.
+        let old = unsafe {
+            bindings::xas_result(
+                &raw mut self.state,
+                bindings::xa_zero_to_null(bindings::xas_store(&raw mut self.state, new)),
+            )
+        };
+
+        // SAFETY: `old` is a valid return value from `xas_result`.
+        let errno = unsafe { bindings::xa_err(old) };
+
+        // NOTE: Storing to an occupied slot never fails. This is by design of
+        // the xarray data structure. If a slot is occupied, a store is a
+        // simple pointer swap.
+        debug_assert!(errno == 0);
+
+        old
+    }
+
+    fn insert(
+        &mut self,
+        value: T,
+        mut preload: Option<&mut XArraySheaf<'_>>,
+    ) -> Result<*mut c_void, StoreError<T>> {
+        build_assert!(
+            T::FOREIGN_ALIGN >= 4,
+            "pointers stored in XArray must be 4-byte aligned"
+        );
+        let new = T::into_foreign(value).cast();
+
+        loop {
+            // SAFETY: `self.state` is a valid `xa_state` by the type invariant. By the same
+            // invariant, `self.state.xa` aliases the xarray reachable through `self.guard`,
+            // whose lock we hold. `new` came from `T::into_foreign`.
+            unsafe { bindings::xas_store(&mut self.state, new) };
+
+            // All arrays created by this abstraction have `XA_FLAGS_TRACK_FREE` set, so the
+            // free mark must be cleared for a newly occupied index, as `__xa_store` does.
+            // This is a no-op if the store above failed.
+            //
+            // SAFETY: `self.state` is a valid `xa_state` by the type invariant, and we hold
+            // the lock on the xarray it refers to.
+            unsafe { bindings::xas_clear_mark(&self.state, bindings::XA_FREE_MARK) };
+
+            match self.status() {
+                Ok(()) => break Ok(new),
+                Err(ENOMEM) => {
+                    debug_assert!(self.state.xa_alloc.is_null());
+                    let node = match preload.as_mut().map(|sheaf| sheaf.alloc().ok_or(ENOMEM)) {
+                        None => break Err(ENOMEM),
+                        Some(Err(e)) => break Err(e),
+                        Some(Ok(node)) => node,
+                    };
+
+                    self.state.xa_alloc = node.into_ptr().cast();
+
+                    // On allocation failure, `xas_store` leaves `XA_ERROR(-ENOMEM)` in
+                    // `self.state.xa_node`, which makes further operations on the state fail
+                    // immediately without consuming `xa_alloc`. Reset the state so the retry
+                    // walks the tree again, as `xas_nomem` does.
+                    self.restart_at(self.state.xa_index);
+                    continue;
+                }
+                Err(e) => break Err(e),
+            }
+        }
+        .map_err(|error| {
+            // SAFETY: `new` came from `T::into_foreign` and `xas_store` does not take
+            // ownership of the value on error.
+            let value = unsafe { T::from_foreign(new) };
+            StoreError { value, error }
+        })
+    }
+
+    /// Consumes `self`, releases any preallocated node held in `xa_alloc`, and
+    /// returns the inner `&mut Guard`.
+    #[inline]
+    pub(crate) fn into_guard(self) -> &'b mut Guard<'a, T> {
+        // Suppress the `Drop` impl so we can move `guard` out by hand.
+        let mut this = core::mem::ManuallyDrop::new(self);
+        free_xa_alloc(&mut this.state);
+        // SAFETY: `ManuallyDrop` prevents `Drop::drop` from running, so this is the only place
+        // that consumes `guard`. `state` has no other resources after `free_xa_alloc`.
+        unsafe { core::ptr::read(&this.guard) }
+    }
 }
 
+mod entry;
+
 // SAFETY: `XArray<T>` has no shared mutable state so it is `Send` iff `T` is `Send`.
 unsafe impl<T: ForeignOwnable + Send> Send for XArray<T> {}
 
diff --git a/rust/kernel/xarray/entry.rs b/rust/kernel/xarray/entry.rs
new file mode 100644
index 00000000000000..3d004f6f8c6cd4
--- /dev/null
+++ b/rust/kernel/xarray/entry.rs
@@ -0,0 +1,381 @@
+// SPDX-License-Identifier: GPL-2.0
+
+use super::{
+    Guard,
+    StoreError,
+    XArraySheaf,
+    XArrayState, //
+};
+use core::ptr::NonNull;
+use kernel::{
+    build_assert::build_assert,
+    prelude::*,
+    types::ForeignOwnable, //
+};
+
+/// Represents either a vacant or occupied entry in an XArray.
+pub enum Entry<'a, 'b, T: ForeignOwnable> {
+    /// A vacant entry that can have a value inserted.
+    Vacant(VacantEntry<'a, 'b, T>),
+    /// An occupied entry containing a value.
+    Occupied(OccupiedEntry<'a, 'b, T>),
+}
+
+impl<T: ForeignOwnable> Entry<'_, '_, T> {
+    /// Returns true if this entry is occupied.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray, Entry}};
+    /// let mut xa = KBox::pin_init(XArray::<KBox<u32>>::new(AllocKind::Alloc), GFP_KERNEL)?;
+    /// let mut guard = xa.lock();
+    ///
+    /// let entry = guard.entry(42);
+    /// assert_eq!(entry.is_occupied(), false);
+    /// drop(entry);
+    ///
+    /// guard.store(42, KBox::new(0x1337u32, GFP_ATOMIC)?, GFP_ATOMIC)?;
+    /// let entry = guard.entry(42);
+    /// assert_eq!(entry.is_occupied(), true);
+    ///
+    /// # Ok::<(), kernel::error::Error>(())
+    /// ```
+    #[inline]
+    pub fn is_occupied(&self) -> bool {
+        matches!(self, Entry::Occupied(_))
+    }
+}
+
+/// A view into a vacant entry in an XArray.
+pub struct VacantEntry<'a, 'b, T: ForeignOwnable> {
+    state: XArrayState<&'b mut Guard<'a, T>>,
+}
+
+impl<'a, 'b, T> VacantEntry<'a, 'b, T>
+where
+    T: ForeignOwnable,
+{
+    pub(crate) fn new(guard: &'b mut Guard<'a, T>, index: usize) -> Self {
+        Self {
+            state: XArrayState::new(guard, index),
+        }
+    }
+
+    /// Consumes the entry and returns a mutable reference to the underlying
+    /// guard.
+    ///
+    /// This releases the slot reservation but retains the lock guard so the
+    /// caller can perform further operations on the array.
+    #[inline]
+    pub fn into_guard(self) -> &'b mut Guard<'a, T> {
+        self.state.into_guard()
+    }
+
+    /// Inserts a value into this vacant entry.
+    ///
+    /// Returns a reference to the newly inserted value.
+    ///
+    /// - This method will fail if the nodes on the path to the index
+    ///   represented by this entry are not present in the XArray and no memory
+    ///   is available via the `preload` argument.
+    /// - This method will not drop the XArray lock.
+    ///
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray, Entry}};
+    /// let mut xa = KBox::pin_init(XArray::<KBox<u32>>::new(AllocKind::Alloc), GFP_KERNEL)?;
+    /// let mut guard = xa.lock();
+    ///
+    /// assert_eq!(guard.get(42), None);
+    ///
+    /// if let Entry::Vacant(entry) = guard.entry(42) {
+    ///     let value = KBox::new(0x1337u32, GFP_ATOMIC)?;
+    ///     let borrowed = entry.insert(value, None)?;
+    ///     assert_eq!(*borrowed, 0x1337);
+    /// }
+    ///
+    /// assert_eq!(guard.get(42).copied(), Some(0x1337));
+    ///
+    /// # Ok::<(), kernel::error::Error>(())
+    /// ```
+    pub fn insert(
+        mut self,
+        value: T,
+        preload: Option<&mut XArraySheaf<'_>>,
+    ) -> Result<T::BorrowedMut<'b>, StoreError<T>> {
+        let new = self.state.insert(value, preload)?;
+
+        // SAFETY: `new` came from `T::into_foreign`. The entry has exclusive
+        // ownership of `new` as it holds a mutable reference to `Guard`.
+        Ok(unsafe { T::borrow_mut(new) })
+    }
+
+    /// Inserts a value and returns an occupied entry representing the newly inserted value.
+    ///
+    /// - This method will fail if the nodes on the path to the index
+    ///   represented by this entry are not present in the XArray and no memory
+    ///   is available via the `preload` argument.
+    /// - This method will not drop the XArray lock.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray, Entry}};
+    /// let mut xa = KBox::pin_init(XArray::<KBox<u32>>::new(AllocKind::Alloc), GFP_KERNEL)?;
+    /// let mut guard = xa.lock();
+    ///
+    /// assert_eq!(guard.get(42), None);
+    ///
+    /// if let Entry::Vacant(entry) = guard.entry(42) {
+    ///     let value = KBox::new(0x1337u32, GFP_ATOMIC)?;
+    ///     let occupied = entry.insert_entry(value, None)?;
+    ///     assert_eq!(occupied.index(), 42);
+    /// }
+    ///
+    /// assert_eq!(guard.get(42).copied(), Some(0x1337));
+    ///
+    /// # Ok::<(), kernel::error::Error>(())
+    /// ```
+    pub fn insert_entry(
+        mut self,
+        value: T,
+        preload: Option<&mut XArraySheaf<'_>>,
+    ) -> Result<OccupiedEntry<'a, 'b, T>, StoreError<T>> {
+        let new = self.state.insert(value, preload)?;
+
+        Ok(OccupiedEntry::<'a, 'b, T> {
+            state: self.state,
+            // SAFETY: `new` came from `T::into_foreign` and is guaranteed non-null.
+            ptr: unsafe { core::ptr::NonNull::new_unchecked(new) },
+        })
+    }
+
+    /// Returns the index of this vacant entry.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray, Entry}};
+    /// let mut xa = KBox::pin_init(XArray::<KBox<u32>>::new(AllocKind::Alloc), GFP_KERNEL)?;
+    /// let mut guard = xa.lock();
+    ///
+    /// assert_eq!(guard.get(42), None);
+    ///
+    /// if let Entry::Vacant(entry) = guard.entry(42) {
+    ///     assert_eq!(entry.index(), 42);
+    /// }
+    ///
+    /// # Ok::<(), kernel::error::Error>(())
+    /// ```
+    #[inline]
+    pub fn index(&self) -> usize {
+        self.state.state.xa_index
+    }
+}
+
+/// A view into an occupied entry in an XArray.
+pub struct OccupiedEntry<'a, 'b, T: ForeignOwnable> {
+    pub(crate) state: XArrayState<&'b mut Guard<'a, T>>,
+    pub(crate) ptr: NonNull<c_void>,
+}
+
+impl<'a, 'b, T> OccupiedEntry<'a, 'b, T>
+where
+    T: ForeignOwnable,
+{
+    pub(crate) fn new(guard: &'b mut Guard<'a, T>, index: usize, ptr: NonNull<c_void>) -> Self {
+        Self {
+            state: XArrayState::new(guard, index),
+            ptr,
+        }
+    }
+
+    /// Consumes the entry and returns a mutable reference to the underlying
+    /// guard.
+    ///
+    /// This releases the borrow on the entry's slot but retains the lock
+    /// guard so the caller can perform further operations on the array.
+    #[inline]
+    pub fn into_guard(self) -> &'b mut Guard<'a, T> {
+        self.state.into_guard()
+    }
+
+    /// Removes the value from this occupied entry and returns it, consuming the entry.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray, Entry}};
+    /// let mut xa = KBox::pin_init(XArray::<KBox<u32>>::new(AllocKind::Alloc), GFP_KERNEL)?;
+    /// let mut guard = xa.lock();
+    ///
+    /// guard.store(42, KBox::new(0x1337u32, GFP_ATOMIC)?, GFP_ATOMIC)?;
+    /// assert_eq!(guard.get(42).copied(), Some(0x1337));
+    ///
+    /// if let Entry::Occupied(entry) = guard.entry(42) {
+    ///     let value = entry.remove();
+    ///     assert_eq!(*value, 0x1337);
+    /// }
+    ///
+    /// assert_eq!(guard.get(42), None);
+    ///
+    /// # Ok::<(), kernel::error::Error>(())
+    /// ```
+    pub fn remove(mut self) -> T {
+        let ptr = self.state.replace(core::ptr::null_mut());
+
+        // SAFETY:
+        // - `ptr` came from `T::into_foreign`.
+        // - As this method takes self by value, the lifetimes of any [`T::Borrowed`] and
+        //   [`T::BorrowedMut`] we have created must have ended.
+        unsafe { T::from_foreign(ptr.cast()) }
+    }
+
+    /// Returns the index of this occupied entry.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray, Entry}};
+    /// let mut xa = KBox::pin_init(XArray::<KBox<u32>>::new(AllocKind::Alloc), GFP_KERNEL)?;
+    /// let mut guard = xa.lock();
+    ///
+    /// guard.store(42, KBox::new(0x1337u32, GFP_ATOMIC)?, GFP_ATOMIC)?;
+    ///
+    /// if let Entry::Occupied(entry) = guard.entry(42) {
+    ///     assert_eq!(entry.index(), 42);
+    /// }
+    ///
+    /// # Ok::<(), kernel::error::Error>(())
+    /// ```
+    #[inline]
+    pub fn index(&self) -> usize {
+        self.state.state.xa_index
+    }
+
+    /// Replaces the value in this occupied entry and returns the old value.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray, Entry}};
+    /// let mut xa = KBox::pin_init(XArray::<KBox<u32>>::new(AllocKind::Alloc), GFP_KERNEL)?;
+    /// let mut guard = xa.lock();
+    ///
+    /// guard.store(42, KBox::new(0x1337u32, GFP_ATOMIC)?, GFP_ATOMIC)?;
+    ///
+    /// if let Entry::Occupied(mut entry) = guard.entry(42) {
+    ///     let new_value = KBox::new(0x9999u32, GFP_ATOMIC)?;
+    ///     let old_value = entry.insert(new_value);
+    ///     assert_eq!(*old_value, 0x1337);
+    /// }
+    ///
+    /// assert_eq!(guard.get(42).copied(), Some(0x9999));
+    ///
+    /// # Ok::<(), kernel::error::Error>(())
+    /// ```
+    pub fn insert(&mut self, value: T) -> T {
+        build_assert!(
+            T::FOREIGN_ALIGN >= 4,
+            "pointers stored in XArray must be 4-byte aligned"
+        );
+        let new = T::into_foreign(value).cast();
+        // SAFETY: `new` came from `T::into_foreign` and is guaranteed non-null.
+        self.ptr = unsafe { NonNull::new_unchecked(new) };
+
+        let old = self.state.replace(new);
+
+        // SAFETY:
+        // - `old` came from `T::into_foreign`.
+        // - As this method takes `self` by mutable reference, the lifetimes of any
+        //   [`T::Borrowed`] and [`T::BorrowedMut`] we have created must have ended.
+        unsafe { T::from_foreign(old) }
+    }
+
+    /// Converts this occupied entry into a mutable reference to the value in the slot represented
+    /// by the entry.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray, Entry}};
+    /// let mut xa = KBox::pin_init(XArray::<KBox<u32>>::new(AllocKind::Alloc), GFP_KERNEL)?;
+    /// let mut guard = xa.lock();
+    ///
+    /// guard.store(42, KBox::new(0x1337u32, GFP_ATOMIC)?, GFP_ATOMIC)?;
+    ///
+    /// if let Entry::Occupied(entry) = guard.entry(42) {
+    ///     let value_ref = entry.into_mut();
+    ///     *value_ref = 0x9999;
+    /// }
+    ///
+    /// assert_eq!(guard.get(42).copied(), Some(0x9999));
+    ///
+    /// # Ok::<(), kernel::error::Error>(())
+    /// ```
+    #[inline]
+    pub fn into_mut(self) -> T::BorrowedMut<'b> {
+        // SAFETY: `ptr` came from `T::into_foreign`.
+        unsafe { T::borrow_mut(self.ptr.as_ptr()) }
+    }
+
+    /// Swaps the value in this entry with the provided value.
+    ///
+    /// Returns the old value that was in the entry.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use kernel::{prelude::*, xarray::{AllocKind, XArray, Entry}};
+    /// let mut xa = KBox::pin_init(XArray::<KBox<u32>>::new(AllocKind::Alloc), GFP_KERNEL)?;
+    /// let mut guard = xa.lock();
+    ///
+    /// guard.store(42, KBox::new(100u32, GFP_ATOMIC)?, GFP_ATOMIC)?;
+    ///
+    /// if let Entry::Occupied(mut entry) = guard.entry(42) {
+    ///     let mut other = 200u32;
+    ///     entry.swap(&mut other);
+    ///     assert_eq!(other, 100);
+    ///     assert_eq!(*entry, 200);
+    /// }
+    ///
+    /// # Ok::<(), kernel::error::Error>(())
+    /// ```
+    pub fn swap<U>(&mut self, other: &mut U)
+    where
+        T: ForeignOwnable<Borrowed<'b> = &'b U, BorrowedMut<'b> = &'b mut U> + 'b,
+        U: 'b,
+    {
+        use core::ops::DerefMut;
+        core::mem::swap(self.deref_mut(), other);
+    }
+}
+
+impl<'a, 'b, T, U> core::ops::Deref for OccupiedEntry<'a, 'b, T>
+where
+    T: ForeignOwnable<Borrowed<'b> = &'b U, BorrowedMut<'b> = &'b mut U> + 'b,
+    U: 'b,
+{
+    type Target = U;
+
+    #[inline]
+    fn deref(&self) -> &Self::Target {
+        // SAFETY: `ptr` came from `T::into_foreign`.
+        unsafe { T::borrow(self.ptr.as_ptr()) }
+    }
+}
+
+impl<'a, 'b, T, U> core::ops::DerefMut for OccupiedEntry<'a, 'b, T>
+where
+    T: ForeignOwnable<Borrowed<'b> = &'b U, BorrowedMut<'b> = &'b mut U> + 'b,
+    U: 'b,
+{
+    #[inline]
+    fn deref_mut(&mut self) -> &mut Self::Target {
+        // SAFETY: `ptr` came from `T::into_foreign`.
+        unsafe { T::borrow_mut(self.ptr.as_ptr()) }
+    }
+}

67/3 2026/11/25 14:03 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 27574
							output: 40
							thoughts: 2424
						

Thoughts:
**KMSAN Assessment: Rust-Based SLUB/XArray Abstractions**

Okay, let's break this down. The user wants to know if these code changes warrant a dedicated KMSAN session. My initial thought is to assess the risk of uninitialized memory reads or information leaks, specifically in relation to user-space interactions, because that's what KMSAN is for. We have to follow the rules: if KASAN, LOCKDEP, or standard sanitizers would catch the issue, we don't need KMSAN.

First, I need to understand the changes. We're looking at Rust abstractions for SLUB sheaves, XArray entry API, preallocation using sheaves, and some minor C code changes that support the Rust implementation. The core of this seems to be managing memory within the kernel, specifically with these new 'sheaves' – a new memory management abstraction.

Now, the critical question: how are objects allocated and initialized? The Rust code utilizes `kmem_cache_alloc_from_sheaf_noprof` and an initializer (`T::init().__init`) for the `SBox`. `XArrayNode`, which is a key structure, relies on `radix_tree_node_ctor` for initialization. Crucially, `radix_tree_node_ctor` uses `memset` to zero the node.  That's important. It's zeroed!

My initial impression is that the Rust code *shouldn't* introduce uninitialized memory issues because of these explicit initializations. It zeroes it.  I don't see any direct copying of kernel structures to user space; we're staying within the kernel.

I need to confirm the KMSAN instrumentation in the Rust code itself. If Rust does not support KMSAN at all, this makes the decision.  I have to ensure that even if KMSAN was enabled in the kernel, it is not possible to exploit this in the Rust or C code due to uninitialized memory issues.

I'm now checking the C code that has changed. `radix_tree_node_ctor` is exported and called from `radix_tree_init`, and the helper functions `xa_zero_to_null` and `xas_result` are added. I am now looking at where `radix_tree_node_cachep` is created, and noticed the function signature change for `kmem_cache_create`.

Okay, back to the key question: Is the Rust code or the C code, with these changes, risking uninitialized memory use?  The initialization is explicit, with `memset` for nodes, and the Rust code depends on proper initialization. I see no direct leak of uninitialized kernel data to user-space.

Therefore, given the nature of the changes (memory management within the kernel, explicit initialization, and no direct user-space interaction), I believe that **we do *not* need a dedicated KMSAN fuzzing session**. Standard KASAN fuzzing, along with the other standard bug detectors, should be sufficient to catch any issues related to this patch.



68/3 2026/11/25 14:04 tool grepper
0m Args:
{
  "Expression": "kmem_cache_create\\(",
  "PathPrefixes": [
    "include/linux/slab.h",
    "mm/"
  ]
}

Results:
{
  "Output": "\nFull output is too long, showing 200 out of 209 lines.\nUse more precise expression or PathPrefixes if possible.\n\nNumber of matching lines per file (15 files in total):\ninclude/linux/slab.h:10\nmm/kasan/kasan_test_c.c:9\nmm/kfence/kfence_test.c:1\nmm/memcontrol.c:1\nmm/memory.c:1\nmm/mempolicy.c:2\nmm/rmap.c:1\nmm/shmem.c:1\nmm/slab.h:1\nmm/slab_common.c:6\nmm/slub.c:1\nmm/swapfile.c:1\nmm/userfaultfd.c:1\nmm/vma_init.c:1\nmm/zsmalloc.c:2\n\ninclude/linux/slab.h=26=enum _slab_flag_bits {\n--\ninclude/linux/slab.h-75-/*\ninclude/linux/slab.h:76: * Flags to pass to kmem_cache_create().\ninclude/linux/slab.h-77- * The ones marked DEBUG need CONFIG_SLUB_DEBUG enabled, otherwise are no-op\n--\ninclude/linux/slab.h-104-#define SLAB_STORE_USER\t\t__SLAB_FLAG_BIT(_SLAB_STORE_USER)\ninclude/linux/slab.h:105:/* Panic if kmem_cache_create() fails */\ninclude/linux/slab.h-106-#define SLAB_PANIC\t\t__SLAB_FLAG_BIT(_SLAB_PANIC)\n--\ninclude/linux/slab.h-159- * locks must be initialized after each and every kmem_struct_alloc().\ninclude/linux/slab.h:160: * Alternatively, make the ctor passed to kmem_cache_create() initialize\ninclude/linux/slab.h-161- * the locks at page-allocation time, as is done in __i915_request_ctor(),\n--\ninclude/linux/slab.h=283=bool slab_is_available(void);\n--\ninclude/linux/slab.h-285-/**\ninclude/linux/slab.h:286: * struct kmem_cache_args - Less common arguments for kmem_cache_create()\ninclude/linux/slab.h-287- *\n--\ninclude/linux/slab.h-293- *\ninclude/linux/slab.h:294: * When %NULL args is passed to kmem_cache_create(), it is equivalent to all\ninclude/linux/slab.h-295- * fields unused.\n--\ninclude/linux/slab.h=393=static inline struct kmem_cache *\ninclude/linux/slab.h:394:__kmem_cache_create(const char *name, unsigned int size, unsigned int align,\ninclude/linux/slab.h-395-\t\t    slab_flags_t flags, void (*ctor)(void *))\n--\ninclude/linux/slab.h-416- * This is a legacy wrapper, new code should use either KMEM_CACHE_USERCOPY()\ninclude/linux/slab.h:417: * if whitelisting a single field is sufficient, or kmem_cache_create() with\ninclude/linux/slab.h-418- * the necessary parameters passed via the args parameter (see\n--\ninclude/linux/slab.h=441=__kmem_cache_default_args(const char *name, unsigned int size,\n--\ninclude/linux/slab.h-464- * The new variant has 4 parameters:\ninclude/linux/slab.h:465: * ``kmem_cache_create(name, object_size, args, flags)``\ninclude/linux/slab.h-466- *\n--\ninclude/linux/slab.h-469- * The legacy variant has 5 parameters:\ninclude/linux/slab.h:470: * ``kmem_cache_create(name, object_size, align, flags, ctor)``\ninclude/linux/slab.h-471- *\n--\ninclude/linux/slab.h-478- */\ninclude/linux/slab.h:479:#define kmem_cache_create(__name, __object_size, __args, ...)           \\\ninclude/linux/slab.h-480-\t_Generic((__args),                                              \\\n--\nmm/kasan/kasan_test_c.c=1030=static void kmem_cache_oob(struct kunit *test)\n--\nmm/kasan/kasan_test_c.c-1035-\nmm/kasan/kasan_test_c.c:1036:\tcache = kmem_cache_create(\"test_cache\", size, 0, 0, NULL);\nmm/kasan/kasan_test_c.c-1037-\tKUNIT_ASSERT_NOT_ERR_OR_NULL(test, cache);\n--\nmm/kasan/kasan_test_c.c=1052=static void kmem_cache_double_free(struct kunit *test)\n--\nmm/kasan/kasan_test_c.c-1057-\nmm/kasan/kasan_test_c.c:1058:\tcache = kmem_cache_create(\"test_cache\", size, 0, 0, NULL);\nmm/kasan/kasan_test_c.c-1059-\tKUNIT_ASSERT_NOT_ERR_OR_NULL(test, cache);\n--\nmm/kasan/kasan_test_c.c=1073=static void kmem_cache_invalid_free(struct kunit *test)\n--\nmm/kasan/kasan_test_c.c-1078-\nmm/kasan/kasan_test_c.c:1079:\tcache = kmem_cache_create(\"test_cache\", size, 0, SLAB_TYPESAFE_BY_RCU,\nmm/kasan/kasan_test_c.c-1080-\t\t\t\t  NULL);\n--\nmm/kasan/kasan_test_c.c=1102=static void kmem_cache_rcu_uaf(struct kunit *test)\n--\nmm/kasan/kasan_test_c.c-1109-\nmm/kasan/kasan_test_c.c:1110:\tcache = kmem_cache_create(\"test_cache\", size, 0, SLAB_TYPESAFE_BY_RCU,\nmm/kasan/kasan_test_c.c-1111-\t\t\t\t  NULL);\n--\nmm/kasan/kasan_test_c.c=1153=static void kmem_cache_rcu_reuse(struct kunit *test)\n--\nmm/kasan/kasan_test_c.c-1159-\nmm/kasan/kasan_test_c.c:1160:\tcache = kmem_cache_create(\"test_cache\", 16, 0, SLAB_TYPESAFE_BY_RCU,\nmm/kasan/kasan_test_c.c-1161-\t\t\t\t  NULL);\n--\nmm/kasan/kasan_test_c.c=1186=static void kmem_cache_double_destroy(struct kunit *test)\n--\nmm/kasan/kasan_test_c.c-1189-\nmm/kasan/kasan_test_c.c:1190:\tcache = kmem_cache_create(\"test_cache\", 200, 0, SLAB_NO_MERGE, NULL);\nmm/kasan/kasan_test_c.c-1191-\tKUNIT_ASSERT_NOT_ERR_OR_NULL(test, cache);\n--\nmm/kasan/kasan_test_c.c=1196=static void kmem_cache_accounted(struct kunit *test)\n--\nmm/kasan/kasan_test_c.c-1202-\nmm/kasan/kasan_test_c.c:1203:\tcache = kmem_cache_create(\"test_cache\", size, 0, SLAB_ACCOUNT, NULL);\nmm/kasan/kasan_test_c.c-1204-\tKUNIT_ASSERT_NOT_ERR_OR_NULL(test, cache);\n--\nmm/kasan/kasan_test_c.c=1223=static void kmem_cache_bulk(struct kunit *test)\n--\nmm/kasan/kasan_test_c.c-1229-\nmm/kasan/kasan_test_c.c:1230:\tcache = kmem_cache_create(\"test_cache\", size, 0, 0, NULL);\nmm/kasan/kasan_test_c.c-1231-\tKUNIT_ASSERT_NOT_ERR_OR_NULL(test, cache);\n--\nmm/kasan/kasan_test_c.c=1269=static struct kmem_cache *mempool_prepare_slab(struct kunit *test, mempool_t *pool, size_t size)\n--\nmm/kasan/kasan_test_c.c-1274-\nmm/kasan/kasan_test_c.c:1275:\tcache = kmem_cache_create(\"test_cache\", size, 0, 0, NULL);\nmm/kasan/kasan_test_c.c-1276-\tKUNIT_ASSERT_NOT_ERR_OR_NULL(test, cache);\n--\nmm/kfence/kfence_test.c=186=static size_t setup_test_cache(struct kunit *test, size_t size, slab_flags_t flags,\n--\nmm/kfence/kfence_test.c-198-\tflags |= SLAB_NO_MERGE | SLAB_ACCOUNT;\nmm/kfence/kfence_test.c:199:\ttest_cache = kmem_cache_create(\"test\", size, 1, flags, ctor);\nmm/kfence/kfence_test.c-200-\tKUNIT_ASSERT_TRUE_MSG(test, test_cache, \"could not create cache\");\n--\nmm/memcontrol.c=5957=int __init mem_cgroup_init(void)\n--\nmm/memcontrol.c-5985-\tmemcg_size = struct_size_t(struct mem_cgroup, nodeinfo, nr_node_ids);\nmm/memcontrol.c:5986:\tmemcg_cachep = kmem_cache_create(\"mem_cgroup\", memcg_size, 0,\nmm/memcontrol.c-5987-\t\t\t\t\t SLAB_PANIC | SLAB_HWCACHE_ALIGN, NULL);\n--\nmm/memory.c=7804=void __init ptlock_cache_init(void)\nmm/memory.c-7805-{\nmm/memory.c:7806:\tpage_ptl_cachep = kmem_cache_create(\"page-\u003eptl\", sizeof(spinlock_t), 0,\nmm/memory.c-7807-\t\t\tSLAB_PANIC, NULL);\n--\nmm/mempolicy.c=3367=void __init numa_policy_init(void)\n--\nmm/mempolicy.c-3372-\nmm/mempolicy.c:3373:\tpolicy_cache = kmem_cache_create(\"numa_policy\",\nmm/mempolicy.c-3374-\t\t\t\t\t sizeof(struct mempolicy),\n--\nmm/mempolicy.c-3376-\nmm/mempolicy.c:3377:\tsn_cache = kmem_cache_create(\"shared_policy_node\",\nmm/mempolicy.c-3378-\t\t\t\t     sizeof(struct sp_node),\n--\nmm/rmap.c=554=void __init anon_vma_init(void)\nmm/rmap.c-555-{\nmm/rmap.c:556:\tanon_vma_cachep = kmem_cache_create(\"anon_vma\", sizeof(struct anon_vma),\nmm/rmap.c-557-\t\t\t0, SLAB_TYPESAFE_BY_RCU|SLAB_PANIC|SLAB_ACCOUNT,\n--\nmm/shmem.c=5408=static void __init shmem_init_inodecache(void)\nmm/shmem.c-5409-{\nmm/shmem.c:5410:\tshmem_inode_cachep = kmem_cache_create(\"shmem_inode_cache\",\nmm/shmem.c-5411-\t\t\t\tsizeof(struct shmem_inode_info),\n--\nmm/slab.h=437=gfp_t kmalloc_fix_flags(gfp_t flags);\n--\nmm/slab.h-439-/* Functions provided by the slab allocators */\nmm/slab.h:440:int do_kmem_cache_create(struct kmem_cache *s, const char *name,\nmm/slab.h-441-\t\t\t unsigned int size, struct kmem_cache_args *args,\n--\nmm/slab_common.c=103=static int kmem_cache_sanity_check(const char *name, unsigned int size)\n--\nmm/slab_common.c-105-\tif (!name || in_interrupt() || !size || size \u003e KMALLOC_MAX_SIZE) {\nmm/slab_common.c:106:\t\tpr_err(\"kmem_cache_create(%s) integrity check failed\\n\", name);\nmm/slab_common.c-107-\t\treturn -EINVAL;\n--\nmm/slab_common.c=232=static struct kmem_cache *create_cache(const char *name,\n--\nmm/slab_common.c-251-\t\tgoto out;\nmm/slab_common.c:252:\terr = do_kmem_cache_create(s, name, object_size, args, flags);\nmm/slab_common.c-253-\tif (err)\n--\nmm/slab_common.c=267=__kmem_cache_alias(const char *name, unsigned int size, slab_flags_t flags,\n--\nmm/slab_common.c-299- *\nmm/slab_common.c:300: * Not to be called directly, use the kmem_cache_create() wrapper with the same\nmm/slab_common.c-301- * parameters.\n--\nmm/slab_common.c=411=static struct kmem_cache *kmem_buckets_cache __ro_after_init;\n--\nmm/slab_common.c-417- *\t  cache. The individual caches with have their sizes as the suffix.\nmm/slab_common.c:418: * @flags: SLAB flags (see kmem_cache_create() for details).\nmm/slab_common.c-419- * @useroffset: Starting offset within an allocation that may be copied\n--\nmm/slab_common.c=711=void __init create_boot_cache(struct kmem_cache *s, const char *name,\n--\nmm/slab_common.c-732-\nmm/slab_common.c:733:\terr = do_kmem_cache_create(s, name, size, \u0026kmem_args, flags);\nmm/slab_common.c-734-\n--\nmm/slab_common.c=1036=void __init create_kmalloc_caches(void)\n--\nmm/slab_common.c-1062-\tif (IS_ENABLED(CONFIG_SLAB_BUCKETS))\nmm/slab_common.c:1063:\t\tkmem_buckets_cache = kmem_cache_create(\"kmalloc_buckets\",\nmm/slab_common.c-1064-\t\t\t\t\t\t       sizeof(kmem_buckets),\n--\nmm/slub.c=8834=void __init kmem_cache_init_late(void)\n--\nmm/slub.c-8843-\nmm/slub.c:8844:int do_kmem_cache_create(struct kmem_cache *s, const char *name,\nmm/slub.c-8845-\t\t\t unsigned int size, struct kmem_cache_args *args,\n--\nmm/swapfile.c=4042=static int __init swapfile_init(void)\n--\nmm/swapfile.c-4051-\tif (!SWP_TABLE_USE_PAGE)\nmm/swapfile.c:4052:\t\tswap_table_cachep = kmem_cache_create(\"swap_table\",\nmm/swapfile.c-4053-\t\t\t\t    sizeof(struct swap_table),\n--\nmm/userfaultfd.c=4825=static int __init userfaultfd_init(void)\n--\nmm/userfaultfd.c-4832-\nmm/userfaultfd.c:4833:\tuserfaultfd_ctx_cachep = kmem_cache_create(\"userfaultfd_ctx_cache\",\nmm/userfaultfd.c-4834-\t\t\t\t\t\tsizeof(struct userfaultfd_ctx),\n--\nmm/vma_init.c=18=void __init vma_state_init(void)\n--\nmm/vma_init.c-25-\n\n"
}

69/3 2026/11/25 14:04 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 34989
							output: 311
							thoughts: 1591
						

Thoughts:
**KMSAN Assessment: No Uninitialized Memory Risks**

Okay, let's break this down. The patch exposes some existing SLUB sheaf functions and introduces Rust abstractions for both SLUB sheaves and XArray. My primary concern is always uninitialized memory, so that's where I start.

First, I checked the exported functions: they're already *there* in `mm/slub.c`; the patch just adds `EXPORT_SYMBOL`. These are all sheaf implementation details. Fine. Then I took a look at the Rust side (`rust/kernel/mm/sheaf.rs`, `rust/kernel/xarray.rs`, and `rust/kernel/xarray/entry.rs`). I needed to see what these new types and abstractions actually *do*.

The key question is: are there any opportunities for uninitialized memory to sneak in? I went through the standard checklist.

1.  **User-space interaction:** No `copy_to_user`, `put_user`, netlink, ioctl, socket operations, or BPF buffers are involved. This is all internal kernel stuff. No problem there.
2.  **Conditional logic:** I looked at initialization in `XArrayState::new` and `KMemCacheHandle::new`. The `xa_state` is initialized field-by-field, and `KMemCacheHandle::new` uses `pin_init::zeroed()` for `kmem_cache_args` which is very explicit. Also, any radix tree node creation uses `radix_tree_node_ctor`, which calls `memset` to zero out the memory.
3.  **Complex data structures:** Again, everything looks properly initialized through zeroing via C constructors and `pin_init::zeroed()`. The same is true for the `radix_tree_node_ctor`.
4.  **Bounds checks:** None were introduced in a way that would expose uninitialized bytes.

So, it *appears* all allocations are initialized.

What about other potential problems? Use-after-free, memory leaks, reference counting issues, concurrency bugs – those are all possibilities. But those are *KASAN* issues, *LOCKDEP* issues, or handled by Rust's borrow checker, type system and standard debuggers. These are *not* uninitialized memory bugs. Even if we're looking at the C side, and considering semantic behavior of the whole change, no uninitialized memory hazards are introduced or exposed.

Let's review the KMSAN rules. The code changes don't introduce uninitialized memory risks that KMSAN would uniquely catch. The patch *doesn't* risk out-of-bounds access, array overflows, NULL pointer dereferences, locking deadlocks, or use-after-free bugs. All new and modified structures are fully initialized or zeroed. No uninitialized memory usage or info-leaks.

Therefore, `NeedsKMSAN = false`. It's a solid no. I'm confident in calling `set-results`.



70/3 2026/11/25 14:05 tool set-results
0m Args:
{
  "KMSANReasoning": "The patch series introduces Rust abstractions for SLUB allocator sheaves (`rust/kernel/mm/sheaf.rs`) and XArray entry/preallocation operations (`rust/kernel/xarray.rs`, `rust/kernel/xarray/entry.rs`), along with exporting several existing SLUB sheaf functions in `mm/slub.c` and updating `radix_tree_init` to configure sheaf capacity.\n\nKMSAN is not required for the following reasons:\n1. No user-space copy boundaries (such as `copy_to_user`, ioctl outputs, netlink attributes, or BPF buffers) are introduced or modified.\n2. All data structures initialized in both C and Rust are fully initialized before use: `struct kmem_cache_args` is zero-initialized, `struct xa_state` explicitly sets all fields, and `radix_tree_node` / `XArrayNode` instances are explicitly zeroed via `radix_tree_node_ctor` (`memset(node, 0, sizeof(*node))`).\n3. Any potential bugs in this patch series involve reference counting, lock guard behavior, lifetime/ownership conversions (`into_ptr`, `static_from_ptr`), or slab management, which fall squarely under KASAN, LOCKDEP, and standard kernel debugging facilities rather than KMSAN uninitialized memory detection.",
  "NeedsKMSAN": false
}

Results:
{
  "KMSANReasoning": "The patch series introduces Rust abstractions for SLUB allocator sheaves (`rust/kernel/mm/sheaf.rs`) and XArray entry/preallocation operations (`rust/kernel/xarray.rs`, `rust/kernel/xarray/entry.rs`), along with exporting several existing SLUB sheaf functions in `mm/slub.c` and updating `radix_tree_init` to configure sheaf capacity.\n\nKMSAN is not required for the following reasons:\n1. No user-space copy boundaries (such as `copy_to_user`, ioctl outputs, netlink attributes, or BPF buffers) are introduced or modified.\n2. All data structures initialized in both C and Rust are fully initialized before use: `struct kmem_cache_args` is zero-initialized, `struct xa_state` explicitly sets all fields, and `radix_tree_node` / `XArrayNode` instances are explicitly zeroed via `radix_tree_node_ctor` (`memset(node, 0, sizeof(*node))`).\n3. Any potential bugs in this patch series involve reference counting, lock guard behavior, lifetime/ownership conversions (`into_ptr`, `static_from_ptr`), or slab management, which fall squarely under KASAN, LOCKDEP, and standard kernel debugging facilities rather than KMSAN uninitialized memory detection.",
  "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)