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