Skip to main content

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