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