Skip to contentSkip to conversation

Preparatory patches for nova-core memory management

PATCH Superseded Joel Fernandes 9 participants 74 messages Feb 18 – Mar 1

Subsystems (12)

v10 of 14 Superseded Latest is v14 →

lore
Share & tools
lore

Joel Fernandes

author reviewer
#0 lore raw

v10 cover Preparatory patches for nova-core memory management

These are initial preparatory patches needed for nova-core memory management support. The series moves the DRM buddy allocator one level up so it can be shared across GPU subsystems, adds Rust FFI and clist bindings, and creates Rust GPU buddy allocator bindings.

The clist/ffi patches are ready, reviewed by Gary and Danilo. Miguel, can you pull those via the rust tree?

The non-Rust DRM buddy related patches are already being pulled into upstream by Dave Airlie but I have included them here as they are needed for the rest of the patches (thanks to Dave for reworking them so they applied).

I will post the nova-core memory management patches as a separate follow-up series just after this one.

The git tree with all these patches can be found at:
git://git.kernel.org/pub/scm/linux/kernel/git/jfern/linux.git (tag: nova/mm)

Joel Fernandes (7):
gpu: Move DRM buddy allocator one level up (part one)
gpu: Move DRM buddy allocator one level up (part two)
rust: ffi: Convert pub use to pub mod and create ffi module
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
nova-core: Kconfig: Sort select statements alphabetically

Koen Koning (1):
gpu: Fix uninitialized buddy for built-in drivers

 Documentation/gpu/drm-mm.rst                  |   10 +-
 MAINTAINERS                                   |   15 +-
 drivers/gpu/Kconfig                           |   13 +
 drivers/gpu/Makefile                          |    3 +-
 drivers/gpu/buddy.c                           | 1322 +++++++++++++++++
 drivers/gpu/drm/Kconfig                       |    5 +-
 drivers/gpu/drm/Kconfig.debug                 |    1 -
 drivers/gpu/drm/Makefile                      |    1 -
 drivers/gpu/drm/amd/amdgpu/amdgpu_ras.c       |    2 +-
 .../gpu/drm/amd/amdgpu/amdgpu_res_cursor.h    |   12 +-
 drivers/gpu/drm/amd/amdgpu/amdgpu_vram_mgr.c  |   79 +-
 drivers/gpu/drm/amd/amdgpu/amdgpu_vram_mgr.h  |   20 +-
 drivers/gpu/drm/drm_buddy.c                   | 1277 +---------------
 drivers/gpu/drm/i915/gem/i915_gem_ttm.c       |    2 +-
 drivers/gpu/drm/i915/i915_scatterlist.c       |   10 +-
 drivers/gpu/drm/i915/i915_ttm_buddy_manager.c |   55 +-
 drivers/gpu/drm/i915/i915_ttm_buddy_manager.h |    4 +-
 .../drm/i915/selftests/intel_memory_region.c  |   20 +-
 drivers/gpu/drm/tests/Makefile                |    1 -
 drivers/gpu/drm/tests/drm_exec_test.c         |    2 -
 drivers/gpu/drm/tests/drm_mm_test.c           |    2 -
 .../gpu/drm/ttm/tests/ttm_bo_validate_test.c  |    4 +-
 drivers/gpu/drm/ttm/tests/ttm_mock_manager.c  |   18 +-
 drivers/gpu/drm/ttm/tests/ttm_mock_manager.h  |    4 +-
 drivers/gpu/drm/xe/xe_res_cursor.h            |   34 +-
 drivers/gpu/drm/xe/xe_svm.c                   |   12 +-
 drivers/gpu/drm/xe/xe_ttm_vram_mgr.c          |   71 +-
 drivers/gpu/drm/xe/xe_ttm_vram_mgr_types.h    |    4 +-
 drivers/gpu/nova-core/Kconfig                 |    3 +-
 drivers/gpu/tests/Makefile                    |    4 +
 .../gpu_buddy_test.c}                         |  416 +++---
 .../lib/drm_random.c => tests/gpu_random.c}   |   18 +-
 .../lib/drm_random.h => tests/gpu_random.h}   |   18 +-
 drivers/video/Kconfig                         |    1 +
 include/drm/drm_buddy.h                       |  163 +-
 include/linux/gpu_buddy.h                     |  177 +++
 rust/bindings/bindings_helper.h               |   11 +
 rust/helpers/gpu.c                            |   23 +
 rust/helpers/helpers.c                        |    2 +
 rust/helpers/list.c                           |   17 +
 rust/kernel/ffi/clist.rs                      |  327 ++++
 rust/kernel/ffi/mod.rs                        |    9 +
 rust/kernel/gpu/buddy.rs                      |  537 +++++++
 rust/kernel/gpu/mod.rs                        |    5 +
 rust/kernel/lib.rs                            |    5 +-
 45 files changed, 2893 insertions(+), 1846 deletions(-)
 create mode 100644 drivers/gpu/Kconfig
 create mode 100644 drivers/gpu/buddy.c
 create mode 100644 drivers/gpu/tests/Makefile
 rename drivers/gpu/{drm/tests/drm_buddy_test.c => tests/gpu_buddy_test.c} (67%)
 rename drivers/gpu/{drm/lib/drm_random.c => tests/gpu_random.c} (59%)
 rename drivers/gpu/{drm/lib/drm_random.h => tests/gpu_random.h} (53%)
 create mode 100644 include/linux/gpu_buddy.h
 create mode 100644 rust/helpers/gpu.c
 create mode 100644 rust/helpers/list.c
 create mode 100644 rust/kernel/ffi/clist.rs
 create mode 100644 rust/kernel/ffi/mod.rs
 create mode 100644 rust/kernel/gpu/buddy.rs
 create mode 100644 rust/kernel/gpu/mod.rs

Cc: Nikola Djukic <[email protected]>
base-commit: 2961f841b025fb234860bac26dfb7fa7cb0fb122

Signature · 1 line
2.34.1
author reviewer
#1 lore raw

PATCH v10 1/8 gpu: Move DRM buddy allocator one level up (part one)

Move the DRM buddy allocator one level up so that it can be used by GPU drivers (example, nova-core) that have usecases other than DRM (such as VFIO vGPU support). Modify the API, structures and Kconfigs to use "gpu_buddy" terminology. Adapt the drivers and tests to use the new API.

The commit cannot be split due to bisectability, however no functional change is intended. Verified by running K-UNIT tests and build tested various configurations.

[airlied: I've split this into two so git can find copies easier. I've also just nuked drm_random library, that stuff needs to be done elsewhere and only the buddy tests seem to be using it].

---
 Documentation/gpu/drm-mm.rst                                | 6 +++---
 drivers/gpu/Makefile                                        | 2 +-
 drivers/gpu/{drm/drm_buddy.c => buddy.c}                    | 2 +-
 drivers/gpu/drm/Kconfig                                     | 4 ----
 drivers/gpu/drm/Kconfig.debug                               | 1 -
 drivers/gpu/drm/Makefile                                    | 3 +--
 drivers/gpu/drm/amd/amdgpu/amdgpu_vram_mgr.h                | 2 +-
 drivers/gpu/drm/i915/gem/i915_gem_ttm.c                     | 2 +-
 drivers/gpu/drm/i915/i915_scatterlist.c                     | 2 +-
 drivers/gpu/drm/i915/i915_ttm_buddy_manager.c               | 2 +-
 drivers/gpu/drm/tests/Makefile                              | 1 -
 drivers/gpu/drm/tests/drm_exec_test.c                       | 2 --
 drivers/gpu/drm/tests/drm_mm_test.c                         | 2 --
 drivers/gpu/drm/ttm/tests/ttm_mock_manager.h                | 2 +-
 drivers/gpu/drm/xe/xe_ttm_vram_mgr_types.h                  | 2 +-
 drivers/gpu/tests/Makefile                                  | 4 ++++
 .../{drm/tests/drm_buddy_test.c => tests/gpu_buddy_test.c}  | 4 ++--
 drivers/gpu/{drm/lib/drm_random.c => tests/gpu_random.c}    | 2 +-
 drivers/gpu/{drm/lib/drm_random.h => tests/gpu_random.h}    | 0
 include/{drm/drm_buddy.h => linux/gpu_buddy.h}              | 0
 20 files changed, 19 insertions(+), 26 deletions(-)
 rename drivers/gpu/{drm/drm_buddy.c => buddy.c} (99%)
 create mode 100644 drivers/gpu/tests/Makefile
 rename drivers/gpu/{drm/tests/drm_buddy_test.c => tests/gpu_buddy_test.c} (99%)
 rename drivers/gpu/{drm/lib/drm_random.c => tests/gpu_random.c} (97%)
 rename drivers/gpu/{drm/lib/drm_random.h => tests/gpu_random.h} (100%)
 rename include/{drm/drm_buddy.h => linux/gpu_buddy.h} (100%)
Documentation/gpu/drm-mm.rst +3 -3
index f22433470c76..ceee0e663237 100644
@@ -526,10 +526,10 @@ DRM GPUVM Function References
 DRM Buddy Allocator
 ===================
 
-DRM Buddy Function References
------------------------------
+Buddy Allocator Function References (GPU buddy)
+-----------------------------------------------
 
-.. kernel-doc:: drivers/gpu/drm/drm_buddy.c
+.. kernel-doc:: drivers/gpu/buddy.c
    :export:
 
 DRM Cache Handling and Fast WC memcpy()
drivers/gpu/Makefile +1 -1
index 36a54d456630..c5292ee2c852 100644
@@ -2,7 +2,7 @@
 # drm/tegra depends on host1x, so if both drivers are built-in care must be
 # taken to initialize them in the correct order. Link order is the only way
 # to ensure this currently.
-obj-y			+= host1x/ drm/ vga/
+obj-y			+= host1x/ drm/ vga/ tests/
 obj-$(CONFIG_IMX_IPUV3_CORE)	+= ipu-v3/
 obj-$(CONFIG_TRACE_GPU_MEM)		+= trace/
 obj-$(CONFIG_NOVA_CORE)		+= nova-core/
drivers/gpu/buddy.c renamed from drivers/gpu/drm/drm_buddy.c +1 -1
similarity index 99%
rename from drivers/gpu/drm/drm_buddy.c
rename to drivers/gpu/buddy.c
index fd34d3755f7c..4cc63d961d26 100644
@@ -10,7 +10,7 @@
 #include <linux/module.h>
 #include <linux/sizes.h>
 
-#include <drm/drm_buddy.h>
+#include <linux/gpu_buddy.h>
 #include <drm/drm_print.h>
 
 enum drm_buddy_free_tree {
drivers/gpu/drm/Kconfig +0 -4
index d3d52310c9cc..ca2a2801e77f 100644
@@ -269,10 +269,6 @@ config DRM_SCHED
 config DRM_PANEL_BACKLIGHT_QUIRKS
 	tristate
 
-config DRM_LIB_RANDOM
-	bool
-	default n
-
 config DRM_PRIVACY_SCREEN
 	bool
 	default n
drivers/gpu/drm/Kconfig.debug +0 -1
index 05dc43c0b8c5..3b7886865335 100644
@@ -69,7 +69,6 @@ config DRM_KUNIT_TEST
 	select DRM_EXPORT_FOR_TESTS if m
 	select DRM_GEM_SHMEM_HELPER
 	select DRM_KUNIT_TEST_HELPERS
-	select DRM_LIB_RANDOM
 	select DRM_SYSFB_HELPER
 	select PRIME_NUMBERS
 	default KUNIT_ALL_TESTS
drivers/gpu/drm/Makefile +1 -2
index ec2c5ff82382..5c86bc908955 100644
@@ -78,7 +78,6 @@ drm-$(CONFIG_DRM_CLIENT) += \
 	drm_client_event.o \
 	drm_client_modeset.o \
 	drm_client_sysrq.o
-drm-$(CONFIG_DRM_LIB_RANDOM) += lib/drm_random.o
 drm-$(CONFIG_COMPAT) += drm_ioc32.o
 drm-$(CONFIG_DRM_PANEL) += drm_panel.o
 drm-$(CONFIG_OF) += drm_of.o
@@ -114,7 +113,7 @@ drm_gpusvm_helper-$(CONFIG_ZONE_DEVICE) += \
 
 obj-$(CONFIG_DRM_GPUSVM) += drm_gpusvm_helper.o
 
-obj-$(CONFIG_DRM_BUDDY) += drm_buddy.o
+obj-$(CONFIG_DRM_BUDDY) += ../buddy.o
 
 drm_dma_helper-y := drm_gem_dma_helper.o
 drm_dma_helper-$(CONFIG_DRM_FBDEV_EMULATION) += drm_fbdev_dma.o
drivers/gpu/drm/amd/amdgpu/amdgpu_vram_mgr.h +1 -1
index 5f5fd9a911c2..874779618056 100644
@@ -24,7 +24,7 @@
 #ifndef __AMDGPU_VRAM_MGR_H__
 #define __AMDGPU_VRAM_MGR_H__
 
-#include <drm/drm_buddy.h>
+#include <linux/gpu_buddy.h>
 
 struct amdgpu_vram_mgr {
 	struct ttm_resource_manager manager;
drivers/gpu/drm/i915/gem/i915_gem_ttm.c +1 -1
index f65fe86c02b5..eeda5daa544f 100644
@@ -5,7 +5,7 @@
 
 #include <linux/shmem_fs.h>
 
-#include <drm/drm_buddy.h>
+#include <linux/gpu_buddy.h>
 #include <drm/drm_print.h>
 #include <drm/ttm/ttm_placement.h>
 #include <drm/ttm/ttm_tt.h>
drivers/gpu/drm/i915/i915_scatterlist.c +1 -1
index 4d830740946d..30246f02bcfe 100644
@@ -7,7 +7,7 @@
 #include "i915_scatterlist.h"
 #include "i915_ttm_buddy_manager.h"
 
-#include <drm/drm_buddy.h>
+#include <linux/gpu_buddy.h>
 #include <drm/drm_mm.h>
 
 #include <linux/slab.h>
drivers/gpu/drm/i915/i915_ttm_buddy_manager.c +1 -1
index d5c6e6605086..6b256d95badd 100644
@@ -5,7 +5,7 @@
 
 #include <linux/slab.h>
 
-#include <drm/drm_buddy.h>
+#include <linux/gpu_buddy.h>
 #include <drm/drm_print.h>
 #include <drm/ttm/ttm_placement.h>
 #include <drm/ttm/ttm_bo.h>
drivers/gpu/drm/tests/Makefile +0 -1
index 87d5d5f9332a..d2e2e3d8349a 100644
@@ -7,7 +7,6 @@ obj-$(CONFIG_DRM_KUNIT_TEST) += \
 	drm_atomic_test.o \
 	drm_atomic_state_test.o \
 	drm_bridge_test.o \
-	drm_buddy_test.o \
 	drm_cmdline_parser_test.o \
 	drm_connector_test.o \
 	drm_damage_helper_test.o \
drivers/gpu/drm/tests/drm_exec_test.c +0 -2
index 3a20c788c51f..2fc47f3b463b 100644
@@ -16,8 +16,6 @@
 #include <drm/drm_gem.h>
 #include <drm/drm_kunit_helpers.h>
 
-#include "../lib/drm_random.h"
-
 struct drm_exec_priv {
 	struct device *dev;
 	struct drm_device *drm;
drivers/gpu/drm/tests/drm_mm_test.c +0 -2
index aec9eccdeae9..e24a619059d8 100644
@@ -16,8 +16,6 @@
 #include <drm/drm_mm.h>
 #include <drm/drm_print.h>
 
-#include "../lib/drm_random.h"
-
 enum {
 	BEST,
 	BOTTOMUP,
drivers/gpu/drm/ttm/tests/ttm_mock_manager.h +1 -1
index e4c95f86a467..96ea8c9aae34 100644
@@ -5,7 +5,7 @@
 #ifndef TTM_MOCK_MANAGER_H
 #define TTM_MOCK_MANAGER_H
 
-#include <drm/drm_buddy.h>
+#include <linux/gpu_buddy.h>
 
 struct ttm_mock_manager {
 	struct ttm_resource_manager man;
drivers/gpu/drm/xe/xe_ttm_vram_mgr_types.h +1 -1
index a71e14818ec2..babeec5511d9 100644
@@ -6,7 +6,7 @@
 #ifndef _XE_TTM_VRAM_MGR_TYPES_H_
 #define _XE_TTM_VRAM_MGR_TYPES_H_
 
-#include <drm/drm_buddy.h>
+#include <linux/gpu_buddy.h>
 #include <drm/ttm/ttm_device.h>
 
 /**
drivers/gpu/tests/Makefile new file +4 -0
new file mode 100644
index 000000000000..8e7654e87d82
@@ -0,0 +1,4 @@
+# SPDX-License-Identifier: GPL-2.0
+
+gpu_buddy_tests-y = gpu_buddy_test.o gpu_random.o
+obj-$(CONFIG_DRM_KUNIT_TEST) += gpu_buddy_tests.o
drivers/gpu/tests/gpu_buddy_test.c renamed from drivers/gpu/drm/tests/drm_buddy_test.c +2 -2
similarity index 99%
rename from drivers/gpu/drm/tests/drm_buddy_test.c
rename to drivers/gpu/tests/gpu_buddy_test.c
index e6f8459c6c54..b905932da990 100644
@@ -10,9 +10,9 @@
 #include <linux/sched/signal.h>
 #include <linux/sizes.h>
 
-#include <drm/drm_buddy.h>
+#include <linux/gpu_buddy.h>
 
-#include "../lib/drm_random.h"
+#include "gpu_random.h"
 
 static unsigned int random_seed;
 
drivers/gpu/tests/gpu_random.c renamed from drivers/gpu/drm/lib/drm_random.c +1 -1
similarity index 97%
rename from drivers/gpu/drm/lib/drm_random.c
rename to drivers/gpu/tests/gpu_random.c
index 0e9dba1ef4af..ddd1f594b5d5 100644
@@ -6,7 +6,7 @@
 #include <linux/slab.h>
 #include <linux/types.h>
 
-#include "drm_random.h"
+#include "gpu_random.h"
 
 u32 drm_prandom_u32_max_state(u32 ep_ro, struct rnd_state *state)
 {
drivers/gpu/tests/gpu_random.h renamed from drivers/gpu/drm/lib/drm_random.h +0 -0
similarity index 100%
rename from drivers/gpu/drm/lib/drm_random.h
rename to drivers/gpu/tests/gpu_random.h
include/linux/gpu_buddy.h renamed from include/drm/drm_buddy.h +0 -0
similarity index 100%
rename from include/drm/drm_buddy.h
rename to include/linux/gpu_buddy.h
Signature · 1 line
2.34.1
author reviewer
#2 lore raw

PATCH v10 2/8 gpu: Move DRM buddy allocator one level up (part two)

In reply to Joel Fernandes

Move the DRM buddy allocator one level up so that it can be used by GPU drivers (example, nova-core) that have usecases other than DRM (such as VFIO vGPU support). Modify the API, structures and Kconfigs to use "gpu_buddy" terminology. Adapt the drivers and tests to use the new API.

The commit cannot be split due to bisectability, however no functional change is intended. Verified by running K-UNIT tests and build tested various configurations.

[airlied: I've split this into two so git can find copies easier. I've also just nuked drm_random library, that stuff needs to be done elsewhere and only the buddy tests seem to be using it].

---
 Documentation/gpu/drm-mm.rst                  |   6 +
 MAINTAINERS                                   |   8 +-
 drivers/gpu/Kconfig                           |  13 +
 drivers/gpu/Makefile                          |   1 +
 drivers/gpu/buddy.c                           | 556 +++++++++---------
 drivers/gpu/drm/Kconfig                       |   1 +
 drivers/gpu/drm/Makefile                      |   2 +-
 drivers/gpu/drm/amd/amdgpu/amdgpu_ras.c       |   2 +-
 .../gpu/drm/amd/amdgpu/amdgpu_res_cursor.h    |  12 +-
 drivers/gpu/drm/amd/amdgpu/amdgpu_vram_mgr.c  |  79 +--
 drivers/gpu/drm/amd/amdgpu/amdgpu_vram_mgr.h  |  18 +-
 drivers/gpu/drm/drm_buddy.c                   |  77 +++
 drivers/gpu/drm/i915/i915_scatterlist.c       |   8 +-
 drivers/gpu/drm/i915/i915_ttm_buddy_manager.c |  55 +-
 drivers/gpu/drm/i915/i915_ttm_buddy_manager.h |   4 +-
 .../drm/i915/selftests/intel_memory_region.c  |  20 +-
 .../gpu/drm/ttm/tests/ttm_bo_validate_test.c  |   4 +-
 drivers/gpu/drm/ttm/tests/ttm_mock_manager.c  |  18 +-
 drivers/gpu/drm/ttm/tests/ttm_mock_manager.h  |   2 +-
 drivers/gpu/drm/xe/xe_res_cursor.h            |  34 +-
 drivers/gpu/drm/xe/xe_svm.c                   |  12 +-
 drivers/gpu/drm/xe/xe_ttm_vram_mgr.c          |  71 +--
 drivers/gpu/drm/xe/xe_ttm_vram_mgr_types.h    |   2 +-
 drivers/gpu/tests/Makefile                    |   2 +-
 drivers/gpu/tests/gpu_buddy_test.c            | 412 ++++++-------
 drivers/gpu/tests/gpu_random.c                |  16 +-
 drivers/gpu/tests/gpu_random.h                |  18 +-
 drivers/video/Kconfig                         |   1 +
 include/drm/drm_buddy.h                       |  18 +
 include/linux/gpu_buddy.h                     | 120 ++--
 30 files changed, 853 insertions(+), 739 deletions(-)
 create mode 100644 drivers/gpu/Kconfig
 create mode 100644 drivers/gpu/drm/drm_buddy.c
 create mode 100644 include/drm/drm_buddy.h
Documentation/gpu/drm-mm.rst +6 -0
index ceee0e663237..32fb506db05b 100644
@@ -532,6 +532,12 @@ Buddy Allocator Function References (GPU buddy)
 .. kernel-doc:: drivers/gpu/buddy.c
    :export:
 
+DRM Buddy Specific Logging Function References
+----------------------------------------------
+
+.. kernel-doc:: drivers/gpu/drm/drm_buddy.c
+   :export:
+
 DRM Cache Handling and Fast WC memcpy()
 =======================================
 
MAINTAINERS +5 -3
index dc82a6bd1a61..14b4f9af0e36 100644
@@ -8905,15 +8905,17 @@ T:	git https://gitlab.freedesktop.org/drm/misc/kernel.git
 F:	drivers/gpu/drm/ttm/
 F:	include/drm/ttm/
 
-DRM BUDDY ALLOCATOR
+GPU BUDDY ALLOCATOR
 M:	Matthew Auld <[email protected]>
 M:	Arun Pravin <[email protected]>
 R:	Christian Koenig <[email protected]>
 L:	[email protected]
 S:	Maintained
 T:	git https://gitlab.freedesktop.org/drm/misc/kernel.git
-F:	drivers/gpu/drm/drm_buddy.c
-F:	drivers/gpu/drm/tests/drm_buddy_test.c
+F:	drivers/gpu/drm_buddy.c
+F:	drivers/gpu/buddy.c
+F:	drivers/gpu/tests/gpu_buddy_test.c
+F:	include/linux/gpu_buddy.h
 F:	include/drm/drm_buddy.h
 
 DRM AUTOMATED TESTING
drivers/gpu/Kconfig new file +13 -0
new file mode 100644
index 000000000000..ebb2ad4b7ea0
@@ -0,0 +1,13 @@
+# SPDX-License-Identifier: GPL-2.0
+
+config GPU_BUDDY
+       bool
+       help
+         A page based buddy allocator for GPU memory.
+
+config GPU_BUDDY_KUNIT_TEST
+       tristate "KUnit tests for GPU buddy allocator" if !KUNIT_ALL_TESTS
+       depends on GPU_BUDDY && KUNIT
+       default KUNIT_ALL_TESTS
+       help
+         KUnit tests for the GPU buddy allocator.
drivers/gpu/Makefile +1 -0
index c5292ee2c852..5cd54d06e262 100644
@@ -6,3 +6,4 @@ obj-y			+= host1x/ drm/ vga/ tests/
 obj-$(CONFIG_IMX_IPUV3_CORE)	+= ipu-v3/
 obj-$(CONFIG_TRACE_GPU_MEM)		+= trace/
 obj-$(CONFIG_NOVA_CORE)		+= nova-core/
+obj-$(CONFIG_GPU_BUDDY)		+= buddy.o
drivers/gpu/buddy.c +271 -285

1,266 lines not on this page · raw message

drivers/gpu/drm/Kconfig +1 -0
index ca2a2801e77f..f48d00fe28cc 100644
@@ -220,6 +220,7 @@ config DRM_GPUSVM
 config DRM_BUDDY
 	tristate
 	depends on DRM
+	select GPU_BUDDY
 	help
 	  A page based buddy allocator
 
drivers/gpu/drm/Makefile +1 -1
index 5c86bc908955..6ff0f6f10b58 100644
@@ -113,7 +113,7 @@ drm_gpusvm_helper-$(CONFIG_ZONE_DEVICE) += \
 
 obj-$(CONFIG_DRM_GPUSVM) += drm_gpusvm_helper.o
 
-obj-$(CONFIG_DRM_BUDDY) += ../buddy.o
+obj-$(CONFIG_DRM_BUDDY) += drm_buddy.o
 
 drm_dma_helper-y := drm_gem_dma_helper.o
 drm_dma_helper-$(CONFIG_DRM_FBDEV_EMULATION) += drm_fbdev_dma.o
drivers/gpu/drm/amd/amdgpu/amdgpu_ras.c +1 -1
index f582113d78b7..149f8f942eae 100644
@@ -5663,7 +5663,7 @@ int amdgpu_ras_add_critical_region(struct amdgpu_device *adev,
 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
 	struct amdgpu_vram_mgr_resource *vres;
 	struct ras_critical_region *region;
-	struct drm_buddy_block *block;
+	struct gpu_buddy_block *block;
 	int ret = 0;
 
 	if (!bo || !bo->tbo.resource)
drivers/gpu/drm/amd/amdgpu/amdgpu_res_cursor.h +6 -6
index be2e56ce1355..8908d9e08a30 100644
@@ -55,7 +55,7 @@ static inline void amdgpu_res_first(struct ttm_resource *res,
 				    uint64_t start, uint64_t size,
 				    struct amdgpu_res_cursor *cur)
 {
-	struct drm_buddy_block *block;
+	struct gpu_buddy_block *block;
 	struct list_head *head, *next;
 	struct drm_mm_node *node;
 
@@ -71,7 +71,7 @@ static inline void amdgpu_res_first(struct ttm_resource *res,
 		head = &to_amdgpu_vram_mgr_resource(res)->blocks;
 
 		block = list_first_entry_or_null(head,
-						 struct drm_buddy_block,
+						 struct gpu_buddy_block,
 						 link);
 		if (!block)
 			goto fallback;
@@ -81,7 +81,7 @@ static inline void amdgpu_res_first(struct ttm_resource *res,
 
 			next = block->link.next;
 			if (next != head)
-				block = list_entry(next, struct drm_buddy_block, link);
+				block = list_entry(next, struct gpu_buddy_block, link);
 		}
 
 		cur->start = amdgpu_vram_mgr_block_start(block) + start;
@@ -125,7 +125,7 @@ static inline void amdgpu_res_first(struct ttm_resource *res,
  */
 static inline void amdgpu_res_next(struct amdgpu_res_cursor *cur, uint64_t size)
 {
-	struct drm_buddy_block *block;
+	struct gpu_buddy_block *block;
 	struct drm_mm_node *node;
 	struct list_head *next;
 
@@ -146,7 +146,7 @@ static inline void amdgpu_res_next(struct amdgpu_res_cursor *cur, uint64_t size)
 		block = cur->node;
 
 		next = block->link.next;
-		block = list_entry(next, struct drm_buddy_block, link);
+		block = list_entry(next, struct gpu_buddy_block, link);
 
 		cur->node = block;
 		cur->start = amdgpu_vram_mgr_block_start(block);
@@ -175,7 +175,7 @@ static inline void amdgpu_res_next(struct amdgpu_res_cursor *cur, uint64_t size)
  */
 static inline bool amdgpu_res_cleared(struct amdgpu_res_cursor *cur)
 {
-	struct drm_buddy_block *block;
+	struct gpu_buddy_block *block;
 
 	switch (cur->mem_type) {
 	case TTM_PL_VRAM:
drivers/gpu/drm/amd/amdgpu/amdgpu_vram_mgr.c +40 -39

259 lines not on this page · raw message

drivers/gpu/drm/amd/amdgpu/amdgpu_vram_mgr.h +9 -9
index 874779618056..429a21a2e9b2 100644
@@ -28,7 +28,7 @@
 
 struct amdgpu_vram_mgr {
 	struct ttm_resource_manager manager;
-	struct drm_buddy mm;
+	struct gpu_buddy mm;
 	/* protects access to buffer objects */
 	struct mutex lock;
 	struct list_head reservations_pending;
@@ -57,19 +57,19 @@ struct amdgpu_vram_mgr_resource {
 	struct amdgpu_vres_task task;
 };
 
-static inline u64 amdgpu_vram_mgr_block_start(struct drm_buddy_block *block)
+static inline u64 amdgpu_vram_mgr_block_start(struct gpu_buddy_block *block)
 {
-	return drm_buddy_block_offset(block);
+	return gpu_buddy_block_offset(block);
 }
 
-static inline u64 amdgpu_vram_mgr_block_size(struct drm_buddy_block *block)
+static inline u64 amdgpu_vram_mgr_block_size(struct gpu_buddy_block *block)
 {
-	return (u64)PAGE_SIZE << drm_buddy_block_order(block);
+	return (u64)PAGE_SIZE << gpu_buddy_block_order(block);
 }
 
-static inline bool amdgpu_vram_mgr_is_cleared(struct drm_buddy_block *block)
+static inline bool amdgpu_vram_mgr_is_cleared(struct gpu_buddy_block *block)
 {
-	return drm_buddy_block_is_clear(block);
+	return gpu_buddy_block_is_clear(block);
 }
 
 static inline struct amdgpu_vram_mgr_resource *
@@ -82,8 +82,8 @@ static inline void amdgpu_vram_mgr_set_cleared(struct ttm_resource *res)
 {
 	struct amdgpu_vram_mgr_resource *ares = to_amdgpu_vram_mgr_resource(res);
 
-	WARN_ON(ares->flags & DRM_BUDDY_CLEARED);
-	ares->flags |= DRM_BUDDY_CLEARED;
+	WARN_ON(ares->flags & GPU_BUDDY_CLEARED);
+	ares->flags |= GPU_BUDDY_CLEARED;
 }
 
 int amdgpu_vram_mgr_query_address_block_info(struct amdgpu_vram_mgr *mgr,
drivers/gpu/drm/drm_buddy.c new file +77 -0

77 lines not on this page · raw message

drivers/gpu/drm/i915/i915_scatterlist.c +4 -4
index 30246f02bcfe..6a34dae13769 100644
@@ -167,9 +167,9 @@ struct i915_refct_sgt *i915_rsgt_from_buddy_resource(struct ttm_resource *res,
 	struct i915_ttm_buddy_resource *bman_res = to_ttm_buddy_resource(res);
 	const u64 size = res->size;
 	const u32 max_segment = round_down(UINT_MAX, page_alignment);
-	struct drm_buddy *mm = bman_res->mm;
+	struct gpu_buddy *mm = bman_res->mm;
 	struct list_head *blocks = &bman_res->blocks;
-	struct drm_buddy_block *block;
+	struct gpu_buddy_block *block;
 	struct i915_refct_sgt *rsgt;
 	struct scatterlist *sg;
 	struct sg_table *st;
@@ -202,8 +202,8 @@ struct i915_refct_sgt *i915_rsgt_from_buddy_resource(struct ttm_resource *res,
 	list_for_each_entry(block, blocks, link) {
 		u64 block_size, offset;
 
-		block_size = min_t(u64, size, drm_buddy_block_size(mm, block));
-		offset = drm_buddy_block_offset(block);
+		block_size = min_t(u64, size, gpu_buddy_block_size(mm, block));
+		offset = gpu_buddy_block_offset(block);
 
 		while (block_size) {
 			u64 len;
drivers/gpu/drm/i915/i915_ttm_buddy_manager.c +28 -27

175 lines not on this page · raw message

drivers/gpu/drm/i915/i915_ttm_buddy_manager.h +2 -2
index d64620712830..1cff018c1689 100644
@@ -13,7 +13,7 @@
 
 struct ttm_device;
 struct ttm_resource_manager;
-struct drm_buddy;
+struct gpu_buddy;
 
 /**
  * struct i915_ttm_buddy_resource
@@ -33,7 +33,7 @@ struct i915_ttm_buddy_resource {
 	struct list_head blocks;
 	unsigned long flags;
 	unsigned long used_visible_size;
-	struct drm_buddy *mm;
+	struct gpu_buddy *mm;
 };
 
 /**
drivers/gpu/drm/i915/selftests/intel_memory_region.c +10 -10
index 7b856b5090f9..8307390943a2 100644
@@ -6,7 +6,7 @@
 #include <linux/prime_numbers.h>
 #include <linux/sort.h>
 
-#include <drm/drm_buddy.h>
+#include <linux/gpu_buddy.h>
 
 #include "../i915_selftest.h"
 
@@ -371,7 +371,7 @@ static int igt_mock_splintered_region(void *arg)
 	struct drm_i915_private *i915 = mem->i915;
 	struct i915_ttm_buddy_resource *res;
 	struct drm_i915_gem_object *obj;
-	struct drm_buddy *mm;
+	struct gpu_buddy *mm;
 	unsigned int expected_order;
 	LIST_HEAD(objects);
 	u64 size;
@@ -447,8 +447,8 @@ static int igt_mock_max_segment(void *arg)
 	struct drm_i915_private *i915 = mem->i915;
 	struct i915_ttm_buddy_resource *res;
 	struct drm_i915_gem_object *obj;
-	struct drm_buddy_block *block;
-	struct drm_buddy *mm;
+	struct gpu_buddy_block *block;
+	struct gpu_buddy *mm;
 	struct list_head *blocks;
 	struct scatterlist *sg;
 	I915_RND_STATE(prng);
@@ -487,8 +487,8 @@ static int igt_mock_max_segment(void *arg)
 	mm = res->mm;
 	size = 0;
 	list_for_each_entry(block, blocks, link) {
-		if (drm_buddy_block_size(mm, block) > size)
-			size = drm_buddy_block_size(mm, block);
+		if (gpu_buddy_block_size(mm, block) > size)
+			size = gpu_buddy_block_size(mm, block);
 	}
 	if (size < max_segment) {
 		pr_err("%s: Failed to create a huge contiguous block [> %u], largest block %lld\n",
@@ -527,14 +527,14 @@ static u64 igt_object_mappable_total(struct drm_i915_gem_object *obj)
 	struct intel_memory_region *mr = obj->mm.region;
 	struct i915_ttm_buddy_resource *bman_res =
 		to_ttm_buddy_resource(obj->mm.res);
-	struct drm_buddy *mm = bman_res->mm;
-	struct drm_buddy_block *block;
+	struct gpu_buddy *mm = bman_res->mm;
+	struct gpu_buddy_block *block;
 	u64 total;
 
 	total = 0;
 	list_for_each_entry(block, &bman_res->blocks, link) {
-		u64 start = drm_buddy_block_offset(block);
-		u64 end = start + drm_buddy_block_size(mm, block);
+		u64 start = gpu_buddy_block_offset(block);
+		u64 end = start + gpu_buddy_block_size(mm, block);
 
 		if (start < resource_size(&mr->io))
 			total += min_t(u64, end, resource_size(&mr->io)) - start;
drivers/gpu/drm/ttm/tests/ttm_bo_validate_test.c +2 -2
index 6d95447a989d..e32f3c8d7b84 100644
@@ -251,7 +251,7 @@ static void ttm_bo_validate_basic(struct kunit *test)
 				   NULL, &dummy_ttm_bo_destroy);
 	KUNIT_EXPECT_EQ(test, err, 0);
 
-	snd_place = ttm_place_kunit_init(test, snd_mem, DRM_BUDDY_TOPDOWN_ALLOCATION);
+	snd_place = ttm_place_kunit_init(test, snd_mem, GPU_BUDDY_TOPDOWN_ALLOCATION);
 	snd_placement = ttm_placement_kunit_init(test, snd_place, 1);
 
 	err = ttm_bo_validate(bo, snd_placement, &ctx_val);
@@ -263,7 +263,7 @@ static void ttm_bo_validate_basic(struct kunit *test)
 	KUNIT_EXPECT_TRUE(test, ttm_tt_is_populated(bo->ttm));
 	KUNIT_EXPECT_EQ(test, bo->resource->mem_type, snd_mem);
 	KUNIT_EXPECT_EQ(test, bo->resource->placement,
-			DRM_BUDDY_TOPDOWN_ALLOCATION);
+			GPU_BUDDY_TOPDOWN_ALLOCATION);
 
 	ttm_bo_fini(bo);
 	ttm_mock_manager_fini(priv->ttm_dev, snd_mem);
drivers/gpu/drm/ttm/tests/ttm_mock_manager.c +9 -9
index dd395229e388..294d56d9067e 100644
@@ -31,7 +31,7 @@ static int ttm_mock_manager_alloc(struct ttm_resource_manager *man,
 {
 	struct ttm_mock_manager *manager = to_mock_mgr(man);
 	struct ttm_mock_resource *mock_res;
-	struct drm_buddy *mm = &manager->mm;
+	struct gpu_buddy *mm = &manager->mm;
 	u64 lpfn, fpfn, alloc_size;
 	int err;
 
@@ -47,14 +47,14 @@ static int ttm_mock_manager_alloc(struct ttm_resource_manager *man,
 	INIT_LIST_HEAD(&mock_res->blocks);
 
 	if (place->flags & TTM_PL_FLAG_TOPDOWN)
-		mock_res->flags |= DRM_BUDDY_TOPDOWN_ALLOCATION;
+		mock_res->flags |= GPU_BUDDY_TOPDOWN_ALLOCATION;
 
 	if (place->flags & TTM_PL_FLAG_CONTIGUOUS)
-		mock_res->flags |= DRM_BUDDY_CONTIGUOUS_ALLOCATION;
+		mock_res->flags |= GPU_BUDDY_CONTIGUOUS_ALLOCATION;
 
 	alloc_size = (uint64_t)mock_res->base.size;
 	mutex_lock(&manager->lock);
-	err = drm_buddy_alloc_blocks(mm, fpfn, lpfn, alloc_size,
+	err = gpu_buddy_alloc_blocks(mm, fpfn, lpfn, alloc_size,
 				     manager->default_page_size,
 				     &mock_res->blocks,
 				     mock_res->flags);
@@ -67,7 +67,7 @@ static int ttm_mock_manager_alloc(struct ttm_resource_manager *man,
 	return 0;
 
 error_free_blocks:
-	drm_buddy_free_list(mm, &mock_res->blocks, 0);
+	gpu_buddy_free_list(mm, &mock_res->blocks, 0);
 	ttm_resource_fini(man, &mock_res->base);
 	mutex_unlock(&manager->lock);
 
@@ -79,10 +79,10 @@ static void ttm_mock_manager_free(struct ttm_resource_manager *man,
 {
 	struct ttm_mock_manager *manager = to_mock_mgr(man);
 	struct ttm_mock_resource *mock_res = to_mock_mgr_resource(res);
-	struct drm_buddy *mm = &manager->mm;
+	struct gpu_buddy *mm = &manager->mm;
 
 	mutex_lock(&manager->lock);
-	drm_buddy_free_list(mm, &mock_res->blocks, 0);
+	gpu_buddy_free_list(mm, &mock_res->blocks, 0);
 	mutex_unlock(&manager->lock);
 
 	ttm_resource_fini(man, res);
@@ -106,7 +106,7 @@ int ttm_mock_manager_init(struct ttm_device *bdev, u32 mem_type, u32 size)
 
 	mutex_init(&manager->lock);
 
-	err = drm_buddy_init(&manager->mm, size, PAGE_SIZE);
+	err = gpu_buddy_init(&manager->mm, size, PAGE_SIZE);
 
 	if (err) {
 		kfree(manager);
@@ -142,7 +142,7 @@ void ttm_mock_manager_fini(struct ttm_device *bdev, u32 mem_type)
 	ttm_resource_manager_set_used(man, false);
 
 	mutex_lock(&mock_man->lock);
-	drm_buddy_fini(&mock_man->mm);
+	gpu_buddy_fini(&mock_man->mm);
 	mutex_unlock(&mock_man->lock);
 
 	ttm_set_driver_manager(bdev, mem_type, NULL);
drivers/gpu/drm/ttm/tests/ttm_mock_manager.h +1 -1
index 96ea8c9aae34..08710756fd8e 100644
@@ -9,7 +9,7 @@
 
 struct ttm_mock_manager {
 	struct ttm_resource_manager man;
-	struct drm_buddy mm;
+	struct gpu_buddy mm;
 	u64 default_page_size;
 	/* protects allocations of mock buffer objects */
 	struct mutex lock;
drivers/gpu/drm/xe/xe_res_cursor.h +17 -17
index 4e00008b7081..5f4ab08c0686 100644
@@ -58,7 +58,7 @@ struct xe_res_cursor {
 	/** @dma_addr: Current element in a struct drm_pagemap_addr array */
 	const struct drm_pagemap_addr *dma_addr;
 	/** @mm: Buddy allocator for VRAM cursor */
-	struct drm_buddy *mm;
+	struct gpu_buddy *mm;
 	/**
 	 * @dma_start: DMA start address for the current segment.
 	 * This may be different to @dma_addr.addr since elements in
@@ -69,7 +69,7 @@ struct xe_res_cursor {
 	u64 dma_seg_size;
 };
 
-static struct drm_buddy *xe_res_get_buddy(struct ttm_resource *res)
+static struct gpu_buddy *xe_res_get_buddy(struct ttm_resource *res)
 {
 	struct ttm_resource_manager *mgr;
 
@@ -104,30 +104,30 @@ static inline void xe_res_first(struct ttm_resource *res,
 	case XE_PL_STOLEN:
 	case XE_PL_VRAM0:
 	case XE_PL_VRAM1: {
-		struct drm_buddy_block *block;
+		struct gpu_buddy_block *block;
 		struct list_head *head, *next;
-		struct drm_buddy *mm = xe_res_get_buddy(res);
+		struct gpu_buddy *mm = xe_res_get_buddy(res);
 
 		head = &to_xe_ttm_vram_mgr_resource(res)->blocks;
 
 		block = list_first_entry_or_null(head,
-						 struct drm_buddy_block,
+						 struct gpu_buddy_block,
 						 link);
 		if (!block)
 			goto fallback;
 
-		while (start >= drm_buddy_block_size(mm, block)) {
-			start -= drm_buddy_block_size(mm, block);
+		while (start >= gpu_buddy_block_size(mm, block)) {
+			start -= gpu_buddy_block_size(mm, block);
 
 			next = block->link.next;
 			if (next != head)
-				block = list_entry(next, struct drm_buddy_block,
+				block = list_entry(next, struct gpu_buddy_block,
 						   link);
 		}
 
 		cur->mm = mm;
-		cur->start = drm_buddy_block_offset(block) + start;
-		cur->size = min(drm_buddy_block_size(mm, block) - start,
+		cur->start = gpu_buddy_block_offset(block) + start;
+		cur->size = min(gpu_buddy_block_size(mm, block) - start,
 				size);
 		cur->remaining = size;
 		cur->node = block;
@@ -259,7 +259,7 @@ static inline void xe_res_first_dma(const struct drm_pagemap_addr *dma_addr,
  */
 static inline void xe_res_next(struct xe_res_cursor *cur, u64 size)
 {
-	struct drm_buddy_block *block;
+	struct gpu_buddy_block *block;
 	struct list_head *next;
 	u64 start;
 
@@ -295,18 +295,18 @@ static inline void xe_res_next(struct xe_res_cursor *cur, u64 size)
 		block = cur->node;
 
 		next = block->link.next;
-		block = list_entry(next, struct drm_buddy_block, link);
+		block = list_entry(next, struct gpu_buddy_block, link);
 
 
-		while (start >= drm_buddy_block_size(cur->mm, block)) {
-			start -= drm_buddy_block_size(cur->mm, block);
+		while (start >= gpu_buddy_block_size(cur->mm, block)) {
+			start -= gpu_buddy_block_size(cur->mm, block);
 
 			next = block->link.next;
-			block = list_entry(next, struct drm_buddy_block, link);
+			block = list_entry(next, struct gpu_buddy_block, link);
 		}
 
-		cur->start = drm_buddy_block_offset(block) + start;
-		cur->size = min(drm_buddy_block_size(cur->mm, block) - start,
+		cur->start = gpu_buddy_block_offset(block) + start;
+		cur->size = min(gpu_buddy_block_size(cur->mm, block) - start,
 				cur->remaining);
 		cur->node = block;
 		break;
drivers/gpu/drm/xe/xe_svm.c +6 -6
index 213f0334518a..cda3bf7e2418 100644
@@ -747,7 +747,7 @@ static u64 block_offset_to_pfn(struct drm_pagemap *dpagemap, u64 offset)
 	return PHYS_PFN(offset + xpagemap->hpa_base);
 }
 
-static struct drm_buddy *vram_to_buddy(struct xe_vram_region *vram)
+static struct gpu_buddy *vram_to_buddy(struct xe_vram_region *vram)
 {
 	return &vram->ttm.mm;
 }
@@ -758,17 +758,17 @@ static int xe_svm_populate_devmem_pfn(struct drm_pagemap_devmem *devmem_allocati
 	struct xe_bo *bo = to_xe_bo(devmem_allocation);
 	struct ttm_resource *res = bo->ttm.resource;
 	struct list_head *blocks = &to_xe_ttm_vram_mgr_resource(res)->blocks;
-	struct drm_buddy_block *block;
+	struct gpu_buddy_block *block;
 	int j = 0;
 
 	list_for_each_entry(block, blocks, link) {
 		struct xe_vram_region *vr = block->private;
-		struct drm_buddy *buddy = vram_to_buddy(vr);
+		struct gpu_buddy *buddy = vram_to_buddy(vr);
 		u64 block_pfn = block_offset_to_pfn(devmem_allocation->dpagemap,
-						    drm_buddy_block_offset(block));
+						    gpu_buddy_block_offset(block));
 		int i;
 
-		for (i = 0; i < drm_buddy_block_size(buddy, block) >> PAGE_SHIFT; ++i)
+		for (i = 0; i < gpu_buddy_block_size(buddy, block) >> PAGE_SHIFT; ++i)
 			pfn[j++] = block_pfn + i;
 	}
 
@@ -1033,7 +1033,7 @@ static int xe_drm_pagemap_populate_mm(struct drm_pagemap *dpagemap,
 	struct dma_fence *pre_migrate_fence = NULL;
 	struct xe_device *xe = vr->xe;
 	struct device *dev = xe->drm.dev;
-	struct drm_buddy_block *block;
+	struct gpu_buddy_block *block;
 	struct xe_validation_ctx vctx;
 	struct list_head *blocks;
 	struct drm_exec exec;
drivers/gpu/drm/xe/xe_ttm_vram_mgr.c +36 -35

207 lines not on this page · raw message

drivers/gpu/drm/xe/xe_ttm_vram_mgr_types.h +1 -1
index babeec5511d9..9106da056b49 100644
@@ -18,7 +18,7 @@ struct xe_ttm_vram_mgr {
 	/** @manager: Base TTM resource manager */
 	struct ttm_resource_manager manager;
 	/** @mm: DRM buddy allocator which manages the VRAM */
-	struct drm_buddy mm;
+	struct gpu_buddy mm;
 	/** @visible_size: Proped size of the CPU visible portion */
 	u64 visible_size;
 	/** @visible_avail: CPU visible portion still unallocated */
drivers/gpu/tests/Makefile +1 -1
index 8e7654e87d82..4183e6e2de45 100644
@@ -1,4 +1,4 @@
 # SPDX-License-Identifier: GPL-2.0
 
 gpu_buddy_tests-y = gpu_buddy_test.o gpu_random.o
-obj-$(CONFIG_DRM_KUNIT_TEST) += gpu_buddy_tests.o
+obj-$(CONFIG_GPU_BUDDY_KUNIT_TEST) += gpu_buddy_tests.o
drivers/gpu/tests/gpu_buddy_test.c +206 -206

541 lines not on this page · raw message

drivers/gpu/tests/gpu_random.c +8 -8
index ddd1f594b5d5..6356372f7e52 100644

Lines of this file are not shown. View the raw message.

drivers/gpu/tests/gpu_random.h +9 -9
index 9f827260a89d..b68cf3448264 100644

Lines of this file are not shown. View the raw message.

drivers/video/Kconfig +1 -0
index 9884f003247d..a7144d275f54 100644

Lines of this file are not shown. View the raw message.

include/drm/drm_buddy.h new file +18 -0
new file mode 100644
index 000000000000..3054369bebff

Lines of this file are not shown. View the raw message.

include/linux/gpu_buddy.h +63 -57

120 lines not on this page · raw message

The rest of this diff is not shown. View the raw message.

Signature · 1 line
2.34.1

Part of the diff is not shown here. View the raw message.

#3 lore raw

Re: [PATCH v10 2/8] gpu: Move DRM buddy allocator one level up (part two)

Quoted 8 lines · Joel Fernandes

Move the DRM buddy allocator one level up so that it can be used by GPU drivers (example, nova-core) that have usecases other than DRM (such as VFIO vGPU support). Modify the API, structures and Kconfigs to use "gpu_buddy" terminology. Adapt the drivers and tests to use the new API.

The commit cannot be split due to bisectability, however no functional change is intended. Verified by running K-UNIT tests and build tested various configurations.

Patches 1 and 2 have the exact same commit log, but each one does only part of it. Let's only keep the part of the log that applies to each patch.

Quoted 69 lines

[airlied: I've split this into two so git can find copies easier. I've also just nuked drm_random library, that stuff needs to be done elsewhere and only the buddy tests seem to be using it].

---
 Documentation/gpu/drm-mm.rst                  |   6 +
 MAINTAINERS                                   |   8 +-
 drivers/gpu/Kconfig                           |  13 +
 drivers/gpu/Makefile                          |   1 +
 drivers/gpu/buddy.c                           | 556 +++++++++---------
 drivers/gpu/drm/Kconfig                       |   1 +
 drivers/gpu/drm/Makefile                      |   2 +-
 drivers/gpu/drm/amd/amdgpu/amdgpu_ras.c       |   2 +-
 .../gpu/drm/amd/amdgpu/amdgpu_res_cursor.h    |  12 +-
 drivers/gpu/drm/amd/amdgpu/amdgpu_vram_mgr.c  |  79 +--
 drivers/gpu/drm/amd/amdgpu/amdgpu_vram_mgr.h  |  18 +-
 drivers/gpu/drm/drm_buddy.c                   |  77 +++
 drivers/gpu/drm/i915/i915_scatterlist.c       |   8 +-
 drivers/gpu/drm/i915/i915_ttm_buddy_manager.c |  55 +-
 drivers/gpu/drm/i915/i915_ttm_buddy_manager.h |   4 +-
 .../drm/i915/selftests/intel_memory_region.c  |  20 +-
 .../gpu/drm/ttm/tests/ttm_bo_validate_test.c  |   4 +-
 drivers/gpu/drm/ttm/tests/ttm_mock_manager.c  |  18 +-
 drivers/gpu/drm/ttm/tests/ttm_mock_manager.h  |   2 +-
 drivers/gpu/drm/xe/xe_res_cursor.h            |  34 +-
 drivers/gpu/drm/xe/xe_svm.c                   |  12 +-
 drivers/gpu/drm/xe/xe_ttm_vram_mgr.c          |  71 +--
 drivers/gpu/drm/xe/xe_ttm_vram_mgr_types.h    |   2 +-
 drivers/gpu/tests/Makefile                    |   2 +-
 drivers/gpu/tests/gpu_buddy_test.c            | 412 ++++++-------
 drivers/gpu/tests/gpu_random.c                |  16 +-
 drivers/gpu/tests/gpu_random.h                |  18 +-
 drivers/video/Kconfig                         |   1 +
 include/drm/drm_buddy.h                       |  18 +
 include/linux/gpu_buddy.h                     | 120 ++--
 30 files changed, 853 insertions(+), 739 deletions(-)
 create mode 100644 drivers/gpu/Kconfig
 create mode 100644 drivers/gpu/drm/drm_buddy.c
 create mode 100644 include/drm/drm_buddy.h
Documentation/gpu/drm-mm.rst +6 -0
index ceee0e663237..32fb506db05b 100644
@@ -532,6 +532,12 @@ Buddy Allocator Function References (GPU buddy)
 .. kernel-doc:: drivers/gpu/buddy.c
    :export:
 
+DRM Buddy Specific Logging Function References
+----------------------------------------------
+
+.. kernel-doc:: drivers/gpu/drm/drm_buddy.c
+   :export:
+
 DRM Cache Handling and Fast WC memcpy()
 =======================================
 
MAINTAINERS +0 -1
index dc82a6bd1a61..14b4f9af0e36 100644
@@ -8905,15 +8905,17 @@ T:	git https://gitlab.freedesktop.org/drm/misc/kernel.git
 F:	drivers/gpu/drm/ttm/
 F:	include/drm/ttm/
 
-DRM BUDDY ALLOCATOR

MAINTAINERS T: git https://gitlab.freedesktop.org/drm/misc/kernel.git · line 8915

Quoted 10 lines
MAINTAINERS +2 -2
+GPU BUDDY ALLOCATOR
 M:	Matthew Auld <[email protected]>
 M:	Arun Pravin <[email protected]>
 R:	Christian Koenig <[email protected]>
 L:	[email protected]
 S:	Maintained
 T:	git https://gitlab.freedesktop.org/drm/misc/kernel.git
-F:	drivers/gpu/drm/drm_buddy.c
-F:	drivers/gpu/drm/tests/drm_buddy_test.c
+F:	drivers/gpu/drm_buddy.c

This line should be drivers/gpu/drm/drm_buddy.c.

MAINTAINERS T: git https://gitlab.freedesktop.org/drm/misc/kernel.git · line 8918

Quoted 3 lines
MAINTAINERS +3 -0
+F:	drivers/gpu/buddy.c
+F:	drivers/gpu/tests/gpu_buddy_test.c
+F:	include/linux/gpu_buddy.h

These files have been moved in patch 1, so their MAINTAINERS entry should also be modified there.

author reviewer
#4 lore raw

Re: [PATCH v10 2/8] gpu: Move DRM buddy allocator one level up (part two)

Quoted 3 lines · Alexandre Courbot

Patches 1 and 2 have the exact same commit log, but each one does only part of it. Let's only keep the part of the log that applies to each patch.

Good catch, will differentiate the commit logs for part one and part two.

Quoted 3 lines
Quoted 1 line

+F: drivers/gpu/drm_buddy.c

This line should be drivers/gpu/drm/drm_buddy.c.

Good catch, will fix.

Quoted 2 lines

These files have been moved in patch 1, so their MAINTAINERS entry should also be modified there.

Right, I'll move the MAINTAINERS changes to the appropriate patch where the files are actually moved.

Thanks,
Joel

author reviewer
#5 lore raw

PATCH v10 3/8 gpu: Fix uninitialized buddy for built-in drivers

In reply to Joel Fernandes

From: Koen Koning <[email protected]>

Use subsys_initcall instead of module_init for the GPU buddy allocator, so its initialization code runs before any gpu drivers. Otherwise, a built-in driver that tries to use the buddy allocator will run into a kernel NULL pointer dereference because slab_blocks is uninitialized.

Specifically, this fixes drm/xe (as built-in) running into a kernel panic during boot, because it uses buddy during device probe.

Fixes ba110db8e1bc ("gpu: Move DRM buddy allocator one level up (part two)")
Cc Joel Fernandes <[email protected]>
Cc Dave Airlie <[email protected]>
Cc Peter Senna Tschudin <[email protected]>
Cc Matthew Auld <[email protected]>
---
 drivers/gpu/buddy.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/gpu/buddy.c +1 -1
index 603c59a2013a..81f57fdf913b 100644
@@ -1315,7 +1315,7 @@ static int __init gpu_buddy_module_init(void)
 	return 0;
 }
 
-module_init(gpu_buddy_module_init);
+subsys_initcall(gpu_buddy_module_init);
 module_exit(gpu_buddy_module_exit);
 
 MODULE_DESCRIPTION("GPU Buddy Allocator");
Signature · 1 line
2.34.1
maintainer
#6 lore raw

Re: [PATCH v10 3/8] gpu: Fix uninitialized buddy for built-in drivers

Quoted 8 lines · Joel Fernandes

From: Koen Koning <[email protected]>

Use subsys_initcall instead of module_init for the GPU buddy allocator, so its initialization code runs before any gpu drivers. Otherwise, a built-in driver that tries to use the buddy allocator will run into a kernel NULL pointer dereference because slab_blocks is uninitialized.

Quoted 4 lines

Specifically, this fixes drm/xe (as built-in) running into a kernel panic during boot, because it uses buddy during device probe.

Fixes ba110db8e1bc ("gpu: Move DRM buddy allocator one level up (part two)")

This Fixes: tag seems wrong. How is this code move related to this problem?

This should rather be:

Fixes 6387a3c4b0c4 ("drm: move the buddy allocator from i915 into common drm")

Also, please add:

Quoted 8 lines

I also think this patch should be sent separately and go through drm-misc-fixes.

author reviewer
#7 lore raw

Re: [PATCH v10 3/8] gpu: Fix uninitialized buddy for built-in drivers

Quoted 7 lines · Danilo Krummrich
Quoted 1 line
Fixes ba110db8e1bc ("gpu: Move DRM buddy allocator one level up (part two)")

This Fixes: tag seems wrong. How is this code move related to this problem?

This should rather be:

Fixes 6387a3c4b0c4 ("drm: move the buddy allocator from i915 into common drm")

You're right, the bug existed since the original move to common drm. Will update the Fixes tag.

Quoted 3 lines

Also, please add:

Will add.

Quoted 1 line

I also think this patch should be sent separately and go through drm-misc-fixes.

Agreed. I'll pull this patch out of the series and send it separately targeting drm-misc-fixes.

Thanks,
Joel

author reviewer
#8 lore raw

Re: [PATCH v10 3/8] gpu: Fix uninitialized buddy for built-in drivers

Quoted 14 lines · Joel Fernandes
Quoted 7 lines · Danilo Krummrich
Quoted 1 line
Fixes ba110db8e1bc ("gpu: Move DRM buddy allocator one level up (part two)")

This Fixes: tag seems wrong. How is this code move related to this problem?

This should rather be:

Fixes 6387a3c4b0c4 ("drm: move the buddy allocator from i915 into common drm")

You're right, the bug existed since the original move to common drm. Will update the Fixes tag.

Quoted 2 lines

Also, please add:

Quoted 9 lines
Quoted 1 line

Will add.

Quoted 1 line

I also think this patch should be sent separately and go through drm-misc-fixes.

Agreed. I'll pull this patch out of the series and send it separately targeting drm-misc-fixes.

I just saw that Koen will send it separately so I'll let him handle it. In future postings, I will put both this fix and earlier 2 patches (part one and two of the move) with prefix [cherry-pick], since the only reason I am carrying them is because it is a dependency that is not yet in torvalds/master branch.

I should have made that clear. Thanks,

--
Joel Fernandes

author reviewer
#9 lore raw

PATCH v10 4/8 rust: ffi: Convert pub use to pub mod and create ffi module

In reply to Joel Fernandes

Convert pub use ffi to pub mod ffi in lib.rs and create the corresponding rust/kernel/ffi/mod.rs module file. Also re-export all C type definitions from ffi crate so that existing kernel::ffi::c_int etc. paths continue to work.

This prepares the ffi module to host additional sub-modules in later patches (clist).

---
 rust/kernel/ffi/mod.rs | 7 +++++++
 rust/kernel/lib.rs     | 3 +--
 2 files changed, 8 insertions(+), 2 deletions(-)
 create mode 100644 rust/kernel/ffi/mod.rs
rust/kernel/ffi/mod.rs new file +7 -0
new file mode 100644
index 000000000000..7d844e9cb339
@@ -0,0 +1,7 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! FFI infrastructure for interfacing with C code.
+
+// Re-export C type definitions from the `ffi` crate so that existing
+// `kernel::ffi::c_int` etc. paths continue to work.
+pub use ::ffi::*;
rust/kernel/lib.rs +1 -2
index 3da92f18f4ee..0a77b4c0ffeb 100644
@@ -62,8 +62,6 @@
 // Allow proc-macros to refer to `::kernel` inside the `kernel` crate (this crate).
 extern crate self as kernel;
 
-pub use ffi;
-
 pub mod acpi;
 pub mod alloc;
 #[cfg(CONFIG_AUXILIARY_BUS)]
@@ -93,6 +91,7 @@
 pub mod drm;
 pub mod error;
 pub mod faux;
+pub mod ffi;
 #[cfg(CONFIG_RUST_FW_LOADER_ABSTRACTIONS)]
 pub mod firmware;
 pub mod fmt;
Signature · 1 line
2.34.1
maintainer Reviewed-by on v10 4/8
#10 lore raw

Re: [PATCH v10 4/8] rust: ffi: Convert pub use to pub mod and create ffi module

Quoted 9 lines · Joel Fernandes

Convert pub use ffi to pub mod ffi in lib.rs and create the corresponding rust/kernel/ffi/mod.rs module file. Also re-export all C type definitions from ffi crate so that existing kernel::ffi::c_int etc. paths continue to work.

This prepares the ffi module to host additional sub-modules in later patches (clist).

author reviewer
#11 lore raw

PATCH v10 5/8 rust: clist: Add support to interface with C linked lists

In reply to 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/ffi/clist.rs | 327 +++++++++++++++++++++++++++++++++++++++
 rust/kernel/ffi/mod.rs   |   2 +
 5 files changed, 354 insertions(+)
 create mode 100644 rust/helpers/list.c
 create mode 100644 rust/kernel/ffi/clist.rs
MAINTAINERS +7 -0
index 14b4f9af0e36..4647f4601038 100644
@@ -23213,6 +23213,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/ffi/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/ffi/clist.rs new file +327 -0

327 lines not on this page · raw message

rust/kernel/ffi/mod.rs +2 -0
index 7d844e9cb339..8c235ca0d1e3 100644
@@ -5,3 +5,5 @@
 // Re-export C type definitions from the `ffi` crate so that existing
 // `kernel::ffi::c_int` etc. paths continue to work.
 pub use ::ffi::*;
+
+pub mod clist;
Signature · 1 line
2.34.1
#12 lore raw

Re: [PATCH v10 5/8] rust: clist: Add support to interface with C linked lists

On Thu Feb 19, 2026 at 5:55 AM JST, Joel Fernandes wrote:
<snip>

Quoted 4 lines
rust/kernel/ffi/clist.rs new file +4 -0
+use core::{
+    iter::FusedIterator,
+    marker::PhantomData, //
+};

rust/kernel/ffi/clist.rs line 101

Quoted 10 lines
rust/kernel/ffi/clist.rs new file +10 -0
+
+use crate::{
+    bindings,
+    types::Opaque, //
+};
+
+use pin_init::{
+    pin_data,
+    pin_init,
+    PinInit //

rustfmt fixed this to

    PinInit, //

<snip>

rust/kernel/ffi/clist.rs line 219

Quoted 7 lines
rust/kernel/ffi/clist.rs new file +7 -0
+impl<'a> FusedIterator for CListHeadIter<'a> {}
+
+/// A typed C linked list with a sentinel head intended for FFI use-cases where
+/// C subsystem manages a linked list that Rust code needs to read. Generally
+/// required only for special cases.
+///
+/// A sentinel head [`ClistHead`] represents the entire linked list and can be used

Typo: CListHead (rustdoc complained about this).

author reviewer
#13 lore raw

Re: [PATCH v10 5/8] rust: clist: Add support to interface with C linked lists

Quoted 5 lines · Alexandre Courbot
Quoted 1 line

+ PinInit //

rustfmt fixed this to

    PinInit, //

Fixed, thanks.

Quoted 3 lines
Quoted 1 line

+/// A sentinel head [ClistHead] represents the entire linked list and can be used

Typo: CListHead (rustdoc complained about this).

Fixed, thanks.

Joel

maintainer
#14 lore raw

Re: [PATCH v10 5/8] rust: clist: Add support to interface with C linked lists

In reply to Joel Fernandes
Quoted 10 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.

For reference: https://lore.kernel.org/rust-for-linux/[email protected]/

maintainer
#16 lore raw

Re: [PATCH v10 5/8] rust: clist: Add support to interface with C linked lists

In reply to Joel Fernandes
Quoted 1 line · Joel Fernandes

+RUST TO C LIST INTERFACES

Maybe this should just be "RUST [FFI]" instead (in case Alex and you want to sign up for looking after FFI helper infrastructure in general)?

Quoted 5 lines
MAINTAINERS +5 -0
+M:	Joel Fernandes <[email protected]>
+M:	Alexandre Courbot <[email protected]>
+L:	[email protected]
+S:	Maintained
+F:	rust/kernel/ffi/clist.rs

<snip>

Quoted 6 lines
rust/kernel/ffi/clist.rs new file +0 -0
new file mode 100644
index 000000000000..a84f395875dc

rust/kernel/ffi/clist.rs line 8

Quoted 8 lines
rust/kernel/ffi/clist.rs new file +8 -0
@@ -0,0 +1,327 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! FFI interface for C doubly circular intrusive linked lists.
+//!
+//! This module provides Rust abstractions for iterating over C `list_head`-based
+//! linked lists. It is intended for FFI use-cases where a C subsystem manages a
+//! circular linked list that Rust code needs to read. This is generally required
+//! only for special cases and should be avoided by drivers.

Maybe generalize the statement a bit and say that this should only be used for cases where C and Rust code share direct access to the same linked list through an FFI interface.

Additionally, add a separate note that this *must not* be used by Rust components that just aim for a linked list primitive and instead refer to the Rust linked list implementation with an intra-doc link.

rust/kernel/ffi/clist.rs line 16

Quoted 8 lines
rust/kernel/ffi/clist.rs new file +8 -0
+//!
+//! # Examples
+//!
+//! ```
+//! use kernel::{
+//!     bindings,
+//!     clist_create,
+//!     types::Opaque, //

Examples don't necessarily need '//' at the end, as they are not automatically formatted anyways.

(I hope that we will have a solution for import formatting before rustfmt supports doc-comments. :)

Quoted 18 lines
rust/kernel/ffi/clist.rs new file +18 -0
+//! };
+//! # // 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) };
+//! #

rust/kernel/ffi/clist.rs line 44

Quoted 10 lines
rust/kernel/ffi/clist.rs new file +10 -0
+//! # let mut items = [
+//! #     MaybeUninit::<SampleItemC>::uninit(),
+//! #     MaybeUninit::<SampleItemC>::uninit(),
+//! #     MaybeUninit::<SampleItemC>::uninit(),
+//! # ];
+//! #
+//! # 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 {

I understand that this is just setup code for a doc-test, but I still think we should hold it to the same standards, i.e. let's separate the different unsafe calls into their own unsafe blocks and add proper safety comments.

Quoted 6 lines
rust/kernel/ffi/clist.rs new file +6 -0
+//! #         (*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);
+//! #     }
+//! # }

<snip>

rust/kernel/ffi/clist.rs line 101

Quoted 4 lines
rust/kernel/ffi/clist.rs new file +4 -0
+use pin_init::{
+    pin_data,
+    pin_init,
+    PinInit //

Should be 'PinInit, //'.

rust/kernel/ffi/clist.rs line 108

Quoted 7 lines
rust/kernel/ffi/clist.rs new file +7 -0
+};
+
+/// FFI wrapper for a C `list_head` object used in intrusive linked lists.
+///
+/// # Invariants
+///
+/// - [`CListHead`] represents an allocated and valid `list_head` structure.

What does "allocated" mean in this context? (Dynamic allocations, stack, .data section of the binary, any of those?)

In case of the latter, I'd just remove "allocated".

rust/kernel/ffi/clist.rs line 121

Quoted 13 lines
rust/kernel/ffi/clist.rs new file +13 -0
+#[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.

Same here, what exactly is meant by "allocated"?

rust/kernel/ffi/clist.rs line 124

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

This is a bit vague I think, concurrent modifications of (other) Rust code are not OK either.

Quoted 11 lines
rust/kernel/ffi/clist.rs new file +11 -0
+    #[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/ffi/clist.rs line 145

Quoted 10 lines
rust/kernel/ffi/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.

I'm not sure whether "valid" in the type invariant implies that the struct list_head is initialized. From a language point of view it is also valid if the pointers are NULL.

So, I think the invariant (and the safety requirements of from_raw()) have to ensure that the struct list_head is initialized in the sense of INIT_LIST_HEAD().

Quoted 2 lines
rust/kernel/ffi/clist.rs new file +2 -0
+        unsafe { Self::from_raw((*raw).next) }
+    }

<snip>

Quoted 25 lines
rust/kernel/ffi/clist.rs new file +25 -0
+/// A typed C linked list with a sentinel head intended for FFI use-cases where
+/// C subsystem manages a linked list that Rust code needs to read. Generally
+/// required only for special cases.
+///
+/// A sentinel head [`ClistHead`] 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/ffi/clist.rs line 249

Quoted 10 lines
rust/kernel/ffi/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() }
+    }

Comments from CListHead also apply here.

Quoted 5 lines
rust/kernel/ffi/clist.rs new file +5 -0
+/// 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`.
+///

rust/kernel/ffi/clist.rs line 306

Quoted 10 lines
rust/kernel/ffi/clist.rs new file +10 -0
+/// # 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:

Given that, we should probably use the same (or a similar) trick as in [1].

[1] https://rust.docs.kernel.org/src/kernel/device.rs.html#665-688

Quoted 21 lines
rust/kernel/ffi/clist.rs new file +21 -0
+///
+/// - `$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 {
+    ($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::ffi::clist::CList::<$rust_type, OFFSET>::from_raw($head)
+    }};
+}
reviewer
#17 lore raw

Re: [PATCH v10 5/8] rust: clist: Add support to interface with C linked lists

Quoted 6 lines · Danilo Krummrich

Examples don't necessarily need '//' at the end, as they are not automatically formatted anyways.

(I hope that we will have a solution for import formatting before rustfmt supports doc-comments. :)

There is format_code_in_doc_comments option in rustfmt, unfortunately it's unstable.

Best,
Gary

author reviewer
#18 lore raw

Re: [PATCH v10 5/8] rust: clist: Add support to interface with C linked lists

In reply to Danilo Krummrich
Quoted 5 lines · Danilo Krummrich
Quoted 1 line · Joel Fernandes

+RUST TO C LIST INTERFACES

Maybe this should just be "RUST [FFI]" instead (in case Alex and you want to sign up for looking after FFI helper infrastructure in general)?

Good idea, done.

Quoted 13 lines
Quoted 1 line

+F: rust/kernel/ffi/clist.rs

<snip>

rust/kernel/ffi/clist.rs line 8

Quoted 4 lines
rust/kernel/ffi/clist.rs new file +4 -0
+//! This module provides Rust abstractions for iterating over C `list_head`-based
+//! linked lists. It is intended for FFI use-cases where a C subsystem manages a
+//! circular linked list that Rust code needs to read. This is generally required
+//! only for special cases and should be avoided by drivers.

Maybe generalize the statement a bit and say that this should only be used for cases where C and Rust code share direct access to the same linked list through an FFI interface.

Quoted 3 lines

Additionally, add a separate note that this *must not* be used by Rust components that just aim for a linked list primitive and instead refer to the Rust linked list implementation with an intra-doc link.

Done. Updated the module doc to say "It should only be used for cases where C and Rust code share direct access to the same linked list through an FFI interface" and added a separate note:

Note: This *must not* be used by Rust components that just need a linked list primitive. Use [kernel::list::List] instead.

Quoted 4 lines
Quoted 1 line

+//! types::Opaque, //

Examples don't necessarily need '//' at the end, as they are not automatically formatted anyways.

Removed from the example. Non-example imports keep the '//' as a rustfmt guard.

Quoted 6 lines

rust/kernel/ffi/clist.rs line 44

Quoted 2 lines
rust/kernel/ffi/clist.rs new file +2 -0
+//! #     // SAFETY: pointers are to allocated test objects with a list_head field.
+//! #     unsafe {

I understand that this is just setup code for a doc-test, but I still think we should hold it to the same standards, i.e. let's separate the different unsafe calls into their own unsafe blocks and add proper safety comments.

Done. Split into three separate unsafe blocks with individual SAFETY comments for the value write, INIT_LIST_HEAD, and list_add_tail calls.

Quoted 3 lines
Quoted 1 line

+ PinInit //

Should be 'PinInit, //'.

Fixed.

Quoted 6 lines
Quoted 1 line

+/// - [CListHead] represents an allocated and valid list_head structure.

What does "allocated" mean in this context? (Dynamic allocations, stack, .data section of the binary, any of those?)

In case of the latter, I'd just remove "allocated".

Removed "allocated". The invariant now reads:

The underlying list_head has been initialized (e.g. via INIT_LIST_HEAD()) and its next/prev pointers are valid and non-NULL.

Quoted 3 lines
Quoted 1 line

+ /// - ptr must be a valid pointer to an allocated and initialized list_head structure.

Same here, what exactly is meant by "allocated"?

Removed "allocated" from from_raw() safety docs as well. Updated to:

ptr must be a valid pointer to an initialized list_head (e.g. via INIT_LIST_HEAD()), with valid non-NULL next/prev pointers.

Quoted 5 lines

rust/kernel/ffi/clist.rs line 124

Quoted 2 lines
rust/kernel/ffi/clist.rs new file +2 -0
+    /// - The list and all linked `list_head` nodes must not be modified by non-Rust code
+    ///   for the lifetime `'a`.

This is a bit vague I think, concurrent modifications of (other) Rust code are not OK either.

Fixed. Changed to "must not be concurrently modified for the lifetime 'a" which covers both Rust and C code.

Quoted 11 lines

rust/kernel/ffi/clist.rs line 145

Quoted 3 lines
rust/kernel/ffi/clist.rs new file +3 -0
+        // SAFETY:
+        // - `self.as_raw()` is valid per type invariants.
+        // - The `next` pointer is guaranteed to be non-NULL.

I'm not sure whether "valid" in the type invariant implies that the struct list_head is initialized. From a language point of view it is also valid if the pointers are NULL.

So, I think the invariant (and the safety requirements of from_raw()) have to ensure that the struct list_head is initialized in the sense of INIT_LIST_HEAD().

Agreed. The invariant and from_raw() safety requirements now explicitly require INIT_LIST_HEAD() initialization with valid non-NULL next/prev pointers. The next() SAFETY comment now reads:

- self.as_raw() is valid and initialized per type invariants.
- The next pointer is valid and non-NULL per type invariants (initialized via INIT_LIST_HEAD() or equivalent).

Quoted 5 lines

rust/kernel/ffi/clist.rs line 229

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

Comments from CListHead also apply here.

Updated CList invariants and from_raw() safety docs to match the CListHead pattern (removed "allocated", added INIT_LIST_HEAD, non-NULL pointers, "concurrently modified").

Quoted 5 lines
Quoted 1 line

+/// This is an unsafe macro. The caller must ensure:

Given that, we should probably use the same (or a similar) trick as in [1].

[1] https://rust.docs.kernel.org/src/kernel/device.rs.html#665-688

Done. Applied the device.rs pattern - the macro now requires clist_create!(unsafe { ... }) syntax, which forces callers to acknowledge the safety requirements at the call site. The macro internally wraps the CList::from_raw call in an unsafe block.

Thanks for the review!

Joel

author reviewer
#19 lore raw

Re: [PATCH v10 5/8] rust: clist: Add support to interface with C linked lists

Quoted 7 lines · Joel Fernandes
Quoted 4 lines · Danilo Krummrich
Quoted 1 line · Joel Fernandes

+RUST TO C LIST INTERFACES

Maybe this should just be "RUST [FFI]" instead (in case Alex and you want to sign up for looking after FFI helper infrastructure in general)?

Good idea, done.

Actually, I am not sure we want to commit to entire RUST FFI infra though its pretty tiny right now. Most of this infra right now is clist, let us start with keeping it as is "RUST TO C LIST INTERFACES" ? Or we could make it "C LIST INTERFACES [RUST]" sections.

Let me know yours and everyone's thoughts.

Thanks,

--
Joel Fernandes

maintainer
#20 lore raw

Re: [PATCH v10 5/8] rust: clist: Add support to interface with C linked lists

Quoted 9 lines · Joel Fernandes
Quoted 6 lines · Joel Fernandes
Quoted 4 lines · Danilo Krummrich
Quoted 1 line · Joel Fernandes

+RUST TO C LIST INTERFACES

Maybe this should just be "RUST [FFI]" instead (in case Alex and you want to sign up for looking after FFI helper infrastructure in general)?

Quoted 6 lines
Quoted 1 line

Good idea, done.

Actually, I am not sure we want to commit to entire RUST FFI infra though its pretty tiny right now. Most of this infra right now is clist, let us start with keeping it as is "RUST TO C LIST INTERFACES" ? Or we could make it "C LIST INTERFACES [RUST]" sections.

I feel like it makes a bit more sense to have an entry for the entire class of "RUST [FFI]" infrastructure.

I could imagine that we will find quite some more cases where an FFI abstraction layer makes sense; at some point it might even go the other way around.

Once that happens, I think it would be good to have people looking after intermediate FFI layers in general. But it does not have to be you of course.

Maybe we can create the "RUST [FFI]" entry already with the following constraint:

RUST [FFI]
M: Joel Fernandes <[email protected]> (CLIST)
M: Alexandre Courbot <[email protected]> (CLIST)
L: [email protected]
S: Maintained
F: rust/kernel/ffi/

author reviewer
#21 lore raw

Re: [PATCH v10 5/8] rust: clist: Add support to interface with C linked lists

Quoted 29 lines · Danilo Krummrich
Quoted 9 lines · Joel Fernandes
Quoted 6 lines · Joel Fernandes
Quoted 4 lines · Danilo Krummrich
Quoted 1 line · Joel Fernandes

+RUST TO C LIST INTERFACES

Maybe this should just be "RUST [FFI]" instead (in case Alex and you want to sign up for looking after FFI helper infrastructure in general)?

Quoted 6 lines
Quoted 1 line

Good idea, done.

Actually, I am not sure we want to commit to entire RUST FFI infra though its pretty tiny right now. Most of this infra right now is clist, let us start with keeping it as is "RUST TO C LIST INTERFACES" ? Or we could make it "C LIST INTERFACES [RUST]" sections.

I feel like it makes a bit more sense to have an entry for the entire class of "RUST [FFI]" infrastructure.

I could imagine that we will find quite some more cases where an FFI abstraction layer makes sense; at some point it might even go the other way around.

Once that happens, I think it would be good to have people looking after intermediate FFI layers in general. But it does not have to be you of course.

Maybe we can create the "RUST [FFI]" entry already with the following constraint:

Quoted 6 lines

RUST [FFI]
M: Joel Fernandes <[email protected]> (CLIST)
M: Alexandre Courbot <[email protected]> (CLIST)
L: [email protected]
S: Maintained
F: rust/kernel/ffi/

Yeah, this is a good idea. I am Ok with that. Alex/Miguel, you're Ok with this too?

If all in agreement, I can make this change for next revision.

Thanks,

--
Joel Fernandes

#22 lore raw

Re: [PATCH v10 5/8] rust: clist: Add support to interface with C linked lists

Quoted 4 lines · Joel Fernandes

Yeah, this is a good idea. I am Ok with that. Alex/Miguel, you're Ok with this too?

If all in agreement, I can make this change for next revision.

It would be very good to get you guys (and NVIDIA) more involved in general, so thank you! :) -- (and Danilo for proposing it)

Do you want that I set up a branch for that like rust-ffi? It is usually what we are doing lately for things like this, and slowly splitting things into more pieces. I see you both have already sent in the past a few GIT PULLs etc., so possibly this is not that interesting for you, but we can still do it.

Cheers,
Miguel

author reviewer
#23 lore raw

Re: [PATCH v10 5/8] rust: clist: Add support to interface with C linked lists

Quoted 9 lines · Miguel Ojeda
Quoted 5 lines · Joel Fernandes

Yeah, this is a good idea. I am Ok with that. Alex/Miguel, you're Ok with this too?

If all in agreement, I can make this change for next revision.

It would be very good to get you guys (and NVIDIA) more involved in general, so thank you! :) -- (and Danilo for proposing it)

Sounds good. :)

Quoted 5 lines

Do you want that I set up a branch for that like rust-ffi? It is usually what we are doing lately for things like this, and slowly splitting things into more pieces. I see you both have already sent in the past a few GIT PULLs etc., so possibly this is not that interesting for you, but we can still do it.

I think let us see how it goes and how much is the volume? If it is light then I/we could send you a pull request from personal kernel.org repository, if not then we can set up a branch at that time. What do you think?

--
Joel Fernandes

#24 lore raw

Re: [PATCH v10 5/8] rust: clist: Add support to interface with C linked lists

Quoted 5 lines · Joel Fernandes

I think let us see how it goes and how much is the volume? If it is light then I/we could send you a pull request from personal kernel.org repository, if not then we can set up a branch at that time. What do you think?

If it is very light, then we could just do Acked-bys, but setting up a branch is easy:

https://github.com/Rust-for-Linux/linux/tree/ffi-next

Please feel free to use it (if so, please let me know your GitHub handle -- I already have Alexandre's); otherwise, we can delete it.

Having all branches in the same place is good for others to have a single place to look into, and has the advantage of being able to add it there as a T: field already.

Thanks!

Cheers,
Miguel

author reviewer
#25 lore raw

Re: [PATCH v10 5/8] rust: clist: Add support to interface with C linked lists

Quoted 7 lines · Miguel Ojeda
Quoted 5 lines · Joel Fernandes

I think let us see how it goes and how much is the volume? If it is light then I/we could send you a pull request from personal kernel.org repository, if not then we can set up a branch at that time. What do you think?

Quoted 7 lines

If it is very light, then we could just do Acked-bys, but setting up a branch is easy:

https://github.com/Rust-for-Linux/linux/tree/ffi-next

Please feel free to use it (if so, please let me know your GitHub handle -- I already have Alexandre's); otherwise, we can delete it.

Sounds good, my github handle is @joelagnel

Quoted 4 lines

Having all branches in the same place is good for others to have a single place to look into, and has the advantage of being able to add it there as a T: field already.

Sure, I'll include it in T:.

Thanks!

--
Joel Fernandes

#26 lore raw

Re: [PATCH v10 5/8] rust: clist: Add support to interface with C linked lists

In reply to Joel Fernandes
Quoted 39 lines · Joel Fernandes
Quoted 29 lines · Danilo Krummrich
Quoted 9 lines · Joel Fernandes
Quoted 6 lines · Joel Fernandes
Quoted 4 lines · Danilo Krummrich
Quoted 1 line · Joel Fernandes

+RUST TO C LIST INTERFACES

Maybe this should just be "RUST [FFI]" instead (in case Alex and you want to sign up for looking after FFI helper infrastructure in general)?

Quoted 6 lines
Quoted 1 line

Good idea, done.

Actually, I am not sure we want to commit to entire RUST FFI infra though its pretty tiny right now. Most of this infra right now is clist, let us start with keeping it as is "RUST TO C LIST INTERFACES" ? Or we could make it "C LIST INTERFACES [RUST]" sections.

I feel like it makes a bit more sense to have an entry for the entire class of "RUST [FFI]" infrastructure.

I could imagine that we will find quite some more cases where an FFI abstraction layer makes sense; at some point it might even go the other way around.

Once that happens, I think it would be good to have people looking after intermediate FFI layers in general. But it does not have to be you of course.

Maybe we can create the "RUST [FFI]" entry already with the following constraint:

Quoted 6 lines

RUST [FFI]
M: Joel Fernandes <[email protected]> (CLIST)
M: Alexandre Courbot <[email protected]> (CLIST)
L: [email protected]
S: Maintained
F: rust/kernel/ffi/

Quoted 3 lines

Yeah, this is a good idea. I am Ok with that. Alex/Miguel, you're Ok with this too?

If all in agreement, I can make this change for next revision.

Sure (once we agree on what the entry should be named), that should be low-bandwidth anyway as folks will be discouraged to use this module whenever possible anyway. :)

reviewer
#27 lore raw

Re: [PATCH v10 5/8] rust: clist: Add support to interface with C linked lists

In reply to Danilo Krummrich
Quoted 12 lines · Danilo Krummrich
Quoted 11 lines · Joel Fernandes
Quoted 7 lines · Joel Fernandes
Quoted 4 lines · Danilo Krummrich
Quoted 1 line · Joel Fernandes

+RUST TO C LIST INTERFACES

Maybe this should just be "RUST [FFI]" instead (in case Alex and you want to sign up for looking after FFI helper infrastructure in general)?

Good idea, done.

Quoted 7 lines
Quoted 4 lines

Actually, I am not sure we want to commit to entire RUST FFI infra though its pretty tiny right now. Most of this infra right now is clist, let us start with keeping it as is "RUST TO C LIST INTERFACES" ? Or we could make it "C LIST INTERFACES [RUST]" sections.

I feel like it makes a bit more sense to have an entry for the entire class of "RUST [FFI]" infrastructure.

I don't think so. Most of the kernel crate is doing FFI. We have a ffi crate defining FFI types, we have CStr/CString which in Rust std is inside std::ffi, etc.

I feel that the FFI infra is the core responsibility of the top-level Rust entry, while specific stuff can be splitted out.

Best,
Gary

Quoted 16 lines

I could imagine that we will find quite some more cases where an FFI abstraction layer makes sense; at some point it might even go the other way around.

Once that happens, I think it would be good to have people looking after intermediate FFI layers in general. But it does not have to be you of course.

Maybe we can create the "RUST [FFI]" entry already with the following constraint:

RUST [FFI]
M: Joel Fernandes <[email protected]> (CLIST)
M: Alexandre Courbot <[email protected]> (CLIST)
L: [email protected]
S: Maintained
F: rust/kernel/ffi/

#28 lore raw

Re: [PATCH v10 5/8] rust: clist: Add support to interface with C linked lists

Quoted 4 lines · Gary Guo

I don't think so. Most of the kernel crate is doing FFI. We have a ffi crate defining FFI types, we have CStr/CString which in Rust std is inside std::ffi, etc.

Yeah, I don't love that name either, for similar reasons.

(The entry would still be a sub-entry, either way).

Thanks!

Cheers,
Miguel

maintainer
#29 lore raw

Re: [PATCH v10 5/8] rust: clist: Add support to interface with C linked lists

In reply to Gary Guo
Quoted 7 lines · Gary Guo
Quoted 2 lines · Danilo Krummrich

I feel like it makes a bit more sense to have an entry for the entire class of "RUST [FFI]" infrastructure.

I don't think so. Most of the kernel crate is doing FFI. We have a ffi crate defining FFI types, we have CStr/CString which in Rust std is inside std::ffi, etc.

The idea is not that everything that somehow has an FFI interface falls under this category, as this would indeed be the majority.

The idea is rather everything that is specifically designed as a helper to implement FFI interactions. (Given that maybe just "RUST [FFI HELPER]"?)

For instance, this would also apply to Opaque and ForeignOwnable. But also CStr and CString, as you say.

But there's also lots of stuff that does not fall under this category, such as pin-init, alloc, syn, num, bits (genmask), fmt, slice, revocable, list, ptr, assert, print, arc, etc.

There are also things that are more on the "partially" side of things, such as transmute, error or aref.

Quoted 2 lines

I feel that the FFI infra is the core responsibility of the top-level Rust entry, while specific stuff can be splitted out.

I think the core responsibilities are compiler and general design topics, such as abstraction design, (safety) documentation, etc., as well as core language infrastructure, such as pin-init, syn, alloc, arc, etc.

Given the definition "helper to implement FFI interactions" I feel like we have much more infrastructure that is not for this specific purpose.

author reviewer
#30 lore raw

Re: [PATCH v10 5/8] rust: clist: Add support to interface with C linked lists

Quoted 9 lines · Danilo Krummrich
Quoted 7 lines · Gary Guo
Quoted 2 lines · Danilo Krummrich

I feel like it makes a bit more sense to have an entry for the entire class of "RUST [FFI]" infrastructure.

I don't think so. Most of the kernel crate is doing FFI. We have a ffi crate defining FFI types, we have CStr/CString which in Rust std is inside std::ffi, etc.

Quoted 5 lines

The idea is not that everything that somehow has an FFI interface falls under this category, as this would indeed be the majority.

The idea is rather everything that is specifically designed as a helper to implement FFI interactions. (Given that maybe just "RUST [FFI HELPER]"?)

I do tend to agree with Danilo on this. Unless someone yells, I will change the maintainer entry to "RUST [FFI HELPER]" for the next spin.

thanks,

--
Joel FErnandes

Quoted 20 lines

For instance, this would also apply to Opaque and ForeignOwnable. But also CStr and CString, as you say.

But there's also lots of stuff that does not fall under this category, such as pin-init, alloc, syn, num, bits (genmask), fmt, slice, revocable, list, ptr, assert, print, arc, etc.

There are also things that are more on the "partially" side of things, such as transmute, error or aref.

Quoted 2 lines

I feel that the FFI infra is the core responsibility of the top-level Rust entry, while specific stuff can be splitted out.

I think the core responsibilities are compiler and general design topics, such as abstraction design, (safety) documentation, etc., as well as core language infrastructure, such as pin-init, syn, alloc, arc, etc.

Given the definition "helper to implement FFI interactions" I feel like we have much more infrastructure that is not for this specific purpose.

#31 lore raw

Re: [PATCH v10 5/8] rust: clist: Add support to interface with C linked lists

Quoted 3 lines · Joel Fernandes

I do tend to agree with Danilo on this. Unless someone yells, I will change the maintainer entry to "RUST [FFI HELPER]" for the next spin.

Not sure I am following the "what FFI means" discussion, but in case it clarifies:

The Rust subsystem is meant to be about anything related in some way to Rust; typically meaning all the things that are not covered elsewhere (including what both Gary and Danilo mention), sometimes with overlap with other "global" infrastructure/subsystems (e.g. Kbuild), sometimes acting as a fallback for Rust code out there if really needed (i.e. similar to Andrew, but for Rust bits), and so on.

From what I understand, Joel and Alexandre want to focus on maintaining the clist bits (at least for now), and if they are both going to have the "(CLIST)" suffix, then it may be simpler to make the entry just that for now since MAINTAINERS it is easy to change anyway.

Now, what kind of things would we want to have inside such a ffi module? (apart from clist). Does it mean the proposal is to eventually move existing things like CStr?

Cheers,
Miguel

reviewer
#32 lore raw

Re: [PATCH v10 5/8] rust: clist: Add support to interface with C linked lists

In reply to Danilo Krummrich
Quoted 9 lines · Danilo Krummrich
Quoted 7 lines · Gary Guo
Quoted 2 lines · Danilo Krummrich

I feel like it makes a bit more sense to have an entry for the entire class of "RUST [FFI]" infrastructure.

I don't think so. Most of the kernel crate is doing FFI. We have a ffi crate defining FFI types, we have CStr/CString which in Rust std is inside std::ffi, etc.

Quoted 6 lines

The idea is not that everything that somehow has an FFI interface falls under this category, as this would indeed be the majority.

The idea is rather everything that is specifically designed as a helper to implement FFI interactions. (Given that maybe just "RUST [FFI HELPER]"?)

I feel like you may want to call it "interop" then, because it's "Rust doing something with interoperation on C data structure". If I understand you correctly, the category you referred here is the area that we could not simply call an FFI function to get the functionality from C side, but rather we need to make sure that we are interpret C data structure correctly to work with C side.

Regards,
Boqun

Quoted 19 lines

For instance, this would also apply to Opaque and ForeignOwnable. But also CStr and CString, as you say.

But there's also lots of stuff that does not fall under this category, such as pin-init, alloc, syn, num, bits (genmask), fmt, slice, revocable, list, ptr, assert, print, arc, etc.

There are also things that are more on the "partially" side of things, such as transmute, error or aref.

Quoted 2 lines

I feel that the FFI infra is the core responsibility of the top-level Rust entry, while specific stuff can be splitted out.

I think the core responsibilities are compiler and general design topics, such as abstraction design, (safety) documentation, etc., as well as core language infrastructure, such as pin-init, syn, alloc, arc, etc.

Given the definition "helper to implement FFI interactions" I feel like we have much more infrastructure that is not for this specific purpose.

author reviewer
#33 lore raw

Re: [PATCH v10 5/8] rust: clist: Add support to interface with C linked lists

Quoted 17 lines · Boqun Feng
Quoted 9 lines · Danilo Krummrich
Quoted 7 lines · Gary Guo
Quoted 2 lines · Danilo Krummrich

I feel like it makes a bit more sense to have an entry for the entire class of "RUST [FFI]" infrastructure.

I don't think so. Most of the kernel crate is doing FFI. We have a ffi crate defining FFI types, we have CStr/CString which in Rust std is inside std::ffi, etc.

Quoted 6 lines

The idea is not that everything that somehow has an FFI interface falls under this category, as this would indeed be the majority.

The idea is rather everything that is specifically designed as a helper to implement FFI interactions. (Given that maybe just "RUST [FFI HELPER]"?)

Quoted 6 lines

I feel like you may want to call it "interop" then, because it's "Rust doing something with interoperation on C data structure". If I understand you correctly, the category you referred here is the area that we could not simply call an FFI function to get the functionality from C side, but rather we need to make sure that we are interpret C data structure correctly to work with C side.

Boqun has a point here: https://en.wikipedia.org/wiki/Language_interoperability

thanks,

--
Joel Fernandes

author reviewer
#34 lore raw

Re: [PATCH v10 5/8] rust: clist: Add support to interface with C linked lists

Quoted 22 lines · Joel Fernandes



Quoted 18 lines · Boqun Feng
Quoted 16 lines · Danilo Krummrich
Quoted 7 lines · Gary Guo
Quoted 2 lines · Danilo Krummrich

I feel like it makes a bit more sense to have an entry for the entire class of "RUST [FFI]" infrastructure.

I don't think so. Most of the kernel crate is doing FFI. We have a ffi crate defining FFI types, we have CStr/CString which in Rust std is inside std::ffi, etc.

The idea is not that everything that somehow has an FFI interface falls under this category, as this would indeed be the majority.

The idea is rather everything that is specifically designed as a helper to implement FFI interactions. (Given that maybe just "RUST [FFI HELPER]"?)

Quoted 9 lines
Quoted 6 lines

I feel like you may want to call it "interop" then, because it's "Rust doing something with interoperation on C data structure". If I understand you correctly, the category you referred here is the area that we could not simply call an FFI function to get the functionality from C side, but rather we need to make sure that we are interpret C data structure correctly to work with C side.

Boqun has a point here: https://en.wikipedia.org/wiki/Language_interoperability

If we move forward with this wording we probably have to then rename the directory to rust/interop. That's probably not worth it I think since ffi and interop seem to be pretty closely related. I suggest let us keep it as helper wording for now as Danilo suggested. We can always change it later if need arises.

Signature · 1 line
Joel Fernandes
#35 lore raw

Re: [PATCH v10 5/8] rust: clist: Add support to interface with C linked lists

In reply to Joel Fernandes
Quoted 26 lines · Joel Fernandes
rust/kernel/ffi/clist.rs new file +26 -0
+/// 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/ffi/clist.rs line 327

Quoted 10 lines
rust/kernel/ffi/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::ffi::clist::CList::<$rust_type, OFFSET>::from_raw($head)
+    }};
+}

This uses offset_of! in a way that requires the offset_of_nested feature, so it doesn't build in rust 1.78.0. The feature is already added to rust_allowed_features, so I think it's ok to add #![feature(offset_of_nested)].

author reviewer
#36 lore raw

Re: [PATCH v10 5/8] rust: clist: Add support to interface with C linked lists

Hi Eliot,

Quoted 34 lines · Eliot Courtney
Quoted 33 lines · Joel Fernandes
rust/kernel/ffi/clist.rs new file +33 -0
+/// 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 {
+    ($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).+);
Quoted 8 lines

rust/kernel/ffi/clist.rs line 327

Quoted 3 lines
rust/kernel/ffi/clist.rs new file +3 -0
+        $crate::ffi::clist::CList::<$rust_type, OFFSET>::from_raw($head)
+    }};
+}

This uses offset_of! in a way that requires the offset_of_nested feature, so it doesn't build in rust 1.78.0. The feature is already added to rust_allowed_features, so I think it's ok to add #![feature(offset_of_nested)].

Maybe I am missing something, but why should the feature be gated behind that if all compiler versions (>= 1.78) support it either in a stable way or via an unstable feature flag?

thanks,

--
Joel Fernandes

#37 lore raw

Re: [PATCH v10 5/8] rust: clist: Add support to interface with C linked lists

Quoted 17 lines · Joel Fernandes
Quoted 8 lines
Quoted 8 lines
rust/kernel/ffi/clist.rs new file +8 -0
+macro_rules! clist_create {
+    ($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).+);
Quoted 8 lines

rust/kernel/ffi/clist.rs line 327

Quoted 3 lines
rust/kernel/ffi/clist.rs new file +3 -0
+        $crate::ffi::clist::CList::<$rust_type, OFFSET>::from_raw($head)
+    }};
+}

This uses offset_of! in a way that requires the offset_of_nested feature, so it doesn't build in rust 1.78.0. The feature is already added to rust_allowed_features, so I think it's ok to add #![feature(offset_of_nested)].

Quoted 3 lines

Maybe I am missing something, but why should the feature be gated behind that if all compiler versions (>= 1.78) support it either in a stable way or via an unstable feature flag?

I think that's why it's in rust_allowed_features. IIUC that's where we put unstable features that are stable enough in all supported compiler versions to be used.

But, rust_allowed_features doesn't apply to the code here, so you'd have to add an allow to rust/kernel/lib.rs.

maintainer
#38 lore raw

Re: [PATCH v10 5/8] rust: clist: Add support to interface with C linked lists

In reply to Joel Fernandes
Quoted 47 lines · Joel Fernandes

Hi Eliot,

Quoted 34 lines · Eliot Courtney
Quoted 33 lines · Joel Fernandes
rust/kernel/ffi/clist.rs new file +33 -0
+/// 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 {
+    ($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).+);
Quoted 8 lines

rust/kernel/ffi/clist.rs line 327

Quoted 3 lines
rust/kernel/ffi/clist.rs new file +3 -0
+        $crate::ffi::clist::CList::<$rust_type, OFFSET>::from_raw($head)
+    }};
+}

This uses offset_of! in a way that requires the offset_of_nested feature, so it doesn't build in rust 1.78.0. The feature is already added to rust_allowed_features, so I think it's ok to add #![feature(offset_of_nested)].

Quoted 3 lines

Maybe I am missing something, but why should the feature be gated behind that if all compiler versions (>= 1.78) support it either in a stable way or via an unstable feature flag?

The rust_allowed_features list only applies to drivers and such. It doesn't apply to the Rust crates in the rust/ directory, which need to use #![feature] annotations manually.

Alice

author reviewer
#39 lore raw

Re: [PATCH v10 5/8] rust: clist: Add support to interface with C linked lists

Quoted 48 lines · Alice Ryhl
Quoted 47 lines · Joel Fernandes

Hi Eliot,

Quoted 42 lines · Eliot Courtney
Quoted 26 lines · Joel Fernandes
rust/kernel/ffi/clist.rs new file +26 -0
+/// 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/ffi/clist.rs line 327

Quoted 10 lines
rust/kernel/ffi/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::ffi::clist::CList::<$rust_type, OFFSET>::from_raw($head)
+    }};
+}

This uses offset_of! in a way that requires the offset_of_nested feature, so it doesn't build in rust 1.78.0. The feature is already added to rust_allowed_features, so I think it's ok to add #![feature(offset_of_nested)].

Quoted 7 lines
Quoted 3 lines

Maybe I am missing something, but why should the feature be gated behind that if all compiler versions (>= 1.78) support it either in a stable way or via an unstable feature flag?

The rust_allowed_features list only applies to drivers and such. It doesn't apply to the Rust crates in the rust/ directory, which need to use #![feature] annotations manually.

Ah fun! Ok, I will add it in in. :)

thanks,

--
Joel Fernandes

#40 lore raw

Re: [PATCH v10 5/8] rust: clist: Add support to interface with C linked lists

Quoted 2 lines · Joel Fernandes

Ah fun! Ok, I will add it in in. :)

To clarify further, the reason is that the crates in rust/ may (and do) use more features (which still need justification), but the rest of the kernel is restricted to those in that "allowed" list only.

https://rust-for-linux.com/unstable-features#usage-in-the-kernel

Cheers,
Miguel

maintainer
#41 lore raw

Re: [PATCH v10 5/8] rust: clist: Add support to interface with C linked lists

In reply to Joel Fernandes
Quoted 10 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.

In general this looks like a useful tool to write other abstractions, so that's good. A few nits below.

Also, I think it would make more sense to split this series into two with titles like this:

* Add clist helper for writing abstractions using C lists
* Move buddy alloctor one level up

That way, you can tell what the series actually does from its title. Yes, the 'why' of a series is very important, and must be included in the cover letter or commit messages, but I think the title of a series should explain the 'what', not the 'why'.

rust/kernel/ffi/clist.rs line 124

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

I don't think C vs Rust is useful here. What you want is that the list is not modified by random other code in ways you didn't expect. It doesn't matter if it's C or Rust code that carries out the illegal modification.

rust/kernel/ffi/clist.rs line 171

Quoted 6 lines
rust/kernel/ffi/clist.rs new file +6 -0
+// SAFETY: [`CListHead`] can be sent to any thread.
+unsafe impl Send for CListHead {}
+
+// 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 {}

Same here. If another piece of Rust code modifies the list in parallel from another thread, you'll have a bad time too. C vs Rust does not matter.

Alice

author reviewer
#42 lore raw

Re: [PATCH v10 5/8] rust: clist: Add support to interface with C linked lists

Hi Alice,

Quoted 18 lines · Alice Ryhl
Quoted 10 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.

In general this looks like a useful tool to write other abstractions, so that's good. A few nits below.

Also, I think it would make more sense to split this series into two with titles like this:

Quoted 7 lines

* Add clist helper for writing abstractions using C lists
* Move buddy alloctor one level up

That way, you can tell what the series actually does from its title. Yes, the 'why' of a series is very important, and must be included in the cover letter or commit messages, but I think the title of a series should explain the 'what', not the 'why'.

Sure, that makes sense I can move the buddy patches into a different series indeed.

Quoted 11 lines

rust/kernel/ffi/clist.rs line 124

Quoted 10 lines
rust/kernel/ffi/clist.rs new file +9 -0
+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`.
Quoted 4 lines

I don't think C vs Rust is useful here. What you want is that the list is not modified by random other code in ways you didn't expect. It doesn't matter if it's C or Rust code that carries out the illegal modification.

Yeah, this is true. I will change it to the following then:

"The list and all linked list_head nodes must not be modified from anywhere for the lifetime 'a."

Quoted 11 lines

rust/kernel/ffi/clist.rs line 171

Quoted 7 lines
rust/kernel/ffi/clist.rs new file +6 -0
+// SAFETY: [`CListHead`] can be sent to any thread.
+unsafe impl Send for CListHead {}
+
+// 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 {}

Same here. If another piece of Rust code modifies the list in parallel from another thread, you'll have a bad time too. C vs Rust does not matter.

Ack, will change it to:
// SAFETY: [CListHead] can be shared among threads as it is // read-only per safety requirements of [CListHead::from_raw].

thanks,

--
Joel Fernandes

maintainer
#43 lore raw

Re: [PATCH v10 5/8] rust: clist: Add support to interface with C linked lists

Quoted 19 lines · Joel Fernandes

Hi Alice,

Quoted 11 lines · Alice Ryhl

rust/kernel/ffi/clist.rs line 124

Quoted 9 lines · Joel Fernandes
rust/kernel/ffi/clist.rs new file +9 -0
+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`.
Quoted 4 lines

I don't think C vs Rust is useful here. What you want is that the list is not modified by random other code in ways you didn't expect. It doesn't matter if it's C or Rust code that carries out the illegal modification.

Quoted 4 lines

Yeah, this is true. I will change it to the following then:

"The list and all linked list_head nodes must not be modified from anywhere for the lifetime 'a."

Ok. Perhaps you should say that it must not be modified except through this CListHead? I guess it depends on whether you want to add methods for changing the list via this API.

Alice

author reviewer
#44 lore raw

Re: [PATCH v10 5/8] rust: clist: Add support to interface with C linked lists

Quoted 20 lines · Alice Ryhl
Quoted 19 lines · Joel Fernandes

Hi Alice,

Quoted 15 lines · Alice Ryhl

rust/kernel/ffi/clist.rs line 124

Quoted 9 lines · Joel Fernandes
rust/kernel/ffi/clist.rs new file +9 -0
+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`.

I don't think C vs Rust is useful here. What you want is that the list is not modified by random other code in ways you didn't expect. It doesn't matter if it's C or Rust code that carries out the illegal modification.

Quoted 9 lines
Quoted 4 lines

Yeah, this is true. I will change it to the following then:

"The list and all linked list_head nodes must not be modified from anywhere for the lifetime 'a."

Ok. Perhaps you should say that it must not be modified except through this CListHead? I guess it depends on whether you want to add methods for changing the list via this API.

At the moment, there isn't a usecase for it but I would predict we would want it for other such use cases, so yet I will change it to your suggestion to future-proof it:

"The list and all linked list_head nodes must not be modified from anywhere for the lifetime 'a, unless done so via any ClistHead APIs."

Let me know if it looks good?

thanks,

--
Joel Fernandes

author reviewer
#45 lore raw

PATCH v10 6/8 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 0a77b4c0ffeb..1cd6feff4f02 100644
@@ -96,6 +96,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
#46 lore raw

Re: [PATCH v10 6/8] rust: gpu: Add GPU buddy allocator bindings

Just a few things caught when building.

On Thu Feb 19, 2026 at 5:55 AM JST, Joel Fernandes wrote:
<snip>

rust/kernel/gpu/buddy.rs line 146

Quoted 13 lines
rust/kernel/gpu/buddy.rs new file +13 -0
+use crate::{
+    bindings,
+    clist_create,
+    error::to_result,
+    ffi::clist::CListHead,
+    new_mutex,
+    prelude::*,
+    sync::{
+        lock::mutex::MutexGuard,
+        Arc,
+        Mutex, //
+    },
+    types::Opaque,

Need a // or rustfmt will reformat.

<snip>

rust/kernel/gpu/buddy.rs line 294

Quoted 13 lines
rust/kernel/gpu/buddy.rs new file +13 -0
+#[pinned_drop]
+impl PinnedDrop for GpuBuddyInner {
+    fn drop(self: Pin<&mut Self>) {
+        let guard = self.lock();
+
+        // SAFETY: guard provides exclusive access to the allocator.
+        unsafe {
+            bindings::gpu_buddy_fini(guard.as_raw());
+        }
+    }
+}
+
+// SAFETY: [`GpuBuddyInner`] can be sent between threads.

No need to link on non-doccomments.

rust/kernel/gpu/buddy.rs line 298

Quoted 4 lines
rust/kernel/gpu/buddy.rs new file +4 -0
+unsafe impl Send for GpuBuddyInner {}
+
+// SAFETY: [`GpuBuddyInner`] is `Sync` because the internal [`GpuBuddyGuard`]
+// serializes all access to the C allocator, preventing data races.

Here as well.

<snip>

rust/kernel/gpu/buddy.rs line 411

Quoted 10 lines
rust/kernel/gpu/buddy.rs new file +10 -0
+/// Allocated blocks from the buddy allocator with automatic cleanup.
+///
+/// This structure owns a list of allocated blocks and ensures they are
+/// automatically freed when dropped. Use `iter()` to iterate over all
+/// allocated [`Block`] structures.
+///
+/// # Invariants
+///
+/// - `list` is an initialized, valid list head containing allocated blocks.
+/// - `buddy` references a valid [`GpuBuddyInner`].

rustdoc complains that this links to a private item in a public doc - we should not mention GpuBuddyInner here.

Quoted 49 lines
rust/kernel/gpu/buddy.rs new file +49 -0
+#[pin_data(PinnedDrop)]
+pub struct AllocatedBlocks {
+    #[pin]
+    list: CListHead,
+    buddy: Arc<GpuBuddyInner>,
+    flags: BuddyFlags,
+}
+
+impl AllocatedBlocks {
+    /// Check if the block list is empty.
+    pub fn is_empty(&self) -> bool {
+        // An empty list head points to itself.
+        !self.list.is_linked()
+    }
+
+    /// Iterate over allocated blocks.
+    ///
+    /// Returns an iterator yielding [`AllocatedBlock`] values. Each [`AllocatedBlock`]
+    /// borrows `self` and is only valid for the duration of that borrow.
+    pub fn iter(&self) -> impl Iterator<Item = AllocatedBlock<'_>> + '_ {
+        // SAFETY: list contains gpu_buddy_block items linked via __bindgen_anon_1.link.
+        let clist = unsafe {
+            clist_create!(
+                self.list.as_raw(),
+                Block,
+                bindings::gpu_buddy_block,
+                __bindgen_anon_1.link
+            )
+        };
+
+        clist
+            .iter()
+            .map(|block| AllocatedBlock { block, alloc: self })
+    }
+}
+
+#[pinned_drop]
+impl PinnedDrop for AllocatedBlocks {
+    fn drop(self: Pin<&mut Self>) {
+        let guard = self.buddy.lock();
+
+        // SAFETY:
+        // - list is valid per the type's invariants.
+        // - guard provides exclusive access to the allocator.
+        // CAST: BuddyFlags were validated to fit in u32 at construction.
+        unsafe {
+            bindings::gpu_buddy_free_list(
+                guard.as_raw(),
+                self.list.as_raw(),

rust/kernel/gpu/buddy.rs line 470

Quoted 10 lines
rust/kernel/gpu/buddy.rs new file +10 -0
+                self.flags.as_raw() as u32,
+            );
+        }
+    }
+}
+
+/// A GPU buddy block.
+///
+/// Transparent wrapper over C `gpu_buddy_block` structure. This type is returned
+/// as references from [`CListIter`] during iteration over [`AllocatedBlocks`].

Link should be [CListIter](kernel::ffi::clist::CListIter) to resolve. But maybe we don't need to share that detail in the public documentation?

#47 lore raw

Re: [PATCH v10 6/8] rust: gpu: Add GPU buddy allocator bindings

Quoted 3 lines · Alexandre Courbot

rustdoc complains that this links to a private item in a public doc - we should not mention GpuBuddyInner here.

If you all think something should be mentioned for practical reasons, then please don't let rustdoc force you to not mention it, i.e. please feel free to remove the square brackets if needed.

In other words, I don't want the intra-doc links convention we have to make it harder for you to write certain things exceptionally.

I hope that helps.

Cheers,
Miguel

author reviewer
#48 lore raw

Re: [PATCH v10 6/8] rust: gpu: Add GPU buddy allocator bindings

Quoted 6 lines · Miguel Ojeda

If you all think something should be mentioned for practical reasons, then please don't let rustdoc force you to not mention it, i.e. please feel free to remove the square brackets if needed.

In other words, I don't want the intra-doc links convention we have to make it harder for you to write certain things exceptionally.

Thanks Miguel, that's helpful! I've kept the GpuBuddyInner mention in the invariants but removed the square brackets to avoid the rustdoc warning while still providing the reference for readers.

Joel

reviewer
#49 lore raw

Re: [PATCH v10 6/8] rust: gpu: Add GPU buddy allocator bindings

Quoted 5 lines · Joel Fernandes
Quoted 4 lines · Miguel Ojeda

If you all think something should be mentioned for practical reasons, then please don't let rustdoc force you to not mention it, i.e. please feel free to remove the square brackets if needed.

Quoted 8 lines
Quoted 2 lines

In other words, I don't want the intra-doc links convention we have to make it harder for you to write certain things exceptionally.

Thanks Miguel, that's helpful! I've kept the GpuBuddyInner mention in the invariants but removed the square brackets to avoid the rustdoc warning while still providing the reference for readers.

Joel

I started to think that the way we document invariants is problematic. For most of the types, the invariants mentioned does not make sense to end up in public facing docs.

Perhaps we should:
- Document invariants on specific fields as doc comments on the fields. So they don't show up in the doc unless document-private-items is enabled.
- Invariants across multiple fields perhaps should either be documented as normal (non-doc) comments, or we do something like:

struct Foo {
    field_a: X,
    field_b: Y,
    // Put invariants here
    _invariant: (),
}

This has an additional benefit where when you're constructing the type, you're forced to write

Foo {
    ...,
    _invariant: (),
}

where you're reminded that invariants exist on the type and cannot forget to write an invariant comment.

Best,
Gary

#50 lore raw

Re: [PATCH v10 6/8] rust: gpu: Add GPU buddy allocator bindings

Quoted 4 lines · Gary Guo

I started to think that the way we document invariants is problematic. For most of the types, the invariants mentioned does not make sense to end up in public facing docs.

Yeah, it isn't ideal.

To give some context in case it helps, so far we said that the # Invariants section is a special case where mentioning private fields is OK-ish if needed/helpful for a reader, even if technically it may not be "proper", i.e. leak details.

One reason was that sometimes private invariants may make the type easier to understand, even if technically it is a private one. We also discussed at some point splitting invariants into public and private ones, and perhaps have rustdoc know about that and only render the private ones when one toggles the private items rendering (runtime toggle, which is another feature I requested -- if it is compile-time as it is the normal flag, then reading the private docs becomes too hard).

Another reason was to be able to have them use doc comments and get a nice rendering output, and your suggestion of using a dummy field would work for that. I like the fact that it makes one remember to write the invariant "natively". On the other hand, it seems like something we could somehow do with changes in tooling, i.e. in rustdoc or Clippy (and perhaps it could be enforced rather than just be a reminder).

Another bit was that sometimes the invariant, even if it applies to a private field, the type may be exposing e.g. a copy of the field through a method, and thus it is useful to know about the invariant anyway. Those cases could/should "properly" be a guarantee on the return value of that method, keeping the invariant private, though.

In short, the current approach makes it easy to write for everyone, but it does have downsides and ideally we would have something better now that everyone is accustomed to writing them.

Cheers,
Miguel

author reviewer
#51 lore raw

Re: [PATCH v10 6/8] rust: gpu: Add GPU buddy allocator bindings

In reply to Alexandre Courbot
Quoted 3 lines · Alexandre Courbot
Quoted 1 line

+ types::Opaque,

Need a // or rustfmt will reformat.

Fixed, thanks.

Quoted 3 lines
Quoted 1 line

+// SAFETY: [GpuBuddyInner] can be sent between threads.

No need to link on non-doccomments.

Fixed. Removed the brackets from SAFETY comments for GpuBuddyInner and GpuBuddyGuard.

Quoted 4 lines
Quoted 1 line

+/// - buddy references a valid [GpuBuddyInner].

rustdoc complains that this links to a private item in a public doc - we should not mention GpuBuddyInner here.

Per Miguel's reply, I've kept the mention but removed the square brackets so it doesn't try to create a link. This way it's still mentioned for practical reference without triggering the rustdoc warning.

Quoted 5 lines
Quoted 1 line

/// as references from [CListIter] during iteration over [AllocatedBlocks].

Link should be [CListIter](kernel::ffi::clist::CListIter) to resolve. But maybe we don't need to share that detail in the public documentation?

Agreed, removed the CListIter reference from the public doc. It now just says "as references during iteration over AllocatedBlocks".

Thanks,
Joel

#52 lore raw

Re: [PATCH v10 6/8] rust: gpu: Add GPU buddy allocator bindings

Quoted 16 lines · Joel Fernandes
Quoted 3 lines · Alexandre Courbot
Quoted 1 line

+ types::Opaque,

Need a // or rustfmt will reformat.

Fixed, thanks.

Quoted 3 lines
Quoted 1 line

+// SAFETY: [GpuBuddyInner] can be sent between threads.

No need to link on non-doccomments.

Fixed. Removed the brackets from SAFETY comments for GpuBuddyInner and GpuBuddyGuard.

Quoted 2 lines
Quoted 1 line

+/// - buddy references a valid [GpuBuddyInner].

Quoted 7 lines
Quoted 2 lines

rustdoc complains that this links to a private item in a public doc - we should not mention GpuBuddyInner here.

Per Miguel's reply, I've kept the mention but removed the square brackets so it doesn't try to create a link. This way it's still mentioned for practical reference without triggering the rustdoc warning.

Won't it be confusing for readers of the public documentation? If a type is private, it shouldn't be needed to folks who read the HTML.

This sounds like we instead want a regular // comment somewhere to guide those who brave the code.

author reviewer
#53 lore raw

Re: [PATCH v10 6/8] rust: gpu: Add GPU buddy allocator bindings

Quoted 25 lines · Alexandre Courbot
Quoted 16 lines · Joel Fernandes
Quoted 3 lines · Alexandre Courbot
Quoted 1 line

+ types::Opaque,

Need a // or rustfmt will reformat.

Fixed, thanks.

Quoted 3 lines
Quoted 1 line

+// SAFETY: [GpuBuddyInner] can be sent between threads.

No need to link on non-doccomments.

Fixed. Removed the brackets from SAFETY comments for GpuBuddyInner and GpuBuddyGuard.

Quoted 2 lines
Quoted 1 line

+/// - buddy references a valid [GpuBuddyInner].

Quoted 7 lines
Quoted 2 lines

rustdoc complains that this links to a private item in a public doc - we should not mention GpuBuddyInner here.

Per Miguel's reply, I've kept the mention but removed the square brackets so it doesn't try to create a link. This way it's still mentioned for practical reference without triggering the rustdoc warning.

Quoted 5 lines

Won't it be confusing for readers of the public documentation? If a type is private, it shouldn't be needed to folks who read the HTML.

This sounds like we instead want a regular // comment somewhere to guide those who brave the code.

You are right about the audience of the docs perhaps not requiring this information. I will remove it then.

thanks,

--
Joel Fernandes

maintainer
#54 lore raw

Re: [PATCH v10 6/8] rust: gpu: Add GPU buddy allocator bindings

In reply to Joel Fernandes

(Cc: Arun, Christian)

Quoted 7 lines · 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.

The patch should also update the MAINTAINERS file accordingly.

(I will go through the code later on.)

author reviewer
#55 lore raw

Re: [PATCH v10 6/8] rust: gpu: Add GPU buddy allocator bindings

Quoted 1 line · Danilo Krummrich

The patch should also update the MAINTAINERS file accordingly.

Will add the MAINTAINERS update for GPU buddy bindings.

Thanks,
Joel

#56 lore raw

Re: [PATCH v10 6/8] rust: gpu: Add GPU buddy allocator bindings

In reply to Joel Fernandes

rust/helpers/gpu.c line 22

Quoted 6 lines · Joel Fernandes
rust/helpers/gpu.c new file +6 -0
+__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);
+}
+

Will rust_helper_gpu_buddy_block_size be used in the future? It doesn't appear to be used in buddy.rs.

author reviewer
#57 lore raw

Re: [PATCH v10 6/8] rust: gpu: Add GPU buddy allocator bindings

Quoted 10 lines · Eliot Courtney

rust/helpers/gpu.c line 22

Quoted 6 lines · Joel Fernandes
rust/helpers/gpu.c new file +6 -0
+__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);
+}
+

Will rust_helper_gpu_buddy_block_size be used in the future? It doesn't appear to be used in buddy.rs.

I think it is worth keeping because it is a pretty basic API the underlying infrastructure. Finding the size of a block can be important in the future IMO. It is only few lines, no?

Thanks,

--
Joel Fernandes

author reviewer
#58 lore raw

Re: [PATCH v10 6/8] rust: gpu: Add GPU buddy allocator bindings

Quoted 14 lines · Joel Fernandes
Quoted 10 lines · Eliot Courtney

rust/helpers/gpu.c line 22

Quoted 6 lines · Joel Fernandes
rust/helpers/gpu.c new file +6 -0
+__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);
+}
+

Will rust_helper_gpu_buddy_block_size be used in the future? It doesn't appear to be used in buddy.rs.

Quoted 3 lines

I think it is worth keeping because it is a pretty basic API the underlying infrastructure. Finding the size of a block can be important in the future IMO. It is only few lines, no?

By the way, this can become important for non-contiguous physical memory allocations where an allocation is split across different blocks. In that case, we would the information size of each individual block, not just the whole allocation. I could probably add a test case for that.

--
Joel Fernandes

maintainer
#59 lore raw

Re: [PATCH v10 6/8] rust: gpu: Add GPU buddy allocator bindings

In reply to Joel Fernandes
Quoted 14 lines · Joel Fernandes
Quoted 10 lines · Eliot Courtney

rust/helpers/gpu.c line 22

Quoted 6 lines · Joel Fernandes
rust/helpers/gpu.c new file +6 -0
+__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);
+}
+

Will rust_helper_gpu_buddy_block_size be used in the future? It doesn't appear to be used in buddy.rs.

Quoted 3 lines

I think it is worth keeping because it is a pretty basic API the underlying infrastructure. Finding the size of a block can be important in the future IMO. It is only few lines, no?

The helper should be added with the code using it.

author reviewer
#60 lore raw

Re: [PATCH v10 6/8] rust: gpu: Add GPU buddy allocator bindings

Quoted 15 lines · Danilo Krummrich
Quoted 14 lines · Joel Fernandes
Quoted 10 lines · Eliot Courtney

rust/helpers/gpu.c line 22

Quoted 6 lines · Joel Fernandes
rust/helpers/gpu.c new file +6 -0
+__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);
+}
+

Will rust_helper_gpu_buddy_block_size be used in the future? It doesn't appear to be used in buddy.rs.

Quoted 5 lines
Quoted 3 lines

I think it is worth keeping because it is a pretty basic API the underlying infrastructure. Finding the size of a block can be important in the future IMO. It is only few lines, no?

The helper should be added with the code using it.

I will add this as a test case to exercise it and include it in that patch.

thanks,

Signature · 1 line
Joel Fernandes
maintainer
#61 lore raw

Re: [PATCH v10 6/8] rust: gpu: Add GPU buddy allocator bindings

Quoted 18 lines · Joel Fernandes
Quoted 15 lines · Danilo Krummrich
Quoted 14 lines · Joel Fernandes
Quoted 10 lines · Eliot Courtney

rust/helpers/gpu.c line 22

Quoted 6 lines · Joel Fernandes
rust/helpers/gpu.c new file +6 -0
+__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);
+}
+

Will rust_helper_gpu_buddy_block_size be used in the future? It doesn't appear to be used in buddy.rs.

Quoted 7 lines
Quoted 5 lines
Quoted 3 lines

I think it is worth keeping because it is a pretty basic API the underlying infrastructure. Finding the size of a block can be important in the future IMO. It is only few lines, no?

The helper should be added with the code using it.

I will add this as a test case to exercise it and include it in that patch.

A test case for a helper? Or do you mean you will add the actual abstraction?

author reviewer
#62 lore raw

Re: [PATCH v10 6/8] rust: gpu: Add GPU buddy allocator bindings

Quoted 23 lines · Danilo Krummrich
Quoted 22 lines · Joel Fernandes
Quoted 19 lines · Danilo Krummrich
Quoted 17 lines · Joel Fernandes
Quoted 10 lines · Eliot Courtney

rust/helpers/gpu.c line 22

Quoted 6 lines · Joel Fernandes
rust/helpers/gpu.c new file +6 -0
+__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);
+}
+

Will rust_helper_gpu_buddy_block_size be used in the future? It doesn't appear to be used in buddy.rs.

I think it is worth keeping because it is a pretty basic API the underlying infrastructure. Finding the size of a block can be important in the future IMO. It is only few lines, no?

Quoted 5 lines
Quoted 3 lines
Quoted 1 line

The helper should be added with the code using it.

I will add this as a test case to exercise it and include it in that patch.

A test case for a helper? Or do you mean you will add the actual abstraction?

Actual abstraction.

thanks,

--
Joel Fernandes

author reviewer
#63 lore raw

PATCH v10 7/8 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..809485167aff 100644
@@ -5,6 +5,7 @@ config NOVA_CORE
 	depends on RUST
 	select RUST_FW_LOADER_ABSTRACTIONS
 	select AUXILIARY_BUS
+	select GPU_BUDDY
 	default n
 	help
 	  Choose this if you want to build the Nova Core driver for Nvidia
Signature · 1 line
2.34.1
#64 lore raw

Re: [PATCH v10 7/8] nova-core: mm: Select GPU_BUDDY for VRAM allocation

Quoted 2 lines · Joel Fernandes

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

Subject prefix should just be nova-core:, as this touches the module's configuration.

I'd also suggest to select GPU_BUDDY in the series that actively starts using it.

#65 lore raw

Re: [PATCH v10 7/8] nova-core: mm: Select GPU_BUDDY for VRAM allocation

Quoted 6 lines · Alexandre Courbot
Quoted 2 lines · Joel Fernandes

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

Subject prefix should just be nova-core:, as this touches the module's configuration.

Or "gpu: nova-core: ", actually.

That's the convention so far, where applicable of course.

Quoted 4 lines

I'd also suggest to select GPU_BUDDY in the series that actively starts using it.

thanks,

Signature · 1 line
John Hubbard
author reviewer
#66 lore raw

Re: [PATCH v10 7/8] nova-core: mm: Select GPU_BUDDY for VRAM allocation

Quoted 3 lines · John Hubbard

Or "gpu: nova-core: ", actually.

That's the convention so far, where applicable of course.

Thanks John, will use "gpu: nova-core:" as the subject prefix.

Joel

author reviewer
#67 lore raw

Re: [PATCH v10 7/8] nova-core: mm: Select GPU_BUDDY for VRAM allocation

In reply to Alexandre Courbot
Quoted 13 lines · Alexandre Courbot
Quoted 2 lines · Joel Fernandes

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

Subject prefix should just be nova-core:, as this touches the module's configuration.

I'd also suggest to select GPU_BUDDY in the series that actively starts using it.

Both suggestions sound good to me.

- -
Joel Fernandes

author reviewer
#68 lore raw

Re: [PATCH v10 7/8] nova-core: mm: Select GPU_BUDDY for VRAM allocation

In reply to Alexandre Courbot
Quoted 2 lines · Alexandre Courbot

Subject prefix should just be nova-core:, as this touches the module's configuration.

Will update to "gpu: nova-core:" per John's suggestion on the convention.

Quoted 2 lines

I'd also suggest to select GPU_BUDDY in the series that actively starts using it.

Makes sense, I'll move the GPU_BUDDY select to the patch that actually starts using it (the mm patch).

Thanks,
Joel

author reviewer
#69 lore raw

PATCH v10 8/8 nova-core: Kconfig: Sort select statements alphabetically

In reply to Joel Fernandes

Reorder the select statements in NOVA_CORE Kconfig to be in alphabetical order.

---
 drivers/gpu/nova-core/Kconfig | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/gpu/nova-core/Kconfig +1 -1
index 809485167aff..6513007bf66f 100644
@@ -3,9 +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
author reviewer
#70 lore raw
In reply to Joel Fernandes

My CC list missed a lot of folks, sorry about that. Adding more CC's to this email to make people aware of the posting. Thankfully it got posted to the archives so for those on rust-for-linux, dri-devel and nouveau lore lists, they would get it.

Thanks,

--
Joel Fernandes

Quoted 92 lines · Joel Fernandes

These are initial preparatory patches needed for nova-core memory management support. The series moves the DRM buddy allocator one level up so it can be shared across GPU subsystems, adds Rust FFI and clist bindings, and creates Rust GPU buddy allocator bindings.

The clist/ffi patches are ready, reviewed by Gary and Danilo. Miguel, can you pull those via the rust tree?

The non-Rust DRM buddy related patches are already being pulled into upstream by Dave Airlie but I have included them here as they are needed for the rest of the patches (thanks to Dave for reworking them so they applied).

I will post the nova-core memory management patches as a separate follow-up series just after this one.

The git tree with all these patches can be found at:
git://git.kernel.org/pub/scm/linux/kernel/git/jfern/linux.git (tag: nova/mm)

Joel Fernandes (7):
gpu: Move DRM buddy allocator one level up (part one)
gpu: Move DRM buddy allocator one level up (part two)
rust: ffi: Convert pub use to pub mod and create ffi module
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
nova-core: Kconfig: Sort select statements alphabetically

Koen Koning (1):
gpu: Fix uninitialized buddy for built-in drivers

 Documentation/gpu/drm-mm.rst                  |   10 +-
 MAINTAINERS                                   |   15 +-
 drivers/gpu/Kconfig                           |   13 +
 drivers/gpu/Makefile                          |    3 +-
 drivers/gpu/buddy.c                           | 1322 +++++++++++++++++
 drivers/gpu/drm/Kconfig                       |    5 +-
 drivers/gpu/drm/Kconfig.debug                 |    1 -
 drivers/gpu/drm/Makefile                      |    1 -
 drivers/gpu/drm/amd/amdgpu/amdgpu_ras.c       |    2 +-
 .../gpu/drm/amd/amdgpu/amdgpu_res_cursor.h    |   12 +-
 drivers/gpu/drm/amd/amdgpu/amdgpu_vram_mgr.c  |   79 +-
 drivers/gpu/drm/amd/amdgpu/amdgpu_vram_mgr.h  |   20 +-
 drivers/gpu/drm/drm_buddy.c                   | 1277 +---------------
 drivers/gpu/drm/i915/gem/i915_gem_ttm.c       |    2 +-
 drivers/gpu/drm/i915/i915_scatterlist.c       |   10 +-
 drivers/gpu/drm/i915/i915_ttm_buddy_manager.c |   55 +-
 drivers/gpu/drm/i915/i915_ttm_buddy_manager.h |    4 +-
 .../drm/i915/selftests/intel_memory_region.c  |   20 +-
 drivers/gpu/drm/tests/Makefile                |    1 -
 drivers/gpu/drm/tests/drm_exec_test.c         |    2 -
 drivers/gpu/drm/tests/drm_mm_test.c           |    2 -
 .../gpu/drm/ttm/tests/ttm_bo_validate_test.c  |    4 +-
 drivers/gpu/drm/ttm/tests/ttm_mock_manager.c  |   18 +-
 drivers/gpu/drm/ttm/tests/ttm_mock_manager.h  |    4 +-
 drivers/gpu/drm/xe/xe_res_cursor.h            |   34 +-
 drivers/gpu/drm/xe/xe_svm.c                   |   12 +-
 drivers/gpu/drm/xe/xe_ttm_vram_mgr.c          |   71 +-
 drivers/gpu/drm/xe/xe_ttm_vram_mgr_types.h    |    4 +-
 drivers/gpu/nova-core/Kconfig                 |    3 +-
 drivers/gpu/tests/Makefile                    |    4 +
 .../gpu_buddy_test.c}                         |  416 +++---
 .../lib/drm_random.c => tests/gpu_random.c}   |   18 +-
 .../lib/drm_random.h => tests/gpu_random.h}   |   18 +-
 drivers/video/Kconfig                         |    1 +
 include/drm/drm_buddy.h                       |  163 +-
 include/linux/gpu_buddy.h                     |  177 +++
 rust/bindings/bindings_helper.h               |   11 +
 rust/helpers/gpu.c                            |   23 +
 rust/helpers/helpers.c                        |    2 +
 rust/helpers/list.c                           |   17 +
 rust/kernel/ffi/clist.rs                      |  327 ++++
 rust/kernel/ffi/mod.rs                        |    9 +
 rust/kernel/gpu/buddy.rs                      |  537 +++++++
 rust/kernel/gpu/mod.rs                        |    5 +
 rust/kernel/lib.rs                            |    5 +-
 45 files changed, 2893 insertions(+), 1846 deletions(-)
 create mode 100644 drivers/gpu/Kconfig
 create mode 100644 drivers/gpu/buddy.c
 create mode 100644 drivers/gpu/tests/Makefile
 rename drivers/gpu/{drm/tests/drm_buddy_test.c => tests/gpu_buddy_test.c} (67%)
 rename drivers/gpu/{drm/lib/drm_random.c => tests/gpu_random.c} (59%)
 rename drivers/gpu/{drm/lib/drm_random.h => tests/gpu_random.h} (53%)
 create mode 100644 include/linux/gpu_buddy.h
 create mode 100644 rust/helpers/gpu.c
 create mode 100644 rust/helpers/list.c
 create mode 100644 rust/kernel/ffi/clist.rs
 create mode 100644 rust/kernel/ffi/mod.rs
 create mode 100644 rust/kernel/gpu/buddy.rs
 create mode 100644 rust/kernel/gpu/mod.rs

Cc: Nikola Djukic <[email protected]>
base-commit: 2961f841b025fb234860bac26dfb7fa7cb0fb122

Signature · 1 line
Joel Fernandes
maintainer
#71 lore raw
In reply to Joel Fernandes
Quoted 2 lines · Joel Fernandes

The clist/ffi patches are ready, reviewed by Gary and Danilo. Miguel, can you pull those via the rust tree?

I requested changes in the last version and have yet to go through this one. I also think that Alex still has some comments (Cc'd him).

Please note that if this goes through the Rust tree, we have to wait for the full upcoming cycle before we can land the GPU buddy abstractions.

Alternatively, if it goes through the Rust tree, Miguel can provide a signed tag for me to merge or we can simply take it through the drm-rust tree in the first place, if Miguel agrees with that.

Quoted 1 line

The non-Rust DRM buddy related patches are already being pulled into upstream

They are in drm-misc-next, I will merge into drm-rust-next once they hit drm-next and -rc1 is out.

Quoted 5 lines

I will post the nova-core memory management patches as a separate follow-up series just after this one.

The git tree with all these patches can be found at:
git://git.kernel.org/pub/scm/linux/kernel/git/jfern/linux.git (tag: nova/mm)

This is now (at least) the third time I have to ask for a patch changelog.

"When sending a next version, add a patch changelog to the cover letter or to individual patches explaining difference against previous submission (see The canonical patch format)." [1, 2]

Please, add a patch changelog.

(This also goes for the nova-core MM series, which is flagged as v7 despite actually being v2).

[1] https://docs.kernel.org/process/submitting-patches.html#respond-to-review-comments
[2] https://docs.kernel.org/process/submitting-patches.html#the-canonical-patch-format

author reviewer
#72 lore raw

Hi, Danilo,

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

The clist/ffi patches are ready, reviewed by Gary and Danilo. Miguel, can you pull those via the rust tree?

I requested changes in the last version and have yet to go through this one. I also think that Alex still has some comments (Cc'd him).

Sure.

Quoted 7 lines

Please note that if this goes through the Rust tree, we have to wait for the full upcoming cycle before we can land the GPU buddy abstractions.

Alternatively, if it goes through the Rust tree, Miguel can provide a signed tag for me to merge or we can simply take it through the drm-rust tree in the first place, if Miguel agrees with that.

Ok.

Quoted 5 lines
Quoted 2 lines

The non-Rust DRM buddy related patches are already being pulled into upstream

They are in drm-misc-next, I will merge into drm-rust-next once they hit drm-next and -rc1 is out.

Ok.

Quoted 7 lines
Quoted 6 lines

I will post the nova-core memory management patches as a separate follow-up series just after this one.

The git tree with all these patches can be found at:
git://git.kernel.org/pub/scm/linux/kernel/git/jfern/linux.git (tag: nova/mm)

Quoted 7 lines

This is now (at least) the third time I have to ask for a patch changelog.

"When sending a next version, add a patch changelog to the cover letter or to individual patches explaining difference against previous submission (see The canonical patch format)." [1, 2]

Please, add a patch changelog.

Ah, I think I did not understand what you meant because of my different interpretation of the words changelog. I have used this term interchangeable in the past to summarize what a set of patches do in the cover letter, not what changed since the last revision.

Anyway here is a changelog:

1. Moving of the clist code to rust ffi
2. Some comment changes in clist and gpu buddy bindings
3. Inclusion of the movement of code on C drm buddy.

For the other series:
- the main change is only for DRM fence signaling related stuff and some test related changes.

If you want I could provide a range diff if it makes it easier. But yeah I did drop the ball a bit on the changelog stuff here. Perhaps buying you a beer the next LPC could be penance?

Quoted 3 lines

(This also goes for the nova-core MM series, which is flagged as v7 despite actually being v2).

No, it was RFC v6, that is when I had included the full stack of these patches. See:
https://lore.kernel.org/all/[email protected]/

I split it this way based on your request. I wanted to keep it all in one series to reduce version number confusion.

Let me know if there’s something else I need to do to make it easier, I can include a proper changelog in future respins.

Best,

Signature · 1 line
Joel Fernandes
author reviewer
#73 lore raw
Quoted 55 lines · Joel Fernandes

Hi, Danilo,

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

The clist/ffi patches are ready, reviewed by Gary and Danilo. Miguel, can you pull those via the rust tree?

I requested changes in the last version and have yet to go through this one. I also think that Alex still has some comments (Cc'd him).

Sure.

Quoted 7 lines

Please note that if this goes through the Rust tree, we have to wait for the full upcoming cycle before we can land the GPU buddy abstractions.

Alternatively, if it goes through the Rust tree, Miguel can provide a signed tag for me to merge or we can simply take it through the drm-rust tree in the first place, if Miguel agrees with that.

Ok.

Quoted 5 lines
Quoted 2 lines

The non-Rust DRM buddy related patches are already being pulled into upstream

They are in drm-misc-next, I will merge into drm-rust-next once they hit drm-next and -rc1 is out.

Ok.

Quoted 7 lines
Quoted 6 lines

I will post the nova-core memory management patches as a separate follow-up series just after this one.

The git tree with all these patches can be found at:
git://git.kernel.org/pub/scm/linux/kernel/git/jfern/linux.git (tag: nova/mm)

Quoted 7 lines

This is now (at least) the third time I have to ask for a patch changelog.

"When sending a next version, add a patch changelog to the cover letter or to individual patches explaining difference against previous submission (see The canonical patch format)." [1, 2]

Please, add a patch changelog.

Ah, I think I did not understand what you meant because of my different interpretation of the words changelog. I have used this term interchangeable in the past to summarize what a set of patches do in the cover letter, not what changed since the last revision.

Quoted 5 lines

Anyway here is a changelog:

1. Moving of the clist code to rust ffi
2. Some comment changes in clist and gpu buddy bindings
3. Inclusion of the movement of code on C drm buddy.

And to clarify, I’ll go try to include this on a patch by patch basis hence forth in the cover letter as suggested by the documentation. Not just what changed since last time summary.

- Joel