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