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