arc.rs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  1. // SPDX-License-Identifier: GPL-2.0
  2. // Copyright (C) 2024 Google LLC.
  3. //! A wrapper around `Arc` for linked lists.
  4. use crate::alloc::{AllocError, Flags};
  5. use crate::prelude::*;
  6. use crate::sync::{Arc, ArcBorrow, UniqueArc};
  7. use core::marker::{PhantomPinned, Unsize};
  8. use core::ops::Deref;
  9. use core::pin::Pin;
  10. use core::sync::atomic::{AtomicBool, Ordering};
  11. /// Declares that this type has some way to ensure that there is exactly one `ListArc` instance for
  12. /// this id.
  13. ///
  14. /// Types that implement this trait should include some kind of logic for keeping track of whether
  15. /// a [`ListArc`] exists or not. We refer to this logic as "the tracking inside `T`".
  16. ///
  17. /// We allow the case where the tracking inside `T` thinks that a [`ListArc`] exists, but actually,
  18. /// there isn't a [`ListArc`]. However, we do not allow the opposite situation where a [`ListArc`]
  19. /// exists, but the tracking thinks it doesn't. This is because the former can at most result in us
  20. /// failing to create a [`ListArc`] when the operation could succeed, whereas the latter can result
  21. /// in the creation of two [`ListArc`] references. Only the latter situation can lead to memory
  22. /// safety issues.
  23. ///
  24. /// A consequence of the above is that you may implement the tracking inside `T` by not actually
  25. /// keeping track of anything. To do this, you always claim that a [`ListArc`] exists, even if
  26. /// there isn't one. This implementation is allowed by the above rule, but it means that
  27. /// [`ListArc`] references can only be created if you have ownership of *all* references to the
  28. /// refcounted object, as you otherwise have no way of knowing whether a [`ListArc`] exists.
  29. pub trait ListArcSafe<const ID: u64 = 0> {
  30. /// Informs the tracking inside this type that it now has a [`ListArc`] reference.
  31. ///
  32. /// This method may be called even if the tracking inside this type thinks that a `ListArc`
  33. /// reference exists. (But only if that's not actually the case.)
  34. ///
  35. /// # Safety
  36. ///
  37. /// Must not be called if a [`ListArc`] already exist for this value.
  38. unsafe fn on_create_list_arc_from_unique(self: Pin<&mut Self>);
  39. /// Informs the tracking inside this type that there is no [`ListArc`] reference anymore.
  40. ///
  41. /// # Safety
  42. ///
  43. /// Must only be called if there is no [`ListArc`] reference, but the tracking thinks there is.
  44. unsafe fn on_drop_list_arc(&self);
  45. }
  46. /// Declares that this type is able to safely attempt to create `ListArc`s at any time.
  47. ///
  48. /// # Safety
  49. ///
  50. /// The guarantees of `try_new_list_arc` must be upheld.
  51. pub unsafe trait TryNewListArc<const ID: u64 = 0>: ListArcSafe<ID> {
  52. /// Attempts to convert an `Arc<Self>` into an `ListArc<Self>`. Returns `true` if the
  53. /// conversion was successful.
  54. ///
  55. /// This method should not be called directly. Use [`ListArc::try_from_arc`] instead.
  56. ///
  57. /// # Guarantees
  58. ///
  59. /// If this call returns `true`, then there is no [`ListArc`] pointing to this value.
  60. /// Additionally, this call will have transitioned the tracking inside `Self` from not thinking
  61. /// that a [`ListArc`] exists, to thinking that a [`ListArc`] exists.
  62. fn try_new_list_arc(&self) -> bool;
  63. }
  64. /// Declares that this type supports [`ListArc`].
  65. ///
  66. /// This macro supports a few different strategies for implementing the tracking inside the type:
  67. ///
  68. /// * The `untracked` strategy does not actually keep track of whether a [`ListArc`] exists. When
  69. /// using this strategy, the only way to create a [`ListArc`] is using a [`UniqueArc`].
  70. /// * The `tracked_by` strategy defers the tracking to a field of the struct. The user much specify
  71. /// which field to defer the tracking to. The field must implement [`ListArcSafe`]. If the field
  72. /// implements [`TryNewListArc`], then the type will also implement [`TryNewListArc`].
  73. ///
  74. /// The `tracked_by` strategy is usually used by deferring to a field of type
  75. /// [`AtomicTracker`]. However, it is also possible to defer the tracking to another struct
  76. /// using also using this macro.
  77. #[macro_export]
  78. macro_rules! impl_list_arc_safe {
  79. (impl$({$($generics:tt)*})? ListArcSafe<$num:tt> for $t:ty { untracked; } $($rest:tt)*) => {
  80. impl$(<$($generics)*>)? $crate::list::ListArcSafe<$num> for $t {
  81. unsafe fn on_create_list_arc_from_unique(self: ::core::pin::Pin<&mut Self>) {}
  82. unsafe fn on_drop_list_arc(&self) {}
  83. }
  84. $crate::list::impl_list_arc_safe! { $($rest)* }
  85. };
  86. (impl$({$($generics:tt)*})? ListArcSafe<$num:tt> for $t:ty {
  87. tracked_by $field:ident : $fty:ty;
  88. } $($rest:tt)*) => {
  89. impl$(<$($generics)*>)? $crate::list::ListArcSafe<$num> for $t {
  90. unsafe fn on_create_list_arc_from_unique(self: ::core::pin::Pin<&mut Self>) {
  91. $crate::assert_pinned!($t, $field, $fty, inline);
  92. // SAFETY: This field is structurally pinned as per the above assertion.
  93. let field = unsafe {
  94. ::core::pin::Pin::map_unchecked_mut(self, |me| &mut me.$field)
  95. };
  96. // SAFETY: The caller promises that there is no `ListArc`.
  97. unsafe {
  98. <$fty as $crate::list::ListArcSafe<$num>>::on_create_list_arc_from_unique(field)
  99. };
  100. }
  101. unsafe fn on_drop_list_arc(&self) {
  102. // SAFETY: The caller promises that there is no `ListArc` reference, and also
  103. // promises that the tracking thinks there is a `ListArc` reference.
  104. unsafe { <$fty as $crate::list::ListArcSafe<$num>>::on_drop_list_arc(&self.$field) };
  105. }
  106. }
  107. unsafe impl$(<$($generics)*>)? $crate::list::TryNewListArc<$num> for $t
  108. where
  109. $fty: TryNewListArc<$num>,
  110. {
  111. fn try_new_list_arc(&self) -> bool {
  112. <$fty as $crate::list::TryNewListArc<$num>>::try_new_list_arc(&self.$field)
  113. }
  114. }
  115. $crate::list::impl_list_arc_safe! { $($rest)* }
  116. };
  117. () => {};
  118. }
  119. pub use impl_list_arc_safe;
  120. /// A wrapper around [`Arc`] that's guaranteed unique for the given id.
  121. ///
  122. /// The `ListArc` type can be thought of as a special reference to a refcounted object that owns the
  123. /// permission to manipulate the `next`/`prev` pointers stored in the refcounted object. By ensuring
  124. /// that each object has only one `ListArc` reference, the owner of that reference is assured
  125. /// exclusive access to the `next`/`prev` pointers. When a `ListArc` is inserted into a [`List`],
  126. /// the [`List`] takes ownership of the `ListArc` reference.
  127. ///
  128. /// There are various strategies to ensuring that a value has only one `ListArc` reference. The
  129. /// simplest is to convert a [`UniqueArc`] into a `ListArc`. However, the refcounted object could
  130. /// also keep track of whether a `ListArc` exists using a boolean, which could allow for the
  131. /// creation of new `ListArc` references from an [`Arc`] reference. Whatever strategy is used, the
  132. /// relevant tracking is referred to as "the tracking inside `T`", and the [`ListArcSafe`] trait
  133. /// (and its subtraits) are used to update the tracking when a `ListArc` is created or destroyed.
  134. ///
  135. /// Note that we allow the case where the tracking inside `T` thinks that a `ListArc` exists, but
  136. /// actually, there isn't a `ListArc`. However, we do not allow the opposite situation where a
  137. /// `ListArc` exists, but the tracking thinks it doesn't. This is because the former can at most
  138. /// result in us failing to create a `ListArc` when the operation could succeed, whereas the latter
  139. /// can result in the creation of two `ListArc` references.
  140. ///
  141. /// While this `ListArc` is unique for the given id, there still might exist normal `Arc`
  142. /// references to the object.
  143. ///
  144. /// # Invariants
  145. ///
  146. /// * Each reference counted object has at most one `ListArc` for each value of `ID`.
  147. /// * The tracking inside `T` is aware that a `ListArc` reference exists.
  148. ///
  149. /// [`List`]: crate::list::List
  150. #[repr(transparent)]
  151. pub struct ListArc<T, const ID: u64 = 0>
  152. where
  153. T: ListArcSafe<ID> + ?Sized,
  154. {
  155. arc: Arc<T>,
  156. }
  157. impl<T: ListArcSafe<ID>, const ID: u64> ListArc<T, ID> {
  158. /// Constructs a new reference counted instance of `T`.
  159. #[inline]
  160. pub fn new(contents: T, flags: Flags) -> Result<Self, AllocError> {
  161. Ok(Self::from(UniqueArc::new(contents, flags)?))
  162. }
  163. /// Use the given initializer to in-place initialize a `T`.
  164. ///
  165. /// If `T: !Unpin` it will not be able to move afterwards.
  166. // We don't implement `InPlaceInit` because `ListArc` is implicitly pinned. This is similar to
  167. // what we do for `Arc`.
  168. #[inline]
  169. pub fn pin_init<E>(init: impl PinInit<T, E>, flags: Flags) -> Result<Self, E>
  170. where
  171. E: From<AllocError>,
  172. {
  173. Ok(Self::from(UniqueArc::try_pin_init(init, flags)?))
  174. }
  175. /// Use the given initializer to in-place initialize a `T`.
  176. ///
  177. /// This is equivalent to [`ListArc<T>::pin_init`], since a [`ListArc`] is always pinned.
  178. #[inline]
  179. pub fn init<E>(init: impl Init<T, E>, flags: Flags) -> Result<Self, E>
  180. where
  181. E: From<AllocError>,
  182. {
  183. Ok(Self::from(UniqueArc::try_init(init, flags)?))
  184. }
  185. }
  186. impl<T, const ID: u64> From<UniqueArc<T>> for ListArc<T, ID>
  187. where
  188. T: ListArcSafe<ID> + ?Sized,
  189. {
  190. /// Convert a [`UniqueArc`] into a [`ListArc`].
  191. #[inline]
  192. fn from(unique: UniqueArc<T>) -> Self {
  193. Self::from(Pin::from(unique))
  194. }
  195. }
  196. impl<T, const ID: u64> From<Pin<UniqueArc<T>>> for ListArc<T, ID>
  197. where
  198. T: ListArcSafe<ID> + ?Sized,
  199. {
  200. /// Convert a pinned [`UniqueArc`] into a [`ListArc`].
  201. #[inline]
  202. fn from(mut unique: Pin<UniqueArc<T>>) -> Self {
  203. // SAFETY: We have a `UniqueArc`, so there is no `ListArc`.
  204. unsafe { T::on_create_list_arc_from_unique(unique.as_mut()) };
  205. let arc = Arc::from(unique);
  206. // SAFETY: We just called `on_create_list_arc_from_unique` on an arc without a `ListArc`,
  207. // so we can create a `ListArc`.
  208. unsafe { Self::transmute_from_arc(arc) }
  209. }
  210. }
  211. impl<T, const ID: u64> ListArc<T, ID>
  212. where
  213. T: ListArcSafe<ID> + ?Sized,
  214. {
  215. /// Creates two `ListArc`s from a [`UniqueArc`].
  216. ///
  217. /// The two ids must be different.
  218. #[inline]
  219. pub fn pair_from_unique<const ID2: u64>(unique: UniqueArc<T>) -> (Self, ListArc<T, ID2>)
  220. where
  221. T: ListArcSafe<ID2>,
  222. {
  223. Self::pair_from_pin_unique(Pin::from(unique))
  224. }
  225. /// Creates two `ListArc`s from a pinned [`UniqueArc`].
  226. ///
  227. /// The two ids must be different.
  228. #[inline]
  229. pub fn pair_from_pin_unique<const ID2: u64>(
  230. mut unique: Pin<UniqueArc<T>>,
  231. ) -> (Self, ListArc<T, ID2>)
  232. where
  233. T: ListArcSafe<ID2>,
  234. {
  235. build_assert!(ID != ID2);
  236. // SAFETY: We have a `UniqueArc`, so there is no `ListArc`.
  237. unsafe { <T as ListArcSafe<ID>>::on_create_list_arc_from_unique(unique.as_mut()) };
  238. // SAFETY: We have a `UniqueArc`, so there is no `ListArc`.
  239. unsafe { <T as ListArcSafe<ID2>>::on_create_list_arc_from_unique(unique.as_mut()) };
  240. let arc1 = Arc::from(unique);
  241. let arc2 = Arc::clone(&arc1);
  242. // SAFETY: We just called `on_create_list_arc_from_unique` on an arc without a `ListArc`
  243. // for both IDs (which are different), so we can create two `ListArc`s.
  244. unsafe {
  245. (
  246. Self::transmute_from_arc(arc1),
  247. ListArc::transmute_from_arc(arc2),
  248. )
  249. }
  250. }
  251. /// Try to create a new `ListArc`.
  252. ///
  253. /// This fails if this value already has a `ListArc`.
  254. pub fn try_from_arc(arc: Arc<T>) -> Result<Self, Arc<T>>
  255. where
  256. T: TryNewListArc<ID>,
  257. {
  258. if arc.try_new_list_arc() {
  259. // SAFETY: The `try_new_list_arc` method returned true, so we made the tracking think
  260. // that a `ListArc` exists. This lets us create a `ListArc`.
  261. Ok(unsafe { Self::transmute_from_arc(arc) })
  262. } else {
  263. Err(arc)
  264. }
  265. }
  266. /// Try to create a new `ListArc`.
  267. ///
  268. /// This fails if this value already has a `ListArc`.
  269. pub fn try_from_arc_borrow(arc: ArcBorrow<'_, T>) -> Option<Self>
  270. where
  271. T: TryNewListArc<ID>,
  272. {
  273. if arc.try_new_list_arc() {
  274. // SAFETY: The `try_new_list_arc` method returned true, so we made the tracking think
  275. // that a `ListArc` exists. This lets us create a `ListArc`.
  276. Some(unsafe { Self::transmute_from_arc(Arc::from(arc)) })
  277. } else {
  278. None
  279. }
  280. }
  281. /// Try to create a new `ListArc`.
  282. ///
  283. /// If it's not possible to create a new `ListArc`, then the `Arc` is dropped. This will never
  284. /// run the destructor of the value.
  285. pub fn try_from_arc_or_drop(arc: Arc<T>) -> Option<Self>
  286. where
  287. T: TryNewListArc<ID>,
  288. {
  289. match Self::try_from_arc(arc) {
  290. Ok(list_arc) => Some(list_arc),
  291. Err(arc) => Arc::into_unique_or_drop(arc).map(Self::from),
  292. }
  293. }
  294. /// Transmutes an [`Arc`] into a `ListArc` without updating the tracking inside `T`.
  295. ///
  296. /// # Safety
  297. ///
  298. /// * The value must not already have a `ListArc` reference.
  299. /// * The tracking inside `T` must think that there is a `ListArc` reference.
  300. #[inline]
  301. unsafe fn transmute_from_arc(arc: Arc<T>) -> Self {
  302. // INVARIANT: By the safety requirements, the invariants on `ListArc` are satisfied.
  303. Self { arc }
  304. }
  305. /// Transmutes a `ListArc` into an [`Arc`] without updating the tracking inside `T`.
  306. ///
  307. /// After this call, the tracking inside `T` will still think that there is a `ListArc`
  308. /// reference.
  309. #[inline]
  310. fn transmute_to_arc(self) -> Arc<T> {
  311. // Use a transmute to skip destructor.
  312. //
  313. // SAFETY: ListArc is repr(transparent).
  314. unsafe { core::mem::transmute(self) }
  315. }
  316. /// Convert ownership of this `ListArc` into a raw pointer.
  317. ///
  318. /// The returned pointer is indistinguishable from pointers returned by [`Arc::into_raw`]. The
  319. /// tracking inside `T` will still think that a `ListArc` exists after this call.
  320. #[inline]
  321. pub fn into_raw(self) -> *const T {
  322. Arc::into_raw(Self::transmute_to_arc(self))
  323. }
  324. /// Take ownership of the `ListArc` from a raw pointer.
  325. ///
  326. /// # Safety
  327. ///
  328. /// * `ptr` must satisfy the safety requirements of [`Arc::from_raw`].
  329. /// * The value must not already have a `ListArc` reference.
  330. /// * The tracking inside `T` must think that there is a `ListArc` reference.
  331. #[inline]
  332. pub unsafe fn from_raw(ptr: *const T) -> Self {
  333. // SAFETY: The pointer satisfies the safety requirements for `Arc::from_raw`.
  334. let arc = unsafe { Arc::from_raw(ptr) };
  335. // SAFETY: The value doesn't already have a `ListArc` reference, but the tracking thinks it
  336. // does.
  337. unsafe { Self::transmute_from_arc(arc) }
  338. }
  339. /// Converts the `ListArc` into an [`Arc`].
  340. #[inline]
  341. pub fn into_arc(self) -> Arc<T> {
  342. let arc = Self::transmute_to_arc(self);
  343. // SAFETY: There is no longer a `ListArc`, but the tracking thinks there is.
  344. unsafe { T::on_drop_list_arc(&arc) };
  345. arc
  346. }
  347. /// Clone a `ListArc` into an [`Arc`].
  348. #[inline]
  349. pub fn clone_arc(&self) -> Arc<T> {
  350. self.arc.clone()
  351. }
  352. /// Returns a reference to an [`Arc`] from the given [`ListArc`].
  353. ///
  354. /// This is useful when the argument of a function call is an [`&Arc`] (e.g., in a method
  355. /// receiver), but we have a [`ListArc`] instead.
  356. ///
  357. /// [`&Arc`]: Arc
  358. #[inline]
  359. pub fn as_arc(&self) -> &Arc<T> {
  360. &self.arc
  361. }
  362. /// Returns an [`ArcBorrow`] from the given [`ListArc`].
  363. ///
  364. /// This is useful when the argument of a function call is an [`ArcBorrow`] (e.g., in a method
  365. /// receiver), but we have an [`Arc`] instead. Getting an [`ArcBorrow`] is free when optimised.
  366. #[inline]
  367. pub fn as_arc_borrow(&self) -> ArcBorrow<'_, T> {
  368. self.arc.as_arc_borrow()
  369. }
  370. /// Compare whether two [`ListArc`] pointers reference the same underlying object.
  371. #[inline]
  372. pub fn ptr_eq(this: &Self, other: &Self) -> bool {
  373. Arc::ptr_eq(&this.arc, &other.arc)
  374. }
  375. }
  376. impl<T, const ID: u64> Deref for ListArc<T, ID>
  377. where
  378. T: ListArcSafe<ID> + ?Sized,
  379. {
  380. type Target = T;
  381. #[inline]
  382. fn deref(&self) -> &Self::Target {
  383. self.arc.deref()
  384. }
  385. }
  386. impl<T, const ID: u64> Drop for ListArc<T, ID>
  387. where
  388. T: ListArcSafe<ID> + ?Sized,
  389. {
  390. #[inline]
  391. fn drop(&mut self) {
  392. // SAFETY: There is no longer a `ListArc`, but the tracking thinks there is by the type
  393. // invariants on `Self`.
  394. unsafe { T::on_drop_list_arc(&self.arc) };
  395. }
  396. }
  397. impl<T, const ID: u64> AsRef<Arc<T>> for ListArc<T, ID>
  398. where
  399. T: ListArcSafe<ID> + ?Sized,
  400. {
  401. #[inline]
  402. fn as_ref(&self) -> &Arc<T> {
  403. self.as_arc()
  404. }
  405. }
  406. // This is to allow coercion from `ListArc<T>` to `ListArc<U>` if `T` can be converted to the
  407. // dynamically-sized type (DST) `U`.
  408. impl<T, U, const ID: u64> core::ops::CoerceUnsized<ListArc<U, ID>> for ListArc<T, ID>
  409. where
  410. T: ListArcSafe<ID> + Unsize<U> + ?Sized,
  411. U: ListArcSafe<ID> + ?Sized,
  412. {
  413. }
  414. // This is to allow `ListArc<U>` to be dispatched on when `ListArc<T>` can be coerced into
  415. // `ListArc<U>`.
  416. impl<T, U, const ID: u64> core::ops::DispatchFromDyn<ListArc<U, ID>> for ListArc<T, ID>
  417. where
  418. T: ListArcSafe<ID> + Unsize<U> + ?Sized,
  419. U: ListArcSafe<ID> + ?Sized,
  420. {
  421. }
  422. /// A utility for tracking whether a [`ListArc`] exists using an atomic.
  423. ///
  424. /// # Invariant
  425. ///
  426. /// If the boolean is `false`, then there is no [`ListArc`] for this value.
  427. #[repr(transparent)]
  428. pub struct AtomicTracker<const ID: u64 = 0> {
  429. inner: AtomicBool,
  430. // This value needs to be pinned to justify the INVARIANT: comment in `AtomicTracker::new`.
  431. _pin: PhantomPinned,
  432. }
  433. impl<const ID: u64> AtomicTracker<ID> {
  434. /// Creates a new initializer for this type.
  435. pub fn new() -> impl PinInit<Self> {
  436. // INVARIANT: Pin-init initializers can't be used on an existing `Arc`, so this value will
  437. // not be constructed in an `Arc` that already has a `ListArc`.
  438. Self {
  439. inner: AtomicBool::new(false),
  440. _pin: PhantomPinned,
  441. }
  442. }
  443. fn project_inner(self: Pin<&mut Self>) -> &mut AtomicBool {
  444. // SAFETY: The `inner` field is not structurally pinned, so we may obtain a mutable
  445. // reference to it even if we only have a pinned reference to `self`.
  446. unsafe { &mut Pin::into_inner_unchecked(self).inner }
  447. }
  448. }
  449. impl<const ID: u64> ListArcSafe<ID> for AtomicTracker<ID> {
  450. unsafe fn on_create_list_arc_from_unique(self: Pin<&mut Self>) {
  451. // INVARIANT: We just created a ListArc, so the boolean should be true.
  452. *self.project_inner().get_mut() = true;
  453. }
  454. unsafe fn on_drop_list_arc(&self) {
  455. // INVARIANT: We just dropped a ListArc, so the boolean should be false.
  456. self.inner.store(false, Ordering::Release);
  457. }
  458. }
  459. // SAFETY: If this method returns `true`, then by the type invariant there is no `ListArc` before
  460. // this call, so it is okay to create a new `ListArc`.
  461. //
  462. // The acquire ordering will synchronize with the release store from the destruction of any
  463. // previous `ListArc`, so if there was a previous `ListArc`, then the destruction of the previous
  464. // `ListArc` happens-before the creation of the new `ListArc`.
  465. unsafe impl<const ID: u64> TryNewListArc<ID> for AtomicTracker<ID> {
  466. fn try_new_list_arc(&self) -> bool {
  467. // INVARIANT: If this method returns true, then the boolean used to be false, and is no
  468. // longer false, so it is okay for the caller to create a new [`ListArc`].
  469. self.inner
  470. .compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed)
  471. .is_ok()
  472. }
  473. }