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