[PATCH 6/8] rust: debugfs: Implement display_file in terms of fmt_file

Matthew Maurer
2025-04-29T23:16:07Z

fmt_file is fundamentally more flexible, this reduces the number of
unsafe blocks, and allows us to append a newline for display_file which
is a good default.

Previous display_file did not append a newline to ensure that all output
strings, including those without trailing newlines, were an option.

Signed-off-by: Matthew Maurer <mmaurer@google.com>
---
rust/kernel/debugfs.rs | 18 ++++--------------
1 file changed, 4 insertions(+), 14 deletions(-)

diff --git a/rust/kernel/debugfs.rs b/rust/kernel/debugfs.rs
index 2faa59d2dae44ab708cb8fca0d23f06f73a95a3a..835df2b5d7311f278d1d15fc8d688809d0ca363f 100644
--- a/rust/kernel/debugfs.rs
+++ b/rust/kernel/debugfs.rs
@@ -108,7 +108,7 @@ fn as_ptr(&self) -> *mut bindings::dentry {
}

/// Create a file in a DebugFS directory with the provided name, and contents from invoking
- /// [`Display::fmt`] on the provided reference.
+ /// [`Display::fmt`] on the provided reference with a trailing newline.
///
/// # Example
///
@@ -124,8 +124,7 @@ pub fn display_file<T: Display + Sized>(
name: &CStr,
data: &'static T,
) -> Result<ARef<Self>> {
- // SAFETY: As `data` lives for the static lifetime, it outlives the file.
- unsafe { self.display_file_raw(name, data) }
+ self.fmt_file(name, data, &|val, f| write!(f, "{val}\n"))
}

/// Create a file in a DebugFS directory with the provided name, and contents from invoking `f`
@@ -367,7 +366,7 @@ unsafe fn new(inner: &'a Dir) -> Self {
}

/// Create a file in a DebugFS directory with the provided name, and contents from invoking
- /// [`Display::fmt`] on the provided reference.
+ /// [`Display::fmt`] on the provided reference with a trailing newline.
///
/// # Example
///
@@ -384,16 +383,7 @@ unsafe fn new(inner: &'a Dir) -> Self {
/// # Ok::<(), Error>(())
/// ```
pub fn display_file<T: Display + Sized>(&self, name: &CStr, data: &'a T) -> Result<()> {
- // We forget the reference because its reference count is implicitly "owned" by the root
- // builder, which we know will use `debugfs_remove` to clean this up. If we release the
- // file here, it will be immediately deleted.
- // SAFETY:
- // Because `Builder`'s invariant says that our lifetime is how long the directory will
- // be available, and is equivariant, `'a` will outlive the base directory, which will be
- // torn down by `debugfs_remove` to prevent access even if an extra refcount is held
- // somewhere.
- core::mem::forget(unsafe { self.inner.display_file_raw(name, data)? });
- Ok(())
+ self.fmt_file(name, data, &|val, f| write!(f, "{val}\n"))
}

/// Creates a nested directory that may live as long as its parent

--
2.49.0.901.g37484f566f-goog