xref: /linux/rust/kernel/list.rs (revision ec7714e4947909190ffb3041a03311a975350fe0)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 // Copyright (C) 2024 Google LLC.
4 
5 //! A linked list implementation.
6 
7 use crate::sync::ArcBorrow;
8 use crate::types::Opaque;
9 use core::iter::{DoubleEndedIterator, FusedIterator};
10 use core::marker::PhantomData;
11 use core::ptr;
12 use pin_init::PinInit;
13 
14 mod impl_list_item_mod;
15 pub use self::impl_list_item_mod::{
16     impl_has_list_links, impl_has_list_links_self_ptr, impl_list_item, HasListLinks, HasSelfPtr,
17 };
18 
19 mod arc;
20 pub use self::arc::{impl_list_arc_safe, AtomicTracker, ListArc, ListArcSafe, TryNewListArc};
21 
22 mod arc_field;
23 pub use self::arc_field::{define_list_arc_field_getter, ListArcField};
24 
25 /// A linked list.
26 ///
27 /// All elements in this linked list will be [`ListArc`] references to the value. Since a value can
28 /// only have one `ListArc` (for each pair of prev/next pointers), this ensures that the same
29 /// prev/next pointers are not used for several linked lists.
30 ///
31 /// # Invariants
32 ///
33 /// * If the list is empty, then `first` is null. Otherwise, `first` points at the `ListLinks`
34 ///   field of the first element in the list.
35 /// * All prev/next pointers in `ListLinks` fields of items in the list are valid and form a cycle.
36 /// * For every item in the list, the list owns the associated [`ListArc`] reference and has
37 ///   exclusive access to the `ListLinks` field.
38 ///
39 /// # Examples
40 ///
41 /// ```
42 /// use kernel::list::*;
43 ///
44 /// #[pin_data]
45 /// struct BasicItem {
46 ///     value: i32,
47 ///     #[pin]
48 ///     links: ListLinks,
49 /// }
50 ///
51 /// impl BasicItem {
52 ///     fn new(value: i32) -> Result<ListArc<Self>> {
53 ///         ListArc::pin_init(try_pin_init!(Self {
54 ///             value,
55 ///             links <- ListLinks::new(),
56 ///         }), GFP_KERNEL)
57 ///     }
58 /// }
59 ///
60 /// impl_has_list_links! {
61 ///     impl HasListLinks<0> for BasicItem { self.links }
62 /// }
63 /// impl_list_arc_safe! {
64 ///     impl ListArcSafe<0> for BasicItem { untracked; }
65 /// }
66 /// impl_list_item! {
67 ///     impl ListItem<0> for BasicItem { using ListLinks; }
68 /// }
69 ///
70 /// // Create a new empty list.
71 /// let mut list = List::new();
72 /// {
73 ///     assert!(list.is_empty());
74 /// }
75 ///
76 /// // Insert 3 elements using `push_back()`.
77 /// list.push_back(BasicItem::new(15)?);
78 /// list.push_back(BasicItem::new(10)?);
79 /// list.push_back(BasicItem::new(30)?);
80 ///
81 /// // Iterate over the list to verify the nodes were inserted correctly.
82 /// // [15, 10, 30]
83 /// {
84 ///     let mut iter = list.iter();
85 ///     assert_eq!(iter.next().unwrap().value, 15);
86 ///     assert_eq!(iter.next().unwrap().value, 10);
87 ///     assert_eq!(iter.next().unwrap().value, 30);
88 ///     assert!(iter.next().is_none());
89 ///
90 ///     // Verify the length of the list.
91 ///     assert_eq!(list.iter().count(), 3);
92 /// }
93 ///
94 /// // Pop the items from the list using `pop_back()` and verify the content.
95 /// {
96 ///     assert_eq!(list.pop_back().unwrap().value, 30);
97 ///     assert_eq!(list.pop_back().unwrap().value, 10);
98 ///     assert_eq!(list.pop_back().unwrap().value, 15);
99 /// }
100 ///
101 /// // Insert 3 elements using `push_front()`.
102 /// list.push_front(BasicItem::new(15)?);
103 /// list.push_front(BasicItem::new(10)?);
104 /// list.push_front(BasicItem::new(30)?);
105 ///
106 /// // Iterate over the list to verify the nodes were inserted correctly.
107 /// // [30, 10, 15]
108 /// {
109 ///     let mut iter = list.iter();
110 ///     assert_eq!(iter.next().unwrap().value, 30);
111 ///     assert_eq!(iter.next().unwrap().value, 10);
112 ///     assert_eq!(iter.next().unwrap().value, 15);
113 ///     assert!(iter.next().is_none());
114 ///
115 ///     // Verify the length of the list.
116 ///     assert_eq!(list.iter().count(), 3);
117 /// }
118 ///
119 /// // Pop the items from the list using `pop_front()` and verify the content.
120 /// {
121 ///     assert_eq!(list.pop_front().unwrap().value, 30);
122 ///     assert_eq!(list.pop_front().unwrap().value, 10);
123 /// }
124 ///
125 /// // Push `list2` to `list` through `push_all_back()`.
126 /// // list: [15]
127 /// // list2: [25, 35]
128 /// {
129 ///     let mut list2 = List::new();
130 ///     list2.push_back(BasicItem::new(25)?);
131 ///     list2.push_back(BasicItem::new(35)?);
132 ///
133 ///     list.push_all_back(&mut list2);
134 ///
135 ///     // list: [15, 25, 35]
136 ///     // list2: []
137 ///     let mut iter = list.iter();
138 ///     assert_eq!(iter.next().unwrap().value, 15);
139 ///     assert_eq!(iter.next().unwrap().value, 25);
140 ///     assert_eq!(iter.next().unwrap().value, 35);
141 ///     assert!(iter.next().is_none());
142 ///     assert!(list2.is_empty());
143 /// }
144 /// # Result::<(), Error>::Ok(())
145 /// ```
146 pub struct List<T: ?Sized + ListItem<ID>, const ID: u64 = 0> {
147     first: *mut ListLinksFields,
148     _ty: PhantomData<ListArc<T, ID>>,
149 }
150 
151 // SAFETY: This is a container of `ListArc<T, ID>`, and access to the container allows the same
152 // type of access to the `ListArc<T, ID>` elements.
153 unsafe impl<T, const ID: u64> Send for List<T, ID>
154 where
155     ListArc<T, ID>: Send,
156     T: ?Sized + ListItem<ID>,
157 {
158 }
159 // SAFETY: This is a container of `ListArc<T, ID>`, and access to the container allows the same
160 // type of access to the `ListArc<T, ID>` elements.
161 unsafe impl<T, const ID: u64> Sync for List<T, ID>
162 where
163     ListArc<T, ID>: Sync,
164     T: ?Sized + ListItem<ID>,
165 {
166 }
167 
168 /// Implemented by types where a [`ListArc<Self>`] can be inserted into a [`List`].
169 ///
170 /// # Safety
171 ///
172 /// Implementers must ensure that they provide the guarantees documented on methods provided by
173 /// this trait.
174 ///
175 /// [`ListArc<Self>`]: ListArc
176 pub unsafe trait ListItem<const ID: u64 = 0>: ListArcSafe<ID> {
177     /// Views the [`ListLinks`] for this value.
178     ///
179     /// # Guarantees
180     ///
181     /// If there is a previous call to `prepare_to_insert` and there is no call to `post_remove`
182     /// since the most recent such call, then this returns the same pointer as the one returned by
183     /// the most recent call to `prepare_to_insert`.
184     ///
185     /// Otherwise, the returned pointer points at a read-only [`ListLinks`] with two null pointers.
186     ///
187     /// # Safety
188     ///
189     /// The provided pointer must point at a valid value. (It need not be in an `Arc`.)
view_links(me: *const Self) -> *mut ListLinks<ID>190     unsafe fn view_links(me: *const Self) -> *mut ListLinks<ID>;
191 
192     /// View the full value given its [`ListLinks`] field.
193     ///
194     /// Can only be used when the value is in a list.
195     ///
196     /// # Guarantees
197     ///
198     /// * Returns the same pointer as the one passed to the most recent call to `prepare_to_insert`.
199     /// * The returned pointer is valid until the next call to `post_remove`.
200     ///
201     /// # Safety
202     ///
203     /// * The provided pointer must originate from the most recent call to `prepare_to_insert`, or
204     ///   from a call to `view_links` that happened after the most recent call to
205     ///   `prepare_to_insert`.
206     /// * Since the most recent call to `prepare_to_insert`, the `post_remove` method must not have
207     ///   been called.
view_value(me: *mut ListLinks<ID>) -> *const Self208     unsafe fn view_value(me: *mut ListLinks<ID>) -> *const Self;
209 
210     /// This is called when an item is inserted into a [`List`].
211     ///
212     /// # Guarantees
213     ///
214     /// The caller is granted exclusive access to the returned [`ListLinks`] until `post_remove` is
215     /// called.
216     ///
217     /// # Safety
218     ///
219     /// * The provided pointer must point at a valid value in an [`Arc`].
220     /// * Calls to `prepare_to_insert` and `post_remove` on the same value must alternate.
221     /// * The caller must own the [`ListArc`] for this value.
222     /// * The caller must not give up ownership of the [`ListArc`] unless `post_remove` has been
223     ///   called after this call to `prepare_to_insert`.
224     ///
225     /// [`Arc`]: crate::sync::Arc
prepare_to_insert(me: *const Self) -> *mut ListLinks<ID>226     unsafe fn prepare_to_insert(me: *const Self) -> *mut ListLinks<ID>;
227 
228     /// This undoes a previous call to `prepare_to_insert`.
229     ///
230     /// # Guarantees
231     ///
232     /// The returned pointer is the pointer that was originally passed to `prepare_to_insert`.
233     ///
234     /// # Safety
235     ///
236     /// The provided pointer must be the pointer returned by the most recent call to
237     /// `prepare_to_insert`.
post_remove(me: *mut ListLinks<ID>) -> *const Self238     unsafe fn post_remove(me: *mut ListLinks<ID>) -> *const Self;
239 }
240 
241 #[repr(C)]
242 #[derive(Copy, Clone)]
243 struct ListLinksFields {
244     next: *mut ListLinksFields,
245     prev: *mut ListLinksFields,
246 }
247 
248 /// The prev/next pointers for an item in a linked list.
249 ///
250 /// # Invariants
251 ///
252 /// The fields are null if and only if this item is not in a list.
253 #[repr(transparent)]
254 pub struct ListLinks<const ID: u64 = 0> {
255     // This type is `!Unpin` for aliasing reasons as the pointers are part of an intrusive linked
256     // list.
257     inner: Opaque<ListLinksFields>,
258 }
259 
260 // SAFETY: The only way to access/modify the pointers inside of `ListLinks<ID>` is via holding the
261 // associated `ListArc<T, ID>`. Since that type correctly implements `Send`, it is impossible to
262 // move this an instance of this type to a different thread if the pointees are `!Send`.
263 unsafe impl<const ID: u64> Send for ListLinks<ID> {}
264 // SAFETY: The type is opaque so immutable references to a ListLinks are useless. Therefore, it's
265 // okay to have immutable access to a ListLinks from several threads at once.
266 unsafe impl<const ID: u64> Sync for ListLinks<ID> {}
267 
268 impl<const ID: u64> ListLinks<ID> {
269     /// Creates a new initializer for this type.
new() -> impl PinInit<Self>270     pub fn new() -> impl PinInit<Self> {
271         // INVARIANT: Pin-init initializers can't be used on an existing `Arc`, so this value will
272         // not be constructed in an `Arc` that already has a `ListArc`.
273         ListLinks {
274             inner: Opaque::new(ListLinksFields {
275                 prev: ptr::null_mut(),
276                 next: ptr::null_mut(),
277             }),
278         }
279     }
280 
281     /// # Safety
282     ///
283     /// `me` must be dereferenceable.
284     #[inline]
fields(me: *mut Self) -> *mut ListLinksFields285     unsafe fn fields(me: *mut Self) -> *mut ListLinksFields {
286         // SAFETY: The caller promises that the pointer is valid.
287         unsafe { Opaque::raw_get(ptr::addr_of!((*me).inner)) }
288     }
289 
290     /// # Safety
291     ///
292     /// `me` must be dereferenceable.
293     #[inline]
from_fields(me: *mut ListLinksFields) -> *mut Self294     unsafe fn from_fields(me: *mut ListLinksFields) -> *mut Self {
295         me.cast()
296     }
297 }
298 
299 /// Similar to [`ListLinks`], but also contains a pointer to the full value.
300 ///
301 /// This type can be used instead of [`ListLinks`] to support lists with trait objects.
302 #[repr(C)]
303 pub struct ListLinksSelfPtr<T: ?Sized, const ID: u64 = 0> {
304     /// The `ListLinks` field inside this value.
305     ///
306     /// This is public so that it can be used with `impl_has_list_links!`.
307     pub inner: ListLinks<ID>,
308     // UnsafeCell is not enough here because we use `Opaque::uninit` as a dummy value, and
309     // `ptr::null()` doesn't work for `T: ?Sized`.
310     self_ptr: Opaque<*const T>,
311 }
312 
313 // SAFETY: The fields of a ListLinksSelfPtr can be moved across thread boundaries.
314 unsafe impl<T: ?Sized + Send, const ID: u64> Send for ListLinksSelfPtr<T, ID> {}
315 // SAFETY: The type is opaque so immutable references to a ListLinksSelfPtr are useless. Therefore,
316 // it's okay to have immutable access to a ListLinks from several threads at once.
317 //
318 // Note that `inner` being a public field does not prevent this type from being opaque, since
319 // `inner` is a opaque type.
320 unsafe impl<T: ?Sized + Sync, const ID: u64> Sync for ListLinksSelfPtr<T, ID> {}
321 
322 impl<T: ?Sized, const ID: u64> ListLinksSelfPtr<T, ID> {
323     /// The offset from the [`ListLinks`] to the self pointer field.
324     pub const LIST_LINKS_SELF_PTR_OFFSET: usize = core::mem::offset_of!(Self, self_ptr);
325 
326     /// Creates a new initializer for this type.
new() -> impl PinInit<Self>327     pub fn new() -> impl PinInit<Self> {
328         // INVARIANT: Pin-init initializers can't be used on an existing `Arc`, so this value will
329         // not be constructed in an `Arc` that already has a `ListArc`.
330         Self {
331             inner: ListLinks {
332                 inner: Opaque::new(ListLinksFields {
333                     prev: ptr::null_mut(),
334                     next: ptr::null_mut(),
335                 }),
336             },
337             self_ptr: Opaque::uninit(),
338         }
339     }
340 }
341 
342 impl<T: ?Sized + ListItem<ID>, const ID: u64> List<T, ID> {
343     /// Creates a new empty list.
new() -> Self344     pub const fn new() -> Self {
345         Self {
346             first: ptr::null_mut(),
347             _ty: PhantomData,
348         }
349     }
350 
351     /// Returns whether this list is empty.
is_empty(&self) -> bool352     pub fn is_empty(&self) -> bool {
353         self.first.is_null()
354     }
355 
356     /// Inserts `item` before `next` in the cycle.
357     ///
358     /// Returns a pointer to the newly inserted element. Never changes `self.first` unless the list
359     /// is empty.
360     ///
361     /// # Safety
362     ///
363     /// * `next` must be an element in this list or null.
364     /// * if `next` is null, then the list must be empty.
insert_inner( &mut self, item: ListArc<T, ID>, next: *mut ListLinksFields, ) -> *mut ListLinksFields365     unsafe fn insert_inner(
366         &mut self,
367         item: ListArc<T, ID>,
368         next: *mut ListLinksFields,
369     ) -> *mut ListLinksFields {
370         let raw_item = ListArc::into_raw(item);
371         // SAFETY:
372         // * We just got `raw_item` from a `ListArc`, so it's in an `Arc`.
373         // * Since we have ownership of the `ListArc`, `post_remove` must have been called after
374         //   the most recent call to `prepare_to_insert`, if any.
375         // * We own the `ListArc`.
376         // * Removing items from this list is always done using `remove_internal_inner`, which
377         //   calls `post_remove` before giving up ownership.
378         let list_links = unsafe { T::prepare_to_insert(raw_item) };
379         // SAFETY: We have not yet called `post_remove`, so `list_links` is still valid.
380         let item = unsafe { ListLinks::fields(list_links) };
381 
382         // Check if the list is empty.
383         if next.is_null() {
384             // SAFETY: The caller just gave us ownership of these fields.
385             // INVARIANT: A linked list with one item should be cyclic.
386             unsafe {
387                 (*item).next = item;
388                 (*item).prev = item;
389             }
390             self.first = item;
391         } else {
392             // SAFETY: By the type invariant, this pointer is valid or null. We just checked that
393             // it's not null, so it must be valid.
394             let prev = unsafe { (*next).prev };
395             // SAFETY: Pointers in a linked list are never dangling, and the caller just gave us
396             // ownership of the fields on `item`.
397             // INVARIANT: This correctly inserts `item` between `prev` and `next`.
398             unsafe {
399                 (*item).next = next;
400                 (*item).prev = prev;
401                 (*prev).next = item;
402                 (*next).prev = item;
403             }
404         }
405 
406         item
407     }
408 
409     /// Add the provided item to the back of the list.
push_back(&mut self, item: ListArc<T, ID>)410     pub fn push_back(&mut self, item: ListArc<T, ID>) {
411         // SAFETY:
412         // * `self.first` is null or in the list.
413         // * `self.first` is only null if the list is empty.
414         unsafe { self.insert_inner(item, self.first) };
415     }
416 
417     /// Add the provided item to the front of the list.
push_front(&mut self, item: ListArc<T, ID>)418     pub fn push_front(&mut self, item: ListArc<T, ID>) {
419         // SAFETY:
420         // * `self.first` is null or in the list.
421         // * `self.first` is only null if the list is empty.
422         let new_elem = unsafe { self.insert_inner(item, self.first) };
423 
424         // INVARIANT: `new_elem` is in the list because we just inserted it.
425         self.first = new_elem;
426     }
427 
428     /// Removes the last item from this list.
pop_back(&mut self) -> Option<ListArc<T, ID>>429     pub fn pop_back(&mut self) -> Option<ListArc<T, ID>> {
430         if self.is_empty() {
431             return None;
432         }
433 
434         // SAFETY: We just checked that the list is not empty.
435         let last = unsafe { (*self.first).prev };
436         // SAFETY: The last item of this list is in this list.
437         Some(unsafe { self.remove_internal(last) })
438     }
439 
440     /// Removes the first item from this list.
pop_front(&mut self) -> Option<ListArc<T, ID>>441     pub fn pop_front(&mut self) -> Option<ListArc<T, ID>> {
442         if self.is_empty() {
443             return None;
444         }
445 
446         // SAFETY: The first item of this list is in this list.
447         Some(unsafe { self.remove_internal(self.first) })
448     }
449 
450     /// Removes the provided item from this list and returns it.
451     ///
452     /// This returns `None` if the item is not in the list. (Note that by the safety requirements,
453     /// this means that the item is not in any list.)
454     ///
455     /// # Safety
456     ///
457     /// `item` must not be in a different linked list (with the same id).
remove(&mut self, item: &T) -> Option<ListArc<T, ID>>458     pub unsafe fn remove(&mut self, item: &T) -> Option<ListArc<T, ID>> {
459         // SAFETY: TODO.
460         let mut item = unsafe { ListLinks::fields(T::view_links(item)) };
461         // SAFETY: The user provided a reference, and reference are never dangling.
462         //
463         // As for why this is not a data race, there are two cases:
464         //
465         //  * If `item` is not in any list, then these fields are read-only and null.
466         //  * If `item` is in this list, then we have exclusive access to these fields since we
467         //    have a mutable reference to the list.
468         //
469         // In either case, there's no race.
470         let ListLinksFields { next, prev } = unsafe { *item };
471 
472         debug_assert_eq!(next.is_null(), prev.is_null());
473         if !next.is_null() {
474             // This is really a no-op, but this ensures that `item` is a raw pointer that was
475             // obtained without going through a pointer->reference->pointer conversion roundtrip.
476             // This ensures that the list is valid under the more restrictive strict provenance
477             // ruleset.
478             //
479             // SAFETY: We just checked that `next` is not null, and it's not dangling by the
480             // list invariants.
481             unsafe {
482                 debug_assert_eq!(item, (*next).prev);
483                 item = (*next).prev;
484             }
485 
486             // SAFETY: We just checked that `item` is in a list, so the caller guarantees that it
487             // is in this list. The pointers are in the right order.
488             Some(unsafe { self.remove_internal_inner(item, next, prev) })
489         } else {
490             None
491         }
492     }
493 
494     /// Removes the provided item from the list.
495     ///
496     /// # Safety
497     ///
498     /// `item` must point at an item in this list.
remove_internal(&mut self, item: *mut ListLinksFields) -> ListArc<T, ID>499     unsafe fn remove_internal(&mut self, item: *mut ListLinksFields) -> ListArc<T, ID> {
500         // SAFETY: The caller promises that this pointer is not dangling, and there's no data race
501         // since we have a mutable reference to the list containing `item`.
502         let ListLinksFields { next, prev } = unsafe { *item };
503         // SAFETY: The pointers are ok and in the right order.
504         unsafe { self.remove_internal_inner(item, next, prev) }
505     }
506 
507     /// Removes the provided item from the list.
508     ///
509     /// # Safety
510     ///
511     /// The `item` pointer must point at an item in this list, and we must have `(*item).next ==
512     /// next` and `(*item).prev == prev`.
remove_internal_inner( &mut self, item: *mut ListLinksFields, next: *mut ListLinksFields, prev: *mut ListLinksFields, ) -> ListArc<T, ID>513     unsafe fn remove_internal_inner(
514         &mut self,
515         item: *mut ListLinksFields,
516         next: *mut ListLinksFields,
517         prev: *mut ListLinksFields,
518     ) -> ListArc<T, ID> {
519         // SAFETY: We have exclusive access to the pointers of items in the list, and the prev/next
520         // pointers are always valid for items in a list.
521         //
522         // INVARIANT: There are three cases:
523         //  * If the list has at least three items, then after removing the item, `prev` and `next`
524         //    will be next to each other.
525         //  * If the list has two items, then the remaining item will point at itself.
526         //  * If the list has one item, then `next == prev == item`, so these writes have no
527         //    effect. The list remains unchanged and `item` is still in the list for now.
528         unsafe {
529             (*next).prev = prev;
530             (*prev).next = next;
531         }
532         // SAFETY: We have exclusive access to items in the list.
533         // INVARIANT: `item` is being removed, so the pointers should be null.
534         unsafe {
535             (*item).prev = ptr::null_mut();
536             (*item).next = ptr::null_mut();
537         }
538         // INVARIANT: There are three cases:
539         //  * If `item` was not the first item, then `self.first` should remain unchanged.
540         //  * If `item` was the first item and there is another item, then we just updated
541         //    `prev->next` to `next`, which is the new first item, and setting `item->next` to null
542         //    did not modify `prev->next`.
543         //  * If `item` was the only item in the list, then `prev == item`, and we just set
544         //    `item->next` to null, so this correctly sets `first` to null now that the list is
545         //    empty.
546         if self.first == item {
547             // SAFETY: The `prev` pointer is the value that `item->prev` had when it was in this
548             // list, so it must be valid. There is no race since `prev` is still in the list and we
549             // still have exclusive access to the list.
550             self.first = unsafe { (*prev).next };
551         }
552 
553         // SAFETY: `item` used to be in the list, so it is dereferenceable by the type invariants
554         // of `List`.
555         let list_links = unsafe { ListLinks::from_fields(item) };
556         // SAFETY: Any pointer in the list originates from a `prepare_to_insert` call.
557         let raw_item = unsafe { T::post_remove(list_links) };
558         // SAFETY: The above call to `post_remove` guarantees that we can recreate the `ListArc`.
559         unsafe { ListArc::from_raw(raw_item) }
560     }
561 
562     /// Moves all items from `other` into `self`.
563     ///
564     /// The items of `other` are added to the back of `self`, so the last item of `other` becomes
565     /// the last item of `self`.
push_all_back(&mut self, other: &mut List<T, ID>)566     pub fn push_all_back(&mut self, other: &mut List<T, ID>) {
567         // First, we insert the elements into `self`. At the end, we make `other` empty.
568         if self.is_empty() {
569             // INVARIANT: All of the elements in `other` become elements of `self`.
570             self.first = other.first;
571         } else if !other.is_empty() {
572             let other_first = other.first;
573             // SAFETY: The other list is not empty, so this pointer is valid.
574             let other_last = unsafe { (*other_first).prev };
575             let self_first = self.first;
576             // SAFETY: The self list is not empty, so this pointer is valid.
577             let self_last = unsafe { (*self_first).prev };
578 
579             // SAFETY: We have exclusive access to both lists, so we can update the pointers.
580             // INVARIANT: This correctly sets the pointers to merge both lists. We do not need to
581             // update `self.first` because the first element of `self` does not change.
582             unsafe {
583                 (*self_first).prev = other_last;
584                 (*other_last).next = self_first;
585                 (*self_last).next = other_first;
586                 (*other_first).prev = self_last;
587             }
588         }
589 
590         // INVARIANT: The other list is now empty, so update its pointer.
591         other.first = ptr::null_mut();
592     }
593 
594     /// Returns a cursor that points before the first element of the list.
cursor_front(&mut self) -> Cursor<'_, T, ID>595     pub fn cursor_front(&mut self) -> Cursor<'_, T, ID> {
596         // INVARIANT: `self.first` is in this list.
597         Cursor {
598             next: self.first,
599             list: self,
600         }
601     }
602 
603     /// Returns a cursor that points after the last element in the list.
cursor_back(&mut self) -> Cursor<'_, T, ID>604     pub fn cursor_back(&mut self) -> Cursor<'_, T, ID> {
605         // INVARIANT: `next` is allowed to be null.
606         Cursor {
607             next: core::ptr::null_mut(),
608             list: self,
609         }
610     }
611 
612     /// Creates an iterator over the list.
iter(&self) -> Iter<'_, T, ID>613     pub fn iter(&self) -> Iter<'_, T, ID> {
614         // INVARIANT: If the list is empty, both pointers are null. Otherwise, both pointers point
615         // at the first element of the same list.
616         Iter {
617             current: self.first,
618             stop: self.first,
619             _ty: PhantomData,
620         }
621     }
622 }
623 
624 impl<T: ?Sized + ListItem<ID>, const ID: u64> Default for List<T, ID> {
default() -> Self625     fn default() -> Self {
626         List::new()
627     }
628 }
629 
630 impl<T: ?Sized + ListItem<ID>, const ID: u64> Drop for List<T, ID> {
drop(&mut self)631     fn drop(&mut self) {
632         while let Some(item) = self.pop_front() {
633             drop(item);
634         }
635     }
636 }
637 
638 /// An iterator over a [`List`].
639 ///
640 /// # Invariants
641 ///
642 /// * There must be a [`List`] that is immutably borrowed for the duration of `'a`.
643 /// * The `current` pointer is null or points at a value in that [`List`].
644 /// * The `stop` pointer is equal to the `first` field of that [`List`].
645 #[derive(Clone)]
646 pub struct Iter<'a, T: ?Sized + ListItem<ID>, const ID: u64 = 0> {
647     current: *mut ListLinksFields,
648     stop: *mut ListLinksFields,
649     _ty: PhantomData<&'a ListArc<T, ID>>,
650 }
651 
652 impl<'a, T: ?Sized + ListItem<ID>, const ID: u64> Iterator for Iter<'a, T, ID> {
653     type Item = ArcBorrow<'a, T>;
654 
next(&mut self) -> Option<ArcBorrow<'a, T>>655     fn next(&mut self) -> Option<ArcBorrow<'a, T>> {
656         if self.current.is_null() {
657             return None;
658         }
659 
660         let current = self.current;
661 
662         // SAFETY: We just checked that `current` is not null, so it is in a list, and hence not
663         // dangling. There's no race because the iterator holds an immutable borrow to the list.
664         let next = unsafe { (*current).next };
665         // INVARIANT: If `current` was the last element of the list, then this updates it to null.
666         // Otherwise, we update it to the next element.
667         self.current = if next != self.stop {
668             next
669         } else {
670             ptr::null_mut()
671         };
672 
673         // SAFETY: The `current` pointer points at a value in the list.
674         let item = unsafe { T::view_value(ListLinks::from_fields(current)) };
675         // SAFETY:
676         // * All values in a list are stored in an `Arc`.
677         // * The value cannot be removed from the list for the duration of the lifetime annotated
678         //   on the returned `ArcBorrow`, because removing it from the list would require mutable
679         //   access to the list. However, the `ArcBorrow` is annotated with the iterator's
680         //   lifetime, and the list is immutably borrowed for that lifetime.
681         // * Values in a list never have a `UniqueArc` reference.
682         Some(unsafe { ArcBorrow::from_raw(item) })
683     }
684 }
685 
686 /// A cursor into a [`List`].
687 ///
688 /// A cursor always rests between two elements in the list. This means that a cursor has a previous
689 /// and next element, but no current element. It also means that it's possible to have a cursor
690 /// into an empty list.
691 ///
692 /// # Examples
693 ///
694 /// ```
695 /// use kernel::prelude::*;
696 /// use kernel::list::{List, ListArc, ListLinks};
697 ///
698 /// #[pin_data]
699 /// struct ListItem {
700 ///     value: u32,
701 ///     #[pin]
702 ///     links: ListLinks,
703 /// }
704 ///
705 /// impl ListItem {
706 ///     fn new(value: u32) -> Result<ListArc<Self>> {
707 ///         ListArc::pin_init(try_pin_init!(Self {
708 ///             value,
709 ///             links <- ListLinks::new(),
710 ///         }), GFP_KERNEL)
711 ///     }
712 /// }
713 ///
714 /// kernel::list::impl_has_list_links! {
715 ///     impl HasListLinks<0> for ListItem { self.links }
716 /// }
717 /// kernel::list::impl_list_arc_safe! {
718 ///     impl ListArcSafe<0> for ListItem { untracked; }
719 /// }
720 /// kernel::list::impl_list_item! {
721 ///     impl ListItem<0> for ListItem { using ListLinks; }
722 /// }
723 ///
724 /// // Use a cursor to remove the first element with the given value.
725 /// fn remove_first(list: &mut List<ListItem>, value: u32) -> Option<ListArc<ListItem>> {
726 ///     let mut cursor = list.cursor_front();
727 ///     while let Some(next) = cursor.peek_next() {
728 ///         if next.value == value {
729 ///             return Some(next.remove());
730 ///         }
731 ///         cursor.move_next();
732 ///     }
733 ///     None
734 /// }
735 ///
736 /// // Use a cursor to remove the last element with the given value.
737 /// fn remove_last(list: &mut List<ListItem>, value: u32) -> Option<ListArc<ListItem>> {
738 ///     let mut cursor = list.cursor_back();
739 ///     while let Some(prev) = cursor.peek_prev() {
740 ///         if prev.value == value {
741 ///             return Some(prev.remove());
742 ///         }
743 ///         cursor.move_prev();
744 ///     }
745 ///     None
746 /// }
747 ///
748 /// // Use a cursor to remove all elements with the given value. The removed elements are moved to
749 /// // a new list.
750 /// fn remove_all(list: &mut List<ListItem>, value: u32) -> List<ListItem> {
751 ///     let mut out = List::new();
752 ///     let mut cursor = list.cursor_front();
753 ///     while let Some(next) = cursor.peek_next() {
754 ///         if next.value == value {
755 ///             out.push_back(next.remove());
756 ///         } else {
757 ///             cursor.move_next();
758 ///         }
759 ///     }
760 ///     out
761 /// }
762 ///
763 /// // Use a cursor to insert a value at a specific index. Returns an error if the index is out of
764 /// // bounds.
765 /// fn insert_at(list: &mut List<ListItem>, new: ListArc<ListItem>, idx: usize) -> Result {
766 ///     let mut cursor = list.cursor_front();
767 ///     for _ in 0..idx {
768 ///         if !cursor.move_next() {
769 ///             return Err(EINVAL);
770 ///         }
771 ///     }
772 ///     cursor.insert_next(new);
773 ///     Ok(())
774 /// }
775 ///
776 /// // Merge two sorted lists into a single sorted list.
777 /// fn merge_sorted(list: &mut List<ListItem>, merge: List<ListItem>) {
778 ///     let mut cursor = list.cursor_front();
779 ///     for to_insert in merge {
780 ///         while let Some(next) = cursor.peek_next() {
781 ///             if to_insert.value < next.value {
782 ///                 break;
783 ///             }
784 ///             cursor.move_next();
785 ///         }
786 ///         cursor.insert_prev(to_insert);
787 ///     }
788 /// }
789 ///
790 /// let mut list = List::new();
791 /// list.push_back(ListItem::new(14)?);
792 /// list.push_back(ListItem::new(12)?);
793 /// list.push_back(ListItem::new(10)?);
794 /// list.push_back(ListItem::new(12)?);
795 /// list.push_back(ListItem::new(15)?);
796 /// list.push_back(ListItem::new(14)?);
797 /// assert_eq!(remove_all(&mut list, 12).iter().count(), 2);
798 /// // [14, 10, 15, 14]
799 /// assert!(remove_first(&mut list, 14).is_some());
800 /// // [10, 15, 14]
801 /// insert_at(&mut list, ListItem::new(12)?, 2)?;
802 /// // [10, 15, 12, 14]
803 /// assert!(remove_last(&mut list, 15).is_some());
804 /// // [10, 12, 14]
805 ///
806 /// let mut list2 = List::new();
807 /// list2.push_back(ListItem::new(11)?);
808 /// list2.push_back(ListItem::new(13)?);
809 /// merge_sorted(&mut list, list2);
810 ///
811 /// let mut items = list.into_iter();
812 /// assert_eq!(items.next().unwrap().value, 10);
813 /// assert_eq!(items.next().unwrap().value, 11);
814 /// assert_eq!(items.next().unwrap().value, 12);
815 /// assert_eq!(items.next().unwrap().value, 13);
816 /// assert_eq!(items.next().unwrap().value, 14);
817 /// assert!(items.next().is_none());
818 /// # Result::<(), Error>::Ok(())
819 /// ```
820 ///
821 /// # Invariants
822 ///
823 /// The `next` pointer is null or points a value in `list`.
824 pub struct Cursor<'a, T: ?Sized + ListItem<ID>, const ID: u64 = 0> {
825     list: &'a mut List<T, ID>,
826     /// Points at the element after this cursor, or null if the cursor is after the last element.
827     next: *mut ListLinksFields,
828 }
829 
830 impl<'a, T: ?Sized + ListItem<ID>, const ID: u64> Cursor<'a, T, ID> {
831     /// Returns a pointer to the element before the cursor.
832     ///
833     /// Returns null if there is no element before the cursor.
prev_ptr(&self) -> *mut ListLinksFields834     fn prev_ptr(&self) -> *mut ListLinksFields {
835         let mut next = self.next;
836         let first = self.list.first;
837         if next == first {
838             // We are before the first element.
839             return core::ptr::null_mut();
840         }
841 
842         if next.is_null() {
843             // We are after the last element, so we need a pointer to the last element, which is
844             // the same as `(*first).prev`.
845             next = first;
846         }
847 
848         // SAFETY: `next` can't be null, because then `first` must also be null, but in that case
849         // we would have exited at the `next == first` check. Thus, `next` is an element in the
850         // list, so we can access its `prev` pointer.
851         unsafe { (*next).prev }
852     }
853 
854     /// Access the element after this cursor.
peek_next(&mut self) -> Option<CursorPeek<'_, 'a, T, true, ID>>855     pub fn peek_next(&mut self) -> Option<CursorPeek<'_, 'a, T, true, ID>> {
856         if self.next.is_null() {
857             return None;
858         }
859 
860         // INVARIANT:
861         // * We just checked that `self.next` is non-null, so it must be in `self.list`.
862         // * `ptr` is equal to `self.next`.
863         Some(CursorPeek {
864             ptr: self.next,
865             cursor: self,
866         })
867     }
868 
869     /// Access the element before this cursor.
peek_prev(&mut self) -> Option<CursorPeek<'_, 'a, T, false, ID>>870     pub fn peek_prev(&mut self) -> Option<CursorPeek<'_, 'a, T, false, ID>> {
871         let prev = self.prev_ptr();
872 
873         if prev.is_null() {
874             return None;
875         }
876 
877         // INVARIANT:
878         // * We just checked that `prev` is non-null, so it must be in `self.list`.
879         // * `self.prev_ptr()` never returns `self.next`.
880         Some(CursorPeek {
881             ptr: prev,
882             cursor: self,
883         })
884     }
885 
886     /// Move the cursor one element forward.
887     ///
888     /// If the cursor is after the last element, then this call does nothing. This call returns
889     /// `true` if the cursor's position was changed.
move_next(&mut self) -> bool890     pub fn move_next(&mut self) -> bool {
891         if self.next.is_null() {
892             return false;
893         }
894 
895         // SAFETY: `self.next` is an element in the list and we borrow the list mutably, so we can
896         // access the `next` field.
897         let mut next = unsafe { (*self.next).next };
898 
899         if next == self.list.first {
900             next = core::ptr::null_mut();
901         }
902 
903         // INVARIANT: `next` is either null or the next element after an element in the list.
904         self.next = next;
905         true
906     }
907 
908     /// Move the cursor one element backwards.
909     ///
910     /// If the cursor is before the first element, then this call does nothing. This call returns
911     /// `true` if the cursor's position was changed.
move_prev(&mut self) -> bool912     pub fn move_prev(&mut self) -> bool {
913         if self.next == self.list.first {
914             return false;
915         }
916 
917         // INVARIANT: `prev_ptr()` always returns a pointer that is null or in the list.
918         self.next = self.prev_ptr();
919         true
920     }
921 
922     /// Inserts an element where the cursor is pointing and get a pointer to the new element.
insert_inner(&mut self, item: ListArc<T, ID>) -> *mut ListLinksFields923     fn insert_inner(&mut self, item: ListArc<T, ID>) -> *mut ListLinksFields {
924         let ptr = if self.next.is_null() {
925             self.list.first
926         } else {
927             self.next
928         };
929         // SAFETY:
930         // * `ptr` is an element in the list or null.
931         // * if `ptr` is null, then `self.list.first` is null so the list is empty.
932         let item = unsafe { self.list.insert_inner(item, ptr) };
933         if self.next == self.list.first {
934             // INVARIANT: We just inserted `item`, so it's a member of list.
935             self.list.first = item;
936         }
937         item
938     }
939 
940     /// Insert an element at this cursor's location.
insert(mut self, item: ListArc<T, ID>)941     pub fn insert(mut self, item: ListArc<T, ID>) {
942         // This is identical to `insert_prev`, but consumes the cursor. This is helpful because it
943         // reduces confusion when the last operation on the cursor is an insertion; in that case,
944         // you just want to insert the element at the cursor, and it is confusing that the call
945         // involves the word prev or next.
946         self.insert_inner(item);
947     }
948 
949     /// Inserts an element after this cursor.
950     ///
951     /// After insertion, the new element will be after the cursor.
insert_next(&mut self, item: ListArc<T, ID>)952     pub fn insert_next(&mut self, item: ListArc<T, ID>) {
953         self.next = self.insert_inner(item);
954     }
955 
956     /// Inserts an element before this cursor.
957     ///
958     /// After insertion, the new element will be before the cursor.
insert_prev(&mut self, item: ListArc<T, ID>)959     pub fn insert_prev(&mut self, item: ListArc<T, ID>) {
960         self.insert_inner(item);
961     }
962 
963     /// Remove the next element from the list.
remove_next(&mut self) -> Option<ListArc<T, ID>>964     pub fn remove_next(&mut self) -> Option<ListArc<T, ID>> {
965         self.peek_next().map(|v| v.remove())
966     }
967 
968     /// Remove the previous element from the list.
remove_prev(&mut self) -> Option<ListArc<T, ID>>969     pub fn remove_prev(&mut self) -> Option<ListArc<T, ID>> {
970         self.peek_prev().map(|v| v.remove())
971     }
972 }
973 
974 /// References the element in the list next to the cursor.
975 ///
976 /// # Invariants
977 ///
978 /// * `ptr` is an element in `self.cursor.list`.
979 /// * `ISNEXT == (self.ptr == self.cursor.next)`.
980 pub struct CursorPeek<'a, 'b, T: ?Sized + ListItem<ID>, const ISNEXT: bool, const ID: u64> {
981     cursor: &'a mut Cursor<'b, T, ID>,
982     ptr: *mut ListLinksFields,
983 }
984 
985 impl<'a, 'b, T: ?Sized + ListItem<ID>, const ISNEXT: bool, const ID: u64>
986     CursorPeek<'a, 'b, T, ISNEXT, ID>
987 {
988     /// Remove the element from the list.
remove(self) -> ListArc<T, ID>989     pub fn remove(self) -> ListArc<T, ID> {
990         if ISNEXT {
991             self.cursor.move_next();
992         }
993 
994         // INVARIANT: `self.ptr` is not equal to `self.cursor.next` due to the above `move_next`
995         // call.
996         // SAFETY: By the type invariants of `Self`, `next` is not null, so `next` is an element of
997         // `self.cursor.list` by the type invariants of `Cursor`.
998         unsafe { self.cursor.list.remove_internal(self.ptr) }
999     }
1000 
1001     /// Access this value as an [`ArcBorrow`].
arc(&self) -> ArcBorrow<'_, T>1002     pub fn arc(&self) -> ArcBorrow<'_, T> {
1003         // SAFETY: `self.ptr` points at an element in `self.cursor.list`.
1004         let me = unsafe { T::view_value(ListLinks::from_fields(self.ptr)) };
1005         // SAFETY:
1006         // * All values in a list are stored in an `Arc`.
1007         // * The value cannot be removed from the list for the duration of the lifetime annotated
1008         //   on the returned `ArcBorrow`, because removing it from the list would require mutable
1009         //   access to the `CursorPeek`, the `Cursor` or the `List`. However, the `ArcBorrow` holds
1010         //   an immutable borrow on the `CursorPeek`, which in turn holds a mutable borrow on the
1011         //   `Cursor`, which in turn holds a mutable borrow on the `List`, so any such mutable
1012         //   access requires first releasing the immutable borrow on the `CursorPeek`.
1013         // * Values in a list never have a `UniqueArc` reference, because the list has a `ListArc`
1014         //   reference, and `UniqueArc` references must be unique.
1015         unsafe { ArcBorrow::from_raw(me) }
1016     }
1017 }
1018 
1019 impl<'a, 'b, T: ?Sized + ListItem<ID>, const ISNEXT: bool, const ID: u64> core::ops::Deref
1020     for CursorPeek<'a, 'b, T, ISNEXT, ID>
1021 {
1022     // If you change the `ptr` field to have type `ArcBorrow<'a, T>`, it might seem like you could
1023     // get rid of the `CursorPeek::arc` method and change the deref target to `ArcBorrow<'a, T>`.
1024     // However, that doesn't work because 'a is too long. You could obtain an `ArcBorrow<'a, T>`
1025     // and then call `CursorPeek::remove` without giving up the `ArcBorrow<'a, T>`, which would be
1026     // unsound.
1027     type Target = T;
1028 
deref(&self) -> &T1029     fn deref(&self) -> &T {
1030         // SAFETY: `self.ptr` points at an element in `self.cursor.list`.
1031         let me = unsafe { T::view_value(ListLinks::from_fields(self.ptr)) };
1032 
1033         // SAFETY: The value cannot be removed from the list for the duration of the lifetime
1034         // annotated on the returned `&T`, because removing it from the list would require mutable
1035         // access to the `CursorPeek`, the `Cursor` or the `List`. However, the `&T` holds an
1036         // immutable borrow on the `CursorPeek`, which in turn holds a mutable borrow on the
1037         // `Cursor`, which in turn holds a mutable borrow on the `List`, so any such mutable access
1038         // requires first releasing the immutable borrow on the `CursorPeek`.
1039         unsafe { &*me }
1040     }
1041 }
1042 
1043 impl<'a, T: ?Sized + ListItem<ID>, const ID: u64> FusedIterator for Iter<'a, T, ID> {}
1044 
1045 impl<'a, T: ?Sized + ListItem<ID>, const ID: u64> IntoIterator for &'a List<T, ID> {
1046     type IntoIter = Iter<'a, T, ID>;
1047     type Item = ArcBorrow<'a, T>;
1048 
into_iter(self) -> Iter<'a, T, ID>1049     fn into_iter(self) -> Iter<'a, T, ID> {
1050         self.iter()
1051     }
1052 }
1053 
1054 /// An owning iterator into a [`List`].
1055 pub struct IntoIter<T: ?Sized + ListItem<ID>, const ID: u64 = 0> {
1056     list: List<T, ID>,
1057 }
1058 
1059 impl<T: ?Sized + ListItem<ID>, const ID: u64> Iterator for IntoIter<T, ID> {
1060     type Item = ListArc<T, ID>;
1061 
next(&mut self) -> Option<ListArc<T, ID>>1062     fn next(&mut self) -> Option<ListArc<T, ID>> {
1063         self.list.pop_front()
1064     }
1065 }
1066 
1067 impl<T: ?Sized + ListItem<ID>, const ID: u64> FusedIterator for IntoIter<T, ID> {}
1068 
1069 impl<T: ?Sized + ListItem<ID>, const ID: u64> DoubleEndedIterator for IntoIter<T, ID> {
next_back(&mut self) -> Option<ListArc<T, ID>>1070     fn next_back(&mut self) -> Option<ListArc<T, ID>> {
1071         self.list.pop_back()
1072     }
1073 }
1074 
1075 impl<T: ?Sized + ListItem<ID>, const ID: u64> IntoIterator for List<T, ID> {
1076     type IntoIter = IntoIter<T, ID>;
1077     type Item = ListArc<T, ID>;
1078 
into_iter(self) -> IntoIter<T, ID>1079     fn into_iter(self) -> IntoIter<T, ID> {
1080         IntoIter { list: self }
1081     }
1082 }
1083