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, Kiocb},
17    iov::{IovIterDest, IovIterSource},
18    mm::virt::VmaNew,
19    prelude::*,
20    seq_file::SeqFile,
21    types::{ForeignOwnable, Opaque},
22};
23use core::{marker::PhantomData, pin::Pin};
24
25/// Options for creating a misc device.
26#[derive(Copy, Clone)]
27pub struct MiscDeviceOptions {
28    /// The name of the miscdevice.
29    pub name: &'static CStr,
30}
31
32impl MiscDeviceOptions {
33    /// Create a raw `struct miscdev` ready for registration.
34    pub const fn into_raw<T: MiscDevice>(self) -> bindings::miscdevice {
35        let mut result: bindings::miscdevice = pin_init::zeroed();
36        result.minor = bindings::MISC_DYNAMIC_MINOR as ffi::c_int;
37        result.name = crate::str::as_char_ptr_in_const_context(self.name);
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    /// Read from this miscdevice.
145    fn read_iter(_kiocb: Kiocb<'_, Self::Ptr>, _iov: &mut IovIterDest<'_>) -> Result<usize> {
146        build_error!(VTABLE_DEFAULT_ERROR)
147    }
148
149    /// Write to this miscdevice.
150    fn write_iter(_kiocb: Kiocb<'_, Self::Ptr>, _iov: &mut IovIterSource<'_>) -> Result<usize> {
151        build_error!(VTABLE_DEFAULT_ERROR)
152    }
153
154    /// Handler for ioctls.
155    ///
156    /// The `cmd` argument is usually manipulated using the utilities in [`kernel::ioctl`].
157    ///
158    /// [`kernel::ioctl`]: mod@crate::ioctl
159    fn ioctl(
160        _device: <Self::Ptr as ForeignOwnable>::Borrowed<'_>,
161        _file: &File,
162        _cmd: u32,
163        _arg: usize,
164    ) -> Result<isize> {
165        build_error!(VTABLE_DEFAULT_ERROR)
166    }
167
168    /// Handler for ioctls.
169    ///
170    /// Used for 32-bit userspace on 64-bit platforms.
171    ///
172    /// This method is optional and only needs to be provided if the ioctl relies on structures
173    /// that have different layout on 32-bit and 64-bit userspace. If no implementation is
174    /// provided, then `compat_ptr_ioctl` will be used instead.
175    #[cfg(CONFIG_COMPAT)]
176    fn compat_ioctl(
177        _device: <Self::Ptr as ForeignOwnable>::Borrowed<'_>,
178        _file: &File,
179        _cmd: u32,
180        _arg: usize,
181    ) -> Result<isize> {
182        build_error!(VTABLE_DEFAULT_ERROR)
183    }
184
185    /// Show info for this fd.
186    fn show_fdinfo(
187        _device: <Self::Ptr as ForeignOwnable>::Borrowed<'_>,
188        _m: &SeqFile,
189        _file: &File,
190    ) {
191        build_error!(VTABLE_DEFAULT_ERROR)
192    }
193}
194
195/// A vtable for the file operations of a Rust miscdevice.
196struct MiscdeviceVTable<T: MiscDevice>(PhantomData<T>);
197
198impl<T: MiscDevice> MiscdeviceVTable<T> {
199    /// # Safety
200    ///
201    /// `file` and `inode` must be the file and inode for a file that is undergoing initialization.
202    /// The file must be associated with a `MiscDeviceRegistration<T>`.
203    unsafe extern "C" fn open(inode: *mut bindings::inode, raw_file: *mut bindings::file) -> c_int {
204        // SAFETY: The pointers are valid and for a file being opened.
205        let ret = unsafe { bindings::generic_file_open(inode, raw_file) };
206        if ret != 0 {
207            return ret;
208        }
209
210        // SAFETY: The open call of a file can access the private data.
211        let misc_ptr = unsafe { (*raw_file).private_data };
212
213        // SAFETY: This is a miscdevice, so `misc_open()` set the private data to a pointer to the
214        // associated `struct miscdevice` before calling into this method. Furthermore,
215        // `misc_open()` ensures that the miscdevice can't be unregistered and freed during this
216        // 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
230        // of this file's private data. All future accesses to the private data is performed by
231        // other fops_* methods in this file, which all correctly cast the private data to the new
232        // type.
233        //
234        // SAFETY: The open call of a file can access the private data.
235        unsafe { (*raw_file).private_data = ptr.into_foreign() };
236
237        0
238    }
239
240    /// # Safety
241    ///
242    /// `file` and `inode` must be the file and inode for a file that is being released. The file
243    /// must be associated with a `MiscDeviceRegistration<T>`.
244    unsafe extern "C" fn release(_inode: *mut bindings::inode, file: *mut bindings::file) -> c_int {
245        // SAFETY: The release call of a file owns the private data.
246        let private = unsafe { (*file).private_data };
247        // SAFETY: The release call of a file owns the private data.
248        let ptr = unsafe { <T::Ptr as ForeignOwnable>::from_foreign(private) };
249
250        // SAFETY:
251        // * The file is valid for the duration of this call.
252        // * There is no active fdget_pos region on the file on this thread.
253        T::release(ptr, unsafe { File::from_raw_file(file) });
254
255        0
256    }
257
258    /// # Safety
259    ///
260    /// `kiocb` must be correspond to a valid file that is associated with a
261    /// `MiscDeviceRegistration<T>`. `iter` must be a valid `struct iov_iter` for writing.
262    unsafe extern "C" fn read_iter(
263        kiocb: *mut bindings::kiocb,
264        iter: *mut bindings::iov_iter,
265    ) -> isize {
266        // SAFETY: The caller provides a valid `struct kiocb` associated with a
267        // `MiscDeviceRegistration<T>` file.
268        let kiocb = unsafe { Kiocb::from_raw(kiocb) };
269        // SAFETY: This is a valid `struct iov_iter` for writing.
270        let iov = unsafe { IovIterDest::from_raw(iter) };
271
272        match T::read_iter(kiocb, iov) {
273            Ok(res) => res as isize,
274            Err(err) => err.to_errno() as isize,
275        }
276    }
277
278    /// # Safety
279    ///
280    /// `kiocb` must be correspond to a valid file that is associated with a
281    /// `MiscDeviceRegistration<T>`. `iter` must be a valid `struct iov_iter` for writing.
282    unsafe extern "C" fn write_iter(
283        kiocb: *mut bindings::kiocb,
284        iter: *mut bindings::iov_iter,
285    ) -> isize {
286        // SAFETY: The caller provides a valid `struct kiocb` associated with a
287        // `MiscDeviceRegistration<T>` file.
288        let kiocb = unsafe { Kiocb::from_raw(kiocb) };
289        // SAFETY: This is a valid `struct iov_iter` for reading.
290        let iov = unsafe { IovIterSource::from_raw(iter) };
291
292        match T::write_iter(kiocb, iov) {
293            Ok(res) => res as isize,
294            Err(err) => err.to_errno() as isize,
295        }
296    }
297
298    /// # Safety
299    ///
300    /// `file` must be a valid file that is associated with a `MiscDeviceRegistration<T>`.
301    /// `vma` must be a vma that is currently being mmap'ed with this file.
302    unsafe extern "C" fn mmap(
303        file: *mut bindings::file,
304        vma: *mut bindings::vm_area_struct,
305    ) -> c_int {
306        // SAFETY: The mmap call of a file can access the private data.
307        let private = unsafe { (*file).private_data };
308        // SAFETY: This is a Rust Miscdevice, so we call `into_foreign` in `open` and
309        // `from_foreign` in `release`, and `fops_mmap` is guaranteed to be called between those
310        // two operations.
311        let device = unsafe { <T::Ptr as ForeignOwnable>::borrow(private.cast()) };
312        // SAFETY: The caller provides a vma that is undergoing initial VMA setup.
313        let area = unsafe { VmaNew::from_raw(vma) };
314        // SAFETY:
315        // * The file is valid for the duration of this call.
316        // * There is no active fdget_pos region on the file on this thread.
317        let file = unsafe { File::from_raw_file(file) };
318
319        match T::mmap(device, file, area) {
320            Ok(()) => 0,
321            Err(err) => err.to_errno(),
322        }
323    }
324
325    /// # Safety
326    ///
327    /// `file` must be a valid file that is associated with a `MiscDeviceRegistration<T>`.
328    unsafe extern "C" fn ioctl(file: *mut bindings::file, cmd: c_uint, arg: c_ulong) -> c_long {
329        // SAFETY: The ioctl call of a file can access the private data.
330        let private = unsafe { (*file).private_data };
331        // SAFETY: Ioctl calls can borrow the private data of the file.
332        let device = unsafe { <T::Ptr as ForeignOwnable>::borrow(private) };
333
334        // SAFETY:
335        // * The file is valid for the duration of this call.
336        // * There is no active fdget_pos region on the file on this thread.
337        let file = unsafe { File::from_raw_file(file) };
338
339        match T::ioctl(device, file, cmd, arg) {
340            Ok(ret) => ret as c_long,
341            Err(err) => err.to_errno() as c_long,
342        }
343    }
344
345    /// # Safety
346    ///
347    /// `file` must be a valid file that is associated with a `MiscDeviceRegistration<T>`.
348    #[cfg(CONFIG_COMPAT)]
349    unsafe extern "C" fn compat_ioctl(
350        file: *mut bindings::file,
351        cmd: c_uint,
352        arg: c_ulong,
353    ) -> c_long {
354        // SAFETY: The compat ioctl call of a file can access the private data.
355        let private = unsafe { (*file).private_data };
356        // SAFETY: Ioctl calls can borrow the private data of the file.
357        let device = unsafe { <T::Ptr as ForeignOwnable>::borrow(private) };
358
359        // SAFETY:
360        // * The file is valid for the duration of this call.
361        // * There is no active fdget_pos region on the file on this thread.
362        let file = unsafe { File::from_raw_file(file) };
363
364        match T::compat_ioctl(device, file, cmd, arg) {
365            Ok(ret) => ret as c_long,
366            Err(err) => err.to_errno() as c_long,
367        }
368    }
369
370    /// # Safety
371    ///
372    /// - `file` must be a valid file that is associated with a `MiscDeviceRegistration<T>`.
373    /// - `seq_file` must be a valid `struct seq_file` that we can write to.
374    unsafe extern "C" fn show_fdinfo(seq_file: *mut bindings::seq_file, file: *mut bindings::file) {
375        // SAFETY: The release call of a file owns the private data.
376        let private = unsafe { (*file).private_data };
377        // SAFETY: Ioctl calls can borrow the private data of the file.
378        let device = unsafe { <T::Ptr as ForeignOwnable>::borrow(private) };
379        // SAFETY:
380        // * The file is valid for the duration of this call.
381        // * There is no active fdget_pos region on the file on this thread.
382        let file = unsafe { File::from_raw_file(file) };
383        // SAFETY: The caller ensures that the pointer is valid and exclusive for the duration in
384        // which this method is called.
385        let m = unsafe { SeqFile::from_raw(seq_file) };
386
387        T::show_fdinfo(device, m, file);
388    }
389
390    const VTABLE: bindings::file_operations = bindings::file_operations {
391        open: Some(Self::open),
392        release: Some(Self::release),
393        mmap: if T::HAS_MMAP { Some(Self::mmap) } else { None },
394        read_iter: if T::HAS_READ_ITER {
395            Some(Self::read_iter)
396        } else {
397            None
398        },
399        write_iter: if T::HAS_WRITE_ITER {
400            Some(Self::write_iter)
401        } else {
402            None
403        },
404        unlocked_ioctl: if T::HAS_IOCTL {
405            Some(Self::ioctl)
406        } else {
407            None
408        },
409        #[cfg(CONFIG_COMPAT)]
410        compat_ioctl: if T::HAS_COMPAT_IOCTL {
411            Some(Self::compat_ioctl)
412        } else if T::HAS_IOCTL {
413            Some(bindings::compat_ptr_ioctl)
414        } else {
415            None
416        },
417        show_fdinfo: if T::HAS_SHOW_FDINFO {
418            Some(Self::show_fdinfo)
419        } else {
420            None
421        },
422        ..pin_init::zeroed()
423    };
424
425    const fn build() -> &'static bindings::file_operations {
426        &Self::VTABLE
427    }
428}