xref: /openbmc/linux/rust/kernel/sync/arc.rs (revision 92c4a1e7)
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 //!
16 //! [`Arc`]: https://doc.rust-lang.org/std/sync/struct.Arc.html
17 
18 use crate::{
19     bindings,
20     error::{self, Error},
21     init::{InPlaceInit, Init, PinInit},
22     types::{ForeignOwnable, Opaque},
23 };
24 use alloc::boxed::Box;
25 use core::{
26     alloc::AllocError,
27     fmt,
28     marker::{PhantomData, Unsize},
29     mem::{ManuallyDrop, MaybeUninit},
30     ops::{Deref, DerefMut},
31     pin::Pin,
32     ptr::NonNull,
33 };
34 
35 mod std_vendor;
36 
37 /// A reference-counted pointer to an instance of `T`.
38 ///
39 /// The reference count is incremented when new instances of [`Arc`] are created, and decremented
40 /// when they are dropped. When the count reaches zero, the underlying `T` is also dropped.
41 ///
42 /// # Invariants
43 ///
44 /// The reference count on an instance of [`Arc`] is always non-zero.
45 /// The object pointed to by [`Arc`] is always pinned.
46 ///
47 /// # Examples
48 ///
49 /// ```
50 /// use kernel::sync::Arc;
51 ///
52 /// struct Example {
53 ///     a: u32,
54 ///     b: u32,
55 /// }
56 ///
57 /// // Create a ref-counted instance of `Example`.
58 /// let obj = Arc::try_new(Example { a: 10, b: 20 })?;
59 ///
60 /// // Get a new pointer to `obj` and increment the refcount.
61 /// let cloned = obj.clone();
62 ///
63 /// // Assert that both `obj` and `cloned` point to the same underlying object.
64 /// assert!(core::ptr::eq(&*obj, &*cloned));
65 ///
66 /// // Destroy `obj` and decrement its refcount.
67 /// drop(obj);
68 ///
69 /// // Check that the values are still accessible through `cloned`.
70 /// assert_eq!(cloned.a, 10);
71 /// assert_eq!(cloned.b, 20);
72 ///
73 /// // The refcount drops to zero when `cloned` goes out of scope, and the memory is freed.
74 /// ```
75 ///
76 /// Using `Arc<T>` as the type of `self`:
77 ///
78 /// ```
79 /// use kernel::sync::Arc;
80 ///
81 /// struct Example {
82 ///     a: u32,
83 ///     b: u32,
84 /// }
85 ///
86 /// impl Example {
87 ///     fn take_over(self: Arc<Self>) {
88 ///         // ...
89 ///     }
90 ///
91 ///     fn use_reference(self: &Arc<Self>) {
92 ///         // ...
93 ///     }
94 /// }
95 ///
96 /// let obj = Arc::try_new(Example { a: 10, b: 20 })?;
97 /// obj.use_reference();
98 /// obj.take_over();
99 /// ```
100 ///
101 /// Coercion from `Arc<Example>` to `Arc<dyn MyTrait>`:
102 ///
103 /// ```
104 /// use kernel::sync::{Arc, ArcBorrow};
105 ///
106 /// trait MyTrait {
107 ///     // Trait has a function whose `self` type is `Arc<Self>`.
108 ///     fn example1(self: Arc<Self>) {}
109 ///
110 ///     // Trait has a function whose `self` type is `ArcBorrow<'_, Self>`.
111 ///     fn example2(self: ArcBorrow<'_, Self>) {}
112 /// }
113 ///
114 /// struct Example;
115 /// impl MyTrait for Example {}
116 ///
117 /// // `obj` has type `Arc<Example>`.
118 /// let obj: Arc<Example> = Arc::try_new(Example)?;
119 ///
120 /// // `coerced` has type `Arc<dyn MyTrait>`.
121 /// let coerced: Arc<dyn MyTrait> = obj;
122 /// ```
123 pub struct Arc<T: ?Sized> {
124     ptr: NonNull<ArcInner<T>>,
125     _p: PhantomData<ArcInner<T>>,
126 }
127 
128 #[repr(C)]
129 struct ArcInner<T: ?Sized> {
130     refcount: Opaque<bindings::refcount_t>,
131     data: T,
132 }
133 
134 // This is to allow [`Arc`] (and variants) to be used as the type of `self`.
135 impl<T: ?Sized> core::ops::Receiver for Arc<T> {}
136 
137 // This is to allow coercion from `Arc<T>` to `Arc<U>` if `T` can be converted to the
138 // dynamically-sized type (DST) `U`.
139 impl<T: ?Sized + Unsize<U>, U: ?Sized> core::ops::CoerceUnsized<Arc<U>> for Arc<T> {}
140 
141 // This is to allow `Arc<U>` to be dispatched on when `Arc<T>` can be coerced into `Arc<U>`.
142 impl<T: ?Sized + Unsize<U>, U: ?Sized> core::ops::DispatchFromDyn<Arc<U>> for Arc<T> {}
143 
144 // SAFETY: It is safe to send `Arc<T>` to another thread when the underlying `T` is `Sync` because
145 // it effectively means sharing `&T` (which is safe because `T` is `Sync`); additionally, it needs
146 // `T` to be `Send` because any thread that has an `Arc<T>` may ultimately access `T` directly, for
147 // example, when the reference count reaches zero and `T` is dropped.
148 unsafe impl<T: ?Sized + Sync + Send> Send for Arc<T> {}
149 
150 // SAFETY: It is safe to send `&Arc<T>` to another thread when the underlying `T` is `Sync` for the
151 // same reason as above. `T` needs to be `Send` as well because a thread can clone an `&Arc<T>`
152 // into an `Arc<T>`, which may lead to `T` being accessed by the same reasoning as above.
153 unsafe impl<T: ?Sized + Sync + Send> Sync for Arc<T> {}
154 
155 impl<T> Arc<T> {
156     /// Constructs a new reference counted instance of `T`.
157     pub fn try_new(contents: T) -> Result<Self, AllocError> {
158         // INVARIANT: The refcount is initialised to a non-zero value.
159         let value = ArcInner {
160             // SAFETY: There are no safety requirements for this FFI call.
161             refcount: Opaque::new(unsafe { bindings::REFCOUNT_INIT(1) }),
162             data: contents,
163         };
164 
165         let inner = Box::try_new(value)?;
166 
167         // SAFETY: We just created `inner` with a reference count of 1, which is owned by the new
168         // `Arc` object.
169         Ok(unsafe { Self::from_inner(Box::leak(inner).into()) })
170     }
171 
172     /// Use the given initializer to in-place initialize a `T`.
173     ///
174     /// If `T: !Unpin` it will not be able to move afterwards.
175     #[inline]
176     pub fn pin_init<E>(init: impl PinInit<T, E>) -> error::Result<Self>
177     where
178         Error: From<E>,
179     {
180         UniqueArc::pin_init(init).map(|u| u.into())
181     }
182 
183     /// Use the given initializer to in-place initialize a `T`.
184     ///
185     /// This is equivalent to [`pin_init`], since an [`Arc`] is always pinned.
186     #[inline]
187     pub fn init<E>(init: impl Init<T, E>) -> error::Result<Self>
188     where
189         Error: From<E>,
190     {
191         UniqueArc::init(init).map(|u| u.into())
192     }
193 }
194 
195 impl<T: ?Sized> Arc<T> {
196     /// Constructs a new [`Arc`] from an existing [`ArcInner`].
197     ///
198     /// # Safety
199     ///
200     /// The caller must ensure that `inner` points to a valid location and has a non-zero reference
201     /// count, one of which will be owned by the new [`Arc`] instance.
202     unsafe fn from_inner(inner: NonNull<ArcInner<T>>) -> Self {
203         // INVARIANT: By the safety requirements, the invariants hold.
204         Arc {
205             ptr: inner,
206             _p: PhantomData,
207         }
208     }
209 
210     /// Returns an [`ArcBorrow`] from the given [`Arc`].
211     ///
212     /// This is useful when the argument of a function call is an [`ArcBorrow`] (e.g., in a method
213     /// receiver), but we have an [`Arc`] instead. Getting an [`ArcBorrow`] is free when optimised.
214     #[inline]
215     pub fn as_arc_borrow(&self) -> ArcBorrow<'_, T> {
216         // SAFETY: The constraint that the lifetime of the shared reference must outlive that of
217         // the returned `ArcBorrow` ensures that the object remains alive and that no mutable
218         // reference can be created.
219         unsafe { ArcBorrow::new(self.ptr) }
220     }
221 }
222 
223 impl<T: 'static> ForeignOwnable for Arc<T> {
224     type Borrowed<'a> = ArcBorrow<'a, T>;
225 
226     fn into_foreign(self) -> *const core::ffi::c_void {
227         ManuallyDrop::new(self).ptr.as_ptr() as _
228     }
229 
230     unsafe fn borrow<'a>(ptr: *const core::ffi::c_void) -> ArcBorrow<'a, T> {
231         // SAFETY: By the safety requirement of this function, we know that `ptr` came from
232         // a previous call to `Arc::into_foreign`.
233         let inner = NonNull::new(ptr as *mut ArcInner<T>).unwrap();
234 
235         // SAFETY: The safety requirements of `from_foreign` ensure that the object remains alive
236         // for the lifetime of the returned value. Additionally, the safety requirements of
237         // `ForeignOwnable::borrow_mut` ensure that no new mutable references are created.
238         unsafe { ArcBorrow::new(inner) }
239     }
240 
241     unsafe fn from_foreign(ptr: *const core::ffi::c_void) -> Self {
242         // SAFETY: By the safety requirement of this function, we know that `ptr` came from
243         // a previous call to `Arc::into_foreign`, which guarantees that `ptr` is valid and
244         // holds a reference count increment that is transferrable to us.
245         unsafe { Self::from_inner(NonNull::new(ptr as _).unwrap()) }
246     }
247 }
248 
249 impl<T: ?Sized> Deref for Arc<T> {
250     type Target = T;
251 
252     fn deref(&self) -> &Self::Target {
253         // SAFETY: By the type invariant, there is necessarily a reference to the object, so it is
254         // safe to dereference it.
255         unsafe { &self.ptr.as_ref().data }
256     }
257 }
258 
259 impl<T: ?Sized> Clone for Arc<T> {
260     fn clone(&self) -> Self {
261         // INVARIANT: C `refcount_inc` saturates the refcount, so it cannot overflow to zero.
262         // SAFETY: By the type invariant, there is necessarily a reference to the object, so it is
263         // safe to increment the refcount.
264         unsafe { bindings::refcount_inc(self.ptr.as_ref().refcount.get()) };
265 
266         // SAFETY: We just incremented the refcount. This increment is now owned by the new `Arc`.
267         unsafe { Self::from_inner(self.ptr) }
268     }
269 }
270 
271 impl<T: ?Sized> Drop for Arc<T> {
272     fn drop(&mut self) {
273         // SAFETY: By the type invariant, there is necessarily a reference to the object. We cannot
274         // touch `refcount` after it's decremented to a non-zero value because another thread/CPU
275         // may concurrently decrement it to zero and free it. It is ok to have a raw pointer to
276         // freed/invalid memory as long as it is never dereferenced.
277         let refcount = unsafe { self.ptr.as_ref() }.refcount.get();
278 
279         // INVARIANT: If the refcount reaches zero, there are no other instances of `Arc`, and
280         // this instance is being dropped, so the broken invariant is not observable.
281         // SAFETY: Also by the type invariant, we are allowed to decrement the refcount.
282         let is_zero = unsafe { bindings::refcount_dec_and_test(refcount) };
283         if is_zero {
284             // The count reached zero, we must free the memory.
285             //
286             // SAFETY: The pointer was initialised from the result of `Box::leak`.
287             unsafe { Box::from_raw(self.ptr.as_ptr()) };
288         }
289     }
290 }
291 
292 impl<T: ?Sized> From<UniqueArc<T>> for Arc<T> {
293     fn from(item: UniqueArc<T>) -> Self {
294         item.inner
295     }
296 }
297 
298 impl<T: ?Sized> From<Pin<UniqueArc<T>>> for Arc<T> {
299     fn from(item: Pin<UniqueArc<T>>) -> Self {
300         // SAFETY: The type invariants of `Arc` guarantee that the data is pinned.
301         unsafe { Pin::into_inner_unchecked(item).inner }
302     }
303 }
304 
305 /// A borrowed reference to an [`Arc`] instance.
306 ///
307 /// For cases when one doesn't ever need to increment the refcount on the allocation, it is simpler
308 /// to use just `&T`, which we can trivially get from an `Arc<T>` instance.
309 ///
310 /// However, when one may need to increment the refcount, it is preferable to use an `ArcBorrow<T>`
311 /// over `&Arc<T>` because the latter results in a double-indirection: a pointer (shared reference)
312 /// to a pointer (`Arc<T>`) to the object (`T`). An [`ArcBorrow`] eliminates this double
313 /// indirection while still allowing one to increment the refcount and getting an `Arc<T>` when/if
314 /// needed.
315 ///
316 /// # Invariants
317 ///
318 /// There are no mutable references to the underlying [`Arc`], and it remains valid for the
319 /// lifetime of the [`ArcBorrow`] instance.
320 ///
321 /// # Example
322 ///
323 /// ```
324 /// use crate::sync::{Arc, ArcBorrow};
325 ///
326 /// struct Example;
327 ///
328 /// fn do_something(e: ArcBorrow<'_, Example>) -> Arc<Example> {
329 ///     e.into()
330 /// }
331 ///
332 /// let obj = Arc::try_new(Example)?;
333 /// let cloned = do_something(obj.as_arc_borrow());
334 ///
335 /// // Assert that both `obj` and `cloned` point to the same underlying object.
336 /// assert!(core::ptr::eq(&*obj, &*cloned));
337 /// ```
338 ///
339 /// Using `ArcBorrow<T>` as the type of `self`:
340 ///
341 /// ```
342 /// use crate::sync::{Arc, ArcBorrow};
343 ///
344 /// struct Example {
345 ///     a: u32,
346 ///     b: u32,
347 /// }
348 ///
349 /// impl Example {
350 ///     fn use_reference(self: ArcBorrow<'_, Self>) {
351 ///         // ...
352 ///     }
353 /// }
354 ///
355 /// let obj = Arc::try_new(Example { a: 10, b: 20 })?;
356 /// obj.as_arc_borrow().use_reference();
357 /// ```
358 pub struct ArcBorrow<'a, T: ?Sized + 'a> {
359     inner: NonNull<ArcInner<T>>,
360     _p: PhantomData<&'a ()>,
361 }
362 
363 // This is to allow [`ArcBorrow`] (and variants) to be used as the type of `self`.
364 impl<T: ?Sized> core::ops::Receiver for ArcBorrow<'_, T> {}
365 
366 // This is to allow `ArcBorrow<U>` to be dispatched on when `ArcBorrow<T>` can be coerced into
367 // `ArcBorrow<U>`.
368 impl<T: ?Sized + Unsize<U>, U: ?Sized> core::ops::DispatchFromDyn<ArcBorrow<'_, U>>
369     for ArcBorrow<'_, T>
370 {
371 }
372 
373 impl<T: ?Sized> Clone for ArcBorrow<'_, T> {
374     fn clone(&self) -> Self {
375         *self
376     }
377 }
378 
379 impl<T: ?Sized> Copy for ArcBorrow<'_, T> {}
380 
381 impl<T: ?Sized> ArcBorrow<'_, T> {
382     /// Creates a new [`ArcBorrow`] instance.
383     ///
384     /// # Safety
385     ///
386     /// Callers must ensure the following for the lifetime of the returned [`ArcBorrow`] instance:
387     /// 1. That `inner` remains valid;
388     /// 2. That no mutable references to `inner` are created.
389     unsafe fn new(inner: NonNull<ArcInner<T>>) -> Self {
390         // INVARIANT: The safety requirements guarantee the invariants.
391         Self {
392             inner,
393             _p: PhantomData,
394         }
395     }
396 }
397 
398 impl<T: ?Sized> From<ArcBorrow<'_, T>> for Arc<T> {
399     fn from(b: ArcBorrow<'_, T>) -> Self {
400         // SAFETY: The existence of `b` guarantees that the refcount is non-zero. `ManuallyDrop`
401         // guarantees that `drop` isn't called, so it's ok that the temporary `Arc` doesn't own the
402         // increment.
403         ManuallyDrop::new(unsafe { Arc::from_inner(b.inner) })
404             .deref()
405             .clone()
406     }
407 }
408 
409 impl<T: ?Sized> Deref for ArcBorrow<'_, T> {
410     type Target = T;
411 
412     fn deref(&self) -> &Self::Target {
413         // SAFETY: By the type invariant, the underlying object is still alive with no mutable
414         // references to it, so it is safe to create a shared reference.
415         unsafe { &self.inner.as_ref().data }
416     }
417 }
418 
419 /// A refcounted object that is known to have a refcount of 1.
420 ///
421 /// It is mutable and can be converted to an [`Arc`] so that it can be shared.
422 ///
423 /// # Invariants
424 ///
425 /// `inner` always has a reference count of 1.
426 ///
427 /// # Examples
428 ///
429 /// In the following example, we make changes to the inner object before turning it into an
430 /// `Arc<Test>` object (after which point, it cannot be mutated directly). Note that `x.into()`
431 /// cannot fail.
432 ///
433 /// ```
434 /// use kernel::sync::{Arc, UniqueArc};
435 ///
436 /// struct Example {
437 ///     a: u32,
438 ///     b: u32,
439 /// }
440 ///
441 /// fn test() -> Result<Arc<Example>> {
442 ///     let mut x = UniqueArc::try_new(Example { a: 10, b: 20 })?;
443 ///     x.a += 1;
444 ///     x.b += 1;
445 ///     Ok(x.into())
446 /// }
447 ///
448 /// # test().unwrap();
449 /// ```
450 ///
451 /// In the following example we first allocate memory for a ref-counted `Example` but we don't
452 /// initialise it on allocation. We do initialise it later with a call to [`UniqueArc::write`],
453 /// followed by a conversion to `Arc<Example>`. This is particularly useful when allocation happens
454 /// in one context (e.g., sleepable) and initialisation in another (e.g., atomic):
455 ///
456 /// ```
457 /// use kernel::sync::{Arc, UniqueArc};
458 ///
459 /// struct Example {
460 ///     a: u32,
461 ///     b: u32,
462 /// }
463 ///
464 /// fn test() -> Result<Arc<Example>> {
465 ///     let x = UniqueArc::try_new_uninit()?;
466 ///     Ok(x.write(Example { a: 10, b: 20 }).into())
467 /// }
468 ///
469 /// # test().unwrap();
470 /// ```
471 ///
472 /// In the last example below, the caller gets a pinned instance of `Example` while converting to
473 /// `Arc<Example>`; this is useful in scenarios where one needs a pinned reference during
474 /// initialisation, for example, when initialising fields that are wrapped in locks.
475 ///
476 /// ```
477 /// use kernel::sync::{Arc, UniqueArc};
478 ///
479 /// struct Example {
480 ///     a: u32,
481 ///     b: u32,
482 /// }
483 ///
484 /// fn test() -> Result<Arc<Example>> {
485 ///     let mut pinned = Pin::from(UniqueArc::try_new(Example { a: 10, b: 20 })?);
486 ///     // We can modify `pinned` because it is `Unpin`.
487 ///     pinned.as_mut().a += 1;
488 ///     Ok(pinned.into())
489 /// }
490 ///
491 /// # test().unwrap();
492 /// ```
493 pub struct UniqueArc<T: ?Sized> {
494     inner: Arc<T>,
495 }
496 
497 impl<T> UniqueArc<T> {
498     /// Tries to allocate a new [`UniqueArc`] instance.
499     pub fn try_new(value: T) -> Result<Self, AllocError> {
500         Ok(Self {
501             // INVARIANT: The newly-created object has a ref-count of 1.
502             inner: Arc::try_new(value)?,
503         })
504     }
505 
506     /// Tries to allocate a new [`UniqueArc`] instance whose contents are not initialised yet.
507     pub fn try_new_uninit() -> Result<UniqueArc<MaybeUninit<T>>, AllocError> {
508         Ok(UniqueArc::<MaybeUninit<T>> {
509             // INVARIANT: The newly-created object has a ref-count of 1.
510             inner: Arc::try_new(MaybeUninit::uninit())?,
511         })
512     }
513 }
514 
515 impl<T> UniqueArc<MaybeUninit<T>> {
516     /// Converts a `UniqueArc<MaybeUninit<T>>` into a `UniqueArc<T>` by writing a value into it.
517     pub fn write(mut self, value: T) -> UniqueArc<T> {
518         self.deref_mut().write(value);
519         // SAFETY: We just wrote the value to be initialized.
520         unsafe { self.assume_init() }
521     }
522 
523     /// Unsafely assume that `self` is initialized.
524     ///
525     /// # Safety
526     ///
527     /// The caller guarantees that the value behind this pointer has been initialized. It is
528     /// *immediate* UB to call this when the value is not initialized.
529     pub unsafe fn assume_init(self) -> UniqueArc<T> {
530         let inner = ManuallyDrop::new(self).inner.ptr;
531         UniqueArc {
532             // SAFETY: The new `Arc` is taking over `ptr` from `self.inner` (which won't be
533             // dropped). The types are compatible because `MaybeUninit<T>` is compatible with `T`.
534             inner: unsafe { Arc::from_inner(inner.cast()) },
535         }
536     }
537 }
538 
539 impl<T: ?Sized> From<UniqueArc<T>> for Pin<UniqueArc<T>> {
540     fn from(obj: UniqueArc<T>) -> Self {
541         // SAFETY: It is not possible to move/replace `T` inside a `Pin<UniqueArc<T>>` (unless `T`
542         // is `Unpin`), so it is ok to convert it to `Pin<UniqueArc<T>>`.
543         unsafe { Pin::new_unchecked(obj) }
544     }
545 }
546 
547 impl<T: ?Sized> Deref for UniqueArc<T> {
548     type Target = T;
549 
550     fn deref(&self) -> &Self::Target {
551         self.inner.deref()
552     }
553 }
554 
555 impl<T: ?Sized> DerefMut for UniqueArc<T> {
556     fn deref_mut(&mut self) -> &mut Self::Target {
557         // SAFETY: By the `Arc` type invariant, there is necessarily a reference to the object, so
558         // it is safe to dereference it. Additionally, we know there is only one reference when
559         // it's inside a `UniqueArc`, so it is safe to get a mutable reference.
560         unsafe { &mut self.inner.ptr.as_mut().data }
561     }
562 }
563 
564 impl<T: fmt::Display + ?Sized> fmt::Display for UniqueArc<T> {
565     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
566         fmt::Display::fmt(self.deref(), f)
567     }
568 }
569 
570 impl<T: fmt::Display + ?Sized> fmt::Display for Arc<T> {
571     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
572         fmt::Display::fmt(self.deref(), f)
573     }
574 }
575 
576 impl<T: fmt::Debug + ?Sized> fmt::Debug for UniqueArc<T> {
577     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
578         fmt::Debug::fmt(self.deref(), f)
579     }
580 }
581 
582 impl<T: fmt::Debug + ?Sized> fmt::Debug for Arc<T> {
583     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
584         fmt::Debug::fmt(self.deref(), f)
585     }
586 }
587