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