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