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