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, fmt, 9 sync::aref::ARef, 10 types::{ForeignOwnable, Opaque}, 11 }; 12 use core::{marker::PhantomData, ptr}; 13 14 #[cfg(CONFIG_PRINTK)] 15 use crate::c_str; 16 use crate::str::CStrExt as _; 17 18 pub mod property; 19 20 /// The core representation of a device in the kernel's driver model. 21 /// 22 /// This structure represents the Rust abstraction for a C `struct device`. A [`Device`] can either 23 /// exist as temporary reference (see also [`Device::from_raw`]), which is only valid within a 24 /// certain scope or as [`ARef<Device>`], owning a dedicated reference count. 25 /// 26 /// # Device Types 27 /// 28 /// A [`Device`] can represent either a bus device or a class device. 29 /// 30 /// ## Bus Devices 31 /// 32 /// A bus device is a [`Device`] that is associated with a physical or virtual bus. Examples of 33 /// buses include PCI, USB, I2C, and SPI. Devices attached to a bus are registered with a specific 34 /// bus type, which facilitates matching devices with appropriate drivers based on IDs or other 35 /// identifying information. Bus devices are visible in sysfs under `/sys/bus/<bus-name>/devices/`. 36 /// 37 /// ## Class Devices 38 /// 39 /// A class device is a [`Device`] that is associated with a logical category of functionality 40 /// rather than a physical bus. Examples of classes include block devices, network interfaces, sound 41 /// cards, and input devices. Class devices are grouped under a common class and exposed to 42 /// userspace via entries in `/sys/class/<class-name>/`. 43 /// 44 /// # Device Context 45 /// 46 /// [`Device`] references are generic over a [`DeviceContext`], which represents the type state of 47 /// a [`Device`]. 48 /// 49 /// As the name indicates, this type state represents the context of the scope the [`Device`] 50 /// reference is valid in. For instance, the [`Bound`] context guarantees that the [`Device`] is 51 /// bound to a driver for the entire duration of the existence of a [`Device<Bound>`] reference. 52 /// 53 /// Other [`DeviceContext`] types besides [`Bound`] are [`Normal`], [`Core`] and [`CoreInternal`]. 54 /// 55 /// Unless selected otherwise [`Device`] defaults to the [`Normal`] [`DeviceContext`], which by 56 /// itself has no additional requirements. 57 /// 58 /// It is always up to the caller of [`Device::from_raw`] to select the correct [`DeviceContext`] 59 /// type for the corresponding scope the [`Device`] reference is created in. 60 /// 61 /// All [`DeviceContext`] types other than [`Normal`] are intended to be used with 62 /// [bus devices](#bus-devices) only. 63 /// 64 /// # Implementing Bus Devices 65 /// 66 /// This section provides a guideline to implement bus specific devices, such as [`pci::Device`] or 67 /// [`platform::Device`]. 68 /// 69 /// A bus specific device should be defined as follows. 70 /// 71 /// ```ignore 72 /// #[repr(transparent)] 73 /// pub struct Device<Ctx: device::DeviceContext = device::Normal>( 74 /// Opaque<bindings::bus_device_type>, 75 /// PhantomData<Ctx>, 76 /// ); 77 /// ``` 78 /// 79 /// Since devices are reference counted, [`AlwaysRefCounted`] should be implemented for `Device` 80 /// (i.e. `Device<Normal>`). Note that [`AlwaysRefCounted`] must not be implemented for any other 81 /// [`DeviceContext`], since all other device context types are only valid within a certain scope. 82 /// 83 /// In order to be able to implement the [`DeviceContext`] dereference hierarchy, bus device 84 /// implementations should call the [`impl_device_context_deref`] macro as shown below. 85 /// 86 /// ```ignore 87 /// // SAFETY: `Device` is a transparent wrapper of a type that doesn't depend on `Device`'s 88 /// // generic argument. 89 /// kernel::impl_device_context_deref!(unsafe { Device }); 90 /// ``` 91 /// 92 /// In order to convert from a any [`Device<Ctx>`] to [`ARef<Device>`], bus devices can implement 93 /// the following macro call. 94 /// 95 /// ```ignore 96 /// kernel::impl_device_context_into_aref!(Device); 97 /// ``` 98 /// 99 /// Bus devices should also implement the following [`AsRef`] implementation, such that users can 100 /// easily derive a generic [`Device`] reference. 101 /// 102 /// ```ignore 103 /// impl<Ctx: device::DeviceContext> AsRef<device::Device<Ctx>> for Device<Ctx> { 104 /// fn as_ref(&self) -> &device::Device<Ctx> { 105 /// ... 106 /// } 107 /// } 108 /// ``` 109 /// 110 /// # Implementing Class Devices 111 /// 112 /// Class device implementations require less infrastructure and depend slightly more on the 113 /// specific subsystem. 114 /// 115 /// An example implementation for a class device could look like this. 116 /// 117 /// ```ignore 118 /// #[repr(C)] 119 /// pub struct Device<T: class::Driver> { 120 /// dev: Opaque<bindings::class_device_type>, 121 /// data: T::Data, 122 /// } 123 /// ``` 124 /// 125 /// This class device uses the sub-classing pattern to embed the driver's private data within the 126 /// allocation of the class device. For this to be possible the class device is generic over the 127 /// class specific `Driver` trait implementation. 128 /// 129 /// Just like any device, class devices are reference counted and should hence implement 130 /// [`AlwaysRefCounted`] for `Device`. 131 /// 132 /// Class devices should also implement the following [`AsRef`] implementation, such that users can 133 /// easily derive a generic [`Device`] reference. 134 /// 135 /// ```ignore 136 /// impl<T: class::Driver> AsRef<device::Device> for Device<T> { 137 /// fn as_ref(&self) -> &device::Device { 138 /// ... 139 /// } 140 /// } 141 /// ``` 142 /// 143 /// An example for a class device implementation is 144 #[cfg_attr(CONFIG_DRM = "y", doc = "[`drm::Device`](kernel::drm::Device).")] 145 #[cfg_attr(not(CONFIG_DRM = "y"), doc = "`drm::Device`.")] 146 /// 147 /// # Invariants 148 /// 149 /// A `Device` instance represents a valid `struct device` created by the C portion of the kernel. 150 /// 151 /// Instances of this type are always reference-counted, that is, a call to `get_device` ensures 152 /// that the allocation remains valid at least until the matching call to `put_device`. 153 /// 154 /// `bindings::device::release` is valid to be called from any thread, hence `ARef<Device>` can be 155 /// dropped from any thread. 156 /// 157 /// [`AlwaysRefCounted`]: kernel::types::AlwaysRefCounted 158 /// [`impl_device_context_deref`]: kernel::impl_device_context_deref 159 /// [`pci::Device`]: kernel::pci::Device 160 /// [`platform::Device`]: kernel::platform::Device 161 #[repr(transparent)] 162 pub struct Device<Ctx: DeviceContext = Normal>(Opaque<bindings::device>, PhantomData<Ctx>); 163 164 impl Device { 165 /// Creates a new reference-counted abstraction instance of an existing `struct device` pointer. 166 /// 167 /// # Safety 168 /// 169 /// Callers must ensure that `ptr` is valid, non-null, and has a non-zero reference count, 170 /// i.e. it must be ensured that the reference count of the C `struct device` `ptr` points to 171 /// can't drop to zero, for the duration of this function call. 172 /// 173 /// It must also be ensured that `bindings::device::release` can be called from any thread. 174 /// While not officially documented, this should be the case for any `struct device`. get_device(ptr: *mut bindings::device) -> ARef<Self>175 pub unsafe fn get_device(ptr: *mut bindings::device) -> ARef<Self> { 176 // SAFETY: By the safety requirements ptr is valid 177 unsafe { Self::from_raw(ptr) }.into() 178 } 179 180 /// Convert a [`&Device`](Device) into a [`&Device<Bound>`](Device<Bound>). 181 /// 182 /// # Safety 183 /// 184 /// The caller is responsible to ensure that the returned [`&Device<Bound>`](Device<Bound>) 185 /// only lives as long as it can be guaranteed that the [`Device`] is actually bound. as_bound(&self) -> &Device<Bound>186 pub unsafe fn as_bound(&self) -> &Device<Bound> { 187 let ptr = core::ptr::from_ref(self); 188 189 // CAST: By the safety requirements the caller is responsible to guarantee that the 190 // returned reference only lives as long as the device is actually bound. 191 let ptr = ptr.cast(); 192 193 // SAFETY: 194 // - `ptr` comes from `from_ref(self)` above, hence it's guaranteed to be valid. 195 // - Any valid `Device` pointer is also a valid pointer for `Device<Bound>`. 196 unsafe { &*ptr } 197 } 198 } 199 200 impl Device<CoreInternal> { 201 /// Store a pointer to the bound driver's private data. set_drvdata(&self, data: impl ForeignOwnable)202 pub fn set_drvdata(&self, data: impl ForeignOwnable) { 203 // SAFETY: By the type invariants, `self.as_raw()` is a valid pointer to a `struct device`. 204 unsafe { bindings::dev_set_drvdata(self.as_raw(), data.into_foreign().cast()) } 205 } 206 207 /// Take ownership of the private data stored in this [`Device`]. 208 /// 209 /// # Safety 210 /// 211 /// - Must only be called once after a preceding call to [`Device::set_drvdata`]. 212 /// - The type `T` must match the type of the `ForeignOwnable` previously stored by 213 /// [`Device::set_drvdata`]. drvdata_obtain<T: ForeignOwnable>(&self) -> T214 pub unsafe fn drvdata_obtain<T: ForeignOwnable>(&self) -> T { 215 // SAFETY: By the type invariants, `self.as_raw()` is a valid pointer to a `struct device`. 216 let ptr = unsafe { bindings::dev_get_drvdata(self.as_raw()) }; 217 218 // SAFETY: 219 // - By the safety requirements of this function, `ptr` comes from a previous call to 220 // `into_foreign()`. 221 // - `dev_get_drvdata()` guarantees to return the same pointer given to `dev_set_drvdata()` 222 // in `into_foreign()`. 223 unsafe { T::from_foreign(ptr.cast()) } 224 } 225 226 /// Borrow the driver's private data bound to this [`Device`]. 227 /// 228 /// # Safety 229 /// 230 /// - Must only be called after a preceding call to [`Device::set_drvdata`] and before 231 /// [`Device::drvdata_obtain`]. 232 /// - The type `T` must match the type of the `ForeignOwnable` previously stored by 233 /// [`Device::set_drvdata`]. drvdata_borrow<T: ForeignOwnable>(&self) -> T::Borrowed<'_>234 pub unsafe fn drvdata_borrow<T: ForeignOwnable>(&self) -> T::Borrowed<'_> { 235 // SAFETY: By the type invariants, `self.as_raw()` is a valid pointer to a `struct device`. 236 let ptr = unsafe { bindings::dev_get_drvdata(self.as_raw()) }; 237 238 // SAFETY: 239 // - By the safety requirements of this function, `ptr` comes from a previous call to 240 // `into_foreign()`. 241 // - `dev_get_drvdata()` guarantees to return the same pointer given to `dev_set_drvdata()` 242 // in `into_foreign()`. 243 unsafe { T::borrow(ptr.cast()) } 244 } 245 } 246 247 impl<Ctx: DeviceContext> Device<Ctx> { 248 /// Obtain the raw `struct device *`. as_raw(&self) -> *mut bindings::device249 pub(crate) fn as_raw(&self) -> *mut bindings::device { 250 self.0.get() 251 } 252 253 /// Returns a reference to the parent device, if any. 254 #[cfg_attr(not(CONFIG_AUXILIARY_BUS), expect(dead_code))] parent(&self) -> Option<&Device>255 pub(crate) fn parent(&self) -> Option<&Device> { 256 // SAFETY: 257 // - By the type invariant `self.as_raw()` is always valid. 258 // - The parent device is only ever set at device creation. 259 let parent = unsafe { (*self.as_raw()).parent }; 260 261 if parent.is_null() { 262 None 263 } else { 264 // SAFETY: 265 // - Since `parent` is not NULL, it must be a valid pointer to a `struct device`. 266 // - `parent` is valid for the lifetime of `self`, since a `struct device` holds a 267 // reference count of its parent. 268 Some(unsafe { Device::from_raw(parent) }) 269 } 270 } 271 272 /// Convert a raw C `struct device` pointer to a `&'a Device`. 273 /// 274 /// # Safety 275 /// 276 /// Callers must ensure that `ptr` is valid, non-null, and has a non-zero reference count, 277 /// i.e. it must be ensured that the reference count of the C `struct device` `ptr` points to 278 /// can't drop to zero, for the duration of this function call and the entire duration when the 279 /// returned reference exists. from_raw<'a>(ptr: *mut bindings::device) -> &'a Self280 pub unsafe fn from_raw<'a>(ptr: *mut bindings::device) -> &'a Self { 281 // SAFETY: Guaranteed by the safety requirements of the function. 282 unsafe { &*ptr.cast() } 283 } 284 285 /// Prints an emergency-level message (level 0) prefixed with device information. 286 /// 287 /// More details are available from [`dev_emerg`]. 288 /// 289 /// [`dev_emerg`]: crate::dev_emerg pr_emerg(&self, args: fmt::Arguments<'_>)290 pub fn pr_emerg(&self, args: fmt::Arguments<'_>) { 291 // SAFETY: `klevel` is null-terminated, uses one of the kernel constants. 292 unsafe { self.printk(bindings::KERN_EMERG, args) }; 293 } 294 295 /// Prints an alert-level message (level 1) prefixed with device information. 296 /// 297 /// More details are available from [`dev_alert`]. 298 /// 299 /// [`dev_alert`]: crate::dev_alert pr_alert(&self, args: fmt::Arguments<'_>)300 pub fn pr_alert(&self, args: fmt::Arguments<'_>) { 301 // SAFETY: `klevel` is null-terminated, uses one of the kernel constants. 302 unsafe { self.printk(bindings::KERN_ALERT, args) }; 303 } 304 305 /// Prints a critical-level message (level 2) prefixed with device information. 306 /// 307 /// More details are available from [`dev_crit`]. 308 /// 309 /// [`dev_crit`]: crate::dev_crit pr_crit(&self, args: fmt::Arguments<'_>)310 pub fn pr_crit(&self, args: fmt::Arguments<'_>) { 311 // SAFETY: `klevel` is null-terminated, uses one of the kernel constants. 312 unsafe { self.printk(bindings::KERN_CRIT, args) }; 313 } 314 315 /// Prints an error-level message (level 3) prefixed with device information. 316 /// 317 /// More details are available from [`dev_err`]. 318 /// 319 /// [`dev_err`]: crate::dev_err pr_err(&self, args: fmt::Arguments<'_>)320 pub fn pr_err(&self, args: fmt::Arguments<'_>) { 321 // SAFETY: `klevel` is null-terminated, uses one of the kernel constants. 322 unsafe { self.printk(bindings::KERN_ERR, args) }; 323 } 324 325 /// Prints a warning-level message (level 4) prefixed with device information. 326 /// 327 /// More details are available from [`dev_warn`]. 328 /// 329 /// [`dev_warn`]: crate::dev_warn pr_warn(&self, args: fmt::Arguments<'_>)330 pub fn pr_warn(&self, args: fmt::Arguments<'_>) { 331 // SAFETY: `klevel` is null-terminated, uses one of the kernel constants. 332 unsafe { self.printk(bindings::KERN_WARNING, args) }; 333 } 334 335 /// Prints a notice-level message (level 5) prefixed with device information. 336 /// 337 /// More details are available from [`dev_notice`]. 338 /// 339 /// [`dev_notice`]: crate::dev_notice pr_notice(&self, args: fmt::Arguments<'_>)340 pub fn pr_notice(&self, args: fmt::Arguments<'_>) { 341 // SAFETY: `klevel` is null-terminated, uses one of the kernel constants. 342 unsafe { self.printk(bindings::KERN_NOTICE, args) }; 343 } 344 345 /// Prints an info-level message (level 6) prefixed with device information. 346 /// 347 /// More details are available from [`dev_info`]. 348 /// 349 /// [`dev_info`]: crate::dev_info pr_info(&self, args: fmt::Arguments<'_>)350 pub fn pr_info(&self, args: fmt::Arguments<'_>) { 351 // SAFETY: `klevel` is null-terminated, uses one of the kernel constants. 352 unsafe { self.printk(bindings::KERN_INFO, args) }; 353 } 354 355 /// Prints a debug-level message (level 7) prefixed with device information. 356 /// 357 /// More details are available from [`dev_dbg`]. 358 /// 359 /// [`dev_dbg`]: crate::dev_dbg pr_dbg(&self, args: fmt::Arguments<'_>)360 pub fn pr_dbg(&self, args: fmt::Arguments<'_>) { 361 if cfg!(debug_assertions) { 362 // SAFETY: `klevel` is null-terminated, uses one of the kernel constants. 363 unsafe { self.printk(bindings::KERN_DEBUG, args) }; 364 } 365 } 366 367 /// Prints the provided message to the console. 368 /// 369 /// # Safety 370 /// 371 /// Callers must ensure that `klevel` is null-terminated; in particular, one of the 372 /// `KERN_*`constants, for example, `KERN_CRIT`, `KERN_ALERT`, etc. 373 #[cfg_attr(not(CONFIG_PRINTK), allow(unused_variables))] printk(&self, klevel: &[u8], msg: fmt::Arguments<'_>)374 unsafe fn printk(&self, klevel: &[u8], msg: fmt::Arguments<'_>) { 375 // SAFETY: `klevel` is null-terminated and one of the kernel constants. `self.as_raw` 376 // is valid because `self` is valid. The "%pA" format string expects a pointer to 377 // `fmt::Arguments`, which is what we're passing as the last argument. 378 #[cfg(CONFIG_PRINTK)] 379 unsafe { 380 bindings::_dev_printk( 381 klevel.as_ptr().cast::<crate::ffi::c_char>(), 382 self.as_raw(), 383 c_str!("%pA").as_char_ptr(), 384 core::ptr::from_ref(&msg).cast::<crate::ffi::c_void>(), 385 ) 386 }; 387 } 388 389 /// Obtain the [`FwNode`](property::FwNode) corresponding to this [`Device`]. fwnode(&self) -> Option<&property::FwNode>390 pub fn fwnode(&self) -> Option<&property::FwNode> { 391 // SAFETY: `self` is valid. 392 let fwnode_handle = unsafe { bindings::__dev_fwnode(self.as_raw()) }; 393 if fwnode_handle.is_null() { 394 return None; 395 } 396 // SAFETY: `fwnode_handle` is valid. Its lifetime is tied to `&self`. We 397 // return a reference instead of an `ARef<FwNode>` because `dev_fwnode()` 398 // doesn't increment the refcount. It is safe to cast from a 399 // `struct fwnode_handle*` to a `*const FwNode` because `FwNode` is 400 // defined as a `#[repr(transparent)]` wrapper around `fwnode_handle`. 401 Some(unsafe { &*fwnode_handle.cast() }) 402 } 403 } 404 405 // SAFETY: `Device` is a transparent wrapper of a type that doesn't depend on `Device`'s generic 406 // argument. 407 kernel::impl_device_context_deref!(unsafe { Device }); 408 kernel::impl_device_context_into_aref!(Device); 409 410 // SAFETY: Instances of `Device` are always reference-counted. 411 unsafe impl crate::sync::aref::AlwaysRefCounted for Device { inc_ref(&self)412 fn inc_ref(&self) { 413 // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero. 414 unsafe { bindings::get_device(self.as_raw()) }; 415 } 416 dec_ref(obj: ptr::NonNull<Self>)417 unsafe fn dec_ref(obj: ptr::NonNull<Self>) { 418 // SAFETY: The safety requirements guarantee that the refcount is non-zero. 419 unsafe { bindings::put_device(obj.cast().as_ptr()) } 420 } 421 } 422 423 // SAFETY: As by the type invariant `Device` can be sent to any thread. 424 unsafe impl Send for Device {} 425 426 // SAFETY: `Device` can be shared among threads because all immutable methods are protected by the 427 // synchronization in `struct device`. 428 unsafe impl Sync for Device {} 429 430 /// Marker trait for the context or scope of a bus specific device. 431 /// 432 /// [`DeviceContext`] is a marker trait for types representing the context of a bus specific 433 /// [`Device`]. 434 /// 435 /// The specific device context types are: [`CoreInternal`], [`Core`], [`Bound`] and [`Normal`]. 436 /// 437 /// [`DeviceContext`] types are hierarchical, which means that there is a strict hierarchy that 438 /// defines which [`DeviceContext`] type can be derived from another. For instance, any 439 /// [`Device<Core>`] can dereference to a [`Device<Bound>`]. 440 /// 441 /// The following enumeration illustrates the dereference hierarchy of [`DeviceContext`] types. 442 /// 443 /// - [`CoreInternal`] => [`Core`] => [`Bound`] => [`Normal`] 444 /// 445 /// Bus devices can automatically implement the dereference hierarchy by using 446 /// [`impl_device_context_deref`]. 447 /// 448 /// Note that the guarantee for a [`Device`] reference to have a certain [`DeviceContext`] comes 449 /// from the specific scope the [`Device`] reference is valid in. 450 /// 451 /// [`impl_device_context_deref`]: kernel::impl_device_context_deref 452 pub trait DeviceContext: private::Sealed {} 453 454 /// The [`Normal`] context is the default [`DeviceContext`] of any [`Device`]. 455 /// 456 /// The normal context does not indicate any specific context. Any `Device<Ctx>` is also a valid 457 /// [`Device<Normal>`]. It is the only [`DeviceContext`] for which it is valid to implement 458 /// [`AlwaysRefCounted`] for. 459 /// 460 /// [`AlwaysRefCounted`]: kernel::types::AlwaysRefCounted 461 pub struct Normal; 462 463 /// The [`Core`] context is the context of a bus specific device when it appears as argument of 464 /// any bus specific callback, such as `probe()`. 465 /// 466 /// The core context indicates that the [`Device<Core>`] reference's scope is limited to the bus 467 /// callback it appears in. It is intended to be used for synchronization purposes. Bus device 468 /// implementations can implement methods for [`Device<Core>`], such that they can only be called 469 /// from bus callbacks. 470 pub struct Core; 471 472 /// Semantically the same as [`Core`], but reserved for internal usage of the corresponding bus 473 /// abstraction. 474 /// 475 /// The internal core context is intended to be used in exactly the same way as the [`Core`] 476 /// context, with the difference that this [`DeviceContext`] is internal to the corresponding bus 477 /// abstraction. 478 /// 479 /// This context mainly exists to share generic [`Device`] infrastructure that should only be called 480 /// from bus callbacks with bus abstractions, but without making them accessible for drivers. 481 pub struct CoreInternal; 482 483 /// The [`Bound`] context is the [`DeviceContext`] of a bus specific device when it is guaranteed to 484 /// be bound to a driver. 485 /// 486 /// The bound context indicates that for the entire duration of the lifetime of a [`Device<Bound>`] 487 /// reference, the [`Device`] is guaranteed to be bound to a driver. 488 /// 489 /// Some APIs, such as [`dma::CoherentAllocation`] or [`Devres`] rely on the [`Device`] to be bound, 490 /// which can be proven with the [`Bound`] device context. 491 /// 492 /// Any abstraction that can guarantee a scope where the corresponding bus device is bound, should 493 /// provide a [`Device<Bound>`] reference to its users for this scope. This allows users to benefit 494 /// from optimizations for accessing device resources, see also [`Devres::access`]. 495 /// 496 /// [`Devres`]: kernel::devres::Devres 497 /// [`Devres::access`]: kernel::devres::Devres::access 498 /// [`dma::CoherentAllocation`]: kernel::dma::CoherentAllocation 499 pub struct Bound; 500 501 mod private { 502 pub trait Sealed {} 503 504 impl Sealed for super::Bound {} 505 impl Sealed for super::Core {} 506 impl Sealed for super::CoreInternal {} 507 impl Sealed for super::Normal {} 508 } 509 510 impl DeviceContext for Bound {} 511 impl DeviceContext for Core {} 512 impl DeviceContext for CoreInternal {} 513 impl DeviceContext for Normal {} 514 515 /// # Safety 516 /// 517 /// The type given as `$device` must be a transparent wrapper of a type that doesn't depend on the 518 /// generic argument of `$device`. 519 #[doc(hidden)] 520 #[macro_export] 521 macro_rules! __impl_device_context_deref { 522 (unsafe { $device:ident, $src:ty => $dst:ty }) => { 523 impl ::core::ops::Deref for $device<$src> { 524 type Target = $device<$dst>; 525 526 fn deref(&self) -> &Self::Target { 527 let ptr: *const Self = self; 528 529 // CAST: `$device<$src>` and `$device<$dst>` transparently wrap the same type by the 530 // safety requirement of the macro. 531 let ptr = ptr.cast::<Self::Target>(); 532 533 // SAFETY: `ptr` was derived from `&self`. 534 unsafe { &*ptr } 535 } 536 } 537 }; 538 } 539 540 /// Implement [`core::ops::Deref`] traits for allowed [`DeviceContext`] conversions of a (bus 541 /// specific) device. 542 /// 543 /// # Safety 544 /// 545 /// The type given as `$device` must be a transparent wrapper of a type that doesn't depend on the 546 /// generic argument of `$device`. 547 #[macro_export] 548 macro_rules! impl_device_context_deref { 549 (unsafe { $device:ident }) => { 550 // SAFETY: This macro has the exact same safety requirement as 551 // `__impl_device_context_deref!`. 552 ::kernel::__impl_device_context_deref!(unsafe { 553 $device, 554 $crate::device::CoreInternal => $crate::device::Core 555 }); 556 557 // SAFETY: This macro has the exact same safety requirement as 558 // `__impl_device_context_deref!`. 559 ::kernel::__impl_device_context_deref!(unsafe { 560 $device, 561 $crate::device::Core => $crate::device::Bound 562 }); 563 564 // SAFETY: This macro has the exact same safety requirement as 565 // `__impl_device_context_deref!`. 566 ::kernel::__impl_device_context_deref!(unsafe { 567 $device, 568 $crate::device::Bound => $crate::device::Normal 569 }); 570 }; 571 } 572 573 #[doc(hidden)] 574 #[macro_export] 575 macro_rules! __impl_device_context_into_aref { 576 ($src:ty, $device:tt) => { 577 impl ::core::convert::From<&$device<$src>> for $crate::sync::aref::ARef<$device> { 578 fn from(dev: &$device<$src>) -> Self { 579 (&**dev).into() 580 } 581 } 582 }; 583 } 584 585 /// Implement [`core::convert::From`], such that all `&Device<Ctx>` can be converted to an 586 /// `ARef<Device>`. 587 #[macro_export] 588 macro_rules! impl_device_context_into_aref { 589 ($device:tt) => { 590 ::kernel::__impl_device_context_into_aref!($crate::device::CoreInternal, $device); 591 ::kernel::__impl_device_context_into_aref!($crate::device::Core, $device); 592 ::kernel::__impl_device_context_into_aref!($crate::device::Bound, $device); 593 }; 594 } 595 596 #[doc(hidden)] 597 #[macro_export] 598 macro_rules! dev_printk { 599 ($method:ident, $dev:expr, $($f:tt)*) => { 600 { 601 ($dev).$method($crate::prelude::fmt!($($f)*)); 602 } 603 } 604 } 605 606 /// Prints an emergency-level message (level 0) prefixed with device information. 607 /// 608 /// This level should be used if the system is unusable. 609 /// 610 /// Equivalent to the kernel's `dev_emerg` macro. 611 /// 612 /// Mimics the interface of [`std::print!`]. More information about the syntax is available from 613 /// [`core::fmt`] and [`std::format!`]. 614 /// 615 /// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html 616 /// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html 617 /// 618 /// # Examples 619 /// 620 /// ``` 621 /// # use kernel::device::Device; 622 /// 623 /// fn example(dev: &Device) { 624 /// dev_emerg!(dev, "hello {}\n", "there"); 625 /// } 626 /// ``` 627 #[macro_export] 628 macro_rules! dev_emerg { 629 ($($f:tt)*) => { $crate::dev_printk!(pr_emerg, $($f)*); } 630 } 631 632 /// Prints an alert-level message (level 1) prefixed with device information. 633 /// 634 /// This level should be used if action must be taken immediately. 635 /// 636 /// Equivalent to the kernel's `dev_alert` macro. 637 /// 638 /// Mimics the interface of [`std::print!`]. More information about the syntax is available from 639 /// [`core::fmt`] and [`std::format!`]. 640 /// 641 /// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html 642 /// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html 643 /// 644 /// # Examples 645 /// 646 /// ``` 647 /// # use kernel::device::Device; 648 /// 649 /// fn example(dev: &Device) { 650 /// dev_alert!(dev, "hello {}\n", "there"); 651 /// } 652 /// ``` 653 #[macro_export] 654 macro_rules! dev_alert { 655 ($($f:tt)*) => { $crate::dev_printk!(pr_alert, $($f)*); } 656 } 657 658 /// Prints a critical-level message (level 2) prefixed with device information. 659 /// 660 /// This level should be used in critical conditions. 661 /// 662 /// Equivalent to the kernel's `dev_crit` macro. 663 /// 664 /// Mimics the interface of [`std::print!`]. More information about the syntax is available from 665 /// [`core::fmt`] and [`std::format!`]. 666 /// 667 /// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html 668 /// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html 669 /// 670 /// # Examples 671 /// 672 /// ``` 673 /// # use kernel::device::Device; 674 /// 675 /// fn example(dev: &Device) { 676 /// dev_crit!(dev, "hello {}\n", "there"); 677 /// } 678 /// ``` 679 #[macro_export] 680 macro_rules! dev_crit { 681 ($($f:tt)*) => { $crate::dev_printk!(pr_crit, $($f)*); } 682 } 683 684 /// Prints an error-level message (level 3) prefixed with device information. 685 /// 686 /// This level should be used in error conditions. 687 /// 688 /// Equivalent to the kernel's `dev_err` macro. 689 /// 690 /// Mimics the interface of [`std::print!`]. More information about the syntax is available from 691 /// [`core::fmt`] and [`std::format!`]. 692 /// 693 /// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html 694 /// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html 695 /// 696 /// # Examples 697 /// 698 /// ``` 699 /// # use kernel::device::Device; 700 /// 701 /// fn example(dev: &Device) { 702 /// dev_err!(dev, "hello {}\n", "there"); 703 /// } 704 /// ``` 705 #[macro_export] 706 macro_rules! dev_err { 707 ($($f:tt)*) => { $crate::dev_printk!(pr_err, $($f)*); } 708 } 709 710 /// Prints a warning-level message (level 4) prefixed with device information. 711 /// 712 /// This level should be used in warning conditions. 713 /// 714 /// Equivalent to the kernel's `dev_warn` macro. 715 /// 716 /// Mimics the interface of [`std::print!`]. More information about the syntax is available from 717 /// [`core::fmt`] and [`std::format!`]. 718 /// 719 /// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html 720 /// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html 721 /// 722 /// # Examples 723 /// 724 /// ``` 725 /// # use kernel::device::Device; 726 /// 727 /// fn example(dev: &Device) { 728 /// dev_warn!(dev, "hello {}\n", "there"); 729 /// } 730 /// ``` 731 #[macro_export] 732 macro_rules! dev_warn { 733 ($($f:tt)*) => { $crate::dev_printk!(pr_warn, $($f)*); } 734 } 735 736 /// Prints a notice-level message (level 5) prefixed with device information. 737 /// 738 /// This level should be used in normal but significant conditions. 739 /// 740 /// Equivalent to the kernel's `dev_notice` macro. 741 /// 742 /// Mimics the interface of [`std::print!`]. More information about the syntax is available from 743 /// [`core::fmt`] and [`std::format!`]. 744 /// 745 /// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html 746 /// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html 747 /// 748 /// # Examples 749 /// 750 /// ``` 751 /// # use kernel::device::Device; 752 /// 753 /// fn example(dev: &Device) { 754 /// dev_notice!(dev, "hello {}\n", "there"); 755 /// } 756 /// ``` 757 #[macro_export] 758 macro_rules! dev_notice { 759 ($($f:tt)*) => { $crate::dev_printk!(pr_notice, $($f)*); } 760 } 761 762 /// Prints an info-level message (level 6) prefixed with device information. 763 /// 764 /// This level should be used for informational messages. 765 /// 766 /// Equivalent to the kernel's `dev_info` macro. 767 /// 768 /// Mimics the interface of [`std::print!`]. More information about the syntax is available from 769 /// [`core::fmt`] and [`std::format!`]. 770 /// 771 /// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html 772 /// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html 773 /// 774 /// # Examples 775 /// 776 /// ``` 777 /// # use kernel::device::Device; 778 /// 779 /// fn example(dev: &Device) { 780 /// dev_info!(dev, "hello {}\n", "there"); 781 /// } 782 /// ``` 783 #[macro_export] 784 macro_rules! dev_info { 785 ($($f:tt)*) => { $crate::dev_printk!(pr_info, $($f)*); } 786 } 787 788 /// Prints a debug-level message (level 7) prefixed with device information. 789 /// 790 /// This level should be used for debug messages. 791 /// 792 /// Equivalent to the kernel's `dev_dbg` macro, except that it doesn't support dynamic debug yet. 793 /// 794 /// Mimics the interface of [`std::print!`]. More information about the syntax is available from 795 /// [`core::fmt`] and [`std::format!`]. 796 /// 797 /// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html 798 /// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html 799 /// 800 /// # Examples 801 /// 802 /// ``` 803 /// # use kernel::device::Device; 804 /// 805 /// fn example(dev: &Device) { 806 /// dev_dbg!(dev, "hello {}\n", "there"); 807 /// } 808 /// ``` 809 #[macro_export] 810 macro_rules! dev_dbg { 811 ($($f:tt)*) => { $crate::dev_printk!(pr_dbg, $($f)*); } 812 } 813