1 // SPDX-License-Identifier: GPL-2.0 2 3 //! Generic devices that are part of the kernel's driver model. 4 //! 5 //! C header: [`include/linux/device.h`](srctree/include/linux/device.h) 6 7 use crate::{ 8 bindings, 9 str::CStr, 10 types::{ARef, Opaque}, 11 }; 12 use core::{fmt, marker::PhantomData, ptr}; 13 14 #[cfg(CONFIG_PRINTK)] 15 use crate::c_str; 16 17 /// A reference-counted device. 18 /// 19 /// This structure represents the Rust abstraction for a C `struct device`. This implementation 20 /// abstracts the usage of an already existing C `struct device` within Rust code that we get 21 /// passed from the C side. 22 /// 23 /// An instance of this abstraction can be obtained temporarily or permanent. 24 /// 25 /// A temporary one is bound to the lifetime of the C `struct device` pointer used for creation. 26 /// A permanent instance is always reference-counted and hence not restricted by any lifetime 27 /// boundaries. 28 /// 29 /// For subsystems it is recommended to create a permanent instance to wrap into a subsystem 30 /// specific device structure (e.g. `pci::Device`). This is useful for passing it to drivers in 31 /// `T::probe()`, such that a driver can store the `ARef<Device>` (equivalent to storing a 32 /// `struct device` pointer in a C driver) for arbitrary purposes, e.g. allocating DMA coherent 33 /// memory. 34 /// 35 /// # Invariants 36 /// 37 /// A `Device` instance represents a valid `struct device` created by the C portion of the kernel. 38 /// 39 /// Instances of this type are always reference-counted, that is, a call to `get_device` ensures 40 /// that the allocation remains valid at least until the matching call to `put_device`. 41 /// 42 /// `bindings::device::release` is valid to be called from any thread, hence `ARef<Device>` can be 43 /// dropped from any thread. 44 #[repr(transparent)] 45 pub struct Device<Ctx: DeviceContext = Normal>(Opaque<bindings::device>, PhantomData<Ctx>); 46 47 impl Device { 48 /// Creates a new reference-counted abstraction instance of an existing `struct device` pointer. 49 /// 50 /// # Safety 51 /// 52 /// Callers must ensure that `ptr` is valid, non-null, and has a non-zero reference count, 53 /// i.e. it must be ensured that the reference count of the C `struct device` `ptr` points to 54 /// can't drop to zero, for the duration of this function call. 55 /// 56 /// It must also be ensured that `bindings::device::release` can be called from any thread. 57 /// While not officially documented, this should be the case for any `struct device`. get_device(ptr: *mut bindings::device) -> ARef<Self>58 pub unsafe fn get_device(ptr: *mut bindings::device) -> ARef<Self> { 59 // SAFETY: By the safety requirements ptr is valid 60 unsafe { Self::as_ref(ptr) }.into() 61 } 62 } 63 64 impl<Ctx: DeviceContext> Device<Ctx> { 65 /// Obtain the raw `struct device *`. as_raw(&self) -> *mut bindings::device66 pub(crate) fn as_raw(&self) -> *mut bindings::device { 67 self.0.get() 68 } 69 70 /// Returns a reference to the parent device, if any. 71 #[cfg_attr(not(CONFIG_AUXILIARY_BUS), expect(dead_code))] parent(&self) -> Option<&Self>72 pub(crate) fn parent(&self) -> Option<&Self> { 73 // SAFETY: 74 // - By the type invariant `self.as_raw()` is always valid. 75 // - The parent device is only ever set at device creation. 76 let parent = unsafe { (*self.as_raw()).parent }; 77 78 if parent.is_null() { 79 None 80 } else { 81 // SAFETY: 82 // - Since `parent` is not NULL, it must be a valid pointer to a `struct device`. 83 // - `parent` is valid for the lifetime of `self`, since a `struct device` holds a 84 // reference count of its parent. 85 Some(unsafe { Self::as_ref(parent) }) 86 } 87 } 88 89 /// Convert a raw C `struct device` pointer to a `&'a Device`. 90 /// 91 /// # Safety 92 /// 93 /// Callers must ensure that `ptr` is valid, non-null, and has a non-zero reference count, 94 /// i.e. it must be ensured that the reference count of the C `struct device` `ptr` points to 95 /// can't drop to zero, for the duration of this function call and the entire duration when the 96 /// returned reference exists. as_ref<'a>(ptr: *mut bindings::device) -> &'a Self97 pub unsafe fn as_ref<'a>(ptr: *mut bindings::device) -> &'a Self { 98 // SAFETY: Guaranteed by the safety requirements of the function. 99 unsafe { &*ptr.cast() } 100 } 101 102 /// Prints an emergency-level message (level 0) prefixed with device information. 103 /// 104 /// More details are available from [`dev_emerg`]. 105 /// 106 /// [`dev_emerg`]: crate::dev_emerg pr_emerg(&self, args: fmt::Arguments<'_>)107 pub fn pr_emerg(&self, args: fmt::Arguments<'_>) { 108 // SAFETY: `klevel` is null-terminated, uses one of the kernel constants. 109 unsafe { self.printk(bindings::KERN_EMERG, args) }; 110 } 111 112 /// Prints an alert-level message (level 1) prefixed with device information. 113 /// 114 /// More details are available from [`dev_alert`]. 115 /// 116 /// [`dev_alert`]: crate::dev_alert pr_alert(&self, args: fmt::Arguments<'_>)117 pub fn pr_alert(&self, args: fmt::Arguments<'_>) { 118 // SAFETY: `klevel` is null-terminated, uses one of the kernel constants. 119 unsafe { self.printk(bindings::KERN_ALERT, args) }; 120 } 121 122 /// Prints a critical-level message (level 2) prefixed with device information. 123 /// 124 /// More details are available from [`dev_crit`]. 125 /// 126 /// [`dev_crit`]: crate::dev_crit pr_crit(&self, args: fmt::Arguments<'_>)127 pub fn pr_crit(&self, args: fmt::Arguments<'_>) { 128 // SAFETY: `klevel` is null-terminated, uses one of the kernel constants. 129 unsafe { self.printk(bindings::KERN_CRIT, args) }; 130 } 131 132 /// Prints an error-level message (level 3) prefixed with device information. 133 /// 134 /// More details are available from [`dev_err`]. 135 /// 136 /// [`dev_err`]: crate::dev_err pr_err(&self, args: fmt::Arguments<'_>)137 pub fn pr_err(&self, args: fmt::Arguments<'_>) { 138 // SAFETY: `klevel` is null-terminated, uses one of the kernel constants. 139 unsafe { self.printk(bindings::KERN_ERR, args) }; 140 } 141 142 /// Prints a warning-level message (level 4) prefixed with device information. 143 /// 144 /// More details are available from [`dev_warn`]. 145 /// 146 /// [`dev_warn`]: crate::dev_warn pr_warn(&self, args: fmt::Arguments<'_>)147 pub fn pr_warn(&self, args: fmt::Arguments<'_>) { 148 // SAFETY: `klevel` is null-terminated, uses one of the kernel constants. 149 unsafe { self.printk(bindings::KERN_WARNING, args) }; 150 } 151 152 /// Prints a notice-level message (level 5) prefixed with device information. 153 /// 154 /// More details are available from [`dev_notice`]. 155 /// 156 /// [`dev_notice`]: crate::dev_notice pr_notice(&self, args: fmt::Arguments<'_>)157 pub fn pr_notice(&self, args: fmt::Arguments<'_>) { 158 // SAFETY: `klevel` is null-terminated, uses one of the kernel constants. 159 unsafe { self.printk(bindings::KERN_NOTICE, args) }; 160 } 161 162 /// Prints an info-level message (level 6) prefixed with device information. 163 /// 164 /// More details are available from [`dev_info`]. 165 /// 166 /// [`dev_info`]: crate::dev_info pr_info(&self, args: fmt::Arguments<'_>)167 pub fn pr_info(&self, args: fmt::Arguments<'_>) { 168 // SAFETY: `klevel` is null-terminated, uses one of the kernel constants. 169 unsafe { self.printk(bindings::KERN_INFO, args) }; 170 } 171 172 /// Prints a debug-level message (level 7) prefixed with device information. 173 /// 174 /// More details are available from [`dev_dbg`]. 175 /// 176 /// [`dev_dbg`]: crate::dev_dbg pr_dbg(&self, args: fmt::Arguments<'_>)177 pub fn pr_dbg(&self, args: fmt::Arguments<'_>) { 178 if cfg!(debug_assertions) { 179 // SAFETY: `klevel` is null-terminated, uses one of the kernel constants. 180 unsafe { self.printk(bindings::KERN_DEBUG, args) }; 181 } 182 } 183 184 /// Prints the provided message to the console. 185 /// 186 /// # Safety 187 /// 188 /// Callers must ensure that `klevel` is null-terminated; in particular, one of the 189 /// `KERN_*`constants, for example, `KERN_CRIT`, `KERN_ALERT`, etc. 190 #[cfg_attr(not(CONFIG_PRINTK), allow(unused_variables))] printk(&self, klevel: &[u8], msg: fmt::Arguments<'_>)191 unsafe fn printk(&self, klevel: &[u8], msg: fmt::Arguments<'_>) { 192 // SAFETY: `klevel` is null-terminated and one of the kernel constants. `self.as_raw` 193 // is valid because `self` is valid. The "%pA" format string expects a pointer to 194 // `fmt::Arguments`, which is what we're passing as the last argument. 195 #[cfg(CONFIG_PRINTK)] 196 unsafe { 197 bindings::_dev_printk( 198 klevel as *const _ as *const crate::ffi::c_char, 199 self.as_raw(), 200 c_str!("%pA").as_char_ptr(), 201 &msg as *const _ as *const crate::ffi::c_void, 202 ) 203 }; 204 } 205 206 /// Checks if property is present or not. property_present(&self, name: &CStr) -> bool207 pub fn property_present(&self, name: &CStr) -> bool { 208 // SAFETY: By the invariant of `CStr`, `name` is null-terminated. 209 unsafe { bindings::device_property_present(self.as_raw().cast_const(), name.as_char_ptr()) } 210 } 211 } 212 213 // SAFETY: `Device` is a transparent wrapper of a type that doesn't depend on `Device`'s generic 214 // argument. 215 kernel::impl_device_context_deref!(unsafe { Device }); 216 kernel::impl_device_context_into_aref!(Device); 217 218 // SAFETY: Instances of `Device` are always reference-counted. 219 unsafe impl crate::types::AlwaysRefCounted for Device { inc_ref(&self)220 fn inc_ref(&self) { 221 // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero. 222 unsafe { bindings::get_device(self.as_raw()) }; 223 } 224 dec_ref(obj: ptr::NonNull<Self>)225 unsafe fn dec_ref(obj: ptr::NonNull<Self>) { 226 // SAFETY: The safety requirements guarantee that the refcount is non-zero. 227 unsafe { bindings::put_device(obj.cast().as_ptr()) } 228 } 229 } 230 231 // SAFETY: As by the type invariant `Device` can be sent to any thread. 232 unsafe impl Send for Device {} 233 234 // SAFETY: `Device` can be shared among threads because all immutable methods are protected by the 235 // synchronization in `struct device`. 236 unsafe impl Sync for Device {} 237 238 /// Marker trait for the context of a bus specific device. 239 /// 240 /// Some functions of a bus specific device should only be called from a certain context, i.e. bus 241 /// callbacks, such as `probe()`. 242 /// 243 /// This is the marker trait for structures representing the context of a bus specific device. 244 pub trait DeviceContext: private::Sealed {} 245 246 /// The [`Normal`] context is the context of a bus specific device when it is not an argument of 247 /// any bus callback. 248 pub struct Normal; 249 250 /// The [`Core`] context is the context of a bus specific device when it is supplied as argument of 251 /// any of the bus callbacks, such as `probe()`. 252 pub struct Core; 253 254 /// The [`Bound`] context is the context of a bus specific device reference when it is guaranteed to 255 /// be bound for the duration of its lifetime. 256 pub struct Bound; 257 258 mod private { 259 pub trait Sealed {} 260 261 impl Sealed for super::Bound {} 262 impl Sealed for super::Core {} 263 impl Sealed for super::Normal {} 264 } 265 266 impl DeviceContext for Bound {} 267 impl DeviceContext for Core {} 268 impl DeviceContext for Normal {} 269 270 /// # Safety 271 /// 272 /// The type given as `$device` must be a transparent wrapper of a type that doesn't depend on the 273 /// generic argument of `$device`. 274 #[doc(hidden)] 275 #[macro_export] 276 macro_rules! __impl_device_context_deref { 277 (unsafe { $device:ident, $src:ty => $dst:ty }) => { 278 impl ::core::ops::Deref for $device<$src> { 279 type Target = $device<$dst>; 280 281 fn deref(&self) -> &Self::Target { 282 let ptr: *const Self = self; 283 284 // CAST: `$device<$src>` and `$device<$dst>` transparently wrap the same type by the 285 // safety requirement of the macro. 286 let ptr = ptr.cast::<Self::Target>(); 287 288 // SAFETY: `ptr` was derived from `&self`. 289 unsafe { &*ptr } 290 } 291 } 292 }; 293 } 294 295 /// Implement [`core::ops::Deref`] traits for allowed [`DeviceContext`] conversions of a (bus 296 /// specific) device. 297 /// 298 /// # Safety 299 /// 300 /// The type given as `$device` must be a transparent wrapper of a type that doesn't depend on the 301 /// generic argument of `$device`. 302 #[macro_export] 303 macro_rules! impl_device_context_deref { 304 (unsafe { $device:ident }) => { 305 // SAFETY: This macro has the exact same safety requirement as 306 // `__impl_device_context_deref!`. 307 ::kernel::__impl_device_context_deref!(unsafe { 308 $device, 309 $crate::device::Core => $crate::device::Bound 310 }); 311 312 // SAFETY: This macro has the exact same safety requirement as 313 // `__impl_device_context_deref!`. 314 ::kernel::__impl_device_context_deref!(unsafe { 315 $device, 316 $crate::device::Bound => $crate::device::Normal 317 }); 318 }; 319 } 320 321 #[doc(hidden)] 322 #[macro_export] 323 macro_rules! __impl_device_context_into_aref { 324 ($src:ty, $device:tt) => { 325 impl ::core::convert::From<&$device<$src>> for $crate::types::ARef<$device> { 326 fn from(dev: &$device<$src>) -> Self { 327 (&**dev).into() 328 } 329 } 330 }; 331 } 332 333 /// Implement [`core::convert::From`], such that all `&Device<Ctx>` can be converted to an 334 /// `ARef<Device>`. 335 #[macro_export] 336 macro_rules! impl_device_context_into_aref { 337 ($device:tt) => { 338 ::kernel::__impl_device_context_into_aref!($crate::device::Core, $device); 339 ::kernel::__impl_device_context_into_aref!($crate::device::Bound, $device); 340 }; 341 } 342 343 #[doc(hidden)] 344 #[macro_export] 345 macro_rules! dev_printk { 346 ($method:ident, $dev:expr, $($f:tt)*) => { 347 { 348 ($dev).$method(::core::format_args!($($f)*)); 349 } 350 } 351 } 352 353 /// Prints an emergency-level message (level 0) prefixed with device information. 354 /// 355 /// This level should be used if the system is unusable. 356 /// 357 /// Equivalent to the kernel's `dev_emerg` macro. 358 /// 359 /// Mimics the interface of [`std::print!`]. More information about the syntax is available from 360 /// [`core::fmt`] and [`std::format!`]. 361 /// 362 /// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html 363 /// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html 364 /// 365 /// # Examples 366 /// 367 /// ``` 368 /// # use kernel::device::Device; 369 /// 370 /// fn example(dev: &Device) { 371 /// dev_emerg!(dev, "hello {}\n", "there"); 372 /// } 373 /// ``` 374 #[macro_export] 375 macro_rules! dev_emerg { 376 ($($f:tt)*) => { $crate::dev_printk!(pr_emerg, $($f)*); } 377 } 378 379 /// Prints an alert-level message (level 1) prefixed with device information. 380 /// 381 /// This level should be used if action must be taken immediately. 382 /// 383 /// Equivalent to the kernel's `dev_alert` macro. 384 /// 385 /// Mimics the interface of [`std::print!`]. More information about the syntax is available from 386 /// [`core::fmt`] and [`std::format!`]. 387 /// 388 /// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html 389 /// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html 390 /// 391 /// # Examples 392 /// 393 /// ``` 394 /// # use kernel::device::Device; 395 /// 396 /// fn example(dev: &Device) { 397 /// dev_alert!(dev, "hello {}\n", "there"); 398 /// } 399 /// ``` 400 #[macro_export] 401 macro_rules! dev_alert { 402 ($($f:tt)*) => { $crate::dev_printk!(pr_alert, $($f)*); } 403 } 404 405 /// Prints a critical-level message (level 2) prefixed with device information. 406 /// 407 /// This level should be used in critical conditions. 408 /// 409 /// Equivalent to the kernel's `dev_crit` macro. 410 /// 411 /// Mimics the interface of [`std::print!`]. More information about the syntax is available from 412 /// [`core::fmt`] and [`std::format!`]. 413 /// 414 /// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html 415 /// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html 416 /// 417 /// # Examples 418 /// 419 /// ``` 420 /// # use kernel::device::Device; 421 /// 422 /// fn example(dev: &Device) { 423 /// dev_crit!(dev, "hello {}\n", "there"); 424 /// } 425 /// ``` 426 #[macro_export] 427 macro_rules! dev_crit { 428 ($($f:tt)*) => { $crate::dev_printk!(pr_crit, $($f)*); } 429 } 430 431 /// Prints an error-level message (level 3) prefixed with device information. 432 /// 433 /// This level should be used in error conditions. 434 /// 435 /// Equivalent to the kernel's `dev_err` macro. 436 /// 437 /// Mimics the interface of [`std::print!`]. More information about the syntax is available from 438 /// [`core::fmt`] and [`std::format!`]. 439 /// 440 /// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html 441 /// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html 442 /// 443 /// # Examples 444 /// 445 /// ``` 446 /// # use kernel::device::Device; 447 /// 448 /// fn example(dev: &Device) { 449 /// dev_err!(dev, "hello {}\n", "there"); 450 /// } 451 /// ``` 452 #[macro_export] 453 macro_rules! dev_err { 454 ($($f:tt)*) => { $crate::dev_printk!(pr_err, $($f)*); } 455 } 456 457 /// Prints a warning-level message (level 4) prefixed with device information. 458 /// 459 /// This level should be used in warning conditions. 460 /// 461 /// Equivalent to the kernel's `dev_warn` macro. 462 /// 463 /// Mimics the interface of [`std::print!`]. More information about the syntax is available from 464 /// [`core::fmt`] and [`std::format!`]. 465 /// 466 /// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html 467 /// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html 468 /// 469 /// # Examples 470 /// 471 /// ``` 472 /// # use kernel::device::Device; 473 /// 474 /// fn example(dev: &Device) { 475 /// dev_warn!(dev, "hello {}\n", "there"); 476 /// } 477 /// ``` 478 #[macro_export] 479 macro_rules! dev_warn { 480 ($($f:tt)*) => { $crate::dev_printk!(pr_warn, $($f)*); } 481 } 482 483 /// Prints a notice-level message (level 5) prefixed with device information. 484 /// 485 /// This level should be used in normal but significant conditions. 486 /// 487 /// Equivalent to the kernel's `dev_notice` macro. 488 /// 489 /// Mimics the interface of [`std::print!`]. More information about the syntax is available from 490 /// [`core::fmt`] and [`std::format!`]. 491 /// 492 /// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html 493 /// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html 494 /// 495 /// # Examples 496 /// 497 /// ``` 498 /// # use kernel::device::Device; 499 /// 500 /// fn example(dev: &Device) { 501 /// dev_notice!(dev, "hello {}\n", "there"); 502 /// } 503 /// ``` 504 #[macro_export] 505 macro_rules! dev_notice { 506 ($($f:tt)*) => { $crate::dev_printk!(pr_notice, $($f)*); } 507 } 508 509 /// Prints an info-level message (level 6) prefixed with device information. 510 /// 511 /// This level should be used for informational messages. 512 /// 513 /// Equivalent to the kernel's `dev_info` macro. 514 /// 515 /// Mimics the interface of [`std::print!`]. More information about the syntax is available from 516 /// [`core::fmt`] and [`std::format!`]. 517 /// 518 /// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html 519 /// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html 520 /// 521 /// # Examples 522 /// 523 /// ``` 524 /// # use kernel::device::Device; 525 /// 526 /// fn example(dev: &Device) { 527 /// dev_info!(dev, "hello {}\n", "there"); 528 /// } 529 /// ``` 530 #[macro_export] 531 macro_rules! dev_info { 532 ($($f:tt)*) => { $crate::dev_printk!(pr_info, $($f)*); } 533 } 534 535 /// Prints a debug-level message (level 7) prefixed with device information. 536 /// 537 /// This level should be used for debug messages. 538 /// 539 /// Equivalent to the kernel's `dev_dbg` macro, except that it doesn't support dynamic debug yet. 540 /// 541 /// Mimics the interface of [`std::print!`]. More information about the syntax is available from 542 /// [`core::fmt`] and [`std::format!`]. 543 /// 544 /// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html 545 /// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html 546 /// 547 /// # Examples 548 /// 549 /// ``` 550 /// # use kernel::device::Device; 551 /// 552 /// fn example(dev: &Device) { 553 /// dev_dbg!(dev, "hello {}\n", "there"); 554 /// } 555 /// ``` 556 #[macro_export] 557 macro_rules! dev_dbg { 558 ($($f:tt)*) => { $crate::dev_printk!(pr_dbg, $($f)*); } 559 } 560