Re: [PATCH v2 4/4] rust: samples: Add debugfs sample
From: Greg Kroah-Hartman
Date: Thu May 01 2025 - 03:40:24 EST
On Wed, Apr 30, 2025 at 11:31:59PM +0000, Matthew Maurer wrote:
> Provides an example of using the Rust DebugFS bindings.
>
> Signed-off-by: Matthew Maurer <mmaurer@xxxxxxxxxx>
Much nicer, many thanks for this!
Some minor comments on the sample code here. As someone coming from C
with limited Rust experience, I think I do understand it, but I think it
could use a bunch of comments to make it more "obvious" what is
happening, see below.
> +static EXAMPLE: AtomicU32 = AtomicU32::new(8);
Wait, why is this set to 8 and then you automatically set it to 10 after
you create the file? No one is ever going to see 8 as a valid value
unless they really race to read the file, right?
> +impl kernel::Module for RustDebugFs {
> + fn init(_this: &'static ThisModule) -> Result<Self> {
> + let debugfs = Dir::new(c_str!("sample_debugfs"));
> + debugfs
> + .fmt_file(c_str!("example"), &EXAMPLE, &|example, f| {
> + writeln!(f, "Reading atomic: {}", example.load(Ordering::Relaxed))
> + })
> + .keep();
> + EXAMPLE.store(10, Ordering::Relaxed);
> + Ok(Self { _debugfs: debugfs })
> + }
> +}
How about this rewrite with comments added to help make things more
obvious:
impl kernel::Module for RustDebugFs {
fn init(_this: &'static ThisModule) -> Result<Self> {
// Create a debugfs directory in the root of the filesystem
// called "sample_debugfs"
let debugfs = Dir::new(c_str!("sample_debugfs"));
// Create a single file in the directory called "example" that
// allows to read from the EXAMPLE atomic variable, and make
// sure it lives past the scope of this function by calling
// .keep() on it.
debugfs
.fmt_file(c_str!("example"), &EXAMPLE, &|example, f| {
writeln!(f, "Reading atomic: {}", example.load(Ordering::Relaxed))
})
.keep();
// Change the value of EXAMPLE to be 10 so that will be the
// value read from the file. Note, the original value 8 will be
// read if the file is read right before this is called.
EXAMPLE.store(10, Ordering::Relaxed);
// Create our module object and save off the pointer to the
// debugfs directory we created. It will be automatically
// removed when the module is unloaded by virtue of the
// reference count to the structure being dropped at that point
// in time.
Ok(Self { _debugfs: debugfs })
}
}
thanks,
greg k-h