// SPDX-License-Identifier: GPL-2.012//! Rust interface for C doubly circular intrusive linked lists.3//!4//! This module provides Rust abstractions for iterating over C `list_head`-based5//! linked lists. It should only be used for cases where C and Rust code share6//! direct access to the same linked list through a C interop interface.7//!8//! Note: This *must not* be used by Rust components that just need a linked list9//! primitive. Use [`kernel::list::List`] instead.10//!11//! # Examples12//!13//! ```14//! use kernel::{15//! bindings,16//! interop::list::clist_create,17//! types::Opaque,18//! };19//! # // Create test list with values (0, 10, 20) - normally done by C code but it is20//! # // emulated here for doctests using the C bindings.21//! # use core::mem::MaybeUninit;22//! #23//! # /// C struct with embedded `list_head` (typically will be allocated by C code).24//! # #[repr(C)]25//! # pub struct SampleItemC {26//! # pub value: i32,27//! # pub link: bindings::list_head,28//! # }29//! #30//! # let mut head = MaybeUninit::<bindings::list_head>::uninit();31//! #32//! # let head = head.as_mut_ptr();33//! # // SAFETY: `head` and all the items are test objects allocated in this scope.34//! # unsafe { bindings::INIT_LIST_HEAD(head) };35//! #36//! # let mut items = [37//! # MaybeUninit::<SampleItemC>::uninit(),38//! # MaybeUninit::<SampleItemC>::uninit(),39//! # MaybeUninit::<SampleItemC>::uninit(),40//! # ];41//! #42//! # for (i, item) in items.iter_mut().enumerate() {43//! # let ptr = item.as_mut_ptr();44//! # // SAFETY: `ptr` points to a valid `MaybeUninit<SampleItemC>`.45//! # unsafe { (*ptr).value = i as i32 * 10 };46//! # // SAFETY: `&raw mut` creates a pointer valid for `INIT_LIST_HEAD`.47//! # unsafe { bindings::INIT_LIST_HEAD(&raw mut (*ptr).link) };48//! # // SAFETY: `link` was just initialized and `head` is a valid list head.49//! # unsafe { bindings::list_add_tail(&mut (*ptr).link, head) };50//! # }51//!52//! /// Rust wrapper for the C struct.53//! ///54//! /// The list item struct in this example is defined in C code as:55//! ///56//! /// ```c57//! /// struct SampleItemC {58//! /// int value;59//! /// struct list_head link;60//! /// };61//! /// ```62//! #[repr(transparent)]63//! pub struct Item(Opaque<SampleItemC>);64//!65//! impl Item {66//! pub fn value(&self) -> i32 {67//! // SAFETY: `Item` has the same layout as `SampleItemC`.68//! unsafe { (*self.0.get()).value }69//! }70//! }71//!72//! // Create typed [`CList`] from sentinel head.73//! // SAFETY: `head` is valid and initialized, items are `SampleItemC` with74//! // embedded `link` field, and `Item` is `#[repr(transparent)]` over `SampleItemC`.75//! let list = unsafe { clist_create!(head, Item, SampleItemC, link) };76//!77//! // Iterate directly over typed items.78//! let mut found_0 = false;79//! let mut found_10 = false;80//! let mut found_20 = false;81//!82//! for item in list.iter() {83//! let val = item.value();84//! if val == 0 { found_0 = true; }85//! if val == 10 { found_10 = true; }86//! if val == 20 { found_20 = true; }87//! }88//!89//! assert!(found_0 && found_10 && found_20);90//! ```9192use core::{93iter::FusedIterator,94marker::PhantomData, //95};9697use crate::{98bindings,99types::Opaque, //100};101102use pin_init::{103pin_data,104pin_init,105PinInit, //106};107108/// FFI wrapper for a C `list_head` object used in intrusive linked lists.109///110/// # Invariants111///112/// - The underlying `list_head` is initialized with valid non-`NULL` `next`/`prev` pointers.113#[pin_data]114#[repr(transparent)]115pub struct CListHead {116#[pin]117inner: Opaque<bindings::list_head>,118}119120impl CListHead {121/// Create a `&CListHead` reference from a raw `list_head` pointer.122///123/// # Safety124///125/// - `ptr` must be a valid pointer to an initialized `list_head` (e.g. via126/// `INIT_LIST_HEAD()`), with valid non-`NULL` `next`/`prev` pointers.127/// - `ptr` must remain valid for the lifetime `'a`.128/// - The list and all linked `list_head` nodes must not be modified from129/// anywhere for the lifetime `'a`, unless done so via any [`CListHead`] APIs.130#[inline]131pub unsafe fn from_raw<'a>(ptr: *mut bindings::list_head) -> &'a Self {132// SAFETY:133// - `CListHead` has the same layout as `list_head`.134// - `ptr` is valid and unmodified for `'a` per caller guarantees.135unsafe { &*ptr.cast() }136}137138/// Get the raw `list_head` pointer.139#[inline]140pub fn as_raw(&self) -> *mut bindings::list_head {141self.inner.get()142}143144/// Get the next [`CListHead`] in the list.145#[inline]146pub fn next(&self) -> &Self {147let raw = self.as_raw();148// SAFETY:149// - `self.as_raw()` is valid and initialized per type invariants.150// - The `next` pointer is valid and non-`NULL` per type invariants151// (initialized via `INIT_LIST_HEAD()` or equivalent).152unsafe { Self::from_raw((*raw).next) }153}154155/// Check if this node is linked in a list (not isolated).156#[inline]157pub fn is_linked(&self) -> bool {158let raw = self.as_raw();159// SAFETY: `self.as_raw()` is valid per type invariants.160unsafe { (*raw).next != raw && (*raw).prev != raw }161}162163/// Returns a pin-initializer for the list head.164pub fn new() -> impl PinInit<Self> {165pin_init!(Self {166// SAFETY: `INIT_LIST_HEAD` initializes `slot` to a valid empty list.167inner <- Opaque::ffi_init(|slot| unsafe { bindings::INIT_LIST_HEAD(slot) }),168})169}170}171172// SAFETY: `list_head` contains no thread-bound state; it only holds173// `next`/`prev` pointers.174unsafe impl Send for CListHead {}175176// SAFETY: `CListHead` can be shared among threads as modifications are177// not allowed at the moment.178unsafe impl Sync for CListHead {}179180impl PartialEq for CListHead {181#[inline]182fn eq(&self, other: &Self) -> bool {183core::ptr::eq(self, other)184}185}186187impl Eq for CListHead {}188189/// Low-level iterator over `list_head` nodes.190///191/// An iterator used to iterate over a C intrusive linked list (`list_head`). The caller has to192/// perform conversion of returned [`CListHead`] to an item (using [`container_of`] or similar).193///194/// # Invariants195///196/// `current` and `sentinel` are valid references into an initialized linked list.197struct CListHeadIter<'a> {198/// Current position in the list.199current: &'a CListHead,200/// The sentinel head (used to detect end of iteration).201sentinel: &'a CListHead,202}203204impl<'a> Iterator for CListHeadIter<'a> {205type Item = &'a CListHead;206207#[inline]208fn next(&mut self) -> Option<Self::Item> {209// Check if we've reached the sentinel (end of list).210if self.current == self.sentinel {211return None;212}213214let item = self.current;215self.current = item.next();216Some(item)217}218}219220impl<'a> FusedIterator for CListHeadIter<'a> {}221222/// A typed C linked list with a sentinel head intended for FFI use-cases where223/// a C subsystem manages a linked list that Rust code needs to read. Generally224/// required only for special cases.225///226/// A sentinel head [`CListHead`] represents the entire linked list and can be used227/// for iteration over items of type `T`; it is not associated with a specific item.228///229/// The const generic `OFFSET` specifies the byte offset of the `list_head` field within230/// the struct that `T` wraps.231///232/// # Invariants233///234/// - The sentinel [`CListHead`] has valid non-`NULL` `next`/`prev` pointers.235/// - `OFFSET` is the byte offset of the `list_head` field within the struct that `T` wraps.236/// - All the list's `list_head` nodes have valid non-`NULL` `next`/`prev` pointers.237#[repr(transparent)]238pub struct CList<T, const OFFSET: usize>(CListHead, PhantomData<T>);239240impl<T, const OFFSET: usize> CList<T, OFFSET> {241/// Create a typed [`CList`] reference from a raw sentinel `list_head` pointer.242///243/// # Safety244///245/// - `ptr` must be a valid pointer to an initialized sentinel `list_head` (e.g. via246/// `INIT_LIST_HEAD()`), with valid non-`NULL` `next`/`prev` pointers.247/// - `ptr` must remain valid for the lifetime `'a`.248/// - The list and all linked nodes must not be concurrently modified for the lifetime `'a`.249/// - The list must contain items where the `list_head` field is at byte offset `OFFSET`.250/// - `T` must be `#[repr(transparent)]` over the C struct.251#[inline]252pub unsafe fn from_raw<'a>(ptr: *mut bindings::list_head) -> &'a Self {253// SAFETY:254// - `CList` has the same layout as `CListHead` due to `#[repr(transparent)]`.255// - Caller guarantees `ptr` is a valid, sentinel `list_head` object.256unsafe { &*ptr.cast() }257}258259/// Check if the list is empty.260#[inline]261pub fn is_empty(&self) -> bool {262!self.0.is_linked()263}264265/// Create an iterator over typed items.266#[inline]267pub fn iter(&self) -> CListIter<'_, T, OFFSET> {268let head = &self.0;269CListIter {270head_iter: CListHeadIter {271current: head.next(),272sentinel: head,273},274_phantom: PhantomData,275}276}277}278279/// High-level iterator over typed list items.280pub struct CListIter<'a, T, const OFFSET: usize> {281head_iter: CListHeadIter<'a>,282_phantom: PhantomData<&'a T>,283}284285impl<'a, T, const OFFSET: usize> Iterator for CListIter<'a, T, OFFSET> {286type Item = &'a T;287288#[inline]289fn next(&mut self) -> Option<Self::Item> {290let head = self.head_iter.next()?;291292// Convert to item using `OFFSET`.293//294// SAFETY: The pointer calculation is valid because `OFFSET` is derived295// from `offset_of!` per type invariants.296Some(unsafe { &*head.as_raw().byte_sub(OFFSET).cast::<T>() })297}298}299300impl<'a, T, const OFFSET: usize> FusedIterator for CListIter<'a, T, OFFSET> {}301302/// Create a C doubly-circular linked list interface [`CList`] from a raw `list_head` pointer.303///304/// This macro creates a `CList<T, OFFSET>` that can iterate over items of type `$rust_type`305/// linked via the `$field` field in the underlying C struct `$c_type`.306///307/// # Arguments308///309/// - `$head`: Raw pointer to the sentinel `list_head` object (`*mut bindings::list_head`).310/// - `$rust_type`: Each item's Rust wrapper type.311/// - `$c_type`: Each item's C struct type that contains the embedded `list_head`.312/// - `$field`: The name of the `list_head` field within the C struct.313///314/// # Safety315///316/// The caller must ensure:317///318/// - `$head` is a valid, initialized sentinel `list_head` (e.g. via `INIT_LIST_HEAD()`)319/// pointing to a list that is not concurrently modified for the lifetime of the [`CList`].320/// - The list contains items of type `$c_type` linked via an embedded `$field`.321/// - `$rust_type` is `#[repr(transparent)]` over `$c_type` or has compatible layout.322///323/// # Examples324///325/// Refer to the examples in the [`crate::interop::list`] module documentation.326#[macro_export]327macro_rules! clist_create {328($head:expr, $rust_type:ty, $c_type:ty, $($field:tt).+) => {{329// Compile-time check that field path is a `list_head`.330let _: fn(*const $c_type) -> *const $crate::bindings::list_head =331|p| &raw const (*p).$($field).+;332333// Calculate offset and create `CList`.334const OFFSET: usize = ::core::mem::offset_of!($c_type, $($field).+);335$crate::interop::list::CList::<$rust_type, OFFSET>::from_raw($head)336}};337}338pub use clist_create;339340341