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