rust-for-linux.vger.kernel.org archive mirror
 help / color / mirror / Atom feed
From: Alice Ryhl <aliceryhl@google.com>
To: rust-for-linux@vger.kernel.org
Cc: "Miguel Ojeda" <ojeda@kernel.org>,
	"Alex Gaynor" <alex.gaynor@gmail.com>,
	"Wedson Almeida Filho" <wedsonaf@gmail.com>,
	"Boqun Feng" <boqun.feng@gmail.com>,
	"Gary Guo" <gary@garyguo.net>,
	"Björn Roy Baron" <bjorn3_gh@protonmail.com>,
	"Benno Lossin" <benno.lossin@proton.me>,
	"Andreas Hindborg" <a.hindborg@samsung.com>,
	"Xiangfei Ding" <dingxiangfei2009@protonmail.ch>,
	"Alice Ryhl" <aliceryhl@google.com>
Subject: [PATCH RFC] rust: experiment with `#[derive(SmartPointer)]`
Date: Fri, 23 Aug 2024 10:54:53 +0000	[thread overview]
Message-ID: <20240823-derive-smart-pointer-v1-1-53769cd37239@google.com> (raw)

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.

Link: https://rust-lang.github.io/rfcs/3621-derive-smart-pointer.html [1]
Link: https://github.com/rust-lang/rust/issues/129465 [2]
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
---
 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(-)

diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs
index 9baea9e9ee1a..6f24e8095b41 100644
--- a/rust/kernel/lib.rs
+++ b/rust/kernel/lib.rs
@@ -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.
diff --git a/rust/kernel/list/arc.rs b/rust/kernel/list/arc.rs
index d801b9dc6291..d0096af6a000 100644
--- a/rust/kernel/list/arc.rs
+++ b/rust/kernel/list/arc.rs
@@ -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
diff --git a/rust/kernel/sync/arc.rs b/rust/kernel/sync/arc.rs
index 3021f30fd822..c3a8b6fda7c4 100644
--- a/rust/kernel/sync/arc.rs
+++ b/rust/kernel/sync/arc.rs
@@ -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
diff --git a/samples/rust/rust_minimal.rs b/samples/rust/rust_minimal.rs
index 2a9eaab62d1c..9d947465c6c3 100644
--- a/samples/rust/rust_minimal.rs
+++ b/samples/rust/rust_minimal.rs
@@ -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: &'static ThisModule) -> 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,
-- 
Alice Ryhl <aliceryhl@google.com>


                 reply	other threads:[~2024-08-23 10:55 UTC|newest]

Thread overview: [no followups] expand[flat|nested]  mbox.gz  Atom feed

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20240823-derive-smart-pointer-v1-1-53769cd37239@google.com \
    --to=aliceryhl@google.com \
    --cc=a.hindborg@samsung.com \
    --cc=alex.gaynor@gmail.com \
    --cc=benno.lossin@proton.me \
    --cc=bjorn3_gh@protonmail.com \
    --cc=boqun.feng@gmail.com \
    --cc=dingxiangfei2009@protonmail.ch \
    --cc=gary@garyguo.net \
    --cc=ojeda@kernel.org \
    --cc=rust-for-linux@vger.kernel.org \
    --cc=wedsonaf@gmail.com \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).