Skip to contentSkip to conversation

rust: DebugFS Bindings

PATCH In review Matthew Maurer 5 participants 38 messages Sep 4, 2025 – Sep 10, 2025

Subsystems (2)
lore
Share & tools
lore
#0 lore raw

v11 cover rust: DebugFS Bindings

This series provides safe DebugFS bindings for Rust, with sample modules using them.

---
Changes in v11:
- Rephrased comments/docs based on list feedback
- Switched longer polymorphic declarations to use where clauses
- Switched TI: PinInit to impl PinInit (this was previously required
for use<>
- Keep Scope private until the scoped interface is added
- Render -> Writer, UpdateFromSlice -> Reader
- Documented that Debug format is subject to change
- Link to v10: https://lore.kernel.org/r/[email protected]

Changes in v10:
- Introduced Scoped to show how either a File or Dir can be bound to
data
- Remove use of use<> for MSRV compatibility
- Added Write support
- Added more complex sample driver using scoped interface
- Updated original sample driver to use writes to drive mutation
- Added FileOps<T> (only for DebugFS, not a kernel-wide abstraction)
to decrease needed unsafe for keeping vtables paired to types.
- Centralized dentry lifecycle management to entry.rs.
- Link to v9: https://lore.kernel.org/r/[email protected]

Changes in v9:
- Switched to PinInit backing instead of ForeignOwnable
- Changed sample to be a platform driver
- Exported a static property
- Demonstrated runtime mutation in platform driver (inc_counter)
- Demonstrated how driver code would interact with data structures
exported through DebugFS (Wrapper)
- Link to v8: https://lore.kernel.org/r/[email protected]

Changes in v8:
- Switched from casts to core::from_{ref, mut} in type change
- Link to v7: https://lore.kernel.org/r/[email protected]

Changes in v7:
- Rewrote entry::Entry -> Entry
- Use c_int and c_void from kernel prelude rather than core
- Removed unnecessary display_open cast
- Switched from Deref + an explicit box to ForeignOwnable for
attaching owned data.
- Made &'static and &'static mut implement ForeignOwnable
- Swapped "driver" to "module" in sample code
- Link to v6: https://lore.kernel.org/r/[email protected]

Changes in v6:
- Replaced explicit lifetimes with children keeping their parents alive.
- Added support for attaching owned data.
- Removed recomendation to only keep root handles and handles you want
to delete around.
- Refactored some code into separate files to improve clarity.
- Link to v5: https://lore.kernel.org/r/[email protected]

Changes in v5:
- Made Dir + File wrappers around Entry
- All functions return owning handles. To discard without drop, use forget. To keep a handle without drop, use ManuallyDrop.
- Fixed bugs around not(CONFIG_DEBUG_FS)
- Removed unnecessary addr_of!
- Link to v4: https://lore.kernel.org/r/[email protected]

Changes in v4:
- Remove SubDir, replace with type-level constant.
- Add lifetime to Dir to prevent subdirectories and files from outliving their parents and triggering an Oops when accessed.
- Split unsafe blocks with two calls into two blocks
- Access private field through direct pointer dereference, avoiding creation of a reference to it.
- Notably not changed - owning/non-owning handle defaults. The best read
I had from the thread was to continue with this mode, but I'm willing
to change if need be.
- Comment changes
- More comment markdown
- Remove scopes from examples
- Put as_ptr properties into a # Guarantees section.
- Link to v3: https://lore.kernel.org/r/[email protected]

Changes in v3:
- Split Dir into Dir/SubDir/File to improve API.
- Add "." to end of all comments.
- Convert INVARIANT to # Invariants on types.
- Add backticks everywhere I found variables/types in my comments.
- Promoted invariant comment to doc comment.
- Extended sample commenting to make it clearer what is happening.
- Link to v2: https://lore.kernel.org/r/[email protected]

Changes in v2:
- Drop support for builder / pinned bindings in initial series
- Remove ARef usage to abstract the dentry nature of handles
- Remove error handling to discourage users from caring whether DebugFS
is enabled.
- Support CONFIG_DEBUG_FS=n while leaving the API available
- Fixed mistaken decimal/octal mixup
- Doc/comment cleanup
- Link to v1: https://lore.kernel.org/r/[email protected]

---
Matthew Maurer (7):
rust: debugfs: Add initial support for directories
rust: debugfs: Add support for read-only files
rust: debugfs: Add support for writable files
rust: debugfs: Add support for callback-based files
samples: rust: Add debugfs sample driver
rust: debugfs: Add support for scoped directories
samples: rust: Add scoped debugfs sample driver

 MAINTAINERS                              |   4 +
 rust/bindings/bindings_helper.h          |   1 +
 rust/kernel/debugfs.rs                   | 594 +++++++++++++++++++++++++++++++
 rust/kernel/debugfs/callback_adapters.rs | 122 +++++++
 rust/kernel/debugfs/entry.rs             | 164 +++++++++
 rust/kernel/debugfs/file_ops.rs          | 247 +++++++++++++
 rust/kernel/debugfs/traits.rs            | 102 ++++++
 rust/kernel/lib.rs                       |   1 +
 samples/rust/Kconfig                     |  22 ++
 samples/rust/Makefile                    |   2 +
 samples/rust/rust_debugfs.rs             | 151 ++++++++
 samples/rust/rust_scoped_debugfs.rs      | 134 +++++++
 12 files changed, 1544 insertions(+)

---
base-commit: f3c5631f70e434e318c44001e2417d4770f06cd0
change-id: 20250428-debugfs-rust-3cd5c97eb7d1

Best regards,

Signature · 1 line
Matthew Maurer <[email protected]>
#1 lore raw

PATCH v11 1/7 rust: debugfs: Add initial support for directories

Adds a debugfs::Dir type that can be used to create and remove DebugFS directories. The Dir handle automatically cleans up the directory on Drop.

---
 MAINTAINERS                     |  2 +
 rust/bindings/bindings_helper.h |  1 +
 rust/kernel/debugfs.rs          | 82 +++++++++++++++++++++++++++++++++++++++++
 rust/kernel/debugfs/entry.rs    | 61 ++++++++++++++++++++++++++++++
 rust/kernel/lib.rs              |  1 +
 5 files changed, 147 insertions(+)
MAINTAINERS +2 -0
index daf520a13bdf6a991c0160a96620f40308c29ee0..8f2dbf71ca3f8f97e4d7619375279ed11d1261b2 100644
@@ -7472,6 +7472,8 @@ F:	include/linux/kobj*
 F:	include/linux/property.h
 F:	include/linux/sysfs.h
 F:	lib/kobj*
+F:	rust/kernel/debugfs.rs
+F:	rust/kernel/debugfs/
 F:	rust/kernel/device.rs
 F:	rust/kernel/device/
 F:	rust/kernel/device_id.rs
rust/bindings/bindings_helper.h +1 -0
index 84d60635e8a9baef1f1a1b2752dc0fa044f8542f..e847820dc807fdda2d682d496a3c6361bb944c10 100644
@@ -46,6 +46,7 @@
 #include <linux/cpufreq.h>
 #include <linux/cpumask.h>
 #include <linux/cred.h>
+#include <linux/debugfs.h>
 #include <linux/device/faux.h>
 #include <linux/dma-mapping.h>
 #include <linux/errname.h>
rust/kernel/debugfs.rs new file +82 -0

82 lines not on this page · raw message

rust/kernel/debugfs/entry.rs new file +61 -0

61 lines not on this page · raw message

rust/kernel/lib.rs +1 -0
index ed53169e795c0badf548025a57f946fa18bc73e3..828620c8441566a638f31d03633fc1bf4c1bda85 100644
@@ -76,6 +76,7 @@
 pub mod cpufreq;
 pub mod cpumask;
 pub mod cred;
+pub mod debugfs;
 pub mod device;
 pub mod device_id;
 pub mod devres;
Signature · 1 line
2.51.0.355.g5224444f11-goog
#2 lore raw

PATCH v11 2/7 rust: debugfs: Add support for read-only files

In reply to Matthew Maurer

Extends the debugfs API to support creating read-only files. This is done via the Dir::read_only_file method, which takes a data object that implements the Writer trait.

The file's content is generated by the Writer implementation, and the file is automatically removed when the returned File handle is dropped.

---
 rust/kernel/debugfs.rs          | 148 +++++++++++++++++++++++++++++++++++++++-
 rust/kernel/debugfs/entry.rs    |  42 ++++++++++++
 rust/kernel/debugfs/file_ops.rs | 128 ++++++++++++++++++++++++++++++++++
 rust/kernel/debugfs/traits.rs   |  33 +++++++++
 4 files changed, 350 insertions(+), 1 deletion(-)
rust/kernel/debugfs.rs +147 -1
index 65be71600b8eda83c0d313f3d205d0713e8e9510..b28665f58cd6a17e188aef5e8c539f6c7433a3b0 100644
@@ -8,12 +8,18 @@
 // When DebugFS is disabled, many parameters are dead. Linting for this isn't helpful.
 #![cfg_attr(not(CONFIG_DEBUG_FS), allow(unused_variables))]
 
-#[cfg(CONFIG_DEBUG_FS)]
 use crate::prelude::*;
 use crate::str::CStr;
 #[cfg(CONFIG_DEBUG_FS)]
 use crate::sync::Arc;
+use core::marker::PhantomPinned;
+use core::ops::Deref;
+
+mod traits;
+pub use traits::Writer;
 
+mod file_ops;
+use file_ops::{FileOps, ReadFile};
 #[cfg(CONFIG_DEBUG_FS)]
 mod entry;
 #[cfg(CONFIG_DEBUG_FS)]
@@ -53,6 +59,34 @@ fn create(name: &CStr, parent: Option<&Dir>) -> Self {
         Self()
     }
 
+    /// Creates a DebugFS file which will own the data produced by the initializer provided in
+    /// `data`.
+    fn create_file<'a, T, E: 'a>(
+        &'a self,
+        name: &'a CStr,
+        data: impl PinInit<T, E> + 'a,
+        file_ops: &'static FileOps<T>,
+    ) -> impl PinInit<File<T>, E> + 'a
+    where
+        T: Sync + 'static,
+    {
+        let scope = Scope::<T>::new(data, move |data| {
+            #[cfg(CONFIG_DEBUG_FS)]
+            if let Some(parent) = &self.0 {
+                // SAFETY: Because data derives from a scope, and our entry will be dropped before
+                // the data is dropped, it is guaranteed to outlive the entry we return.
+                unsafe { Entry::dynamic_file(name, parent.clone(), data, file_ops) }
+            } else {
+                Entry::empty()
+            }
+        });
+        try_pin_init! {
+            File {
+                scope <- scope
+            } ? E
+        }
+    }
+
     /// Create a new directory in DebugFS at the root.
     ///
     /// # Examples
@@ -79,4 +113,116 @@ pub fn new(name: &CStr) -> Self {
     pub fn subdir(&self, name: &CStr) -> Self {
         Dir::create(name, Some(self))
     }
+
+    /// Creates a read-only file in this directory.
+    ///
+    /// The file's contents are produced by invoking [`Writer::write`] on the value initialized by
+    /// `data`.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use kernel::c_str;
+    /// # use kernel::debugfs::Dir;
+    /// # use kernel::prelude::*;
+    /// # let dir = Dir::new(c_str!("my_debugfs_dir"));
+    /// let file = KBox::pin_init(dir.read_only_file(c_str!("foo"), 200), GFP_KERNEL)?;
+    /// // "my_debugfs_dir/foo" now contains the number 200.
+    /// // The file is removed when `file` is dropped.
+    /// # Ok::<(), Error>(())
+    /// ```
+    pub fn read_only_file<'a, T, E: 'a>(
+        &'a self,
+        name: &'a CStr,
+        data: impl PinInit<T, E> + 'a,
+    ) -> impl PinInit<File<T>, E> + 'a
+    where
+        T: Writer + Send + Sync + 'static,
+    {
+        let file_ops = &<T as ReadFile<_>>::FILE_OPS;
+        self.create_file(name, data, file_ops)
+    }
+}
+
+#[pin_data]
+/// Handle to a DebugFS scope, which ensures that attached `data` will outlive the provided
+/// [`Entry`] without moving.
+/// Currently, this is used to back [`File`] so that its `read` and/or `write` implementations
+/// can assume that their backing data is still alive.
+struct Scope<T> {
+    // This order is load-bearing for drops - `_entry` must be dropped before `data`.
+    #[cfg(CONFIG_DEBUG_FS)]
+    _entry: Entry,
+    #[pin]
+    data: T,
+    // Even if `T` is `Unpin`, we still can't allow it to be moved.
+    #[pin]
+    _pin: PhantomPinned,
+}
+
+#[pin_data]
+/// Handle to a DebugFS file, owning its backing data.
+///
+/// When dropped, the DebugFS file will be removed and the attached data will be dropped.
+pub struct File<T> {
+    #[pin]
+    scope: Scope<T>,
+}
+
+#[cfg(not(CONFIG_DEBUG_FS))]
+impl<'b, T: 'b> Scope<T> {
+    fn new<E: 'b, F>(data: impl PinInit<T, E> + 'b, init: F) -> impl PinInit<Self, E> + 'b
+    where
+        F: for<'a> FnOnce(&'a T) -> Entry + 'b,
+    {
+        try_pin_init! {
+            Self {
+                data <- data,
+                _pin: PhantomPinned
+            } ? E
+        }
+        .pin_chain(|scope| {
+            init(&scope.data);
+            Ok(())
+        })
+    }
+}
+
+#[cfg(CONFIG_DEBUG_FS)]
+impl<'b, T: 'b> Scope<T> {
+    fn entry_mut(self: Pin<&mut Self>) -> &mut Entry {
+        // SAFETY: _entry is not structurally pinned.
+        unsafe { &mut Pin::into_inner_unchecked(self)._entry }
+    }
+
+    fn new<E: 'b, F>(data: impl PinInit<T, E> + 'b, init: F) -> impl PinInit<Self, E> + 'b
+    where
+        F: for<'a> FnOnce(&'a T) -> Entry + 'b,
+    {
+        try_pin_init! {
+            Self {
+                _entry: Entry::empty(),
+                data <- data,
+                _pin: PhantomPinned
+            } ? E
+        }
+        .pin_chain(|scope| {
+            *scope.entry_mut() = init(&scope.data);
+            Ok(())
+        })
+    }
+}
+
+impl<T> Deref for Scope<T> {
+    type Target = T;
+    fn deref(&self) -> &T {
+        &self.data
+    }
+}
+
+impl<T> Deref for File<T> {
+    type Target = T;
+    fn deref(&self) -> &T {
+        &self.scope
+    }
 }
rust/kernel/debugfs/entry.rs +42 -0

54 lines not on this page · raw message

rust/kernel/debugfs/file_ops.rs new file +128 -0

128 lines not on this page · raw message

rust/kernel/debugfs/traits.rs new file +33 -0
new file mode 100644
index 0000000000000000000000000000000000000000..0e6e461324de42a3d80b692264d50e78a48f561d
@@ -0,0 +1,33 @@
+// SPDX-License-Identifier: GPL-2.0
+// Copyright (C) 2025 Google LLC.
+
+//! Traits for rendering or updating values exported to DebugFS.
+
+use crate::sync::Mutex;
+use core::fmt::{self, Debug, Formatter};
+
+/// A trait for types that can be written into a string.
+///
+/// This works very similarly to `Debug`, and is automatically implemented if `Debug` is
+/// implemented for a type. It is also implemented for any writable type inside a `Mutex`.
+///
+/// The derived implementation of `Debug` [may
+/// change](https://doc.rust-lang.org/std/fmt/trait.Debug.html#stability)
+/// between Rust versions, so if stability is key for your use case, please implement `Writer`
+/// explicitly instead.
+pub trait Writer {
+    /// Formats the value using the given formatter.
+    fn write(&self, f: &mut Formatter<'_>) -> fmt::Result;
+}
+
+impl<T: Writer> Writer for Mutex<T> {
+    fn write(&self, f: &mut Formatter<'_>) -> fmt::Result {
+        self.lock().write(f)
+    }
+}
+
+impl<T: Debug> Writer for T {
+    fn write(&self, f: &mut Formatter<'_>) -> fmt::Result {
+        writeln!(f, "{self:?}")
+    }
+}
Signature · 1 line
2.51.0.355.g5224444f11-goog
#3 lore raw

Re: [PATCH v11 2/7] rust: debugfs: Add support for read-only files

Quoted 415 lines · Matthew Maurer

Extends the debugfs API to support creating read-only files. This is done via the Dir::read_only_file method, which takes a data object that implements the Writer trait.

The file's content is generated by the Writer implementation, and the file is automatically removed when the returned File handle is dropped.

---
 rust/kernel/debugfs.rs          | 148 +++++++++++++++++++++++++++++++++++++++-
 rust/kernel/debugfs/entry.rs    |  42 ++++++++++++
 rust/kernel/debugfs/file_ops.rs | 128 ++++++++++++++++++++++++++++++++++
 rust/kernel/debugfs/traits.rs   |  33 +++++++++
 4 files changed, 350 insertions(+), 1 deletion(-)
rust/kernel/debugfs.rs +147 -1
index 65be71600b8eda83c0d313f3d205d0713e8e9510..b28665f58cd6a17e188aef5e8c539f6c7433a3b0 100644
@@ -8,12 +8,18 @@
 // When DebugFS is disabled, many parameters are dead. Linting for this isn't helpful.
 #![cfg_attr(not(CONFIG_DEBUG_FS), allow(unused_variables))]
 
-#[cfg(CONFIG_DEBUG_FS)]
 use crate::prelude::*;
 use crate::str::CStr;
 #[cfg(CONFIG_DEBUG_FS)]
 use crate::sync::Arc;
+use core::marker::PhantomPinned;
+use core::ops::Deref;
+
+mod traits;
+pub use traits::Writer;
 
+mod file_ops;
+use file_ops::{FileOps, ReadFile};
 #[cfg(CONFIG_DEBUG_FS)]
 mod entry;
 #[cfg(CONFIG_DEBUG_FS)]
@@ -53,6 +59,34 @@ fn create(name: &CStr, parent: Option<&Dir>) -> Self {
         Self()
     }
 
+    /// Creates a DebugFS file which will own the data produced by the initializer provided in
+    /// `data`.
+    fn create_file<'a, T, E: 'a>(
+        &'a self,
+        name: &'a CStr,
+        data: impl PinInit<T, E> + 'a,
+        file_ops: &'static FileOps<T>,
+    ) -> impl PinInit<File<T>, E> + 'a
+    where
+        T: Sync + 'static,
+    {
+        let scope = Scope::<T>::new(data, move |data| {
+            #[cfg(CONFIG_DEBUG_FS)]
+            if let Some(parent) = &self.0 {
+                // SAFETY: Because data derives from a scope, and our entry will be dropped before
+                // the data is dropped, it is guaranteed to outlive the entry we return.
+                unsafe { Entry::dynamic_file(name, parent.clone(), data, file_ops) }
+            } else {
+                Entry::empty()
+            }
+        });
+        try_pin_init! {
+            File {
+                scope <- scope
+            } ? E
+        }
+    }
+
     /// Create a new directory in DebugFS at the root.
     ///
     /// # Examples
@@ -79,4 +113,116 @@ pub fn new(name: &CStr) -> Self {
     pub fn subdir(&self, name: &CStr) -> Self {
         Dir::create(name, Some(self))
     }
+
+    /// Creates a read-only file in this directory.
+    ///
+    /// The file's contents are produced by invoking [`Writer::write`] on the value initialized by
+    /// `data`.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use kernel::c_str;
+    /// # use kernel::debugfs::Dir;
+    /// # use kernel::prelude::*;
+    /// # let dir = Dir::new(c_str!("my_debugfs_dir"));
+    /// let file = KBox::pin_init(dir.read_only_file(c_str!("foo"), 200), GFP_KERNEL)?;
+    /// // "my_debugfs_dir/foo" now contains the number 200.
+    /// // The file is removed when `file` is dropped.
+    /// # Ok::<(), Error>(())
+    /// ```
+    pub fn read_only_file<'a, T, E: 'a>(
+        &'a self,
+        name: &'a CStr,
+        data: impl PinInit<T, E> + 'a,
+    ) -> impl PinInit<File<T>, E> + 'a
+    where
+        T: Writer + Send + Sync + 'static,
+    {
+        let file_ops = &<T as ReadFile<_>>::FILE_OPS;
+        self.create_file(name, data, file_ops)
+    }
+}
+
+#[pin_data]
+/// Handle to a DebugFS scope, which ensures that attached `data` will outlive the provided
+/// [`Entry`] without moving.
+/// Currently, this is used to back [`File`] so that its `read` and/or `write` implementations
+/// can assume that their backing data is still alive.
+struct Scope<T> {
+    // This order is load-bearing for drops - `_entry` must be dropped before `data`.
+    #[cfg(CONFIG_DEBUG_FS)]
+    _entry: Entry,
+    #[pin]
+    data: T,
+    // Even if `T` is `Unpin`, we still can't allow it to be moved.
+    #[pin]
+    _pin: PhantomPinned,
+}
+
+#[pin_data]
+/// Handle to a DebugFS file, owning its backing data.
+///
+/// When dropped, the DebugFS file will be removed and the attached data will be dropped.
+pub struct File<T> {
+    #[pin]
+    scope: Scope<T>,
+}
+
+#[cfg(not(CONFIG_DEBUG_FS))]
+impl<'b, T: 'b> Scope<T> {
+    fn new<E: 'b, F>(data: impl PinInit<T, E> + 'b, init: F) -> impl PinInit<Self, E> + 'b
+    where
+        F: for<'a> FnOnce(&'a T) -> Entry + 'b,
+    {
+        try_pin_init! {
+            Self {
+                data <- data,
+                _pin: PhantomPinned
+            } ? E
+        }
+        .pin_chain(|scope| {
+            init(&scope.data);
+            Ok(())
+        })
+    }
+}
+
+#[cfg(CONFIG_DEBUG_FS)]
+impl<'b, T: 'b> Scope<T> {
+    fn entry_mut(self: Pin<&mut Self>) -> &mut Entry {
+        // SAFETY: _entry is not structurally pinned.
+        unsafe { &mut Pin::into_inner_unchecked(self)._entry }
+    }
+
+    fn new<E: 'b, F>(data: impl PinInit<T, E> + 'b, init: F) -> impl PinInit<Self, E> + 'b
+    where
+        F: for<'a> FnOnce(&'a T) -> Entry + 'b,
+    {
+        try_pin_init! {
+            Self {
+                _entry: Entry::empty(),
+                data <- data,
+                _pin: PhantomPinned
+            } ? E
+        }
+        .pin_chain(|scope| {
+            *scope.entry_mut() = init(&scope.data);
+            Ok(())
+        })
+    }
+}
+
+impl<T> Deref for Scope<T> {
+    type Target = T;
+    fn deref(&self) -> &T {
+        &self.data
+    }
+}
+
+impl<T> Deref for File<T> {
+    type Target = T;
+    fn deref(&self) -> &T {
+        &self.scope
+    }
 }
rust/kernel/debugfs/entry.rs +42 -0
index d2fba0e65e20e954e2a33e776b872bac4adb12e8..227fa50b7a79aeab49779e54b8c4241f455777c3 100644
@@ -1,6 +1,8 @@
 // SPDX-License-Identifier: GPL-2.0
 // Copyright (C) 2025 Google LLC.
 
+use crate::debugfs::file_ops::FileOps;
+use crate::ffi::c_void;
 use crate::str::CStr;
 use crate::sync::Arc;
 
@@ -40,6 +42,46 @@ pub(crate) fn dynamic_dir(name: &CStr, parent: Option<Arc<Self>>) -> Self {
         }
     }
 
+    /// # Safety
+    ///
+    /// * `data` must outlive the returned `Entry`.
+    pub(crate) unsafe fn dynamic_file<T>(
+        name: &CStr,
+        parent: Arc<Self>,
+        data: &T,
+        file_ops: &'static FileOps<T>,
+    ) -> Self {
+        // SAFETY: The invariants of this function's arguments ensure the safety of this call.
+        // * `name` is a valid C string by the invariants of `&CStr`.
+        // * `parent.as_ptr()` is a pointer to a valid `dentry` by invariant.
+        // * The caller guarantees that `data` will outlive the returned `Entry`.
+        // * The guarantees on `FileOps` assert the vtable will be compatible with the data we have
+        //   provided.
+        let entry = unsafe {
+            bindings::debugfs_create_file_full(
+                name.as_char_ptr(),
+                file_ops.mode(),
+                parent.as_ptr(),
+                core::ptr::from_ref(data) as *mut c_void,
+                core::ptr::null(),
+                &**file_ops,
+            )
+        };
+
+        Entry {
+            entry,
+            _parent: Some(parent),
+        }
+    }
+
+    /// Constructs a placeholder DebugFS [`Entry`].
+    pub(crate) fn empty() -> Self {
+        Self {
+            entry: core::ptr::null_mut(),
+            _parent: None,
+        }
+    }
+
     /// Returns the pointer representation of the DebugFS directory.
     ///
     /// # Guarantees
rust/kernel/debugfs/file_ops.rs new file +128 -0
new file mode 100644
index 0000000000000000000000000000000000000000..c2fbef96580eaa2fab7cc8c1ba559c3284d12e1b
@@ -0,0 +1,128 @@
+// SPDX-License-Identifier: GPL-2.0
+// Copyright (C) 2025 Google LLC.
+
+use super::Writer;
+use crate::prelude::*;
+use crate::seq_file::SeqFile;
+use crate::seq_print;
+use core::fmt::{Display, Formatter, Result};
+use core::marker::PhantomData;
+
+#[cfg(CONFIG_DEBUG_FS)]
+use core::ops::Deref;
+
+/// # Invariant
+///
+/// `FileOps<T>` will always contain an `operations` which is safe to use for a file backed
+/// off an inode which has a pointer to a `T` in its private data that is safe to convert
+/// into a reference.
+pub(super) struct FileOps<T> {
+    #[cfg(CONFIG_DEBUG_FS)]
+    operations: bindings::file_operations,
+    #[cfg(CONFIG_DEBUG_FS)]
+    mode: u16,
+    _phantom: PhantomData<T>,
+}
+
+impl<T> FileOps<T> {
+    /// # Safety
+    ///
+    /// The caller asserts that the provided `operations` is safe to use for a file whose
+    /// inode has a pointer to `T` in its private data that is safe to convert into a reference.
+    const unsafe fn new(operations: bindings::file_operations, mode: u16) -> Self {
+        Self {
+            #[cfg(CONFIG_DEBUG_FS)]
+            operations,
+            #[cfg(CONFIG_DEBUG_FS)]
+            mode,
+            _phantom: PhantomData,
+        }
+    }
+
+    #[cfg(CONFIG_DEBUG_FS)]
+    pub(crate) const fn mode(&self) -> u16 {
+        self.mode
+    }
+}
+
+#[cfg(CONFIG_DEBUG_FS)]
+impl<T> Deref for FileOps<T> {
+    type Target = bindings::file_operations;
+
+    fn deref(&self) -> &Self::Target {
+        &self.operations
+    }
+}
+
+struct WriterAdapter<T>(T);
+
+impl<'a, T: Writer> Display for WriterAdapter<&'a T> {
+    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
+        self.0.write(f)
+    }
+}
+
+/// Implements `open` for `file_operations` via `single_open` to fill out a `seq_file`.
+///
+/// # Safety
+///
+/// * `inode`'s private pointer must point to a value of type `T` which will outlive the `inode`
+///   and will not have any unique references alias it during the call.
+/// * `file` must point to a live, not-yet-initialized file object.
+unsafe extern "C" fn writer_open<T: Writer + Sync>(
+    inode: *mut bindings::inode,
+    file: *mut bindings::file,
+) -> c_int {
+    // SAFETY: The caller ensures that `inode` is a valid pointer.
+    let data = unsafe { (*inode).i_private };
+    // SAFETY:
+    // * `file` is acceptable by caller precondition.
+    // * `print_act` will be called on a `seq_file` with private data set to the third argument,
+    //   so we meet its safety requirements.
+    // * The `data` pointer passed in the third argument is a valid `T` pointer that outlives
+    //   this call by caller preconditions.
+    unsafe { bindings::single_open(file, Some(writer_act::<T>), data) }
+}
+
+/// Prints private data stashed in a seq_file to that seq file.
+///
+/// # Safety
+///
+/// `seq` must point to a live `seq_file` whose private data is a valid pointer to a `T` which may
+/// not have any unique references alias it during the call.
+unsafe extern "C" fn writer_act<T: Writer + Sync>(
+    seq: *mut bindings::seq_file,
+    _: *mut c_void,
+) -> c_int {
+    // SAFETY: By caller precondition, this pointer is valid pointer to a `T`, and
+    // there are not and will not be any unique references until we are done.
+    let data = unsafe { &*((*seq).private.cast::<T>()) };
+    // SAFETY: By caller precondition, `seq_file` points to a live `seq_file`, so we can lift
+    // it.
+    let seq_file = unsafe { SeqFile::from_raw(seq) };
+    seq_print!(seq_file, "{}", WriterAdapter(data));
+    0
+}
+
+// Work around lack of generic const items.
+pub(crate) trait ReadFile<T> {
+    const FILE_OPS: FileOps<T>;
+}
+
+impl<T: Writer + Sync> ReadFile<T> for T {
+    const FILE_OPS: FileOps<T> = {
+        let operations = bindings::file_operations {
+            read: Some(bindings::seq_read),
+            llseek: Some(bindings::seq_lseek),
+            release: Some(bindings::single_release),
+            open: Some(writer_open::<Self>),
+            // SAFETY: `file_operations` supports zeroes in all fields.
+            ..unsafe { core::mem::zeroed() }
+        };
+        // SAFETY: `operations` is all stock `seq_file` implementations except for `writer_open`.
+        // `open`'s only requirement beyond what is provided to all open functions is that the
+        // inode's data pointer must point to a `T` that will outlive it, which matches the
+        // `FileOps` requirements.
+        unsafe { FileOps::new(operations, 0o400) }
+    };
+}
rust/kernel/debugfs/traits.rs new file +23 -0
new file mode 100644
index 0000000000000000000000000000000000000000..0e6e461324de42a3d80b692264d50e78a48f561d
@@ -0,0 +1,33 @@
+// SPDX-License-Identifier: GPL-2.0
+// Copyright (C) 2025 Google LLC.
+
+//! Traits for rendering or updating values exported to DebugFS.
+
+use crate::sync::Mutex;
+use core::fmt::{self, Debug, Formatter};
+
+/// A trait for types that can be written into a string.
+///
+/// This works very similarly to `Debug`, and is automatically implemented if `Debug` is
+/// implemented for a type. It is also implemented for any writable type inside a `Mutex`.
+///
+/// The derived implementation of `Debug` [may
+/// change](https://doc.rust-lang.org/std/fmt/trait.Debug.html#stability)
+/// between Rust versions, so if stability is key for your use case, please implement `Writer`
+/// explicitly instead.
+pub trait Writer {
+    /// Formats the value using the given formatter.
+    fn write(&self, f: &mut Formatter<'_>) -> fmt::Result;
+}
+
+impl<T: Writer> Writer for Mutex<T> {

rust/kernel/debugfs/traits.rs line 33

Quoted 10 lines
rust/kernel/debugfs/traits.rs new file +10 -0
+    fn write(&self, f: &mut Formatter<'_>) -> fmt::Result {
+        self.lock().write(f)
+    }
+}
+
+impl<T: Debug> Writer for T {
+    fn write(&self, f: &mut Formatter<'_>) -> fmt::Result {
+        writeln!(f, "{self:?}")
+    }
+}

I tried using this in a "tiny" test module I had written, and I get the following build error:

--> samples/rust/rust_debugfs2.rs:64:53

    |
64  |         _file = root.read_only_file(c_str!("name"), &hw_soc_info.name);
    |                      --------------                 ^^^^^^^^^^^^^^^^^ expected `&u32`, found `&&CStr`
    |                      |
    |                      arguments to this method are incorrect
    |

= note: expected reference &u32
found reference &&'static kernel::prelude::CStr

I'm trying to "just" print a CStr, which is defined as:

struct HwSocInfo {
    id: u32,
    ver: u32,
    raw_id: u32,
    foundry: u32,
    name: &'static CStr,
}

Is this just a "user is holding it wrong" error on my side, or can this api not handle CStr values?

thanks,

greg k-h

maintainer
#4 lore raw

Re: [PATCH v11 2/7] rust: debugfs: Add support for read-only files

Quoted 23 lines · Greg Kroah-Hartman

I tried using this in a "tiny" test module I had written, and I get the following build error:

   --> samples/rust/rust_debugfs2.rs:64:53
    |
64  |         _file = root.read_only_file(c_str!("name"), &hw_soc_info.name);
    |                      --------------                 ^^^^^^^^^^^^^^^^^ expected `&u32`, found `&&CStr`
    |                      |
    |                      arguments to this method are incorrect
    |

= note: expected reference &u32
found reference &&'static kernel::prelude::CStr

I'm trying to "just" print a CStr, which is defined as:

struct HwSocInfo {
    id: u32,
    ver: u32,
    raw_id: u32,
    foundry: u32,
    name: &'static CStr,
}
Quoted 2 lines

Is this just a "user is holding it wrong" error on my side, or can this api not handle CStr values?

What you're doing should fundamentally work.

The above error suggests that your declaration of _file is File<&u32> rather than File<&'static CStr>.

Also note the double reference you create with &hw_soc_info.name, this should just be hw_soc_info.name.

You can also test this case by applying the following diff the the sample in v5:

samples/rust/rust_debugfs.rs +3 -0
index b26eea3ee723..475502f30b1a 100644
@@ -59,6 +59,8 @@ struct RustDebugFs {
     #[pin]
     _compatible: File<CString>,
     #[pin]
+    _test: File<&'static CStr>,
+    #[pin]
     counter: File<AtomicUsize>,
     #[pin]
     inner: File<Mutex<Inner>>,
@@ -140,6 +142,7 @@ fn new(pdev: &platform::Device<Core>) -> impl PinInit<Self, Error> + '_ {
                         .property_read::<CString>(c_str!("compatible"))
                         .required_by(dev)?,
                 ),
+                _test <- debugfs.read_only_file(c_str!("test"), c_str!("some_value")),
                 counter <- Self::build_counter(&debugfs),
                 inner <- Self::build_inner(&debugfs),
                 _debugfs: debugfs,
maintainer
#5 lore raw

Re: [PATCH v11 2/7] rust: debugfs: Add support for read-only files

Quoted 29 lines · Danilo Krummrich
Quoted 23 lines · Greg Kroah-Hartman

I tried using this in a "tiny" test module I had written, and I get the following build error:

   --> samples/rust/rust_debugfs2.rs:64:53
    |
64  |         _file = root.read_only_file(c_str!("name"), &hw_soc_info.name);
    |                      --------------                 ^^^^^^^^^^^^^^^^^ expected `&u32`, found `&&CStr`
    |                      |
    |                      arguments to this method are incorrect
    |

= note: expected reference &u32
found reference &&'static kernel::prelude::CStr

I'm trying to "just" print a CStr, which is defined as:

struct HwSocInfo {
    id: u32,
    ver: u32,
    raw_id: u32,
    foundry: u32,
    name: &'static CStr,
}
Quoted 2 lines

Is this just a "user is holding it wrong" error on my side, or can this api not handle CStr values?

What you're doing should fundamentally work.

Quoted 7 lines

The above error suggests that your declaration of _file is File<&u32> rather than File<&'static CStr>.

Also note the double reference you create with &hw_soc_info.name, this should just be hw_soc_info.name.

You can also test this case by applying the following diff the the sample in v5:

*sample in patch 5

Quoted 22 lines
samples/rust/rust_debugfs.rs +3 -0
index b26eea3ee723..475502f30b1a 100644
@@ -59,6 +59,8 @@ struct RustDebugFs {
     #[pin]
     _compatible: File<CString>,
     #[pin]
+    _test: File<&'static CStr>,
+    #[pin]
     counter: File<AtomicUsize>,
     #[pin]
     inner: File<Mutex<Inner>>,
@@ -140,6 +142,7 @@ fn new(pdev: &platform::Device<Core>) -> impl PinInit<Self, Error> + '_ {
                         .property_read::<CString>(c_str!("compatible"))
                         .required_by(dev)?,
                 ),
+                _test <- debugfs.read_only_file(c_str!("test"), c_str!("some_value")),
                 counter <- Self::build_counter(&debugfs),
                 inner <- Self::build_inner(&debugfs),
                 _debugfs: debugfs,
#6 lore raw

Re: [PATCH v11 2/7] rust: debugfs: Add support for read-only files

In reply to Danilo Krummrich
Quoted 24 lines · Danilo Krummrich
Quoted 23 lines · Greg Kroah-Hartman

I tried using this in a "tiny" test module I had written, and I get the following build error:

   --> samples/rust/rust_debugfs2.rs:64:53
    |
64  |         _file = root.read_only_file(c_str!("name"), &hw_soc_info.name);
    |                      --------------                 ^^^^^^^^^^^^^^^^^ expected `&u32`, found `&&CStr`
    |                      |
    |                      arguments to this method are incorrect
    |

= note: expected reference &u32
found reference &&'static kernel::prelude::CStr

I'm trying to "just" print a CStr, which is defined as:

struct HwSocInfo {
    id: u32,
    ver: u32,
    raw_id: u32,
    foundry: u32,
    name: &'static CStr,
}
Quoted 7 lines
Quoted 2 lines

Is this just a "user is holding it wrong" error on my side, or can this api not handle CStr values?

What you're doing should fundamentally work.

The above error suggests that your declaration of _file is File<&u32> rather than File<&'static CStr>.

Ah, ick, I missed that the return type would be different here. Yes, I was doing a bunch of file creation calls:

        let mut _file = root.read_only_file(c_str!("id"), &hw_soc_info.id);
        _file = root.read_only_file(c_str!("ver"), &hw_soc_info.ver);
        _file = root.read_only_file(c_str!("raw_id"), &hw_soc_info.raw_id);
        _file = root.read_only_file(c_str!("name"), &hw_soc_info.name);

As I don't care about the return value here at all.

But really, I should just write this as:

        root.read_only_file(c_str!("id"), &hw_soc_info.id);
        root.read_only_file(c_str!("ver"), &hw_soc_info.ver);
        root.read_only_file(c_str!("raw_id"), &hw_soc_info.raw_id);
        root.read_only_file(c_str!("name"), hw_soc_info.name);

with, as you point out:

Quoted 2 lines

Also note the double reference you create with &hw_soc_info.name, this should just be hw_soc_info.name.

Yes, sorry, my fault there.

Quoted 16 lines

You can also test this case by applying the following diff the the sample in v5:

samples/rust/rust_debugfs.rs +2 -0
index b26eea3ee723..475502f30b1a 100644
@@ -59,6 +59,8 @@ struct RustDebugFs {
     #[pin]
     _compatible: File<CString>,
     #[pin]
+    _test: File<&'static CStr>,
+    #[pin]
     counter: File<AtomicUsize>,
     #[pin]
     inner: File<Mutex<Inner>>,

samples/rust/rust_debugfs.rs fn new(pdev: &platform::Device<Core>) -> impl PinInit<Self, Error> + '_ { · line 145

Quoted 4 lines
samples/rust/rust_debugfs.rs +1 -0
@@ -140,6 +142,7 @@ fn new(pdev: &platform::Device<Core>) -> impl PinInit<Self, Error> + '_ {
                         .property_read::<CString>(c_str!("compatible"))
                         .required_by(dev)?,
                 ),
+                _test <- debugfs.read_only_file(c_str!("test"), c_str!("some_value")),

Cool, but again, we do not want to ever be storing individual debugfs files. Well, we can, but for 90% of the cases, we do not, we only want to remove the whole directory when that goes out of scope, which will clean up the files then.

thanks,

greg k-h

maintainer
#7 lore raw

Re: [PATCH v11 2/7] rust: debugfs: Add support for read-only files

Quoted 16 lines · Greg Kroah-Hartman
Quoted 15 lines · Danilo Krummrich
samples/rust/rust_debugfs.rs +2 -0
index b26eea3ee723..475502f30b1a 100644
@@ -59,6 +59,8 @@ struct RustDebugFs {
     #[pin]
     _compatible: File<CString>,
     #[pin]
+    _test: File<&'static CStr>,
+    #[pin]
     counter: File<AtomicUsize>,
     #[pin]
     inner: File<Mutex<Inner>>,
@@ -140,6 +142,7 @@ fn new(pdev: &platform::Device<Core>) -> impl PinInit<Self, Error> + '_ {
                         .property_read::<CString>(c_str!("compatible"))
Quoted 8 lines

samples/rust/rust_debugfs.rs fn new(pdev: &platform::Device<Core>) -> impl PinInit<Self, Error> + '_ { · line 145

Quoted 3 lines
samples/rust/rust_debugfs.rs +1 -0
                         .required_by(dev)?,
                 ),
+                _test <- debugfs.read_only_file(c_str!("test"), c_str!("some_value")),

Cool, but again, we do not want to ever be storing individual debugfs files. Well, we can, but for 90% of the cases, we do not, we only want to remove the whole directory when that goes out of scope, which will clean up the files then.

This API does not work in the way that you have a struct storing the data you want to expose *and* another one for the files with the data attached.

The File type contains the actual data. For instance, if you have a struct Foo, where you want to expose the members through debugfs you would *not* do:

	struct Foo {
	   a: u32,
	   b: u32,
	}

	struct FooFiles {
	   a: File<&u32>,
	   b: File<&u32>
	}

and then create an instance of Foo *and* another instance of FooFiles to export them via debugfs.

Instead you would change your struct Foo to just be:

	struct Foo {
	   a: File<u32>,
	   b: File<u32>,
	}

If you now create an instance of Foo (let's call it foo), then foo.a or foo.b dereferences to the inner type, i.e. the u32. Or in other words foo still behaves as if a and b would be u32 values. For instance:

   if foo.a == 42 {
      pr_info!("Foo::b = {}\n", foo.b);
   }

The fact that the backing files of a and b are removed from debugfs when Foo is dropped is necessary since otherwise we create a UAF.

Think of File<T> as a containers like you think of KBox<T>.

KBox<T> behaves exactly like T, but silently manages the backing kmalloc() allocation that T lives in.

With File<T> it's exactly the same, it behaves exactly like the T that lives within File<T>, but silently manages the debugfs file the T is exposed by.

#8 lore raw

Re: [PATCH v11 2/7] rust: debugfs: Add support for read-only files

Quoted 42 lines · Danilo Krummrich
Quoted 16 lines · Greg Kroah-Hartman
Quoted 15 lines · Danilo Krummrich
samples/rust/rust_debugfs.rs +2 -0
index b26eea3ee723..475502f30b1a 100644
@@ -59,6 +59,8 @@ struct RustDebugFs {
     #[pin]
     _compatible: File<CString>,
     #[pin]
+    _test: File<&'static CStr>,
+    #[pin]
     counter: File<AtomicUsize>,
     #[pin]
     inner: File<Mutex<Inner>>,
@@ -140,6 +142,7 @@ fn new(pdev: &platform::Device<Core>) -> impl PinInit<Self, Error> + '_ {
                         .property_read::<CString>(c_str!("compatible"))
Quoted 8 lines

samples/rust/rust_debugfs.rs fn new(pdev: &platform::Device<Core>) -> impl PinInit<Self, Error> + '_ { · line 145

Quoted 3 lines
samples/rust/rust_debugfs.rs +1 -0
                         .required_by(dev)?,
                 ),
+                _test <- debugfs.read_only_file(c_str!("test"), c_str!("some_value")),

Cool, but again, we do not want to ever be storing individual debugfs files. Well, we can, but for 90% of the cases, we do not, we only want to remove the whole directory when that goes out of scope, which will clean up the files then.

This API does not work in the way that you have a struct storing the data you want to expose *and* another one for the files with the data attached.

The File type contains the actual data. For instance, if you have a struct Foo, where you want to expose the members through debugfs you would *not* do:

	struct Foo {
	   a: u32,
	   b: u32,
	}

	struct FooFiles {
	   a: File<&u32>,
	   b: File<&u32>
	}
Quoted 2 lines

and then create an instance of Foo *and* another instance of FooFiles to export them via debugfs.

Ah, that's exactly what I was trying to do.

Quoted 7 lines

Instead you would change your struct Foo to just be:

	struct Foo {
	   a: File<u32>,
	   b: File<u32>,
	}
Quoted 7 lines

If you now create an instance of Foo (let's call it foo), then foo.a or foo.b dereferences to the inner type, i.e. the u32. Or in other words foo still behaves as if a and b would be u32 values. For instance:

   if foo.a == 42 {
      pr_info!("Foo::b = {}\n", foo.b);
   }

Oh that's not going to work well at all :(

Think about something "simple" like a pci config descriptor. You have a structure, with fields, already sitting there. You want to expose those fields in debugfs. So you want to only create debugfs files in one location in a driver, you don't want ALL users of those fields to have to go through a File<T> api, right? That would be crazy, all drivers would end up always having File<T> everywhere.

Quoted 2 lines

The fact that the backing files of a and b are removed from debugfs when Foo is dropped is necessary since otherwise we create a UAF.

That's fine, but:

Quoted 1 line

Think of File<T> as a containers like you think of KBox<T>.

Ok, but again, you are now forcing all users to think of debugfs as the main "interface" to those variables, which is not true (nor should it be.)

Quoted 5 lines

KBox<T> behaves exactly like T, but silently manages the backing kmalloc() allocation that T lives in.

With File<T> it's exactly the same, it behaves exactly like the T that lives within File<T>, but silently manages the debugfs file the T is exposed by.

And what happens if debugfs is not enabled? What about if creating the file fails? The variable still needs to be present and active and working.

thanks,

greg k-h

reviewer
#9 lore raw

Re: [PATCH v11 2/7] rust: debugfs: Add support for read-only files

Quoted 76 lines · Greg Kroah-Hartman
Quoted 42 lines · Danilo Krummrich
Quoted 16 lines · Greg Kroah-Hartman
Quoted 15 lines · Danilo Krummrich
samples/rust/rust_debugfs.rs +2 -0
index b26eea3ee723..475502f30b1a 100644
@@ -59,6 +59,8 @@ struct RustDebugFs {
     #[pin]
     _compatible: File<CString>,
     #[pin]
+    _test: File<&'static CStr>,
+    #[pin]
     counter: File<AtomicUsize>,
     #[pin]
     inner: File<Mutex<Inner>>,
@@ -140,6 +142,7 @@ fn new(pdev: &platform::Device<Core>) -> impl PinInit<Self, Error> + '_ {
                         .property_read::<CString>(c_str!("compatible"))
Quoted 8 lines

samples/rust/rust_debugfs.rs fn new(pdev: &platform::Device<Core>) -> impl PinInit<Self, Error> + '_ { · line 145

Quoted 3 lines
samples/rust/rust_debugfs.rs +1 -0
                         .required_by(dev)?,
                 ),
+                _test <- debugfs.read_only_file(c_str!("test"), c_str!("some_value")),

Cool, but again, we do not want to ever be storing individual debugfs files. Well, we can, but for 90% of the cases, we do not, we only want to remove the whole directory when that goes out of scope, which will clean up the files then.

This API does not work in the way that you have a struct storing the data you want to expose *and* another one for the files with the data attached.

The File type contains the actual data. For instance, if you have a struct Foo, where you want to expose the members through debugfs you would *not* do:

      struct Foo {
         a: u32,
         b: u32,
      }

      struct FooFiles {
         a: File<&u32>,
         b: File<&u32>
      }
Quoted 2 lines

and then create an instance of Foo *and* another instance of FooFiles to export them via debugfs.

Ah, that's exactly what I was trying to do.

Quoted 7 lines

Instead you would change your struct Foo to just be:

      struct Foo {
         a: File<u32>,
         b: File<u32>,
      }
Quoted 7 lines

If you now create an instance of Foo (let's call it foo), then foo.a or foo.b dereferences to the inner type, i.e. the u32. Or in other words foo still behaves as if a and b would be u32 values. For instance:

   if foo.a == 42 {
      pr_info!("Foo::b = {}\n", foo.b);
   }

Oh that's not going to work well at all :(

Think about something "simple" like a pci config descriptor. You have a structure, with fields, already sitting there. You want to expose those fields in debugfs. So you want to only create debugfs files in one location in a driver, you don't want ALL users of those fields to have to go through a File<T> api, right? That would be crazy, all drivers would end up always having File<T> everywhere.

Quoted 2 lines

The fact that the backing files of a and b are removed from debugfs when Foo is dropped is necessary since otherwise we create a UAF.

Quoted 7 lines

That's fine, but:

Quoted 1 line

Think of File<T> as a containers like you think of KBox<T>.

Ok, but again, you are now forcing all users to think of debugfs as the main "interface" to those variables, which is not true (nor should it be.)

All of these things is why I recommended to Matthew that he should add back the scoped API, since it doesn't have all these drawbacks.

Alice

maintainer
#10 lore raw

Re: [PATCH v11 2/7] rust: debugfs: Add support for read-only files

Quoted 2 lines · Alice Ryhl

All of these things is why I recommended to Matthew that he should add back the scoped API, since it doesn't have all these drawbacks.

Yeah, I think it's the correct solution to make those cases nicer.

maintainer
#11 lore raw

Re: [PATCH v11 2/7] rust: debugfs: Add support for read-only files

In reply to Greg Kroah-Hartman
Quoted 43 lines · Greg Kroah-Hartman
Quoted 42 lines · Danilo Krummrich
Quoted 16 lines · Greg Kroah-Hartman
Quoted 15 lines · Danilo Krummrich
samples/rust/rust_debugfs.rs +2 -0
index b26eea3ee723..475502f30b1a 100644
@@ -59,6 +59,8 @@ struct RustDebugFs {
     #[pin]
     _compatible: File<CString>,
     #[pin]
+    _test: File<&'static CStr>,
+    #[pin]
     counter: File<AtomicUsize>,
     #[pin]
     inner: File<Mutex<Inner>>,
@@ -140,6 +142,7 @@ fn new(pdev: &platform::Device<Core>) -> impl PinInit<Self, Error> + '_ {
                         .property_read::<CString>(c_str!("compatible"))
Quoted 8 lines

samples/rust/rust_debugfs.rs fn new(pdev: &platform::Device<Core>) -> impl PinInit<Self, Error> + '_ { · line 145

Quoted 3 lines
samples/rust/rust_debugfs.rs +1 -0
                         .required_by(dev)?,
                 ),
+                _test <- debugfs.read_only_file(c_str!("test"), c_str!("some_value")),

Cool, but again, we do not want to ever be storing individual debugfs files. Well, we can, but for 90% of the cases, we do not, we only want to remove the whole directory when that goes out of scope, which will clean up the files then.

This API does not work in the way that you have a struct storing the data you want to expose *and* another one for the files with the data attached.

The File type contains the actual data. For instance, if you have a struct Foo, where you want to expose the members through debugfs you would *not* do:

	struct Foo {
	   a: u32,
	   b: u32,
	}

	struct FooFiles {
	   a: File<&u32>,
	   b: File<&u32>
	}
Quoted 4 lines
Quoted 2 lines

and then create an instance of Foo *and* another instance of FooFiles to export them via debugfs.

Ah, that's exactly what I was trying to do.

But that's bad, then we're back at the lifetime problem from the beginning, because the File<&Foo> then somehow needs to ensure that the instance Foo remains alive as long as File<&Foo> or the backing directory exists.

So, you eventually end of with Foo needing to be reference counted with its own memory allocation, which horribly messes with your lifetimes in the driver.

You don't want a a field to be reference counted just because it's exposed via debugfs.

Quoted 15 lines
Quoted 7 lines

Instead you would change your struct Foo to just be:

	struct Foo {
	   a: File<u32>,
	   b: File<u32>,
	}
Quoted 7 lines

If you now create an instance of Foo (let's call it foo), then foo.a or foo.b dereferences to the inner type, i.e. the u32. Or in other words foo still behaves as if a and b would be u32 values. For instance:

   if foo.a == 42 {
      pr_info!("Foo::b = {}\n", foo.b);
   }
Quoted 5 lines

Oh that's not going to work well at all :(

Think about something "simple" like a pci config descriptor. You have a structure, with fields, already sitting there. You want to expose those fields in debugfs.

This is more of a special case that is addressed by the Scope API in patch 6 and patch 7, so we should be good.

Quoted 14 lines
Quoted 2 lines

The fact that the backing files of a and b are removed from debugfs when Foo is dropped is necessary since otherwise we create a UAF.

That's fine, but:

Quoted 1 line

Think of File<T> as a containers like you think of KBox<T>.

Ok, but again, you are now forcing all users to think of debugfs as the main "interface" to those variables, which is not true (nor should it be.)

Quoted 3 lines

KBox<T> behaves exactly like T, but silently manages the backing kmalloc() allocation that T lives in.

Quoted 6 lines
Quoted 2 lines

With File<T> it's exactly the same, it behaves exactly like the T that lives within File<T>, but silently manages the debugfs file the T is exposed by.

And what happens if debugfs is not enabled? What about if creating the file fails? The variable still needs to be present and active and working.

This is the case, the variable will still be present and active in any case.

#12 lore raw

Re: [PATCH v11 2/7] rust: debugfs: Add support for read-only files

Quoted 47 lines · Danilo Krummrich
Quoted 46 lines · Greg Kroah-Hartman
Quoted 44 lines · Danilo Krummrich
Quoted 16 lines · Greg Kroah-Hartman
Quoted 15 lines · Danilo Krummrich
samples/rust/rust_debugfs.rs +2 -0
index b26eea3ee723..475502f30b1a 100644
@@ -59,6 +59,8 @@ struct RustDebugFs {
     #[pin]
     _compatible: File<CString>,
     #[pin]
+    _test: File<&'static CStr>,
+    #[pin]
     counter: File<AtomicUsize>,
     #[pin]
     inner: File<Mutex<Inner>>,
@@ -140,6 +142,7 @@ fn new(pdev: &platform::Device<Core>) -> impl PinInit<Self, Error> + '_ {
                         .property_read::<CString>(c_str!("compatible"))
Quoted 8 lines

samples/rust/rust_debugfs.rs fn new(pdev: &platform::Device<Core>) -> impl PinInit<Self, Error> + '_ { · line 145

Quoted 3 lines
samples/rust/rust_debugfs.rs +1 -0
                         .required_by(dev)?,
                 ),
+                _test <- debugfs.read_only_file(c_str!("test"), c_str!("some_value")),

Cool, but again, we do not want to ever be storing individual debugfs files. Well, we can, but for 90% of the cases, we do not, we only want to remove the whole directory when that goes out of scope, which will clean up the files then.

This API does not work in the way that you have a struct storing the data you want to expose *and* another one for the files with the data attached.

The File type contains the actual data. For instance, if you have a struct Foo, where you want to expose the members through debugfs you would *not* do:

	struct Foo {
	   a: u32,
	   b: u32,
	}

	struct FooFiles {
	   a: File<&u32>,
	   b: File<&u32>
	}

and then create an instance of Foo *and* another instance of FooFiles to export them via debugfs.

Quoted 8 lines
Quoted 1 line

Ah, that's exactly what I was trying to do.

But that's bad, then we're back at the lifetime problem from the beginning, because the File<&Foo> then somehow needs to ensure that the instance Foo remains alive as long as File<&Foo> or the backing directory exists.

So, you eventually end of with Foo needing to be reference counted with its own memory allocation, which horribly messes with your lifetimes in the driver.

Once I want to drop Foo, FooFiles should "go out of scope" and be gone. If a backing file descriptor is still held open, it will then become "stale" and not work. Much like the revokable stuff works.

Note, none of this is in the C code today, and debugfs is bound to root permissions, so it's not really an issue, but I can understand the goal of correctness...

Anyway, I looked at the scoped example here, and I don't see how that works any differently. How can I use it to have a single Dir "handle" that when goes out of scope, can drop the files attached to it that were created to reference Foo.a and Foo.b in your example above?

Quoted 2 lines

You don't want a a field to be reference counted just because it's exposed via debugfs.

Exactly, the data is the thing driving this, not the debugfs file.

Quoted 15 lines
Quoted 15 lines
Quoted 14 lines

Instead you would change your struct Foo to just be:

	struct Foo {
	   a: File<u32>,
	   b: File<u32>,
	}

If you now create an instance of Foo (let's call it foo), then foo.a or foo.b dereferences to the inner type, i.e. the u32. Or in other words foo still behaves as if a and b would be u32 values. For instance:

   if foo.a == 42 {
      pr_info!("Foo::b = {}\n", foo.b);
   }
Quoted 8 lines
Quoted 5 lines

Oh that's not going to work well at all :(

Think about something "simple" like a pci config descriptor. You have a structure, with fields, already sitting there. You want to expose those fields in debugfs.

This is more of a special case that is addressed by the Scope API in patch 6 and patch 7, so we should be good.

See above for my lack of understanding of that :)

Quoted 5 lines
Quoted 3 lines

And what happens if debugfs is not enabled? What about if creating the file fails? The variable still needs to be present and active and working.

This is the case, the variable will still be present and active in any case.

Ugh, but really, that's very unworkable overall. While I see the logic here, it's making the debugfs interface be the "main" one, when really that is just an afterthought and is NOT the thing to focus on at all.

Again, debugfs is just "on the side for debugging", let's not force it to be the way that data is accessed within the kernel itself, like is being done with the wrapping of File<T> here.

thanks,

greg k-h

maintainer
#13 lore raw

Re: [PATCH v11 2/7] rust: debugfs: Add support for read-only files

Quoted 50 lines · Greg Kroah-Hartman
Quoted 49 lines · Danilo Krummrich
Quoted 47 lines · Greg Kroah-Hartman
Quoted 42 lines · Danilo Krummrich
Quoted 16 lines · Greg Kroah-Hartman
Quoted 15 lines · Danilo Krummrich
samples/rust/rust_debugfs.rs +2 -0
index b26eea3ee723..475502f30b1a 100644
@@ -59,6 +59,8 @@ struct RustDebugFs {
     #[pin]
     _compatible: File<CString>,
     #[pin]
+    _test: File<&'static CStr>,
+    #[pin]
     counter: File<AtomicUsize>,
     #[pin]
     inner: File<Mutex<Inner>>,
@@ -140,6 +142,7 @@ fn new(pdev: &platform::Device<Core>) -> impl PinInit<Self, Error> + '_ {
                         .property_read::<CString>(c_str!("compatible"))
Quoted 8 lines

samples/rust/rust_debugfs.rs fn new(pdev: &platform::Device<Core>) -> impl PinInit<Self, Error> + '_ { · line 145

Quoted 3 lines
samples/rust/rust_debugfs.rs +1 -0
                         .required_by(dev)?,
                 ),
+                _test <- debugfs.read_only_file(c_str!("test"), c_str!("some_value")),

Cool, but again, we do not want to ever be storing individual debugfs files. Well, we can, but for 90% of the cases, we do not, we only want to remove the whole directory when that goes out of scope, which will clean up the files then.

This API does not work in the way that you have a struct storing the data you want to expose *and* another one for the files with the data attached.

The File type contains the actual data. For instance, if you have a struct Foo, where you want to expose the members through debugfs you would *not* do:

	struct Foo {
	   a: u32,
	   b: u32,
	}

	struct FooFiles {
	   a: File<&u32>,
	   b: File<&u32>
	}
Quoted 2 lines

and then create an instance of Foo *and* another instance of FooFiles to export them via debugfs.

Ah, that's exactly what I was trying to do.

Quoted 8 lines
Quoted 6 lines

But that's bad, then we're back at the lifetime problem from the beginning, because the File<&Foo> then somehow needs to ensure that the instance Foo remains alive as long as File<&Foo> or the backing directory exists.

So, you eventually end of with Foo needing to be reference counted with its own memory allocation, which horribly messes with your lifetimes in the driver.

Once I want to drop Foo, FooFiles should "go out of scope" and be gone.

We agree on the goal here, but unfortunately it's not really possible. There are two options that were already exercised:

(1) Force that FooFiles (or FooDir) is bound to the lifetime of a reference of Foo with FooDir<&'a Foo>.

This isn't workable because we then can't store both of them into the same parent structure.

(2) Reference count Foo (Arc<Foo>) and make FooDir own a referenc count of Foo.

But this is bad for the mentioned reasons. :(

(3) The File<T> API we have now, which gives you the behavior you ask for with Scope<T>.

Where Scope<T> creates a directory and owns the data you pass to it, e.g. a pci config descriptor.

The user can create an arbitrary number of files exporting any of the fields in date that live in the scope and don't need to be tracked separately, i.e. don't create separate object instances.

The directory (and hence all the files) is removed once the Scope<T> is dropped, including the data it owns.

Quoted 6 lines

If a backing file descriptor is still held open, it will then become "stale" and not work. Much like the revokable stuff works.

Note, none of this is in the C code today, and debugfs is bound to root permissions, so it's not really an issue, but I can understand the goal of correctness...

The lifetime guarantee we talk about is about the debugfs file still having a pointer to data that has already been dropped / freed.

In C you have to remove the debugfs file or directly (and hence the file) before the data exposed through it is freed. In C this is on the driver to take care of.

(If in C a driver has multiple structures exported in the same debugfs directory it has to manually take care of keeping all structures alive as long as the directory (and hence all files) exist.)

In Rust we need the abstraction to guarantee this.

Quoted 4 lines

Anyway, I looked at the scoped example here, and I don't see how that works any differently. How can I use it to have a single Dir "handle" that when goes out of scope, can drop the files attached to it that were created to reference Foo.a and Foo.b in your example above?

In the example above you would move Foo into the Scope<Foo>. For instance:

	let dir = root_dir.scope(foo, cstr!("subdir"), |foo, dir| {
		dir.read_only_file(c_str!("a"), foo.a);
		dir.read_only_file(c_str!("b"), foo.b);
	});

Note that those methods don't return anything, they're automatically bound to the Scope in lifetime.

So, Foo could be your pci config descriptor.

If dir is dropped, everything dies, the Scope, the "subdir" directory, all the files and also Foo.

I can provide some working code later on (currently in a meeting). :)

#14 lore raw

Re: [PATCH v11 2/7] rust: debugfs: Add support for read-only files

Quoted 122 lines · Danilo Krummrich
Quoted 50 lines · Greg Kroah-Hartman
Quoted 49 lines · Danilo Krummrich
Quoted 47 lines · Greg Kroah-Hartman
Quoted 42 lines · Danilo Krummrich
Quoted 16 lines · Greg Kroah-Hartman
Quoted 15 lines · Danilo Krummrich
samples/rust/rust_debugfs.rs +2 -0
index b26eea3ee723..475502f30b1a 100644
@@ -59,6 +59,8 @@ struct RustDebugFs {
     #[pin]
     _compatible: File<CString>,
     #[pin]
+    _test: File<&'static CStr>,
+    #[pin]
     counter: File<AtomicUsize>,
     #[pin]
     inner: File<Mutex<Inner>>,
@@ -140,6 +142,7 @@ fn new(pdev: &platform::Device<Core>) -> impl PinInit<Self, Error> + '_ {
                         .property_read::<CString>(c_str!("compatible"))
Quoted 8 lines

samples/rust/rust_debugfs.rs fn new(pdev: &platform::Device<Core>) -> impl PinInit<Self, Error> + '_ { · line 145

Quoted 3 lines
samples/rust/rust_debugfs.rs +1 -0
                         .required_by(dev)?,
                 ),
+                _test <- debugfs.read_only_file(c_str!("test"), c_str!("some_value")),

Cool, but again, we do not want to ever be storing individual debugfs files. Well, we can, but for 90% of the cases, we do not, we only want to remove the whole directory when that goes out of scope, which will clean up the files then.

This API does not work in the way that you have a struct storing the data you want to expose *and* another one for the files with the data attached.

The File type contains the actual data. For instance, if you have a struct Foo, where you want to expose the members through debugfs you would *not* do:

	struct Foo {
	   a: u32,
	   b: u32,
	}

	struct FooFiles {
	   a: File<&u32>,
	   b: File<&u32>
	}
Quoted 2 lines

and then create an instance of Foo *and* another instance of FooFiles to export them via debugfs.

Ah, that's exactly what I was trying to do.

Quoted 8 lines
Quoted 6 lines

But that's bad, then we're back at the lifetime problem from the beginning, because the File<&Foo> then somehow needs to ensure that the instance Foo remains alive as long as File<&Foo> or the backing directory exists.

So, you eventually end of with Foo needing to be reference counted with its own memory allocation, which horribly messes with your lifetimes in the driver.

Once I want to drop Foo, FooFiles should "go out of scope" and be gone.

We agree on the goal here, but unfortunately it's not really possible. There are two options that were already exercised:

(1) Force that FooFiles (or FooDir) is bound to the lifetime of a reference of Foo with FooDir<&'a Foo>.

This isn't workable because we then can't store both of them into the same parent structure.

(2) Reference count Foo (Arc<Foo>) and make FooDir own a referenc count of Foo.

But this is bad for the mentioned reasons. :(

(3) The File<T> API we have now, which gives you the behavior you ask for with Scope<T>.

Where Scope<T> creates a directory and owns the data you pass to it, e.g. a pci config descriptor.

The user can create an arbitrary number of files exporting any of the fields in date that live in the scope and don't need to be tracked separately, i.e. don't create separate object instances.

The directory (and hence all the files) is removed once the Scope<T> is dropped, including the data it owns.

Quoted 6 lines

If a backing file descriptor is still held open, it will then become "stale" and not work. Much like the revokable stuff works.

Note, none of this is in the C code today, and debugfs is bound to root permissions, so it's not really an issue, but I can understand the goal of correctness...

The lifetime guarantee we talk about is about the debugfs file still having a pointer to data that has already been dropped / freed.

In C you have to remove the debugfs file or directly (and hence the file) before the data exposed through it is freed. In C this is on the driver to take care of.

(If in C a driver has multiple structures exported in the same debugfs directory it has to manually take care of keeping all structures alive as long as the directory (and hence all files) exist.)

In Rust we need the abstraction to guarantee this.

Quoted 4 lines

Anyway, I looked at the scoped example here, and I don't see how that works any differently. How can I use it to have a single Dir "handle" that when goes out of scope, can drop the files attached to it that were created to reference Foo.a and Foo.b in your example above?

In the example above you would move Foo into the Scope<Foo>. For instance:

	let dir = root_dir.scope(foo, cstr!("subdir"), |foo, dir| {
		dir.read_only_file(c_str!("a"), foo.a);
		dir.read_only_file(c_str!("b"), foo.b);
	});

Note that those methods don't return anything, they're automatically bound to the Scope in lifetime.

Quoted 6 lines

So, Foo could be your pci config descriptor.

If dir is dropped, everything dies, the Scope, the "subdir" directory, all the files and also Foo.

I can provide some working code later on (currently in a meeting). :)

Working code for the simple "foo" example will be good. Here's my horrible (and will not build) example I was trying to get to work.

thanks,

greg k-h

maintainer
#15 lore raw

Re: [PATCH v11 2/7] rust: debugfs: Add support for read-only files

Quoted 1 line · Greg Kroah-Hartman

On Mon, Sep 08, 2025 at 04:59:16PM +0200, Danilo Krummrich wrote:

<snip>

Quoted 26 lines
Quoted 26 lines

We agree on the goal here, but unfortunately it's not really possible. There are two options that were already exercised:

(1) Force that FooFiles (or FooDir) is bound to the lifetime of a reference of Foo with FooDir<&'a Foo>.

This isn't workable because we then can't store both of them into the same parent structure.

(2) Reference count Foo (Arc<Foo>) and make FooDir own a referenc count of Foo.

But this is bad for the mentioned reasons. :(

(3) The File<T> API we have now, which gives you the behavior you ask for with Scope<T>.

Where Scope<T> creates a directory and owns the data you pass to it, e.g. a pci config descriptor.

The user can create an arbitrary number of files exporting any of the fields in date that live in the scope and don't need to be tracked separately, i.e. don't create separate object instances.

The directory (and hence all the files) is removed once the Scope<T> is dropped, including the data it owns.

<snip>

Quoted 4 lines
Quoted 1 line

I can provide some working code later on (currently in a meeting). :)

Working code for the simple "foo" example will be good. Here's my horrible (and will not build) example I was trying to get to work.

Here it comes [1]. :)

[1] rust_debugfs_soc_info.rs

// SPDX-License-Identifier: GPL-2.0

//! Simple debugfs::Scope example.

use kernel::c_str;
use kernel::debugfs::{Dir, Scope};
use kernel::prelude::*;

module! {
type: MyModule,
name: "MyModule",
description: "Just a simple test module.",
license: "GPL",
}

#[derive(Debug)]

struct HwSocInfo {
    name: &'static CStr,
    ver: u32,
    id: u32,
}
impl HwSocInfo {
    fn new(name: &'static CStr, ver: u32, id: u32) -> Self {
        Self { name, ver, id }
    }
}
struct MyModule {
    // Dropped when MyModule is released (e.g. through `rmmod`).
    //
    // This will drop the inner `HwSocInfo`, the "foo" directory, and all files created within this
    // directory.
    _scope: Pin<KBox<Scope<HwSocInfo>>>,
}
impl kernel::Module for MyModule {
    fn init(_module: &'static kernel::ThisModule) -> Result<Self, Error> {
        let root_dir = Dir::new(c_str!("my_module"));

        // Obtain some `HwSocInfo`, could from anywhere.
        let soc_info = HwSocInfo::new(c_str!("foo"), 24, 42);

        let scope = KBox::pin_init(
            // Create directory scope, that contains some data and a bunch of files exporting this
            // data.
            root_dir.scope(soc_info, c_str!("hw_soc_info"), |soc_info, dir| {
                dir.read_only_file(c_str!("name"), &soc_info.name);
                dir.read_only_file(c_str!("ver"), &soc_info.ver);
                dir.read_only_file(c_str!("id"), &soc_info.id);
            }),
            GFP_KERNEL,
        )?;

        // Print the contents of `soc_info` that were moved into `scope`.
        pr_info!("HwSocInfo: {:?}\n", &**scope);

        Ok(Self { _scope: scope })
    }
}
maintainer
#16 lore raw

Re: [PATCH v11 2/7] rust: debugfs: Add support for read-only files

Quoted 71 lines · Danilo Krummrich
Quoted 1 line · Greg Kroah-Hartman

On Mon, Sep 08, 2025 at 04:59:16PM +0200, Danilo Krummrich wrote:

<snip>

Quoted 26 lines
Quoted 26 lines

We agree on the goal here, but unfortunately it's not really possible. There are two options that were already exercised:

(1) Force that FooFiles (or FooDir) is bound to the lifetime of a reference of Foo with FooDir<&'a Foo>.

This isn't workable because we then can't store both of them into the same parent structure.

(2) Reference count Foo (Arc<Foo>) and make FooDir own a referenc count of Foo.

But this is bad for the mentioned reasons. :(

(3) The File<T> API we have now, which gives you the behavior you ask for with Scope<T>.

Where Scope<T> creates a directory and owns the data you pass to it, e.g. a pci config descriptor.

The user can create an arbitrary number of files exporting any of the fields in date that live in the scope and don't need to be tracked separately, i.e. don't create separate object instances.

The directory (and hence all the files) is removed once the Scope<T> is dropped, including the data it owns.

<snip>

Quoted 4 lines
Quoted 1 line

I can provide some working code later on (currently in a meeting). :)

Working code for the simple "foo" example will be good. Here's my horrible (and will not build) example I was trying to get to work.

Here it comes [1]. :)

[1] rust_debugfs_soc_info.rs

// SPDX-License-Identifier: GPL-2.0

//! Simple debugfs::Scope example.

use kernel::c_str;
use kernel::debugfs::{Dir, Scope};
use kernel::prelude::*;

module! {
type: MyModule,
name: "MyModule",
description: "Just a simple test module.",
license: "GPL",
}

#[derive(Debug)]

struct HwSocInfo {
    name: &'static CStr,
    ver: u32,
    id: u32,
}
impl HwSocInfo {
    fn new(name: &'static CStr, ver: u32, id: u32) -> Self {
        Self { name, ver, id }
    }
}
Quoted 6 lines
struct MyModule {
    // Dropped when MyModule is released (e.g. through `rmmod`).
    //
    // This will drop the inner `HwSocInfo`, the "foo" directory, and all files created within this
    // directory.
    _scope: Pin<KBox<Scope<HwSocInfo>>>,

And yes, I get that HwSocInfo now lives within a debugfs structure, just like with

	struct Data {
	   version: File<u32>,
	}

but those become transparent wrappers if debugfs is disabled, i.e. zero overhead. They also won't make the driver fail if anything with debugfs goes south if enabled.

And I also understand your point that now they're part of a "real" data structure. But in the end, debugfs *is* part of the driver. And while we should ensure that it doesn't impact drivers as much as possible (which we do), I don't think that we necessarily have to hide the fact entirely.

Having that said, I also don't really see an alternative. If we really want debugfs structures to be entirely separate we would have to either

(1) reference count fields exposed through debugfs, or

(2) make the interface unsafe, use raw pointers and assert that a debugfs file never out-lives the data it exposes, just like in C.

As I mentioned previously, while File<T> is visible in driver structures only,
(1) even enforces drivers to break their lifetime patterns, which is much worse and not acceptable I think.

I would even say that (2) is better than (1), because it becomes safe when debugfs is disabled. Yet I think both (1) and (2) are much worse that what we have right now.

And I think the Scope API helps a lot in keeping things reasonable for cases where a lot of fields of a single structure should be exposed separately, such as the one you sketched up.

Quoted 26 lines

}

impl kernel::Module for MyModule {
    fn init(_module: &'static kernel::ThisModule) -> Result<Self, Error> {
        let root_dir = Dir::new(c_str!("my_module"));

        // Obtain some `HwSocInfo`, could from anywhere.
        let soc_info = HwSocInfo::new(c_str!("foo"), 24, 42);

        let scope = KBox::pin_init(
            // Create directory scope, that contains some data and a bunch of files exporting this
            // data.
            root_dir.scope(soc_info, c_str!("hw_soc_info"), |soc_info, dir| {
                dir.read_only_file(c_str!("name"), &soc_info.name);
                dir.read_only_file(c_str!("ver"), &soc_info.ver);
                dir.read_only_file(c_str!("id"), &soc_info.id);
            }),
            GFP_KERNEL,
        )?;

        // Print the contents of `soc_info` that were moved into `scope`.
        pr_info!("HwSocInfo: {:?}\n", &**scope);

        Ok(Self { _scope: scope })
    }
}
#17 lore raw

Re: [PATCH v11 2/7] rust: debugfs: Add support for read-only files

Quoted 107 lines · Danilo Krummrich
Quoted 71 lines · Danilo Krummrich
Quoted 1 line · Greg Kroah-Hartman

On Mon, Sep 08, 2025 at 04:59:16PM +0200, Danilo Krummrich wrote:

<snip>

Quoted 26 lines
Quoted 26 lines

We agree on the goal here, but unfortunately it's not really possible. There are two options that were already exercised:

(1) Force that FooFiles (or FooDir) is bound to the lifetime of a reference of Foo with FooDir<&'a Foo>.

This isn't workable because we then can't store both of them into the same parent structure.

(2) Reference count Foo (Arc<Foo>) and make FooDir own a referenc count of Foo.

But this is bad for the mentioned reasons. :(

(3) The File<T> API we have now, which gives you the behavior you ask for with Scope<T>.

Where Scope<T> creates a directory and owns the data you pass to it, e.g. a pci config descriptor.

The user can create an arbitrary number of files exporting any of the fields in date that live in the scope and don't need to be tracked separately, i.e. don't create separate object instances.

The directory (and hence all the files) is removed once the Scope<T> is dropped, including the data it owns.

<snip>

Quoted 4 lines
Quoted 1 line

I can provide some working code later on (currently in a meeting). :)

Working code for the simple "foo" example will be good. Here's my horrible (and will not build) example I was trying to get to work.

Here it comes [1]. :)

[1] rust_debugfs_soc_info.rs

// SPDX-License-Identifier: GPL-2.0

//! Simple debugfs::Scope example.

use kernel::c_str;
use kernel::debugfs::{Dir, Scope};
use kernel::prelude::*;

module! {
type: MyModule,
name: "MyModule",
description: "Just a simple test module.",
license: "GPL",
}

#[derive(Debug)]

struct HwSocInfo {
    name: &'static CStr,
    ver: u32,
    id: u32,
}
impl HwSocInfo {
    fn new(name: &'static CStr, ver: u32, id: u32) -> Self {
        Self { name, ver, id }
    }
}
Quoted 6 lines
struct MyModule {
    // Dropped when MyModule is released (e.g. through `rmmod`).
    //
    // This will drop the inner `HwSocInfo`, the "foo" directory, and all files created within this
    // directory.
    _scope: Pin<KBox<Scope<HwSocInfo>>>,

And yes, I get that HwSocInfo now lives within a debugfs structure, just like with

	struct Data {
	   version: File<u32>,
	}

but those become transparent wrappers if debugfs is disabled, i.e. zero overhead. They also won't make the driver fail if anything with debugfs goes south if enabled.

And I also understand your point that now they're part of a "real" data structure. But in the end, debugfs *is* part of the driver. And while we should ensure that it doesn't impact drivers as much as possible (which we do), I don't think that we necessarily have to hide the fact entirely.

Having that said, I also don't really see an alternative. If we really want debugfs structures to be entirely separate we would have to either

(1) reference count fields exposed through debugfs, or

(2) make the interface unsafe, use raw pointers and assert that a debugfs file never out-lives the data it exposes, just like in C.

As I mentioned previously, while File<T> is visible in driver structures only,
(1) even enforces drivers to break their lifetime patterns, which is much worse and not acceptable I think.

Quoted 7 lines

I would even say that (2) is better than (1), because it becomes safe when debugfs is disabled. Yet I think both (1) and (2) are much worse that what we have right now.

And I think the Scope API helps a lot in keeping things reasonable for cases where a lot of fields of a single structure should be exposed separately, such as the one you sketched up.

Thanks for the example (and the rewrite of my example.)

This makes more sense, but I'm worried that this puts debugfs "front and center" for data structures that normally had nothing to do with debugfs at all.

So I took at look at the USB and PCI drivers to see what they do as those are "real-world" users of debugfs, not just "soc info" stuff, and it turns out that you are right. The use of debugfs is normally NOT using just simple wrappers around variables like our examples are doing, but are explicit "read/write" type things that do stuff to a structure, AND those structures need to be properly referenced, so that things do not go wrong when structures are removed.

So, after digging through this some more today, I think I'm ok with it. Let's merge this now, and let's see how it gets used and if it's unwieldy, hey, we can always change it!

thanks,

greg k-h

maintainer
#18 lore raw

Re: [PATCH v11 2/7] rust: debugfs: Add support for read-only files

In reply to Greg Kroah-Hartman
Quoted 2 lines · Greg Kroah-Hartman

Working code for the simple "foo" example will be good. Here's my horrible (and will not build) example I was trying to get to work.

I think our examples were pretty close already, but here's also your file. :)

// SPDX-License-Identifier: GPL-2.0

// Copyright (C) 2025 Greg Kroah-Hartman <[email protected]> // Copyright (C) 2025 The Linux Foundation

//! Sample debugfs rust module that emulates soc_info to try to see just how well the api can //! work...

use core::fmt;
use kernel::c_str;
use kernel::debugfs::{Dir, Scope};
use kernel::prelude::*;

module! {
type: SocInfo,
name: "rust_soc_info",
authors: ["Greg Kroah-Hartman"],
description: "Rust soc_info sample driver",
license: "GPL",
}

fn foundry_print(foundry: &u32, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    writeln!(f, "Foundry: {}", foundry)
}

// Fake "hardware SOC info object that ideally would read from the hardware to get the info. // For now just use some fake data
#[derive(Debug)]

struct HwSocInfo {
    id: u32,
    ver: u32,
    raw_id: u32,
    foundry: u32,
    name: &'static CStr,
}
impl HwSocInfo {
    fn new() -> Self {
        Self {
            id: 123,
            ver: 456,
            raw_id: 789,
            foundry: 0,
            name: c_str!("hw_soc name"),
        }
    }
}
struct SocInfo {
    _debug_dir: Dir,
    _hw_soc_info: Pin<KBox<Scope<HwSocInfo>>>,
}
impl kernel::Module for SocInfo {
    fn init(_this: &'static ThisModule) -> Result<Self> {
        // Read from the hardware and get our structure information
        let hw_soc_info = HwSocInfo::new();

        // Create the root directory
        let root = Dir::new(c_str!("rust_soc_info"));

        let scope = KBox::pin_init(
            // Create directory scope, that contains some data and a bunch of files exporting this
            // data.
            root.scope(hw_soc_info, c_str!("hw_soc_info"), |hw_soc_info, dir| {
                dir.read_only_file(c_str!("id"), &hw_soc_info.id);
                dir.read_only_file(c_str!("ver"), &hw_soc_info.ver);
                dir.read_only_file(c_str!("raw_id"), &hw_soc_info.raw_id);
                dir.read_only_file(c_str!("name"), &hw_soc_info.name);
                dir.read_callback_file(c_str!("foundry"), &hw_soc_info.foundry, &foundry_print);
            }),
            GFP_KERNEL,
        )?;

        let soc_info: &HwSocInfo = &scope;

        // Print the contents of `soc_info` that were moved into `scope`.
        pr_info!("HwSocInfo: {:?}\n", soc_info);

        Ok(Self {
            _debug_dir: root,
            _hw_soc_info: scope,
        })
    }
}
#19 lore raw

Re: [PATCH v11 2/7] rust: debugfs: Add support for read-only files

In reply to Matthew Maurer
Quoted 130 lines · Matthew Maurer

Extends the debugfs API to support creating read-only files. This is done via the Dir::read_only_file method, which takes a data object that implements the Writer trait.

The file's content is generated by the Writer implementation, and the file is automatically removed when the returned File handle is dropped.

---
 rust/kernel/debugfs.rs          | 148 +++++++++++++++++++++++++++++++++++++++-
 rust/kernel/debugfs/entry.rs    |  42 ++++++++++++
 rust/kernel/debugfs/file_ops.rs | 128 ++++++++++++++++++++++++++++++++++
 rust/kernel/debugfs/traits.rs   |  33 +++++++++
 4 files changed, 350 insertions(+), 1 deletion(-)
rust/kernel/debugfs.rs +86 -1
index 65be71600b8eda83c0d313f3d205d0713e8e9510..b28665f58cd6a17e188aef5e8c539f6c7433a3b0 100644
@@ -8,12 +8,18 @@
 // When DebugFS is disabled, many parameters are dead. Linting for this isn't helpful.
 #![cfg_attr(not(CONFIG_DEBUG_FS), allow(unused_variables))]
 
-#[cfg(CONFIG_DEBUG_FS)]
 use crate::prelude::*;
 use crate::str::CStr;
 #[cfg(CONFIG_DEBUG_FS)]
 use crate::sync::Arc;
+use core::marker::PhantomPinned;
+use core::ops::Deref;
+
+mod traits;
+pub use traits::Writer;
 
+mod file_ops;
+use file_ops::{FileOps, ReadFile};
 #[cfg(CONFIG_DEBUG_FS)]
 mod entry;
 #[cfg(CONFIG_DEBUG_FS)]
@@ -53,6 +59,34 @@ fn create(name: &CStr, parent: Option<&Dir>) -> Self {
         Self()
     }
 
+    /// Creates a DebugFS file which will own the data produced by the initializer provided in
+    /// `data`.
+    fn create_file<'a, T, E: 'a>(
+        &'a self,
+        name: &'a CStr,
+        data: impl PinInit<T, E> + 'a,
+        file_ops: &'static FileOps<T>,
+    ) -> impl PinInit<File<T>, E> + 'a
+    where
+        T: Sync + 'static,
+    {
+        let scope = Scope::<T>::new(data, move |data| {
+            #[cfg(CONFIG_DEBUG_FS)]
+            if let Some(parent) = &self.0 {
+                // SAFETY: Because data derives from a scope, and our entry will be dropped before
+                // the data is dropped, it is guaranteed to outlive the entry we return.
+                unsafe { Entry::dynamic_file(name, parent.clone(), data, file_ops) }
+            } else {
+                Entry::empty()
+            }
+        });
+        try_pin_init! {
+            File {
+                scope <- scope
+            } ? E
+        }
+    }
+
     /// Create a new directory in DebugFS at the root.
     ///
     /// # Examples
@@ -79,4 +113,116 @@ pub fn new(name: &CStr) -> Self {
     pub fn subdir(&self, name: &CStr) -> Self {
         Dir::create(name, Some(self))
     }
+
+    /// Creates a read-only file in this directory.
+    ///
+    /// The file's contents are produced by invoking [`Writer::write`] on the value initialized by
+    /// `data`.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use kernel::c_str;
+    /// # use kernel::debugfs::Dir;
+    /// # use kernel::prelude::*;
+    /// # let dir = Dir::new(c_str!("my_debugfs_dir"));
+    /// let file = KBox::pin_init(dir.read_only_file(c_str!("foo"), 200), GFP_KERNEL)?;
+    /// // "my_debugfs_dir/foo" now contains the number 200.
+    /// // The file is removed when `file` is dropped.
+    /// # Ok::<(), Error>(())
+    /// ```
+    pub fn read_only_file<'a, T, E: 'a>(
+        &'a self,
+        name: &'a CStr,
+        data: impl PinInit<T, E> + 'a,
+    ) -> impl PinInit<File<T>, E> + 'a
+    where
+        T: Writer + Send + Sync + 'static,
+    {
+        let file_ops = &<T as ReadFile<_>>::FILE_OPS;
+        self.create_file(name, data, file_ops)
+    }
+}
+
+#[pin_data]
+/// Handle to a DebugFS scope, which ensures that attached `data` will outlive the provided
+/// [`Entry`] without moving.
+/// Currently, this is used to back [`File`] so that its `read` and/or `write` implementations
+/// can assume that their backing data is still alive.
+struct Scope<T> {
+    // This order is load-bearing for drops - `_entry` must be dropped before `data`.
+    #[cfg(CONFIG_DEBUG_FS)]
+    _entry: Entry,
+    #[pin]
+    data: T,
+    // Even if `T` is `Unpin`, we still can't allow it to be moved.
+    #[pin]
+    _pin: PhantomPinned,
+}
+
+#[pin_data]
+/// Handle to a DebugFS file, owning its backing data.
+///
+/// When dropped, the DebugFS file will be removed and the attached data will be dropped.

rust/kernel/debugfs.rs pub fn new(name: &CStr) -> Self { · line 176

Quoted 10 lines
rust/kernel/debugfs.rs +10 -0
+pub struct File<T> {
+    #[pin]
+    scope: Scope<T>,
+}
+
+#[cfg(not(CONFIG_DEBUG_FS))]
+impl<'b, T: 'b> Scope<T> {
+    fn new<E: 'b, F>(data: impl PinInit<T, E> + 'b, init: F) -> impl PinInit<Self, E> + 'b
+    where
+        F: for<'a> FnOnce(&'a T) -> Entry + 'b,

Inspired by Greg's & Danilo's discussion I tried building with CONFIG_DEBUG_FS disabled. And get

error[E0412]: cannot find type Entry in this scope
--> rust/kernel/debugfs.rs:351:37

    |
351 |         F: for<'a> FnOnce(&'a T) -> Entry + 'b,
    |                                     ^^^^^ not found in this scope

And giving it some Entry (for my 1.81.0)

error: hidden lifetime parameters in types are deprecated
--> rust/kernel/debugfs.rs:352:37

    |
352 |         F: for<'a> FnOnce(&'a T) -> Entry + 'b,
    |                                     ^^^^^ expected lifetime parameter

Dirk

maintainer
#20 lore raw

Re: [PATCH v11 2/7] rust: debugfs: Add support for read-only files

Quoted 16 lines · Dirk Behme

Review

Quoted 5 lines · Matthew Maurer
(quoted diff) +5 -0
+#[cfg(not(CONFIG_DEBUG_FS))]
+impl<'b, T: 'b> Scope<T> {
+    fn new<E: 'b, F>(data: impl PinInit<T, E> + 'b, init: F) -> impl PinInit<Self, E> + 'b
+    where
+        F: for<'a> FnOnce(&'a T) -> Entry + 'b,

Inspired by Greg's & Danilo's discussion I tried building with CONFIG_DEBUG_FS disabled. And get

error[E0412]: cannot find type Entry in this scope
--> rust/kernel/debugfs.rs:351:37

    |
351 |         F: for<'a> FnOnce(&'a T) -> Entry + 'b,
    |                                     ^^^^^ not found in this scope
Quoted 7 lines

And giving it some Entry (for my 1.81.0)

error: hidden lifetime parameters in types are deprecated
--> rust/kernel/debugfs.rs:352:37

    |
352 |         F: for<'a> FnOnce(&'a T) -> Entry + 'b,
    |                                     ^^^^^ expected lifetime parameter

Yeah, I caught this as well and fixed it up on my end with the following diff:

rust/kernel/debugfs.rs +1 -1
index ecfcce845d3f..1f25777743db 100644
@@ -348,7 +348,7 @@ pub struct File<T> {
 impl<'b, T: 'b> Scope<T> {
     fn new<E: 'b, F>(data: impl PinInit<T, E> + 'b, init: F) -> impl PinInit<Self, E> + 'b
     where
-        F: for<'a> FnOnce(&'a T) -> Entry + 'b,
+        F: for<'a> FnOnce(&'a T) + 'b,
     {
         try_pin_init! {
             Self {
#21 lore raw

Re: [PATCH v11 2/7] rust: debugfs: Add support for read-only files

Quoted 33 lines · Danilo Krummrich
Quoted 16 lines · Dirk Behme

Review

Quoted 5 lines · Matthew Maurer
(quoted diff) +5 -0
+#[cfg(not(CONFIG_DEBUG_FS))]
+impl<'b, T: 'b> Scope<T> {
+    fn new<E: 'b, F>(data: impl PinInit<T, E> + 'b, init: F) -> impl PinInit<Self, E> + 'b
+    where
+        F: for<'a> FnOnce(&'a T) -> Entry + 'b,

Inspired by Greg's & Danilo's discussion I tried building with CONFIG_DEBUG_FS disabled. And get

error[E0412]: cannot find type Entry in this scope
--> rust/kernel/debugfs.rs:351:37

    |
351 |         F: for<'a> FnOnce(&'a T) -> Entry + 'b,
    |                                     ^^^^^ not found in this scope
Quoted 7 lines

And giving it some Entry (for my 1.81.0)

error: hidden lifetime parameters in types are deprecated
--> rust/kernel/debugfs.rs:352:37

    |
352 |         F: for<'a> FnOnce(&'a T) -> Entry + 'b,
    |                                     ^^^^^ expected lifetime parameter

Yeah, I caught this as well and fixed it up on my end with the following diff:

rust/kernel/debugfs.rs +0 -0
index ecfcce845d3f..1f25777743db 100644

rust/kernel/debugfs.rs pub struct File<T> { · line 354

Quoted 8 lines
rust/kernel/debugfs.rs +1 -1
@@ -348,7 +348,7 @@ pub struct File<T> {
 impl<'b, T: 'b> Scope<T> {
     fn new<E: 'b, F>(data: impl PinInit<T, E> + 'b, init: F) -> impl PinInit<Self, E> + 'b
     where
-        F: for<'a> FnOnce(&'a T) -> Entry + 'b,
+        F: for<'a> FnOnce(&'a T) + 'b,
     {
         try_pin_init! {
             Self {

Can you send this as a fix-up patch?

thanks,

greg k-h

maintainer
#22 lore raw

Re: [PATCH v11 2/7] rust: debugfs: Add support for read-only files

Quoted 28 lines · Greg Kroah-Hartman
Quoted 27 lines · Danilo Krummrich
Quoted 16 lines · Dirk Behme

Review

Quoted 5 lines · Matthew Maurer
(quoted diff) +5 -0
+#[cfg(not(CONFIG_DEBUG_FS))]
+impl<'b, T: 'b> Scope<T> {
+    fn new<E: 'b, F>(data: impl PinInit<T, E> + 'b, init: F) -> impl PinInit<Self, E> + 'b
+    where
+        F: for<'a> FnOnce(&'a T) -> Entry + 'b,

Inspired by Greg's & Danilo's discussion I tried building with CONFIG_DEBUG_FS disabled. And get

error[E0412]: cannot find type Entry in this scope
--> rust/kernel/debugfs.rs:351:37

    |
351 |         F: for<'a> FnOnce(&'a T) -> Entry + 'b,
    |                                     ^^^^^ not found in this scope
Quoted 7 lines

And giving it some Entry (for my 1.81.0)

error: hidden lifetime parameters in types are deprecated
--> rust/kernel/debugfs.rs:352:37

    |
352 |         F: for<'a> FnOnce(&'a T) -> Entry + 'b,
    |                                     ^^^^^ expected lifetime parameter

Yeah, I caught this as well and fixed it up on my end with the following diff:

Quoted 16 lines
Quoted 6 lines
rust/kernel/debugfs.rs +0 -0
index ecfcce845d3f..1f25777743db 100644

rust/kernel/debugfs.rs pub struct File<T> { · line 354

Quoted 8 lines
rust/kernel/debugfs.rs +1 -1
@@ -348,7 +348,7 @@ pub struct File<T> {
 impl<'b, T: 'b> Scope<T> {
     fn new<E: 'b, F>(data: impl PinInit<T, E> + 'b, init: F) -> impl PinInit<Self, E> + 'b
     where
-        F: for<'a> FnOnce(&'a T) -> Entry + 'b,
+        F: for<'a> FnOnce(&'a T) + 'b,
     {
         try_pin_init! {
             Self {

Can you send this as a fix-up patch?

If you don't mind I would fix this (and one other nit) up on apply. :)

#23 lore raw

Re: [PATCH v11 2/7] rust: debugfs: Add support for read-only files

Quoted 46 lines · Danilo Krummrich
Quoted 28 lines · Greg Kroah-Hartman
Quoted 27 lines · Danilo Krummrich
Quoted 16 lines · Dirk Behme

Review

Quoted 5 lines · Matthew Maurer
(quoted diff) +5 -0
+#[cfg(not(CONFIG_DEBUG_FS))]
+impl<'b, T: 'b> Scope<T> {
+    fn new<E: 'b, F>(data: impl PinInit<T, E> + 'b, init: F) -> impl PinInit<Self, E> + 'b
+    where
+        F: for<'a> FnOnce(&'a T) -> Entry + 'b,

Inspired by Greg's & Danilo's discussion I tried building with CONFIG_DEBUG_FS disabled. And get

error[E0412]: cannot find type Entry in this scope
--> rust/kernel/debugfs.rs:351:37

    |
351 |         F: for<'a> FnOnce(&'a T) -> Entry + 'b,
    |                                     ^^^^^ not found in this scope
Quoted 7 lines

And giving it some Entry (for my 1.81.0)

error: hidden lifetime parameters in types are deprecated
--> rust/kernel/debugfs.rs:352:37

    |
352 |         F: for<'a> FnOnce(&'a T) -> Entry + 'b,
    |                                     ^^^^^ expected lifetime parameter

Yeah, I caught this as well and fixed it up on my end with the following diff:

Quoted 16 lines
Quoted 6 lines
rust/kernel/debugfs.rs +0 -0
index ecfcce845d3f..1f25777743db 100644

rust/kernel/debugfs.rs pub struct File<T> { · line 354

Quoted 8 lines
rust/kernel/debugfs.rs +1 -1
@@ -348,7 +348,7 @@ pub struct File<T> {
 impl<'b, T: 'b> Scope<T> {
     fn new<E: 'b, F>(data: impl PinInit<T, E> + 'b, init: F) -> impl PinInit<Self, E> + 'b
     where
-        F: for<'a> FnOnce(&'a T) -> Entry + 'b,
+        F: for<'a> FnOnce(&'a T) + 'b,
     {
         try_pin_init! {
             Self {

Can you send this as a fix-up patch?

Quoted 1 line

If you don't mind I would fix this (and one other nit) up on apply. :)

I've pushed these to driver-core-testing if you could fix it up as I don't know what the other change was?

thanks,

greg k-h

maintainer
#24 lore raw

Re: [PATCH v11 2/7] rust: debugfs: Add support for read-only files

Quoted 2 lines · Greg Kroah-Hartman

I've pushed these to driver-core-testing if you could fix it up as I don't know what the other change was?

Sure, will do.

maintainer
#25 lore raw

Re: [PATCH v11 2/7] rust: debugfs: Add support for read-only files

Quoted 5 lines · Danilo Krummrich
Quoted 2 lines · Greg Kroah-Hartman

I've pushed these to driver-core-testing if you could fix it up as I don't know what the other change was?

Sure, will do.

* rust: debugfs: Add initial support for directories
* rust: debugfs: Add support for read-only files

[ Fixup build failure when CONFIG_DEBUGFS=n. - Danilo ]

* rust: debugfs: Add support for writable files

    [ Fix up Result<()> -> Result. - Danilo ]

* rust: debugfs: Add support for callback-based files

    [ Fix up Result<(), Error> -> Result. - Danilo ]

* samples: rust: Add debugfs sample driver

[ Change ACPI ID "LNUXDEBF" to "LNUXBEEF". - Danilo ]

* rust: debugfs: Add support for scoped directories

[ Fix up Result<(), Error> -> Result; fix spurious backtick in
doc-comment. - Danilo ]

* samples: rust: Add scoped debugfs sample driver

    [ Rename "scoped_debugfs" -> "debugfs_scoped", fix up
      Result<(), Error> -> Result. - Danilo ]
#26 lore raw

PATCH v11 3/7 rust: debugfs: Add support for writable files

In reply to Matthew Maurer

Extends the debugfs API to support creating writable files. This is done via the Dir::write_only_file and Dir::read_write_file methods, which take a data object that implements the Reader trait.

---
 rust/kernel/debugfs.rs          |  37 ++++++++++++-
 rust/kernel/debugfs/file_ops.rs | 113 +++++++++++++++++++++++++++++++++++++++-
 rust/kernel/debugfs/traits.rs   |  69 ++++++++++++++++++++++++
 3 files changed, 216 insertions(+), 3 deletions(-)
rust/kernel/debugfs.rs +35 -2
index b28665f58cd6a17e188aef5e8c539f6c7433a3b0..1f041f09a6eaf5603170ce4c7724b3ef50eecf13 100644
@@ -16,10 +16,10 @@
 use core::ops::Deref;
 
 mod traits;
-pub use traits::Writer;
+pub use traits::{Reader, Writer};
 
 mod file_ops;
-use file_ops::{FileOps, ReadFile};
+use file_ops::{FileOps, ReadFile, ReadWriteFile, WriteFile};
 #[cfg(CONFIG_DEBUG_FS)]
 mod entry;
 #[cfg(CONFIG_DEBUG_FS)]
@@ -142,6 +142,39 @@ pub fn read_only_file<'a, T, E: 'a>(
         let file_ops = &<T as ReadFile<_>>::FILE_OPS;
         self.create_file(name, data, file_ops)
     }
+
+    /// Creates a read-write file in this directory.
+    ///
+    /// Reading the file uses the [`Writer`] implementation.
+    /// Writing to the file uses the [`Reader`] implementation.
+    pub fn read_write_file<'a, T, E: 'a>(
+        &'a self,
+        name: &'a CStr,
+        data: impl PinInit<T, E> + 'a,
+    ) -> impl PinInit<File<T>, E> + 'a
+    where
+        T: Writer + Reader + Send + Sync + 'static,
+    {
+        let file_ops = &<T as ReadWriteFile<_>>::FILE_OPS;
+        self.create_file(name, data, file_ops)
+    }
+
+    /// Creates a write-only file in this directory.
+    ///
+    /// The file owns its backing data. Writing to the file uses the [`Reader`]
+    /// implementation.
+    ///
+    /// The file is removed when the returned [`File`] is dropped.
+    pub fn write_only_file<'a, T, E: 'a>(
+        &'a self,
+        name: &'a CStr,
+        data: impl PinInit<T, E> + 'a,
+    ) -> impl PinInit<File<T>, E> + 'a
+    where
+        T: Reader + Send + Sync + 'static,
+    {
+        self.create_file(name, data, &T::FILE_OPS)
+    }
 }
 
 #[pin_data]
rust/kernel/debugfs/file_ops.rs +112 -1

125 lines not on this page · raw message

rust/kernel/debugfs/traits.rs +69 -0

80 lines not on this page · raw message

Signature · 1 line
2.51.0.355.g5224444f11-goog
#27 lore raw

PATCH v11 4/7 rust: debugfs: Add support for callback-based files

In reply to Matthew Maurer

Extends the debugfs API to support creating files with content generated and updated by callbacks. This is done via the read_callback_file, write_callback_file, and read_write_callback_file methods.

These methods allow for more flexible file definition, either because the type already has a Writer or Reader method that doesn't do what you'd like, or because you cannot implement it (e.g. because it's a type defined in another crate or a primitive type).

---
 rust/kernel/debugfs.rs                   |  89 ++++++++++++++++++++++
 rust/kernel/debugfs/callback_adapters.rs | 122 +++++++++++++++++++++++++++++++
 rust/kernel/debugfs/file_ops.rs          |   8 ++
 3 files changed, 219 insertions(+)
rust/kernel/debugfs.rs +89 -0
index 1f041f09a6eaf5603170ce4c7724b3ef50eecf13..1032f279da380c549991e903c4162b7e4aaec571 100644
@@ -12,12 +12,16 @@
 use crate::str::CStr;
 #[cfg(CONFIG_DEBUG_FS)]
 use crate::sync::Arc;
+use crate::uaccess::UserSliceReader;
+use core::fmt;
 use core::marker::PhantomPinned;
 use core::ops::Deref;
 
 mod traits;
 pub use traits::{Reader, Writer};
 
+mod callback_adapters;
+use callback_adapters::{FormatAdapter, NoWriter, WritableAdapter};
 mod file_ops;
 use file_ops::{FileOps, ReadFile, ReadWriteFile, WriteFile};
 #[cfg(CONFIG_DEBUG_FS)]
@@ -143,6 +147,46 @@ pub fn read_only_file<'a, T, E: 'a>(
         self.create_file(name, data, file_ops)
     }
 
+    /// Creates a read-only file in this directory, with contents from a callback.
+    ///
+    /// `f` must be a function item or a non-capturing closure.
+    /// This is statically asserted and not a safety requirement.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use core::sync::atomic::{AtomicU32, Ordering};
+    /// # use kernel::c_str;
+    /// # use kernel::debugfs::Dir;
+    /// # use kernel::prelude::*;
+    /// # let dir = Dir::new(c_str!("foo"));
+    /// let file = KBox::pin_init(
+    ///     dir.read_callback_file(c_str!("bar"),
+    ///     AtomicU32::new(3),
+    ///     &|val, f| {
+    ///       let out = val.load(Ordering::Relaxed);
+    ///       writeln!(f, "{out:#010x}")
+    ///     }),
+    ///     GFP_KERNEL)?;
+    /// // Reading "foo/bar" will show "0x00000003".
+    /// file.store(10, Ordering::Relaxed);
+    /// // Reading "foo/bar" will now show "0x0000000a".
+    /// # Ok::<(), Error>(())
+    /// ```
+    pub fn read_callback_file<'a, T, E: 'a, F>(
+        &'a self,
+        name: &'a CStr,
+        data: impl PinInit<T, E> + 'a,
+        _f: &'static F,
+    ) -> impl PinInit<File<T>, E> + 'a
+    where
+        T: Send + Sync + 'static,
+        F: Fn(&T, &mut fmt::Formatter<'_>) -> fmt::Result + Send + Sync,
+    {
+        let file_ops = <FormatAdapter<T, F>>::FILE_OPS.adapt();
+        self.create_file(name, data, file_ops)
+    }
+
     /// Creates a read-write file in this directory.
     ///
     /// Reading the file uses the [`Writer`] implementation.
@@ -159,6 +203,31 @@ pub fn read_write_file<'a, T, E: 'a>(
         self.create_file(name, data, file_ops)
     }
 
+    /// Creates a read-write file in this directory, with logic from callbacks.
+    ///
+    /// Reading from the file is handled by `f`. Writing to the file is handled by `w`.
+    ///
+    /// `f` and `w` must be function items or non-capturing closures.
+    /// This is statically asserted and not a safety requirement.
+    pub fn read_write_callback_file<'a, T, E: 'a, F, W>(
+        &'a self,
+        name: &'a CStr,
+        data: impl PinInit<T, E> + 'a,
+        _f: &'static F,
+        _w: &'static W,
+    ) -> impl PinInit<File<T>, E> + 'a
+    where
+        T: Send + Sync + 'static,
+        F: Fn(&T, &mut fmt::Formatter<'_>) -> fmt::Result + Send + Sync,
+        W: Fn(&T, &mut UserSliceReader) -> Result<(), Error> + Send + Sync,
+    {
+        let file_ops =
+            <WritableAdapter<FormatAdapter<T, F>, W> as file_ops::ReadWriteFile<_>>::FILE_OPS
+                .adapt()
+                .adapt();
+        self.create_file(name, data, file_ops)
+    }
+
     /// Creates a write-only file in this directory.
     ///
     /// The file owns its backing data. Writing to the file uses the [`Reader`]
@@ -175,6 +244,26 @@ pub fn write_only_file<'a, T, E: 'a>(
     {
         self.create_file(name, data, &T::FILE_OPS)
     }
+
+    /// Creates a write-only file in this directory, with write logic from a callback.
+    ///
+    /// `w` must be a function item or a non-capturing closure.
+    /// This is statically asserted and not a safety requirement.
+    pub fn write_callback_file<'a, T, E: 'a, W>(
+        &'a self,
+        name: &'a CStr,
+        data: impl PinInit<T, E> + 'a,
+        _w: &'static W,
+    ) -> impl PinInit<File<T>, E> + 'a
+    where
+        T: Send + Sync + 'static,
+        W: Fn(&T, &mut UserSliceReader) -> Result<(), Error> + Send + Sync,
+    {
+        let file_ops = <WritableAdapter<NoWriter<T>, W> as WriteFile<_>>::FILE_OPS
+            .adapt()
+            .adapt();
+        self.create_file(name, data, file_ops)
+    }
 }
 
 #[pin_data]
rust/kernel/debugfs/callback_adapters.rs new file +122 -0

122 lines not on this page · raw message

rust/kernel/debugfs/file_ops.rs +8 -0
index 2060c8d14d83455efa6ec179669f2c3fcc35ccaf..50fead17b6f31feaf1caaef31c24ccdf6d8a5835 100644
@@ -2,6 +2,7 @@
 // Copyright (C) 2025 Google LLC.
 
 use super::{Reader, Writer};
+use crate::debugfs::callback_adapters::Adapter;
 use crate::prelude::*;
 use crate::seq_file::SeqFile;
 use crate::seq_print;
@@ -46,6 +47,13 @@ pub(crate) const fn mode(&self) -> u16 {
     }
 }
 
+impl<T: Adapter> FileOps<T> {
+    pub(super) const fn adapt(&self) -> &FileOps<T::Inner> {
+        // SAFETY: `Adapter` asserts that `T` can be legally cast to `T::Inner`.
+        unsafe { core::mem::transmute(self) }
+    }
+}
+
 #[cfg(CONFIG_DEBUG_FS)]
 impl<T> Deref for FileOps<T> {
     type Target = bindings::file_operations;
Signature · 1 line
2.51.0.355.g5224444f11-goog
#28 lore raw

PATCH v11 5/7 samples: rust: Add debugfs sample driver

In reply to Matthew Maurer

Adds a new sample driver that demonstrates the debugfs APIs.

The driver creates a directory in debugfs and populates it with a few files:
- A read-only file that displays a fwnode property.
- A read-write file that exposes an atomic counter.
- A read-write file that exposes a custom struct.

This sample serves as a basic example of how to use the debugfs::Dir and debugfs::File APIs to create and manage debugfs entries.

---
 MAINTAINERS                  |   1 +
 samples/rust/Kconfig         |  11 ++++
 samples/rust/Makefile        |   1 +
 samples/rust/rust_debugfs.rs | 151 +++++++++++++++++++++++++++++++++++++++++++
 4 files changed, 164 insertions(+)
MAINTAINERS +1 -0
index 8f2dbf71ca3f8f97e4d7619375279ed11d1261b2..5b6db584a33dd7ee39de3fdd0085d2bd7b7bef0e 100644
@@ -7481,6 +7481,7 @@ F:	rust/kernel/devres.rs
 F:	rust/kernel/driver.rs
 F:	rust/kernel/faux.rs
 F:	rust/kernel/platform.rs
+F:	samples/rust/rust_debugfs.rs
 F:	samples/rust/rust_driver_platform.rs
 F:	samples/rust/rust_driver_faux.rs
 
samples/rust/Kconfig +11 -0
index 7f7371a004ee0a8f67dca99c836596709a70c4fa..01101db41ae31b08a86d048cdd27da8ef9bb23a2 100644
@@ -62,6 +62,17 @@ config SAMPLE_RUST_DMA
 
 	  If unsure, say N.
 
+config SAMPLE_RUST_DEBUGFS
+	tristate "DebugFS Test Module"
+	depends on DEBUG_FS
+	help
+	  This option builds the Rust DebugFS Test module sample.
+
+	  To compile this as a module, choose M here:
+	  the module will be called rust_debugfs.
+
+	  If unsure, say N.
+
 config SAMPLE_RUST_DRIVER_PCI
 	tristate "PCI Driver"
 	depends on PCI
samples/rust/Makefile +1 -0
index bd2faad63b4f3befe7d1ed5139fe25c7a8b6d7f6..61276222a99f8cc6d7f84c26d0533b30815ebadd 100644
@@ -4,6 +4,7 @@ ccflags-y += -I$(src)				# needed for trace events
 obj-$(CONFIG_SAMPLE_RUST_MINIMAL)		+= rust_minimal.o
 obj-$(CONFIG_SAMPLE_RUST_MISC_DEVICE)		+= rust_misc_device.o
 obj-$(CONFIG_SAMPLE_RUST_PRINT)			+= rust_print.o
+obj-$(CONFIG_SAMPLE_RUST_DEBUGFS)		+= rust_debugfs.o
 obj-$(CONFIG_SAMPLE_RUST_DMA)			+= rust_dma.o
 obj-$(CONFIG_SAMPLE_RUST_DRIVER_PCI)		+= rust_driver_pci.o
 obj-$(CONFIG_SAMPLE_RUST_DRIVER_PLATFORM)	+= rust_driver_platform.o
samples/rust/rust_debugfs.rs new file +151 -0

151 lines not on this page · raw message

Signature · 1 line
2.51.0.355.g5224444f11-goog
maintainer
#29 lore raw

Re: [PATCH v11 5/7] samples: rust: Add debugfs sample driver

samples/rust/rust_debugfs.rs line 98

Quoted 5 lines · Matthew Maurer
samples/rust/rust_debugfs.rs new file +5 -0
+kernel::acpi_device_table!(
+    ACPI_TABLE,
+    MODULE_ACPI_TABLE,
+    <RustDebugFs as platform::Driver>::IdInfo,
+    [(acpi::DeviceId::new(c_str!("LNUXDEBF")), ())]

This should use "LNUXBEEF", as we explicitly reserved it for sample and test code.

I think we could reserve more if we see a benefit, but so far it's only used by the platform driver sample, so we should be good.

Either way, no need to resend for this only, it can be fixed up on apply. :)

samples/rust/rust_debugfs.rs line 103

Quoted 5 lines
samples/rust/rust_debugfs.rs new file +5 -0
+);
+
+impl platform::Driver for RustDebugFs {
+    type IdInfo = ();
+    const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = None;

NIT: This defaults to None, so it can be omitted.

Quoted 1 line

+ const ACPI_ID_TABLE: Option<acpi::IdTable<Self::IdInfo>> = Some(&ACPI_TABLE);

#30 lore raw

Re: [PATCH v11 5/7] samples: rust: Add debugfs sample driver

Quoted 8 lines · Danilo Krummrich

samples/rust/rust_debugfs.rs line 98

Quoted 5 lines · Matthew Maurer
samples/rust/rust_debugfs.rs new file +5 -0
+kernel::acpi_device_table!(
+    ACPI_TABLE,
+    MODULE_ACPI_TABLE,
+    <RustDebugFs as platform::Driver>::IdInfo,
+    [(acpi::DeviceId::new(c_str!("LNUXDEBF")), ())]
Quoted 7 lines

This should use "LNUXBEEF", as we explicitly reserved it for sample and test code.

I think we could reserve more if we see a benefit, but so far it's only used by the platform driver sample, so we should be good.

Either way, no need to resend for this only, it can be fixed up on apply. :)

Ah, thanks, I was unaware that it was specially reserved and so tried to pick something distinct. You fixing up this and the OF_ID_TABLE on apply SGTM.

Quoted 10 lines

samples/rust/rust_debugfs.rs line 103

Quoted 6 lines
samples/rust/rust_debugfs.rs new file +5 -0
+);
+
+impl platform::Driver for RustDebugFs {
+    type IdInfo = ();
+    const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = None;

NIT: This defaults to None, so it can be omitted.

Quoted 1 line

+ const ACPI_ID_TABLE: Option<acpi::IdTable<Self::IdInfo>> = Some(&ACPI_TABLE);

maintainer
#31 lore raw

Re: [PATCH v11 5/7] samples: rust: Add debugfs sample driver

Quoted 12 lines · Matthew Maurer
Quoted 11 lines · Danilo Krummrich

samples/rust/rust_debugfs.rs line 98

Quoted 5 lines · Matthew Maurer
samples/rust/rust_debugfs.rs new file +5 -0
+kernel::acpi_device_table!(
+    ACPI_TABLE,
+    MODULE_ACPI_TABLE,
+    <RustDebugFs as platform::Driver>::IdInfo,
+    [(acpi::DeviceId::new(c_str!("LNUXDEBF")), ())]

This should use "LNUXBEEF", as we explicitly reserved it for sample and test code.

Quoted 8 lines
Quoted 4 lines

I think we could reserve more if we see a benefit, but so far it's only used by the platform driver sample, so we should be good.

Either way, no need to resend for this only, it can be fixed up on apply. :)

Ah, thanks, I was unaware that it was specially reserved and so tried to pick something distinct. You fixing up this and the OF_ID_TABLE on apply SGTM.

Ok, I will wait for Greg to have a look first.

- Danilo

#32 lore raw

Re: [PATCH v11 5/7] samples: rust: Add debugfs sample driver

In reply to Matthew Maurer
Quoted 125 lines · Matthew Maurer

Adds a new sample driver that demonstrates the debugfs APIs.

The driver creates a directory in debugfs and populates it with a few files:
- A read-only file that displays a fwnode property.
- A read-write file that exposes an atomic counter.
- A read-write file that exposes a custom struct.

This sample serves as a basic example of how to use the debugfs::Dir and debugfs::File APIs to create and manage debugfs entries.

---
 MAINTAINERS                  |   1 +
 samples/rust/Kconfig         |  11 ++++
 samples/rust/Makefile        |   1 +
 samples/rust/rust_debugfs.rs | 151 +++++++++++++++++++++++++++++++++++++++++++
 4 files changed, 164 insertions(+)
MAINTAINERS +1 -0
index 8f2dbf71ca3f8f97e4d7619375279ed11d1261b2..5b6db584a33dd7ee39de3fdd0085d2bd7b7bef0e 100644
@@ -7481,6 +7481,7 @@ F:	rust/kernel/devres.rs
 F:	rust/kernel/driver.rs
 F:	rust/kernel/faux.rs
 F:	rust/kernel/platform.rs
+F:	samples/rust/rust_debugfs.rs
 F:	samples/rust/rust_driver_platform.rs
 F:	samples/rust/rust_driver_faux.rs
 
samples/rust/Kconfig +11 -0
index 7f7371a004ee0a8f67dca99c836596709a70c4fa..01101db41ae31b08a86d048cdd27da8ef9bb23a2 100644
@@ -62,6 +62,17 @@ config SAMPLE_RUST_DMA
 
 	  If unsure, say N.
 
+config SAMPLE_RUST_DEBUGFS
+	tristate "DebugFS Test Module"
+	depends on DEBUG_FS
+	help
+	  This option builds the Rust DebugFS Test module sample.
+
+	  To compile this as a module, choose M here:
+	  the module will be called rust_debugfs.
+
+	  If unsure, say N.
+
 config SAMPLE_RUST_DRIVER_PCI
 	tristate "PCI Driver"
 	depends on PCI
samples/rust/Makefile +1 -0
index bd2faad63b4f3befe7d1ed5139fe25c7a8b6d7f6..61276222a99f8cc6d7f84c26d0533b30815ebadd 100644
@@ -4,6 +4,7 @@ ccflags-y += -I$(src)				# needed for trace events
 obj-$(CONFIG_SAMPLE_RUST_MINIMAL)		+= rust_minimal.o
 obj-$(CONFIG_SAMPLE_RUST_MISC_DEVICE)		+= rust_misc_device.o
 obj-$(CONFIG_SAMPLE_RUST_PRINT)			+= rust_print.o
+obj-$(CONFIG_SAMPLE_RUST_DEBUGFS)		+= rust_debugfs.o
 obj-$(CONFIG_SAMPLE_RUST_DMA)			+= rust_dma.o
 obj-$(CONFIG_SAMPLE_RUST_DRIVER_PCI)		+= rust_driver_pci.o
 obj-$(CONFIG_SAMPLE_RUST_DRIVER_PLATFORM)	+= rust_driver_platform.o
samples/rust/rust_debugfs.rs new file +54 -0
new file mode 100644
index 0000000000000000000000000000000000000000..8d394f06b37e69ea1c30a3b0d8444c80562cc5ab
@@ -0,0 +1,151 @@
+// SPDX-License-Identifier: GPL-2.0
+
+// Copyright (C) 2025 Google LLC.
+
+//! Sample DebugFS exporting platform driver
+//!
+//! To successfully probe this driver with ACPI, use an ssdt that looks like
+//!
+//! ```dsl
+//! DefinitionBlock ("", "SSDT", 2, "TEST", "VIRTACPI", 0x00000001)
+//! {
+//!    Scope (\_SB)
+//!    {
+//!        Device (T432)
+//!        {
+//!            Name (_HID, "LNUXDEBF")  // ACPI hardware ID to match
+//!            Name (_UID, 1)
+//!            Name (_STA, 0x0F)        // Device present, enabled
+//!            Name (_DSD, Package () { // Sample attribute
+//!                ToUUID("daffd814-6eba-4d8c-8a91-bc9bbf4aa301"),
+//!                Package() {
+//!                    Package(2) {"compatible", "sample-debugfs"}
+//!                }
+//!            })
+//!            Name (_CRS, ResourceTemplate ()
+//!            {
+//!                Memory32Fixed (ReadWrite, 0xFED00000, 0x1000)
+//!            })
+//!        }
+//!    }
+//! }
+//! ```
+
+use core::str::FromStr;
+use core::sync::atomic::AtomicUsize;
+use core::sync::atomic::Ordering;
+use kernel::c_str;
+use kernel::debugfs::{Dir, File};
+use kernel::new_mutex;
+use kernel::prelude::*;
+use kernel::sync::Mutex;
+
+use kernel::{acpi, device::Core, of, platform, str::CString, types::ARef};
+
+kernel::module_platform_driver! {
+    type: RustDebugFs,
+    name: "rust_debugfs",
+    authors: ["Matthew Maurer"],
+    description: "Rust DebugFS usage sample",
+    license: "GPL",
+}
+
+#[pin_data]
+struct RustDebugFs {

samples/rust/rust_debugfs.rs line 64

Quoted 10 lines
samples/rust/rust_debugfs.rs new file +10 -0
+    pdev: ARef<platform::Device>,
+    // As we only hold these for drop effect (to remove the directory/files) we have a leading
+    // underscore to indicate to the compiler that we don't expect to use this field directly.
+    _debugfs: Dir,
+    #[pin]
+    _compatible: File<CString>,
+    #[pin]
+    counter: File<AtomicUsize>,
+    #[pin]
+    inner: File<Mutex<Inner>>,

Why are you saving the file pointers here at all? They shouldn't be needed to keep around, all that should be needed is the Dir, right? If not, this needs to be revisited...

And why do you need to keep "counter"? Shouldn't that be passed back somehow in the callback automatically?

You use it:

samples/rust/rust_debugfs.rs line 112

Quoted 12 lines
samples/rust/rust_debugfs.rs new file +12 -0
+impl platform::Driver for RustDebugFs {
+    type IdInfo = ();
+    const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = None;
+    const ACPI_ID_TABLE: Option<acpi::IdTable<Self::IdInfo>> = Some(&ACPI_TABLE);
+
+    fn probe(
+        pdev: &platform::Device<Core>,
+        _info: Option<&Self::IdInfo>,
+    ) -> Result<Pin<KBox<Self>>> {
+        let result = KBox::try_pin_init(RustDebugFs::new(pdev), GFP_KERNEL)?;
+        // We can still mutate fields through the files which are atomic or mutexed:
+        result.counter.store(91, Ordering::Relaxed);

Here? This feels odd, the file is the wrapper for the variable you want the file to show? That feels backwards. Usually the variable is always present, and then you can create a debugfs file to read/modify it. But if debugfs is NOT enabled, you can still use the variable, it's just the file logic that is gone, right?

So what would this file look like without debugfs being enabled? Would the atomic variable still be here? I think it wouldn't, which is not ok...

Or am I confused again?

thanks,

greg k-h

maintainer
#33 lore raw

Re: [PATCH v11 5/7] samples: rust: Add debugfs sample driver

Quoted 132 lines · Greg Kroah-Hartman
Quoted 131 lines · Matthew Maurer

Adds a new sample driver that demonstrates the debugfs APIs.

The driver creates a directory in debugfs and populates it with a few files:
- A read-only file that displays a fwnode property.
- A read-write file that exposes an atomic counter.
- A read-write file that exposes a custom struct.

This sample serves as a basic example of how to use the debugfs::Dir and debugfs::File APIs to create and manage debugfs entries.

---
 MAINTAINERS                  |   1 +
 samples/rust/Kconfig         |  11 ++++
 samples/rust/Makefile        |   1 +
 samples/rust/rust_debugfs.rs | 151 +++++++++++++++++++++++++++++++++++++++++++
 4 files changed, 164 insertions(+)
MAINTAINERS +1 -0
index 8f2dbf71ca3f8f97e4d7619375279ed11d1261b2..5b6db584a33dd7ee39de3fdd0085d2bd7b7bef0e 100644
@@ -7481,6 +7481,7 @@ F:	rust/kernel/devres.rs
 F:	rust/kernel/driver.rs
 F:	rust/kernel/faux.rs
 F:	rust/kernel/platform.rs
+F:	samples/rust/rust_debugfs.rs
 F:	samples/rust/rust_driver_platform.rs
 F:	samples/rust/rust_driver_faux.rs
 
samples/rust/Kconfig +11 -0
index 7f7371a004ee0a8f67dca99c836596709a70c4fa..01101db41ae31b08a86d048cdd27da8ef9bb23a2 100644
@@ -62,6 +62,17 @@ config SAMPLE_RUST_DMA
 
 	  If unsure, say N.
 
+config SAMPLE_RUST_DEBUGFS
+	tristate "DebugFS Test Module"
+	depends on DEBUG_FS
+	help
+	  This option builds the Rust DebugFS Test module sample.
+
+	  To compile this as a module, choose M here:
+	  the module will be called rust_debugfs.
+
+	  If unsure, say N.
+
 config SAMPLE_RUST_DRIVER_PCI
 	tristate "PCI Driver"
 	depends on PCI
samples/rust/Makefile +1 -0
index bd2faad63b4f3befe7d1ed5139fe25c7a8b6d7f6..61276222a99f8cc6d7f84c26d0533b30815ebadd 100644
@@ -4,6 +4,7 @@ ccflags-y += -I$(src)				# needed for trace events
 obj-$(CONFIG_SAMPLE_RUST_MINIMAL)		+= rust_minimal.o
 obj-$(CONFIG_SAMPLE_RUST_MISC_DEVICE)		+= rust_misc_device.o
 obj-$(CONFIG_SAMPLE_RUST_PRINT)			+= rust_print.o
+obj-$(CONFIG_SAMPLE_RUST_DEBUGFS)		+= rust_debugfs.o
 obj-$(CONFIG_SAMPLE_RUST_DMA)			+= rust_dma.o
 obj-$(CONFIG_SAMPLE_RUST_DRIVER_PCI)		+= rust_driver_pci.o
 obj-$(CONFIG_SAMPLE_RUST_DRIVER_PLATFORM)	+= rust_driver_platform.o
samples/rust/rust_debugfs.rs new file +60 -0
new file mode 100644
index 0000000000000000000000000000000000000000..8d394f06b37e69ea1c30a3b0d8444c80562cc5ab
@@ -0,0 +1,151 @@
+// SPDX-License-Identifier: GPL-2.0
+
+// Copyright (C) 2025 Google LLC.
+
+//! Sample DebugFS exporting platform driver
+//!
+//! To successfully probe this driver with ACPI, use an ssdt that looks like
+//!
+//! ```dsl
+//! DefinitionBlock ("", "SSDT", 2, "TEST", "VIRTACPI", 0x00000001)
+//! {
+//!    Scope (\_SB)
+//!    {
+//!        Device (T432)
+//!        {
+//!            Name (_HID, "LNUXDEBF")  // ACPI hardware ID to match
+//!            Name (_UID, 1)
+//!            Name (_STA, 0x0F)        // Device present, enabled
+//!            Name (_DSD, Package () { // Sample attribute
+//!                ToUUID("daffd814-6eba-4d8c-8a91-bc9bbf4aa301"),
+//!                Package() {
+//!                    Package(2) {"compatible", "sample-debugfs"}
+//!                }
+//!            })
+//!            Name (_CRS, ResourceTemplate ()
+//!            {
+//!                Memory32Fixed (ReadWrite, 0xFED00000, 0x1000)
+//!            })
+//!        }
+//!    }
+//! }
+//! ```
+
+use core::str::FromStr;
+use core::sync::atomic::AtomicUsize;
+use core::sync::atomic::Ordering;
+use kernel::c_str;
+use kernel::debugfs::{Dir, File};
+use kernel::new_mutex;
+use kernel::prelude::*;
+use kernel::sync::Mutex;
+
+use kernel::{acpi, device::Core, of, platform, str::CString, types::ARef};
+
+kernel::module_platform_driver! {
+    type: RustDebugFs,
+    name: "rust_debugfs",
+    authors: ["Matthew Maurer"],
+    description: "Rust DebugFS usage sample",
+    license: "GPL",
+}
+
+#[pin_data]
+struct RustDebugFs {
+    pdev: ARef<platform::Device>,
+    // As we only hold these for drop effect (to remove the directory/files) we have a leading
+    // underscore to indicate to the compiler that we don't expect to use this field directly.
+    _debugfs: Dir,
+    #[pin]
+    _compatible: File<CString>,
Quoted 8 lines

samples/rust/rust_debugfs.rs line 64

Quoted 4 lines
samples/rust/rust_debugfs.rs new file +4 -0
+    #[pin]
+    counter: File<AtomicUsize>,
+    #[pin]
+    inner: File<Mutex<Inner>>,

Why are you saving the file pointers here at all? They shouldn't be needed to keep around, all that should be needed is the Dir, right? If not, this needs to be revisited...

It's not really the file pointers, but the actual data, i.e. a CString, AtomicUsize and a Mutex<Inner>. That they're wrapped by the File<T> type, only means that they're exported via debugfs (if enabled, otherwise they are not).

Quoted 10 lines
Quoted 10 lines
samples/rust/rust_debugfs.rs new file +10 -0
+impl platform::Driver for RustDebugFs {
+    type IdInfo = ();
+    const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = None;
+    const ACPI_ID_TABLE: Option<acpi::IdTable<Self::IdInfo>> = Some(&ACPI_TABLE);
+
+    fn probe(
+        pdev: &platform::Device<Core>,
+        _info: Option<&Self::IdInfo>,
+    ) -> Result<Pin<KBox<Self>>> {
+        let result = KBox::try_pin_init(RustDebugFs::new(pdev), GFP_KERNEL)?;
Quoted 8 lines

samples/rust/rust_debugfs.rs line 112

Quoted 2 lines
samples/rust/rust_debugfs.rs new file +2 -0
+        // We can still mutate fields through the files which are atomic or mutexed:
+        result.counter.store(91, Ordering::Relaxed);

Here? This feels odd, the file is the wrapper for the variable you want the file to show? That feels backwards. Usually the variable is always present, and then you can create a debugfs file to read/modify it. But if debugfs is NOT enabled, you can still use the variable, it's just the file logic that is gone, right?

Please see [1]. :)

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

Quoted 3 lines

So what would this file look like without debugfs being enabled? Would the atomic variable still be here? I think it wouldn't, which is not ok...

Yes, that atomic would still be there, the File<AtomicUsize> behaves exactly like a standalone AtomicUsize (except that it exports it in debugfs), and in case of debugfs disabled you would access the atomic the exact same way, just that no actual debugfs file exporting the AtomicUsize is created in the background -- so fully transparent.

#34 lore raw

PATCH v11 6/7 rust: debugfs: Add support for scoped directories

In reply to Matthew Maurer

Introduces the concept of a ScopedDir, which allows for the creation of debugfs directories and files that are tied to the lifetime of a particular data structure. This ensures that debugfs entries do not outlive the data they refer to.

The new Dir::scope method creates a new directory that is owned by a Scope handle. All files and subdirectories created within this scope are automatically cleaned up when the Scope is dropped.

---
 rust/kernel/debugfs.rs       | 262 +++++++++++++++++++++++++++++++++++++++++--
 rust/kernel/debugfs/entry.rs |  73 +++++++++++-
 2 files changed, 320 insertions(+), 15 deletions(-)
rust/kernel/debugfs.rs +253 -9
index 1032f279da380c549991e903c4162b7e4aaec571..ecfcce845d3f1e9183a55e16629564776f80c6f0 100644
@@ -14,7 +14,10 @@
 use crate::sync::Arc;
 use crate::uaccess::UserSliceReader;
 use core::fmt;
+use core::marker::PhantomData;
 use core::marker::PhantomPinned;
+#[cfg(CONFIG_DEBUG_FS)]
+use core::mem::ManuallyDrop;
 use core::ops::Deref;
 
 mod traits;
@@ -40,7 +43,7 @@
 // able to refer to us. In this case, we need to silently fail. All future child directories/files
 // will silently fail as well.
 #[derive(Clone)]
-pub struct Dir(#[cfg(CONFIG_DEBUG_FS)] Option<Arc<Entry>>);
+pub struct Dir(#[cfg(CONFIG_DEBUG_FS)] Option<Arc<Entry<'static>>>);
 
 impl Dir {
     /// Create a new directory in DebugFS. If `parent` is [`None`], it will be created at the root.
@@ -264,17 +267,67 @@ pub fn write_callback_file<'a, T, E: 'a, W>(
             .adapt();
         self.create_file(name, data, file_ops)
     }
+
+    // While this function is safe, it is intentionally not public because it's a bit of a
+    // footgun.
+    //
+    // Unless you also extract the `entry` later and schedule it for `Drop` at the appropriate
+    // time, a `ScopedDir` with a `Dir` parent will never be deleted.
+    fn scoped_dir<'data>(&self, name: &CStr) -> ScopedDir<'data, 'static> {
+        #[cfg(CONFIG_DEBUG_FS)]
+        {
+            let parent_entry = match &self.0 {
+                None => return ScopedDir::empty(),
+                Some(entry) => entry.clone(),
+            };
+            ScopedDir {
+                entry: ManuallyDrop::new(Entry::dynamic_dir(name, Some(parent_entry))),
+                _phantom: PhantomData,
+            }
+        }
+        #[cfg(not(CONFIG_DEBUG_FS))]
+        ScopedDir::empty()
+    }
+
+    /// Creates a new scope, which is a directory associated with some data `T`.
+    ///
+    /// The created directory will be a subdirectory of `self`. The `init` closure is called to
+    /// populate the directory with files and subdirectories. These files can reference the data
+    /// stored in the scope.
+    ///
+    /// The entire directory tree created within the scope will be removed when the returned
+    /// `Scope` handle is dropped.
+    pub fn scope<'a, T: 'a, E: 'a, F>(
+        &'a self,
+        data: impl PinInit<T, E> + 'a,
+        name: &'a CStr,
+        init: F,
+    ) -> impl PinInit<Scope<T>, E> + 'a
+    where
+        F: for<'data, 'dir> FnOnce(&'data T, &'dir ScopedDir<'data, 'dir>) + 'a,
+    {
+        Scope::new(data, |data| {
+            let scoped = self.scoped_dir(name);
+            init(data, &scoped);
+            scoped.into_entry()
+        })
+    }
 }
 
 #[pin_data]
-/// Handle to a DebugFS scope, which ensures that attached `data` will outlive the provided
-/// [`Entry`] without moving.
-/// Currently, this is used to back [`File`] so that its `read` and/or `write` implementations
-/// can assume that their backing data is still alive.
-struct Scope<T> {
+/// Handle to a DebugFS scope, which ensures that attached `data` will outlive the DebugFS entry
+/// without moving.
+///
+/// This is internally used to back [`File`], and used in the API to represent the attachment
+/// of a directory lifetime to a data structure which may be jointly accessed by a number of
+/// different files.
+///
+/// When dropped, a `Scope` will remove all directories and files in the filesystem backed by the
+/// attached data structure prior to releasing the attached data.
+pub struct Scope<T> {
     // This order is load-bearing for drops - `_entry` must be dropped before `data`.
     #[cfg(CONFIG_DEBUG_FS)]
-    _entry: Entry,
+    _entry: Entry<'static>,
     #[pin]
     data: T,
     // Even if `T` is `Unpin`, we still can't allow it to be moved.
@@ -312,14 +365,14 @@ fn new<E: 'b, F>(data: impl PinInit<T, E> + 'b, init: F) -> impl PinInit<Self, E
 
 #[cfg(CONFIG_DEBUG_FS)]
 impl<'b, T: 'b> Scope<T> {
-    fn entry_mut(self: Pin<&mut Self>) -> &mut Entry {
+    fn entry_mut(self: Pin<&mut Self>) -> &mut Entry<'static> {
         // SAFETY: _entry is not structurally pinned.
         unsafe { &mut Pin::into_inner_unchecked(self)._entry }
     }
 
     fn new<E: 'b, F>(data: impl PinInit<T, E> + 'b, init: F) -> impl PinInit<Self, E> + 'b
     where
-        F: for<'a> FnOnce(&'a T) -> Entry + 'b,
+        F: for<'a> FnOnce(&'a T) -> Entry<'static> + 'b,
     {
         try_pin_init! {
             Self {
@@ -335,6 +388,31 @@ fn new<E: 'b, F>(data: impl PinInit<T, E> + 'b, init: F) -> impl PinInit<Self, E
     }
 }
 
+impl<'a, T: 'a> Scope<T> {
+    /// Creates a new scope, which is a directory at the root of the debugfs filesystem,
+    /// associated with some data `T`.
+    ///
+    /// The `init` closure is called to populate the directory with files and subdirectories. These
+    /// files can reference the data stored in the scope.
+    ///
+    /// The entire directory tree created within the scope will be removed when the returned
+    /// `Scope` handle is dropped.
+    pub fn dir<E: 'a, F>(
+        data: impl PinInit<T, E> + 'a,
+        name: &'a CStr,
+        init: F,
+    ) -> impl PinInit<Self, E> + 'a
+    where
+        F: for<'data, 'dir> FnOnce(&'data T, &'dir ScopedDir<'data, 'dir>) + 'a,
+    {
+        Scope::new(data, |data| {
+            let scoped = ScopedDir::new(name);
+            init(data, &scoped);
+            scoped.into_entry()
+        })
+    }
+}
+
 impl<T> Deref for Scope<T> {
     type Target = T;
     fn deref(&self) -> &T {
@@ -348,3 +426,169 @@ fn deref(&self) -> &T {
         &self.scope
     }
 }
+
+/// A handle to a directory which will live at most `'dir`, accessing data that will live for at
+/// least `'data`.
+///
+/// Dropping a ScopedDir will not delete or clean it up, this is expected to occur through dropping
+/// the `Scope` that created it.
+pub struct ScopedDir<'data, 'dir> {
+    #[cfg(CONFIG_DEBUG_FS)]
+    entry: ManuallyDrop<Entry<'dir>>,
+    _phantom: PhantomData<fn(&'data ()) -> &'dir ()>,
+}
+
+impl<'data, 'dir> ScopedDir<'data, 'dir> {
+    /// Creates a subdirectory inside this `ScopedDir`.
+    ///
+    /// The returned directory handle cannot outlive this one.
+    pub fn dir<'dir2>(&'dir2 self, name: &CStr) -> ScopedDir<'data, 'dir2> {
+        #[cfg(not(CONFIG_DEBUG_FS))]
+        let _ = name;
+        ScopedDir {
+            #[cfg(CONFIG_DEBUG_FS)]
+            entry: ManuallyDrop::new(Entry::dir(name, Some(&*self.entry))),
+            _phantom: PhantomData,
+        }
+    }
+
+    fn create_file<T: Sync>(&self, name: &CStr, data: &'data T, vtable: &'static FileOps<T>) {
+        #[cfg(CONFIG_DEBUG_FS)]
+        core::mem::forget(Entry::file(name, &self.entry, data, vtable));
+    }
+
+    /// Creates a read-only file in this directory.
+    ///
+    /// The file's contents are produced by invoking [`Writer::write`]`.
+    ///
+    /// 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 read_only_file<T: Writer + Send + Sync + 'static>(&self, name: &CStr, data: &'data T) {
+        self.create_file(name, data, &T::FILE_OPS)
+    }
+
+    /// Creates a read-only file in this directory, with contents from a callback.
+    ///
+    /// The file contents are generated by calling `f` with `data`.
+    ///
+    ///
+    /// `f` must be a function item or a non-capturing closure.
+    /// This is statically asserted and not a safety requirement.
+    ///
+    /// 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 read_callback_file<T, F>(&self, name: &CStr, data: &'data T, _f: &'static F)
+    where
+        T: Send + Sync + 'static,
+        F: Fn(&T, &mut fmt::Formatter<'_>) -> fmt::Result + Send + Sync,
+    {
+        let vtable = <FormatAdapter<T, F> as ReadFile<_>>::FILE_OPS.adapt();
+        self.create_file(name, data, vtable)
+    }
+
+    /// Creates a read-write file in this directory.
+    ///
+    /// Reading the file uses the [`Writer`] implementation on `data`. Writing to the file uses
+    /// the [`Reader`] implementation on `data`.
+    ///
+    /// 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 read_write_file<T: Writer + Reader + Send + Sync + 'static>(
+        &self,
+        name: &CStr,
+        data: &'data T,
+    ) {
+        let vtable = &<T as ReadWriteFile<_>>::FILE_OPS;
+        self.create_file(name, data, vtable)
+    }
+
+    /// Creates a read-write file in this directory, with logic from callbacks.
+    ///
+    /// Reading from the file is handled by `f`. Writing to the file is handled by `w`.
+    ///
+    /// `f` and `w` must be function items or non-capturing closures.
+    /// This is statically asserted and not a safety requirement.
+    ///
+    /// 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 read_write_callback_file<T, F, W>(
+        &self,
+        name: &CStr,
+        data: &'data T,
+        _f: &'static F,
+        _w: &'static W,
+    ) where
+        T: Send + Sync + 'static,
+        F: Fn(&T, &mut fmt::Formatter<'_>) -> fmt::Result + Send + Sync,
+        W: Fn(&T, &mut UserSliceReader) -> Result<(), Error> + Send + Sync,
+    {
+        let vtable = <WritableAdapter<FormatAdapter<T, F>, W> as ReadWriteFile<_>>::FILE_OPS
+            .adapt()
+            .adapt();
+        self.create_file(name, data, vtable)
+    }
+
+    /// Creates a write-only file in this directory.
+    ///
+    /// Writing to the file uses the [`Reader`] implementation on `data`.
+    ///
+    /// 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 write_only_file<T: Reader + Send + Sync + 'static>(&self, name: &CStr, data: &'data T) {
+        let vtable = &<T as WriteFile<_>>::FILE_OPS;
+        self.create_file(name, data, vtable)
+    }
+
+    /// Creates a write-only file in this directory, with write logic from a callback.
+    ///
+    /// Writing to the file is handled by `w`.
+    ///
+    /// `w` must be a function item or a non-capturing closure.
+    /// This is statically asserted and not a safety requirement.
+    ///
+    /// 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 write_only_callback_file<T, W>(&self, name: &CStr, data: &'data T, _w: &'static W)
+    where
+        T: Send + Sync + 'static,
+        W: Fn(&T, &mut UserSliceReader) -> Result<(), Error> + Send + Sync,
+    {
+        let vtable = &<WritableAdapter<NoWriter<T>, W> as WriteFile<_>>::FILE_OPS
+            .adapt()
+            .adapt();
+        self.create_file(name, data, vtable)
+    }
+
+    fn empty() -> Self {
+        ScopedDir {
+            #[cfg(CONFIG_DEBUG_FS)]
+            entry: ManuallyDrop::new(Entry::empty()),
+            _phantom: PhantomData,
+        }
+    }
+    #[cfg(CONFIG_DEBUG_FS)]
+    fn into_entry(self) -> Entry<'dir> {
+        ManuallyDrop::into_inner(self.entry)
+    }
+    #[cfg(not(CONFIG_DEBUG_FS))]
+    fn into_entry(self) {}
+}
+
+impl<'data> ScopedDir<'data, 'static> {
+    // This is safe, but intentionally not exported due to footgun status. A ScopedDir with no
+    // parent will never be released by default, and needs to have its entry extracted and used
+    // somewhere.
+    fn new(name: &CStr) -> ScopedDir<'data, 'static> {
+        ScopedDir {
+            #[cfg(CONFIG_DEBUG_FS)]
+            entry: ManuallyDrop::new(Entry::dir(name, None)),
+            _phantom: PhantomData,
+        }
+    }
+}
rust/kernel/debugfs/entry.rs +67 -6

120 lines not on this page · raw message

Signature · 1 line
2.51.0.355.g5224444f11-goog
#35 lore raw

PATCH v11 7/7 samples: rust: Add scoped debugfs sample driver

In reply to Matthew Maurer

Adds a new sample driver rust_scoped_debugfs that demonstrates the use of the scoped debugfs APIs.

The driver creates a control directory with two write-only files, create and remove. Writing a name and a series of numbers to create will create a new subdirectory under a dynamic directory. This new subdirectory will contain files that expose the numbers as atomic values.

Writing a name to remove will remove the corresponding subdirectory from the dynamic directory.

This sample serves as an example of how to use the debugfs::Scope and debugfs::ScopedDir APIs to create and manage debugfs entries that are tied to the lifetime of a data structure.

---
 MAINTAINERS                         |   1 +
 samples/rust/Kconfig                |  11 +++
 samples/rust/Makefile               |   1 +
 samples/rust/rust_scoped_debugfs.rs | 134 ++++++++++++++++++++++++++++++++++++
 4 files changed, 147 insertions(+)
MAINTAINERS +1 -0
index 5b6db584a33dd7ee39de3fdd0085d2bd7b7bef0e..2cbe890085dbb6a652623b38dd0eadeeaa127a94 100644
@@ -7482,6 +7482,7 @@ F:	rust/kernel/driver.rs
 F:	rust/kernel/faux.rs
 F:	rust/kernel/platform.rs
 F:	samples/rust/rust_debugfs.rs
+F:	samples/rust/rust_scoped_debugfs.rs
 F:	samples/rust/rust_driver_platform.rs
 F:	samples/rust/rust_driver_faux.rs
 
samples/rust/Kconfig +11 -0
index 01101db41ae31b08a86d048cdd27da8ef9bb23a2..3372935519d658529ee7ba25fb2c3fff6adae8c4 100644
@@ -73,6 +73,17 @@ config SAMPLE_RUST_DEBUGFS
 
 	  If unsure, say N.
 
+config SAMPLE_RUST_SCOPED_DEBUGFS
+	tristate "Scoped DebugFS Test Module"
+	depends on DEBUG_FS
+	help
+	  This option builds the Rust Scoped DebugFS Test module sample.
+
+	  To compile this as a module, choose M here:
+	  the module will be called rust_scoped_debugfs.
+
+	  If unsure, say N.
+
 config SAMPLE_RUST_DRIVER_PCI
 	tristate "PCI Driver"
 	depends on PCI
samples/rust/Makefile +1 -0
index 61276222a99f8cc6d7f84c26d0533b30815ebadd..de10b7f4db3996dc57be813ceb076d050ad8f65a 100644
@@ -5,6 +5,7 @@ obj-$(CONFIG_SAMPLE_RUST_MINIMAL)		+= rust_minimal.o
 obj-$(CONFIG_SAMPLE_RUST_MISC_DEVICE)		+= rust_misc_device.o
 obj-$(CONFIG_SAMPLE_RUST_PRINT)			+= rust_print.o
 obj-$(CONFIG_SAMPLE_RUST_DEBUGFS)		+= rust_debugfs.o
+obj-$(CONFIG_SAMPLE_RUST_SCOPED_DEBUGFS)	+= rust_scoped_debugfs.o
 obj-$(CONFIG_SAMPLE_RUST_DMA)			+= rust_dma.o
 obj-$(CONFIG_SAMPLE_RUST_DRIVER_PCI)		+= rust_driver_pci.o
 obj-$(CONFIG_SAMPLE_RUST_DRIVER_PLATFORM)	+= rust_driver_platform.o
samples/rust/rust_scoped_debugfs.rs new file +134 -0

134 lines not on this page · raw message

Signature · 1 line
2.51.0.355.g5224444f11-goog
#36 lore raw

Re: [PATCH v11 7/7] samples: rust: Add scoped debugfs sample driver

Quoted 16 lines · Matthew Maurer

Adds a new sample driver rust_scoped_debugfs that demonstrates the use of the scoped debugfs APIs.

The driver creates a control directory with two write-only files, create and remove. Writing a name and a series of numbers to create will create a new subdirectory under a dynamic directory. This new subdirectory will contain files that expose the numbers as atomic values.

Writing a name to remove will remove the corresponding subdirectory from the dynamic directory.

This sample serves as an example of how to use the debugfs::Scope and debugfs::ScopedDir APIs to create and manage debugfs entries that are tied to the lifetime of a data structure.

Quoted 6 lines
---
 MAINTAINERS                         |   1 +
 samples/rust/Kconfig                |  11 +++
 samples/rust/Makefile               |   1 +
 samples/rust/rust_scoped_debugfs.rs | 134 ++++++++++++++++++++++++++++++++++++

Nit, should be called "rust_debugfs_scoped.rs" to make it more obvious this is a debugfs thing (noun-verb).

thanks,

greg k-h