rust: experiment with `#[derive(SmartPointer)]`
Alice Ryhl
maintainerRFC PATCH 1/1 rust: experiment with `#[derive(SmartPointer)]`
I am sending this RFC patch to share my experience with using the new #[derive(SmartPointer)] feature [1] with our custom smart pointers. The feature is being added so that the kernel can stop using the unstable dispatch_from_dyn and unsize features.
In general, the feature appears to work. As can be seen in the change to rust_minimal.rs, it is possible to use Arc together with a dynamic trait object, and the trait object is object safe even though it uses the custom smart pointer as a self parameter.
I did run into one nit, which is that Arc requires the #[pointee] annotation even though there's only one generic paramter. I filed an issue [2] about this.
--- rust/kernel/lib.rs | 3 +-- rust/kernel/list/arc.rs | 23 +++-------------------- rust/kernel/sync/arc.rs | 24 +++++++----------------- samples/rust/rust_minimal.rs | 15 +++++++++++++++ 4 files changed, 26 insertions(+), 39 deletions(-)
rust/kernel/lib.rs +1 -2
@@ -13,10 +13,9 @@#![no_std] #![feature(coerce_unsized)] -#![feature(dispatch_from_dyn)] +#![feature(derive_smart_pointer)] #![feature(new_uninit)] #![feature(receiver_trait)] -#![feature(unsize)] // Ensure conditional compilation based on the kernel configuration works; // otherwise we may silently break things like initcall handling.
rust/kernel/list/arc.rs +3 -20
@@ -7,7 +7,7 @@use crate ::alloc::{AllocError ,Flags };use crate ::prelude::*;use crate ::sync::{Arc ,ArcBorrow ,UniqueArc }; -use core::marker::{PhantomPinned ,Unsize }; +use core::marker::{PhantomPinned ,SmartPointer };use core::ops::Deref ;use core::pin::Pin ;use core::sync::atomic::{AtomicBool ,Ordering };
@@ -158,8 +158,9 @@ fn try_new_list_arc(&self) -> bool {/// * The tracking inside `T` is aware that a `ListArc` reference exists. /// /// [`List`]: crate::list::List +#[derive( SmartPointer )] #[repr(transparent)] -pub struct ListArc <T ,const ID :u64 =0 > +pub struct ListArc <#[pointee] T ,const ID :u64 =0 >where T :ListArcSafe <ID > + ?Sized , {
@@ -444,24 +445,6 @@ fn as_ref(&self) -> &Arc<T> {// This is to allow [`ListArc`] (and variants) to be used as the type of `self`. impl <T ,const ID :u64 > core::ops::Receiver for ListArc <T ,ID >where T :ListArcSafe <ID > + ?Sized {} -// This is to allow coercion from `ListArc<T>` to `ListArc<U>` if `T` can be converted to the -// dynamically-sized type (DST) `U`. -impl <T ,U ,const ID :u64 > core::ops::CoerceUnsized <ListArc <U ,ID >>for ListArc <T ,ID > -where -T :ListArcSafe <ID > +Unsize <U > + ?Sized , -U :ListArcSafe <ID > + ?Sized , -{ -} - -// This is to allow `ListArc<U>` to be dispatched on when `ListArc<T>` can be coerced into -// `ListArc<U>`. -impl <T ,U ,const ID :u64 > core::ops::DispatchFromDyn <ListArc <U ,ID >>for ListArc <T ,ID > -where -T :ListArcSafe <ID > +Unsize <U > + ?Sized , -U :ListArcSafe <ID > + ?Sized , -{ -} -/// A utility for tracking whether a [`ListArc`] exists using an atomic. /// /// # Invariant
rust/kernel/sync/arc.rs +7 -17
@@ -27,7 +27,7 @@use core::{ alloc::Layout , fmt, - marker::{PhantomData ,Unsize }, + marker::{PhantomData ,SmartPointer }, mem::{ManuallyDrop ,MaybeUninit }, ops::{Deref ,DerefMut }, pin::Pin ,
@@ -126,7 +126,9 @@/// let coerced: Arc<dyn MyTrait> = obj; /// # Ok::<(), Error>(()) /// ``` -pub struct Arc <T : ?Sized > { +#[derive( SmartPointer )] +#[repr(transparent)] +pub struct Arc <#[pointee] T : ?Sized > { ptr:NonNull <ArcInner <T >>, _p:PhantomData <ArcInner <T >>, }
@@ -174,13 +176,6 @@ unsafe fn container_of(ptr: *const T) -> NonNull<ArcInner<T>> {// This is to allow [`Arc`] (and variants) to be used as the type of `self`. impl <T : ?Sized > core::ops::Receiver for Arc <T > {} -// This is to allow coercion from `Arc<T>` to `Arc<U>` if `T` can be converted to the -// dynamically-sized type (DST) `U`. -impl <T : ?Sized +Unsize <U >,U : ?Sized > core::ops::CoerceUnsized <Arc <U >>for Arc <T > {} - -// This is to allow `Arc<U>` to be dispatched on when `Arc<T>` can be coerced into `Arc<U>`. -impl <T : ?Sized +Unsize <U >,U : ?Sized > core::ops::DispatchFromDyn <Arc <U >>for Arc <T > {} -// SAFETY: It is safe to send `Arc<T>` to another thread when the underlying `T` is `Sync` because // it effectively means sharing `&T` (which is safe because `T` is `Sync`); additionally, it needs // `T` to be `Send` because any thread that has an `Arc<T>` may ultimately access `T` using a
@@ -475,7 +470,9 @@ fn from(item: Pin<UniqueArc<T>>) -> Self {/// obj.as_arc_borrow().use_reference(); /// # Ok::<(), Error>(()) /// ``` -pub struct ArcBorrow <'a,T : ?Sized + 'a> { +#[derive( SmartPointer )] +#[repr(transparent)] +pub struct ArcBorrow <'a,#[pointee] T : ?Sized + 'a> { inner:NonNull <ArcInner <T >>, _p:PhantomData <&'a ()>, }
@@ -483,13 +480,6 @@ pub struct ArcBorrow<'a, T: ?Sized + 'a> {// This is to allow [`ArcBorrow`] (and variants) to be used as the type of `self`. impl <T : ?Sized > core::ops::Receiver for ArcBorrow <'_,T > {} -// This is to allow `ArcBorrow<U>` to be dispatched on when `ArcBorrow<T>` can be coerced into -// `ArcBorrow<U>`. -impl <T : ?Sized +Unsize <U >,U : ?Sized > core::ops::DispatchFromDyn <ArcBorrow <'_,U >> -for ArcBorrow <'_,T > -{ -} -impl <T : ?Sized >Clone for ArcBorrow <'_,T > {fn clone (&self) ->Self { *self
samples/rust/rust_minimal.rs +15 -0
@@ -3,6 +3,7 @@//! Rust minimal sample. use kernel::prelude::*; +use kernel::sync::Arc ;module! {type :RustMinimal ,
@@ -16,6 +17,15 @@ struct RustMinimal { numbers: Vec<i32>, } +trait MyTrait { +fn my_fn (self:Arc <Self >); +} +impl MyTrait for Vec <i32 > { +fn my_fn (self:Arc <Self >) { +pr_info! ("{:?}" , self.as_slice ()); + } +} +impl kernel::Module for RustMinimal {fn init (_module: &'staticThisModule ) ->Result <Self > {pr_info! ("Rust minimal sample (init)\n" );
@@ -26,6 +36,11 @@ fn init(_module: &'static ThisModule) -> Result<Self> { numbers.push (108 ,GFP_KERNEL )?; numbers.push (200 ,GFP_KERNEL )?; +let in_arc = kernel::sync::Arc ::new (numbers)?; + in_arc.my_fn (); +let arc_dyn:Arc <dyn MyTrait > = in_arc; + arc_dyn.my_fn (); +Ok (RustMinimal { numbers }) } }
---
base-commit: b204bbc53f958fc3119d63bf2cda5a526e7267a4
change-id: 20240823-derive-smart-pointer-390a7f1f510c
Best regards,
Signature · 1 line
Alice Ryhl <[email protected]>
kernel test robot
build botkernel test robot noticed the following build errors:
Hi Alice,
[This is a private test report for your RFC patch.] kernel test robot noticed the following build errors:
[auto build test ERROR on b204bbc53f958fc3119d63bf2cda5a526e7267a4]
url: https://github.com/intel-lab-lkp/linux/commits/Alice-Ryhl/rust-experiment-with-derive-SmartPointer/20240826-125309 base: b204bbc53f958fc3119d63bf2cda5a526e7267a4 patch link: https://lore.kernel.org/r/20240823-derive-smart-pointer-v1-1-53769cd37239%40google.com patch subject: [PATCH RFC] rust: experiment with `#[derive(SmartPointer)]` config: x86_64-rhel-8.3-rust (https://download.01.org/0day-ci/archive/20240829/[email protected]/config) compiler: clang version 18.1.5 (https://github.com/llvm/llvm-project 617a15a9eac96088ae5e9134248d8236e34b91b1) reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20240829/[email protected]/reproduce)
If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/
All errors (new ones prefixed by >>):
>> error[E0432]: unresolved import `core::marker::SmartPointer`
--> rust/kernel/list/arc.rs:10:35
|
10 | use core::marker::{PhantomPinned, SmartPointer};
| ^^^^^^^^^^^^ no SmartPointer in marker
--
>> error[E0432]: unresolved import `core::marker::SmartPointer`
--> rust/kernel/sync/arc.rs:30:27
|
30 | marker::{PhantomData, SmartPointer},
| ^^^^^^^^^^^^ no SmartPointer in marker
--
>> error: cannot find attribute `pointee` in this scope
--> rust/kernel/list/arc.rs:163:22
|
163 | pub struct ListArc<#[pointee] T, const ID: u64 = 0>
| ^^^^^^^
--
>> error: cannot find attribute `pointee` in this scope
--> rust/kernel/sync/arc.rs:131:18
|
131 | pub struct Arc<#[pointee] T: ?Sized> {
| ^^^^^^^
--
>> error: cannot find attribute `pointee` in this scope
--> rust/kernel/sync/arc.rs:475:28
|
475 | pub struct ArcBorrow<'a, #[pointee] T: ?Sized + 'a> {
| ^^^^^^^
--
>> error[E0635]: unknown feature `derive_smart_pointer`
--> rust/kernel/lib.rs:16:12
|
16 | #![feature(derive_smart_pointer)]
| ^^^^^^^^^^^^^^^^^^^^
Signature · 2 lines
0-DAY CI Kernel Test Service https://github.com/intel/lkp-tests/wiki