xref: /openbmc/linux/rust/kernel/sync/arc.rs (revision 47329ba14b5aac1ac975544eee71ecc888557d23)
19dc04365SWedson Almeida Filho // SPDX-License-Identifier: GPL-2.0
29dc04365SWedson Almeida Filho 
39dc04365SWedson Almeida Filho //! A reference-counted pointer.
49dc04365SWedson Almeida Filho //!
59dc04365SWedson Almeida Filho //! This module implements a way for users to create reference-counted objects and pointers to
69dc04365SWedson Almeida Filho //! them. Such a pointer automatically increments and decrements the count, and drops the
79dc04365SWedson Almeida Filho //! underlying object when it reaches zero. It is also safe to use concurrently from multiple
89dc04365SWedson Almeida Filho //! threads.
99dc04365SWedson Almeida Filho //!
109dc04365SWedson Almeida Filho //! It is different from the standard library's [`Arc`] in a few ways:
119dc04365SWedson Almeida Filho //! 1. It is backed by the kernel's `refcount_t` type.
129dc04365SWedson Almeida Filho //! 2. It does not support weak references, which allows it to be half the size.
139dc04365SWedson Almeida Filho //! 3. It saturates the reference count instead of aborting when it goes over a threshold.
149dc04365SWedson Almeida Filho //! 4. It does not provide a `get_mut` method, so the ref counted object is pinned.
159dc04365SWedson Almeida Filho //!
169dc04365SWedson Almeida Filho //! [`Arc`]: https://doc.rust-lang.org/std/sync/struct.Arc.html
179dc04365SWedson Almeida Filho 
180c7ae432SWedson Almeida Filho use crate::{
190c7ae432SWedson Almeida Filho     bindings,
2092c4a1e7SBenno Lossin     error::{self, Error},
21701608bdSBenno Lossin     init::{self, InPlaceInit, Init, PinInit},
22701608bdSBenno Lossin     try_init,
230c7ae432SWedson Almeida Filho     types::{ForeignOwnable, Opaque},
240c7ae432SWedson Almeida Filho };
259dc04365SWedson Almeida Filho use alloc::boxed::Box;
26f75cb6fcSWedson Almeida Filho use core::{
27d6dbca35SBenno Lossin     alloc::AllocError,
2800140a83SBoqun Feng     fmt,
29f75cb6fcSWedson Almeida Filho     marker::{PhantomData, Unsize},
3070e42ebbSWedson Almeida Filho     mem::{ManuallyDrop, MaybeUninit},
3170e42ebbSWedson Almeida Filho     ops::{Deref, DerefMut},
3270e42ebbSWedson Almeida Filho     pin::Pin,
33f75cb6fcSWedson Almeida Filho     ptr::NonNull,
34f75cb6fcSWedson Almeida Filho };
35701608bdSBenno Lossin use macros::pin_data;
369dc04365SWedson Almeida Filho 
371edd0337SAsahi Lina mod std_vendor;
381edd0337SAsahi Lina 
399dc04365SWedson Almeida Filho /// A reference-counted pointer to an instance of `T`.
409dc04365SWedson Almeida Filho ///
419dc04365SWedson Almeida Filho /// The reference count is incremented when new instances of [`Arc`] are created, and decremented
429dc04365SWedson Almeida Filho /// when they are dropped. When the count reaches zero, the underlying `T` is also dropped.
439dc04365SWedson Almeida Filho ///
449dc04365SWedson Almeida Filho /// # Invariants
459dc04365SWedson Almeida Filho ///
469dc04365SWedson Almeida Filho /// The reference count on an instance of [`Arc`] is always non-zero.
479dc04365SWedson Almeida Filho /// The object pointed to by [`Arc`] is always pinned.
489dc04365SWedson Almeida Filho ///
499dc04365SWedson Almeida Filho /// # Examples
509dc04365SWedson Almeida Filho ///
519dc04365SWedson Almeida Filho /// ```
529dc04365SWedson Almeida Filho /// use kernel::sync::Arc;
539dc04365SWedson Almeida Filho ///
549dc04365SWedson Almeida Filho /// struct Example {
559dc04365SWedson Almeida Filho ///     a: u32,
569dc04365SWedson Almeida Filho ///     b: u32,
579dc04365SWedson Almeida Filho /// }
589dc04365SWedson Almeida Filho ///
599dc04365SWedson Almeida Filho /// // Create a ref-counted instance of `Example`.
609dc04365SWedson Almeida Filho /// let obj = Arc::try_new(Example { a: 10, b: 20 })?;
619dc04365SWedson Almeida Filho ///
629dc04365SWedson Almeida Filho /// // Get a new pointer to `obj` and increment the refcount.
639dc04365SWedson Almeida Filho /// let cloned = obj.clone();
649dc04365SWedson Almeida Filho ///
659dc04365SWedson Almeida Filho /// // Assert that both `obj` and `cloned` point to the same underlying object.
669dc04365SWedson Almeida Filho /// assert!(core::ptr::eq(&*obj, &*cloned));
679dc04365SWedson Almeida Filho ///
689dc04365SWedson Almeida Filho /// // Destroy `obj` and decrement its refcount.
699dc04365SWedson Almeida Filho /// drop(obj);
709dc04365SWedson Almeida Filho ///
719dc04365SWedson Almeida Filho /// // Check that the values are still accessible through `cloned`.
729dc04365SWedson Almeida Filho /// assert_eq!(cloned.a, 10);
739dc04365SWedson Almeida Filho /// assert_eq!(cloned.b, 20);
749dc04365SWedson Almeida Filho ///
759dc04365SWedson Almeida Filho /// // The refcount drops to zero when `cloned` goes out of scope, and the memory is freed.
769dc04365SWedson Almeida Filho /// ```
7753528772SWedson Almeida Filho ///
7853528772SWedson Almeida Filho /// Using `Arc<T>` as the type of `self`:
7953528772SWedson Almeida Filho ///
8053528772SWedson Almeida Filho /// ```
8153528772SWedson Almeida Filho /// use kernel::sync::Arc;
8253528772SWedson Almeida Filho ///
8353528772SWedson Almeida Filho /// struct Example {
8453528772SWedson Almeida Filho ///     a: u32,
8553528772SWedson Almeida Filho ///     b: u32,
8653528772SWedson Almeida Filho /// }
8753528772SWedson Almeida Filho ///
8853528772SWedson Almeida Filho /// impl Example {
8953528772SWedson Almeida Filho ///     fn take_over(self: Arc<Self>) {
9053528772SWedson Almeida Filho ///         // ...
9153528772SWedson Almeida Filho ///     }
9253528772SWedson Almeida Filho ///
9353528772SWedson Almeida Filho ///     fn use_reference(self: &Arc<Self>) {
9453528772SWedson Almeida Filho ///         // ...
9553528772SWedson Almeida Filho ///     }
9653528772SWedson Almeida Filho /// }
9753528772SWedson Almeida Filho ///
9853528772SWedson Almeida Filho /// let obj = Arc::try_new(Example { a: 10, b: 20 })?;
9953528772SWedson Almeida Filho /// obj.use_reference();
10053528772SWedson Almeida Filho /// obj.take_over();
10153528772SWedson Almeida Filho /// ```
102f75cb6fcSWedson Almeida Filho ///
103f75cb6fcSWedson Almeida Filho /// Coercion from `Arc<Example>` to `Arc<dyn MyTrait>`:
104f75cb6fcSWedson Almeida Filho ///
105f75cb6fcSWedson Almeida Filho /// ```
1060748424aSWedson Almeida Filho /// use kernel::sync::{Arc, ArcBorrow};
107f75cb6fcSWedson Almeida Filho ///
1080748424aSWedson Almeida Filho /// trait MyTrait {
1090748424aSWedson Almeida Filho ///     // Trait has a function whose `self` type is `Arc<Self>`.
1100748424aSWedson Almeida Filho ///     fn example1(self: Arc<Self>) {}
1110748424aSWedson Almeida Filho ///
1120748424aSWedson Almeida Filho ///     // Trait has a function whose `self` type is `ArcBorrow<'_, Self>`.
1130748424aSWedson Almeida Filho ///     fn example2(self: ArcBorrow<'_, Self>) {}
1140748424aSWedson Almeida Filho /// }
115f75cb6fcSWedson Almeida Filho ///
116f75cb6fcSWedson Almeida Filho /// struct Example;
117f75cb6fcSWedson Almeida Filho /// impl MyTrait for Example {}
118f75cb6fcSWedson Almeida Filho ///
119f75cb6fcSWedson Almeida Filho /// // `obj` has type `Arc<Example>`.
120f75cb6fcSWedson Almeida Filho /// let obj: Arc<Example> = Arc::try_new(Example)?;
121f75cb6fcSWedson Almeida Filho ///
122f75cb6fcSWedson Almeida Filho /// // `coerced` has type `Arc<dyn MyTrait>`.
123f75cb6fcSWedson Almeida Filho /// let coerced: Arc<dyn MyTrait> = obj;
124f75cb6fcSWedson Almeida Filho /// ```
1259dc04365SWedson Almeida Filho pub struct Arc<T: ?Sized> {
1269dc04365SWedson Almeida Filho     ptr: NonNull<ArcInner<T>>,
1279dc04365SWedson Almeida Filho     _p: PhantomData<ArcInner<T>>,
1289dc04365SWedson Almeida Filho }
1299dc04365SWedson Almeida Filho 
130701608bdSBenno Lossin #[pin_data]
1319dc04365SWedson Almeida Filho #[repr(C)]
1329dc04365SWedson Almeida Filho struct ArcInner<T: ?Sized> {
1339dc04365SWedson Almeida Filho     refcount: Opaque<bindings::refcount_t>,
1349dc04365SWedson Almeida Filho     data: T,
1359dc04365SWedson Almeida Filho }
1369dc04365SWedson Almeida Filho 
13753528772SWedson Almeida Filho // This is to allow [`Arc`] (and variants) to be used as the type of `self`.
13853528772SWedson Almeida Filho impl<T: ?Sized> core::ops::Receiver for Arc<T> {}
13953528772SWedson Almeida Filho 
140f75cb6fcSWedson Almeida Filho // This is to allow coercion from `Arc<T>` to `Arc<U>` if `T` can be converted to the
141f75cb6fcSWedson Almeida Filho // dynamically-sized type (DST) `U`.
142f75cb6fcSWedson Almeida Filho impl<T: ?Sized + Unsize<U>, U: ?Sized> core::ops::CoerceUnsized<Arc<U>> for Arc<T> {}
143f75cb6fcSWedson Almeida Filho 
1440748424aSWedson Almeida Filho // This is to allow `Arc<U>` to be dispatched on when `Arc<T>` can be coerced into `Arc<U>`.
1450748424aSWedson Almeida Filho impl<T: ?Sized + Unsize<U>, U: ?Sized> core::ops::DispatchFromDyn<Arc<U>> for Arc<T> {}
1460748424aSWedson Almeida Filho 
1479dc04365SWedson Almeida Filho // SAFETY: It is safe to send `Arc<T>` to another thread when the underlying `T` is `Sync` because
1489dc04365SWedson Almeida Filho // it effectively means sharing `&T` (which is safe because `T` is `Sync`); additionally, it needs
1499dc04365SWedson Almeida Filho // `T` to be `Send` because any thread that has an `Arc<T>` may ultimately access `T` directly, for
1509dc04365SWedson Almeida Filho // example, when the reference count reaches zero and `T` is dropped.
1519dc04365SWedson Almeida Filho unsafe impl<T: ?Sized + Sync + Send> Send for Arc<T> {}
1529dc04365SWedson Almeida Filho 
1539dc04365SWedson Almeida Filho // SAFETY: It is safe to send `&Arc<T>` to another thread when the underlying `T` is `Sync` for the
1549dc04365SWedson Almeida Filho // same reason as above. `T` needs to be `Send` as well because a thread can clone an `&Arc<T>`
1559dc04365SWedson Almeida Filho // into an `Arc<T>`, which may lead to `T` being accessed by the same reasoning as above.
1569dc04365SWedson Almeida Filho unsafe impl<T: ?Sized + Sync + Send> Sync for Arc<T> {}
1579dc04365SWedson Almeida Filho 
1589dc04365SWedson Almeida Filho impl<T> Arc<T> {
1599dc04365SWedson Almeida Filho     /// Constructs a new reference counted instance of `T`.
160d6dbca35SBenno Lossin     pub fn try_new(contents: T) -> Result<Self, AllocError> {
1619dc04365SWedson Almeida Filho         // INVARIANT: The refcount is initialised to a non-zero value.
1629dc04365SWedson Almeida Filho         let value = ArcInner {
1639dc04365SWedson Almeida Filho             // SAFETY: There are no safety requirements for this FFI call.
1649dc04365SWedson Almeida Filho             refcount: Opaque::new(unsafe { bindings::REFCOUNT_INIT(1) }),
1659dc04365SWedson Almeida Filho             data: contents,
1669dc04365SWedson Almeida Filho         };
1679dc04365SWedson Almeida Filho 
1689dc04365SWedson Almeida Filho         let inner = Box::try_new(value)?;
1699dc04365SWedson Almeida Filho 
1709dc04365SWedson Almeida Filho         // SAFETY: We just created `inner` with a reference count of 1, which is owned by the new
1719dc04365SWedson Almeida Filho         // `Arc` object.
1729dc04365SWedson Almeida Filho         Ok(unsafe { Self::from_inner(Box::leak(inner).into()) })
1739dc04365SWedson Almeida Filho     }
17492c4a1e7SBenno Lossin 
17592c4a1e7SBenno Lossin     /// Use the given initializer to in-place initialize a `T`.
17692c4a1e7SBenno Lossin     ///
17792c4a1e7SBenno Lossin     /// If `T: !Unpin` it will not be able to move afterwards.
17892c4a1e7SBenno Lossin     #[inline]
17992c4a1e7SBenno Lossin     pub fn pin_init<E>(init: impl PinInit<T, E>) -> error::Result<Self>
18092c4a1e7SBenno Lossin     where
18192c4a1e7SBenno Lossin         Error: From<E>,
18292c4a1e7SBenno Lossin     {
18392c4a1e7SBenno Lossin         UniqueArc::pin_init(init).map(|u| u.into())
18492c4a1e7SBenno Lossin     }
18592c4a1e7SBenno Lossin 
18692c4a1e7SBenno Lossin     /// Use the given initializer to in-place initialize a `T`.
18792c4a1e7SBenno Lossin     ///
188eed7a146SMiguel Ojeda     /// This is equivalent to [`Arc<T>::pin_init`], since an [`Arc`] is always pinned.
18992c4a1e7SBenno Lossin     #[inline]
19092c4a1e7SBenno Lossin     pub fn init<E>(init: impl Init<T, E>) -> error::Result<Self>
19192c4a1e7SBenno Lossin     where
19292c4a1e7SBenno Lossin         Error: From<E>,
19392c4a1e7SBenno Lossin     {
19492c4a1e7SBenno Lossin         UniqueArc::init(init).map(|u| u.into())
19592c4a1e7SBenno Lossin     }
1969dc04365SWedson Almeida Filho }
1979dc04365SWedson Almeida Filho 
1989dc04365SWedson Almeida Filho impl<T: ?Sized> Arc<T> {
1999dc04365SWedson Almeida Filho     /// Constructs a new [`Arc`] from an existing [`ArcInner`].
2009dc04365SWedson Almeida Filho     ///
2019dc04365SWedson Almeida Filho     /// # Safety
2029dc04365SWedson Almeida Filho     ///
2039dc04365SWedson Almeida Filho     /// The caller must ensure that `inner` points to a valid location and has a non-zero reference
2049dc04365SWedson Almeida Filho     /// count, one of which will be owned by the new [`Arc`] instance.
2059dc04365SWedson Almeida Filho     unsafe fn from_inner(inner: NonNull<ArcInner<T>>) -> Self {
2069dc04365SWedson Almeida Filho         // INVARIANT: By the safety requirements, the invariants hold.
2079dc04365SWedson Almeida Filho         Arc {
2089dc04365SWedson Almeida Filho             ptr: inner,
2099dc04365SWedson Almeida Filho             _p: PhantomData,
2109dc04365SWedson Almeida Filho         }
2119dc04365SWedson Almeida Filho     }
21217f67160SWedson Almeida Filho 
21317f67160SWedson Almeida Filho     /// Returns an [`ArcBorrow`] from the given [`Arc`].
21417f67160SWedson Almeida Filho     ///
21517f67160SWedson Almeida Filho     /// This is useful when the argument of a function call is an [`ArcBorrow`] (e.g., in a method
21617f67160SWedson Almeida Filho     /// receiver), but we have an [`Arc`] instead. Getting an [`ArcBorrow`] is free when optimised.
21717f67160SWedson Almeida Filho     #[inline]
21817f67160SWedson Almeida Filho     pub fn as_arc_borrow(&self) -> ArcBorrow<'_, T> {
21917f67160SWedson Almeida Filho         // SAFETY: The constraint that the lifetime of the shared reference must outlive that of
22017f67160SWedson Almeida Filho         // the returned `ArcBorrow` ensures that the object remains alive and that no mutable
22117f67160SWedson Almeida Filho         // reference can be created.
22217f67160SWedson Almeida Filho         unsafe { ArcBorrow::new(self.ptr) }
22317f67160SWedson Almeida Filho     }
224bd780aeaSAlice Ryhl 
225bd780aeaSAlice Ryhl     /// Compare whether two [`Arc`] pointers reference the same underlying object.
226bd780aeaSAlice Ryhl     pub fn ptr_eq(this: &Self, other: &Self) -> bool {
227bd780aeaSAlice Ryhl         core::ptr::eq(this.ptr.as_ptr(), other.ptr.as_ptr())
228bd780aeaSAlice Ryhl     }
2299dc04365SWedson Almeida Filho }
2309dc04365SWedson Almeida Filho 
2310c7ae432SWedson Almeida Filho impl<T: 'static> ForeignOwnable for Arc<T> {
2320c7ae432SWedson Almeida Filho     type Borrowed<'a> = ArcBorrow<'a, T>;
2330c7ae432SWedson Almeida Filho 
2340c7ae432SWedson Almeida Filho     fn into_foreign(self) -> *const core::ffi::c_void {
2350c7ae432SWedson Almeida Filho         ManuallyDrop::new(self).ptr.as_ptr() as _
2360c7ae432SWedson Almeida Filho     }
2370c7ae432SWedson Almeida Filho 
2380c7ae432SWedson Almeida Filho     unsafe fn borrow<'a>(ptr: *const core::ffi::c_void) -> ArcBorrow<'a, T> {
2390c7ae432SWedson Almeida Filho         // SAFETY: By the safety requirement of this function, we know that `ptr` came from
2400c7ae432SWedson Almeida Filho         // a previous call to `Arc::into_foreign`.
2410c7ae432SWedson Almeida Filho         let inner = NonNull::new(ptr as *mut ArcInner<T>).unwrap();
2420c7ae432SWedson Almeida Filho 
2430c7ae432SWedson Almeida Filho         // SAFETY: The safety requirements of `from_foreign` ensure that the object remains alive
2440c7ae432SWedson Almeida Filho         // for the lifetime of the returned value. Additionally, the safety requirements of
2450c7ae432SWedson Almeida Filho         // `ForeignOwnable::borrow_mut` ensure that no new mutable references are created.
2460c7ae432SWedson Almeida Filho         unsafe { ArcBorrow::new(inner) }
2470c7ae432SWedson Almeida Filho     }
2480c7ae432SWedson Almeida Filho 
2490c7ae432SWedson Almeida Filho     unsafe fn from_foreign(ptr: *const core::ffi::c_void) -> Self {
2500c7ae432SWedson Almeida Filho         // SAFETY: By the safety requirement of this function, we know that `ptr` came from
2510c7ae432SWedson Almeida Filho         // a previous call to `Arc::into_foreign`, which guarantees that `ptr` is valid and
2520c7ae432SWedson Almeida Filho         // holds a reference count increment that is transferrable to us.
2530c7ae432SWedson Almeida Filho         unsafe { Self::from_inner(NonNull::new(ptr as _).unwrap()) }
2540c7ae432SWedson Almeida Filho     }
2550c7ae432SWedson Almeida Filho }
2560c7ae432SWedson Almeida Filho 
2579dc04365SWedson Almeida Filho impl<T: ?Sized> Deref for Arc<T> {
2589dc04365SWedson Almeida Filho     type Target = T;
2599dc04365SWedson Almeida Filho 
2609dc04365SWedson Almeida Filho     fn deref(&self) -> &Self::Target {
2619dc04365SWedson Almeida Filho         // SAFETY: By the type invariant, there is necessarily a reference to the object, so it is
2629dc04365SWedson Almeida Filho         // safe to dereference it.
2639dc04365SWedson Almeida Filho         unsafe { &self.ptr.as_ref().data }
2649dc04365SWedson Almeida Filho     }
2659dc04365SWedson Almeida Filho }
2669dc04365SWedson Almeida Filho 
267*47329ba1SAlice Ryhl impl<T: ?Sized> AsRef<T> for Arc<T> {
268*47329ba1SAlice Ryhl     fn as_ref(&self) -> &T {
269*47329ba1SAlice Ryhl         self.deref()
270*47329ba1SAlice Ryhl     }
271*47329ba1SAlice Ryhl }
272*47329ba1SAlice Ryhl 
2739dc04365SWedson Almeida Filho impl<T: ?Sized> Clone for Arc<T> {
2749dc04365SWedson Almeida Filho     fn clone(&self) -> Self {
2759dc04365SWedson Almeida Filho         // INVARIANT: C `refcount_inc` saturates the refcount, so it cannot overflow to zero.
2769dc04365SWedson Almeida Filho         // SAFETY: By the type invariant, there is necessarily a reference to the object, so it is
2779dc04365SWedson Almeida Filho         // safe to increment the refcount.
2789dc04365SWedson Almeida Filho         unsafe { bindings::refcount_inc(self.ptr.as_ref().refcount.get()) };
2799dc04365SWedson Almeida Filho 
2809dc04365SWedson Almeida Filho         // SAFETY: We just incremented the refcount. This increment is now owned by the new `Arc`.
2819dc04365SWedson Almeida Filho         unsafe { Self::from_inner(self.ptr) }
2829dc04365SWedson Almeida Filho     }
2839dc04365SWedson Almeida Filho }
2849dc04365SWedson Almeida Filho 
2859dc04365SWedson Almeida Filho impl<T: ?Sized> Drop for Arc<T> {
2869dc04365SWedson Almeida Filho     fn drop(&mut self) {
2879dc04365SWedson Almeida Filho         // SAFETY: By the type invariant, there is necessarily a reference to the object. We cannot
2889dc04365SWedson Almeida Filho         // touch `refcount` after it's decremented to a non-zero value because another thread/CPU
2899dc04365SWedson Almeida Filho         // may concurrently decrement it to zero and free it. It is ok to have a raw pointer to
2909dc04365SWedson Almeida Filho         // freed/invalid memory as long as it is never dereferenced.
2919dc04365SWedson Almeida Filho         let refcount = unsafe { self.ptr.as_ref() }.refcount.get();
2929dc04365SWedson Almeida Filho 
2939dc04365SWedson Almeida Filho         // INVARIANT: If the refcount reaches zero, there are no other instances of `Arc`, and
2949dc04365SWedson Almeida Filho         // this instance is being dropped, so the broken invariant is not observable.
2959dc04365SWedson Almeida Filho         // SAFETY: Also by the type invariant, we are allowed to decrement the refcount.
2969dc04365SWedson Almeida Filho         let is_zero = unsafe { bindings::refcount_dec_and_test(refcount) };
2979dc04365SWedson Almeida Filho         if is_zero {
2989dc04365SWedson Almeida Filho             // The count reached zero, we must free the memory.
2999dc04365SWedson Almeida Filho             //
3009dc04365SWedson Almeida Filho             // SAFETY: The pointer was initialised from the result of `Box::leak`.
3019dc04365SWedson Almeida Filho             unsafe { Box::from_raw(self.ptr.as_ptr()) };
3029dc04365SWedson Almeida Filho         }
3039dc04365SWedson Almeida Filho     }
3049dc04365SWedson Almeida Filho }
30517f67160SWedson Almeida Filho 
30670e42ebbSWedson Almeida Filho impl<T: ?Sized> From<UniqueArc<T>> for Arc<T> {
30770e42ebbSWedson Almeida Filho     fn from(item: UniqueArc<T>) -> Self {
30870e42ebbSWedson Almeida Filho         item.inner
30970e42ebbSWedson Almeida Filho     }
31070e42ebbSWedson Almeida Filho }
31170e42ebbSWedson Almeida Filho 
31270e42ebbSWedson Almeida Filho impl<T: ?Sized> From<Pin<UniqueArc<T>>> for Arc<T> {
31370e42ebbSWedson Almeida Filho     fn from(item: Pin<UniqueArc<T>>) -> Self {
31470e42ebbSWedson Almeida Filho         // SAFETY: The type invariants of `Arc` guarantee that the data is pinned.
31570e42ebbSWedson Almeida Filho         unsafe { Pin::into_inner_unchecked(item).inner }
31670e42ebbSWedson Almeida Filho     }
31770e42ebbSWedson Almeida Filho }
31870e42ebbSWedson Almeida Filho 
31917f67160SWedson Almeida Filho /// A borrowed reference to an [`Arc`] instance.
32017f67160SWedson Almeida Filho ///
32117f67160SWedson Almeida Filho /// For cases when one doesn't ever need to increment the refcount on the allocation, it is simpler
32217f67160SWedson Almeida Filho /// to use just `&T`, which we can trivially get from an `Arc<T>` instance.
32317f67160SWedson Almeida Filho ///
32417f67160SWedson Almeida Filho /// However, when one may need to increment the refcount, it is preferable to use an `ArcBorrow<T>`
32517f67160SWedson Almeida Filho /// over `&Arc<T>` because the latter results in a double-indirection: a pointer (shared reference)
32617f67160SWedson Almeida Filho /// to a pointer (`Arc<T>`) to the object (`T`). An [`ArcBorrow`] eliminates this double
32717f67160SWedson Almeida Filho /// indirection while still allowing one to increment the refcount and getting an `Arc<T>` when/if
32817f67160SWedson Almeida Filho /// needed.
32917f67160SWedson Almeida Filho ///
33017f67160SWedson Almeida Filho /// # Invariants
33117f67160SWedson Almeida Filho ///
33217f67160SWedson Almeida Filho /// There are no mutable references to the underlying [`Arc`], and it remains valid for the
33317f67160SWedson Almeida Filho /// lifetime of the [`ArcBorrow`] instance.
33417f67160SWedson Almeida Filho ///
33517f67160SWedson Almeida Filho /// # Example
33617f67160SWedson Almeida Filho ///
33717f67160SWedson Almeida Filho /// ```
33817f67160SWedson Almeida Filho /// use crate::sync::{Arc, ArcBorrow};
33917f67160SWedson Almeida Filho ///
34017f67160SWedson Almeida Filho /// struct Example;
34117f67160SWedson Almeida Filho ///
34217f67160SWedson Almeida Filho /// fn do_something(e: ArcBorrow<'_, Example>) -> Arc<Example> {
34317f67160SWedson Almeida Filho ///     e.into()
34417f67160SWedson Almeida Filho /// }
34517f67160SWedson Almeida Filho ///
34617f67160SWedson Almeida Filho /// let obj = Arc::try_new(Example)?;
34717f67160SWedson Almeida Filho /// let cloned = do_something(obj.as_arc_borrow());
34817f67160SWedson Almeida Filho ///
34917f67160SWedson Almeida Filho /// // Assert that both `obj` and `cloned` point to the same underlying object.
35017f67160SWedson Almeida Filho /// assert!(core::ptr::eq(&*obj, &*cloned));
35117f67160SWedson Almeida Filho /// ```
35292a655aeSWedson Almeida Filho ///
35392a655aeSWedson Almeida Filho /// Using `ArcBorrow<T>` as the type of `self`:
35492a655aeSWedson Almeida Filho ///
35592a655aeSWedson Almeida Filho /// ```
35692a655aeSWedson Almeida Filho /// use crate::sync::{Arc, ArcBorrow};
35792a655aeSWedson Almeida Filho ///
35892a655aeSWedson Almeida Filho /// struct Example {
35992a655aeSWedson Almeida Filho ///     a: u32,
36092a655aeSWedson Almeida Filho ///     b: u32,
36192a655aeSWedson Almeida Filho /// }
36292a655aeSWedson Almeida Filho ///
36392a655aeSWedson Almeida Filho /// impl Example {
36492a655aeSWedson Almeida Filho ///     fn use_reference(self: ArcBorrow<'_, Self>) {
36592a655aeSWedson Almeida Filho ///         // ...
36692a655aeSWedson Almeida Filho ///     }
36792a655aeSWedson Almeida Filho /// }
36892a655aeSWedson Almeida Filho ///
36992a655aeSWedson Almeida Filho /// let obj = Arc::try_new(Example { a: 10, b: 20 })?;
37092a655aeSWedson Almeida Filho /// obj.as_arc_borrow().use_reference();
37192a655aeSWedson Almeida Filho /// ```
37217f67160SWedson Almeida Filho pub struct ArcBorrow<'a, T: ?Sized + 'a> {
37317f67160SWedson Almeida Filho     inner: NonNull<ArcInner<T>>,
37417f67160SWedson Almeida Filho     _p: PhantomData<&'a ()>,
37517f67160SWedson Almeida Filho }
37617f67160SWedson Almeida Filho 
37792a655aeSWedson Almeida Filho // This is to allow [`ArcBorrow`] (and variants) to be used as the type of `self`.
37892a655aeSWedson Almeida Filho impl<T: ?Sized> core::ops::Receiver for ArcBorrow<'_, T> {}
37992a655aeSWedson Almeida Filho 
3800748424aSWedson Almeida Filho // This is to allow `ArcBorrow<U>` to be dispatched on when `ArcBorrow<T>` can be coerced into
3810748424aSWedson Almeida Filho // `ArcBorrow<U>`.
3820748424aSWedson Almeida Filho impl<T: ?Sized + Unsize<U>, U: ?Sized> core::ops::DispatchFromDyn<ArcBorrow<'_, U>>
3830748424aSWedson Almeida Filho     for ArcBorrow<'_, T>
3840748424aSWedson Almeida Filho {
3850748424aSWedson Almeida Filho }
3860748424aSWedson Almeida Filho 
38717f67160SWedson Almeida Filho impl<T: ?Sized> Clone for ArcBorrow<'_, T> {
38817f67160SWedson Almeida Filho     fn clone(&self) -> Self {
38917f67160SWedson Almeida Filho         *self
39017f67160SWedson Almeida Filho     }
39117f67160SWedson Almeida Filho }
39217f67160SWedson Almeida Filho 
39317f67160SWedson Almeida Filho impl<T: ?Sized> Copy for ArcBorrow<'_, T> {}
39417f67160SWedson Almeida Filho 
39517f67160SWedson Almeida Filho impl<T: ?Sized> ArcBorrow<'_, T> {
39617f67160SWedson Almeida Filho     /// Creates a new [`ArcBorrow`] instance.
39717f67160SWedson Almeida Filho     ///
39817f67160SWedson Almeida Filho     /// # Safety
39917f67160SWedson Almeida Filho     ///
40017f67160SWedson Almeida Filho     /// Callers must ensure the following for the lifetime of the returned [`ArcBorrow`] instance:
40117f67160SWedson Almeida Filho     /// 1. That `inner` remains valid;
40217f67160SWedson Almeida Filho     /// 2. That no mutable references to `inner` are created.
40317f67160SWedson Almeida Filho     unsafe fn new(inner: NonNull<ArcInner<T>>) -> Self {
40417f67160SWedson Almeida Filho         // INVARIANT: The safety requirements guarantee the invariants.
40517f67160SWedson Almeida Filho         Self {
40617f67160SWedson Almeida Filho             inner,
40717f67160SWedson Almeida Filho             _p: PhantomData,
40817f67160SWedson Almeida Filho         }
40917f67160SWedson Almeida Filho     }
41017f67160SWedson Almeida Filho }
41117f67160SWedson Almeida Filho 
41217f67160SWedson Almeida Filho impl<T: ?Sized> From<ArcBorrow<'_, T>> for Arc<T> {
41317f67160SWedson Almeida Filho     fn from(b: ArcBorrow<'_, T>) -> Self {
41417f67160SWedson Almeida Filho         // SAFETY: The existence of `b` guarantees that the refcount is non-zero. `ManuallyDrop`
41517f67160SWedson Almeida Filho         // guarantees that `drop` isn't called, so it's ok that the temporary `Arc` doesn't own the
41617f67160SWedson Almeida Filho         // increment.
41717f67160SWedson Almeida Filho         ManuallyDrop::new(unsafe { Arc::from_inner(b.inner) })
41817f67160SWedson Almeida Filho             .deref()
41917f67160SWedson Almeida Filho             .clone()
42017f67160SWedson Almeida Filho     }
42117f67160SWedson Almeida Filho }
42217f67160SWedson Almeida Filho 
42317f67160SWedson Almeida Filho impl<T: ?Sized> Deref for ArcBorrow<'_, T> {
42417f67160SWedson Almeida Filho     type Target = T;
42517f67160SWedson Almeida Filho 
42617f67160SWedson Almeida Filho     fn deref(&self) -> &Self::Target {
42717f67160SWedson Almeida Filho         // SAFETY: By the type invariant, the underlying object is still alive with no mutable
42817f67160SWedson Almeida Filho         // references to it, so it is safe to create a shared reference.
42917f67160SWedson Almeida Filho         unsafe { &self.inner.as_ref().data }
43017f67160SWedson Almeida Filho     }
43117f67160SWedson Almeida Filho }
43270e42ebbSWedson Almeida Filho 
43370e42ebbSWedson Almeida Filho /// A refcounted object that is known to have a refcount of 1.
43470e42ebbSWedson Almeida Filho ///
43570e42ebbSWedson Almeida Filho /// It is mutable and can be converted to an [`Arc`] so that it can be shared.
43670e42ebbSWedson Almeida Filho ///
43770e42ebbSWedson Almeida Filho /// # Invariants
43870e42ebbSWedson Almeida Filho ///
43970e42ebbSWedson Almeida Filho /// `inner` always has a reference count of 1.
44070e42ebbSWedson Almeida Filho ///
44170e42ebbSWedson Almeida Filho /// # Examples
44270e42ebbSWedson Almeida Filho ///
44370e42ebbSWedson Almeida Filho /// In the following example, we make changes to the inner object before turning it into an
44470e42ebbSWedson Almeida Filho /// `Arc<Test>` object (after which point, it cannot be mutated directly). Note that `x.into()`
44570e42ebbSWedson Almeida Filho /// cannot fail.
44670e42ebbSWedson Almeida Filho ///
44770e42ebbSWedson Almeida Filho /// ```
44870e42ebbSWedson Almeida Filho /// use kernel::sync::{Arc, UniqueArc};
44970e42ebbSWedson Almeida Filho ///
45070e42ebbSWedson Almeida Filho /// struct Example {
45170e42ebbSWedson Almeida Filho ///     a: u32,
45270e42ebbSWedson Almeida Filho ///     b: u32,
45370e42ebbSWedson Almeida Filho /// }
45470e42ebbSWedson Almeida Filho ///
45570e42ebbSWedson Almeida Filho /// fn test() -> Result<Arc<Example>> {
45670e42ebbSWedson Almeida Filho ///     let mut x = UniqueArc::try_new(Example { a: 10, b: 20 })?;
45770e42ebbSWedson Almeida Filho ///     x.a += 1;
45870e42ebbSWedson Almeida Filho ///     x.b += 1;
45970e42ebbSWedson Almeida Filho ///     Ok(x.into())
46070e42ebbSWedson Almeida Filho /// }
46170e42ebbSWedson Almeida Filho ///
46270e42ebbSWedson Almeida Filho /// # test().unwrap();
46370e42ebbSWedson Almeida Filho /// ```
46470e42ebbSWedson Almeida Filho ///
46570e42ebbSWedson Almeida Filho /// In the following example we first allocate memory for a ref-counted `Example` but we don't
46670e42ebbSWedson Almeida Filho /// initialise it on allocation. We do initialise it later with a call to [`UniqueArc::write`],
46770e42ebbSWedson Almeida Filho /// followed by a conversion to `Arc<Example>`. This is particularly useful when allocation happens
46870e42ebbSWedson Almeida Filho /// in one context (e.g., sleepable) and initialisation in another (e.g., atomic):
46970e42ebbSWedson Almeida Filho ///
47070e42ebbSWedson Almeida Filho /// ```
47170e42ebbSWedson Almeida Filho /// use kernel::sync::{Arc, UniqueArc};
47270e42ebbSWedson Almeida Filho ///
47370e42ebbSWedson Almeida Filho /// struct Example {
47470e42ebbSWedson Almeida Filho ///     a: u32,
47570e42ebbSWedson Almeida Filho ///     b: u32,
47670e42ebbSWedson Almeida Filho /// }
47770e42ebbSWedson Almeida Filho ///
47870e42ebbSWedson Almeida Filho /// fn test() -> Result<Arc<Example>> {
47970e42ebbSWedson Almeida Filho ///     let x = UniqueArc::try_new_uninit()?;
48070e42ebbSWedson Almeida Filho ///     Ok(x.write(Example { a: 10, b: 20 }).into())
48170e42ebbSWedson Almeida Filho /// }
48270e42ebbSWedson Almeida Filho ///
48370e42ebbSWedson Almeida Filho /// # test().unwrap();
48470e42ebbSWedson Almeida Filho /// ```
48570e42ebbSWedson Almeida Filho ///
48670e42ebbSWedson Almeida Filho /// In the last example below, the caller gets a pinned instance of `Example` while converting to
48770e42ebbSWedson Almeida Filho /// `Arc<Example>`; this is useful in scenarios where one needs a pinned reference during
48870e42ebbSWedson Almeida Filho /// initialisation, for example, when initialising fields that are wrapped in locks.
48970e42ebbSWedson Almeida Filho ///
49070e42ebbSWedson Almeida Filho /// ```
49170e42ebbSWedson Almeida Filho /// use kernel::sync::{Arc, UniqueArc};
49270e42ebbSWedson Almeida Filho ///
49370e42ebbSWedson Almeida Filho /// struct Example {
49470e42ebbSWedson Almeida Filho ///     a: u32,
49570e42ebbSWedson Almeida Filho ///     b: u32,
49670e42ebbSWedson Almeida Filho /// }
49770e42ebbSWedson Almeida Filho ///
49870e42ebbSWedson Almeida Filho /// fn test() -> Result<Arc<Example>> {
49970e42ebbSWedson Almeida Filho ///     let mut pinned = Pin::from(UniqueArc::try_new(Example { a: 10, b: 20 })?);
50070e42ebbSWedson Almeida Filho ///     // We can modify `pinned` because it is `Unpin`.
50170e42ebbSWedson Almeida Filho ///     pinned.as_mut().a += 1;
50270e42ebbSWedson Almeida Filho ///     Ok(pinned.into())
50370e42ebbSWedson Almeida Filho /// }
50470e42ebbSWedson Almeida Filho ///
50570e42ebbSWedson Almeida Filho /// # test().unwrap();
50670e42ebbSWedson Almeida Filho /// ```
50770e42ebbSWedson Almeida Filho pub struct UniqueArc<T: ?Sized> {
50870e42ebbSWedson Almeida Filho     inner: Arc<T>,
50970e42ebbSWedson Almeida Filho }
51070e42ebbSWedson Almeida Filho 
51170e42ebbSWedson Almeida Filho impl<T> UniqueArc<T> {
51270e42ebbSWedson Almeida Filho     /// Tries to allocate a new [`UniqueArc`] instance.
513d6dbca35SBenno Lossin     pub fn try_new(value: T) -> Result<Self, AllocError> {
51470e42ebbSWedson Almeida Filho         Ok(Self {
51570e42ebbSWedson Almeida Filho             // INVARIANT: The newly-created object has a ref-count of 1.
51670e42ebbSWedson Almeida Filho             inner: Arc::try_new(value)?,
51770e42ebbSWedson Almeida Filho         })
51870e42ebbSWedson Almeida Filho     }
51970e42ebbSWedson Almeida Filho 
52070e42ebbSWedson Almeida Filho     /// Tries to allocate a new [`UniqueArc`] instance whose contents are not initialised yet.
521d6dbca35SBenno Lossin     pub fn try_new_uninit() -> Result<UniqueArc<MaybeUninit<T>>, AllocError> {
522701608bdSBenno Lossin         // INVARIANT: The refcount is initialised to a non-zero value.
523701608bdSBenno Lossin         let inner = Box::try_init::<AllocError>(try_init!(ArcInner {
524701608bdSBenno Lossin             // SAFETY: There are no safety requirements for this FFI call.
525701608bdSBenno Lossin             refcount: Opaque::new(unsafe { bindings::REFCOUNT_INIT(1) }),
526701608bdSBenno Lossin             data <- init::uninit::<T, AllocError>(),
527701608bdSBenno Lossin         }? AllocError))?;
528701608bdSBenno Lossin         Ok(UniqueArc {
52970e42ebbSWedson Almeida Filho             // INVARIANT: The newly-created object has a ref-count of 1.
530701608bdSBenno Lossin             // SAFETY: The pointer from the `Box` is valid.
531701608bdSBenno Lossin             inner: unsafe { Arc::from_inner(Box::leak(inner).into()) },
53270e42ebbSWedson Almeida Filho         })
53370e42ebbSWedson Almeida Filho     }
53470e42ebbSWedson Almeida Filho }
53570e42ebbSWedson Almeida Filho 
53670e42ebbSWedson Almeida Filho impl<T> UniqueArc<MaybeUninit<T>> {
53770e42ebbSWedson Almeida Filho     /// Converts a `UniqueArc<MaybeUninit<T>>` into a `UniqueArc<T>` by writing a value into it.
53870e42ebbSWedson Almeida Filho     pub fn write(mut self, value: T) -> UniqueArc<T> {
53970e42ebbSWedson Almeida Filho         self.deref_mut().write(value);
54031d95c2fSAsahi Lina         // SAFETY: We just wrote the value to be initialized.
54131d95c2fSAsahi Lina         unsafe { self.assume_init() }
54231d95c2fSAsahi Lina     }
54331d95c2fSAsahi Lina 
54431d95c2fSAsahi Lina     /// Unsafely assume that `self` is initialized.
54531d95c2fSAsahi Lina     ///
54631d95c2fSAsahi Lina     /// # Safety
54731d95c2fSAsahi Lina     ///
54831d95c2fSAsahi Lina     /// The caller guarantees that the value behind this pointer has been initialized. It is
54931d95c2fSAsahi Lina     /// *immediate* UB to call this when the value is not initialized.
55031d95c2fSAsahi Lina     pub unsafe fn assume_init(self) -> UniqueArc<T> {
55170e42ebbSWedson Almeida Filho         let inner = ManuallyDrop::new(self).inner.ptr;
55270e42ebbSWedson Almeida Filho         UniqueArc {
55370e42ebbSWedson Almeida Filho             // SAFETY: The new `Arc` is taking over `ptr` from `self.inner` (which won't be
55470e42ebbSWedson Almeida Filho             // dropped). The types are compatible because `MaybeUninit<T>` is compatible with `T`.
55570e42ebbSWedson Almeida Filho             inner: unsafe { Arc::from_inner(inner.cast()) },
55670e42ebbSWedson Almeida Filho         }
55770e42ebbSWedson Almeida Filho     }
5581944caa8SBenno Lossin 
5591944caa8SBenno Lossin     /// Initialize `self` using the given initializer.
5601944caa8SBenno Lossin     pub fn init_with<E>(mut self, init: impl Init<T, E>) -> core::result::Result<UniqueArc<T>, E> {
5611944caa8SBenno Lossin         // SAFETY: The supplied pointer is valid for initialization.
5621944caa8SBenno Lossin         match unsafe { init.__init(self.as_mut_ptr()) } {
5631944caa8SBenno Lossin             // SAFETY: Initialization completed successfully.
5641944caa8SBenno Lossin             Ok(()) => Ok(unsafe { self.assume_init() }),
5651944caa8SBenno Lossin             Err(err) => Err(err),
5661944caa8SBenno Lossin         }
5671944caa8SBenno Lossin     }
5681944caa8SBenno Lossin 
5691944caa8SBenno Lossin     /// Pin-initialize `self` using the given pin-initializer.
5701944caa8SBenno Lossin     pub fn pin_init_with<E>(
5711944caa8SBenno Lossin         mut self,
5721944caa8SBenno Lossin         init: impl PinInit<T, E>,
5731944caa8SBenno Lossin     ) -> core::result::Result<Pin<UniqueArc<T>>, E> {
5741944caa8SBenno Lossin         // SAFETY: The supplied pointer is valid for initialization and we will later pin the value
5751944caa8SBenno Lossin         // to ensure it does not move.
5761944caa8SBenno Lossin         match unsafe { init.__pinned_init(self.as_mut_ptr()) } {
5771944caa8SBenno Lossin             // SAFETY: Initialization completed successfully.
5781944caa8SBenno Lossin             Ok(()) => Ok(unsafe { self.assume_init() }.into()),
5791944caa8SBenno Lossin             Err(err) => Err(err),
5801944caa8SBenno Lossin         }
5811944caa8SBenno Lossin     }
58270e42ebbSWedson Almeida Filho }
58370e42ebbSWedson Almeida Filho 
58470e42ebbSWedson Almeida Filho impl<T: ?Sized> From<UniqueArc<T>> for Pin<UniqueArc<T>> {
58570e42ebbSWedson Almeida Filho     fn from(obj: UniqueArc<T>) -> Self {
58670e42ebbSWedson Almeida Filho         // SAFETY: It is not possible to move/replace `T` inside a `Pin<UniqueArc<T>>` (unless `T`
58770e42ebbSWedson Almeida Filho         // is `Unpin`), so it is ok to convert it to `Pin<UniqueArc<T>>`.
58870e42ebbSWedson Almeida Filho         unsafe { Pin::new_unchecked(obj) }
58970e42ebbSWedson Almeida Filho     }
59070e42ebbSWedson Almeida Filho }
59170e42ebbSWedson Almeida Filho 
59270e42ebbSWedson Almeida Filho impl<T: ?Sized> Deref for UniqueArc<T> {
59370e42ebbSWedson Almeida Filho     type Target = T;
59470e42ebbSWedson Almeida Filho 
59570e42ebbSWedson Almeida Filho     fn deref(&self) -> &Self::Target {
59670e42ebbSWedson Almeida Filho         self.inner.deref()
59770e42ebbSWedson Almeida Filho     }
59870e42ebbSWedson Almeida Filho }
59970e42ebbSWedson Almeida Filho 
60070e42ebbSWedson Almeida Filho impl<T: ?Sized> DerefMut for UniqueArc<T> {
60170e42ebbSWedson Almeida Filho     fn deref_mut(&mut self) -> &mut Self::Target {
60270e42ebbSWedson Almeida Filho         // SAFETY: By the `Arc` type invariant, there is necessarily a reference to the object, so
60370e42ebbSWedson Almeida Filho         // it is safe to dereference it. Additionally, we know there is only one reference when
60470e42ebbSWedson Almeida Filho         // it's inside a `UniqueArc`, so it is safe to get a mutable reference.
60570e42ebbSWedson Almeida Filho         unsafe { &mut self.inner.ptr.as_mut().data }
60670e42ebbSWedson Almeida Filho     }
60770e42ebbSWedson Almeida Filho }
60800140a83SBoqun Feng 
60900140a83SBoqun Feng impl<T: fmt::Display + ?Sized> fmt::Display for UniqueArc<T> {
61000140a83SBoqun Feng     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61100140a83SBoqun Feng         fmt::Display::fmt(self.deref(), f)
61200140a83SBoqun Feng     }
61300140a83SBoqun Feng }
61400140a83SBoqun Feng 
61500140a83SBoqun Feng impl<T: fmt::Display + ?Sized> fmt::Display for Arc<T> {
61600140a83SBoqun Feng     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61700140a83SBoqun Feng         fmt::Display::fmt(self.deref(), f)
61800140a83SBoqun Feng     }
61900140a83SBoqun Feng }
62000140a83SBoqun Feng 
62100140a83SBoqun Feng impl<T: fmt::Debug + ?Sized> fmt::Debug for UniqueArc<T> {
62200140a83SBoqun Feng     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62300140a83SBoqun Feng         fmt::Debug::fmt(self.deref(), f)
62400140a83SBoqun Feng     }
62500140a83SBoqun Feng }
62600140a83SBoqun Feng 
62700140a83SBoqun Feng impl<T: fmt::Debug + ?Sized> fmt::Debug for Arc<T> {
62800140a83SBoqun Feng     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62900140a83SBoqun Feng         fmt::Debug::fmt(self.deref(), f)
63000140a83SBoqun Feng     }
63100140a83SBoqun Feng }
632