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