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