kernel/debugfs/
file_ops.rs

1// SPDX-License-Identifier: GPL-2.0
2// Copyright (C) 2025 Google LLC.
3
4use super::{Reader, Writer};
5use crate::debugfs::callback_adapters::Adapter;
6use crate::prelude::*;
7use crate::seq_file::SeqFile;
8use crate::seq_print;
9use crate::uaccess::UserSlice;
10use core::fmt::{Display, Formatter, Result};
11use core::marker::PhantomData;
12
13#[cfg(CONFIG_DEBUG_FS)]
14use core::ops::Deref;
15
16/// # Invariant
17///
18/// `FileOps<T>` will always contain an `operations` which is safe to use for a file backed
19/// off an inode which has a pointer to a `T` in its private data that is safe to convert
20/// into a reference.
21pub(super) struct FileOps<T> {
22    #[cfg(CONFIG_DEBUG_FS)]
23    operations: bindings::file_operations,
24    #[cfg(CONFIG_DEBUG_FS)]
25    mode: u16,
26    _phantom: PhantomData<T>,
27}
28
29impl<T> FileOps<T> {
30    /// # Safety
31    ///
32    /// The caller asserts that the provided `operations` is safe to use for a file whose
33    /// inode has a pointer to `T` in its private data that is safe to convert into a reference.
34    const unsafe fn new(operations: bindings::file_operations, mode: u16) -> Self {
35        Self {
36            #[cfg(CONFIG_DEBUG_FS)]
37            operations,
38            #[cfg(CONFIG_DEBUG_FS)]
39            mode,
40            _phantom: PhantomData,
41        }
42    }
43
44    #[cfg(CONFIG_DEBUG_FS)]
45    pub(crate) const fn mode(&self) -> u16 {
46        self.mode
47    }
48}
49
50impl<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
57#[cfg(CONFIG_DEBUG_FS)]
58impl<T> Deref for FileOps<T> {
59    type Target = bindings::file_operations;
60
61    fn deref(&self) -> &Self::Target {
62        &self.operations
63    }
64}
65
66struct WriterAdapter<T>(T);
67
68impl<'a, T: Writer> Display for WriterAdapter<&'a T> {
69    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
70        self.0.write(f)
71    }
72}
73
74/// Implements `open` for `file_operations` via `single_open` to fill out a `seq_file`.
75///
76/// # Safety
77///
78/// * `inode`'s private pointer must point to a value of type `T` which will outlive the `inode`
79///   and will not have any unique references alias it during the call.
80/// * `file` must point to a live, not-yet-initialized file object.
81unsafe extern "C" fn writer_open<T: Writer + Sync>(
82    inode: *mut bindings::inode,
83    file: *mut bindings::file,
84) -> c_int {
85    // SAFETY: The caller ensures that `inode` is a valid pointer.
86    let data = unsafe { (*inode).i_private };
87    // SAFETY:
88    // * `file` is acceptable by caller precondition.
89    // * `print_act` will be called on a `seq_file` with private data set to the third argument,
90    //   so we meet its safety requirements.
91    // * The `data` pointer passed in the third argument is a valid `T` pointer that outlives
92    //   this call by caller preconditions.
93    unsafe { bindings::single_open(file, Some(writer_act::<T>), data) }
94}
95
96/// Prints private data stashed in a seq_file to that seq file.
97///
98/// # Safety
99///
100/// `seq` must point to a live `seq_file` whose private data is a valid pointer to a `T` which may
101/// not have any unique references alias it during the call.
102unsafe extern "C" fn writer_act<T: Writer + Sync>(
103    seq: *mut bindings::seq_file,
104    _: *mut c_void,
105) -> c_int {
106    // SAFETY: By caller precondition, this pointer is valid pointer to a `T`, and
107    // there are not and will not be any unique references until we are done.
108    let data = unsafe { &*((*seq).private.cast::<T>()) };
109    // SAFETY: By caller precondition, `seq_file` points to a live `seq_file`, so we can lift
110    // it.
111    let seq_file = unsafe { SeqFile::from_raw(seq) };
112    seq_print!(seq_file, "{}", WriterAdapter(data));
113    0
114}
115
116// Work around lack of generic const items.
117pub(crate) trait ReadFile<T> {
118    const FILE_OPS: FileOps<T>;
119}
120
121impl<T: Writer + Sync> ReadFile<T> for T {
122    const FILE_OPS: FileOps<T> = {
123        let operations = bindings::file_operations {
124            read: Some(bindings::seq_read),
125            llseek: Some(bindings::seq_lseek),
126            release: Some(bindings::single_release),
127            open: Some(writer_open::<Self>),
128            // SAFETY: `file_operations` supports zeroes in all fields.
129            ..unsafe { core::mem::zeroed() }
130        };
131        // SAFETY: `operations` is all stock `seq_file` implementations except for `writer_open`.
132        // `open`'s only requirement beyond what is provided to all open functions is that the
133        // inode's data pointer must point to a `T` that will outlive it, which matches the
134        // `FileOps` requirements.
135        unsafe { FileOps::new(operations, 0o400) }
136    };
137}
138
139fn read<T: Reader + Sync>(data: &T, buf: *const c_char, count: usize) -> isize {
140    let mut reader = UserSlice::new(UserPtr::from_ptr(buf as *mut c_void), count).reader();
141
142    if let Err(e) = data.read_from_slice(&mut reader) {
143        return e.to_errno() as isize;
144    }
145
146    count as isize
147}
148
149/// # Safety
150///
151/// `file` must be a valid pointer to a `file` struct.
152/// The `private_data` of the file must contain a valid pointer to a `seq_file` whose
153/// `private` data in turn points to a `T` that implements `Reader`.
154/// `buf` must be a valid user-space buffer.
155pub(crate) unsafe extern "C" fn write<T: Reader + Sync>(
156    file: *mut bindings::file,
157    buf: *const c_char,
158    count: usize,
159    _ppos: *mut bindings::loff_t,
160) -> isize {
161    // SAFETY: The file was opened with `single_open`, which sets `private_data` to a `seq_file`.
162    let seq = unsafe { &mut *((*file).private_data.cast::<bindings::seq_file>()) };
163    // SAFETY: By caller precondition, this pointer is live and points to a value of type `T`.
164    let data = unsafe { &*(seq.private as *const T) };
165    read(data, buf, count)
166}
167
168// A trait to get the file operations for a type.
169pub(crate) trait ReadWriteFile<T> {
170    const FILE_OPS: FileOps<T>;
171}
172
173impl<T: Writer + Reader + Sync> ReadWriteFile<T> for T {
174    const FILE_OPS: FileOps<T> = {
175        let operations = bindings::file_operations {
176            open: Some(writer_open::<T>),
177            read: Some(bindings::seq_read),
178            write: Some(write::<T>),
179            llseek: Some(bindings::seq_lseek),
180            release: Some(bindings::single_release),
181            // SAFETY: `file_operations` supports zeroes in all fields.
182            ..unsafe { core::mem::zeroed() }
183        };
184        // SAFETY: `operations` is all stock `seq_file` implementations except for `writer_open`
185        // and `write`.
186        // `writer_open`'s only requirement beyond what is provided to all open functions is that
187        // the inode's data pointer must point to a `T` that will outlive it, which matches the
188        // `FileOps` requirements.
189        // `write` only requires that the file's private data pointer points to `seq_file`
190        // which points to a `T` that will outlive it, which matches what `writer_open`
191        // provides.
192        unsafe { FileOps::new(operations, 0o600) }
193    };
194}
195
196/// # Safety
197///
198/// `inode` must be a valid pointer to an `inode` struct.
199/// `file` must be a valid pointer to a `file` struct.
200unsafe extern "C" fn write_only_open(
201    inode: *mut bindings::inode,
202    file: *mut bindings::file,
203) -> c_int {
204    // SAFETY: The caller ensures that `inode` and `file` are valid pointers.
205    unsafe { (*file).private_data = (*inode).i_private };
206    0
207}
208
209/// # Safety
210///
211/// * `file` must be a valid pointer to a `file` struct.
212/// * The `private_data` of the file must contain a valid pointer to a `T` that implements
213///   `Reader`.
214/// * `buf` must be a valid user-space buffer.
215pub(crate) unsafe extern "C" fn write_only_write<T: Reader + Sync>(
216    file: *mut bindings::file,
217    buf: *const c_char,
218    count: usize,
219    _ppos: *mut bindings::loff_t,
220) -> isize {
221    // SAFETY: The caller ensures that `file` is a valid pointer and that `private_data` holds a
222    // valid pointer to `T`.
223    let data = unsafe { &*((*file).private_data as *const T) };
224    read(data, buf, count)
225}
226
227pub(crate) trait WriteFile<T> {
228    const FILE_OPS: FileOps<T>;
229}
230
231impl<T: Reader + Sync> WriteFile<T> for T {
232    const FILE_OPS: FileOps<T> = {
233        let operations = bindings::file_operations {
234            open: Some(write_only_open),
235            write: Some(write_only_write::<T>),
236            llseek: Some(bindings::noop_llseek),
237            // SAFETY: `file_operations` supports zeroes in all fields.
238            ..unsafe { core::mem::zeroed() }
239        };
240        // SAFETY:
241        // * `write_only_open` populates the file private data with the inode private data
242        // * `write_only_write`'s only requirement is that the private data of the file point to
243        //   a `T` and be legal to convert to a shared reference, which `write_only_open`
244        //   satisfies.
245        unsafe { FileOps::new(operations, 0o200) }
246    };
247}