1 // SPDX-License-Identifier: GPL-2.0
3 // Copyright (C) 2024 Google LLC.
5 //! Miscdevice support.
7 //! C headers: [`include/linux/miscdevice.h`](srctree/include/linux/miscdevice.h).
9 //! Reference: <https://www.kernel.org/doc/html/latest/driver-api/misc_devices.html>
13 error::{to_result, Error, Result, VTABLE_DEFAULT_ERROR},
16 types::{ForeignOwnable, Opaque},
19 ffi::{c_int, c_long, c_uint, c_ulong},
25 /// Options for creating a misc device.
26 #[derive(Copy, Clone)]
27 pub struct MiscDeviceOptions {
28 /// The name of the miscdevice.
29 pub name: &'static CStr,
32 impl MiscDeviceOptions {
33 /// Create a raw `struct miscdev` ready for registration.
34 pub const fn into_raw<T: MiscDevice>(self) -> bindings::miscdevice {
35 // SAFETY: All zeros is valid for this C type.
36 let mut result: bindings::miscdevice = unsafe { MaybeUninit::zeroed().assume_init() };
37 result.minor = bindings::MISC_DYNAMIC_MINOR as _;
38 result.name = self.name.as_char_ptr();
39 result.fops = create_vtable::<T>();
44 /// A registration of a miscdevice.
48 /// `inner` is a registered misc device.
50 #[pin_data(PinnedDrop)]
51 pub struct MiscDeviceRegistration<T> {
53 inner: Opaque<bindings::miscdevice>,
57 // SAFETY: It is allowed to call `misc_deregister` on a different thread from where you called
59 unsafe impl<T> Send for MiscDeviceRegistration<T> {}
60 // SAFETY: All `&self` methods on this type are written to ensure that it is safe to call them in
62 unsafe impl<T> Sync for MiscDeviceRegistration<T> {}
64 impl<T: MiscDevice> MiscDeviceRegistration<T> {
65 /// Register a misc device.
66 pub fn register(opts: MiscDeviceOptions) -> impl PinInit<Self, Error> {
68 inner <- Opaque::try_ffi_init(move |slot: *mut bindings::miscdevice| {
69 // SAFETY: The initializer can write to the provided `slot`.
70 unsafe { slot.write(opts.into_raw::<T>()) };
72 // SAFETY: We just wrote the misc device options to the slot. The miscdevice will
73 // get unregistered before `slot` is deallocated because the memory is pinned and
74 // the destructor of this type deallocates the memory.
75 // INVARIANT: If this returns `Ok(())`, then the `slot` will contain a registered
77 to_result(unsafe { bindings::misc_register(slot) })
83 /// Returns a raw pointer to the misc device.
84 pub fn as_raw(&self) -> *mut bindings::miscdevice {
90 impl<T> PinnedDrop for MiscDeviceRegistration<T> {
91 fn drop(self: Pin<&mut Self>) {
92 // SAFETY: We know that the device is registered by the type invariants.
93 unsafe { bindings::misc_deregister(self.inner.get()) };
97 /// Trait implemented by the private data of an open misc device.
99 pub trait MiscDevice {
100 /// What kind of pointer should `Self` be wrapped in.
101 type Ptr: ForeignOwnable + Send + Sync;
103 /// Called when the misc device is opened.
105 /// The returned pointer will be stored as the private data for the file.
106 fn open() -> Result<Self::Ptr>;
108 /// Called when the misc device is released.
109 fn release(device: Self::Ptr) {
113 /// Handler for ioctls.
115 /// The `cmd` argument is usually manipulated using the utilties in [`kernel::ioctl`].
117 /// [`kernel::ioctl`]: mod@crate::ioctl
119 _device: <Self::Ptr as ForeignOwnable>::Borrowed<'_>,
123 kernel::build_error(VTABLE_DEFAULT_ERROR)
126 /// Handler for ioctls.
128 /// Used for 32-bit userspace on 64-bit platforms.
130 /// This method is optional and only needs to be provided if the ioctl relies on structures
131 /// that have different layout on 32-bit and 64-bit userspace. If no implementation is
132 /// provided, then `compat_ptr_ioctl` will be used instead.
133 #[cfg(CONFIG_COMPAT)]
135 _device: <Self::Ptr as ForeignOwnable>::Borrowed<'_>,
139 kernel::build_error(VTABLE_DEFAULT_ERROR)
143 const fn create_vtable<T: MiscDevice>() -> &'static bindings::file_operations {
144 const fn maybe_fn<T: Copy>(check: bool, func: T) -> Option<T> {
152 struct VtableHelper<T: MiscDevice> {
155 impl<T: MiscDevice> VtableHelper<T> {
156 const VTABLE: bindings::file_operations = bindings::file_operations {
157 open: Some(fops_open::<T>),
158 release: Some(fops_release::<T>),
159 unlocked_ioctl: maybe_fn(T::HAS_IOCTL, fops_ioctl::<T>),
160 #[cfg(CONFIG_COMPAT)]
161 compat_ioctl: if T::HAS_COMPAT_IOCTL {
162 Some(fops_compat_ioctl::<T>)
163 } else if T::HAS_IOCTL {
164 Some(bindings::compat_ptr_ioctl)
168 // SAFETY: All zeros is a valid value for `bindings::file_operations`.
169 ..unsafe { MaybeUninit::zeroed().assume_init() }
173 &VtableHelper::<T>::VTABLE
178 /// `file` and `inode` must be the file and inode for a file that is undergoing initialization.
179 /// The file must be associated with a `MiscDeviceRegistration<T>`.
180 unsafe extern "C" fn fops_open<T: MiscDevice>(
181 inode: *mut bindings::inode,
182 file: *mut bindings::file,
184 // SAFETY: The pointers are valid and for a file being opened.
185 let ret = unsafe { bindings::generic_file_open(inode, file) };
190 let ptr = match T::open() {
192 Err(err) => return err.to_errno(),
195 // SAFETY: The open call of a file owns the private data.
196 unsafe { (*file).private_data = ptr.into_foreign().cast_mut() };
203 /// `file` and `inode` must be the file and inode for a file that is being released. The file must
204 /// be associated with a `MiscDeviceRegistration<T>`.
205 unsafe extern "C" fn fops_release<T: MiscDevice>(
206 _inode: *mut bindings::inode,
207 file: *mut bindings::file,
209 // SAFETY: The release call of a file owns the private data.
210 let private = unsafe { (*file).private_data };
211 // SAFETY: The release call of a file owns the private data.
212 let ptr = unsafe { <T::Ptr as ForeignOwnable>::from_foreign(private) };
221 /// `file` must be a valid file that is associated with a `MiscDeviceRegistration<T>`.
222 unsafe extern "C" fn fops_ioctl<T: MiscDevice>(
223 file: *mut bindings::file,
227 // SAFETY: The ioctl call of a file can access the private data.
228 let private = unsafe { (*file).private_data };
229 // SAFETY: Ioctl calls can borrow the private data of the file.
230 let device = unsafe { <T::Ptr as ForeignOwnable>::borrow(private) };
232 match T::ioctl(device, cmd, arg as usize) {
233 Ok(ret) => ret as c_long,
234 Err(err) => err.to_errno() as c_long,
240 /// `file` must be a valid file that is associated with a `MiscDeviceRegistration<T>`.
241 #[cfg(CONFIG_COMPAT)]
242 unsafe extern "C" fn fops_compat_ioctl<T: MiscDevice>(
243 file: *mut bindings::file,
247 // SAFETY: The compat ioctl call of a file can access the private data.
248 let private = unsafe { (*file).private_data };
249 // SAFETY: Ioctl calls can borrow the private data of the file.
250 let device = unsafe { <T::Ptr as ForeignOwnable>::borrow(private) };
252 match T::compat_ioctl(device, cmd, arg as usize) {
253 Ok(ret) => ret as c_long,
254 Err(err) => err.to_errno() as c_long,