// 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,16mm::virt::VmaNew,17prelude::*,18seq_file::SeqFile,19types::{ForeignOwnable, Opaque},20};21use core::{marker::PhantomData, mem::MaybeUninit, pin::Pin};2223/// Options for creating a misc device.24#[derive(Copy, Clone)]25pub struct MiscDeviceOptions {26/// The name of the miscdevice.27pub name: &'static CStr,28}2930impl MiscDeviceOptions {31/// Create a raw `struct miscdev` ready for registration.32pub const fn into_raw<T: MiscDevice>(self) -> bindings::miscdevice {33// SAFETY: All zeros is valid for this C type.34let mut result: bindings::miscdevice = unsafe { MaybeUninit::zeroed().assume_init() };35result.minor = bindings::MISC_DYNAMIC_MINOR as ffi::c_int;36result.name = crate::str::as_char_ptr_in_const_context(self.name);37result.fops = MiscdeviceVTable::<T>::build();38result39}40}4142/// A registration of a miscdevice.43///44/// # Invariants45///46/// - `inner` contains a `struct miscdevice` that is registered using47/// `misc_register()`.48/// - This registration remains valid for the entire lifetime of the49/// [`MiscDeviceRegistration`] instance.50/// - Deregistration occurs exactly once in [`Drop`] via `misc_deregister()`.51/// - `inner` wraps a valid, pinned `miscdevice` created using52/// [`MiscDeviceOptions::into_raw`].53#[repr(transparent)]54#[pin_data(PinnedDrop)]55pub struct MiscDeviceRegistration<T> {56#[pin]57inner: Opaque<bindings::miscdevice>,58_t: PhantomData<T>,59}6061// SAFETY: It is allowed to call `misc_deregister` on a different thread from where you called62// `misc_register`.63unsafe impl<T> Send for MiscDeviceRegistration<T> {}64// SAFETY: All `&self` methods on this type are written to ensure that it is safe to call them in65// parallel.66unsafe impl<T> Sync for MiscDeviceRegistration<T> {}6768impl<T: MiscDevice> MiscDeviceRegistration<T> {69/// Register a misc device.70pub fn register(opts: MiscDeviceOptions) -> impl PinInit<Self, Error> {71try_pin_init!(Self {72inner <- Opaque::try_ffi_init(move |slot: *mut bindings::miscdevice| {73// SAFETY: The initializer can write to the provided `slot`.74unsafe { slot.write(opts.into_raw::<T>()) };7576// SAFETY: We just wrote the misc device options to the slot. The miscdevice will77// get unregistered before `slot` is deallocated because the memory is pinned and78// the destructor of this type deallocates the memory.79// INVARIANT: If this returns `Ok(())`, then the `slot` will contain a registered80// misc device.81to_result(unsafe { bindings::misc_register(slot) })82}),83_t: PhantomData,84})85}8687/// Returns a raw pointer to the misc device.88pub fn as_raw(&self) -> *mut bindings::miscdevice {89self.inner.get()90}9192/// Access the `this_device` field.93pub fn device(&self) -> &Device {94// SAFETY: This can only be called after a successful register(), which always95// initialises `this_device` with a valid device. Furthermore, the signature of this96// function tells the borrow-checker that the `&Device` reference must not outlive the97// `&MiscDeviceRegistration<T>` used to obtain it, so the last use of the reference must be98// before the underlying `struct miscdevice` is destroyed.99unsafe { Device::from_raw((*self.as_raw()).this_device) }100}101}102103#[pinned_drop]104impl<T> PinnedDrop for MiscDeviceRegistration<T> {105fn drop(self: Pin<&mut Self>) {106// SAFETY: We know that the device is registered by the type invariants.107unsafe { bindings::misc_deregister(self.inner.get()) };108}109}110111/// Trait implemented by the private data of an open misc device.112#[vtable]113pub trait MiscDevice: Sized {114/// What kind of pointer should `Self` be wrapped in.115type Ptr: ForeignOwnable + Send + Sync;116117/// Called when the misc device is opened.118///119/// The returned pointer will be stored as the private data for the file.120fn open(_file: &File, _misc: &MiscDeviceRegistration<Self>) -> Result<Self::Ptr>;121122/// Called when the misc device is released.123fn release(device: Self::Ptr, _file: &File) {124drop(device);125}126127/// Handle for mmap.128///129/// This function is invoked when a user space process invokes the `mmap` system call on130/// `file`. The function is a callback that is part of the VMA initializer. The kernel will do131/// initial setup of the VMA before calling this function. The function can then interact with132/// the VMA initialization by calling methods of `vma`. If the function does not return an133/// error, the kernel will complete initialization of the VMA according to the properties of134/// `vma`.135fn mmap(136_device: <Self::Ptr as ForeignOwnable>::Borrowed<'_>,137_file: &File,138_vma: &VmaNew,139) -> Result {140build_error!(VTABLE_DEFAULT_ERROR)141}142143/// Handler for ioctls.144///145/// The `cmd` argument is usually manipulated using the utilities in [`kernel::ioctl`].146///147/// [`kernel::ioctl`]: mod@crate::ioctl148fn ioctl(149_device: <Self::Ptr as ForeignOwnable>::Borrowed<'_>,150_file: &File,151_cmd: u32,152_arg: usize,153) -> Result<isize> {154build_error!(VTABLE_DEFAULT_ERROR)155}156157/// Handler for ioctls.158///159/// Used for 32-bit userspace on 64-bit platforms.160///161/// This method is optional and only needs to be provided if the ioctl relies on structures162/// that have different layout on 32-bit and 64-bit userspace. If no implementation is163/// provided, then `compat_ptr_ioctl` will be used instead.164#[cfg(CONFIG_COMPAT)]165fn compat_ioctl(166_device: <Self::Ptr as ForeignOwnable>::Borrowed<'_>,167_file: &File,168_cmd: u32,169_arg: usize,170) -> Result<isize> {171build_error!(VTABLE_DEFAULT_ERROR)172}173174/// Show info for this fd.175fn show_fdinfo(176_device: <Self::Ptr as ForeignOwnable>::Borrowed<'_>,177_m: &SeqFile,178_file: &File,179) {180build_error!(VTABLE_DEFAULT_ERROR)181}182}183184/// A vtable for the file operations of a Rust miscdevice.185struct MiscdeviceVTable<T: MiscDevice>(PhantomData<T>);186187impl<T: MiscDevice> MiscdeviceVTable<T> {188/// # Safety189///190/// `file` and `inode` must be the file and inode for a file that is undergoing initialization.191/// The file must be associated with a `MiscDeviceRegistration<T>`.192unsafe extern "C" fn open(inode: *mut bindings::inode, raw_file: *mut bindings::file) -> c_int {193// SAFETY: The pointers are valid and for a file being opened.194let ret = unsafe { bindings::generic_file_open(inode, raw_file) };195if ret != 0 {196return ret;197}198199// SAFETY: The open call of a file can access the private data.200let misc_ptr = unsafe { (*raw_file).private_data };201202// SAFETY: This is a miscdevice, so `misc_open()` set the private data to a pointer to the203// associated `struct miscdevice` before calling into this method. Furthermore,204// `misc_open()` ensures that the miscdevice can't be unregistered and freed during this205// call to `fops_open`.206let misc = unsafe { &*misc_ptr.cast::<MiscDeviceRegistration<T>>() };207208// SAFETY:209// * This underlying file is valid for (much longer than) the duration of `T::open`.210// * There is no active fdget_pos region on the file on this thread.211let file = unsafe { File::from_raw_file(raw_file) };212213let ptr = match T::open(file, misc) {214Ok(ptr) => ptr,215Err(err) => return err.to_errno(),216};217218// This overwrites the private data with the value specified by the user, changing the type219// of this file's private data. All future accesses to the private data is performed by220// other fops_* methods in this file, which all correctly cast the private data to the new221// type.222//223// SAFETY: The open call of a file can access the private data.224unsafe { (*raw_file).private_data = ptr.into_foreign() };2252260227}228229/// # Safety230///231/// `file` and `inode` must be the file and inode for a file that is being released. The file232/// must be associated with a `MiscDeviceRegistration<T>`.233unsafe extern "C" fn release(_inode: *mut bindings::inode, file: *mut bindings::file) -> c_int {234// SAFETY: The release call of a file owns the private data.235let private = unsafe { (*file).private_data };236// SAFETY: The release call of a file owns the private data.237let ptr = unsafe { <T::Ptr as ForeignOwnable>::from_foreign(private) };238239// SAFETY:240// * The file is valid for the duration of this call.241// * There is no active fdget_pos region on the file on this thread.242T::release(ptr, unsafe { File::from_raw_file(file) });2432440245}246247/// # Safety248///249/// `file` must be a valid file that is associated with a `MiscDeviceRegistration<T>`.250/// `vma` must be a vma that is currently being mmap'ed with this file.251unsafe extern "C" fn mmap(252file: *mut bindings::file,253vma: *mut bindings::vm_area_struct,254) -> c_int {255// SAFETY: The mmap call of a file can access the private data.256let private = unsafe { (*file).private_data };257// SAFETY: This is a Rust Miscdevice, so we call `into_foreign` in `open` and258// `from_foreign` in `release`, and `fops_mmap` is guaranteed to be called between those259// two operations.260let device = unsafe { <T::Ptr as ForeignOwnable>::borrow(private.cast()) };261// SAFETY: The caller provides a vma that is undergoing initial VMA setup.262let area = unsafe { VmaNew::from_raw(vma) };263// SAFETY:264// * The file is valid for the duration of this call.265// * There is no active fdget_pos region on the file on this thread.266let file = unsafe { File::from_raw_file(file) };267268match T::mmap(device, file, area) {269Ok(()) => 0,270Err(err) => err.to_errno(),271}272}273274/// # Safety275///276/// `file` must be a valid file that is associated with a `MiscDeviceRegistration<T>`.277unsafe extern "C" fn ioctl(file: *mut bindings::file, cmd: c_uint, arg: c_ulong) -> c_long {278// SAFETY: The ioctl call of a file can access the private data.279let private = unsafe { (*file).private_data };280// SAFETY: Ioctl calls can borrow the private data of the file.281let device = unsafe { <T::Ptr as ForeignOwnable>::borrow(private) };282283// SAFETY:284// * The file is valid for the duration of this call.285// * There is no active fdget_pos region on the file on this thread.286let file = unsafe { File::from_raw_file(file) };287288match T::ioctl(device, file, cmd, arg) {289Ok(ret) => ret as c_long,290Err(err) => err.to_errno() as c_long,291}292}293294/// # Safety295///296/// `file` must be a valid file that is associated with a `MiscDeviceRegistration<T>`.297#[cfg(CONFIG_COMPAT)]298unsafe extern "C" fn compat_ioctl(299file: *mut bindings::file,300cmd: c_uint,301arg: c_ulong,302) -> c_long {303// SAFETY: The compat ioctl call of a file can access the private data.304let private = unsafe { (*file).private_data };305// SAFETY: Ioctl calls can borrow the private data of the file.306let device = unsafe { <T::Ptr as ForeignOwnable>::borrow(private) };307308// SAFETY:309// * The file is valid for the duration of this call.310// * There is no active fdget_pos region on the file on this thread.311let file = unsafe { File::from_raw_file(file) };312313match T::compat_ioctl(device, file, cmd, arg) {314Ok(ret) => ret as c_long,315Err(err) => err.to_errno() as c_long,316}317}318319/// # Safety320///321/// - `file` must be a valid file that is associated with a `MiscDeviceRegistration<T>`.322/// - `seq_file` must be a valid `struct seq_file` that we can write to.323unsafe extern "C" fn show_fdinfo(seq_file: *mut bindings::seq_file, file: *mut bindings::file) {324// SAFETY: The release call of a file owns the private data.325let private = unsafe { (*file).private_data };326// SAFETY: Ioctl calls can borrow the private data of the file.327let device = unsafe { <T::Ptr as ForeignOwnable>::borrow(private) };328// SAFETY:329// * The file is valid for the duration of this call.330// * There is no active fdget_pos region on the file on this thread.331let file = unsafe { File::from_raw_file(file) };332// SAFETY: The caller ensures that the pointer is valid and exclusive for the duration in333// which this method is called.334let m = unsafe { SeqFile::from_raw(seq_file) };335336T::show_fdinfo(device, m, file);337}338339const VTABLE: bindings::file_operations = bindings::file_operations {340open: Some(Self::open),341release: Some(Self::release),342mmap: if T::HAS_MMAP { Some(Self::mmap) } else { None },343unlocked_ioctl: if T::HAS_IOCTL {344Some(Self::ioctl)345} else {346None347},348#[cfg(CONFIG_COMPAT)]349compat_ioctl: if T::HAS_COMPAT_IOCTL {350Some(Self::compat_ioctl)351} else if T::HAS_IOCTL {352Some(bindings::compat_ptr_ioctl)353} else {354None355},356show_fdinfo: if T::HAS_SHOW_FDINFO {357Some(Self::show_fdinfo)358} else {359None360},361// SAFETY: All zeros is a valid value for `bindings::file_operations`.362..unsafe { MaybeUninit::zeroed().assume_init() }363};364365const fn build() -> &'static bindings::file_operations {366&Self::VTABLE367}368}369370371