// SPDX-License-Identifier: GPL-2.012// Copyright (C) 2024 Google LLC.34//! A linked list implementation.56use crate::sync::ArcBorrow;7use crate::types::Opaque;8use core::iter::{DoubleEndedIterator, FusedIterator};9use core::marker::PhantomData;10use core::ptr;11use pin_init::PinInit;1213mod impl_list_item_mod;14pub use self::impl_list_item_mod::{15impl_has_list_links, impl_has_list_links_self_ptr, impl_list_item, HasListLinks, HasSelfPtr,16};1718mod arc;19pub use self::arc::{impl_list_arc_safe, AtomicTracker, ListArc, ListArcSafe, TryNewListArc};2021mod arc_field;22pub use self::arc_field::{define_list_arc_field_getter, ListArcField};2324/// A linked list.25///26/// All elements in this linked list will be [`ListArc`] references to the value. Since a value can27/// only have one `ListArc` (for each pair of prev/next pointers), this ensures that the same28/// prev/next pointers are not used for several linked lists.29///30/// # Invariants31///32/// * If the list is empty, then `first` is null. Otherwise, `first` points at the `ListLinks`33/// field of the first element in the list.34/// * All prev/next pointers in `ListLinks` fields of items in the list are valid and form a cycle.35/// * For every item in the list, the list owns the associated [`ListArc`] reference and has36/// exclusive access to the `ListLinks` field.37///38/// # Examples39///40/// Use [`ListLinks`] as the type of the intrusive field.41///42/// ```43/// use kernel::list::*;44///45/// #[pin_data]46/// struct BasicItem {47/// value: i32,48/// #[pin]49/// links: ListLinks,50/// }51///52/// impl BasicItem {53/// fn new(value: i32) -> Result<ListArc<Self>> {54/// ListArc::pin_init(try_pin_init!(Self {55/// value,56/// links <- ListLinks::new(),57/// }), GFP_KERNEL)58/// }59/// }60///61/// impl_list_arc_safe! {62/// impl ListArcSafe<0> for BasicItem { untracked; }63/// }64/// impl_list_item! {65/// impl ListItem<0> for BasicItem { using ListLinks { self.links }; }66/// }67///68/// // Create a new empty list.69/// let mut list = List::new();70/// {71/// assert!(list.is_empty());72/// }73///74/// // Insert 3 elements using `push_back()`.75/// list.push_back(BasicItem::new(15)?);76/// list.push_back(BasicItem::new(10)?);77/// list.push_back(BasicItem::new(30)?);78///79/// // Iterate over the list to verify the nodes were inserted correctly.80/// // [15, 10, 30]81/// {82/// let mut iter = list.iter();83/// assert_eq!(iter.next().ok_or(EINVAL)?.value, 15);84/// assert_eq!(iter.next().ok_or(EINVAL)?.value, 10);85/// assert_eq!(iter.next().ok_or(EINVAL)?.value, 30);86/// assert!(iter.next().is_none());87///88/// // Verify the length of the list.89/// assert_eq!(list.iter().count(), 3);90/// }91///92/// // Pop the items from the list using `pop_back()` and verify the content.93/// {94/// assert_eq!(list.pop_back().ok_or(EINVAL)?.value, 30);95/// assert_eq!(list.pop_back().ok_or(EINVAL)?.value, 10);96/// assert_eq!(list.pop_back().ok_or(EINVAL)?.value, 15);97/// }98///99/// // Insert 3 elements using `push_front()`.100/// list.push_front(BasicItem::new(15)?);101/// list.push_front(BasicItem::new(10)?);102/// list.push_front(BasicItem::new(30)?);103///104/// // Iterate over the list to verify the nodes were inserted correctly.105/// // [30, 10, 15]106/// {107/// let mut iter = list.iter();108/// assert_eq!(iter.next().ok_or(EINVAL)?.value, 30);109/// assert_eq!(iter.next().ok_or(EINVAL)?.value, 10);110/// assert_eq!(iter.next().ok_or(EINVAL)?.value, 15);111/// assert!(iter.next().is_none());112///113/// // Verify the length of the list.114/// assert_eq!(list.iter().count(), 3);115/// }116///117/// // Pop the items from the list using `pop_front()` and verify the content.118/// {119/// assert_eq!(list.pop_front().ok_or(EINVAL)?.value, 30);120/// assert_eq!(list.pop_front().ok_or(EINVAL)?.value, 10);121/// }122///123/// // Push `list2` to `list` through `push_all_back()`.124/// // list: [15]125/// // list2: [25, 35]126/// {127/// let mut list2 = List::new();128/// list2.push_back(BasicItem::new(25)?);129/// list2.push_back(BasicItem::new(35)?);130///131/// list.push_all_back(&mut list2);132///133/// // list: [15, 25, 35]134/// // list2: []135/// let mut iter = list.iter();136/// assert_eq!(iter.next().ok_or(EINVAL)?.value, 15);137/// assert_eq!(iter.next().ok_or(EINVAL)?.value, 25);138/// assert_eq!(iter.next().ok_or(EINVAL)?.value, 35);139/// assert!(iter.next().is_none());140/// assert!(list2.is_empty());141/// }142/// # Result::<(), Error>::Ok(())143/// ```144///145/// Use [`ListLinksSelfPtr`] as the type of the intrusive field. This allows a list of trait object146/// type.147///148/// ```149/// use kernel::list::*;150///151/// trait Foo {152/// fn foo(&self) -> (&'static str, i32);153/// }154///155/// #[pin_data]156/// struct DTWrap<T: ?Sized> {157/// #[pin]158/// links: ListLinksSelfPtr<DTWrap<dyn Foo>>,159/// value: T,160/// }161///162/// impl<T> DTWrap<T> {163/// fn new(value: T) -> Result<ListArc<Self>> {164/// ListArc::pin_init(try_pin_init!(Self {165/// value,166/// links <- ListLinksSelfPtr::new(),167/// }), GFP_KERNEL)168/// }169/// }170///171/// impl_list_arc_safe! {172/// impl{T: ?Sized} ListArcSafe<0> for DTWrap<T> { untracked; }173/// }174/// impl_list_item! {175/// impl ListItem<0> for DTWrap<dyn Foo> { using ListLinksSelfPtr { self.links }; }176/// }177///178/// // Create a new empty list.179/// let mut list = List::<DTWrap<dyn Foo>>::new();180/// {181/// assert!(list.is_empty());182/// }183///184/// struct A(i32);185/// // `A` returns the inner value for `foo`.186/// impl Foo for A { fn foo(&self) -> (&'static str, i32) { ("a", self.0) } }187///188/// struct B;189/// // `B` always returns 42.190/// impl Foo for B { fn foo(&self) -> (&'static str, i32) { ("b", 42) } }191///192/// // Insert 3 element using `push_back()`.193/// list.push_back(DTWrap::new(A(15))?);194/// list.push_back(DTWrap::new(A(32))?);195/// list.push_back(DTWrap::new(B)?);196///197/// // Iterate over the list to verify the nodes were inserted correctly.198/// // [A(15), A(32), B]199/// {200/// let mut iter = list.iter();201/// assert_eq!(iter.next().ok_or(EINVAL)?.value.foo(), ("a", 15));202/// assert_eq!(iter.next().ok_or(EINVAL)?.value.foo(), ("a", 32));203/// assert_eq!(iter.next().ok_or(EINVAL)?.value.foo(), ("b", 42));204/// assert!(iter.next().is_none());205///206/// // Verify the length of the list.207/// assert_eq!(list.iter().count(), 3);208/// }209///210/// // Pop the items from the list using `pop_back()` and verify the content.211/// {212/// assert_eq!(list.pop_back().ok_or(EINVAL)?.value.foo(), ("b", 42));213/// assert_eq!(list.pop_back().ok_or(EINVAL)?.value.foo(), ("a", 32));214/// assert_eq!(list.pop_back().ok_or(EINVAL)?.value.foo(), ("a", 15));215/// }216///217/// // Insert 3 elements using `push_front()`.218/// list.push_front(DTWrap::new(A(15))?);219/// list.push_front(DTWrap::new(A(32))?);220/// list.push_front(DTWrap::new(B)?);221///222/// // Iterate over the list to verify the nodes were inserted correctly.223/// // [B, A(32), A(15)]224/// {225/// let mut iter = list.iter();226/// assert_eq!(iter.next().ok_or(EINVAL)?.value.foo(), ("b", 42));227/// assert_eq!(iter.next().ok_or(EINVAL)?.value.foo(), ("a", 32));228/// assert_eq!(iter.next().ok_or(EINVAL)?.value.foo(), ("a", 15));229/// assert!(iter.next().is_none());230///231/// // Verify the length of the list.232/// assert_eq!(list.iter().count(), 3);233/// }234///235/// // Pop the items from the list using `pop_front()` and verify the content.236/// {237/// assert_eq!(list.pop_back().ok_or(EINVAL)?.value.foo(), ("a", 15));238/// assert_eq!(list.pop_back().ok_or(EINVAL)?.value.foo(), ("a", 32));239/// }240///241/// // Push `list2` to `list` through `push_all_back()`.242/// // list: [B]243/// // list2: [B, A(25)]244/// {245/// let mut list2 = List::<DTWrap<dyn Foo>>::new();246/// list2.push_back(DTWrap::new(B)?);247/// list2.push_back(DTWrap::new(A(25))?);248///249/// list.push_all_back(&mut list2);250///251/// // list: [B, B, A(25)]252/// // list2: []253/// let mut iter = list.iter();254/// assert_eq!(iter.next().ok_or(EINVAL)?.value.foo(), ("b", 42));255/// assert_eq!(iter.next().ok_or(EINVAL)?.value.foo(), ("b", 42));256/// assert_eq!(iter.next().ok_or(EINVAL)?.value.foo(), ("a", 25));257/// assert!(iter.next().is_none());258/// assert!(list2.is_empty());259/// }260/// # Result::<(), Error>::Ok(())261/// ```262pub struct List<T: ?Sized + ListItem<ID>, const ID: u64 = 0> {263first: *mut ListLinksFields,264_ty: PhantomData<ListArc<T, ID>>,265}266267// SAFETY: This is a container of `ListArc<T, ID>`, and access to the container allows the same268// type of access to the `ListArc<T, ID>` elements.269unsafe impl<T, const ID: u64> Send for List<T, ID>270where271ListArc<T, ID>: Send,272T: ?Sized + ListItem<ID>,273{274}275// SAFETY: This is a container of `ListArc<T, ID>`, and access to the container allows the same276// type of access to the `ListArc<T, ID>` elements.277unsafe impl<T, const ID: u64> Sync for List<T, ID>278where279ListArc<T, ID>: Sync,280T: ?Sized + ListItem<ID>,281{282}283284/// Implemented by types where a [`ListArc<Self>`] can be inserted into a [`List`].285///286/// # Safety287///288/// Implementers must ensure that they provide the guarantees documented on methods provided by289/// this trait.290///291/// [`ListArc<Self>`]: ListArc292pub unsafe trait ListItem<const ID: u64 = 0>: ListArcSafe<ID> {293/// Views the [`ListLinks`] for this value.294///295/// # Guarantees296///297/// If there is a previous call to `prepare_to_insert` and there is no call to `post_remove`298/// since the most recent such call, then this returns the same pointer as the one returned by299/// the most recent call to `prepare_to_insert`.300///301/// Otherwise, the returned pointer points at a read-only [`ListLinks`] with two null pointers.302///303/// # Safety304///305/// The provided pointer must point at a valid value. (It need not be in an `Arc`.)306unsafe fn view_links(me: *const Self) -> *mut ListLinks<ID>;307308/// View the full value given its [`ListLinks`] field.309///310/// Can only be used when the value is in a list.311///312/// # Guarantees313///314/// * Returns the same pointer as the one passed to the most recent call to `prepare_to_insert`.315/// * The returned pointer is valid until the next call to `post_remove`.316///317/// # Safety318///319/// * The provided pointer must originate from the most recent call to `prepare_to_insert`, or320/// from a call to `view_links` that happened after the most recent call to321/// `prepare_to_insert`.322/// * Since the most recent call to `prepare_to_insert`, the `post_remove` method must not have323/// been called.324unsafe fn view_value(me: *mut ListLinks<ID>) -> *const Self;325326/// This is called when an item is inserted into a [`List`].327///328/// # Guarantees329///330/// The caller is granted exclusive access to the returned [`ListLinks`] until `post_remove` is331/// called.332///333/// # Safety334///335/// * The provided pointer must point at a valid value in an [`Arc`].336/// * Calls to `prepare_to_insert` and `post_remove` on the same value must alternate.337/// * The caller must own the [`ListArc`] for this value.338/// * The caller must not give up ownership of the [`ListArc`] unless `post_remove` has been339/// called after this call to `prepare_to_insert`.340///341/// [`Arc`]: crate::sync::Arc342unsafe fn prepare_to_insert(me: *const Self) -> *mut ListLinks<ID>;343344/// This undoes a previous call to `prepare_to_insert`.345///346/// # Guarantees347///348/// The returned pointer is the pointer that was originally passed to `prepare_to_insert`.349///350/// # Safety351///352/// The provided pointer must be the pointer returned by the most recent call to353/// `prepare_to_insert`.354unsafe fn post_remove(me: *mut ListLinks<ID>) -> *const Self;355}356357#[repr(C)]358#[derive(Copy, Clone)]359struct ListLinksFields {360next: *mut ListLinksFields,361prev: *mut ListLinksFields,362}363364/// The prev/next pointers for an item in a linked list.365///366/// # Invariants367///368/// The fields are null if and only if this item is not in a list.369#[repr(transparent)]370pub struct ListLinks<const ID: u64 = 0> {371// This type is `!Unpin` for aliasing reasons as the pointers are part of an intrusive linked372// list.373inner: Opaque<ListLinksFields>,374}375376// SAFETY: The only way to access/modify the pointers inside of `ListLinks<ID>` is via holding the377// associated `ListArc<T, ID>`. Since that type correctly implements `Send`, it is impossible to378// move this an instance of this type to a different thread if the pointees are `!Send`.379unsafe impl<const ID: u64> Send for ListLinks<ID> {}380// SAFETY: The type is opaque so immutable references to a ListLinks are useless. Therefore, it's381// okay to have immutable access to a ListLinks from several threads at once.382unsafe impl<const ID: u64> Sync for ListLinks<ID> {}383384impl<const ID: u64> ListLinks<ID> {385/// Creates a new initializer for this type.386pub fn new() -> impl PinInit<Self> {387// INVARIANT: Pin-init initializers can't be used on an existing `Arc`, so this value will388// not be constructed in an `Arc` that already has a `ListArc`.389ListLinks {390inner: Opaque::new(ListLinksFields {391prev: ptr::null_mut(),392next: ptr::null_mut(),393}),394}395}396397/// # Safety398///399/// `me` must be dereferenceable.400#[inline]401unsafe fn fields(me: *mut Self) -> *mut ListLinksFields {402// SAFETY: The caller promises that the pointer is valid.403unsafe { Opaque::cast_into(ptr::addr_of!((*me).inner)) }404}405406/// # Safety407///408/// `me` must be dereferenceable.409#[inline]410unsafe fn from_fields(me: *mut ListLinksFields) -> *mut Self {411me.cast()412}413}414415/// Similar to [`ListLinks`], but also contains a pointer to the full value.416///417/// This type can be used instead of [`ListLinks`] to support lists with trait objects.418#[repr(C)]419pub struct ListLinksSelfPtr<T: ?Sized, const ID: u64 = 0> {420/// The `ListLinks` field inside this value.421///422/// This is public so that it can be used with `impl_has_list_links!`.423pub inner: ListLinks<ID>,424// UnsafeCell is not enough here because we use `Opaque::uninit` as a dummy value, and425// `ptr::null()` doesn't work for `T: ?Sized`.426self_ptr: Opaque<*const T>,427}428429// SAFETY: The fields of a ListLinksSelfPtr can be moved across thread boundaries.430unsafe impl<T: ?Sized + Send, const ID: u64> Send for ListLinksSelfPtr<T, ID> {}431// SAFETY: The type is opaque so immutable references to a ListLinksSelfPtr are useless. Therefore,432// it's okay to have immutable access to a ListLinks from several threads at once.433//434// Note that `inner` being a public field does not prevent this type from being opaque, since435// `inner` is a opaque type.436unsafe impl<T: ?Sized + Sync, const ID: u64> Sync for ListLinksSelfPtr<T, ID> {}437438impl<T: ?Sized, const ID: u64> ListLinksSelfPtr<T, ID> {439/// Creates a new initializer for this type.440pub fn new() -> impl PinInit<Self> {441// INVARIANT: Pin-init initializers can't be used on an existing `Arc`, so this value will442// not be constructed in an `Arc` that already has a `ListArc`.443Self {444inner: ListLinks {445inner: Opaque::new(ListLinksFields {446prev: ptr::null_mut(),447next: ptr::null_mut(),448}),449},450self_ptr: Opaque::uninit(),451}452}453454/// Returns a pointer to the self pointer.455///456/// # Safety457///458/// The provided pointer must point at a valid struct of type `Self`.459pub unsafe fn raw_get_self_ptr(me: *const Self) -> *const Opaque<*const T> {460// SAFETY: The caller promises that the pointer is valid.461unsafe { ptr::addr_of!((*me).self_ptr) }462}463}464465impl<T: ?Sized + ListItem<ID>, const ID: u64> List<T, ID> {466/// Creates a new empty list.467pub const fn new() -> Self {468Self {469first: ptr::null_mut(),470_ty: PhantomData,471}472}473474/// Returns whether this list is empty.475pub fn is_empty(&self) -> bool {476self.first.is_null()477}478479/// Inserts `item` before `next` in the cycle.480///481/// Returns a pointer to the newly inserted element. Never changes `self.first` unless the list482/// is empty.483///484/// # Safety485///486/// * `next` must be an element in this list or null.487/// * if `next` is null, then the list must be empty.488unsafe fn insert_inner(489&mut self,490item: ListArc<T, ID>,491next: *mut ListLinksFields,492) -> *mut ListLinksFields {493let raw_item = ListArc::into_raw(item);494// SAFETY:495// * We just got `raw_item` from a `ListArc`, so it's in an `Arc`.496// * Since we have ownership of the `ListArc`, `post_remove` must have been called after497// the most recent call to `prepare_to_insert`, if any.498// * We own the `ListArc`.499// * Removing items from this list is always done using `remove_internal_inner`, which500// calls `post_remove` before giving up ownership.501let list_links = unsafe { T::prepare_to_insert(raw_item) };502// SAFETY: We have not yet called `post_remove`, so `list_links` is still valid.503let item = unsafe { ListLinks::fields(list_links) };504505// Check if the list is empty.506if next.is_null() {507// SAFETY: The caller just gave us ownership of these fields.508// INVARIANT: A linked list with one item should be cyclic.509unsafe {510(*item).next = item;511(*item).prev = item;512}513self.first = item;514} else {515// SAFETY: By the type invariant, this pointer is valid or null. We just checked that516// it's not null, so it must be valid.517let prev = unsafe { (*next).prev };518// SAFETY: Pointers in a linked list are never dangling, and the caller just gave us519// ownership of the fields on `item`.520// INVARIANT: This correctly inserts `item` between `prev` and `next`.521unsafe {522(*item).next = next;523(*item).prev = prev;524(*prev).next = item;525(*next).prev = item;526}527}528529item530}531532/// Add the provided item to the back of the list.533pub fn push_back(&mut self, item: ListArc<T, ID>) {534// SAFETY:535// * `self.first` is null or in the list.536// * `self.first` is only null if the list is empty.537unsafe { self.insert_inner(item, self.first) };538}539540/// Add the provided item to the front of the list.541pub fn push_front(&mut self, item: ListArc<T, ID>) {542// SAFETY:543// * `self.first` is null or in the list.544// * `self.first` is only null if the list is empty.545let new_elem = unsafe { self.insert_inner(item, self.first) };546547// INVARIANT: `new_elem` is in the list because we just inserted it.548self.first = new_elem;549}550551/// Removes the last item from this list.552pub fn pop_back(&mut self) -> Option<ListArc<T, ID>> {553if self.is_empty() {554return None;555}556557// SAFETY: We just checked that the list is not empty.558let last = unsafe { (*self.first).prev };559// SAFETY: The last item of this list is in this list.560Some(unsafe { self.remove_internal(last) })561}562563/// Removes the first item from this list.564pub fn pop_front(&mut self) -> Option<ListArc<T, ID>> {565if self.is_empty() {566return None;567}568569// SAFETY: The first item of this list is in this list.570Some(unsafe { self.remove_internal(self.first) })571}572573/// Removes the provided item from this list and returns it.574///575/// This returns `None` if the item is not in the list. (Note that by the safety requirements,576/// this means that the item is not in any list.)577///578/// # Safety579///580/// `item` must not be in a different linked list (with the same id).581pub unsafe fn remove(&mut self, item: &T) -> Option<ListArc<T, ID>> {582// SAFETY: TODO.583let mut item = unsafe { ListLinks::fields(T::view_links(item)) };584// SAFETY: The user provided a reference, and reference are never dangling.585//586// As for why this is not a data race, there are two cases:587//588// * If `item` is not in any list, then these fields are read-only and null.589// * If `item` is in this list, then we have exclusive access to these fields since we590// have a mutable reference to the list.591//592// In either case, there's no race.593let ListLinksFields { next, prev } = unsafe { *item };594595debug_assert_eq!(next.is_null(), prev.is_null());596if !next.is_null() {597// This is really a no-op, but this ensures that `item` is a raw pointer that was598// obtained without going through a pointer->reference->pointer conversion roundtrip.599// This ensures that the list is valid under the more restrictive strict provenance600// ruleset.601//602// SAFETY: We just checked that `next` is not null, and it's not dangling by the603// list invariants.604unsafe {605debug_assert_eq!(item, (*next).prev);606item = (*next).prev;607}608609// SAFETY: We just checked that `item` is in a list, so the caller guarantees that it610// is in this list. The pointers are in the right order.611Some(unsafe { self.remove_internal_inner(item, next, prev) })612} else {613None614}615}616617/// Removes the provided item from the list.618///619/// # Safety620///621/// `item` must point at an item in this list.622unsafe fn remove_internal(&mut self, item: *mut ListLinksFields) -> ListArc<T, ID> {623// SAFETY: The caller promises that this pointer is not dangling, and there's no data race624// since we have a mutable reference to the list containing `item`.625let ListLinksFields { next, prev } = unsafe { *item };626// SAFETY: The pointers are ok and in the right order.627unsafe { self.remove_internal_inner(item, next, prev) }628}629630/// Removes the provided item from the list.631///632/// # Safety633///634/// The `item` pointer must point at an item in this list, and we must have `(*item).next ==635/// next` and `(*item).prev == prev`.636unsafe fn remove_internal_inner(637&mut self,638item: *mut ListLinksFields,639next: *mut ListLinksFields,640prev: *mut ListLinksFields,641) -> ListArc<T, ID> {642// SAFETY: We have exclusive access to the pointers of items in the list, and the prev/next643// pointers are always valid for items in a list.644//645// INVARIANT: There are three cases:646// * If the list has at least three items, then after removing the item, `prev` and `next`647// will be next to each other.648// * If the list has two items, then the remaining item will point at itself.649// * If the list has one item, then `next == prev == item`, so these writes have no650// effect. The list remains unchanged and `item` is still in the list for now.651unsafe {652(*next).prev = prev;653(*prev).next = next;654}655// SAFETY: We have exclusive access to items in the list.656// INVARIANT: `item` is being removed, so the pointers should be null.657unsafe {658(*item).prev = ptr::null_mut();659(*item).next = ptr::null_mut();660}661// INVARIANT: There are three cases:662// * If `item` was not the first item, then `self.first` should remain unchanged.663// * If `item` was the first item and there is another item, then we just updated664// `prev->next` to `next`, which is the new first item, and setting `item->next` to null665// did not modify `prev->next`.666// * If `item` was the only item in the list, then `prev == item`, and we just set667// `item->next` to null, so this correctly sets `first` to null now that the list is668// empty.669if self.first == item {670// SAFETY: The `prev` pointer is the value that `item->prev` had when it was in this671// list, so it must be valid. There is no race since `prev` is still in the list and we672// still have exclusive access to the list.673self.first = unsafe { (*prev).next };674}675676// SAFETY: `item` used to be in the list, so it is dereferenceable by the type invariants677// of `List`.678let list_links = unsafe { ListLinks::from_fields(item) };679// SAFETY: Any pointer in the list originates from a `prepare_to_insert` call.680let raw_item = unsafe { T::post_remove(list_links) };681// SAFETY: The above call to `post_remove` guarantees that we can recreate the `ListArc`.682unsafe { ListArc::from_raw(raw_item) }683}684685/// Moves all items from `other` into `self`.686///687/// The items of `other` are added to the back of `self`, so the last item of `other` becomes688/// the last item of `self`.689pub fn push_all_back(&mut self, other: &mut List<T, ID>) {690// First, we insert the elements into `self`. At the end, we make `other` empty.691if self.is_empty() {692// INVARIANT: All of the elements in `other` become elements of `self`.693self.first = other.first;694} else if !other.is_empty() {695let other_first = other.first;696// SAFETY: The other list is not empty, so this pointer is valid.697let other_last = unsafe { (*other_first).prev };698let self_first = self.first;699// SAFETY: The self list is not empty, so this pointer is valid.700let self_last = unsafe { (*self_first).prev };701702// SAFETY: We have exclusive access to both lists, so we can update the pointers.703// INVARIANT: This correctly sets the pointers to merge both lists. We do not need to704// update `self.first` because the first element of `self` does not change.705unsafe {706(*self_first).prev = other_last;707(*other_last).next = self_first;708(*self_last).next = other_first;709(*other_first).prev = self_last;710}711}712713// INVARIANT: The other list is now empty, so update its pointer.714other.first = ptr::null_mut();715}716717/// Returns a cursor that points before the first element of the list.718pub fn cursor_front(&mut self) -> Cursor<'_, T, ID> {719// INVARIANT: `self.first` is in this list.720Cursor {721next: self.first,722list: self,723}724}725726/// Returns a cursor that points after the last element in the list.727pub fn cursor_back(&mut self) -> Cursor<'_, T, ID> {728// INVARIANT: `next` is allowed to be null.729Cursor {730next: core::ptr::null_mut(),731list: self,732}733}734735/// Creates an iterator over the list.736pub fn iter(&self) -> Iter<'_, T, ID> {737// INVARIANT: If the list is empty, both pointers are null. Otherwise, both pointers point738// at the first element of the same list.739Iter {740current: self.first,741stop: self.first,742_ty: PhantomData,743}744}745}746747impl<T: ?Sized + ListItem<ID>, const ID: u64> Default for List<T, ID> {748fn default() -> Self {749List::new()750}751}752753impl<T: ?Sized + ListItem<ID>, const ID: u64> Drop for List<T, ID> {754fn drop(&mut self) {755while let Some(item) = self.pop_front() {756drop(item);757}758}759}760761/// An iterator over a [`List`].762///763/// # Invariants764///765/// * There must be a [`List`] that is immutably borrowed for the duration of `'a`.766/// * The `current` pointer is null or points at a value in that [`List`].767/// * The `stop` pointer is equal to the `first` field of that [`List`].768#[derive(Clone)]769pub struct Iter<'a, T: ?Sized + ListItem<ID>, const ID: u64 = 0> {770current: *mut ListLinksFields,771stop: *mut ListLinksFields,772_ty: PhantomData<&'a ListArc<T, ID>>,773}774775impl<'a, T: ?Sized + ListItem<ID>, const ID: u64> Iterator for Iter<'a, T, ID> {776type Item = ArcBorrow<'a, T>;777778fn next(&mut self) -> Option<ArcBorrow<'a, T>> {779if self.current.is_null() {780return None;781}782783let current = self.current;784785// SAFETY: We just checked that `current` is not null, so it is in a list, and hence not786// dangling. There's no race because the iterator holds an immutable borrow to the list.787let next = unsafe { (*current).next };788// INVARIANT: If `current` was the last element of the list, then this updates it to null.789// Otherwise, we update it to the next element.790self.current = if next != self.stop {791next792} else {793ptr::null_mut()794};795796// SAFETY: The `current` pointer points at a value in the list.797let item = unsafe { T::view_value(ListLinks::from_fields(current)) };798// SAFETY:799// * All values in a list are stored in an `Arc`.800// * The value cannot be removed from the list for the duration of the lifetime annotated801// on the returned `ArcBorrow`, because removing it from the list would require mutable802// access to the list. However, the `ArcBorrow` is annotated with the iterator's803// lifetime, and the list is immutably borrowed for that lifetime.804// * Values in a list never have a `UniqueArc` reference.805Some(unsafe { ArcBorrow::from_raw(item) })806}807}808809/// A cursor into a [`List`].810///811/// A cursor always rests between two elements in the list. This means that a cursor has a previous812/// and next element, but no current element. It also means that it's possible to have a cursor813/// into an empty list.814///815/// # Examples816///817/// ```818/// use kernel::prelude::*;819/// use kernel::list::{List, ListArc, ListLinks};820///821/// #[pin_data]822/// struct ListItem {823/// value: u32,824/// #[pin]825/// links: ListLinks,826/// }827///828/// impl ListItem {829/// fn new(value: u32) -> Result<ListArc<Self>> {830/// ListArc::pin_init(try_pin_init!(Self {831/// value,832/// links <- ListLinks::new(),833/// }), GFP_KERNEL)834/// }835/// }836///837/// kernel::list::impl_list_arc_safe! {838/// impl ListArcSafe<0> for ListItem { untracked; }839/// }840/// kernel::list::impl_list_item! {841/// impl ListItem<0> for ListItem { using ListLinks { self.links }; }842/// }843///844/// // Use a cursor to remove the first element with the given value.845/// fn remove_first(list: &mut List<ListItem>, value: u32) -> Option<ListArc<ListItem>> {846/// let mut cursor = list.cursor_front();847/// while let Some(next) = cursor.peek_next() {848/// if next.value == value {849/// return Some(next.remove());850/// }851/// cursor.move_next();852/// }853/// None854/// }855///856/// // Use a cursor to remove the last element with the given value.857/// fn remove_last(list: &mut List<ListItem>, value: u32) -> Option<ListArc<ListItem>> {858/// let mut cursor = list.cursor_back();859/// while let Some(prev) = cursor.peek_prev() {860/// if prev.value == value {861/// return Some(prev.remove());862/// }863/// cursor.move_prev();864/// }865/// None866/// }867///868/// // Use a cursor to remove all elements with the given value. The removed elements are moved to869/// // a new list.870/// fn remove_all(list: &mut List<ListItem>, value: u32) -> List<ListItem> {871/// let mut out = List::new();872/// let mut cursor = list.cursor_front();873/// while let Some(next) = cursor.peek_next() {874/// if next.value == value {875/// out.push_back(next.remove());876/// } else {877/// cursor.move_next();878/// }879/// }880/// out881/// }882///883/// // Use a cursor to insert a value at a specific index. Returns an error if the index is out of884/// // bounds.885/// fn insert_at(list: &mut List<ListItem>, new: ListArc<ListItem>, idx: usize) -> Result {886/// let mut cursor = list.cursor_front();887/// for _ in 0..idx {888/// if !cursor.move_next() {889/// return Err(EINVAL);890/// }891/// }892/// cursor.insert_next(new);893/// Ok(())894/// }895///896/// // Merge two sorted lists into a single sorted list.897/// fn merge_sorted(list: &mut List<ListItem>, merge: List<ListItem>) {898/// let mut cursor = list.cursor_front();899/// for to_insert in merge {900/// while let Some(next) = cursor.peek_next() {901/// if to_insert.value < next.value {902/// break;903/// }904/// cursor.move_next();905/// }906/// cursor.insert_prev(to_insert);907/// }908/// }909///910/// let mut list = List::new();911/// list.push_back(ListItem::new(14)?);912/// list.push_back(ListItem::new(12)?);913/// list.push_back(ListItem::new(10)?);914/// list.push_back(ListItem::new(12)?);915/// list.push_back(ListItem::new(15)?);916/// list.push_back(ListItem::new(14)?);917/// assert_eq!(remove_all(&mut list, 12).iter().count(), 2);918/// // [14, 10, 15, 14]919/// assert!(remove_first(&mut list, 14).is_some());920/// // [10, 15, 14]921/// insert_at(&mut list, ListItem::new(12)?, 2)?;922/// // [10, 15, 12, 14]923/// assert!(remove_last(&mut list, 15).is_some());924/// // [10, 12, 14]925///926/// let mut list2 = List::new();927/// list2.push_back(ListItem::new(11)?);928/// list2.push_back(ListItem::new(13)?);929/// merge_sorted(&mut list, list2);930///931/// let mut items = list.into_iter();932/// assert_eq!(items.next().ok_or(EINVAL)?.value, 10);933/// assert_eq!(items.next().ok_or(EINVAL)?.value, 11);934/// assert_eq!(items.next().ok_or(EINVAL)?.value, 12);935/// assert_eq!(items.next().ok_or(EINVAL)?.value, 13);936/// assert_eq!(items.next().ok_or(EINVAL)?.value, 14);937/// assert!(items.next().is_none());938/// # Result::<(), Error>::Ok(())939/// ```940///941/// # Invariants942///943/// The `next` pointer is null or points a value in `list`.944pub struct Cursor<'a, T: ?Sized + ListItem<ID>, const ID: u64 = 0> {945list: &'a mut List<T, ID>,946/// Points at the element after this cursor, or null if the cursor is after the last element.947next: *mut ListLinksFields,948}949950impl<'a, T: ?Sized + ListItem<ID>, const ID: u64> Cursor<'a, T, ID> {951/// Returns a pointer to the element before the cursor.952///953/// Returns null if there is no element before the cursor.954fn prev_ptr(&self) -> *mut ListLinksFields {955let mut next = self.next;956let first = self.list.first;957if next == first {958// We are before the first element.959return core::ptr::null_mut();960}961962if next.is_null() {963// We are after the last element, so we need a pointer to the last element, which is964// the same as `(*first).prev`.965next = first;966}967968// SAFETY: `next` can't be null, because then `first` must also be null, but in that case969// we would have exited at the `next == first` check. Thus, `next` is an element in the970// list, so we can access its `prev` pointer.971unsafe { (*next).prev }972}973974/// Access the element after this cursor.975pub fn peek_next(&mut self) -> Option<CursorPeek<'_, 'a, T, true, ID>> {976if self.next.is_null() {977return None;978}979980// INVARIANT:981// * We just checked that `self.next` is non-null, so it must be in `self.list`.982// * `ptr` is equal to `self.next`.983Some(CursorPeek {984ptr: self.next,985cursor: self,986})987}988989/// Access the element before this cursor.990pub fn peek_prev(&mut self) -> Option<CursorPeek<'_, 'a, T, false, ID>> {991let prev = self.prev_ptr();992993if prev.is_null() {994return None;995}996997// INVARIANT:998// * We just checked that `prev` is non-null, so it must be in `self.list`.999// * `self.prev_ptr()` never returns `self.next`.1000Some(CursorPeek {1001ptr: prev,1002cursor: self,1003})1004}10051006/// Move the cursor one element forward.1007///1008/// If the cursor is after the last element, then this call does nothing. This call returns1009/// `true` if the cursor's position was changed.1010pub fn move_next(&mut self) -> bool {1011if self.next.is_null() {1012return false;1013}10141015// SAFETY: `self.next` is an element in the list and we borrow the list mutably, so we can1016// access the `next` field.1017let mut next = unsafe { (*self.next).next };10181019if next == self.list.first {1020next = core::ptr::null_mut();1021}10221023// INVARIANT: `next` is either null or the next element after an element in the list.1024self.next = next;1025true1026}10271028/// Move the cursor one element backwards.1029///1030/// If the cursor is before the first element, then this call does nothing. This call returns1031/// `true` if the cursor's position was changed.1032pub fn move_prev(&mut self) -> bool {1033if self.next == self.list.first {1034return false;1035}10361037// INVARIANT: `prev_ptr()` always returns a pointer that is null or in the list.1038self.next = self.prev_ptr();1039true1040}10411042/// Inserts an element where the cursor is pointing and get a pointer to the new element.1043fn insert_inner(&mut self, item: ListArc<T, ID>) -> *mut ListLinksFields {1044let ptr = if self.next.is_null() {1045self.list.first1046} else {1047self.next1048};1049// SAFETY:1050// * `ptr` is an element in the list or null.1051// * if `ptr` is null, then `self.list.first` is null so the list is empty.1052let item = unsafe { self.list.insert_inner(item, ptr) };1053if self.next == self.list.first {1054// INVARIANT: We just inserted `item`, so it's a member of list.1055self.list.first = item;1056}1057item1058}10591060/// Insert an element at this cursor's location.1061pub fn insert(mut self, item: ListArc<T, ID>) {1062// This is identical to `insert_prev`, but consumes the cursor. This is helpful because it1063// reduces confusion when the last operation on the cursor is an insertion; in that case,1064// you just want to insert the element at the cursor, and it is confusing that the call1065// involves the word prev or next.1066self.insert_inner(item);1067}10681069/// Inserts an element after this cursor.1070///1071/// After insertion, the new element will be after the cursor.1072pub fn insert_next(&mut self, item: ListArc<T, ID>) {1073self.next = self.insert_inner(item);1074}10751076/// Inserts an element before this cursor.1077///1078/// After insertion, the new element will be before the cursor.1079pub fn insert_prev(&mut self, item: ListArc<T, ID>) {1080self.insert_inner(item);1081}10821083/// Remove the next element from the list.1084pub fn remove_next(&mut self) -> Option<ListArc<T, ID>> {1085self.peek_next().map(|v| v.remove())1086}10871088/// Remove the previous element from the list.1089pub fn remove_prev(&mut self) -> Option<ListArc<T, ID>> {1090self.peek_prev().map(|v| v.remove())1091}1092}10931094/// References the element in the list next to the cursor.1095///1096/// # Invariants1097///1098/// * `ptr` is an element in `self.cursor.list`.1099/// * `ISNEXT == (self.ptr == self.cursor.next)`.1100pub struct CursorPeek<'a, 'b, T: ?Sized + ListItem<ID>, const ISNEXT: bool, const ID: u64> {1101cursor: &'a mut Cursor<'b, T, ID>,1102ptr: *mut ListLinksFields,1103}11041105impl<'a, 'b, T: ?Sized + ListItem<ID>, const ISNEXT: bool, const ID: u64>1106CursorPeek<'a, 'b, T, ISNEXT, ID>1107{1108/// Remove the element from the list.1109pub fn remove(self) -> ListArc<T, ID> {1110if ISNEXT {1111self.cursor.move_next();1112}11131114// INVARIANT: `self.ptr` is not equal to `self.cursor.next` due to the above `move_next`1115// call.1116// SAFETY: By the type invariants of `Self`, `next` is not null, so `next` is an element of1117// `self.cursor.list` by the type invariants of `Cursor`.1118unsafe { self.cursor.list.remove_internal(self.ptr) }1119}11201121/// Access this value as an [`ArcBorrow`].1122pub fn arc(&self) -> ArcBorrow<'_, T> {1123// SAFETY: `self.ptr` points at an element in `self.cursor.list`.1124let me = unsafe { T::view_value(ListLinks::from_fields(self.ptr)) };1125// SAFETY:1126// * All values in a list are stored in an `Arc`.1127// * The value cannot be removed from the list for the duration of the lifetime annotated1128// on the returned `ArcBorrow`, because removing it from the list would require mutable1129// access to the `CursorPeek`, the `Cursor` or the `List`. However, the `ArcBorrow` holds1130// an immutable borrow on the `CursorPeek`, which in turn holds a mutable borrow on the1131// `Cursor`, which in turn holds a mutable borrow on the `List`, so any such mutable1132// access requires first releasing the immutable borrow on the `CursorPeek`.1133// * Values in a list never have a `UniqueArc` reference, because the list has a `ListArc`1134// reference, and `UniqueArc` references must be unique.1135unsafe { ArcBorrow::from_raw(me) }1136}1137}11381139impl<'a, 'b, T: ?Sized + ListItem<ID>, const ISNEXT: bool, const ID: u64> core::ops::Deref1140for CursorPeek<'a, 'b, T, ISNEXT, ID>1141{1142// If you change the `ptr` field to have type `ArcBorrow<'a, T>`, it might seem like you could1143// get rid of the `CursorPeek::arc` method and change the deref target to `ArcBorrow<'a, T>`.1144// However, that doesn't work because 'a is too long. You could obtain an `ArcBorrow<'a, T>`1145// and then call `CursorPeek::remove` without giving up the `ArcBorrow<'a, T>`, which would be1146// unsound.1147type Target = T;11481149fn deref(&self) -> &T {1150// SAFETY: `self.ptr` points at an element in `self.cursor.list`.1151let me = unsafe { T::view_value(ListLinks::from_fields(self.ptr)) };11521153// SAFETY: The value cannot be removed from the list for the duration of the lifetime1154// annotated on the returned `&T`, because removing it from the list would require mutable1155// access to the `CursorPeek`, the `Cursor` or the `List`. However, the `&T` holds an1156// immutable borrow on the `CursorPeek`, which in turn holds a mutable borrow on the1157// `Cursor`, which in turn holds a mutable borrow on the `List`, so any such mutable access1158// requires first releasing the immutable borrow on the `CursorPeek`.1159unsafe { &*me }1160}1161}11621163impl<'a, T: ?Sized + ListItem<ID>, const ID: u64> FusedIterator for Iter<'a, T, ID> {}11641165impl<'a, T: ?Sized + ListItem<ID>, const ID: u64> IntoIterator for &'a List<T, ID> {1166type IntoIter = Iter<'a, T, ID>;1167type Item = ArcBorrow<'a, T>;11681169fn into_iter(self) -> Iter<'a, T, ID> {1170self.iter()1171}1172}11731174/// An owning iterator into a [`List`].1175pub struct IntoIter<T: ?Sized + ListItem<ID>, const ID: u64 = 0> {1176list: List<T, ID>,1177}11781179impl<T: ?Sized + ListItem<ID>, const ID: u64> Iterator for IntoIter<T, ID> {1180type Item = ListArc<T, ID>;11811182fn next(&mut self) -> Option<ListArc<T, ID>> {1183self.list.pop_front()1184}1185}11861187impl<T: ?Sized + ListItem<ID>, const ID: u64> FusedIterator for IntoIter<T, ID> {}11881189impl<T: ?Sized + ListItem<ID>, const ID: u64> DoubleEndedIterator for IntoIter<T, ID> {1190fn next_back(&mut self) -> Option<ListArc<T, ID>> {1191self.list.pop_back()1192}1193}11941195impl<T: ?Sized + ListItem<ID>, const ID: u64> IntoIterator for List<T, ID> {1196type IntoIter = IntoIter<T, ID>;1197type Item = ListArc<T, ID>;11981199fn into_iter(self) -> IntoIter<T, ID> {1200IntoIter { list: self }1201}1202}120312041205