xref: /linux/rust/kernel/debugfs/file_ops.rs (revision 5e40b591cb46c0379d5406fa5548c9b2a3801353)
1 // SPDX-License-Identifier: GPL-2.0
2 // Copyright (C) 2025 Google LLC.
3 
4 use super::Writer;
5 use crate::prelude::*;
6 use crate::seq_file::SeqFile;
7 use crate::seq_print;
8 use core::fmt::{Display, Formatter, Result};
9 use core::marker::PhantomData;
10 
11 #[cfg(CONFIG_DEBUG_FS)]
12 use core::ops::Deref;
13 
14 /// # Invariant
15 ///
16 /// `FileOps<T>` will always contain an `operations` which is safe to use for a file backed
17 /// off an inode which has a pointer to a `T` in its private data that is safe to convert
18 /// into a reference.
19 pub(super) struct FileOps<T> {
20     #[cfg(CONFIG_DEBUG_FS)]
21     operations: bindings::file_operations,
22     #[cfg(CONFIG_DEBUG_FS)]
23     mode: u16,
24     _phantom: PhantomData<T>,
25 }
26 
27 impl<T> FileOps<T> {
28     /// # Safety
29     ///
30     /// The caller asserts that the provided `operations` is safe to use for a file whose
31     /// inode has a pointer to `T` in its private data that is safe to convert into a reference.
32     const unsafe fn new(operations: bindings::file_operations, mode: u16) -> Self {
33         Self {
34             #[cfg(CONFIG_DEBUG_FS)]
35             operations,
36             #[cfg(CONFIG_DEBUG_FS)]
37             mode,
38             _phantom: PhantomData,
39         }
40     }
41 
42     #[cfg(CONFIG_DEBUG_FS)]
43     pub(crate) const fn mode(&self) -> u16 {
44         self.mode
45     }
46 }
47 
48 #[cfg(CONFIG_DEBUG_FS)]
49 impl<T> Deref for FileOps<T> {
50     type Target = bindings::file_operations;
51 
52     fn deref(&self) -> &Self::Target {
53         &self.operations
54     }
55 }
56 
57 struct WriterAdapter<T>(T);
58 
59 impl<'a, T: Writer> Display for WriterAdapter<&'a T> {
60     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
61         self.0.write(f)
62     }
63 }
64 
65 /// Implements `open` for `file_operations` via `single_open` to fill out a `seq_file`.
66 ///
67 /// # Safety
68 ///
69 /// * `inode`'s private pointer must point to a value of type `T` which will outlive the `inode`
70 ///   and will not have any unique references alias it during the call.
71 /// * `file` must point to a live, not-yet-initialized file object.
72 unsafe extern "C" fn writer_open<T: Writer + Sync>(
73     inode: *mut bindings::inode,
74     file: *mut bindings::file,
75 ) -> c_int {
76     // SAFETY: The caller ensures that `inode` is a valid pointer.
77     let data = unsafe { (*inode).i_private };
78     // SAFETY:
79     // * `file` is acceptable by caller precondition.
80     // * `print_act` will be called on a `seq_file` with private data set to the third argument,
81     //   so we meet its safety requirements.
82     // * The `data` pointer passed in the third argument is a valid `T` pointer that outlives
83     //   this call by caller preconditions.
84     unsafe { bindings::single_open(file, Some(writer_act::<T>), data) }
85 }
86 
87 /// Prints private data stashed in a seq_file to that seq file.
88 ///
89 /// # Safety
90 ///
91 /// `seq` must point to a live `seq_file` whose private data is a valid pointer to a `T` which may
92 /// not have any unique references alias it during the call.
93 unsafe extern "C" fn writer_act<T: Writer + Sync>(
94     seq: *mut bindings::seq_file,
95     _: *mut c_void,
96 ) -> c_int {
97     // SAFETY: By caller precondition, this pointer is valid pointer to a `T`, and
98     // there are not and will not be any unique references until we are done.
99     let data = unsafe { &*((*seq).private.cast::<T>()) };
100     // SAFETY: By caller precondition, `seq_file` points to a live `seq_file`, so we can lift
101     // it.
102     let seq_file = unsafe { SeqFile::from_raw(seq) };
103     seq_print!(seq_file, "{}", WriterAdapter(data));
104     0
105 }
106 
107 // Work around lack of generic const items.
108 pub(crate) trait ReadFile<T> {
109     const FILE_OPS: FileOps<T>;
110 }
111 
112 impl<T: Writer + Sync> ReadFile<T> for T {
113     const FILE_OPS: FileOps<T> = {
114         let operations = bindings::file_operations {
115             read: Some(bindings::seq_read),
116             llseek: Some(bindings::seq_lseek),
117             release: Some(bindings::single_release),
118             open: Some(writer_open::<Self>),
119             // SAFETY: `file_operations` supports zeroes in all fields.
120             ..unsafe { core::mem::zeroed() }
121         };
122         // SAFETY: `operations` is all stock `seq_file` implementations except for `writer_open`.
123         // `open`'s only requirement beyond what is provided to all open functions is that the
124         // inode's data pointer must point to a `T` that will outlive it, which matches the
125         // `FileOps` requirements.
126         unsafe { FileOps::new(operations, 0o400) }
127     };
128 }
129