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