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.
514pub struct Core<'a>(PhantomData<&'a ()>);
515
516/// Semantically the same as [`Core`], but reserved for internal usage of the corresponding bus
517/// abstraction.
518///
519/// The internal core context is intended to be used in exactly the same way as the [`Core`]
520/// context, with the difference that this [`DeviceContext`] is internal to the corresponding bus
521/// abstraction.
522///
523/// This context mainly exists to share generic [`Device`] infrastructure that should only be called
524/// from bus callbacks with bus abstractions, but without making them accessible for drivers.
525pub struct CoreInternal<'a>(PhantomData<&'a ()>);
526
527/// The [`Bound`] context is the [`DeviceContext`] of a bus specific device when it is guaranteed to
528/// be bound to a driver.
529///
530/// The bound context indicates that for the entire duration of the lifetime of a [`Device<Bound>`]
531/// reference, the [`Device`] is guaranteed to be bound to a driver.
532///
533/// Some APIs, such as [`dma::Coherent`] or [`Devres`] rely on the [`Device`] to be bound,
534/// which can be proven with the [`Bound`] device context.
535///
536/// Any abstraction that can guarantee a scope where the corresponding bus device is bound, should
537/// provide a [`Device<Bound>`] reference to its users for this scope. This allows users to benefit
538/// from optimizations for accessing device resources, see also [`Devres::access`].
539///
540/// [`Devres`]: kernel::devres::Devres
541/// [`Devres::access`]: kernel::devres::Devres::access
542/// [`dma::Coherent`]: kernel::dma::Coherent
543pub struct Bound;
544
545mod private {
546 pub trait Sealed {}
547
548 impl Sealed for super::Bound {}
549 impl<'a> Sealed for super::Core<'a> {}
550 impl<'a> Sealed for super::CoreInternal<'a> {}
551 impl Sealed for super::Normal {}
552}
553
554impl DeviceContext for Bound {}
555impl<'a> DeviceContext for Core<'a> {}
556impl<'a> DeviceContext for CoreInternal<'a> {}
557impl DeviceContext for Normal {}
558
559impl<Ctx: DeviceContext> AsRef<Device<Ctx>> for Device<Ctx> {
560 #[inline]
561 fn as_ref(&self) -> &Device<Ctx> {
562 self
563 }
564}
565
566/// Convert device references to bus device references.
567///
568/// Bus devices can implement this trait to allow abstractions to provide the bus device in
569/// class device callbacks.
570///
571/// This must not be used by drivers and is intended for bus and class device abstractions only.
572///
573/// # Safety
574///
575/// `AsBusDevice::OFFSET` must be the offset of the embedded base `struct device` field within a
576/// bus device structure.
577pub unsafe trait AsBusDevice<Ctx: DeviceContext>: AsRef<Device<Ctx>> {
578 /// The relative offset to the device field.
579 ///
580 /// Use `offset_of!(bindings, field)` macro to avoid breakage.
581 const OFFSET: usize;
582
583 /// Convert a reference to [`Device`] into `Self`.
584 ///
585 /// # Safety
586 ///
587 /// `dev` must be contained in `Self`.
588 unsafe fn from_device(dev: &Device<Ctx>) -> &Self
589 where
590 Self: Sized,
591 {
592 let raw = dev.as_raw();
593 // SAFETY: `raw - Self::OFFSET` is guaranteed by the safety requirements
594 // to be a valid pointer to `Self`.
595 unsafe { &*raw.byte_sub(Self::OFFSET).cast::<Self>() }
596 }
597}
598
599/// # Safety
600///
601/// The type given as `$device` must be a transparent wrapper of a type that doesn't depend on the
602/// generic argument of `$device`.
603#[doc(hidden)]
604#[macro_export]
605macro_rules! __impl_device_context_deref {
606 (unsafe { $device:ident, <$lt:lifetime> $src:ty => $dst:ty }) => {
607 impl<$lt> ::core::ops::Deref for $device<$src> {
608 type Target = $device<$dst>;
609
610 fn deref(&self) -> &Self::Target {
611 let ptr: *const Self = self;
612
613 // CAST: `$device<$src>` and `$device<$dst>` transparently wrap the same type by the
614 // safety requirement of the macro.
615 let ptr = ptr.cast::<Self::Target>();
616
617 // SAFETY: `ptr` was derived from `&self`.
618 unsafe { &*ptr }
619 }
620 }
621 };
622 (unsafe { $device:ident, $src:ty => $dst:ty }) => {
623 impl ::core::ops::Deref for $device<$src> {
624 type Target = $device<$dst>;
625
626 fn deref(&self) -> &Self::Target {
627 let ptr: *const Self = self;
628
629 // CAST: `$device<$src>` and `$device<$dst>` transparently wrap the same type by the
630 // safety requirement of the macro.
631 let ptr = ptr.cast::<Self::Target>();
632
633 // SAFETY: `ptr` was derived from `&self`.
634 unsafe { &*ptr }
635 }
636 }
637 };
638}
639
640/// Implement [`core::ops::Deref`] traits for allowed [`DeviceContext`] conversions of a (bus
641/// specific) device.
642///
643/// # Safety
644///
645/// The type given as `$device` must be a transparent wrapper of a type that doesn't depend on the
646/// generic argument of `$device`.
647#[macro_export]
648macro_rules! impl_device_context_deref {
649 (unsafe { $device:ident }) => {
650 // SAFETY: This macro has the exact same safety requirement as
651 // `__impl_device_context_deref!`.
652 ::kernel::__impl_device_context_deref!(unsafe {
653 $device,
654 <'a> $crate::device::CoreInternal<'a> => $crate::device::Core<'a>
655 });
656
657 // SAFETY: This macro has the exact same safety requirement as
658 // `__impl_device_context_deref!`.
659 ::kernel::__impl_device_context_deref!(unsafe {
660 $device,
661 <'a> $crate::device::Core<'a> => $crate::device::Bound
662 });
663
664 // SAFETY: This macro has the exact same safety requirement as
665 // `__impl_device_context_deref!`.
666 ::kernel::__impl_device_context_deref!(unsafe {
667 $device,
668 $crate::device::Bound => $crate::device::Normal
669 });
670 };
671}
672
673#[doc(hidden)]
674#[macro_export]
675macro_rules! __impl_device_context_into_aref {
676 (<$lt:lifetime> $src:ty, $device:tt) => {
677 impl<$lt> ::core::convert::From<&$device<$src>> for $crate::sync::aref::ARef<$device> {
678 fn from(dev: &$device<$src>) -> Self {
679 (&**dev).into()
680 }
681 }
682 };
683 ($src:ty, $device:tt) => {
684 impl ::core::convert::From<&$device<$src>> for $crate::sync::aref::ARef<$device> {
685 fn from(dev: &$device<$src>) -> Self {
686 (&**dev).into()
687 }
688 }
689 };
690}
691
692/// Implement [`core::convert::From`], such that all `&Device<Ctx>` can be converted to an
693/// `ARef<Device>`.
694#[macro_export]
695macro_rules! impl_device_context_into_aref {
696 ($device:tt) => {
697 ::kernel::__impl_device_context_into_aref!(
698 <'a> $crate::device::CoreInternal<'a>, $device
699 );
700 ::kernel::__impl_device_context_into_aref!(
701 <'a> $crate::device::Core<'a>, $device
702 );
703 ::kernel::__impl_device_context_into_aref!($crate::device::Bound, $device);
704 };
705}
706
707#[doc(hidden)]
708#[macro_export]
709macro_rules! dev_printk {
710 ($method:ident, $dev:expr, $($f:tt)*) => {
711 {
712 $crate::device::Device::$method($dev.as_ref(), $crate::prelude::fmt!($($f)*))
713 }
714 }
715}
716
717/// Prints an emergency-level message (level 0) prefixed with device information.
718///
719/// This level should be used if the system is unusable.
720///
721/// Equivalent to the kernel's `dev_emerg` macro.
722///
723/// Mimics the interface of [`std::print!`]. More information about the syntax is available from
724/// [`core::fmt`] and [`std::format!`].
725///
726/// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
727/// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html
728///
729/// # Examples
730///
731/// ```
732/// # use kernel::device::Device;
733///
734/// fn example(dev: &Device) {
735/// dev_emerg!(dev, "hello {}\n", "there");
736/// }
737/// ```
738#[macro_export]
739macro_rules! dev_emerg {
740 ($($f:tt)*) => { $crate::dev_printk!(pr_emerg, $($f)*); }
741}
742
743/// Prints an alert-level message (level 1) prefixed with device information.
744///
745/// This level should be used if action must be taken immediately.
746///
747/// Equivalent to the kernel's `dev_alert` macro.
748///
749/// Mimics the interface of [`std::print!`]. More information about the syntax is available from
750/// [`core::fmt`] and [`std::format!`].
751///
752/// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
753/// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html
754///
755/// # Examples
756///
757/// ```
758/// # use kernel::device::Device;
759///
760/// fn example(dev: &Device) {
761/// dev_alert!(dev, "hello {}\n", "there");
762/// }
763/// ```
764#[macro_export]
765macro_rules! dev_alert {
766 ($($f:tt)*) => { $crate::dev_printk!(pr_alert, $($f)*); }
767}
768
769/// Prints a critical-level message (level 2) prefixed with device information.
770///
771/// This level should be used in critical conditions.
772///
773/// Equivalent to the kernel's `dev_crit` macro.
774///
775/// Mimics the interface of [`std::print!`]. More information about the syntax is available from
776/// [`core::fmt`] and [`std::format!`].
777///
778/// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
779/// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html
780///
781/// # Examples
782///
783/// ```
784/// # use kernel::device::Device;
785///
786/// fn example(dev: &Device) {
787/// dev_crit!(dev, "hello {}\n", "there");
788/// }
789/// ```
790#[macro_export]
791macro_rules! dev_crit {
792 ($($f:tt)*) => { $crate::dev_printk!(pr_crit, $($f)*); }
793}
794
795/// Prints an error-level message (level 3) prefixed with device information.
796///
797/// This level should be used in error conditions.
798///
799/// Equivalent to the kernel's `dev_err` macro.
800///
801/// Mimics the interface of [`std::print!`]. More information about the syntax is available from
802/// [`core::fmt`] and [`std::format!`].
803///
804/// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
805/// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html
806///
807/// # Examples
808///
809/// ```
810/// # use kernel::device::Device;
811///
812/// fn example(dev: &Device) {
813/// dev_err!(dev, "hello {}\n", "there");
814/// }
815/// ```
816#[macro_export]
817macro_rules! dev_err {
818 ($($f:tt)*) => { $crate::dev_printk!(pr_err, $($f)*); }
819}
820
821/// Prints a warning-level message (level 4) prefixed with device information.
822///
823/// This level should be used in warning conditions.
824///
825/// Equivalent to the kernel's `dev_warn` macro.
826///
827/// Mimics the interface of [`std::print!`]. More information about the syntax is available from
828/// [`core::fmt`] and [`std::format!`].
829///
830/// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
831/// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html
832///
833/// # Examples
834///
835/// ```
836/// # use kernel::device::Device;
837///
838/// fn example(dev: &Device) {
839/// dev_warn!(dev, "hello {}\n", "there");
840/// }
841/// ```
842#[macro_export]
843macro_rules! dev_warn {
844 ($($f:tt)*) => { $crate::dev_printk!(pr_warn, $($f)*); }
845}
846
847/// Prints a notice-level message (level 5) prefixed with device information.
848///
849/// This level should be used in normal but significant conditions.
850///
851/// Equivalent to the kernel's `dev_notice` macro.
852///
853/// Mimics the interface of [`std::print!`]. More information about the syntax is available from
854/// [`core::fmt`] and [`std::format!`].
855///
856/// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
857/// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html
858///
859/// # Examples
860///
861/// ```
862/// # use kernel::device::Device;
863///
864/// fn example(dev: &Device) {
865/// dev_notice!(dev, "hello {}\n", "there");
866/// }
867/// ```
868#[macro_export]
869macro_rules! dev_notice {
870 ($($f:tt)*) => { $crate::dev_printk!(pr_notice, $($f)*); }
871}
872
873/// Prints an info-level message (level 6) prefixed with device information.
874///
875/// This level should be used for informational messages.
876///
877/// Equivalent to the kernel's `dev_info` macro.
878///
879/// Mimics the interface of [`std::print!`]. More information about the syntax is available from
880/// [`core::fmt`] and [`std::format!`].
881///
882/// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
883/// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html
884///
885/// # Examples
886///
887/// ```
888/// # use kernel::device::Device;
889///
890/// fn example(dev: &Device) {
891/// dev_info!(dev, "hello {}\n", "there");
892/// }
893/// ```
894#[macro_export]
895macro_rules! dev_info {
896 ($($f:tt)*) => { $crate::dev_printk!(pr_info, $($f)*); }
897}
898
899/// Prints a debug-level message (level 7) prefixed with device information.
900///
901/// This level should be used for debug messages.
902///
903/// Equivalent to the kernel's `dev_dbg` macro, except that it doesn't support dynamic debug yet.
904///
905/// Mimics the interface of [`std::print!`]. More information about the syntax is available from
906/// [`core::fmt`] and [`std::format!`].
907///
908/// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
909/// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html
910///
911/// # Examples
912///
913/// ```
914/// # use kernel::device::Device;
915///
916/// fn example(dev: &Device) {
917/// dev_dbg!(dev, "hello {}\n", "there");
918/// }
919/// ```
920#[macro_export]
921macro_rules! dev_dbg {
922 ($($f:tt)*) => { $crate::dev_printk!(pr_dbg, $($f)*); }
923}