Skip to contentSkip to conversation

rust: xarray: add entry API with preloading

PATCH Superseded Andreas Hindborg 4 participants 33 messages Jun 4 – Aug 28 2 messages not in the archive

Subsystems (6)

v4 of 6 Superseded Latest is v6 →

lore
Share & tools
lore
author maintainer
#31 lore raw

PATCH v4 8/11 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 | 407 ++++++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 408 insertions(+)
rust/kernel/mm.rs +1 -0
index 4764d7b68f2a..1aa44424b0d5 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 +407 -0

407 lines not on this page · raw message

Signature · 1 line
2.51.2
author maintainer
#34 lore raw

PATCH v4 11/11 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           | 185 +++++++++++++++++++++++++++++++++++-----
 rust/kernel/xarray/entry.rs     |  29 +++++--
 5 files changed, 194 insertions(+), 31 deletions(-)
include/linux/radix-tree.h +3 -0
index eae67015ce51..c3699f12b070 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 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 d4093367a4a8..03fae45d5076 100644
@@ -130,6 +130,9 @@ const gfp_t RUST_CONST_HELPER_XA_FLAGS_ALLOC1 = XA_FLAGS_ALLOC1;
  * see https://github.com/rust-lang/rust-bindgen/issues/3347.
  */
 const size_t RUST_CONST_HELPER_XAS_RESTART = (size_t)XAS_RESTART;
+const size_t RUST_CONST_HELPER_XA_CHUNK_SHIFT = XA_CHUNK_SHIFT;
+const size_t RUST_CONST_HELPER_XA_CHUNK_SIZE = XA_CHUNK_SIZE;
+extern struct kmem_cache *radix_tree_node_cachep;
 
 const vm_flags_t RUST_CONST_HELPER_VM_MERGEABLE = VM_MERGEABLE;
 const vm_flags_t RUST_CONST_HELPER_VM_READ = VM_READ;
rust/kernel/xarray.rs +165 -20

259 lines not on this page · raw message

rust/kernel/xarray/entry.rs +20 -9
index 5ad79a499156..e979481dd57e 100644
@@ -3,6 +3,7 @@
 use super::{
     Guard,
     StoreError,
+    XArraySheaf,
     XArrayState, //
 };
 use core::ptr::NonNull;
@@ -29,9 +30,9 @@ impl<T: ForeignOwnable> Entry<'_, '_, T> {
     /// let mut xa = KBox::pin_init(XArray::<KBox<u32>>::new(AllocKind::Alloc), GFP_KERNEL)?;
     /// let mut guard = xa.lock();
     ///
-    ///
     /// let entry = guard.entry(42);
     /// assert_eq!(entry.is_occupied(), false);
+    /// drop(entry);
     ///
     /// guard.store(42, KBox::new(0x1337u32, GFP_ATOMIC)?, GFP_ATOMIC)?;
     /// let entry = guard.entry(42);
@@ -73,7 +74,8 @@ pub fn into_guard(self) -> &'b mut Guard<'a, T> {
     /// Returns a reference to the newly inserted value.
     ///
     /// - This method will fail if the nodes on the path to the index
-    ///   represented by this entry are not present in the XArray.
+    ///   represented by this entry are not present in the XArray and no memory
+    ///   is available via the `preload` argument.
     /// - This method will not drop the XArray lock.
     ///
     ///
@@ -88,7 +90,7 @@ pub fn into_guard(self) -> &'b mut Guard<'a, T> {
     ///
     /// if let Entry::Vacant(entry) = guard.entry(42) {
     ///     let value = KBox::new(0x1337u32, GFP_ATOMIC)?;
-    ///     let borrowed = entry.insert(value)?;
+    ///     let borrowed = entry.insert(value, None)?;
     ///     assert_eq!(*borrowed, 0x1337);
     /// }
     ///
@@ -96,8 +98,12 @@ pub fn into_guard(self) -> &'b mut Guard<'a, T> {
     ///
     /// # Ok::<(), kernel::error::Error>(())
     /// ```
-    pub fn insert(mut self, value: T) -> Result<T::BorrowedMut<'b>, StoreError<T>> {
-        let new = self.state.insert(value)?;
+    pub fn insert(
+        mut self,
+        value: T,
+        preload: Option<&mut XArraySheaf<'_>>,
+    ) -> Result<T::BorrowedMut<'b>, StoreError<T>> {
+        let new = self.state.insert(value, preload)?;
 
         // SAFETY: `new` came from `T::into_foreign`. The entry has exclusive
         // ownership of `new` as it holds a mutable reference to `Guard`.
@@ -107,7 +113,8 @@ pub fn insert(mut self, value: T) -> Result<T::BorrowedMut<'b>, StoreError<T>> {
     /// Inserts a value and returns an occupied entry representing the newly inserted value.
     ///
     /// - This method will fail if the nodes on the path to the index
-    ///   represented by this entry are not present in the XArray.
+    ///   represented by this entry are not present in the XArray and no memory
+    ///   is available via the `preload` argument.
     /// - This method will not drop the XArray lock.
     ///
     /// # Examples
@@ -121,7 +128,7 @@ pub fn insert(mut self, value: T) -> Result<T::BorrowedMut<'b>, StoreError<T>> {
     ///
     /// if let Entry::Vacant(entry) = guard.entry(42) {
     ///     let value = KBox::new(0x1337u32, GFP_ATOMIC)?;
-    ///     let occupied = entry.insert_entry(value)?;
+    ///     let occupied = entry.insert_entry(value, None)?;
     ///     assert_eq!(occupied.index(), 42);
     /// }
     ///
@@ -129,8 +136,12 @@ pub fn insert(mut self, value: T) -> Result<T::BorrowedMut<'b>, StoreError<T>> {
     ///
     /// # Ok::<(), kernel::error::Error>(())
     /// ```
-    pub fn insert_entry(mut self, value: T) -> Result<OccupiedEntry<'a, 'b, T>, StoreError<T>> {
-        let new = self.state.insert(value)?;
+    pub fn insert_entry(
+        mut self,
+        value: T,
+        preload: Option<&mut XArraySheaf<'_>>,
+    ) -> Result<OccupiedEntry<'a, 'b, T>, StoreError<T>> {
+        let new = self.state.insert(value, preload)?;
 
         Ok(OccupiedEntry::<'a, 'b, T> {
             state: self.state,
Signature · 1 line
2.51.2
author maintainer
#22 lore raw

PATCH v4 6/11 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 | 69 +++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 69 insertions(+)
rust/kernel/xarray.rs +69 -0
index 7da57c778669..7efa8a36d559 100644
@@ -231,6 +231,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()
+    }
+
+    /// 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:
@@ -360,6 +421,14 @@ fn load(&mut self) -> Option<NonNull<c_void>> {
         let ptr = unsafe { bindings::xas_load(&raw mut self.state) };
         NonNull::new(ptr.cast())
     }
+
+    fn load_next(&mut self) -> Option<(usize, NonNull<c_void>)> {
+        // SAFETY: `self.state` is a valid `xa_state` by the type invariant. By the same
+        // invariant, `self.state.xa` aliases the xarray reachable through `self.guard`, whose
+        // lock we hold.
+        let ptr = unsafe { bindings::xas_find(&raw mut self.state, usize::MAX) };
+        NonNull::new(ptr).map(|ptr| (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
#33 lore raw

PATCH v4 10/11 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.51.2
author maintainer
#11 lore raw

PATCH v4 3/11 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.

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

The struct and its constructor are marked with #[expect(dead_code)] as there are no users yet. We will remove this annotation in a later patch.

---
 rust/bindings/bindings_helper.h |  7 +++++
 rust/kernel/xarray.rs           | 66 ++++++++++++++++++++++++++++++++++++++++-
 2 files changed, 72 insertions(+), 1 deletion(-)
rust/bindings/bindings_helper.h +7 -0
index 446dbeaf0866..d4093367a4a8 100644
@@ -123,6 +123,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/kernel/xarray.rs +65 -1

78 lines not on this page · raw message

Signature · 1 line
2.51.2
author maintainer
#7 lore raw

PATCH v4 2/11 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 | 8 ++++++++
 1 file changed, 8 insertions(+)
rust/kernel/xarray.rs +8 -0
index b80fb7a262d0..d54942aeb201 100644
@@ -193,6 +193,14 @@ pub struct StoreError<T> {
     pub value: T,
 }
 
+impl<T> kernel::fmt::Debug for StoreError<T> {
+    fn fmt(&self, f: &mut kernel::fmt::Formatter<'_>) -> kernel::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
#27 lore raw

PATCH v4 7/11 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.

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 C macros that are not directly accessible from Rust.

Also update MAINTAINERS to cover the new rust files.

---
 MAINTAINERS                 |   1 +
 rust/helpers/xarray.c       |  17 ++
 rust/kernel/xarray.rs       | 131 +++++++++++++++
 rust/kernel/xarray/entry.rs | 385 ++++++++++++++++++++++++++++++++++++++++++++
 4 files changed, 534 insertions(+)
MAINTAINERS +1 -0
index 882214b0e7db..8bc0f7d95dce 100644
@@ -28984,6 +28984,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/helpers/xarray.c +17 -0
index 08979b304341..19fce6862c78 100644
@@ -26,3 +26,20 @@ __rust_helper void rust_helper_xa_unlock(struct xarray *xa)
 {
 	return xa_unlock(xa);
 }
+
+void *rust_helper_xas_result(struct xa_state *xas, void *curr)
+{
+	if (xa_err(xas->xa_node))
+		curr = xas->xa_node;
+	return curr;
+}
+
+void *rust_helper_xa_zero_to_null(void *entry)
+{
+	return xa_is_zero(entry) ? NULL : entry;
+}
+
+int rust_helper_xas_error(const struct xa_state *xas)
+{
+	return xas_error(xas);
+}
rust/kernel/xarray.rs +131 -0

162 lines not on this page · raw message

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

385 lines not on this page · raw message

Signature · 1 line
2.51.2
author maintainer
#1 lore raw

PATCH v4 1/11 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.
- Break long assert_eq! statement in documentation across multiple lines for better readability.

---
 rust/kernel/xarray.rs | 36 +++++++++++++++++++++++++++++-------
 1 file changed, 29 insertions(+), 7 deletions(-)
rust/kernel/xarray.rs +29 -7
index 46e5f43223fe..b80fb7a262d0 100644
@@ -4,14 +4,33 @@
 //!
 //! C header: [`include/linux/xarray.h`](srctree/include/linux/xarray.h)
 
-use crate::{
-    alloc, bindings, build_assert,
-    error::{Error, Result},
+use core::{
+    iter,
+    marker::PhantomData,
+    pin::Pin,
+    ptr::NonNull, //
+};
+use kernel::{
+    alloc,
+    bindings,
+    build_assert, //
+    error::{
+        Error,
+        Result, //
+    },
     ffi::c_void,
-    types::{ForeignOwnable, NotThreadSafe, Opaque},
+    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.
 ///
@@ -44,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
#32 lore raw

PATCH v4 9/11 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]>
---
 mm/slub.c               |   4 +
 rust/kernel/mm/sheaf.rs | 343 +++++++++++++++++++++++++++++++++++++++++++-----
 2 files changed, 317 insertions(+), 30 deletions(-)
mm/slub.c +4 -0
index 0baa906f39ab..87f138588100 100644
@@ -5063,6 +5063,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()
@@ -5118,6 +5119,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
@@ -5174,6 +5176,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()
@@ -5211,6 +5214,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 +313 -30

462 lines not on this page · raw message

Signature · 1 line
2.51.2

Andreas Hindborg

author maintainer
#0 lore raw

v4 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 adds an abstraction for the C xa_state structure. This is a prerequisite for all the subsequent patches.

- Patch 4 removes an unnecessary rcu lock in xarray::Guard::load.

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

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 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]

---
Andreas Hindborg (11):
rust: xarray: minor formatting fixes
rust: xarray: add debug format for StoreError
rust: xarray: add XArrayState
rust: xarray: use xas_load instead of xa_load in Guard::load
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

 MAINTAINERS                     |   1 +
 include/linux/radix-tree.h      |   3 +
 lib/radix-tree.c                |  19 +-
 mm/slub.c                       |   4 +
 rust/bindings/bindings_helper.h |  10 +
 rust/helpers/xarray.c           |  17 +
 rust/kernel/mm.rs               |   1 +
 rust/kernel/mm/sheaf.rs         | 690 ++++++++++++++++++++++++++++++++++++++++
 rust/kernel/xarray.rs           | 502 +++++++++++++++++++++++++++--
 rust/kernel/xarray/entry.rs     | 396 +++++++++++++++++++++++
 10 files changed, 1605 insertions(+), 38 deletions(-)

---
base-commit: 7fd2df204f342fc17d1a0bfcd474b24232fb0f32
change-id: 20251203-xarray-entry-send-00230f0744e6

Best regards,

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

PATCH v4 4/11 rust: xarray: use `xas_load` instead of `xa_load` in `Guard::load`

Replace the call to xa_load with xas_load in Guard::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.

This change also removes the #[expect(dead_code)] annotation from XArrayState and its constructor, as they are now in use.

---
 rust/kernel/xarray.rs | 16 ++++++++++------
 1 file changed, 10 insertions(+), 6 deletions(-)
rust/kernel/xarray.rs +10 -6
index 6d0d4905004a..05e6dc1ffe69 100644
@@ -216,10 +216,8 @@ fn load<F, U>(&self, index: usize, f: F) -> Option<U>
     where
         F: FnOnce(NonNull<c_void>) -> U,
     {
-        // SAFETY: `self.xa.xa` is always valid by the type invariant.
-        let ptr = unsafe { bindings::xa_load(self.xa.xa.get(), index) };
-        let ptr = NonNull::new(ptr.cast())?;
-        Some(f(ptr))
+        let mut state = XArrayState::new(self, index);
+        Some(f(state.load()?))
     }
 
     /// Provides a reference to the element at the given index.
@@ -333,14 +331,12 @@ fn xa_ptr(&self) -> *mut bindings::xarray {
 ///
 /// - `state` is always a valid `bindings::xa_state`.
 /// - `state.xa` aliases the xarray reachable through `guard`.
-#[expect(dead_code)]
 pub(crate) struct XArrayState<R: GuardRef> {
     guard: R,
     state: bindings::xa_state,
 }
 
 impl<R: GuardRef> XArrayState<R> {
-    #[expect(dead_code)]
     fn new(guard: R, index: usize) -> Self {
         let xa_ptr = guard.xa_ptr();
         // INVARIANT: `state` is initialized to a valid `xa_state` whose `xa` field aliases the
@@ -361,6 +357,14 @@ fn new(guard: R, index: usize) -> Self {
             },
         }
     }
+
+    fn load(&mut self) -> Option<NonNull<c_void>> {
+        // SAFETY: `self.state` is a valid `xa_state` by the type invariant. By the same
+        // invariant, `self.state.xa` aliases the xarray reachable through `self.guard`, whose
+        // lock we hold.
+        let ptr = unsafe { bindings::xas_load(&raw mut self.state) };
+        NonNull::new(ptr.cast())
+    }
 }
 
 // SAFETY: `XArray<T>` has no shared mutable state so it is `Send` iff `T` is `Send`.
Signature · 1 line
2.51.2
author maintainer
#18 lore raw

PATCH v4 5/11 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.

---
 rust/kernel/xarray.rs | 23 +++++++++--------------
 1 file changed, 9 insertions(+), 14 deletions(-)
rust/kernel/xarray.rs +9 -14
index 05e6dc1ffe69..7da57c778669 100644
@@ -212,28 +212,23 @@ 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()?))
+    fn load(&self, index: usize) -> Option<NonNull<c_void>> {
+        XArrayState::new(self, index).load()
     }
 
     /// Provides a reference to the element at the given index.
     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.
     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
maintainer
#8 lore raw

Re: [PATCH v4 02/11] rust: xarray: add debug format for `StoreError`

In reply to Andreas Hindborg
Quoted 6 lines · Andreas Hindborg
rust/kernel/xarray.rs +0 -0
index b80fb7a262d0..d54942aeb201 100644
@@ -193,6 +193,14 @@ pub struct StoreError<T> {
     pub value: T,

rust/kernel/xarray.rs pub struct StoreError<T> { · line 203

Quoted 10 lines
rust/kernel/xarray.rs +8 -0
 }
 
+impl<T> kernel::fmt::Debug for StoreError<T> {
+    fn fmt(&self, f: &mut kernel::fmt::Formatter<'_>) -> kernel::fmt::Result {
+        f.debug_struct("StoreError")
+            .field("error", &self.error)
+            .finish()
+    }
+}
+

Maybe an import of kernel::fmt at the top would be cleaner.

Signature · 1 line
Tamir Duberstein <[email protected]>
maintainer
#12 lore raw

Re: [PATCH v4 03/11] rust: xarray: add `XArrayState`

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

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

The struct and its constructor are marked with #[expect(dead_code)] as there are no users yet. We will remove this annotation in a later patch.

The review of this patch in v3 requested the next patch be absorbed into it.

Quoted 8 lines
rust/kernel/xarray.rs +0 -0
index d54942aeb201..6d0d4905004a 100644
@@ -299,6 +302,67 @@ pub fn store(

[ ... skip 17 lines ... ]

rust/kernel/xarray.rs pub fn store( · line 324

Quoted 6 lines
rust/kernel/xarray.rs +6 -0
+impl<'a, T: ForeignOwnable> GuardRef for &mut Guard<'a, T> {
+    type Value = T;
+    fn xa_ptr(&self) -> *mut bindings::xarray {
+        self.xa.xa.get()
+    }
+}

I'm having a hard time understanding the need for this trait, and it is not described in the commit message at all. How is this different than using Deref? &mut T has a blanket Deref<Target = T> impl.

Signature · 1 line
Tamir Duberstein <[email protected]>
maintainer
#19 lore raw

Re: [PATCH v4 05/11] rust: xarray: simplify `Guard::load`

In reply to Andreas Hindborg
Quoted 2 lines · Andreas Hindborg

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

This is simpler, but the closure-based API was here for a reason (to avoid passing around untyped pointers). This patch is estabilishing the style for subsequent patches, but doesn't honestly describe that it is doing so.

Quoted 8 lines
rust/kernel/xarray.rs +0 -0
index 05e6dc1ffe69..7da57c778669 100644
@@ -212,28 +212,23 @@ fn from(value: StoreError<T>) -> Self {

[ ... skip 26 lines ... ]

rust/kernel/xarray.rs fn from(value: StoreError<T>) -> Self { · line 229

Quoted 6 lines
rust/kernel/xarray.rs +2 -4
-        self.load(index, |ptr| {
-            // SAFETY: `ptr` came from `T::into_foreign`.
-            unsafe { T::borrow_mut(ptr.as_ptr()) }
-        })
+        let ptr = self.load(index)?;
+

Inconsistent whitespace.

Signature · 1 line
Tamir Duberstein <[email protected]>
maintainer
#23 lore raw

Re: [PATCH v4 06/11] rust: xarray: add `find_next` and `find_next_mut`

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

The previous patch re-hosts existing XArray methods on XArrayState, but this patch and subsequent ones are choosing to grow the XArray API rather than promote XArrayState to a proper abstraction that users should prefer. Are you sure that's the right choice?

Signature · 1 line
Tamir Duberstein <[email protected]>
maintainer
#28 lore raw

Re: [PATCH v4 07/11] rust: xarray: add entry API

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

There's a lot more API here than this lets on. find_next_entry{,_circular}, Entry::is_occupied, into_guard, insert{,_entry} (do we need both?), index, OccupiedEntry::swap, Deref{,Mut}.

It's not clear that all this API is needed, and this message does not attempt to justify it. It is also inconsistent with the split in patches 3 and 4.

Quoted 12 lines
rust/helpers/xarray.c +2 -0
index 08979b304341..19fce6862c78 100644
@@ -26,3 +26,20 @@ __rust_helper void rust_helper_xa_unlock(struct xarray *xa)
 {
 	return xa_unlock(xa);
 }
+
+void *rust_helper_xas_result(struct xa_state *xas, void *curr)

rust/helpers/xarray.c __rust_helper void rust_helper_xa_unlock(struct xarray *xa) · line 40

Quoted 10 lines
rust/helpers/xarray.c +10 -0
+{
+	if (xa_err(xas->xa_node))
+		curr = xas->xa_node;
+	return curr;
+}
+
+void *rust_helper_xa_zero_to_null(void *entry)
+{
+	return xa_is_zero(entry) ? NULL : entry;
+}

These functions already exist in C, but are static inline in xarray.c. Can we move them to the header instead of duplicating them here please? That is what I did in 79ada2ae ("xarray: extract helper from __xa_{insert,cmpxchg}").

Signature · 1 line
Tamir Duberstein <[email protected]>
author maintainer
#9 lore raw

Re: [PATCH v4 02/11] rust: xarray: add debug format for `StoreError`

In reply to Tamir Duberstein
Quoted 9 lines · Tamir Duberstein
Quoted 8 lines · Andreas Hindborg
rust/kernel/xarray.rs +0 -0
index b80fb7a262d0..d54942aeb201 100644
@@ -193,6 +193,14 @@ pub struct StoreError<T> {
     pub value: T,
 }
 
Quoted 10 lines

rust/kernel/xarray.rs pub struct StoreError<T> { · line 203

Quoted 8 lines
rust/kernel/xarray.rs +8 -0
+impl<T> kernel::fmt::Debug for StoreError<T> {
+    fn fmt(&self, f: &mut kernel::fmt::Formatter<'_>) -> kernel::fmt::Result {
+        f.debug_struct("StoreError")
+            .field("error", &self.error)
+            .finish()
+    }
+}
+

Maybe an import of kernel::fmt at the top would be cleaner.

Ok, I can do that.

Best regards,
Andreas Hindborg

author maintainer
#13 lore raw

Re: [PATCH v4 03/11] rust: xarray: add `XArrayState`

In reply to Tamir Duberstein
Quoted 6 lines · Tamir Duberstein
Quoted 5 lines · 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.

Quoted 8 lines
Quoted 5 lines

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

The struct and its constructor are marked with #[expect(dead_code)] as there are no users yet. We will remove this annotation in a later patch.

The review of this patch in v3 requested the next patch be absorbed into it.

I must have missed that.

Quoted 19 lines
Quoted 9 lines
rust/kernel/xarray.rs +0 -0
index d54942aeb201..6d0d4905004a 100644
@@ -299,6 +302,67 @@ pub fn store(

[ ... skip 17 lines ... ]

rust/kernel/xarray.rs

Quoted 6 lines
rust/kernel/xarray.rs +6 -0
+impl<'a, T: ForeignOwnable> GuardRef for &mut Guard<'a, T> {
+    type Value = T;
+    fn xa_ptr(&self) -> *mut bindings::xarray {
+        self.xa.xa.get()
+    }
+}

I'm having a hard time understanding the need for this trait, and it is not described in the commit message at all. How is this different than using Deref? &mut T has a blanket Deref<Target = T> impl.

I needed XArrayState to be generic over &Guard<'a, T> and &mut Guard<'a, T> with ability to obtain the raw xarray pointer through the guard, and ability to name T. I did not consider just using Deref, but we can do that. The bounds on the impl block become a bit more complicated, but I guess that is fine. Here is a diff (against head of series):

rust/kernel/xarray.rs +12 -29
index cbb16368c2ca..f5a499c23778 100644
@@ -551,27 +551,6 @@ pub fn insert_entry<'b>(
     }
 }
 
-/// A reference to a [`Guard`], either shared or mutable, that exposes the
-/// underlying xarray pointer and the value type stored in the array.
-pub(crate) trait GuardRef {
-    type Value: ForeignOwnable;
-    fn xa_ptr(&self) -> *mut bindings::xarray;
-}
-
-impl<'a, T: ForeignOwnable> GuardRef for &Guard<'a, T> {
-    type Value = T;
-    fn xa_ptr(&self) -> *mut bindings::xarray {
-        self.xa.xa.get()
-    }
-}
-
-impl<'a, T: ForeignOwnable> GuardRef for &mut Guard<'a, T> {
-    type Value = T;
-    fn xa_ptr(&self) -> *mut bindings::xarray {
-        self.xa.xa.get()
-    }
-}
-
 /// Internal state for XArray iteration and entry operations.
 ///
 /// `R` is the borrow held on the guard: either `&Guard` for read-only callers
@@ -582,12 +561,12 @@ fn xa_ptr(&self) -> *mut bindings::xarray {
 ///
 /// - `state` is always a valid `bindings::xa_state`.
 /// - `state.xa` aliases the xarray reachable through `guard`.
-pub(crate) struct XArrayState<R: GuardRef> {
+pub(crate) struct XArrayState<R> {
     guard: R,
     state: bindings::xa_state,
 }
 
-impl<R: GuardRef> Drop for XArrayState<R> {
+impl<R> Drop for XArrayState<R> {
     fn drop(&mut self) {
         free_xa_alloc(&mut self.state);
     }
@@ -611,9 +590,13 @@ fn free_xa_alloc(state: &mut bindings::xa_state) {
     }
 }
 
-impl<R: GuardRef> XArrayState<R> {
+impl<'a, R, T> XArrayState<R>
+where
+    T: ForeignOwnable + 'a,
+    R: core::ops::Deref<Target = Guard<'a, T>>
+{
     fn new(guard: R, index: usize) -> Self {
-        let xa_ptr = guard.xa_ptr();
+        let xa_ptr = guard.xa.xa.get();
         // INVARIANT: `state` is initialized to a valid `xa_state` whose `xa` field aliases the
         // xarray reachable through `guard`.
         Self {
@@ -656,10 +639,10 @@ fn status(&self) -> Result {
 
     fn insert(
         &mut self,
-        value: R::Value,
+        value: T,
         mut preload: Option<&mut XArraySheaf<'_>>,
-    ) -> Result<*mut c_void, StoreError<R::Value>> {
-        let new = R::Value::into_foreign(value).cast();
+    ) -> Result<*mut c_void, StoreError<T>> {
+        let new = T::into_foreign(value).cast();
 
         loop {
             // SAFETY: `self.state` is a valid `xa_state` by the type invariant. By the same
@@ -686,7 +669,7 @@ fn insert(
         .map_err(|error| {
             // SAFETY: `new` came from `R::Value::into_foreign` and `xas_store` does not take
             // ownership of the value on error.
-            let value = unsafe { R::Value::from_foreign(new) };
+            let value = unsafe { T::from_foreign(new) };
             StoreError { value, error }
         })
     }

---

Best regards,
Andreas Hindborg

author maintainer
#20 lore raw

Re: [PATCH v4 05/11] rust: xarray: simplify `Guard::load`

In reply to Tamir Duberstein
Quoted 8 lines · Tamir Duberstein
Quoted 2 lines · Andreas Hindborg

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

This is simpler, but the closure-based API was here for a reason (to avoid passing around untyped pointers). This patch is estabilishing the style for subsequent patches, but doesn't honestly describe that it is doing so.

I'll be sure to mention this in the commit message for next spin.

Quoted 17 lines
Quoted 9 lines
rust/kernel/xarray.rs +0 -0
index 05e6dc1ffe69..7da57c778669 100644
@@ -212,28 +212,23 @@ fn from(value: StoreError<T>) -> Self {

[ ... skip 26 lines ... ]

rust/kernel/xarray.rs fn from(value: StoreError<T>) -> Self { · line 229

Quoted 6 lines
rust/kernel/xarray.rs +2 -4
-        self.load(index, |ptr| {
-            // SAFETY: `ptr` came from `T::into_foreign`.
-            unsafe { T::borrow_mut(ptr.as_ptr()) }
-        })
+        let ptr = self.load(index)?;
+

Inconsistent whitespace.

Thanks!

Best regards,
Andreas Hindborg

author maintainer
#4 lore raw

Re: [PATCH v4 01/11] rust: xarray: minor formatting fixes

In reply to a message not in the archive
Quoted 36 lines · <[email protected]> writes:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:

Pre-existing issues:
- [High] Guard::store temporarily drops the exclusive lock, violating Guard mutual exclusion semantics. --

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

rust: xarray: minor formatting fixes

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

Quoted 4 lines
rust/kernel/xarray.rs +0 -0
index 46e5f43223fe8..b80fb7a262d0c 100644

[ ... ]

rust/kernel/xarray.rs line 69

Quoted 9 lines
rust/kernel/xarray.rs +4 -1
@@ -44,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)
+/// );

[Severity: High]
This isn't a bug introduced by this patch, but since Guard::store calls __xa_store which explicitly drops the xa_lock to allocate memory if called with blocking flags (like GFP_KERNEL here), doesn't this violate the expected mutual exclusion guarantee of the Guard?

Quoted 6 lines

In Rust, a lock guard is fundamentally expected to provide strict, continuous mutual exclusion for its entire lifetime. Temporarily releasing the lock while a Guard is held breaks this invariant. Any caller relying on the Guard to ensure atomicity (such as check-and-update patterns) will be exposed to silent Time-Of-Check to Time-Of-Use (TOCTOU) race conditions, as other threads can mutate the array while the lock is dropped.

Should we rename Guard to something else to clarify this, or do you think it is enough with added documentation on Guard?

Best regards,
Andreas Hindborg

reviewer
#5 lore raw

Re: [PATCH v4 01/11] rust: xarray: minor formatting fixes

Quoted 45 lines · Andreas Hindborg
Quoted 36 lines · <[email protected]> writes:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:

Pre-existing issues:
- [High] Guard::store temporarily drops the exclusive lock, violating Guard mutual exclusion semantics. --

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

rust: xarray: minor formatting fixes

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

Quoted 4 lines
rust/kernel/xarray.rs +0 -0
index 46e5f43223fe8..b80fb7a262d0c 100644

[ ... ]

rust/kernel/xarray.rs line 69

Quoted 9 lines
rust/kernel/xarray.rs +4 -1
@@ -44,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)
+/// );

[Severity: High]
This isn't a bug introduced by this patch, but since Guard::store calls __xa_store which explicitly drops the xa_lock to allocate memory if called with blocking flags (like GFP_KERNEL here), doesn't this violate the expected mutual exclusion guarantee of the Guard?

Quoted 6 lines

In Rust, a lock guard is fundamentally expected to provide strict, continuous mutual exclusion for its entire lifetime. Temporarily releasing the lock while a Guard is held breaks this invariant. Any caller relying on the Guard to ensure atomicity (such as check-and-update patterns) will be exposed to silent Time-Of-Check to Time-Of-Use (TOCTOU) race conditions, as other threads can mutate the array while the lock is dropped.

Quoted 2 lines

Should we rename Guard to something else to clarify this, or do you think it is enough with added documentation on Guard?

It's fine. MutexGuard::unlocked exist for parking-lot crate, it's not that we're introducing a new concept here.

Documentation is sufficient.

Best,
Gary

Quoted 4 lines

Best regards,
Andreas Hindborg

author maintainer
#29 lore raw

Re: [PATCH v4 07/11] rust: xarray: add entry API

In reply to Tamir Duberstein
Quoted 10 lines · Tamir Duberstein
Quoted 4 lines · 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.

There's a lot more API here than this lets on. find_next_entry{,_circular}, Entry::is_occupied, into_guard, insert{,_entry} (do we need both?), index, OccupiedEntry::swap, Deref{,Mut}.

I can amend the commit message to enumerate the added methods.

Quoted 3 lines

It's not clear that all this API is needed, and this message does not attempt to justify it. It is also inconsistent with the split in patches 3 and 4.

What do you mean when you say that it is not clear that the API is needed? Are you referring to callers of this code? This is initially for the rust null block driver, as expressed in the cover letter.

I'm not sure why you think this is inconsistent with patch 3 and 4?

Quoted 20 lines
Quoted 20 lines
rust/helpers/xarray.c +9 -0
index 08979b304341..19fce6862c78 100644
@@ -26,3 +26,20 @@ __rust_helper void rust_helper_xa_unlock(struct xarray *xa)
 {
 	return xa_unlock(xa);
 }
+
+void *rust_helper_xas_result(struct xa_state *xas, void *curr)
+{
+	if (xa_err(xas->xa_node))
+		curr = xas->xa_node;
+	return curr;
+}
+
+void *rust_helper_xa_zero_to_null(void *entry)
Quoted 8 lines

rust/helpers/xarray.c __rust_helper void rust_helper_xa_unlock(struct xarray *xa) · line 40

Quoted 3 lines
rust/helpers/xarray.c +3 -0
+{
+	return xa_is_zero(entry) ? NULL : entry;
+}

These functions already exist in C, but are static inline in xarray.c. Can we move them to the header instead of duplicating them here please? That is what I did in 79ada2ae ("xarray: extract helper from __xa_{insert,cmpxchg}").

This is a great idea. I will follow up with a cleanup once this stuff is in. Getting changes in the xarray C code has a rather high latency. I would rather not be blocked by that at the moment.

Best regards,
Andreas Hindborg

author maintainer
#24 lore raw

Re: [PATCH v4 06/11] rust: xarray: add `find_next` and `find_next_mut`

In reply to Tamir Duberstein
Quoted 5 lines · Tamir Duberstein
Quoted 4 lines · 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.

Quoted 7 lines
Quoted 2 lines

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.

The previous patch re-hosts existing XArray methods on XArrayState, but this patch and subsequent ones are choosing to grow the XArray API rather than promote XArrayState to a proper abstraction that users should prefer. Are you sure that's the right choice?

We have the Entry API (introduced in patch 7) for users to interact with the XArray in a stateful manner. I think adding these public methods on Guard makes sense.

Best regards,
Andreas Hindborg

#14 lore raw

Re: [PATCH v4 03/11] rust: xarray: add `XArrayState`

In reply to Andreas Hindborg

Hi Andreas,

My main worry here is cursor invalidation, i.e.: what happens if someone mutates the tree while we have live instances of XArrayState handed out via patch 7? For example, what if someone writes "self.state.guard.remove(...)" inside the kernel crate itself while some user code has an OccupiedEntry?

I think this could be solved by hiding XArrayState in its own module and exposing only a small set of checked helpers while its fields remain private so that we carefully vet against the situation above.

Additionally we have to ensure that, in order to get the guard, one must destroy the XArrayState, for the same reason. This is currently the case with into_guard() IIUC, but I think it's worth to spell it out in the invariant section.

— Daniel

reviewer Reviewed-by on v4 5/11
#21 lore raw

Re: [PATCH v4 05/11] rust: xarray: simplify `Guard::load`

In reply to Andreas Hindborg
Quoted 60 lines · Andreas Hindborg

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

---
rust/kernel/xarray.rs | 23 +++++++++--------------

1 file changed, 9 insertions(+), 14 deletions(-)
rust/kernel/xarray.rs +9 -14
index 05e6dc1ffe69..7da57c778669 100644
@@ -212,28 +212,23 @@ 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()?))
+    fn load(&self, index: usize) -> Option<NonNull<c_void>> {
+        XArrayState::new(self, index).load()
    }
 
    /// Provides a reference to the element at the given index.
    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.
    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 · 2 lines
-- 
2.51.2
#25 lore raw

Re: [PATCH v4 06/11] rust: xarray: add `find_next` and `find_next_mut`

In reply to Andreas Hindborg

Hi Andreas,

I wonder if we can't hoist most of these calls accessing self.state.state to the XArrayState directly? For example, I see this in a couple of places:

+ bindings::xas_result(
+ &mut self.state.state,
+ bindings::xa_zero_to_null(bindings::xas_store(
+ &mut self.state.state,
+ core::ptr::null_mut(),
+ )),
+ )

How about XArrayState::replace(new: *mut c_void) -> *mut c_void?

Also:

+ state.state.xa_node = bindings::XAS_RESTART as *mut bindings::xa_node;
+ state.state.xa_index = 0;

Could be e.g.: "restart_at(index)”.

WDYT?

— Daniel

author maintainer
#15 lore raw

Re: [PATCH v4 03/11] rust: xarray: add `XArrayState`

In reply to Daniel Almeida
Quoted 6 lines · Daniel Almeida

Hi Andreas,

My main worry here is cursor invalidation, i.e.: what happens if someone mutates the tree while we have live instances of XArrayState handed out via patch 7? For example, what if someone writes "self.state.guard.remove(...)" inside the kernel crate itself while some user code has an OccupiedEntry?

The type system handles this. Obtaining Entry requires a mutable reference whose lifetime is extended to the Entry. So while entry is alive, it is not possible to construct XArrayState.

For the operations directly on Guard that require shared ownership, multiple XArrayState instances may exist at the same time. But as these are only used for reads and can never modify the tree, invalidation can not occur.

Quoted 4 lines

I think this could be solved by hiding XArrayState in its own module and exposing only a small set of checked helpers while its fields remain private so that we carefully vet against the situation above.

I did not consider safe code within the xarray module modifying the fields of the state object. Do we really need to handle that?

Quoted 4 lines

Additionally we have to ensure that, in order to get the guard, one must destroy the XArrayState, for the same reason. This is currently the case with into_guard() IIUC, but I think it's worth to spell it out in the invariant section.

Since users outside of the module cannot construct Guard safely, I don't think this is an issue?

But, something is not right. I did not consider the safety of XArrayState::new, because it is a private method. But it should be unsafe as it is, because it allows insert operations with only a shared reference to the guard.

I think if I just gate he modifying operations (only XArrayState::insert for now) on R being a mutable reference to the guard, we should be fine?

Best regards,
Andreas Hindborg

author maintainer
#26 lore raw

Re: [PATCH v4 06/11] rust: xarray: add `find_next` and `find_next_mut`

In reply to Daniel Almeida
Quoted 21 lines · Daniel Almeida

Hi Andreas,

I wonder if we can't hoist most of these calls accessing self.state.state to the XArrayState directly? For example, I see this in a couple of places:

(quoted diff) +7 -0
+            bindings::xas_result(
+                &mut self.state.state,
+                bindings::xa_zero_to_null(bindings::xas_store(
+                    &mut self.state.state,
+                    core::ptr::null_mut(),
+                )),
+            )

How about XArrayState::replace(new: *mut c_void) -> *mut c_void?

Also:

(quoted diff) +2 -0
+                state.state.xa_node = bindings::XAS_RESTART as *mut bindings::xa_node;
+                state.state.xa_index = 0;
Quoted 4 lines

Could be e.g.: "restart_at(index)”.

WDYT?

I think that is a good suggestion, I will do that.

Best regards,
Andreas Hindborg

author maintainer
#30 lore raw

Re: [PATCH v4 07/11] rust: xarray: add entry API

In reply to Andreas Hindborg
Quoted 8 lines · Andreas Hindborg
Quoted 6 lines · Tamir Duberstein
Quoted 4 lines · 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.

Quoted 6 lines
Quoted 4 lines

There's a lot more API here than this lets on. find_next_entry{,_circular}, Entry::is_occupied, into_guard, insert{,_entry} (do we need both?), index, OccupiedEntry::swap, Deref{,Mut}.

I can amend the commit message to enumerate the added methods.

Looking over this again, I was pondering on removing insert in favor of insert_entry, but I decided the duplication is OK. From the caller perspective, code will be cleaner to read for simple insert operations with the insert method. But complex query/replace operations can be completed more efficient with the entry API by avoiding multiple tree walks.

Similarly for is_occupied, code at call sites will be easier to read when using this method.

Best regards,
Andreas Hindborg