drm/tyr: add debugfs support
Subsystems (8)
v2 cover drm/tyr: add debugfs support
Add debugfs support for the Tyr DRM driver.
The series adds a SeqShow trait for seq_file-backed debugfs files with lifecycle hooks, a DrmSeqShow adapter with DRM device lifecycle management, and a gpuvas debugfs file in Tyr exposing GPU VA space information.
Additionally, fix a use-after-free in the DRM debugfs open/release paths where a device could be unregistered while a debugfs file remains open.
This is based on drm-rust-next and depends on:
[PATCH v10 0/7] drm/tyr: firmware loading and MCU boot support
https://lore.kernel.org/r/[email protected]
See the full dependency and commit history at [1].
---
Changes in v2:
- Reworked the debugfs implementation per feedback from Danilo on v1:
dropped the hazptr/revocable-based approach in favor of the DRM debugfs_init callback and generic seq_file abstractions.
- Fixed a UAF in drm_debugfs where a device could be unregistered while
a debugfs file remains open (drm_dev_get/put across file lifetime).
- Link to v1: https://lore.kernel.org/r/[email protected]
---
Alvin Sun (9):
rust: seq_file: add as_raw() method
rust: debugfs: add SeqShow trait and seq_file file operations
rust: debugfs: add Entry::from_raw and ScopedDir::from_dentry
drm: move debugfs_init after dev->registered is set
rust: drm: add debugfs_init callback to Driver trait
rust: drm: add DrmSeqShow seq_file adapter
rust: drm: gpuvm: add dump_gpuva_info to UniqueRefGpuVm drm/tyr: add gpuvas debugfs file
drm/debugfs: hold device reference for the lifetime of open files
drivers/gpu/drm/drm_debugfs.c | 45 ++++++++++++++++--- drivers/gpu/drm/drm_drv.c | 5 +++ drivers/gpu/drm/tyr/debugfs.rs | 65 +++++++++++++++++++++++++++ drivers/gpu/drm/tyr/driver.rs | 16 +++++++ drivers/gpu/drm/tyr/fw.rs | 8 ++++ drivers/gpu/drm/tyr/tyr.rs | 1 + drivers/gpu/drm/tyr/vm.rs | 5 +++ rust/bindings/bindings_helper.h | 1 + rust/kernel/debugfs.rs | 35 ++++++++++++++- rust/kernel/debugfs/entry.rs | 15 ++++++- rust/kernel/debugfs/file_ops.rs | 97 +++++++++++++++++++++++++++++++++++++++++ rust/kernel/debugfs/traits.rs | 30 ++++++++++++- rust/kernel/drm/debugfs.rs | 49 +++++++++++++++++++++ rust/kernel/drm/device.rs | 36 ++++++++++++++- rust/kernel/drm/driver.rs | 11 +++++ rust/kernel/drm/gpuvm/mod.rs | 8 ++++ rust/kernel/drm/mod.rs | 1 + rust/kernel/seq_file.rs | 6 +++ 18 files changed, 422 insertions(+), 12 deletions(-)
---
base-commit: 0ffc014cb2abfc79d161662b125e085b3e7107e7
change-id: 20260730-tyr-debugfs-v2-608cef77d6e9
Best regards,
Signature · 1 line
Alvin Sun <[email protected]>
PATCH v2 1/9 rust: seq_file: add as_raw() method
Add a method to obtain a raw pointer to the underlying struct seq_file, needed for FFI calls into C (e.g. drm_debugfs_gpuva_info).
--- rust/kernel/seq_file.rs | 6 ++++++ 1 file changed, 6 insertions(+)
rust/kernel/seq_file.rs +6 -0
@@ -29,6 +29,12 @@ pub unsafe fn from_raw<'a>(ptr: *mut bindings::seq_file) -> &'a SeqFile {unsafe { &*ptr.cast () } } +/// Returns a raw pointer to the underlying `struct seq_file`. +#[inline] +pub fn as_raw (&self) -> *mut bindings::seq_file { + self.inner.get () + } +/// Used by the [`seq_print`] macro. #[inline] pub fn call_printf (&self, args: fmt::Arguments <'_>) {
Signature · 1 line
2.43.0
PATCH v2 2/9 rust: debugfs: add SeqShow trait and seq_file file operations
In reply to Alvin SunAdd SeqShow trait for seq_file-backed debugfs files with optional open/release lifecycle hooks. Needed by DRM and other subsystems to expose readable debugfs state via seq_file.
--- rust/kernel/debugfs.rs | 16 ++++++- rust/kernel/debugfs/file_ops.rs | 97 +++++++++++++++++++++++++++++++++++++++++ rust/kernel/debugfs/traits.rs | 30 ++++++++++++- 3 files changed, 141 insertions(+), 2 deletions(-)
rust/kernel/debugfs.rs +15 -1
@@ -24,7 +24,7 @@ PhantomData, PhantomPinned, // }, - ops::Deref, + ops::Deref, // };mod traits;
@@ -33,6 +33,7 @@ BinaryReaderMut, BinaryWriter, Reader, + SeqShow, Writer, // };
@@ -51,6 +52,7 @@ FileOps, ReadFile, ReadWriteFile, + SeqReadFile, WriteFile, // };
@@ -588,6 +590,18 @@ pub fn read_callback_file<T, F>(&self, name: &CStr, data: &'data T, _f: &'static self.create_file (name, data, vtable) } +/// Creates a seq_file debugfs file in this directory. +/// +/// The file's contents are produced by invoking [`SeqShow::show`] with +/// `data` on each read. +/// +/// This function does not produce an owning handle to the file. The created +/// file is removed when the [`Scope`] that this directory belongs to is +/// dropped. +pub fn seq_file <S :SeqShow <U >,U :Sync + 'static>(&self, name: &CStr , data: &'dataU ) { + self.create_file (name, data, &<S as SeqReadFile <U >>::FILE_OPS ) + } +/// Creates a read-write file in this directory. /// /// Reading the file uses the [`Writer`] implementation on `data`. Writing to the file uses
rust/kernel/debugfs/file_ops.rs +97 -0
120 lines not on this page · raw message
rust/kernel/debugfs/traits.rs +29 -1
@@ -8,6 +8,7 @@ fmt, fs::file, prelude::*, + seq_file::SeqFile, sync::{ atomic::{Atomic ,
@@ -33,7 +34,8 @@ Deref, DerefMut, // }, - str::FromStr, + ptr::NonNull, + str::FromStr, // };/// A trait for types that can be written into a string.
@@ -338,3 +340,29 @@ fn read_from_slice( self.deref ().read_from_slice (reader, offset) } } + +/// Renders `data` into a seq_file. +/// +/// `data` is the value stashed as the debugfs file's `i_private` at creation +/// time. `show` is invoked on each read to produce the file's contents. +/// +/// `open` and `release` are optional lifecycle hooks called during file open +/// and release. They can be used to manage the lifetime of `data` (e.g., +/// reference counting). Default implementations are no-ops. +pub trait SeqShow <T > { +/// Writes debugfs output for the file. +fn show (data: &T , m: &SeqFile ) ->Result ; + +/// Called during file open, before `single_open`. +fn open (_data: &T ) ->Result { +Ok (()) + } + +/// Called during file release, before `single_release`. +/// +/// # Safety +/// +/// `data` must point to valid memory, kept alive by actions taken in +/// [`Self::open`] (e.g., incrementing a reference count). +unsafe fn release (_data:NonNull <T >) {} +}
Signature · 1 line
2.43.0
PATCH v2 3/9 rust: debugfs: add Entry::from_raw and ScopedDir::from_dentry
In reply to Alvin SunAdd methods to construct debugfs abstractions from raw C dentry pointers. Needed by DRM debugfs_init callback to create ScopedDir from the root dentry provided by C core.
--- rust/kernel/debugfs.rs | 19 +++++++++++++++++++ rust/kernel/debugfs/entry.rs | 15 ++++++++++++++- 2 files changed, 33 insertions(+), 1 deletion(-)
rust/kernel/debugfs.rs +19 -0
@@ -735,4 +735,23 @@ fn new(name: &CStr) -> ScopedDir<'data, 'static> { _phantom: PhantomData, } } + +/// Creates a [`ScopedDir`] wrapping an existing debugfs dentry. +/// +/// Files created under this directory are not automatically removed on drop; +/// their lifetime is tied to the dentry owner. +/// +/// # Safety +/// +/// The caller must ensure the dentry remains valid for the lifetime of the +/// returned `ScopedDir`. +pub unsafe fn from_dentry (dentry: *mut bindings::dentry ) ->Self { +let _ = dentry; +ScopedDir { +#[cfg( CONFIG_DEBUG_FS )] +// SAFETY: The caller guarantees the dentry is valid and outlives this `ScopedDir`. + entry:ManuallyDrop ::new (unsafe {Entry ::from_raw (dentry) }), + _phantom:PhantomData , + } + } }
rust/kernel/debugfs/entry.rs +14 -1
@@ -8,7 +8,7 @@ CStr, CStrExt as _, // }, - sync::Arc, + sync::Arc, // };use core::marker::PhantomData ;
@@ -87,6 +87,19 @@ pub(crate) unsafe fn dynamic_file<T>( }impl <'a>Entry <'a> { +/// Wraps a raw dentry pointer. +/// +/// # Safety +/// +/// The caller must ensure the dentry is valid and outlives this `Entry`. +pub (crate )unsafe fn from_raw (entry: *mut bindings::dentry ) ->Self { +Self { + entry, + _parent:None , + _phantom:PhantomData , + } + } +pub (crate )fn dir (name: &CStr , parent:Option <&'aEntry <'_>>) ->Self {let parent_ptr =match &parent { Some(entry) => entry.as_ptr(),
Signature · 1 line
2.43.0
PATCH v2 4/9 drm: move debugfs_init after dev->registered is set
In reply to Alvin SunThe debugfs_init callback was invoked by drm_debugfs_register before dev->registered is set to true. Moving it to drm_dev_register after dev->registered = true fixes the Ioctl type invariant violation.
--- drivers/gpu/drm/drm_debugfs.c | 3 --- drivers/gpu/drm/drm_drv.c | 5 +++++ 2 files changed, 5 insertions(+), 3 deletions(-)
drivers/gpu/drm/drm_debugfs.c +0 -3
@@ -442,9 +442,6 @@ int drm_debugfs_register(struct drm_minor *minor, int minor_id)/* TODO: Only for compatibility with drivers */ minor->debugfs_root = dev->debugfs_root; -if (dev->driver->debugfs_init && dev->render != minor) - dev->driver->debugfs_init (minor); -return 0 ; }
drivers/gpu/drm/drm_drv.c +5 -0
@@ -1101,6 +1101,11 @@ int drm_dev_register(struct drm_device *dev, unsigned long flags) dev->registered = true; dev->unplugged = false; +/* Call debugfs_init after the device is fully registered. */ +if (dev->driver->debugfs_init && dev->primary && + dev->render != dev->primary) + dev->driver->debugfs_init (dev->primary); +if (driver->load) { ret = driver->load (dev, flags);if (ret)
Signature · 1 line
2.43.0
PATCH v2 5/9 rust: drm: add debugfs_init callback to Driver trait
In reply to Alvin SunAdd debugfs_init method to the Driver trait, enabling Rust DRM drivers to populate debugfs entries during device registration. The C callback converts from raw C minor/dentry types to Rust Device and ScopedDir references.
--- rust/bindings/bindings_helper.h | 1 + rust/kernel/drm/device.rs | 36 ++++++++++++++++++++++++++++++++++-- rust/kernel/drm/driver.rs | 11 +++++++++++ 3 files changed, 46 insertions(+), 2 deletions(-)
rust/bindings/bindings_helper.h +1 -0
@@ -30,6 +30,7 @@#include <linux/acpi.h> #include <linux/gpu_buddy.h> +#include <drm/drm_debugfs.h> #include <drm/drm_device.h> #include <drm/drm_drv.h> #include <drm/drm_file.h>
rust/kernel/drm/device.rs +34 -2
@@ -7,6 +7,7 @@use crate ::{ alloc::allocator::Kmalloc , bindings, + debugfs::ScopedDir , device, drm::{ self,
@@ -39,7 +40,7 @@ ptr::{ self,NonNull ,// - }, + }, // };#[cfg( CONFIG_DRM_LEGACY )]
@@ -170,7 +171,7 @@ const fn compute_features() -> u32 { release: Some(Device::<T>::release), master_set: None, master_drop: None, - debugfs_init: None, + debugfs_init: Some(Device::<T, Normal>::debugfs_init_callback), gem_create_object: T::Object::ALLOC_OPS.gem_create_object, prime_handle_to_fd: T::Object::ALLOC_OPS.prime_handle_to_fd,
@@ -353,6 +354,37 @@ extern "C" fn release(ptr: *mut bindings::drm_device) {unsafe { core::ptr::drop_in_place (this) }; } +/// C callback for `drm_driver.debugfs_init`. +/// +/// # Safety +/// +/// The DRM core guarantees that `minor` is valid and non-null when calling +/// this callback, and that `minor->dev` is a valid `drm_device` embedded +/// in a `Device<T>`. +unsafe extern "C" fn debugfs_init_callback (minor: *mut bindings::drm_minor ) { +// SAFETY: `minor` is valid and non-null per the function's safety +// precondition. +let dev_ptr =unsafe { (*minor).dev }; +// SAFETY: `minor` is valid per the function's safety precondition. +let debugfs_root =unsafe { (*minor).debugfs_root }; + +// Debugfs may be disabled. +if debugfs_root.is_null () { +return ; + } + +// SAFETY: `dev_ptr` points to a valid `drm_device` embedded in +// `Device<T, Normal>`. `debugfs_init` runs during registration, so +// the `Normal` context is correct. +let device =unsafe {Device ::<T ,Normal >::from_raw (dev_ptr) }; + +// SAFETY: `debugfs_root` is a valid dentry that remains alive as long as the +// DRM device is registered, which outlives this `ScopedDir`. +let dir =unsafe {ScopedDir ::from_dentry (debugfs_root) }; + +T ::debugfs_init (device, &dir); + } +/// Change the [`DeviceContext`] for a [`Device`]. /// /// # Safety
rust/kernel/drm/driver.rs +11 -0
@@ -6,6 +6,7 @@use crate ::{ bindings, + debugfs::ScopedDir , device, drm, error::to_result,
@@ -138,6 +139,16 @@ pub trait Driver {/// usable from the render node (i.e. marked DRM_RENDER_ALLOW), whereas /// userspace processes using the master node can invoke any ioctl. const FEAT_RENDER :bool =false ; + +/// Populates debugfs for this DRM device. +/// +/// Called by the DRM core during registration, once per minor (callback +/// runs after `dev->registered`). +fn debugfs_init <'a>(_dev: &'a drm::Device <Self , drm::Normal >, _dir: &ScopedDir <'a, 'static>) +where +Self :Sized , + { + } }/// The registration type of a `drm::Device`.
Signature · 1 line
2.43.0
PATCH v2 6/9 rust: drm: add DrmSeqShow seq_file adapter
In reply to Alvin SunAdd DrmSeqShow trait and its SeqShow blanket impl for Device<T, Normal>, enabling Rust DRM drivers to expose device state via debugfs seq_file entries. Device registration data is kept alive for the duration of each seq_file read.
--- rust/kernel/drm/debugfs.rs | 49 ++++++++++++++++++++++++++++++++++++++++++++++ rust/kernel/drm/mod.rs | 1 + 2 files changed, 50 insertions(+)
rust/kernel/drm/debugfs.rs new file +49 -0
@@ -0,0 +1,49 @@ +// SPDX-License-Identifier: GPL-2.0 OR MIT + +//! DRM-specific debugfs seq_file helpers. + +use crate ::{ + debugfs, + drm, + prelude::*, + seq_file, + sync::aref::AlwaysRefCounted ,// +}; +use core::ptr::NonNull ; + +/// Renders DRM device state into a seq_file under SRCU protection. +/// +/// Pass an implementing type to +/// [`debugfs::ScopedDir::seq_file`]. The `show` +/// method receives a [`drm::RegistrationGuard`] that keeps DRM device data alive +/// for its duration. +pub trait DrmSeqShow <T : drm::Driver > { +/// Writes debugfs output for the file. +fn show (guard: &drm::RegistrationGuard <'_,T >, m: &seq_file::SeqFile ) ->Result ; +} + +impl <S :DrmSeqShow <T >,T : drm::Driver > debugfs::SeqShow <drm::Device <T , drm::Normal >>for S { +fn show (dev: &drm::Device <T , drm::Normal >, m: &seq_file::SeqFile ) ->Result { +// SAFETY: `debugfs_init` runs after `dev->registered = true` is set, +// so the `Ioctl` invariant is satisfied. `Normal` and `Ioctl` share +// an identical layout. +let dev =unsafe { dev.assume_ctx ::<drm::Ioctl >() }; + +let Some (guard) = dev.registration_guard ()else { +return Err (ENODEV ); + }; +S ::show (&guard, m) + } + +fn open (dev: &drm::Device <T , drm::Normal >) ->Result { +// Hold a device reference so the device is not freed while the file is open. + dev.inc_ref (); +Ok (()) + } + +unsafe fn release (dev:NonNull <drm::Device <T , drm::Normal >>) { +// Drop the reference taken in `open`. +// SAFETY: `dev` is valid per this function's safety contract. +unsafe { drm::Device ::<T >::dec_ref (dev) }; + } +}
rust/kernel/drm/mod.rs +1 -0
@@ -2,6 +2,7 @@//! DRM subsystem abstractions. +pub mod debugfs;pub mod device;pub mod driver;pub mod file;
Signature · 1 line
2.43.0
PATCH v2 7/9 rust: drm: gpuvm: add dump_gpuva_info to UniqueRefGpuVm
In reply to Alvin SunAdd method wrapping drm_debugfs_gpuva_info to dump GPU VA space mappings into a seq_file. Needed by the Tyr gpuvas debugfs file.
--- rust/kernel/drm/gpuvm/mod.rs | 8 ++++++++ 1 file changed, 8 insertions(+)
rust/kernel/drm/gpuvm/mod.rs +8 -0
@@ -312,6 +312,14 @@ pub fn data_ref(&self) -> &T {unsafe { &*self.0 .data.get () } } +/// Dumps GPU VA space info into a seq_file. +/// +/// Wraps the C `drm_debugfs_gpuva_info` function. +pub fn dump_gpuva_info (&self, m: &crate ::seq_file::SeqFile ) ->Result { +// SAFETY: `m.as_raw()` and `self.as_raw()` are valid by the type invariants. +to_result (unsafe { bindings::drm_debugfs_gpuva_info (m.as_raw (), self.as_raw ()) }) + } +/// Access the data owned by this `UniqueRefGpuVm` mutably. #[inline] pub fn data (&mut self) -> &mut T {
Signature · 1 line
2.43.0
PATCH v2 8/9 drm/tyr: add gpuvas debugfs file
In reply to Alvin SunAdd a gpuvas debugfs file listing all GPU VAs for the Tyr DRM driver. Collects VMs into a shared list during firmware init and renders them via dump_gpuva_info on read.
--- drivers/gpu/drm/tyr/debugfs.rs | 65 ++++++++++++++++++++++++++++++++++++++++++ drivers/gpu/drm/tyr/driver.rs | 16 +++++++++++ drivers/gpu/drm/tyr/fw.rs | 8 ++++++ drivers/gpu/drm/tyr/tyr.rs | 1 + drivers/gpu/drm/tyr/vm.rs | 5 ++++ 5 files changed, 95 insertions(+)
drivers/gpu/drm/tyr/debugfs.rs new file +65 -0
@@ -0,0 +1,65 @@ +// SPDX-License-Identifier: GPL-2.0 or MIT + +//! Debugfs support for the Tyr DRM driver. + +use kernel::{ + alloc::KVec , + drm, + new_mutex, + prelude::*, + seq_file, + sync::{ +Arc , +Mutex ,// + },// +}; + +use crate ::{ + driver::TyrDrmDriver , + vm::Vm ,// +}; + +/// Registry of VMs for debugfs access. +#[pin_data] +pub (crate )struct VmRegistry <'drm> { +#[pin] + vms:Mutex <KVec <Arc <Vm <'drm>>>>, +} + +impl <'drm>VmRegistry <'drm> { +pub (crate )fn new () ->impl PinInit <Self > { +pin_init! (Self { vms <-new_mutex! (KVec ::new ()) }) + } + +pub (crate )fn register (&self, vm:Arc <Vm <'drm>>) ->Result { +Ok (self.vms.lock ().push (vm,GFP_KERNEL )?) + } + +fn for_each (&self,mut f:impl FnMut (&Vm <'drm>) ->Result ) ->Result { +for vmin self.vms.lock ().iter () { +f (vm)?; + } +Ok (()) + } +} + +/// Debugfs data associated with a device. +/// +/// Each field corresponds to a debugfs file. +pub (crate )struct DebugfsData <'drm> { +pub (crate ) gpuvas:Pin <KBox <VmRegistry <'drm>>>, +} + +/// `DrmSeqShow` implementation for the `gpuvas` debugfs file. +pub (crate )struct GpuvasShow ; + +impl drm::debugfs::DrmSeqShow <TyrDrmDriver >for GpuvasShow { +fn show (guard: &drm::RegistrationGuard <'_,TyrDrmDriver >, m: &seq_file::SeqFile ) ->Result { + guard.registration_data_with (|reg_data| { + reg_data + .debugfs_data + .gpuvas + .for_each (|vm| vm.dump_gpuva_info (m)) + }) + } +}
drivers/gpu/drm/tyr/driver.rs +16 -0
@@ -7,6 +7,7 @@ Clk, OptionalClk, // }, + debugfs::ScopedDir, device::{Bound ,Core ,
@@ -45,6 +46,11 @@ };use crate ::{ + debugfs::{ +DebugfsData , +GpuvasShow , +VmRegistry ,// + }, file::TyrDrmFileData , fw::{ irq::{
@@ -86,6 +92,8 @@ pub(crate) struct TyrDrmRegistrationData<'drm> {/// Firmware sections. pub(crate) fw: Arc<Firmware<'drm>>, + pub(crate) debugfs_data: DebugfsData<'drm>, +#[pin] clks: Mutex<Clocks>,
@@ -167,11 +175,14 @@ fn probe<'bound>(let mmu =Mmu ::new (pdev.as_ref (), iomem.as_arc_borrow (), &gpu_info)?; +let vms =KBox ::pin_init (VmRegistry ::new (),GFP_KERNEL )?; +let firmware =Firmware ::new ( pdev.as_ref (), iomem.clone (), &unreg_dev, mmu.as_arc_borrow (), + &vms, &gpu_info, )?;
@@ -194,6 +205,7 @@ fn probe<'bound>( let reg_data = pin_init!(TyrDrmRegistrationData { pdev, fw: firmware, + debugfs_data: DebugfsData { gpuvas: vms }, clks <- new_mutex!(Clocks { core: core_clk, stacks: stacks_clk,
@@ -248,6 +260,10 @@ impl drm::Driver for TyrDrmDriver { kernel::declare_drm_ioctls! { (PANTHOR_DEV_QUERY , drm_panthor_dev_query, ioctl::RENDER_ALLOW ,TyrDrmFileData ::dev_query), } + +fn debugfs_init <'a>(dev: &'a drm::Device <Self , drm::Normal >, dir: &ScopedDir <'a, 'static>) { + dir.seq_file ::<GpuvasShow ,_ >(c"gpuvas" , dev); + } }struct Clocks {
drivers/gpu/drm/tyr/fw.rs +8 -0
@@ -47,6 +47,7 @@ };use crate ::{ + debugfs::VmRegistry , driver::{IoMem ,TyrDrmDevice ,//
@@ -251,6 +252,7 @@ pub(crate) fn new( iomem: Arc<IoMem<'drm>>, ddev: &TyrDrmDevice, mmu: ArcBorrow<'_, Mmu<'drm>>, + gpuvas: &VmRegistry<'drm>, gpu_info: &GpuInfo, ) -> Result<Arc<Firmware<'drm>>> {let vm =Vm ::new (dev, ddev, mmu, gpu_info)?;
@@ -300,6 +302,12 @@ pub(crate) fn new( )?) })(); +if result.is_ok () { +if let Err (e) = gpuvas.register (vm.clone ()) { +dev_warn! (dev,"failed to register VM: {e:?}\n" ); + } + } +if result.is_err () { vm.kill (); }
drivers/gpu/drm/tyr/tyr.rs +1 -0
@@ -7,6 +7,7 @@use crate ::driver::TyrPlatformDriver ; +mod debugfs;mod driver;mod file;mod fw;
drivers/gpu/drm/tyr/vm.rs +5 -0
@@ -401,6 +401,11 @@ pub(crate) fn activate(&self) -> Result { }) } +/// Dumps GPU VA space info into a seq_file. +pub (crate )fn dump_gpuva_info (&self, m: &kernel::seq_file::SeqFile ) ->Result { + self.gpuvm_unique.lock ().dump_gpuva_info (m) + } +/// Deactivate the VM by evicting it from its address space slot. fn deactivate (&self) ->Result { self.mmu.deactivate_vm (&self.as_data).inspect_err (|e| {
Signature · 1 line
2.43.0
PATCH v2 9/9 drm/debugfs: hold device reference for the lifetime of open files
In reply to Alvin SunHold a device reference (via drm_dev_get/put) across the lifetime of open debugfs files. Prevents use-after-free when a device is unregistered while a debugfs file remains open. Both drm_debugfs_open (legacy info_list) and drm_debugfs_entry_open (drm_debugfs_add_file) paths are covered.
--- drivers/gpu/drm/drm_debugfs.c | 42 ++++++++++++++++++++++++++++++++++++++---- 1 file changed, 38 insertions(+), 4 deletions(-)
drivers/gpu/drm/drm_debugfs.c +38 -4
@@ -159,11 +159,28 @@ static const struct drm_debugfs_info drm_debugfs_list[] = {static int drm_debugfs_open (struct inode *inode,struct file *file) {struct drm_info_node *node = inode->i_private; +struct drm_device *dev = node->minor->dev; +int ret;if (!device_is_registered (node->minor->kdev))return -ENODEV ; -return single_open (file, node->info_ent->show, node); +drm_dev_get (dev); + + ret =single_open (file, node->info_ent->show, node); +if (ret) +drm_dev_put (dev); + +return ret; +} + +static int drm_debugfs_release (struct inode *inode,struct file *file) +{ +struct drm_info_node *node = + ((struct seq_file *)file->private_data)->private; + +drm_dev_put (node->minor->dev); +return single_release (inode, file); }static int drm_debugfs_entry_open (struct inode *inode,struct file *file)
@@ -171,11 +188,28 @@ static int drm_debugfs_entry_open(struct inode *inode, struct file *file)struct drm_debugfs_entry *entry = inode->i_private;struct drm_debugfs_info *node = &entry->file;struct drm_minor *minor = entry->dev->primary ?: entry->dev->accel; +struct drm_device *dev = entry->dev; +int ret;if (!device_is_registered (minor->kdev))return -ENODEV ; -return single_open (file, node->show, entry); +drm_dev_get (dev); + + ret =single_open (file, node->show, entry); +if (ret) +drm_dev_put (dev); + +return ret; +} + +static int drm_debugfs_entry_release (struct inode *inode,struct file *file) +{ +struct drm_debugfs_entry *entry = + ((struct seq_file *)file->private_data)->private; + +drm_dev_put (entry->dev); +return single_release (inode, file); }static const struct file_operations drm_debugfs_entry_fops = {
@@ -183,7 +217,7 @@ static const struct file_operations drm_debugfs_entry_fops = { .open = drm_debugfs_entry_open, .read = seq_read, .llseek = seq_lseek, - .release = single_release, + .release = drm_debugfs_entry_release, };static const struct file_operations drm_debugfs_fops = {
@@ -191,7 +225,7 @@ static const struct file_operations drm_debugfs_fops = { .open = drm_debugfs_open, .read = seq_read, .llseek = seq_lseek, - .release = single_release, + .release = drm_debugfs_release, };/**
Signature · 1 line
2.43.0
Alice Ryhl
maintainerRe: [PATCH v2 8/9] drm/tyr: add gpuvas debugfs file
In reply to Alvin SunQuoted 53 lines · Alvin Sun
Add a gpuvas debugfs file listing all GPU VAs for the Tyr DRM driver. Collects VMs into a shared list during firmware init and renders them via
dump_gpuva_infoon read.Signed-off-by Alvin Sun <[email protected]>--- drivers/gpu/drm/tyr/debugfs.rs | 65 ++++++++++++++++++++++++++++++++++++++++++ drivers/gpu/drm/tyr/driver.rs | 16 +++++++++++ drivers/gpu/drm/tyr/fw.rs | 8 ++++++ drivers/gpu/drm/tyr/tyr.rs | 1 + drivers/gpu/drm/tyr/vm.rs | 5 ++++ 5 files changed, 95 insertions(+)drivers/gpu/drm/tyr/debugfs.rs new file +34
-0@@ -0,0 +1,65 @@ +// SPDX-License-Identifier: GPL-2.0 or MIT + +//! Debugfs support for the Tyr DRM driver. + +use kernel::{ + alloc::KVec , + drm, + new_mutex, + prelude::*, + seq_file, + sync::{ +Arc , +Mutex ,// + },// +}; + +use crate ::{ + driver::TyrDrmDriver , + vm::Vm ,// +}; + +/// Registry of VMs for debugfs access. +#[pin_data] +pub (crate )struct VmRegistry <'drm> { +#[pin] + vms:Mutex <KVec <Arc <Vm <'drm>>>>, +} + +impl <'drm>VmRegistry <'drm> { +pub (crate )fn new () ->impl PinInit <Self > { +pin_init! (Self { vms <-new_mutex! (KVec ::new ()) }) + } + +pub (crate )fn register (&self, vm:Arc <Vm <'drm>>) ->Result {
drivers/gpu/drm/tyr/debugfs.rs line 44
Quoted 10 lines
drivers/gpu/drm/tyr/debugfs.rs new file +10
-0+Ok (self.vms.lock ().push (vm,GFP_KERNEL )?) + } + +fn for_each (&self,mut f:impl FnMut (&Vm <'drm>) ->Result ) ->Result { +for vmin self.vms.lock ().iter () { +f (vm)?; + } +Ok (()) + } +}
This code maintains a separate list of all of the vms for access from debugfs, but I would have expected that this is not necessary. If we already store the vms inside the driver's private data, then can't we just access them from the normal storage location?
By having multiple copies of the same information, you risk that they get out of sync. In this case, you never remove vms from the list even if the vm stops being used, which seems wrong.
Alice
Re: [PATCH v2 7/9] rust: drm: gpuvm: add dump_gpuva_info to UniqueRefGpuVm
In reply to Alvin SunQuoted 13 lines · Alvin Sun
Add method wrapping
drm_debugfs_gpuva_infoto dump GPU VA space mappings into aseq_file. Needed by the Tyr gpuvas debugfs file.Signed-off-by Alvin Sun <[email protected]>--- rust/kernel/drm/gpuvm/mod.rs | 8 ++++++++ 1 file changed, 8 insertions(+)rust/kernel/drm/gpuvm/mod.rs +0
-0
rust/kernel/drm/gpuvm/mod.rs pub fn data_ref(&self) -> &T { · line 321
Quoted 10 lines
rust/kernel/drm/gpuvm/mod.rs +7
-0@@ -312,6 +312,14 @@ pub fn data_ref(&self) -> &T {unsafe { &*self.0 .data.get () } } +/// Dumps GPU VA space info into a seq_file. +/// +/// Wraps the C `drm_debugfs_gpuva_info` function. +pub fn dump_gpuva_info (&self, m: &crate ::seq_file::SeqFile ) ->Result { +// SAFETY: `m.as_raw()` and `self.as_raw()` are valid by the type invariants. +to_result (unsafe { bindings::drm_debugfs_gpuva_info (m.as_raw (), self.as_raw ()) }) + }
This can be marked inline. Otherwise:
Alice Ryhl
maintainerRe: [PATCH v2 2/9] rust: debugfs: add SeqShow trait and seq_file file operations
In reply to Alvin SunQuoted 35 lines · Alvin Sun
rust/kernel/debugfs/file_ops.rs +34
-0+/// Show callback for `SeqShow` types. +/// +/// # Safety +/// +/// The seq_file core guarantees that `seq` points to a live `seq_file` and that +/// `seq->private` is a valid pointer to a `T` with no outstanding mutable +/// references. +unsafe extern "C" fn seq_file_show <S :SeqShow <T >,T :Sync >( + seq: *mut bindings::seq_file , + _: *mut crate ::ffi::c_void , +) ->crate ::ffi::c_int { +// SAFETY: `seq->private` is a valid `T` pointer with no outstanding +// mutable references. +let data =unsafe { &*((*seq).private.cast ::<T >()) }; +// SAFETY: `seq` points to a live `seq_file`. +let m =unsafe {SeqFile ::from_raw (seq) }; +from_result (||S ::show (data, m).map (|()|0 )) +} + +/// Renders `data` into a seq_file. +/// +/// `data` is the value stashed as the debugfs file's `i_private` at creation +/// time. `show` is invoked on each read to produce the file's contents. +/// +/// `open` and `release` are optional lifecycle hooks called during file open +/// and release. They can be used to manage the lifetime of `data` (e.g., +/// reference counting). Default implementations are no-ops. +pub trait SeqShow <T > { +/// Writes debugfs output for the file. +fn show (data: &T , m: &SeqFile ) ->Result ; + +/// Called during file open, before `single_open`. +fn open (_data: &T ) ->Result { +Ok (())
rust/kernel/debugfs/file_ops.rs fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { · line 201
Quoted 10 lines
rust/kernel/debugfs/file_ops.rs +10
-0+ } + +/// Called during file release, before `single_release`. +/// +/// # Safety +/// +/// `data` must point to valid memory, kept alive by actions taken in +/// [`Self::open`] (e.g., incrementing a reference count). +unsafe fn release (_data:NonNull <T >) {} +}
Hmm. So in a later patch you implement SeqShow in the following manner:
fn open(dev: &drm::Device<T, drm::Normal>) -> Result {
// Hold a device reference so the device is not freed while the file is open.
dev.inc_ref();
Ok(())
}
unsafe fn release(dev: NonNull<drm::Device<T, drm::Normal>>) {
// Drop the reference taken in `open`.
// SAFETY: `dev` is valid per this function's safety contract.
unsafe { drm::Device::<T>::dec_ref(dev) };
}I don't understand why this increment/decrement pair is necessary. Just based on the code, it *looks* like you have them because otherwise show() might get called with a dangling pointer to the drm device, but the inc_ref() in open() ensures it stays alive.
Quoted 3 lines · earlier in this patch you
The
seq_filecore guarantees thatseqpoints to a liveseq_fileand thatseq->privateis a valid pointer to aTwith no outstanding mutable references.
So based on this, you are saying that open()/release() do not need to do anything special for the value to stay alive.
These seem contradictory. Could you clarify the situation?
Alice
Daniel Almeida
maintainerRe: [PATCH v2 8/9] drm/tyr: add gpuvas debugfs file
In reply to Alice RyhlQuoted 65 lines · Alice Ryhl
Quoted 60 lines · Alvin Sun
Add a gpuvas debugfs file listing all GPU VAs for the Tyr DRM driver. Collects VMs into a shared list during firmware init and renders them via
dump_gpuva_infoon read.Signed-off-by Alvin Sun <[email protected]>---
drivers/gpu/drm/tyr/debugfs.rs | 65 ++++++++++++++++++++++++++++++++++++++++++ drivers/gpu/drm/tyr/driver.rs | 16 +++++++++++ drivers/gpu/drm/tyr/fw.rs | 8 ++++++ drivers/gpu/drm/tyr/tyr.rs | 1 + drivers/gpu/drm/tyr/vm.rs | 5 ++++ 5 files changed, 95 insertions(+)drivers/gpu/drm/tyr/debugfs.rs new file +41
-0@@ -0,0 +1,65 @@ +// SPDX-License-Identifier: GPL-2.0 or MIT + +//! Debugfs support for the Tyr DRM driver. + +use kernel::{ + alloc::KVec , + drm, + new_mutex, + prelude::*, + seq_file, + sync::{ +Arc , +Mutex ,// + },// +}; + +use crate ::{ + driver::TyrDrmDriver , + vm::Vm ,// +}; + +/// Registry of VMs for debugfs access. +#[pin_data] +pub (crate )struct VmRegistry <'drm> { +#[pin] + vms:Mutex <KVec <Arc <Vm <'drm>>>>, +} + +impl <'drm>VmRegistry <'drm> { +pub (crate )fn new () ->impl PinInit <Self > { +pin_init! (Self { vms <-new_mutex! (KVec ::new ()) }) + } + +pub (crate )fn register (&self, vm:Arc <Vm <'drm>>) ->Result { +Ok (self.vms.lock ().push (vm,GFP_KERNEL )?) + } + +fn for_each (&self,mut f:impl FnMut (&Vm <'drm>) ->Result ) ->Result { +for vmin self.vms.lock ().iter () { +f (vm)?; + }
Quoted 8 lines
drivers/gpu/drm/tyr/debugfs.rs line 44
Quoted 3 lines
drivers/gpu/drm/tyr/debugfs.rs new file +3
-0+Ok (()) + } +}This code maintains a separate list of all of the vms for access from debugfs, but I would have expected that this is not necessary. If we already store the vms inside the driver's private data, then can't we just access them from the normal storage location?
Panthor also has a similar concept. I agree that we can reach the VMs from other places, but they’re scattered, and this type buys the convenience to do so, which we will need for other, non-debugfs-related features.
I wonder if we should move the registry to the top level in the private data, though:
i.e.: {
fw: ..
mmu: …
registry: VmRegistry
}
Quoted 6 lines
By having multiple copies of the same information, you risk that they get out of sync. In this case, you never remove vms from the list even if the vm stops being used, which seems wrong.
Alice
I think this can be solved by having vm::new() take a &VmRegistry argument, same for vm::destroy(). This forces callers to provide the list so it can be kept in sync.
This is just one approach though, perhaps someone has a better idea?
— Daniel
Re: [PATCH v2 2/9] rust: debugfs: add SeqShow trait and seq_file file operations
In reply to Alice RyhlQuoted 66 lines · Alice Ryhl
Quoted 34 lines · Alvin Sun
rust/kernel/debugfs/file_ops.rs +34
-0+/// Show callback for `SeqShow` types. +/// +/// # Safety +/// +/// The seq_file core guarantees that `seq` points to a live `seq_file` and that +/// `seq->private` is a valid pointer to a `T` with no outstanding mutable +/// references. +unsafe extern "C" fn seq_file_show <S :SeqShow <T >,T :Sync >( + seq: *mut bindings::seq_file , + _: *mut crate ::ffi::c_void , +) ->crate ::ffi::c_int { +// SAFETY: `seq->private` is a valid `T` pointer with no outstanding +// mutable references. +let data =unsafe { &*((*seq).private.cast ::<T >()) }; +// SAFETY: `seq` points to a live `seq_file`. +let m =unsafe {SeqFile ::from_raw (seq) }; +from_result (||S ::show (data, m).map (|()|0 )) +} + +/// Renders `data` into a seq_file. +/// +/// `data` is the value stashed as the debugfs file's `i_private` at creation +/// time. `show` is invoked on each read to produce the file's contents. +/// +/// `open` and `release` are optional lifecycle hooks called during file open +/// and release. They can be used to manage the lifetime of `data` (e.g., +/// reference counting). Default implementations are no-ops. +pub trait SeqShow <T > { +/// Writes debugfs output for the file. +fn show (data: &T , m: &SeqFile ) ->Result ; + +/// Called during file open, before `single_open`. +fn open (_data: &T ) ->Result { +Ok (())rust/kernel/debugfs/file_ops.rs fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { · line 201
Quoted 10 lines
rust/kernel/debugfs/file_ops.rs +10
-0+ } + +/// Called during file release, before `single_release`. +/// +/// # Safety +/// +/// `data` must point to valid memory, kept alive by actions taken in +/// [`Self::open`] (e.g., incrementing a reference count). +unsafe fn release (_data:NonNull <T >) {} +}Hmm. So in a later patch you implement SeqShow in the following manner:
fn open(dev: &drm::Device<T, drm::Normal>) -> Result { // Hold a device reference so the device is not freed while the file is open. dev.inc_ref(); Ok(()) } unsafe fn release(dev: NonNull<drm::Device<T, drm::Normal>>) { // Drop the reference taken in `open`. // SAFETY: `dev` is valid per this function's safety contract. unsafe { drm::Device::<T>::dec_ref(dev) }; }I don't understand why this increment/decrement pair is necessary. Just based on the code, it *looks* like you have them because otherwise
show()might get called with a dangling pointer to the drm device, but theinc_ref()inopen()ensures it stays alive.However, earlier in this patch you said:
Quoted 7 lines
Quoted 3 lines
The
seq_filecore guarantees thatseqpoints to a liveseq_fileand thatseq->privateis a valid pointer to aTwith no outstanding mutable references.So based on this, you are saying that open()/release() do not need to do anything special for the value to stay alive.
These seem contradictory. Could you clarify the situation?
You're right. The SeqShow trait documentation was inaccurate -- the framework does not manage the lifetime of data, so inc_ref/dec_ref in DrmSeqShow is necessary to prevent show() from accessing a freed device.
Will fix the doc in the next revision.
Best regards,
Alvin
Quoted 2 lines
Alice
Alice Ryhl
maintainerRe: [PATCH v2 2/9] rust: debugfs: add SeqShow trait and seq_file file operations
Quoted 75 lines · Alvin Sun
Quoted 72 lines · Alice Ryhl
Quoted 34 lines · Alvin Sun
rust/kernel/debugfs/file_ops.rs +34
-0+/// Show callback for `SeqShow` types. +/// +/// # Safety +/// +/// The seq_file core guarantees that `seq` points to a live `seq_file` and that +/// `seq->private` is a valid pointer to a `T` with no outstanding mutable +/// references. +unsafe extern "C" fn seq_file_show <S :SeqShow <T >,T :Sync >( + seq: *mut bindings::seq_file , + _: *mut crate ::ffi::c_void , +) ->crate ::ffi::c_int { +// SAFETY: `seq->private` is a valid `T` pointer with no outstanding +// mutable references. +let data =unsafe { &*((*seq).private.cast ::<T >()) }; +// SAFETY: `seq` points to a live `seq_file`. +let m =unsafe {SeqFile ::from_raw (seq) }; +from_result (||S ::show (data, m).map (|()|0 )) +} + +/// Renders `data` into a seq_file. +/// +/// `data` is the value stashed as the debugfs file's `i_private` at creation +/// time. `show` is invoked on each read to produce the file's contents. +/// +/// `open` and `release` are optional lifecycle hooks called during file open +/// and release. They can be used to manage the lifetime of `data` (e.g., +/// reference counting). Default implementations are no-ops. +pub trait SeqShow <T > { +/// Writes debugfs output for the file. +fn show (data: &T , m: &SeqFile ) ->Result ; + +/// Called during file open, before `single_open`. +fn open (_data: &T ) ->Result { +Ok (())rust/kernel/debugfs/file_ops.rs fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { · line 201
Quoted 10 lines
rust/kernel/debugfs/file_ops.rs +10
-0+ } + +/// Called during file release, before `single_release`. +/// +/// # Safety +/// +/// `data` must point to valid memory, kept alive by actions taken in +/// [`Self::open`] (e.g., incrementing a reference count). +unsafe fn release (_data:NonNull <T >) {} +}Hmm. So in a later patch you implement SeqShow in the following manner:
fn open(dev: &drm::Device<T, drm::Normal>) -> Result { // Hold a device reference so the device is not freed while the file is open. dev.inc_ref(); Ok(()) } unsafe fn release(dev: NonNull<drm::Device<T, drm::Normal>>) { // Drop the reference taken in `open`. // SAFETY: `dev` is valid per this function's safety contract. unsafe { drm::Device::<T>::dec_ref(dev) }; }I don't understand why this increment/decrement pair is necessary. Just based on the code, it *looks* like you have them because otherwise
show()might get called with a dangling pointer to the drm device, but theinc_ref()inopen()ensures it stays alive.Quoted 3 lines · earlier in this patch you
The
seq_filecore guarantees thatseqpoints to a liveseq_fileand thatseq->privateis a valid pointer to aTwith no outstanding mutable references.So based on this, you are saying that open()/release() do not need to do anything special for the value to stay alive.
Quoted 8 lines
Quoted 1 line
These seem contradictory. Could you clarify the situation?
You're right. The
SeqShowtrait documentation was inaccurate -- the framework does not manage the lifetime ofdata, soinc_ref/dec_refinDrmSeqShowis necessary to preventshow()from accessing a freed device.Will fix the doc in the next revision.
I'm not convinced that works soundness-wise. If I just leave open/release empty, then I will be able to access a &T inside of show(), but there's nothing keeping it alive, so I could dereference a freed &T in safe code that way.
I think we need the seq file to instead own some sort of value. Then, show() can be passed the a reference to value it has ownership of, and release() can be said type's destructor.
Alice
Danilo Krummrich
maintainerRe: [PATCH v2 2/9] rust: debugfs: add SeqShow trait and seq_file file operations
In reply to Alvin Sunrust/kernel/debugfs/traits.rs fn read_from_slice( · line 351
Quoted 8 lines · Alvin Sun
rust/kernel/debugfs/traits.rs +8
-0+/// Renders `data` into a seq_file. +/// +/// `data` is the value stashed as the debugfs file's `i_private` at creation +/// time. `show` is invoked on each read to produce the file's contents. +/// +/// `open` and `release` are optional lifecycle hooks called during file open +/// and release. They can be used to manage the lifetime of `data` (e.g., +/// reference counting). Default implementations are no-ops.
The open() and release() callbacks shouldn't be needed. The existing C (proxy file ops) and Rust code already ensures to wait for in-flight file operations, so show() can't run after debugfs_remove().
Both the existing Rust debugfs code and the DRM code use the full proxy fops.
Quoted 17 lines
rust/kernel/debugfs/traits.rs +17
-0+pub trait SeqShow <T > { +/// Writes debugfs output for the file. +fn show (data: &T , m: &SeqFile ) ->Result ; + +/// Called during file open, before `single_open`. +fn open (_data: &T ) ->Result { +Ok (()) + } + +/// Called during file release, before `single_release`. +/// +/// # Safety +/// +/// `data` must point to valid memory, kept alive by actions taken in +/// [`Self::open`] (e.g., incrementing a reference count). +unsafe fn release (_data:NonNull <T >) {} +}
Danilo Krummrich
maintainerRe: [PATCH v2 3/9] rust: debugfs: add Entry::from_raw and ScopedDir::from_dentry
In reply to Alvin SunQuoted 8 lines · Alvin Sun
rust/kernel/debugfs.rs +8
-0+/// Creates a [`ScopedDir`] wrapping an existing debugfs dentry. +/// +/// Files created under this directory are not automatically removed on drop; +/// their lifetime is tied to the dentry owner. +/// +/// # Safety +/// +/// The caller must ensure the dentry remains valid for the lifetime of the
rust/kernel/debugfs.rs fn new(name: &CStr) -> ScopedDir<'data, 'static> { · line 756
Quoted 10 lines
rust/kernel/debugfs.rs +10
-0+/// returned `ScopedDir`. +pub unsafe fn from_dentry (dentry: *mut bindings::dentry ) ->Self { +let _ = dentry; +ScopedDir { +#[cfg( CONFIG_DEBUG_FS )] +// SAFETY: The caller guarantees the dentry is valid and outlives this `ScopedDir`. + entry:ManuallyDrop ::new (unsafe {Entry ::from_raw (dentry) }), + _phantom:PhantomData , + } + }
I think what you actually want to express is that the DRM debugfs root dir represents a view into an existing scope, where the data is T::RegistrationData.
Additionally, we want to be able to derive new debugfs::Scopes from this that are shorter lived, so we can create new debugfs::Scopes e.g. in drm::DriverFile<'a>, which I currently work on.
So, what I'm thinking of is a type like:
pub struct ScopeRef<'a, T> {
#[cfg(CONFIG_DEBUG_FS)]
dentry: Option<NonNull<bindings::dentry>>,
data: &'a T,
}which has a corresponding unsafe constructor and provides methods to e.g. create a new directory, returning a new ScopeRef<'a, T>, which can be stored in lifetime scoped data.
Additionally, but that's somewhat orthogonal, we want debugfs::Scope to support lifetime data, so a scope can participate in the driver lifecycle; the corresponding synchronization is already in place with full proxy fops.
Danilo Krummrich
maintainerRe: [PATCH v2 5/9] rust: drm: add debugfs_init callback to Driver trait
In reply to Alvin Sunrust/kernel/drm/driver.rs pub trait Driver { · line 152
Quoted 10 lines · Alvin Sun
rust/kernel/drm/driver.rs +9
-0+/// Populates debugfs for this DRM device. +/// +/// Called by the DRM core during registration, once per minor (callback +/// runs after `dev->registered`). +fn debugfs_init <'a>(_dev: &'a drm::Device <Self , drm::Normal >, _dir: &ScopedDir <'a, 'static>) +where +Self :Sized , + { + } }
This could just be
fn debugfs_init(dir: &debugfs::ScopeRef<'_, Self::RegistrationData<'_>>)
as it is only needed to populate files / directories for exposing things in RegistrationData.
Subsequent debugfs::Scopes can be registered from drm::File<'_>::open() and IOCTLs (I also work on introducing HRT private data for IOCTLs; semantically equivalent to a Vec in DriverFile<'_> or RegistrationData<'_>, but managed by the subsystem).
Danilo Krummrich
maintainerRe: [PATCH v2 6/9] rust: drm: add DrmSeqShow seq_file adapter
In reply to Alvin SunQuoted 6 lines · Alvin Sun
Add DrmSeqShow trait and its SeqShow blanket impl for Device<T, Normal>, enabling Rust DRM drivers to expose device state via debugfs
seq_fileentries. Device registration data is kept alive for the duration of eachseq_fileread.Signed-off-by Alvin Sun <[email protected]>
This patch shouldn't be needed with the ScopeRef approach. The full proxy already guarantees show() can't run after debugfs_remove_recursive(). So, the driver can just implement plain debugfs::SeqShow<RegistrationData<'_>>.
Danilo Krummrich
maintainerRe: [PATCH v2 8/9] drm/tyr: add gpuvas debugfs file
In reply to Alvin Sundrivers/gpu/drm/tyr/debugfs.rs line 65
Quoted 10 lines · Alvin Sun
drivers/gpu/drm/tyr/debugfs.rs new file +10
-0+impl drm::debugfs::DrmSeqShow <TyrDrmDriver >for GpuvasShow { +fn show (guard: &drm::RegistrationGuard <'_,TyrDrmDriver >, m: &seq_file::SeqFile ) ->Result { + guard.registration_data_with (|reg_data| { + reg_data + .debugfs_data + .gpuvas + .for_each (|vm| vm.dump_gpuva_info (m)) + }) + } +}
Should simplify to:
impl SeqShow<TyrDrmRegistrationData<'_>> for GpuvasShow {
fn show(reg_data: &TyrDrmRegistrationData<'_>, m: &SeqFile) -> Result {
reg_data
.debugfs_data
.gpuvas
.for_each(|vm| vm.dump_gpuva_info(m))
}
}drivers/gpu/drm/tyr/driver.rs impl drm::Driver for TyrDrmDriver { · line 266
Quoted 3 lines
drivers/gpu/drm/tyr/driver.rs +3
-0+fn debugfs_init <'a>(dev: &'a drm::Device <Self , drm::Normal >, dir: &ScopedDir <'a, 'static>) { + dir.seq_file ::<GpuvasShow ,_ >(c"gpuvas" , dev); + }
Should become:
fn debugfs_init(dir: &debugfs::ScopeRef<'_, TyrDrmRegistrationData<'_>>) {
dir.seq_file::<GpuvasShow>(c"gpuvas");
}Danilo Krummrich
maintainerRe: [PATCH v2 9/9] drm/debugfs: hold device reference for the lifetime of open files
In reply to Alvin SunQuoted 35 lines · Alvin Sun
Hold a device reference (via drm_dev_get/put) across the lifetime of open debugfs files. Prevents use-after-free when a device is unregistered while a debugfs file remains open. Both
drm_debugfs_open(legacyinfo_list) anddrm_debugfs_entry_open(drm_debugfs_add_file) paths are covered.Fixes 1c9cacbea8805 ("drm/debugfs: create device-centered debugfs functions")Fixes 28a62277e06f9 ("drm: Convert proc files to seq_file and introduce debugfs")Signed-off-by Alvin Sun <[email protected]>--- drivers/gpu/drm/drm_debugfs.c | 42 ++++++++++++++++++++++++++++++++++++++---- 1 file changed, 38 insertions(+), 4 deletions(-)drivers/gpu/drm/drm_debugfs.c +9
-1@@ -159,11 +159,28 @@ static const struct drm_debugfs_info drm_debugfs_list[] = {static int drm_debugfs_open (struct inode *inode,struct file *file) {struct drm_info_node *node = inode->i_private; +struct drm_device *dev = node->minor->dev; +int ret;if (!device_is_registered (node->minor->kdev))return -ENODEV ; -return single_open (file, node->info_ent->show, node); +drm_dev_get (dev); + + ret =single_open (file, node->info_ent->show, node); +if (ret) +drm_dev_put (dev); + +return ret;
drivers/gpu/drm/drm_debugfs.c static const struct drm_debugfs_info drm_debugfs_list[] = { · line 184
Quoted 10 lines
drivers/gpu/drm/drm_debugfs.c +9
-0+} + +static int drm_debugfs_release (struct inode *inode,struct file *file) +{ +struct drm_info_node *node = + ((struct seq_file *)file->private_data)->private; + +drm_dev_put (node->minor->dev); +return single_release (inode, file); }
This isn't needed; in drm_dev_unregister() we call debugfs_remove_recursive(), which already waits for all in-flight file operations. The DRM device itself is guaranteed to be valid as long as it is registered.
Re: [PATCH v2 9/9] drm/debugfs: hold device reference for the lifetime of open files
Quoted 41 lines · Danilo Krummrich
Quoted 40 lines · Alvin Sun
Hold a device reference (via drm_dev_get/put) across the lifetime of open debugfs files. Prevents use-after-free when a device is unregistered while a debugfs file remains open. Both
drm_debugfs_open(legacyinfo_list) anddrm_debugfs_entry_open(drm_debugfs_add_file) paths are covered.Fixes 1c9cacbea8805 ("drm/debugfs: create device-centered debugfs functions")Fixes 28a62277e06f9 ("drm: Convert proc files to seq_file and introduce debugfs")Signed-off-by Alvin Sun <[email protected]>--- drivers/gpu/drm/drm_debugfs.c | 42 ++++++++++++++++++++++++++++++++++++++---- 1 file changed, 38 insertions(+), 4 deletions(-)drivers/gpu/drm/drm_debugfs.c +14
-1@@ -159,11 +159,28 @@ static const struct drm_debugfs_info drm_debugfs_list[] = {static int drm_debugfs_open (struct inode *inode,struct file *file) {struct drm_info_node *node = inode->i_private; +struct drm_device *dev = node->minor->dev; +int ret;if (!device_is_registered (node->minor->kdev))return -ENODEV ; -return single_open (file, node->info_ent->show, node); +drm_dev_get (dev); + + ret =single_open (file, node->info_ent->show, node); +if (ret) +drm_dev_put (dev); + +return ret; +} + +static int drm_debugfs_release (struct inode *inode,struct file *file) +{ + struct drm_info_node *node =
Quoted 8 lines
drivers/gpu/drm/drm_debugfs.c static const struct drm_debugfs_info drm_debugfs_list[] = { · line 184
Quoted 5 lines
drivers/gpu/drm/drm_debugfs.c +4
-0+ ((struct seq_file *)file->private_data)->private; + +drm_dev_put (node->minor->dev); +return single_release (inode, file); }This isn't needed; in
drm_dev_unregister()we calldebugfs_remove_recursive(), which already waits for all in-flight file operations. The DRM device itself is guaranteed to be valid as long as it is registered.
Thanks for the review. Sorry for the delay — I was on vacation the last few days.
v3 is ready, incorporating the feedback, and I'll send it out shortly.
Best regards,
Alvin