Skip to contentSkip to conversation

rust: xarray: add entry API with preloading

PATCH Superseded Andreas Hindborg 9 participants 60 messages Feb 9 – Feb 25

Subsystems (6)

v3 of 6 Superseded Latest is v6 →

lore
Share & tools
lore

Andreas Hindborg

author maintainer
#0 lore raw

v3 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-3 add some minor convenience functionality.

- Patch 4 adds an abstraction for the C xa_state structure. This is a prerequisite for all the subsequent patches.

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

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

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

- Patch 8 adds an entry API.

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

- Patch 11 enables sheafs for the xarray kmem_cache.

- Patch 12 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 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 (12):
rust: xarray: minor formatting fixes
rust: xarray: add debug format for StoreError
rust: xarray: add contains_index method
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 |   4 +
 rust/helpers/xarray.c           |  17 +
 rust/kernel/mm.rs               |   1 +
 rust/kernel/mm/sheaf.rs         | 690 ++++++++++++++++++++++++++++++++++++++++
 rust/kernel/xarray.rs           | 477 +++++++++++++++++++++++++--
 rust/kernel/xarray/entry.rs     | 378 ++++++++++++++++++++++
 10 files changed, 1556 insertions(+), 38 deletions(-)

---
base-commit: 18f7fcd5e69a04df57b563360b88be72471d6b62
change-id: 20251203-xarray-entry-send-00230f0744e6

Best regards,

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

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

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

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

---
 rust/kernel/xarray.rs | 36 +++++++++++++++++++++++++++++-------
 1 file changed, 29 insertions(+), 7 deletions(-)
rust/kernel/xarray.rs +29 -7
index a49d6db288458..88625c9abf4ef 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
Reviewed-by on v3 1/12
#2 lore raw

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

Quoted 10 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.
- Break long assert_eq! statement in documentation across multiple lines for better readability.

Quoted 4 lines
Acked-by on v3 1/12
#3 lore raw

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

In reply to Andreas Hindborg
Quoted 10 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.
- Break long assert_eq! statement in documentation across multiple lines for better readability.

Quoted 3 lines
Quoted 66 lines
---
 rust/kernel/xarray.rs | 36 +++++++++++++++++++++++++++++-------
 1 file changed, 29 insertions(+), 7 deletions(-)
rust/kernel/xarray.rs +29 -7
index a49d6db288458..88625c9abf4ef 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 · 2 lines
-- 
2.51.2
Reviewed-by on v3 1/12
#4 lore raw

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

In reply to Andreas Hindborg
Quoted 78 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.
- 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 a49d6db288458..88625c9abf4ef 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 · 2 lines
-- 
2.51.2

LGTM

Quoted 1 line
author maintainer
#5 lore raw

PATCH v3 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 | 8 ++++++++
 1 file changed, 8 insertions(+)
rust/kernel/xarray.rs +8 -0
index 88625c9abf4ef..d9762c6bef19c 100644
@@ -193,6 +193,14 @@ pub struct StoreError<T> {
     pub value: T,
 }
 
+impl<T> core::fmt::Debug for StoreError<T> {
+    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
+        f.debug_struct("StoreError")
+            .field("error", &self.error)
+            .finish()
+    }
+}
+
 impl<T> From<StoreError<T>> for Error {
     fn from(value: StoreError<T>) -> Self {
         value.error
Signature · 1 line
2.51.2
Reviewed-by on v3 2/12
#6 lore raw

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

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

---
 rust/kernel/xarray.rs | 8 ++++++++
 1 file changed, 8 insertions(+)
rust/kernel/xarray.rs +0 -0
index 88625c9abf4ef..d9762c6bef19c 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> core::fmt::Debug for StoreError<T> {
+    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
+        f.debug_struct("StoreError")
+            .field("error", &self.error)
+            .finish()
+    }
+}
+

Is there any best practice for when to include use core::fmt::*, so you can avoid being verbose here?

I see other cases like this, but I couldn't find anything in the code guidelines.

#7 lore raw

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

Quoted 33 lines · Daniel Gomez
Quoted 17 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.

---
 rust/kernel/xarray.rs | 8 ++++++++
 1 file changed, 8 insertions(+)
rust/kernel/xarray.rs +0 -0
index 88625c9abf4ef..d9762c6bef19c 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> core::fmt::Debug for StoreError<T> {
+    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
+        f.debug_struct("StoreError")
+            .field("error", &self.error)
+            .finish()
+    }
+}
+

Is there any best practice for when to include use core::fmt::*, so you can avoid being verbose here?

Quoted 2 lines

I see other cases like this, but I couldn't find anything in the code guidelines.

It would probably be better to use kernel::fmt::* rather than core::fmt so that we can interpose our own trait in the future, if we want.

author maintainer
#8 lore raw

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

Quoted 34 lines · Tamir Duberstein
Quoted 33 lines · Daniel Gomez
Quoted 17 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.

---
 rust/kernel/xarray.rs | 8 ++++++++
 1 file changed, 8 insertions(+)
rust/kernel/xarray.rs +0 -0
index 88625c9abf4ef..d9762c6bef19c 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> core::fmt::Debug for StoreError<T> {
+    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
+        f.debug_struct("StoreError")
+            .field("error", &self.error)
+            .finish()
+    }
+}
+

Is there any best practice for when to include use core::fmt::*, so you can avoid being verbose here?

Quoted 2 lines
Quoted 2 lines

I see other cases like this, but I couldn't find anything in the code guidelines.

I don't think there is a best practice here. I feel that if we only invoke a path a few times, we might as well write it out at the use site rather than clobber the name space of the compilation unit.

Quoted 4 lines

It would probably be better to use kernel::fmt::* rather than core::fmt so that we can interpose our own trait in the future, if we want.

I'll change to kernel::fmt::*.

Best regards,
Andreas Hindborg

Acked-by on v3 2/12
#9 lore raw

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

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

Quoted 29 lines
---
 rust/kernel/xarray.rs | 8 ++++++++
 1 file changed, 8 insertions(+)
rust/kernel/xarray.rs +8 -0
index 88625c9abf4ef..d9762c6bef19c 100644
@@ -193,6 +193,14 @@ pub struct StoreError<T> {
     pub value: T,
 }
 
+impl<T> core::fmt::Debug for StoreError<T> {
+    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
+        f.debug_struct("StoreError")
+            .field("error", &self.error)
+            .finish()
+    }
+}
+
 impl<T> From<StoreError<T>> for Error {
     fn from(value: StoreError<T>) -> Self {
         value.error
Signature · 2 lines
-- 
2.51.2
author maintainer
#10 lore raw

PATCH v3 3/12 rust: xarray: add `contains_index` method

In reply to Andreas Hindborg

Add a convenience method contains_index to check whether an element exists at a given index in the XArray. This method provides a more ergonomic API compared to calling get and checking for Some.

---
 rust/kernel/xarray.rs | 21 +++++++++++++++++++++
 1 file changed, 21 insertions(+)
rust/kernel/xarray.rs +21 -0
index d9762c6bef19c..ede48b5e1dba3 100644
@@ -218,6 +218,27 @@ fn load<F, U>(&self, index: usize, f: F) -> Option<U>
         Some(f(ptr))
     }
 
+    /// Checks if the XArray contains an element at the specified index.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use kernel::{alloc::{flags::GFP_KERNEL, kbox::KBox}, xarray::{AllocKind, XArray}};
+    /// let xa = KBox::pin_init(XArray::new(AllocKind::Alloc), GFP_KERNEL)?;
+    ///
+    /// let mut guard = xa.lock();
+    /// assert_eq!(guard.contains_index(42), false);
+    ///
+    /// guard.store(42, KBox::new(0u32, GFP_KERNEL)?, GFP_KERNEL)?;
+    ///
+    /// assert_eq!(guard.contains_index(42), true);
+    ///
+    /// # Ok::<(), kernel::error::Error>(())
+    /// ```
+    pub fn contains_index(&self, index: usize) -> bool {
+        self.get(index).is_some()
+    }
+
     /// Provides a reference to the element at the given index.
     pub fn get(&self, index: usize) -> Option<T::Borrowed<'_>> {
         self.load(index, |ptr| {
Signature · 1 line
2.51.2
Reviewed-by on v3 3/12
#11 lore raw

Re: [PATCH v3 03/12] rust: xarray: add `contains_index` method

Quoted 14 lines · Andreas Hindborg

Add a convenience method contains_index to check whether an element exists at a given index in the XArray. This method provides a more ergonomic API compared to calling get and checking for Some.

---
 rust/kernel/xarray.rs | 21 +++++++++++++++++++++
 1 file changed, 21 insertions(+)
rust/kernel/xarray.rs +0 -0
index d9762c6bef19c..ede48b5e1dba3 100644

rust/kernel/xarray.rs fn load<F, U>(&self, index: usize, f: F) -> Option<U> · line 227

Quoted 10 lines
rust/kernel/xarray.rs +7 -0
@@ -218,6 +218,27 @@ fn load<F, U>(&self, index: usize, f: F) -> Option<U>
         Some(f(ptr))
     }
 
+    /// Checks if the XArray contains an element at the specified index.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use kernel::{alloc::{flags::GFP_KERNEL, kbox::KBox}, xarray::{AllocKind, XArray}};
+    /// let xa = KBox::pin_init(XArray::new(AllocKind::Alloc), GFP_KERNEL)?;

Side comment: I'd also update the examples to the new coding style. And it'd probably be cleaner in the first commit.

rust/kernel/xarray.rs fn load<F, U>(&self, index: usize, f: F) -> Option<U> · line 238

Quoted 11 lines
rust/kernel/xarray.rs +11 -0
+    ///
+    /// let mut guard = xa.lock();
+    /// assert_eq!(guard.contains_index(42), false);
+    ///
+    /// guard.store(42, KBox::new(0u32, GFP_KERNEL)?, GFP_KERNEL)?;
+    ///
+    /// assert_eq!(guard.contains_index(42), true);
+    ///
+    /// # Ok::<(), kernel::error::Error>(())
+    /// ```
+    pub fn contains_index(&self, index: usize) -> bool {

Nit. The method name may imply there's a contains_*() variant. I'd rename it to contains() so we are consistent with the rest of the API.

author maintainer
#12 lore raw

Re: [PATCH v3 03/12] rust: xarray: add `contains_index` method

Quoted 18 lines · Daniel Gomez
Quoted 17 lines · Andreas Hindborg

Add a convenience method contains_index to check whether an element exists at a given index in the XArray. This method provides a more ergonomic API compared to calling get and checking for Some.

---
 rust/kernel/xarray.rs | 21 +++++++++++++++++++++
 1 file changed, 21 insertions(+)
rust/kernel/xarray.rs +0 -0
index d9762c6bef19c..ede48b5e1dba3 100644
@@ -218,6 +218,27 @@ fn load<F, U>(&self, index: usize, f: F) -> Option<U>
         Some(f(ptr))
     }
 
Quoted 10 lines

rust/kernel/xarray.rs fn load<F, U>(&self, index: usize, f: F) -> Option<U> · line 227

Quoted 7 lines
rust/kernel/xarray.rs +7 -0
+    /// Checks if the XArray contains an element at the specified index.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use kernel::{alloc::{flags::GFP_KERNEL, kbox::KBox}, xarray::{AllocKind, XArray}};
+    /// let xa = KBox::pin_init(XArray::new(AllocKind::Alloc), GFP_KERNEL)?;

Side comment: I'd also update the examples to the new coding style. And it'd probably be cleaner in the first commit.

I'll switch to the vertical import style.

Quoted 13 lines

rust/kernel/xarray.rs fn load<F, U>(&self, index: usize, f: F) -> Option<U> · line 238

Quoted 12 lines
rust/kernel/xarray.rs +11 -0
+    ///
+    /// let mut guard = xa.lock();
+    /// assert_eq!(guard.contains_index(42), false);
+    ///
+    /// guard.store(42, KBox::new(0u32, GFP_KERNEL)?, GFP_KERNEL)?;
+    ///
+    /// assert_eq!(guard.contains_index(42), true);
+    ///
+    /// # Ok::<(), kernel::error::Error>(())
+    /// ```
+    pub fn contains_index(&self, index: usize) -> bool {
Quoted 2 lines

Nit. The method name may imply there's a contains_*() variant. I'd rename it to contains() so we are consistent with the rest of the API.

I disagree with this one. contains might cheat the reader as it is not obvious whether we are querying for a key or value.

Quoted 2 lines

Thanks!

Best regards,
Andreas Hindborg

#13 lore raw

Re: [PATCH v3 03/12] rust: xarray: add `contains_index` method

In reply to Andreas Hindborg
Quoted 6 lines · Andreas Hindborg

Add a convenience method contains_index to check whether an element exists at a given index in the XArray. This method provides a more ergonomic API compared to calling get and checking for Some.

As I said in v1 I'm -1 on this change. As gregkh would say: it's hard to review a new API without seeing its user.

author maintainer
#14 lore raw

Re: [PATCH v3 03/12] rust: xarray: add `contains_index` method

Quoted 10 lines · Tamir Duberstein
Quoted 6 lines · Andreas Hindborg

Add a convenience method contains_index to check whether an element exists at a given index in the XArray. This method provides a more ergonomic API compared to calling get and checking for Some.

As I said in v1 I'm -1 on this change. As gregkh would say: it's hard to review a new API without seeing its user.

I already gave you the user inline [1] and if you wish you can also see it in a downstream tree [2]. Gary already explained why this is required with the current implementation of the borrow checker [3].

Best regards,
Andreas Hindborg

[1] https://lore.kernel.org/r/[email protected]
[2] https://github.com/metaspace/linux/blob/aa43a6ecb68a785a90e167609aa57c5a0860d123/drivers/block/rnull/disk_storage.rs#L218
[3] https://lore.kernel.org/r/[email protected]

#15 lore raw

Re: [PATCH v3 03/12] rust: xarray: add `contains_index` method

Quoted 9 lines · Andreas Hindborg
Quoted 6 lines · Tamir Duberstein
Quoted 5 lines · Andreas Hindborg

Add a convenience method contains_index to check whether an element exists at a given index in the XArray. This method provides a more ergonomic API compared to calling get and checking for Some.

Quoted 8 lines
Quoted 4 lines
Quoted 1 line

As I said in v1 I'm -1 on this change. As gregkh would say: it's hard to review a new API without seeing its user.

I already gave you the user inline [1] and if you wish you can also see it in a downstream tree [2]. Gary already explained why this is required with the current implementation of the borrow checker [3].

Yeah, that's fine, and the poor ergonomics are IMO a feature - I should see the ugly is_some() call in your code, because it's a useful signal that something non-obvious is going. This function hides that, which I think is not better.

Quoted 8 lines

Best regards,
Andreas Hindborg

[1] https://lore.kernel.org/r/[email protected]
[2] https://github.com/metaspace/linux/blob/aa43a6ecb68a785a90e167609aa57c5a0860d123/drivers/block/rnull/disk_storage.rs#L218
[3] https://lore.kernel.org/r/[email protected]

#16 lore raw

Re: [PATCH v3 03/12] rust: xarray: add `contains_index` method

In reply to Andreas Hindborg
Quoted 3 lines · Andreas Hindborg

Add a convenience method contains_index to check whether an element exists at a given index in the XArray. This method provides a more ergonomic API compared to calling get and checking for Some.

I think this is going to result in less efficient code for most uses.

Most users use the results returned, not just checking if there is or is not a value. So if you find the value an xarray state and then just throw it away and find it again, it'll be less efficient.

If there are users that do use the xarray to just check if something exists or not (which there probably are?), then it should be in a wrapper for that code and not the generic API. Otherwise we will have users pop up to use this method when they should not.

Quoted 43 lines
---
 rust/kernel/xarray.rs | 21 +++++++++++++++++++++
 1 file changed, 21 insertions(+)
rust/kernel/xarray.rs +21 -0
index d9762c6bef19c..ede48b5e1dba3 100644
@@ -218,6 +218,27 @@ fn load<F, U>(&self, index: usize, f: F) -> Option<U>
         Some(f(ptr))
     }
 
+    /// Checks if the XArray contains an element at the specified index.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use kernel::{alloc::{flags::GFP_KERNEL, kbox::KBox}, xarray::{AllocKind, XArray}};
+    /// let xa = KBox::pin_init(XArray::new(AllocKind::Alloc), GFP_KERNEL)?;
+    ///
+    /// let mut guard = xa.lock();
+    /// assert_eq!(guard.contains_index(42), false);
+    ///
+    /// guard.store(42, KBox::new(0u32, GFP_KERNEL)?, GFP_KERNEL)?;
+    ///
+    /// assert_eq!(guard.contains_index(42), true);
+    ///
+    /// # Ok::<(), kernel::error::Error>(())
+    /// ```
+    pub fn contains_index(&self, index: usize) -> bool {
+        self.get(index).is_some()
+    }
+
     /// Provides a reference to the element at the given index.
     pub fn get(&self, index: usize) -> Option<T::Borrowed<'_>> {
         self.load(index, |ptr| {
Signature · 2 lines
-- 
2.51.2
author maintainer
#17 lore raw

Re: [PATCH v3 03/12] rust: xarray: add `contains_index` method

Quoted 7 lines · Liam R. Howlett
Quoted 3 lines · Andreas Hindborg

Add a convenience method contains_index to check whether an element exists at a given index in the XArray. This method provides a more ergonomic API compared to calling get and checking for Some.

I think this is going to result in less efficient code for most uses.

Quoted 8 lines

Most users use the results returned, not just checking if there is or is not a value. So if you find the value an xarray state and then just throw it away and find it again, it'll be less efficient.

If there are users that do use the xarray to just check if something exists or not (which there probably are?), then it should be in a wrapper for that code and not the generic API. Otherwise we will have users pop up to use this method when they should not.

I agree in that I would prefer matching on the result of a lookup and using that result. This is not always possible due to a limitation in the current implementation of the borrow checker. Please see my response to Tamir [1], it has all the pointers.

Since we cannot use a match statement in certain situations, we have to fall back to something that does not borrow from the collections, like array.get(index).is_some(). I would argue that

if array.contains_index(foo) { ... }

is easier to read than

if array.get(foo).is_some() { ... }

And I don't think array.contains() is going to have worse codegen than array.get(index).is_some().

Best regards,
Andreas Hindborg

[1] https://lore.kernel.org/rust-for-linux/[email protected]/T/#m95fb90870c511491f4f487dbf852c689cd0733f4

#18 lore raw

Re: [PATCH v3 03/12] rust: xarray: add `contains_index` method

Quoted 27 lines · Andreas Hindborg
Quoted 7 lines · Liam R. Howlett
Quoted 3 lines · Andreas Hindborg

Add a convenience method contains_index to check whether an element exists at a given index in the XArray. This method provides a more ergonomic API compared to calling get and checking for Some.

I think this is going to result in less efficient code for most uses.

Quoted 8 lines

Most users use the results returned, not just checking if there is or is not a value. So if you find the value an xarray state and then just throw it away and find it again, it'll be less efficient.

If there are users that do use the xarray to just check if something exists or not (which there probably are?), then it should be in a wrapper for that code and not the generic API. Otherwise we will have users pop up to use this method when they should not.

I agree in that I would prefer matching on the result of a lookup and using that result. This is not always possible due to a limitation in the current implementation of the borrow checker. Please see my response to Tamir [1], it has all the pointers.

Since we cannot use a match statement in certain situations, we have to fall back to something that does not borrow from the collections, like array.get(index).is_some(). I would argue that

Quoted 8 lines

if array.contains_index(foo) { ... }

is easier to read than

if array.get(foo).is_some() { ... }

And I don't think array.contains() is going to have worse codegen than array.get(index).is_some().

This is probably my lack of rust knowledge...

My concern is around API usage. I am concerned people will use xas as a throw-away lookup with this API and cause more walks of the xarray to the same location.

In the normal API, we have lookups like this; you take a lock, look something up, drop the lock and return it. Since the life cycle of the stored information is outside the scope of the xarray, the user is dependent on the entry being stable by some other means after the xarray lock is dropped.

In the advanced API, we do more within the locked area, usually.

Usually, applications don't just print out there is a value, they do something with it. So I would expect a real example to be something like (this horrible psudo-c/rust mangled mess):

let entry = array.get_mut(foo);

if (entry.is_some()) {
        /* do something with entry */
        send_to_party(entry);
} else {
        /* deal with it not existing */
}

What I don't want to do:

if (array.contains_index(foo)) {
        entry = array.get_mut(foo);
} else {
        ...
}

Where contains_index(foo) sets up an xas, walks to the location, returns the entry (or not) and then translates into a boolean.. then if it's true we set up another xas to walk to the same location.

That is, the worst code gen would come from this:
if (array.get(foo).is_some()) { array.get_mut(foo).. }

From what you said here and the link, you are saying we need to do this in certain situations due to rust's borrow checker and the lifetime, but I cannot see why we would need to walk the xarray twice from the example provided.

And making it easier to do this could result in a lot more users doubling xarray walks without realising that it's a bad idea (unless it's this special case).

...

Quoted 3 lines

[1] https://lore.kernel.org/rust-for-linux/[email protected]/T/#m95fb90870c511491f4f487dbf852c689cd0733f4

I have trouble following 'the taken arm' in your link. I think you mean one of the branches based on the existence of the entry, but I don't know which is the 'taken' and how 'self' is out of scope.

Other links off the above link seem to indicate it is a problem with the rust borrow checking hitting a false positive.

It seems we need to look up things twice to work around the false positive - or implement something like get_or_insert()?

Or, wait for the new checker to be released - but that doesn't fix all the false positives, just this one?

So, do all users of the xarray suffer from this false positive?

Thanks,
Liam

author maintainer
#19 lore raw

Re: [PATCH v3 03/12] rust: xarray: add `contains_index` method

Quoted 44 lines · Liam R. Howlett
Quoted 27 lines · Andreas Hindborg
Quoted 7 lines · Liam R. Howlett
Quoted 3 lines · Andreas Hindborg

Add a convenience method contains_index to check whether an element exists at a given index in the XArray. This method provides a more ergonomic API compared to calling get and checking for Some.

I think this is going to result in less efficient code for most uses.

Quoted 8 lines

Most users use the results returned, not just checking if there is or is not a value. So if you find the value an xarray state and then just throw it away and find it again, it'll be less efficient.

If there are users that do use the xarray to just check if something exists or not (which there probably are?), then it should be in a wrapper for that code and not the generic API. Otherwise we will have users pop up to use this method when they should not.

I agree in that I would prefer matching on the result of a lookup and using that result. This is not always possible due to a limitation in the current implementation of the borrow checker. Please see my response to Tamir [1], it has all the pointers.

Since we cannot use a match statement in certain situations, we have to fall back to something that does not borrow from the collections, like array.get(index).is_some(). I would argue that

Quoted 8 lines

if array.contains_index(foo) { ... }

is easier to read than

if array.get(foo).is_some() { ... }

And I don't think array.contains() is going to have worse codegen than array.get(index).is_some().

This is probably my lack of rust knowledge...

My concern is around API usage. I am concerned people will use xas as a throw-away lookup with this API and cause more walks of the xarray to the same location.

Quoted 5 lines

In the normal API, we have lookups like this; you take a lock, look something up, drop the lock and return it. Since the life cycle of the stored information is outside the scope of the xarray, the user is dependent on the entry being stable by some other means after the xarray lock is dropped.

As discussed elsewhere, the current Rust XArray API only has fully exclusive access, no reader/writer separation.

After a lookup the returned object is bound to the lifetime of lock. So you cannot drop the lock while holding a mutable reference to something in the collection, and the "other means" part of your paragraph is automatically handled in Rust.

Quoted 23 lines

In the advanced API, we do more within the locked area, usually.

Usually, applications don't just print out there is a value, they do something with it. So I would expect a real example to be something like (this horrible psudo-c/rust mangled mess):

let entry = array.get_mut(foo);

if (entry.is_some()) {
        /* do something with entry */
        send_to_party(entry);
} else {
        /* deal with it not existing */
}

What I don't want to do:

if (array.contains_index(foo)) {
        entry = array.get_mut(foo);
} else {
        ...
}
Quoted 6 lines

Where contains_index(foo) sets up an xas, walks to the location, returns the entry (or not) and then translates into a boolean.. then if it's true we set up another xas to walk to the same location.

That is, the worst code gen would come from this:
if (array.get(foo).is_some()) { array.get_mut(foo).. }

You are completely right, this causes two walks to the same location, which is not great.

Quoted 4 lines

From what you said here and the link, you are saying we need to do this in certain situations due to rust's borrow checker and the lifetime, but I cannot see why we would need to walk the xarray twice from the example provided.

Let me try to explain with an example using user space Rust. Consider a situation where we have two two key-value mapping data structures. Since we are in user space, I'll go with BTreeMap from the standard library, but it could be XArray in the kernel.

If we want to implement a transaction across these two KV maps, we probably need to take a lock to get mutable access to them. Let's represent this with a struct Maps that has two fields a and b for these two mutable references:

  use std::collections::{
      BTreeMap,
      btree_map::{Entry, OccupiedEntry},
  };

  type MapType = BTreeMap<u32, u32>;

struct Maps<'a> {
a: &'a mut MapType,
b: &'a mut MapType,
}

Now we have two locked data structures and we can implement our transaction over them. Let's say the algorithm is the following:

- Given a key, if that key exists in map A, return a mutable reference to the value for that key in map A.
- Else, move the key and value for the lowest ordered key from map A to map B and return a mutable reference the that value in map B.

My first attempt at implementing this algorithm would be something like this:

  fn transaction_impl1<'a>(maps: &'a mut Maps, key: u32) -> &'a mut u32 {
      if let Entry::Occupied(o) = maps.a.entry(key) {
          o.into_mut()
      } else {
          let value = maps.a.first_entry().expect("Not empty").remove();
          maps.b.entry(key).or_insert(value)
      }
  }

However, this does not compile.

error[E0499]: cannot borrow *maps.a as mutable more than once at a time

    --> src/main.rs:51:21
     |
  47 |   fn transaction_impl1<'a>(maps: &'a mut Maps, key: u32) -> &'a mut u32 {
     |                        -- lifetime `'a` defined here
  48 |       if let Entry::Occupied(o) = maps.a.entry(key) {
     |       -                           ------ first mutable borrow occurs here
     |  _____|
     | |
  49 | |         o.into_mut()
  50 | |     } else {
  51 | |         let value = maps.a.first_entry().expect("Not empty").remove();
     | |                     ^^^^^^ second mutable borrow occurs here
  52 | |         maps.b.entry(key).or_insert(value)
  53 | |     }
     | |_____- returning this value requires that `*maps.a` is borrowed for `'a`

The into_mut() on line 49 captures the lifetime of o, and because the value is returned from the function, it must live for 'a, which is till the end of the function.

As far as I understand, this is a borrow checker limitation. It is easy for us to look at this code and decide that the borrow on line 51 will never alias with the borrow on line 49.

If we change the code so that we do not capture the lifetime of the returned object across the if/else, the code will compile:

  fn transaction_impl2<'a>(maps: &'a mut Maps, key: u32) -> &'a mut u32 {
      if maps.a.contains_key(&key) {
          maps.a.get_mut(&key).expect("Key is present")
      } else {
          let value = maps.a.first_entry().expect("Not empty").remove();
          maps.b.entry(key).or_insert(value)
      }
  }

But now we do two walks in maps.a in the taken path, which is not efficient.

Quoted 17 lines

And making it easier to do this could result in a lot more users doubling xarray walks without realising that it's a bad idea (unless it's this special case).

...

Quoted 3 lines

[1] https://lore.kernel.org/rust-for-linux/[email protected]/T/#m95fb90870c511491f4f487dbf852c689cd0733f4

I have trouble following 'the taken arm' in your link. I think you mean one of the branches based on the existence of the entry, but I don't know which is the 'taken' and how 'self' is out of scope.

Other links off the above link seem to indicate it is a problem with the rust borrow checking hitting a false positive.

Quoted 7 lines

It seems we need to look up things twice to work around the false positive - or implement something like get_or_insert()?

Or, wait for the new checker to be released - but that doesn't fix all the false positives, just this one?

So, do all users of the xarray suffer from this false positive?

Not all users will suffer from this. The following code compiles fine:

  fn transaction_impl3<'a>(maps: &'a mut Maps, key: u32, value: u32) -> &'a mut u32 {
      if let Entry::Occupied(o) = maps.a.entry(key) {
          o.into_mut()
      } else {
          maps.b.entry(key).or_insert(value)
      }
  }

This is valid because the lifetime captured by o.into_mut() is not used on the other match arm.

I hope this helps clarify the situation.

Best regards,
Andreas Hindborg

author maintainer
#20 lore raw

Re: [PATCH v3 03/12] rust: xarray: add `contains_index` method

Quoted 3 lines · Andreas Hindborg

As far as I understand, this is a borrow checker limitation. It is easy for us to look at this code and decide that the borrow on line 51 will never alias with the borrow on line 49.

I did a bit of googling, and this seems to be a well known issue with the current implementation of lifetime analysis in the rust compiler. Apparently this kind of code used to be OK [1] but the Rust devs decided to remove the code that allowed this, because it was causing excessive compilation times [2]. The upside is that this is solved by the new lifetime analysis implementation called "Polonius" and it is the intention to replace the existing implementation with Polonius at some point [3].

Best regards,
Andreas Hindborg

[1] https://github.com/rust-lang/rust/issues/51545
[2] https://smallcultfollowing.com/babysteps/blog/2018/06/15/mir-based-borrow-check-nll-status-update/
[3] https://rust-lang.github.io/polonius/current_status.html

maintainer
#21 lore raw

Re: [PATCH v3 03/12] rust: xarray: add `contains_index` method

Quoted 7 lines · Andreas Hindborg
Quoted 3 lines · Andreas Hindborg

As far as I understand, this is a borrow checker limitation. It is easy for us to look at this code and decide that the borrow on line 51 will never alias with the borrow on line 49.

Quoted 8 lines

I did a bit of googling, and this seems to be a well known issue with the current implementation of lifetime analysis in the rust compiler. Apparently this kind of code used to be OK [1] but the Rust devs decided to remove the code that allowed this, because it was causing excessive compilation times [2]. The upside is that this is solved by the new lifetime analysis implementation called "Polonius" and it is the intention to replace the existing implementation with Polonius at some point [3].

I believe the standard fix for this issue is to provide an entry api similar to HashMap::entry(). See the rbtree for an example, as it already provides such API.

Alice

author maintainer
#22 lore raw

Re: [PATCH v3 03/12] rust: xarray: add `contains_index` method

Quoted 17 lines · Alice Ryhl
Quoted 7 lines · Andreas Hindborg
Quoted 3 lines · Andreas Hindborg

As far as I understand, this is a borrow checker limitation. It is easy for us to look at this code and decide that the borrow on line 51 will never alias with the borrow on line 49.

Quoted 8 lines

I did a bit of googling, and this seems to be a well known issue with the current implementation of lifetime analysis in the rust compiler. Apparently this kind of code used to be OK [1] but the Rust devs decided to remove the code that allowed this, because it was causing excessive compilation times [2]. The upside is that this is solved by the new lifetime analysis implementation called "Polonius" and it is the intention to replace the existing implementation with Polonius at some point [3].

Quoted 3 lines

I believe the standard fix for this issue is to provide an entry api similar to HashMap::entry(). See the rbtree for an example, as it already provides such API.

The example above [1] is using the BTreeMap entry API to produce the issue. Are the BTreeMap and HashMap entry APIs significantly different, or is there something else I missed?

Best regards,
Andreas Hindborg

[1] https://lore.kernel.org/r/[email protected]

#23 lore raw

Re: [PATCH v3 03/12] rust: xarray: add `contains_index` method

Quoted 19 lines · Andreas Hindborg
Quoted 17 lines · Alice Ryhl
Quoted 15 lines · Andreas Hindborg
Quoted 3 lines · Andreas Hindborg

As far as I understand, this is a borrow checker limitation. It is easy for us to look at this code and decide that the borrow on line 51 will never alias with the borrow on line 49.

I did a bit of googling, and this seems to be a well known issue with the current implementation of lifetime analysis in the rust compiler. Apparently this kind of code used to be OK [1] but the Rust devs decided to remove the code that allowed this, because it was causing excessive compilation times [2]. The upside is that this is solved by the new lifetime analysis implementation called "Polonius" and it is the intention to replace the existing implementation with Polonius at some point [3].

Quoted 3 lines
Quoted 3 lines

I believe the standard fix for this issue is to provide an entry api similar to HashMap::entry(). See the rbtree for an example, as it already provides such API.

Alice, can you provide a link to the rbtree code please?

Quoted 4 lines

The example above [1] is using the BTreeMap entry API to produce the issue. Are the BTreeMap and HashMap entry APIs significantly different, or is there something else I missed?

From what I can find, the HashMap is different specifically for this reason.

This is where my question about get_or_insert() came from, the HashSet has this workaround, maybe?

AFAICT, the hash workaround is done in the Entry code that takes a different reference(?) based on the variant (enum?) returned [1].

Or maybe it's about the way branches are evaluated by the checker? Are these different

But I'm really fumbling around this while I learn what you are all doing! Thanks for all the education on this stuff, it's helping me understand where we are headed. Hopefully I help along the way this time.

Thanks,
Liam

[1]. https://doc.rust-lang.org/std/collections/hash_map/enum.Entry.html

maintainer
#24 lore raw

Re: [PATCH v3 03/12] rust: xarray: add `contains_index` method

Quoted 20 lines · Liam R. Howlett
Quoted 19 lines · Andreas Hindborg
Quoted 17 lines · Alice Ryhl
Quoted 15 lines · Andreas Hindborg
Quoted 3 lines · Andreas Hindborg

As far as I understand, this is a borrow checker limitation. It is easy for us to look at this code and decide that the borrow on line 51 will never alias with the borrow on line 49.

I did a bit of googling, and this seems to be a well known issue with the current implementation of lifetime analysis in the rust compiler. Apparently this kind of code used to be OK [1] but the Rust devs decided to remove the code that allowed this, because it was causing excessive compilation times [2]. The upside is that this is solved by the new lifetime analysis implementation called "Polonius" and it is the intention to replace the existing implementation with Polonius at some point [3].

Quoted 5 lines
Quoted 3 lines
Quoted 3 lines

I believe the standard fix for this issue is to provide an entry api similar to HashMap::entry(). See the rbtree for an example, as it already provides such API.

Alice, can you provide a link to the rbtree code please?

Please see rust/kernel/rbtree.rs in the kernel tree.

Alice

maintainer
#25 lore raw

Re: [PATCH v3 03/12] rust: xarray: add `contains_index` method

In reply to Andreas Hindborg
Quoted 23 lines · Andreas Hindborg
Quoted 17 lines · Alice Ryhl
Quoted 7 lines · Andreas Hindborg
Quoted 3 lines · Andreas Hindborg

As far as I understand, this is a borrow checker limitation. It is easy for us to look at this code and decide that the borrow on line 51 will never alias with the borrow on line 49.

Quoted 8 lines

I did a bit of googling, and this seems to be a well known issue with the current implementation of lifetime analysis in the rust compiler. Apparently this kind of code used to be OK [1] but the Rust devs decided to remove the code that allowed this, because it was causing excessive compilation times [2]. The upside is that this is solved by the new lifetime analysis implementation called "Polonius" and it is the intention to replace the existing implementation with Polonius at some point [3].

Quoted 3 lines

I believe the standard fix for this issue is to provide an entry api similar to HashMap::entry(). See the rbtree for an example, as it already provides such API.

Quoted 8 lines

The example above [1] is using the BTreeMap entry API to produce the issue. Are the BTreeMap and HashMap entry APIs significantly different, or is there something else I missed?

Best regards,
Andreas Hindborg

[1] https://lore.kernel.org/r/[email protected]

Hrm, tricky. I think it would work if the entry type had an into_map() that consumes the entry and returns a &mut to the original map.

  fn transaction_impl1<'a>(maps: &'a mut Maps, key: u32) -> &'a mut u32 {
      match maps.a.entry(key) {
          Entry::Occupied(o) => o.into_mut()
          Entry::Vacant(v) => {
              let map_a = v.into_map();
              let value = map_a.first_entry().expect("Not empty").remove();
              maps.b.entry(key).or_insert(value)
          }
      }
  }

The HashMap and BTreeMap apis are not particularly different.

Alice

author maintainer
#26 lore raw

Re: [PATCH v3 03/12] rust: xarray: add `contains_index` method

Quoted 36 lines · Alice Ryhl
Quoted 23 lines · Andreas Hindborg
Quoted 17 lines · Alice Ryhl
Quoted 7 lines · Andreas Hindborg
Quoted 3 lines · Andreas Hindborg

As far as I understand, this is a borrow checker limitation. It is easy for us to look at this code and decide that the borrow on line 51 will never alias with the borrow on line 49.

Quoted 8 lines

I did a bit of googling, and this seems to be a well known issue with the current implementation of lifetime analysis in the rust compiler. Apparently this kind of code used to be OK [1] but the Rust devs decided to remove the code that allowed this, because it was causing excessive compilation times [2]. The upside is that this is solved by the new lifetime analysis implementation called "Polonius" and it is the intention to replace the existing implementation with Polonius at some point [3].

Quoted 3 lines

I believe the standard fix for this issue is to provide an entry api similar to HashMap::entry(). See the rbtree for an example, as it already provides such API.

Quoted 8 lines

The example above [1] is using the BTreeMap entry API to produce the issue. Are the BTreeMap and HashMap entry APIs significantly different, or is there something else I missed?

Best regards,
Andreas Hindborg

[1] https://lore.kernel.org/r/[email protected]

Hrm, tricky. I think it would work if the entry type had an into_map() that consumes the entry and returns a &mut to the original map.

Quoted 10 lines
  fn transaction_impl1<'a>(maps: &'a mut Maps, key: u32) -> &'a mut u32 {
      match maps.a.entry(key) {
          Entry::Occupied(o) => o.into_mut()
          Entry::Vacant(v) => {
              let map_a = v.into_map();
              let value = map_a.first_entry().expect("Not empty").remove();
              maps.b.entry(key).or_insert(value)
          }
      }
  }

I see. In my use case, this line

  map_a.first_entry().expect("Not empty").remove();

is not open coded. Rather, it is in a function on Maps:

  impl<'a> Maps<'a> {
      fn foo(&mut self) -> u32 {
          self.a.first_entry().expect("Not empty").remove()
      }
  }

  fn transaction_impl1<'a>(maps: &'a mut Maps, key: u32) -> &'a mut u32 {
      match maps.a.entry(key) {
          Entry::Occupied(o) => o.into_mut(),
          Entry::Vacant(v) => {
              let value = maps.foo();
              maps.foo();
              maps.b.entry(key).or_insert(value)
          }
      }
  }

In the actual code, Maps::foo is not a small short function, which is why I extracted it into a function.

I think I could make this work if I just put everything in one big function, but that does not seem like the right solution.

Am I holding it wrong here, or is this just the way it is?

My transaction_imp1 is get_or_alloc_cache_page [1] and my foo is extract_cache_page [2] if you want to have a look.

Best regards,
Andreas Hindborg

[1] https://git.kernel.org/pub/scm/linux/kernel/git/a.hindborg/linux.git/tree/drivers/block/rnull/disk_storage.rs?h=rnull-v6.19-rc5#n209
[2] https://git.kernel.org/pub/scm/linux/kernel/git/a.hindborg/linux.git/tree/drivers/block/rnull/disk_storage.rs?h=rnull-v6.19-rc5#n148

#27 lore raw

Re: [PATCH v3 03/12] rust: xarray: add `contains_index` method

In reply to Andreas Hindborg
Quoted 2 lines · Andreas Hindborg

Apparently this kind of code used to be OK [1] but the Rust devs decided

I don't think it used to be OK -- I think that issue was talking about code that required non-lexical lifetimes, which was an unstable feature back then, and the behavior changed while they worked on it.

When NLLs became stable later on (years later), the feature never allowed the code.

Cheers,
Miguel

author maintainer
#28 lore raw

Re: [PATCH v3 03/12] rust: xarray: add `contains_index` method

Quoted 7 lines · Miguel Ojeda
Quoted 2 lines · Andreas Hindborg

Apparently this kind of code used to be OK [1] but the Rust devs decided

I don't think it used to be OK -- I think that issue was talking about code that required non-lexical lifetimes, which was an unstable feature back then, and the behavior changed while they worked on it.

Right. The devil is in the details. My point is that the analysis to support this was deemed to be too computationally expensive to roll out, but the intention is to achieve a similar analysis at some point in the future, via Polonius.

Best regards,
Andreas Hindborg

#29 lore raw

Re: [PATCH v3 03/12] rust: xarray: add `contains_index` method

Quoted 5 lines · Andreas Hindborg

Right. The devil is in the details. My point is that the analysis to support this was deemed to be too computationally expensive to roll out, but the intention is to achieve a similar analysis at some point in the future, via Polonius.

Yeah, that is fine, I just wanted to avoid confusion, because it sounded like Rust broke (a lot of) existing code, which wouldn't have been acceptable (for the kernel and many other projects).

Cheers,
Miguel

author maintainer
#30 lore raw

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

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 |  1 +
 rust/kernel/xarray.rs           | 41 ++++++++++++++++++++++++++++++++++++++++-
 2 files changed, 41 insertions(+), 1 deletion(-)
rust/bindings/bindings_helper.h +1 -0
index a067038b4b422..58605c32e8102 100644
@@ -117,6 +117,7 @@ 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;
+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 +40 -1

53 lines not on this page · raw message

Signature · 1 line
2.51.2
#31 lore raw

Re: [PATCH v3 04/12] rust: xarray: add `XArrayState`

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.

It makes sense to me to merge patch 4 and 5 to avoid this.

Quoted 11 lines
---
 rust/bindings/bindings_helper.h |  1 +
 rust/kernel/xarray.rs           | 41 ++++++++++++++++++++++++++++++++++++++++-
 2 files changed, 41 insertions(+), 1 deletion(-)
rust/bindings/bindings_helper.h +0 -0
index a067038b4b422..58605c32e8102 100644

...

Quoted 1 line
rust/bindings/bindings_helper.h +0 -0
@@ -319,6 +322,42 @@ pub fn store(

...

rust/bindings/bindings_helper.h

Quoted 13 lines
rust/bindings/bindings_helper.h +13 -0
+impl<'a, 'b, T: ForeignOwnable> XArrayState<'a, 'b, T> {
+    #[expect(dead_code)]
+    fn new(access: &'b Guard<'a, T>, index: usize) -> Self {
+        let ptr = access.xa.xa.get();
+        // INVARIANT: We initialize `self.state` to a valid value below.
+        Self {
+            _access: PhantomData,
+            state: bindings::xa_state {
+                xa: ptr,
+                xa_index: index,
+                xa_shift: 0,
+                xa_sibs: 0,
+                xa_offset: 0,

To match C XArray __XA_STATE() we should also pass shift and sibs. Even if the only use case we have currently is setting these to 0 (XA_STATE()).

author maintainer
#32 lore raw

Re: [PATCH v3 04/12] rust: xarray: add `XArrayState`

Quoted 6 lines · Daniel Gomez
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 7 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.

It makes sense to me to merge patch 4 and 5 to avoid this.

It's always a balance. When I merge things I tend to get comments that I should split things out to make them easier to digest and review.

Best regards,
Andreas Hindborg

#33 lore raw

Re: [PATCH v3 04/12] rust: xarray: add `XArrayState`

In reply to Andreas Hindborg
Quoted 23 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.

---
 rust/bindings/bindings_helper.h |  1 +
 rust/kernel/xarray.rs           | 41 ++++++++++++++++++++++++++++++++++++++++-
 2 files changed, 41 insertions(+), 1 deletion(-)
rust/bindings/bindings_helper.h +0 -0
index a067038b4b422..58605c32e8102 100644

rust/bindings/bindings_helper.h const xa_mark_t RUST_CONST_HELPER_XA_PRESENT = XA_PRESENT; · line 120

Quoted 4 lines
rust/bindings/bindings_helper.h +1 -0
@@ -117,6 +117,7 @@ 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;
+const size_t RUST_CONST_HELPER_XAS_RESTART = (size_t)XAS_RESTART;

Please add a comment to explain the cast.

Quoted 67 lines
rust/bindings/bindings_helper.h +0 -0
 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 +40 -2
index ede48b5e1dba3..d1246ec114898 100644
@@ -8,7 +8,10 @@
     iter,
     marker::PhantomData,
     pin::Pin,
-    ptr::NonNull, //
+    ptr::{
+        null_mut,
+        NonNull, //
+    },
 };
 use kernel::{
     alloc,
@@ -319,6 +322,42 @@ pub fn store(
     }
 }
 
+/// Internal state for XArray iteration and entry operations.
+///
+/// # Invariants
+///
+/// - `state` is always a valid `bindings::xa_state`.
+#[expect(dead_code)]
+pub(crate) struct XArrayState<'a, 'b, T: ForeignOwnable> {
+    /// Holds a reference to the lock guard to ensure the lock is not dropped
+    /// while `Self` is live.
+    _access: PhantomData<&'b Guard<'a, T>>,
+    state: bindings::xa_state,
+}
+
+impl<'a, 'b, T: ForeignOwnable> XArrayState<'a, 'b, T> {
+    #[expect(dead_code)]
+    fn new(access: &'b Guard<'a, T>, index: usize) -> Self {
+        let ptr = access.xa.xa.get();
+        // INVARIANT: We initialize `self.state` to a valid value below.
+        Self {
+            _access: PhantomData,
+            state: bindings::xa_state {
+                xa: ptr,
+                xa_index: index,
+                xa_shift: 0,
+                xa_sibs: 0,
+                xa_offset: 0,
+                xa_pad: 0,
+                xa_node: bindings::XAS_RESTART as *mut bindings::xa_node,
+                xa_alloc: null_mut(),
+                xa_update: None,
+                xa_lru: null_mut(),
+            },
+        }
+    }
+}
+
 // SAFETY: `XArray<T>` has no shared mutable state so it is `Send` iff `T` is `Send`.
 unsafe impl<T: ForeignOwnable + Send> Send for XArray<T> {}
 
 
--

2.51.2

author maintainer
#34 lore raw

Re: [PATCH v3 04/12] rust: xarray: add `XArrayState`

Quoted 25 lines · Tamir Duberstein
Quoted 24 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.

---
 rust/bindings/bindings_helper.h |  1 +
 rust/kernel/xarray.rs           | 41 ++++++++++++++++++++++++++++++++++++++++-
 2 files changed, 41 insertions(+), 1 deletion(-)
rust/bindings/bindings_helper.h +0 -0
index a067038b4b422..58605c32e8102 100644
@@ -117,6 +117,7 @@ const xa_mark_t RUST_CONST_HELPER_XA_PRESENT = XA_PRESENT;
 
Quoted 5 lines

rust/bindings/bindings_helper.h const xa_mark_t RUST_CONST_HELPER_XA_PRESENT = XA_PRESENT; · line 120

Quoted 3 lines
rust/bindings/bindings_helper.h +1 -0
 const gfp_t RUST_CONST_HELPER_XA_FLAGS_ALLOC = XA_FLAGS_ALLOC;
 const gfp_t RUST_CONST_HELPER_XA_FLAGS_ALLOC1 = XA_FLAGS_ALLOC1;
+const size_t RUST_CONST_HELPER_XAS_RESTART = (size_t)XAS_RESTART;

Please add a comment to explain the cast.

How is this:

// XAS_RESTART is defined with type struct xa_node *. bindgen // cannot generate pointer typed constants, so we cast to size_t.

Best regards,
Andreas Hindborg

#35 lore raw

Re: [PATCH v3 04/12] rust: xarray: add `XArrayState`

Quoted 34 lines · Andreas Hindborg
Quoted 25 lines · Tamir Duberstein
Quoted 24 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.

---
 rust/bindings/bindings_helper.h |  1 +
 rust/kernel/xarray.rs           | 41 ++++++++++++++++++++++++++++++++++++++++-
 2 files changed, 41 insertions(+), 1 deletion(-)
rust/bindings/bindings_helper.h +0 -0
index a067038b4b422..58605c32e8102 100644
@@ -117,6 +117,7 @@ const xa_mark_t RUST_CONST_HELPER_XA_PRESENT = XA_PRESENT;
 
Quoted 5 lines

rust/bindings/bindings_helper.h const xa_mark_t RUST_CONST_HELPER_XA_PRESENT = XA_PRESENT; · line 120

Quoted 3 lines
rust/bindings/bindings_helper.h +1 -0
 const gfp_t RUST_CONST_HELPER_XA_FLAGS_ALLOC = XA_FLAGS_ALLOC;
 const gfp_t RUST_CONST_HELPER_XA_FLAGS_ALLOC1 = XA_FLAGS_ALLOC1;
+const size_t RUST_CONST_HELPER_XAS_RESTART = (size_t)XAS_RESTART;

Please add a comment to explain the cast.

Quoted 4 lines

How is this:

// XAS_RESTART is defined with type struct xa_node *. bindgen // cannot generate pointer typed constants, so we cast to size_t.

Can we include a citation or explain why bindgen can't generate pointer typed constants?

Quoted 6 lines

Best regards,
Andreas Hindborg

author maintainer
#36 lore raw

Re: [PATCH v3 04/12] rust: xarray: add `XArrayState`

Quoted 35 lines · Tamir Duberstein
Quoted 34 lines · Andreas Hindborg
Quoted 30 lines · Tamir Duberstein
Quoted 23 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.

---
 rust/bindings/bindings_helper.h |  1 +
 rust/kernel/xarray.rs           | 41 ++++++++++++++++++++++++++++++++++++++++-
 2 files changed, 41 insertions(+), 1 deletion(-)
rust/bindings/bindings_helper.h +0 -0
index a067038b4b422..58605c32e8102 100644

rust/bindings/bindings_helper.h const xa_mark_t RUST_CONST_HELPER_XA_PRESENT = XA_PRESENT; · line 120

Quoted 4 lines
rust/bindings/bindings_helper.h +1 -0
@@ -117,6 +117,7 @@ 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;
+const size_t RUST_CONST_HELPER_XAS_RESTART = (size_t)XAS_RESTART;

Please add a comment to explain the cast.

Quoted 7 lines
Quoted 4 lines

How is this:

// XAS_RESTART is defined with type struct xa_node *. bindgen // cannot generate pointer typed constants, so we cast to size_t.

Can we include a citation or explain why bindgen can't generate pointer typed constants?

If you have one, I can add it. I don't know why this is the case. My guess is that it's just not implemented yet.

Best regards,
Andreas Hindborg

#37 lore raw

Re: [PATCH v3 04/12] rust: xarray: add `XArrayState`

Quoted 40 lines · Andreas Hindborg
Quoted 37 lines · Tamir Duberstein
Quoted 36 lines · Andreas Hindborg
Quoted 25 lines · Tamir Duberstein
Quoted 24 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.

---
 rust/bindings/bindings_helper.h |  1 +
 rust/kernel/xarray.rs           | 41 ++++++++++++++++++++++++++++++++++++++++-
 2 files changed, 41 insertions(+), 1 deletion(-)
rust/bindings/bindings_helper.h +0 -0
index a067038b4b422..58605c32e8102 100644
@@ -117,6 +117,7 @@ const xa_mark_t RUST_CONST_HELPER_XA_PRESENT = XA_PRESENT;
 
Quoted 5 lines

rust/bindings/bindings_helper.h const xa_mark_t RUST_CONST_HELPER_XA_PRESENT = XA_PRESENT; · line 120

Quoted 3 lines
rust/bindings/bindings_helper.h +1 -0
 const gfp_t RUST_CONST_HELPER_XA_FLAGS_ALLOC = XA_FLAGS_ALLOC;
 const gfp_t RUST_CONST_HELPER_XA_FLAGS_ALLOC1 = XA_FLAGS_ALLOC1;
+const size_t RUST_CONST_HELPER_XAS_RESTART = (size_t)XAS_RESTART;

Please add a comment to explain the cast.

How is this:

Quoted 8 lines
Quoted 5 lines
Quoted 2 lines

// XAS_RESTART is defined with type struct xa_node *. bindgen // cannot generate pointer typed constants, so we cast to size_t.

Can we include a citation or explain why bindgen can't generate pointer typed constants?

If you have one, I can add it. I don't know why this is the case. My guess is that it's just not implemented yet.

If that's the state of your understanding, that's what the comment should say. But IMO the burden of finding out the reason, filing appropriate issues upstream, and documenting these things is on you as part of this change.

Quoted 4 lines

Best regards,
Andreas Hindborg

author maintainer
#38 lore raw

Re: [PATCH v3 04/12] rust: xarray: add `XArrayState`

Quoted 47 lines · Tamir Duberstein
Quoted 46 lines · Andreas Hindborg
Quoted 42 lines · Tamir Duberstein
Quoted 34 lines · Andreas Hindborg
Quoted 25 lines · Tamir Duberstein
Quoted 24 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.

---
 rust/bindings/bindings_helper.h |  1 +
 rust/kernel/xarray.rs           | 41 ++++++++++++++++++++++++++++++++++++++++-
 2 files changed, 41 insertions(+), 1 deletion(-)
rust/bindings/bindings_helper.h +0 -0
index a067038b4b422..58605c32e8102 100644
@@ -117,6 +117,7 @@ const xa_mark_t RUST_CONST_HELPER_XA_PRESENT = XA_PRESENT;
 
Quoted 5 lines

rust/bindings/bindings_helper.h const xa_mark_t RUST_CONST_HELPER_XA_PRESENT = XA_PRESENT; · line 120

Quoted 3 lines
rust/bindings/bindings_helper.h +1 -0
 const gfp_t RUST_CONST_HELPER_XA_FLAGS_ALLOC = XA_FLAGS_ALLOC;
 const gfp_t RUST_CONST_HELPER_XA_FLAGS_ALLOC1 = XA_FLAGS_ALLOC1;
+const size_t RUST_CONST_HELPER_XAS_RESTART = (size_t)XAS_RESTART;

Please add a comment to explain the cast.

Quoted 4 lines

How is this:

// XAS_RESTART is defined with type struct xa_node *. bindgen // cannot generate pointer typed constants, so we cast to size_t.

Can we include a citation or explain why bindgen can't generate pointer typed constants?

Quoted 7 lines
Quoted 2 lines

If you have one, I can add it. I don't know why this is the case. My guess is that it's just not implemented yet.

If that's the state of your understanding, that's what the comment should say. But IMO the burden of finding out the reason, filing appropriate issues upstream, and documenting these things is on you as part of this change.

I opened an issue with bindgen [1]. Depending on what they say I will update the comment.

Best regards,
Andreas Hindborg

[1] https://github.com/rust-lang/rust-bindgen/issues/3347

author maintainer
#39 lore raw

PATCH v3 5/12 rust: xarray: use `xas_load` instead of `xa_load` in `Guard::load`

In reply to Andreas Hindborg

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 | 15 +++++++++------
 1 file changed, 9 insertions(+), 6 deletions(-)
rust/kernel/xarray.rs +9 -6
index d1246ec114898..eadddafb180ec 100644
@@ -215,10 +215,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()?))
     }
 
     /// Checks if the XArray contains an element at the specified index.
@@ -327,7 +325,6 @@ pub fn store(
 /// # Invariants
 ///
 /// - `state` is always a valid `bindings::xa_state`.
-#[expect(dead_code)]
 pub(crate) struct XArrayState<'a, 'b, T: ForeignOwnable> {
     /// Holds a reference to the lock guard to ensure the lock is not dropped
     /// while `Self` is live.
@@ -336,7 +333,6 @@ pub(crate) struct XArrayState<'a, 'b, T: ForeignOwnable> {
 }
 
 impl<'a, 'b, T: ForeignOwnable> XArrayState<'a, 'b, T> {
-    #[expect(dead_code)]
     fn new(access: &'b Guard<'a, T>, index: usize) -> Self {
         let ptr = access.xa.xa.get();
         // INVARIANT: We initialize `self.state` to a valid value below.
@@ -356,6 +352,13 @@ fn new(access: &'b Guard<'a, T>, index: usize) -> Self {
             },
         }
     }
+
+    fn load(&mut self) -> Option<NonNull<c_void>> {
+        // SAFETY: `state.state` is always valid by the type invariant of
+        // `XArrayState and we hold the xarray lock`.
+        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
#40 lore raw

Re: [PATCH v3 05/12] rust: xarray: use `xas_load` instead of `xa_load` in `Guard::load`

Quoted 8 lines · Andreas Hindborg

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.

I don't understand the locking here.

You are saying that, since you hold the xarray write lock, you won't be taking the rcu read lock, but then you change the api of load? That seems wrong to me.

Any readers of the api that calls load will now need to hold the rcu read lock externally. If you're doing this, then you should indicate that is necessary in the function name, like the C side does. Otherwise you are limiting the users to the advanced API, aren't you?

Or are you saying that xarray can only be used if you hold the exclusive lock, which is now a read and write lock?

Quoted 59 lines
---
 rust/kernel/xarray.rs | 15 +++++++++------
 1 file changed, 9 insertions(+), 6 deletions(-)
rust/kernel/xarray.rs +9 -6
index d1246ec114898..eadddafb180ec 100644
@@ -215,10 +215,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()?))
     }
 
     /// Checks if the XArray contains an element at the specified index.
@@ -327,7 +325,6 @@ pub fn store(
 /// # Invariants
 ///
 /// - `state` is always a valid `bindings::xa_state`.
-#[expect(dead_code)]
 pub(crate) struct XArrayState<'a, 'b, T: ForeignOwnable> {
     /// Holds a reference to the lock guard to ensure the lock is not dropped
     /// while `Self` is live.
@@ -336,7 +333,6 @@ pub(crate) struct XArrayState<'a, 'b, T: ForeignOwnable> {
 }
 
 impl<'a, 'b, T: ForeignOwnable> XArrayState<'a, 'b, T> {
-    #[expect(dead_code)]
     fn new(access: &'b Guard<'a, T>, index: usize) -> Self {
         let ptr = access.xa.xa.get();
         // INVARIANT: We initialize `self.state` to a valid value below.
@@ -356,6 +352,13 @@ fn new(access: &'b Guard<'a, T>, index: usize) -> Self {
             },
         }
     }
+
+    fn load(&mut self) -> Option<NonNull<c_void>> {
+        // SAFETY: `state.state` is always valid by the type invariant of
+        // `XArrayState and we hold the xarray lock`.
+        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 · 2 lines
-- 
2.51.2
maintainer Acked-by
#41 lore raw

Re: [PATCH v3 05/12] rust: xarray: use `xas_load` instead of `xa_load` in `Guard::load`

Quoted 8 lines · Liam R. Howlett
Quoted 6 lines · Andreas Hindborg

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.

Quoted 8 lines
Quoted 2 lines

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

I don't understand the locking here.

You are saying that, since you hold the xarray write lock, you won't be taking the rcu read lock, but then you change the api of load? That seems wrong to me.

This patch doesn't change the API of load. Andreas is saying that the type system already requires the caller to hold the xarray spin lock when load is called, meaning acquiring the RCU lock isn't necessary.

Quoted 5 lines

Any readers of the api that calls load will now need to hold the rcu read lock externally. If you're doing this, then you should indicate that is necessary in the function name, like the C side does. Otherwise you are limiting the users to the advanced API, aren't you?

The existing API already requires users to hold the xarray lock.

Quoted 3 lines

Or are you saying that xarray can only be used if you hold the exclusive lock, which is now a read and write lock?

Yes - except for the word "now"; I'm not sure what you mean by it.

Quoted 3 lines
Quoted 3 lines
Quoted 4 lines
Quoted 4 lines
---
 rust/kernel/xarray.rs | 15 +++++++++------
 1 file changed, 9 insertions(+), 6 deletions(-)
Quoted 14 lines
Quoted 5 lines
rust/kernel/xarray.rs +0 -0
index d1246ec114898..eadddafb180ec 100644

rust/kernel/xarray.rs fn load<F, U>(&self, index: usize, f: F) -> Option<U> · line 219

Quoted 9 lines
rust/kernel/xarray.rs +2 -4
@@ -215,10 +215,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()?))

This can probably be written as state.load().map(f).

Quoted 39 lines
Quoted 39 lines
rust/kernel/xarray.rs +7 -3
     }
 
     /// Checks if the XArray contains an element at the specified index.
@@ -327,7 +325,6 @@ pub fn store(
 /// # Invariants
 ///
 /// - `state` is always a valid `bindings::xa_state`.
-#[expect(dead_code)]
 pub(crate) struct XArrayState<'a, 'b, T: ForeignOwnable> {
     /// Holds a reference to the lock guard to ensure the lock is not dropped
     /// while `Self` is live.
@@ -336,7 +333,6 @@ pub(crate) struct XArrayState<'a, 'b, T: ForeignOwnable> {
 }
 
 impl<'a, 'b, T: ForeignOwnable> XArrayState<'a, 'b, T> {
-    #[expect(dead_code)]
     fn new(access: &'b Guard<'a, T>, index: usize) -> Self {
         let ptr = access.xa.xa.get();
         // INVARIANT: We initialize `self.state` to a valid value below.
@@ -356,6 +352,13 @@ fn new(access: &'b Guard<'a, T>, index: usize) -> Self {
             },
         }
     }
+
+    fn load(&mut self) -> Option<NonNull<c_void>> {
+        // SAFETY: `state.state` is always valid by the type invariant of
+        // `XArrayState and we hold the xarray lock`.
+        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`.
 
--

2.51.2

#42 lore raw

Re: [PATCH v3 05/12] rust: xarray: use `xas_load` instead of `xa_load` in `Guard::load`

Quoted 15 lines · Tamir Duberstein
Quoted 13 lines · Liam R. Howlett
Quoted 8 lines · Andreas Hindborg

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.

I don't understand the locking here.

Quoted 7 lines
Quoted 3 lines

You are saying that, since you hold the xarray write lock, you won't be taking the rcu read lock, but then you change the api of load? That seems wrong to me.

This patch doesn't change the API of load. Andreas is saying that the type system already requires the caller to hold the xarray spin lock when load is called, meaning acquiring the RCU lock isn't necessary.

What I mean is that the API can no longer be called when holding the RCU read lock. You seem to imply this is already the case though.

Quoted 7 lines
Quoted 6 lines

Any readers of the api that calls load will now need to hold the rcu read lock externally. If you're doing this, then you should indicate that is necessary in the function name, like the C side does. Otherwise you are limiting the users to the advanced API, aren't you?

Quoted 7 lines

The existing API already requires users to hold the xarray lock.

Quoted 3 lines

Or are you saying that xarray can only be used if you hold the exclusive lock, which is now a read and write lock?

Yes - except for the word "now"; I'm not sure what you mean by it.

I'm trying to understand the locking on the rust side.

I think you answered it by telling me that all readers and writers use the spinlock.

Is this a temporary limitation?

Thanks,
Liam

maintainer
#43 lore raw

Re: [PATCH v3 05/12] rust: xarray: use `xas_load` instead of `xa_load` in `Guard::load`

Quoted 41 lines · Liam R. Howlett
Quoted 15 lines · Tamir Duberstein
Quoted 13 lines · Liam R. Howlett
Quoted 8 lines · Andreas Hindborg

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.

I don't understand the locking here.

Quoted 7 lines
Quoted 3 lines

You are saying that, since you hold the xarray write lock, you won't be taking the rcu read lock, but then you change the api of load? That seems wrong to me.

This patch doesn't change the API of load. Andreas is saying that the type system already requires the caller to hold the xarray spin lock when load is called, meaning acquiring the RCU lock isn't necessary.

What I mean is that the API can no longer be called when holding the RCU read lock. You seem to imply this is already the case though.

Quoted 13 lines
Quoted 6 lines

Any readers of the api that calls load will now need to hold the rcu read lock externally. If you're doing this, then you should indicate that is necessary in the function name, like the C side does. Otherwise you are limiting the users to the advanced API, aren't you?

The existing API already requires users to hold the xarray lock.

Quoted 3 lines

Or are you saying that xarray can only be used if you hold the exclusive lock, which is now a read and write lock?

Quoted 6 lines
Quoted 1 line

Yes - except for the word "now"; I'm not sure what you mean by it.

I'm trying to understand the locking on the rust side.

I think you answered it by telling me that all readers and writers use the spinlock.

Indeed. The current API doesn't expose load on the xarray at all; load is only available on the "guard" type. An instance of "guard" can exist only when the lock is held. The lock is unlocked when the guard is dropped.

Quoted 2 lines

Is this a temporary limitation?

Maybe? I don't think RfL has good abstractions for RCU yet. For example, exposing load directly on the xarray using xa_load would require a way to guarantee that the returned pointer's target isn't being concurrently mutated (e.g. under the xarray lock). I'm not aware of anyone asking for this, though.

Quoted 3 lines

Thanks,
Liam

maintainer
#44 lore raw

Re: [PATCH v3 05/12] rust: xarray: use `xas_load` instead of `xa_load` in `Guard::load`

Quoted 10 lines · Tamir Duberstein
Quoted 1 line · Liam R. Howlett

Is this a temporary limitation?

Maybe? I don't think RfL has good abstractions for RCU yet. For example, exposing load directly on the xarray using xa_load would require a way to guarantee that the returned pointer's target isn't being concurrently mutated (e.g. under the xarray lock). I'm not aware of anyone asking for this, though.

It's relatively easy to add an rcu-backed load using the RCU abstractions we have today. I already shared an RFC containing such a method for the maple tree, and it would not be much different for xarray.
https://lore.kernel.org/all/[email protected]/

Alice

#45 lore raw

Re: [PATCH v3 05/12] rust: xarray: use `xas_load` instead of `xa_load` in `Guard::load`

Quoted 12 lines · Alice Ryhl
Quoted 10 lines · Tamir Duberstein
Quoted 1 line · Liam R. Howlett

Is this a temporary limitation?

Maybe? I don't think RfL has good abstractions for RCU yet. For example, exposing load directly on the xarray using xa_load would require a way to guarantee that the returned pointer's target isn't being concurrently mutated (e.g. under the xarray lock). I'm not aware of anyone asking for this, though.

Quoted 6 lines

It's relatively easy to add an rcu-backed load using the RCU abstractions we have today. I already shared an RFC containing such a method for the maple tree, and it would not be much different for xarray.
https://lore.kernel.org/all/[email protected]/

It would probably be worth having two loads then, one that does rcu_read_lock()/unlock() and one for writer/advanced users like we have on the C side of things.

Or at least name the load() function to indicate which is implemented today?

At least on the maple tree side, we have both interfaces and users for both. I just found the change to remove the rcu safety odd because I assumed both are needed.

Thanks,
Liam

reviewer
#46 lore raw

Re: [PATCH v3 05/12] rust: xarray: use `xas_load` instead of `xa_load` in `Guard::load`

Quoted 10 lines · Liam R. Howlett
Quoted 9 lines · Alice Ryhl
Quoted 8 lines · Tamir Duberstein
Quoted 1 line · Liam R. Howlett

Is this a temporary limitation?

Maybe? I don't think RfL has good abstractions for RCU yet. For example, exposing load directly on the xarray using xa_load would require a way to guarantee that the returned pointer's target isn't

Well, if we only return a pointer, we don't need to guarantee that, right? Because it's up to the user to provide that guarantee. So we could have XArray::load() (not Guard::load()) that just calls xa_load(). Also see below.

Quoted 8 lines
Quoted 8 lines
Quoted 2 lines

being concurrently mutated (e.g. under the xarray lock). I'm not aware of anyone asking for this, though.

It's relatively easy to add an rcu-backed load using the RCU abstractions we have today. I already shared an RFC containing such a method for the maple tree, and it would not be much different for xarray.
https://lore.kernel.org/all/[email protected]/

I need to point out a difference between xas_load() and Alice's usage (also what Tamir mentioned above) there, what Alice needs (at least from her patchset) is the existence of the object is protected by RCU, i.e. if there is someone else dropping the object, a RCU read lock would still guarantee the access to the object is valid.

However, the internal RCU usage of both xarray and maple tree is to protect the *internal* data structure if I'm not missing anything, i.e. an writer may change the array or the tree while a reader is reading, the internal structure itself is still consistent and valid. But the nothing guarantees the object you read is still valid. For example, you can have an xa_erase() racing with an xa_load():

	<writer>			<reader>
	ptr = xa_erase(xa, idx);
					ptr = xa_load(xa, idx);
	reclaim(ptr);
					use(ptr); // <- object may be gone

the users of xarray needs to use other mechanism to guarantee the existence of the object.

In Alice's case, she in fact used an RCU read side critical section with a larger scope to protect the object as well, which is definitely nice to have, but not only way of using maple/xarray.

Quoted 6 lines
Quoted 1 line

It would probably be worth having two loads then, one that does rcu_read_lock()/unlock() and one for writer/advanced users like we have on the C side of things.

Agreed. But we may need more ;-)

Here IIUC that Andreas does is adding a load() for Guard of XArray, which is the load for a writer and most certainly you won't need to take an RCU read lock for that. The load of a reader can be added as I suggested above (similar as your "rcu_read_lock()/unlock()" suggestion above), but no object existence guarantee. We likely need a third API that can provide the object existence similar to what Alice had in maple tree.

Quoted 3 lines

Or at least name the load() function to indicate which is implemented today?

It's a namespace thing ;-) , the function in this patch is kernel::xarray::Guard::load(), and as I suggest here kernel::xarray::XArray::load() should be the same as xa_load().

Regards,
Boqun

Quoted 6 lines

At least on the maple tree side, we have both interfaces and users for both. I just found the change to remove the rcu safety odd because I assumed both are needed.

Thanks,
Liam

#47 lore raw

Re: [PATCH v3 05/12] rust: xarray: use `xas_load` instead of `xa_load` in `Guard::load`

Quoted 70 lines · Boqun Feng
Quoted 10 lines · Liam R. Howlett
Quoted 9 lines · Alice Ryhl
Quoted 8 lines · Tamir Duberstein
Quoted 1 line · Liam R. Howlett

Is this a temporary limitation?

Maybe? I don't think RfL has good abstractions for RCU yet. For example, exposing load directly on the xarray using xa_load would require a way to guarantee that the returned pointer's target isn't

Well, if we only return a pointer, we don't need to guarantee that, right? Because it's up to the user to provide that guarantee. So we could have XArray::load() (not Guard::load()) that just calls xa_load(). Also see below.

Quoted 8 lines
Quoted 8 lines
Quoted 2 lines

being concurrently mutated (e.g. under the xarray lock). I'm not aware of anyone asking for this, though.

It's relatively easy to add an rcu-backed load using the RCU abstractions we have today. I already shared an RFC containing such a method for the maple tree, and it would not be much different for xarray.
https://lore.kernel.org/all/[email protected]/

I need to point out a difference between xas_load() and Alice's usage (also what Tamir mentioned above) there, what Alice needs (at least from her patchset) is the existence of the object is protected by RCU, i.e. if there is someone else dropping the object, a RCU read lock would still guarantee the access to the object is valid.

However, the internal RCU usage of both xarray and maple tree is to protect the *internal* data structure if I'm not missing anything, i.e. an writer may change the array or the tree while a reader is reading, the internal structure itself is still consistent and valid. But the nothing guarantees the object you read is still valid. For example, you can have an xa_erase() racing with an xa_load():

        <writer>                        <reader>
        ptr = xa_erase(xa, idx);
                                        ptr = xa_load(xa, idx);
        reclaim(ptr);
                                        use(ptr); // <- object may be gone

the users of xarray needs to use other mechanism to guarantee the existence of the object.

In Alice's case, she in fact used an RCU read side critical section with a larger scope to protect the object as well, which is definitely nice to have, but not only way of using maple/xarray.

Quoted 6 lines
Quoted 1 line

It would probably be worth having two loads then, one that does rcu_read_lock()/unlock() and one for writer/advanced users like we have on the C side of things.

Agreed. But we may need more ;-)

Here IIUC that Andreas does is adding a load() for Guard of XArray, which is the load for a writer and most certainly you won't need to take an RCU read lock for that. The load of a reader can be added as I suggested above (similar as your "rcu_read_lock()/unlock()" suggestion above), but no object existence guarantee. We likely need a third API that can provide the object existence similar to what Alice had in maple tree.

Quoted 7 lines
Quoted 3 lines

Or at least name the load() function to indicate which is implemented today?

It's a namespace thing ;-) , the function in this patch is kernel::xarray::Guard::load(), and as I suggest here kernel::xarray::XArray::load() should be the same as xa_load().

Just to clarify: kernel::xarray::XArray::load() does not currently exist and no one has yet asked for it.

Quoted 11 lines

Regards,
Boqun

Quoted 6 lines

At least on the maple tree side, we have both interfaces and users for both. I just found the change to remove the rcu safety odd because I assumed both are needed.

Thanks,
Liam

reviewer
#48 lore raw

Re: [PATCH v3 05/12] rust: xarray: use `xas_load` instead of `xa_load` in `Guard::load`

Quoted 75 lines · Tamir Duberstein
Quoted 74 lines · Boqun Feng
Quoted 10 lines · Liam R. Howlett
Quoted 9 lines · Alice Ryhl
Quoted 8 lines · Tamir Duberstein
Quoted 1 line · Liam R. Howlett

Is this a temporary limitation?

Maybe? I don't think RfL has good abstractions for RCU yet. For example, exposing load directly on the xarray using xa_load would require a way to guarantee that the returned pointer's target isn't

Well, if we only return a pointer, we don't need to guarantee that, right? Because it's up to the user to provide that guarantee. So we could have XArray::load() (not Guard::load()) that just calls xa_load(). Also see below.

Quoted 8 lines
Quoted 8 lines
Quoted 2 lines

being concurrently mutated (e.g. under the xarray lock). I'm not aware of anyone asking for this, though.

It's relatively easy to add an rcu-backed load using the RCU abstractions we have today. I already shared an RFC containing such a method for the maple tree, and it would not be much different for xarray.
https://lore.kernel.org/all/[email protected]/

I need to point out a difference between xas_load() and Alice's usage (also what Tamir mentioned above) there, what Alice needs (at least from her patchset) is the existence of the object is protected by RCU, i.e. if there is someone else dropping the object, a RCU read lock would still guarantee the access to the object is valid.

However, the internal RCU usage of both xarray and maple tree is to protect the *internal* data structure if I'm not missing anything, i.e. an writer may change the array or the tree while a reader is reading, the internal structure itself is still consistent and valid. But the nothing guarantees the object you read is still valid. For example, you can have an xa_erase() racing with an xa_load():

        <writer>                        <reader>
        ptr = xa_erase(xa, idx);
                                        ptr = xa_load(xa, idx);
        reclaim(ptr);
                                        use(ptr); // <- object may be gone

the users of xarray needs to use other mechanism to guarantee the existence of the object.

In Alice's case, she in fact used an RCU read side critical section with a larger scope to protect the object as well, which is definitely nice to have, but not only way of using maple/xarray.

Quoted 6 lines
Quoted 1 line

It would probably be worth having two loads then, one that does rcu_read_lock()/unlock() and one for writer/advanced users like we have on the C side of things.

Agreed. But we may need more ;-)

Here IIUC that Andreas does is adding a load() for Guard of XArray, which is the load for a writer and most certainly you won't need to take an RCU read lock for that. The load of a reader can be added as I suggested above (similar as your "rcu_read_lock()/unlock()" suggestion above), but no object existence guarantee. We likely need a third API that can provide the object existence similar to what Alice had in maple tree.

Quoted 3 lines

Or at least name the load() function to indicate which is implemented today?

Quoted 7 lines
Quoted 3 lines

It's a namespace thing ;-) , the function in this patch is kernel::xarray::Guard::load(), and as I suggest here kernel::xarray::XArray::load() should be the same as xa_load().

Just to clarify: kernel::xarray::XArray::load() does not currently exist and no one has yet asked for it.

Yeah ;-) I meant to say we can add it if there is a user and we can use xa_load() to implement that.

Regards,
Boqun

Quoted 11 lines
Quoted 11 lines

Regards,
Boqun

Quoted 6 lines

At least on the maple tree side, we have both interfaces and users for both. I just found the change to remove the rcu safety odd because I assumed both are needed.

Thanks,
Liam

#49 lore raw

Re: [PATCH v3 05/12] rust: xarray: use `xas_load` instead of `xa_load` in `Guard::load`

In reply to Boqun Feng
Quoted 45 lines · Boqun Feng
Quoted 10 lines · Liam R. Howlett
Quoted 9 lines · Alice Ryhl
Quoted 8 lines · Tamir Duberstein
Quoted 1 line · Liam R. Howlett

Is this a temporary limitation?

Maybe? I don't think RfL has good abstractions for RCU yet. For example, exposing load directly on the xarray using xa_load would require a way to guarantee that the returned pointer's target isn't

Well, if we only return a pointer, we don't need to guarantee that, right? Because it's up to the user to provide that guarantee. So we could have XArray::load() (not Guard::load()) that just calls xa_load(). Also see below.

Quoted 8 lines
Quoted 8 lines
Quoted 2 lines

being concurrently mutated (e.g. under the xarray lock). I'm not aware of anyone asking for this, though.

It's relatively easy to add an rcu-backed load using the RCU abstractions we have today. I already shared an RFC containing such a method for the maple tree, and it would not be much different for xarray.
https://lore.kernel.org/all/[email protected]/

I need to point out a difference between xas_load() and Alice's usage (also what Tamir mentioned above) there, what Alice needs (at least from her patchset) is the existence of the object is protected by RCU, i.e. if there is someone else dropping the object, a RCU read lock would still guarantee the access to the object is valid.

However, the internal RCU usage of both xarray and maple tree is to protect the *internal* data structure if I'm not missing anything, i.e. an writer may change the array or the tree while a reader is reading, the internal structure itself is still consistent and valid. But the nothing guarantees the object you read is still valid. For example, you can have an xa_erase() racing with an xa_load():

	<writer>			<reader>
	ptr = xa_erase(xa, idx);
					ptr = xa_load(xa, idx);
	reclaim(ptr);
					use(ptr); // <- object may be gone
Quoted 6 lines

the users of xarray needs to use other mechanism to guarantee the existence of the object.

In Alice's case, she in fact used an RCU read side critical section with a larger scope to protect the object as well, which is definitely nice to have, but not only way of using maple/xarray.

The lock surrounding the ptr is only useful if your ptr is rcu protected, which isn't always the case. So having the rcu read side critical section extended to the life of the ptr means you've extended the rcu window for no reason when the ptr is protected in another way. This may perform poorly, depending on the situation.

Quoted 18 lines
Quoted 7 lines
Quoted 2 lines

It would probably be worth having two loads then, one that does rcu_read_lock()/unlock() and one for writer/advanced users like we have on the C side of things.

Agreed. But we may need more ;-)

Here IIUC that Andreas does is adding a load() for Guard of XArray, which is the load for a writer and most certainly you won't need to take an RCU read lock for that. The load of a reader can be added as I suggested above (similar as your "rcu_read_lock()/unlock()" suggestion above), but no object existence guarantee. We likely need a third API that can provide the object existence similar to what Alice had in maple tree.

Quoted 7 lines
Quoted 3 lines

Or at least name the load() function to indicate which is implemented today?

It's a namespace thing ;-) , the function in this patch is kernel::xarray::Guard::load(), and as I suggest here kernel::xarray::XArray::load() should be the same as xa_load().

Ah, okay.. this might be hard to follow in code, but I guess the compiler will catch the wrong user. That is, Guard::load() would not be written out, we'd just see array.load() in both cases?

It's also more confusing with the borrowck false positive issue in play. That is, using Guard::load() will do more work than necessary, I believe?

It is odd that only one of these exist, especially considering we have users for both on the C side. I guess the other one will be added once it's needed.

Thanks,
Liam

reviewer
#50 lore raw

Re: [PATCH v3 05/12] rust: xarray: use `xas_load` instead of `xa_load` in `Guard::load`

Quoted 49 lines · Liam R. Howlett
Quoted 48 lines · Boqun Feng
Quoted 10 lines · Liam R. Howlett
Quoted 9 lines · Alice Ryhl
Quoted 8 lines · Tamir Duberstein
Quoted 1 line · Liam R. Howlett

Is this a temporary limitation?

Maybe? I don't think RfL has good abstractions for RCU yet. For example, exposing load directly on the xarray using xa_load would require a way to guarantee that the returned pointer's target isn't

Well, if we only return a pointer, we don't need to guarantee that, right? Because it's up to the user to provide that guarantee. So we could have XArray::load() (not Guard::load()) that just calls xa_load(). Also see below.

Quoted 8 lines
Quoted 8 lines
Quoted 2 lines

being concurrently mutated (e.g. under the xarray lock). I'm not aware of anyone asking for this, though.

It's relatively easy to add an rcu-backed load using the RCU abstractions we have today. I already shared an RFC containing such a method for the maple tree, and it would not be much different for xarray.
https://lore.kernel.org/all/[email protected]/

I need to point out a difference between xas_load() and Alice's usage (also what Tamir mentioned above) there, what Alice needs (at least from her patchset) is the existence of the object is protected by RCU, i.e. if there is someone else dropping the object, a RCU read lock would still guarantee the access to the object is valid.

However, the internal RCU usage of both xarray and maple tree is to protect the *internal* data structure if I'm not missing anything, i.e. an writer may change the array or the tree while a reader is reading, the internal structure itself is still consistent and valid. But the nothing guarantees the object you read is still valid. For example, you can have an xa_erase() racing with an xa_load():

	<writer>			<reader>
	ptr = xa_erase(xa, idx);
					ptr = xa_load(xa, idx);
	reclaim(ptr);
					use(ptr); // <- object may be gone

the users of xarray needs to use other mechanism to guarantee the existence of the object.

Quoted 6 lines
Quoted 3 lines

In Alice's case, she in fact used an RCU read side critical section with a larger scope to protect the object as well, which is definitely nice to have, but not only way of using maple/xarray.

The lock surrounding the ptr is only useful if your ptr is rcu protected, which isn't always the case. So having the rcu read side

Right, so what Alice had in her patchset linked was introducing an RCU protected type wrapper for an object, so that is particularly for the case where the object is under RCU protection. (I would like to arrange the implementation and API in a slight different way for that patchset, but the idea is solid)

Quoted 26 lines

critical section extended to the life of the ptr means you've extended the rcu window for no reason when the ptr is protected in another way. This may perform poorly, depending on the situation.

Quoted 22 lines
Quoted 7 lines
Quoted 2 lines

It would probably be worth having two loads then, one that does rcu_read_lock()/unlock() and one for writer/advanced users like we have on the C side of things.

Agreed. But we may need more ;-)

Here IIUC that Andreas does is adding a load() for Guard of XArray, which is the load for a writer and most certainly you won't need to take an RCU read lock for that. The load of a reader can be added as I suggested above (similar as your "rcu_read_lock()/unlock()" suggestion above), but no object existence guarantee. We likely need a third API that can provide the object existence similar to what Alice had in maple tree.

Quoted 3 lines

Or at least name the load() function to indicate which is implemented today?

Quoted 8 lines
Quoted 3 lines

It's a namespace thing ;-) , the function in this patch is kernel::xarray::Guard::load(), and as I suggest here kernel::xarray::XArray::load() should be the same as xa_load().

Ah, okay.. this might be hard to follow in code, but I guess the compiler will catch the wrong user. That is, Guard::load() would not be written out, we'd just see array.load() in both cases?

For Guard::load() case, you will need to write:

	let ptr = xa.lock().load();

or

	let guard = xa.lock();
	let ptr = guard.load();

for XArray::load() case, you will need to write:

	let ptr = xa.load();
Quoted 3 lines

It's also more confusing with the borrowck false positive issue in play. That is, using Guard::load() will do more work than necessary, I believe?

I'm not following that thread closely, but seem so.

Quoted 4 lines

It is odd that only one of these exist, especially considering we have users for both on the C side. I guess the other one will be added once it's needed.

Yeah, this is the place where I don't agree with the "you must have a user to upstream an API" rule ;-) A reader's load(), even with no user, would completes the concept of what an XArrary is.

Regards,
Boqun

Quoted 2 lines

Thanks,
Liam

author maintainer
#51 lore raw

PATCH v3 6/12 rust: xarray: simplify `Guard::load`

In reply to Andreas Hindborg

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

---
 rust/kernel/xarray.rs | 23 +++++++++--------------
 1 file changed, 9 insertions(+), 14 deletions(-)
rust/kernel/xarray.rs +9 -14
index eadddafb180ec..e654bf56dc97c 100644
@@ -211,12 +211,8 @@ 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()
     }
 
     /// Checks if the XArray contains an element at the specified index.
@@ -242,18 +238,17 @@ pub fn contains_index(&self, index: usize) -> bool {
 
     /// 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
author maintainer
#52 lore raw

PATCH v3 7/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 | 68 +++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 68 insertions(+)
rust/kernel/xarray.rs +68 -0
index e654bf56dc97c..656ec897a0c41 100644
@@ -251,6 +251,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_KERNEL)?, GFP_KERNEL)?;
+    /// guard.store(20, KBox::new(20u32, GFP_KERNEL)?, GFP_KERNEL)?;
+    ///
+    /// 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_KERNEL)?, GFP_KERNEL)?;
+    /// guard.store(20, KBox::new(20u32, GFP_KERNEL)?, GFP_KERNEL)?;
+    ///
+    /// 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:
@@ -354,6 +415,13 @@ 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 always valid by the type invariant of
+        // `XArrayState` and the we hold the xarray lock.
+        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
#53 lore raw

PATCH v3 8/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.

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       | 123 +++++++++++++++
 rust/kernel/xarray/entry.rs | 367 ++++++++++++++++++++++++++++++++++++++++++++
 4 files changed, 508 insertions(+)
MAINTAINERS +1 -0
index 0efa8cc6775b7..8202515c6065b 100644
@@ -28361,6 +28361,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 60b299f11451d..425a6cc494734 100644
@@ -26,3 +26,20 @@ 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 +123 -0

154 lines not on this page · raw message

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

367 lines not on this page · raw message

Signature · 1 line
2.51.2
author maintainer
#54 lore raw

PATCH v3 9/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 | 407 ++++++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 408 insertions(+)
rust/kernel/mm.rs +1 -0
index 4764d7b68f2a7..1aa44424b0d53 100644
@@ -18,6 +18,7 @@
 };
 use core::{ops::Deref, ptr::NonNull};
 
+pub mod sheaf;
 pub mod virt;
 use virt::VmaRef;
 
rust/kernel/mm/sheaf.rs new file +407 -0

407 lines not on this page · raw message

Signature · 1 line
2.51.2
author maintainer
#55 lore raw

PATCH v3 10/12 rust: mm: sheaf: allow use of C initialized static caches

In reply to Andreas Hindborg

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

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

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

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

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

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

Cc Vlastimil Babka <[email protected]>
Cc "Liam R. Howlett" <[email protected]>
Cc "Matthew Wilcox (Oracle)" <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
---
 mm/slub.c               |   4 +
 rust/kernel/mm/sheaf.rs | 343 +++++++++++++++++++++++++++++++++++++++++++-----
 2 files changed, 317 insertions(+), 30 deletions(-)
mm/slub.c +4 -0
index f77b7407c51bc..7c6b1d28778d0 100644
@@ -5428,6 +5428,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()
@@ -5483,6 +5484,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
@@ -5536,6 +5538,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()
@@ -5573,6 +5576,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
author maintainer
#56 lore raw

PATCH v3 11/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 976b9bd02a1b5..1cf0012b15ade 100644
@@ -1598,10 +1598,16 @@ void __init radix_tree_init(void)
 	BUILD_BUG_ON(RADIX_TREE_MAX_TAGS + __GFP_BITS_SHIFT > 32);
 	BUILD_BUG_ON(ROOT_IS_IDR & ~GFP_ZONEMASK);
 	BUILD_BUG_ON(XA_CHUNK_SIZE > 255);
-	radix_tree_node_cachep = kmem_cache_create("radix_tree_node",
-			sizeof(struct radix_tree_node), 0,
-			SLAB_PANIC | SLAB_RECLAIM_ACCOUNT,
-			radix_tree_node_ctor);
+
+	struct kmem_cache_args args = {
+		.ctor = radix_tree_node_ctor,
+		.sheaf_capacity = 64,
+	};
+
+	radix_tree_node_cachep = kmem_cache_create(
+		"radix_tree_node", sizeof(struct radix_tree_node), &args,
+		SLAB_PANIC | SLAB_RECLAIM_ACCOUNT);
+
 	ret = cpuhp_setup_state_nocalls(CPUHP_RADIX_DEAD, "lib/radix:dead",
 					NULL, radix_tree_cpu_dead);
 	WARN_ON(ret < 0);
Signature · 1 line
2.51.2
#57 lore raw

Re: [PATCH v3 11/12] xarray, radix-tree: enable sheaf support for kmem_cache

Quoted 16 lines · 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 +0 -0
index 976b9bd02a1b5..1cf0012b15ade 100644
@@ -1598,10 +1598,16 @@ void __init radix_tree_init(void)
 	BUILD_BUG_ON(RADIX_TREE_MAX_TAGS + __GFP_BITS_SHIFT > 32);
 	BUILD_BUG_ON(ROOT_IS_IDR & ~GFP_ZONEMASK);

lib/radix-tree.c void __init radix_tree_init(void) · line 1605

Quoted 10 lines
lib/radix-tree.c +5 -4
 	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,
+	};

Is the sheaf_capacity matching the number of slots in an XArray node? If so, this should be bindings::XA_CHUNK_SIZE.

author maintainer
#58 lore raw

Re: [PATCH v3 11/12] xarray, radix-tree: enable sheaf support for kmem_cache

Quoted 22 lines · Daniel Gomez
Quoted 21 lines · 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 +0 -4
index 976b9bd02a1b5..1cf0012b15ade 100644
@@ -1598,10 +1598,16 @@ void __init radix_tree_init(void)
 	BUILD_BUG_ON(RADIX_TREE_MAX_TAGS + __GFP_BITS_SHIFT > 32);
 	BUILD_BUG_ON(ROOT_IS_IDR & ~GFP_ZONEMASK);
 	BUILD_BUG_ON(XA_CHUNK_SIZE > 255);
-	radix_tree_node_cachep = kmem_cache_create("radix_tree_node",
-			sizeof(struct radix_tree_node), 0,
-			SLAB_PANIC | SLAB_RECLAIM_ACCOUNT,
-			radix_tree_node_ctor);
Quoted 8 lines

lib/radix-tree.c void __init radix_tree_init(void) · line 1605

Quoted 5 lines
lib/radix-tree.c +5 -0
+
+	struct kmem_cache_args args = {
+		.ctor = radix_tree_node_ctor,
+		.sheaf_capacity = 64,
+	};

Is the sheaf_capacity matching the number of slots in an XArray node? If so, this should be bindings::XA_CHUNK_SIZE.

It is not, it is arbitrarily chosen to large enough to gain an advantage but small enough to not waste too much memory.

For rust null block, it needs to be at least large enough to insert two leaf nodes.

Best regards,
Andreas Hindborg

author maintainer
#59 lore raw

PATCH v3 12/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           | 172 +++++++++++++++++++++++++++++++++++-----
 rust/kernel/xarray/entry.rs     |  29 ++++---
 5 files changed, 182 insertions(+), 30 deletions(-)
include/linux/radix-tree.h +3 -0
index eae67015ce51a..c3699f12b070c 100644
@@ -469,4 +469,7 @@ static __always_inline void __rcu **radix_tree_next_slot(void __rcu **slot,
 	     slot = radix_tree_next_slot(slot, iter,			\
 				RADIX_TREE_ITER_TAGGED | tag))
 
+
+void radix_tree_node_ctor(void *arg);
+
 #endif /* _LINUX_RADIX_TREE_H */
lib/radix-tree.c +3 -2
index 1cf0012b15ade..ddd67ce672f5c 100644
@@ -33,6 +33,7 @@
  * Radix tree node cache.
  */
 struct kmem_cache *radix_tree_node_cachep;
+EXPORT_SYMBOL(radix_tree_node_cachep);
 
 /*
  * The radix tree is variable-height, so an insert operation not only has
@@ -1566,14 +1567,14 @@ void idr_destroy(struct idr *idr)
 }
 EXPORT_SYMBOL(idr_destroy);
 
-static void
-radix_tree_node_ctor(void *arg)
+void radix_tree_node_ctor(void *arg)
 {
 	struct radix_tree_node *node = arg;
 
 	memset(node, 0, sizeof(*node));
 	INIT_LIST_HEAD(&node->private_list);
 }
+EXPORT_SYMBOL(radix_tree_node_ctor);
 
 static int radix_tree_cpu_dead(unsigned int cpu)
 {
rust/bindings/bindings_helper.h +3 -0
index 58605c32e8102..652f08ad888cd 100644
@@ -118,6 +118,9 @@ 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;
 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 +153 -19

239 lines not on this page · raw message

rust/kernel/xarray/entry.rs +20 -9
index 1b1c21bed7022..ff500be3832b7 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_KERNEL)?, GFP_KERNEL)?;
     /// let entry = guard.entry(42);
@@ -64,7 +65,8 @@ pub(crate) fn new(guard: &'b mut Guard<'a, T>, index: usize) -> Self {
     /// 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.
     ///
     ///
@@ -79,7 +81,7 @@ pub(crate) fn new(guard: &'b mut Guard<'a, T>, index: usize) -> Self {
     ///
     /// if let Entry::Vacant(entry) = guard.entry(42) {
     ///     let value = KBox::new(0x1337u32, GFP_KERNEL)?;
-    ///     let borrowed = entry.insert(value)?;
+    ///     let borrowed = entry.insert(value, None)?;
     ///     assert_eq!(*borrowed, 0x1337);
     /// }
     ///
@@ -87,8 +89,12 @@ pub(crate) fn new(guard: &'b mut Guard<'a, T>, index: usize) -> Self {
     ///
     /// # 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`.
@@ -98,7 +104,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
@@ -112,7 +119,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_KERNEL)?;
-    ///     let occupied = entry.insert_entry(value)?;
+    ///     let occupied = entry.insert_entry(value, None)?;
     ///     assert_eq!(occupied.index(), 42);
     /// }
     ///
@@ -120,8 +127,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