xref: /linux/rust/kernel/sync/arc.rs (revision d7bf4786b5250b0e490a937d1f8a16ee3a54adbe)
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, InPlaceInit, Init, PinInit},
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 macros::pin_data;
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> Arc<T> {
206     /// Constructs a new reference counted instance of `T`.
207     pub fn new(contents: T, flags: Flags) -> Result<Self, AllocError> {
208         // INVARIANT: The refcount is initialised to a non-zero value.
209         let value = ArcInner {
210             // SAFETY: There are no safety requirements for this FFI call.
211             refcount: Opaque::new(unsafe { bindings::REFCOUNT_INIT(1) }),
212             data: contents,
213         };
214 
215         let inner = KBox::new(value, flags)?;
216         let inner = KBox::leak(inner).into();
217 
218         // SAFETY: We just created `inner` with a reference count of 1, which is owned by the new
219         // `Arc` object.
220         Ok(unsafe { Self::from_inner(inner) })
221     }
222 }
223 
224 impl<T: ?Sized> Arc<T> {
225     /// Constructs a new [`Arc`] from an existing [`ArcInner`].
226     ///
227     /// # Safety
228     ///
229     /// The caller must ensure that `inner` points to a valid location and has a non-zero reference
230     /// count, one of which will be owned by the new [`Arc`] instance.
231     unsafe fn from_inner(inner: NonNull<ArcInner<T>>) -> Self {
232         // INVARIANT: By the safety requirements, the invariants hold.
233         Arc {
234             ptr: inner,
235             _p: PhantomData,
236         }
237     }
238 
239     /// Convert the [`Arc`] into a raw pointer.
240     ///
241     /// The raw pointer has ownership of the refcount that this Arc object owned.
242     pub fn into_raw(self) -> *const T {
243         let ptr = self.ptr.as_ptr();
244         core::mem::forget(self);
245         // SAFETY: The pointer is valid.
246         unsafe { core::ptr::addr_of!((*ptr).data) }
247     }
248 
249     /// Return a raw pointer to the data in this arc.
250     pub fn as_ptr(this: &Self) -> *const T {
251         let ptr = this.ptr.as_ptr();
252 
253         // SAFETY: As `ptr` points to a valid allocation of type `ArcInner`,
254         // field projection to `data`is within bounds of the allocation.
255         unsafe { core::ptr::addr_of!((*ptr).data) }
256     }
257 
258     /// Recreates an [`Arc`] instance previously deconstructed via [`Arc::into_raw`].
259     ///
260     /// # Safety
261     ///
262     /// `ptr` must have been returned by a previous call to [`Arc::into_raw`]. Additionally, it
263     /// must not be called more than once for each previous call to [`Arc::into_raw`].
264     pub unsafe fn from_raw(ptr: *const T) -> Self {
265         // SAFETY: The caller promises that this pointer originates from a call to `into_raw` on an
266         // `Arc` that is still valid.
267         let ptr = unsafe { ArcInner::container_of(ptr) };
268 
269         // SAFETY: By the safety requirements we know that `ptr` came from `Arc::into_raw`, so the
270         // reference count held then will be owned by the new `Arc` object.
271         unsafe { Self::from_inner(ptr) }
272     }
273 
274     /// Returns an [`ArcBorrow`] from the given [`Arc`].
275     ///
276     /// This is useful when the argument of a function call is an [`ArcBorrow`] (e.g., in a method
277     /// receiver), but we have an [`Arc`] instead. Getting an [`ArcBorrow`] is free when optimised.
278     #[inline]
279     pub fn as_arc_borrow(&self) -> ArcBorrow<'_, T> {
280         // SAFETY: The constraint that the lifetime of the shared reference must outlive that of
281         // the returned `ArcBorrow` ensures that the object remains alive and that no mutable
282         // reference can be created.
283         unsafe { ArcBorrow::new(self.ptr) }
284     }
285 
286     /// Compare whether two [`Arc`] pointers reference the same underlying object.
287     pub fn ptr_eq(this: &Self, other: &Self) -> bool {
288         core::ptr::eq(this.ptr.as_ptr(), other.ptr.as_ptr())
289     }
290 
291     /// Converts this [`Arc`] into a [`UniqueArc`], or destroys it if it is not unique.
292     ///
293     /// When this destroys the `Arc`, it does so while properly avoiding races. This means that
294     /// this method will never call the destructor of the value.
295     ///
296     /// # Examples
297     ///
298     /// ```
299     /// use kernel::sync::{Arc, UniqueArc};
300     ///
301     /// let arc = Arc::new(42, GFP_KERNEL)?;
302     /// let unique_arc = arc.into_unique_or_drop();
303     ///
304     /// // The above conversion should succeed since refcount of `arc` is 1.
305     /// assert!(unique_arc.is_some());
306     ///
307     /// assert_eq!(*(unique_arc.unwrap()), 42);
308     ///
309     /// # Ok::<(), Error>(())
310     /// ```
311     ///
312     /// ```
313     /// use kernel::sync::{Arc, UniqueArc};
314     ///
315     /// let arc = Arc::new(42, GFP_KERNEL)?;
316     /// let another = arc.clone();
317     ///
318     /// let unique_arc = arc.into_unique_or_drop();
319     ///
320     /// // The above conversion should fail since refcount of `arc` is >1.
321     /// assert!(unique_arc.is_none());
322     ///
323     /// # Ok::<(), Error>(())
324     /// ```
325     pub fn into_unique_or_drop(self) -> Option<Pin<UniqueArc<T>>> {
326         // We will manually manage the refcount in this method, so we disable the destructor.
327         let me = ManuallyDrop::new(self);
328         // SAFETY: We own a refcount, so the pointer is still valid.
329         let refcount = unsafe { me.ptr.as_ref() }.refcount.get();
330 
331         // If the refcount reaches a non-zero value, then we have destroyed this `Arc` and will
332         // return without further touching the `Arc`. If the refcount reaches zero, then there are
333         // no other arcs, and we can create a `UniqueArc`.
334         //
335         // SAFETY: We own a refcount, so the pointer is not dangling.
336         let is_zero = unsafe { bindings::refcount_dec_and_test(refcount) };
337         if is_zero {
338             // SAFETY: We have exclusive access to the arc, so we can perform unsynchronized
339             // accesses to the refcount.
340             unsafe { core::ptr::write(refcount, bindings::REFCOUNT_INIT(1)) };
341 
342             // INVARIANT: We own the only refcount to this arc, so we may create a `UniqueArc`. We
343             // must pin the `UniqueArc` because the values was previously in an `Arc`, and they pin
344             // their values.
345             Some(Pin::from(UniqueArc {
346                 inner: ManuallyDrop::into_inner(me),
347             }))
348         } else {
349             None
350         }
351     }
352 }
353 
354 impl<T: 'static> ForeignOwnable for Arc<T> {
355     type Borrowed<'a> = ArcBorrow<'a, T>;
356     type BorrowedMut<'a> = Self::Borrowed<'a>;
357 
358     fn into_foreign(self) -> *mut crate::ffi::c_void {
359         ManuallyDrop::new(self).ptr.as_ptr().cast()
360     }
361 
362     unsafe fn from_foreign(ptr: *mut crate::ffi::c_void) -> Self {
363         // SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous
364         // call to `Self::into_foreign`.
365         let inner = unsafe { NonNull::new_unchecked(ptr.cast::<ArcInner<T>>()) };
366 
367         // SAFETY: By the safety requirement of this function, we know that `ptr` came from
368         // a previous call to `Arc::into_foreign`, which guarantees that `ptr` is valid and
369         // holds a reference count increment that is transferrable to us.
370         unsafe { Self::from_inner(inner) }
371     }
372 
373     unsafe fn borrow<'a>(ptr: *mut crate::ffi::c_void) -> ArcBorrow<'a, T> {
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: The safety requirements of `from_foreign` ensure that the object remains alive
379         // for the lifetime of the returned value.
380         unsafe { ArcBorrow::new(inner) }
381     }
382 
383     unsafe fn borrow_mut<'a>(ptr: *mut crate::ffi::c_void) -> ArcBorrow<'a, T> {
384         // SAFETY: The safety requirements for `borrow_mut` are a superset of the safety
385         // requirements for `borrow`.
386         unsafe { Self::borrow(ptr) }
387     }
388 }
389 
390 impl<T: ?Sized> Deref for Arc<T> {
391     type Target = T;
392 
393     fn deref(&self) -> &Self::Target {
394         // SAFETY: By the type invariant, there is necessarily a reference to the object, so it is
395         // safe to dereference it.
396         unsafe { &self.ptr.as_ref().data }
397     }
398 }
399 
400 impl<T: ?Sized> AsRef<T> for Arc<T> {
401     fn as_ref(&self) -> &T {
402         self.deref()
403     }
404 }
405 
406 impl<T: ?Sized> Clone for Arc<T> {
407     fn clone(&self) -> Self {
408         // SAFETY: By the type invariant, there is necessarily a reference to the object, so it is
409         // safe to dereference it.
410         let refcount = unsafe { self.ptr.as_ref() }.refcount.get();
411 
412         // INVARIANT: C `refcount_inc` saturates the refcount, so it cannot overflow to zero.
413         // SAFETY: By the type invariant, there is necessarily a reference to the object, so it is
414         // safe to increment the refcount.
415         unsafe { bindings::refcount_inc(refcount) };
416 
417         // SAFETY: We just incremented the refcount. This increment is now owned by the new `Arc`.
418         unsafe { Self::from_inner(self.ptr) }
419     }
420 }
421 
422 impl<T: ?Sized> Drop for Arc<T> {
423     fn drop(&mut self) {
424         // SAFETY: By the type invariant, there is necessarily a reference to the object. We cannot
425         // touch `refcount` after it's decremented to a non-zero value because another thread/CPU
426         // may concurrently decrement it to zero and free it. It is ok to have a raw pointer to
427         // freed/invalid memory as long as it is never dereferenced.
428         let refcount = unsafe { self.ptr.as_ref() }.refcount.get();
429 
430         // INVARIANT: If the refcount reaches zero, there are no other instances of `Arc`, and
431         // this instance is being dropped, so the broken invariant is not observable.
432         // SAFETY: Also by the type invariant, we are allowed to decrement the refcount.
433         let is_zero = unsafe { bindings::refcount_dec_and_test(refcount) };
434         if is_zero {
435             // The count reached zero, we must free the memory.
436             //
437             // SAFETY: The pointer was initialised from the result of `KBox::leak`.
438             unsafe { drop(KBox::from_raw(self.ptr.as_ptr())) };
439         }
440     }
441 }
442 
443 impl<T: ?Sized> From<UniqueArc<T>> for Arc<T> {
444     fn from(item: UniqueArc<T>) -> Self {
445         item.inner
446     }
447 }
448 
449 impl<T: ?Sized> From<Pin<UniqueArc<T>>> for Arc<T> {
450     fn from(item: Pin<UniqueArc<T>>) -> Self {
451         // SAFETY: The type invariants of `Arc` guarantee that the data is pinned.
452         unsafe { Pin::into_inner_unchecked(item).inner }
453     }
454 }
455 
456 /// A borrowed reference to an [`Arc`] instance.
457 ///
458 /// For cases when one doesn't ever need to increment the refcount on the allocation, it is simpler
459 /// to use just `&T`, which we can trivially get from an [`Arc<T>`] instance.
460 ///
461 /// However, when one may need to increment the refcount, it is preferable to use an `ArcBorrow<T>`
462 /// over `&Arc<T>` because the latter results in a double-indirection: a pointer (shared reference)
463 /// to a pointer ([`Arc<T>`]) to the object (`T`). An [`ArcBorrow`] eliminates this double
464 /// indirection while still allowing one to increment the refcount and getting an [`Arc<T>`] when/if
465 /// needed.
466 ///
467 /// # Invariants
468 ///
469 /// There are no mutable references to the underlying [`Arc`], and it remains valid for the
470 /// lifetime of the [`ArcBorrow`] instance.
471 ///
472 /// # Example
473 ///
474 /// ```
475 /// use kernel::sync::{Arc, ArcBorrow};
476 ///
477 /// struct Example;
478 ///
479 /// fn do_something(e: ArcBorrow<'_, Example>) -> Arc<Example> {
480 ///     e.into()
481 /// }
482 ///
483 /// let obj = Arc::new(Example, GFP_KERNEL)?;
484 /// let cloned = do_something(obj.as_arc_borrow());
485 ///
486 /// // Assert that both `obj` and `cloned` point to the same underlying object.
487 /// assert!(core::ptr::eq(&*obj, &*cloned));
488 /// # Ok::<(), Error>(())
489 /// ```
490 ///
491 /// Using `ArcBorrow<T>` as the type of `self`:
492 ///
493 /// ```
494 /// use kernel::sync::{Arc, ArcBorrow};
495 ///
496 /// struct Example {
497 ///     a: u32,
498 ///     b: u32,
499 /// }
500 ///
501 /// impl Example {
502 ///     fn use_reference(self: ArcBorrow<'_, Self>) {
503 ///         // ...
504 ///     }
505 /// }
506 ///
507 /// let obj = Arc::new(Example { a: 10, b: 20 }, GFP_KERNEL)?;
508 /// obj.as_arc_borrow().use_reference();
509 /// # Ok::<(), Error>(())
510 /// ```
511 #[repr(transparent)]
512 #[cfg_attr(CONFIG_RUSTC_HAS_COERCE_POINTEE, derive(core::marker::CoercePointee))]
513 pub struct ArcBorrow<'a, T: ?Sized + 'a> {
514     inner: NonNull<ArcInner<T>>,
515     _p: PhantomData<&'a ()>,
516 }
517 
518 // This is to allow `ArcBorrow<U>` to be dispatched on when `ArcBorrow<T>` can be coerced into
519 // `ArcBorrow<U>`.
520 #[cfg(not(CONFIG_RUSTC_HAS_COERCE_POINTEE))]
521 impl<T: ?Sized + core::marker::Unsize<U>, U: ?Sized> core::ops::DispatchFromDyn<ArcBorrow<'_, U>>
522     for ArcBorrow<'_, T>
523 {
524 }
525 
526 impl<T: ?Sized> Clone for ArcBorrow<'_, T> {
527     fn clone(&self) -> Self {
528         *self
529     }
530 }
531 
532 impl<T: ?Sized> Copy for ArcBorrow<'_, T> {}
533 
534 impl<T: ?Sized> ArcBorrow<'_, T> {
535     /// Creates a new [`ArcBorrow`] instance.
536     ///
537     /// # Safety
538     ///
539     /// Callers must ensure the following for the lifetime of the returned [`ArcBorrow`] instance:
540     /// 1. That `inner` remains valid;
541     /// 2. That no mutable references to `inner` are created.
542     unsafe fn new(inner: NonNull<ArcInner<T>>) -> Self {
543         // INVARIANT: The safety requirements guarantee the invariants.
544         Self {
545             inner,
546             _p: PhantomData,
547         }
548     }
549 
550     /// Creates an [`ArcBorrow`] to an [`Arc`] that has previously been deconstructed with
551     /// [`Arc::into_raw`] or [`Arc::as_ptr`].
552     ///
553     /// # Safety
554     ///
555     /// * The provided pointer must originate from a call to [`Arc::into_raw`] or [`Arc::as_ptr`].
556     /// * For the duration of the lifetime annotated on this `ArcBorrow`, the reference count must
557     ///   not hit zero.
558     /// * For the duration of the lifetime annotated on this `ArcBorrow`, there must not be a
559     ///   [`UniqueArc`] reference to this value.
560     pub unsafe fn from_raw(ptr: *const T) -> Self {
561         // SAFETY: The caller promises that this pointer originates from a call to `into_raw` on an
562         // `Arc` that is still valid.
563         let ptr = unsafe { ArcInner::container_of(ptr) };
564 
565         // SAFETY: The caller promises that the value remains valid since the reference count must
566         // not hit zero, and no mutable reference will be created since that would involve a
567         // `UniqueArc`.
568         unsafe { Self::new(ptr) }
569     }
570 }
571 
572 impl<T: ?Sized> From<ArcBorrow<'_, T>> for Arc<T> {
573     fn from(b: ArcBorrow<'_, T>) -> Self {
574         // SAFETY: The existence of `b` guarantees that the refcount is non-zero. `ManuallyDrop`
575         // guarantees that `drop` isn't called, so it's ok that the temporary `Arc` doesn't own the
576         // increment.
577         ManuallyDrop::new(unsafe { Arc::from_inner(b.inner) })
578             .deref()
579             .clone()
580     }
581 }
582 
583 impl<T: ?Sized> Deref for ArcBorrow<'_, T> {
584     type Target = T;
585 
586     fn deref(&self) -> &Self::Target {
587         // SAFETY: By the type invariant, the underlying object is still alive with no mutable
588         // references to it, so it is safe to create a shared reference.
589         unsafe { &self.inner.as_ref().data }
590     }
591 }
592 
593 /// A refcounted object that is known to have a refcount of 1.
594 ///
595 /// It is mutable and can be converted to an [`Arc`] so that it can be shared.
596 ///
597 /// # Invariants
598 ///
599 /// `inner` always has a reference count of 1.
600 ///
601 /// # Examples
602 ///
603 /// In the following example, we make changes to the inner object before turning it into an
604 /// `Arc<Test>` object (after which point, it cannot be mutated directly). Note that `x.into()`
605 /// cannot fail.
606 ///
607 /// ```
608 /// use kernel::sync::{Arc, UniqueArc};
609 ///
610 /// struct Example {
611 ///     a: u32,
612 ///     b: u32,
613 /// }
614 ///
615 /// fn test() -> Result<Arc<Example>> {
616 ///     let mut x = UniqueArc::new(Example { a: 10, b: 20 }, GFP_KERNEL)?;
617 ///     x.a += 1;
618 ///     x.b += 1;
619 ///     Ok(x.into())
620 /// }
621 ///
622 /// # test().unwrap();
623 /// ```
624 ///
625 /// In the following example we first allocate memory for a refcounted `Example` but we don't
626 /// initialise it on allocation. We do initialise it later with a call to [`UniqueArc::write`],
627 /// followed by a conversion to `Arc<Example>`. This is particularly useful when allocation happens
628 /// in one context (e.g., sleepable) and initialisation in another (e.g., atomic):
629 ///
630 /// ```
631 /// use kernel::sync::{Arc, UniqueArc};
632 ///
633 /// struct Example {
634 ///     a: u32,
635 ///     b: u32,
636 /// }
637 ///
638 /// fn test() -> Result<Arc<Example>> {
639 ///     let x = UniqueArc::new_uninit(GFP_KERNEL)?;
640 ///     Ok(x.write(Example { a: 10, b: 20 }).into())
641 /// }
642 ///
643 /// # test().unwrap();
644 /// ```
645 ///
646 /// In the last example below, the caller gets a pinned instance of `Example` while converting to
647 /// `Arc<Example>`; this is useful in scenarios where one needs a pinned reference during
648 /// initialisation, for example, when initialising fields that are wrapped in locks.
649 ///
650 /// ```
651 /// use kernel::sync::{Arc, UniqueArc};
652 ///
653 /// struct Example {
654 ///     a: u32,
655 ///     b: u32,
656 /// }
657 ///
658 /// fn test() -> Result<Arc<Example>> {
659 ///     let mut pinned = Pin::from(UniqueArc::new(Example { a: 10, b: 20 }, GFP_KERNEL)?);
660 ///     // We can modify `pinned` because it is `Unpin`.
661 ///     pinned.as_mut().a += 1;
662 ///     Ok(pinned.into())
663 /// }
664 ///
665 /// # test().unwrap();
666 /// ```
667 pub struct UniqueArc<T: ?Sized> {
668     inner: Arc<T>,
669 }
670 
671 impl<T> UniqueArc<T> {
672     /// Tries to allocate a new [`UniqueArc`] instance.
673     pub fn new(value: T, flags: Flags) -> Result<Self, AllocError> {
674         Ok(Self {
675             // INVARIANT: The newly-created object has a refcount of 1.
676             inner: Arc::new(value, flags)?,
677         })
678     }
679 
680     /// Tries to allocate a new [`UniqueArc`] instance whose contents are not initialised yet.
681     pub fn new_uninit(flags: Flags) -> Result<UniqueArc<MaybeUninit<T>>, AllocError> {
682         // INVARIANT: The refcount is initialised to a non-zero value.
683         let inner = KBox::try_init::<AllocError>(
684             try_init!(ArcInner {
685                 // SAFETY: There are no safety requirements for this FFI call.
686                 refcount: Opaque::new(unsafe { bindings::REFCOUNT_INIT(1) }),
687                 data <- init::uninit::<T, AllocError>(),
688             }? AllocError),
689             flags,
690         )?;
691         Ok(UniqueArc {
692             // INVARIANT: The newly-created object has a refcount of 1.
693             // SAFETY: The pointer from the `KBox` is valid.
694             inner: unsafe { Arc::from_inner(KBox::leak(inner).into()) },
695         })
696     }
697 }
698 
699 impl<T> UniqueArc<MaybeUninit<T>> {
700     /// Converts a `UniqueArc<MaybeUninit<T>>` into a `UniqueArc<T>` by writing a value into it.
701     pub fn write(mut self, value: T) -> UniqueArc<T> {
702         self.deref_mut().write(value);
703         // SAFETY: We just wrote the value to be initialized.
704         unsafe { self.assume_init() }
705     }
706 
707     /// Unsafely assume that `self` is initialized.
708     ///
709     /// # Safety
710     ///
711     /// The caller guarantees that the value behind this pointer has been initialized. It is
712     /// *immediate* UB to call this when the value is not initialized.
713     pub unsafe fn assume_init(self) -> UniqueArc<T> {
714         let inner = ManuallyDrop::new(self).inner.ptr;
715         UniqueArc {
716             // SAFETY: The new `Arc` is taking over `ptr` from `self.inner` (which won't be
717             // dropped). The types are compatible because `MaybeUninit<T>` is compatible with `T`.
718             inner: unsafe { Arc::from_inner(inner.cast()) },
719         }
720     }
721 
722     /// Initialize `self` using the given initializer.
723     pub fn init_with<E>(mut self, init: impl Init<T, E>) -> core::result::Result<UniqueArc<T>, E> {
724         // SAFETY: The supplied pointer is valid for initialization.
725         match unsafe { init.__init(self.as_mut_ptr()) } {
726             // SAFETY: Initialization completed successfully.
727             Ok(()) => Ok(unsafe { self.assume_init() }),
728             Err(err) => Err(err),
729         }
730     }
731 
732     /// Pin-initialize `self` using the given pin-initializer.
733     pub fn pin_init_with<E>(
734         mut self,
735         init: impl PinInit<T, E>,
736     ) -> core::result::Result<Pin<UniqueArc<T>>, E> {
737         // SAFETY: The supplied pointer is valid for initialization and we will later pin the value
738         // to ensure it does not move.
739         match unsafe { init.__pinned_init(self.as_mut_ptr()) } {
740             // SAFETY: Initialization completed successfully.
741             Ok(()) => Ok(unsafe { self.assume_init() }.into()),
742             Err(err) => Err(err),
743         }
744     }
745 }
746 
747 impl<T: ?Sized> From<UniqueArc<T>> for Pin<UniqueArc<T>> {
748     fn from(obj: UniqueArc<T>) -> Self {
749         // SAFETY: It is not possible to move/replace `T` inside a `Pin<UniqueArc<T>>` (unless `T`
750         // is `Unpin`), so it is ok to convert it to `Pin<UniqueArc<T>>`.
751         unsafe { Pin::new_unchecked(obj) }
752     }
753 }
754 
755 impl<T: ?Sized> Deref for UniqueArc<T> {
756     type Target = T;
757 
758     fn deref(&self) -> &Self::Target {
759         self.inner.deref()
760     }
761 }
762 
763 impl<T: ?Sized> DerefMut for UniqueArc<T> {
764     fn deref_mut(&mut self) -> &mut Self::Target {
765         // SAFETY: By the `Arc` type invariant, there is necessarily a reference to the object, so
766         // it is safe to dereference it. Additionally, we know there is only one reference when
767         // it's inside a `UniqueArc`, so it is safe to get a mutable reference.
768         unsafe { &mut self.inner.ptr.as_mut().data }
769     }
770 }
771 
772 impl<T: fmt::Display + ?Sized> fmt::Display for UniqueArc<T> {
773     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
774         fmt::Display::fmt(self.deref(), f)
775     }
776 }
777 
778 impl<T: fmt::Display + ?Sized> fmt::Display for Arc<T> {
779     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
780         fmt::Display::fmt(self.deref(), f)
781     }
782 }
783 
784 impl<T: fmt::Debug + ?Sized> fmt::Debug for UniqueArc<T> {
785     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
786         fmt::Debug::fmt(self.deref(), f)
787     }
788 }
789 
790 impl<T: fmt::Debug + ?Sized> fmt::Debug for Arc<T> {
791     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
792         fmt::Debug::fmt(self.deref(), f)
793     }
794 }
795