From: Andreas Hindborg <a.hindborg@kernel.org>
To: "Miguel Ojeda" <ojeda@kernel.org>,
"Alex Gaynor" <alex.gaynor@gmail.com>,
"Gary Guo" <gary@garyguo.net>,
"Björn Roy Baron" <bjorn3_gh@protonmail.com>,
"Benno Lossin" <lossin@kernel.org>,
"Alice Ryhl" <aliceryhl@google.com>,
"Trevor Gross" <tmgross@umich.edu>,
"Danilo Krummrich" <dakr@kernel.org>,
"Andrew Morton" <akpm@linux-foundation.org>,
"Christoph Lameter" <cl@gentwo.org>,
"David Rientjes" <rientjes@google.com>,
"Roman Gushchin" <roman.gushchin@linux.dev>,
"Tamir Duberstein" <tamird@kernel.org>,
"Boqun Feng" <boqun@kernel.org>,
"Lorenzo Stoakes" <ljs@kernel.org>,
"Liam R. Howlett" <liam@infradead.org>,
"Vlastimil Babka" <vbabka@kernel.org>,
"Harry Yoo" <harry@kernel.org>, "Hao Li" <hao.li@linux.dev>,
"Tamir Duberstein" <tamird@kernel.org>,
"Boqun Feng" <boqun@kernel.org>,
"Lorenzo Stoakes" <ljs@kernel.org>,
"Liam R. Howlett" <liam@infradead.org>,
"Vlastimil Babka" <vbabka@kernel.org>,
"Harry Yoo" <harry@kernel.org>
Cc: Daniel Gomez <da.gomez@kernel.org>,
rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org,
linux-mm@kvack.org, Andreas Hindborg <a.hindborg@kernel.org>,
"Matthew Wilcox (Oracle)" <willy@infradead.org>
Subject: [PATCH v4 11/11] rust: xarray: add preload API
Date: Thu, 04 Jun 2026 21:58:17 +0200 [thread overview]
Message-ID: <20260604-xarray-entry-send-v4-11-965f6028790e@kernel.org> (raw)
In-Reply-To: <20260604-xarray-entry-send-v4-0-965f6028790e@kernel.org>
Add a preload API that allows preallocating memory for XArray
insertions. This enables insertions to proceed without allocation
failures in contexts where memory allocation is not desirable, such as
in atomic contexts.
The implementation introduces `XArrayNode` representing a single XArray
node and `XArraySheaf` as a type alias for a sheaf of preallocated
nodes.
Add the function `xarray_kmem_cache` to provide access to the global XArray
node cache for creating sheaves.
Update `VacantEntry::insert` and `VacantEntry::insert_entry` to accept
an optional sheaf argument for preloaded memory. Add a new
`Guard::insert_entry` method for inserting with preload support. When an
insertion would fail due to ENOMEM, the XArray state API automatically
consumes a preallocated node from the sheaf if available.
Export `radix_tree_node_ctor` and `radix_tree_node_cachep` from C to
enable Rust code to work with the radix tree node cache.
Cc: "Liam R. Howlett" <Liam.Howlett@oracle.com>
Cc: "Matthew Wilcox (Oracle)" <willy@infradead.org>
Signed-off-by: Andreas Hindborg <a.hindborg@kernel.org>
---
include/linux/radix-tree.h | 3 +
lib/radix-tree.c | 5 +-
rust/bindings/bindings_helper.h | 3 +
rust/kernel/xarray.rs | 185 +++++++++++++++++++++++++++++++++++-----
rust/kernel/xarray/entry.rs | 29 +++++--
5 files changed, 194 insertions(+), 31 deletions(-)
diff --git a/include/linux/radix-tree.h b/include/linux/radix-tree.h
index eae67015ce51..c3699f12b070 100644
--- a/include/linux/radix-tree.h
+++ b/include/linux/radix-tree.h
@@ -469,4 +469,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/lib/radix-tree.c b/lib/radix-tree.c
index 1cf0012b15ad..ddd67ce672f5 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)
{
diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h
index d4093367a4a8..03fae45d5076 100644
--- a/rust/bindings/bindings_helper.h
+++ b/rust/bindings/bindings_helper.h
@@ -130,6 +130,9 @@ const gfp_t RUST_CONST_HELPER_XA_FLAGS_ALLOC1 = XA_FLAGS_ALLOC1;
* 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/kernel/xarray.rs b/rust/kernel/xarray.rs
index f6d5e5908c8b..cbb16368c2ca 100644
--- a/rust/kernel/xarray.rs
+++ b/rust/kernel/xarray.rs
@@ -5,6 +5,7 @@
//! C header: [`include/linux/xarray.h`](srctree/include/linux/xarray.h)
use core::{
+ convert::Infallible,
iter,
marker::PhantomData,
pin::Pin,
@@ -23,11 +24,17 @@
bindings,
build_assert, //
error::{
+ code::*,
to_result,
Error,
Result, //
},
ffi::c_void,
+ mm::sheaf::{
+ KMemCache,
+ SBox,
+ StaticSheaf, //
+ },
types::{
ForeignOwnable,
NotThreadSafe,
@@ -35,12 +42,54 @@
},
};
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.
+pub struct XArrayNode {
+ node: Opaque<bindings::xa_node>,
+}
+
+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 initalization.
+ 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.
///
/// This is similar to a [`crate::alloc::kvec::Vec<Option<T>>`], but more efficient when there are
@@ -137,15 +186,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()))
}
@@ -166,7 +222,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,
@@ -250,7 +305,7 @@ pub fn get_mut(&mut self, index: usize) -> Option<T::BorrowedMut<'_>> {
///
/// match guard.entry(42) {
/// Entry::Vacant(entry) => {
- /// entry.insert(KBox::new(0x1337u32, GFP_KERNEL)?)?;
+ /// entry.insert(KBox::new(0x1337u32, GFP_ATOMIC)?, None)?;
/// }
/// Entry::Occupied(_) => unreachable!("We did not insert an entry yet"),
/// }
@@ -455,6 +510,45 @@ 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,
+ }),
+ }
+ }
}
/// A reference to a [`Guard`], either shared or mutable, that exposes the
@@ -493,6 +587,30 @@ pub(crate) struct XArrayState<R: GuardRef> {
state: bindings::xa_state,
}
+impl<R: GuardRef> 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<R: GuardRef> XArrayState<R> {
fn new(guard: R, index: usize) -> Self {
let xa_ptr = guard.xa_ptr();
@@ -536,15 +654,36 @@ fn status(&self) -> Result {
to_result(unsafe { bindings::xas_error(&self.state) })
}
- fn insert(&mut self, value: R::Value) -> Result<*mut c_void, StoreError<R::Value>> {
+ fn insert(
+ &mut self,
+ value: R::Value,
+ mut preload: Option<&mut XArraySheaf<'_>>,
+ ) -> Result<*mut c_void, StoreError<R::Value>> {
let new = R::Value::into_foreign(value).cast();
- // 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 `R::Value::into_foreign`.
- unsafe { bindings::xas_store(&mut self.state, new) };
-
- self.status().map(|()| new).map_err(|error| {
+ 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 `R::Value::into_foreign`.
+ unsafe { bindings::xas_store(&mut self.state, new) };
+
+ 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();
+ continue;
+ }
+ Err(e) => break Err(e),
+ }
+ }
+ .map_err(|error| {
// SAFETY: `new` came from `R::Value::into_foreign` and `xas_store` does not take
// ownership of the value on error.
let value = unsafe { R::Value::from_foreign(new) };
@@ -554,9 +693,15 @@ fn insert(&mut self, value: R::Value) -> Result<*mut c_void, StoreError<R::Value
}
impl<'a, 'b, T: ForeignOwnable> XArrayState<&'b mut Guard<'a, T>> {
- /// Consumes `self` and returns the inner `&mut Guard`.
+ /// Consumes `self`, releases any preallocated node held in `xa_alloc`, and
+ /// returns the inner `&mut Guard`.
pub(crate) fn into_guard(self) -> &'b mut Guard<'a, T> {
- self.guard
+ // 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) }
}
}
diff --git a/rust/kernel/xarray/entry.rs b/rust/kernel/xarray/entry.rs
index 5ad79a499156..e979481dd57e 100644
--- a/rust/kernel/xarray/entry.rs
+++ b/rust/kernel/xarray/entry.rs
@@ -3,6 +3,7 @@
use super::{
Guard,
StoreError,
+ XArraySheaf,
XArrayState, //
};
use core::ptr::NonNull;
@@ -29,9 +30,9 @@ impl<T: ForeignOwnable> Entry<'_, '_, T> {
/// 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);
@@ -73,7 +74,8 @@ pub fn into_guard(self) -> &'b mut Guard<'a, T> {
/// 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.
+ /// 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.
///
///
@@ -88,7 +90,7 @@ pub fn into_guard(self) -> &'b mut Guard<'a, T> {
///
/// if let Entry::Vacant(entry) = guard.entry(42) {
/// let value = KBox::new(0x1337u32, GFP_ATOMIC)?;
- /// let borrowed = entry.insert(value)?;
+ /// let borrowed = entry.insert(value, None)?;
/// assert_eq!(*borrowed, 0x1337);
/// }
///
@@ -96,8 +98,12 @@ pub fn into_guard(self) -> &'b mut Guard<'a, T> {
///
/// # Ok::<(), kernel::error::Error>(())
/// ```
- pub fn insert(mut self, value: T) -> Result<T::BorrowedMut<'b>, StoreError<T>> {
- let new = self.state.insert(value)?;
+ 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`.
@@ -107,7 +113,8 @@ pub fn insert(mut self, value: T) -> Result<T::BorrowedMut<'b>, StoreError<T>> {
/// 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.
+ /// 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
@@ -121,7 +128,7 @@ pub fn insert(mut self, value: T) -> Result<T::BorrowedMut<'b>, StoreError<T>> {
///
/// if let Entry::Vacant(entry) = guard.entry(42) {
/// let value = KBox::new(0x1337u32, GFP_ATOMIC)?;
- /// let occupied = entry.insert_entry(value)?;
+ /// let occupied = entry.insert_entry(value, None)?;
/// assert_eq!(occupied.index(), 42);
/// }
///
@@ -129,8 +136,12 @@ pub fn insert(mut self, value: T) -> Result<T::BorrowedMut<'b>, StoreError<T>> {
///
/// # Ok::<(), kernel::error::Error>(())
/// ```
- pub fn insert_entry(mut self, value: T) -> Result<OccupiedEntry<'a, 'b, T>, StoreError<T>> {
- let new = self.state.insert(value)?;
+ 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,
--
2.51.2
prev parent reply other threads:[~2026-06-04 19:59 UTC|newest]
Thread overview: 12+ messages / expand[flat|nested] mbox.gz Atom feed top
2026-06-04 19:58 [PATCH v4 00/11] rust: xarray: add entry API with preloading Andreas Hindborg
2026-06-04 19:58 ` [PATCH v4 01/11] rust: xarray: minor formatting fixes Andreas Hindborg
2026-06-04 19:58 ` [PATCH v4 02/11] rust: xarray: add debug format for `StoreError` Andreas Hindborg
2026-06-04 19:58 ` [PATCH v4 03/11] rust: xarray: add `XArrayState` Andreas Hindborg
2026-06-04 19:58 ` [PATCH v4 04/11] rust: xarray: use `xas_load` instead of `xa_load` in `Guard::load` Andreas Hindborg
2026-06-04 19:58 ` [PATCH v4 05/11] rust: xarray: simplify `Guard::load` Andreas Hindborg
2026-06-04 19:58 ` [PATCH v4 06/11] rust: xarray: add `find_next` and `find_next_mut` Andreas Hindborg
2026-06-04 19:58 ` [PATCH v4 07/11] rust: xarray: add entry API Andreas Hindborg
2026-06-04 19:58 ` [PATCH v4 08/11] rust: mm: add abstractions for allocating from a `sheaf` Andreas Hindborg
2026-06-04 19:58 ` [PATCH v4 09/11] rust: mm: sheaf: allow use of C initialized static caches Andreas Hindborg
2026-06-04 19:58 ` [PATCH v4 10/11] xarray, radix-tree: enable sheaf support for kmem_cache Andreas Hindborg
2026-06-04 19:58 ` Andreas Hindborg [this message]
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
Avoid top-posting and favor interleaved quoting:
https://en.wikipedia.org/wiki/Posting_style#Interleaved_style
* Reply using the --to, --cc, and --in-reply-to
switches of git-send-email(1):
git send-email \
--in-reply-to=20260604-xarray-entry-send-v4-11-965f6028790e@kernel.org \
--to=a.hindborg@kernel.org \
--cc=akpm@linux-foundation.org \
--cc=alex.gaynor@gmail.com \
--cc=aliceryhl@google.com \
--cc=bjorn3_gh@protonmail.com \
--cc=boqun@kernel.org \
--cc=cl@gentwo.org \
--cc=da.gomez@kernel.org \
--cc=dakr@kernel.org \
--cc=gary@garyguo.net \
--cc=hao.li@linux.dev \
--cc=harry@kernel.org \
--cc=liam@infradead.org \
--cc=linux-kernel@vger.kernel.org \
--cc=linux-mm@kvack.org \
--cc=ljs@kernel.org \
--cc=lossin@kernel.org \
--cc=ojeda@kernel.org \
--cc=rientjes@google.com \
--cc=roman.gushchin@linux.dev \
--cc=rust-for-linux@vger.kernel.org \
--cc=tamird@kernel.org \
--cc=tmgross@umich.edu \
--cc=vbabka@kernel.org \
--cc=willy@infradead.org \
/path/to/YOUR_REPLY
https://kernel.org/pub/software/scm/git/docs/git-send-email.html
* If your mail client supports setting the In-Reply-To header
via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line
before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox