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 mm::virt::VmaNew,
18 prelude::*,
19 seq_file::SeqFile,
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 ffi::c_int;
37 result.name = self.name.as_char_ptr();
38 result.fops = MiscdeviceVTable::<T>::build();
39 result
40 }
41}
42
43/// A registration of a miscdevice.
44///
45/// # Invariants
46///
47/// - `inner` contains a `struct miscdevice` that is registered using
48/// `misc_register()`.
49/// - This registration remains valid for the entire lifetime of the
50/// [`MiscDeviceRegistration`] instance.
51/// - Deregistration occurs exactly once in [`Drop`] via `misc_deregister()`.
52/// - `inner` wraps a valid, pinned `miscdevice` created using
53/// [`MiscDeviceOptions::into_raw`].
54#[repr(transparent)]
55#[pin_data(PinnedDrop)]
56pub struct MiscDeviceRegistration<T> {
57 #[pin]
58 inner: Opaque<bindings::miscdevice>,
59 _t: PhantomData<T>,
60}
61
62// SAFETY: It is allowed to call `misc_deregister` on a different thread from where you called
63// `misc_register`.
64unsafe impl<T> Send for MiscDeviceRegistration<T> {}
65// SAFETY: All `&self` methods on this type are written to ensure that it is safe to call them in
66// parallel.
67unsafe impl<T> Sync for MiscDeviceRegistration<T> {}
68
69impl<T: MiscDevice> MiscDeviceRegistration<T> {
70 /// Register a misc device.
71 pub fn register(opts: MiscDeviceOptions) -> impl PinInit<Self, Error> {
72 try_pin_init!(Self {
73 inner <- Opaque::try_ffi_init(move |slot: *mut bindings::miscdevice| {
74 // SAFETY: The initializer can write to the provided `slot`.
75 unsafe { slot.write(opts.into_raw::<T>()) };
76
77 // SAFETY: We just wrote the misc device options to the slot. The miscdevice will
78 // get unregistered before `slot` is deallocated because the memory is pinned and
79 // the destructor of this type deallocates the memory.
80 // INVARIANT: If this returns `Ok(())`, then the `slot` will contain a registered
81 // misc device.
82 to_result(unsafe { bindings::misc_register(slot) })
83 }),
84 _t: PhantomData,
85 })
86 }
87
88 /// Returns a raw pointer to the misc device.
89 pub fn as_raw(&self) -> *mut bindings::miscdevice {
90 self.inner.get()
91 }
92
93 /// Access the `this_device` field.
94 pub fn device(&self) -> &Device {
95 // SAFETY: This can only be called after a successful register(), which always
96 // initialises `this_device` with a valid device. Furthermore, the signature of this
97 // function tells the borrow-checker that the `&Device` reference must not outlive the
98 // `&MiscDeviceRegistration<T>` used to obtain it, so the last use of the reference must be
99 // before the underlying `struct miscdevice` is destroyed.
100 unsafe { Device::from_raw((*self.as_raw()).this_device) }
101 }
102}
103
104#[pinned_drop]
105impl<T> PinnedDrop for MiscDeviceRegistration<T> {
106 fn drop(self: Pin<&mut Self>) {
107 // SAFETY: We know that the device is registered by the type invariants.
108 unsafe { bindings::misc_deregister(self.inner.get()) };
109 }
110}
111
112/// Trait implemented by the private data of an open misc device.
113#[vtable]
114pub trait MiscDevice: Sized {
115 /// What kind of pointer should `Self` be wrapped in.
116 type Ptr: ForeignOwnable + Send + Sync;
117
118 /// Called when the misc device is opened.
119 ///
120 /// The returned pointer will be stored as the private data for the file.
121 fn open(_file: &File, _misc: &MiscDeviceRegistration<Self>) -> Result<Self::Ptr>;
122
123 /// Called when the misc device is released.
124 fn release(device: Self::Ptr, _file: &File) {
125 drop(device);
126 }
127
128 /// Handle for mmap.
129 ///
130 /// This function is invoked when a user space process invokes the `mmap` system call on
131 /// `file`. The function is a callback that is part of the VMA initializer. The kernel will do
132 /// initial setup of the VMA before calling this function. The function can then interact with
133 /// the VMA initialization by calling methods of `vma`. If the function does not return an
134 /// error, the kernel will complete initialization of the VMA according to the properties of
135 /// `vma`.
136 fn mmap(
137 _device: <Self::Ptr as ForeignOwnable>::Borrowed<'_>,
138 _file: &File,
139 _vma: &VmaNew,
140 ) -> Result {
141 build_error!(VTABLE_DEFAULT_ERROR)
142 }
143
144 /// Handler for ioctls.
145 ///
146 /// The `cmd` argument is usually manipulated using the utilities in [`kernel::ioctl`].
147 ///
148 /// [`kernel::ioctl`]: mod@crate::ioctl
149 fn ioctl(
150 _device: <Self::Ptr as ForeignOwnable>::Borrowed<'_>,
151 _file: &File,
152 _cmd: u32,
153 _arg: usize,
154 ) -> Result<isize> {
155 build_error!(VTABLE_DEFAULT_ERROR)
156 }
157
158 /// Handler for ioctls.
159 ///
160 /// Used for 32-bit userspace on 64-bit platforms.
161 ///
162 /// This method is optional and only needs to be provided if the ioctl relies on structures
163 /// that have different layout on 32-bit and 64-bit userspace. If no implementation is
164 /// provided, then `compat_ptr_ioctl` will be used instead.
165 #[cfg(CONFIG_COMPAT)]
166 fn compat_ioctl(
167 _device: <Self::Ptr as ForeignOwnable>::Borrowed<'_>,
168 _file: &File,
169 _cmd: u32,
170 _arg: usize,
171 ) -> Result<isize> {
172 build_error!(VTABLE_DEFAULT_ERROR)
173 }
174
175 /// Show info for this fd.
176 fn show_fdinfo(
177 _device: <Self::Ptr as ForeignOwnable>::Borrowed<'_>,
178 _m: &SeqFile,
179 _file: &File,
180 ) {
181 build_error!(VTABLE_DEFAULT_ERROR)
182 }
183}
184
185/// A vtable for the file operations of a Rust miscdevice.
186struct MiscdeviceVTable<T: MiscDevice>(PhantomData<T>);
187
188impl<T: MiscDevice> MiscdeviceVTable<T> {
189 /// # Safety
190 ///
191 /// `file` and `inode` must be the file and inode for a file that is undergoing initialization.
192 /// The file must be associated with a `MiscDeviceRegistration<T>`.
193 unsafe extern "C" fn open(inode: *mut bindings::inode, raw_file: *mut bindings::file) -> c_int {
194 // SAFETY: The pointers are valid and for a file being opened.
195 let ret = unsafe { bindings::generic_file_open(inode, raw_file) };
196 if ret != 0 {
197 return ret;
198 }
199
200 // SAFETY: The open call of a file can access the private data.
201 let misc_ptr = unsafe { (*raw_file).private_data };
202
203 // SAFETY: This is a miscdevice, so `misc_open()` set the private data to a pointer to the
204 // associated `struct miscdevice` before calling into this method. Furthermore,
205 // `misc_open()` ensures that the miscdevice can't be unregistered and freed during this
206 // call to `fops_open`.
207 let misc = unsafe { &*misc_ptr.cast::<MiscDeviceRegistration<T>>() };
208
209 // SAFETY:
210 // * This underlying file is valid for (much longer than) the duration of `T::open`.
211 // * There is no active fdget_pos region on the file on this thread.
212 let file = unsafe { File::from_raw_file(raw_file) };
213
214 let ptr = match T::open(file, misc) {
215 Ok(ptr) => ptr,
216 Err(err) => return err.to_errno(),
217 };
218
219 // This overwrites the private data with the value specified by the user, changing the type
220 // of this file's private data. All future accesses to the private data is performed by
221 // other fops_* methods in this file, which all correctly cast the private data to the new
222 // type.
223 //
224 // SAFETY: The open call of a file can access the private data.
225 unsafe { (*raw_file).private_data = ptr.into_foreign() };
226
227 0
228 }
229
230 /// # Safety
231 ///
232 /// `file` and `inode` must be the file and inode for a file that is being released. The file
233 /// must be associated with a `MiscDeviceRegistration<T>`.
234 unsafe extern "C" fn release(_inode: *mut bindings::inode, file: *mut bindings::file) -> c_int {
235 // SAFETY: The release call of a file owns the private data.
236 let private = unsafe { (*file).private_data };
237 // SAFETY: The release call of a file owns the private data.
238 let ptr = unsafe { <T::Ptr as ForeignOwnable>::from_foreign(private) };
239
240 // SAFETY:
241 // * The file is valid for the duration of this call.
242 // * There is no active fdget_pos region on the file on this thread.
243 T::release(ptr, unsafe { File::from_raw_file(file) });
244
245 0
246 }
247
248 /// # Safety
249 ///
250 /// `file` must be a valid file that is associated with a `MiscDeviceRegistration<T>`.
251 /// `vma` must be a vma that is currently being mmap'ed with this file.
252 unsafe extern "C" fn mmap(
253 file: *mut bindings::file,
254 vma: *mut bindings::vm_area_struct,
255 ) -> c_int {
256 // SAFETY: The mmap call of a file can access the private data.
257 let private = unsafe { (*file).private_data };
258 // SAFETY: This is a Rust Miscdevice, so we call `into_foreign` in `open` and
259 // `from_foreign` in `release`, and `fops_mmap` is guaranteed to be called between those
260 // two operations.
261 let device = unsafe { <T::Ptr as ForeignOwnable>::borrow(private.cast()) };
262 // SAFETY: The caller provides a vma that is undergoing initial VMA setup.
263 let area = unsafe { VmaNew::from_raw(vma) };
264 // SAFETY:
265 // * The file is valid for the duration of this call.
266 // * There is no active fdget_pos region on the file on this thread.
267 let file = unsafe { File::from_raw_file(file) };
268
269 match T::mmap(device, file, area) {
270 Ok(()) => 0,
271 Err(err) => err.to_errno(),
272 }
273 }
274
275 /// # Safety
276 ///
277 /// `file` must be a valid file that is associated with a `MiscDeviceRegistration<T>`.
278 unsafe extern "C" fn ioctl(file: *mut bindings::file, cmd: c_uint, arg: c_ulong) -> c_long {
279 // SAFETY: The ioctl call of a file can access the private data.
280 let private = unsafe { (*file).private_data };
281 // SAFETY: Ioctl calls can borrow the private data of the file.
282 let device = unsafe { <T::Ptr as ForeignOwnable>::borrow(private) };
283
284 // SAFETY:
285 // * The file is valid for the duration of this call.
286 // * There is no active fdget_pos region on the file on this thread.
287 let file = unsafe { File::from_raw_file(file) };
288
289 match T::ioctl(device, file, cmd, arg) {
290 Ok(ret) => ret as c_long,
291 Err(err) => err.to_errno() as c_long,
292 }
293 }
294
295 /// # Safety
296 ///
297 /// `file` must be a valid file that is associated with a `MiscDeviceRegistration<T>`.
298 #[cfg(CONFIG_COMPAT)]
299 unsafe extern "C" fn compat_ioctl(
300 file: *mut bindings::file,
301 cmd: c_uint,
302 arg: c_ulong,
303 ) -> c_long {
304 // SAFETY: The compat ioctl call of a file can access the private data.
305 let private = unsafe { (*file).private_data };
306 // SAFETY: Ioctl calls can borrow the private data of the file.
307 let device = unsafe { <T::Ptr as ForeignOwnable>::borrow(private) };
308
309 // SAFETY:
310 // * The file is valid for the duration of this call.
311 // * There is no active fdget_pos region on the file on this thread.
312 let file = unsafe { File::from_raw_file(file) };
313
314 match T::compat_ioctl(device, file, cmd, arg) {
315 Ok(ret) => ret as c_long,
316 Err(err) => err.to_errno() as c_long,
317 }
318 }
319
320 /// # Safety
321 ///
322 /// - `file` must be a valid file that is associated with a `MiscDeviceRegistration<T>`.
323 /// - `seq_file` must be a valid `struct seq_file` that we can write to.
324 unsafe extern "C" fn show_fdinfo(seq_file: *mut bindings::seq_file, file: *mut bindings::file) {
325 // SAFETY: The release call of a file owns the private data.
326 let private = unsafe { (*file).private_data };
327 // SAFETY: Ioctl calls can borrow the private data of the file.
328 let device = unsafe { <T::Ptr as ForeignOwnable>::borrow(private) };
329 // SAFETY:
330 // * The file is valid for the duration of this call.
331 // * There is no active fdget_pos region on the file on this thread.
332 let file = unsafe { File::from_raw_file(file) };
333 // SAFETY: The caller ensures that the pointer is valid and exclusive for the duration in
334 // which this method is called.
335 let m = unsafe { SeqFile::from_raw(seq_file) };
336
337 T::show_fdinfo(device, m, file);
338 }
339
340 const VTABLE: bindings::file_operations = bindings::file_operations {
341 open: Some(Self::open),
342 release: Some(Self::release),
343 mmap: if T::HAS_MMAP { Some(Self::mmap) } else { None },
344 unlocked_ioctl: if T::HAS_IOCTL {
345 Some(Self::ioctl)
346 } else {
347 None
348 },
349 #[cfg(CONFIG_COMPAT)]
350 compat_ioctl: if T::HAS_COMPAT_IOCTL {
351 Some(Self::compat_ioctl)
352 } else if T::HAS_IOCTL {
353 Some(bindings::compat_ptr_ioctl)
354 } else {
355 None
356 },
357 show_fdinfo: if T::HAS_SHOW_FDINFO {
358 Some(Self::show_fdinfo)
359 } else {
360 None
361 },
362 // SAFETY: All zeros is a valid value for `bindings::file_operations`.
363 ..unsafe { MaybeUninit::zeroed().assume_init() }
364 };
365
366 const fn build() -> &'static bindings::file_operations {
367 &Self::VTABLE
368 }
369}