This repository was archived by the owner on Mar 7, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 122
Expand file tree
/
Copy pathchrdev.rs
More file actions
193 lines (172 loc) · 5.6 KB
/
chrdev.rs
File metadata and controls
193 lines (172 loc) · 5.6 KB
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
use core::convert::TryInto;
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::user_ptr::{UserSlicePtr, UserSlicePtrWriter};
pub fn builder(name: &'static str) -> KernelResult<Builder> {
if !name.ends_with('\x00') {
return Err(Error::EINVAL);
}
return Ok(Builder {
name,
0,
file_ops: vec![],
});
}
pub struct Builder {
name: &'static str,
minor_start: u16,
file_ops: Vec<&'static FileOperationsVtable>,
}
impl Builder {
pub fn start_minor_at(&mut self, minor_start: u16) {
self.minor_start = minor_start;
}
pub fn register_device<T: FileOperations>(mut self) -> Builder {
self.file_ops.push(&T::VTABLE);
return self;
}
pub fn build(self) -> KernelResult<Registration> {
let mut dev: bindings::dev_t = 0;
let res = unsafe {
bindings::alloc_chrdev_region(
&mut dev,
self.minor_start.into(),
self.file_ops.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.file_ops.len() as _);
return Err(Error::from_kernel_errno(rc));
}
}
}
return Ok(Registration {
dev,
count: self.file_ops.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;
return 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;
return written as c_types::c_ssize_t;
}
Err(e) => return 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));
return 0;
}
impl FileOperationsVtable {
pub const fn new<T: FileOperations>() -> FileOperationsVtable {
return FileOperationsVtable(bindings::file_operations {
open: Some(open_callback::<T>),
read: Some(read_callback::<T>),
release: Some(release_callback::<T>),
check_flags: None,
clone_file_range: None,
compat_ioctl: None,
copy_file_range: None,
dedupe_file_range: None,
fallocate: None,
fasync: None,
flock: None,
flush: None,
fsync: None,
get_unmapped_area: None,
iterate: None,
iterate_shared: None,
llseek: None,
lock: None,
mmap: None,
#[cfg(kernel_4_15_0_or_greataer)]
mmap_supported_flags: 0,
owner: ptr::null_mut(),
poll: None,
read_iter: 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<()>;
}