Skip to content

Commit d285e59

Browse files
committed
seq_file.rs: Rust version of seq_operations
Adds a trait which allows Rust modules to implement the seq_operations interface and use it to create a `/proc` file. Signed-off-by: Adam Bratschi-Kaye <[email protected]>
1 parent 99bec9d commit d285e59

File tree

7 files changed

+454
-0
lines changed

7 files changed

+454
-0
lines changed

rust/kernel/bindings_helper.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,9 @@
33
#include <linux/cdev.h>
44
#include <linux/fs.h>
55
#include <linux/module.h>
6+
#include <linux/proc_fs.h>
67
#include <linux/random.h>
8+
#include <linux/seq_file.h>
79
#include <linux/slab.h>
810
#include <linux/sysctl.h>
911
#include <linux/uaccess.h>

rust/kernel/lib.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,12 @@ pub mod module_param;
5353

5454
pub mod prelude;
5555
pub mod print;
56+
57+
#[cfg(CONFIG_PROC_FS)]
58+
pub mod proc_fs;
59+
5660
pub mod random;
61+
pub mod seq_file;
5762
mod static_assert;
5863
pub mod sync;
5964

rust/kernel/proc_fs.rs

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
// SPDX-License-Identifier: GPL-2.0
2+
3+
//! Type for defining `proc` files.
4+
//!
5+
//! This module allows Rust devices to create entries in `/proc` from a
6+
//! [`bindings::proc_ops`] vtable.
7+
//!
8+
//! C header: [`include/linux/proc_fs.h`](../../../include/linux/proc_fs.h)
9+
//!
10+
//! Reference: <https://www.kernel.org/doc/html/latest/filesystems/proc.html>
11+
12+
use core::{
13+
marker::{PhantomData, Sync},
14+
ops::Deref,
15+
ptr,
16+
};
17+
18+
use crate::{bindings, c_types, file_operations::PointerWrapper, CStr, Error, KernelResult};
19+
20+
/// An entry under `/proc` containing data of type `T`.
21+
///
22+
/// This is the Rust equivalent to [`proc_dir_entry`] on the C side.
23+
///
24+
/// # Invariants
25+
///
26+
/// The [`ProcDirEntry::proc_dir_entry`] is a valid pointer.
27+
/// [`ProcDirEntry::data`] points to the PDE data of
28+
/// [`ProcDirEntry::proc_dir_entry`].
29+
/// [`ProcDirEntry::data`] was created by a call to `W::into_pointer`.
30+
///
31+
/// [`proc_dir_entry`]: ../../../fs/proc/internal.h
32+
pub struct ProcDirEntry<T, W: PointerWrapper<T>> {
33+
proc_dir_entry: *mut bindings::proc_dir_entry,
34+
data: *const T,
35+
_wrapper: PhantomData<W>,
36+
}
37+
38+
// SAFETY: The `proc_dir_entry` and `data` raw pointers aren't accessible.
39+
unsafe impl<T, W: PointerWrapper<T>> Sync for ProcDirEntry<T, W> {}
40+
41+
impl<T, W: PointerWrapper<T>> Drop for ProcDirEntry<T, W> {
42+
fn drop(&mut self) {
43+
// SAFETY: Calling a C function. `proc_dir_entry` is a valid pointer to
44+
// a `bindings::proc_dir_entry` because it was created by a call to
45+
// `proc_create_data` which only returns valid pointers.
46+
unsafe {
47+
bindings::proc_remove(self.proc_dir_entry);
48+
}
49+
// SAFETY: `self.data` was created by a call to `W::into_pointer`.
50+
unsafe { drop(W::from_pointer(self.data)) }
51+
}
52+
}
53+
54+
/// Create a seq_file entry in `/proc` containing data of type `T`.
55+
///
56+
/// Corresponds to [`proc_create_seq_private`] on the C side.
57+
///
58+
/// [`proc_create_seq_private`]: ../../../fs/proc/generic.c
59+
pub(crate) fn proc_create_seq_private<T, W: PointerWrapper<T>>(
60+
name: CStr<'static>,
61+
seq_ops: &'static bindings::seq_operations,
62+
data: W,
63+
) -> KernelResult<ProcDirEntry<T, W>> {
64+
let data = data.into_pointer();
65+
let name = name.deref().as_ptr() as *const u8 as *const c_types::c_char;
66+
67+
// SAFETY: Calling a C function. `name` is guaranteed to be null terminated
68+
// because it is of type `CStr`.
69+
let proc_dir_entry = unsafe {
70+
bindings::proc_create_seq_private(
71+
name,
72+
0,
73+
ptr::null_mut(),
74+
seq_ops,
75+
0,
76+
data as *mut c_types::c_void,
77+
)
78+
};
79+
if proc_dir_entry.is_null() {
80+
Err(Error::ENOMEM)
81+
} else {
82+
// INVARIANT: `proc_dir_entry` is a valid pointer.
83+
// The `data` points to the data stored in `proc_dir_entry`, and
84+
// `data` was created by `W::into_pointer`.
85+
Ok(ProcDirEntry {
86+
proc_dir_entry,
87+
data,
88+
_wrapper: PhantomData,
89+
})
90+
}
91+
}

rust/kernel/seq_file.rs

Lines changed: 190 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,190 @@
1+
// SPDX-License-Identifier: GPL-2.0
2+
3+
//! Trait for defining `seq_file`s.
4+
//!
5+
//! This module allows Rust devices to implement [`struct seq_operations`] and
6+
//! and create a file under `/proc` based on that implementation.
7+
//!
8+
//! C header: [`include/linux/seq_file.h`](../../../include/linux/seq_file.h)
9+
//!
10+
//! Reference: <https://www.kernel.org/doc/html/latest/filesystems/seq_file.html>
11+
12+
// Currently this module is only usable through proc_fs.
13+
#![cfg_attr(not(CONFIG_PROC_FS), allow(dead_code))]
14+
15+
use alloc::boxed::Box;
16+
use core::{
17+
iter::{Iterator, Peekable},
18+
marker::PhantomData,
19+
ptr,
20+
};
21+
22+
use crate::{bindings, c_types, cstr, CStr};
23+
24+
#[cfg(CONFIG_PROC_FS)]
25+
pub use proc::proc_create_seq;
26+
27+
/// Rust equivalent of the [`seq_operations`] interface on the C side.
28+
///
29+
/// # Example
30+
///
31+
/// ```
32+
/// struct Data(&'static [String]);
33+
///
34+
/// impl seq_file::SeqOperations for Data {
35+
/// type Item = &'static String;
36+
/// type Iterator = core::slice::Iter<'static, String>;
37+
///
38+
/// fn start(arg: &Data) -> Option<Box<Peekable<Self::Iterator>>> {
39+
/// let iter = arg.0.iter();
40+
/// Box::try_new(iter.peekable()).ok()
41+
/// }
42+
///
43+
/// fn display(item: &Self::Item) -> &str {
44+
/// &item[..]
45+
/// }
46+
/// }
47+
/// ```
48+
///
49+
/// [`seq_operations`]: ../../../include/linux/seq_file.h
50+
pub trait SeqOperations {
51+
/// Type produced on each iteration.
52+
type Item;
53+
54+
/// Type created when the seq file is opened.
55+
type Iterator: Iterator<Item = Self::Item>;
56+
57+
/// Called once each time the `seq_file` is opened.
58+
fn start(arg: &Self) -> Option<Box<Peekable<Self::Iterator>>>;
59+
60+
/// How the item will be displayed to the reader.
61+
fn display(item: &Self::Item) -> &str;
62+
}
63+
64+
extern "C" fn stop_callback<T: SeqOperations>(
65+
_m: *mut bindings::seq_file,
66+
v: *mut c_types::c_void,
67+
) {
68+
if !v.is_null() {
69+
// SAFETY: `v` was created by a previous call to `next_callback` or
70+
// `start_callback` and both functions return either a null pointer
71+
// or pointer generated by `Box<Peekable<T::Iterator>>::into_raw`.
72+
drop(unsafe { Box::from_raw(v as *mut Peekable<T::Iterator>) })
73+
}
74+
}
75+
76+
extern "C" fn next_callback<T: SeqOperations>(
77+
_m: *mut bindings::seq_file,
78+
v: *mut c_types::c_void,
79+
pos: *mut bindings::loff_t,
80+
) -> *mut c_types::c_void {
81+
if v.is_null() {
82+
return ptr::null_mut();
83+
}
84+
85+
// SAFETY: `v` was created by a previous call to `next_callback` or
86+
// `start_callback` and both functions return either a null pointer
87+
// or pointer generated by `Box<Peekable<T::Iterator>>::into_raw`.
88+
// We already checked for he null pointer case above.
89+
let mut iterator = unsafe { Box::from_raw(v as *mut Peekable<T::Iterator>) };
90+
91+
// SAFETY: The caller guarantees tha `pos` is a valid pointer to an
92+
// `loff_t` and expects this function to mutate the value.
93+
unsafe {
94+
*pos += 1;
95+
}
96+
97+
if iterator.next().is_none() {
98+
return ptr::null_mut();
99+
}
100+
101+
match iterator.peek() {
102+
Some(_next) => Box::into_raw(iterator) as *mut c_types::c_void,
103+
None => ptr::null_mut(),
104+
}
105+
}
106+
107+
extern "C" fn show_callback<T: SeqOperations>(
108+
m: *mut bindings::seq_file,
109+
v: *mut c_types::c_void,
110+
) -> c_types::c_int {
111+
const FORMAT: CStr<'static> = cstr!("%.*s");
112+
// SAFETY: `v` was created by a previous call to `next_callback` or
113+
// `start_callback` and both functions return either a null pointer
114+
// or pointer generated by `Box<Peekable<T::Iterator>>::into_raw`.
115+
if let Some(iterator) = unsafe { (v as *mut Peekable<T::Iterator>).as_mut() } {
116+
if let Some(item) = iterator.peek() {
117+
let s = T::display(item);
118+
// SAFETY: Calling a C function. `FORMAT` is null terminated because
119+
// it comes from a `CStr`. `s` does not need to be null terminated
120+
// because we are only printing the first `s.len()` bytes.
121+
unsafe {
122+
bindings::seq_printf(
123+
m,
124+
FORMAT.as_ptr() as *const c_types::c_char,
125+
s.len(),
126+
s.as_ptr() as *const u8 as *const c_types::c_char,
127+
);
128+
}
129+
}
130+
}
131+
0
132+
}
133+
134+
extern "C" fn start_callback<T: SeqOperations>(
135+
m: *mut bindings::seq_file,
136+
pos: *mut bindings::loff_t,
137+
) -> *mut c_types::c_void {
138+
// SAFETY: This function will be called by opening a proc file generated
139+
// from `proc_create_seq_private` on the C side with data of type `T`. That
140+
// guarantees that that the proc_dir_entry data of the associated inode
141+
// is a valid pointer to `T`.
142+
let arg = unsafe { &*(bindings::PDE_DATA((*(*m).file).f_inode) as *const T) };
143+
// SAFETY: The caller guarantees that `pos` points to a valid `loff_t`.
144+
let pos = unsafe { *pos };
145+
match T::start(arg) {
146+
Some(mut wrapper) => {
147+
for _ in 0..pos {
148+
wrapper.next();
149+
}
150+
match wrapper.peek() {
151+
Some(_next) => Box::into_raw(wrapper) as *mut c_types::c_void,
152+
None => ptr::null_mut(),
153+
}
154+
}
155+
None => ptr::null_mut(),
156+
}
157+
}
158+
159+
struct SeqFileOperationsVTable<T>(PhantomData<T>);
160+
161+
impl<T: SeqOperations> SeqFileOperationsVTable<T> {
162+
const VTABLE: bindings::seq_operations = bindings::seq_operations {
163+
start: Some(start_callback::<T>),
164+
stop: Some(stop_callback::<T>),
165+
next: Some(next_callback::<T>),
166+
show: Some(show_callback::<T>),
167+
};
168+
169+
const fn build() -> &'static bindings::seq_operations {
170+
&Self::VTABLE
171+
}
172+
}
173+
174+
#[cfg(CONFIG_PROC_FS)]
175+
mod proc {
176+
use super::*;
177+
use crate::{
178+
file_operations::PointerWrapper,
179+
proc_fs::{self, ProcDirEntry},
180+
KernelResult,
181+
};
182+
183+
/// Create an entry in `/proc` for a `seq_file`.
184+
pub fn proc_create_seq<T: SeqOperations, W: PointerWrapper<T>>(
185+
name: CStr<'static>,
186+
data: W,
187+
) -> KernelResult<ProcDirEntry<T, W>> {
188+
proc_fs::proc_create_seq_private(name, SeqFileOperationsVTable::<T>::build(), data)
189+
}
190+
}

samples/rust/Kconfig

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,4 +110,15 @@ config SAMPLE_RUST_RANDOM
110110

111111
If unsure, say N.
112112

113+
config SAMPLE_RUST_SEQ_FILE
114+
tristate "Seq file"
115+
depends on PROC_FS
116+
help
117+
This option builds the Rust seq_file sample.
118+
119+
To compile this as a module, choose M here:
120+
the module will be called rust_seq_file.
121+
122+
If unsure, say N.
123+
113124
endif # SAMPLES_RUST

samples/rust/Makefile

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,3 +10,4 @@ obj-$(CONFIG_SAMPLE_RUST_STACK_PROBING) += rust_stack_probing.o
1010
obj-$(CONFIG_SAMPLE_RUST_SEMAPHORE) += rust_semaphore.o
1111
obj-$(CONFIG_SAMPLE_RUST_SEMAPHORE_C) += rust_semaphore_c.o
1212
obj-$(CONFIG_SAMPLE_RUST_RANDOM) += rust_random.o
13+
obj-$(CONFIG_SAMPLE_RUST_SEQ_FILE) += rust_seq_file.o

0 commit comments

Comments
 (0)