arc.rs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754
  1. // SPDX-License-Identifier: GPL-2.0
  2. //! A reference-counted pointer.
  3. //!
  4. //! This module implements a way for users to create reference-counted objects and pointers to
  5. //! them. Such a pointer automatically increments and decrements the count, and drops the
  6. //! underlying object when it reaches zero. It is also safe to use concurrently from multiple
  7. //! threads.
  8. //!
  9. //! It is different from the standard library's [`Arc`] in a few ways:
  10. //! 1. It is backed by the kernel's `refcount_t` type.
  11. //! 2. It does not support weak references, which allows it to be half the size.
  12. //! 3. It saturates the reference count instead of aborting when it goes over a threshold.
  13. //! 4. It does not provide a `get_mut` method, so the ref counted object is pinned.
  14. //! 5. The object in [`Arc`] is pinned implicitly.
  15. //!
  16. //! [`Arc`]: https://doc.rust-lang.org/std/sync/struct.Arc.html
  17. use crate::{
  18. alloc::{AllocError, Flags, KBox},
  19. bindings,
  20. init::{self, InPlaceInit, Init, PinInit},
  21. try_init,
  22. types::{ForeignOwnable, Opaque},
  23. };
  24. use core::{
  25. alloc::Layout,
  26. fmt,
  27. marker::{PhantomData, Unsize},
  28. mem::{ManuallyDrop, MaybeUninit},
  29. ops::{Deref, DerefMut},
  30. pin::Pin,
  31. ptr::NonNull,
  32. };
  33. use macros::pin_data;
  34. mod std_vendor;
  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 refcounted instance of `Example`.
  56. /// let obj = Arc::new(Example { a: 10, b: 20 }, GFP_KERNEL)?;
  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. /// # Ok::<(), Error>(())
  73. /// ```
  74. ///
  75. /// Using `Arc<T>` as the type of `self`:
  76. ///
  77. /// ```
  78. /// use kernel::sync::Arc;
  79. ///
  80. /// struct Example {
  81. /// a: u32,
  82. /// b: u32,
  83. /// }
  84. ///
  85. /// impl Example {
  86. /// fn take_over(self: Arc<Self>) {
  87. /// // ...
  88. /// }
  89. ///
  90. /// fn use_reference(self: &Arc<Self>) {
  91. /// // ...
  92. /// }
  93. /// }
  94. ///
  95. /// let obj = Arc::new(Example { a: 10, b: 20 }, GFP_KERNEL)?;
  96. /// obj.use_reference();
  97. /// obj.take_over();
  98. /// # Ok::<(), Error>(())
  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::new(Example, GFP_KERNEL)?;
  119. ///
  120. /// // `coerced` has type `Arc<dyn MyTrait>`.
  121. /// let coerced: Arc<dyn MyTrait> = obj;
  122. /// # Ok::<(), Error>(())
  123. /// ```
  124. pub struct Arc<T: ?Sized> {
  125. ptr: NonNull<ArcInner<T>>,
  126. _p: PhantomData<ArcInner<T>>,
  127. }
  128. #[pin_data]
  129. #[repr(C)]
  130. struct ArcInner<T: ?Sized> {
  131. refcount: Opaque<bindings::refcount_t>,
  132. data: T,
  133. }
  134. impl<T: ?Sized> ArcInner<T> {
  135. /// Converts a pointer to the contents of an [`Arc`] into a pointer to the [`ArcInner`].
  136. ///
  137. /// # Safety
  138. ///
  139. /// `ptr` must have been returned by a previous call to [`Arc::into_raw`], and the `Arc` must
  140. /// not yet have been destroyed.
  141. unsafe fn container_of(ptr: *const T) -> NonNull<ArcInner<T>> {
  142. let refcount_layout = Layout::new::<bindings::refcount_t>();
  143. // SAFETY: The caller guarantees that the pointer is valid.
  144. let val_layout = Layout::for_value(unsafe { &*ptr });
  145. // SAFETY: We're computing the layout of a real struct that existed when compiling this
  146. // binary, so its layout is not so large that it can trigger arithmetic overflow.
  147. let val_offset = unsafe { refcount_layout.extend(val_layout).unwrap_unchecked().1 };
  148. // Pointer casts leave the metadata unchanged. This is okay because the metadata of `T` and
  149. // `ArcInner<T>` is the same since `ArcInner` is a struct with `T` as its last field.
  150. //
  151. // This is documented at:
  152. // <https://doc.rust-lang.org/std/ptr/trait.Pointee.html>.
  153. let ptr = ptr as *const ArcInner<T>;
  154. // SAFETY: The pointer is in-bounds of an allocation both before and after offsetting the
  155. // pointer, since it originates from a previous call to `Arc::into_raw` on an `Arc` that is
  156. // still valid.
  157. let ptr = unsafe { ptr.byte_sub(val_offset) };
  158. // SAFETY: The pointer can't be null since you can't have an `ArcInner<T>` value at the null
  159. // address.
  160. unsafe { NonNull::new_unchecked(ptr.cast_mut()) }
  161. }
  162. }
  163. // This is to allow coercion from `Arc<T>` to `Arc<U>` if `T` can be converted to the
  164. // dynamically-sized type (DST) `U`.
  165. impl<T: ?Sized + Unsize<U>, U: ?Sized> core::ops::CoerceUnsized<Arc<U>> for Arc<T> {}
  166. // This is to allow `Arc<U>` to be dispatched on when `Arc<T>` can be coerced into `Arc<U>`.
  167. impl<T: ?Sized + Unsize<U>, U: ?Sized> core::ops::DispatchFromDyn<Arc<U>> for Arc<T> {}
  168. // SAFETY: It is safe to send `Arc<T>` to another thread when the underlying `T` is `Sync` because
  169. // it effectively means sharing `&T` (which is safe because `T` is `Sync`); additionally, it needs
  170. // `T` to be `Send` because any thread that has an `Arc<T>` may ultimately access `T` using a
  171. // mutable reference when the reference count reaches zero and `T` is dropped.
  172. unsafe impl<T: ?Sized + Sync + Send> Send for Arc<T> {}
  173. // SAFETY: It is safe to send `&Arc<T>` to another thread when the underlying `T` is `Sync`
  174. // because it effectively means sharing `&T` (which is safe because `T` is `Sync`); additionally,
  175. // it needs `T` to be `Send` because any thread that has a `&Arc<T>` may clone it and get an
  176. // `Arc<T>` on that thread, so the thread may ultimately access `T` using a mutable reference when
  177. // the reference count reaches zero and `T` is dropped.
  178. unsafe impl<T: ?Sized + Sync + Send> Sync for Arc<T> {}
  179. impl<T> Arc<T> {
  180. /// Constructs a new reference counted instance of `T`.
  181. pub fn new(contents: T, flags: Flags) -> Result<Self, AllocError> {
  182. // INVARIANT: The refcount is initialised to a non-zero value.
  183. let value = ArcInner {
  184. // SAFETY: There are no safety requirements for this FFI call.
  185. refcount: Opaque::new(unsafe { bindings::REFCOUNT_INIT(1) }),
  186. data: contents,
  187. };
  188. let inner = KBox::new(value, flags)?;
  189. // SAFETY: We just created `inner` with a reference count of 1, which is owned by the new
  190. // `Arc` object.
  191. Ok(unsafe { Self::from_inner(KBox::leak(inner).into()) })
  192. }
  193. }
  194. impl<T: ?Sized> Arc<T> {
  195. /// Constructs a new [`Arc`] from an existing [`ArcInner`].
  196. ///
  197. /// # Safety
  198. ///
  199. /// The caller must ensure that `inner` points to a valid location and has a non-zero reference
  200. /// count, one of which will be owned by the new [`Arc`] instance.
  201. unsafe fn from_inner(inner: NonNull<ArcInner<T>>) -> Self {
  202. // INVARIANT: By the safety requirements, the invariants hold.
  203. Arc {
  204. ptr: inner,
  205. _p: PhantomData,
  206. }
  207. }
  208. /// Convert the [`Arc`] into a raw pointer.
  209. ///
  210. /// The raw pointer has ownership of the refcount that this Arc object owned.
  211. pub fn into_raw(self) -> *const T {
  212. let ptr = self.ptr.as_ptr();
  213. core::mem::forget(self);
  214. // SAFETY: The pointer is valid.
  215. unsafe { core::ptr::addr_of!((*ptr).data) }
  216. }
  217. /// Recreates an [`Arc`] instance previously deconstructed via [`Arc::into_raw`].
  218. ///
  219. /// # Safety
  220. ///
  221. /// `ptr` must have been returned by a previous call to [`Arc::into_raw`]. Additionally, it
  222. /// must not be called more than once for each previous call to [`Arc::into_raw`].
  223. pub unsafe fn from_raw(ptr: *const T) -> Self {
  224. // SAFETY: The caller promises that this pointer originates from a call to `into_raw` on an
  225. // `Arc` that is still valid.
  226. let ptr = unsafe { ArcInner::container_of(ptr) };
  227. // SAFETY: By the safety requirements we know that `ptr` came from `Arc::into_raw`, so the
  228. // reference count held then will be owned by the new `Arc` object.
  229. unsafe { Self::from_inner(ptr) }
  230. }
  231. /// Returns an [`ArcBorrow`] from the given [`Arc`].
  232. ///
  233. /// This is useful when the argument of a function call is an [`ArcBorrow`] (e.g., in a method
  234. /// receiver), but we have an [`Arc`] instead. Getting an [`ArcBorrow`] is free when optimised.
  235. #[inline]
  236. pub fn as_arc_borrow(&self) -> ArcBorrow<'_, T> {
  237. // SAFETY: The constraint that the lifetime of the shared reference must outlive that of
  238. // the returned `ArcBorrow` ensures that the object remains alive and that no mutable
  239. // reference can be created.
  240. unsafe { ArcBorrow::new(self.ptr) }
  241. }
  242. /// Compare whether two [`Arc`] pointers reference the same underlying object.
  243. pub fn ptr_eq(this: &Self, other: &Self) -> bool {
  244. core::ptr::eq(this.ptr.as_ptr(), other.ptr.as_ptr())
  245. }
  246. /// Converts this [`Arc`] into a [`UniqueArc`], or destroys it if it is not unique.
  247. ///
  248. /// When this destroys the `Arc`, it does so while properly avoiding races. This means that
  249. /// this method will never call the destructor of the value.
  250. ///
  251. /// # Examples
  252. ///
  253. /// ```
  254. /// use kernel::sync::{Arc, UniqueArc};
  255. ///
  256. /// let arc = Arc::new(42, GFP_KERNEL)?;
  257. /// let unique_arc = arc.into_unique_or_drop();
  258. ///
  259. /// // The above conversion should succeed since refcount of `arc` is 1.
  260. /// assert!(unique_arc.is_some());
  261. ///
  262. /// assert_eq!(*(unique_arc.unwrap()), 42);
  263. ///
  264. /// # Ok::<(), Error>(())
  265. /// ```
  266. ///
  267. /// ```
  268. /// use kernel::sync::{Arc, UniqueArc};
  269. ///
  270. /// let arc = Arc::new(42, GFP_KERNEL)?;
  271. /// let another = arc.clone();
  272. ///
  273. /// let unique_arc = arc.into_unique_or_drop();
  274. ///
  275. /// // The above conversion should fail since refcount of `arc` is >1.
  276. /// assert!(unique_arc.is_none());
  277. ///
  278. /// # Ok::<(), Error>(())
  279. /// ```
  280. pub fn into_unique_or_drop(self) -> Option<Pin<UniqueArc<T>>> {
  281. // We will manually manage the refcount in this method, so we disable the destructor.
  282. let me = ManuallyDrop::new(self);
  283. // SAFETY: We own a refcount, so the pointer is still valid.
  284. let refcount = unsafe { me.ptr.as_ref() }.refcount.get();
  285. // If the refcount reaches a non-zero value, then we have destroyed this `Arc` and will
  286. // return without further touching the `Arc`. If the refcount reaches zero, then there are
  287. // no other arcs, and we can create a `UniqueArc`.
  288. //
  289. // SAFETY: We own a refcount, so the pointer is not dangling.
  290. let is_zero = unsafe { bindings::refcount_dec_and_test(refcount) };
  291. if is_zero {
  292. // SAFETY: We have exclusive access to the arc, so we can perform unsynchronized
  293. // accesses to the refcount.
  294. unsafe { core::ptr::write(refcount, bindings::REFCOUNT_INIT(1)) };
  295. // INVARIANT: We own the only refcount to this arc, so we may create a `UniqueArc`. We
  296. // must pin the `UniqueArc` because the values was previously in an `Arc`, and they pin
  297. // their values.
  298. Some(Pin::from(UniqueArc {
  299. inner: ManuallyDrop::into_inner(me),
  300. }))
  301. } else {
  302. None
  303. }
  304. }
  305. }
  306. impl<T: 'static> ForeignOwnable for Arc<T> {
  307. type Borrowed<'a> = ArcBorrow<'a, T>;
  308. fn into_foreign(self) -> *const crate::ffi::c_void {
  309. ManuallyDrop::new(self).ptr.as_ptr() as _
  310. }
  311. unsafe fn borrow<'a>(ptr: *const crate::ffi::c_void) -> ArcBorrow<'a, T> {
  312. // By the safety requirement of this function, we know that `ptr` came from
  313. // a previous call to `Arc::into_foreign`.
  314. let inner = NonNull::new(ptr as *mut ArcInner<T>).unwrap();
  315. // SAFETY: The safety requirements of `from_foreign` ensure that the object remains alive
  316. // for the lifetime of the returned value.
  317. unsafe { ArcBorrow::new(inner) }
  318. }
  319. unsafe fn from_foreign(ptr: *const crate::ffi::c_void) -> Self {
  320. // SAFETY: By the safety requirement of this function, we know that `ptr` came from
  321. // a previous call to `Arc::into_foreign`, which guarantees that `ptr` is valid and
  322. // holds a reference count increment that is transferrable to us.
  323. unsafe { Self::from_inner(NonNull::new(ptr as _).unwrap()) }
  324. }
  325. }
  326. impl<T: ?Sized> Deref for Arc<T> {
  327. type Target = T;
  328. fn deref(&self) -> &Self::Target {
  329. // SAFETY: By the type invariant, there is necessarily a reference to the object, so it is
  330. // safe to dereference it.
  331. unsafe { &self.ptr.as_ref().data }
  332. }
  333. }
  334. impl<T: ?Sized> AsRef<T> for Arc<T> {
  335. fn as_ref(&self) -> &T {
  336. self.deref()
  337. }
  338. }
  339. impl<T: ?Sized> Clone for Arc<T> {
  340. fn clone(&self) -> Self {
  341. // INVARIANT: C `refcount_inc` saturates the refcount, so it cannot overflow to zero.
  342. // SAFETY: By the type invariant, there is necessarily a reference to the object, so it is
  343. // safe to increment the refcount.
  344. unsafe { bindings::refcount_inc(self.ptr.as_ref().refcount.get()) };
  345. // SAFETY: We just incremented the refcount. This increment is now owned by the new `Arc`.
  346. unsafe { Self::from_inner(self.ptr) }
  347. }
  348. }
  349. impl<T: ?Sized> Drop for Arc<T> {
  350. fn drop(&mut self) {
  351. // SAFETY: By the type invariant, there is necessarily a reference to the object. We cannot
  352. // touch `refcount` after it's decremented to a non-zero value because another thread/CPU
  353. // may concurrently decrement it to zero and free it. It is ok to have a raw pointer to
  354. // freed/invalid memory as long as it is never dereferenced.
  355. let refcount = unsafe { self.ptr.as_ref() }.refcount.get();
  356. // INVARIANT: If the refcount reaches zero, there are no other instances of `Arc`, and
  357. // this instance is being dropped, so the broken invariant is not observable.
  358. // SAFETY: Also by the type invariant, we are allowed to decrement the refcount.
  359. let is_zero = unsafe { bindings::refcount_dec_and_test(refcount) };
  360. if is_zero {
  361. // The count reached zero, we must free the memory.
  362. //
  363. // SAFETY: The pointer was initialised from the result of `KBox::leak`.
  364. unsafe { drop(KBox::from_raw(self.ptr.as_ptr())) };
  365. }
  366. }
  367. }
  368. impl<T: ?Sized> From<UniqueArc<T>> for Arc<T> {
  369. fn from(item: UniqueArc<T>) -> Self {
  370. item.inner
  371. }
  372. }
  373. impl<T: ?Sized> From<Pin<UniqueArc<T>>> for Arc<T> {
  374. fn from(item: Pin<UniqueArc<T>>) -> Self {
  375. // SAFETY: The type invariants of `Arc` guarantee that the data is pinned.
  376. unsafe { Pin::into_inner_unchecked(item).inner }
  377. }
  378. }
  379. /// A borrowed reference to an [`Arc`] instance.
  380. ///
  381. /// For cases when one doesn't ever need to increment the refcount on the allocation, it is simpler
  382. /// to use just `&T`, which we can trivially get from an [`Arc<T>`] instance.
  383. ///
  384. /// However, when one may need to increment the refcount, it is preferable to use an `ArcBorrow<T>`
  385. /// over `&Arc<T>` because the latter results in a double-indirection: a pointer (shared reference)
  386. /// to a pointer ([`Arc<T>`]) to the object (`T`). An [`ArcBorrow`] eliminates this double
  387. /// indirection while still allowing one to increment the refcount and getting an [`Arc<T>`] when/if
  388. /// needed.
  389. ///
  390. /// # Invariants
  391. ///
  392. /// There are no mutable references to the underlying [`Arc`], and it remains valid for the
  393. /// lifetime of the [`ArcBorrow`] instance.
  394. ///
  395. /// # Example
  396. ///
  397. /// ```
  398. /// use kernel::sync::{Arc, ArcBorrow};
  399. ///
  400. /// struct Example;
  401. ///
  402. /// fn do_something(e: ArcBorrow<'_, Example>) -> Arc<Example> {
  403. /// e.into()
  404. /// }
  405. ///
  406. /// let obj = Arc::new(Example, GFP_KERNEL)?;
  407. /// let cloned = do_something(obj.as_arc_borrow());
  408. ///
  409. /// // Assert that both `obj` and `cloned` point to the same underlying object.
  410. /// assert!(core::ptr::eq(&*obj, &*cloned));
  411. /// # Ok::<(), Error>(())
  412. /// ```
  413. ///
  414. /// Using `ArcBorrow<T>` as the type of `self`:
  415. ///
  416. /// ```
  417. /// use kernel::sync::{Arc, ArcBorrow};
  418. ///
  419. /// struct Example {
  420. /// a: u32,
  421. /// b: u32,
  422. /// }
  423. ///
  424. /// impl Example {
  425. /// fn use_reference(self: ArcBorrow<'_, Self>) {
  426. /// // ...
  427. /// }
  428. /// }
  429. ///
  430. /// let obj = Arc::new(Example { a: 10, b: 20 }, GFP_KERNEL)?;
  431. /// obj.as_arc_borrow().use_reference();
  432. /// # Ok::<(), Error>(())
  433. /// ```
  434. pub struct ArcBorrow<'a, T: ?Sized + 'a> {
  435. inner: NonNull<ArcInner<T>>,
  436. _p: PhantomData<&'a ()>,
  437. }
  438. // This is to allow `ArcBorrow<U>` to be dispatched on when `ArcBorrow<T>` can be coerced into
  439. // `ArcBorrow<U>`.
  440. impl<T: ?Sized + Unsize<U>, U: ?Sized> core::ops::DispatchFromDyn<ArcBorrow<'_, U>>
  441. for ArcBorrow<'_, T>
  442. {
  443. }
  444. impl<T: ?Sized> Clone for ArcBorrow<'_, T> {
  445. fn clone(&self) -> Self {
  446. *self
  447. }
  448. }
  449. impl<T: ?Sized> Copy for ArcBorrow<'_, T> {}
  450. impl<T: ?Sized> ArcBorrow<'_, T> {
  451. /// Creates a new [`ArcBorrow`] instance.
  452. ///
  453. /// # Safety
  454. ///
  455. /// Callers must ensure the following for the lifetime of the returned [`ArcBorrow`] instance:
  456. /// 1. That `inner` remains valid;
  457. /// 2. That no mutable references to `inner` are created.
  458. unsafe fn new(inner: NonNull<ArcInner<T>>) -> Self {
  459. // INVARIANT: The safety requirements guarantee the invariants.
  460. Self {
  461. inner,
  462. _p: PhantomData,
  463. }
  464. }
  465. /// Creates an [`ArcBorrow`] to an [`Arc`] that has previously been deconstructed with
  466. /// [`Arc::into_raw`].
  467. ///
  468. /// # Safety
  469. ///
  470. /// * The provided pointer must originate from a call to [`Arc::into_raw`].
  471. /// * For the duration of the lifetime annotated on this `ArcBorrow`, the reference count must
  472. /// not hit zero.
  473. /// * For the duration of the lifetime annotated on this `ArcBorrow`, there must not be a
  474. /// [`UniqueArc`] reference to this value.
  475. pub unsafe fn from_raw(ptr: *const T) -> Self {
  476. // SAFETY: The caller promises that this pointer originates from a call to `into_raw` on an
  477. // `Arc` that is still valid.
  478. let ptr = unsafe { ArcInner::container_of(ptr) };
  479. // SAFETY: The caller promises that the value remains valid since the reference count must
  480. // not hit zero, and no mutable reference will be created since that would involve a
  481. // `UniqueArc`.
  482. unsafe { Self::new(ptr) }
  483. }
  484. }
  485. impl<T: ?Sized> From<ArcBorrow<'_, T>> for Arc<T> {
  486. fn from(b: ArcBorrow<'_, T>) -> Self {
  487. // SAFETY: The existence of `b` guarantees that the refcount is non-zero. `ManuallyDrop`
  488. // guarantees that `drop` isn't called, so it's ok that the temporary `Arc` doesn't own the
  489. // increment.
  490. ManuallyDrop::new(unsafe { Arc::from_inner(b.inner) })
  491. .deref()
  492. .clone()
  493. }
  494. }
  495. impl<T: ?Sized> Deref for ArcBorrow<'_, T> {
  496. type Target = T;
  497. fn deref(&self) -> &Self::Target {
  498. // SAFETY: By the type invariant, the underlying object is still alive with no mutable
  499. // references to it, so it is safe to create a shared reference.
  500. unsafe { &self.inner.as_ref().data }
  501. }
  502. }
  503. /// A refcounted object that is known to have a refcount of 1.
  504. ///
  505. /// It is mutable and can be converted to an [`Arc`] so that it can be shared.
  506. ///
  507. /// # Invariants
  508. ///
  509. /// `inner` always has a reference count of 1.
  510. ///
  511. /// # Examples
  512. ///
  513. /// In the following example, we make changes to the inner object before turning it into an
  514. /// `Arc<Test>` object (after which point, it cannot be mutated directly). Note that `x.into()`
  515. /// cannot fail.
  516. ///
  517. /// ```
  518. /// use kernel::sync::{Arc, UniqueArc};
  519. ///
  520. /// struct Example {
  521. /// a: u32,
  522. /// b: u32,
  523. /// }
  524. ///
  525. /// fn test() -> Result<Arc<Example>> {
  526. /// let mut x = UniqueArc::new(Example { a: 10, b: 20 }, GFP_KERNEL)?;
  527. /// x.a += 1;
  528. /// x.b += 1;
  529. /// Ok(x.into())
  530. /// }
  531. ///
  532. /// # test().unwrap();
  533. /// ```
  534. ///
  535. /// In the following example we first allocate memory for a refcounted `Example` but we don't
  536. /// initialise it on allocation. We do initialise it later with a call to [`UniqueArc::write`],
  537. /// followed by a conversion to `Arc<Example>`. This is particularly useful when allocation happens
  538. /// in one context (e.g., sleepable) and initialisation in another (e.g., atomic):
  539. ///
  540. /// ```
  541. /// use kernel::sync::{Arc, UniqueArc};
  542. ///
  543. /// struct Example {
  544. /// a: u32,
  545. /// b: u32,
  546. /// }
  547. ///
  548. /// fn test() -> Result<Arc<Example>> {
  549. /// let x = UniqueArc::new_uninit(GFP_KERNEL)?;
  550. /// Ok(x.write(Example { a: 10, b: 20 }).into())
  551. /// }
  552. ///
  553. /// # test().unwrap();
  554. /// ```
  555. ///
  556. /// In the last example below, the caller gets a pinned instance of `Example` while converting to
  557. /// `Arc<Example>`; this is useful in scenarios where one needs a pinned reference during
  558. /// initialisation, for example, when initialising fields that are wrapped in locks.
  559. ///
  560. /// ```
  561. /// use kernel::sync::{Arc, UniqueArc};
  562. ///
  563. /// struct Example {
  564. /// a: u32,
  565. /// b: u32,
  566. /// }
  567. ///
  568. /// fn test() -> Result<Arc<Example>> {
  569. /// let mut pinned = Pin::from(UniqueArc::new(Example { a: 10, b: 20 }, GFP_KERNEL)?);
  570. /// // We can modify `pinned` because it is `Unpin`.
  571. /// pinned.as_mut().a += 1;
  572. /// Ok(pinned.into())
  573. /// }
  574. ///
  575. /// # test().unwrap();
  576. /// ```
  577. pub struct UniqueArc<T: ?Sized> {
  578. inner: Arc<T>,
  579. }
  580. impl<T> UniqueArc<T> {
  581. /// Tries to allocate a new [`UniqueArc`] instance.
  582. pub fn new(value: T, flags: Flags) -> Result<Self, AllocError> {
  583. Ok(Self {
  584. // INVARIANT: The newly-created object has a refcount of 1.
  585. inner: Arc::new(value, flags)?,
  586. })
  587. }
  588. /// Tries to allocate a new [`UniqueArc`] instance whose contents are not initialised yet.
  589. pub fn new_uninit(flags: Flags) -> Result<UniqueArc<MaybeUninit<T>>, AllocError> {
  590. // INVARIANT: The refcount is initialised to a non-zero value.
  591. let inner = KBox::try_init::<AllocError>(
  592. try_init!(ArcInner {
  593. // SAFETY: There are no safety requirements for this FFI call.
  594. refcount: Opaque::new(unsafe { bindings::REFCOUNT_INIT(1) }),
  595. data <- init::uninit::<T, AllocError>(),
  596. }? AllocError),
  597. flags,
  598. )?;
  599. Ok(UniqueArc {
  600. // INVARIANT: The newly-created object has a refcount of 1.
  601. // SAFETY: The pointer from the `KBox` is valid.
  602. inner: unsafe { Arc::from_inner(KBox::leak(inner).into()) },
  603. })
  604. }
  605. }
  606. impl<T> UniqueArc<MaybeUninit<T>> {
  607. /// Converts a `UniqueArc<MaybeUninit<T>>` into a `UniqueArc<T>` by writing a value into it.
  608. pub fn write(mut self, value: T) -> UniqueArc<T> {
  609. self.deref_mut().write(value);
  610. // SAFETY: We just wrote the value to be initialized.
  611. unsafe { self.assume_init() }
  612. }
  613. /// Unsafely assume that `self` is initialized.
  614. ///
  615. /// # Safety
  616. ///
  617. /// The caller guarantees that the value behind this pointer has been initialized. It is
  618. /// *immediate* UB to call this when the value is not initialized.
  619. pub unsafe fn assume_init(self) -> UniqueArc<T> {
  620. let inner = ManuallyDrop::new(self).inner.ptr;
  621. UniqueArc {
  622. // SAFETY: The new `Arc` is taking over `ptr` from `self.inner` (which won't be
  623. // dropped). The types are compatible because `MaybeUninit<T>` is compatible with `T`.
  624. inner: unsafe { Arc::from_inner(inner.cast()) },
  625. }
  626. }
  627. /// Initialize `self` using the given initializer.
  628. pub fn init_with<E>(mut self, init: impl Init<T, E>) -> core::result::Result<UniqueArc<T>, E> {
  629. // SAFETY: The supplied pointer is valid for initialization.
  630. match unsafe { init.__init(self.as_mut_ptr()) } {
  631. // SAFETY: Initialization completed successfully.
  632. Ok(()) => Ok(unsafe { self.assume_init() }),
  633. Err(err) => Err(err),
  634. }
  635. }
  636. /// Pin-initialize `self` using the given pin-initializer.
  637. pub fn pin_init_with<E>(
  638. mut self,
  639. init: impl PinInit<T, E>,
  640. ) -> core::result::Result<Pin<UniqueArc<T>>, E> {
  641. // SAFETY: The supplied pointer is valid for initialization and we will later pin the value
  642. // to ensure it does not move.
  643. match unsafe { init.__pinned_init(self.as_mut_ptr()) } {
  644. // SAFETY: Initialization completed successfully.
  645. Ok(()) => Ok(unsafe { self.assume_init() }.into()),
  646. Err(err) => Err(err),
  647. }
  648. }
  649. }
  650. impl<T: ?Sized> From<UniqueArc<T>> for Pin<UniqueArc<T>> {
  651. fn from(obj: UniqueArc<T>) -> Self {
  652. // SAFETY: It is not possible to move/replace `T` inside a `Pin<UniqueArc<T>>` (unless `T`
  653. // is `Unpin`), so it is ok to convert it to `Pin<UniqueArc<T>>`.
  654. unsafe { Pin::new_unchecked(obj) }
  655. }
  656. }
  657. impl<T: ?Sized> Deref for UniqueArc<T> {
  658. type Target = T;
  659. fn deref(&self) -> &Self::Target {
  660. self.inner.deref()
  661. }
  662. }
  663. impl<T: ?Sized> DerefMut for UniqueArc<T> {
  664. fn deref_mut(&mut self) -> &mut Self::Target {
  665. // SAFETY: By the `Arc` type invariant, there is necessarily a reference to the object, so
  666. // it is safe to dereference it. Additionally, we know there is only one reference when
  667. // it's inside a `UniqueArc`, so it is safe to get a mutable reference.
  668. unsafe { &mut self.inner.ptr.as_mut().data }
  669. }
  670. }
  671. impl<T: fmt::Display + ?Sized> fmt::Display for UniqueArc<T> {
  672. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  673. fmt::Display::fmt(self.deref(), f)
  674. }
  675. }
  676. impl<T: fmt::Display + ?Sized> fmt::Display for Arc<T> {
  677. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  678. fmt::Display::fmt(self.deref(), f)
  679. }
  680. }
  681. impl<T: fmt::Debug + ?Sized> fmt::Debug for UniqueArc<T> {
  682. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  683. fmt::Debug::fmt(self.deref(), f)
  684. }
  685. }
  686. impl<T: fmt::Debug + ?Sized> fmt::Debug for Arc<T> {
  687. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  688. fmt::Debug::fmt(self.deref(), f)
  689. }
  690. }