// SPDX-License-Identifier: GPL-2.012// Copyright (C) 2024 Google LLC.34//! A wrapper around `Arc` for linked lists.56use crate::alloc::{AllocError, Flags};7use crate::prelude::*;8use crate::sync::{Arc, ArcBorrow, UniqueArc};9use core::marker::PhantomPinned;10use core::ops::Deref;11use core::pin::Pin;12use core::sync::atomic::{AtomicBool, Ordering};1314/// Declares that this type has some way to ensure that there is exactly one `ListArc` instance for15/// this id.16///17/// Types that implement this trait should include some kind of logic for keeping track of whether18/// a [`ListArc`] exists or not. We refer to this logic as "the tracking inside `T`".19///20/// We allow the case where the tracking inside `T` thinks that a [`ListArc`] exists, but actually,21/// there isn't a [`ListArc`]. However, we do not allow the opposite situation where a [`ListArc`]22/// exists, but the tracking thinks it doesn't. This is because the former can at most result in us23/// failing to create a [`ListArc`] when the operation could succeed, whereas the latter can result24/// in the creation of two [`ListArc`] references. Only the latter situation can lead to memory25/// safety issues.26///27/// A consequence of the above is that you may implement the tracking inside `T` by not actually28/// keeping track of anything. To do this, you always claim that a [`ListArc`] exists, even if29/// there isn't one. This implementation is allowed by the above rule, but it means that30/// [`ListArc`] references can only be created if you have ownership of *all* references to the31/// refcounted object, as you otherwise have no way of knowing whether a [`ListArc`] exists.32pub trait ListArcSafe<const ID: u64 = 0> {33/// Informs the tracking inside this type that it now has a [`ListArc`] reference.34///35/// This method may be called even if the tracking inside this type thinks that a `ListArc`36/// reference exists. (But only if that's not actually the case.)37///38/// # Safety39///40/// Must not be called if a [`ListArc`] already exist for this value.41unsafe fn on_create_list_arc_from_unique(self: Pin<&mut Self>);4243/// Informs the tracking inside this type that there is no [`ListArc`] reference anymore.44///45/// # Safety46///47/// Must only be called if there is no [`ListArc`] reference, but the tracking thinks there is.48unsafe fn on_drop_list_arc(&self);49}5051/// Declares that this type is able to safely attempt to create `ListArc`s at any time.52///53/// # Safety54///55/// The guarantees of `try_new_list_arc` must be upheld.56pub unsafe trait TryNewListArc<const ID: u64 = 0>: ListArcSafe<ID> {57/// Attempts to convert an `Arc<Self>` into an `ListArc<Self>`. Returns `true` if the58/// conversion was successful.59///60/// This method should not be called directly. Use [`ListArc::try_from_arc`] instead.61///62/// # Guarantees63///64/// If this call returns `true`, then there is no [`ListArc`] pointing to this value.65/// Additionally, this call will have transitioned the tracking inside `Self` from not thinking66/// that a [`ListArc`] exists, to thinking that a [`ListArc`] exists.67fn try_new_list_arc(&self) -> bool;68}6970/// Declares that this type supports [`ListArc`].71///72/// This macro supports a few different strategies for implementing the tracking inside the type:73///74/// * The `untracked` strategy does not actually keep track of whether a [`ListArc`] exists. When75/// using this strategy, the only way to create a [`ListArc`] is using a [`UniqueArc`].76/// * The `tracked_by` strategy defers the tracking to a field of the struct. The user must specify77/// which field to defer the tracking to. The field must implement [`ListArcSafe`]. If the field78/// implements [`TryNewListArc`], then the type will also implement [`TryNewListArc`].79///80/// The `tracked_by` strategy is usually used by deferring to a field of type81/// [`AtomicTracker`]. However, it is also possible to defer the tracking to another struct82/// using also using this macro.83#[macro_export]84macro_rules! impl_list_arc_safe {85(impl$({$($generics:tt)*})? ListArcSafe<$num:tt> for $t:ty { untracked; } $($rest:tt)*) => {86impl$(<$($generics)*>)? $crate::list::ListArcSafe<$num> for $t {87unsafe fn on_create_list_arc_from_unique(self: ::core::pin::Pin<&mut Self>) {}88unsafe fn on_drop_list_arc(&self) {}89}90$crate::list::impl_list_arc_safe! { $($rest)* }91};9293(impl$({$($generics:tt)*})? ListArcSafe<$num:tt> for $t:ty {94tracked_by $field:ident : $fty:ty;95} $($rest:tt)*) => {96impl$(<$($generics)*>)? $crate::list::ListArcSafe<$num> for $t {97unsafe fn on_create_list_arc_from_unique(self: ::core::pin::Pin<&mut Self>) {98::pin_init::assert_pinned!($t, $field, $fty, inline);99100// SAFETY: This field is structurally pinned as per the above assertion.101let field = unsafe {102::core::pin::Pin::map_unchecked_mut(self, |me| &mut me.$field)103};104// SAFETY: The caller promises that there is no `ListArc`.105unsafe {106<$fty as $crate::list::ListArcSafe<$num>>::on_create_list_arc_from_unique(field)107};108}109unsafe fn on_drop_list_arc(&self) {110// SAFETY: The caller promises that there is no `ListArc` reference, and also111// promises that the tracking thinks there is a `ListArc` reference.112unsafe { <$fty as $crate::list::ListArcSafe<$num>>::on_drop_list_arc(&self.$field) };113}114}115unsafe impl$(<$($generics)*>)? $crate::list::TryNewListArc<$num> for $t116where117$fty: TryNewListArc<$num>,118{119fn try_new_list_arc(&self) -> bool {120<$fty as $crate::list::TryNewListArc<$num>>::try_new_list_arc(&self.$field)121}122}123$crate::list::impl_list_arc_safe! { $($rest)* }124};125126() => {};127}128pub use impl_list_arc_safe;129130/// A wrapper around [`Arc`] that's guaranteed unique for the given id.131///132/// The `ListArc` type can be thought of as a special reference to a refcounted object that owns the133/// permission to manipulate the `next`/`prev` pointers stored in the refcounted object. By ensuring134/// that each object has only one `ListArc` reference, the owner of that reference is assured135/// exclusive access to the `next`/`prev` pointers. When a `ListArc` is inserted into a [`List`],136/// the [`List`] takes ownership of the `ListArc` reference.137///138/// There are various strategies to ensuring that a value has only one `ListArc` reference. The139/// simplest is to convert a [`UniqueArc`] into a `ListArc`. However, the refcounted object could140/// also keep track of whether a `ListArc` exists using a boolean, which could allow for the141/// creation of new `ListArc` references from an [`Arc`] reference. Whatever strategy is used, the142/// relevant tracking is referred to as "the tracking inside `T`", and the [`ListArcSafe`] trait143/// (and its subtraits) are used to update the tracking when a `ListArc` is created or destroyed.144///145/// Note that we allow the case where the tracking inside `T` thinks that a `ListArc` exists, but146/// actually, there isn't a `ListArc`. However, we do not allow the opposite situation where a147/// `ListArc` exists, but the tracking thinks it doesn't. This is because the former can at most148/// result in us failing to create a `ListArc` when the operation could succeed, whereas the latter149/// can result in the creation of two `ListArc` references.150///151/// While this `ListArc` is unique for the given id, there still might exist normal `Arc`152/// references to the object.153///154/// # Invariants155///156/// * Each reference counted object has at most one `ListArc` for each value of `ID`.157/// * The tracking inside `T` is aware that a `ListArc` reference exists.158///159/// [`List`]: crate::list::List160#[repr(transparent)]161#[cfg_attr(CONFIG_RUSTC_HAS_COERCE_POINTEE, derive(core::marker::CoercePointee))]162pub struct ListArc<T, const ID: u64 = 0>163where164T: ListArcSafe<ID> + ?Sized,165{166arc: Arc<T>,167}168169impl<T: ListArcSafe<ID>, const ID: u64> ListArc<T, ID> {170/// Constructs a new reference counted instance of `T`.171#[inline]172pub fn new(contents: T, flags: Flags) -> Result<Self, AllocError> {173Ok(Self::from(UniqueArc::new(contents, flags)?))174}175176/// Use the given initializer to in-place initialize a `T`.177///178/// If `T: !Unpin` it will not be able to move afterwards.179// We don't implement `InPlaceInit` because `ListArc` is implicitly pinned. This is similar to180// what we do for `Arc`.181#[inline]182pub fn pin_init<E>(init: impl PinInit<T, E>, flags: Flags) -> Result<Self, E>183where184E: From<AllocError>,185{186Ok(Self::from(UniqueArc::try_pin_init(init, flags)?))187}188189/// Use the given initializer to in-place initialize a `T`.190///191/// This is equivalent to [`ListArc<T>::pin_init`], since a [`ListArc`] is always pinned.192#[inline]193pub fn init<E>(init: impl Init<T, E>, flags: Flags) -> Result<Self, E>194where195E: From<AllocError>,196{197Ok(Self::from(UniqueArc::try_init(init, flags)?))198}199}200201impl<T, const ID: u64> From<UniqueArc<T>> for ListArc<T, ID>202where203T: ListArcSafe<ID> + ?Sized,204{205/// Convert a [`UniqueArc`] into a [`ListArc`].206#[inline]207fn from(unique: UniqueArc<T>) -> Self {208Self::from(Pin::from(unique))209}210}211212impl<T, const ID: u64> From<Pin<UniqueArc<T>>> for ListArc<T, ID>213where214T: ListArcSafe<ID> + ?Sized,215{216/// Convert a pinned [`UniqueArc`] into a [`ListArc`].217#[inline]218fn from(mut unique: Pin<UniqueArc<T>>) -> Self {219// SAFETY: We have a `UniqueArc`, so there is no `ListArc`.220unsafe { T::on_create_list_arc_from_unique(unique.as_mut()) };221let arc = Arc::from(unique);222// SAFETY: We just called `on_create_list_arc_from_unique` on an arc without a `ListArc`,223// so we can create a `ListArc`.224unsafe { Self::transmute_from_arc(arc) }225}226}227228impl<T, const ID: u64> ListArc<T, ID>229where230T: ListArcSafe<ID> + ?Sized,231{232/// Creates two `ListArc`s from a [`UniqueArc`].233///234/// The two ids must be different.235#[inline]236pub fn pair_from_unique<const ID2: u64>(unique: UniqueArc<T>) -> (Self, ListArc<T, ID2>)237where238T: ListArcSafe<ID2>,239{240Self::pair_from_pin_unique(Pin::from(unique))241}242243/// Creates two `ListArc`s from a pinned [`UniqueArc`].244///245/// The two ids must be different.246#[inline]247pub fn pair_from_pin_unique<const ID2: u64>(248mut unique: Pin<UniqueArc<T>>,249) -> (Self, ListArc<T, ID2>)250where251T: ListArcSafe<ID2>,252{253build_assert!(ID != ID2);254255// SAFETY: We have a `UniqueArc`, so there is no `ListArc`.256unsafe { <T as ListArcSafe<ID>>::on_create_list_arc_from_unique(unique.as_mut()) };257// SAFETY: We have a `UniqueArc`, so there is no `ListArc`.258unsafe { <T as ListArcSafe<ID2>>::on_create_list_arc_from_unique(unique.as_mut()) };259260let arc1 = Arc::from(unique);261let arc2 = Arc::clone(&arc1);262263// SAFETY: We just called `on_create_list_arc_from_unique` on an arc without a `ListArc`264// for both IDs (which are different), so we can create two `ListArc`s.265unsafe {266(267Self::transmute_from_arc(arc1),268ListArc::transmute_from_arc(arc2),269)270}271}272273/// Try to create a new `ListArc`.274///275/// This fails if this value already has a `ListArc`.276pub fn try_from_arc(arc: Arc<T>) -> Result<Self, Arc<T>>277where278T: TryNewListArc<ID>,279{280if arc.try_new_list_arc() {281// SAFETY: The `try_new_list_arc` method returned true, so we made the tracking think282// that a `ListArc` exists. This lets us create a `ListArc`.283Ok(unsafe { Self::transmute_from_arc(arc) })284} else {285Err(arc)286}287}288289/// Try to create a new `ListArc`.290///291/// This fails if this value already has a `ListArc`.292pub fn try_from_arc_borrow(arc: ArcBorrow<'_, T>) -> Option<Self>293where294T: TryNewListArc<ID>,295{296if arc.try_new_list_arc() {297// SAFETY: The `try_new_list_arc` method returned true, so we made the tracking think298// that a `ListArc` exists. This lets us create a `ListArc`.299Some(unsafe { Self::transmute_from_arc(Arc::from(arc)) })300} else {301None302}303}304305/// Try to create a new `ListArc`.306///307/// If it's not possible to create a new `ListArc`, then the `Arc` is dropped. This will never308/// run the destructor of the value.309pub fn try_from_arc_or_drop(arc: Arc<T>) -> Option<Self>310where311T: TryNewListArc<ID>,312{313match Self::try_from_arc(arc) {314Ok(list_arc) => Some(list_arc),315Err(arc) => Arc::into_unique_or_drop(arc).map(Self::from),316}317}318319/// Transmutes an [`Arc`] into a `ListArc` without updating the tracking inside `T`.320///321/// # Safety322///323/// * The value must not already have a `ListArc` reference.324/// * The tracking inside `T` must think that there is a `ListArc` reference.325#[inline]326unsafe fn transmute_from_arc(arc: Arc<T>) -> Self {327// INVARIANT: By the safety requirements, the invariants on `ListArc` are satisfied.328Self { arc }329}330331/// Transmutes a `ListArc` into an [`Arc`] without updating the tracking inside `T`.332///333/// After this call, the tracking inside `T` will still think that there is a `ListArc`334/// reference.335#[inline]336fn transmute_to_arc(self) -> Arc<T> {337// Use a transmute to skip destructor.338//339// SAFETY: ListArc is repr(transparent).340unsafe { core::mem::transmute(self) }341}342343/// Convert ownership of this `ListArc` into a raw pointer.344///345/// The returned pointer is indistinguishable from pointers returned by [`Arc::into_raw`]. The346/// tracking inside `T` will still think that a `ListArc` exists after this call.347#[inline]348pub fn into_raw(self) -> *const T {349Arc::into_raw(Self::transmute_to_arc(self))350}351352/// Take ownership of the `ListArc` from a raw pointer.353///354/// # Safety355///356/// * `ptr` must satisfy the safety requirements of [`Arc::from_raw`].357/// * The value must not already have a `ListArc` reference.358/// * The tracking inside `T` must think that there is a `ListArc` reference.359#[inline]360pub unsafe fn from_raw(ptr: *const T) -> Self {361// SAFETY: The pointer satisfies the safety requirements for `Arc::from_raw`.362let arc = unsafe { Arc::from_raw(ptr) };363// SAFETY: The value doesn't already have a `ListArc` reference, but the tracking thinks it364// does.365unsafe { Self::transmute_from_arc(arc) }366}367368/// Converts the `ListArc` into an [`Arc`].369#[inline]370pub fn into_arc(self) -> Arc<T> {371let arc = Self::transmute_to_arc(self);372// SAFETY: There is no longer a `ListArc`, but the tracking thinks there is.373unsafe { T::on_drop_list_arc(&arc) };374arc375}376377/// Clone a `ListArc` into an [`Arc`].378#[inline]379pub fn clone_arc(&self) -> Arc<T> {380self.arc.clone()381}382383/// Returns a reference to an [`Arc`] from the given [`ListArc`].384///385/// This is useful when the argument of a function call is an [`&Arc`] (e.g., in a method386/// receiver), but we have a [`ListArc`] instead.387///388/// [`&Arc`]: Arc389#[inline]390pub fn as_arc(&self) -> &Arc<T> {391&self.arc392}393394/// Returns an [`ArcBorrow`] from the given [`ListArc`].395///396/// This is useful when the argument of a function call is an [`ArcBorrow`] (e.g., in a method397/// receiver), but we have an [`Arc`] instead. Getting an [`ArcBorrow`] is free when optimised.398#[inline]399pub fn as_arc_borrow(&self) -> ArcBorrow<'_, T> {400self.arc.as_arc_borrow()401}402403/// Compare whether two [`ListArc`] pointers reference the same underlying object.404#[inline]405pub fn ptr_eq(this: &Self, other: &Self) -> bool {406Arc::ptr_eq(&this.arc, &other.arc)407}408}409410impl<T, const ID: u64> Deref for ListArc<T, ID>411where412T: ListArcSafe<ID> + ?Sized,413{414type Target = T;415416#[inline]417fn deref(&self) -> &Self::Target {418self.arc.deref()419}420}421422impl<T, const ID: u64> Drop for ListArc<T, ID>423where424T: ListArcSafe<ID> + ?Sized,425{426#[inline]427fn drop(&mut self) {428// SAFETY: There is no longer a `ListArc`, but the tracking thinks there is by the type429// invariants on `Self`.430unsafe { T::on_drop_list_arc(&self.arc) };431}432}433434impl<T, const ID: u64> AsRef<Arc<T>> for ListArc<T, ID>435where436T: ListArcSafe<ID> + ?Sized,437{438#[inline]439fn as_ref(&self) -> &Arc<T> {440self.as_arc()441}442}443444// This is to allow coercion from `ListArc<T>` to `ListArc<U>` if `T` can be converted to the445// dynamically-sized type (DST) `U`.446#[cfg(not(CONFIG_RUSTC_HAS_COERCE_POINTEE))]447impl<T, U, const ID: u64> core::ops::CoerceUnsized<ListArc<U, ID>> for ListArc<T, ID>448where449T: ListArcSafe<ID> + core::marker::Unsize<U> + ?Sized,450U: ListArcSafe<ID> + ?Sized,451{452}453454// This is to allow `ListArc<U>` to be dispatched on when `ListArc<T>` can be coerced into455// `ListArc<U>`.456#[cfg(not(CONFIG_RUSTC_HAS_COERCE_POINTEE))]457impl<T, U, const ID: u64> core::ops::DispatchFromDyn<ListArc<U, ID>> for ListArc<T, ID>458where459T: ListArcSafe<ID> + core::marker::Unsize<U> + ?Sized,460U: ListArcSafe<ID> + ?Sized,461{462}463464/// A utility for tracking whether a [`ListArc`] exists using an atomic.465///466/// # Invariants467///468/// If the boolean is `false`, then there is no [`ListArc`] for this value.469#[repr(transparent)]470pub struct AtomicTracker<const ID: u64 = 0> {471inner: AtomicBool,472// This value needs to be pinned to justify the INVARIANT: comment in `AtomicTracker::new`.473_pin: PhantomPinned,474}475476impl<const ID: u64> AtomicTracker<ID> {477/// Creates a new initializer for this type.478pub fn new() -> impl PinInit<Self> {479// INVARIANT: Pin-init initializers can't be used on an existing `Arc`, so this value will480// not be constructed in an `Arc` that already has a `ListArc`.481Self {482inner: AtomicBool::new(false),483_pin: PhantomPinned,484}485}486487fn project_inner(self: Pin<&mut Self>) -> &mut AtomicBool {488// SAFETY: The `inner` field is not structurally pinned, so we may obtain a mutable489// reference to it even if we only have a pinned reference to `self`.490unsafe { &mut Pin::into_inner_unchecked(self).inner }491}492}493494impl<const ID: u64> ListArcSafe<ID> for AtomicTracker<ID> {495unsafe fn on_create_list_arc_from_unique(self: Pin<&mut Self>) {496// INVARIANT: We just created a ListArc, so the boolean should be true.497*self.project_inner().get_mut() = true;498}499500unsafe fn on_drop_list_arc(&self) {501// INVARIANT: We just dropped a ListArc, so the boolean should be false.502self.inner.store(false, Ordering::Release);503}504}505506// SAFETY: If this method returns `true`, then by the type invariant there is no `ListArc` before507// this call, so it is okay to create a new `ListArc`.508//509// The acquire ordering will synchronize with the release store from the destruction of any510// previous `ListArc`, so if there was a previous `ListArc`, then the destruction of the previous511// `ListArc` happens-before the creation of the new `ListArc`.512unsafe impl<const ID: u64> TryNewListArc<ID> for AtomicTracker<ID> {513fn try_new_list_arc(&self) -> bool {514// INVARIANT: If this method returns true, then the boolean used to be false, and is no515// longer false, so it is okay for the caller to create a new [`ListArc`].516self.inner517.compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed)518.is_ok()519}520}521522523