// SPDX-License-Identifier: GPL-2.012//! Generic devices that are part of the kernel's driver model.3//!4//! C header: [`include/linux/device.h`](srctree/include/linux/device.h)56use crate::{7bindings, fmt,8prelude::*,9sync::aref::ARef,10types::{ForeignOwnable, Opaque},11};12use core::{any::TypeId, marker::PhantomData, ptr};1314#[cfg(CONFIG_PRINTK)]15use crate::c_str;1617pub mod property;1819// Assert that we can `read()` / `write()` a `TypeId` instance from / into `struct driver_type`.20static_assert!(core::mem::size_of::<bindings::driver_type>() >= core::mem::size_of::<TypeId>());2122/// 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 either25/// exist as temporary reference (see also [`Device::from_raw`]), which is only valid within a26/// certain scope or as [`ARef<Device>`], owning a dedicated reference count.27///28/// # Device Types29///30/// A [`Device`] can represent either a bus device or a class device.31///32/// ## Bus Devices33///34/// A bus device is a [`Device`] that is associated with a physical or virtual bus. Examples of35/// buses include PCI, USB, I2C, and SPI. Devices attached to a bus are registered with a specific36/// bus type, which facilitates matching devices with appropriate drivers based on IDs or other37/// identifying information. Bus devices are visible in sysfs under `/sys/bus/<bus-name>/devices/`.38///39/// ## Class Devices40///41/// A class device is a [`Device`] that is associated with a logical category of functionality42/// rather than a physical bus. Examples of classes include block devices, network interfaces, sound43/// cards, and input devices. Class devices are grouped under a common class and exposed to44/// userspace via entries in `/sys/class/<class-name>/`.45///46/// # Device Context47///48/// [`Device`] references are generic over a [`DeviceContext`], which represents the type state of49/// 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`] is53/// 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 by58/// 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 with64/// [bus devices](#bus-devices) only.65///66/// # Implementing Bus Devices67///68/// This section provides a guideline to implement bus specific devices, such as:69#[cfg_attr(CONFIG_PCI, doc = "* [`pci::Device`](kernel::pci::Device)")]70/// * [`platform::Device`]71///72/// A bus specific device should be defined as follows.73///74/// ```ignore75/// #[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 other84/// [`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 device87/// implementations should call the [`impl_device_context_deref`] macro as shown below.88///89/// ```ignore90/// // SAFETY: `Device` is a transparent wrapper of a type that doesn't depend on `Device`'s91/// // 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 implement96/// the following macro call.97///98/// ```ignore99/// kernel::impl_device_context_into_aref!(Device);100/// ```101///102/// Bus devices should also implement the following [`AsRef`] implementation, such that users can103/// easily derive a generic [`Device`] reference.104///105/// ```ignore106/// 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 Devices114///115/// Class device implementations require less infrastructure and depend slightly more on the116/// specific subsystem.117///118/// An example implementation for a class device could look like this.119///120/// ```ignore121/// #[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 the129/// allocation of the class device. For this to be possible the class device is generic over the130/// class specific `Driver` trait implementation.131///132/// Just like any device, class devices are reference counted and should hence implement133/// [`AlwaysRefCounted`] for `Device`.134///135/// Class devices should also implement the following [`AsRef`] implementation, such that users can136/// easily derive a generic [`Device`] reference.137///138/// ```ignore139/// 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 is147#[cfg_attr(CONFIG_DRM = "y", doc = "[`drm::Device`](kernel::drm::Device).")]148#[cfg_attr(not(CONFIG_DRM = "y"), doc = "`drm::Device`.")]149///150/// # Invariants151///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` ensures155/// 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 be158/// dropped from any thread.159///160/// [`AlwaysRefCounted`]: kernel::types::AlwaysRefCounted161/// [`impl_device_context_deref`]: kernel::impl_device_context_deref162/// [`platform::Device`]: kernel::platform::Device163#[repr(transparent)]164pub struct Device<Ctx: DeviceContext = Normal>(Opaque<bindings::device>, PhantomData<Ctx>);165166impl Device {167/// Creates a new reference-counted abstraction instance of an existing `struct device` pointer.168///169/// # Safety170///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 to173/// 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`.177pub unsafe fn get_device(ptr: *mut bindings::device) -> ARef<Self> {178// SAFETY: By the safety requirements ptr is valid179unsafe { Self::from_raw(ptr) }.into()180}181182/// Convert a [`&Device`](Device) into a [`&Device<Bound>`](Device<Bound>).183///184/// # Safety185///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.188pub unsafe fn as_bound(&self) -> &Device<Bound> {189let ptr = core::ptr::from_ref(self);190191// CAST: By the safety requirements the caller is responsible to guarantee that the192// returned reference only lives as long as the device is actually bound.193let ptr = ptr.cast();194195// 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>`.198unsafe { &*ptr }199}200}201202impl Device<CoreInternal> {203fn set_type_id<T: 'static>(&self) {204// SAFETY: By the type invariants, `self.as_raw()` is a valid pointer to a `struct device`.205let private = unsafe { (*self.as_raw()).p };206207// SAFETY: For a bound device (implied by the `CoreInternal` device context), `private` is208// guaranteed to be a valid pointer to a `struct device_private`.209let driver_type = unsafe { &raw mut (*private).driver_type };210211// SAFETY: `driver_type` is valid for (unaligned) writes of a `TypeId`.212unsafe {213driver_type214.cast::<TypeId>()215.write_unaligned(TypeId::of::<T>())216};217}218219/// Store a pointer to the bound driver's private data.220pub fn set_drvdata<T: 'static>(&self, data: impl PinInit<T, Error>) -> Result {221let data = KBox::pin_init(data, GFP_KERNEL)?;222223// SAFETY: By the type invariants, `self.as_raw()` is a valid pointer to a `struct device`.224unsafe { bindings::dev_set_drvdata(self.as_raw(), data.into_foreign().cast()) };225self.set_type_id::<T>();226227Ok(())228}229230/// Take ownership of the private data stored in this [`Device`].231///232/// # Safety233///234/// - The type `T` must match the type of the `ForeignOwnable` previously stored by235/// [`Device::set_drvdata`].236pub(crate) unsafe fn drvdata_obtain<T: 'static>(&self) -> Option<Pin<KBox<T>>> {237// SAFETY: By the type invariants, `self.as_raw()` is a valid pointer to a `struct device`.238let ptr = unsafe { bindings::dev_get_drvdata(self.as_raw()) };239240// SAFETY: By the type invariants, `self.as_raw()` is a valid pointer to a `struct device`.241unsafe { bindings::dev_set_drvdata(self.as_raw(), core::ptr::null_mut()) };242243if ptr.is_null() {244return None;245}246247// SAFETY:248// - If `ptr` is not NULL, it comes from a previous call to `into_foreign()`.249// - `dev_get_drvdata()` guarantees to return the same pointer given to `dev_set_drvdata()`250// in `into_foreign()`.251Some(unsafe { Pin::<KBox<T>>::from_foreign(ptr.cast()) })252}253254/// Borrow the driver's private data bound to this [`Device`].255///256/// # Safety257///258/// - Must only be called after a preceding call to [`Device::set_drvdata`] and before the259/// device is fully unbound.260/// - The type `T` must match the type of the `ForeignOwnable` previously stored by261/// [`Device::set_drvdata`].262pub unsafe fn drvdata_borrow<T: 'static>(&self) -> Pin<&T> {263// SAFETY: `drvdata_unchecked()` has the exact same safety requirements as the ones264// required by this method.265unsafe { self.drvdata_unchecked() }266}267}268269impl Device<Bound> {270/// Borrow the driver's private data bound to this [`Device`].271///272/// # Safety273///274/// - Must only be called after a preceding call to [`Device::set_drvdata`] and before275/// the device is fully unbound.276/// - The type `T` must match the type of the `ForeignOwnable` previously stored by277/// [`Device::set_drvdata`].278unsafe fn drvdata_unchecked<T: 'static>(&self) -> Pin<&T> {279// SAFETY: By the type invariants, `self.as_raw()` is a valid pointer to a `struct device`.280let ptr = unsafe { bindings::dev_get_drvdata(self.as_raw()) };281282// SAFETY:283// - By the safety requirements of this function, `ptr` comes from a previous call to284// `into_foreign()`.285// - `dev_get_drvdata()` guarantees to return the same pointer given to `dev_set_drvdata()`286// in `into_foreign()`.287unsafe { Pin::<KBox<T>>::borrow(ptr.cast()) }288}289290fn match_type_id<T: 'static>(&self) -> Result {291// SAFETY: By the type invariants, `self.as_raw()` is a valid pointer to a `struct device`.292let private = unsafe { (*self.as_raw()).p };293294// SAFETY: For a bound device, `private` is guaranteed to be a valid pointer to a295// `struct device_private`.296let driver_type = unsafe { &raw mut (*private).driver_type };297298// SAFETY:299// - `driver_type` is valid for (unaligned) reads of a `TypeId`.300// - A bound device guarantees that `driver_type` contains a valid `TypeId` value.301let type_id = unsafe { driver_type.cast::<TypeId>().read_unaligned() };302303if type_id != TypeId::of::<T>() {304return Err(EINVAL);305}306307Ok(())308}309310/// Access a driver's private data.311///312/// Returns a pinned reference to the driver's private data or [`EINVAL`] if it doesn't match313/// the asserted type `T`.314pub fn drvdata<T: 'static>(&self) -> Result<Pin<&T>> {315// SAFETY: By the type invariants, `self.as_raw()` is a valid pointer to a `struct device`.316if unsafe { bindings::dev_get_drvdata(self.as_raw()) }.is_null() {317return Err(ENOENT);318}319320self.match_type_id::<T>()?;321322// SAFETY:323// - The above check of `dev_get_drvdata()` guarantees that we are called after324// `set_drvdata()`.325// - We've just checked that the type of the driver's private data is in fact `T`.326Ok(unsafe { self.drvdata_unchecked() })327}328}329330impl<Ctx: DeviceContext> Device<Ctx> {331/// Obtain the raw `struct device *`.332pub(crate) fn as_raw(&self) -> *mut bindings::device {333self.0.get()334}335336/// Returns a reference to the parent device, if any.337#[cfg_attr(not(CONFIG_AUXILIARY_BUS), expect(dead_code))]338pub(crate) fn parent(&self) -> Option<&Device> {339// SAFETY:340// - By the type invariant `self.as_raw()` is always valid.341// - The parent device is only ever set at device creation.342let parent = unsafe { (*self.as_raw()).parent };343344if parent.is_null() {345None346} else {347// SAFETY:348// - Since `parent` is not NULL, it must be a valid pointer to a `struct device`.349// - `parent` is valid for the lifetime of `self`, since a `struct device` holds a350// reference count of its parent.351Some(unsafe { Device::from_raw(parent) })352}353}354355/// Convert a raw C `struct device` pointer to a `&'a Device`.356///357/// # Safety358///359/// Callers must ensure that `ptr` is valid, non-null, and has a non-zero reference count,360/// i.e. it must be ensured that the reference count of the C `struct device` `ptr` points to361/// can't drop to zero, for the duration of this function call and the entire duration when the362/// returned reference exists.363pub unsafe fn from_raw<'a>(ptr: *mut bindings::device) -> &'a Self {364// SAFETY: Guaranteed by the safety requirements of the function.365unsafe { &*ptr.cast() }366}367368/// Prints an emergency-level message (level 0) prefixed with device information.369///370/// More details are available from [`dev_emerg`].371///372/// [`dev_emerg`]: crate::dev_emerg373pub fn pr_emerg(&self, args: fmt::Arguments<'_>) {374// SAFETY: `klevel` is null-terminated, uses one of the kernel constants.375unsafe { self.printk(bindings::KERN_EMERG, args) };376}377378/// Prints an alert-level message (level 1) prefixed with device information.379///380/// More details are available from [`dev_alert`].381///382/// [`dev_alert`]: crate::dev_alert383pub fn pr_alert(&self, args: fmt::Arguments<'_>) {384// SAFETY: `klevel` is null-terminated, uses one of the kernel constants.385unsafe { self.printk(bindings::KERN_ALERT, args) };386}387388/// Prints a critical-level message (level 2) prefixed with device information.389///390/// More details are available from [`dev_crit`].391///392/// [`dev_crit`]: crate::dev_crit393pub fn pr_crit(&self, args: fmt::Arguments<'_>) {394// SAFETY: `klevel` is null-terminated, uses one of the kernel constants.395unsafe { self.printk(bindings::KERN_CRIT, args) };396}397398/// Prints an error-level message (level 3) prefixed with device information.399///400/// More details are available from [`dev_err`].401///402/// [`dev_err`]: crate::dev_err403pub fn pr_err(&self, args: fmt::Arguments<'_>) {404// SAFETY: `klevel` is null-terminated, uses one of the kernel constants.405unsafe { self.printk(bindings::KERN_ERR, args) };406}407408/// Prints a warning-level message (level 4) prefixed with device information.409///410/// More details are available from [`dev_warn`].411///412/// [`dev_warn`]: crate::dev_warn413pub fn pr_warn(&self, args: fmt::Arguments<'_>) {414// SAFETY: `klevel` is null-terminated, uses one of the kernel constants.415unsafe { self.printk(bindings::KERN_WARNING, args) };416}417418/// Prints a notice-level message (level 5) prefixed with device information.419///420/// More details are available from [`dev_notice`].421///422/// [`dev_notice`]: crate::dev_notice423pub fn pr_notice(&self, args: fmt::Arguments<'_>) {424// SAFETY: `klevel` is null-terminated, uses one of the kernel constants.425unsafe { self.printk(bindings::KERN_NOTICE, args) };426}427428/// Prints an info-level message (level 6) prefixed with device information.429///430/// More details are available from [`dev_info`].431///432/// [`dev_info`]: crate::dev_info433pub fn pr_info(&self, args: fmt::Arguments<'_>) {434// SAFETY: `klevel` is null-terminated, uses one of the kernel constants.435unsafe { self.printk(bindings::KERN_INFO, args) };436}437438/// Prints a debug-level message (level 7) prefixed with device information.439///440/// More details are available from [`dev_dbg`].441///442/// [`dev_dbg`]: crate::dev_dbg443pub fn pr_dbg(&self, args: fmt::Arguments<'_>) {444if cfg!(debug_assertions) {445// SAFETY: `klevel` is null-terminated, uses one of the kernel constants.446unsafe { self.printk(bindings::KERN_DEBUG, args) };447}448}449450/// Prints the provided message to the console.451///452/// # Safety453///454/// Callers must ensure that `klevel` is null-terminated; in particular, one of the455/// `KERN_*`constants, for example, `KERN_CRIT`, `KERN_ALERT`, etc.456#[cfg_attr(not(CONFIG_PRINTK), allow(unused_variables))]457unsafe fn printk(&self, klevel: &[u8], msg: fmt::Arguments<'_>) {458// SAFETY: `klevel` is null-terminated and one of the kernel constants. `self.as_raw`459// is valid because `self` is valid. The "%pA" format string expects a pointer to460// `fmt::Arguments`, which is what we're passing as the last argument.461#[cfg(CONFIG_PRINTK)]462unsafe {463bindings::_dev_printk(464klevel.as_ptr().cast::<crate::ffi::c_char>(),465self.as_raw(),466c_str!("%pA").as_char_ptr(),467core::ptr::from_ref(&msg).cast::<crate::ffi::c_void>(),468)469};470}471472/// Obtain the [`FwNode`](property::FwNode) corresponding to this [`Device`].473pub fn fwnode(&self) -> Option<&property::FwNode> {474// SAFETY: `self` is valid.475let fwnode_handle = unsafe { bindings::__dev_fwnode(self.as_raw()) };476if fwnode_handle.is_null() {477return None;478}479// SAFETY: `fwnode_handle` is valid. Its lifetime is tied to `&self`. We480// return a reference instead of an `ARef<FwNode>` because `dev_fwnode()`481// doesn't increment the refcount. It is safe to cast from a482// `struct fwnode_handle*` to a `*const FwNode` because `FwNode` is483// defined as a `#[repr(transparent)]` wrapper around `fwnode_handle`.484Some(unsafe { &*fwnode_handle.cast() })485}486}487488// SAFETY: `Device` is a transparent wrapper of a type that doesn't depend on `Device`'s generic489// argument.490kernel::impl_device_context_deref!(unsafe { Device });491kernel::impl_device_context_into_aref!(Device);492493// SAFETY: Instances of `Device` are always reference-counted.494unsafe impl crate::sync::aref::AlwaysRefCounted for Device {495fn inc_ref(&self) {496// SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.497unsafe { bindings::get_device(self.as_raw()) };498}499500unsafe fn dec_ref(obj: ptr::NonNull<Self>) {501// SAFETY: The safety requirements guarantee that the refcount is non-zero.502unsafe { bindings::put_device(obj.cast().as_ptr()) }503}504}505506// SAFETY: As by the type invariant `Device` can be sent to any thread.507unsafe impl Send for Device {}508509// SAFETY: `Device` can be shared among threads because all immutable methods are protected by the510// synchronization in `struct device`.511unsafe impl Sync for Device {}512513/// Marker trait for the context or scope of a bus specific device.514///515/// [`DeviceContext`] is a marker trait for types representing the context of a bus specific516/// [`Device`].517///518/// The specific device context types are: [`CoreInternal`], [`Core`], [`Bound`] and [`Normal`].519///520/// [`DeviceContext`] types are hierarchical, which means that there is a strict hierarchy that521/// defines which [`DeviceContext`] type can be derived from another. For instance, any522/// [`Device<Core>`] can dereference to a [`Device<Bound>`].523///524/// The following enumeration illustrates the dereference hierarchy of [`DeviceContext`] types.525///526/// - [`CoreInternal`] => [`Core`] => [`Bound`] => [`Normal`]527///528/// Bus devices can automatically implement the dereference hierarchy by using529/// [`impl_device_context_deref`].530///531/// Note that the guarantee for a [`Device`] reference to have a certain [`DeviceContext`] comes532/// from the specific scope the [`Device`] reference is valid in.533///534/// [`impl_device_context_deref`]: kernel::impl_device_context_deref535pub trait DeviceContext: private::Sealed {}536537/// The [`Normal`] context is the default [`DeviceContext`] of any [`Device`].538///539/// The normal context does not indicate any specific context. Any `Device<Ctx>` is also a valid540/// [`Device<Normal>`]. It is the only [`DeviceContext`] for which it is valid to implement541/// [`AlwaysRefCounted`] for.542///543/// [`AlwaysRefCounted`]: kernel::types::AlwaysRefCounted544pub struct Normal;545546/// The [`Core`] context is the context of a bus specific device when it appears as argument of547/// any bus specific callback, such as `probe()`.548///549/// The core context indicates that the [`Device<Core>`] reference's scope is limited to the bus550/// callback it appears in. It is intended to be used for synchronization purposes. Bus device551/// implementations can implement methods for [`Device<Core>`], such that they can only be called552/// from bus callbacks.553pub struct Core;554555/// Semantically the same as [`Core`], but reserved for internal usage of the corresponding bus556/// abstraction.557///558/// The internal core context is intended to be used in exactly the same way as the [`Core`]559/// context, with the difference that this [`DeviceContext`] is internal to the corresponding bus560/// abstraction.561///562/// This context mainly exists to share generic [`Device`] infrastructure that should only be called563/// from bus callbacks with bus abstractions, but without making them accessible for drivers.564pub struct CoreInternal;565566/// The [`Bound`] context is the [`DeviceContext`] of a bus specific device when it is guaranteed to567/// be bound to a driver.568///569/// The bound context indicates that for the entire duration of the lifetime of a [`Device<Bound>`]570/// reference, the [`Device`] is guaranteed to be bound to a driver.571///572/// Some APIs, such as [`dma::CoherentAllocation`] or [`Devres`] rely on the [`Device`] to be bound,573/// which can be proven with the [`Bound`] device context.574///575/// Any abstraction that can guarantee a scope where the corresponding bus device is bound, should576/// provide a [`Device<Bound>`] reference to its users for this scope. This allows users to benefit577/// from optimizations for accessing device resources, see also [`Devres::access`].578///579/// [`Devres`]: kernel::devres::Devres580/// [`Devres::access`]: kernel::devres::Devres::access581/// [`dma::CoherentAllocation`]: kernel::dma::CoherentAllocation582pub struct Bound;583584mod private {585pub trait Sealed {}586587impl Sealed for super::Bound {}588impl Sealed for super::Core {}589impl Sealed for super::CoreInternal {}590impl Sealed for super::Normal {}591}592593impl DeviceContext for Bound {}594impl DeviceContext for Core {}595impl DeviceContext for CoreInternal {}596impl DeviceContext for Normal {}597598/// Convert device references to bus device references.599///600/// Bus devices can implement this trait to allow abstractions to provide the bus device in601/// class device callbacks.602///603/// This must not be used by drivers and is intended for bus and class device abstractions only.604///605/// # Safety606///607/// `AsBusDevice::OFFSET` must be the offset of the embedded base `struct device` field within a608/// bus device structure.609pub unsafe trait AsBusDevice<Ctx: DeviceContext>: AsRef<Device<Ctx>> {610/// The relative offset to the device field.611///612/// Use `offset_of!(bindings, field)` macro to avoid breakage.613const OFFSET: usize;614615/// Convert a reference to [`Device`] into `Self`.616///617/// # Safety618///619/// `dev` must be contained in `Self`.620unsafe fn from_device(dev: &Device<Ctx>) -> &Self621where622Self: Sized,623{624let raw = dev.as_raw();625// SAFETY: `raw - Self::OFFSET` is guaranteed by the safety requirements626// to be a valid pointer to `Self`.627unsafe { &*raw.byte_sub(Self::OFFSET).cast::<Self>() }628}629}630631/// # Safety632///633/// The type given as `$device` must be a transparent wrapper of a type that doesn't depend on the634/// generic argument of `$device`.635#[doc(hidden)]636#[macro_export]637macro_rules! __impl_device_context_deref {638(unsafe { $device:ident, $src:ty => $dst:ty }) => {639impl ::core::ops::Deref for $device<$src> {640type Target = $device<$dst>;641642fn deref(&self) -> &Self::Target {643let ptr: *const Self = self;644645// CAST: `$device<$src>` and `$device<$dst>` transparently wrap the same type by the646// safety requirement of the macro.647let ptr = ptr.cast::<Self::Target>();648649// SAFETY: `ptr` was derived from `&self`.650unsafe { &*ptr }651}652}653};654}655656/// Implement [`core::ops::Deref`] traits for allowed [`DeviceContext`] conversions of a (bus657/// specific) device.658///659/// # Safety660///661/// The type given as `$device` must be a transparent wrapper of a type that doesn't depend on the662/// generic argument of `$device`.663#[macro_export]664macro_rules! impl_device_context_deref {665(unsafe { $device:ident }) => {666// SAFETY: This macro has the exact same safety requirement as667// `__impl_device_context_deref!`.668::kernel::__impl_device_context_deref!(unsafe {669$device,670$crate::device::CoreInternal => $crate::device::Core671});672673// SAFETY: This macro has the exact same safety requirement as674// `__impl_device_context_deref!`.675::kernel::__impl_device_context_deref!(unsafe {676$device,677$crate::device::Core => $crate::device::Bound678});679680// SAFETY: This macro has the exact same safety requirement as681// `__impl_device_context_deref!`.682::kernel::__impl_device_context_deref!(unsafe {683$device,684$crate::device::Bound => $crate::device::Normal685});686};687}688689#[doc(hidden)]690#[macro_export]691macro_rules! __impl_device_context_into_aref {692($src:ty, $device:tt) => {693impl ::core::convert::From<&$device<$src>> for $crate::sync::aref::ARef<$device> {694fn from(dev: &$device<$src>) -> Self {695(&**dev).into()696}697}698};699}700701/// Implement [`core::convert::From`], such that all `&Device<Ctx>` can be converted to an702/// `ARef<Device>`.703#[macro_export]704macro_rules! impl_device_context_into_aref {705($device:tt) => {706::kernel::__impl_device_context_into_aref!($crate::device::CoreInternal, $device);707::kernel::__impl_device_context_into_aref!($crate::device::Core, $device);708::kernel::__impl_device_context_into_aref!($crate::device::Bound, $device);709};710}711712#[doc(hidden)]713#[macro_export]714macro_rules! dev_printk {715($method:ident, $dev:expr, $($f:tt)*) => {716{717($dev).$method($crate::prelude::fmt!($($f)*));718}719}720}721722/// Prints an emergency-level message (level 0) prefixed with device information.723///724/// This level should be used if the system is unusable.725///726/// Equivalent to the kernel's `dev_emerg` macro.727///728/// Mimics the interface of [`std::print!`]. More information about the syntax is available from729/// [`core::fmt`] and [`std::format!`].730///731/// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html732/// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html733///734/// # Examples735///736/// ```737/// # use kernel::device::Device;738///739/// fn example(dev: &Device) {740/// dev_emerg!(dev, "hello {}\n", "there");741/// }742/// ```743#[macro_export]744macro_rules! dev_emerg {745($($f:tt)*) => { $crate::dev_printk!(pr_emerg, $($f)*); }746}747748/// Prints an alert-level message (level 1) prefixed with device information.749///750/// This level should be used if action must be taken immediately.751///752/// Equivalent to the kernel's `dev_alert` macro.753///754/// Mimics the interface of [`std::print!`]. More information about the syntax is available from755/// [`core::fmt`] and [`std::format!`].756///757/// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html758/// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html759///760/// # Examples761///762/// ```763/// # use kernel::device::Device;764///765/// fn example(dev: &Device) {766/// dev_alert!(dev, "hello {}\n", "there");767/// }768/// ```769#[macro_export]770macro_rules! dev_alert {771($($f:tt)*) => { $crate::dev_printk!(pr_alert, $($f)*); }772}773774/// Prints a critical-level message (level 2) prefixed with device information.775///776/// This level should be used in critical conditions.777///778/// Equivalent to the kernel's `dev_crit` macro.779///780/// Mimics the interface of [`std::print!`]. More information about the syntax is available from781/// [`core::fmt`] and [`std::format!`].782///783/// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html784/// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html785///786/// # Examples787///788/// ```789/// # use kernel::device::Device;790///791/// fn example(dev: &Device) {792/// dev_crit!(dev, "hello {}\n", "there");793/// }794/// ```795#[macro_export]796macro_rules! dev_crit {797($($f:tt)*) => { $crate::dev_printk!(pr_crit, $($f)*); }798}799800/// Prints an error-level message (level 3) prefixed with device information.801///802/// This level should be used in error conditions.803///804/// Equivalent to the kernel's `dev_err` macro.805///806/// Mimics the interface of [`std::print!`]. More information about the syntax is available from807/// [`core::fmt`] and [`std::format!`].808///809/// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html810/// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html811///812/// # Examples813///814/// ```815/// # use kernel::device::Device;816///817/// fn example(dev: &Device) {818/// dev_err!(dev, "hello {}\n", "there");819/// }820/// ```821#[macro_export]822macro_rules! dev_err {823($($f:tt)*) => { $crate::dev_printk!(pr_err, $($f)*); }824}825826/// Prints a warning-level message (level 4) prefixed with device information.827///828/// This level should be used in warning conditions.829///830/// Equivalent to the kernel's `dev_warn` macro.831///832/// Mimics the interface of [`std::print!`]. More information about the syntax is available from833/// [`core::fmt`] and [`std::format!`].834///835/// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html836/// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html837///838/// # Examples839///840/// ```841/// # use kernel::device::Device;842///843/// fn example(dev: &Device) {844/// dev_warn!(dev, "hello {}\n", "there");845/// }846/// ```847#[macro_export]848macro_rules! dev_warn {849($($f:tt)*) => { $crate::dev_printk!(pr_warn, $($f)*); }850}851852/// Prints a notice-level message (level 5) prefixed with device information.853///854/// This level should be used in normal but significant conditions.855///856/// Equivalent to the kernel's `dev_notice` macro.857///858/// Mimics the interface of [`std::print!`]. More information about the syntax is available from859/// [`core::fmt`] and [`std::format!`].860///861/// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html862/// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html863///864/// # Examples865///866/// ```867/// # use kernel::device::Device;868///869/// fn example(dev: &Device) {870/// dev_notice!(dev, "hello {}\n", "there");871/// }872/// ```873#[macro_export]874macro_rules! dev_notice {875($($f:tt)*) => { $crate::dev_printk!(pr_notice, $($f)*); }876}877878/// Prints an info-level message (level 6) prefixed with device information.879///880/// This level should be used for informational messages.881///882/// Equivalent to the kernel's `dev_info` macro.883///884/// Mimics the interface of [`std::print!`]. More information about the syntax is available from885/// [`core::fmt`] and [`std::format!`].886///887/// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html888/// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html889///890/// # Examples891///892/// ```893/// # use kernel::device::Device;894///895/// fn example(dev: &Device) {896/// dev_info!(dev, "hello {}\n", "there");897/// }898/// ```899#[macro_export]900macro_rules! dev_info {901($($f:tt)*) => { $crate::dev_printk!(pr_info, $($f)*); }902}903904/// Prints a debug-level message (level 7) prefixed with device information.905///906/// This level should be used for debug messages.907///908/// Equivalent to the kernel's `dev_dbg` macro, except that it doesn't support dynamic debug yet.909///910/// Mimics the interface of [`std::print!`]. More information about the syntax is available from911/// [`core::fmt`] and [`std::format!`].912///913/// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html914/// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html915///916/// # Examples917///918/// ```919/// # use kernel::device::Device;920///921/// fn example(dev: &Device) {922/// dev_dbg!(dev, "hello {}\n", "there");923/// }924/// ```925#[macro_export]926macro_rules! dev_dbg {927($($f:tt)*) => { $crate::dev_printk!(pr_dbg, $($f)*); }928}929930931