Skip to content

Commit 40ecc49

Browse files
maurerDanilo Krummrich
authored andcommitted
rust: debugfs: Add support for callback-based files
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). Signed-off-by: Matthew Maurer <mmaurer@google.com> Tested-by: Dirk Behme <dirk.behme@de.bosch.com> Acked-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> Link: https://lore.kernel.org/r/20250904-debugfs-rust-v11-4-7d12a165685a@google.com [ Fix up Result<(), Error> -> Result. - Danilo ] Signed-off-by: Danilo Krummrich <dakr@kernel.org>
1 parent 839dc1d commit 40ecc49

3 files changed

Lines changed: 219 additions & 0 deletions

File tree

rust/kernel/debugfs.rs

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,16 @@ use crate::prelude::*;
1212
use crate::str::CStr;
1313
#[cfg(CONFIG_DEBUG_FS)]
1414
use crate::sync::Arc;
15+
use crate::uaccess::UserSliceReader;
16+
use core::fmt;
1517
use core::marker::PhantomPinned;
1618
use core::ops::Deref;
1719

1820
mod traits;
1921
pub use traits::{Reader, Writer};
2022

23+
mod callback_adapters;
24+
use callback_adapters::{FormatAdapter, NoWriter, WritableAdapter};
2125
mod file_ops;
2226
use file_ops::{FileOps, ReadFile, ReadWriteFile, WriteFile};
2327
#[cfg(CONFIG_DEBUG_FS)]
@@ -143,6 +147,46 @@ impl Dir {
143147
self.create_file(name, data, file_ops)
144148
}
145149

150+
/// Creates a read-only file in this directory, with contents from a callback.
151+
///
152+
/// `f` must be a function item or a non-capturing closure.
153+
/// This is statically asserted and not a safety requirement.
154+
///
155+
/// # Examples
156+
///
157+
/// ```
158+
/// # use core::sync::atomic::{AtomicU32, Ordering};
159+
/// # use kernel::c_str;
160+
/// # use kernel::debugfs::Dir;
161+
/// # use kernel::prelude::*;
162+
/// # let dir = Dir::new(c_str!("foo"));
163+
/// let file = KBox::pin_init(
164+
/// dir.read_callback_file(c_str!("bar"),
165+
/// AtomicU32::new(3),
166+
/// &|val, f| {
167+
/// let out = val.load(Ordering::Relaxed);
168+
/// writeln!(f, "{out:#010x}")
169+
/// }),
170+
/// GFP_KERNEL)?;
171+
/// // Reading "foo/bar" will show "0x00000003".
172+
/// file.store(10, Ordering::Relaxed);
173+
/// // Reading "foo/bar" will now show "0x0000000a".
174+
/// # Ok::<(), Error>(())
175+
/// ```
176+
pub fn read_callback_file<'a, T, E: 'a, F>(
177+
&'a self,
178+
name: &'a CStr,
179+
data: impl PinInit<T, E> + 'a,
180+
_f: &'static F,
181+
) -> impl PinInit<File<T>, E> + 'a
182+
where
183+
T: Send + Sync + 'static,
184+
F: Fn(&T, &mut fmt::Formatter<'_>) -> fmt::Result + Send + Sync,
185+
{
186+
let file_ops = <FormatAdapter<T, F>>::FILE_OPS.adapt();
187+
self.create_file(name, data, file_ops)
188+
}
189+
146190
/// Creates a read-write file in this directory.
147191
///
148192
/// Reading the file uses the [`Writer`] implementation.
@@ -159,6 +203,31 @@ impl Dir {
159203
self.create_file(name, data, file_ops)
160204
}
161205

206+
/// Creates a read-write file in this directory, with logic from callbacks.
207+
///
208+
/// Reading from the file is handled by `f`. Writing to the file is handled by `w`.
209+
///
210+
/// `f` and `w` must be function items or non-capturing closures.
211+
/// This is statically asserted and not a safety requirement.
212+
pub fn read_write_callback_file<'a, T, E: 'a, F, W>(
213+
&'a self,
214+
name: &'a CStr,
215+
data: impl PinInit<T, E> + 'a,
216+
_f: &'static F,
217+
_w: &'static W,
218+
) -> impl PinInit<File<T>, E> + 'a
219+
where
220+
T: Send + Sync + 'static,
221+
F: Fn(&T, &mut fmt::Formatter<'_>) -> fmt::Result + Send + Sync,
222+
W: Fn(&T, &mut UserSliceReader) -> Result + Send + Sync,
223+
{
224+
let file_ops =
225+
<WritableAdapter<FormatAdapter<T, F>, W> as file_ops::ReadWriteFile<_>>::FILE_OPS
226+
.adapt()
227+
.adapt();
228+
self.create_file(name, data, file_ops)
229+
}
230+
162231
/// Creates a write-only file in this directory.
163232
///
164233
/// The file owns its backing data. Writing to the file uses the [`Reader`]
@@ -175,6 +244,26 @@ impl Dir {
175244
{
176245
self.create_file(name, data, &T::FILE_OPS)
177246
}
247+
248+
/// Creates a write-only file in this directory, with write logic from a callback.
249+
///
250+
/// `w` must be a function item or a non-capturing closure.
251+
/// This is statically asserted and not a safety requirement.
252+
pub fn write_callback_file<'a, T, E: 'a, W>(
253+
&'a self,
254+
name: &'a CStr,
255+
data: impl PinInit<T, E> + 'a,
256+
_w: &'static W,
257+
) -> impl PinInit<File<T>, E> + 'a
258+
where
259+
T: Send + Sync + 'static,
260+
W: Fn(&T, &mut UserSliceReader) -> Result + Send + Sync,
261+
{
262+
let file_ops = <WritableAdapter<NoWriter<T>, W> as WriteFile<_>>::FILE_OPS
263+
.adapt()
264+
.adapt();
265+
self.create_file(name, data, file_ops)
266+
}
178267
}
179268

180269
#[pin_data]
Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
// SPDX-License-Identifier: GPL-2.0
2+
// Copyright (C) 2025 Google LLC.
3+
4+
//! Adapters which allow the user to supply a write or read implementation as a value rather
5+
//! than a trait implementation. If provided, it will override the trait implementation.
6+
7+
use super::{Reader, Writer};
8+
use crate::prelude::*;
9+
use crate::uaccess::UserSliceReader;
10+
use core::fmt;
11+
use core::fmt::Formatter;
12+
use core::marker::PhantomData;
13+
use core::ops::Deref;
14+
15+
/// # Safety
16+
///
17+
/// To implement this trait, it must be safe to cast a `&Self` to a `&Inner`.
18+
/// It is intended for use in unstacking adapters out of `FileOps` backings.
19+
pub(crate) unsafe trait Adapter {
20+
type Inner;
21+
}
22+
23+
/// Adapter to implement `Reader` via a callback with the same representation as `T`.
24+
///
25+
/// * Layer it on top of `WriterAdapter` if you want to add a custom callback for `write`.
26+
/// * Layer it on top of `NoWriter` to pass through any support present on the underlying type.
27+
///
28+
/// # Invariants
29+
///
30+
/// If an instance for `WritableAdapter<_, W>` is constructed, `W` is inhabited.
31+
#[repr(transparent)]
32+
pub(crate) struct WritableAdapter<D, W> {
33+
inner: D,
34+
_writer: PhantomData<W>,
35+
}
36+
37+
// SAFETY: Stripping off the adapter only removes constraints
38+
unsafe impl<D, W> Adapter for WritableAdapter<D, W> {
39+
type Inner = D;
40+
}
41+
42+
impl<D: Writer, W> Writer for WritableAdapter<D, W> {
43+
fn write(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
44+
self.inner.write(fmt)
45+
}
46+
}
47+
48+
impl<D: Deref, W> Reader for WritableAdapter<D, W>
49+
where
50+
W: Fn(&D::Target, &mut UserSliceReader) -> Result + Send + Sync + 'static,
51+
{
52+
fn read_from_slice(&self, reader: &mut UserSliceReader) -> Result {
53+
// SAFETY: WritableAdapter<_, W> can only be constructed if W is inhabited
54+
let w: &W = unsafe { materialize_zst() };
55+
w(self.inner.deref(), reader)
56+
}
57+
}
58+
59+
/// Adapter to implement `Writer` via a callback with the same representation as `T`.
60+
///
61+
/// # Invariants
62+
///
63+
/// If an instance for `FormatAdapter<_, F>` is constructed, `F` is inhabited.
64+
#[repr(transparent)]
65+
pub(crate) struct FormatAdapter<D, F> {
66+
inner: D,
67+
_formatter: PhantomData<F>,
68+
}
69+
70+
impl<D, F> Deref for FormatAdapter<D, F> {
71+
type Target = D;
72+
fn deref(&self) -> &D {
73+
&self.inner
74+
}
75+
}
76+
77+
impl<D, F> Writer for FormatAdapter<D, F>
78+
where
79+
F: Fn(&D, &mut Formatter<'_>) -> fmt::Result + 'static,
80+
{
81+
fn write(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
82+
// SAFETY: FormatAdapter<_, F> can only be constructed if F is inhabited
83+
let f: &F = unsafe { materialize_zst() };
84+
f(&self.inner, fmt)
85+
}
86+
}
87+
88+
// SAFETY: Stripping off the adapter only removes constraints
89+
unsafe impl<D, F> Adapter for FormatAdapter<D, F> {
90+
type Inner = D;
91+
}
92+
93+
#[repr(transparent)]
94+
pub(crate) struct NoWriter<D> {
95+
inner: D,
96+
}
97+
98+
// SAFETY: Stripping off the adapter only removes constraints
99+
unsafe impl<D> Adapter for NoWriter<D> {
100+
type Inner = D;
101+
}
102+
103+
impl<D> Deref for NoWriter<D> {
104+
type Target = D;
105+
fn deref(&self) -> &D {
106+
&self.inner
107+
}
108+
}
109+
110+
/// For types with a unique value, produce a static reference to it.
111+
///
112+
/// # Safety
113+
///
114+
/// The caller asserts that F is inhabited
115+
unsafe fn materialize_zst<F>() -> &'static F {
116+
const { assert!(core::mem::size_of::<F>() == 0) };
117+
let zst_dangle: core::ptr::NonNull<F> = core::ptr::NonNull::dangling();
118+
// SAFETY: While the pointer is dangling, it is a dangling pointer to a ZST, based on the
119+
// assertion above. The type is also inhabited, by the caller's assertion. This means
120+
// we can materialize it.
121+
unsafe { zst_dangle.as_ref() }
122+
}

rust/kernel/debugfs/file_ops.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
// Copyright (C) 2025 Google LLC.
33

44
use super::{Reader, Writer};
5+
use crate::debugfs::callback_adapters::Adapter;
56
use crate::prelude::*;
67
use crate::seq_file::SeqFile;
78
use crate::seq_print;
@@ -46,6 +47,13 @@ impl<T> FileOps<T> {
4647
}
4748
}
4849

50+
impl<T: Adapter> FileOps<T> {
51+
pub(super) const fn adapt(&self) -> &FileOps<T::Inner> {
52+
// SAFETY: `Adapter` asserts that `T` can be legally cast to `T::Inner`.
53+
unsafe { core::mem::transmute(self) }
54+
}
55+
}
56+
4957
#[cfg(CONFIG_DEBUG_FS)]
5058
impl<T> Deref for FileOps<T> {
5159
type Target = bindings::file_operations;

0 commit comments

Comments
 (0)