kernel/
device.rs

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