Skip to main content

kernel/sync/
arc.rs

1// SPDX-License-Identifier: GPL-2.0
2
3//! A reference-counted pointer.
4//!
5//! This module implements a way for users to create reference-counted objects and pointers to
6//! them. Such a pointer automatically increments and decrements the count, and drops the
7//! underlying object when it reaches zero. It is also safe to use concurrently from multiple
8//! threads.
9//!
10//! It is different from the standard library's [`Arc`] in a few ways:
11//! 1. It is backed by the kernel's [`Refcount`] type.
12//! 2. It does not support weak references, which allows it to be half the size.
13//! 3. It saturates the reference count instead of aborting when it goes over a threshold.
14//! 4. It does not provide a `get_mut` method, so the ref counted object is pinned.
15//! 5. The object in [`Arc`] is pinned implicitly.
16//!
17//! [`Arc`]: https://doc.rust-lang.org/std/sync/struct.Arc.html
18
19use crate::{
20    alloc::{AllocError, Flags, KBox},
21    ffi::c_void,
22    fmt,
23    init::InPlaceInit,
24    sync::Refcount,
25    try_init,
26    types::ForeignOwnable,
27};
28use core::{
29    alloc::Layout,
30    borrow::{Borrow, BorrowMut},
31    marker::PhantomData,
32    mem::{ManuallyDrop, MaybeUninit},
33    ops::{Deref, DerefMut},
34    pin::Pin,
35    ptr::NonNull,
36};
37use pin_init::{self, pin_data, InPlaceWrite, Init, PinInit};
38
39mod std_vendor;
40
41/// A reference-counted pointer to an instance of `T`.
42///
43/// The reference count is incremented when new instances of [`Arc`] are created, and decremented
44/// when they are dropped. When the count reaches zero, the underlying `T` is also dropped.
45///
46/// # Invariants
47///
48/// The reference count on an instance of [`Arc`] is always non-zero.
49/// The object pointed to by [`Arc`] is always pinned.
50///
51/// # Examples
52///
53/// ```
54/// use kernel::sync::Arc;
55///
56/// struct Example {
57///     a: u32,
58///     b: u32,
59/// }
60///
61/// // Create a refcounted instance of `Example`.
62/// let obj = Arc::new(Example { a: 10, b: 20 }, GFP_KERNEL)?;
63///
64/// // Get a new pointer to `obj` and increment the refcount.
65/// let cloned = obj.clone();
66///
67/// // Assert that both `obj` and `cloned` point to the same underlying object.
68/// assert!(core::ptr::eq(&*obj, &*cloned));
69///
70/// // Destroy `obj` and decrement its refcount.
71/// drop(obj);
72///
73/// // Check that the values are still accessible through `cloned`.
74/// assert_eq!(cloned.a, 10);
75/// assert_eq!(cloned.b, 20);
76///
77/// // The refcount drops to zero when `cloned` goes out of scope, and the memory is freed.
78/// # Ok::<(), Error>(())
79/// ```
80///
81/// Using `Arc<T>` as the type of `self`:
82///
83/// ```
84/// use kernel::sync::Arc;
85///
86/// struct Example {
87///     a: u32,
88///     b: u32,
89/// }
90///
91/// impl Example {
92///     fn take_over(self: Arc<Self>) {
93///         // ...
94///     }
95///
96///     fn use_reference(self: &Arc<Self>) {
97///         // ...
98///     }
99/// }
100///
101/// let obj = Arc::new(Example { a: 10, b: 20 }, GFP_KERNEL)?;
102/// obj.use_reference();
103/// obj.take_over();
104/// # Ok::<(), Error>(())
105/// ```
106///
107/// Coercion from `Arc<Example>` to `Arc<dyn MyTrait>`:
108///
109/// ```
110/// use kernel::sync::{Arc, ArcBorrow};
111///
112/// trait MyTrait {
113///     // Trait has a function whose `self` type is `Arc<Self>`.
114///     fn example1(self: Arc<Self>) {}
115///
116///     // Trait has a function whose `self` type is `ArcBorrow<'_, Self>`.
117///     fn example2(self: ArcBorrow<'_, Self>) {}
118/// }
119///
120/// struct Example;
121/// impl MyTrait for Example {}
122///
123/// // `obj` has type `Arc<Example>`.
124/// let obj: Arc<Example> = Arc::new(Example, GFP_KERNEL)?;
125///
126/// // `coerced` has type `Arc<dyn MyTrait>`.
127/// let coerced: Arc<dyn MyTrait> = obj;
128/// # Ok::<(), Error>(())
129/// ```
130#[repr(transparent)]
131#[derive(core::marker::CoercePointee)]
132pub struct Arc<T: ?Sized> {
133    ptr: NonNull<ArcInner<T>>,
134    // NB: this informs dropck that objects of type `ArcInner<T>` may be used in `<Arc<T> as
135    // Drop>::drop`. Note that dropck already assumes that objects of type `T` may be used in
136    // `<Arc<T> as Drop>::drop` and the distinction between `T` and `ArcInner<T>` is not presently
137    // meaningful with respect to dropck - but this may change in the future so this is left here
138    // out of an abundance of caution.
139    //
140    // See <https://doc.rust-lang.org/nomicon/phantom-data.html#generic-parameters-and-drop-checking>
141    // for more detail on the semantics of dropck in the presence of `PhantomData`.
142    _p: PhantomData<ArcInner<T>>,
143}
144
145#[pin_data]
146#[repr(C)]
147struct ArcInner<T: ?Sized> {
148    refcount: Refcount,
149    data: T,
150}
151
152impl<T: ?Sized> ArcInner<T> {
153    /// Converts a pointer to the contents of an [`Arc`] into a pointer to the [`ArcInner`].
154    ///
155    /// # Safety
156    ///
157    /// `ptr` must have been returned by a previous call to [`Arc::into_raw`], and the `Arc` must
158    /// not yet have been destroyed.
159    unsafe fn container_of(ptr: *const T) -> NonNull<ArcInner<T>> {
160        let refcount_layout = Layout::new::<Refcount>();
161        // SAFETY: The caller guarantees that the pointer is valid.
162        let val_layout = Layout::for_value(unsafe { &*ptr });
163        // SAFETY: We're computing the layout of a real struct that existed when compiling this
164        // binary, so its layout is not so large that it can trigger arithmetic overflow.
165        let val_offset = unsafe { refcount_layout.extend(val_layout).unwrap_unchecked().1 };
166
167        // Pointer casts leave the metadata unchanged. This is okay because the metadata of `T` and
168        // `ArcInner<T>` is the same since `ArcInner` is a struct with `T` as its last field.
169        //
170        // This is documented at:
171        // <https://doc.rust-lang.org/std/ptr/trait.Pointee.html>.
172        let ptr = ptr as *const ArcInner<T>;
173
174        // SAFETY: The pointer is in-bounds of an allocation both before and after offsetting the
175        // pointer, since it originates from a previous call to `Arc::into_raw` on an `Arc` that is
176        // still valid.
177        let ptr = unsafe { ptr.byte_sub(val_offset) };
178
179        // SAFETY: The pointer can't be null since you can't have an `ArcInner<T>` value at the null
180        // address.
181        unsafe { NonNull::new_unchecked(ptr.cast_mut()) }
182    }
183}
184
185// SAFETY: It is safe to send `Arc<T>` to another thread when the underlying `T` is `Sync` because
186// it effectively means sharing `&T` (which is safe because `T` is `Sync`); additionally, it needs
187// `T` to be `Send` because any thread that has an `Arc<T>` may ultimately access `T` using a
188// mutable reference when the reference count reaches zero and `T` is dropped.
189unsafe impl<T: ?Sized + Sync + Send> Send for Arc<T> {}
190
191// SAFETY: It is safe to send `&Arc<T>` to another thread when the underlying `T` is `Sync`
192// because it effectively means sharing `&T` (which is safe because `T` is `Sync`); additionally,
193// it needs `T` to be `Send` because any thread that has a `&Arc<T>` may clone it and get an
194// `Arc<T>` on that thread, so the thread may ultimately access `T` using a mutable reference when
195// the reference count reaches zero and `T` is dropped.
196unsafe impl<T: ?Sized + Sync + Send> Sync for Arc<T> {}
197
198impl<T> InPlaceInit<T> for Arc<T> {
199    type PinnedSelf = Self;
200
201    #[inline]
202    fn try_pin_init<E>(init: impl PinInit<T, E>, flags: Flags) -> Result<Self::PinnedSelf, E>
203    where
204        E: From<AllocError>,
205    {
206        UniqueArc::try_pin_init(init, flags).map(|u| u.into())
207    }
208
209    #[inline]
210    fn try_init<E>(init: impl Init<T, E>, flags: Flags) -> Result<Self, E>
211    where
212        E: From<AllocError>,
213    {
214        UniqueArc::try_init(init, flags).map(|u| u.into())
215    }
216}
217
218impl<T> Arc<T> {
219    /// Constructs a new reference counted instance of `T`.
220    pub fn new(contents: T, flags: Flags) -> Result<Self, AllocError> {
221        // INVARIANT: The refcount is initialised to a non-zero value.
222        let value = ArcInner {
223            refcount: Refcount::new(1),
224            data: contents,
225        };
226
227        let inner = KBox::new(value, flags)?;
228        let inner = KBox::leak(inner).into();
229
230        // SAFETY: We just created `inner` with a reference count of 1, which is owned by the new
231        // `Arc` object.
232        Ok(unsafe { Self::from_inner(inner) })
233    }
234
235    /// The offset that the value is stored at.
236    pub const DATA_OFFSET: usize = core::mem::offset_of!(ArcInner<T>, data);
237}
238
239impl<T: ?Sized> Arc<T> {
240    /// Constructs a new [`Arc`] from an existing [`ArcInner`].
241    ///
242    /// # Safety
243    ///
244    /// The caller must ensure that `inner` points to a valid location and has a non-zero reference
245    /// count, one of which will be owned by the new [`Arc`] instance.
246    unsafe fn from_inner(inner: NonNull<ArcInner<T>>) -> Self {
247        // INVARIANT: By the safety requirements, the invariants hold.
248        Arc {
249            ptr: inner,
250            _p: PhantomData,
251        }
252    }
253
254    /// Convert the [`Arc`] into a raw pointer.
255    ///
256    /// The raw pointer has ownership of the refcount that this Arc object owned.
257    pub fn into_raw(self) -> *const T {
258        let ptr = self.ptr.as_ptr();
259        core::mem::forget(self);
260        // SAFETY: The pointer is valid.
261        unsafe { core::ptr::addr_of!((*ptr).data) }
262    }
263
264    /// Return a raw pointer to the data in this arc.
265    pub fn as_ptr(this: &Self) -> *const T {
266        let ptr = this.ptr.as_ptr();
267
268        // SAFETY: As `ptr` points to a valid allocation of type `ArcInner`,
269        // field projection to `data`is within bounds of the allocation.
270        unsafe { core::ptr::addr_of!((*ptr).data) }
271    }
272
273    /// Recreates an [`Arc`] instance previously deconstructed via [`Arc::into_raw`].
274    ///
275    /// # Safety
276    ///
277    /// `ptr` must have been returned by a previous call to [`Arc::into_raw`]. Additionally, it
278    /// must not be called more than once for each previous call to [`Arc::into_raw`].
279    pub unsafe fn from_raw(ptr: *const T) -> Self {
280        // SAFETY: The caller promises that this pointer originates from a call to `into_raw` on an
281        // `Arc` that is still valid.
282        let ptr = unsafe { ArcInner::container_of(ptr) };
283
284        // SAFETY: By the safety requirements we know that `ptr` came from `Arc::into_raw`, so the
285        // reference count held then will be owned by the new `Arc` object.
286        unsafe { Self::from_inner(ptr) }
287    }
288
289    /// Returns an [`ArcBorrow`] from the given [`Arc`].
290    ///
291    /// This is useful when the argument of a function call is an [`ArcBorrow`] (e.g., in a method
292    /// receiver), but we have an [`Arc`] instead. Getting an [`ArcBorrow`] is free when optimised.
293    #[inline]
294    pub fn as_arc_borrow(&self) -> ArcBorrow<'_, T> {
295        // SAFETY: The constraint that the lifetime of the shared reference must outlive that of
296        // the returned `ArcBorrow` ensures that the object remains alive and that no mutable
297        // reference can be created.
298        unsafe { ArcBorrow::new(self.ptr) }
299    }
300
301    /// Compare whether two [`Arc`] pointers reference the same underlying object.
302    pub fn ptr_eq(this: &Self, other: &Self) -> bool {
303        core::ptr::eq(this.ptr.as_ptr(), other.ptr.as_ptr())
304    }
305
306    /// Converts this [`Arc`] into a [`UniqueArc`], or destroys it if it is not unique.
307    ///
308    /// When this destroys the `Arc`, it does so while properly avoiding races. This means that
309    /// this method will never call the destructor of the value.
310    ///
311    /// # Examples
312    ///
313    /// ```
314    /// use kernel::sync::{Arc, UniqueArc};
315    ///
316    /// let arc = Arc::new(42, GFP_KERNEL)?;
317    /// let unique_arc = Arc::into_unique_or_drop(arc);
318    ///
319    /// // The above conversion should succeed since refcount of `arc` is 1.
320    /// assert!(unique_arc.is_some());
321    ///
322    /// assert_eq!(*(unique_arc.unwrap()), 42);
323    ///
324    /// # Ok::<(), Error>(())
325    /// ```
326    ///
327    /// ```
328    /// use kernel::sync::{Arc, UniqueArc};
329    ///
330    /// let arc = Arc::new(42, GFP_KERNEL)?;
331    /// let another = arc.clone();
332    ///
333    /// let unique_arc = Arc::into_unique_or_drop(arc);
334    ///
335    /// // The above conversion should fail since refcount of `arc` is >1.
336    /// assert!(unique_arc.is_none());
337    ///
338    /// # Ok::<(), Error>(())
339    /// ```
340    pub fn into_unique_or_drop(this: Self) -> Option<Pin<UniqueArc<T>>> {
341        // We will manually manage the refcount in this method, so we disable the destructor.
342        let this = ManuallyDrop::new(this);
343        // SAFETY: We own a refcount, so the pointer is still valid.
344        let refcount = unsafe { &this.ptr.as_ref().refcount };
345
346        // If the refcount reaches a non-zero value, then we have destroyed this `Arc` and will
347        // return without further touching the `Arc`. If the refcount reaches zero, then there are
348        // no other arcs, and we can create a `UniqueArc`.
349        if refcount.dec_and_test() {
350            refcount.set(1);
351
352            // INVARIANT: We own the only refcount to this arc, so we may create a `UniqueArc`. We
353            // must pin the `UniqueArc` because the values was previously in an `Arc`, and they pin
354            // their values.
355            Some(Pin::from(UniqueArc {
356                inner: ManuallyDrop::into_inner(this),
357            }))
358        } else {
359            None
360        }
361    }
362}
363
364// SAFETY: The pointer returned by `into_foreign` was originally allocated as an
365// `KBox<ArcInner<T>>`, so that type is what determines the alignment.
366unsafe impl<T: 'static> ForeignOwnable for Arc<T> {
367    const FOREIGN_ALIGN: usize = <KBox<ArcInner<T>> as ForeignOwnable>::FOREIGN_ALIGN;
368
369    type Borrowed<'a> = ArcBorrow<'a, T>;
370    type BorrowedMut<'a> = Self::Borrowed<'a>;
371
372    fn into_foreign(self) -> *mut c_void {
373        ManuallyDrop::new(self).ptr.as_ptr().cast()
374    }
375
376    unsafe fn from_foreign(ptr: *mut c_void) -> Self {
377        // SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous
378        // call to `Self::into_foreign`.
379        let inner = unsafe { NonNull::new_unchecked(ptr.cast::<ArcInner<T>>()) };
380
381        // SAFETY: By the safety requirement of this function, we know that `ptr` came from
382        // a previous call to `Arc::into_foreign`, which guarantees that `ptr` is valid and
383        // holds a reference count increment that is transferrable to us.
384        unsafe { Self::from_inner(inner) }
385    }
386
387    unsafe fn borrow<'a>(ptr: *mut c_void) -> ArcBorrow<'a, T> {
388        // SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous
389        // call to `Self::into_foreign`.
390        let inner = unsafe { NonNull::new_unchecked(ptr.cast::<ArcInner<T>>()) };
391
392        // SAFETY: The safety requirements of `from_foreign` ensure that the object remains alive
393        // for the lifetime of the returned value.
394        unsafe { ArcBorrow::new(inner) }
395    }
396
397    unsafe fn borrow_mut<'a>(ptr: *mut c_void) -> ArcBorrow<'a, T> {
398        // SAFETY: The safety requirements for `borrow_mut` are a superset of the safety
399        // requirements for `borrow`.
400        unsafe { <Self as ForeignOwnable>::borrow(ptr) }
401    }
402}
403
404impl<T: ?Sized> Deref for Arc<T> {
405    type Target = T;
406
407    fn deref(&self) -> &Self::Target {
408        // SAFETY: By the type invariant, there is necessarily a reference to the object, so it is
409        // safe to dereference it.
410        unsafe { &self.ptr.as_ref().data }
411    }
412}
413
414impl<T: ?Sized> AsRef<T> for Arc<T> {
415    fn as_ref(&self) -> &T {
416        self.deref()
417    }
418}
419
420/// # Examples
421///
422/// ```
423/// # use core::borrow::Borrow;
424/// # use kernel::sync::Arc;
425/// struct Foo<B: Borrow<u32>>(B);
426///
427/// // Owned instance.
428/// let owned = Foo(1);
429///
430/// // Shared instance.
431/// let arc = Arc::new(1, GFP_KERNEL)?;
432/// let shared = Foo(arc.clone());
433///
434/// let i = 1;
435/// // Borrowed from `i`.
436/// let borrowed = Foo(&i);
437/// # Ok::<(), Error>(())
438/// ```
439impl<T: ?Sized> Borrow<T> for Arc<T> {
440    fn borrow(&self) -> &T {
441        self.deref()
442    }
443}
444
445impl<T: ?Sized> Clone for Arc<T> {
446    fn clone(&self) -> Self {
447        // INVARIANT: `Refcount` saturates the refcount, so it cannot overflow to zero.
448        // SAFETY: By the type invariant, there is necessarily a reference to the object, so it is
449        // safe to increment the refcount.
450        unsafe { self.ptr.as_ref() }.refcount.inc();
451
452        // SAFETY: We just incremented the refcount. This increment is now owned by the new `Arc`.
453        unsafe { Self::from_inner(self.ptr) }
454    }
455}
456
457impl<T: ?Sized> Drop for Arc<T> {
458    fn drop(&mut self) {
459        // INVARIANT: If the refcount reaches zero, there are no other instances of `Arc`, and
460        // this instance is being dropped, so the broken invariant is not observable.
461        // SAFETY: By the type invariant, there is necessarily a reference to the object.
462        let is_zero = unsafe { self.ptr.as_ref() }.refcount.dec_and_test();
463        if is_zero {
464            // The count reached zero, we must free the memory.
465            //
466            // SAFETY: The pointer was initialised from the result of `KBox::leak`.
467            unsafe { drop(KBox::from_raw(self.ptr.as_ptr())) };
468        }
469    }
470}
471
472impl<T: ?Sized> From<UniqueArc<T>> for Arc<T> {
473    fn from(item: UniqueArc<T>) -> Self {
474        item.inner
475    }
476}
477
478impl<T: ?Sized> From<Pin<UniqueArc<T>>> for Arc<T> {
479    fn from(item: Pin<UniqueArc<T>>) -> Self {
480        // SAFETY: The type invariants of `Arc` guarantee that the data is pinned.
481        unsafe { Pin::into_inner_unchecked(item).inner }
482    }
483}
484
485/// A borrowed reference to an [`Arc`] instance.
486///
487/// For cases when one doesn't ever need to increment the refcount on the allocation, it is simpler
488/// to use just `&T`, which we can trivially get from an [`Arc<T>`] instance.
489///
490/// However, when one may need to increment the refcount, it is preferable to use an `ArcBorrow<T>`
491/// over `&Arc<T>` because the latter results in a double-indirection: a pointer (shared reference)
492/// to a pointer ([`Arc<T>`]) to the object (`T`). An [`ArcBorrow`] eliminates this double
493/// indirection while still allowing one to increment the refcount and getting an [`Arc<T>`] when/if
494/// needed.
495///
496/// # Invariants
497///
498/// There are no mutable references to the underlying [`Arc`], and it remains valid for the
499/// lifetime of the [`ArcBorrow`] instance.
500///
501/// # Examples
502///
503/// ```
504/// use kernel::sync::{Arc, ArcBorrow};
505///
506/// struct Example;
507///
508/// fn do_something(e: ArcBorrow<'_, Example>) -> Arc<Example> {
509///     e.into()
510/// }
511///
512/// let obj = Arc::new(Example, GFP_KERNEL)?;
513/// let cloned = do_something(obj.as_arc_borrow());
514///
515/// // Assert that both `obj` and `cloned` point to the same underlying object.
516/// assert!(core::ptr::eq(&*obj, &*cloned));
517/// # Ok::<(), Error>(())
518/// ```
519///
520/// Using `ArcBorrow<T>` as the type of `self`:
521///
522/// ```
523/// use kernel::sync::{Arc, ArcBorrow};
524///
525/// struct Example {
526///     a: u32,
527///     b: u32,
528/// }
529///
530/// impl Example {
531///     fn use_reference(self: ArcBorrow<'_, Self>) {
532///         // ...
533///     }
534/// }
535///
536/// let obj = Arc::new(Example { a: 10, b: 20 }, GFP_KERNEL)?;
537/// obj.as_arc_borrow().use_reference();
538/// # Ok::<(), Error>(())
539/// ```
540#[repr(transparent)]
541#[derive(core::marker::CoercePointee)]
542pub struct ArcBorrow<'a, T: ?Sized + 'a> {
543    inner: NonNull<ArcInner<T>>,
544    _p: PhantomData<&'a ()>,
545}
546
547impl<T: ?Sized> Clone for ArcBorrow<'_, T> {
548    fn clone(&self) -> Self {
549        *self
550    }
551}
552
553impl<T: ?Sized> Copy for ArcBorrow<'_, T> {}
554
555impl<T: ?Sized> ArcBorrow<'_, T> {
556    /// Creates a new [`ArcBorrow`] instance.
557    ///
558    /// # Safety
559    ///
560    /// Callers must ensure the following for the lifetime of the returned [`ArcBorrow`] instance:
561    /// 1. That `inner` remains valid;
562    /// 2. That no mutable references to `inner` are created.
563    unsafe fn new(inner: NonNull<ArcInner<T>>) -> Self {
564        // INVARIANT: The safety requirements guarantee the invariants.
565        Self {
566            inner,
567            _p: PhantomData,
568        }
569    }
570
571    /// Creates an [`ArcBorrow`] to an [`Arc`] that has previously been deconstructed with
572    /// [`Arc::into_raw`] or [`Arc::as_ptr`].
573    ///
574    /// # Safety
575    ///
576    /// * The provided pointer must originate from a call to [`Arc::into_raw`] or [`Arc::as_ptr`].
577    /// * For the duration of the lifetime annotated on this `ArcBorrow`, the reference count must
578    ///   not hit zero.
579    /// * For the duration of the lifetime annotated on this `ArcBorrow`, there must not be a
580    ///   [`UniqueArc`] reference to this value.
581    pub unsafe fn from_raw(ptr: *const T) -> Self {
582        // SAFETY: The caller promises that this pointer originates from a call to `into_raw` on an
583        // `Arc` that is still valid.
584        let ptr = unsafe { ArcInner::container_of(ptr) };
585
586        // SAFETY: The caller promises that the value remains valid since the reference count must
587        // not hit zero, and no mutable reference will be created since that would involve a
588        // `UniqueArc`.
589        unsafe { Self::new(ptr) }
590    }
591}
592
593impl<T: ?Sized> From<ArcBorrow<'_, T>> for Arc<T> {
594    fn from(b: ArcBorrow<'_, T>) -> Self {
595        // SAFETY: The existence of `b` guarantees that the refcount is non-zero. `ManuallyDrop`
596        // guarantees that `drop` isn't called, so it's ok that the temporary `Arc` doesn't own the
597        // increment.
598        ManuallyDrop::new(unsafe { Arc::from_inner(b.inner) })
599            .deref()
600            .clone()
601    }
602}
603
604impl<T: ?Sized> Deref for ArcBorrow<'_, T> {
605    type Target = T;
606
607    fn deref(&self) -> &Self::Target {
608        // SAFETY: By the type invariant, the underlying object is still alive with no mutable
609        // references to it, so it is safe to create a shared reference.
610        unsafe { &self.inner.as_ref().data }
611    }
612}
613
614/// A refcounted object that is known to have a refcount of 1.
615///
616/// It is mutable and can be converted to an [`Arc`] so that it can be shared.
617///
618/// # Invariants
619///
620/// `inner` always has a reference count of 1.
621///
622/// # Examples
623///
624/// In the following example, we make changes to the inner object before turning it into an
625/// `Arc<Test>` object (after which point, it cannot be mutated directly). Note that `x.into()`
626/// cannot fail.
627///
628/// ```
629/// use kernel::sync::{Arc, UniqueArc};
630///
631/// struct Example {
632///     a: u32,
633///     b: u32,
634/// }
635///
636/// fn test() -> Result<Arc<Example>> {
637///     let mut x = UniqueArc::new(Example { a: 10, b: 20 }, GFP_KERNEL)?;
638///     x.a += 1;
639///     x.b += 1;
640///     Ok(x.into())
641/// }
642///
643/// # test().unwrap();
644/// ```
645///
646/// In the following example we first allocate memory for a refcounted `Example` but we don't
647/// initialise it on allocation. We do initialise it later with a call to [`UniqueArc::write`],
648/// followed by a conversion to `Arc<Example>`. This is particularly useful when allocation happens
649/// in one context (e.g., sleepable) and initialisation in another (e.g., atomic):
650///
651/// ```
652/// use kernel::sync::{Arc, UniqueArc};
653///
654/// struct Example {
655///     a: u32,
656///     b: u32,
657/// }
658///
659/// fn test() -> Result<Arc<Example>> {
660///     let x = UniqueArc::new_uninit(GFP_KERNEL)?;
661///     Ok(x.write(Example { a: 10, b: 20 }).into())
662/// }
663///
664/// # test().unwrap();
665/// ```
666///
667/// In the last example below, the caller gets a pinned instance of `Example` while converting to
668/// `Arc<Example>`; this is useful in scenarios where one needs a pinned reference during
669/// initialisation, for example, when initialising fields that are wrapped in locks.
670///
671/// ```
672/// use kernel::sync::{Arc, UniqueArc};
673///
674/// struct Example {
675///     a: u32,
676///     b: u32,
677/// }
678///
679/// fn test() -> Result<Arc<Example>> {
680///     let mut pinned = Pin::from(UniqueArc::new(Example { a: 10, b: 20 }, GFP_KERNEL)?);
681///     // We can modify `pinned` because it is `Unpin`.
682///     pinned.as_mut().a += 1;
683///     Ok(pinned.into())
684/// }
685///
686/// # test().unwrap();
687/// ```
688pub struct UniqueArc<T: ?Sized> {
689    inner: Arc<T>,
690}
691
692impl<T> InPlaceInit<T> for UniqueArc<T> {
693    type PinnedSelf = Pin<Self>;
694
695    #[inline]
696    fn try_pin_init<E>(init: impl PinInit<T, E>, flags: Flags) -> Result<Self::PinnedSelf, E>
697    where
698        E: From<AllocError>,
699    {
700        UniqueArc::new_uninit(flags)?.write_pin_init(init)
701    }
702
703    #[inline]
704    fn try_init<E>(init: impl Init<T, E>, flags: Flags) -> Result<Self, E>
705    where
706        E: From<AllocError>,
707    {
708        UniqueArc::new_uninit(flags)?.write_init(init)
709    }
710}
711
712impl<T> InPlaceWrite<T> for UniqueArc<MaybeUninit<T>> {
713    type Initialized = UniqueArc<T>;
714
715    fn write_init<E>(mut self, init: impl Init<T, E>) -> Result<Self::Initialized, E> {
716        let slot = self.as_mut_ptr();
717        // SAFETY: When init errors/panics, slot will get deallocated but not dropped,
718        // slot is valid.
719        unsafe { init.__init(slot)? };
720        // SAFETY: All fields have been initialized.
721        Ok(unsafe { self.assume_init() })
722    }
723
724    fn write_pin_init<E>(mut self, init: impl PinInit<T, E>) -> Result<Pin<Self::Initialized>, E> {
725        let slot = self.as_mut_ptr();
726        // SAFETY: When init errors/panics, slot will get deallocated but not dropped,
727        // slot is valid and will not be moved, because we pin it later.
728        unsafe { init.__pinned_init(slot)? };
729        // SAFETY: All fields have been initialized.
730        Ok(unsafe { self.assume_init() }.into())
731    }
732}
733
734impl<T> UniqueArc<T> {
735    /// Tries to allocate a new [`UniqueArc`] instance.
736    pub fn new(value: T, flags: Flags) -> Result<Self, AllocError> {
737        Ok(Self {
738            // INVARIANT: The newly-created object has a refcount of 1.
739            inner: Arc::new(value, flags)?,
740        })
741    }
742
743    /// Tries to allocate a new [`UniqueArc`] instance whose contents are not initialised yet.
744    pub fn new_uninit(flags: Flags) -> Result<UniqueArc<MaybeUninit<T>>, AllocError> {
745        // INVARIANT: The refcount is initialised to a non-zero value.
746        let inner = KBox::try_init::<AllocError>(
747            try_init!(ArcInner {
748                refcount: Refcount::new(1),
749                data <- pin_init::uninit::<T, AllocError>(),
750            }? AllocError),
751            flags,
752        )?;
753        Ok(UniqueArc {
754            // INVARIANT: The newly-created object has a refcount of 1.
755            // SAFETY: The pointer from the `KBox` is valid.
756            inner: unsafe { Arc::from_inner(KBox::leak(inner).into()) },
757        })
758    }
759}
760
761impl<T> UniqueArc<MaybeUninit<T>> {
762    /// Converts a `UniqueArc<MaybeUninit<T>>` into a `UniqueArc<T>` by writing a value into it.
763    pub fn write(mut self, value: T) -> UniqueArc<T> {
764        self.deref_mut().write(value);
765        // SAFETY: We just wrote the value to be initialized.
766        unsafe { self.assume_init() }
767    }
768
769    /// Unsafely assume that `self` is initialized.
770    ///
771    /// # Safety
772    ///
773    /// The caller guarantees that the value behind this pointer has been initialized. It is
774    /// *immediate* UB to call this when the value is not initialized.
775    pub unsafe fn assume_init(self) -> UniqueArc<T> {
776        let inner = ManuallyDrop::new(self).inner.ptr;
777        UniqueArc {
778            // SAFETY: The new `Arc` is taking over `ptr` from `self.inner` (which won't be
779            // dropped). The types are compatible because `MaybeUninit<T>` is compatible with `T`.
780            inner: unsafe { Arc::from_inner(inner.cast()) },
781        }
782    }
783
784    /// Initialize `self` using the given initializer.
785    pub fn init_with<E>(mut self, init: impl Init<T, E>) -> core::result::Result<UniqueArc<T>, E> {
786        // SAFETY: The supplied pointer is valid for initialization.
787        match unsafe { init.__init(self.as_mut_ptr()) } {
788            // SAFETY: Initialization completed successfully.
789            Ok(()) => Ok(unsafe { self.assume_init() }),
790            Err(err) => Err(err),
791        }
792    }
793
794    /// Pin-initialize `self` using the given pin-initializer.
795    pub fn pin_init_with<E>(
796        mut self,
797        init: impl PinInit<T, E>,
798    ) -> core::result::Result<Pin<UniqueArc<T>>, E> {
799        // SAFETY: The supplied pointer is valid for initialization and we will later pin the value
800        // to ensure it does not move.
801        match unsafe { init.__pinned_init(self.as_mut_ptr()) } {
802            // SAFETY: Initialization completed successfully.
803            Ok(()) => Ok(unsafe { self.assume_init() }.into()),
804            Err(err) => Err(err),
805        }
806    }
807}
808
809impl<T: ?Sized> From<UniqueArc<T>> for Pin<UniqueArc<T>> {
810    fn from(obj: UniqueArc<T>) -> Self {
811        // SAFETY: It is not possible to move/replace `T` inside a `Pin<UniqueArc<T>>` (unless `T`
812        // is `Unpin`), so it is ok to convert it to `Pin<UniqueArc<T>>`.
813        unsafe { Pin::new_unchecked(obj) }
814    }
815}
816
817impl<T: ?Sized> Deref for UniqueArc<T> {
818    type Target = T;
819
820    fn deref(&self) -> &Self::Target {
821        self.inner.deref()
822    }
823}
824
825impl<T: ?Sized> DerefMut for UniqueArc<T> {
826    fn deref_mut(&mut self) -> &mut Self::Target {
827        // SAFETY: By the `Arc` type invariant, there is necessarily a reference to the object, so
828        // it is safe to dereference it. Additionally, we know there is only one reference when
829        // it's inside a `UniqueArc`, so it is safe to get a mutable reference.
830        unsafe { &mut self.inner.ptr.as_mut().data }
831    }
832}
833
834/// # Examples
835///
836/// ```
837/// # use core::borrow::Borrow;
838/// # use kernel::sync::UniqueArc;
839/// struct Foo<B: Borrow<u32>>(B);
840///
841/// // Owned instance.
842/// let owned = Foo(1);
843///
844/// // Owned instance using `UniqueArc`.
845/// let arc = UniqueArc::new(1, GFP_KERNEL)?;
846/// let shared = Foo(arc);
847///
848/// let i = 1;
849/// // Borrowed from `i`.
850/// let borrowed = Foo(&i);
851/// # Ok::<(), Error>(())
852/// ```
853impl<T: ?Sized> Borrow<T> for UniqueArc<T> {
854    fn borrow(&self) -> &T {
855        self.deref()
856    }
857}
858
859/// # Examples
860///
861/// ```
862/// # use core::borrow::BorrowMut;
863/// # use kernel::sync::UniqueArc;
864/// struct Foo<B: BorrowMut<u32>>(B);
865///
866/// // Owned instance.
867/// let owned = Foo(1);
868///
869/// // Owned instance using `UniqueArc`.
870/// let arc = UniqueArc::new(1, GFP_KERNEL)?;
871/// let shared = Foo(arc);
872///
873/// let mut i = 1;
874/// // Borrowed from `i`.
875/// let borrowed = Foo(&mut i);
876/// # Ok::<(), Error>(())
877/// ```
878impl<T: ?Sized> BorrowMut<T> for UniqueArc<T> {
879    fn borrow_mut(&mut self) -> &mut T {
880        self.deref_mut()
881    }
882}
883
884impl<T: fmt::Display + ?Sized> fmt::Display for UniqueArc<T> {
885    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
886        fmt::Display::fmt(self.deref(), f)
887    }
888}
889
890impl<T: fmt::Display + ?Sized> fmt::Display for Arc<T> {
891    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
892        fmt::Display::fmt(self.deref(), f)
893    }
894}
895
896impl<T: fmt::Debug + ?Sized> fmt::Debug for UniqueArc<T> {
897    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
898        fmt::Debug::fmt(self.deref(), f)
899    }
900}
901
902impl<T: fmt::Debug + ?Sized> fmt::Debug for Arc<T> {
903    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
904        fmt::Debug::fmt(self.deref(), f)
905    }
906}