Skip to main content

kernel/
device.rs

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