Skip to contentSkip to conversation

rust: Add CList and GPU buddy allocator bindings

PATCH Superseded Joel Fernandes 6 participants 21 messages Feb 9 – Feb 11

Subsystems (7)

v8 of 14 Superseded Latest is v14 →

lore
Share & tools
lore

Joel Fernandes

author reviewer
#0 lore raw

v8 cover rust: Add CList and GPU buddy allocator bindings

Changes from v7 to v8:

his series provides Rust infrastructure needed for nova-core memory management. 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.

v7->v8:
Various changes suggested by Danilo, Gary, Daniel. Added tags.
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   |   1 +
 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        | 530 ++++++++++++++++++++++++++++++++
 rust/kernel/gpu/mod.rs          |   5 +
 rust/kernel/lib.rs              |   3 +
 10 files changed, 919 insertions(+)
 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
Signature · 1 line
2.34.1
author reviewer
#1 lore raw

PATCH v8 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 900fc00b73e6..310bb479260c 100644
@@ -23204,6 +23204,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
#2 lore raw

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

kernel test robot noticed the following build errors:

Hi Joel,

kernel test robot noticed the following build errors:

[auto build test ERROR on next-20260209]

url:    https://github.com/intel-lab-lkp/linux/commits/Joel-Fernandes/rust-clist-Add-support-to-interface-with-C-linked-lists/20260210-054655
base:   next-20260209
patch link:    https://lore.kernel.org/r/20260209214246.2783990-2-joelagnelf%40nvidia.com
patch subject: [PATCH -next v8 1/3] rust: clist: Add support to interface with C linked lists
config: x86_64-rhel-9.4-rust (https://download.01.org/0day-ci/archive/20260210/[email protected]/config)
compiler: clang version 20.1.8 (https://github.com/llvm/llvm-project 87f0227cb60147a26a1eeb4fb06e3b505e9c7261)
rustc: rustc 1.88.0 (6b00bc388 2025-06-23)
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20260210/[email protected]/reproduce)

If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/

All errors (new ones prefixed by >>):

   PATH=/opt/cross/clang-20/bin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
   INFO PATH=/opt/cross/rustc-1.88.0-bindgen-0.72.1/cargo/bin:/opt/cross/clang-20/bin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
   /usr/bin/timeout -k 100 12h /usr/bin/make KCFLAGS=\ -fno-crash-diagnostics\ -Wno-error=return-type\ -Wreturn-type\ -funsigned-char\ -Wundef\ -falign-functions=64 W=1 --keep-going LLVM=1 -j32 -C source O=/kbuild/obj/consumer/x86_64-rhel-9.4-rust ARCH=x86_64 SHELL=/bin/bash rustfmtcheck 
   make: Entering directory '/kbuild/src/consumer'
   make[1]: Entering directory '/kbuild/obj/consumer/x86_64-rhel-9.4-rust'
   Diff in tools/perf/tests/workloads/code_with_type.rs:10:
    #[no_mangle]
    pub extern "C" fn test_rs(count: u32) {
   -    let mut b =  Buf { data1: 0, data2: String::from("data"), data3: 0};
   +    let mut b = Buf {
   +        data1: 0,
   +        data2: String::from("data"),
   +        data3: 0,
   +    };
    
        for _ in 1..count {
            b.data1 += 1;
>> Diff in rust/kernel/clist.rs:93:
    use pin_init::{
        pin_data,
        pin_init,
   -    PinInit //
   +    PinInit, //
    };
    
    /// Wraps a `list_head` object for use in intrusive linked lists.
>> Diff in rust/kernel/clist.rs:93:
    use pin_init::{
        pin_data,
        pin_init,
   -    PinInit //
   +    PinInit, //
    };
    
    /// Wraps a `list_head` object for use in intrusive linked lists.

make[2]: *** [Makefile:1903: rustfmt] Error 123
make[2]: Target 'rustfmtcheck' not remade because of errors. make[1]: Leaving directory '/kbuild/obj/consumer/x86_64-rhel-9.4-rust' make[1]: *** [Makefile:248: __sub-make] Error 2
make[1]: Target 'rustfmtcheck' not remade because of errors.
make: *** [Makefile:248: __sub-make] Error 2
make: Target 'rustfmtcheck' not remade because of errors.
make: Leaving directory '/kbuild/src/consumer'

Signature · 2 lines
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki
#3 lore raw

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

Quoted 11 lines · kernel test robot

Diff in tools/perf/tests/workloads/code_with_type.rs:10:

    #[no_mangle]
    pub extern "C" fn test_rs(count: u32) {
   -    let mut b =  Buf { data1: 0, data2: String::from("data"), data3: 0};
   +    let mut b = Buf {
   +        data1: 0,
   +        data2: String::from("data"),
   +        data3: 0,

+ };

This part is an independent issue that sadly got into the latest linux-next tag, so it can be ignored here:

https://lore.kernel.org/lkml/CANiq72mW=hcvUGt=WENRiYVeVbb2bnYzizE00Eo-MW3b_MwRrg@mail.gmail.com/

Cheers,
Miguel

maintainer
#4 lore raw

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

In reply to Joel Fernandes
Quoted 1 line · Joel Fernandes
 rust/kernel/clist.rs   | 320 +++++++++++++++++++++++++++++++++++++++++

I think we should move this under rust/kernel/ffi/ to make it obvious that this is FFI infrastructure.

rust/kernel/clist.rs line 3

Quoted 9 lines
rust/kernel/clist.rs new file +3 -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.

Here and in the struct documentation, I'd suggest to clearly point out the use-cases, i.e. that this infrastructure is for FFI use-cases only and should not be used otherwise in drivers, etc.

author reviewer
#5 lore raw

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

Quoted 6 lines · Danilo Krummrich
Quoted 1 line · Joel Fernandes
 rust/kernel/clist.rs   | 320 +++++++++++++++++++++++++++++++++++++++++

I think we should move this under rust/kernel/ffi/ to make it obvious that this is FFI infrastructure.

Quoted 13 lines

rust/kernel/clist.rs line 3

Quoted 9 lines
rust/kernel/clist.rs new file +3 -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.

Here and in the struct documentation, I'd suggest to clearly point out the use-cases, i.e. that this infrastructure is for FFI use-cases only and should not be used otherwise in drivers, etc

I am curious why we would not want to have drivers be able to use CList. I thought that was the point of making it pub at the module/item level as well. I think it is possible a rust driver may have a reference to a CList in the future.

But I will update the current usecase above, as you suggested, good point.

thanks,

- Joel

maintainer
#6 lore raw

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

Quoted 21 lines · Joel Fernandes
Quoted 6 lines · Danilo Krummrich
Quoted 1 line · Joel Fernandes
 rust/kernel/clist.rs   | 320 +++++++++++++++++++++++++++++++++++++++++

I think we should move this under rust/kernel/ffi/ to make it obvious that this is FFI infrastructure.

Quoted 13 lines

rust/kernel/clist.rs line 3

Quoted 9 lines
rust/kernel/clist.rs new file +3 -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.

Here and in the struct documentation, I'd suggest to clearly point out the use-cases, i.e. that this infrastructure is for FFI use-cases only and should not be used otherwise in drivers, etc

Quoted 4 lines

I am curious why we would not want to have drivers be able to use CList. I thought that was the point of making it pub at the module/item level as well. I think it is possible a rust driver may have a reference to a CList in the future.

It is a (partially) unsafe API built to support FFI interactions. The absolute majority of drivers should not have any FFI interactions themselves. nova-core is the "odd one" as it will have an interface with a C driver (vGPU).

Besides a few "odd" drivers, there may be quite some subsystem abstractions that become users of the API. In the future build system, subsystems and drivers will become individual crates.

Quoted 1 line

But I will update the current usecase above, as you suggested, good point.

reviewer Reviewed-by on v8 1/3
#7 lore raw

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

In reply to Joel Fernandes

Hi Joel,

Quoted 11 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.

Sorry for not replying to your question on v7, I’ve been a bit sick recently.

author reviewer
#8 lore raw

PATCH v8 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        | 530 ++++++++++++++++++++++++++++++++
 rust/kernel/gpu/mod.rs          |   5 +
 rust/kernel/lib.rs              |   2 +
 6 files changed, 572 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 +530 -0

530 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
#9 lore raw

Re: [PATCH -next v8 2/3] rust: gpu: Add GPU buddy allocator bindings

kernel test robot noticed the following build errors:

Hi Joel,

kernel test robot noticed the following build errors:

[auto build test ERROR on next-20260209]

url:    https://github.com/intel-lab-lkp/linux/commits/Joel-Fernandes/rust-clist-Add-support-to-interface-with-C-linked-lists/20260210-054655
base:   next-20260209
patch link:    https://lore.kernel.org/r/20260209214246.2783990-3-joelagnelf%40nvidia.com
patch subject: [PATCH -next v8 2/3] rust: gpu: Add GPU buddy allocator bindings
config: x86_64-rhel-9.4-rust (https://download.01.org/0day-ci/archive/20260210/[email protected]/config)
compiler: clang version 20.1.8 (https://github.com/llvm/llvm-project 87f0227cb60147a26a1eeb4fb06e3b505e9c7261)
rustc: rustc 1.88.0 (6b00bc388 2025-06-23)
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20260210/[email protected]/reproduce)

If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/

All errors (new ones prefixed by >>):

>> rust/bindings/bindings_helper.h:32:10: fatal error: 'linux/gpu_buddy.h' file not found
>> Unable to generate bindings: clang diagnosed error: rust/bindings/bindings_helper.h:32:10: fatal error: 'linux/gpu_buddy.h' file not found
--
>> rust/helpers/gpu.c:3:10: fatal error: 'linux/gpu_buddy.h' file not found
>> Unable to generate bindings: clang diagnosed error: rust/helpers/gpu.c:3:10: fatal error: 'linux/gpu_buddy.h' file not found
--
   In file included from rust/helpers/helpers.c:35:
>> rust/helpers/gpu.c:3:10: fatal error: 'linux/gpu_buddy.h' file not found

3 | #include <linux/gpu_buddy.h>
| ^~~~~~~~~~~~~~~~~~~
1 error generated.

vim +32 rust/bindings/bindings_helper.h

    30	
    31	#include <linux/acpi.h>
  > 32	#include <linux/gpu_buddy.h>
    33	#include <drm/drm_device.h>
    34	#include <drm/drm_drv.h>
    35	#include <drm/drm_file.h>
    36	#include <drm/drm_gem.h>
    37	#include <drm/drm_ioctl.h>
    38	#include <kunit/test.h>
    39	#include <linux/auxiliary_bus.h>
    40	#include <linux/bitmap.h>
    41	#include <linux/blk-mq.h>
    42	#include <linux/blk_types.h>
    43	#include <linux/blkdev.h>
    44	#include <linux/clk.h>
    45	#include <linux/completion.h>
    46	#include <linux/configfs.h>
    47	#include <linux/cpu.h>
    48	#include <linux/cpufreq.h>
    49	#include <linux/cpumask.h>
    50	#include <linux/cred.h>
    51	#include <linux/debugfs.h>
    52	#include <linux/device/faux.h>
    53	#include <linux/dma-direction.h>
    54	#include <linux/dma-mapping.h>
    55	#include <linux/errname.h>
    56	#include <linux/ethtool.h>
    57	#include <linux/fdtable.h>
    58	#include <linux/file.h>
    59	#include <linux/firmware.h>
    60	#include <linux/fs.h>
    61	#include <linux/i2c.h>
    62	#include <linux/interrupt.h>
    63	#include <linux/io-pgtable.h>
    64	#include <linux/ioport.h>
    65	#include <linux/jiffies.h>
    66	#include <linux/jump_label.h>
    67	#include <linux/mdio.h>
    68	#include <linux/mm.h>
    69	#include <linux/miscdevice.h>
    70	#include <linux/of_device.h>
    71	#include <linux/pci.h>
    72	#include <linux/phy.h>
    73	#include <linux/pid_namespace.h>
    74	#include <linux/platform_device.h>
    75	#include <linux/pm_opp.h>
    76	#include <linux/poll.h>
    77	#include <linux/property.h>
    78	#include <linux/pwm.h>
    79	#include <linux/random.h>
    80	#include <linux/refcount.h>
    81	#include <linux/regulator/consumer.h>
    82	#include <linux/sched.h>
    83	#include <linux/security.h>
    84	#include <linux/slab.h>
    85	#include <linux/sys_soc.h>
    86	#include <linux/task_work.h>
    87	#include <linux/tracepoint.h>
    88	#include <linux/usb.h>
    89	#include <linux/wait.h>
    90	#include <linux/workqueue.h>
    91	#include <linux/xarray.h>
    92	#include <trace/events/rust_sample.h>
    93	
Signature · 2 lines
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki
maintainer
#10 lore raw

Re: [PATCH -next v8 2/3] rust: gpu: Add GPU buddy allocator bindings

In reply to Joel Fernandes

On Mon Feb 9, 2026 at 10:42 PM CET, Joel Fernandes wrote:

[...]

Quoted 1 line

+//! params.size_bytes = SZ_8M as u64;

It looks there are ~30 occurences of as u64 in this example code, which seems quite inconvinient for drivers.

In nova-core I proposed to have FromSafeCast / IntoSafeCast for usize, u32 and u64, which would help here as well, once factored out.

But even this seems pretty annoying. I wonder if we should just have separate 64-bit size constants, as they'd be pretty useful in other places as well, e.g. GPUVM.

Quoted 8 lines
rust/kernel/gpu/buddy.rs new file +8 -0
+/// Inner structure holding the actual buddy allocator.
+///
+/// # Synchronization
+///
+/// The C `gpu_buddy` API requires synchronization (see `include/linux/gpu_buddy.h`).
+/// The internal [`GpuBuddyGuard`] ensures that the lock is held for all
+/// allocator and free operations, preventing races between concurrent allocations
+/// and the freeing that occurs when [`AllocatedBlocks`] is dropped.

rust/kernel/gpu/buddy.rs line 242

Quoted 10 lines
rust/kernel/gpu/buddy.rs new file +10 -0
+///
+/// # Invariants
+///
+/// The inner [`Opaque`] contains a valid, initialized buddy allocator.
+#[pin_data(PinnedDrop)]
+struct GpuBuddyInner {
+    #[pin]
+    inner: Opaque<bindings::gpu_buddy>,
+    #[pin]
+    lock: Mutex<()>,

Why don't we have the mutex around the Opaque<bindings::gpu_buddy>? It's the only field the mutex does protect.

Is it because mutex does not take an impl PinInit? If so, we should add a comment with a proper TODO.

rust/kernel/gpu/buddy.rs line 253

Quoted 11 lines
rust/kernel/gpu/buddy.rs new file +11 -0
+    /// Base offset for all allocations (does not change after init).
+    base_offset: u64,
+    /// Cached chunk size (does not change after init).
+    chunk_size: u64,
+    /// Cached total size (does not change after init).
+    size: u64,
+}
+
+impl GpuBuddyInner {
+    /// Create a pin-initializer for the buddy allocator.
+    fn new(params: &GpuBuddyParams) -> impl PinInit<Self, Error> {

I think we can just pass them by value, they shouldn't be needed anymore after the GpuBuddy instance has been constructed.

Quoted 16 lines
rust/kernel/gpu/buddy.rs new file +16 -0
+        let base_offset = params.base_offset_bytes;
+        let size = params.physical_memory_size_bytes;
+        let chunk_size = params.chunk_size_bytes;
+
+        try_pin_init!(Self {
+            inner <- Opaque::try_ffi_init(|ptr| {
+                // SAFETY: ptr points to valid uninitialized memory from the pin-init
+                // infrastructure. gpu_buddy_init will initialize the structure.
+                to_result(unsafe { bindings::gpu_buddy_init(ptr, size, chunk_size) })
+            }),
+            lock <- new_mutex!(()),
+            base_offset: base_offset,
+            chunk_size: chunk_size,
+            size: size,
+        })
+    }

<snip>

Quoted 6 lines
rust/kernel/gpu/buddy.rs new file +6 -0
+/// GPU buddy allocator instance.
+///
+/// This structure wraps the C `gpu_buddy` allocator using reference counting.
+/// The allocator is automatically cleaned up when all references are dropped.
+///
+/// # Invariants

rust/kernel/gpu/buddy.rs line 331

Quoted 10 lines
rust/kernel/gpu/buddy.rs new file +10 -0
+///
+/// The inner [`Arc`] points to a valid, initialized GPU buddy allocator.
+pub struct GpuBuddy(Arc<GpuBuddyInner>);
+
+impl GpuBuddy {
+    /// Create a new buddy allocator.
+    ///
+    /// Creates a buddy allocator that manages a contiguous address space of the given
+    /// size, with the specified minimum allocation unit (chunk_size must be at least 4KB).
+    pub fn new(params: &GpuBuddyParams) -> Result<Self> {

Same here, we should be able to take this by value.

Quoted 5 lines
rust/kernel/gpu/buddy.rs new file +5 -0
+        Ok(Self(Arc::pin_init(
+            GpuBuddyInner::new(params),
+            GFP_KERNEL,
+        )?))
+    }

<snip>

rust/kernel/gpu/buddy.rs line 367

Quoted 8 lines
rust/kernel/gpu/buddy.rs new file +8 -0
+    /// Allocate blocks from the buddy allocator.
+    ///
+    /// Returns an [`Arc<AllocatedBlocks>`] structure that owns the allocated blocks
+    /// and automatically frees them when all references are dropped.
+    ///
+    /// Takes `&self` instead of `&mut self` because the internal [`Mutex`] provides
+    /// synchronization - no external `&mut` exclusivity needed.
+    pub fn alloc_blocks(&self, params: &GpuBuddyAllocParams) -> Result<Arc<AllocatedBlocks>> {

Why do we force a reference count here? I think we should just return impl PinInit<AllocatedBlocks, Error> and let the driver decide where to initialize the object, no?

I.e. what if the driver wants to store additional data in a driver private structure? Then we'd need two allocations otherwise and another reference count in the worst case.

Quoted 29 lines
rust/kernel/gpu/buddy.rs new file +29 -0
+        let buddy_arc = Arc::clone(&self.0);
+
+        // Create pin-initializer that initializes list and allocates blocks.
+        let init = try_pin_init!(AllocatedBlocks {
+            buddy: Arc::clone(&buddy_arc),
+            list <- CListHead::new(),
+            flags: params.buddy_flags,
+            _: {
+                // Lock while allocating to serialize with concurrent frees.
+                let guard = buddy.lock();
+
+                // SAFETY: `guard` provides exclusive access to the buddy allocator.
+                to_result(unsafe {
+                    bindings::gpu_buddy_alloc_blocks(
+                        guard.as_raw(),
+                        params.start_range_address,
+                        params.end_range_address,
+                        params.size_bytes,
+                        params.min_block_size_bytes,
+                        list.as_raw(),
+                        params.buddy_flags.as_raw(),
+                    )
+                })?
+            }
+        });
+
+        Arc::pin_init(init, GFP_KERNEL)
+    }
+}
author reviewer
#11 lore raw

Re: [PATCH -next v8 2/3] rust: gpu: Add GPU buddy allocator bindings

Hi Danilo,

Thanks for the review!

Quoted 9 lines · Danilo Krummrich

On Mon Feb 9, 2026 at 10:42 PM CET, Joel Fernandes wrote:

[...]

Quoted 1 line

+//! params.size_bytes = SZ_8M as u64;

It looks there are ~30 occurences of as u64 in this example code, which seems quite inconvinient for drivers.

Quoted 6 lines

In nova-core I proposed to have FromSafeCast / IntoSafeCast for usize, u32 and u64, which would help here as well, once factored out.

But even this seems pretty annoying. I wonder if we should just have separate 64-bit size constants, as they'd be pretty useful in other places as well, e.g. GPUVM.

Agreed, the as u64 casts are verbose. Note that these are only in the doc examples -- actual driver code (e.g. nova-core) already uses FromSafeCast/IntoSafeCast from your nova-core patches [1]. Once those traits are factored out of nova-core into a shared kernel crate location, I can update the examples to use them instead.

Since the doc examples live outside nova-core, I suggest let us keep it as using as for now. Thoughts?

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

Quoted 10 lines

rust/kernel/gpu/buddy.rs line 242

Quoted 6 lines
rust/kernel/gpu/buddy.rs new file +6 -0
+#[pin_data(PinnedDrop)]
+struct GpuBuddyInner {
+    #[pin]
+    inner: Opaque<bindings::gpu_buddy>,
+    #[pin]
+    lock: Mutex<()>,

Why don't we have the mutex around the Opaque<bindings::gpu_buddy>? It's the only field the mutex does protect.

Quoted 2 lines

Is it because mutex does not take an impl PinInit? If so, we should add a comment with a proper TODO.

Correct, that is the reason. I'll add a TODO comment in the next version explaining this limitation.

Quoted 6 lines

rust/kernel/gpu/buddy.rs line 253

Quoted 3 lines
rust/kernel/gpu/buddy.rs new file +3 -0
+impl GpuBuddyInner {
+    /// Create a pin-initializer for the buddy allocator.
+    fn new(params: &GpuBuddyParams) -> impl PinInit<Self, Error> {

I think we can just pass them by value, they shouldn't be needed anymore after the GpuBuddy instance has been constructed.

Dave Airlie specifically reviewed this in RFC v6 and recommended passing by reference rather than by value [2]:

"maybe we should pass them as non-mutable references, but I don't think
there is any point in passing them by value ever."

The params are also reused in practice -- the doc examples show the same GpuBuddyParams being used repeatedly. References
avoid unnecessary copies for this reuse pattern.

[2] https://lore.kernel.org/all/CAPM=9tyL_Cq3+qWc4A41p7eqnNDLS1APUEeUbaQyJ46YDkipVw@mail.gmail.com/

Quoted 3 lines
Quoted 1 line

+ pub fn new(params: &GpuBuddyParams) -> Result<Self> {

Same here, we should be able to take this by value.

Same reasoning as above.

Quoted 9 lines
Quoted 1 line

+ pub fn alloc_blocks(&self, params: &GpuBuddyAllocParams) -> Result<Arc<AllocatedBlocks>> {

Why do we force a reference count here? I think we should just return impl PinInit<AllocatedBlocks, Error> and let the driver decide where to initialize the object, no?

I.e. what if the driver wants to store additional data in a driver private structure? Then we'd need two allocations otherwise and another reference count in the worst case.

Good point. The reason I had Arc was to anticipate potential shared ownership use cases, but at the moment there is no such use case
in nova-core -- each AllocatedBlocks has a single owner.

I'll change this to return impl PinInit<AllocatedBlocks, Error> in the next version. If a shared ownership use case arises later, we
can always add an Arc-returning convenience wrapper.

For the nova-core side, the field would change from KVec<Arc<AllocatedBlocks>> to KVec<Pin<KBox<AllocatedBlocks>>>, which works fine I think.

Signature · 1 line
Joel Fernandes
maintainer
#12 lore raw

Re: [PATCH -next v8 2/3] rust: gpu: Add GPU buddy allocator bindings

Quoted 10 lines · Joel Fernandes
Quoted 6 lines

rust/kernel/gpu/buddy.rs line 253

Quoted 3 lines
rust/kernel/gpu/buddy.rs new file +3 -0
+impl GpuBuddyInner {
+    /// Create a pin-initializer for the buddy allocator.
+    fn new(params: &GpuBuddyParams) -> impl PinInit<Self, Error> {

I think we can just pass them by value, they shouldn't be needed anymore after the GpuBuddy instance has been constructed.

Dave Airlie specifically reviewed this in RFC v6 and recommended passing by reference rather than by value [2]:

Quoted 6 lines

"maybe we should pass them as non-mutable references, but I don't think
there is any point in passing them by value ever."

The params are also reused in practice -- the doc examples show the same GpuBuddyParams being used repeatedly. References
avoid unnecessary copies for this reuse pattern.

Well, that's for GpuBuddyAllocParams, those are indeed reused and shouldn't be copied all the time.

But my comment was about GpuBuddyParams, I don't see a reason those are reused (neither are they in the example), so it makes more sense to pass them by value, such that they are consumed. (I.e. I'm not asking for adding Copy/Clone.)

Quoted 15 lines

[2] https://lore.kernel.org/all/CAPM=9tyL_Cq3+qWc4A41p7eqnNDLS1APUEeUbaQyJ46YDkipVw@mail.gmail.com/

Quoted 3 lines
Quoted 1 line

+ pub fn new(params: &GpuBuddyParams) -> Result<Self> {

Same here, we should be able to take this by value.

Same reasoning as above.

Quoted 6 lines
Quoted 1 line

+ pub fn alloc_blocks(&self, params: &GpuBuddyAllocParams) -> Result<Arc<AllocatedBlocks>> {

Why do we force a reference count here? I think we should just return impl PinInit<AllocatedBlocks, Error> and let the driver decide where to initialize the object, no?

Quoted 7 lines
Quoted 3 lines

I.e. what if the driver wants to store additional data in a driver private structure? Then we'd need two allocations otherwise and another reference count in the worst case.

Good point. The reason I had Arc was to anticipate potential shared ownership use cases, but at the moment there is no such use case
in nova-core -- each AllocatedBlocks has a single owner.

Sure, but drivers can always pass an impl PinInit to Arc::pin_init() themselves.

Quoted 3 lines

I'll change this to return impl PinInit<AllocatedBlocks, Error> in the next version. If a shared ownership use case arises later, we
can always add an Arc-returning convenience wrapper.

I don't think we should, don't give drivers a reason to go for more allocations they actually need for convinience.

author reviewer
#13 lore raw

Re: [PATCH -next v8 2/3] rust: gpu: Add GPU buddy allocator bindings

Agreed with all these comments, will revise accordingly.

Thanks.

Quoted 58 lines · Danilo Krummrich
Quoted 10 lines · Joel Fernandes
Quoted 6 lines

rust/kernel/gpu/buddy.rs line 253

Quoted 3 lines
rust/kernel/gpu/buddy.rs new file +3 -0
+impl GpuBuddyInner {
+    /// Create a pin-initializer for the buddy allocator.
+    fn new(params: &GpuBuddyParams) -> impl PinInit<Self, Error> {

I think we can just pass them by value, they shouldn't be needed anymore after the GpuBuddy instance has been constructed.

Dave Airlie specifically reviewed this in RFC v6 and recommended passing by reference rather than by value [2]:

Quoted 6 lines

"maybe we should pass them as non-mutable references, but I don't think
there is any point in passing them by value ever."

The params are also reused in practice -- the doc examples show the same GpuBuddyParams being used repeatedly. References
avoid unnecessary copies for this reuse pattern.

Well, that's for GpuBuddyAllocParams, those are indeed reused and shouldn't be copied all the time.

But my comment was about GpuBuddyParams, I don't see a reason those are reused (neither are they in the example), so it makes more sense to pass them by value, such that they are consumed. (I.e. I'm not asking for adding Copy/Clone.)

Quoted 15 lines

[2] https://lore.kernel.org/all/CAPM=9tyL_Cq3+qWc4A41p7eqnNDLS1APUEeUbaQyJ46YDkipVw@mail.gmail.com/

Quoted 3 lines
Quoted 1 line

+ pub fn new(params: &GpuBuddyParams) -> Result<Self> {

Same here, we should be able to take this by value.

Same reasoning as above.

Quoted 6 lines
Quoted 1 line

+ pub fn alloc_blocks(&self, params: &GpuBuddyAllocParams) -> Result<Arc<AllocatedBlocks>> {

Why do we force a reference count here? I think we should just return impl PinInit<AllocatedBlocks, Error> and let the driver decide where to initialize the object, no?

Quoted 7 lines
Quoted 3 lines

I.e. what if the driver wants to store additional data in a driver private structure? Then we'd need two allocations otherwise and another reference count in the worst case.

Good point. The reason I had Arc was to anticipate potential shared ownership use cases, but at the moment there is no such use case
in nova-core -- each AllocatedBlocks has a single owner.

Sure, but drivers can always pass an impl PinInit to Arc::pin_init() themselves.

Quoted 3 lines

I'll change this to return impl PinInit<AllocatedBlocks, Error> in the next version. If a shared ownership use case arises later, we
can always add an Arc-returning convenience wrapper.

I don't think we should, don't give drivers a reason to go for more allocations they actually need for convinience.

author reviewer
#14 lore raw

Re: [PATCH -next v8 2/3] rust: gpu: Add GPU buddy allocator bindings

In reply to Danilo Krummrich
Quoted 6 lines · Danilo Krummrich
Quoted 3 lines

I'll change this to return impl PinInit<AllocatedBlocks, Error> in the next version. If a shared ownership use case arises later, we
can always add an Arc-returning convenience wrapper.

I don't think we should, don't give drivers a reason to go for more allocations they actually need for convinience.

I wasn't implying to give reason to go for more allocations, it is about a reference to the same allocation that may be required to be shared from multiple objects for whatever reason. But again, currently we don't have a use case for that.

Signature · 1 line
Joel Fernandes
maintainer
#15 lore raw

Re: [PATCH -next v8 2/3] rust: gpu: Add GPU buddy allocator bindings

Quoted 3 lines · Joel Fernandes

I wasn't implying to give reason to go for more allocations, it is about a reference to the same allocation that may be required to be shared from multiple objects for whatever reason. But again, currently we don't have a use case for that.

Sure, I just mentioned it since returning an Arc instead of an impl PinInit removes the option for drivers to embed additional driver specific data into the same allocation, i.e. it might set the wrong incentive.

author reviewer
#16 lore raw

Re: [PATCH -next v8 2/3] rust: gpu: Add GPU buddy allocator bindings

Quoted 8 lines · Danilo Krummrich
Quoted 3 lines · Joel Fernandes

I wasn't implying to give reason to go for more allocations, it is about a reference to the same allocation that may be required to be shared from multiple objects for whatever reason. But again, currently we don't have a use case for that.

Sure, I just mentioned it since returning an Arc instead of an impl PinInit removes the option for drivers to embed additional driver specific data into the same allocation, i.e. it might set the wrong incentive.

Makes sense, thanks!

--
Joel Fernandes

#17 lore raw

Re: [PATCH -next v8 2/3] rust: gpu: Add GPU buddy allocator bindings

In reply to Joel Fernandes
kernel test robot noticed the following build errors:

Hi Joel,

kernel test robot noticed the following build errors:

[auto build test ERROR on next-20260209]

url:    https://github.com/intel-lab-lkp/linux/commits/Joel-Fernandes/rust-clist-Add-support-to-interface-with-C-linked-lists/20260210-054655
base:   next-20260209
patch link:    https://lore.kernel.org/r/20260209214246.2783990-3-joelagnelf%40nvidia.com
patch subject: [PATCH -next v8 2/3] rust: gpu: Add GPU buddy allocator bindings
config: x86_64-buildonly-randconfig-001-20260210 (https://download.01.org/0day-ci/archive/20260210/[email protected]/config)
compiler: clang version 20.1.8 (https://github.com/llvm/llvm-project 87f0227cb60147a26a1eeb4fb06e3b505e9c7261)
rustc: rustc 1.88.0 (6b00bc388 2025-06-23)
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20260210/[email protected]/reproduce)

If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/

All errors (new ones prefixed by >>):

In file included from rust/helpers/helpers.c:35:

>> rust/helpers/gpu.c:3:10: fatal error: 'linux/gpu_buddy.h' file not found
   3 | #include <linux/gpu_buddy.h>
   |          ^~~~~~~~~~~~~~~~~~~
   1 error generated.
   make[3]: *** [rust/Makefile:640: rust/helpers/helpers.o] Error 1 shuffle=1268030489
>> rust/helpers/gpu.c:3:10: fatal error: 'linux/gpu_buddy.h' file not found
>> Unable to generate bindings: clang diagnosed error: rust/helpers/gpu.c:3:10: fatal error: 'linux/gpu_buddy.h' file not found
--
   make[3]: *** [rust/Makefile:496: rust/bindings/bindings_helpers_generated.rs] Error 1 shuffle=1268030489
   make[3]: *** Deleting file 'rust/bindings/bindings_helpers_generated.rs'
>> rust/bindings/bindings_helper.h:32:10: fatal error: 'linux/gpu_buddy.h' file not found
>> Unable to generate bindings: clang diagnosed error: rust/bindings/bindings_helper.h:32:10: fatal error: 'linux/gpu_buddy.h' file not found

vim +3 rust/helpers/gpu.c

     2	
   > 3	#include <linux/gpu_buddy.h>
     4	
Signature · 2 lines
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki
author reviewer
#18 lore raw

PATCH v8 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 | 1 +
 1 file changed, 1 insertion(+)
drivers/gpu/nova-core/Kconfig +1 -0
index 527920f9c4d3..c129764daa23 100644
@@ -3,6 +3,7 @@ config NOVA_CORE
 	depends on 64BIT
 	depends on PCI
 	depends on RUST
+	select GPU_BUDDY
 	select RUST_FW_LOADER_ABSTRACTIONS
 	select AUXILIARY_BUS
 	default n
Signature · 1 line
2.34.1
maintainer
#19 lore raw

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

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

Quoted 12 lines · Joel Fernandes
drivers/gpu/nova-core/Kconfig +1 -0
index 527920f9c4d3..c129764daa23 100644
@@ -3,6 +3,7 @@ config NOVA_CORE
 	depends on 64BIT
 	depends on PCI
 	depends on RUST
+	select GPU_BUDDY
 	select RUST_FW_LOADER_ABSTRACTIONS
 	select AUXILIARY_BUS
 	default n

NIT: Let's get the 'select' list ordered. :)

#20 lore raw

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

In reply to Joel Fernandes
== Series Details ==

== Series Details ==

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

== Summary ==

Error: patch https://patchwork.freedesktop.org/api/1.0/series/161236/revisions/2/mbox/ not applied
Applying: rust: clist: Add support to interface with C linked lists
Using index info to reconstruct a base tree...
M MAINTAINERS
M rust/helpers/helpers.c
M rust/kernel/lib.rs
Falling back to patching base and 3-way merge...
Auto-merging rust/kernel/lib.rs
Auto-merging rust/helpers/helpers.c
Auto-merging MAINTAINERS
CONFLICT (content): Merge conflict in MAINTAINERS
error: Failed to merge in the changes.
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