rust: xarray: add `insert` and `reserve`
Subsystems (6)
cover rust: xarray: add `insert` and `reserve`
Please see individual patches.
---
Tamir Duberstein (3):
rust: xarray: use the prelude
rust: xarray: implement Default for AllocKind
rust: xarray: add insert and reserve
include/linux/xarray.h | 2 + lib/xarray.c | 28 ++- rust/helpers/xarray.c | 5 + rust/kernel/xarray.rs | 460 +++++++++++++++++++++++++++++++++++++++++++++++-- 4 files changed, 472 insertions(+), 23 deletions(-)
---
base-commit: 769e324b66b0d92d04f315d0c45a0f72737c7494
change-id: 20250701-xarray-insert-reserve-bd811ad46a1d
Best regards,
Signature · 1 line
Tamir Duberstein <[email protected]>
PATCH 1/3 rust: xarray: use the prelude
Using the prelude is customary in the kernel crate.
--- rust/kernel/xarray.rs | 34 ++++++++++++++++++++-------------- 1 file changed, 20 insertions(+), 14 deletions(-)
rust/kernel/xarray.rs +20 -14
@@ -5,16 +5,15 @@//! C header: [`include/linux/xarray.h`](srctree/include/linux/xarray.h) use crate ::{ - alloc, bindings, build_assert, - error::{Error ,Result }, + alloc, + prelude::*, types::{ForeignOwnable ,NotThreadSafe ,Opaque }, }; -use core::{iter, marker::PhantomData , mem, pin::Pin , ptr::NonNull }; -use pin_init::{pin_data, pin_init, pinned_drop,PinInit }; +use core::{iter, marker::PhantomData , mem, ptr::NonNull };/// An array which efficiently maps sparse integer indices to owned objects. /// -/// This is similar to a [`crate::alloc::kvec::Vec<Option<T>>`], but more efficient when there are +/// This is similar to a [`Vec<Option<T>>`], but more efficient when there are /// holes in the index space, and can be efficiently grown. /// /// # Invariants
@@ -104,16 +103,23 @@ pub fn new(kind: AllocKind) -> impl PinInit<Self> {fn iter (&self) ->impl Iterator <Item =NonNull <T ::PointedTo >> + '_ {let mut index =0 ; -// SAFETY: `self.xa` is always valid by the type invariant. - iter::once (unsafe { - bindings::xa_find (self.xa.get (), &mut index, usize::MAX , bindings::XA_PRESENT ) - }) - .chain (iter::from_fn (move || { + core::iter::Iterator ::chain (// SAFETY: `self.xa` is always valid by the type invariant. -Some (unsafe { - bindings::xa_find_after (self.xa.get (), &mut index, usize::MAX , bindings::XA_PRESENT ) - }) - })) + iter::once (unsafe { + bindings::xa_find (self.xa.get (), &mut index, usize::MAX , bindings::XA_PRESENT ) + }), + iter::from_fn (move || { +// SAFETY: `self.xa` is always valid by the type invariant. +Some (unsafe { + bindings::xa_find_after ( + self.xa.get (), + &mut index, + usize::MAX , + bindings::XA_PRESENT , + ) + }) + }), + ) .map_while (|ptr|NonNull ::new (ptr.cast ())) }
Signature · 1 line
2.50.0
PATCH 2/3 rust: xarray: implement Default for AllocKind
In reply to Tamir DubersteinMost users are likely to want 0-indexed arrays. Clean up the documentation test accordingly.
--- rust/kernel/xarray.rs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-)
rust/kernel/xarray.rs +6 -3
@@ -24,10 +24,11 @@/// # Examples /// /// ```rust -/// use kernel::alloc::KBox; -/// use kernel::xarray::{AllocKind, XArray}; +/// # use kernel::alloc::KBox; +/// # use kernel::xarray::XArray; +/// # use pin_init::stack_pin_init; /// -/// let xa = KBox::pin_init(XArray::new(AllocKind::Alloc1), GFP_KERNEL)?; +/// stack_pin_init!(let xa = XArray::new(Default::default())); /// /// let dead = KBox::new(0xdead, GFP_KERNEL)?; /// let beef = KBox::new(0xbeef, GFP_KERNEL)?;
@@ -75,8 +76,10 @@ fn drop(self: Pin<&mut Self>) { }/// Flags passed to [`XArray::new`] to configure the array's allocation tracking behavior. +#[derive( Default )] pub enum AllocKind {/// Consider the first element to be at index 0. +#[default] Alloc ,/// Consider the first element to be at index 1. Alloc1 ,
Signature · 1 line
2.50.0
PATCH 3/3 rust: xarray: add `insert` and `reserve`
In reply to Tamir DubersteinAdd Guard::{insert,reserve} and Guard::{insert,reserve}_limit, which are akin to __xa_{alloc,insert} in C.
Note that unlike xa_reserve which only ensures that memory is allocated, the semantics of Reservation are stricter and require precise management of the reservation. Indices which have been reserved can still be overwritten with Guard::store, which allows for C-like semantics if desired.
__xa_cmpxchg_raw is exported to facilitate the semantics described above.
--- include/linux/xarray.h | 2 + lib/xarray.c | 28 +++- rust/helpers/xarray.c | 5 + rust/kernel/xarray.rs | 419 ++++++++++++++++++++++++++++++++++++++++++++++++- 4 files changed, 447 insertions(+), 7 deletions(-)
include/linux/xarray.h +2 -0
@@ -563,6 +563,8 @@ void *__xa_erase(struct xarray *, unsigned long index);void *__xa_store (struct xarray *,unsigned long index,void *entry,gfp_t );void *__xa_cmpxchg (struct xarray *,unsigned long index,void *old,void *entry,gfp_t ); +void *__xa_cmpxchg_raw (struct xarray *,unsigned long index,void *old, +void *entry,gfp_t );int __must_check __xa_insert (struct xarray *,unsigned long index,void *entry,gfp_t ); int __must_check __xa_alloc(struct xarray *, u32 *id, void *entry,
lib/xarray.c +24 -4
@@ -1738,9 +1738,6 @@ void *xa_store(struct xarray *xa, unsigned long index, void *entry, gfp_t gfp) }EXPORT_SYMBOL (xa_store); -static inline void *__xa_cmpxchg_raw (struct xarray *xa,unsigned long index, -void *old,void *entry,gfp_t gfp); -/** * __xa_cmpxchg() - Conditionally replace an entry in the XArray. * @xa: XArray.
@@ -1767,7 +1764,29 @@ void *__xa_cmpxchg(struct xarray *xa, unsigned long index, }EXPORT_SYMBOL (__xa_cmpxchg); -static inline void *__xa_cmpxchg_raw (struct xarray *xa,unsigned long index, +/** +* __xa_cmpxchg_raw() - Conditionally replace an entry in the XArray. +* @xa: XArray. +* @index: Index into array. +* @old: Old value to test against. +* @entry: New value to place in array. +* @gfp: Memory allocation flags. +* +* You must already be holding the xa_lock when calling this function. +* It will drop the lock if needed to allocate memory, and then reacquire +* it afterwards. +* +* If the entry at @index is the same as @old, replace it with @entry. +* If the return value is equal to @old, then the exchange was successful. +* +* This function is the same as __xa_cmpxchg() except that it does not coerce +* XA_ZERO_ENTRY to NULL on egress. +* +* Context: Any context. Expects xa_lock to be held on entry. May +* release and reacquire xa_lock if @gfp flags permit. +* Return: The old value at this index or xa_err() if an error happened. +*/ +void *__xa_cmpxchg_raw (struct xarray *xa,unsigned long index,void *old,void *entry,gfp_t gfp) {XA_STATE (xas, xa, index);
@@ -1787,6 +1806,7 @@ static inline void *__xa_cmpxchg_raw(struct xarray *xa, unsigned long index,return xas_result (&xas, curr); } +EXPORT_SYMBOL (__xa_cmpxchg_raw);/** * __xa_insert() - Store this entry in the XArray if no entry is present.
rust/helpers/xarray.c +5 -0
@@ -2,6 +2,11 @@#include <linux/xarray.h> +void *rust_helper_xa_zero_entry (void ) +{ +return XA_ZERO_ENTRY ; +} +int rust_helper_xa_err (void *entry) {return xa_err (entry);
rust/kernel/xarray.rs +416 -3
464 lines not on this page · raw message
Signature · 1 line
2.50.0
Re: [PATCH 1/3] rust: xarray: use the prelude
In reply to Tamir DubersteinQuoted 33 lines · Tamir Duberstein
Using the prelude is customary in the kernel crate.
Signed-off-by Tamir Duberstein <[email protected]>--- rust/kernel/xarray.rs | 34 ++++++++++++++++++++-------------- 1 file changed, 20 insertions(+), 14 deletions(-)rust/kernel/xarray.rs +4
-5@@ -5,16 +5,15 @@//! C header: [`include/linux/xarray.h`](srctree/include/linux/xarray.h) use crate ::{ - alloc, bindings, build_assert, - error::{Error ,Result }, + alloc, + prelude::*, types::{ForeignOwnable ,NotThreadSafe ,Opaque }, }; -use core::{iter, marker::PhantomData , mem, pin::Pin , ptr::NonNull }; -use pin_init::{pin_data, pin_init, pinned_drop,PinInit }; +use core::{iter, marker::PhantomData , mem, ptr::NonNull };/// An array which efficiently maps sparse integer indices to owned objects. /// -/// This is similar to a [`crate::alloc::kvec::Vec<Option<T>>`], but more efficient when there are +/// This is similar to a [`Vec<Option<T>>`], but more efficient when there are /// holes in the index space, and can be efficiently grown. /// /// # Invariants
rust/kernel/xarray.rs pub fn new(kind: AllocKind) -> impl PinInit<Self> { · line 106
Quoted 9 lines
rust/kernel/xarray.rs +1
-5@@ -104,16 +103,23 @@ pub fn new(kind: AllocKind) -> impl PinInit<Self> {fn iter (&self) ->impl Iterator <Item =NonNull <T ::PointedTo >> + '_ {let mut index =0 ; -// SAFETY: `self.xa` is always valid by the type invariant. - iter::once (unsafe { - bindings::xa_find (self.xa.get (), &mut index, usize::MAX , bindings::XA_PRESENT ) - }) - .chain(iter::from_fn(move || { + core::iter::Iterator::chain(
Does this part come from using the prelude? If not, either we need to split the patch or we need to mention it in the changelog at least.
Also since we use core::iter above, we can avoid the core:: here.
Regards,
Boqun
Quoted 27 lines
rust/kernel/xarray.rs +15
-4// SAFETY: `self.xa` is always valid by the type invariant. -Some (unsafe { - bindings::xa_find_after (self.xa.get (), &mut index, usize::MAX , bindings::XA_PRESENT ) - }) - })) + iter::once(unsafe { + bindings::xa_find(self.xa.get(), &mut index, usize::MAX, bindings::XA_PRESENT) + }), + iter::from_fn (move || { +// SAFETY: `self.xa` is always valid by the type invariant. +Some (unsafe { + bindings::xa_find_after ( + self.xa.get (), + &mut index, + usize::MAX , + bindings::XA_PRESENT , + ) + }) + }), + ) .map_while (|ptr|NonNull ::new (ptr.cast ())) }Signature · 2 lines
-- 2.50.0
Re: [PATCH 1/3] rust: xarray: use the prelude
Quoted 38 lines · Boqun Feng
Quoted 36 lines · Tamir Duberstein
Using the prelude is customary in the kernel crate.
Signed-off-by Tamir Duberstein <[email protected]>--- rust/kernel/xarray.rs | 34 ++++++++++++++++++++-------------- 1 file changed, 20 insertions(+), 14 deletions(-)rust/kernel/xarray.rs +4
-5@@ -5,16 +5,15 @@//! C header: [`include/linux/xarray.h`](srctree/include/linux/xarray.h) use crate ::{ - alloc, bindings, build_assert, - error::{Error ,Result }, + alloc, + prelude::*, types::{ForeignOwnable ,NotThreadSafe ,Opaque }, }; -use core::{iter, marker::PhantomData , mem, pin::Pin , ptr::NonNull }; -use pin_init::{pin_data, pin_init, pinned_drop,PinInit }; +use core::{iter, marker::PhantomData , mem, ptr::NonNull };/// An array which efficiently maps sparse integer indices to owned objects. /// -/// This is similar to a [`crate::alloc::kvec::Vec<Option<T>>`], but more efficient when there are +/// This is similar to a [`Vec<Option<T>>`], but more efficient when there are /// holes in the index space, and can be efficiently grown. /// /// # Invariants @@ -104,16 +103,23 @@ pub fn new(kind: AllocKind) -> impl PinInit<Self> {fn iter (&self) ->impl Iterator <Item =NonNull <T ::PointedTo >> + '_ {let mut index =0 ;
Quoted 9 lines
rust/kernel/xarray.rs pub fn new(kind: AllocKind) -> impl PinInit<Self> { · line 106
Quoted 6 lines
rust/kernel/xarray.rs +1
-5-// SAFETY: `self.xa` is always valid by the type invariant. - iter::once (unsafe { - bindings::xa_find (self.xa.get (), &mut index, usize::MAX , bindings::XA_PRESENT ) - }) - .chain(iter::from_fn(move || { + core::iter::Iterator::chain(Does this part come from using the prelude? If not, either we need to split the patch or we need to mention it in the changelog at least.
Yes, it's from using the prelude - PinInit also has a chain method that causes ambiguity here.
Quoted 1 line
Also since we
use core::iterabove, we can avoid thecore::here.
Good point.
Quoted 3 lines · Tamir Duberstein
Add
Guard::{insert,reserve}andGuard::{insert,reserve}_limit, which are akin to__xa_{alloc,insert}in C.
Who will be using this? i.e. we need to justify adding code, typically by mentioning the users.
By the way, it may help splitting the C parts into its own patch, so that Matthew can focus on that (but maybe you all already discussed this).
Also, unit tests are great, thanks for adding those. Can we add examples as well? Maybe on the module-level docs, given the rest are there.
Quoted 1 line
+ /// Wrapper around
__xa_alloc.
We try to mention what something does in the title at least, even if it is just copied from the C docs -- you can reference those docs too for more context, e.g. [__xa_alloc] to:
https://docs.kernel.org/core-api/xarray.html#c.__xa_alloc
Cheers,
Miguel
Re: [PATCH 1/3] rust: xarray: use the prelude
In reply to Tamir DubersteinQuoted 49 lines · Tamir Duberstein
Quoted 38 lines · Boqun Feng
Quoted 36 lines · Tamir Duberstein
Using the prelude is customary in the kernel crate.
Signed-off-by Tamir Duberstein <[email protected]>--- rust/kernel/xarray.rs | 34 ++++++++++++++++++++-------------- 1 file changed, 20 insertions(+), 14 deletions(-)rust/kernel/xarray.rs +4
-5@@ -5,16 +5,15 @@//! C header: [`include/linux/xarray.h`](srctree/include/linux/xarray.h) use crate ::{ - alloc, bindings, build_assert, - error::{Error ,Result }, + alloc, + prelude::*, types::{ForeignOwnable ,NotThreadSafe ,Opaque }, }; -use core::{iter, marker::PhantomData , mem, pin::Pin , ptr::NonNull }; -use pin_init::{pin_data, pin_init, pinned_drop,PinInit }; +use core::{iter, marker::PhantomData , mem, ptr::NonNull };/// An array which efficiently maps sparse integer indices to owned objects. /// -/// This is similar to a [`crate::alloc::kvec::Vec<Option<T>>`], but more efficient when there are +/// This is similar to a [`Vec<Option<T>>`], but more efficient when there are /// holes in the index space, and can be efficiently grown. /// /// # Invariants @@ -104,16 +103,23 @@ pub fn new(kind: AllocKind) -> impl PinInit<Self> {fn iter (&self) ->impl Iterator <Item =NonNull <T ::PointedTo >> + '_ {let mut index =0 ;Quoted 9 lines
rust/kernel/xarray.rs pub fn new(kind: AllocKind) -> impl PinInit<Self> { · line 106
Quoted 6 lines
rust/kernel/xarray.rs +1
-5-// SAFETY: `self.xa` is always valid by the type invariant. - iter::once (unsafe { - bindings::xa_find (self.xa.get (), &mut index, usize::MAX , bindings::XA_PRESENT ) - }) - .chain(iter::from_fn(move || { + core::iter::Iterator::chain(Does this part come from using the prelude? If not, either we need to split the patch or we need to mention it in the changelog at least.
Quoted 2 lines
Yes, it's from using the prelude - PinInit also has a chain method that causes ambiguity here.
Maybe you can mention this in the change log as well. Like "Calling iter::chain() with the associated function style to disambiguate with PinInit::chain()". Make it easier to review (and remember) why.
Regards,
Boqun
Quoted 5 lines
Quoted 2 lines
Also since we
use core::iterabove, we can avoid thecore::here.Good point.
Quoted 8 lines · Miguel Ojeda
Quoted 3 lines · Tamir Duberstein
Add
Guard::{insert,reserve}andGuard::{insert,reserve}_limit, which are akin to__xa_{alloc,insert}in C.Who will be using this? i.e. we need to justify adding code, typically by mentioning the users.
Daniel, could you name your use case?
Alice, could you confirm whether rust binder needs this or not?
Andreas, did you also need this?
Quoted 3 lines
By the way, it may help splitting the C parts into its own patch, so that Matthew can focus on that (but maybe you all already discussed this).
Happy to do so if it makes Matthew's life easier, but I'd prefer to keep it together so the motivation is clearer in the git log. Matthew:
any preference?
Quoted 3 lines
Also, unit tests are great, thanks for adding those. Can we add examples as well? Maybe on the module-level docs, given the rest are there.
Will do. I ported all the examples to unit tests now that we have kunit, but I'll bring some examples back.
Quoted 8 lines
Quoted 2 lines
+ /// Wrapper around
__xa_alloc.We try to mention what something does in the title at least, even if it is just copied from the C docs -- you can reference those docs too for more context, e.g. [
__xa_alloc] to:
👍
Re: [PATCH 1/3] rust: xarray: use the prelude
In reply to Boqun FengQuoted 51 lines · Boqun Feng
Quoted 49 lines · Tamir Duberstein
Quoted 47 lines · Boqun Feng
Quoted 33 lines · Tamir Duberstein
Using the prelude is customary in the kernel crate.
Signed-off-by Tamir Duberstein <[email protected]>--- rust/kernel/xarray.rs | 34 ++++++++++++++++++++-------------- 1 file changed, 20 insertions(+), 14 deletions(-)rust/kernel/xarray.rs +4
-5@@ -5,16 +5,15 @@//! C header: [`include/linux/xarray.h`](srctree/include/linux/xarray.h) use crate ::{ - alloc, bindings, build_assert, - error::{Error ,Result }, + alloc, + prelude::*, types::{ForeignOwnable ,NotThreadSafe ,Opaque }, }; -use core::{iter, marker::PhantomData , mem, pin::Pin , ptr::NonNull }; -use pin_init::{pin_data, pin_init, pinned_drop,PinInit }; +use core::{iter, marker::PhantomData , mem, ptr::NonNull };/// An array which efficiently maps sparse integer indices to owned objects. /// -/// This is similar to a [`crate::alloc::kvec::Vec<Option<T>>`], but more efficient when there are +/// This is similar to a [`Vec<Option<T>>`], but more efficient when there are /// holes in the index space, and can be efficiently grown. /// /// # Invariants rust/kernel/xarray.rs pub fn new(kind: AllocKind) -> impl PinInit<Self> { · line 106
Quoted 9 lines
rust/kernel/xarray.rs +1
-5@@ -104,16 +103,23 @@ pub fn new(kind: AllocKind) -> impl PinInit<Self> {fn iter (&self) ->impl Iterator <Item =NonNull <T ::PointedTo >> + '_ {let mut index =0 ; -// SAFETY: `self.xa` is always valid by the type invariant. - iter::once (unsafe { - bindings::xa_find (self.xa.get (), &mut index, usize::MAX , bindings::XA_PRESENT ) - }) - .chain(iter::from_fn(move || { + core::iter::Iterator::chain(Does this part come from using the prelude? If not, either we need to split the patch or we need to mention it in the changelog at least.
Quoted 6 lines
Quoted 2 lines
Yes, it's from using the prelude - PinInit also has a chain method that causes ambiguity here.
Maybe you can mention this in the change log as well. Like "Calling
iter::chain()with the associated function style to disambiguate withPinInit::chain()". Make it easier to review (and remember) why.
Yep, done for the next spin.
Daniel Almeida
reviewerHi, this is on my todo list.
Again, thanks Tamir for working on this.
Quoted 7 lines · Tamir Duberstein
Quoted 3 lines · Miguel Ojeda
Quoted 1 line · Tamir Duberstein
Quoted 7 lines
Quoted 5 lines
Quoted 2 lines
Add
Guard::{insert,reserve}andGuard::{insert,reserve}_limit, which are akin to__xa_{alloc,insert}in C.Who will be using this? i.e. we need to justify adding code, typically by mentioning the users.
Daniel, could you name your use case?
My main use case is for insert_limit.
Tyr uses xarrays to keep track of resources allocated by userspace, and we need to impose limits on how many resources can be allocated at once.
insert_limits() provides the exact semantics needed, i.e.: insert somewhere in the array as long as there is vacant space in the given range.
— Daniel
Quoted 7 lines · Miguel Ojeda
Quoted 3 lines · Tamir Duberstein
Add
Guard::{insert,reserve}andGuard::{insert,reserve}_limit, which are akin to__xa_{alloc,insert}in C.Who will be using this? i.e. we need to justify adding code, typically by mentioning the users.
xa_alloc() / reserve() is used by asahi. It's still using our own abstraction but I'm in the progress of rebase onto the upstream xarray abstractions from v6.16-rc1. Once I'm done I'll reply with "Tested-by:".
Janne
Alice Ryhl
reviewerQuoted 8 lines · Miguel Ojeda
Quoted 3 lines · Tamir Duberstein
Add
Guard::{insert,reserve}andGuard::{insert,reserve}_limit, which are akin to__xa_{alloc,insert}in C.Who will be using this? i.e. we need to justify adding code, typically by mentioning the users.
Rust Binder does have a user for reserve. As for xa_alloc, Rust Binder may end up using it, but the current plan is to use Burak's bitmap work instead.
Alice
Quoted 7 lines · Janne Grunau
Quoted 5 lines · Miguel Ojeda
Quoted 3 lines · Tamir Duberstein
Add
Guard::{insert,reserve}andGuard::{insert,reserve}_limit, which are akin to__xa_{alloc,insert}in C.
Quoted 8 lines
Quoted 2 lines
Who will be using this? i.e. we need to justify adding code, typically by mentioning the users.
xa_alloc()/reserve()is used by asahi. It's still using our own abstraction but I'm in the progress of rebase onto the upstream xarray abstractions from v6.16-rc1. Once I'm done I'll reply with "Tested-by:".Janne
Thanks Janne. I'll wait for your Tested-by before sending v2. Tamir
Quoted 9 lines · Tamir Duberstein
Please see individual patches.
Signed-off-by Tamir Duberstein <[email protected]>---
Tamir Duberstein (3):
rust: xarray: use the prelude
rust: xarray: implement Default for AllocKind
rust: xarray: addinsertandreserve
Quoted 5 lines
include/linux/xarray.h | 2 + lib/xarray.c | 28 ++- rust/helpers/xarray.c | 5 + rust/kernel/xarray.rs | 460 +++++++++++++++++++++++++++++++++++++++++++++++-- 4 files changed, 472 insertions(+), 23 deletions(-)
thanks, series is tested with the asahi driver and works as expected. Usage is limited to ::reserve_limits() and ::fill() of the reservation so only covering a part of the change.
Whole series
Janne