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