kernel/
device.rs

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