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