Skip to contentSkip to conversation

rust: Add CList and GPU buddy allocator bindings

PATCH Superseded Joel Fernandes 4 participants 16 messages Feb 10 – Feb 20 1 message not in the archive

Subsystems (7)

v9 of 14 Superseded Latest is v14 →

lore
Share & tools
lore

Joel Fernandes

author reviewer
#0 lore raw

v9 cover rust: Add CList and GPU buddy allocator bindings

This series provides CList module for interfacing with linked lists, GPU buddy allocator bindings for physical memory management in nova-core and nova-core Kconfig change to select GPU_BUDDY.

The clist patch (patch 1) is independent and go through any tree. The other 2 patches depend on the DRM buddy code movement patch as a prerequisite, a version of which is now in drm-misc-next:
https://lore.kernel.org/all/[email protected]/

Based on linux-next.

The git tree with all patches can be found at:
git://git.kernel.org/pub/scm/linux/kernel/git/jfern/linux.git (tag: clist-gpu-buddy-v9-20260210)

Link to v8: https://lore.kernel.org/all/[email protected]/
Link to v7: https://lore.kernel.org/all/[email protected]/

Joel Fernandes (3):
rust: clist: Add support to interface with C linked lists
rust: gpu: Add GPU buddy allocator bindings
nova-core: mm: Select GPU_BUDDY for VRAM allocation

 MAINTAINERS                     |   7 +
 drivers/gpu/nova-core/Kconfig   |   3 +-
 rust/bindings/bindings_helper.h |  11 +
 rust/helpers/gpu.c              |  23 ++
 rust/helpers/helpers.c          |   2 +
 rust/helpers/list.c             |  17 +
 rust/kernel/clist.rs            | 320 +++++++++++++++++++
 rust/kernel/gpu/buddy.rs        | 537 ++++++++++++++++++++++++++++++++
 rust/kernel/gpu/mod.rs          |   5 +
 rust/kernel/lib.rs              |   3 +
 10 files changed, 927 insertions(+), 1 deletion(-)
 create mode 100644 rust/helpers/gpu.c
 create mode 100644 rust/helpers/list.c
 create mode 100644 rust/kernel/clist.rs
 create mode 100644 rust/kernel/gpu/buddy.rs
 create mode 100644 rust/kernel/gpu/mod.rs

base-commit: fd9678829d6dd0c10fde080b536abf4b1121c346
prerequisite-patch-id: 51e9eb2490026debebe75b8a0a9ce0c3991cd580

Signature · 1 line
2.34.1
author reviewer
#1 lore raw

PATCH v9 1/3 rust: clist: Add support to interface with C linked lists

Add a new module clist for working with C's doubly circular linked lists. Provide low-level iteration over list nodes.

Typed iteration over actual items is provided with a clist_create macro to assist in creation of the CList type.

---
 MAINTAINERS            |   7 +
 rust/helpers/helpers.c |   1 +
 rust/helpers/list.c    |  17 +++
 rust/kernel/clist.rs   | 320 +++++++++++++++++++++++++++++++++++++++++
 rust/kernel/lib.rs     |   1 +
 5 files changed, 346 insertions(+)
 create mode 100644 rust/helpers/list.c
 create mode 100644 rust/kernel/clist.rs
MAINTAINERS +7 -0
index 7cfb766112cd..b0050b478dc9 100644
@@ -23205,6 +23205,13 @@ S:	Maintained
 T:	git https://github.com/Rust-for-Linux/linux.git rust-analyzer-next
 F:	scripts/generate_rust_analyzer.py
 
+RUST TO C LIST INTERFACES
+M:	Joel Fernandes <[email protected]>
+M:	Alexandre Courbot <[email protected]>
+L:	[email protected]
+S:	Maintained
+F:	rust/kernel/clist.rs
+
 RXRPC SOCKETS (AF_RXRPC)
 M:	David Howells <[email protected]>
 M:	Marc Dionne <[email protected]>
rust/helpers/helpers.c +1 -0
index a3c42e51f00a..724fcb8240ac 100644
@@ -35,6 +35,7 @@
 #include "io.c"
 #include "jump_label.c"
 #include "kunit.c"
+#include "list.c"
 #include "maple_tree.c"
 #include "mm.c"
 #include "mutex.c"
rust/helpers/list.c new file +17 -0
new file mode 100644
index 000000000000..4c1f9c111ec8
@@ -0,0 +1,17 @@
+// SPDX-License-Identifier: GPL-2.0
+
+/*
+ * Helpers for C Circular doubly linked list implementation.
+ */
+
+#include <linux/list.h>
+
+__rust_helper void rust_helper_INIT_LIST_HEAD(struct list_head *list)
+{
+	INIT_LIST_HEAD(list);
+}
+
+__rust_helper void rust_helper_list_add_tail(struct list_head *new, struct list_head *head)
+{
+	list_add_tail(new, head);
+}
rust/kernel/clist.rs new file +320 -0

320 lines not on this page · raw message

rust/kernel/lib.rs +1 -0
index 3da92f18f4ee..fe711d34ca1e 100644
@@ -75,6 +75,7 @@
 pub mod bug;
 #[doc(hidden)]
 pub mod build_assert;
+pub mod clist;
 pub mod clk;
 #[cfg(CONFIG_CONFIGFS_FS)]
 pub mod configfs;
Signature · 1 line
2.34.1
maintainer
#2 lore raw

Re: [PATCH -next v9 1/3] rust: clist: Add support to interface with C linked lists

Quoted 9 lines · Joel Fernandes

Add a new module clist for working with C's doubly circular linked lists. Provide low-level iteration over list nodes.

Typed iteration over actual items is provided with a clist_create macro to assist in creation of the CList type.

I think you forgot to address my comments from [1].

[1] https://lore.kernel.org/all/[email protected]/

author reviewer
#3 lore raw

Re: [PATCH -next v9 1/3] rust: clist: Add support to interface with C linked lists

Quoted 7 lines · Danilo Krummrich
Quoted 6 lines · Joel Fernandes

Add a new module clist for working with C's doubly circular linked lists. Provide low-level iteration over list nodes.

Typed iteration over actual items is provided with a clist_create macro to assist in creation of the CList type.

Quoted 7 lines
Quoted 3 lines

I think you forgot to address my comments from [1].

[1] https://lore.kernel.org/all/[email protected]/

Indeed I missed that reply, sorry. Will address them.

Thanks.

--
Joel Fernandes

#4 lore raw

Re: [PATCH -next v9 1/3] rust: clist: Add support to interface with C linked lists

In reply to Joel Fernandes

I saw that v10 has been sent, but since the code is mostly identical this review should still apply (I was in the middle of writing it before going to sleep).

Quoted 55 lines · Joel Fernandes

Add a new module clist for working with C's doubly circular linked lists. Provide low-level iteration over list nodes.

Typed iteration over actual items is provided with a clist_create macro to assist in creation of the CList type.

---
 MAINTAINERS            |   7 +
 rust/helpers/helpers.c |   1 +
 rust/helpers/list.c    |  17 +++
 rust/kernel/clist.rs   | 320 +++++++++++++++++++++++++++++++++++++++++
 rust/kernel/lib.rs     |   1 +
 5 files changed, 346 insertions(+)
 create mode 100644 rust/helpers/list.c
 create mode 100644 rust/kernel/clist.rs
MAINTAINERS +7 -0
index 7cfb766112cd..b0050b478dc9 100644
@@ -23205,6 +23205,13 @@ S:	Maintained
 T:	git https://github.com/Rust-for-Linux/linux.git rust-analyzer-next
 F:	scripts/generate_rust_analyzer.py
 
+RUST TO C LIST INTERFACES
+M:	Joel Fernandes <[email protected]>
+M:	Alexandre Courbot <[email protected]>
+L:	[email protected]
+S:	Maintained
+F:	rust/kernel/clist.rs
+
 RXRPC SOCKETS (AF_RXRPC)
 M:	David Howells <[email protected]>
 M:	Marc Dionne <[email protected]>
rust/helpers/helpers.c +1 -0
index a3c42e51f00a..724fcb8240ac 100644
@@ -35,6 +35,7 @@
 #include "io.c"
 #include "jump_label.c"
 #include "kunit.c"
+#include "list.c"
 #include "maple_tree.c"
 #include "mm.c"
 #include "mutex.c"
rust/helpers/list.c new file +0 -0
new file mode 100644
index 000000000000..4c1f9c111ec8

rust/helpers/list.c line 4

Quoted 4 lines
rust/helpers/list.c new file +4 -0
@@ -0,0 +1,17 @@
+// SPDX-License-Identifier: GPL-2.0
+
+/*
+ * Helpers for C Circular doubly linked list implementation.

nit: "Circular" doesn't need a capital "C".

Quoted 52 lines
rust/helpers/list.c new file +13 -0
+ */
+
+#include <linux/list.h>
+
+__rust_helper void rust_helper_INIT_LIST_HEAD(struct list_head *list)
+{
+	INIT_LIST_HEAD(list);
+}
+
+__rust_helper void rust_helper_list_add_tail(struct list_head *new, struct list_head *head)
+{
+	list_add_tail(new, head);
+}
rust/kernel/clist.rs new file +33 -0
new file mode 100644
index 000000000000..8aa72b5d54be
@@ -0,0 +1,320 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! A C doubly circular intrusive linked list interface for rust code.
+//!
+//! # Examples
+//!
+//! ```
+//! use kernel::{
+//!     bindings,
+//!     clist_create,
+//!     types::Opaque, //
+//! };
+//! # // Create test list with values (0, 10, 20) - normally done by C code but it is
+//! # // emulated here for doctests using the C bindings.
+//! # use core::mem::MaybeUninit;
+//! #
+//! # /// C struct with embedded `list_head` (typically will be allocated by C code).
+//! # #[repr(C)]
+//! # pub struct SampleItemC {
+//! #     pub value: i32,
+//! #     pub link: bindings::list_head,
+//! # }
+//! #
+//! # let mut head = MaybeUninit::<bindings::list_head>::uninit();
+//! #
+//! # let head = head.as_mut_ptr();
+//! # // SAFETY: head and all the items are test objects allocated in this scope.
+//! # unsafe { bindings::INIT_LIST_HEAD(head) };
+//! #
+//! # let mut items = [
+//! #     MaybeUninit::<SampleItemC>::uninit(),
+//! #     MaybeUninit::<SampleItemC>::uninit(),
+//! #     MaybeUninit::<SampleItemC>::uninit(),

rust/kernel/clist.rs line 43

Quoted 10 lines
rust/kernel/clist.rs new file +10 -0
+//! # ];
+//! #
+//! # for (i, item) in items.iter_mut().enumerate() {
+//! #     let ptr = item.as_mut_ptr();
+//! #     // SAFETY: pointers are to allocated test objects with a list_head field.
+//! #     unsafe {
+//! #         (*ptr).value = i as i32 * 10;
+//! #         // &raw mut computes address of link directly as link is uninitialized.
+//! #         bindings::INIT_LIST_HEAD(&raw mut (*ptr).link);
+//! #         bindings::list_add_tail(&mut (*ptr).link, head);

Is the INIT_LIST_HEAD line needed? list_add_tail will immediately overwrite the initial values of ptr.link.

Quoted 13 lines
rust/kernel/clist.rs new file +13 -0
+//! #     }
+//! # }
+//!
+//! // Rust wrapper for the C struct.
+//! // The list item struct in this example is defined in C code as:
+//! //   struct SampleItemC {
+//! //       int value;
+//! //       struct list_head link;
+//! //   };
+//! //
+//! #[repr(transparent)]
+//! pub struct Item(Opaque<SampleItemC>);
+//!

rust/kernel/clist.rs line 66

Quoted 10 lines
rust/kernel/clist.rs new file +10 -0
+//! impl Item {
+//!     pub fn value(&self) -> i32 {
+//!         // SAFETY: [`Item`] has same layout as [`SampleItemC`].
+//!         unsafe { (*self.0.get()).value }
+//!     }
+//! }
+//!
+//! // Create typed [`CList`] from sentinel head.
+//! // SAFETY: head is valid, items are [`SampleItemC`] with embedded `link` field.
+//! let list = unsafe { clist_create!(head, Item, SampleItemC, link) };

head appears in the documentation for the first time here - it would help to make at least its declaration visible, or add a comment specifying its type.

Quoted 64 lines
rust/kernel/clist.rs new file +64 -0
+//!
+//! // Iterate directly over typed items.
+//! let mut found_0 = false;
+//! let mut found_10 = false;
+//! let mut found_20 = false;
+//!
+//! for item in list.iter() {
+//!     let val = item.value();
+//!     if val == 0 { found_0 = true; }
+//!     if val == 10 { found_10 = true; }
+//!     if val == 20 { found_20 = true; }
+//! }
+//!
+//! assert!(found_0 && found_10 && found_20);
+//! ```
+
+use core::{
+    iter::FusedIterator,
+    marker::PhantomData, //
+};
+
+use crate::{
+    bindings,
+    types::Opaque, //
+};
+
+use pin_init::{
+    pin_data,
+    pin_init,
+    PinInit //
+};
+
+/// Wraps a `list_head` object for use in intrusive linked lists.
+///
+/// # Invariants
+///
+/// - [`CListHead`] represents an allocated and valid `list_head` structure.
+#[pin_data]
+#[repr(transparent)]
+pub struct CListHead {
+    #[pin]
+    inner: Opaque<bindings::list_head>,
+}
+
+impl CListHead {
+    /// Create a `&CListHead` reference from a raw `list_head` pointer.
+    ///
+    /// # Safety
+    ///
+    /// - `ptr` must be a valid pointer to an allocated and initialized `list_head` structure.
+    /// - `ptr` must remain valid and unmodified for the lifetime `'a`.
+    /// - The list and all linked `list_head` nodes must not be modified by non-Rust code
+    ///   for the lifetime `'a`.
+    #[inline]
+    pub unsafe fn from_raw<'a>(ptr: *mut bindings::list_head) -> &'a Self {
+        // SAFETY:
+        // - [`CListHead`] has same layout as `list_head`.
+        // - `ptr` is valid and unmodified for 'a per caller guarantees.
+        unsafe { &*ptr.cast() }
+    }
+
+    /// Get the raw `list_head` pointer.
+    #[inline]
+    pub fn as_raw(&self) -> *mut bindings::list_head {

rust/kernel/clist.rs line 140

Quoted 10 lines
rust/kernel/clist.rs new file +10 -0
+        self.inner.get()
+    }
+
+    /// Get the next [`CListHead`] in the list.
+    #[inline]
+    pub fn next(&self) -> &Self {
+        let raw = self.as_raw();
+        // SAFETY:
+        // - `self.as_raw()` is valid per type invariants.
+        // - The `next` pointer is guaranteed to be non-NULL.

Safety nit: the SAFETY comment should mention what guarantees that next is non-NULL. Also the safety section of from_raw has 3 items, but this only justifies 2.

rust/kernel/clist.rs line 150

Quoted 10 lines
rust/kernel/clist.rs new file +10 -0
+        unsafe { Self::from_raw((*raw).next) }
+    }
+
+    /// Check if this node is linked in a list (not isolated).
+    #[inline]
+    pub fn is_linked(&self) -> bool {
+        let raw = self.as_raw();
+        // SAFETY: self.as_raw() is valid per type invariants.
+        unsafe { (*raw).next != raw && (*raw).prev != raw }
+    }

This will return true on a non-empty sentinel head - is that intended?

Since this is only used in CList::is_empty, and in the GPU buddy's is_empty method, is this the right name? The code also mirrors C's list_empty...

rust/kernel/clist.rs line 162

Quoted 12 lines
rust/kernel/clist.rs new file +12 -0
+
+    /// Pin-initializer that initializes the list head.
+    pub fn new() -> impl PinInit<Self> {
+        pin_init!(Self {
+            // SAFETY: `INIT_LIST_HEAD` initializes `slot` to a valid empty list.
+            inner <- Opaque::ffi_init(|slot| unsafe { bindings::INIT_LIST_HEAD(slot) }),
+        })
+    }
+}
+
+// SAFETY: [`CListHead`] can be sent to any thread.
+unsafe impl Send for CListHead {}

That safety comment is circular. I guess you mean to say that list_head can be sent to any thread?

Quoted 36 lines
rust/kernel/clist.rs new file +36 -0
+
+// SAFETY: [`CListHead`] can be shared among threads as it is not modified
+// by non-Rust code per safety requirements of [`CListHead::from_raw`].
+unsafe impl Sync for CListHead {}
+
+impl PartialEq for CListHead {
+    #[inline]
+    fn eq(&self, other: &Self) -> bool {
+        core::ptr::eq(self, other)
+    }
+}
+
+impl Eq for CListHead {}
+
+/// Low-level iterator over `list_head` nodes.
+///
+/// An iterator used to iterate over a C intrusive linked list (`list_head`). Caller has to
+/// perform conversion of returned [`CListHead`] to an item (using `container_of` macro or similar).
+///
+/// # Invariants
+///
+/// [`CListHeadIter`] is iterating over an allocated, initialized and valid list.
+struct CListHeadIter<'a> {
+    /// Current position in the list.
+    current: &'a CListHead,
+    /// The sentinel head (used to detect end of iteration).
+    sentinel: &'a CListHead,
+}
+
+impl<'a> Iterator for CListHeadIter<'a> {
+    type Item = &'a CListHead;
+
+    #[inline]
+    fn next(&mut self) -> Option<Self::Item> {
+        // Check if we've reached the sentinel (end of list).
+        if self.current == self.sentinel {

rust/kernel/clist.rs line 208

Quoted 10 lines
rust/kernel/clist.rs new file +10 -0
+            return None;
+        }
+
+        let item = self.current;
+        self.current = item.next();
+        Some(item)
+    }
+}
+
+impl<'a> FusedIterator for CListHeadIter<'a> {}

I asked this a couple of times ([1], [2]) but got no reply, so let me try again. :) Given that list_head is doubly-linked, can we also implement DoubleEndedIterator?

This can be done in a follow-up patch but should be there eventually as C lists are often parsed in both directions.

[1] https://lore.kernel.org/all/[email protected]/
[2] https://lore.kernel.org/all/[email protected]/

Quoted 24 lines
rust/kernel/clist.rs new file +24 -0
+
+/// A typed C linked list with a sentinel head.
+///
+/// A sentinel head represents the entire linked list and can be used for
+/// iteration over items of type `T`, it is not associated with a specific item.
+///
+/// The const generic `OFFSET` specifies the byte offset of the `list_head` field within
+/// the struct that `T` wraps.
+///
+/// # Invariants
+///
+/// - The [`CListHead`] is an allocated and valid sentinel C `list_head` structure.
+/// - `OFFSET` is the byte offset of the `list_head` field within the struct that `T` wraps.
+/// - All the list's `list_head` nodes are allocated and have valid next/prev pointers.
+#[repr(transparent)]
+pub struct CList<T, const OFFSET: usize>(CListHead, PhantomData<T>);
+
+impl<T, const OFFSET: usize> CList<T, OFFSET> {
+    /// Create a typed [`CList`] reference from a raw sentinel `list_head` pointer.
+    ///
+    /// # Safety
+    ///
+    /// - `ptr` must be a valid pointer to an allocated and initialized `list_head` structure
+    ///   representing a list sentinel.

rust/kernel/clist.rs line 242

Quoted 10 lines
rust/kernel/clist.rs new file +10 -0
+    /// - `ptr` must remain valid and unmodified for the lifetime `'a`.
+    /// - The list must contain items where the `list_head` field is at byte offset `OFFSET`.
+    /// - `T` must be `#[repr(transparent)]` over the C struct.
+    #[inline]
+    pub unsafe fn from_raw<'a>(ptr: *mut bindings::list_head) -> &'a Self {
+        // SAFETY:
+        // - [`CList`] has same layout as [`CListHead`] due to repr(transparent).
+        // - Caller guarantees `ptr` is a valid, sentinel `list_head` object.
+        unsafe { &*ptr.cast() }
+    }

IIUC you can call CListHead::from_raw here instead of repeating its code.

Quoted 21 lines
rust/kernel/clist.rs new file +21 -0
+
+    /// Check if the list is empty.
+    #[inline]
+    pub fn is_empty(&self) -> bool {
+        !self.0.is_linked()
+    }
+
+    /// Create an iterator over typed items.
+    #[inline]
+    pub fn iter(&self) -> CListIter<'_, T, OFFSET> {
+        let head = &self.0;
+        CListIter {
+            head_iter: CListHeadIter {
+                current: head.next(),
+                sentinel: head,
+            },
+            _phantom: PhantomData,
+        }
+    }
+}
+

rust/kernel/clist.rs line 273

Quoted 10 lines
rust/kernel/clist.rs new file +10 -0
+/// High-level iterator over typed list items.
+pub struct CListIter<'a, T, const OFFSET: usize> {
+    head_iter: CListHeadIter<'a>,
+    _phantom: PhantomData<&'a T>,
+}
+
+impl<'a, T, const OFFSET: usize> Iterator for CListIter<'a, T, OFFSET> {
+    type Item = &'a T;
+
+    fn next(&mut self) -> Option<Self::Item> {

This method is the only one not marked #[inline].

Quoted 37 lines
rust/kernel/clist.rs new file +37 -0
+        let head = self.head_iter.next()?;
+
+        // Convert to item using OFFSET.
+        // SAFETY: `item_ptr` calculation from `OFFSET` (calculated using offset_of!)
+        // is valid per invariants.
+        Some(unsafe { &*head.as_raw().byte_sub(OFFSET).cast::<T>() })
+    }
+}
+
+impl<'a, T, const OFFSET: usize> FusedIterator for CListIter<'a, T, OFFSET> {}
+
+/// Create a C doubly-circular linked list interface `CList` from a raw `list_head` pointer.
+///
+/// This macro creates a `CList<T, OFFSET>` that can iterate over items of type `$rust_type`
+/// linked via the `$field` field in the underlying C struct `$c_type`.
+///
+/// # Arguments
+///
+/// - `$head`: Raw pointer to the sentinel `list_head` object (`*mut bindings::list_head`).
+/// - `$rust_type`: Each item's rust wrapper type.
+/// - `$c_type`: Each item's C struct type that contains the embedded `list_head`.
+/// - `$field`: The name of the `list_head` field within the C struct.
+///
+/// # Safety
+///
+/// This is an unsafe macro. The caller must ensure:
+///
+/// - `$head` is a valid, initialized sentinel `list_head` pointing to a list that remains
+///   unmodified for the lifetime of the rust `CList`.
+/// - The list contains items of type `$c_type` linked via an embedded `$field`.
+/// - `$rust_type` is `#[repr(transparent)]` over `$c_type` or has compatible layout.
+///
+/// # Examples
+///
+/// Refer to the examples in this module's documentation.
+#[macro_export]
+macro_rules! clist_create {

rust/kernel/clist.rs line 320

Quoted 10 lines
rust/kernel/clist.rs new file +10 -0
+    ($head:expr, $rust_type:ty, $c_type:ty, $($field:tt).+) => {{
+        // Compile-time check that field path is a list_head.
+        let _: fn(*const $c_type) -> *const $crate::bindings::list_head =
+            |p| &raw const (*p).$($field).+;
+
+        // Calculate offset and create `CList`.
+        const OFFSET: usize = ::core::mem::offset_of!($c_type, $($field).+);
+        $crate::clist::CList::<$rust_type, OFFSET>::from_raw($head)
+    }};
+}

I find it difficult to remember which argument fits where in the macro's syntax (I have the same problem every time I need to use list_for_each_entry_safe for instance).

Since Rust macros let us be more creative, how about something like this:

    let list = unsafe { clist_create!(head => Item, SampleItemC.link) };

It makes it more obvious that we use head to iterate through a list of Items, using the link member of SampleItemC. There are probably better syntaxes; the above is just an example.

author reviewer
#5 lore raw

Re: [PATCH -next v9 1/3] rust: clist: Add support to interface with C linked lists

On Thu, 19 Feb 2026 09:35:31 +0900, Alexandre Courbot wrote:

[...]

Quoted 9 lines

I asked this a couple of times ([1], [2]) but got no reply, so let me try again. :) Given that list_head is doubly-linked, can we also implement DoubleEndedIterator?

This can be done in a follow-up patch but should be there eventually as C lists are often parsed in both directions.

[1] https://lore.kernel.org/all/[email protected]/
[2] https://lore.kernel.org/all/[email protected]/

There was a lot of redesign and you only mentioned it as an optional suggestion and there several higher priority comments.

Anyway, I disagree. I don't think there's a use case for DoubleEndedIterator at the moment -- none of the current users of clist need reverse iteration. I'd prefer to keep the interface minimal and add it when there's an actual need for it, rather than adding API surface that nobody uses. If a usecase comes up, we can always trivially add it.

(will look at other comments in the morning, its night for me).

Thanks,

Signature · 1 line
Joel Fernandes
#6 lore raw

Re: [PATCH -next v9 1/3] rust: clist: Add support to interface with C linked lists

Quoted 14 lines · Joel Fernandes

On Thu, 19 Feb 2026 09:35:31 +0900, Alexandre Courbot wrote:

[...]

Quoted 9 lines

I asked this a couple of times ([1], [2]) but got no reply, so let me try again. :) Given that list_head is doubly-linked, can we also implement DoubleEndedIterator?

This can be done in a follow-up patch but should be there eventually as C lists are often parsed in both directions.

[1] https://lore.kernel.org/all/[email protected]/
[2] https://lore.kernel.org/all/[email protected]/

Quoted 8 lines

There was a lot of redesign and you only mentioned it as an optional suggestion and there several higher priority comments.

Anyway, I disagree. I don't think there's a use case for DoubleEndedIterator at the moment -- none of the current users of clist need reverse iteration. I'd prefer to keep the interface minimal and add it when there's an actual need for it, rather than adding API surface that nobody uses. If a usecase comes up, we can always trivially add it.

It's a double-linked list still, and DoubleEndedIterator a standard Rust trait. Adding it now would spare us the trouble of deciding which tree takes the feature when it eventually lands.

But even without it the series still stands, so your call.

author reviewer
#7 lore raw

Re: [PATCH -next v9 1/3] rust: clist: Add support to interface with C linked lists

In reply to Alexandre Courbot
Quoted 3 lines · Alexandre Courbot

I saw that v10 has been sent, but since the code is mostly identical this review should still apply (I was in the middle of writing it before going to sleep).

Thanks for the thorough review, Alex! All comments addressed below.

Quoted 3 lines
Quoted 1 line

+ * Helpers for C Circular doubly linked list implementation.

nit: "Circular" doesn't need a capital "C".

Fixed.

Quoted 9 lines

rust/kernel/clist.rs line 43

Quoted 6 lines
rust/kernel/clist.rs new file +6 -0
+//! #     // SAFETY: pointers are to allocated test objects with a list_head field.
+//! #     unsafe {
+//! #         (*ptr).value = i as i32 * 10;
+//! #         // &raw mut computes address of link directly as link is uninitialized.
+//! #         bindings::INIT_LIST_HEAD(&raw mut (*ptr).link);
+//! #         bindings::list_add_tail(&mut (*ptr).link, head);

Is the INIT_LIST_HEAD line needed? list_add_tail will immediately overwrite the initial values of ptr.link.

Good point - list_add_tail does overwrite the link fields. However I'm keeping the INIT_LIST_HEAD call because the doctest is meant to show the full pattern of working with list_head from Rust, including proper initialization. Also, skipping it would mean calling list_add_tail on an uninitialized list_head, which while it works in practice (since list_add_tail overwrites both fields), feels wrong to demonstrate in an example.

Quoted 5 lines
Quoted 1 line

+//! let list = unsafe { clist_create!(head, Item, SampleItemC, link) };

head appears in the documentation for the first time here - it would help to make at least its declaration visible, or add a comment specifying its type.

The head declaration is in the hidden doctest setup code (marked with # ). Since it's setup code that would be done by C in practice, keeping it hidden seems right. The SAFETY comment on the clist_create! call now documents what head is.

Quoted 9 lines

rust/kernel/clist.rs line 242

Quoted 6 lines
rust/kernel/clist.rs new file +6 -0
+    pub unsafe fn from_raw<'a>(ptr: *mut bindings::list_head) -> &'a Self {
+        // SAFETY:
+        // - [`CList`] has same layout as [`CListHead`] due to repr(transparent).
+        // - Caller guarantees `ptr` is a valid, sentinel `list_head` object.
+        unsafe { &*ptr.cast() }
+    }

IIUC you can call CListHead::from_raw here instead of repeating its code.

CListHead::from_raw returns &CListHead, but we need &CList<T, OFFSET>. Since CList is repr(transparent) over CListHead, the direct ptr.cast() is the correct approach - we'd need an additional cast after CListHead::from_raw anyway, which would be more code, not less.

Quoted 3 lines
Quoted 1 line

+ fn next(&mut self) -> Option<Self::Item> {

This method is the only one not marked #[inline].

Added #[inline], thanks for catching that.

Quoted 5 lines
Quoted 1 line

+impl<'a> FusedIterator for CListHeadIter<'a> {}

I asked this a couple of times ([1], [2]) but got no reply, so let me try again. :) Given that list_head is doubly-linked, can we also implement DoubleEndedIterator?

Apologies for the missed replies! Yes, DoubleEndedIterator makes sense for doubly-linked lists. I'll add it as a follow-up patch since it requires a prev() method and some additional iterator state tracking.

Quoted 5 lines

rust/kernel/clist.rs line 162

Quoted 2 lines
rust/kernel/clist.rs new file +2 -0
+// SAFETY: [`CListHead`] can be sent to any thread.
+unsafe impl Send for CListHead {}

That safety comment is circular. I guess you mean to say that list_head can be sent to any thread?

Fixed. Updated to: "list_head contains no thread-bound state; it only holds next/prev pointers."

Quoted 4 lines

Since Rust macros let us be more creative, how about something like this:

    let list = unsafe { clist_create!(head => Item, SampleItemC.link) };

Interesting idea! For now I've kept the current comma-separated syntax but with the device.rs unsafe pattern:

clist_create!(unsafe { head, Item, SampleItemC, link })

This keeps consistency with other kernel macros. The unsafe { } block is the key improvement from Danilo's review. We can explore syntax sugar in a follow-up if desired.

Thanks,
Joel

author reviewer
#8 lore raw

Re: [PATCH -next v9 1/3] rust: clist: Add support to interface with C linked lists

Quoted 8 lines · Joel Fernandes
Quoted 4 lines
Quoted 1 line

+impl<'a> FusedIterator for CListHeadIter<'a> {}

I asked this a couple of times ([1], [2]) but got no reply, so let me try again. 🙂 Given that list_head is doubly-linked, can we also implement DoubleEndedIterator?

Apologies for the missed replies! Yes, DoubleEndedIterator makes sense for doubly-linked lists. I'll add it as a follow-up patch since it requires a prev() method and some additional iterator state tracking.

And looks like I am short of sleep, I replied yesterday night (now you know why I don't work at night :-D) saying we did not want to do the DoubleEndedIterator yet without a proper usecase for it. Anyway, the point is I wont do it in this series and file it away as "future patch" in my TODO :)

Signature · 1 line
Joel Fernandes
#9 lore raw

Re: [PATCH -next v9 1/3] rust: clist: Add support to interface with C linked lists

In reply to Joel Fernandes

On Fri Feb 20, 2026 at 12:29 AM JST, Joel Fernandes wrote:
<snip>

Quoted 7 lines
Quoted 7 lines
Quoted 6 lines
rust/kernel/clist.rs new file +6 -0
+    pub unsafe fn from_raw<'a>(ptr: *mut bindings::list_head) -> &'a Self {
+        // SAFETY:
+        // - [`CList`] has same layout as [`CListHead`] due to repr(transparent).
+        // - Caller guarantees `ptr` is a valid, sentinel `list_head` object.
+        unsafe { &*ptr.cast() }
+    }
Quoted 7 lines
Quoted 2 lines

IIUC you can call CListHead::from_raw here instead of repeating its code.

CListHead::from_raw returns &CListHead, but we need &CList<T, OFFSET>. Since CList is repr(transparent) over CListHead, the direct ptr.cast() is the correct approach - we'd need an additional cast after CListHead::from_raw anyway, which would be more code, not less.

Ah, in that case that works, yes.

Quoted 8 lines
Quoted 3 lines
Quoted 1 line

+ fn next(&mut self) -> Option<Self::Item> {

This method is the only one not marked #[inline].

Added #[inline], thanks for catching that.

Quoted 2 lines
Quoted 1 line

+impl<'a> FusedIterator for CListHeadIter<'a> {}

Quoted 7 lines
Quoted 3 lines

I asked this a couple of times ([1], [2]) but got no reply, so let me try again. :) Given that list_head is doubly-linked, can we also implement DoubleEndedIterator?

Apologies for the missed replies! Yes, DoubleEndedIterator makes sense for doubly-linked lists. I'll add it as a follow-up patch since it requires a prev() method and some additional iterator state tracking.

Mmm, I expected (without trying) that it would be trivial, but if it requires big changes to the iterator then let's consider that as a follow-up indeed to avoid delaying this series further.

author reviewer
#10 lore raw

PATCH v9 2/3 rust: gpu: Add GPU buddy allocator bindings

In reply to Joel Fernandes

Add safe Rust abstractions over the Linux kernel's GPU buddy allocator for physical memory management. The GPU buddy allocator implements a binary buddy system useful for GPU physical memory allocation. nova-core will use it for physical memory allocation.

---
 rust/bindings/bindings_helper.h |  11 +
 rust/helpers/gpu.c              |  23 ++
 rust/helpers/helpers.c          |   1 +
 rust/kernel/gpu/buddy.rs        | 537 ++++++++++++++++++++++++++++++++
 rust/kernel/gpu/mod.rs          |   5 +
 rust/kernel/lib.rs              |   2 +
 6 files changed, 579 insertions(+)
 create mode 100644 rust/helpers/gpu.c
 create mode 100644 rust/kernel/gpu/buddy.rs
 create mode 100644 rust/kernel/gpu/mod.rs
rust/bindings/bindings_helper.h +11 -0
index 083cc44aa952..dbb765a9fdbd 100644
@@ -29,6 +29,7 @@
 #include <linux/hrtimer_types.h>
 
 #include <linux/acpi.h>
+#include <linux/gpu_buddy.h>
 #include <drm/drm_device.h>
 #include <drm/drm_drv.h>
 #include <drm/drm_file.h>
@@ -146,6 +147,16 @@ const vm_flags_t RUST_CONST_HELPER_VM_MIXEDMAP = VM_MIXEDMAP;
 const vm_flags_t RUST_CONST_HELPER_VM_HUGEPAGE = VM_HUGEPAGE;
 const vm_flags_t RUST_CONST_HELPER_VM_NOHUGEPAGE = VM_NOHUGEPAGE;
 
+#if IS_ENABLED(CONFIG_GPU_BUDDY)
+const unsigned long RUST_CONST_HELPER_GPU_BUDDY_RANGE_ALLOCATION = GPU_BUDDY_RANGE_ALLOCATION;
+const unsigned long RUST_CONST_HELPER_GPU_BUDDY_TOPDOWN_ALLOCATION = GPU_BUDDY_TOPDOWN_ALLOCATION;
+const unsigned long RUST_CONST_HELPER_GPU_BUDDY_CONTIGUOUS_ALLOCATION =
+								GPU_BUDDY_CONTIGUOUS_ALLOCATION;
+const unsigned long RUST_CONST_HELPER_GPU_BUDDY_CLEAR_ALLOCATION = GPU_BUDDY_CLEAR_ALLOCATION;
+const unsigned long RUST_CONST_HELPER_GPU_BUDDY_CLEARED = GPU_BUDDY_CLEARED;
+const unsigned long RUST_CONST_HELPER_GPU_BUDDY_TRIM_DISABLE = GPU_BUDDY_TRIM_DISABLE;
+#endif
+
 #if IS_ENABLED(CONFIG_ANDROID_BINDER_IPC_RUST)
 #include "../../drivers/android/binder/rust_binder.h"
 #include "../../drivers/android/binder/rust_binder_events.h"
rust/helpers/gpu.c new file +23 -0
new file mode 100644
index 000000000000..38b1a4e6bef8
@@ -0,0 +1,23 @@
+// SPDX-License-Identifier: GPL-2.0
+
+#include <linux/gpu_buddy.h>
+
+#ifdef CONFIG_GPU_BUDDY
+
+__rust_helper u64 rust_helper_gpu_buddy_block_offset(const struct gpu_buddy_block *block)
+{
+	return gpu_buddy_block_offset(block);
+}
+
+__rust_helper unsigned int rust_helper_gpu_buddy_block_order(struct gpu_buddy_block *block)
+{
+	return gpu_buddy_block_order(block);
+}
+
+__rust_helper u64 rust_helper_gpu_buddy_block_size(struct gpu_buddy *mm,
+						   struct gpu_buddy_block *block)
+{
+	return gpu_buddy_block_size(mm, block);
+}
+
+#endif /* CONFIG_GPU_BUDDY */
rust/helpers/helpers.c +1 -0
index 724fcb8240ac..a53929ce52a3 100644
@@ -32,6 +32,7 @@
 #include "err.c"
 #include "irq.c"
 #include "fs.c"
+#include "gpu.c"
 #include "io.c"
 #include "jump_label.c"
 #include "kunit.c"
rust/kernel/gpu/buddy.rs new file +537 -0

537 lines not on this page · raw message

rust/kernel/gpu/mod.rs new file +5 -0
new file mode 100644
index 000000000000..8f25e6367edc
@@ -0,0 +1,5 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! GPU subsystem abstractions.
+
+pub mod buddy;
rust/kernel/lib.rs +2 -0
index fe711d34ca1e..02ec5b9b22c8 100644
@@ -98,6 +98,8 @@
 pub mod firmware;
 pub mod fmt;
 pub mod fs;
+#[cfg(CONFIG_GPU_BUDDY)]
+pub mod gpu;
 #[cfg(CONFIG_I2C = "y")]
 pub mod i2c;
 pub mod id_pool;
Signature · 1 line
2.34.1
author reviewer
#11 lore raw

PATCH v9 3/3 nova-core: mm: Select GPU_BUDDY for VRAM allocation

In reply to Joel Fernandes

nova-core will use the GPU buddy allocator for physical VRAM management. Enable it in Kconfig.

---
 drivers/gpu/nova-core/Kconfig | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/gpu/nova-core/Kconfig +2 -1
index 527920f9c4d3..6513007bf66f 100644
@@ -3,8 +3,9 @@ config NOVA_CORE
 	depends on 64BIT
 	depends on PCI
 	depends on RUST
-	select RUST_FW_LOADER_ABSTRACTIONS
 	select AUXILIARY_BUS
+	select GPU_BUDDY
+	select RUST_FW_LOADER_ABSTRACTIONS
 	default n
 	help
 	  Choose this if you want to build the Nova Core driver for Nvidia
Signature · 1 line
2.34.1
maintainer
#12 lore raw

Re: [PATCH -next v9 3/3] nova-core: mm: Select GPU_BUDDY for VRAM allocation

Quoted 13 lines · Joel Fernandes

nova-core will use the GPU buddy allocator for physical VRAM management. Enable it in Kconfig.

---
 drivers/gpu/nova-core/Kconfig | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/gpu/nova-core/Kconfig +0 -0
index 527920f9c4d3..6513007bf66f 100644

drivers/gpu/nova-core/Kconfig config NOVA_CORE · line 6

Quoted 4 lines
drivers/gpu/nova-core/Kconfig +0 -1
@@ -3,8 +3,9 @@ config NOVA_CORE
 	depends on 64BIT
 	depends on PCI
 	depends on RUST
-	select RUST_FW_LOADER_ABSTRACTIONS

I think moving this should be a separate patch.

Quoted 8 lines
drivers/gpu/nova-core/Kconfig +2 -0
 	select AUXILIARY_BUS
+	select GPU_BUDDY
+	select RUST_FW_LOADER_ABSTRACTIONS
 	default n
 	help
 	  Choose this if you want to build the Nova Core driver for Nvidia
Signature · 1 line
2.34.1
#13 lore raw

✗ Fi.CI.BUILD: failure for rust: Add CList and GPU buddy allocator bindings (rev3)

In reply to Joel Fernandes
== Series Details ==

== Series Details ==

Series: rust: Add CList and GPU buddy allocator bindings (rev3)
URL : https://patchwork.freedesktop.org/series/161236/
State : failure

== Summary ==

Error: patch https://patchwork.freedesktop.org/api/1.0/series/161236/revisions/3/mbox/ not applied
Applying: rust: clist: Add support to interface with C linked lists
error: sha1 information is lacking or useless (MAINTAINERS).
error: could not build fake ancestor
hint: Use 'git am --show-current-patch=diff' to see the failed patch
Patch failed at 0001 rust: clist: Add support to interface with C linked lists When you have resolved this problem, run "git am --continue".
If you prefer to skip this patch, run "git am --skip" instead.
To restore the original branch and stop patching, run "git am --abort".
Build failed, no error log produced