// SPDX-License-Identifier: GPL-2.012// Copyright (C) 2024 Google LLC.34//! Miscdevice support.5//!6//! C headers: [`include/linux/miscdevice.h`](srctree/include/linux/miscdevice.h).7//!8//! Reference: <https://www.kernel.org/doc/html/latest/driver-api/misc_devices.html>910use crate::{11bindings,12device::Device,13error::{to_result, Error, Result, VTABLE_DEFAULT_ERROR},14ffi::{c_int, c_long, c_uint, c_ulong},15fs::{File, Kiocb},16iov::{IovIterDest, IovIterSource},17mm::virt::VmaNew,18prelude::*,19seq_file::SeqFile,20types::{ForeignOwnable, Opaque},21};22use core::{marker::PhantomData, mem::MaybeUninit, pin::Pin};2324/// Options for creating a misc device.25#[derive(Copy, Clone)]26pub struct MiscDeviceOptions {27/// The name of the miscdevice.28pub name: &'static CStr,29}3031impl MiscDeviceOptions {32/// Create a raw `struct miscdev` ready for registration.33pub const fn into_raw<T: MiscDevice>(self) -> bindings::miscdevice {34// SAFETY: All zeros is valid for this C type.35let mut result: bindings::miscdevice = unsafe { MaybeUninit::zeroed().assume_init() };36result.minor = bindings::MISC_DYNAMIC_MINOR as ffi::c_int;37result.name = crate::str::as_char_ptr_in_const_context(self.name);38result.fops = MiscdeviceVTable::<T>::build();39result40}41}4243/// A registration of a miscdevice.44///45/// # Invariants46///47/// - `inner` contains a `struct miscdevice` that is registered using48/// `misc_register()`.49/// - This registration remains valid for the entire lifetime of the50/// [`MiscDeviceRegistration`] instance.51/// - Deregistration occurs exactly once in [`Drop`] via `misc_deregister()`.52/// - `inner` wraps a valid, pinned `miscdevice` created using53/// [`MiscDeviceOptions::into_raw`].54#[repr(transparent)]55#[pin_data(PinnedDrop)]56pub struct MiscDeviceRegistration<T> {57#[pin]58inner: Opaque<bindings::miscdevice>,59_t: PhantomData<T>,60}6162// SAFETY: It is allowed to call `misc_deregister` on a different thread from where you called63// `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 in66// parallel.67unsafe impl<T> Sync for MiscDeviceRegistration<T> {}6869impl<T: MiscDevice> MiscDeviceRegistration<T> {70/// Register a misc device.71pub fn register(opts: MiscDeviceOptions) -> impl PinInit<Self, Error> {72try_pin_init!(Self {73inner <- Opaque::try_ffi_init(move |slot: *mut bindings::miscdevice| {74// SAFETY: The initializer can write to the provided `slot`.75unsafe { slot.write(opts.into_raw::<T>()) };7677// SAFETY: We just wrote the misc device options to the slot. The miscdevice will78// get unregistered before `slot` is deallocated because the memory is pinned and79// the destructor of this type deallocates the memory.80// INVARIANT: If this returns `Ok(())`, then the `slot` will contain a registered81// misc device.82to_result(unsafe { bindings::misc_register(slot) })83}),84_t: PhantomData,85})86}8788/// Returns a raw pointer to the misc device.89pub fn as_raw(&self) -> *mut bindings::miscdevice {90self.inner.get()91}9293/// Access the `this_device` field.94pub fn device(&self) -> &Device {95// SAFETY: This can only be called after a successful register(), which always96// initialises `this_device` with a valid device. Furthermore, the signature of this97// function tells the borrow-checker that the `&Device` reference must not outlive the98// `&MiscDeviceRegistration<T>` used to obtain it, so the last use of the reference must be99// before the underlying `struct miscdevice` is destroyed.100unsafe { Device::from_raw((*self.as_raw()).this_device) }101}102}103104#[pinned_drop]105impl<T> PinnedDrop for MiscDeviceRegistration<T> {106fn drop(self: Pin<&mut Self>) {107// SAFETY: We know that the device is registered by the type invariants.108unsafe { bindings::misc_deregister(self.inner.get()) };109}110}111112/// 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.116type Ptr: ForeignOwnable + Send + Sync;117118/// Called when the misc device is opened.119///120/// The returned pointer will be stored as the private data for the file.121fn open(_file: &File, _misc: &MiscDeviceRegistration<Self>) -> Result<Self::Ptr>;122123/// Called when the misc device is released.124fn release(device: Self::Ptr, _file: &File) {125drop(device);126}127128/// Handle for mmap.129///130/// This function is invoked when a user space process invokes the `mmap` system call on131/// `file`. The function is a callback that is part of the VMA initializer. The kernel will do132/// initial setup of the VMA before calling this function. The function can then interact with133/// the VMA initialization by calling methods of `vma`. If the function does not return an134/// error, the kernel will complete initialization of the VMA according to the properties of135/// `vma`.136fn mmap(137_device: <Self::Ptr as ForeignOwnable>::Borrowed<'_>,138_file: &File,139_vma: &VmaNew,140) -> Result {141build_error!(VTABLE_DEFAULT_ERROR)142}143144/// Read from this miscdevice.145fn read_iter(_kiocb: Kiocb<'_, Self::Ptr>, _iov: &mut IovIterDest<'_>) -> Result<usize> {146build_error!(VTABLE_DEFAULT_ERROR)147}148149/// Write to this miscdevice.150fn write_iter(_kiocb: Kiocb<'_, Self::Ptr>, _iov: &mut IovIterSource<'_>) -> Result<usize> {151build_error!(VTABLE_DEFAULT_ERROR)152}153154/// Handler for ioctls.155///156/// The `cmd` argument is usually manipulated using the utilities in [`kernel::ioctl`].157///158/// [`kernel::ioctl`]: mod@crate::ioctl159fn ioctl(160_device: <Self::Ptr as ForeignOwnable>::Borrowed<'_>,161_file: &File,162_cmd: u32,163_arg: usize,164) -> Result<isize> {165build_error!(VTABLE_DEFAULT_ERROR)166}167168/// 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 structures173/// that have different layout on 32-bit and 64-bit userspace. If no implementation is174/// provided, then `compat_ptr_ioctl` will be used instead.175#[cfg(CONFIG_COMPAT)]176fn compat_ioctl(177_device: <Self::Ptr as ForeignOwnable>::Borrowed<'_>,178_file: &File,179_cmd: u32,180_arg: usize,181) -> Result<isize> {182build_error!(VTABLE_DEFAULT_ERROR)183}184185/// Show info for this fd.186fn show_fdinfo(187_device: <Self::Ptr as ForeignOwnable>::Borrowed<'_>,188_m: &SeqFile,189_file: &File,190) {191build_error!(VTABLE_DEFAULT_ERROR)192}193}194195/// A vtable for the file operations of a Rust miscdevice.196struct MiscdeviceVTable<T: MiscDevice>(PhantomData<T>);197198impl<T: MiscDevice> MiscdeviceVTable<T> {199/// # Safety200///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>`.203unsafe 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.205let ret = unsafe { bindings::generic_file_open(inode, raw_file) };206if ret != 0 {207return ret;208}209210// SAFETY: The open call of a file can access the private data.211let misc_ptr = unsafe { (*raw_file).private_data };212213// SAFETY: This is a miscdevice, so `misc_open()` set the private data to a pointer to the214// associated `struct miscdevice` before calling into this method. Furthermore,215// `misc_open()` ensures that the miscdevice can't be unregistered and freed during this216// call to `fops_open`.217let misc = unsafe { &*misc_ptr.cast::<MiscDeviceRegistration<T>>() };218219// 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.222let file = unsafe { File::from_raw_file(raw_file) };223224let ptr = match T::open(file, misc) {225Ok(ptr) => ptr,226Err(err) => return err.to_errno(),227};228229// This overwrites the private data with the value specified by the user, changing the type230// of this file's private data. All future accesses to the private data is performed by231// other fops_* methods in this file, which all correctly cast the private data to the new232// type.233//234// SAFETY: The open call of a file can access the private data.235unsafe { (*raw_file).private_data = ptr.into_foreign() };2362370238}239240/// # Safety241///242/// `file` and `inode` must be the file and inode for a file that is being released. The file243/// must be associated with a `MiscDeviceRegistration<T>`.244unsafe 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.246let private = unsafe { (*file).private_data };247// SAFETY: The release call of a file owns the private data.248let ptr = unsafe { <T::Ptr as ForeignOwnable>::from_foreign(private) };249250// 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.253T::release(ptr, unsafe { File::from_raw_file(file) });2542550256}257258/// # Safety259///260/// `kiocb` must be correspond to a valid file that is associated with a261/// `MiscDeviceRegistration<T>`. `iter` must be a valid `struct iov_iter` for writing.262unsafe extern "C" fn read_iter(263kiocb: *mut bindings::kiocb,264iter: *mut bindings::iov_iter,265) -> isize {266// SAFETY: The caller provides a valid `struct kiocb` associated with a267// `MiscDeviceRegistration<T>` file.268let kiocb = unsafe { Kiocb::from_raw(kiocb) };269// SAFETY: This is a valid `struct iov_iter` for writing.270let iov = unsafe { IovIterDest::from_raw(iter) };271272match T::read_iter(kiocb, iov) {273Ok(res) => res as isize,274Err(err) => err.to_errno() as isize,275}276}277278/// # Safety279///280/// `kiocb` must be correspond to a valid file that is associated with a281/// `MiscDeviceRegistration<T>`. `iter` must be a valid `struct iov_iter` for writing.282unsafe extern "C" fn write_iter(283kiocb: *mut bindings::kiocb,284iter: *mut bindings::iov_iter,285) -> isize {286// SAFETY: The caller provides a valid `struct kiocb` associated with a287// `MiscDeviceRegistration<T>` file.288let kiocb = unsafe { Kiocb::from_raw(kiocb) };289// SAFETY: This is a valid `struct iov_iter` for reading.290let iov = unsafe { IovIterSource::from_raw(iter) };291292match T::write_iter(kiocb, iov) {293Ok(res) => res as isize,294Err(err) => err.to_errno() as isize,295}296}297298/// # Safety299///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.302unsafe extern "C" fn mmap(303file: *mut bindings::file,304vma: *mut bindings::vm_area_struct,305) -> c_int {306// SAFETY: The mmap call of a file can access the private data.307let private = unsafe { (*file).private_data };308// SAFETY: This is a Rust Miscdevice, so we call `into_foreign` in `open` and309// `from_foreign` in `release`, and `fops_mmap` is guaranteed to be called between those310// two operations.311let device = unsafe { <T::Ptr as ForeignOwnable>::borrow(private.cast()) };312// SAFETY: The caller provides a vma that is undergoing initial VMA setup.313let 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.317let file = unsafe { File::from_raw_file(file) };318319match T::mmap(device, file, area) {320Ok(()) => 0,321Err(err) => err.to_errno(),322}323}324325/// # Safety326///327/// `file` must be a valid file that is associated with a `MiscDeviceRegistration<T>`.328unsafe 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.330let private = unsafe { (*file).private_data };331// SAFETY: Ioctl calls can borrow the private data of the file.332let device = unsafe { <T::Ptr as ForeignOwnable>::borrow(private) };333334// 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.337let file = unsafe { File::from_raw_file(file) };338339match T::ioctl(device, file, cmd, arg) {340Ok(ret) => ret as c_long,341Err(err) => err.to_errno() as c_long,342}343}344345/// # Safety346///347/// `file` must be a valid file that is associated with a `MiscDeviceRegistration<T>`.348#[cfg(CONFIG_COMPAT)]349unsafe extern "C" fn compat_ioctl(350file: *mut bindings::file,351cmd: c_uint,352arg: c_ulong,353) -> c_long {354// SAFETY: The compat ioctl call of a file can access the private data.355let private = unsafe { (*file).private_data };356// SAFETY: Ioctl calls can borrow the private data of the file.357let device = unsafe { <T::Ptr as ForeignOwnable>::borrow(private) };358359// 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.362let file = unsafe { File::from_raw_file(file) };363364match T::compat_ioctl(device, file, cmd, arg) {365Ok(ret) => ret as c_long,366Err(err) => err.to_errno() as c_long,367}368}369370/// # Safety371///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.374unsafe 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.376let private = unsafe { (*file).private_data };377// SAFETY: Ioctl calls can borrow the private data of the file.378let 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.382let file = unsafe { File::from_raw_file(file) };383// SAFETY: The caller ensures that the pointer is valid and exclusive for the duration in384// which this method is called.385let m = unsafe { SeqFile::from_raw(seq_file) };386387T::show_fdinfo(device, m, file);388}389390const VTABLE: bindings::file_operations = bindings::file_operations {391open: Some(Self::open),392release: Some(Self::release),393mmap: if T::HAS_MMAP { Some(Self::mmap) } else { None },394read_iter: if T::HAS_READ_ITER {395Some(Self::read_iter)396} else {397None398},399write_iter: if T::HAS_WRITE_ITER {400Some(Self::write_iter)401} else {402None403},404unlocked_ioctl: if T::HAS_IOCTL {405Some(Self::ioctl)406} else {407None408},409#[cfg(CONFIG_COMPAT)]410compat_ioctl: if T::HAS_COMPAT_IOCTL {411Some(Self::compat_ioctl)412} else if T::HAS_IOCTL {413Some(bindings::compat_ptr_ioctl)414} else {415None416},417show_fdinfo: if T::HAS_SHOW_FDINFO {418Some(Self::show_fdinfo)419} else {420None421},422// SAFETY: All zeros is a valid value for `bindings::file_operations`.423..unsafe { MaybeUninit::zeroed().assume_init() }424};425426const fn build() -> &'static bindings::file_operations {427&Self::VTABLE428}429}430431432