Skip to contentSkip to conversation

Rust GPUVM immediate mode

PATCH Applied Alice Ryhl 2 participants 7 messages Apr 9 – May 5

Subsystems (5)
lore
Share & tools
lore

Alice Ryhl

author maintainer
#0 lore raw

v6 cover Rust GPUVM immediate mode

This series provides an immediate mode GPUVM implementation.

Only immediate mode is provided for Rust code, as all planned Rust drivers intend to use GPUVM in immediate mode.

---
Changes in v6:
- Rebase on drm-rust-next-2026-04-06. As a result, the dma-resv helpers patch is dropped because it was already merged into drm-rust-next.
- Fix Send/Sync impls for GpuVm<T> to take T:Send into account.
- Fix Send/Sync impls and data()/data_ref() methods on UniqueRefGpuVm to take T:Send and T:Shync into account.
- Pass __GFP_ZERO to kbox, so that data is zeroed when calling drm_gpuvm_init.
- Call drm_gpuvm_bo_extobj_add() in obtain() even if it returns an existing pointer to avoid race condition.
- Check that vm_bo is from the correct GpuVm in sm_map().
- Change sm_map() to take &GpuVmBo instead of ARef<GpuVmBo>.
- Document that sparse VAs are not yet supported.
- Link to v5: https://lore.kernel.org/r/[email protected]

Changes in v5:
- Rename GpuVmCore to UniqueRefGpuVm.
- Implement Send/Sync for GpuVm.
- Move helpers/dma-resv.c in MAINTAINERS
- Improve GpuVmBo allocation and free docs
- Add "in GEM list" invariant to GpuVmBo
- also mention said invariant on GpuVa
- Replace GpuVmBoRegistered with ARef<GpuVmBo>
- Add TODO about dma-resv lock usage
- Add __rust_helper to helpers/drm_gpuvm.c
- Change _invariant type to silence type complexity clippy lint
- Link to v4: https://lore.kernel.org/r/[email protected]

Changes in v4:
- Add trait bound so that DriverGpuVm::Object must be the same type as Driver::Object.
- Add rust/helpers/dma-resv.c to MAINTAINERS.
- Add __rust_helper to dma_resv_lock and dma_resv_unlock.
- Rename GpuVm::raw_resv_lock() to GpuVm::raw_resv()
- Reword comment in obtain() for adding to extobj list.
- Fix typo in commit message referring to GpuVm<_> instead of GpuVmBo<_>.
- Changed the PhantomData type used for invariance and add comment. (No functional change.)
- Rename offset to gem_offset in args to sm_map().
- Link to v3: https://lore.kernel.org/r/[email protected]

Changes in v3:
- C prerequisites have landed, so only Rust part is present.
- The logic for drm_exec was removed, and is for a follow-up.
- Split up into patches.
- Add lifetime to SmStepContext.
- Docs filled out.
- Mutex abstractions used for GEM gpuva lock.
- Drop 'shared data' concept for now. (Can be added back later if required.)
- Rename 'core' field to 'data'.
- GpuVmCore<T> now derefs to GpuVm<T> instead of T.
- Renamed GpuVmBoObtain to GpuVmBoResident.
- Probably more changes I forgot.
- Link to v2: https://lore.kernel.org/r/[email protected]

Changes in v2:
- For this version, only the C prerequisites are included. Rust will be sent as follow-up.
- Add comment to drm_gpuvm_bo_destroy_not_in_lists()
- Add Fixes: tag.
- Pick up Reviewed-by tags.
- Link to v1: https://lore.kernel.org/r/[email protected]

---
Alice Ryhl (4):
rust: gpuvm: add GpuVm::obtain()
rust: gpuvm: add GpuVa struct
rust: gpuvm: add GpuVmCore::sm_unmap()
rust: gpuvm: add GpuVmCore::sm_map()

Asahi Lina (1):
rust: drm: add base GPUVM immediate mode abstraction

 MAINTAINERS                     |   2 +
 rust/bindings/bindings_helper.h |   1 +
 rust/helpers/drm_gpuvm.c        |  26 +++
 rust/helpers/helpers.c          |   1 +
 rust/kernel/drm/gpuvm/mod.rs    | 328 ++++++++++++++++++++++++++++++
 rust/kernel/drm/gpuvm/sm_ops.rs | 429 ++++++++++++++++++++++++++++++++++++++++
 rust/kernel/drm/gpuvm/va.rs     | 168 ++++++++++++++++
 rust/kernel/drm/gpuvm/vm_bo.rs  | 249 +++++++++++++++++++++++
 rust/kernel/drm/mod.rs          |   1 +
 9 files changed, 1205 insertions(+)

---
base-commit: a7a080bb4236ebe577b6776d940d1717912ff6dd
change-id: 20251128-gpuvm-rust-b719cac27ad6

Best regards,

Signature · 1 line
Alice Ryhl <[email protected]>
author maintainer
#1 lore raw

PATCH v6 1/5 rust: drm: add base GPUVM immediate mode abstraction

From: Asahi Lina <[email protected]>

Add a GPUVM abstraction to be used by Rust GPU drivers.

GPUVM keeps track of a GPU's virtual address (VA) space and manages the corresponding virtual mappings represented by "GPU VA" objects. It also keeps track of the gem::Object<T> used to back the mappings through GpuVmBo<T>.

This abstraction is only usable by drivers that wish to use GPUVM in immediate mode. This allows us to build the locking scheme into the API design. It means that the GEM mutex is used for the GEM gpuva list, and that the resv lock is used for the extobj list. The evicted list is not yet used in this version.

This abstraction provides a special handle called the UniqueRefGpuVm, which is a wrapper around ARef<GpuVm> that provides access to the interval tree. Generally, all changes to the address space requires mutable access to this unique handle.

---
 MAINTAINERS                     |   2 +
 rust/bindings/bindings_helper.h |   1 +
 rust/helpers/drm_gpuvm.c        |  20 ++++
 rust/helpers/helpers.c          |   1 +
 rust/kernel/drm/gpuvm/mod.rs    | 260 ++++++++++++++++++++++++++++++++++++++++
 rust/kernel/drm/mod.rs          |   1 +
 6 files changed, 285 insertions(+)
MAINTAINERS +2 -0
index b01791963e25..9c93fa23654c 100644
@@ -8858,6 +8858,8 @@ S:	Supported
 T:	git https://gitlab.freedesktop.org/drm/misc/kernel.git
 F:	drivers/gpu/drm/drm_gpuvm.c
 F:	include/drm/drm_gpuvm.h
+F:	rust/helpers/drm_gpuvm.c
+F:	rust/kernel/drm/gpuvm/
 
 DRM LOG
 M:	Jocelyn Falempe <[email protected]>
rust/bindings/bindings_helper.h +1 -0
index eda8f50d3a3c..cb06a7ff795b 100644
@@ -35,6 +35,7 @@
 #include <drm/drm_file.h>
 #include <drm/drm_gem.h>
 #include <drm/drm_gem_shmem_helper.h>
+#include <drm/drm_gpuvm.h>
 #include <drm/drm_ioctl.h>
 #include <kunit/test.h>
 #include <linux/auxiliary_bus.h>
rust/helpers/drm_gpuvm.c new file +20 -0
new file mode 100644
index 000000000000..18cf104a8bc7
@@ -0,0 +1,20 @@
+// SPDX-License-Identifier: GPL-2.0 or MIT
+
+#ifdef CONFIG_DRM_GPUVM
+
+#include <drm/drm_gpuvm.h>
+
+__rust_helper
+struct drm_gpuvm *rust_helper_drm_gpuvm_get(struct drm_gpuvm *obj)
+{
+	return drm_gpuvm_get(obj);
+}
+
+__rust_helper
+bool rust_helper_drm_gpuvm_is_extobj(struct drm_gpuvm *gpuvm,
+				     struct drm_gem_object *obj)
+{
+	return drm_gpuvm_is_extobj(gpuvm, obj);
+}
+
+#endif // CONFIG_DRM_GPUVM
rust/helpers/helpers.c +1 -0
index b6b20ad2e0e6..875a9788ad40 100644
@@ -30,6 +30,7 @@
 #include "dma.c"
 #include "dma-resv.c"
 #include "drm.c"
+#include "drm_gpuvm.c"
 #include "err.c"
 #include "irq.c"
 #include "fs.c"
rust/kernel/drm/gpuvm/mod.rs new file +260 -0

260 lines not on this page · raw message

rust/kernel/drm/mod.rs +1 -0
index 1b82b6945edf..a4b6c5430198 100644
@@ -6,6 +6,7 @@
 pub mod driver;
 pub mod file;
 pub mod gem;
+pub mod gpuvm;
 pub mod ioctl;
 
 pub use self::device::Device;
Signature · 1 line
2.53.0.1213.gd9a14994de-goog
author maintainer
#2 lore raw

PATCH v6 2/5 rust: gpuvm: add GpuVm::obtain()

In reply to Alice Ryhl

This provides a mechanism to create (or look up) VMBO instances, which represent the mapping between GPUVM and GEM objects.

The GpuVmBoRegistered<T> type can be considered like ARef<GpuVm<T>>, except that no way to increment the refcount is provided.

The GpuVmBoAlloc<T> type is more akin to a pre-allocated GpuVmBo<T>, so it's not really a GpuVmBo<T> yet. Its destructor could call drm_gpuvm_bo_destroy_not_in_lists(), but as the type is currently private and never called anywhere, this perf optimization does not need to happen now.

Pre-allocating and obtaining the gpuvm_bo object is exposed as a single step. This could theoretically be a problem if one wanted to call drm_gpuvm_bo_obtain_prealloc() during the fence signalling critical path, but that's not a possibility because:

1. Adding the BO to the extobj list requires the resv lock, so it cannot happen during the fence signalling critical path.
2. obtain() requires that the BO is not in the extobj list, so obtain() must be called before adding the BO to the extobj list.

Thus, drm_gpuvm_bo_obtain_prealloc() cannot be called during the fence signalling critical path. (For extobjs at least.)

---
 rust/helpers/drm_gpuvm.c       |   6 +
 rust/kernel/drm/gpuvm/mod.rs   |  32 +++++-
 rust/kernel/drm/gpuvm/vm_bo.rs | 242 +++++++++++++++++++++++++++++++++++++++++
 3 files changed, 277 insertions(+), 3 deletions(-)
rust/helpers/drm_gpuvm.c +6 -0
index 18cf104a8bc7..ca959d9a66f6 100644
@@ -4,6 +4,12 @@
 
 #include <drm/drm_gpuvm.h>
 
+__rust_helper
+struct drm_gpuvm_bo *rust_helper_drm_gpuvm_bo_get(struct drm_gpuvm_bo *vm_bo)
+{
+	return drm_gpuvm_bo_get(vm_bo);
+}
+
 __rust_helper
 struct drm_gpuvm *rust_helper_drm_gpuvm_get(struct drm_gpuvm *obj)
 {
rust/kernel/drm/gpuvm/mod.rs +29 -3
index 1d9138d989b3..56e02b49a581 100644
@@ -25,13 +25,20 @@
 
 use core::{
     cell::UnsafeCell,
+    mem::ManuallyDrop,
     ops::{
         Deref,
         Range, //
     },
-    ptr::NonNull, //
+    ptr::{
+        self,
+        NonNull, //
+    }, //
 };
 
+mod vm_bo;
+pub use self::vm_bo::*;
+
 /// A DRM GPU VA manager.
 ///
 /// This object is refcounted, but the locations of mapped ranges may only be accessed or changed
@@ -83,8 +90,8 @@ const fn vtable() -> &'static bindings::drm_gpuvm_ops {
             vm_free: Some(Self::vm_free),
             op_alloc: None,
             op_free: None,
-            vm_bo_alloc: None,
-            vm_bo_free: None,
+            vm_bo_alloc: GpuVmBo::<T>::ALLOC_FN,
+            vm_bo_free: GpuVmBo::<T>::FREE_FN,
             vm_bo_validate: None,
             sm_step_map: None,
             sm_step_unmap: None,
@@ -184,6 +191,16 @@ pub fn va_range(&self) -> Range<u64> {
         Range { start, end }
     }
 
+    /// Get or create the [`GpuVmBo`] for this gem object.
+    #[inline]
+    pub fn obtain(
+        &self,
+        obj: &T::Object,
+        data: impl PinInit<T::VmBoData>,
+    ) -> Result<ARef<GpuVmBo<T>>, AllocError> {
+        Ok(GpuVmBoAlloc::new(self, obj, data)?.obtain())
+    }
+
     /// Clean up buffer objects that are no longer used.
     #[inline]
     pub fn deferred_cleanup(&self) {
@@ -209,6 +226,12 @@ pub fn is_extobj(&self, obj: &T::Object) -> bool {
         // SAFETY: By type invariants we can free it when refcount hits zero.
         drop(unsafe { KBox::from_raw(me) })
     }
+
+    #[inline]
+    fn raw_resv(&self) -> *mut bindings::dma_resv {
+        // SAFETY: `r_obj` is immutable and valid for duration of GPUVM.
+        unsafe { (*(*self.as_raw()).r_obj).resv }
+    }
 }
 
 /// The manager for a GPUVM.
@@ -218,6 +241,9 @@ pub trait DriverGpuVm: Sized + Send {
 
     /// The kind of GEM object stored in this GPUVM.
     type Object: IntoGEMObject;
+
+    /// Data stored with each [`struct drm_gpuvm_bo`](struct@GpuVmBo).
+    type VmBoData;
 }
 
 /// The core of the DRM GPU VA manager.
rust/kernel/drm/gpuvm/vm_bo.rs new file +242 -0

242 lines not on this page · raw message

Signature · 1 line
2.53.0.1213.gd9a14994de-goog
author maintainer
#3 lore raw

PATCH v6 3/5 rust: gpuvm: add GpuVa struct

In reply to Alice Ryhl

This struct will be used to keep track of individual mapped ranges in the GPU's virtual memory.

Sparse VAs are not yet supported.

---
 rust/kernel/drm/gpuvm/mod.rs   |  19 ++++-
 rust/kernel/drm/gpuvm/va.rs    | 169 +++++++++++++++++++++++++++++++++++++++++
 rust/kernel/drm/gpuvm/vm_bo.rs |   1 -
 3 files changed, 185 insertions(+), 4 deletions(-)
rust/kernel/drm/gpuvm/mod.rs +16 -3
index 56e02b49a581..78951e8aa5d3 100644
@@ -11,7 +11,10 @@
 //! C header: [`include/drm/drm_gpuvm.h`](srctree/include/drm/drm_gpuvm.h)
 
 use kernel::{
-    alloc::AllocError,
+    alloc::{
+        AllocError,
+        Flags as AllocFlags, //
+    },
     bindings,
     drm,
     drm::gem::IntoGEMObject,
@@ -25,9 +28,13 @@
 
 use core::{
     cell::UnsafeCell,
-    mem::ManuallyDrop,
+    mem::{
+        ManuallyDrop,
+        MaybeUninit, //
+    },
     ops::{
         Deref,
+        DerefMut,
         Range, //
     },
     ptr::{
@@ -36,6 +43,9 @@
     }, //
 };
 
+mod va;
+pub use self::va::*;
+
 mod vm_bo;
 pub use self::vm_bo::*;
 
@@ -48,7 +58,7 @@
 ///
 /// * Stored in an allocation managed by the refcount in `self.vm`.
 /// * Access to `data` and the gpuvm interval tree is controlled via the [`UniqueRefGpuVm`] type.
-/// * Does not contain any sparse `GpuVa` instances.
+/// * Does not contain any sparse [`GpuVa<T>`] instances.
 #[pin_data]
 pub struct GpuVm<T: DriverGpuVm> {
     #[pin]
@@ -242,6 +252,9 @@ pub trait DriverGpuVm: Sized + Send {
     /// The kind of GEM object stored in this GPUVM.
     type Object: IntoGEMObject;
 
+    /// Data stored with each [`struct drm_gpuva`](struct@GpuVa).
+    type VaData;
+
     /// Data stored with each [`struct drm_gpuvm_bo`](struct@GpuVmBo).
     type VmBoData;
 }
rust/kernel/drm/gpuvm/va.rs new file +169 -0

169 lines not on this page · raw message

rust/kernel/drm/gpuvm/vm_bo.rs +0 -1
index 65f03f93bd21..05fd7998f4bd 100644
@@ -114,7 +114,6 @@ impl<T: DriverGpuVm> GpuVmBo<T> {
     /// For the duration of `'a`, the pointer must reference a valid `drm_gpuvm_bo` associated with
     /// a [`GpuVm<T>`]. The BO must also be present in the GEM list.
     #[inline]
-    #[expect(dead_code)]
     pub(crate) unsafe fn from_raw<'a>(ptr: *mut bindings::drm_gpuvm_bo) -> &'a Self {
         // SAFETY: `drm_gpuvm_bo` is first field and `repr(C)`.
         unsafe { &*ptr.cast() }
Signature · 1 line
2.53.0.1213.gd9a14994de-goog
author maintainer
#4 lore raw

PATCH v6 4/5 rust: gpuvm: add GpuVmCore::sm_unmap()

In reply to Alice Ryhl

Add the entrypoint for unmapping ranges in the GPUVM, and provide callbacks and VA types for the implementation.

---
 rust/kernel/drm/gpuvm/mod.rs    |  30 ++++-
 rust/kernel/drm/gpuvm/sm_ops.rs | 272 ++++++++++++++++++++++++++++++++++++++++
 rust/kernel/drm/gpuvm/va.rs     |   1 -
 rust/kernel/drm/gpuvm/vm_bo.rs  |   8 ++
 4 files changed, 306 insertions(+), 5 deletions(-)
rust/kernel/drm/gpuvm/mod.rs +26 -4
index 78951e8aa5d3..a6436abd0f9c 100644
@@ -18,6 +18,7 @@
     bindings,
     drm,
     drm::gem::IntoGEMObject,
+    error::to_result,
     prelude::*,
     sync::aref::{
         ARef,
@@ -28,6 +29,7 @@
 
 use core::{
     cell::UnsafeCell,
+    marker::PhantomData,
     mem::{
         ManuallyDrop,
         MaybeUninit, //
@@ -43,12 +45,15 @@
     }, //
 };
 
-mod va;
-pub use self::va::*;
+mod sm_ops;
+pub use self::sm_ops::*;
 
 mod vm_bo;
 pub use self::vm_bo::*;
 
+mod va;
+pub use self::va::*;
+
 /// A DRM GPU VA manager.
 ///
 /// This object is refcounted, but the locations of mapped ranges may only be accessed or changed
@@ -104,8 +109,8 @@ const fn vtable() -> &'static bindings::drm_gpuvm_ops {
             vm_bo_free: GpuVmBo::<T>::FREE_FN,
             vm_bo_validate: None,
             sm_step_map: None,
-            sm_step_unmap: None,
-            sm_step_remap: None,
+            sm_step_unmap: Some(Self::sm_step_unmap),
+            sm_step_remap: Some(Self::sm_step_remap),
         }
     }
 
@@ -257,6 +262,23 @@ pub trait DriverGpuVm: Sized + Send {
 
     /// Data stored with each [`struct drm_gpuvm_bo`](struct@GpuVmBo).
     type VmBoData;
+
+    /// The private data passed to callbacks.
+    type SmContext<'ctx>;
+
+    /// Indicates that an existing mapping should be removed.
+    fn sm_step_unmap<'op, 'ctx>(
+        &mut self,
+        op: OpUnmap<'op, Self>,
+        context: &mut Self::SmContext<'ctx>,
+    ) -> Result<OpUnmapped<'op, Self>, Error>;
+
+    /// Indicates that an existing mapping should be split up.
+    fn sm_step_remap<'op, 'ctx>(
+        &mut self,
+        op: OpRemap<'op, Self>,
+        context: &mut Self::SmContext<'ctx>,
+    ) -> Result<OpRemapped<'op, Self>, Error>;
 }
 
 /// The core of the DRM GPU VA manager.
rust/kernel/drm/gpuvm/sm_ops.rs new file +272 -0

272 lines not on this page · raw message

rust/kernel/drm/gpuvm/va.rs +0 -1
index 227c259f7db9..0b09fe44ab39 100644
@@ -1,6 +1,5 @@
 // SPDX-License-Identifier: GPL-2.0 OR MIT
 
-#![expect(dead_code)]
 use super::*;
 
 /// Represents that a range of a GEM object is mapped in this [`GpuVm`] instance.
rust/kernel/drm/gpuvm/vm_bo.rs +8 -0
index 05fd7998f4bd..c064ac63897b 100644
@@ -144,6 +144,14 @@ pub fn obj(&self) -> &T::Object {
     pub fn data(&self) -> &T::VmBoData {
         &self.data
     }
+
+    pub(super) fn lock_gpuva(&self) -> crate::sync::MutexGuard<'_, ()> {
+        // SAFETY: The GEM object is valid.
+        let ptr = unsafe { &raw mut (*self.obj().as_raw()).gpuva.lock };
+        // SAFETY: The GEM object is valid, so the mutex is properly initialized.
+        let mutex = unsafe { crate::sync::Mutex::from_raw(ptr) };
+        mutex.lock()
+    }
 }
 
 /// A pre-allocated [`GpuVmBo`] object.
Signature · 1 line
2.53.0.1213.gd9a14994de-goog
author maintainer
#5 lore raw

PATCH v6 5/5 rust: gpuvm: add GpuVmCore::sm_map()

In reply to Alice Ryhl

Finally also add the operation for creating new mappings. Mapping operations need extra data in the context since they involve a vm_bo coming from the outside.

---
 rust/kernel/drm/gpuvm/mod.rs    |   9 ++-
 rust/kernel/drm/gpuvm/sm_ops.rs | 167 ++++++++++++++++++++++++++++++++++++++--
 2 files changed, 170 insertions(+), 6 deletions(-)
rust/kernel/drm/gpuvm/mod.rs +8 -1
index a6436abd0f9c..dc755f248143 100644
@@ -108,7 +108,7 @@ const fn vtable() -> &'static bindings::drm_gpuvm_ops {
             vm_bo_alloc: GpuVmBo::<T>::ALLOC_FN,
             vm_bo_free: GpuVmBo::<T>::FREE_FN,
             vm_bo_validate: None,
-            sm_step_map: None,
+            sm_step_map: Some(Self::sm_step_map),
             sm_step_unmap: Some(Self::sm_step_unmap),
             sm_step_remap: Some(Self::sm_step_remap),
         }
@@ -266,6 +266,13 @@ pub trait DriverGpuVm: Sized + Send {
     /// The private data passed to callbacks.
     type SmContext<'ctx>;
 
+    /// Indicates that a new mapping should be created.
+    fn sm_step_map<'op, 'ctx>(
+        &mut self,
+        op: OpMap<'op, Self>,
+        context: &mut Self::SmContext<'ctx>,
+    ) -> Result<OpMapped<'op, Self>, Error>;
+
     /// Indicates that an existing mapping should be removed.
     fn sm_step_unmap<'op, 'ctx>(
         &mut self,
rust/kernel/drm/gpuvm/sm_ops.rs +162 -5

205 lines not on this page · raw message

Signature · 1 line
2.53.0.1213.gd9a14994de-goog
maintainer Applied
#6 lore raw
In reply to Alice Ryhl
Quoted 1 line · Alice Ryhl

[PATCH v6 0/5] Rust GPUVM immediate mode

Applied, thanks!

Branch: drm-rust-next
Tree: https://gitlab.freedesktop.org/drm/rust/kernel.git

[1/5] rust: drm: add base GPUVM immediate mode abstraction

      commit: 82b78182eacf
[2/5] rust: gpuvm: add GpuVm::obtain()
      commit: 71a3921111bd
[3/5] rust: gpuvm: add GpuVa struct
      commit: 5540a9c747b3
[4/5] rust: gpuvm: add GpuVmCore::sm_unmap()
      commit: dc3846045f69
[5/5] rust: gpuvm: add GpuVmCore::sm_map()
      commit: 0b715b1e382b

The patches will appear in the next linux-next integration (typically within 24 hours on weekdays).

The patches are queued up for the upcoming merge window for the next major kernel release.