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