This repository has been archived by the owner on Mar 7, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 117
/
chrdev.rs
198 lines (179 loc) · 5.88 KB
/
chrdev.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
use core::convert::TryInto;
use core::ops::Range;
use core::{mem, ptr};
use alloc::boxed::Box;
use alloc::vec;
use alloc::vec::Vec;
use crate::bindings;
use crate::c_types;
use crate::error::{Error, KernelResult};
use crate::types::CStr;
use crate::user_ptr::{UserSlicePtr, UserSlicePtrWriter};
pub fn builder(name: &'static CStr, minors: Range<u16>) -> KernelResult<Builder> {
Ok(Builder {
name,
minors,
file_ops: vec![],
})
}
pub struct Builder {
name: &'static CStr,
minors: Range<u16>,
file_ops: Vec<&'static FileOperationsVtable>,
}
impl Builder {
pub fn register_device<T: FileOperations>(mut self) -> Builder {
if self.file_ops.len() >= self.minors.len() {
panic!("More devices registered than minor numbers allocated.")
}
self.file_ops.push(&T::VTABLE);
self
}
pub fn build(self) -> KernelResult<Registration> {
let mut dev: bindings::dev_t = 0;
let res = unsafe {
bindings::alloc_chrdev_region(
&mut dev,
self.minors.start.into(),
self.minors.len().try_into()?,
self.name.as_ptr() as *const c_types::c_char,
)
};
if res != 0 {
return Err(Error::from_kernel_errno(res));
}
// Turn this into a boxed slice immediately because the kernel stores pointers into it, and
// so that data should never be moved.
let mut cdevs = vec![unsafe { mem::zeroed() }; self.file_ops.len()].into_boxed_slice();
for (i, file_op) in self.file_ops.iter().enumerate() {
unsafe {
bindings::cdev_init(&mut cdevs[i], &file_op.0);
cdevs[i].owner = &mut bindings::__this_module;
let rc = bindings::cdev_add(&mut cdevs[i], dev + i as bindings::dev_t, 1);
if rc != 0 {
// Clean up the ones that were allocated.
for j in 0..=i {
bindings::cdev_del(&mut cdevs[j]);
}
bindings::unregister_chrdev_region(dev, self.minors.len() as _);
return Err(Error::from_kernel_errno(rc));
}
}
}
Ok(Registration {
dev,
count: self.minors.len(),
cdevs,
})
}
}
pub struct Registration {
dev: bindings::dev_t,
count: usize,
cdevs: Box<[bindings::cdev]>,
}
// This is safe because Registration doesn't actually expose any methods.
unsafe impl Sync for Registration {}
impl Drop for Registration {
fn drop(&mut self) {
unsafe {
for dev in self.cdevs.iter_mut() {
bindings::cdev_del(dev);
}
bindings::unregister_chrdev_region(self.dev, self.count as _);
}
}
}
pub struct FileOperationsVtable(bindings::file_operations);
unsafe extern "C" fn open_callback<T: FileOperations>(
_inode: *mut bindings::inode,
file: *mut bindings::file,
) -> c_types::c_int {
let f = match T::open() {
Ok(f) => Box::new(f),
Err(e) => return e.to_kernel_errno(),
};
(*file).private_data = Box::into_raw(f) as *mut c_types::c_void;
0
}
unsafe extern "C" fn read_callback<T: FileOperations>(
file: *mut bindings::file,
buf: *mut c_types::c_char,
len: c_types::c_size_t,
offset: *mut bindings::loff_t,
) -> c_types::c_ssize_t {
let mut data = match UserSlicePtr::new(buf as *mut c_types::c_void, len) {
Ok(ptr) => ptr.writer(),
Err(e) => return e.to_kernel_errno() as c_types::c_ssize_t,
};
let f = &*((*file).private_data as *const T);
// TODO: Pass offset to read()?
match f.read(&mut data) {
Ok(()) => {
let written = len - data.len();
(*offset) += written as bindings::loff_t;
written as c_types::c_ssize_t
}
Err(e) => e.to_kernel_errno() as c_types::c_ssize_t,
}
}
unsafe extern "C" fn release_callback<T: FileOperations>(
_inode: *mut bindings::inode,
file: *mut bindings::file,
) -> c_types::c_int {
let ptr = mem::replace(&mut (*file).private_data, ptr::null_mut());
drop(Box::from_raw(ptr as *mut T));
0
}
impl FileOperationsVtable {
pub const fn new<T: FileOperations>() -> FileOperationsVtable {
FileOperationsVtable(bindings::file_operations {
open: Some(open_callback::<T>),
read: Some(read_callback::<T>),
release: Some(release_callback::<T>),
check_flags: None,
#[cfg(not(kernel_4_20_0_or_greater))]
clone_file_range: None,
compat_ioctl: None,
copy_file_range: None,
#[cfg(not(kernel_4_20_0_or_greater))]
dedupe_file_range: None,
fallocate: None,
#[cfg(kernel_4_19_0_or_greater)]
fadvise: None,
fasync: None,
flock: None,
flush: None,
fsync: None,
get_unmapped_area: None,
iterate: None,
iterate_shared: None,
#[cfg(kernel_5_1_0_or_greater)]
iopoll: None,
llseek: None,
lock: None,
mmap: None,
#[cfg(kernel_4_15_0_or_greater)]
mmap_supported_flags: 0,
owner: ptr::null_mut(),
poll: None,
read_iter: None,
#[cfg(kernel_4_20_0_or_greater)]
remap_file_range: None,
sendpage: None,
setfl: None,
setlease: None,
show_fdinfo: None,
splice_read: None,
splice_write: None,
unlocked_ioctl: None,
write: None,
write_iter: None,
})
}
}
pub trait FileOperations: Sync + Sized {
const VTABLE: FileOperationsVtable;
fn open() -> KernelResult<Self>;
fn read(&self, buf: &mut UserSlicePtrWriter) -> KernelResult<()>;
}