xref: /linux/rust/kernel/device.rs (revision 0242623384c767b1156b61b67894b4ecf6682b8b)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 //! Generic devices that are part of the kernel's driver model.
4 //!
5 //! C header: [`include/linux/device.h`](srctree/include/linux/device.h)
6 
7 use crate::{
8     bindings, fmt,
9     prelude::*,
10     sync::aref::ARef,
11     types::{ForeignOwnable, Opaque},
12 };
13 use core::{marker::PhantomData, ptr};
14 
15 #[cfg(CONFIG_PRINTK)]
16 use crate::c_str;
17 
18 pub 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)]
162 pub struct Device<Ctx: DeviceContext = Normal>(Opaque<bindings::device>, PhantomData<Ctx>);
163 
164 impl 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     pub unsafe fn get_device(ptr: *mut bindings::device) -> ARef<Self> {
176         // SAFETY: By the safety requirements ptr is valid
177         unsafe { Self::from_raw(ptr) }.into()
178     }
179 
180     /// Convert a [`&Device`](Device) into a [`&Device<Bound>`](Device<Bound>).
181     ///
182     /// # Safety
183     ///
184     /// The caller is responsible to ensure that the returned [`&Device<Bound>`](Device<Bound>)
185     /// only lives as long as it can be guaranteed that the [`Device`] is actually bound.
186     pub unsafe fn as_bound(&self) -> &Device<Bound> {
187         let ptr = core::ptr::from_ref(self);
188 
189         // CAST: By the safety requirements the caller is responsible to guarantee that the
190         // returned reference only lives as long as the device is actually bound.
191         let ptr = ptr.cast();
192 
193         // SAFETY:
194         // - `ptr` comes from `from_ref(self)` above, hence it's guaranteed to be valid.
195         // - Any valid `Device` pointer is also a valid pointer for `Device<Bound>`.
196         unsafe { &*ptr }
197     }
198 }
199 
200 impl Device<CoreInternal> {
201     /// Store a pointer to the bound driver's private data.
202     pub fn set_drvdata<T: 'static>(&self, data: impl PinInit<T, Error>) -> Result {
203         let data = KBox::pin_init(data, GFP_KERNEL)?;
204 
205         // SAFETY: By the type invariants, `self.as_raw()` is a valid pointer to a `struct device`.
206         unsafe { bindings::dev_set_drvdata(self.as_raw(), data.into_foreign().cast()) };
207 
208         Ok(())
209     }
210 
211     /// Take ownership of the private data stored in this [`Device`].
212     ///
213     /// # Safety
214     ///
215     /// - Must only be called once after a preceding call to [`Device::set_drvdata`].
216     /// - The type `T` must match the type of the `ForeignOwnable` previously stored by
217     ///   [`Device::set_drvdata`].
218     pub unsafe fn drvdata_obtain<T: ForeignOwnable>(&self) -> T {
219         // SAFETY: By the type invariants, `self.as_raw()` is a valid pointer to a `struct device`.
220         let ptr = unsafe { bindings::dev_get_drvdata(self.as_raw()) };
221 
222         // SAFETY:
223         // - By the safety requirements of this function, `ptr` comes from a previous call to
224         //   `into_foreign()`.
225         // - `dev_get_drvdata()` guarantees to return the same pointer given to `dev_set_drvdata()`
226         //   in `into_foreign()`.
227         unsafe { T::from_foreign(ptr.cast()) }
228     }
229 
230     /// Borrow the driver's private data bound to this [`Device`].
231     ///
232     /// # Safety
233     ///
234     /// - Must only be called after a preceding call to [`Device::set_drvdata`] and before
235     ///   [`Device::drvdata_obtain`].
236     /// - The type `T` must match the type of the `ForeignOwnable` previously stored by
237     ///   [`Device::set_drvdata`].
238     pub unsafe fn drvdata_borrow<T: ForeignOwnable>(&self) -> T::Borrowed<'_> {
239         // SAFETY: By the type invariants, `self.as_raw()` is a valid pointer to a `struct device`.
240         let ptr = unsafe { bindings::dev_get_drvdata(self.as_raw()) };
241 
242         // SAFETY:
243         // - By the safety requirements of this function, `ptr` comes from a previous call to
244         //   `into_foreign()`.
245         // - `dev_get_drvdata()` guarantees to return the same pointer given to `dev_set_drvdata()`
246         //   in `into_foreign()`.
247         unsafe { T::borrow(ptr.cast()) }
248     }
249 }
250 
251 impl<Ctx: DeviceContext> Device<Ctx> {
252     /// Obtain the raw `struct device *`.
253     pub(crate) fn as_raw(&self) -> *mut bindings::device {
254         self.0.get()
255     }
256 
257     /// Returns a reference to the parent device, if any.
258     #[cfg_attr(not(CONFIG_AUXILIARY_BUS), expect(dead_code))]
259     pub(crate) fn parent(&self) -> Option<&Self> {
260         // SAFETY:
261         // - By the type invariant `self.as_raw()` is always valid.
262         // - The parent device is only ever set at device creation.
263         let parent = unsafe { (*self.as_raw()).parent };
264 
265         if parent.is_null() {
266             None
267         } else {
268             // SAFETY:
269             // - Since `parent` is not NULL, it must be a valid pointer to a `struct device`.
270             // - `parent` is valid for the lifetime of `self`, since a `struct device` holds a
271             //   reference count of its parent.
272             Some(unsafe { Self::from_raw(parent) })
273         }
274     }
275 
276     /// Convert a raw C `struct device` pointer to a `&'a Device`.
277     ///
278     /// # Safety
279     ///
280     /// Callers must ensure that `ptr` is valid, non-null, and has a non-zero reference count,
281     /// i.e. it must be ensured that the reference count of the C `struct device` `ptr` points to
282     /// can't drop to zero, for the duration of this function call and the entire duration when the
283     /// returned reference exists.
284     pub unsafe fn from_raw<'a>(ptr: *mut bindings::device) -> &'a Self {
285         // SAFETY: Guaranteed by the safety requirements of the function.
286         unsafe { &*ptr.cast() }
287     }
288 
289     /// Prints an emergency-level message (level 0) prefixed with device information.
290     ///
291     /// More details are available from [`dev_emerg`].
292     ///
293     /// [`dev_emerg`]: crate::dev_emerg
294     pub fn pr_emerg(&self, args: fmt::Arguments<'_>) {
295         // SAFETY: `klevel` is null-terminated, uses one of the kernel constants.
296         unsafe { self.printk(bindings::KERN_EMERG, args) };
297     }
298 
299     /// Prints an alert-level message (level 1) prefixed with device information.
300     ///
301     /// More details are available from [`dev_alert`].
302     ///
303     /// [`dev_alert`]: crate::dev_alert
304     pub fn pr_alert(&self, args: fmt::Arguments<'_>) {
305         // SAFETY: `klevel` is null-terminated, uses one of the kernel constants.
306         unsafe { self.printk(bindings::KERN_ALERT, args) };
307     }
308 
309     /// Prints a critical-level message (level 2) prefixed with device information.
310     ///
311     /// More details are available from [`dev_crit`].
312     ///
313     /// [`dev_crit`]: crate::dev_crit
314     pub fn pr_crit(&self, args: fmt::Arguments<'_>) {
315         // SAFETY: `klevel` is null-terminated, uses one of the kernel constants.
316         unsafe { self.printk(bindings::KERN_CRIT, args) };
317     }
318 
319     /// Prints an error-level message (level 3) prefixed with device information.
320     ///
321     /// More details are available from [`dev_err`].
322     ///
323     /// [`dev_err`]: crate::dev_err
324     pub fn pr_err(&self, args: fmt::Arguments<'_>) {
325         // SAFETY: `klevel` is null-terminated, uses one of the kernel constants.
326         unsafe { self.printk(bindings::KERN_ERR, args) };
327     }
328 
329     /// Prints a warning-level message (level 4) prefixed with device information.
330     ///
331     /// More details are available from [`dev_warn`].
332     ///
333     /// [`dev_warn`]: crate::dev_warn
334     pub fn pr_warn(&self, args: fmt::Arguments<'_>) {
335         // SAFETY: `klevel` is null-terminated, uses one of the kernel constants.
336         unsafe { self.printk(bindings::KERN_WARNING, args) };
337     }
338 
339     /// Prints a notice-level message (level 5) prefixed with device information.
340     ///
341     /// More details are available from [`dev_notice`].
342     ///
343     /// [`dev_notice`]: crate::dev_notice
344     pub fn pr_notice(&self, args: fmt::Arguments<'_>) {
345         // SAFETY: `klevel` is null-terminated, uses one of the kernel constants.
346         unsafe { self.printk(bindings::KERN_NOTICE, args) };
347     }
348 
349     /// Prints an info-level message (level 6) prefixed with device information.
350     ///
351     /// More details are available from [`dev_info`].
352     ///
353     /// [`dev_info`]: crate::dev_info
354     pub fn pr_info(&self, args: fmt::Arguments<'_>) {
355         // SAFETY: `klevel` is null-terminated, uses one of the kernel constants.
356         unsafe { self.printk(bindings::KERN_INFO, args) };
357     }
358 
359     /// Prints a debug-level message (level 7) prefixed with device information.
360     ///
361     /// More details are available from [`dev_dbg`].
362     ///
363     /// [`dev_dbg`]: crate::dev_dbg
364     pub fn pr_dbg(&self, args: fmt::Arguments<'_>) {
365         if cfg!(debug_assertions) {
366             // SAFETY: `klevel` is null-terminated, uses one of the kernel constants.
367             unsafe { self.printk(bindings::KERN_DEBUG, args) };
368         }
369     }
370 
371     /// Prints the provided message to the console.
372     ///
373     /// # Safety
374     ///
375     /// Callers must ensure that `klevel` is null-terminated; in particular, one of the
376     /// `KERN_*`constants, for example, `KERN_CRIT`, `KERN_ALERT`, etc.
377     #[cfg_attr(not(CONFIG_PRINTK), allow(unused_variables))]
378     unsafe fn printk(&self, klevel: &[u8], msg: fmt::Arguments<'_>) {
379         // SAFETY: `klevel` is null-terminated and one of the kernel constants. `self.as_raw`
380         // is valid because `self` is valid. The "%pA" format string expects a pointer to
381         // `fmt::Arguments`, which is what we're passing as the last argument.
382         #[cfg(CONFIG_PRINTK)]
383         unsafe {
384             bindings::_dev_printk(
385                 klevel.as_ptr().cast::<crate::ffi::c_char>(),
386                 self.as_raw(),
387                 c_str!("%pA").as_char_ptr(),
388                 core::ptr::from_ref(&msg).cast::<crate::ffi::c_void>(),
389             )
390         };
391     }
392 
393     /// Obtain the [`FwNode`](property::FwNode) corresponding to this [`Device`].
394     pub fn fwnode(&self) -> Option<&property::FwNode> {
395         // SAFETY: `self` is valid.
396         let fwnode_handle = unsafe { bindings::__dev_fwnode(self.as_raw()) };
397         if fwnode_handle.is_null() {
398             return None;
399         }
400         // SAFETY: `fwnode_handle` is valid. Its lifetime is tied to `&self`. We
401         // return a reference instead of an `ARef<FwNode>` because `dev_fwnode()`
402         // doesn't increment the refcount. It is safe to cast from a
403         // `struct fwnode_handle*` to a `*const FwNode` because `FwNode` is
404         // defined as a `#[repr(transparent)]` wrapper around `fwnode_handle`.
405         Some(unsafe { &*fwnode_handle.cast() })
406     }
407 }
408 
409 // SAFETY: `Device` is a transparent wrapper of a type that doesn't depend on `Device`'s generic
410 // argument.
411 kernel::impl_device_context_deref!(unsafe { Device });
412 kernel::impl_device_context_into_aref!(Device);
413 
414 // SAFETY: Instances of `Device` are always reference-counted.
415 unsafe impl crate::sync::aref::AlwaysRefCounted for Device {
416     fn inc_ref(&self) {
417         // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
418         unsafe { bindings::get_device(self.as_raw()) };
419     }
420 
421     unsafe fn dec_ref(obj: ptr::NonNull<Self>) {
422         // SAFETY: The safety requirements guarantee that the refcount is non-zero.
423         unsafe { bindings::put_device(obj.cast().as_ptr()) }
424     }
425 }
426 
427 // SAFETY: As by the type invariant `Device` can be sent to any thread.
428 unsafe impl Send for Device {}
429 
430 // SAFETY: `Device` can be shared among threads because all immutable methods are protected by the
431 // synchronization in `struct device`.
432 unsafe impl Sync for Device {}
433 
434 /// Marker trait for the context or scope of a bus specific device.
435 ///
436 /// [`DeviceContext`] is a marker trait for types representing the context of a bus specific
437 /// [`Device`].
438 ///
439 /// The specific device context types are: [`CoreInternal`], [`Core`], [`Bound`] and [`Normal`].
440 ///
441 /// [`DeviceContext`] types are hierarchical, which means that there is a strict hierarchy that
442 /// defines which [`DeviceContext`] type can be derived from another. For instance, any
443 /// [`Device<Core>`] can dereference to a [`Device<Bound>`].
444 ///
445 /// The following enumeration illustrates the dereference hierarchy of [`DeviceContext`] types.
446 ///
447 /// - [`CoreInternal`] => [`Core`] => [`Bound`] => [`Normal`]
448 ///
449 /// Bus devices can automatically implement the dereference hierarchy by using
450 /// [`impl_device_context_deref`].
451 ///
452 /// Note that the guarantee for a [`Device`] reference to have a certain [`DeviceContext`] comes
453 /// from the specific scope the [`Device`] reference is valid in.
454 ///
455 /// [`impl_device_context_deref`]: kernel::impl_device_context_deref
456 pub trait DeviceContext: private::Sealed {}
457 
458 /// The [`Normal`] context is the default [`DeviceContext`] of any [`Device`].
459 ///
460 /// The normal context does not indicate any specific context. Any `Device<Ctx>` is also a valid
461 /// [`Device<Normal>`]. It is the only [`DeviceContext`] for which it is valid to implement
462 /// [`AlwaysRefCounted`] for.
463 ///
464 /// [`AlwaysRefCounted`]: kernel::types::AlwaysRefCounted
465 pub struct Normal;
466 
467 /// The [`Core`] context is the context of a bus specific device when it appears as argument of
468 /// any bus specific callback, such as `probe()`.
469 ///
470 /// The core context indicates that the [`Device<Core>`] reference's scope is limited to the bus
471 /// callback it appears in. It is intended to be used for synchronization purposes. Bus device
472 /// implementations can implement methods for [`Device<Core>`], such that they can only be called
473 /// from bus callbacks.
474 pub struct Core;
475 
476 /// Semantically the same as [`Core`], but reserved for internal usage of the corresponding bus
477 /// abstraction.
478 ///
479 /// The internal core context is intended to be used in exactly the same way as the [`Core`]
480 /// context, with the difference that this [`DeviceContext`] is internal to the corresponding bus
481 /// abstraction.
482 ///
483 /// This context mainly exists to share generic [`Device`] infrastructure that should only be called
484 /// from bus callbacks with bus abstractions, but without making them accessible for drivers.
485 pub struct CoreInternal;
486 
487 /// The [`Bound`] context is the [`DeviceContext`] of a bus specific device when it is guaranteed to
488 /// be bound to a driver.
489 ///
490 /// The bound context indicates that for the entire duration of the lifetime of a [`Device<Bound>`]
491 /// reference, the [`Device`] is guaranteed to be bound to a driver.
492 ///
493 /// Some APIs, such as [`dma::CoherentAllocation`] or [`Devres`] rely on the [`Device`] to be bound,
494 /// which can be proven with the [`Bound`] device context.
495 ///
496 /// Any abstraction that can guarantee a scope where the corresponding bus device is bound, should
497 /// provide a [`Device<Bound>`] reference to its users for this scope. This allows users to benefit
498 /// from optimizations for accessing device resources, see also [`Devres::access`].
499 ///
500 /// [`Devres`]: kernel::devres::Devres
501 /// [`Devres::access`]: kernel::devres::Devres::access
502 /// [`dma::CoherentAllocation`]: kernel::dma::CoherentAllocation
503 pub struct Bound;
504 
505 mod private {
506     pub trait Sealed {}
507 
508     impl Sealed for super::Bound {}
509     impl Sealed for super::Core {}
510     impl Sealed for super::CoreInternal {}
511     impl Sealed for super::Normal {}
512 }
513 
514 impl DeviceContext for Bound {}
515 impl DeviceContext for Core {}
516 impl DeviceContext for CoreInternal {}
517 impl DeviceContext for Normal {}
518 
519 /// # Safety
520 ///
521 /// The type given as `$device` must be a transparent wrapper of a type that doesn't depend on the
522 /// generic argument of `$device`.
523 #[doc(hidden)]
524 #[macro_export]
525 macro_rules! __impl_device_context_deref {
526     (unsafe { $device:ident, $src:ty => $dst:ty }) => {
527         impl ::core::ops::Deref for $device<$src> {
528             type Target = $device<$dst>;
529 
530             fn deref(&self) -> &Self::Target {
531                 let ptr: *const Self = self;
532 
533                 // CAST: `$device<$src>` and `$device<$dst>` transparently wrap the same type by the
534                 // safety requirement of the macro.
535                 let ptr = ptr.cast::<Self::Target>();
536 
537                 // SAFETY: `ptr` was derived from `&self`.
538                 unsafe { &*ptr }
539             }
540         }
541     };
542 }
543 
544 /// Implement [`core::ops::Deref`] traits for allowed [`DeviceContext`] conversions of a (bus
545 /// specific) device.
546 ///
547 /// # Safety
548 ///
549 /// The type given as `$device` must be a transparent wrapper of a type that doesn't depend on the
550 /// generic argument of `$device`.
551 #[macro_export]
552 macro_rules! impl_device_context_deref {
553     (unsafe { $device:ident }) => {
554         // SAFETY: This macro has the exact same safety requirement as
555         // `__impl_device_context_deref!`.
556         ::kernel::__impl_device_context_deref!(unsafe {
557             $device,
558             $crate::device::CoreInternal => $crate::device::Core
559         });
560 
561         // SAFETY: This macro has the exact same safety requirement as
562         // `__impl_device_context_deref!`.
563         ::kernel::__impl_device_context_deref!(unsafe {
564             $device,
565             $crate::device::Core => $crate::device::Bound
566         });
567 
568         // SAFETY: This macro has the exact same safety requirement as
569         // `__impl_device_context_deref!`.
570         ::kernel::__impl_device_context_deref!(unsafe {
571             $device,
572             $crate::device::Bound => $crate::device::Normal
573         });
574     };
575 }
576 
577 #[doc(hidden)]
578 #[macro_export]
579 macro_rules! __impl_device_context_into_aref {
580     ($src:ty, $device:tt) => {
581         impl ::core::convert::From<&$device<$src>> for $crate::sync::aref::ARef<$device> {
582             fn from(dev: &$device<$src>) -> Self {
583                 (&**dev).into()
584             }
585         }
586     };
587 }
588 
589 /// Implement [`core::convert::From`], such that all `&Device<Ctx>` can be converted to an
590 /// `ARef<Device>`.
591 #[macro_export]
592 macro_rules! impl_device_context_into_aref {
593     ($device:tt) => {
594         ::kernel::__impl_device_context_into_aref!($crate::device::CoreInternal, $device);
595         ::kernel::__impl_device_context_into_aref!($crate::device::Core, $device);
596         ::kernel::__impl_device_context_into_aref!($crate::device::Bound, $device);
597     };
598 }
599 
600 #[doc(hidden)]
601 #[macro_export]
602 macro_rules! dev_printk {
603     ($method:ident, $dev:expr, $($f:tt)*) => {
604         {
605             ($dev).$method($crate::prelude::fmt!($($f)*));
606         }
607     }
608 }
609 
610 /// Prints an emergency-level message (level 0) prefixed with device information.
611 ///
612 /// This level should be used if the system is unusable.
613 ///
614 /// Equivalent to the kernel's `dev_emerg` macro.
615 ///
616 /// Mimics the interface of [`std::print!`]. More information about the syntax is available from
617 /// [`core::fmt`] and [`std::format!`].
618 ///
619 /// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
620 /// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html
621 ///
622 /// # Examples
623 ///
624 /// ```
625 /// # use kernel::device::Device;
626 ///
627 /// fn example(dev: &Device) {
628 ///     dev_emerg!(dev, "hello {}\n", "there");
629 /// }
630 /// ```
631 #[macro_export]
632 macro_rules! dev_emerg {
633     ($($f:tt)*) => { $crate::dev_printk!(pr_emerg, $($f)*); }
634 }
635 
636 /// Prints an alert-level message (level 1) prefixed with device information.
637 ///
638 /// This level should be used if action must be taken immediately.
639 ///
640 /// Equivalent to the kernel's `dev_alert` macro.
641 ///
642 /// Mimics the interface of [`std::print!`]. More information about the syntax is available from
643 /// [`core::fmt`] and [`std::format!`].
644 ///
645 /// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
646 /// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html
647 ///
648 /// # Examples
649 ///
650 /// ```
651 /// # use kernel::device::Device;
652 ///
653 /// fn example(dev: &Device) {
654 ///     dev_alert!(dev, "hello {}\n", "there");
655 /// }
656 /// ```
657 #[macro_export]
658 macro_rules! dev_alert {
659     ($($f:tt)*) => { $crate::dev_printk!(pr_alert, $($f)*); }
660 }
661 
662 /// Prints a critical-level message (level 2) prefixed with device information.
663 ///
664 /// This level should be used in critical conditions.
665 ///
666 /// Equivalent to the kernel's `dev_crit` macro.
667 ///
668 /// Mimics the interface of [`std::print!`]. More information about the syntax is available from
669 /// [`core::fmt`] and [`std::format!`].
670 ///
671 /// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
672 /// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html
673 ///
674 /// # Examples
675 ///
676 /// ```
677 /// # use kernel::device::Device;
678 ///
679 /// fn example(dev: &Device) {
680 ///     dev_crit!(dev, "hello {}\n", "there");
681 /// }
682 /// ```
683 #[macro_export]
684 macro_rules! dev_crit {
685     ($($f:tt)*) => { $crate::dev_printk!(pr_crit, $($f)*); }
686 }
687 
688 /// Prints an error-level message (level 3) prefixed with device information.
689 ///
690 /// This level should be used in error conditions.
691 ///
692 /// Equivalent to the kernel's `dev_err` macro.
693 ///
694 /// Mimics the interface of [`std::print!`]. More information about the syntax is available from
695 /// [`core::fmt`] and [`std::format!`].
696 ///
697 /// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
698 /// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html
699 ///
700 /// # Examples
701 ///
702 /// ```
703 /// # use kernel::device::Device;
704 ///
705 /// fn example(dev: &Device) {
706 ///     dev_err!(dev, "hello {}\n", "there");
707 /// }
708 /// ```
709 #[macro_export]
710 macro_rules! dev_err {
711     ($($f:tt)*) => { $crate::dev_printk!(pr_err, $($f)*); }
712 }
713 
714 /// Prints a warning-level message (level 4) prefixed with device information.
715 ///
716 /// This level should be used in warning conditions.
717 ///
718 /// Equivalent to the kernel's `dev_warn` macro.
719 ///
720 /// Mimics the interface of [`std::print!`]. More information about the syntax is available from
721 /// [`core::fmt`] and [`std::format!`].
722 ///
723 /// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
724 /// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html
725 ///
726 /// # Examples
727 ///
728 /// ```
729 /// # use kernel::device::Device;
730 ///
731 /// fn example(dev: &Device) {
732 ///     dev_warn!(dev, "hello {}\n", "there");
733 /// }
734 /// ```
735 #[macro_export]
736 macro_rules! dev_warn {
737     ($($f:tt)*) => { $crate::dev_printk!(pr_warn, $($f)*); }
738 }
739 
740 /// Prints a notice-level message (level 5) prefixed with device information.
741 ///
742 /// This level should be used in normal but significant conditions.
743 ///
744 /// Equivalent to the kernel's `dev_notice` macro.
745 ///
746 /// Mimics the interface of [`std::print!`]. More information about the syntax is available from
747 /// [`core::fmt`] and [`std::format!`].
748 ///
749 /// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
750 /// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html
751 ///
752 /// # Examples
753 ///
754 /// ```
755 /// # use kernel::device::Device;
756 ///
757 /// fn example(dev: &Device) {
758 ///     dev_notice!(dev, "hello {}\n", "there");
759 /// }
760 /// ```
761 #[macro_export]
762 macro_rules! dev_notice {
763     ($($f:tt)*) => { $crate::dev_printk!(pr_notice, $($f)*); }
764 }
765 
766 /// Prints an info-level message (level 6) prefixed with device information.
767 ///
768 /// This level should be used for informational messages.
769 ///
770 /// Equivalent to the kernel's `dev_info` macro.
771 ///
772 /// Mimics the interface of [`std::print!`]. More information about the syntax is available from
773 /// [`core::fmt`] and [`std::format!`].
774 ///
775 /// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
776 /// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html
777 ///
778 /// # Examples
779 ///
780 /// ```
781 /// # use kernel::device::Device;
782 ///
783 /// fn example(dev: &Device) {
784 ///     dev_info!(dev, "hello {}\n", "there");
785 /// }
786 /// ```
787 #[macro_export]
788 macro_rules! dev_info {
789     ($($f:tt)*) => { $crate::dev_printk!(pr_info, $($f)*); }
790 }
791 
792 /// Prints a debug-level message (level 7) prefixed with device information.
793 ///
794 /// This level should be used for debug messages.
795 ///
796 /// Equivalent to the kernel's `dev_dbg` macro, except that it doesn't support dynamic debug yet.
797 ///
798 /// Mimics the interface of [`std::print!`]. More information about the syntax is available from
799 /// [`core::fmt`] and [`std::format!`].
800 ///
801 /// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
802 /// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html
803 ///
804 /// # Examples
805 ///
806 /// ```
807 /// # use kernel::device::Device;
808 ///
809 /// fn example(dev: &Device) {
810 ///     dev_dbg!(dev, "hello {}\n", "there");
811 /// }
812 /// ```
813 #[macro_export]
814 macro_rules! dev_dbg {
815     ($($f:tt)*) => { $crate::dev_printk!(pr_dbg, $($f)*); }
816 }
817