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