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 11 use 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 types::{ForeignOwnable, Opaque}, 21 }; 22 use core::{marker::PhantomData, mem::MaybeUninit, pin::Pin}; 23 24 /// Options for creating a misc device. 25 #[derive(Copy, Clone)] 26 pub struct MiscDeviceOptions { 27 /// The name of the miscdevice. 28 pub name: &'static CStr, 29 } 30 31 impl 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)] 50 pub 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`. 58 unsafe 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. 61 unsafe impl<T> Sync for MiscDeviceRegistration<T> {} 62 63 impl<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] 99 impl<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] 108 pub 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 /// Handle for mmap. 123 /// 124 /// This function is invoked when a user space process invokes the `mmap` system call on 125 /// `file`. The function is a callback that is part of the VMA initializer. The kernel will do 126 /// initial setup of the VMA before calling this function. The function can then interact with 127 /// the VMA initialization by calling methods of `vma`. If the function does not return an 128 /// error, the kernel will complete initialization of the VMA according to the properties of 129 /// `vma`. 130 fn mmap( 131 _device: <Self::Ptr as ForeignOwnable>::Borrowed<'_>, 132 _file: &File, 133 _vma: &VmaNew, 134 ) -> Result { 135 build_error!(VTABLE_DEFAULT_ERROR) 136 } 137 138 /// Handler for ioctls. 139 /// 140 /// The `cmd` argument is usually manipulated using the utilities in [`kernel::ioctl`]. 141 /// 142 /// [`kernel::ioctl`]: mod@crate::ioctl 143 fn ioctl( 144 _device: <Self::Ptr as ForeignOwnable>::Borrowed<'_>, 145 _file: &File, 146 _cmd: u32, 147 _arg: usize, 148 ) -> Result<isize> { 149 build_error!(VTABLE_DEFAULT_ERROR) 150 } 151 152 /// Handler for ioctls. 153 /// 154 /// Used for 32-bit userspace on 64-bit platforms. 155 /// 156 /// This method is optional and only needs to be provided if the ioctl relies on structures 157 /// that have different layout on 32-bit and 64-bit userspace. If no implementation is 158 /// provided, then `compat_ptr_ioctl` will be used instead. 159 #[cfg(CONFIG_COMPAT)] 160 fn compat_ioctl( 161 _device: <Self::Ptr as ForeignOwnable>::Borrowed<'_>, 162 _file: &File, 163 _cmd: u32, 164 _arg: usize, 165 ) -> Result<isize> { 166 build_error!(VTABLE_DEFAULT_ERROR) 167 } 168 169 /// Show info for this fd. 170 fn show_fdinfo( 171 _device: <Self::Ptr as ForeignOwnable>::Borrowed<'_>, 172 _m: &SeqFile, 173 _file: &File, 174 ) { 175 build_error!(VTABLE_DEFAULT_ERROR) 176 } 177 } 178 179 /// A vtable for the file operations of a Rust miscdevice. 180 struct MiscdeviceVTable<T: MiscDevice>(PhantomData<T>); 181 182 impl<T: MiscDevice> MiscdeviceVTable<T> { 183 /// # Safety 184 /// 185 /// `file` and `inode` must be the file and inode for a file that is undergoing initialization. 186 /// The file must be associated with a `MiscDeviceRegistration<T>`. 187 unsafe extern "C" fn open(inode: *mut bindings::inode, raw_file: *mut bindings::file) -> c_int { 188 // SAFETY: The pointers are valid and for a file being opened. 189 let ret = unsafe { bindings::generic_file_open(inode, raw_file) }; 190 if ret != 0 { 191 return ret; 192 } 193 194 // SAFETY: The open call of a file can access the private data. 195 let misc_ptr = unsafe { (*raw_file).private_data }; 196 197 // SAFETY: This is a miscdevice, so `misc_open()` set the private data to a pointer to the 198 // associated `struct miscdevice` before calling into this method. Furthermore, 199 // `misc_open()` ensures that the miscdevice can't be unregistered and freed during this 200 // call to `fops_open`. 201 let misc = unsafe { &*misc_ptr.cast::<MiscDeviceRegistration<T>>() }; 202 203 // SAFETY: 204 // * This underlying file is valid for (much longer than) the duration of `T::open`. 205 // * There is no active fdget_pos region on the file on this thread. 206 let file = unsafe { File::from_raw_file(raw_file) }; 207 208 let ptr = match T::open(file, misc) { 209 Ok(ptr) => ptr, 210 Err(err) => return err.to_errno(), 211 }; 212 213 // This overwrites the private data with the value specified by the user, changing the type 214 // of this file's private data. All future accesses to the private data is performed by 215 // other fops_* methods in this file, which all correctly cast the private data to the new 216 // type. 217 // 218 // SAFETY: The open call of a file can access the private data. 219 unsafe { (*raw_file).private_data = ptr.into_foreign().cast() }; 220 221 0 222 } 223 224 /// # Safety 225 /// 226 /// `file` and `inode` must be the file and inode for a file that is being released. The file 227 /// must be associated with a `MiscDeviceRegistration<T>`. 228 unsafe extern "C" fn release(_inode: *mut bindings::inode, file: *mut bindings::file) -> c_int { 229 // SAFETY: The release call of a file owns the private data. 230 let private = unsafe { (*file).private_data }.cast(); 231 // SAFETY: The release call of a file owns the private data. 232 let ptr = unsafe { <T::Ptr as ForeignOwnable>::from_foreign(private) }; 233 234 // SAFETY: 235 // * The file is valid for the duration of this call. 236 // * There is no active fdget_pos region on the file on this thread. 237 T::release(ptr, unsafe { File::from_raw_file(file) }); 238 239 0 240 } 241 242 /// # Safety 243 /// 244 /// `file` must be a valid file that is associated with a `MiscDeviceRegistration<T>`. 245 /// `vma` must be a vma that is currently being mmap'ed with this file. 246 unsafe extern "C" fn mmap( 247 file: *mut bindings::file, 248 vma: *mut bindings::vm_area_struct, 249 ) -> c_int { 250 // SAFETY: The mmap call of a file can access the private data. 251 let private = unsafe { (*file).private_data }; 252 // SAFETY: This is a Rust Miscdevice, so we call `into_foreign` in `open` and 253 // `from_foreign` in `release`, and `fops_mmap` is guaranteed to be called between those 254 // two operations. 255 let device = unsafe { <T::Ptr as ForeignOwnable>::borrow(private.cast()) }; 256 // SAFETY: The caller provides a vma that is undergoing initial VMA setup. 257 let area = unsafe { VmaNew::from_raw(vma) }; 258 // SAFETY: 259 // * The file is valid for the duration of this call. 260 // * There is no active fdget_pos region on the file on this thread. 261 let file = unsafe { File::from_raw_file(file) }; 262 263 match T::mmap(device, file, area) { 264 Ok(()) => 0, 265 Err(err) => err.to_errno(), 266 } 267 } 268 269 /// # Safety 270 /// 271 /// `file` must be a valid file that is associated with a `MiscDeviceRegistration<T>`. 272 unsafe extern "C" fn ioctl(file: *mut bindings::file, cmd: c_uint, arg: c_ulong) -> c_long { 273 // SAFETY: The ioctl call of a file can access the private data. 274 let private = unsafe { (*file).private_data }.cast(); 275 // SAFETY: Ioctl calls can borrow the private data of the file. 276 let device = unsafe { <T::Ptr as ForeignOwnable>::borrow(private) }; 277 278 // SAFETY: 279 // * The file is valid for the duration of this call. 280 // * There is no active fdget_pos region on the file on this thread. 281 let file = unsafe { File::from_raw_file(file) }; 282 283 match T::ioctl(device, file, cmd, arg) { 284 Ok(ret) => ret as c_long, 285 Err(err) => err.to_errno() as c_long, 286 } 287 } 288 289 /// # Safety 290 /// 291 /// `file` must be a valid file that is associated with a `MiscDeviceRegistration<T>`. 292 #[cfg(CONFIG_COMPAT)] 293 unsafe extern "C" fn compat_ioctl( 294 file: *mut bindings::file, 295 cmd: c_uint, 296 arg: c_ulong, 297 ) -> c_long { 298 // SAFETY: The compat ioctl call of a file can access the private data. 299 let private = unsafe { (*file).private_data }.cast(); 300 // SAFETY: Ioctl calls can borrow the private data of the file. 301 let device = unsafe { <T::Ptr as ForeignOwnable>::borrow(private) }; 302 303 // SAFETY: 304 // * The file is valid for the duration of this call. 305 // * There is no active fdget_pos region on the file on this thread. 306 let file = unsafe { File::from_raw_file(file) }; 307 308 match T::compat_ioctl(device, file, cmd, arg) { 309 Ok(ret) => ret as c_long, 310 Err(err) => err.to_errno() as c_long, 311 } 312 } 313 314 /// # Safety 315 /// 316 /// - `file` must be a valid file that is associated with a `MiscDeviceRegistration<T>`. 317 /// - `seq_file` must be a valid `struct seq_file` that we can write to. 318 unsafe extern "C" fn show_fdinfo(seq_file: *mut bindings::seq_file, file: *mut bindings::file) { 319 // SAFETY: The release call of a file owns the private data. 320 let private = unsafe { (*file).private_data }.cast(); 321 // SAFETY: Ioctl calls can borrow the private data of the file. 322 let device = unsafe { <T::Ptr as ForeignOwnable>::borrow(private) }; 323 // SAFETY: 324 // * The file is valid for the duration of this call. 325 // * There is no active fdget_pos region on the file on this thread. 326 let file = unsafe { File::from_raw_file(file) }; 327 // SAFETY: The caller ensures that the pointer is valid and exclusive for the duration in 328 // which this method is called. 329 let m = unsafe { SeqFile::from_raw(seq_file) }; 330 331 T::show_fdinfo(device, m, file); 332 } 333 334 const VTABLE: bindings::file_operations = bindings::file_operations { 335 open: Some(Self::open), 336 release: Some(Self::release), 337 mmap: if T::HAS_MMAP { Some(Self::mmap) } else { None }, 338 unlocked_ioctl: if T::HAS_IOCTL { 339 Some(Self::ioctl) 340 } else { 341 None 342 }, 343 #[cfg(CONFIG_COMPAT)] 344 compat_ioctl: if T::HAS_COMPAT_IOCTL { 345 Some(Self::compat_ioctl) 346 } else if T::HAS_IOCTL { 347 Some(bindings::compat_ptr_ioctl) 348 } else { 349 None 350 }, 351 show_fdinfo: if T::HAS_SHOW_FDINFO { 352 Some(Self::show_fdinfo) 353 } else { 354 None 355 }, 356 // SAFETY: All zeros is a valid value for `bindings::file_operations`. 357 ..unsafe { MaybeUninit::zeroed().assume_init() } 358 }; 359 360 const fn build() -> &'static bindings::file_operations { 361 &Self::VTABLE 362 } 363 } 364