Skip to contentSkip to conversation

rust: xarray: add entry API with preloading

PATCH Superseded Andreas Hindborg 2 participants 17 messages Sep 2 – Nov 17

Subsystems (8)

v5 of 6 Superseded Latest is v6 →

lore
Share & tools
lore

Andreas Hindborg

author maintainer
#0 lore raw

v5 cover rust: xarray: add entry API with preloading

This patch series is a mashup of cleanups, bugfixes and feature additions for the Rust XArray abstractions.

- Patch 1 starts by fixing minor formatting issues and bringing use statements up to date with the new coding guidelines.

- Patch 2 add some minor convenience functionality.

- Patch 3 moves two static C helper functions to the xarray header so that they can be called from Rust helpers.

- Patch 4 adds an abstraction for the C xa_state structure and uses it in xarray::Guard::load, removing an unnecessary rcu lock. This is a prerequisite for all the subsequent patches.

- Patch 5 is a simplifying refactor of xarray::Guard::load.

- Patch 6 adds two new methods for finding items with keys that are larger than a given integer.

- Patch 7 adds an entry API.

- Patch 8-9 adds support for object caches based on sheafs.

- Patch 10 enables sheafs for the xarray kmem_cache.

- Patch 11 adds preloading to the new entry API.

- Patch 12 documents that Guard::store may temporarily drop the xarray lock.

The feature additions in this series are dependencies for the rust null block driver, most of which is still downstream.

Best regards,
Andreas

---
Changes in v5:
- Rebase on v7.2.
- Update the cover letter.
- Adapt the entry API to the new lifetime bounds on ForeignOwnable::Borrowed and ForeignOwnable::BorrowedMut.
- Squash the xas_load conversion into the XArrayState patch (Tamir).
- Replace the GuardRef trait with a Deref bound on XArrayState (Tamir).
- Filter internal XA_ZERO_ENTRY entries in XArrayState::load and load_next (Sashiko).
- Add a new patch moving xas_result() and xa_zero_to_null() to the xarray header instead of duplicating them in the Rust helpers (Tamir).
- Require an exclusive guard reference for XArrayState::insert.
- Add XArrayState::replace and XArrayState::restart_at helpers and use them in the entry code (Daniel).
- Clear XA_FREE_MARK when inserting through the entry API (Sashiko).
- Reset the xa_state cursor before retrying a failed store in XArrayState::insert (Sashiko).
- Check for NULL before running the object initializer in Sheaf::alloc (Sashiko).
- Set cache object alignment to the alignment of T in KMemCacheHandle::new (Sashiko).
- Restrict the SBox raw pointer round trip to static caches (Sashiko).
- Implement Send and Sync for the sheaf types and Send for XArrayNode where sound (Sashiko).
- Add #[repr(transparent)] to XArrayNode (Sashiko).
- Document that dropping the last KMemCacheHandle reference may sleep (Sashiko).
- Add a new patch documenting that Guard::store may temporarily drop the lock (Sashiko).
- Import kernel::fmt in the StoreError Debug implementation (Tamir).
- Add the __rust_helper attribute to the new C helpers (Sashiko).
- Add #[inline] to small forwarding functions in the xarray and sheaf abstractions (Sashiko).
- Fix the SAFETY comment in OccupiedEntry::insert (Sashiko).
- Fix the KMemCacheInit::init documentation (Sashiko).
- Update the Guard::load simplification commit message to note it establishes the untyped pointer style for the rest of the series (Tamir).
- Remove a stray blank line in Guard::get_mut (Tamir).
- Expand the entry API commit message to describe and motivate the added API surface (Tamir).
- Collect Daniel's Reviewed-by tags. The tag for the XArrayState patch is dropped due to substantial rework of the patch.
- Link to v4: https://msgid.link/[email protected]

Changes in v4:
- Rebase on v7.1-rc2.
- Drop contains_index patch (Tamir).
- Use kernel::fmt::* rather than core::fmt::* (Tamir).
- Add into_guard to VacantEntry and OccupiedEntry for releasing the entry borrow while keeping the lock guard (Alice).
- Refactor XArrayState over a new GuardRef trait to support both &Guard and &mut Guard borrows.
- Improve the XArrayState type invariant and update SAFETY comments.
- Document the (size_t)XAS_RESTART cast in bindings_helper.h (Tamir).
- Use GFP_ATOMIC when allocating under spinlock in the examples.
- Link to v3: https://msgid.link/[email protected]

Changes in v3:
- Fix a misconception about sheaf availablility under CONFIG_SLUB_TINY and CONFIG_SLUB_DEBUG.
- Add missing patch to enable sheaf support in xarray kmem_cache.
- Update commit messages for last 3 patches.
- Link to v2: https://msgid.link/[email protected]

Changes in v2:
- Rebase on v6.19-rc8.
- Update the cover letter.
- Implement preloading with sheafs.
- Investigate generating RUST_CONST_HELPER_XAS_RESTART as pointer -> Not possible.
- Correct wording of commit message for patch "rust: xarray: use xas_load instead of xa_load in Guard::load".
- Correct wording of commit message for patch "rust: xarray: add find_next and find_next_mut".
- Remove last patch (lockdep static key fix) from series, to be sent separately.
- Expand note on why store to occupied slot cannot fail.
- Change signature of OccupiedEntry::swap to match core::mem::swap.
- Move // NOTEs about storing NULL closer to relevant checks.
- Move insert_internal to XArrayState.
- Share logic between find_next and find_next_entry.
- Rename XArray::get_entry to XArray::entry.
- Make load_next a method on XArrayState.
- Move load logic to XArrayState.
- Use PhantomData to capture lifetime of Guard for XArrayState.
- Link to v1: https://lore.kernel.org/r/[email protected]

To: Tamir Duberstein <[email protected]>
To: Andreas Hindborg <[email protected]>
To: Miguel Ojeda <[email protected]>
To: Boqun Feng <[email protected]>
To: Gary Guo <[email protected]>
To: Björn Roy Baron <[email protected]>
To: Benno Lossin <[email protected]>
To: Alice Ryhl <[email protected]>
To: Trevor Gross <[email protected]>
To: Danilo Krummrich <[email protected]>
To: Daniel Almeida <[email protected]>
To: Alexandre Courbot <[email protected]>
To: Onur Özkan <[email protected]>
To: Matthew Wilcox <[email protected]>
To: Andrew Morton <[email protected]>
To: Lorenzo Stoakes <[email protected]>
To: "Liam R. Howlett" <[email protected]>
To: Vlastimil Babka <[email protected]>
To: Harry Yoo <[email protected]>
To: Hao Li <[email protected]>
To: Christoph Lameter <[email protected]>
To: David Rientjes <[email protected]>
To: Roman Gushchin <[email protected]>
Cc: [email protected]
Cc: [email protected]
Cc: [email protected]
Cc: [email protected]

---
Andreas Hindborg (12):
rust: xarray: minor formatting fixes
rust: xarray: add debug format for StoreError
xarray: move xas_result() and xa_zero_to_null() to the header
rust: xarray: add XArrayState
rust: xarray: simplify Guard::load
rust: xarray: add find_next and find_next_mut
rust: xarray: add entry API
rust: mm: add abstractions for allocating from a sheaf
rust: mm: sheaf: allow use of C initialized static caches xarray, radix-tree: enable sheaf support for kmem_cache
rust: xarray: add preload API
rust: xarray: document Guard lock drop semantics

 MAINTAINERS                     |   1 +
 include/linux/radix-tree.h      |   3 +
 include/linux/xarray.h          |  26 ++
 lib/radix-tree.c                |  19 +-
 lib/xarray.c                    |  12 -
 mm/slub.c                       |   4 +
 rust/bindings/bindings_helper.h |  11 +
 rust/helpers/xarray.c           |  15 +
 rust/kernel/mm.rs               |   1 +
 rust/kernel/mm/sheaf.rs         | 769 ++++++++++++++++++++++++++++++++++++++++
 rust/kernel/xarray.rs           | 599 +++++++++++++++++++++++++++++--
 rust/kernel/xarray/entry.rs     | 373 +++++++++++++++++++
 12 files changed, 1782 insertions(+), 51 deletions(-)

---
base-commit: 8d3ae59288f1e7d58d76558a6ee96d533bc5019f
change-id: 20251203-xarray-entry-send-00230f0744e6

Best regards,

Signature · 1 line
Andreas Hindborg <[email protected]>
author maintainer
#1 lore raw

PATCH v5 1/12 rust: xarray: minor formatting fixes

Fix formatting in xarray module to comply with kernel coding guidelines:

- Update use clauses to use vertical layout with each import on its own line.
- Add trailing empty comments to preserve formatting and prevent rustfmt from collapsing imports.
- Break long assert_eq! statement in documentation across multiple lines for better readability.

---
 rust/kernel/xarray.rs | 30 +++++++++++++++++++++++-------
 1 file changed, 23 insertions(+), 7 deletions(-)
rust/kernel/xarray.rs +23 -7
index 987c9c0c21989..02f93ae1f92de 100644
@@ -4,20 +4,33 @@
 //!
 //! C header: [`include/linux/xarray.h`](srctree/include/linux/xarray.h)
 
-use crate::{
+use core::{
+    iter,
+    marker::PhantomData,
+    pin::Pin,
+    ptr::NonNull, //
+};
+use kernel::{
     alloc,
     bindings,
-    build_assert::build_assert,
-    error::{Error, Result},
+    build_assert::build_assert, //
+    error::{
+        Error,
+        Result, //
+    },
     ffi::c_void,
     types::{
         ForeignOwnable,
         NotThreadSafe,
         Opaque, //
-    }, //
+    },
+};
+use pin_init::{
+    pin_data,
+    pin_init,
+    pinned_drop,
+    PinInit, //
 };
-use core::{iter, marker::PhantomData, pin::Pin, ptr::NonNull};
-use pin_init::{pin_data, pin_init, pinned_drop, PinInit};
 
 /// An array which efficiently maps sparse integer indices to owned objects.
 ///
@@ -50,7 +63,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);
Signature · 1 line
2.51.2
author maintainer
#2 lore raw

PATCH v5 2/12 rust: xarray: add debug format for `StoreError`

In reply to Andreas Hindborg

Add a Debug implementation for StoreError<T> to enable better error reporting and debugging. The implementation only displays the error field and omits the value field, as T may not implement Debug.

---
 rust/kernel/xarray.rs | 9 +++++++++
 1 file changed, 9 insertions(+)
rust/kernel/xarray.rs +9 -0
index 02f93ae1f92d..4335caab8cca 100644
@@ -19,6 +19,7 @@
         Result, //
     },
     ffi::c_void,
+    fmt,
     types::{
         ForeignOwnable,
         NotThreadSafe,
@@ -193,6 +194,14 @@ pub struct StoreError<T> {
     pub value: T,
 }
 
+impl<T> fmt::Debug for StoreError<T> {
+    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 {
Signature · 1 line
2.51.2
author maintainer
#3 lore raw

PATCH v5 3/12 xarray: move xas_result() and xa_zero_to_null() to the header

In reply to Andreas Hindborg

The functions xas_result() and xa_zero_to_null() are static in lib/xarray.c. Upcoming Rust XArray changes need to call them from Rust helper functions. Move them to include/linux/xarray.h as static inline functions, following the approach of commit 79ada2ae6615 ("xarray: extract helper from __xa_{insert,cmpxchg}").

No functional change.

---
 include/linux/xarray.h | 26 ++++++++++++++++++++++++++
 lib/xarray.c           | 12 ------------
 2 files changed, 26 insertions(+), 12 deletions(-)
include/linux/xarray.h +26 -0
index be850174e802e..db2520864aaa7 100644
@@ -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.
lib/xarray.c +0 -12
index 9a8b4916540cf..cddb44f6b4ab2 100644
@@ -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;
@@ -1624,13 +1619,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.
Signature · 1 line
2.51.2
author maintainer
#4 lore raw

PATCH v5 4/12 rust: xarray: add `XArrayState`

In reply to Andreas Hindborg

Add XArrayState as internal state for XArray iteration and entry operations. This struct wraps the C xa_state structure and holds a reference to a Guard to ensure exclusive access to the XArray for the lifetime of the state object. XArrayState is generic over the guard borrow through a Deref bound, so it can hold either a shared or a mutable reference to the guard.

Use the new state in Guard::load by replacing the call to xa_load with xas_load. The xa_load function takes the RCU lock internally, which we do not need, since the Guard already holds an exclusive lock on the XArray. The xas_load function operates on xa_state and assumes the required locks are already held.

Unlike xa_load, 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 the C normal API does, exposing the xa_zero_to_null helper for this purpose.

The XAS_RESTART constant is also exposed through the bindings helper to properly initialize the xa_node field.

The guard field of XArrayState is not read until a later patch adds into_guard, so it is annotated with #[expect(dead_code)] until then.

Assisted-by LLM
---
 rust/bindings/bindings_helper.h |  7 ++++
 rust/helpers/xarray.c           |  5 +++
 rust/kernel/xarray.rs           | 74 ++++++++++++++++++++++++++++++++++++++---
 3 files changed, 81 insertions(+), 5 deletions(-)
rust/bindings/bindings_helper.h +7 -0
index 1124785e210b3..419e6b74fedc3 100644
@@ -124,6 +124,13 @@ const xa_mark_t RUST_CONST_HELPER_XA_PRESENT = XA_PRESENT;
 
 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 vm_flags_t RUST_CONST_HELPER_VM_MERGEABLE = VM_MERGEABLE;
 const vm_flags_t RUST_CONST_HELPER_VM_READ = VM_READ;
rust/helpers/xarray.c +5 -0
index 08979b3043410..79799c55c3d73 100644
@@ -26,3 +26,8 @@ __rust_helper void rust_helper_xa_unlock(struct xarray *xa)
 {
 	return xa_unlock(xa);
 }
+
+__rust_helper void *rust_helper_xa_zero_to_null(void *entry)
+{
+	return xa_zero_to_null(entry);
+}
rust/kernel/xarray.rs +69 -5

92 lines not on this page · raw message

Signature · 1 line
2.51.2
author maintainer
#5 lore raw

PATCH v5 5/12 rust: xarray: simplify `Guard::load`

In reply to Andreas Hindborg

Simplify the implementation by removing the closure-based API from Guard::load in favor of returning Option<NonNull<c_void>> directly.

The closure-based API existed to avoid passing around untyped pointers. The following patches add find and entry operations that need to store the returned pointer in entry objects and pass it between internal functions, where the closure style does not scale. Change load to return the pointer directly, establishing the style used for the rest of the series. Pointers are still only converted to references at the public API boundary.

---
 rust/kernel/xarray.rs | 25 +++++++++++--------------
 1 file changed, 11 insertions(+), 14 deletions(-)
rust/kernel/xarray.rs +11 -14
index e8082df2b479..a14f874ad630 100644
@@ -213,28 +213,25 @@ 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,
-    {
-        let mut state = XArrayState::new(self, index);
-        Some(f(state.load()?))
+    #[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.
+    #[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| {
-            // SAFETY: `ptr` came from `T::into_foreign`.
-            unsafe { T::borrow_mut(ptr.as_ptr()) }
-        })
+        let ptr = self.load(index)?;
+        // SAFETY: `ptr` came from `T::into_foreign`.
+        Some(unsafe { T::borrow_mut(ptr.as_ptr()) })
     }
 
     /// Removes and returns the element at the given index.
Signature · 1 line
2.51.2
author maintainer
#6 lore raw

PATCH v5 6/12 rust: xarray: add `find_next` and `find_next_mut`

In reply to Andreas Hindborg

Add methods to find the next element in an XArray starting from a given index. The methods return a tuple containing the index where the element was found and a reference to the element.

The implementation uses the XArray state API via xas_find to avoid taking the rcu lock as an exclusive lock is already held by Guard.

Assisted-by LLM
---
 rust/kernel/xarray.rs | 101 ++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 101 insertions(+)
rust/kernel/xarray.rs +101 -0
index a14f874ad630..9993783fc854 100644
@@ -219,6 +219,22 @@ fn load(&self, index: usize) -> Option<NonNull<c_void>> {
     }
 
     /// 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<'_>> {
         let ptr = self.load(index)?;
@@ -234,6 +250,67 @@ pub fn get_mut(&mut self, index: usize) -> Option<T::BorrowedMut<'_>> {
         Some(unsafe { T::borrow_mut(ptr.as_ptr()) })
     }
 
+    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>(())
+    /// ```
+    pub fn find_next(&self, index: usize) -> Option<(usize, T::Borrowed<'_>)> {
+        self.load_next(index)
+            // SAFETY: `ptr` came from `T::into_foreign`.
+            .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>(())
+    /// ```
+    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()) }))
+    }
+
     /// Removes and returns the element at the given index.
     pub fn remove(&mut self, index: usize) -> Option<T> {
         // SAFETY:
@@ -359,6 +436,30 @@ fn load(&mut self) -> Option<NonNull<c_void>> {
         // 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));
+            }
+        }
+    }
 }
 
 // SAFETY: `XArray<T>` has no shared mutable state so it is `Send` iff `T` is `Send`.
Signature · 1 line
2.51.2
author maintainer
#7 lore raw

PATCH v5 7/12 rust: xarray: add entry API

In reply to Andreas Hindborg

Add an Entry API for XArray that provides ergonomic access to array slots that may be vacant or occupied. The API follows the pattern of Rust's standard library HashMap entry API, allowing efficient conditional insertion and modification of entries.

Guard::entry returns an Entry that is either Vacant or Occupied. The functionality provided by the two entry types is motivated by the needs of the Rust null block driver memory backing implementation:

- VacantEntry::insert inserts a value and returns a borrow of it. VacantEntry::insert_entry inserts a value and returns an OccupiedEntry instead, for callers that need to perform further operations on the slot after insertion.
- OccupiedEntry provides access to the value through Deref and DerefMut, replaces the value through insert or swap, and removes it from the array through remove.
- Entry::is_occupied and the index methods support conditional logic and bookkeeping in callers.
- into_guard releases the borrow of the slot and returns the underlying guard, so a caller can continue operating on the array without dropping the lock.
- Guard::find_next_entry and Guard::find_next_entry_circular return an OccupiedEntry for the next occupied slot, the latter wrapping around at the end of the array. Guard::insert_entry combines lookup and insertion into one operation.

The implementation uses the XArray state API (xas_* functions) for efficient operations without requiring multiple lookups. Helper functions are added to rust/helpers/xarray.c to wrap static inline C functions that are not directly accessible from Rust.

Also update MAINTAINERS to cover the new rust files.

Assisted-by LLM
---
 MAINTAINERS                     |   1 +
 rust/bindings/bindings_helper.h |   1 +
 rust/helpers/xarray.c           |  10 ++
 rust/kernel/xarray.rs           | 174 ++++++++++++++++++-
 rust/kernel/xarray/entry.rs     | 362 ++++++++++++++++++++++++++++++++++++++++
 5 files changed, 544 insertions(+), 4 deletions(-)
MAINTAINERS +1 -0
index 8014b9f8253ed..b2c9911b88d1d 100644
@@ -29347,6 +29347,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 <[email protected]>
rust/bindings/bindings_helper.h +1 -0
index 419e6b74fedc3..5dda2bb36e3c2 100644
@@ -121,6 +121,7 @@ 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;
rust/helpers/xarray.c +10 -0
index 79799c55c3d73..d7548a17ae0d0 100644
@@ -27,7 +27,17 @@ __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);
+}
rust/kernel/xarray.rs +170 -4

211 lines not on this page · raw message

rust/kernel/xarray/entry.rs new file +362 -0

362 lines not on this page · raw message

Signature · 1 line
2.51.2
author maintainer
#8 lore raw

PATCH v5 8/12 rust: mm: add abstractions for allocating from a `sheaf`

In reply to Andreas Hindborg

Add Rust APIs for allocating objects from a sheaf.

Introduce a reduced abstraction KMemCacheInit for struct kmem_cache to support management of the Sheafs.

Initialize objects using in-place initialization when objects are allocated from a Sheaf. This is different from C which tends to do some initialization when the cache is filled. This approach is chosen because there is no destructor/drop capability in struct kmem_cache that can be invoked when the cache is dropped.

Cc Vlastimil Babka <[email protected]>
Cc "Liam R. Howlett" <[email protected]>
Cc "Matthew Wilcox (Oracle)" <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Assisted-by LLM
---
 rust/kernel/mm.rs       |   1 +
 rust/kernel/mm/sheaf.rs | 466 ++++++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 467 insertions(+)
rust/kernel/mm.rs +1 -0
index 4764d7b68f2a7..1aa44424b0d53 100644
@@ -18,6 +18,7 @@
 };
 use core::{ops::Deref, ptr::NonNull};
 
+pub mod sheaf;
 pub mod virt;
 use virt::VmaRef;
 
rust/kernel/mm/sheaf.rs new file +466 -0

466 lines not on this page · raw message

Signature · 1 line
2.51.2
maintainer Acked-by on v5 8/12
#9 lore raw

Re: [PATCH v5 08/12] rust: mm: add abstractions for allocating from a `sheaf`

Quoted 11 lines · Andreas Hindborg

Add Rust APIs for allocating objects from a sheaf.

Introduce a reduced abstraction KMemCacheInit for struct kmem_cache to support management of the Sheafs.

Initialize objects using in-place initialization when objects are allocated from a Sheaf. This is different from C which tends to do some initialization when the cache is filled. This approach is chosen because there is no destructor/drop capability in struct kmem_cache that can be invoked when the cache is dropped.

Quoted 7 lines
Cc Vlastimil Babka <[email protected]>
Cc "Liam R. Howlett" <[email protected]>
Cc "Matthew Wilcox (Oracle)" <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Assisted-by LLM

Note that currently all caches have sheaves (except CONFIG_SLUB_TINY or slab_debug enabled), and sheaf_capacity on creation is treated as a minimum, which the automated sizing calculation can make larger - in case you want to reflect this detail in some of the description comments.

author maintainer
#10 lore raw

Re: [PATCH v5 08/12] rust: mm: add abstractions for allocating from a `sheaf`

Quoted 20 lines · Vlastimil Babka (SUSE)
Quoted 11 lines · Andreas Hindborg

Add Rust APIs for allocating objects from a sheaf.

Introduce a reduced abstraction KMemCacheInit for struct kmem_cache to support management of the Sheafs.

Initialize objects using in-place initialization when objects are allocated from a Sheaf. This is different from C which tends to do some initialization when the cache is filled. This approach is chosen because there is no destructor/drop capability in struct kmem_cache that can be invoked when the cache is dropped.

Quoted 7 lines
Cc Vlastimil Babka <[email protected]>
Cc "Liam R. Howlett" <[email protected]>
Cc "Matthew Wilcox (Oracle)" <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Assisted-by LLM
Quoted 6 lines

Note that currently all caches have sheaves (except CONFIG_SLUB_TINY or slab_debug enabled), and sheaf_capacity on creation is treated as a minimum, which the automated sizing calculation can make larger - in case you want to reflect this detail in some of the description comments.

Thanks, I will update the documentation sections!

Best regards,
Andreas Hindborg

author maintainer
#11 lore raw

PATCH v5 9/12 rust: mm: sheaf: allow use of C initialized static caches

In reply to Andreas Hindborg

Extend the sheaf abstraction to support caches initialized by C at kernel boot time, in addition to dynamically created Rust caches.

Introduce KMemCache<T> as a transparent wrapper around kmem_cache for static caches with 'static lifetime. Rename the previous KMemCache<T> to KMemCacheHandle<T> to represent dynamically created, reference-counted caches.

Add Static and Dynamic marker types along with StaticSheaf and DynamicSheaf type aliases to distinguish sheaves from each cache type. The Sheaf type now carries lifetime and allocation mode type parameters.

Add SBox::into_ptr() and SBox::static_from_ptr() methods for passing allocations through C code via raw pointers.

Add KMemCache::from_raw() for wrapping C-initialized static caches and Sheaf::refill() for replenishing a sheaf to a minimum size.

Export kmem_cache_prefill_sheaf, kmem_cache_return_sheaf, kmem_cache_refill_sheaf, and kmem_cache_alloc_from_sheaf_noprof to allow Rust module code to use the sheaf API.

Cc Vlastimil Babka <[email protected]>
Cc "Liam R. Howlett" <[email protected]>
Cc "Matthew Wilcox (Oracle)" <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Assisted-by LLM
---
 mm/slub.c               |   4 +
 rust/kernel/mm/sheaf.rs | 401 ++++++++++++++++++++++++++++++++++++++++++------
 2 files changed, 356 insertions(+), 49 deletions(-)
mm/slub.c +4 -0
index 0337e60db5ac..d81dbf2abb86 100644
@@ -5101,6 +5101,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()
@@ -5156,6 +5157,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
@@ -5211,6 +5213,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()
@@ -5249,6 +5252,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)
 {
rust/kernel/mm/sheaf.rs +352 -49

560 lines not on this page · raw message

Signature · 1 line
2.51.2
maintainer Acked-by on v5 9/12
#12 lore raw

Re: [PATCH v5 09/12] rust: mm: sheaf: allow use of C initialized static caches

Quoted 2 lines · Andreas Hindborg

Extend the sheaf abstraction to support caches initialized by C at kernel boot time, in addition to dynamically created Rust caches.

Nit: in C code caches can be also dynamically created :)

Quoted 19 lines

Introduce KMemCache<T> as a transparent wrapper around kmem_cache for static caches with 'static lifetime. Rename the previous KMemCache<T> to KMemCacheHandle<T> to represent dynamically created, reference-counted caches.

Add Static and Dynamic marker types along with StaticSheaf and DynamicSheaf type aliases to distinguish sheaves from each cache type. The Sheaf type now carries lifetime and allocation mode type parameters.

Add SBox::into_ptr() and SBox::static_from_ptr() methods for passing allocations through C code via raw pointers.

Add KMemCache::from_raw() for wrapping C-initialized static caches and Sheaf::refill() for replenishing a sheaf to a minimum size.

Export kmem_cache_prefill_sheaf, kmem_cache_return_sheaf, kmem_cache_refill_sheaf, and kmem_cache_alloc_from_sheaf_noprof to allow Rust module code to use the sheaf API.

Quoted 7 lines
Cc Vlastimil Babka <[email protected]>
Cc "Liam R. Howlett" <[email protected]>
Cc "Matthew Wilcox (Oracle)" <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Assisted-by LLM
author maintainer
#13 lore raw

Re: [PATCH v5 09/12] rust: mm: sheaf: allow use of C initialized static caches

Quoted 5 lines · Vlastimil Babka (SUSE)
Quoted 2 lines · Andreas Hindborg

Extend the sheaf abstraction to support caches initialized by C at kernel boot time, in addition to dynamically created Rust caches.

Nit: in C code caches can be also dynamically created :)

Right. But the Rust abstractions do not support interacting with those. Only dynamic caches created through the Rust API or static ones created in C are supported.

Quoted 28 lines
Quoted 20 lines

Introduce KMemCache<T> as a transparent wrapper around kmem_cache for static caches with 'static lifetime. Rename the previous KMemCache<T> to KMemCacheHandle<T> to represent dynamically created, reference-counted caches.

Add Static and Dynamic marker types along with StaticSheaf and DynamicSheaf type aliases to distinguish sheaves from each cache type. The Sheaf type now carries lifetime and allocation mode type parameters.

Add SBox::into_ptr() and SBox::static_from_ptr() methods for passing allocations through C code via raw pointers.

Add KMemCache::from_raw() for wrapping C-initialized static caches and Sheaf::refill() for replenishing a sheaf to a minimum size.

Export kmem_cache_prefill_sheaf, kmem_cache_return_sheaf, kmem_cache_refill_sheaf, and kmem_cache_alloc_from_sheaf_noprof to allow Rust module code to use the sheaf API.

Quoted 7 lines
Cc Vlastimil Babka <[email protected]>
Cc "Liam R. Howlett" <[email protected]>
Cc "Matthew Wilcox (Oracle)" <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Assisted-by LLM
Quoted 1 line

Thanks!

Best regards,
Andreas Hindborg

author maintainer
#14 lore raw

PATCH v5 10/12 xarray, radix-tree: enable sheaf support for kmem_cache

In reply to Andreas Hindborg

The rust null block driver plans to rely on preloading xarray nodes from the radix_tree_node_cachep kmem_cache.

Cc "Matthew Wilcox (Oracle)" <[email protected]>
Assisted-by LLM
---
 lib/radix-tree.c | 14 ++++++++++----
 1 file changed, 10 insertions(+), 4 deletions(-)
lib/radix-tree.c +10 -4
index 976b9bd02a1b5..1cf0012b15ade 100644
@@ -1598,10 +1598,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);
Signature · 1 line
2.51.2
author maintainer
#15 lore raw

PATCH v5 11/12 rust: xarray: add preload API

In reply to Andreas Hindborg

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" <[email protected]>
Cc "Matthew Wilcox (Oracle)" <[email protected]>
Assisted-by LLM
---
 include/linux/radix-tree.h      |   3 +
 lib/radix-tree.c                |   5 +-
 rust/bindings/bindings_helper.h |   3 +
 rust/kernel/xarray.rs           | 214 +++++++++++++++++++++++++++++++++++-----
 rust/kernel/xarray/entry.rs     |  27 +++--
 5 files changed, 215 insertions(+), 37 deletions(-)
include/linux/radix-tree.h +3 -0
index eae67015ce51a..c3699f12b070c 100644
@@ -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 */
lib/radix-tree.c +3 -2
index 1cf0012b15ade..ddd67ce672f5c 100644
@@ -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)
 {
rust/bindings/bindings_helper.h +3 -0
index 5dda2bb36e3c2..ccbd92880dc88 100644
@@ -132,6 +132,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;
rust/kernel/xarray.rs +187 -27

291 lines not on this page · raw message

rust/kernel/xarray/entry.rs +19 -8
index c6c5385e6b4f9..bd295358d9751 100644
@@ -3,6 +3,7 @@
 use super::{
     Guard,
     StoreError,
+    XArraySheaf,
     XArrayState, //
 };
 use core::ptr::NonNull;
@@ -75,7 +76,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.
     ///
     ///
@@ -90,7 +92,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);
     /// }
     ///
@@ -98,8 +100,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`.
@@ -109,7 +115,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
@@ -123,7 +130,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);
     /// }
     ///
@@ -131,8 +138,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,
Signature · 1 line
2.51.2
author maintainer
#16 lore raw

PATCH v5 12/12 rust: xarray: document `Guard` lock drop semantics

In reply to Andreas Hindborg

Guard::store calls __xa_store, which drops the xarray lock to allocate memory when called with blocking allocation flags and reacquires it afterwards. A Rust lock guard is normally expected to provide continuous mutual exclusion for its entire lifetime, so this behavior can surprise users: a check-then-act sequence spanning a blocking store call is not atomic.

Document the behavior on Guard and expand the store docs, pointing to the entry API with preallocated memory as the way to modify the array without dropping the lock.

---
 rust/kernel/xarray.rs | 22 +++++++++++++++++++++-
 1 file changed, 21 insertions(+), 1 deletion(-)
rust/kernel/xarray.rs +21 -1
index 87123ab96a92..a11472acc661 100644
@@ -242,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>,
@@ -485,7 +500,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.
     ///
Signature · 1 line
2.51.2