Skip to contentSkip to conversation

rust: xarray: add entry API with preloading

PATCH Applied Andreas Hindborg 3 participants 20 messages Nov 20 – Nov 23

Subsystems (8)
lore
Share & tools
lore
author maintainer
#15 lore raw

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

In reply to Andreas Hindborg

Extend the sheaf abstraction to support caches that are never destroyed, such as caches created by C code at kernel boot time, in addition to reference-counted caches created through the abstraction.

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 caches that are created through the abstraction, reference-counted, and destroyed when the last reference is dropped.

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]>
---
 mm/slub.c               |   4 +
 rust/kernel/mm/sheaf.rs | 397 +++++++++++++++++++++++++++++++++++++++++-------
 2 files changed, 342 insertions(+), 59 deletions(-)
mm/slub.c +4 -0
index cd671b934719..21811b9ff791 100644
@@ -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)
 {
rust/kernel/mm/sheaf.rs +338 -59

559 lines not on this page · raw message

Signature · 1 line
2.54.0

Andreas Hindborg

author maintainer
#0 lore raw

v6 cover rust: xarray: add entry API with preloading

This patch series is a mashup of cleanups 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 adds 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.

- Patches 8-9 add support for sheaf-based object caches.

- Patch 10 enables sheaf support 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 v6:
- Rebase on v7.4-rc2.
- Assert pointer alignment when inserting through the entry API (Sashiko).
- Correct the documentation of the sheaf capacity: the requested capacity is a minimum, and requesting a larger sheaf yields an oversize sheaf rather than a warning (Vlastimil, Sashiko).
- Describe static and dynamic caches by whether they are destroyed, rather than by the language creating them, in the sheaf documentation and commit message (Vlastimil).
- Document that dropping a Sheaf never destroys its cache (Sashiko).
- Document the reference counting done when allocating from a dynamic cache (Sashiko).
- Merge the two identical Sheaf::alloc implementations.
- Add missing #[inline] annotations to small forwarding functions (Sashiko).
- Move the trailing empty comment to the last item of the import list and mention the crate to kernel change in the commit message (Sashiko).
- Remove the drop call from the Entry::is_occupied example until Drop is implemented for XArrayState, to keep each patch clippy clean.
- Link to v5: https://msgid.link/[email protected]

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         | 762 ++++++++++++++++++++++++++++++++++++++++
 rust/kernel/xarray.rs           | 605 +++++++++++++++++++++++++++++--
 rust/kernel/xarray/entry.rs     | 381 ++++++++++++++++++++
 12 files changed, 1791 insertions(+), 49 deletions(-)

---
base-commit: 7475ea8b58616b33c04afb976cf0fbaad9dd63fb
change-id: 20251203-xarray-entry-send-00230f0744e6

Best regards,

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

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

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 183808971683..94386678ef81 100644
@@ -214,28 +214,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.54.0
author maintainer
#17 lore raw

PATCH v6 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]>
---
 lib/radix-tree.c | 14 ++++++++++----
 1 file changed, 10 insertions(+), 4 deletions(-)
lib/radix-tree.c +10 -4
index 976b9bd02a1b..1cf0012b15ad 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.54.0
author maintainer
#5 lore raw

PATCH v6 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 be850174e802..db2520864aaa 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 bfe7bef80f34..49fbec5f6c38 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;
@@ -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.
Signature · 1 line
2.54.0
author maintainer
#18 lore raw

PATCH v6 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]>
---
 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     |  28 ++++--
 5 files changed, 216 insertions(+), 37 deletions(-)
include/linux/radix-tree.h +3 -0
index 057edc4cbb6e..ac5fc299399c 100644
@@ -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 */
lib/radix-tree.c +3 -2
index 1cf0012b15ad..ddd67ce672f5 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 dd7c84b1a564..fb76a2d30449 100644
@@ -138,6 +138,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

295 lines not on this page · raw message

rust/kernel/xarray/entry.rs +20 -8
index e2f01a49c55e..3d004f6f8c6c 100644
@@ -3,6 +3,7 @@
 use super::{
     Guard,
     StoreError,
+    XArraySheaf,
     XArrayState, //
 };
 use core::ptr::NonNull;
@@ -32,6 +33,7 @@ impl<T: ForeignOwnable> Entry<'_, '_, T> {
     ///
     /// 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);
@@ -75,7 +77,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 +93,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 +101,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 +116,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 +131,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 +139,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.54.0
author maintainer
#3 lore raw

PATCH v6 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 | 10 ++++++++++
 1 file changed, 10 insertions(+)
rust/kernel/xarray.rs +10 -0
index 4f4b6bf5750d..19581b9dfe9e 100644
@@ -19,6 +19,7 @@
         Result, //
     },
     ffi::c_void,
+    fmt,
     types::{
         ForeignOwnable,
         NotThreadSafe,
@@ -193,6 +194,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 {
Signature · 1 line
2.54.0
author maintainer
#11 lore raw

PATCH v6 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]>
---
 rust/kernel/mm.rs       |   1 +
 rust/kernel/mm/sheaf.rs | 483 ++++++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 484 insertions(+)
rust/kernel/mm.rs +1 -0
index 58bc1793fdaf..c1920f049170 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 +483 -0

483 lines not on this page · raw message

Signature · 1 line
2.54.0
author maintainer
#8 lore raw

PATCH v6 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.

---
 rust/kernel/xarray.rs | 104 ++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 104 insertions(+)
rust/kernel/xarray.rs +104 -0
index 94386678ef81..07ec08223fbd 100644
@@ -220,6 +220,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)?;
@@ -235,6 +251,70 @@ pub fn get_mut(&mut self, index: usize) -> Option<T::BorrowedMut<'_>> {
         Some(unsafe { T::borrow_mut(ptr.as_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`.
+            .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()) }))
+    }
+
     /// Removes and returns the element at the given index.
     pub fn remove(&mut self, index: usize) -> Option<T> {
         // SAFETY:
@@ -361,6 +441,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.54.0
author maintainer
#6 lore raw

PATCH v6 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.

---
 rust/bindings/bindings_helper.h |  7 ++++
 rust/helpers/xarray.c           |  5 +++
 rust/kernel/xarray.rs           | 75 ++++++++++++++++++++++++++++++++++++++---
 3 files changed, 82 insertions(+), 5 deletions(-)
rust/bindings/bindings_helper.h +7 -0
index 3791af0aadc7..517c5872ad25 100644
@@ -130,6 +130,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 08979b304341..79799c55c3d7 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 +70 -5

93 lines not on this page · raw message

Signature · 1 line
2.54.0
author maintainer
#1 lore raw

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

In reply to Andreas Hindborg

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.
- Refer to the kernel crate as kernel rather than crate in use clauses.
- Break long assert_eq! statement in documentation across multiple lines for better readability.

---
 rust/kernel/xarray.rs | 26 +++++++++++++++++++++-----
 1 file changed, 21 insertions(+), 5 deletions(-)
rust/kernel/xarray.rs +21 -5
index 987c9c0c2198..4f4b6bf5750d 100644
@@ -4,11 +4,20 @@
 //!
 //! 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},
+    error::{
+        Error,
+        Result, //
+    },
     ffi::c_void,
     types::{
         ForeignOwnable,
@@ -16,8 +25,12 @@
         Opaque, //
     }, //
 };
-use core::{iter, marker::PhantomData, pin::Pin, ptr::NonNull};
-use pin_init::{pin_data, pin_init, pinned_drop, PinInit};
+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.54.0
author maintainer
#9 lore raw

PATCH v6 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.

---
 MAINTAINERS                     |   1 +
 rust/bindings/bindings_helper.h |   1 +
 rust/helpers/xarray.c           |  10 ++
 rust/kernel/xarray.rs           | 179 ++++++++++++++++++-
 rust/kernel/xarray/entry.rs     | 369 ++++++++++++++++++++++++++++++++++++++++
 5 files changed, 556 insertions(+), 4 deletions(-)
MAINTAINERS +1 -0
index 222b7fc2c3aa..845503be1f28 100644
@@ -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 <[email protected]>
rust/bindings/bindings_helper.h +1 -0
index 517c5872ad25..dd7c84b1a564 100644
@@ -127,6 +127,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 79799c55c3d7..d7548a17ae0d 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 +175 -4

216 lines not on this page · raw message

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

369 lines not on this page · raw message

Signature · 1 line
2.54.0
author maintainer
#19 lore raw

PATCH v6 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 b13d06f9b0df..20792b09c126 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>,
@@ -489,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.
     ///
Signature · 1 line
2.54.0
#10 lore raw

Re: [PATCH v6 07/12] rust: xarray: add entry API

In reply to Andreas Hindborg
Thank you for your contribution! Sashiko AI review found 3 potential issues to consider: - [Medium] rust: xarray: OccupiedEntry deref() and deref_mut() use Guard borrow lifetime - [Low] rust…

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider:
- [Medium] rust: xarray: OccupiedEntry deref() and deref_mut() use Guard borrow lifetime
- [Low] rust: xarray: Guard::entry() discards walked XArrayState from load()
- [Low] rust: xarray: inaccurate doc comments and missing Guard::insert_entry()
--

commit 6b0e265e85674545670123d4c157941bef632ae4
Author: Andreas Hindborg <[email protected]>

rust: xarray: add entry API

This commit adds an Entry API (Entry, VacantEntry, and OccupiedEntry) to the Rust XArray abstraction using the xas_* state operations.

Quoted 4 lines
rust/kernel/xarray.rs +0 -0
index 07ec08223fbd2..3ff94c05a15a1 100644

[ ... ]

Quoted 5 lines
rust/kernel/xarray.rs +1 -0
@@ -251,6 +257,35 @@ pub fn get_mut(&mut self, index: usize) -> Option<T::BorrowedMut<'_>> {
         Some(unsafe { T::borrow_mut(ptr.as_ptr()) })
     }
 
+    /// Gets an entry for the specified index, which can be vacant or occupied.

[ ... ]

rust/kernel/xarray.rs pub fn get_mut(&mut self, index: usize) -> Option<T::BorrowedMut<'_>> { · line 287

Quoted 6 lines
rust/kernel/xarray.rs +6 -0
+    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)),
+        }
+    }

[Severity: Low]
Does Guard::entry() discard the walked XArrayState from self.load(index) and force a second tree walk on subsequent entry operations?

self.load(index) constructs a temporary XArrayState, walks the tree via xas_load(), and drops that state on return. VacantEntry::new() and OccupiedEntry::new() then construct a fresh XArrayState with xa_node reset to XAS_RESTART, so a later insert(), replace(), or remove() walks the tree from the root again. Constructing a single XArrayState in Guard::entry(), calling state.load(), and passing that state into VacantEntry or OccupiedEntry would preserve the positioned cursor.

Quoted 5 lines
rust/kernel/xarray/entry.rs new file +0 -0
new file mode 100644
index 0000000000000..e2f01a49c55e0

[ ... ]

Quoted 7 lines
rust/kernel/xarray/entry.rs new file +7 -0
+    /// 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.
+    /// - This method will not drop the XArray lock.

[ ... ]

Quoted 3 lines
rust/kernel/xarray/entry.rs new file +3 -0
+    /// Swaps the value in this entry with the provided value.
+    ///
+    /// Returns the old value that was in the entry.

[ ... ]

rust/kernel/xarray/entry.rs line 343

Quoted 9 lines
rust/kernel/xarray/entry.rs new file +9 -0
+    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);
+    }
+}

[Severity: Low]
This isn't a bug, but a few documentation comments do not match the implementation:

VacantEntry::insert() and VacantEntry::insert_entry() say they fail if the nodes on the path to the index are not present, whereas xas_store() allocates missing nodes with GFP_NOWAIT and only fails if that allocation fails.

OccupiedEntry::swap() says it returns the old value, but it swaps in place with other and returns ().

Also, the commit message mentions Guard::insert_entry, which is not added until commit "rust: xarray: add preload API" later in this series.

Quoted 15 lines
rust/kernel/xarray/entry.rs new file +15 -0
+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>

rust/kernel/xarray/entry.rs line 369

Quoted 10 lines
rust/kernel/xarray/entry.rs new file +10 -0
+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()) }
+    }
+}

[Severity: Medium]
Do OccupiedEntry::deref() and OccupiedEntry::deref_mut() violate the ForeignOwnable::borrow() and ForeignOwnable::borrow_mut() safety contracts by instantiating them with the Guard borrow lifetime 'b instead of the lifetime of &self or &mut self?

Because the where-clauses only constrain T::Borrowed<'b> = &'b U and T::BorrowedMut<'b> = &'b mut U for the fixed outer lifetime 'b, calling T::borrow() or T::borrow_mut() here produces a borrow for the entire Guard borrow lifetime 'b before reborrowing it for &self or &mut self. ForeignOwnable::borrow_mut<'a>() requires that 'a not overlap with the lifetime of any other call to borrow() or borrow_mut() on the same object, and both methods require that any call to from_foreign() happen after 'a ends. Dereferencing an OccupiedEntry (for example in OccupiedEntry::swap()) and then dereferencing it again or calling OccupiedEntry::insert() or OccupiedEntry::remove() creates overlapping 'b borrows or runs T::from_foreign() while 'b is still active.

In addition, requiring BorrowedMut<'b> = &'b mut U on the Deref implementation prevents shared dereferencing for ForeignOwnable types such as Arc or ARef that do not yield &mut U from BorrowedMut.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=7
#12 lore raw

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

In reply to Andreas Hindborg
Thank you for your contribution! Sashiko AI review found 4 potential issues to consider: - [Medium] rust: mm: Sheaf::alloc() bypasses alloc_hooks() by calling _noprof directly - [Low] rust: mm…

Thank you for your contribution! Sashiko AI review found 4 potential issues to consider:
- [Medium] rust: mm: Sheaf::alloc() bypasses alloc_hooks() by calling _noprof directly
- [Low] rust: mm: missing #[inline] on small C-forwarding methods in sheaf.rs
- [Low] rust: mm: imports in sheaf.rs do not follow kernel vertical import style
- [Low] rust: mm: direct call to internal PinInit::__init() in Sheaf::alloc()
--

commit 5e97f4874e1bec1246089d6fb000afa8148da652
Author: Andreas Hindborg <[email protected]>

rust: mm: add abstractions for allocating from a sheaf

This commit adds Rust abstractions (KMemCache, KMemCacheInit, Sheaf, and SBox) for pre-allocating and allocating slab objects using SLUB sheaves.

Quoted 6 lines
rust/kernel/mm/sheaf.rs new file +0 -0
new file mode 100644
index 0000000000000..1bc0c3dca900f
@@ -0,0 +1,483 @@

[ ... ]

rust/kernel/mm/sheaf.rs line 85

Quoted 10 lines
rust/kernel/mm/sheaf.rs new file +10 -0
+use core::{
+    convert::Infallible,
+    marker::PhantomData,
+    ops::{Deref, DerefMut},
+    ptr::NonNull,
+};
+
+use kernel::prelude::*;
+
+use crate::sync::{Arc, ArcBorrow};

[Severity: Low]
These imports group multiple items on one line instead of using the kernel vertical import style from Documentation/rust/coding-guidelines.rst (one item per line with a trailing // comment).

[ ... ]

rust/kernel/mm/sheaf.rs line 248

Quoted 9 lines
rust/kernel/mm/sheaf.rs new file +9 -0
+impl<T: KMemCacheInit<T>> Drop for KMemCache<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()) };
+    }
+}

[Severity: Low]
KMemCache::drop(), Sheaf::alloc(), Sheaf::drop(), and SBox::drop() are small functions in the kernel crate that forward directly to C bindings, so they should be marked #[inline].

[ ... ]

rust/kernel/mm/sheaf.rs line 382

Quoted 6 lines
rust/kernel/mm/sheaf.rs new file +6 -0
+    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())
+        };

[Severity: Medium]
Does calling kmem_cache_alloc_from_sheaf_noprof() directly bypass alloc_hooks() and leave current->alloc_tag unset when CONFIG_MEM_ALLOC_PROFILING is enabled?

In C, kmem_cache_alloc_from_sheaf() is a macro wrapping kmem_cache_alloc_from_sheaf_noprof() in alloc_hooks() to set current->alloc_tag before slab_post_alloc_hook() runs __alloc_tagging_slab_alloc_hook():

mm/slub.c:__alloc_tagging_slab_alloc_hook() {
	...
	if (likely(obj_exts)) {
		...
		alloc_tag_add(ref, current->alloc_tag, s->size);
		put_slab_obj_exts(obj_exts);
	} else {
		if (!is_kfence_address(object))
			alloc_tag_set_inaccurate(current->alloc_tag);
	}
}

With current->alloc_tag left NULL, CONFIG_MEM_ALLOC_PROFILING_DEBUG triggers WARN_ONCE() in alloc_tag_add_check() on allocation and in alloc_tag_sub_check() on free, and if prepare_slab_obj_exts_hook() fails to allocate obj_exts under memory pressure, alloc_tag_set_inaccurate() dereferences NULL current->alloc_tag. Wrapping the kmem_cache_alloc_from_sheaf() macro in a __rust_helper in rust/helpers/slab.c would preserve the profiling hooks.

rust/kernel/mm/sheaf.rs line 390

Quoted 8 lines
rust/kernel/mm/sheaf.rs new file +8 -0
+
+        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");

[Severity: Low]
PinInit::__init() is an internal trait method not meant to be called directly. Following commit ea7da3116015 ("rust: treewide: replace __pinned_init with raw_[try_]init"), could this use pin_init::raw_init(ptr.as_ptr(), T::init()) instead, which also avoids the expect()?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=8
#16 lore raw

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

In reply to Andreas Hindborg
Thank you for your contribution! Sashiko AI review found 4 potential issues to consider: - [Low] rust: mm: sheaf: missing #[inline] on small helpers and C-binding wrappers - [Low] rust: mm: sheaf…

Thank you for your contribution! Sashiko AI review found 4 potential issues to consider:
- [Low] rust: mm: sheaf: missing #[inline] on small helpers and C-binding wrappers
- [Low] rust: mm: sheaf: non-vertical crate import formatting
- [Low] rust: mm: sheaf: SBox erases cache mode, allowing into_ptr() on dynamic caches
- [Low] rust: mm: sheaf: missing INVARIANT comments and raw pointer in CacheRef::Static
--

commit c03ff5cdfb00d1a6cfd826320ab8e9750410636a
Author: Andreas Hindborg <[email protected]>

rust: mm: sheaf: allow use of C initialized static caches

This commit extends the Rust sheaf abstraction to support C-initialized static slab caches alongside reference-counted dynamic caches, adding raw pointer conversion helpers for SBox and exporting the underlying C sheaf functions.

In rust/kernel/mm/sheaf.rs at line 95 (crate imports):

[Severity: Low]
Could the crate import block use the kernel vertical import style, placing Arc and ArcBorrow on separate lines?

In rust/kernel/mm/sheaf.rs at lines 172, 616, and 717 (KMemCache::sheaf, CacheRef, and SBox::static_from_ptr):

[Severity: Low]
CacheRef documents an # Invariants section requiring CacheRef::Static to hold a NonNull pointer to a valid KMemCache<T> with 'static lifetime, derived from a &'static KMemCache<T> reference, and CacheRef::as_raw() relies on this invariant in its SAFETY comment. However, neither KMemCache::sheaf() nor SBox::static_from_ptr() includes an // INVARIANT:
comment when constructing CacheRef::Static, and SBox::static_from_ptr() constructs CacheRef::Static by casting a raw *mut bindings::kmem_cache pointer rather than taking a &'static KMemCache<T>. Could both construction sites document how the CacheRef invariant holds, and could SBox::static_from_ptr() accept &'static KMemCache<T> directly?

In rust/kernel/mm/sheaf.rs at lines 197, 548, 628, 694, and 717 (KMemCache::from_raw, Sheaf::refill, CacheRef::clone, SBox::into_ptr, and SBox::static_from_ptr):

[Severity: Low]
Could KMemCache::from_raw(), Sheaf::refill(), CacheRef::clone(), SBox::into_ptr(), and SBox::static_from_ptr() be marked with #[inline] to match the other small helpers and C-binding wrappers in this module and enable cross-crate inlining?

In rust/kernel/mm/sheaf.rs at lines 667 and 694 (SBox and SBox::into_ptr):

[Severity: Low]
Should SBox carry the Static or Dynamic mode parameter A (or encode the cache reference type via A) so into_ptr() is only callable on static-cache allocations?

Because Sheaf::alloc() erases A into a runtime CacheRef<T> enum inside SBox<T>, SBox::into_ptr() is exposed as a safe method on allocations from a DynamicSheaf as well. Calling into_ptr() on a dynamic allocation triggers the debug_assert!() in builds with CONFIG_RUST_DEBUG_ASSERTIONS=y (which is not mentioned in a # Panics doc section and contradicts the doc comment saying it leaks a reference), and permanently leaks an Arc<KMemCacheHandle<T>> reference in non-debug builds so the underlying kmem_cache is never destroyed.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=9
#13 lore raw

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

In reply to Andreas Hindborg
Quoted 13 lines · Andreas Hindborg
rust/kernel/mm/sheaf.rs new file +13 -0
+/// 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` holds a reference to the [`KMemCache`] it was allocated from.
+/// Dropping the `SBox` may thus drop the last reference to the cache and
+/// destroy the cache, which may sleep. See the `# Context` section of
+/// [`KMemCache`].

rust/kernel/mm/sheaf.rs line 441

Quoted 10 lines
rust/kernel/mm/sheaf.rs new file +10 -0
+///
+/// # 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: Arc<KMemCache<T>>,
+}

I did only notice this patch just now, will take a closer look later on. But this all looks like it belongs into the alloc module.

Thanks,
Danilo

author maintainer
#14 lore raw

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

Quoted 19 lines · Danilo Krummrich
Quoted 18 lines · Andreas Hindborg
rust/kernel/mm/sheaf.rs new file +18 -0
+/// 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` holds a reference to the [`KMemCache`] it was allocated from.
+/// Dropping the `SBox` may thus drop the last reference to the cache and
+/// destroy the cache, which may sleep. See the `# Context` section of
+/// [`KMemCache`].
+///
+/// # Invariants
+///
+/// - `ptr` points to a valid, initialized object of type `T`.
+/// - `cache` is the cache from which this object was allocated.
Quoted 8 lines

rust/kernel/mm/sheaf.rs line 441

Quoted 5 lines
rust/kernel/mm/sheaf.rs new file +5 -0
+/// - The object remains valid for the lifetime of the `SBox`.
+pub struct SBox<T: KMemCacheInit<T>> {
+    ptr: NonNull<T>,
+    cache: Arc<KMemCache<T>>,
+}

I did only notice this patch just now, will take a closer look later on. But this all looks like it belongs into the alloc module.

Yea, could be we should move it to alloc.

Best regards,
Andreas Hindborg

author maintainer Applied
#4 lore raw

Re: [PATCH v6 02/12] rust: xarray: add debug format for `StoreError`

In reply to Andreas Hindborg
Quoted 3 lines · 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.

Applied, thanks!

[02/12] rust: xarray: add debug format for StoreError

        commit: fe0612239662b50da2fb7b95409be1f3aa7a2f1f

Best regards,

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

Re: [PATCH v6 01/12] rust: xarray: minor formatting fixes

In reply to Andreas Hindborg
Quoted 12 lines · Andreas Hindborg

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.
- Refer to the kernel crate as kernel rather than crate in use clauses.
- Break long assert_eq! statement in documentation across multiple lines for better readability.

Quoted 1 line

[...]

Applied, thanks!

[01/12] rust: xarray: minor formatting fixes

        commit: 62cac56c118c96bf2026275a0edc80f1b3a87375

Best regards,

Signature · 1 line
Andreas Hindborg <[email protected]>