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