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