[PATCH v3 2/2] rust: sync: add `Arc::into_unique_or_drop`

Alice Ryhl posted 2 patches 1 year, 11 months ago
There is a newer version of this series
[PATCH v3 2/2] rust: sync: add `Arc::into_unique_or_drop`
Posted by Alice Ryhl 1 year, 11 months ago
Decrement the refcount of an `Arc`, but handle the case where it hits
zero by taking ownership of the now-unique `Arc`, instead of destroying
and deallocating it.

This is a dependency of the linked list that Rust Binder uses. The
linked list uses this method as part of its `ListArc` abstraction.

Signed-off-by: Alice Ryhl <aliceryhl@google.com>
---
 rust/kernel/sync/arc.rs | 30 ++++++++++++++++++++++++++++++
 1 file changed, 30 insertions(+)

diff --git a/rust/kernel/sync/arc.rs b/rust/kernel/sync/arc.rs
index 53addb8876c2..ef8b520f65a8 100644
--- a/rust/kernel/sync/arc.rs
+++ b/rust/kernel/sync/arc.rs
@@ -290,6 +290,36 @@ pub fn as_arc_borrow(&self) -> ArcBorrow<'_, T> {
     pub fn ptr_eq(this: &Self, other: &Self) -> bool {
         core::ptr::eq(this.ptr.as_ptr(), other.ptr.as_ptr())
     }
+
+    /// Converts this [`Arc`] into a [`UniqueArc`], or destroys it if it is not unique.
+    ///
+    /// When this destroys the `Arc`, it does so while properly avoiding races. This means that
+    /// this method will never call the destructor of the value.
+    pub fn into_unique_or_drop(self) -> Option<Pin<UniqueArc<T>>> {
+        // We will manually manage the refcount in this method, so we disable the destructor.
+        let me = ManuallyDrop::new(self);
+        // SAFETY: We own a refcount, so the pointer is still valid.
+        let refcount = unsafe { me.ptr.as_ref() }.refcount.get();
+
+        // If the refcount reaches a non-zero value, then we have destroyed this `Arc` and will
+        // return without further touching the `Arc`. If the refcount reaches zero, then there are
+        // no other arcs, and we can create a `UniqueArc`.
+        //
+        // SAFETY: We own a refcount, so the pointer is not dangling.
+        let is_zero = unsafe { bindings::refcount_dec_and_test(refcount) };
+        if is_zero {
+            // SAFETY: We have exclusive access to the arc, so we can perform unsynchronized
+            // accesses to the refcount.
+            unsafe { core::ptr::write(refcount, bindings::REFCOUNT_INIT(1)) };
+
+            // INVARIANT: We own the only refcount to this arc, so we may create a `UniqueArc`. We
+            // must pin the `UniqueArc` because the values was previously in an `Arc`, and they pin
+            // their values.
+            Some(Pin::from(UniqueArc { inner: ManuallyDrop::into_inner(me) }))
+        } else {
+            None
+        }
+    }
 }
 
 impl<T: 'static> ForeignOwnable for Arc<T> {

-- 
2.44.0.278.ge034bb2e1d-goog
Re: [PATCH v3 2/2] rust: sync: add `Arc::into_unique_or_drop`
Posted by Boqun Feng 1 year, 11 months ago
On Mon, Mar 11, 2024 at 04:08:19PM +0000, Alice Ryhl wrote:
> Decrement the refcount of an `Arc`, but handle the case where it hits
> zero by taking ownership of the now-unique `Arc`, instead of destroying
> and deallocating it.
> 
> This is a dependency of the linked list that Rust Binder uses. The
> linked list uses this method as part of its `ListArc` abstraction.
> 
> Signed-off-by: Alice Ryhl <aliceryhl@google.com>
> ---
>  rust/kernel/sync/arc.rs | 30 ++++++++++++++++++++++++++++++
>  1 file changed, 30 insertions(+)
> 
> diff --git a/rust/kernel/sync/arc.rs b/rust/kernel/sync/arc.rs
> index 53addb8876c2..ef8b520f65a8 100644
> --- a/rust/kernel/sync/arc.rs
> +++ b/rust/kernel/sync/arc.rs
> @@ -290,6 +290,36 @@ pub fn as_arc_borrow(&self) -> ArcBorrow<'_, T> {
>      pub fn ptr_eq(this: &Self, other: &Self) -> bool {
>          core::ptr::eq(this.ptr.as_ptr(), other.ptr.as_ptr())
>      }
> +
> +    /// Converts this [`Arc`] into a [`UniqueArc`], or destroys it if it is not unique.
> +    ///
> +    /// When this destroys the `Arc`, it does so while properly avoiding races. This means that
> +    /// this method will never call the destructor of the value.
> +    pub fn into_unique_or_drop(self) -> Option<Pin<UniqueArc<T>>> {
> +        // We will manually manage the refcount in this method, so we disable the destructor.
> +        let me = ManuallyDrop::new(self);
> +        // SAFETY: We own a refcount, so the pointer is still valid.
> +        let refcount = unsafe { me.ptr.as_ref() }.refcount.get();
> +
> +        // If the refcount reaches a non-zero value, then we have destroyed this `Arc` and will
> +        // return without further touching the `Arc`. If the refcount reaches zero, then there are
> +        // no other arcs, and we can create a `UniqueArc`.
> +        //
> +        // SAFETY: We own a refcount, so the pointer is not dangling.
> +        let is_zero = unsafe { bindings::refcount_dec_and_test(refcount) };
> +        if is_zero {
> +            // SAFETY: We have exclusive access to the arc, so we can perform unsynchronized
> +            // accesses to the refcount.
> +            unsafe { core::ptr::write(refcount, bindings::REFCOUNT_INIT(1)) };
> +
> +            // INVARIANT: We own the only refcount to this arc, so we may create a `UniqueArc`. We
> +            // must pin the `UniqueArc` because the values was previously in an `Arc`, and they pin
> +            // their values.
> +            Some(Pin::from(UniqueArc { inner: ManuallyDrop::into_inner(me) }))
> +        } else {
> +            None
> +        }
> +    }
>  }
>  
>  impl<T: 'static> ForeignOwnable for Arc<T> {
> 

The code looks good, and FWIW, I added the Examples section for the
function since I at least need something to run when queuing it to
rust-dev branch ;-) And I think it's overall good to have examples for
every `pub` function. If there is a next version (which is unlikely),
feel free to fold it. I can also send it alone once Miguel put your
patches into the rust-next branch.

Regards,
Boqun

--------------------------------------------------->8
From 7d26d1177a2788ba96c607fd9dc45baf469fb439 Mon Sep 17 00:00:00 2001
From: Boqun Feng <boqun.feng@gmail.com>
Date: Tue, 12 Mar 2024 10:03:39 -0700
Subject: [PATCH] kernel: sync: Add "Examples" section for
 Arc::into_unique_or_drop()

These examples provide better documentation and can serve as unit tests
as well, so add them.

Signed-off-by: Boqun Feng <boqun.feng@gmail.com>
---
 rust/kernel/sync/arc.rs | 30 ++++++++++++++++++++++++++++++
 1 file changed, 30 insertions(+)

diff --git a/rust/kernel/sync/arc.rs b/rust/kernel/sync/arc.rs
index fda737f5b1e9..7cf066cfb321 100644
--- a/rust/kernel/sync/arc.rs
+++ b/rust/kernel/sync/arc.rs
@@ -295,6 +295,36 @@ pub fn ptr_eq(this: &Self, other: &Self) -> bool {
     ///
     /// When this destroys the `Arc`, it does so while properly avoiding races. This means that
     /// this method will never call the destructor of the value.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use kernel::sync::{Arc, UniqueArc};
+    ///
+    /// let arc = Arc::try_new(42)?;
+    /// let unique_arc = arc.into_unique_or_drop();
+    ///
+    /// // The above conversion should succeed since refcount of `arc` is 1.
+    /// assert!(unique_arc.is_some());
+    ///
+    /// assert_eq!(*(unique_arc.unwrap()), 42);
+    ///
+    /// # Ok::<(), Error>(())
+    /// ```
+    ///
+    /// ```
+    /// use kernel::sync::{Arc, UniqueArc};
+    ///
+    /// let arc = Arc::try_new(42)?;
+    /// let another = arc.clone();
+    ///
+    /// let unique_arc = arc.into_unique_or_drop();
+    ///
+    /// // The above conversion should fail since refcount of `arc` is >1.
+    /// assert!(unique_arc.is_none());
+    ///
+    /// # Ok::<(), Error>(())
+    /// ```
     pub fn into_unique_or_drop(self) -> Option<Pin<UniqueArc<T>>> {
         // We will manually manage the refcount in this method, so we disable the destructor.
         let me = ManuallyDrop::new(self);
-- 
2.44.0
Re: [PATCH v3 2/2] rust: sync: add `Arc::into_unique_or_drop`
Posted by Alice Ryhl 1 year, 11 months ago
Boqun Feng <boqun.feng@gmail.com> writes:
> The code looks good, and FWIW, I added the Examples section for the
> function since I at least need something to run when queuing it to
> rust-dev branch ;-) And I think it's overall good to have examples for
> every `pub` function. If there is a next version (which is unlikely),
> feel free to fold it. I can also send it alone once Miguel put your
> patches into the rust-next branch.

Thanks! If you have reviewed it, could I have your Reviewed-by tag?

> From 7d26d1177a2788ba96c607fd9dc45baf469fb439 Mon Sep 17 00:00:00 2001
> From: Boqun Feng <boqun.feng@gmail.com>
> Date: Tue, 12 Mar 2024 10:03:39 -0700
> Subject: [PATCH] kernel: sync: Add "Examples" section for
>  Arc::into_unique_or_drop()
> 
> These examples provide better documentation and can serve as unit tests
> as well, so add them.
> 
> Signed-off-by: Boqun Feng <boqun.feng@gmail.com>

Reviewed-by: Alice Ryhl <aliceryhl@google.com>

Alice
Re: [PATCH v3 2/2] rust: sync: add `Arc::into_unique_or_drop`
Posted by Boqun Feng 1 year, 11 months ago
On Wed, Mar 13, 2024 at 09:50:59AM +0000, Alice Ryhl wrote:
> Boqun Feng <boqun.feng@gmail.com> writes:
> > The code looks good, and FWIW, I added the Examples section for the
> > function since I at least need something to run when queuing it to
> > rust-dev branch ;-) And I think it's overall good to have examples for
> > every `pub` function. If there is a next version (which is unlikely),
> > feel free to fold it. I can also send it alone once Miguel put your
> > patches into the rust-next branch.
> 
> Thanks! If you have reviewed it, could I have your Reviewed-by tag?
> 

Done.

> > From 7d26d1177a2788ba96c607fd9dc45baf469fb439 Mon Sep 17 00:00:00 2001
> > From: Boqun Feng <boqun.feng@gmail.com>
> > Date: Tue, 12 Mar 2024 10:03:39 -0700
> > Subject: [PATCH] kernel: sync: Add "Examples" section for
> >  Arc::into_unique_or_drop()
> > 
> > These examples provide better documentation and can serve as unit tests
> > as well, so add them.
> > 
> > Signed-off-by: Boqun Feng <boqun.feng@gmail.com>
> 
> Reviewed-by: Alice Ryhl <aliceryhl@google.com>
> 

Thanks! I will add it.

Regards,
Boqun

> Alice
Re: [PATCH v3 2/2] rust: sync: add `Arc::into_unique_or_drop`
Posted by Benno Lossin 1 year, 11 months ago
On 3/11/24 17:08, Alice Ryhl wrote:
> Decrement the refcount of an `Arc`, but handle the case where it hits
> zero by taking ownership of the now-unique `Arc`, instead of destroying
> and deallocating it.
> 
> This is a dependency of the linked list that Rust Binder uses. The
> linked list uses this method as part of its `ListArc` abstraction.
> 
> Signed-off-by: Alice Ryhl <aliceryhl@google.com>

Reviewed-by: Benno Lossin <benno.lossin@proton.me>