Re: [PATCH v6 3/5] rust: debugfs: Support arbitrary owned backing for File
From: Alice Ryhl
Date: Wed Jun 18 2025 - 04:19:25 EST
On Wed, Jun 18, 2025 at 02:28:15AM +0000, Matthew Maurer wrote:
> This allows `File`s to be backed by `Deref<Target=T>` rather than just
> `&'static T`. This means that dynamically allocated objects can be
> attached to `File`s without needing to take extra steps to create a
> pinned reference that's guaranteed to live long enough.
>
> Signed-off-by: Matthew Maurer <mmaurer@xxxxxxxxxx>
> ---
> rust/kernel/debugfs.rs | 51 ++++++++++++++++++++++++++++++++++++++------------
> 1 file changed, 39 insertions(+), 12 deletions(-)
>
> diff --git a/rust/kernel/debugfs.rs b/rust/kernel/debugfs.rs
> index 6a89557d8cf49327d2984d15741ffb6640defd70..cd83f21cf2818f406575941ebbc6c426575643e4 100644
> --- a/rust/kernel/debugfs.rs
> +++ b/rust/kernel/debugfs.rs
> @@ -5,12 +5,13 @@
> //!
> //! C header: [`include/linux/debugfs.h`](srctree/include/linux/debugfs.h)
>
> -#[cfg(CONFIG_DEBUG_FS)]
> +use crate::alloc::KBox;
> use crate::prelude::GFP_KERNEL;
> use crate::str::CStr;
> #[cfg(CONFIG_DEBUG_FS)]
> use crate::sync::Arc;
> use core::fmt::Display;
> +use core::ops::Deref;
>
> #[cfg(CONFIG_DEBUG_FS)]
> mod display_file;
> @@ -61,40 +62,59 @@ fn create(_name: &CStr, _parent: Option<&Dir>) -> Self {
> }
>
> #[cfg(CONFIG_DEBUG_FS)]
> - fn create_file<T: Display + Sized>(&self, name: &CStr, data: &'static T) -> File {
> + fn create_file<D: Deref<Target = T> + 'static + Send + Sync, T: Display>(
> + &self,
> + name: &CStr,
> + data: D,
> + ) -> File {
> + let mut file = File {
> + _entry: entry::Entry::empty(),
> + _data: None,
> + };
> + let Some(data) = KBox::new(data, GFP_KERNEL).ok() else {
> + return file;
> + };
We may want to consider using the ForeignOwnable trait here instead. The
trait is implemented by anything that can be converted to/from a void
pointer, so you can:
* When creating the file, convert it to a void pointer that you store in
File and pass to debugfs_create_file_full.
* When displaying the file, create a borrowed version of the void
pointer and display that.
* When freeing the File, convert the void pointer back into an owned
value and drop it.
For cases where a box really is necessary, the user can create a box and
pass it themselves. But if the user already has a pointer type (e.g. and
Arc<T> or &'static T) then they can pass that pointer directly and the
pointer is stored as a void pointer without the Box indirection.
Alice