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