Skip to contentSkip to conversation

rust: xarray: Add an abstraction for XArray

PATCH In review Maíra Canal 7 participants 15 messages Mar 10, 2024 – Mar 26, 2024

Subsystems (4)
lore
Share & tools
lore
#0 lore raw

v8 cover rust: xarray: Add an abstraction for XArray

This abstraction is part of the set of dependencies I need to upstream rustgem, a virtual GEM provider driver in the DRM [1]. Also, this abstraction will be useful for the upstreaming process of the drm/asahi driver.

Best Regards,
- Maíra

Changelog
=========

v1 -> v2: https://lore.kernel.org/r/[email protected]

- Added Pin requirement for all XArray operations, to close a soundness hole due to the lock in the XArray (locks are not safe to move while locked). Creation does not require pinning in place, since the lock cannot be acquired at that point.
- Added safety note to Drop impl about why we don't need to do the lock unlock dance to ensure soundness in case of a dropped lock guard.
- Downstream drm/asahi driver was also rebased on this version to prove it works (previously it was still on a pre-v1 version).
- This still depends on the Error series (v1). v2 of that will need a trivial rename of Error::from_kernel_errno -> Error::from_errno. If this version of XArray ends up looking good, I'll send a trivial v4 of XArray with the rename, after sending the v2 of the Error series.

v2 -> v3: https://lore.kernel.org/r/[email protected]

- Updated to the error v2/v3 series API.
- Renamed err to ret for consistency with the other instance.

v3 -> v4: https://lore.kernel.org/rust-for-linux/[email protected]/

- Rebase on top of rust-next.

v4 -> v5: https://lore.kernel.org/rust-for-linux/[email protected]/T/

- Use Gary's suggestion for the Deref trait - no unsafe code! (Benno Lossin)
- Use NonNull (Benno Lossin)
- Not spelling out the lifetimes (Benno Lossin)
- Change XArray invariants (Benno Lossin)
- Add all SAFETY comments (Benno Lossin)
- Use kernel::error::to_result (Benno Lossin)
- s/alloc_limits/alloc_limits_opt (Benno Lossin)
- Split unsafe block (Benno Lossin)
- Make error handling of the function alloc_limits_opt through ScopeGuard (Benno Lossin)
- Use ScopeGuard in the function get (Benno Lossin)

v5 -> v6: https://lore.kernel.org/rust-for-linux/[email protected]/T/

- Update constants to the new format (RUST_CONST_HELPER)
- Add invariant for self.0 being a pointer derived from T::from_foreign (Benno Lossin)
- Fix the place of the INVARIANT comments (Benno Lossin)
- Use the Pin-Init API (Benno Lossin)
- Remove PhantomPinned from XArray (Benno Lossin)
- Add new requirements for calling xa_unlock() (Benno Lossin)
- Improve SAFETY comments (Benno Lossin)
- Split unsafe block (Benno Lossin)
- s/alloc_limits_opt/insert_between (Benno Lossin)
- Specify the target type of the cast (Andreas Hindborg/Trevor Gross)
- Guarantee that T is 4-byte aligned (Andreas Hindborg)
- Add code examples in the code (Boqun Feng)

v6 -> v7: https://lore.kernel.org/rust-for-linux/[email protected]/T/

- Change the INVARIANT from Guard (Boqun Feng)
- Change the INVARIANT from XArray (Boqun Feng)
- Change INVARIANT to # Invariant (Benno Lossin)
- Move XArray definition to the top of the file (Benno Lossin)
- Show structs from examples (Benno Lossin)
- Import XArray directly (Benno Lossin)
- Adjust some SAFETY comments (Benno Lossin & Alice Ryhl)
- Reestructure the NonNull block (Alice Ryhl)
- Create method to_index() (Alice Ryhl)
- Use drop(T::from_foreign(new)) (Alice Ryhl)
- Both Sync and Send requires Send (Alice Ryhl)
- Add FOREIGN_ALIGN to trait ForeignOwnable (Alice Ryhl)

v7 -> v8: https://lore.kernel.org/rust-for-linux/[email protected]/T/

* Fix clippy complains (Andreas Hindborg)
* Move semicolon outside of the unsafe block (Alice Ryhl)
* Remove PhantomData from Reservation (Alice Ryhl)
* Add drop call in insert_between (Alice Ryhl)
* Use "# Invariants" on the XArray struct (Alice Ryhl)
* Don't mention that you use pin-init to make self.xa be initialized and valid. (Alice Ryhl)
* Change Guard NonNull<T> to NonNull<c_void>, since that's the type used by into_foreign (Alice Ryhl)
* Migrate the C header to the new srctree/ notation (Miguel Ojeda)
* Keep comments at 100 columns (Miguel Ojeda)
* Use intra-doc links where possible (Miguel Ojeda)
* Misc fixes in the comments (Miguel Ojeda)

[1] https://github.com/mairacanal/linux/pull/11

Asahi Lina (1):
rust: xarray: Add an abstraction for XArray

Maíra Canal (1):
rust: types: add FOREIGN_ALIGN to ForeignOwnable

 rust/bindings/bindings_helper.h |  17 ++
 rust/helpers.c                  |  37 +++
 rust/kernel/lib.rs              |   1 +
 rust/kernel/sync/arc.rs         |   2 +
 rust/kernel/types.rs            |   7 +
 rust/kernel/xarray.rs           | 407 ++++++++++++++++++++++++++++++++
 6 files changed, 471 insertions(+)
 create mode 100644 rust/kernel/xarray.rs

--
2.43.0

#1 lore raw

PATCH v8 1/2 rust: types: add FOREIGN_ALIGN to ForeignOwnable

There are cases where we need to check the alignment of the pointers returned by into_foreign. Currently, this is not possible to be done at build time. Therefore, add a property to the trait ForeignOwnable, which specifies the alignment of the pointers returned by into_foreign.

---
 rust/kernel/sync/arc.rs | 2 ++
 rust/kernel/types.rs    | 7 +++++++
 2 files changed, 9 insertions(+)
rust/kernel/sync/arc.rs +2 -0
index 7d4c4bf58388..da5c8cc325b6 100644
@@ -274,6 +274,8 @@ pub fn ptr_eq(this: &Self, other: &Self) -> bool {
 }
 
 impl<T: 'static> ForeignOwnable for Arc<T> {
+    const FOREIGN_ALIGN: usize = core::mem::align_of::<ArcInner<T>>();
+
     type Borrowed<'a> = ArcBorrow<'a, T>;
 
     fn into_foreign(self) -> *const core::ffi::c_void {
rust/kernel/types.rs +7 -0
index aa77bad9bce4..76cd4226dd35 100644
@@ -20,6 +20,9 @@
 /// This trait is meant to be used in cases when Rust objects are stored in C objects and
 /// eventually "freed" back to Rust.
 pub trait ForeignOwnable: Sized {
+    /// The alignment of pointers returned by `into_foreign`.
+    const FOREIGN_ALIGN: usize;
+
     /// Type of values borrowed between calls to [`ForeignOwnable::into_foreign`] and
     /// [`ForeignOwnable::from_foreign`].
     type Borrowed<'a>;
@@ -68,6 +71,8 @@ unsafe fn try_from_foreign(ptr: *const core::ffi::c_void) -> Option<Self> {
 }
 
 impl<T: 'static> ForeignOwnable for Box<T> {
+    const FOREIGN_ALIGN: usize = core::mem::align_of::<T>();
+
     type Borrowed<'a> = &'a T;
 
     fn into_foreign(self) -> *const core::ffi::c_void {
@@ -90,6 +95,8 @@ unsafe fn from_foreign(ptr: *const core::ffi::c_void) -> Self {
 }
 
 impl ForeignOwnable for () {
+    const FOREIGN_ALIGN: usize = core::mem::align_of::<()>();
+
     type Borrowed<'a> = ();
 
     fn into_foreign(self) -> *const core::ffi::c_void {

--
2.43.0

#2 lore raw

Re: [PATCH v8 1/2] rust: types: add FOREIGN_ALIGN to ForeignOwnable

Quoted 33 lines · Maíra Canal

There are cases where we need to check the alignment of the pointers returned by into_foreign. Currently, this is not possible to be done at build time. Therefore, add a property to the trait ForeignOwnable, which specifies the alignment of the pointers returned by into_foreign.

---
  rust/kernel/sync/arc.rs | 2 ++
  rust/kernel/types.rs    | 7 +++++++
  2 files changed, 9 insertions(+)
rust/kernel/sync/arc.rs +2 -0
index 7d4c4bf58388..da5c8cc325b6 100644
@@ -274,6 +274,8 @@ pub fn ptr_eq(this: &Self, other: &Self) -> bool {
  }
 
  impl<T: 'static> ForeignOwnable for Arc<T> {
+    const FOREIGN_ALIGN: usize = core::mem::align_of::<ArcInner<T>>();
+
      type Borrowed<'a> = ArcBorrow<'a, T>;
 
      fn into_foreign(self) -> *const core::ffi::c_void {
rust/kernel/types.rs +0 -0
index aa77bad9bce4..76cd4226dd35 100644

rust/kernel/types.rs line 25

Quoted 6 lines
rust/kernel/types.rs +3 -0
@@ -20,6 +20,9 @@
  /// This trait is meant to be used in cases when Rust objects are stored in C objects and
  /// eventually "freed" back to Rust.
  pub trait ForeignOwnable: Sized {
+    /// The alignment of pointers returned by `into_foreign`.
+    const FOREIGN_ALIGN: usize;
+

I think we need to make the trait unsafe, since we want unsafe code to be able to rely on this value being correct.

Signature · 2 lines
Cheers,
Benno
Quoted 24 lines
rust/kernel/types.rs +4 -1
      /// Type of values borrowed between calls to [`ForeignOwnable::into_foreign`] and
      /// [`ForeignOwnable::from_foreign`].
      type Borrowed<'a>;
@@ -68,6 +71,8 @@ unsafe fn try_from_foreign(ptr: *const core::ffi::c_void) -> Option<Self> {
  }
 
  impl<T: 'static> ForeignOwnable for Box<T> {
+    const FOREIGN_ALIGN: usize = core::mem::align_of::<T>();
+
      type Borrowed<'a> = &'a T;
 
      fn into_foreign(self) -> *const core::ffi::c_void {
@@ -90,6 +95,8 @@ unsafe fn from_foreign(ptr: *const core::ffi::c_void) -> Self {
  }
 
  impl ForeignOwnable for () {
+    const FOREIGN_ALIGN: usize = core::mem::align_of::<()>();
+
      type Borrowed<'a> = ();
 
      fn into_foreign(self) -> *const core::ffi::c_void {
--

2.43.0

#3 lore raw

PATCH v8 2/2 rust: xarray: Add an abstraction for XArray

In reply to Maíra Canal

From: Asahi Lina <[email protected]>

The XArray is an abstract data type which behaves like a very large array of pointers. Add a Rust abstraction for this data type.

The initial implementation uses explicit locking on get operations and returns a guard which blocks mutation, ensuring that the referenced object remains alive. To avoid excessive serialization, users are expected to use an inner type that can be efficiently cloned (such as Arc<T>), and eagerly clone and drop the guard to unblock other users after a lookup.

Future variants may support using RCU instead to avoid mutex locking.

This abstraction also introduces a reservation mechanism, which can be used by alloc-capable XArrays to reserve a free slot without immediately filling it, and then do so at a later time. If the reservation is dropped without being filled, the slot is freed again for other users, which eliminates the need for explicit cleanup code.

---
 rust/bindings/bindings_helper.h |  17 ++
 rust/helpers.c                  |  37 +++
 rust/kernel/lib.rs              |   1 +
 rust/kernel/xarray.rs           | 407 ++++++++++++++++++++++++++++++++
 4 files changed, 462 insertions(+)
 create mode 100644 rust/kernel/xarray.rs
rust/bindings/bindings_helper.h +17 -0
index 65b98831b975..7a6be07038ce 100644
@@ -17,8 +17,25 @@
 #include <linux/slab.h>
 #include <linux/wait.h>
 #include <linux/workqueue.h>
+#include <linux/xarray.h>
 
 /* `bindgen` gets confused at certain things. */
 const size_t RUST_CONST_HELPER_ARCH_SLAB_MINALIGN = ARCH_SLAB_MINALIGN;
 const gfp_t RUST_CONST_HELPER_GFP_KERNEL = GFP_KERNEL;
 const gfp_t RUST_CONST_HELPER___GFP_ZERO = __GFP_ZERO;
+
+const gfp_t RUST_CONST_HELPER_XA_FLAGS_LOCK_IRQ = XA_FLAGS_LOCK_IRQ;
+const gfp_t RUST_CONST_HELPER_XA_FLAGS_LOCK_BH = XA_FLAGS_LOCK_BH;
+const gfp_t RUST_CONST_HELPER_XA_FLAGS_TRACK_FREE = XA_FLAGS_TRACK_FREE;
+const gfp_t RUST_CONST_HELPER_XA_FLAGS_ZERO_BUSY = XA_FLAGS_ZERO_BUSY;
+const gfp_t RUST_CONST_HELPER_XA_FLAGS_ALLOC_WRAPPED = XA_FLAGS_ALLOC_WRAPPED;
+const gfp_t RUST_CONST_HELPER_XA_FLAGS_ACCOUNT = XA_FLAGS_ACCOUNT;
+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 xa_mark_t RUST_CONST_HELPER_XA_MARK_0 = XA_MARK_0;
+const xa_mark_t RUST_CONST_HELPER_XA_MARK_1 = XA_MARK_1;
+const xa_mark_t RUST_CONST_HELPER_XA_MARK_2 = XA_MARK_2;
+const xa_mark_t RUST_CONST_HELPER_XA_PRESENT = XA_PRESENT;
+const xa_mark_t RUST_CONST_HELPER_XA_MARK_MAX = XA_MARK_MAX;
+const xa_mark_t RUST_CONST_HELPER_XA_FREE_MARK = XA_FREE_MARK;
rust/helpers.c +37 -0
index 70e59efd92bc..72a7f9c596ad 100644
@@ -31,6 +31,7 @@
 #include <linux/spinlock.h>
 #include <linux/wait.h>
 #include <linux/workqueue.h>
+#include <linux/xarray.h>
 
 __noreturn void rust_helper_BUG(void)
 {
@@ -157,6 +158,42 @@ void rust_helper_init_work_with_key(struct work_struct *work, work_func_t func,
 }
 EXPORT_SYMBOL_GPL(rust_helper_init_work_with_key);
 
+void rust_helper_xa_init_flags(struct xarray *xa, gfp_t flags)
+{
+	xa_init_flags(xa, flags);
+}
+EXPORT_SYMBOL_GPL(rust_helper_xa_init_flags);
+
+bool rust_helper_xa_empty(struct xarray *xa)
+{
+	return xa_empty(xa);
+}
+EXPORT_SYMBOL_GPL(rust_helper_xa_empty);
+
+int rust_helper_xa_alloc(struct xarray *xa, u32 *id, void *entry, struct xa_limit limit, gfp_t gfp)
+{
+	return xa_alloc(xa, id, entry, limit, gfp);
+}
+EXPORT_SYMBOL_GPL(rust_helper_xa_alloc);
+
+void rust_helper_xa_lock(struct xarray *xa)
+{
+	xa_lock(xa);
+}
+EXPORT_SYMBOL_GPL(rust_helper_xa_lock);
+
+void rust_helper_xa_unlock(struct xarray *xa)
+{
+	xa_unlock(xa);
+}
+EXPORT_SYMBOL_GPL(rust_helper_xa_unlock);
+
+int rust_helper_xa_err(void *entry)
+{
+	return xa_err(entry);
+}
+EXPORT_SYMBOL_GPL(rust_helper_xa_err);
+
 /*
  * `bindgen` binds the C `size_t` type as the Rust `usize` type, so we can
  * use it in contexts where Rust expects a `usize` like slice (array) indices.
rust/kernel/lib.rs +1 -0
index be68d5e567b1..ec7e5b5c2d0a 100644
@@ -50,6 +50,7 @@
 pub mod time;
 pub mod types;
 pub mod workqueue;
+pub mod xarray;
 
 #[doc(hidden)]
 pub use bindings;
rust/kernel/xarray.rs new file +407 -0

407 lines not on this page · raw message

Signature · 1 line
2.43.0
maintainer Reviewed-by on v8 2/2
#4 lore raw
Quoted 21 lines · Maíra Canal

From: Asahi Lina <[email protected]>

The XArray is an abstract data type which behaves like a very large array of pointers. Add a Rust abstraction for this data type.

The initial implementation uses explicit locking on get operations and returns a guard which blocks mutation, ensuring that the referenced object remains alive. To avoid excessive serialization, users are expected to use an inner type that can be efficiently cloned (such as Arc<T>), and eagerly clone and drop the guard to unblock other users after a lookup.

Future variants may support using RCU instead to avoid mutex locking.

This abstraction also introduces a reservation mechanism, which can be used by alloc-capable XArrays to reserve a free slot without immediately filling it, and then do so at a later time. If the reservation is dropped without being filled, the slot is freed again for other users, which eliminates the need for explicit cleanup code.

Quoted 4 lines

Overall looks good to me.

rust/kernel/xarray.rs line 317

Quoted 6 lines
rust/kernel/xarray.rs new file +6 -0
+        if ret < 0 {
+            Err(Error::from_errno(ret))
+        } else {
+            guard.dismiss();
+            Ok(id as usize)
+        }

You could make this easier to read using to_result.

to_result(ret)?;
guard.dismiss();
Ok(id as usize)

Alice

#5 lore raw
Quoted 46 lines · Alice Ryhl
Quoted 28 lines · Maíra Canal

From: Asahi Lina <[email protected]>

The XArray is an abstract data type which behaves like a very large array of pointers. Add a Rust abstraction for this data type.

The initial implementation uses explicit locking on get operations and
returns a guard which blocks mutation, ensuring that the referenced object remains alive. To avoid excessive serialization, users are expected to use an inner type that can be efficiently cloned (such as
Arc<T>), and eagerly clone and drop the guard to unblock other users
after a lookup.

Future variants may support using RCU instead to avoid mutex locking.

This abstraction also introduces a reservation mechanism, which can be
used by alloc-capable XArrays to reserve a free slot without immediately
filling it, and then do so at a later time. If the reservation is dropped without being filled, the slot is freed again for other users,
which eliminates the need for explicit cleanup code.

Quoted 4 lines

Overall looks good to me.

Quoted 6 lines

+        if ret < 0 {
+            Err(Error::from_errno(ret))
+        } else {
+            guard.dismiss();
+            Ok(id as usize)
+        }

Quoted 5 lines

You could make this easier to read using to_result.

to_result(ret)?;
guard.dismiss();
Ok(id as usize)

My 2 cents, I'd go for classic kernel style:

if ret < 0 {
    return Err(...);
}

guard.dismiss();
Ok(id as usize)

P.

Quoted 3 lines

Alice

#6 lore raw

On 3/19/24 2:32 AM, Philipp Stanner wrote:
...

Quoted 17 lines
Quoted 8 lines
Quoted 7 lines

+        if ret < 0 {
+            Err(Error::from_errno(ret))
+        } else {
+            guard.dismiss();
+            Ok(id as usize)
+        }

Quoted 5 lines

You could make this easier to read using to_result.

to_result(ret)?;
guard.dismiss();
Ok(id as usize)

My 2 cents, I'd go for classic kernel style:

Quoted 7 lines
if ret < 0 {
     return Err(...);
}

guard.dismiss();
Ok(id as usize)

Yes.

As a "standard" C-based kernel person who is trying to move into Rust for Linux, I hereby invoke my Rust-newbie powers to confirm that the "clasic kernel style" above goes into my head much faster and easier, yes. :)

I hope I'm not violating any "this is how Rust idioms must be" conventions. But if not, then all other things being equal, it is of course a nice touch to make the code more readable to the rest of the kernel folks.

thanks,

Signature · 2 lines
John Hubbard
NVIDIA
#7 lore raw
Quoted 27 lines · John Hubbard

On 3/19/24 2:32 AM, Philipp Stanner wrote:
...

Quoted 17 lines
Quoted 8 lines
Quoted 7 lines

+        if ret < 0 {
+            Err(Error::from_errno(ret))
+        } else {
+            guard.dismiss();
+            Ok(id as usize)
+        }

Quoted 5 lines

You could make this easier to read using to_result.

to_result(ret)?;
guard.dismiss();
Ok(id as usize)

My 2 cents, I'd go for classic kernel style:

Quoted 7 lines
if ret < 0 {
     return Err(...);
}

guard.dismiss();
Ok(id as usize)

Quoted 7 lines

Yes.

As a "standard" C-based kernel person who is trying to move into Rust for Linux, I hereby invoke my Rust-newbie powers to confirm that the "clasic kernel style" above goes into my head much faster and easier, yes. :)

Hope I'm still belong to a "standard C-based kernel person" ;-) My problem on "if ret < 0 { ... }" is: what's the type of "ret", and is it "negative means failure" or "non-zero means failure"? Now for this particular code, the assignment of "ret" and the use of "ret" is pretty close, so it doesn't matter. But in the code where "ret" is used for multiple function calls and there is code in-between, then I'd prefer we use to_result (i.e. Result type and question mark operator).

Quoted 5 lines

I hope I'm not violating any "this is how Rust idioms must be" conventions. But if not, then all other things being equal, it is of course a nice touch to make the code more readable to the rest of the kernel folks.

One more extra point from myself only: if one is using Rust for drivers or subsystem they are going to take care of it in the future, it's totally fine for them to pick coding styles that they feel comfortable, I don't want to make people who do the real work feel frustrated because "this is how Rust idioms must be", also I don't believe tools should restrict people. But in the "kernel" crate (i.e. for core kernel part), I want to make it "Rusty" since it's the point of the experiement ("you asked for it ;-)).

Hope we can find a balanced point when we learn more and more ;-)

Regards,
Boqun

Quoted 6 lines

thanks,

Signature · 2 lines
John Hubbard
NVIDIA
#8 lore raw
Quoted 36 lines · Boqun Feng
Quoted 27 lines · John Hubbard

On 3/19/24 2:32 AM, Philipp Stanner wrote:
...

Quoted 17 lines
Quoted 8 lines
Quoted 7 lines

+        if ret < 0 {
+            Err(Error::from_errno(ret))
+        } else {
+            guard.dismiss();
+            Ok(id as usize)
+        }

Quoted 5 lines

You could make this easier to read using to_result.

to_result(ret)?;
guard.dismiss();
Ok(id as usize)

My 2 cents, I'd go for classic kernel style:

Quoted 7 lines
if ret < 0 {
      return Err(...);
}

guard.dismiss();
Ok(id as usize)

Quoted 7 lines

Yes.

As a "standard" C-based kernel person who is trying to move into Rust for Linux, I hereby invoke my Rust-newbie powers to confirm that the "clasic kernel style" above goes into my head much faster and easier, yes. :)

Quoted 7 lines

Hope I'm still belong to a "standard C-based kernel person" ;-) My problem on "if ret < 0 { ... }" is: what's the type of "ret", and is it "negative means failure" or "non-zero means failure"? Now for this particular code, the assignment of "ret" and the use of "ret" is pretty close, so it doesn't matter. But in the code where "ret" is used for multiple function calls and there is code in-between, then I'd prefer we use to_result (i.e. Result type and question mark operator).

No argument there. I was more focused on the readability of: do a clean check for failure, and returning directly in that case. And then continuing on with non-failure-case code. The to_result() part makes sense and can fit right into that.

Quoted 6 lines
Quoted 5 lines

I hope I'm not violating any "this is how Rust idioms must be" conventions. But if not, then all other things being equal, it is of course a nice touch to make the code more readable to the rest of the kernel folks.

Quoted 9 lines

One more extra point from myself only: if one is using Rust for drivers or subsystem they are going to take care of it in the future, it's totally fine for them to pick coding styles that they feel comfortable, I don't want to make people who do the real work feel frustrated because "this is how Rust idioms must be", also I don't believe tools should restrict people. But in the "kernel" crate (i.e. for core kernel part), I want to make it "Rusty" since it's the point of the experiement ("you asked for it ;-)).

OK, I understand that reasoning.

Quoted 1 line

Hope we can find a balanced point when we learn more and more ;-)

Yes. And to continue with the metaphor, I'm attempting here to put a light thumb on the scale. :)

thanks,

Signature · 2 lines
John Hubbard
NVIDIA
#9 lore raw
In reply to Boqun Feng
Quoted 39 lines · Boqun Feng
Quoted 29 lines · John Hubbard

On 3/19/24 2:32 AM, Philipp Stanner wrote:
...

Quoted 17 lines
Quoted 8 lines
Quoted 7 lines

+        if ret < 0 {
+            Err(Error::from_errno(ret))
+        } else {
+            guard.dismiss();
+            Ok(id as usize)
+        }

Quoted 5 lines

You could make this easier to read using to_result.

to_result(ret)?;
guard.dismiss();
Ok(id as usize)

My 2 cents, I'd go for classic kernel style:

Quoted 7 lines

if ret < 0 {
     return Err(...);
}

guard.dismiss();
Ok(id as usize)

Yes.

Quoted 8 lines

As a "standard" C-based kernel person who is trying to move into Rust
for Linux, I hereby invoke my Rust-newbie powers to confirm that the
"clasic kernel style" above goes into my head much faster and easier,
yes. :)

Quoted 10 lines

Hope I'm still belong to a "standard C-based kernel person" ;-) My problem on "if ret < 0 { ... }" is: what's the type of "ret", and is it
"negative means failure" or "non-zero means failure"? Now for this particular code, the assignment of "ret" and the use of "ret" is pretty
close, so it doesn't matter. But in the code where "ret" is used for multiple function calls and there is code in-between, then I'd prefer we
use to_result (i.e. Result type and question mark operator).

Yeah, the issue we're running into here is that it's a quite different way of programming since you create bindings on the fly with let.

I actually think it would be nice to have variable declarations at the top of the functions, but that would obviously very frequently collide with Rust's concept of data being immutable by default.

Regarding our example, my hope would be that if ret < 0 should always be fine, because, what else could it be? A float? And such patterns should only appear where you interact with C, since pure Rust should definitely always have all result status packed in Result or Option.

Quoted 9 lines
Quoted 8 lines

I hope I'm not violating any "this is how Rust idioms must be" conventions. But if not, then all other things being equal, it is of
course a nice touch to make the code more readable to the rest of the
kernel folks.

Quoted 9 lines

One more extra point from myself only: if one is using Rust for drivers
or subsystem they are going to take care of it in the future, it's totally fine for them to pick coding styles that they feel comfortable,
I don't want to make people who do the real work feel frustrated because
"this is how Rust idioms must be", also I don't believe tools should restrict people.

I'm very happy to hear that we're on sync here :)

Though there will be a lot to be discussed and done. As I see it, so far the clippy rules for example are global, aren't they?

In any case I don't even think they shouldn't be global, but that they should behave more like checkpatch.

I think the ideal end result would be one where we have rules and enforcement similar to how it's done in C:
C has checkpatch, which fires errors for some things, and warnings for others. And, if it makes sense, you or the maintainer can ignore the warning.

When the build chain checks global rules we can't really ignore any rule without some kind of annotation in the code, because otherwise we'd permanently spam the build log

Quoted 6 lines

But in the "kernel" crate (i.e. for core kernel part),
I want to make it "Rusty" since it's the point of the experiement ("you
asked for it ;-)).

Hope we can find a balanced point when we learn more and more ;-)

Yeah, I get where that comes from. Many new languages attempt to end endless style discussions etc. by axiomatically defining a canonical style.

But we're living in this special world called kernel with its own laws of physics so to speak. To some degree we already have to use a "dialect / flavor" of Rust (CStr, try_push()?)
Will be interesting to see how it all plays out for us once the users and use cases increase in number more and more

Many greetings,
P.

Quoted 11 lines

Regards,
Boqun

Quoted 6 lines

thanks,

Signature · 2 lines
John Hubbard
NVIDIA
#10 lore raw
Quoted 4 lines · Philipp Stanner

I actually think it would be nice to have variable declarations at the top of the functions, but that would obviously very frequently collide with Rust's concept of data being immutable by default.

It is true that deferring bindings sometimes allows for more immutability (this also applies to kernel C to some degree with variables at the top, by the way). However, it is more about other things like when new objects can be constructed (when can invariants be set), when destructors run and in what order, even the type itself (rebinding).

But it is not just this (where to place variables/bindings) -- there are other kernel C guidelines that do not make sense for Rust, and trying to apply them is a bad idea.

Where possible and where it makes sense, we should try to keep it consistent, of course. For instance, naming concerns have been discussed many times (avoiding different names for existing things) -- that can be indeed be confusing and introduce mental overhead, and thus we try to avoid it, even if sometimes it may have been locally the best solution.

Quoted 2 lines

Regarding our example, my hope would be that if ret < 0 should always be fine, because, what else could it be? A float?

I think one of the things Boqun was referring to were the semantics of the value, which is why one advantage of to_result is that, when dealing with a C function that does not follow the usual pattern, it stands out more.

Quoted 4 lines

I'm very happy to hear that we're on sync here :)

Though there will be a lot to be discussed and done. As I see it, so far the clippy rules for example are global, aren't they?

Yeah, and that is intentional.

Of course, as with anything else, there can be exceptions where they make sense. But the point is to avoid diverging in how we write the code in different parts of the kernel unless there is a good reason.

This is essentially the same as the formatting discussion. The flags for rustfmt, Clippy or the compiler diagnostics can and will change to try to come up with the optimal set as we learn more (and as new flags appear or if they change behavior in a way that we didn't expect -- hopefully not -- etc.), but they should be consistent for the entire kernel, except where there is a good reason not to.

Quoted 5 lines

I think the ideal end result would be one where we have rules and enforcement similar to how it's done in C:
C has checkpatch, which fires errors for some things, and warnings for others. And, if it makes sense, you or the maintainer can ignore the warning.

I may not be understanding this part, but that is already the case, no?

In any case, I am not sure we should look at checkpatch.pl as a reference here, because it is a tool that we apply against patches, i.e. something done at a given point in time once against "ephemeral" entities.

In other words, it is always possible to ignore any and all of its warnings/errors, at the discretion of the maintainer, and thus it is not as big of a deal to have false positives for the checks (in fact, it is good that it does, because it allows checkpatch.pl more leeway to catch more issues).

We could have different sets like with W=, though, including perhaps one for "development" where it is even more relaxed (e.g. no missing documentation warning).

Quoted 3 lines

When the build chain checks global rules we can't really ignore any rule without some kind of annotation in the code, because otherwise we'd permanently spam the build log

That is the intention, i.e. that they are enforced as much as reasonably possible, but one can still ignore the rule if really needed (and even better, one can do it as locally as possible, e.g. right at the item that requires it instead of file-wide).

Quoted 9 lines

Yeah, I get where that comes from. Many new languages attempt to end endless style discussions etc. by axiomatically defining a canonical style.

But we're living in this special world called kernel with its own laws of physics so to speak. To some degree we already have to use a "dialect / flavor" of Rust (CStr, try_push()?)
Will be interesting to see how it all plays out for us once the users and use cases increase in number more and more

The "dialect" you are speaking about is global for the kernel. That is completely fine, and as you say, needed in some aspects.

But what we do not want is to end up with different "dialects" within the kernel, unless there is a very good reason for exceptional cases.

Cheers,
Miguel

#11 lore raw
Quoted 28 lines · Miguel Ojeda
Quoted 6 lines · Philipp Stanner

I actually think it would be nice to have variable declarations at the
top of the functions, but that would obviously very frequently collide
with Rust's concept of data being immutable by default.

It is true that deferring bindings sometimes allows for more immutability (this also applies to kernel C to some degree with variables at the top, by the way). However, it is more about other things like when new objects can be constructed (when can invariants be set), when destructors run and in what order, even the type itself (rebinding).

But it is not just this (where to place variables/bindings) -- there are other kernel C guidelines that do not make sense for Rust, and trying to apply them is a bad idea.

Where possible and where it makes sense, we should try to keep it consistent, of course. For instance, naming concerns have been discussed many times (avoiding different names for existing things) - -
that can be indeed be confusing and introduce mental overhead, and thus we try to avoid it, even if sometimes it may have been locally the best solution.

Quoted 8 lines
Quoted 2 lines

Regarding our example, my hope would be that if ret < 0 should always be fine, because, what else could it be? A float?

I think one of the things Boqun was referring to were the semantics of
the value, which is why one advantage of to_result is that, when dealing with a C function that does not follow the usual pattern, it stands out more.

You mean if ret was a pointer that, consequently, would have to be checked for equality rather then for less-than 0?

Quoted 29 lines
Quoted 6 lines

I'm very happy to hear that we're on sync here :)

Though there will be a lot to be discussed and done. As I see it, so
far the clippy rules for example are global, aren't they?

Yeah, and that is intentional.

Of course, as with anything else, there can be exceptions where they make sense. But the point is to avoid diverging in how we write the code in different parts of the kernel unless there is a good reason.

This is essentially the same as the formatting discussion. The flags for rustfmt, Clippy or the compiler diagnostics can and will change to try to come up with the optimal set as we learn more (and as new flags appear or if they change behavior in a way that we didn't expect
-- hopefully not -- etc.), but they should be consistent for the entire kernel, except where there is a good reason not to.

Quoted 7 lines

I think the ideal end result would be one where we have rules and enforcement similar to how it's done in C:
C has checkpatch, which fires errors for some things, and warnings for
others. And, if it makes sense, you or the maintainer can ignore the
warning.

Quoted 2 lines

I may not be understanding this part, but that is already the case, no?

The difference is that checkpatch is an additional tool that is not tied to the compiler or build chain.

Quoted 18 lines

In any case, I am not sure we should look at checkpatch.pl as a reference here, because it is a tool that we apply against patches, i.e. something done at a given point in time once against "ephemeral" entities.

In other words, it is always possible to ignore any and all of its warnings/errors, at the discretion of the maintainer, and thus it is not as big of a deal to have false positives for the checks (in fact, it is good that it does, because it allows checkpatch.pl more leeway
to catch more issues).

We could have different sets like with W=, though, including perhaps
one for "development" where it is even more relaxed (e.g. no missing documentation warning).

Quoted 8 lines
Quoted 3 lines

When the build chain checks global rules we can't really ignore any rule without some kind of annotation in the code, because otherwise we'd permanently spam the build log

That is the intention, i.e. that they are enforced as much as reasonably possible, but one can still ignore the rule if really needed (and even better, one can do it as locally as possible, e.g. right at the item that requires it instead of file-wide).

Yes, and I think that shouldn't be done. The C coding guideline is more of a recommendation.

Nothing in C complains about you doing a return; over a goto out;. The current setting, however, would fire warnings (or isn't it even classified as a build error?) if you add return in Rust at the end of a code path.

I believe that memory-safety-related mechanisms and rules should be "enforced as much as reasonably possible", because that's the entire point of Rust in the kernel.

Everything else should in my opinion be as free as in C.

Quoted 15 lines
Quoted 7 lines

Yeah, I get where that comes from. Many new languages attempt to end
endless style discussions etc. by axiomatically defining a canonical
style.

Quoted 7 lines

But we're living in this special world called kernel with its own laws
of physics so to speak. To some degree we already have to use a "dialect / flavor" of Rust (CStr, try_push()?)
Will be interesting to see how it all plays out for us once the users
and use cases increase in number more and more

Quoted 6 lines

The "dialect" you are speaking about is global for the kernel. That is
completely fine, and as you say, needed in some aspects.

But what we do not want is to end up with different "dialects" within the kernel, unless there is a very good reason for exceptional cases.

Agreed, that should be global.

In fact, almost everything should be global.

The only thing we don't agree on is what should be a per-default strictly enforced rule, and what should be a recommendation.

P.

Quoted 4 lines

Cheers,
Miguel

#12 lore raw
Quoted 3 lines · Philipp Stanner

You mean if ret was a pointer that, consequently, would have to be checked for equality rather then for less-than 0?

No, I meant a C function that happens to return an int with different semantics (e.g. encoding for the error) than the usual ones (Rust does not allow to compare a raw pointer with an integer).

Quoted 2 lines

The difference is that checkpatch is an additional tool that is not tied to the compiler or build chain.

Perhaps a better comparison would be Sparse or Coccinelle then? (i.e. in that we ideally would test the source code, not the patches, all the time).

In any case, if you mean to have kernel-only lints, Gary created klint
[1] for that and Julia and Tathagata announced Coccinelle for Rust [2] some months ago.

We hope we can start putting these tools into good use soon (not to say they are not useful already, e.g. klint already found actual issues in the past), ideally running them all the time for all code.

Unless you mean replicating all the compiler diagnostics -- that is not really feasible (bandwidth-wise) and I am not sure what we would gain in practice. We don't do that either for kernel C.

[1] https://rust-for-linux.com/klint
[2] https://rust-for-linux.com/coccinelle-for-rust

Quoted 2 lines

Yes, and I think that shouldn't be done. The C coding guideline is more of a recommendation.

Kernel C is quite consistent (relative to what you could randomly do in C), even including the big differences from some subsystems. So, in practice, some of the guidelines are rules.

For Rust, we had the chance to be even more consistent (thanks to having the tooling available from the start), and we went for that, because we see that as a good thing that will pay off long term.

Cheers,
Miguel

#13 lore raw
In reply to Boqun Feng
Quoted 9 lines · Boqun Feng

One more extra point from myself only: if one is using Rust for drivers or subsystem they are going to take care of it in the future, it's totally fine for them to pick coding styles that they feel comfortable, I don't want to make people who do the real work feel frustrated because "this is how Rust idioms must be", also I don't believe tools should restrict people. But in the "kernel" crate (i.e. for core kernel part), I want to make it "Rusty" since it's the point of the experiement ("you asked for it ;-)).

We should aim to be as consistent as possible for all the kernel, not just the "core kernel".

Yes, there should be flexibility. In fact, sometimes it is just impossible, unreasonable, impractical and/or annoying to be consistent. And, as you say, we should definitely avoid making people frustrated for inane reasons.

But we should not introduce flexibility for bad reasons either.

And this is the kind of thing that it is very hard to restrict later. So even if we are a bit "over the top" in some cases now (the current compiler/Clippy flags could be already arguably so, at times), the point is to figure out what makes sense to keep long term. In other words, instead of discussing how to create local coding styles, we should be discussing what should be changed for everybody (e.g. because a particular diagnostic may too annoying now, because a style is found to be better than another like if ret < 0 ... vs. to_result and so on).

Cheers,
Miguel

#14 lore raw
In reply to Maíra Canal

On 3/10/24 00:57, Maíra Canal wrote:

[...]

rust/kernel/xarray.rs line 88

Quoted 6 lines
rust/kernel/xarray.rs new file +6 -0
+// Convenience impl for [`ForeignOwnable`] types whose [`Borrowed`] form
+// implements [`Deref`].
+impl<'a, T: ForeignOwnable> Deref for Guard<'a, T>
+where
+    T::Borrowed<'a>: Deref,
+    for<'b> T::Borrowed<'b>: Into<&'b <T::Borrowed<'a> as Deref>::Target>,

I took a look at this again and it currently is not really helpful. ArcBorrow<'b, T> does not implement Into<&'b T> and it never is going to, since it is impossible due to Rust's orphan rules. We have two options:
1. Remove this impl.
2. Create a IntoRef trait that does the job instead and implement it for ArcBorrow.

If you go for option 2, I think IntoRef should look like this:

     pub trait IntoRef<'a, T: ?Sized> {
         fn into_ref(self) -> &'a T;
     }

But this can also easily be done in a future patch, so feel free to choose option 1.

rust/kernel/xarray.rs line 100

Quoted 12 lines
rust/kernel/xarray.rs new file +12 -0
+{
+    type Target = <T::Borrowed<'a> as Deref>::Target;
+
+    fn deref(&self) -> &Self::Target {
+        self.borrow().into()
+    }
+}
+
+impl<'a, T: ForeignOwnable> Drop for Guard<'a, T> {
+    fn drop(&mut self) {
+        // SAFETY: By the type invariant, we own the [`XArray`] lock, so we must
+        // unlock it here.

I think the "so we must unlock it here" part is unnecessary.

Quoted 3 lines
rust/kernel/xarray.rs new file +3 -0
+        unsafe { bindings::xa_unlock(self.1.xa.get()) };
+    }
+}

[...]

Quoted 24 lines
rust/kernel/xarray.rs new file +24 -0
+/// # Examples
+///
+/// ```rust
+/// use kernel::xarray::{XArray, flags};
+/// use kernel::sync::Arc;
+///
+/// struct Foo {
+///     a: u32,
+///     b: u32,
+/// }
+///
+/// let arr = Box::pin_init(XArray::<Arc<Foo>>::new(flags::ALLOC1))?;
+///
+/// let item = Arc::try_new(Foo { a : 1, b: 2 })?;
+/// let index = arr.alloc(item)?;
+///
+/// if let Some(guard) = arr.get_locked(index) {
+///     assert_eq!(guard.borrow().a, 1);
+///     assert_eq!(guard.borrow().b, 2);
+/// } else {
+///     pr_info!("No value found in index {}", index);
+/// }
+///
+/// let item = Arc::try_new(Foo { a : 3, b: 4 })?;

rust/kernel/xarray.rs line 174

Quoted 10 lines
rust/kernel/xarray.rs new file +10 -0
+/// let index = arr.alloc(item)?;
+///
+/// if let Some(removed_data) = arr.remove(index) {
+///     assert_eq!(removed_data.a, 3);
+///     assert_eq!(removed_data.b, 4);
+/// } else {
+///     pr_info!("No value found in index {}", index);
+/// }
+/// # Ok::<(), Error>(())
+/// ```

I think it would make more sense to move these examples into the documentation of XArray<T> itself.

Quoted 15 lines
rust/kernel/xarray.rs new file +15 -0
+impl<T: ForeignOwnable> XArray<T> {
+    /// Creates a new [`XArray`] with the given flags.
+    pub fn new(flags: Flags) -> impl PinInit<Self> {
+        pin_init!(Self {
+            // SAFETY: `xa` is valid while the closure is called.
+            xa <- Opaque::ffi_init(|xa| unsafe {
+                bindings::xa_init_flags(xa, flags)
+            }),
+            _p: PhantomData,
+        })
+    }
+
+    /// Converts [`usize`] to `unsigned long`.
+    fn to_index(i: usize) -> c_ulong {
+        // The type is `unsigned long`, which is always the same as `usize` in

rust/kernel/xarray.rs line 199

Quoted 10 lines
rust/kernel/xarray.rs new file +10 -0
+        // the kernel.
+        build_assert!(mem::size_of::<usize>() == mem::size_of::<c_ulong>());
+        i as c_ulong
+    }
+
+    /// Replaces an entry with a new value, returning the old value (if any).
+    pub fn replace(&self, index: usize, value: T) -> Result<Option<T>> {
+        let new = value.into_foreign();
+
+        build_assert!(T::FOREIGN_ALIGN >= 4);

This looks good. Which unsafe function call required this again? I can't find it in the safety comments below.

As I wrote in my mail to the first patch, ForeignOwnable needs to guarantee that T::FOREIGN_ALIGN actually is the alignment of the pointers returned by into_foreign(), so it must be an unsafe trait.

rust/kernel/xarray.rs line 208

Quoted 9 lines
rust/kernel/xarray.rs new file +9 -0
+
+        // SAFETY: `new` just came from [`into_foreign()`], and we dismiss this guard
+        // if the `xa_store` operation succeeds and takes ownership of the pointer.
+        let guard = ScopeGuard::new(|| unsafe {
+            drop(T::from_foreign(new));
+        });
+
+        // SAFETY: `self.xa` is always valid by the type invariant, and we are
+        // storing a [`T::into_foreign()`] result which upholds the later invariants.

The second part of this comment should be an INVARIANT comment instead. So "INVARIANT: new came from [T::into_foreign()]."

Quoted 10 lines
rust/kernel/xarray.rs new file +10 -0
+        let old = unsafe {
+            bindings::xa_store(
+                self.xa.get(),
+                Self::to_index(index),
+                new.cast_mut(),
+                bindings::GFP_KERNEL,
+            )
+        };
+
+        // SAFETY: `xa_store` returns the old entry at this index on success or

rust/kernel/xarray.rs line 228

Quoted 10 lines
rust/kernel/xarray.rs new file +10 -0
+        // a [`XArray`] result, which can be turn into an errno through `xa_err`.
+        to_result(unsafe { bindings::xa_err(old) })?;
+        guard.dismiss();
+
+        Ok(if old.is_null() {
+            None
+        } else {
+            // SAFETY: The old value must have been stored by either this function or
+            // `insert_between`, both of which ensure non-NULL entries are valid
+            // [`ForeignOwnable`] pointers.

This should be replaced by "by the type invariant of Self, old is either NULL, or came from T::into_foreign().".

Quoted 3 lines
rust/kernel/xarray.rs new file +3 -0
+            Some(unsafe { T::from_foreign(old) })
+        })
+    }

[...]

Quoted 20 lines
rust/kernel/xarray.rs new file +20 -0
+    /// Allocates a new index in the array, optionally storing a new value into
+    /// it, with configurable bounds for the index range to allocate from.
+    ///
+    /// If `value` is [`None`], then the index is reserved from further allocation
+    /// but remains free for storing a value into it.
+    fn insert_between(&self, value: Option<T>, min: u32, max: u32) -> Result<usize> {
+        let new = value.map_or(core::ptr::null(), |a| a.into_foreign());
+        let mut id: u32 = 0;
+
+        let guard = ScopeGuard::new(|| {
+            if !new.is_null() {
+                // SAFETY: If `new` is not NULL, it came from the [`ForeignOwnable`]
+                // we got from the caller.
+                unsafe { drop(T::from_foreign(new)) };
+            }
+        });
+
+        // SAFETY: `self.xa` is always valid by the type invariant.
+        //
+        // If this succeeds, it takes ownership of the passed `T` (if any).

rust/kernel/xarray.rs line 310

Quoted 10 lines
rust/kernel/xarray.rs new file +10 -0
+        // If it fails, we must drop the `T` again.
+        let ret = unsafe {
+            bindings::xa_alloc(
+                self.xa.get(),
+                &mut id,
+                new.cast_mut(),
+                bindings::xa_limit { min, max },
+                bindings::GFP_KERNEL,
+            )
+        };

This function call is missing an INVARIANT comment stating that new is either NULL or came from T::into_foreign().

Quoted 8 lines
rust/kernel/xarray.rs new file +8 -0
+
+        if ret < 0 {
+            Err(Error::from_errno(ret))
+        } else {
+            guard.dismiss();
+            Ok(id as usize)
+        }
+    }

[...]

Quoted 4 lines
rust/kernel/xarray.rs new file +4 -0
+// SAFETY: It is safe to send `XArray<T>` to another thread when the underlying
+// `T` is `Send` because XArray is thread-safe and all mutation operations are
+// internally locked. `T` must be `ForeignOwnable` because all pointers stored
+// in the array are pointers obtained by calling `T::into_foreign` or are NULL

rust/kernel/xarray.rs line 407

Quoted 10 lines
rust/kernel/xarray.rs new file +10 -0
+// pointers.
+unsafe impl<T: Send + ForeignOwnable> Send for XArray<T> {}
+//
+// SAFETY: It is safe to send `&XArray<T>` to another thread when the underlying
+// `T` is `Sync` because it effectively means sharing `&T` (which is safe because
+// `T` is `Sync`). Additionally, `T` is `Send` because XArray is thread-safe and
+// all mutation operations are internally locked. `T` must be `ForeignOwnable`
+// because all pointers stored in the array are pointers obtained by calling
+// `T::into_foreign` or are NULL pointers.
+unsafe impl<T: Send + Sync + ForeignOwnable> Sync for XArray<T> {}

The part about "T must be ForeignOwnable..." is not needed here.

Signature · 2 lines
Cheers,
Benno
Quoted 3 lines

--
2.43.0