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

Matthew Maurer posted 7 patches 1 month, 2 weeks ago
There is a newer version of this series
[PATCH v10 5/7] samples: rust: Add debugfs sample driver
Posted by Matthew Maurer 1 month, 2 weeks ago
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.

Signed-off-by: Matthew Maurer <mmaurer@google.com>
---
 MAINTAINERS                  |   1 +
 samples/rust/Kconfig         |  11 ++++
 samples/rust/Makefile        |   1 +
 samples/rust/rust_debugfs.rs | 151 +++++++++++++++++++++++++++++++++++++++++++
 4 files changed, 164 insertions(+)

diff --git a/MAINTAINERS b/MAINTAINERS
index 8f2dbf71ca3f8f97e4d7619375279ed11d1261b2..5b6db584a33dd7ee39de3fdd0085d2bd7b7bef0e 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -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
 
diff --git a/samples/rust/Kconfig b/samples/rust/Kconfig
index 7f7371a004ee0a8f67dca99c836596709a70c4fa..01101db41ae31b08a86d048cdd27da8ef9bb23a2 100644
--- a/samples/rust/Kconfig
+++ b/samples/rust/Kconfig
@@ -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
diff --git a/samples/rust/Makefile b/samples/rust/Makefile
index bd2faad63b4f3befe7d1ed5139fe25c7a8b6d7f6..61276222a99f8cc6d7f84c26d0533b30815ebadd 100644
--- a/samples/rust/Makefile
+++ b/samples/rust/Makefile
@@ -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
diff --git a/samples/rust/rust_debugfs.rs b/samples/rust/rust_debugfs.rs
new file mode 100644
index 0000000000000000000000000000000000000000..8d394f06b37e69ea1c30a3b0d8444c80562cc5ab
--- /dev/null
+++ b/samples/rust/rust_debugfs.rs
@@ -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>,
+    #[pin]
+    counter: File<AtomicUsize>,
+    #[pin]
+    inner: File<Mutex<Inner>>,
+}
+
+#[derive(Debug)]
+struct Inner {
+    x: u32,
+    y: u32,
+}
+
+impl FromStr for Inner {
+    type Err = Error;
+    fn from_str(s: &str) -> Result<Self> {
+        let mut parts = s.split_whitespace();
+        let x = parts
+            .next()
+            .ok_or(EINVAL)?
+            .parse::<u32>()
+            .map_err(|_| EINVAL)?;
+        let y = parts
+            .next()
+            .ok_or(EINVAL)?
+            .parse::<u32>()
+            .map_err(|_| EINVAL)?;
+        if parts.next().is_some() {
+            return Err(EINVAL);
+        }
+        Ok(Inner { x, y })
+    }
+}
+
+kernel::acpi_device_table!(
+    ACPI_TABLE,
+    MODULE_ACPI_TABLE,
+    <RustDebugFs as platform::Driver>::IdInfo,
+    [(acpi::DeviceId::new(c_str!("LNUXDEBF")), ())]
+);
+
+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);
+        {
+            let mut guard = result.inner.lock();
+            guard.x = guard.y;
+            guard.y = 42;
+        }
+        Ok(result)
+    }
+}
+
+impl RustDebugFs {
+    fn build_counter(dir: &Dir) -> impl PinInit<File<AtomicUsize>> + '_ {
+        dir.read_write_file(c_str!("counter"), AtomicUsize::new(0))
+    }
+
+    fn build_inner(dir: &Dir) -> impl PinInit<File<Mutex<Inner>>> + '_ {
+        dir.read_write_file(c_str!("pair"), new_mutex!(Inner { x: 3, y: 10 }))
+    }
+
+    fn new(pdev: &platform::Device<Core>) -> impl PinInit<Self, Error> + '_ {
+        let debugfs = Dir::new(c_str!("sample_debugfs"));
+        let dev = pdev.as_ref();
+
+        try_pin_init! {
+            Self {
+                _compatible <- debugfs.read_only_file(
+                    c_str!("compatible"),
+                    dev.fwnode()
+                        .ok_or(ENOENT)?
+                        .property_read::<CString>(c_str!("compatible"))
+                        .required_by(dev)?,
+                ),
+                counter <- Self::build_counter(&debugfs),
+                inner <- Self::build_inner(&debugfs),
+                _debugfs: debugfs,
+                pdev: pdev.into(),
+            }
+        }
+    }
+}

-- 
2.51.0.rc1.167.g924127e9c0-goog
Re: [PATCH v10 5/7] samples: rust: Add debugfs sample driver
Posted by Danilo Krummrich 1 month, 2 weeks ago
On Wed Aug 20, 2025 at 12:53 AM CEST, Matthew Maurer wrote:
> 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.
>
> Signed-off-by: Matthew Maurer <mmaurer@google.com>

This is a great example, thanks! I really like how the API turned out.

When it comes to the newly added Scope API - and I assume this does not come at
a surprise - I have some concerns.

But first, thanks a lot for posting the socinfo driver in both variants, with
and without the Scope API.

I had a brief look at both of those and I can see why you want this.

With the Scope thing you can indeed write things a bit more compressed (I think
in the patches the differences looks quite a bit bigger than it actually is,
because the scope-based one uses quite some code from the file-based one).

I think the downsides are mainly:

  - The degree of complexity added for a rather specific use-case, that is also
    perfectly representable with the file-based API.

  - It makes it convinient to expose multiple fields grouped under the same lock
    as separate files, which design wise we shouln't encourage for the reasons
    we discussed in v8.

I think for the sake of getting this series merged, which I would really love to
see, I think we should focus on the file-based API first. Once we got this
landed I think we can still revisit the Scope idea and have some more discussion
about it.

I will have a more detailed look tomorrow (at least for the patches 1-5).

Thanks again for working on this!

- Danilo
Re: [PATCH v10 5/7] samples: rust: Add debugfs sample driver
Posted by Matthew Maurer 1 month, 2 weeks ago
On Tue, Aug 19, 2025 at 5:34 PM Danilo Krummrich <dakr@kernel.org> wrote:
>
> On Wed Aug 20, 2025 at 12:53 AM CEST, Matthew Maurer wrote:
> > 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.
> >
> > Signed-off-by: Matthew Maurer <mmaurer@google.com>
>
> This is a great example, thanks! I really like how the API turned out.
>
> When it comes to the newly added Scope API - and I assume this does not come at
> a surprise - I have some concerns.

Yes, I expected this to be the case, but inspired by some of the
comments about wanting to just create files off fields and forget
about them, I wanted to take one more crack at it.

>
> But first, thanks a lot for posting the socinfo driver in both variants, with
> and without the Scope API.
>
> I had a brief look at both of those and I can see why you want this.
>
> With the Scope thing you can indeed write things a bit more compressed (I think
> in the patches the differences looks quite a bit bigger than it actually is,
> because the scope-based one uses quite some code from the file-based one).
>
> I think the downsides are mainly:
>
>   - The degree of complexity added for a rather specific use-case, that is also
>     perfectly representable with the file-based API.
I don't *think* this is just for this use case - if I just wanted to
improve the DebugFS use case, I'd mostly be looking at additional code
for `pin-init` (adding an `Option` placement + a few ergonomic
improvements to `pin_init` would slim off a large chunk of the code).
The idea here was that a file might not always directly correspond to
a field in a data structure, and the `File` API forces it to be one.
We could decide that forcing every file to be a data structure field
is a good idea, but I'm not certain it is.
>
>   - It makes it convinient to expose multiple fields grouped under the same lock
>     as separate files, which design wise we shouln't encourage for the reasons
>     we discussed in v8.
It's still pretty convenient to do this with `File`. I don't know how
common it'll be in kernel code, but in userspace Rust, `Arc<Mutex<T>>`
is a very common primitive. I would be unsurprised to see someone use
this pattern to expose separate fields as separate files if we go with
the `File` API.
>
> I think for the sake of getting this series merged, which I would really love to
> see, I think we should focus on the file-based API first. Once we got this
> landed I think we can still revisit the Scope idea and have some more discussion
> about it.

This is why I put the scope API and sample as patches on the end chain
of the series - it is possible to merge only the `File`-based API if
that's what we want to do first, and consider the rest later.

>
> I will have a more detailed look tomorrow (at least for the patches 1-5).
>
> Thanks again for working on this!
>
> - Danilo
Re: [PATCH v10 5/7] samples: rust: Add debugfs sample driver
Posted by Benno Lossin 1 month, 2 weeks ago
On Wed Aug 20, 2025 at 2:40 AM CEST, Matthew Maurer wrote:
> On Tue, Aug 19, 2025 at 5:34 PM Danilo Krummrich <dakr@kernel.org> wrote:
>>
>> On Wed Aug 20, 2025 at 12:53 AM CEST, Matthew Maurer wrote:
>> > 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.
>> >
>> > Signed-off-by: Matthew Maurer <mmaurer@google.com>
>>
>> This is a great example, thanks! I really like how the API turned out.
>>
>> When it comes to the newly added Scope API - and I assume this does not come at
>> a surprise - I have some concerns.
>
> Yes, I expected this to be the case, but inspired by some of the
> comments about wanting to just create files off fields and forget
> about them, I wanted to take one more crack at it.
>
>>
>> But first, thanks a lot for posting the socinfo driver in both variants, with
>> and without the Scope API.
>>
>> I had a brief look at both of those and I can see why you want this.
>>
>> With the Scope thing you can indeed write things a bit more compressed (I think
>> in the patches the differences looks quite a bit bigger than it actually is,
>> because the scope-based one uses quite some code from the file-based one).
>>
>> I think the downsides are mainly:
>>
>>   - The degree of complexity added for a rather specific use-case, that is also
>>     perfectly representable with the file-based API.
> I don't *think* this is just for this use case - if I just wanted to
> improve the DebugFS use case, I'd mostly be looking at additional code
> for `pin-init` (adding an `Option` placement + a few ergonomic

`Option` is currently not possible to support, since we can't set solely
the discriminant (it must always be a write to the entire enum, thus
requiring a move), see [1].

[1]: https://github.com/Rust-for-Linux/pin-init/issues/59

> improvements to `pin_init` would slim off a large chunk of the code).

I'd be interested in what kinds of improvements you need, maybe they are
simple enough to just include :)

---
Cheers,
Benno

> The idea here was that a file might not always directly correspond to
> a field in a data structure, and the `File` API forces it to be one.
> We could decide that forcing every file to be a data structure field
> is a good idea, but I'm not certain it is.
Re: [PATCH v10 5/7] samples: rust: Add debugfs sample driver
Posted by Matthew Maurer 1 month, 2 weeks ago
On Tue, Aug 19, 2025 at 5:40 PM Matthew Maurer <mmaurer@google.com> wrote:
>
> On Tue, Aug 19, 2025 at 5:34 PM Danilo Krummrich <dakr@kernel.org> wrote:
> >
> > On Wed Aug 20, 2025 at 12:53 AM CEST, Matthew Maurer wrote:
> > > 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.
> > >
> > > Signed-off-by: Matthew Maurer <mmaurer@google.com>
> >
> > This is a great example, thanks! I really like how the API turned out.
> >
> > When it comes to the newly added Scope API - and I assume this does not come at
> > a surprise - I have some concerns.
>
> Yes, I expected this to be the case, but inspired by some of the
> comments about wanting to just create files off fields and forget
> about them, I wanted to take one more crack at it.
>
> >
> > But first, thanks a lot for posting the socinfo driver in both variants, with
> > and without the Scope API.
> >
> > I had a brief look at both of those and I can see why you want this.
> >
> > With the Scope thing you can indeed write things a bit more compressed (I think
> > in the patches the differences looks quite a bit bigger than it actually is,
> > because the scope-based one uses quite some code from the file-based one).
> >
> > I think the downsides are mainly:
> >
> >   - The degree of complexity added for a rather specific use-case, that is also
> >     perfectly representable with the file-based API.
> I don't *think* this is just for this use case - if I just wanted to
> improve the DebugFS use case, I'd mostly be looking at additional code
Edit: Socinfo use case
> for `pin-init` (adding an `Option` placement + a few ergonomic
> improvements to `pin_init` would slim off a large chunk of the code).
> The idea here was that a file might not always directly correspond to
> a field in a data structure, and the `File` API forces it to be one.
> We could decide that forcing every file to be a data structure field
> is a good idea, but I'm not certain it is.
> >
> >   - It makes it convinient to expose multiple fields grouped under the same lock
> >     as separate files, which design wise we shouln't encourage for the reasons
> >     we discussed in v8.
> It's still pretty convenient to do this with `File`. I don't know how
> common it'll be in kernel code, but in userspace Rust, `Arc<Mutex<T>>`
> is a very common primitive. I would be unsurprised to see someone use
> this pattern to expose separate fields as separate files if we go with
> the `File` API.
> >
> > I think for the sake of getting this series merged, which I would really love to
> > see, I think we should focus on the file-based API first. Once we got this
> > landed I think we can still revisit the Scope idea and have some more discussion
> > about it.
>
> This is why I put the scope API and sample as patches on the end chain
> of the series - it is possible to merge only the `File`-based API if
> that's what we want to do first, and consider the rest later.
>
> >
> > I will have a more detailed look tomorrow (at least for the patches 1-5).
> >
> > Thanks again for working on this!
> >
> > - Danilo