Skip to content

Commit 4a10261

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 fc2b177 commit 4a10261

File tree

7 files changed

+469
-0
lines changed

7 files changed

+469
-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: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
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, types::PointerWrapper, CStr, Error, Result};
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 `T::into_pointer`.
30+
///
31+
/// [`proc_dir_entry`]: ../../../fs/proc/internal.h
32+
pub struct ProcDirEntry<T: PointerWrapper> {
33+
proc_dir_entry: *mut bindings::proc_dir_entry,
34+
data: *const c_types::c_void,
35+
_wrapper: PhantomData<T>,
36+
}
37+
38+
// SAFETY: The `proc_dir_entry` and `data` raw pointers aren't accessible.
39+
unsafe impl<T: PointerWrapper> Sync for ProcDirEntry<T> {}
40+
41+
impl<T: PointerWrapper> Drop for ProcDirEntry<T> {
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 `T::into_pointer`.
50+
unsafe { drop(T::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+
/// # Safety
59+
///
60+
/// The caller must ensure that `T` is the type `seq_ops` expects to be stored in
61+
/// the data of the resulting `proc_dir_entry`.
62+
///
63+
/// [`proc_create_seq_private`]: ../../../fs/proc/generic.c
64+
pub(crate) unsafe fn proc_create_seq_private<T: PointerWrapper>(
65+
name: CStr<'static>,
66+
seq_ops: &'static bindings::seq_operations,
67+
data: T,
68+
) -> Result<ProcDirEntry<T>> {
69+
let data = data.into_pointer();
70+
let name = name.deref().as_ptr() as *const u8 as *const c_types::c_char;
71+
72+
// SAFETY: Calling a C function. `name` is guaranteed to be null terminated
73+
// because it is of type `CStr`.
74+
let proc_dir_entry = bindings::proc_create_seq_private(
75+
name,
76+
0,
77+
ptr::null_mut(),
78+
seq_ops,
79+
0,
80+
data as *mut c_types::c_void,
81+
);
82+
if proc_dir_entry.is_null() {
83+
Err(Error::ENOMEM)
84+
} else {
85+
// INVARIANT: `proc_dir_entry` is a valid pointer.
86+
// The `data` points to the data stored in `proc_dir_entry`, and
87+
// `data` was created by `T::into_pointer`.
88+
Ok(ProcDirEntry {
89+
proc_dir_entry,
90+
data,
91+
_wrapper: PhantomData,
92+
})
93+
}
94+
}

rust/kernel/seq_file.rs

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

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)