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