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