kernel/miscdevice.rs
1// SPDX-License-Identifier: GPL-2.0
2
3// Copyright (C) 2024 Google LLC.
4
5//! Miscdevice support.
6//!
7//! C headers: [`include/linux/miscdevice.h`](srctree/include/linux/miscdevice.h).
8//!
9//! Reference: <https://www.kernel.org/doc/html/latest/driver-api/misc_devices.html>
10
11use crate::{
12 bindings,
13 device::Device,
14 error::{to_result, Error, Result, VTABLE_DEFAULT_ERROR},
15 ffi::{c_int, c_long, c_uint, c_ulong},
16 fs::File,
17 prelude::*,
18 seq_file::SeqFile,
19 str::CStr,
20 types::{ForeignOwnable, Opaque},
21};
22use core::{marker::PhantomData, mem::MaybeUninit, pin::Pin};
23
24/// Options for creating a misc device.
25#[derive(Copy, Clone)]
26pub struct MiscDeviceOptions {
27 /// The name of the miscdevice.
28 pub name: &'static CStr,
29}
30
31impl MiscDeviceOptions {
32 /// Create a raw `struct miscdev` ready for registration.
33 pub const fn into_raw<T: MiscDevice>(self) -> bindings::miscdevice {
34 // SAFETY: All zeros is valid for this C type.
35 let mut result: bindings::miscdevice = unsafe { MaybeUninit::zeroed().assume_init() };
36 result.minor = bindings::MISC_DYNAMIC_MINOR as _;
37 result.name = self.name.as_char_ptr();
38 result.fops = create_vtable::<T>();
39 result
40 }
41}
42
43/// A registration of a miscdevice.
44///
45/// # Invariants
46///
47/// `inner` is a registered misc device.
48#[repr(transparent)]
49#[pin_data(PinnedDrop)]
50pub struct MiscDeviceRegistration<T> {
51 #[pin]
52 inner: Opaque<bindings::miscdevice>,
53 _t: PhantomData<T>,
54}
55
56// SAFETY: It is allowed to call `misc_deregister` on a different thread from where you called
57// `misc_register`.
58unsafe impl<T> Send for MiscDeviceRegistration<T> {}
59// SAFETY: All `&self` methods on this type are written to ensure that it is safe to call them in
60// parallel.
61unsafe impl<T> Sync for MiscDeviceRegistration<T> {}
62
63impl<T: MiscDevice> MiscDeviceRegistration<T> {
64 /// Register a misc device.
65 pub fn register(opts: MiscDeviceOptions) -> impl PinInit<Self, Error> {
66 try_pin_init!(Self {
67 inner <- Opaque::try_ffi_init(move |slot: *mut bindings::miscdevice| {
68 // SAFETY: The initializer can write to the provided `slot`.
69 unsafe { slot.write(opts.into_raw::<T>()) };
70
71 // SAFETY: We just wrote the misc device options to the slot. The miscdevice will
72 // get unregistered before `slot` is deallocated because the memory is pinned and
73 // the destructor of this type deallocates the memory.
74 // INVARIANT: If this returns `Ok(())`, then the `slot` will contain a registered
75 // misc device.
76 to_result(unsafe { bindings::misc_register(slot) })
77 }),
78 _t: PhantomData,
79 })
80 }
81
82 /// Returns a raw pointer to the misc device.
83 pub fn as_raw(&self) -> *mut bindings::miscdevice {
84 self.inner.get()
85 }
86
87 /// Access the `this_device` field.
88 pub fn device(&self) -> &Device {
89 // SAFETY: This can only be called after a successful register(), which always
90 // initialises `this_device` with a valid device. Furthermore, the signature of this
91 // function tells the borrow-checker that the `&Device` reference must not outlive the
92 // `&MiscDeviceRegistration<T>` used to obtain it, so the last use of the reference must be
93 // before the underlying `struct miscdevice` is destroyed.
94 unsafe { Device::as_ref((*self.as_raw()).this_device) }
95 }
96}
97
98#[pinned_drop]
99impl<T> PinnedDrop for MiscDeviceRegistration<T> {
100 fn drop(self: Pin<&mut Self>) {
101 // SAFETY: We know that the device is registered by the type invariants.
102 unsafe { bindings::misc_deregister(self.inner.get()) };
103 }
104}
105
106/// Trait implemented by the private data of an open misc device.
107#[vtable]
108pub trait MiscDevice: Sized {
109 /// What kind of pointer should `Self` be wrapped in.
110 type Ptr: ForeignOwnable + Send + Sync;
111
112 /// Called when the misc device is opened.
113 ///
114 /// The returned pointer will be stored as the private data for the file.
115 fn open(_file: &File, _misc: &MiscDeviceRegistration<Self>) -> Result<Self::Ptr>;
116
117 /// Called when the misc device is released.
118 fn release(device: Self::Ptr, _file: &File) {
119 drop(device);
120 }
121
122 /// Handler for ioctls.
123 ///
124 /// The `cmd` argument is usually manipulated using the utilties in [`kernel::ioctl`].
125 ///
126 /// [`kernel::ioctl`]: mod@crate::ioctl
127 fn ioctl(
128 _device: <Self::Ptr as ForeignOwnable>::Borrowed<'_>,
129 _file: &File,
130 _cmd: u32,
131 _arg: usize,
132 ) -> Result<isize> {
133 build_error!(VTABLE_DEFAULT_ERROR)
134 }
135
136 /// Handler for ioctls.
137 ///
138 /// Used for 32-bit userspace on 64-bit platforms.
139 ///
140 /// This method is optional and only needs to be provided if the ioctl relies on structures
141 /// that have different layout on 32-bit and 64-bit userspace. If no implementation is
142 /// provided, then `compat_ptr_ioctl` will be used instead.
143 #[cfg(CONFIG_COMPAT)]
144 fn compat_ioctl(
145 _device: <Self::Ptr as ForeignOwnable>::Borrowed<'_>,
146 _file: &File,
147 _cmd: u32,
148 _arg: usize,
149 ) -> Result<isize> {
150 build_error!(VTABLE_DEFAULT_ERROR)
151 }
152
153 /// Show info for this fd.
154 fn show_fdinfo(
155 _device: <Self::Ptr as ForeignOwnable>::Borrowed<'_>,
156 _m: &SeqFile,
157 _file: &File,
158 ) {
159 build_error!(VTABLE_DEFAULT_ERROR)
160 }
161}
162
163const fn create_vtable<T: MiscDevice>() -> &'static bindings::file_operations {
164 const fn maybe_fn<T: Copy>(check: bool, func: T) -> Option<T> {
165 if check {
166 Some(func)
167 } else {
168 None
169 }
170 }
171
172 struct VtableHelper<T: MiscDevice> {
173 _t: PhantomData<T>,
174 }
175 impl<T: MiscDevice> VtableHelper<T> {
176 const VTABLE: bindings::file_operations = bindings::file_operations {
177 open: Some(fops_open::<T>),
178 release: Some(fops_release::<T>),
179 unlocked_ioctl: maybe_fn(T::HAS_IOCTL, fops_ioctl::<T>),
180 #[cfg(CONFIG_COMPAT)]
181 compat_ioctl: if T::HAS_COMPAT_IOCTL {
182 Some(fops_compat_ioctl::<T>)
183 } else if T::HAS_IOCTL {
184 Some(bindings::compat_ptr_ioctl)
185 } else {
186 None
187 },
188 show_fdinfo: maybe_fn(T::HAS_SHOW_FDINFO, fops_show_fdinfo::<T>),
189 // SAFETY: All zeros is a valid value for `bindings::file_operations`.
190 ..unsafe { MaybeUninit::zeroed().assume_init() }
191 };
192 }
193
194 &VtableHelper::<T>::VTABLE
195}
196
197/// # Safety
198///
199/// `file` and `inode` must be the file and inode for a file that is undergoing initialization.
200/// The file must be associated with a `MiscDeviceRegistration<T>`.
201unsafe extern "C" fn fops_open<T: MiscDevice>(
202 inode: *mut bindings::inode,
203 raw_file: *mut bindings::file,
204) -> c_int {
205 // SAFETY: The pointers are valid and for a file being opened.
206 let ret = unsafe { bindings::generic_file_open(inode, raw_file) };
207 if ret != 0 {
208 return ret;
209 }
210
211 // SAFETY: The open call of a file can access the private data.
212 let misc_ptr = unsafe { (*raw_file).private_data };
213
214 // SAFETY: This is a miscdevice, so `misc_open()` set the private data to a pointer to the
215 // associated `struct miscdevice` before calling into this method. Furthermore, `misc_open()`
216 // ensures that the miscdevice can't be unregistered and freed during this call to `fops_open`.
217 let misc = unsafe { &*misc_ptr.cast::<MiscDeviceRegistration<T>>() };
218
219 // SAFETY:
220 // * This underlying file is valid for (much longer than) the duration of `T::open`.
221 // * There is no active fdget_pos region on the file on this thread.
222 let file = unsafe { File::from_raw_file(raw_file) };
223
224 let ptr = match T::open(file, misc) {
225 Ok(ptr) => ptr,
226 Err(err) => return err.to_errno(),
227 };
228
229 // This overwrites the private data with the value specified by the user, changing the type of
230 // this file's private data. All future accesses to the private data is performed by other
231 // fops_* methods in this file, which all correctly cast the private data to the new type.
232 //
233 // SAFETY: The open call of a file can access the private data.
234 unsafe { (*raw_file).private_data = ptr.into_foreign() };
235
236 0
237}
238
239/// # Safety
240///
241/// `file` and `inode` must be the file and inode for a file that is being released. The file must
242/// be associated with a `MiscDeviceRegistration<T>`.
243unsafe extern "C" fn fops_release<T: MiscDevice>(
244 _inode: *mut bindings::inode,
245 file: *mut bindings::file,
246) -> c_int {
247 // SAFETY: The release call of a file owns the private data.
248 let private = unsafe { (*file).private_data };
249 // SAFETY: The release call of a file owns the private data.
250 let ptr = unsafe { <T::Ptr as ForeignOwnable>::from_foreign(private) };
251
252 // SAFETY:
253 // * The file is valid for the duration of this call.
254 // * There is no active fdget_pos region on the file on this thread.
255 T::release(ptr, unsafe { File::from_raw_file(file) });
256
257 0
258}
259
260/// # Safety
261///
262/// `file` must be a valid file that is associated with a `MiscDeviceRegistration<T>`.
263unsafe extern "C" fn fops_ioctl<T: MiscDevice>(
264 file: *mut bindings::file,
265 cmd: c_uint,
266 arg: c_ulong,
267) -> c_long {
268 // SAFETY: The ioctl call of a file can access the private data.
269 let private = unsafe { (*file).private_data };
270 // SAFETY: Ioctl calls can borrow the private data of the file.
271 let device = unsafe { <T::Ptr as ForeignOwnable>::borrow(private) };
272
273 // SAFETY:
274 // * The file is valid for the duration of this call.
275 // * There is no active fdget_pos region on the file on this thread.
276 let file = unsafe { File::from_raw_file(file) };
277
278 match T::ioctl(device, file, cmd, arg) {
279 Ok(ret) => ret as c_long,
280 Err(err) => err.to_errno() as c_long,
281 }
282}
283
284/// # Safety
285///
286/// `file` must be a valid file that is associated with a `MiscDeviceRegistration<T>`.
287#[cfg(CONFIG_COMPAT)]
288unsafe extern "C" fn fops_compat_ioctl<T: MiscDevice>(
289 file: *mut bindings::file,
290 cmd: c_uint,
291 arg: c_ulong,
292) -> c_long {
293 // SAFETY: The compat ioctl call of a file can access the private data.
294 let private = unsafe { (*file).private_data };
295 // SAFETY: Ioctl calls can borrow the private data of the file.
296 let device = unsafe { <T::Ptr as ForeignOwnable>::borrow(private) };
297
298 // SAFETY:
299 // * The file is valid for the duration of this call.
300 // * There is no active fdget_pos region on the file on this thread.
301 let file = unsafe { File::from_raw_file(file) };
302
303 match T::compat_ioctl(device, file, cmd, arg) {
304 Ok(ret) => ret as c_long,
305 Err(err) => err.to_errno() as c_long,
306 }
307}
308
309/// # Safety
310///
311/// - `file` must be a valid file that is associated with a `MiscDeviceRegistration<T>`.
312/// - `seq_file` must be a valid `struct seq_file` that we can write to.
313unsafe extern "C" fn fops_show_fdinfo<T: MiscDevice>(
314 seq_file: *mut bindings::seq_file,
315 file: *mut bindings::file,
316) {
317 // SAFETY: The release call of a file owns the private data.
318 let private = unsafe { (*file).private_data };
319 // SAFETY: Ioctl calls can borrow the private data of the file.
320 let device = unsafe { <T::Ptr as ForeignOwnable>::borrow(private) };
321 // SAFETY:
322 // * The file is valid for the duration of this call.
323 // * There is no active fdget_pos region on the file on this thread.
324 let file = unsafe { File::from_raw_file(file) };
325 // SAFETY: The caller ensures that the pointer is valid and exclusive for the duration in which
326 // this method is called.
327 let m = unsafe { SeqFile::from_raw(seq_file) };
328
329 T::show_fdinfo(device, m, file);
330}