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