// 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/// When using this method, be careful with using `mem::take` on the same list as that may579/// result in violating the safety requirements of this method.580///581/// # Safety582///583/// `item` must not be in a different linked list (with the same id).584pub unsafe fn remove(&mut self, item: &T) -> Option<ListArc<T, ID>> {585// SAFETY: TODO.586let mut item = unsafe { ListLinks::fields(T::view_links(item)) };587// SAFETY: The user provided a reference, and reference are never dangling.588//589// As for why this is not a data race, there are two cases:590//591// * If `item` is not in any list, then these fields are read-only and null.592// * If `item` is in this list, then we have exclusive access to these fields since we593// have a mutable reference to the list.594//595// In either case, there's no race.596let ListLinksFields { next, prev } = unsafe { *item };597598debug_assert_eq!(next.is_null(), prev.is_null());599if !next.is_null() {600// This is really a no-op, but this ensures that `item` is a raw pointer that was601// obtained without going through a pointer->reference->pointer conversion roundtrip.602// This ensures that the list is valid under the more restrictive strict provenance603// ruleset.604//605// SAFETY: We just checked that `next` is not null, and it's not dangling by the606// list invariants.607unsafe {608debug_assert_eq!(item, (*next).prev);609item = (*next).prev;610}611612// SAFETY: We just checked that `item` is in a list, so the caller guarantees that it613// is in this list. The pointers are in the right order.614Some(unsafe { self.remove_internal_inner(item, next, prev) })615} else {616None617}618}619620/// Removes the provided item from the list.621///622/// # Safety623///624/// `item` must point at an item in this list.625unsafe fn remove_internal(&mut self, item: *mut ListLinksFields) -> ListArc<T, ID> {626// SAFETY: The caller promises that this pointer is not dangling, and there's no data race627// since we have a mutable reference to the list containing `item`.628let ListLinksFields { next, prev } = unsafe { *item };629// SAFETY: The pointers are ok and in the right order.630unsafe { self.remove_internal_inner(item, next, prev) }631}632633/// Removes the provided item from the list.634///635/// # Safety636///637/// The `item` pointer must point at an item in this list, and we must have `(*item).next ==638/// next` and `(*item).prev == prev`.639unsafe fn remove_internal_inner(640&mut self,641item: *mut ListLinksFields,642next: *mut ListLinksFields,643prev: *mut ListLinksFields,644) -> ListArc<T, ID> {645// SAFETY: We have exclusive access to the pointers of items in the list, and the prev/next646// pointers are always valid for items in a list.647//648// INVARIANT: There are three cases:649// * If the list has at least three items, then after removing the item, `prev` and `next`650// will be next to each other.651// * If the list has two items, then the remaining item will point at itself.652// * If the list has one item, then `next == prev == item`, so these writes have no653// effect. The list remains unchanged and `item` is still in the list for now.654unsafe {655(*next).prev = prev;656(*prev).next = next;657}658// SAFETY: We have exclusive access to items in the list.659// INVARIANT: `item` is being removed, so the pointers should be null.660unsafe {661(*item).prev = ptr::null_mut();662(*item).next = ptr::null_mut();663}664// INVARIANT: There are three cases:665// * If `item` was not the first item, then `self.first` should remain unchanged.666// * If `item` was the first item and there is another item, then we just updated667// `prev->next` to `next`, which is the new first item, and setting `item->next` to null668// did not modify `prev->next`.669// * If `item` was the only item in the list, then `prev == item`, and we just set670// `item->next` to null, so this correctly sets `first` to null now that the list is671// empty.672if self.first == item {673// SAFETY: The `prev` pointer is the value that `item->prev` had when it was in this674// list, so it must be valid. There is no race since `prev` is still in the list and we675// still have exclusive access to the list.676self.first = unsafe { (*prev).next };677}678679// SAFETY: `item` used to be in the list, so it is dereferenceable by the type invariants680// of `List`.681let list_links = unsafe { ListLinks::from_fields(item) };682// SAFETY: Any pointer in the list originates from a `prepare_to_insert` call.683let raw_item = unsafe { T::post_remove(list_links) };684// SAFETY: The above call to `post_remove` guarantees that we can recreate the `ListArc`.685unsafe { ListArc::from_raw(raw_item) }686}687688/// Moves all items from `other` into `self`.689///690/// The items of `other` are added to the back of `self`, so the last item of `other` becomes691/// the last item of `self`.692pub fn push_all_back(&mut self, other: &mut List<T, ID>) {693// First, we insert the elements into `self`. At the end, we make `other` empty.694if self.is_empty() {695// INVARIANT: All of the elements in `other` become elements of `self`.696self.first = other.first;697} else if !other.is_empty() {698let other_first = other.first;699// SAFETY: The other list is not empty, so this pointer is valid.700let other_last = unsafe { (*other_first).prev };701let self_first = self.first;702// SAFETY: The self list is not empty, so this pointer is valid.703let self_last = unsafe { (*self_first).prev };704705// SAFETY: We have exclusive access to both lists, so we can update the pointers.706// INVARIANT: This correctly sets the pointers to merge both lists. We do not need to707// update `self.first` because the first element of `self` does not change.708unsafe {709(*self_first).prev = other_last;710(*other_last).next = self_first;711(*self_last).next = other_first;712(*other_first).prev = self_last;713}714}715716// INVARIANT: The other list is now empty, so update its pointer.717other.first = ptr::null_mut();718}719720/// Returns a cursor that points before the first element of the list.721pub fn cursor_front(&mut self) -> Cursor<'_, T, ID> {722// INVARIANT: `self.first` is in this list.723Cursor {724next: self.first,725list: self,726}727}728729/// Returns a cursor that points after the last element in the list.730pub fn cursor_back(&mut self) -> Cursor<'_, T, ID> {731// INVARIANT: `next` is allowed to be null.732Cursor {733next: core::ptr::null_mut(),734list: self,735}736}737738/// Creates an iterator over the list.739pub fn iter(&self) -> Iter<'_, T, ID> {740// INVARIANT: If the list is empty, both pointers are null. Otherwise, both pointers point741// at the first element of the same list.742Iter {743current: self.first,744stop: self.first,745_ty: PhantomData,746}747}748}749750impl<T: ?Sized + ListItem<ID>, const ID: u64> Default for List<T, ID> {751fn default() -> Self {752List::new()753}754}755756impl<T: ?Sized + ListItem<ID>, const ID: u64> Drop for List<T, ID> {757fn drop(&mut self) {758while let Some(item) = self.pop_front() {759drop(item);760}761}762}763764/// An iterator over a [`List`].765///766/// # Invariants767///768/// * There must be a [`List`] that is immutably borrowed for the duration of `'a`.769/// * The `current` pointer is null or points at a value in that [`List`].770/// * The `stop` pointer is equal to the `first` field of that [`List`].771#[derive(Clone)]772pub struct Iter<'a, T: ?Sized + ListItem<ID>, const ID: u64 = 0> {773current: *mut ListLinksFields,774stop: *mut ListLinksFields,775_ty: PhantomData<&'a ListArc<T, ID>>,776}777778impl<'a, T: ?Sized + ListItem<ID>, const ID: u64> Iterator for Iter<'a, T, ID> {779type Item = ArcBorrow<'a, T>;780781fn next(&mut self) -> Option<ArcBorrow<'a, T>> {782if self.current.is_null() {783return None;784}785786let current = self.current;787788// SAFETY: We just checked that `current` is not null, so it is in a list, and hence not789// dangling. There's no race because the iterator holds an immutable borrow to the list.790let next = unsafe { (*current).next };791// INVARIANT: If `current` was the last element of the list, then this updates it to null.792// Otherwise, we update it to the next element.793self.current = if next != self.stop {794next795} else {796ptr::null_mut()797};798799// SAFETY: The `current` pointer points at a value in the list.800let item = unsafe { T::view_value(ListLinks::from_fields(current)) };801// SAFETY:802// * All values in a list are stored in an `Arc`.803// * The value cannot be removed from the list for the duration of the lifetime annotated804// on the returned `ArcBorrow`, because removing it from the list would require mutable805// access to the list. However, the `ArcBorrow` is annotated with the iterator's806// lifetime, and the list is immutably borrowed for that lifetime.807// * Values in a list never have a `UniqueArc` reference.808Some(unsafe { ArcBorrow::from_raw(item) })809}810}811812/// A cursor into a [`List`].813///814/// A cursor always rests between two elements in the list. This means that a cursor has a previous815/// and next element, but no current element. It also means that it's possible to have a cursor816/// into an empty list.817///818/// # Examples819///820/// ```821/// use kernel::prelude::*;822/// use kernel::list::{List, ListArc, ListLinks};823///824/// #[pin_data]825/// struct ListItem {826/// value: u32,827/// #[pin]828/// links: ListLinks,829/// }830///831/// impl ListItem {832/// fn new(value: u32) -> Result<ListArc<Self>> {833/// ListArc::pin_init(try_pin_init!(Self {834/// value,835/// links <- ListLinks::new(),836/// }), GFP_KERNEL)837/// }838/// }839///840/// kernel::list::impl_list_arc_safe! {841/// impl ListArcSafe<0> for ListItem { untracked; }842/// }843/// kernel::list::impl_list_item! {844/// impl ListItem<0> for ListItem { using ListLinks { self.links }; }845/// }846///847/// // Use a cursor to remove the first element with the given value.848/// fn remove_first(list: &mut List<ListItem>, value: u32) -> Option<ListArc<ListItem>> {849/// let mut cursor = list.cursor_front();850/// while let Some(next) = cursor.peek_next() {851/// if next.value == value {852/// return Some(next.remove());853/// }854/// cursor.move_next();855/// }856/// None857/// }858///859/// // Use a cursor to remove the last element with the given value.860/// fn remove_last(list: &mut List<ListItem>, value: u32) -> Option<ListArc<ListItem>> {861/// let mut cursor = list.cursor_back();862/// while let Some(prev) = cursor.peek_prev() {863/// if prev.value == value {864/// return Some(prev.remove());865/// }866/// cursor.move_prev();867/// }868/// None869/// }870///871/// // Use a cursor to remove all elements with the given value. The removed elements are moved to872/// // a new list.873/// fn remove_all(list: &mut List<ListItem>, value: u32) -> List<ListItem> {874/// let mut out = List::new();875/// let mut cursor = list.cursor_front();876/// while let Some(next) = cursor.peek_next() {877/// if next.value == value {878/// out.push_back(next.remove());879/// } else {880/// cursor.move_next();881/// }882/// }883/// out884/// }885///886/// // Use a cursor to insert a value at a specific index. Returns an error if the index is out of887/// // bounds.888/// fn insert_at(list: &mut List<ListItem>, new: ListArc<ListItem>, idx: usize) -> Result {889/// let mut cursor = list.cursor_front();890/// for _ in 0..idx {891/// if !cursor.move_next() {892/// return Err(EINVAL);893/// }894/// }895/// cursor.insert_next(new);896/// Ok(())897/// }898///899/// // Merge two sorted lists into a single sorted list.900/// fn merge_sorted(list: &mut List<ListItem>, merge: List<ListItem>) {901/// let mut cursor = list.cursor_front();902/// for to_insert in merge {903/// while let Some(next) = cursor.peek_next() {904/// if to_insert.value < next.value {905/// break;906/// }907/// cursor.move_next();908/// }909/// cursor.insert_prev(to_insert);910/// }911/// }912///913/// let mut list = List::new();914/// list.push_back(ListItem::new(14)?);915/// list.push_back(ListItem::new(12)?);916/// list.push_back(ListItem::new(10)?);917/// list.push_back(ListItem::new(12)?);918/// list.push_back(ListItem::new(15)?);919/// list.push_back(ListItem::new(14)?);920/// assert_eq!(remove_all(&mut list, 12).iter().count(), 2);921/// // [14, 10, 15, 14]922/// assert!(remove_first(&mut list, 14).is_some());923/// // [10, 15, 14]924/// insert_at(&mut list, ListItem::new(12)?, 2)?;925/// // [10, 15, 12, 14]926/// assert!(remove_last(&mut list, 15).is_some());927/// // [10, 12, 14]928///929/// let mut list2 = List::new();930/// list2.push_back(ListItem::new(11)?);931/// list2.push_back(ListItem::new(13)?);932/// merge_sorted(&mut list, list2);933///934/// let mut items = list.into_iter();935/// assert_eq!(items.next().ok_or(EINVAL)?.value, 10);936/// assert_eq!(items.next().ok_or(EINVAL)?.value, 11);937/// assert_eq!(items.next().ok_or(EINVAL)?.value, 12);938/// assert_eq!(items.next().ok_or(EINVAL)?.value, 13);939/// assert_eq!(items.next().ok_or(EINVAL)?.value, 14);940/// assert!(items.next().is_none());941/// # Result::<(), Error>::Ok(())942/// ```943///944/// # Invariants945///946/// The `next` pointer is null or points a value in `list`.947pub struct Cursor<'a, T: ?Sized + ListItem<ID>, const ID: u64 = 0> {948list: &'a mut List<T, ID>,949/// Points at the element after this cursor, or null if the cursor is after the last element.950next: *mut ListLinksFields,951}952953impl<'a, T: ?Sized + ListItem<ID>, const ID: u64> Cursor<'a, T, ID> {954/// Returns a pointer to the element before the cursor.955///956/// Returns null if there is no element before the cursor.957fn prev_ptr(&self) -> *mut ListLinksFields {958let mut next = self.next;959let first = self.list.first;960if next == first {961// We are before the first element.962return core::ptr::null_mut();963}964965if next.is_null() {966// We are after the last element, so we need a pointer to the last element, which is967// the same as `(*first).prev`.968next = first;969}970971// SAFETY: `next` can't be null, because then `first` must also be null, but in that case972// we would have exited at the `next == first` check. Thus, `next` is an element in the973// list, so we can access its `prev` pointer.974unsafe { (*next).prev }975}976977/// Access the element after this cursor.978pub fn peek_next(&mut self) -> Option<CursorPeek<'_, 'a, T, true, ID>> {979if self.next.is_null() {980return None;981}982983// INVARIANT:984// * We just checked that `self.next` is non-null, so it must be in `self.list`.985// * `ptr` is equal to `self.next`.986Some(CursorPeek {987ptr: self.next,988cursor: self,989})990}991992/// Access the element before this cursor.993pub fn peek_prev(&mut self) -> Option<CursorPeek<'_, 'a, T, false, ID>> {994let prev = self.prev_ptr();995996if prev.is_null() {997return None;998}9991000// INVARIANT:1001// * We just checked that `prev` is non-null, so it must be in `self.list`.1002// * `self.prev_ptr()` never returns `self.next`.1003Some(CursorPeek {1004ptr: prev,1005cursor: self,1006})1007}10081009/// Move the cursor one element forward.1010///1011/// If the cursor is after the last element, then this call does nothing. This call returns1012/// `true` if the cursor's position was changed.1013pub fn move_next(&mut self) -> bool {1014if self.next.is_null() {1015return false;1016}10171018// SAFETY: `self.next` is an element in the list and we borrow the list mutably, so we can1019// access the `next` field.1020let mut next = unsafe { (*self.next).next };10211022if next == self.list.first {1023next = core::ptr::null_mut();1024}10251026// INVARIANT: `next` is either null or the next element after an element in the list.1027self.next = next;1028true1029}10301031/// Move the cursor one element backwards.1032///1033/// If the cursor is before the first element, then this call does nothing. This call returns1034/// `true` if the cursor's position was changed.1035pub fn move_prev(&mut self) -> bool {1036if self.next == self.list.first {1037return false;1038}10391040// INVARIANT: `prev_ptr()` always returns a pointer that is null or in the list.1041self.next = self.prev_ptr();1042true1043}10441045/// Inserts an element where the cursor is pointing and get a pointer to the new element.1046fn insert_inner(&mut self, item: ListArc<T, ID>) -> *mut ListLinksFields {1047let ptr = if self.next.is_null() {1048self.list.first1049} else {1050self.next1051};1052// SAFETY:1053// * `ptr` is an element in the list or null.1054// * if `ptr` is null, then `self.list.first` is null so the list is empty.1055let item = unsafe { self.list.insert_inner(item, ptr) };1056if self.next == self.list.first {1057// INVARIANT: We just inserted `item`, so it's a member of list.1058self.list.first = item;1059}1060item1061}10621063/// Insert an element at this cursor's location.1064pub fn insert(mut self, item: ListArc<T, ID>) {1065// This is identical to `insert_prev`, but consumes the cursor. This is helpful because it1066// reduces confusion when the last operation on the cursor is an insertion; in that case,1067// you just want to insert the element at the cursor, and it is confusing that the call1068// involves the word prev or next.1069self.insert_inner(item);1070}10711072/// Inserts an element after this cursor.1073///1074/// After insertion, the new element will be after the cursor.1075pub fn insert_next(&mut self, item: ListArc<T, ID>) {1076self.next = self.insert_inner(item);1077}10781079/// Inserts an element before this cursor.1080///1081/// After insertion, the new element will be before the cursor.1082pub fn insert_prev(&mut self, item: ListArc<T, ID>) {1083self.insert_inner(item);1084}10851086/// Remove the next element from the list.1087pub fn remove_next(&mut self) -> Option<ListArc<T, ID>> {1088self.peek_next().map(|v| v.remove())1089}10901091/// Remove the previous element from the list.1092pub fn remove_prev(&mut self) -> Option<ListArc<T, ID>> {1093self.peek_prev().map(|v| v.remove())1094}1095}10961097/// References the element in the list next to the cursor.1098///1099/// # Invariants1100///1101/// * `ptr` is an element in `self.cursor.list`.1102/// * `ISNEXT == (self.ptr == self.cursor.next)`.1103pub struct CursorPeek<'a, 'b, T: ?Sized + ListItem<ID>, const ISNEXT: bool, const ID: u64> {1104cursor: &'a mut Cursor<'b, T, ID>,1105ptr: *mut ListLinksFields,1106}11071108impl<'a, 'b, T: ?Sized + ListItem<ID>, const ISNEXT: bool, const ID: u64>1109CursorPeek<'a, 'b, T, ISNEXT, ID>1110{1111/// Remove the element from the list.1112pub fn remove(self) -> ListArc<T, ID> {1113if ISNEXT {1114self.cursor.move_next();1115}11161117// INVARIANT: `self.ptr` is not equal to `self.cursor.next` due to the above `move_next`1118// call.1119// SAFETY: By the type invariants of `Self`, `next` is not null, so `next` is an element of1120// `self.cursor.list` by the type invariants of `Cursor`.1121unsafe { self.cursor.list.remove_internal(self.ptr) }1122}11231124/// Access this value as an [`ArcBorrow`].1125pub fn arc(&self) -> ArcBorrow<'_, T> {1126// SAFETY: `self.ptr` points at an element in `self.cursor.list`.1127let me = unsafe { T::view_value(ListLinks::from_fields(self.ptr)) };1128// SAFETY:1129// * All values in a list are stored in an `Arc`.1130// * The value cannot be removed from the list for the duration of the lifetime annotated1131// on the returned `ArcBorrow`, because removing it from the list would require mutable1132// access to the `CursorPeek`, the `Cursor` or the `List`. However, the `ArcBorrow` holds1133// an immutable borrow on the `CursorPeek`, which in turn holds a mutable borrow on the1134// `Cursor`, which in turn holds a mutable borrow on the `List`, so any such mutable1135// access requires first releasing the immutable borrow on the `CursorPeek`.1136// * Values in a list never have a `UniqueArc` reference, because the list has a `ListArc`1137// reference, and `UniqueArc` references must be unique.1138unsafe { ArcBorrow::from_raw(me) }1139}1140}11411142impl<'a, 'b, T: ?Sized + ListItem<ID>, const ISNEXT: bool, const ID: u64> core::ops::Deref1143for CursorPeek<'a, 'b, T, ISNEXT, ID>1144{1145// If you change the `ptr` field to have type `ArcBorrow<'a, T>`, it might seem like you could1146// get rid of the `CursorPeek::arc` method and change the deref target to `ArcBorrow<'a, T>`.1147// However, that doesn't work because 'a is too long. You could obtain an `ArcBorrow<'a, T>`1148// and then call `CursorPeek::remove` without giving up the `ArcBorrow<'a, T>`, which would be1149// unsound.1150type Target = T;11511152fn deref(&self) -> &T {1153// SAFETY: `self.ptr` points at an element in `self.cursor.list`.1154let me = unsafe { T::view_value(ListLinks::from_fields(self.ptr)) };11551156// SAFETY: The value cannot be removed from the list for the duration of the lifetime1157// annotated on the returned `&T`, because removing it from the list would require mutable1158// access to the `CursorPeek`, the `Cursor` or the `List`. However, the `&T` holds an1159// immutable borrow on the `CursorPeek`, which in turn holds a mutable borrow on the1160// `Cursor`, which in turn holds a mutable borrow on the `List`, so any such mutable access1161// requires first releasing the immutable borrow on the `CursorPeek`.1162unsafe { &*me }1163}1164}11651166impl<'a, T: ?Sized + ListItem<ID>, const ID: u64> FusedIterator for Iter<'a, T, ID> {}11671168impl<'a, T: ?Sized + ListItem<ID>, const ID: u64> IntoIterator for &'a List<T, ID> {1169type IntoIter = Iter<'a, T, ID>;1170type Item = ArcBorrow<'a, T>;11711172fn into_iter(self) -> Iter<'a, T, ID> {1173self.iter()1174}1175}11761177/// An owning iterator into a [`List`].1178pub struct IntoIter<T: ?Sized + ListItem<ID>, const ID: u64 = 0> {1179list: List<T, ID>,1180}11811182impl<T: ?Sized + ListItem<ID>, const ID: u64> Iterator for IntoIter<T, ID> {1183type Item = ListArc<T, ID>;11841185fn next(&mut self) -> Option<ListArc<T, ID>> {1186self.list.pop_front()1187}1188}11891190impl<T: ?Sized + ListItem<ID>, const ID: u64> FusedIterator for IntoIter<T, ID> {}11911192impl<T: ?Sized + ListItem<ID>, const ID: u64> DoubleEndedIterator for IntoIter<T, ID> {1193fn next_back(&mut self) -> Option<ListArc<T, ID>> {1194self.list.pop_back()1195}1196}11971198impl<T: ?Sized + ListItem<ID>, const ID: u64> IntoIterator for List<T, ID> {1199type IntoIter = IntoIter<T, ID>;1200type Item = ListArc<T, ID>;12011202fn into_iter(self) -> IntoIter<T, ID> {1203IntoIter { list: self }1204}1205}120612071208