Skip to contentSkip to conversation

lifetime-parameterized DRM File private data

PATCH Applied Danilo Krummrich 4 participants 12 messages Nov 18 – Nov 20

Subsystems (6)
lore
Share & tools
lore

Danilo Krummrich

author maintainer
#0 lore raw

v3 cover lifetime-parameterized DRM File private data

DRM file private data is currently 'static, preventing drivers from borrowing registration-scoped resources in their per-file state. This series makes Driver::File lifetime-parameterized, so file data can borrow from RegistrationData.

File data is guaranteed to be dropped before registration data, either when the file is closed normally or when the device is unregistered, whichever comes first. To enforce this during unbind, Registration::drop() revokes all open file data and waits for its destruction before dropping registration data.

fops.open is wrapped in a RegistrationGuard (drm_dev_enter/exit) so that after drm_dev_unplug() all successfully opened files are accounted for. GEM open/close callbacks are similarly gated to prevent access to stale file data after unbind.

The series is based on drm-rust-next with [1] applied; a branch with the patches is available in [2].

[1] https://lore.kernel.org/all/[email protected]/
[2] https://git.kernel.org/pub/scm/linux/kernel/git/dakr/linux.git/log/?h=drm/file

Changes in v3:
- Move the DriverFile bound to Driver::File<'a>.
- Require Send + Sync for DriverFile.
- Use Atomic<u64> for open_count.
- Explain driver_priv synchronization in postclose_callback().

Changes in v2:
- Replace ForLt with Driver::File<'a>; use inner_with() for file-data access and allow returning borrowed fields.
- Use Opaque<bindings::drm_file> during teardown.
- Drop file data outside filelist_mutex; also clean up file data on registration failure.
- Reject cross-device GEM handles.
- Clarify safety documentation and add inline annotations.

Danilo Krummrich (7):
rust: drm: rename Ioctl device context to Userspace
rust: drm: gem: gate open/close callbacks with RegistrationGuard
rust: drm: move file_operations from gem to device
rust: fs: add iminor() helper
rust: drm: wrap fops open with RegistrationGuard
rust: drm: return impl PinInit from DriverFile::open()
rust: drm: make Driver::File lifetime-parameterized

 drivers/gpu/drm/nova/driver.rs |   2 +-
 drivers/gpu/drm/nova/file.rs   |  16 +--
 drivers/gpu/drm/nova/gem.rs    |   8 +-
 drivers/gpu/drm/tyr/driver.rs  |   2 +-
 drivers/gpu/drm/tyr/file.rs    |  13 ++-
 rust/helpers/fs.c              |   5 +
 rust/kernel/drm/device.rs      | 136 ++++++++++++++++++++++----
 rust/kernel/drm/driver.rs      | 113 ++++++++++++++++++++--
 rust/kernel/drm/file.rs        | 172 ++++++++++++++++++++++++---------
 rust/kernel/drm/gem/mod.rs     |  80 +++++++++------
 rust/kernel/drm/gem/shmem.rs   |  11 ++-
 rust/kernel/drm/ioctl.rs       |  18 ++--
 rust/kernel/drm/mod.rs         |   2 +-
 13 files changed, 446 insertions(+), 132 deletions(-)

base-commit: 23eb2cfcf15209d149f407e462704c21b9ce9cc4

Signature · 1 line
2.56.1
author maintainer
#1 lore raw

PATCH v3 1/7 rust: drm: rename Ioctl device context to Userspace

The Ioctl DeviceContext typestate represents a device that has been registered with userspace at some point. This context is not specific to ioctl dispatch; it applies equally to GEM handle callbacks, mmap, fdinfo, and any other operation triggered by userspace on a registered device.

Rename it to Userspace to accurately reflect its semantics.

---
 rust/kernel/drm/device.rs | 21 ++++++++++++---------
 rust/kernel/drm/ioctl.rs  | 12 ++++++------
 rust/kernel/drm/mod.rs    |  2 +-
 3 files changed, 19 insertions(+), 16 deletions(-)
rust/kernel/drm/device.rs +12 -9
index 6b88ade28e24..dd1c83fef323 100644
@@ -79,12 +79,12 @@ macro_rules! drm_legacy_fields {
 ///
 /// - [`Normal`]: The general-purpose, reference-counted context. A [`Device`] in this context may
 ///   or may not be registered with userspace.
-/// - [`Ioctl`]: The device has been registered with userspace at some point; used in ioctl
-///   dispatch context.
+/// - [`Userspace`]: The device has been registered with userspace at some point; used in
+///   callbacks triggered by userspace operations.
 /// - [`Registered`]: The device is currently registered with userspace and the parent bus device
 ///   is bound.
 ///
-/// Both `Device<T, Ioctl>` and `Device<T, Registered>` dereference to `Device<T>` ([`Normal`]),
+/// Both `Device<T, Userspace>` and `Device<T, Registered>` dereference to `Device<T>` ([`Normal`]),
 /// so any method available on a [`Normal`] device is also available in the other contexts.
 pub trait DeviceContext: Sealed + Send + Sync + 'static {}
 
@@ -120,14 +120,17 @@ impl DeviceContext for Registered {}
 /// unregistering or already unregistered. `drm_dev_enter()` can guard against this, ensuring the
 /// device remains registered for the duration of the critical section.
 ///
+/// This context is used for all callbacks triggered by userspace operations: ioctls, GEM handle
+/// management, mmap, fdinfo, etc.
+///
 /// # Invariants
 ///
 /// A [`Device`] in this context has been registered with userspace via `drm_dev_register()` at
 /// some point.
-pub struct Ioctl;
+pub struct Userspace;
 
-impl Sealed for Ioctl {}
-impl DeviceContext for Ioctl {}
+impl Sealed for Userspace {}
+impl DeviceContext for Userspace {}
 
 /// A [`Device`] which is known at compile-time to be unregistered with userspace.
 ///
@@ -344,7 +347,7 @@ pub(crate) unsafe fn assume_ctx<NewCtx: DeviceContext>(&self) -> &Device<T, NewC
     }
 }
 
-impl<T: drm::Driver> Device<T, Ioctl> {
+impl<T: drm::Driver> Device<T, Userspace> {
     /// Guard against the parent bus device being unbound.
     ///
     /// Returns a [`RegistrationGuard`] if the device has not been unplugged, [`None`] otherwise.
@@ -467,12 +470,12 @@ fn deref(&self) -> &Self::Target {
     }
 }
 
-impl<T: drm::Driver> Deref for Device<T, Ioctl> {
+impl<T: drm::Driver> Deref for Device<T, Userspace> {
     type Target = Device<T>;
 
     #[inline]
     fn deref(&self) -> &Self::Target {
-        // SAFETY: The caller holds a `Device<T, Ioctl>`, which guarantees all invariants
+        // SAFETY: The caller holds a `Device<T, Userspace>`, which guarantees all invariants
         // of the weaker `Normal` context.
         unsafe { self.assume_ctx() }
     }
rust/kernel/drm/ioctl.rs +6 -6
index 64af9eacc306..9934b23c36eb 100644
@@ -71,14 +71,14 @@ pub mod internal {
     pub use bindings::drm_file;
     pub use bindings::drm_ioctl_desc;
 
-    /// Cast an [`Ioctl`] DRM device pointer to [`Registered`], preserving the driver type
+    /// Cast a [`Userspace`] DRM device pointer to [`Registered`], preserving the driver type
     /// parameter `T`.
     ///
     /// Used by [`declare_drm_ioctls!`] to anchor type inference.
     #[doc(hidden)]
     #[inline]
     pub const fn __dev_ctx_cast<T: crate::drm::Driver>(
-        ptr: *const crate::drm::Device<T, crate::drm::Ioctl>,
+        ptr: *const crate::drm::Device<T, crate::drm::Userspace>,
     ) -> *const crate::drm::Device<T, crate::drm::Registered> {
         ptr.cast()
     }
@@ -144,14 +144,14 @@ macro_rules! declare_drm_ioctls {
                             // - The DRM device must have been registered when we're called through
                             //   an IOCTL.
                             //
-                            // INVARIANT: The `Ioctl` context requires that the device has been
-                            // registered via `drm_dev_register()` at some point; the DRM core
-                            // guarantees this for ioctl dispatch callbacks.
+                            // INVARIANT: The `Userspace` context requires that the device has
+                            // been registered via `drm_dev_register()` at some point; the DRM
+                            // core guarantees this for ioctl dispatch callbacks.
                             //
                             // FIXME: Currently there is nothing enforcing that the types of the
                             // dev/file match the current driver these ioctls are being declared
                             // for, and it's not clear how to enforce this within the type system.
-                            let dev: &$crate::drm::device::Device<_, $crate::drm::Ioctl> =
+                            let dev: &$crate::drm::device::Device<_, $crate::drm::Userspace> =
                                 $crate::drm::device::Device::from_raw(raw_dev);
 
                             // Type-inference anchor: the closure is never called but ties `dev`'s
rust/kernel/drm/mod.rs +1 -1
index fd6ed35bc35a..7fcf2465a82e 100644
@@ -11,11 +11,11 @@
 
 pub use self::device::Device;
 pub use self::device::DeviceContext;
-pub use self::device::Ioctl;
 pub use self::device::Normal;
 pub use self::device::Registered;
 pub use self::device::RegistrationGuard;
 pub use self::device::UnregisteredDevice;
+pub use self::device::Userspace;
 pub use self::driver::Driver;
 pub use self::driver::DriverInfo;
 pub use self::driver::Registration;
Signature · 1 line
2.56.1
author maintainer
#2 lore raw

PATCH v3 2/7 rust: drm: gem: gate open/close callbacks with RegistrationGuard

In reply to Danilo Krummrich

Wrap the GEM object open and close callbacks with a RegistrationGuard (drm_dev_enter / drm_dev_exit) to ensure the driver callbacks only run while the parent bus device is bound.

If the device has been unbound, open returns -ENODEV and close silently returns. This prevents driver code from accessing device resources after unbind and is a prerequisite for making drm::Driver::File lifetime-parameterized, since GEM callbacks receive a &drm::File that could otherwise be used to access invalidated file private data.

---
 rust/kernel/drm/gem/mod.rs | 16 ++++++++++++++++
 1 file changed, 16 insertions(+)
rust/kernel/drm/gem/mod.rs +16 -0
index 85657a39e146..94355081edab 100644
@@ -128,6 +128,14 @@ extern "C" fn open_callback<T: DriverObject>(
     raw_obj: *mut bindings::drm_gem_object,
     raw_file: *mut bindings::drm_file,
 ) -> core::ffi::c_int {
+    // SAFETY: `raw_obj` is a valid pointer to a `struct drm_gem_object` with a valid `dev`.
+    let dev: &drm::Device<T::Driver, drm::Userspace> =
+        unsafe { drm::Device::from_raw((*raw_obj).dev) };
+
+    let Some(_guard) = dev.registration_guard() else {
+        return ENODEV.to_errno();
+    };
+
     // SAFETY: `open_callback` is only ever called with a valid pointer to a `struct drm_file`.
     let file = unsafe { DriverFile::<T>::from_raw(raw_file) };
 
@@ -148,6 +156,14 @@ extern "C" fn close_callback<T: DriverObject>(
     raw_obj: *mut bindings::drm_gem_object,
     raw_file: *mut bindings::drm_file,
 ) {
+    // SAFETY: `raw_obj` is a valid pointer to a `struct drm_gem_object` with a valid `dev`.
+    let dev: &drm::Device<T::Driver, drm::Userspace> =
+        unsafe { drm::Device::from_raw((*raw_obj).dev) };
+
+    let Some(_guard) = dev.registration_guard() else {
+        return;
+    };
+
     // SAFETY: `open_callback` is only ever called with a valid pointer to a `struct drm_file`.
     let file = unsafe { DriverFile::<T>::from_raw(raw_file) };
 
Signature · 1 line
2.56.1
author maintainer
#3 lore raw

PATCH v3 3/7 rust: drm: move file_operations from gem to device

In reply to Danilo Krummrich

Move the file_operations definition from drm::gem::create_fops() into UnregisteredDevice in drm::device. This is the file_operations of the DRM minor device, set through the drm_driver struct. It is not specific to GEM.

---
 rust/kernel/drm/device.rs  | 23 ++++++++++++++++++++---
 rust/kernel/drm/gem/mod.rs | 20 --------------------
 2 files changed, 20 insertions(+), 23 deletions(-)
rust/kernel/drm/device.rs +20 -3
index dd1c83fef323..3340fa0dc46b 100644
@@ -195,11 +195,28 @@ const fn compute_features() -> u32 {
         driver_features: Self::compute_features(),
         ioctls: T::IOCTLS.as_ptr(),
         num_ioctls: T::IOCTLS.len() as i32,
-        fops: &Self::GEM_FOPS,
+        fops: &Self::FOPS,
     };
 
-    const GEM_FOPS: bindings::file_operations =
-        drm::gem::create_fops(crate::module::this_module::<T::OwnerModule>().as_ptr());
+    const FOPS: bindings::file_operations = {
+        let mut fops: bindings::file_operations = pin_init::zeroed();
+
+        fops.owner = crate::module::this_module::<T::OwnerModule>().as_ptr();
+        fops.open = Some(bindings::drm_open);
+        fops.release = Some(bindings::drm_release);
+        fops.unlocked_ioctl = Some(bindings::drm_ioctl);
+        #[cfg(CONFIG_COMPAT)]
+        {
+            fops.compat_ioctl = Some(bindings::drm_compat_ioctl);
+        }
+        fops.poll = Some(bindings::drm_poll);
+        fops.read = Some(bindings::drm_read);
+        fops.llseek = Some(bindings::noop_llseek);
+        fops.mmap = Some(bindings::drm_gem_mmap);
+        fops.fop_flags = bindings::FOP_UNSIGNED_OFFSET;
+
+        fops
+    };
 
     /// Create a new `UnregisteredDevice` for a `drm::Driver`.
     ///
rust/kernel/drm/gem/mod.rs +0 -20
index 94355081edab..260f36817f96 100644
@@ -388,23 +388,3 @@ impl<T: DriverObject, Ctx: DeviceContext> AllocImpl for Object<T, Ctx> {
         dumb_map_offset: None,
     };
 }
-
-pub(super) const fn create_fops(owner: *mut bindings::module) -> bindings::file_operations {
-    let mut fops: bindings::file_operations = pin_init::zeroed();
-
-    fops.owner = owner;
-    fops.open = Some(bindings::drm_open);
-    fops.release = Some(bindings::drm_release);
-    fops.unlocked_ioctl = Some(bindings::drm_ioctl);
-    #[cfg(CONFIG_COMPAT)]
-    {
-        fops.compat_ioctl = Some(bindings::drm_compat_ioctl);
-    }
-    fops.poll = Some(bindings::drm_poll);
-    fops.read = Some(bindings::drm_read);
-    fops.llseek = Some(bindings::noop_llseek);
-    fops.mmap = Some(bindings::drm_gem_mmap);
-    fops.fop_flags = bindings::FOP_UNSIGNED_OFFSET;
-
-    fops
-}
Signature · 1 line
2.56.1
author maintainer
#4 lore raw

PATCH v3 4/7 rust: fs: add iminor() helper

In reply to Danilo Krummrich

Add a Rust helper for iminor(), which extracts the minor number from a struct inode. This is a static inline function in the C headers, so bindgen does not generate a binding for it.

---
 rust/helpers/fs.c | 5 +++++
 1 file changed, 5 insertions(+)
rust/helpers/fs.c +5 -0
index 789d60fb8908..d6f9782db178 100644
@@ -10,3 +10,8 @@ __rust_helper struct file *rust_helper_get_file(struct file *f)
 {
 	return get_file(f);
 }
+
+__rust_helper unsigned int rust_helper_iminor(const struct inode *inode)
+{
+	return iminor(inode);
+}
Signature · 1 line
2.56.1
author maintainer
#6 lore raw

PATCH v3 5/7 rust: drm: wrap fops open with RegistrationGuard

In reply to Danilo Krummrich

Add a Minor abstraction with RAII release and a fops_open() wrapper that holds a RegistrationGuard (drm_dev_enter / drm_dev_exit) across the entire drm_open() call.

This guarantees that drm_dev_unplug() in Registration::drop() waits for the full open sequence to complete, so all files are visible in the filelist when iterating for cleanup.

---
 rust/kernel/drm/device.rs | 63 ++++++++++++++++++++++++++++++++++++++-
 1 file changed, 62 insertions(+), 1 deletion(-)
rust/kernel/drm/device.rs +62 -1
index 3340fa0dc46b..b8444499b39c 100644
@@ -42,6 +42,42 @@
     },
 };
 
+/// A reference to a `struct drm_minor` with RAII release.
+struct Minor(NonNull<bindings::drm_minor>);
+
+// Methods use `#[inline(never)]` to prevent the unexported `drm_minor_acquire()` /
+// `drm_minor_release()` symbols from being inlined into driver modules.
+impl Minor {
+    /// Acquire a minor by ID. Increments the underlying device's refcount.
+    #[inline(never)]
+    fn acquire(minor_id: u32) -> Result<Self> {
+        // SAFETY: `drm_minors_xa` is a valid global xarray; any `minor_id` is safe to
+        // look up (returns ERR_PTR on failure).
+        let ptr =
+            unsafe { bindings::drm_minor_acquire(&raw mut bindings::drm_minors_xa, minor_id) };
+        Ok(Self(NonNull::new(from_err_ptr(ptr)?).ok_or(ENODEV)?))
+    }
+
+    /// Returns a reference to the DRM device for this minor.
+    ///
+    /// # Safety
+    ///
+    /// The caller must ensure that the minor belongs to a `Device<T>`.
+    unsafe fn device<T: drm::Driver>(&self) -> &Device<T, Userspace> {
+        // SAFETY: The minor is valid (from `drm_minor_acquire()`) and `minor->dev`
+        // is a valid `drm_device`. The caller guarantees it is a `Device<T>`.
+        unsafe { Device::from_raw((*self.0.as_ptr()).dev) }
+    }
+}
+
+impl Drop for Minor {
+    #[inline(never)]
+    fn drop(&mut self) {
+        // SAFETY: `self.0` came from `drm_minor_acquire()` and has not been released yet.
+        unsafe { bindings::drm_minor_release(self.0.as_ptr()) }
+    }
+}
+
 #[cfg(CONFIG_DRM_LEGACY)]
 macro_rules! drm_legacy_fields {
     ( $($field:ident: $val:expr),* $(,)? ) => {
@@ -198,11 +234,36 @@ const fn compute_features() -> u32 {
         fops: &Self::FOPS,
     };
 
+    /// Wrapper for `fops.open` that holds a [`RegistrationGuard`] across the entire `drm_open()`
+    /// call. This guarantees that `drm_dev_unplug()` in `Registration::drop()` waits for the full
+    /// open sequence.
+    extern "C" fn fops_open(inode: *mut bindings::inode, filp: *mut bindings::file) -> c_int {
+        let f = || -> Result<c_int> {
+            // SAFETY: `inode` is valid.
+            let minor_id = unsafe { bindings::iminor(inode) };
+            let minor = Minor::acquire(minor_id)?;
+
+            // SAFETY: `fops_open` is only installed for devices of type `T` (via `FOPS`).
+            let _guard = (unsafe { minor.device::<T>() })
+                .registration_guard()
+                .ok_or(ENODEV)?;
+
+            // SAFETY: `inode` and `filp` are valid. The RegistrationGuard ensures the entire
+            // `drm_open()` runs within the SRCU critical section.
+            Ok(unsafe { bindings::drm_open(inode, filp) })
+        };
+
+        match f() {
+            Ok(ret) => ret,
+            Err(e) => e.to_errno(),
+        }
+    }
+
     const FOPS: bindings::file_operations = {
         let mut fops: bindings::file_operations = pin_init::zeroed();
 
         fops.owner = crate::module::this_module::<T::OwnerModule>().as_ptr();
-        fops.open = Some(bindings::drm_open);
+        fops.open = Some(Self::fops_open);
         fops.release = Some(bindings::drm_release);
         fops.unlocked_ioctl = Some(bindings::drm_ioctl);
         #[cfg(CONFIG_COMPAT)]
Signature · 1 line
2.56.1
author maintainer
#7 lore raw

PATCH v3 6/7 rust: drm: return impl PinInit from DriverFile::open()

In reply to Danilo Krummrich

Change DriverFile::open() to return impl PinInit<Self, Error> instead of Result<Pin<KBox<Self>>>, consistent with how bus device private data works.

Drivers no longer need to allocate a Pin<KBox<_>> themselves; they just return an initializer and the subsystem takes care of the allocation.

---
 drivers/gpu/drm/nova/file.rs | 5 ++---
 drivers/gpu/drm/tyr/file.rs  | 4 ++--
 rust/kernel/drm/file.rs      | 5 +++--
 rust/kernel/drm/gem/shmem.rs | 4 ++--
 4 files changed, 9 insertions(+), 9 deletions(-)
drivers/gpu/drm/nova/file.rs +2 -3
index a05264917a0b..13642f83289d 100644
@@ -7,7 +7,6 @@
 };
 use crate::gem::NovaObject;
 use kernel::{
-    alloc::flags::*,
     drm::{
         self,
         gem::BaseObject,
@@ -103,8 +102,8 @@ fn write_info<T: AsBytes>(info: &mut uapi::drm_nova_info, value: T) -> Result {
 impl drm::file::DriverFile for File {
     type Driver = NovaDriver;
 
-    fn open(_dev: &NovaDevice) -> Result<Pin<KBox<Self>>> {
-        Ok(KBox::new(Self, GFP_KERNEL)?.into())
+    fn open(_dev: &NovaDevice) -> impl PinInit<Self, Error> {
+        Ok(Self)
     }
 }
 
drivers/gpu/drm/tyr/file.rs +2 -2
index 9f60a90d4948..6850708cfcdd 100644
@@ -25,8 +25,8 @@ pub(crate) struct TyrDrmFileData {}
 impl drm::file::DriverFile for TyrDrmFileData {
     type Driver = TyrDrmDriver;
 
-    fn open(_dev: &drm::Device<Self::Driver>) -> Result<Pin<KBox<Self>>> {
-        KBox::try_pin_init(try_pin_init!(Self {}), GFP_KERNEL)
+    fn open(_dev: &drm::Device<Self::Driver>) -> impl PinInit<Self, Error> {
+        Ok(Self {})
     }
 }
 
rust/kernel/drm/file.rs +3 -2
index 10160601ce5a..bd5e4ca2977f 100644
@@ -18,7 +18,7 @@ pub trait DriverFile {
     type Driver: drm::Driver;
 
     /// Open a new file (called when a client opens the DRM device).
-    fn open(device: &drm::Device<Self::Driver>) -> Result<Pin<KBox<Self>>>;
+    fn open(device: &drm::Device<Self::Driver>) -> impl PinInit<Self, Error>;
 }
 
 /// An open DRM File.
@@ -70,7 +70,8 @@ pub(crate) extern "C" fn open_callback(
         // SAFETY: `raw_file` is a valid pointer to a `struct drm_file`.
         let file = unsafe { File::<T>::from_raw(raw_file) };
 
-        let inner = match T::open(drm) {
+        let init = T::open(drm);
+        let inner = match KBox::try_pin_init(init, GFP_KERNEL) {
             Err(e) => {
                 return e.to_errno();
             }
rust/kernel/drm/gem/shmem.rs +2 -2
index 24cb5343e0db..1a4f81e3b5b5 100644
@@ -604,8 +604,8 @@ struct KunitObject {}
     impl drm::file::DriverFile for KunitFile {
         type Driver = KunitDriver;
 
-        fn open(_dev: &drm::Device<KunitDriver>) -> Result<Pin<KBox<Self>>> {
-            Ok(KBox::new(Self, GFP_KERNEL)?.into())
+        fn open(_dev: &drm::Device<KunitDriver>) -> impl PinInit<Self, Error> {
+            Ok(Self)
         }
     }
 
Signature · 1 line
2.56.1
author maintainer
#8 lore raw

PATCH v3 7/7 rust: drm: make Driver::File lifetime-parameterized

In reply to Danilo Krummrich

Make the DRM file private data lifetime-parameterized, allowing drivers to borrow from RegistrationData in their per-file data.

Introduce DriverFile<'a> as a lifetime-parameterized trait that receives both the device and registration data in open(). Parametrize File<D> on the driver type rather than the file data type, deriving the concrete file type through Driver::File<'a>.

Add inner_with() to access the driver file data from a File<D> reference.

Ensure file data is always dropped before registration data:

- In Registration::drop(), detach driver_priv for all open files under filelist_mutex, then drop the detached data after releasing the mutex and wait for file-data destruction in concurrent postclose_callback() calls via an open_count / WaitQueue pair on drm::Device.

- In postclose_callback(), skip the drop if driver_priv has already been NULLed by the filelist iteration. The NULL write is visible through the filelist_mutex acquire/release chain in drm_close_helper().

---
 drivers/gpu/drm/nova/driver.rs |   2 +-
 drivers/gpu/drm/nova/file.rs   |  13 ++-
 drivers/gpu/drm/nova/gem.rs    |   8 +-
 drivers/gpu/drm/tyr/driver.rs  |   2 +-
 drivers/gpu/drm/tyr/file.rs    |  11 ++-
 rust/kernel/drm/device.rs      |  31 +++++-
 rust/kernel/drm/driver.rs      | 113 +++++++++++++++++++--
 rust/kernel/drm/file.rs        | 173 ++++++++++++++++++++++++---------
 rust/kernel/drm/gem/mod.rs     |  44 ++++++---
 rust/kernel/drm/gem/shmem.rs   |   9 +-
 rust/kernel/drm/ioctl.rs       |   6 +-
 11 files changed, 322 insertions(+), 90 deletions(-)
drivers/gpu/drm/nova/driver.rs +1 -1
index 44a52e60b3c7..f2d40e6fab21 100644
@@ -90,7 +90,7 @@ fn probe<'bound>(
 impl drm::Driver for NovaDriver {
     type Data = ();
     type RegistrationData<'a> = DrmRegData<'a>;
-    type File = File;
+    type File<'a> = File;
     type Object = gem::Object<NovaObject>;
     type ParentDevice<Ctx: DeviceContext> = auxiliary::Device<Ctx>;
 
drivers/gpu/drm/nova/file.rs +8 -5
index 13642f83289d..8b800f821e2c 100644
@@ -99,10 +99,13 @@ fn write_info<T: AsBytes>(info: &mut uapi::drm_nova_info, value: T) -> Result {
     Ok(())
 }
 
-impl drm::file::DriverFile for File {
+impl drm::file::DriverFile<'_> for File {
     type Driver = NovaDriver;
 
-    fn open(_dev: &NovaDevice) -> impl PinInit<Self, Error> {
+    fn open(
+        _device: &NovaDevice<Registered>,
+        _reg_data: &DrmRegData<'_>,
+    ) -> impl PinInit<Self, Error> {
         Ok(Self)
     }
 }
@@ -113,7 +116,7 @@ pub(crate) fn gem_create(
         dev: &NovaDevice<Registered>,
         _reg_data: &DrmRegData<'_>,
         req: &mut uapi::drm_nova_gem_create,
-        file: &drm::File<File>,
+        file: &drm::File<NovaDriver>,
     ) -> Result<u32> {
         let obj = NovaObject::new(dev, req.size.try_into()?)?;
 
@@ -127,7 +130,7 @@ pub(crate) fn gem_info(
         _dev: &NovaDevice<Registered>,
         _reg_data: &DrmRegData<'_>,
         req: &mut uapi::drm_nova_gem_info,
-        file: &drm::File<File>,
+        file: &drm::File<NovaDriver>,
     ) -> Result<u32> {
         let bo = NovaObject::lookup_handle(file, req.handle)?;
 
@@ -141,7 +144,7 @@ pub(crate) fn info(
         _dev: &NovaDevice<Registered>,
         reg_data: &DrmRegData<'_>,
         info: &mut uapi::drm_nova_info,
-        _file: &drm::File<File>,
+        _file: &drm::File<NovaDriver>,
     ) -> Result<u32> {
         match info.id {
             uapi::DRM_NOVA_INFO_GPU => write_info(info, GpuInfo::new(reg_data)?)?,
drivers/gpu/drm/nova/gem.rs +4 -4
index 2b6fe9dc0bfa..2a21ff8ba579 100644
@@ -11,9 +11,9 @@
     sync::aref::ARef,
 };
 
-use crate::{
-    driver::{NovaDevice, NovaDriver},
-    file::File,
+use crate::driver::{
+    NovaDevice,
+    NovaDriver, //
 };
 
 /// GEM Object inner driver data
@@ -43,7 +43,7 @@ pub(crate) fn new(dev: &NovaDevice, size: usize) -> Result<ARef<gem::Object<Self
     /// Look up a GEM object handle for a `File` and return an `ObjectRef` for it.
     #[inline]
     pub(crate) fn lookup_handle(
-        file: &drm::File<File>,
+        file: &drm::File<NovaDriver>,
         handle: u32,
     ) -> Result<ARef<gem::Object<Self>>> {
         gem::Object::lookup_handle(file, handle)
drivers/gpu/drm/tyr/driver.rs +1 -1
index c2b99d67369f..46caf7b336d9 100644
@@ -209,7 +209,7 @@ fn drop(self: Pin<&mut Self>) {}
 impl drm::Driver for TyrDrmDriver {
     type Data = ();
     type RegistrationData<'drm> = TyrDrmRegistrationData<'drm>;
-    type File = TyrDrmFileData;
+    type File<'a> = TyrDrmFileData;
     type Object = Bo;
     type ParentDevice<Ctx: DeviceContext> = platform::Device<Ctx>;
 
drivers/gpu/drm/tyr/file.rs +7 -4
index 6850708cfcdd..933a365cb016 100644
@@ -19,13 +19,16 @@
 #[pin_data]
 pub(crate) struct TyrDrmFileData {}
 
-/// Convenience type alias for our DRM `File` type
-pub(crate) type TyrDrmFile = drm::file::File<TyrDrmFileData>;
+/// Convenience type alias for our DRM `File` type.
+pub(crate) type TyrDrmFile = drm::file::File<TyrDrmDriver>;
 
-impl drm::file::DriverFile for TyrDrmFileData {
+impl drm::file::DriverFile<'_> for TyrDrmFileData {
     type Driver = TyrDrmDriver;
 
-    fn open(_dev: &drm::Device<Self::Driver>) -> impl PinInit<Self, Error> {
+    fn open(
+        _device: &TyrDrmDevice<Registered>,
+        _reg_data: &TyrDrmRegistrationData<'_>,
+    ) -> impl PinInit<Self, Error> {
         Ok(Self {})
     }
 }
rust/kernel/drm/device.rs +26 -5
index b8444499b39c..9dfb71cb2e69 100644
@@ -15,9 +15,13 @@
     },
     error::from_err_ptr,
     prelude::*,
-    sync::aref::{
-        ARef,
-        AlwaysRefCounted, //
+    sync::{
+        aref::{
+            ARef,
+            AlwaysRefCounted, //
+        },
+        atomic::Atomic,
+        WaitQueue,
     },
     types::{
         NotThreadSafe,
@@ -203,8 +207,8 @@ const fn compute_features() -> u32 {
 
     const VTABLE: bindings::drm_driver = drm_legacy_fields! {
         load: None,
-        open: Some(drm::File::<T::File>::open_callback),
-        postclose: Some(drm::File::<T::File>::postclose_callback),
+        open: Some(drm::File::<T>::open_callback),
+        postclose: Some(drm::File::<T>::postclose_callback),
         unload: None,
         release: Some(Device::<T>::release),
         master_set: None,
@@ -333,6 +337,21 @@ pub fn new(
         // SAFETY: `raw_drm` is valid; no concurrent access before registration.
         unsafe { (*raw_drm.as_ptr()).registration_data = UnsafeCell::new(NonNull::dangling()) };
 
+        // SAFETY: `raw_drm` is valid; no concurrent access before registration.
+        unsafe { (*raw_drm.as_ptr()).open_count = Atomic::new(0) };
+
+        // SAFETY:
+        // - `raw_drm` is valid and `open_count_wq` is uninitialized; no concurrent access
+        //   before registration.
+        // - The field is pinned because the Device is pinned (refcounted, allocated by
+        //   `__drm_dev_alloc()`, never moved).
+        unsafe {
+            pin_init::raw_init(
+                &raw mut (*raw_drm.as_ptr()).open_count_wq,
+                crate::new_waitqueue!("drm_open_count"),
+            )
+        };
+
         // SAFETY: The reference count is one, and now we take ownership of that reference as a
         // `drm::Device`.
         // INVARIANT: We just created the device above, but have yet to call `drm_dev_register`.
@@ -357,6 +376,8 @@ pub struct Device<T: drm::Driver, C: DeviceContext = Normal> {
     dev: Opaque<bindings::drm_device>,
     data: T::Data,
     pub(super) registration_data: UnsafeCell<NonNull<T::RegistrationData<'static>>>,
+    pub(super) open_count: Atomic<u64>,
+    pub(super) open_count_wq: WaitQueue,
     _ctx: PhantomData<C>,
 }
 
rust/kernel/drm/driver.rs +106 -7

144 lines not on this page · raw message

rust/kernel/drm/file.rs +126 -47

222 lines not on this page · raw message

rust/kernel/drm/gem/mod.rs +33 -11

86 lines not on this page · raw message

rust/kernel/drm/gem/shmem.rs +6 -3
index 1a4f81e3b5b5..1558b6079edf 100644
@@ -601,10 +601,13 @@ struct KunitObject {}
         desc: c"Kunit",
     };
 
-    impl drm::file::DriverFile for KunitFile {
+    impl drm::file::DriverFile<'_> for KunitFile {
         type Driver = KunitDriver;
 
-        fn open(_dev: &drm::Device<KunitDriver>) -> impl PinInit<Self, Error> {
+        fn open(
+            _device: &drm::Device<KunitDriver, drm::Registered>,
+            _reg_data: &(),
+        ) -> impl PinInit<Self, Error> {
             Ok(Self)
         }
     }
@@ -626,7 +629,7 @@ fn new(
     impl drm::Driver for KunitDriver {
         type Data = KunitData;
         type RegistrationData<'a> = ();
-        type File = KunitFile;
+        type File<'a> = KunitFile;
         type Object = Object<KunitObject>;
         type ParentDevice<Ctx: device::DeviceContext> = faux::Device<Ctx>;
 
rust/kernel/drm/ioctl.rs +4 -2
index 9934b23c36eb..65c326348c64 100644
@@ -97,7 +97,7 @@ pub const fn __dev_ctx_cast<T: crate::drm::Driver>(
 /// fn foo(device: &kernel::drm::Device<Self, kernel::drm::Registered>,
 ///        reg_data: &Self::RegistrationData<'_>,
 ///        data: &mut uapi::argument_type,
-///        file: &kernel::drm::File<Self::File>,
+///        file: &kernel::drm::File<Self>,
 /// ) -> Result<u32>
 /// ```
 /// where `Self` is the drm::drv::Driver implementation these ioctls are being declared within.
@@ -192,7 +192,9 @@ macro_rules! declare_drm_ioctls {
                             // There is no concurrent access or aliasing; no other references
                             // to this object exist during this call.
                             let data = unsafe { &mut *(raw_data.cast::<$crate::uapi::$struct>()) };
-                            // SAFETY: This is just the DRM file structure
+                            // SAFETY:
+                            // - The DRM core provides a valid file for this device.
+                            // - `guard` is held for the entire use of the file reference.
                             let file = unsafe { $crate::drm::File::from_raw(raw_file) };
 
                             match guard.registration_data_with(|reg_data| {
Signature · 1 line
2.56.1
maintainer Reviewed-by on v3 7/7
#9 lore raw

Re: [PATCH v3 7/7] rust: drm: make Driver::File lifetime-parameterized

On Wed, Nov 18, 2026 at 05:29:48PM +0100, Danilo Krummrich wrote:

The v3 updates look good to me, thanks!

Alice

reviewer Reviewed-by on v3 7/7
#10 lore raw

Re: [PATCH v3 7/7] rust: drm: make Driver::File lifetime-parameterized

In reply to Danilo Krummrich
Quoted 17 lines · Danilo Krummrich

Make the DRM file private data lifetime-parameterized, allowing drivers to borrow from RegistrationData in their per-file data.

Introduce DriverFile<'a> as a lifetime-parameterized trait that receives both the device and registration data in open(). Parametrize File<D> on the driver type rather than the file data type, deriving the concrete file type through Driver::File<'a>.

Add inner_with() to access the driver file data from a File<D> reference.

Ensure file data is always dropped before registration data:

- In Registration::drop(), detach driver_priv for all open files under filelist_mutex, then drop the detached data after releasing the mutex and wait for file-data destruction in concurrent postclose_callback() calls via an open_count / WaitQueue pair on drm::Device.

Quoted 8 lines

- In postclose_callback(), skip the drop if driver_priv has already been NULLed by the filelist iteration. The NULL write is visible through the filelist_mutex acquire/release chain in drm_close_helper().

Quoted 13 lines
---
 drivers/gpu/drm/nova/driver.rs |   2 +-
 drivers/gpu/drm/nova/file.rs   |  13 ++-
 drivers/gpu/drm/nova/gem.rs    |   8 +-
 drivers/gpu/drm/tyr/driver.rs  |   2 +-
 drivers/gpu/drm/tyr/file.rs    |  11 ++-
 rust/kernel/drm/device.rs      |  31 +++++-
 rust/kernel/drm/driver.rs      | 113 +++++++++++++++++++--
 rust/kernel/drm/file.rs        | 173 ++++++++++++++++++++++++---------
 rust/kernel/drm/gem/mod.rs     |  44 ++++++---
 rust/kernel/drm/gem/shmem.rs   |   9 +-
 rust/kernel/drm/ioctl.rs       |   6 +-
 11 files changed, 322 insertions(+), 90 deletions(-)
author maintainer Applied
#11 lore raw
In reply to Danilo Krummrich
Quoted 1 line · Danilo Krummrich

[PATCH v3 0/7] lifetime-parameterized DRM File private data

Applied, thanks!

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

[1/7] rust: drm: rename Ioctl device context to Userspace

      commit: 69976e5f24ed
[2/7] rust: drm: gem: gate open/close callbacks with RegistrationGuard
      commit: 6f90031b5cf9
[3/7] rust: drm: move file_operations from gem to device
      commit: acce9c14569d
[4/7] rust: fs: add iminor() helper
      commit: d63e44ab58dd
[5/7] rust: drm: wrap fops open with RegistrationGuard
      commit: 5a31079c7c5f
[6/7] rust: drm: return impl PinInit from DriverFile::open()
      commit: b8ab877d7b44
[7/7] rust: drm: make Driver::File lifetime-parameterized
      commit: fed919c71b52

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.