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