xref: /openbmc/linux/rust/kernel/sync/arc.rs (revision 70e42ebbf6416e8005d8e08ae521b7d5cc5a8b3a)
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 
189dc04365SWedson Almeida Filho use crate::{bindings, error::Result, types::Opaque};
199dc04365SWedson Almeida Filho use alloc::boxed::Box;
20f75cb6fcSWedson Almeida Filho use core::{
21f75cb6fcSWedson Almeida Filho     marker::{PhantomData, Unsize},
22*70e42ebbSWedson Almeida Filho     mem::{ManuallyDrop, MaybeUninit},
23*70e42ebbSWedson Almeida Filho     ops::{Deref, DerefMut},
24*70e42ebbSWedson Almeida Filho     pin::Pin,
25f75cb6fcSWedson Almeida Filho     ptr::NonNull,
26f75cb6fcSWedson Almeida Filho };
279dc04365SWedson Almeida Filho 
289dc04365SWedson Almeida Filho /// A reference-counted pointer to an instance of `T`.
299dc04365SWedson Almeida Filho ///
309dc04365SWedson Almeida Filho /// The reference count is incremented when new instances of [`Arc`] are created, and decremented
319dc04365SWedson Almeida Filho /// when they are dropped. When the count reaches zero, the underlying `T` is also dropped.
329dc04365SWedson Almeida Filho ///
339dc04365SWedson Almeida Filho /// # Invariants
349dc04365SWedson Almeida Filho ///
359dc04365SWedson Almeida Filho /// The reference count on an instance of [`Arc`] is always non-zero.
369dc04365SWedson Almeida Filho /// The object pointed to by [`Arc`] is always pinned.
379dc04365SWedson Almeida Filho ///
389dc04365SWedson Almeida Filho /// # Examples
399dc04365SWedson Almeida Filho ///
409dc04365SWedson Almeida Filho /// ```
419dc04365SWedson Almeida Filho /// use kernel::sync::Arc;
429dc04365SWedson Almeida Filho ///
439dc04365SWedson Almeida Filho /// struct Example {
449dc04365SWedson Almeida Filho ///     a: u32,
459dc04365SWedson Almeida Filho ///     b: u32,
469dc04365SWedson Almeida Filho /// }
479dc04365SWedson Almeida Filho ///
489dc04365SWedson Almeida Filho /// // Create a ref-counted instance of `Example`.
499dc04365SWedson Almeida Filho /// let obj = Arc::try_new(Example { a: 10, b: 20 })?;
509dc04365SWedson Almeida Filho ///
519dc04365SWedson Almeida Filho /// // Get a new pointer to `obj` and increment the refcount.
529dc04365SWedson Almeida Filho /// let cloned = obj.clone();
539dc04365SWedson Almeida Filho ///
549dc04365SWedson Almeida Filho /// // Assert that both `obj` and `cloned` point to the same underlying object.
559dc04365SWedson Almeida Filho /// assert!(core::ptr::eq(&*obj, &*cloned));
569dc04365SWedson Almeida Filho ///
579dc04365SWedson Almeida Filho /// // Destroy `obj` and decrement its refcount.
589dc04365SWedson Almeida Filho /// drop(obj);
599dc04365SWedson Almeida Filho ///
609dc04365SWedson Almeida Filho /// // Check that the values are still accessible through `cloned`.
619dc04365SWedson Almeida Filho /// assert_eq!(cloned.a, 10);
629dc04365SWedson Almeida Filho /// assert_eq!(cloned.b, 20);
639dc04365SWedson Almeida Filho ///
649dc04365SWedson Almeida Filho /// // The refcount drops to zero when `cloned` goes out of scope, and the memory is freed.
659dc04365SWedson Almeida Filho /// ```
6653528772SWedson Almeida Filho ///
6753528772SWedson Almeida Filho /// Using `Arc<T>` as the type of `self`:
6853528772SWedson Almeida Filho ///
6953528772SWedson Almeida Filho /// ```
7053528772SWedson Almeida Filho /// use kernel::sync::Arc;
7153528772SWedson Almeida Filho ///
7253528772SWedson Almeida Filho /// struct Example {
7353528772SWedson Almeida Filho ///     a: u32,
7453528772SWedson Almeida Filho ///     b: u32,
7553528772SWedson Almeida Filho /// }
7653528772SWedson Almeida Filho ///
7753528772SWedson Almeida Filho /// impl Example {
7853528772SWedson Almeida Filho ///     fn take_over(self: Arc<Self>) {
7953528772SWedson Almeida Filho ///         // ...
8053528772SWedson Almeida Filho ///     }
8153528772SWedson Almeida Filho ///
8253528772SWedson Almeida Filho ///     fn use_reference(self: &Arc<Self>) {
8353528772SWedson Almeida Filho ///         // ...
8453528772SWedson Almeida Filho ///     }
8553528772SWedson Almeida Filho /// }
8653528772SWedson Almeida Filho ///
8753528772SWedson Almeida Filho /// let obj = Arc::try_new(Example { a: 10, b: 20 })?;
8853528772SWedson Almeida Filho /// obj.use_reference();
8953528772SWedson Almeida Filho /// obj.take_over();
9053528772SWedson Almeida Filho /// ```
91f75cb6fcSWedson Almeida Filho ///
92f75cb6fcSWedson Almeida Filho /// Coercion from `Arc<Example>` to `Arc<dyn MyTrait>`:
93f75cb6fcSWedson Almeida Filho ///
94f75cb6fcSWedson Almeida Filho /// ```
95f75cb6fcSWedson Almeida Filho /// use kernel::sync::Arc;
96f75cb6fcSWedson Almeida Filho ///
97f75cb6fcSWedson Almeida Filho /// trait MyTrait {}
98f75cb6fcSWedson Almeida Filho ///
99f75cb6fcSWedson Almeida Filho /// struct Example;
100f75cb6fcSWedson Almeida Filho /// impl MyTrait for Example {}
101f75cb6fcSWedson Almeida Filho ///
102f75cb6fcSWedson Almeida Filho /// // `obj` has type `Arc<Example>`.
103f75cb6fcSWedson Almeida Filho /// let obj: Arc<Example> = Arc::try_new(Example)?;
104f75cb6fcSWedson Almeida Filho ///
105f75cb6fcSWedson Almeida Filho /// // `coerced` has type `Arc<dyn MyTrait>`.
106f75cb6fcSWedson Almeida Filho /// let coerced: Arc<dyn MyTrait> = obj;
107f75cb6fcSWedson Almeida Filho /// ```
1089dc04365SWedson Almeida Filho pub struct Arc<T: ?Sized> {
1099dc04365SWedson Almeida Filho     ptr: NonNull<ArcInner<T>>,
1109dc04365SWedson Almeida Filho     _p: PhantomData<ArcInner<T>>,
1119dc04365SWedson Almeida Filho }
1129dc04365SWedson Almeida Filho 
1139dc04365SWedson Almeida Filho #[repr(C)]
1149dc04365SWedson Almeida Filho struct ArcInner<T: ?Sized> {
1159dc04365SWedson Almeida Filho     refcount: Opaque<bindings::refcount_t>,
1169dc04365SWedson Almeida Filho     data: T,
1179dc04365SWedson Almeida Filho }
1189dc04365SWedson Almeida Filho 
11953528772SWedson Almeida Filho // This is to allow [`Arc`] (and variants) to be used as the type of `self`.
12053528772SWedson Almeida Filho impl<T: ?Sized> core::ops::Receiver for Arc<T> {}
12153528772SWedson Almeida Filho 
122f75cb6fcSWedson Almeida Filho // This is to allow coercion from `Arc<T>` to `Arc<U>` if `T` can be converted to the
123f75cb6fcSWedson Almeida Filho // dynamically-sized type (DST) `U`.
124f75cb6fcSWedson Almeida Filho impl<T: ?Sized + Unsize<U>, U: ?Sized> core::ops::CoerceUnsized<Arc<U>> for Arc<T> {}
125f75cb6fcSWedson Almeida Filho 
1269dc04365SWedson Almeida Filho // SAFETY: It is safe to send `Arc<T>` to another thread when the underlying `T` is `Sync` because
1279dc04365SWedson Almeida Filho // it effectively means sharing `&T` (which is safe because `T` is `Sync`); additionally, it needs
1289dc04365SWedson Almeida Filho // `T` to be `Send` because any thread that has an `Arc<T>` may ultimately access `T` directly, for
1299dc04365SWedson Almeida Filho // example, when the reference count reaches zero and `T` is dropped.
1309dc04365SWedson Almeida Filho unsafe impl<T: ?Sized + Sync + Send> Send for Arc<T> {}
1319dc04365SWedson Almeida Filho 
1329dc04365SWedson Almeida Filho // SAFETY: It is safe to send `&Arc<T>` to another thread when the underlying `T` is `Sync` for the
1339dc04365SWedson Almeida Filho // same reason as above. `T` needs to be `Send` as well because a thread can clone an `&Arc<T>`
1349dc04365SWedson Almeida Filho // into an `Arc<T>`, which may lead to `T` being accessed by the same reasoning as above.
1359dc04365SWedson Almeida Filho unsafe impl<T: ?Sized + Sync + Send> Sync for Arc<T> {}
1369dc04365SWedson Almeida Filho 
1379dc04365SWedson Almeida Filho impl<T> Arc<T> {
1389dc04365SWedson Almeida Filho     /// Constructs a new reference counted instance of `T`.
1399dc04365SWedson Almeida Filho     pub fn try_new(contents: T) -> Result<Self> {
1409dc04365SWedson Almeida Filho         // INVARIANT: The refcount is initialised to a non-zero value.
1419dc04365SWedson Almeida Filho         let value = ArcInner {
1429dc04365SWedson Almeida Filho             // SAFETY: There are no safety requirements for this FFI call.
1439dc04365SWedson Almeida Filho             refcount: Opaque::new(unsafe { bindings::REFCOUNT_INIT(1) }),
1449dc04365SWedson Almeida Filho             data: contents,
1459dc04365SWedson Almeida Filho         };
1469dc04365SWedson Almeida Filho 
1479dc04365SWedson Almeida Filho         let inner = Box::try_new(value)?;
1489dc04365SWedson Almeida Filho 
1499dc04365SWedson Almeida Filho         // SAFETY: We just created `inner` with a reference count of 1, which is owned by the new
1509dc04365SWedson Almeida Filho         // `Arc` object.
1519dc04365SWedson Almeida Filho         Ok(unsafe { Self::from_inner(Box::leak(inner).into()) })
1529dc04365SWedson Almeida Filho     }
1539dc04365SWedson Almeida Filho }
1549dc04365SWedson Almeida Filho 
1559dc04365SWedson Almeida Filho impl<T: ?Sized> Arc<T> {
1569dc04365SWedson Almeida Filho     /// Constructs a new [`Arc`] from an existing [`ArcInner`].
1579dc04365SWedson Almeida Filho     ///
1589dc04365SWedson Almeida Filho     /// # Safety
1599dc04365SWedson Almeida Filho     ///
1609dc04365SWedson Almeida Filho     /// The caller must ensure that `inner` points to a valid location and has a non-zero reference
1619dc04365SWedson Almeida Filho     /// count, one of which will be owned by the new [`Arc`] instance.
1629dc04365SWedson Almeida Filho     unsafe fn from_inner(inner: NonNull<ArcInner<T>>) -> Self {
1639dc04365SWedson Almeida Filho         // INVARIANT: By the safety requirements, the invariants hold.
1649dc04365SWedson Almeida Filho         Arc {
1659dc04365SWedson Almeida Filho             ptr: inner,
1669dc04365SWedson Almeida Filho             _p: PhantomData,
1679dc04365SWedson Almeida Filho         }
1689dc04365SWedson Almeida Filho     }
16917f67160SWedson Almeida Filho 
17017f67160SWedson Almeida Filho     /// Returns an [`ArcBorrow`] from the given [`Arc`].
17117f67160SWedson Almeida Filho     ///
17217f67160SWedson Almeida Filho     /// This is useful when the argument of a function call is an [`ArcBorrow`] (e.g., in a method
17317f67160SWedson Almeida Filho     /// receiver), but we have an [`Arc`] instead. Getting an [`ArcBorrow`] is free when optimised.
17417f67160SWedson Almeida Filho     #[inline]
17517f67160SWedson Almeida Filho     pub fn as_arc_borrow(&self) -> ArcBorrow<'_, T> {
17617f67160SWedson Almeida Filho         // SAFETY: The constraint that the lifetime of the shared reference must outlive that of
17717f67160SWedson Almeida Filho         // the returned `ArcBorrow` ensures that the object remains alive and that no mutable
17817f67160SWedson Almeida Filho         // reference can be created.
17917f67160SWedson Almeida Filho         unsafe { ArcBorrow::new(self.ptr) }
18017f67160SWedson Almeida Filho     }
1819dc04365SWedson Almeida Filho }
1829dc04365SWedson Almeida Filho 
1839dc04365SWedson Almeida Filho impl<T: ?Sized> Deref for Arc<T> {
1849dc04365SWedson Almeida Filho     type Target = T;
1859dc04365SWedson Almeida Filho 
1869dc04365SWedson Almeida Filho     fn deref(&self) -> &Self::Target {
1879dc04365SWedson Almeida Filho         // SAFETY: By the type invariant, there is necessarily a reference to the object, so it is
1889dc04365SWedson Almeida Filho         // safe to dereference it.
1899dc04365SWedson Almeida Filho         unsafe { &self.ptr.as_ref().data }
1909dc04365SWedson Almeida Filho     }
1919dc04365SWedson Almeida Filho }
1929dc04365SWedson Almeida Filho 
1939dc04365SWedson Almeida Filho impl<T: ?Sized> Clone for Arc<T> {
1949dc04365SWedson Almeida Filho     fn clone(&self) -> Self {
1959dc04365SWedson Almeida Filho         // INVARIANT: C `refcount_inc` saturates the refcount, so it cannot overflow to zero.
1969dc04365SWedson Almeida Filho         // SAFETY: By the type invariant, there is necessarily a reference to the object, so it is
1979dc04365SWedson Almeida Filho         // safe to increment the refcount.
1989dc04365SWedson Almeida Filho         unsafe { bindings::refcount_inc(self.ptr.as_ref().refcount.get()) };
1999dc04365SWedson Almeida Filho 
2009dc04365SWedson Almeida Filho         // SAFETY: We just incremented the refcount. This increment is now owned by the new `Arc`.
2019dc04365SWedson Almeida Filho         unsafe { Self::from_inner(self.ptr) }
2029dc04365SWedson Almeida Filho     }
2039dc04365SWedson Almeida Filho }
2049dc04365SWedson Almeida Filho 
2059dc04365SWedson Almeida Filho impl<T: ?Sized> Drop for Arc<T> {
2069dc04365SWedson Almeida Filho     fn drop(&mut self) {
2079dc04365SWedson Almeida Filho         // SAFETY: By the type invariant, there is necessarily a reference to the object. We cannot
2089dc04365SWedson Almeida Filho         // touch `refcount` after it's decremented to a non-zero value because another thread/CPU
2099dc04365SWedson Almeida Filho         // may concurrently decrement it to zero and free it. It is ok to have a raw pointer to
2109dc04365SWedson Almeida Filho         // freed/invalid memory as long as it is never dereferenced.
2119dc04365SWedson Almeida Filho         let refcount = unsafe { self.ptr.as_ref() }.refcount.get();
2129dc04365SWedson Almeida Filho 
2139dc04365SWedson Almeida Filho         // INVARIANT: If the refcount reaches zero, there are no other instances of `Arc`, and
2149dc04365SWedson Almeida Filho         // this instance is being dropped, so the broken invariant is not observable.
2159dc04365SWedson Almeida Filho         // SAFETY: Also by the type invariant, we are allowed to decrement the refcount.
2169dc04365SWedson Almeida Filho         let is_zero = unsafe { bindings::refcount_dec_and_test(refcount) };
2179dc04365SWedson Almeida Filho         if is_zero {
2189dc04365SWedson Almeida Filho             // The count reached zero, we must free the memory.
2199dc04365SWedson Almeida Filho             //
2209dc04365SWedson Almeida Filho             // SAFETY: The pointer was initialised from the result of `Box::leak`.
2219dc04365SWedson Almeida Filho             unsafe { Box::from_raw(self.ptr.as_ptr()) };
2229dc04365SWedson Almeida Filho         }
2239dc04365SWedson Almeida Filho     }
2249dc04365SWedson Almeida Filho }
22517f67160SWedson Almeida Filho 
226*70e42ebbSWedson Almeida Filho impl<T: ?Sized> From<UniqueArc<T>> for Arc<T> {
227*70e42ebbSWedson Almeida Filho     fn from(item: UniqueArc<T>) -> Self {
228*70e42ebbSWedson Almeida Filho         item.inner
229*70e42ebbSWedson Almeida Filho     }
230*70e42ebbSWedson Almeida Filho }
231*70e42ebbSWedson Almeida Filho 
232*70e42ebbSWedson Almeida Filho impl<T: ?Sized> From<Pin<UniqueArc<T>>> for Arc<T> {
233*70e42ebbSWedson Almeida Filho     fn from(item: Pin<UniqueArc<T>>) -> Self {
234*70e42ebbSWedson Almeida Filho         // SAFETY: The type invariants of `Arc` guarantee that the data is pinned.
235*70e42ebbSWedson Almeida Filho         unsafe { Pin::into_inner_unchecked(item).inner }
236*70e42ebbSWedson Almeida Filho     }
237*70e42ebbSWedson Almeida Filho }
238*70e42ebbSWedson Almeida Filho 
23917f67160SWedson Almeida Filho /// A borrowed reference to an [`Arc`] instance.
24017f67160SWedson Almeida Filho ///
24117f67160SWedson Almeida Filho /// For cases when one doesn't ever need to increment the refcount on the allocation, it is simpler
24217f67160SWedson Almeida Filho /// to use just `&T`, which we can trivially get from an `Arc<T>` instance.
24317f67160SWedson Almeida Filho ///
24417f67160SWedson Almeida Filho /// However, when one may need to increment the refcount, it is preferable to use an `ArcBorrow<T>`
24517f67160SWedson Almeida Filho /// over `&Arc<T>` because the latter results in a double-indirection: a pointer (shared reference)
24617f67160SWedson Almeida Filho /// to a pointer (`Arc<T>`) to the object (`T`). An [`ArcBorrow`] eliminates this double
24717f67160SWedson Almeida Filho /// indirection while still allowing one to increment the refcount and getting an `Arc<T>` when/if
24817f67160SWedson Almeida Filho /// needed.
24917f67160SWedson Almeida Filho ///
25017f67160SWedson Almeida Filho /// # Invariants
25117f67160SWedson Almeida Filho ///
25217f67160SWedson Almeida Filho /// There are no mutable references to the underlying [`Arc`], and it remains valid for the
25317f67160SWedson Almeida Filho /// lifetime of the [`ArcBorrow`] instance.
25417f67160SWedson Almeida Filho ///
25517f67160SWedson Almeida Filho /// # Example
25617f67160SWedson Almeida Filho ///
25717f67160SWedson Almeida Filho /// ```
25817f67160SWedson Almeida Filho /// use crate::sync::{Arc, ArcBorrow};
25917f67160SWedson Almeida Filho ///
26017f67160SWedson Almeida Filho /// struct Example;
26117f67160SWedson Almeida Filho ///
26217f67160SWedson Almeida Filho /// fn do_something(e: ArcBorrow<'_, Example>) -> Arc<Example> {
26317f67160SWedson Almeida Filho ///     e.into()
26417f67160SWedson Almeida Filho /// }
26517f67160SWedson Almeida Filho ///
26617f67160SWedson Almeida Filho /// let obj = Arc::try_new(Example)?;
26717f67160SWedson Almeida Filho /// let cloned = do_something(obj.as_arc_borrow());
26817f67160SWedson Almeida Filho ///
26917f67160SWedson Almeida Filho /// // Assert that both `obj` and `cloned` point to the same underlying object.
27017f67160SWedson Almeida Filho /// assert!(core::ptr::eq(&*obj, &*cloned));
27117f67160SWedson Almeida Filho /// ```
27292a655aeSWedson Almeida Filho ///
27392a655aeSWedson Almeida Filho /// Using `ArcBorrow<T>` as the type of `self`:
27492a655aeSWedson Almeida Filho ///
27592a655aeSWedson Almeida Filho /// ```
27692a655aeSWedson Almeida Filho /// use crate::sync::{Arc, ArcBorrow};
27792a655aeSWedson Almeida Filho ///
27892a655aeSWedson Almeida Filho /// struct Example {
27992a655aeSWedson Almeida Filho ///     a: u32,
28092a655aeSWedson Almeida Filho ///     b: u32,
28192a655aeSWedson Almeida Filho /// }
28292a655aeSWedson Almeida Filho ///
28392a655aeSWedson Almeida Filho /// impl Example {
28492a655aeSWedson Almeida Filho ///     fn use_reference(self: ArcBorrow<'_, Self>) {
28592a655aeSWedson Almeida Filho ///         // ...
28692a655aeSWedson Almeida Filho ///     }
28792a655aeSWedson Almeida Filho /// }
28892a655aeSWedson Almeida Filho ///
28992a655aeSWedson Almeida Filho /// let obj = Arc::try_new(Example { a: 10, b: 20 })?;
29092a655aeSWedson Almeida Filho /// obj.as_arc_borrow().use_reference();
29192a655aeSWedson Almeida Filho /// ```
29217f67160SWedson Almeida Filho pub struct ArcBorrow<'a, T: ?Sized + 'a> {
29317f67160SWedson Almeida Filho     inner: NonNull<ArcInner<T>>,
29417f67160SWedson Almeida Filho     _p: PhantomData<&'a ()>,
29517f67160SWedson Almeida Filho }
29617f67160SWedson Almeida Filho 
29792a655aeSWedson Almeida Filho // This is to allow [`ArcBorrow`] (and variants) to be used as the type of `self`.
29892a655aeSWedson Almeida Filho impl<T: ?Sized> core::ops::Receiver for ArcBorrow<'_, T> {}
29992a655aeSWedson Almeida Filho 
30017f67160SWedson Almeida Filho impl<T: ?Sized> Clone for ArcBorrow<'_, T> {
30117f67160SWedson Almeida Filho     fn clone(&self) -> Self {
30217f67160SWedson Almeida Filho         *self
30317f67160SWedson Almeida Filho     }
30417f67160SWedson Almeida Filho }
30517f67160SWedson Almeida Filho 
30617f67160SWedson Almeida Filho impl<T: ?Sized> Copy for ArcBorrow<'_, T> {}
30717f67160SWedson Almeida Filho 
30817f67160SWedson Almeida Filho impl<T: ?Sized> ArcBorrow<'_, T> {
30917f67160SWedson Almeida Filho     /// Creates a new [`ArcBorrow`] instance.
31017f67160SWedson Almeida Filho     ///
31117f67160SWedson Almeida Filho     /// # Safety
31217f67160SWedson Almeida Filho     ///
31317f67160SWedson Almeida Filho     /// Callers must ensure the following for the lifetime of the returned [`ArcBorrow`] instance:
31417f67160SWedson Almeida Filho     /// 1. That `inner` remains valid;
31517f67160SWedson Almeida Filho     /// 2. That no mutable references to `inner` are created.
31617f67160SWedson Almeida Filho     unsafe fn new(inner: NonNull<ArcInner<T>>) -> Self {
31717f67160SWedson Almeida Filho         // INVARIANT: The safety requirements guarantee the invariants.
31817f67160SWedson Almeida Filho         Self {
31917f67160SWedson Almeida Filho             inner,
32017f67160SWedson Almeida Filho             _p: PhantomData,
32117f67160SWedson Almeida Filho         }
32217f67160SWedson Almeida Filho     }
32317f67160SWedson Almeida Filho }
32417f67160SWedson Almeida Filho 
32517f67160SWedson Almeida Filho impl<T: ?Sized> From<ArcBorrow<'_, T>> for Arc<T> {
32617f67160SWedson Almeida Filho     fn from(b: ArcBorrow<'_, T>) -> Self {
32717f67160SWedson Almeida Filho         // SAFETY: The existence of `b` guarantees that the refcount is non-zero. `ManuallyDrop`
32817f67160SWedson Almeida Filho         // guarantees that `drop` isn't called, so it's ok that the temporary `Arc` doesn't own the
32917f67160SWedson Almeida Filho         // increment.
33017f67160SWedson Almeida Filho         ManuallyDrop::new(unsafe { Arc::from_inner(b.inner) })
33117f67160SWedson Almeida Filho             .deref()
33217f67160SWedson Almeida Filho             .clone()
33317f67160SWedson Almeida Filho     }
33417f67160SWedson Almeida Filho }
33517f67160SWedson Almeida Filho 
33617f67160SWedson Almeida Filho impl<T: ?Sized> Deref for ArcBorrow<'_, T> {
33717f67160SWedson Almeida Filho     type Target = T;
33817f67160SWedson Almeida Filho 
33917f67160SWedson Almeida Filho     fn deref(&self) -> &Self::Target {
34017f67160SWedson Almeida Filho         // SAFETY: By the type invariant, the underlying object is still alive with no mutable
34117f67160SWedson Almeida Filho         // references to it, so it is safe to create a shared reference.
34217f67160SWedson Almeida Filho         unsafe { &self.inner.as_ref().data }
34317f67160SWedson Almeida Filho     }
34417f67160SWedson Almeida Filho }
345*70e42ebbSWedson Almeida Filho 
346*70e42ebbSWedson Almeida Filho /// A refcounted object that is known to have a refcount of 1.
347*70e42ebbSWedson Almeida Filho ///
348*70e42ebbSWedson Almeida Filho /// It is mutable and can be converted to an [`Arc`] so that it can be shared.
349*70e42ebbSWedson Almeida Filho ///
350*70e42ebbSWedson Almeida Filho /// # Invariants
351*70e42ebbSWedson Almeida Filho ///
352*70e42ebbSWedson Almeida Filho /// `inner` always has a reference count of 1.
353*70e42ebbSWedson Almeida Filho ///
354*70e42ebbSWedson Almeida Filho /// # Examples
355*70e42ebbSWedson Almeida Filho ///
356*70e42ebbSWedson Almeida Filho /// In the following example, we make changes to the inner object before turning it into an
357*70e42ebbSWedson Almeida Filho /// `Arc<Test>` object (after which point, it cannot be mutated directly). Note that `x.into()`
358*70e42ebbSWedson Almeida Filho /// cannot fail.
359*70e42ebbSWedson Almeida Filho ///
360*70e42ebbSWedson Almeida Filho /// ```
361*70e42ebbSWedson Almeida Filho /// use kernel::sync::{Arc, UniqueArc};
362*70e42ebbSWedson Almeida Filho ///
363*70e42ebbSWedson Almeida Filho /// struct Example {
364*70e42ebbSWedson Almeida Filho ///     a: u32,
365*70e42ebbSWedson Almeida Filho ///     b: u32,
366*70e42ebbSWedson Almeida Filho /// }
367*70e42ebbSWedson Almeida Filho ///
368*70e42ebbSWedson Almeida Filho /// fn test() -> Result<Arc<Example>> {
369*70e42ebbSWedson Almeida Filho ///     let mut x = UniqueArc::try_new(Example { a: 10, b: 20 })?;
370*70e42ebbSWedson Almeida Filho ///     x.a += 1;
371*70e42ebbSWedson Almeida Filho ///     x.b += 1;
372*70e42ebbSWedson Almeida Filho ///     Ok(x.into())
373*70e42ebbSWedson Almeida Filho /// }
374*70e42ebbSWedson Almeida Filho ///
375*70e42ebbSWedson Almeida Filho /// # test().unwrap();
376*70e42ebbSWedson Almeida Filho /// ```
377*70e42ebbSWedson Almeida Filho ///
378*70e42ebbSWedson Almeida Filho /// In the following example we first allocate memory for a ref-counted `Example` but we don't
379*70e42ebbSWedson Almeida Filho /// initialise it on allocation. We do initialise it later with a call to [`UniqueArc::write`],
380*70e42ebbSWedson Almeida Filho /// followed by a conversion to `Arc<Example>`. This is particularly useful when allocation happens
381*70e42ebbSWedson Almeida Filho /// in one context (e.g., sleepable) and initialisation in another (e.g., atomic):
382*70e42ebbSWedson Almeida Filho ///
383*70e42ebbSWedson Almeida Filho /// ```
384*70e42ebbSWedson Almeida Filho /// use kernel::sync::{Arc, UniqueArc};
385*70e42ebbSWedson Almeida Filho ///
386*70e42ebbSWedson Almeida Filho /// struct Example {
387*70e42ebbSWedson Almeida Filho ///     a: u32,
388*70e42ebbSWedson Almeida Filho ///     b: u32,
389*70e42ebbSWedson Almeida Filho /// }
390*70e42ebbSWedson Almeida Filho ///
391*70e42ebbSWedson Almeida Filho /// fn test() -> Result<Arc<Example>> {
392*70e42ebbSWedson Almeida Filho ///     let x = UniqueArc::try_new_uninit()?;
393*70e42ebbSWedson Almeida Filho ///     Ok(x.write(Example { a: 10, b: 20 }).into())
394*70e42ebbSWedson Almeida Filho /// }
395*70e42ebbSWedson Almeida Filho ///
396*70e42ebbSWedson Almeida Filho /// # test().unwrap();
397*70e42ebbSWedson Almeida Filho /// ```
398*70e42ebbSWedson Almeida Filho ///
399*70e42ebbSWedson Almeida Filho /// In the last example below, the caller gets a pinned instance of `Example` while converting to
400*70e42ebbSWedson Almeida Filho /// `Arc<Example>`; this is useful in scenarios where one needs a pinned reference during
401*70e42ebbSWedson Almeida Filho /// initialisation, for example, when initialising fields that are wrapped in locks.
402*70e42ebbSWedson Almeida Filho ///
403*70e42ebbSWedson Almeida Filho /// ```
404*70e42ebbSWedson Almeida Filho /// use kernel::sync::{Arc, UniqueArc};
405*70e42ebbSWedson Almeida Filho ///
406*70e42ebbSWedson Almeida Filho /// struct Example {
407*70e42ebbSWedson Almeida Filho ///     a: u32,
408*70e42ebbSWedson Almeida Filho ///     b: u32,
409*70e42ebbSWedson Almeida Filho /// }
410*70e42ebbSWedson Almeida Filho ///
411*70e42ebbSWedson Almeida Filho /// fn test() -> Result<Arc<Example>> {
412*70e42ebbSWedson Almeida Filho ///     let mut pinned = Pin::from(UniqueArc::try_new(Example { a: 10, b: 20 })?);
413*70e42ebbSWedson Almeida Filho ///     // We can modify `pinned` because it is `Unpin`.
414*70e42ebbSWedson Almeida Filho ///     pinned.as_mut().a += 1;
415*70e42ebbSWedson Almeida Filho ///     Ok(pinned.into())
416*70e42ebbSWedson Almeida Filho /// }
417*70e42ebbSWedson Almeida Filho ///
418*70e42ebbSWedson Almeida Filho /// # test().unwrap();
419*70e42ebbSWedson Almeida Filho /// ```
420*70e42ebbSWedson Almeida Filho pub struct UniqueArc<T: ?Sized> {
421*70e42ebbSWedson Almeida Filho     inner: Arc<T>,
422*70e42ebbSWedson Almeida Filho }
423*70e42ebbSWedson Almeida Filho 
424*70e42ebbSWedson Almeida Filho impl<T> UniqueArc<T> {
425*70e42ebbSWedson Almeida Filho     /// Tries to allocate a new [`UniqueArc`] instance.
426*70e42ebbSWedson Almeida Filho     pub fn try_new(value: T) -> Result<Self> {
427*70e42ebbSWedson Almeida Filho         Ok(Self {
428*70e42ebbSWedson Almeida Filho             // INVARIANT: The newly-created object has a ref-count of 1.
429*70e42ebbSWedson Almeida Filho             inner: Arc::try_new(value)?,
430*70e42ebbSWedson Almeida Filho         })
431*70e42ebbSWedson Almeida Filho     }
432*70e42ebbSWedson Almeida Filho 
433*70e42ebbSWedson Almeida Filho     /// Tries to allocate a new [`UniqueArc`] instance whose contents are not initialised yet.
434*70e42ebbSWedson Almeida Filho     pub fn try_new_uninit() -> Result<UniqueArc<MaybeUninit<T>>> {
435*70e42ebbSWedson Almeida Filho         Ok(UniqueArc::<MaybeUninit<T>> {
436*70e42ebbSWedson Almeida Filho             // INVARIANT: The newly-created object has a ref-count of 1.
437*70e42ebbSWedson Almeida Filho             inner: Arc::try_new(MaybeUninit::uninit())?,
438*70e42ebbSWedson Almeida Filho         })
439*70e42ebbSWedson Almeida Filho     }
440*70e42ebbSWedson Almeida Filho }
441*70e42ebbSWedson Almeida Filho 
442*70e42ebbSWedson Almeida Filho impl<T> UniqueArc<MaybeUninit<T>> {
443*70e42ebbSWedson Almeida Filho     /// Converts a `UniqueArc<MaybeUninit<T>>` into a `UniqueArc<T>` by writing a value into it.
444*70e42ebbSWedson Almeida Filho     pub fn write(mut self, value: T) -> UniqueArc<T> {
445*70e42ebbSWedson Almeida Filho         self.deref_mut().write(value);
446*70e42ebbSWedson Almeida Filho         let inner = ManuallyDrop::new(self).inner.ptr;
447*70e42ebbSWedson Almeida Filho         UniqueArc {
448*70e42ebbSWedson Almeida Filho             // SAFETY: The new `Arc` is taking over `ptr` from `self.inner` (which won't be
449*70e42ebbSWedson Almeida Filho             // dropped). The types are compatible because `MaybeUninit<T>` is compatible with `T`.
450*70e42ebbSWedson Almeida Filho             inner: unsafe { Arc::from_inner(inner.cast()) },
451*70e42ebbSWedson Almeida Filho         }
452*70e42ebbSWedson Almeida Filho     }
453*70e42ebbSWedson Almeida Filho }
454*70e42ebbSWedson Almeida Filho 
455*70e42ebbSWedson Almeida Filho impl<T: ?Sized> From<UniqueArc<T>> for Pin<UniqueArc<T>> {
456*70e42ebbSWedson Almeida Filho     fn from(obj: UniqueArc<T>) -> Self {
457*70e42ebbSWedson Almeida Filho         // SAFETY: It is not possible to move/replace `T` inside a `Pin<UniqueArc<T>>` (unless `T`
458*70e42ebbSWedson Almeida Filho         // is `Unpin`), so it is ok to convert it to `Pin<UniqueArc<T>>`.
459*70e42ebbSWedson Almeida Filho         unsafe { Pin::new_unchecked(obj) }
460*70e42ebbSWedson Almeida Filho     }
461*70e42ebbSWedson Almeida Filho }
462*70e42ebbSWedson Almeida Filho 
463*70e42ebbSWedson Almeida Filho impl<T: ?Sized> Deref for UniqueArc<T> {
464*70e42ebbSWedson Almeida Filho     type Target = T;
465*70e42ebbSWedson Almeida Filho 
466*70e42ebbSWedson Almeida Filho     fn deref(&self) -> &Self::Target {
467*70e42ebbSWedson Almeida Filho         self.inner.deref()
468*70e42ebbSWedson Almeida Filho     }
469*70e42ebbSWedson Almeida Filho }
470*70e42ebbSWedson Almeida Filho 
471*70e42ebbSWedson Almeida Filho impl<T: ?Sized> DerefMut for UniqueArc<T> {
472*70e42ebbSWedson Almeida Filho     fn deref_mut(&mut self) -> &mut Self::Target {
473*70e42ebbSWedson Almeida Filho         // SAFETY: By the `Arc` type invariant, there is necessarily a reference to the object, so
474*70e42ebbSWedson Almeida Filho         // it is safe to dereference it. Additionally, we know there is only one reference when
475*70e42ebbSWedson Almeida Filho         // it's inside a `UniqueArc`, so it is safe to get a mutable reference.
476*70e42ebbSWedson Almeida Filho         unsafe { &mut self.inner.ptr.as_mut().data }
477*70e42ebbSWedson Almeida Filho     }
478*70e42ebbSWedson Almeida Filho }
479