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    marker::PhantomData,
19    ptr, //
20};
21
22pub mod property;
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:
71#[cfg_attr(CONFIG_PCI, doc = "* [`pci::Device`](kernel::pci::Device)")]
72/// * [`platform::Device`]
73///
74/// A bus specific device should be defined as follows.
75///
76/// ```ignore
77/// #[repr(transparent)]
78/// pub struct Device<Ctx: device::DeviceContext = device::Normal>(
79///     Opaque<bindings::bus_device_type>,
80///     PhantomData<Ctx>,
81/// );
82/// ```
83///
84/// Since devices are reference counted, [`AlwaysRefCounted`] should be implemented for `Device`
85/// (i.e. `Device<Normal>`). Note that [`AlwaysRefCounted`] must not be implemented for any other
86/// [`DeviceContext`], since all other device context types are only valid within a certain scope.
87///
88/// In order to be able to implement the [`DeviceContext`] dereference hierarchy, bus device
89/// implementations should call the [`impl_device_context_deref`] macro as shown below.
90///
91/// ```ignore
92/// // SAFETY: `Device` is a transparent wrapper of a type that doesn't depend on `Device`'s
93/// // generic argument.
94/// kernel::impl_device_context_deref!(unsafe { Device });
95/// ```
96///
97/// In order to convert from a any [`Device<Ctx>`] to [`ARef<Device>`], bus devices can implement
98/// the following macro call.
99///
100/// ```ignore
101/// kernel::impl_device_context_into_aref!(Device);
102/// ```
103///
104/// Bus devices should also implement the following [`AsRef`] implementation, such that users can
105/// easily derive a generic [`Device`] reference.
106///
107/// ```ignore
108/// impl<Ctx: device::DeviceContext> AsRef<device::Device<Ctx>> for Device<Ctx> {
109///     fn as_ref(&self) -> &device::Device<Ctx> {
110///         ...
111///     }
112/// }
113/// ```
114///
115/// # Implementing Class Devices
116///
117/// Class device implementations require less infrastructure and depend slightly more on the
118/// specific subsystem.
119///
120/// An example implementation for a class device could look like this.
121///
122/// ```ignore
123/// #[repr(C)]
124/// pub struct Device<T: class::Driver> {
125///     dev: Opaque<bindings::class_device_type>,
126///     data: T::Data,
127/// }
128/// ```
129///
130/// This class device uses the sub-classing pattern to embed the driver's private data within the
131/// allocation of the class device. For this to be possible the class device is generic over the
132/// class specific `Driver` trait implementation.
133///
134/// Just like any device, class devices are reference counted and should hence implement
135/// [`AlwaysRefCounted`] for `Device`.
136///
137/// Class devices should also implement the following [`AsRef`] implementation, such that users can
138/// easily derive a generic [`Device`] reference.
139///
140/// ```ignore
141/// impl<T: class::Driver> AsRef<device::Device> for Device<T> {
142///     fn as_ref(&self) -> &device::Device {
143///         ...
144///     }
145/// }
146/// ```
147///
148/// An example for a class device implementation is
149#[cfg_attr(CONFIG_DRM = "y", doc = "[`drm::Device`](kernel::drm::Device).")]
150#[cfg_attr(not(CONFIG_DRM = "y"), doc = "`drm::Device`.")]
151///
152/// # Invariants
153///
154/// A `Device` instance represents a valid `struct device` created by the C portion of the kernel.
155///
156/// Instances of this type are always reference-counted, that is, a call to `get_device` ensures
157/// that the allocation remains valid at least until the matching call to `put_device`.
158///
159/// `bindings::device::release` is valid to be called from any thread, hence `ARef<Device>` can be
160/// dropped from any thread.
161///
162/// [`AlwaysRefCounted`]: kernel::sync::aref::AlwaysRefCounted
163/// [`impl_device_context_deref`]: kernel::impl_device_context_deref
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<'a> Device<CoreInternal<'a>> {
205    /// Store a pointer to the bound driver's private data.
206    pub fn set_drvdata<T>(&self, data: impl PinInit<T, Error>) -> Result {
207        let data = KBox::pin_init(data, GFP_KERNEL)?;
208
209        // SAFETY: By the type invariants, `self.as_raw()` is a valid pointer to a `struct device`.
210        unsafe { bindings::dev_set_drvdata(self.as_raw(), data.into_foreign().cast()) };
211
212        Ok(())
213    }
214
215    /// Take ownership of the private data stored in this [`Device`].
216    ///
217    /// # Safety
218    ///
219    /// - The type `T` must match the type of the `ForeignOwnable` previously stored by
220    ///   [`Device::set_drvdata`].
221    pub(crate) unsafe fn drvdata_obtain<T>(&self) -> Option<Pin<KBox<T>>> {
222        // SAFETY: By the type invariants, `self.as_raw()` is a valid pointer to a `struct device`.
223        let ptr = unsafe { bindings::dev_get_drvdata(self.as_raw()) };
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(), core::ptr::null_mut()) };
227
228        if ptr.is_null() {
229            return None;
230        }
231
232        // SAFETY:
233        // - If `ptr` is not NULL, it comes from a previous call to `into_foreign()`.
234        // - `dev_get_drvdata()` guarantees to return the same pointer given to `dev_set_drvdata()`
235        //   in `into_foreign()`.
236        Some(unsafe { Pin::<KBox<T>>::from_foreign(ptr.cast()) })
237    }
238
239    /// Borrow the driver's private data bound to this [`Device`].
240    ///
241    /// # Safety
242    ///
243    /// - Must only be called after a preceding call to [`Device::set_drvdata`] and before the
244    ///   device is fully unbound.
245    /// - The type `T` must match the type of the `ForeignOwnable` previously stored by
246    ///   [`Device::set_drvdata`].
247    pub unsafe fn drvdata_borrow<T>(&self) -> Pin<&T> {
248        // SAFETY: `drvdata_unchecked()` has the exact same safety requirements as the ones
249        // required by this method.
250        unsafe { self.drvdata_unchecked() }
251    }
252}
253
254impl Device<Bound> {
255    /// Borrow the driver's private data bound to this [`Device`].
256    ///
257    /// # Safety
258    ///
259    /// - Must only be called after a preceding call to [`Device::set_drvdata`] and before
260    ///   the device is fully unbound.
261    /// - The type `T` must match the type of the `ForeignOwnable` previously stored by
262    ///   [`Device::set_drvdata`].
263    unsafe fn drvdata_unchecked<T>(&self) -> Pin<&T> {
264        // SAFETY: By the type invariants, `self.as_raw()` is a valid pointer to a `struct device`.
265        let ptr = unsafe { bindings::dev_get_drvdata(self.as_raw()) };
266
267        // SAFETY:
268        // - By the safety requirements of this function, `ptr` comes from a previous call to
269        //   `into_foreign()`.
270        // - `dev_get_drvdata()` guarantees to return the same pointer given to `dev_set_drvdata()`
271        //   in `into_foreign()`.
272        unsafe { Pin::<KBox<T>>::borrow(ptr.cast()) }
273    }
274}
275
276impl<Ctx: DeviceContext> Device<Ctx> {
277    /// Obtain the raw `struct device *`.
278    pub(crate) fn as_raw(&self) -> *mut bindings::device {
279        self.0.get()
280    }
281
282    /// Returns a reference to the parent device, if any.
283    #[cfg_attr(not(CONFIG_AUXILIARY_BUS), expect(dead_code))]
284    pub(crate) fn parent(&self) -> Option<&Device> {
285        // SAFETY:
286        // - By the type invariant `self.as_raw()` is always valid.
287        // - The parent device is only ever set at device creation.
288        let parent = unsafe { (*self.as_raw()).parent };
289
290        if parent.is_null() {
291            None
292        } else {
293            // SAFETY:
294            // - Since `parent` is not NULL, it must be a valid pointer to a `struct device`.
295            // - `parent` is valid for the lifetime of `self`, since a `struct device` holds a
296            //   reference count of its parent.
297            Some(unsafe { Device::from_raw(parent) })
298        }
299    }
300
301    /// Convert a raw C `struct device` pointer to a `&'a Device`.
302    ///
303    /// # Safety
304    ///
305    /// Callers must ensure that `ptr` is valid, non-null, and has a non-zero reference count,
306    /// i.e. it must be ensured that the reference count of the C `struct device` `ptr` points to
307    /// can't drop to zero, for the duration of this function call and the entire duration when the
308    /// returned reference exists.
309    pub unsafe fn from_raw<'a>(ptr: *mut bindings::device) -> &'a Self {
310        // SAFETY: Guaranteed by the safety requirements of the function.
311        unsafe { &*ptr.cast() }
312    }
313
314    /// Prints an emergency-level message (level 0) prefixed with device information.
315    ///
316    /// More details are available from [`dev_emerg`].
317    ///
318    /// [`dev_emerg`]: crate::dev_emerg
319    pub fn pr_emerg(&self, args: fmt::Arguments<'_>) {
320        // SAFETY: `klevel` is null-terminated, uses one of the kernel constants.
321        unsafe { self.printk(bindings::KERN_EMERG, args) };
322    }
323
324    /// Prints an alert-level message (level 1) prefixed with device information.
325    ///
326    /// More details are available from [`dev_alert`].
327    ///
328    /// [`dev_alert`]: crate::dev_alert
329    pub fn pr_alert(&self, args: fmt::Arguments<'_>) {
330        // SAFETY: `klevel` is null-terminated, uses one of the kernel constants.
331        unsafe { self.printk(bindings::KERN_ALERT, args) };
332    }
333
334    /// Prints a critical-level message (level 2) prefixed with device information.
335    ///
336    /// More details are available from [`dev_crit`].
337    ///
338    /// [`dev_crit`]: crate::dev_crit
339    pub fn pr_crit(&self, args: fmt::Arguments<'_>) {
340        // SAFETY: `klevel` is null-terminated, uses one of the kernel constants.
341        unsafe { self.printk(bindings::KERN_CRIT, args) };
342    }
343
344    /// Prints an error-level message (level 3) prefixed with device information.
345    ///
346    /// More details are available from [`dev_err`].
347    ///
348    /// [`dev_err`]: crate::dev_err
349    pub fn pr_err(&self, args: fmt::Arguments<'_>) {
350        // SAFETY: `klevel` is null-terminated, uses one of the kernel constants.
351        unsafe { self.printk(bindings::KERN_ERR, args) };
352    }
353
354    /// Prints a warning-level message (level 4) prefixed with device information.
355    ///
356    /// More details are available from [`dev_warn`].
357    ///
358    /// [`dev_warn`]: crate::dev_warn
359    pub fn pr_warn(&self, args: fmt::Arguments<'_>) {
360        // SAFETY: `klevel` is null-terminated, uses one of the kernel constants.
361        unsafe { self.printk(bindings::KERN_WARNING, args) };
362    }
363
364    /// Prints a notice-level message (level 5) prefixed with device information.
365    ///
366    /// More details are available from [`dev_notice`].
367    ///
368    /// [`dev_notice`]: crate::dev_notice
369    pub fn pr_notice(&self, args: fmt::Arguments<'_>) {
370        // SAFETY: `klevel` is null-terminated, uses one of the kernel constants.
371        unsafe { self.printk(bindings::KERN_NOTICE, args) };
372    }
373
374    /// Prints an info-level message (level 6) prefixed with device information.
375    ///
376    /// More details are available from [`dev_info`].
377    ///
378    /// [`dev_info`]: crate::dev_info
379    pub fn pr_info(&self, args: fmt::Arguments<'_>) {
380        // SAFETY: `klevel` is null-terminated, uses one of the kernel constants.
381        unsafe { self.printk(bindings::KERN_INFO, args) };
382    }
383
384    /// Prints a debug-level message (level 7) prefixed with device information.
385    ///
386    /// More details are available from [`dev_dbg`].
387    ///
388    /// [`dev_dbg`]: crate::dev_dbg
389    pub fn pr_dbg(&self, args: fmt::Arguments<'_>) {
390        if cfg!(debug_assertions) {
391            // SAFETY: `klevel` is null-terminated, uses one of the kernel constants.
392            unsafe { self.printk(bindings::KERN_DEBUG, args) };
393        }
394    }
395
396    /// Prints the provided message to the console.
397    ///
398    /// # Safety
399    ///
400    /// Callers must ensure that `klevel` is null-terminated; in particular, one of the
401    /// `KERN_*`constants, for example, `KERN_CRIT`, `KERN_ALERT`, etc.
402    #[cfg_attr(not(CONFIG_PRINTK), allow(unused_variables))]
403    unsafe fn printk(&self, klevel: &[u8], msg: fmt::Arguments<'_>) {
404        // SAFETY: `klevel` is null-terminated and one of the kernel constants. `self.as_raw`
405        // is valid because `self` is valid. The "%pA" format string expects a pointer to
406        // `fmt::Arguments`, which is what we're passing as the last argument.
407        #[cfg(CONFIG_PRINTK)]
408        unsafe {
409            bindings::_dev_printk(
410                klevel.as_ptr().cast::<crate::ffi::c_char>(),
411                self.as_raw(),
412                c"%pA".as_char_ptr(),
413                core::ptr::from_ref(&msg).cast::<crate::ffi::c_void>(),
414            )
415        };
416    }
417
418    /// Obtain the [`FwNode`](property::FwNode) corresponding to this [`Device`].
419    pub fn fwnode(&self) -> Option<&property::FwNode> {
420        // SAFETY: `self` is valid.
421        let fwnode_handle = unsafe { bindings::__dev_fwnode(self.as_raw()) };
422        if fwnode_handle.is_null() {
423            return None;
424        }
425        // SAFETY: `fwnode_handle` is valid. Its lifetime is tied to `&self`. We
426        // return a reference instead of an `ARef<FwNode>` because `dev_fwnode()`
427        // doesn't increment the refcount. It is safe to cast from a
428        // `struct fwnode_handle*` to a `*const FwNode` because `FwNode` is
429        // defined as a `#[repr(transparent)]` wrapper around `fwnode_handle`.
430        Some(unsafe { &*fwnode_handle.cast() })
431    }
432
433    /// Returns the name of the device.
434    ///
435    /// This is the kobject name of the device, or its initial name if the kobject is not yet
436    /// available.
437    #[inline]
438    pub fn name(&self) -> &CStr {
439        // SAFETY: By its type invariant `self.as_raw()` is a valid pointer to a `struct device`.
440        // The returned string is valid for the lifetime of the device.
441        unsafe { CStr::from_char_ptr(bindings::dev_name(self.as_raw())) }
442    }
443}
444
445// SAFETY: `Device` is a transparent wrapper of a type that doesn't depend on `Device`'s generic
446// argument.
447kernel::impl_device_context_deref!(unsafe { Device });
448kernel::impl_device_context_into_aref!(Device);
449
450// SAFETY: Instances of `Device` are always reference-counted.
451unsafe impl crate::sync::aref::AlwaysRefCounted for Device {
452    fn inc_ref(&self) {
453        // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
454        unsafe { bindings::get_device(self.as_raw()) };
455    }
456
457    unsafe fn dec_ref(obj: ptr::NonNull<Self>) {
458        // SAFETY: The safety requirements guarantee that the refcount is non-zero.
459        unsafe { bindings::put_device(obj.cast().as_ptr()) }
460    }
461}
462
463// SAFETY: As by the type invariant `Device` can be sent to any thread.
464unsafe impl Send for Device {}
465
466// SAFETY: `Device` can be shared among threads because all immutable methods are protected by the
467// synchronization in `struct device`.
468unsafe impl Sync for Device {}
469
470// SAFETY: Same as `Device<Normal>` -- the underlying `struct device` is the same; `Bound` is a
471// zero-sized type-state marker that does not affect thread safety.
472unsafe impl Sync for Device<Bound> {}
473
474/// Marker trait for the context or scope of a bus specific device.
475///
476/// [`DeviceContext`] is a marker trait for types representing the context of a bus specific
477/// [`Device`].
478///
479/// The specific device context types are: [`CoreInternal`], [`Core`], [`Bound`] and [`Normal`].
480///
481/// [`DeviceContext`] types are hierarchical, which means that there is a strict hierarchy that
482/// defines which [`DeviceContext`] type can be derived from another. For instance, any
483/// [`Device<Core>`] can dereference to a [`Device<Bound>`].
484///
485/// The following enumeration illustrates the dereference hierarchy of [`DeviceContext`] types.
486///
487/// - [`CoreInternal`] => [`Core`] => [`Bound`] => [`Normal`]
488///
489/// Bus devices can automatically implement the dereference hierarchy by using
490/// [`impl_device_context_deref`].
491///
492/// Note that the guarantee for a [`Device`] reference to have a certain [`DeviceContext`] comes
493/// from the specific scope the [`Device`] reference is valid in.
494///
495/// [`impl_device_context_deref`]: kernel::impl_device_context_deref
496pub trait DeviceContext: private::Sealed {}
497
498/// The [`Normal`] context is the default [`DeviceContext`] of any [`Device`].
499///
500/// The normal context does not indicate any specific context. Any `Device<Ctx>` is also a valid
501/// [`Device<Normal>`]. It is the only [`DeviceContext`] for which it is valid to implement
502/// [`AlwaysRefCounted`] for.
503///
504/// [`AlwaysRefCounted`]: kernel::sync::aref::AlwaysRefCounted
505pub struct Normal;
506
507/// The [`Core`] context is the context of a bus specific device when it appears as argument of
508/// any bus specific callback, such as `probe()`.
509///
510/// The core context indicates that the [`Device<Core>`] reference's scope is limited to the bus
511/// callback it appears in. It is intended to be used for synchronization purposes. Bus device
512/// implementations can implement methods for [`Device<Core>`], such that they can only be called
513/// from bus callbacks.
514///
515/// The lifetime `'a` is for "lifetime branding" purpose. Callbacks need to polymorphic over this
516/// lifetime so the `&'bound Device<Core<'_>>` provided to them cannot outlive the scope of the
517/// function. For this reason, it needs to be invariant.
518pub struct Core<'a>(PhantomData<fn(&'a ()) -> &'a ()>);
519
520/// Semantically the same as [`Core`], but reserved for internal usage of the corresponding bus
521/// abstraction.
522///
523/// The internal core context is intended to be used in exactly the same way as the [`Core`]
524/// context, with the difference that this [`DeviceContext`] is internal to the corresponding bus
525/// abstraction.
526///
527/// This context mainly exists to share generic [`Device`] infrastructure that should only be called
528/// from bus callbacks with bus abstractions, but without making them accessible for drivers.
529///
530/// Lifetime `'a` is invariant for the same reason as [`Core`].
531pub struct CoreInternal<'a>(PhantomData<fn(&'a ()) -> &'a ()>);
532
533/// The [`Bound`] context is the [`DeviceContext`] of a bus specific device when it is guaranteed to
534/// be bound to a driver.
535///
536/// The bound context indicates that for the entire duration of the lifetime of a [`Device<Bound>`]
537/// reference, the [`Device`] is guaranteed to be bound to a driver.
538///
539/// Some APIs, such as [`dma::Coherent`] or [`Devres`] rely on the [`Device`] to be bound,
540/// which can be proven with the [`Bound`] device context.
541///
542/// Any abstraction that can guarantee a scope where the corresponding bus device is bound, should
543/// provide a [`Device<Bound>`] reference to its users for this scope. This allows users to benefit
544/// from optimizations for accessing device resources, see also [`Devres::access`].
545///
546/// [`Devres`]: kernel::devres::Devres
547/// [`Devres::access`]: kernel::devres::Devres::access
548/// [`dma::Coherent`]: kernel::dma::Coherent
549pub struct Bound;
550
551mod private {
552    pub trait Sealed {}
553
554    impl Sealed for super::Bound {}
555    impl<'a> Sealed for super::Core<'a> {}
556    impl<'a> Sealed for super::CoreInternal<'a> {}
557    impl Sealed for super::Normal {}
558}
559
560impl DeviceContext for Bound {}
561impl<'a> DeviceContext for Core<'a> {}
562impl<'a> DeviceContext for CoreInternal<'a> {}
563impl DeviceContext for Normal {}
564
565impl<Ctx: DeviceContext> AsRef<Device<Ctx>> for Device<Ctx> {
566    #[inline]
567    fn as_ref(&self) -> &Device<Ctx> {
568        self
569    }
570}
571
572/// Convert device references to bus device references.
573///
574/// Bus devices can implement this trait to allow abstractions to provide the bus device in
575/// class device callbacks.
576///
577/// This must not be used by drivers and is intended for bus and class device abstractions only.
578///
579/// # Safety
580///
581/// `AsBusDevice::OFFSET` must be the offset of the embedded base `struct device` field within a
582/// bus device structure.
583pub unsafe trait AsBusDevice<Ctx: DeviceContext>: AsRef<Device<Ctx>> {
584    /// The relative offset to the device field.
585    ///
586    /// Use `offset_of!(bindings, field)` macro to avoid breakage.
587    const OFFSET: usize;
588
589    /// Convert a reference to [`Device`] into `Self`.
590    ///
591    /// # Safety
592    ///
593    /// `dev` must be contained in `Self`.
594    unsafe fn from_device(dev: &Device<Ctx>) -> &Self
595    where
596        Self: Sized,
597    {
598        let raw = dev.as_raw();
599        // SAFETY: `raw - Self::OFFSET` is guaranteed by the safety requirements
600        // to be a valid pointer to `Self`.
601        unsafe { &*raw.byte_sub(Self::OFFSET).cast::<Self>() }
602    }
603}
604
605/// # Safety
606///
607/// The type given as `$device` must be a transparent wrapper of a type that doesn't depend on the
608/// generic argument of `$device`.
609#[doc(hidden)]
610#[macro_export]
611macro_rules! __impl_device_context_deref {
612    (unsafe { $device:ident, <$lt:lifetime> $src:ty => $dst:ty }) => {
613        impl<$lt> ::core::ops::Deref for $device<$src> {
614            type Target = $device<$dst>;
615
616            fn deref(&self) -> &Self::Target {
617                let ptr: *const Self = self;
618
619                // CAST: `$device<$src>` and `$device<$dst>` transparently wrap the same type by the
620                // safety requirement of the macro.
621                let ptr = ptr.cast::<Self::Target>();
622
623                // SAFETY: `ptr` was derived from `&self`.
624                unsafe { &*ptr }
625            }
626        }
627    };
628    (unsafe { $device:ident, $src:ty => $dst:ty }) => {
629        impl ::core::ops::Deref for $device<$src> {
630            type Target = $device<$dst>;
631
632            fn deref(&self) -> &Self::Target {
633                let ptr: *const Self = self;
634
635                // CAST: `$device<$src>` and `$device<$dst>` transparently wrap the same type by the
636                // safety requirement of the macro.
637                let ptr = ptr.cast::<Self::Target>();
638
639                // SAFETY: `ptr` was derived from `&self`.
640                unsafe { &*ptr }
641            }
642        }
643    };
644}
645
646/// Implement [`core::ops::Deref`] traits for allowed [`DeviceContext`] conversions of a (bus
647/// specific) device.
648///
649/// # Safety
650///
651/// The type given as `$device` must be a transparent wrapper of a type that doesn't depend on the
652/// generic argument of `$device`.
653#[macro_export]
654macro_rules! impl_device_context_deref {
655    (unsafe { $device:ident }) => {
656        // SAFETY: This macro has the exact same safety requirement as
657        // `__impl_device_context_deref!`.
658        ::kernel::__impl_device_context_deref!(unsafe {
659            $device,
660            <'a> $crate::device::CoreInternal<'a> => $crate::device::Core<'a>
661        });
662
663        // SAFETY: This macro has the exact same safety requirement as
664        // `__impl_device_context_deref!`.
665        ::kernel::__impl_device_context_deref!(unsafe {
666            $device,
667            <'a> $crate::device::Core<'a> => $crate::device::Bound
668        });
669
670        // SAFETY: This macro has the exact same safety requirement as
671        // `__impl_device_context_deref!`.
672        ::kernel::__impl_device_context_deref!(unsafe {
673            $device,
674            $crate::device::Bound => $crate::device::Normal
675        });
676    };
677}
678
679#[doc(hidden)]
680#[macro_export]
681macro_rules! __impl_device_context_into_aref {
682    (<$lt:lifetime> $src:ty, $device:tt) => {
683        impl<$lt> ::core::convert::From<&$device<$src>> for $crate::sync::aref::ARef<$device> {
684            fn from(dev: &$device<$src>) -> Self {
685                (&**dev).into()
686            }
687        }
688    };
689    ($src:ty, $device:tt) => {
690        impl ::core::convert::From<&$device<$src>> for $crate::sync::aref::ARef<$device> {
691            fn from(dev: &$device<$src>) -> Self {
692                (&**dev).into()
693            }
694        }
695    };
696}
697
698/// Implement [`core::convert::From`], such that all `&Device<Ctx>` can be converted to an
699/// `ARef<Device>`.
700#[macro_export]
701macro_rules! impl_device_context_into_aref {
702    ($device:tt) => {
703        ::kernel::__impl_device_context_into_aref!(
704            <'a> $crate::device::CoreInternal<'a>, $device
705        );
706        ::kernel::__impl_device_context_into_aref!(
707            <'a> $crate::device::Core<'a>, $device
708        );
709        ::kernel::__impl_device_context_into_aref!($crate::device::Bound, $device);
710    };
711}
712
713#[doc(hidden)]
714#[macro_export]
715macro_rules! dev_printk {
716    ($method:ident, $dev:expr, $($f:tt)*) => {
717        $crate::device::Device::$method($dev.as_ref(), $crate::prelude::fmt!($($f)*))
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}