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 types::{ARef, Opaque},
10};
11use core::{fmt, marker::PhantomData, ptr};
12
13#[cfg(CONFIG_PRINTK)]
14use crate::c_str;
15
16pub mod property;
17
18/// A reference-counted device.
19///
20/// This structure represents the Rust abstraction for a C `struct device`. This implementation
21/// abstracts the usage of an already existing C `struct device` within Rust code that we get
22/// passed from the C side.
23///
24/// An instance of this abstraction can be obtained temporarily or permanent.
25///
26/// A temporary one is bound to the lifetime of the C `struct device` pointer used for creation.
27/// A permanent instance is always reference-counted and hence not restricted by any lifetime
28/// boundaries.
29///
30/// For subsystems it is recommended to create a permanent instance to wrap into a subsystem
31/// specific device structure (e.g. `pci::Device`). This is useful for passing it to drivers in
32/// `T::probe()`, such that a driver can store the `ARef<Device>` (equivalent to storing a
33/// `struct device` pointer in a C driver) for arbitrary purposes, e.g. allocating DMA coherent
34/// memory.
35///
36/// # Invariants
37///
38/// A `Device` instance represents a valid `struct device` created by the C portion of the kernel.
39///
40/// Instances of this type are always reference-counted, that is, a call to `get_device` ensures
41/// that the allocation remains valid at least until the matching call to `put_device`.
42///
43/// `bindings::device::release` is valid to be called from any thread, hence `ARef<Device>` can be
44/// dropped from any thread.
45#[repr(transparent)]
46pub struct Device<Ctx: DeviceContext = Normal>(Opaque<bindings::device>, PhantomData<Ctx>);
47
48impl Device {
49 /// Creates a new reference-counted abstraction instance of an existing `struct device` pointer.
50 ///
51 /// # Safety
52 ///
53 /// Callers must ensure that `ptr` is valid, non-null, and has a non-zero reference count,
54 /// i.e. it must be ensured that the reference count of the C `struct device` `ptr` points to
55 /// can't drop to zero, for the duration of this function call.
56 ///
57 /// It must also be ensured that `bindings::device::release` can be called from any thread.
58 /// While not officially documented, this should be the case for any `struct device`.
59 pub unsafe fn get_device(ptr: *mut bindings::device) -> ARef<Self> {
60 // SAFETY: By the safety requirements ptr is valid
61 unsafe { Self::as_ref(ptr) }.into()
62 }
63}
64
65impl<Ctx: DeviceContext> Device<Ctx> {
66 /// Obtain the raw `struct device *`.
67 pub(crate) fn as_raw(&self) -> *mut bindings::device {
68 self.0.get()
69 }
70
71 /// Returns a reference to the parent device, if any.
72 #[cfg_attr(not(CONFIG_AUXILIARY_BUS), expect(dead_code))]
73 pub(crate) fn parent(&self) -> Option<&Self> {
74 // SAFETY:
75 // - By the type invariant `self.as_raw()` is always valid.
76 // - The parent device is only ever set at device creation.
77 let parent = unsafe { (*self.as_raw()).parent };
78
79 if parent.is_null() {
80 None
81 } else {
82 // SAFETY:
83 // - Since `parent` is not NULL, it must be a valid pointer to a `struct device`.
84 // - `parent` is valid for the lifetime of `self`, since a `struct device` holds a
85 // reference count of its parent.
86 Some(unsafe { Self::as_ref(parent) })
87 }
88 }
89
90 /// Convert a raw C `struct device` pointer to a `&'a Device`.
91 ///
92 /// # Safety
93 ///
94 /// Callers must ensure that `ptr` is valid, non-null, and has a non-zero reference count,
95 /// i.e. it must be ensured that the reference count of the C `struct device` `ptr` points to
96 /// can't drop to zero, for the duration of this function call and the entire duration when the
97 /// returned reference exists.
98 pub unsafe fn as_ref<'a>(ptr: *mut bindings::device) -> &'a Self {
99 // SAFETY: Guaranteed by the safety requirements of the function.
100 unsafe { &*ptr.cast() }
101 }
102
103 /// Prints an emergency-level message (level 0) prefixed with device information.
104 ///
105 /// More details are available from [`dev_emerg`].
106 ///
107 /// [`dev_emerg`]: crate::dev_emerg
108 pub fn pr_emerg(&self, args: fmt::Arguments<'_>) {
109 // SAFETY: `klevel` is null-terminated, uses one of the kernel constants.
110 unsafe { self.printk(bindings::KERN_EMERG, args) };
111 }
112
113 /// Prints an alert-level message (level 1) prefixed with device information.
114 ///
115 /// More details are available from [`dev_alert`].
116 ///
117 /// [`dev_alert`]: crate::dev_alert
118 pub fn pr_alert(&self, args: fmt::Arguments<'_>) {
119 // SAFETY: `klevel` is null-terminated, uses one of the kernel constants.
120 unsafe { self.printk(bindings::KERN_ALERT, args) };
121 }
122
123 /// Prints a critical-level message (level 2) prefixed with device information.
124 ///
125 /// More details are available from [`dev_crit`].
126 ///
127 /// [`dev_crit`]: crate::dev_crit
128 pub fn pr_crit(&self, args: fmt::Arguments<'_>) {
129 // SAFETY: `klevel` is null-terminated, uses one of the kernel constants.
130 unsafe { self.printk(bindings::KERN_CRIT, args) };
131 }
132
133 /// Prints an error-level message (level 3) prefixed with device information.
134 ///
135 /// More details are available from [`dev_err`].
136 ///
137 /// [`dev_err`]: crate::dev_err
138 pub fn pr_err(&self, args: fmt::Arguments<'_>) {
139 // SAFETY: `klevel` is null-terminated, uses one of the kernel constants.
140 unsafe { self.printk(bindings::KERN_ERR, args) };
141 }
142
143 /// Prints a warning-level message (level 4) prefixed with device information.
144 ///
145 /// More details are available from [`dev_warn`].
146 ///
147 /// [`dev_warn`]: crate::dev_warn
148 pub fn pr_warn(&self, args: fmt::Arguments<'_>) {
149 // SAFETY: `klevel` is null-terminated, uses one of the kernel constants.
150 unsafe { self.printk(bindings::KERN_WARNING, args) };
151 }
152
153 /// Prints a notice-level message (level 5) prefixed with device information.
154 ///
155 /// More details are available from [`dev_notice`].
156 ///
157 /// [`dev_notice`]: crate::dev_notice
158 pub fn pr_notice(&self, args: fmt::Arguments<'_>) {
159 // SAFETY: `klevel` is null-terminated, uses one of the kernel constants.
160 unsafe { self.printk(bindings::KERN_NOTICE, args) };
161 }
162
163 /// Prints an info-level message (level 6) prefixed with device information.
164 ///
165 /// More details are available from [`dev_info`].
166 ///
167 /// [`dev_info`]: crate::dev_info
168 pub fn pr_info(&self, args: fmt::Arguments<'_>) {
169 // SAFETY: `klevel` is null-terminated, uses one of the kernel constants.
170 unsafe { self.printk(bindings::KERN_INFO, args) };
171 }
172
173 /// Prints a debug-level message (level 7) prefixed with device information.
174 ///
175 /// More details are available from [`dev_dbg`].
176 ///
177 /// [`dev_dbg`]: crate::dev_dbg
178 pub fn pr_dbg(&self, args: fmt::Arguments<'_>) {
179 if cfg!(debug_assertions) {
180 // SAFETY: `klevel` is null-terminated, uses one of the kernel constants.
181 unsafe { self.printk(bindings::KERN_DEBUG, args) };
182 }
183 }
184
185 /// Prints the provided message to the console.
186 ///
187 /// # Safety
188 ///
189 /// Callers must ensure that `klevel` is null-terminated; in particular, one of the
190 /// `KERN_*`constants, for example, `KERN_CRIT`, `KERN_ALERT`, etc.
191 #[cfg_attr(not(CONFIG_PRINTK), allow(unused_variables))]
192 unsafe fn printk(&self, klevel: &[u8], msg: fmt::Arguments<'_>) {
193 // SAFETY: `klevel` is null-terminated and one of the kernel constants. `self.as_raw`
194 // is valid because `self` is valid. The "%pA" format string expects a pointer to
195 // `fmt::Arguments`, which is what we're passing as the last argument.
196 #[cfg(CONFIG_PRINTK)]
197 unsafe {
198 bindings::_dev_printk(
199 klevel.as_ptr().cast::<crate::ffi::c_char>(),
200 self.as_raw(),
201 c_str!("%pA").as_char_ptr(),
202 core::ptr::from_ref(&msg).cast::<crate::ffi::c_void>(),
203 )
204 };
205 }
206
207 /// Obtain the [`FwNode`](property::FwNode) corresponding to this [`Device`].
208 pub fn fwnode(&self) -> Option<&property::FwNode> {
209 // SAFETY: `self` is valid.
210 let fwnode_handle = unsafe { bindings::__dev_fwnode(self.as_raw()) };
211 if fwnode_handle.is_null() {
212 return None;
213 }
214 // SAFETY: `fwnode_handle` is valid. Its lifetime is tied to `&self`. We
215 // return a reference instead of an `ARef<FwNode>` because `dev_fwnode()`
216 // doesn't increment the refcount. It is safe to cast from a
217 // `struct fwnode_handle*` to a `*const FwNode` because `FwNode` is
218 // defined as a `#[repr(transparent)]` wrapper around `fwnode_handle`.
219 Some(unsafe { &*fwnode_handle.cast() })
220 }
221}
222
223// SAFETY: `Device` is a transparent wrapper of a type that doesn't depend on `Device`'s generic
224// argument.
225kernel::impl_device_context_deref!(unsafe { Device });
226kernel::impl_device_context_into_aref!(Device);
227
228// SAFETY: Instances of `Device` are always reference-counted.
229unsafe impl crate::types::AlwaysRefCounted for Device {
230 fn inc_ref(&self) {
231 // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
232 unsafe { bindings::get_device(self.as_raw()) };
233 }
234
235 unsafe fn dec_ref(obj: ptr::NonNull<Self>) {
236 // SAFETY: The safety requirements guarantee that the refcount is non-zero.
237 unsafe { bindings::put_device(obj.cast().as_ptr()) }
238 }
239}
240
241// SAFETY: As by the type invariant `Device` can be sent to any thread.
242unsafe impl Send for Device {}
243
244// SAFETY: `Device` can be shared among threads because all immutable methods are protected by the
245// synchronization in `struct device`.
246unsafe impl Sync for Device {}
247
248/// Marker trait for the context of a bus specific device.
249///
250/// Some functions of a bus specific device should only be called from a certain context, i.e. bus
251/// callbacks, such as `probe()`.
252///
253/// This is the marker trait for structures representing the context of a bus specific device.
254pub trait DeviceContext: private::Sealed {}
255
256/// The [`Normal`] context is the context of a bus specific device when it is not an argument of
257/// any bus callback.
258pub struct Normal;
259
260/// The [`Core`] context is the context of a bus specific device when it is supplied as argument of
261/// any of the bus callbacks, such as `probe()`.
262pub struct Core;
263
264/// The [`Bound`] context is the context of a bus specific device reference when it is guaranteed to
265/// be bound for the duration of its lifetime.
266pub struct Bound;
267
268mod private {
269 pub trait Sealed {}
270
271 impl Sealed for super::Bound {}
272 impl Sealed for super::Core {}
273 impl Sealed for super::Normal {}
274}
275
276impl DeviceContext for Bound {}
277impl DeviceContext for Core {}
278impl DeviceContext for Normal {}
279
280/// # Safety
281///
282/// The type given as `$device` must be a transparent wrapper of a type that doesn't depend on the
283/// generic argument of `$device`.
284#[doc(hidden)]
285#[macro_export]
286macro_rules! __impl_device_context_deref {
287 (unsafe { $device:ident, $src:ty => $dst:ty }) => {
288 impl ::core::ops::Deref for $device<$src> {
289 type Target = $device<$dst>;
290
291 fn deref(&self) -> &Self::Target {
292 let ptr: *const Self = self;
293
294 // CAST: `$device<$src>` and `$device<$dst>` transparently wrap the same type by the
295 // safety requirement of the macro.
296 let ptr = ptr.cast::<Self::Target>();
297
298 // SAFETY: `ptr` was derived from `&self`.
299 unsafe { &*ptr }
300 }
301 }
302 };
303}
304
305/// Implement [`core::ops::Deref`] traits for allowed [`DeviceContext`] conversions of a (bus
306/// specific) device.
307///
308/// # Safety
309///
310/// The type given as `$device` must be a transparent wrapper of a type that doesn't depend on the
311/// generic argument of `$device`.
312#[macro_export]
313macro_rules! impl_device_context_deref {
314 (unsafe { $device:ident }) => {
315 // SAFETY: This macro has the exact same safety requirement as
316 // `__impl_device_context_deref!`.
317 ::kernel::__impl_device_context_deref!(unsafe {
318 $device,
319 $crate::device::Core => $crate::device::Bound
320 });
321
322 // SAFETY: This macro has the exact same safety requirement as
323 // `__impl_device_context_deref!`.
324 ::kernel::__impl_device_context_deref!(unsafe {
325 $device,
326 $crate::device::Bound => $crate::device::Normal
327 });
328 };
329}
330
331#[doc(hidden)]
332#[macro_export]
333macro_rules! __impl_device_context_into_aref {
334 ($src:ty, $device:tt) => {
335 impl ::core::convert::From<&$device<$src>> for $crate::types::ARef<$device> {
336 fn from(dev: &$device<$src>) -> Self {
337 (&**dev).into()
338 }
339 }
340 };
341}
342
343/// Implement [`core::convert::From`], such that all `&Device<Ctx>` can be converted to an
344/// `ARef<Device>`.
345#[macro_export]
346macro_rules! impl_device_context_into_aref {
347 ($device:tt) => {
348 ::kernel::__impl_device_context_into_aref!($crate::device::Core, $device);
349 ::kernel::__impl_device_context_into_aref!($crate::device::Bound, $device);
350 };
351}
352
353#[doc(hidden)]
354#[macro_export]
355macro_rules! dev_printk {
356 ($method:ident, $dev:expr, $($f:tt)*) => {
357 {
358 ($dev).$method(::core::format_args!($($f)*));
359 }
360 }
361}
362
363/// Prints an emergency-level message (level 0) prefixed with device information.
364///
365/// This level should be used if the system is unusable.
366///
367/// Equivalent to the kernel's `dev_emerg` macro.
368///
369/// Mimics the interface of [`std::print!`]. More information about the syntax is available from
370/// [`core::fmt`] and [`std::format!`].
371///
372/// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
373/// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html
374///
375/// # Examples
376///
377/// ```
378/// # use kernel::device::Device;
379///
380/// fn example(dev: &Device) {
381/// dev_emerg!(dev, "hello {}\n", "there");
382/// }
383/// ```
384#[macro_export]
385macro_rules! dev_emerg {
386 ($($f:tt)*) => { $crate::dev_printk!(pr_emerg, $($f)*); }
387}
388
389/// Prints an alert-level message (level 1) prefixed with device information.
390///
391/// This level should be used if action must be taken immediately.
392///
393/// Equivalent to the kernel's `dev_alert` macro.
394///
395/// Mimics the interface of [`std::print!`]. More information about the syntax is available from
396/// [`core::fmt`] and [`std::format!`].
397///
398/// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
399/// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html
400///
401/// # Examples
402///
403/// ```
404/// # use kernel::device::Device;
405///
406/// fn example(dev: &Device) {
407/// dev_alert!(dev, "hello {}\n", "there");
408/// }
409/// ```
410#[macro_export]
411macro_rules! dev_alert {
412 ($($f:tt)*) => { $crate::dev_printk!(pr_alert, $($f)*); }
413}
414
415/// Prints a critical-level message (level 2) prefixed with device information.
416///
417/// This level should be used in critical conditions.
418///
419/// Equivalent to the kernel's `dev_crit` macro.
420///
421/// Mimics the interface of [`std::print!`]. More information about the syntax is available from
422/// [`core::fmt`] and [`std::format!`].
423///
424/// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
425/// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html
426///
427/// # Examples
428///
429/// ```
430/// # use kernel::device::Device;
431///
432/// fn example(dev: &Device) {
433/// dev_crit!(dev, "hello {}\n", "there");
434/// }
435/// ```
436#[macro_export]
437macro_rules! dev_crit {
438 ($($f:tt)*) => { $crate::dev_printk!(pr_crit, $($f)*); }
439}
440
441/// Prints an error-level message (level 3) prefixed with device information.
442///
443/// This level should be used in error conditions.
444///
445/// Equivalent to the kernel's `dev_err` macro.
446///
447/// Mimics the interface of [`std::print!`]. More information about the syntax is available from
448/// [`core::fmt`] and [`std::format!`].
449///
450/// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
451/// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html
452///
453/// # Examples
454///
455/// ```
456/// # use kernel::device::Device;
457///
458/// fn example(dev: &Device) {
459/// dev_err!(dev, "hello {}\n", "there");
460/// }
461/// ```
462#[macro_export]
463macro_rules! dev_err {
464 ($($f:tt)*) => { $crate::dev_printk!(pr_err, $($f)*); }
465}
466
467/// Prints a warning-level message (level 4) prefixed with device information.
468///
469/// This level should be used in warning conditions.
470///
471/// Equivalent to the kernel's `dev_warn` macro.
472///
473/// Mimics the interface of [`std::print!`]. More information about the syntax is available from
474/// [`core::fmt`] and [`std::format!`].
475///
476/// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
477/// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html
478///
479/// # Examples
480///
481/// ```
482/// # use kernel::device::Device;
483///
484/// fn example(dev: &Device) {
485/// dev_warn!(dev, "hello {}\n", "there");
486/// }
487/// ```
488#[macro_export]
489macro_rules! dev_warn {
490 ($($f:tt)*) => { $crate::dev_printk!(pr_warn, $($f)*); }
491}
492
493/// Prints a notice-level message (level 5) prefixed with device information.
494///
495/// This level should be used in normal but significant conditions.
496///
497/// Equivalent to the kernel's `dev_notice` macro.
498///
499/// Mimics the interface of [`std::print!`]. More information about the syntax is available from
500/// [`core::fmt`] and [`std::format!`].
501///
502/// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
503/// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html
504///
505/// # Examples
506///
507/// ```
508/// # use kernel::device::Device;
509///
510/// fn example(dev: &Device) {
511/// dev_notice!(dev, "hello {}\n", "there");
512/// }
513/// ```
514#[macro_export]
515macro_rules! dev_notice {
516 ($($f:tt)*) => { $crate::dev_printk!(pr_notice, $($f)*); }
517}
518
519/// Prints an info-level message (level 6) prefixed with device information.
520///
521/// This level should be used for informational messages.
522///
523/// Equivalent to the kernel's `dev_info` macro.
524///
525/// Mimics the interface of [`std::print!`]. More information about the syntax is available from
526/// [`core::fmt`] and [`std::format!`].
527///
528/// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
529/// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html
530///
531/// # Examples
532///
533/// ```
534/// # use kernel::device::Device;
535///
536/// fn example(dev: &Device) {
537/// dev_info!(dev, "hello {}\n", "there");
538/// }
539/// ```
540#[macro_export]
541macro_rules! dev_info {
542 ($($f:tt)*) => { $crate::dev_printk!(pr_info, $($f)*); }
543}
544
545/// Prints a debug-level message (level 7) prefixed with device information.
546///
547/// This level should be used for debug messages.
548///
549/// Equivalent to the kernel's `dev_dbg` macro, except that it doesn't support dynamic debug yet.
550///
551/// Mimics the interface of [`std::print!`]. More information about the syntax is available from
552/// [`core::fmt`] and [`std::format!`].
553///
554/// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
555/// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html
556///
557/// # Examples
558///
559/// ```
560/// # use kernel::device::Device;
561///
562/// fn example(dev: &Device) {
563/// dev_dbg!(dev, "hello {}\n", "there");
564/// }
565/// ```
566#[macro_export]
567macro_rules! dev_dbg {
568 ($($f:tt)*) => { $crate::dev_printk!(pr_dbg, $($f)*); }
569}