Skip to main content

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