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, 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(Opaque<bindings::device>);
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    /// Obtain the raw `struct device *`.
64    pub(crate) fn as_raw(&self) -> *mut bindings::device {
65        self.0.get()
66    }
67
68    /// Convert a raw C `struct device` pointer to a `&'a Device`.
69    ///
70    /// # Safety
71    ///
72    /// Callers must ensure that `ptr` is valid, non-null, and has a non-zero reference count,
73    /// i.e. it must be ensured that the reference count of the C `struct device` `ptr` points to
74    /// can't drop to zero, for the duration of this function call and the entire duration when the
75    /// returned reference exists.
76    pub unsafe fn as_ref<'a>(ptr: *mut bindings::device) -> &'a Self {
77        // SAFETY: Guaranteed by the safety requirements of the function.
78        unsafe { &*ptr.cast() }
79    }
80
81    /// Prints an emergency-level message (level 0) prefixed with device information.
82    ///
83    /// More details are available from [`dev_emerg`].
84    ///
85    /// [`dev_emerg`]: crate::dev_emerg
86    pub fn pr_emerg(&self, args: fmt::Arguments<'_>) {
87        // SAFETY: `klevel` is null-terminated, uses one of the kernel constants.
88        unsafe { self.printk(bindings::KERN_EMERG, args) };
89    }
90
91    /// Prints an alert-level message (level 1) prefixed with device information.
92    ///
93    /// More details are available from [`dev_alert`].
94    ///
95    /// [`dev_alert`]: crate::dev_alert
96    pub fn pr_alert(&self, args: fmt::Arguments<'_>) {
97        // SAFETY: `klevel` is null-terminated, uses one of the kernel constants.
98        unsafe { self.printk(bindings::KERN_ALERT, args) };
99    }
100
101    /// Prints a critical-level message (level 2) prefixed with device information.
102    ///
103    /// More details are available from [`dev_crit`].
104    ///
105    /// [`dev_crit`]: crate::dev_crit
106    pub fn pr_crit(&self, args: fmt::Arguments<'_>) {
107        // SAFETY: `klevel` is null-terminated, uses one of the kernel constants.
108        unsafe { self.printk(bindings::KERN_CRIT, args) };
109    }
110
111    /// Prints an error-level message (level 3) prefixed with device information.
112    ///
113    /// More details are available from [`dev_err`].
114    ///
115    /// [`dev_err`]: crate::dev_err
116    pub fn pr_err(&self, args: fmt::Arguments<'_>) {
117        // SAFETY: `klevel` is null-terminated, uses one of the kernel constants.
118        unsafe { self.printk(bindings::KERN_ERR, args) };
119    }
120
121    /// Prints a warning-level message (level 4) prefixed with device information.
122    ///
123    /// More details are available from [`dev_warn`].
124    ///
125    /// [`dev_warn`]: crate::dev_warn
126    pub fn pr_warn(&self, args: fmt::Arguments<'_>) {
127        // SAFETY: `klevel` is null-terminated, uses one of the kernel constants.
128        unsafe { self.printk(bindings::KERN_WARNING, args) };
129    }
130
131    /// Prints a notice-level message (level 5) prefixed with device information.
132    ///
133    /// More details are available from [`dev_notice`].
134    ///
135    /// [`dev_notice`]: crate::dev_notice
136    pub fn pr_notice(&self, args: fmt::Arguments<'_>) {
137        // SAFETY: `klevel` is null-terminated, uses one of the kernel constants.
138        unsafe { self.printk(bindings::KERN_NOTICE, args) };
139    }
140
141    /// Prints an info-level message (level 6) prefixed with device information.
142    ///
143    /// More details are available from [`dev_info`].
144    ///
145    /// [`dev_info`]: crate::dev_info
146    pub fn pr_info(&self, args: fmt::Arguments<'_>) {
147        // SAFETY: `klevel` is null-terminated, uses one of the kernel constants.
148        unsafe { self.printk(bindings::KERN_INFO, args) };
149    }
150
151    /// Prints a debug-level message (level 7) prefixed with device information.
152    ///
153    /// More details are available from [`dev_dbg`].
154    ///
155    /// [`dev_dbg`]: crate::dev_dbg
156    pub fn pr_dbg(&self, args: fmt::Arguments<'_>) {
157        if cfg!(debug_assertions) {
158            // SAFETY: `klevel` is null-terminated, uses one of the kernel constants.
159            unsafe { self.printk(bindings::KERN_DEBUG, args) };
160        }
161    }
162
163    /// Prints the provided message to the console.
164    ///
165    /// # Safety
166    ///
167    /// Callers must ensure that `klevel` is null-terminated; in particular, one of the
168    /// `KERN_*`constants, for example, `KERN_CRIT`, `KERN_ALERT`, etc.
169    #[cfg_attr(not(CONFIG_PRINTK), allow(unused_variables))]
170    unsafe fn printk(&self, klevel: &[u8], msg: fmt::Arguments<'_>) {
171        // SAFETY: `klevel` is null-terminated and one of the kernel constants. `self.as_raw`
172        // is valid because `self` is valid. The "%pA" format string expects a pointer to
173        // `fmt::Arguments`, which is what we're passing as the last argument.
174        #[cfg(CONFIG_PRINTK)]
175        unsafe {
176            bindings::_dev_printk(
177                klevel as *const _ as *const crate::ffi::c_char,
178                self.as_raw(),
179                c_str!("%pA").as_char_ptr(),
180                &msg as *const _ as *const crate::ffi::c_void,
181            )
182        };
183    }
184
185    /// Checks if property is present or not.
186    pub fn property_present(&self, name: &CStr) -> bool {
187        // SAFETY: By the invariant of `CStr`, `name` is null-terminated.
188        unsafe { bindings::device_property_present(self.as_raw().cast_const(), name.as_char_ptr()) }
189    }
190}
191
192// SAFETY: Instances of `Device` are always reference-counted.
193unsafe impl crate::types::AlwaysRefCounted for Device {
194    fn inc_ref(&self) {
195        // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
196        unsafe { bindings::get_device(self.as_raw()) };
197    }
198
199    unsafe fn dec_ref(obj: ptr::NonNull<Self>) {
200        // SAFETY: The safety requirements guarantee that the refcount is non-zero.
201        unsafe { bindings::put_device(obj.cast().as_ptr()) }
202    }
203}
204
205// SAFETY: As by the type invariant `Device` can be sent to any thread.
206unsafe impl Send for Device {}
207
208// SAFETY: `Device` can be shared among threads because all immutable methods are protected by the
209// synchronization in `struct device`.
210unsafe impl Sync for Device {}
211
212/// Marker trait for the context of a bus specific device.
213///
214/// Some functions of a bus specific device should only be called from a certain context, i.e. bus
215/// callbacks, such as `probe()`.
216///
217/// This is the marker trait for structures representing the context of a bus specific device.
218pub trait DeviceContext: private::Sealed {}
219
220/// The [`Normal`] context is the context of a bus specific device when it is not an argument of
221/// any bus callback.
222pub struct Normal;
223
224/// The [`Core`] context is the context of a bus specific device when it is supplied as argument of
225/// any of the bus callbacks, such as `probe()`.
226pub struct Core;
227
228mod private {
229    pub trait Sealed {}
230
231    impl Sealed for super::Core {}
232    impl Sealed for super::Normal {}
233}
234
235impl DeviceContext for Core {}
236impl DeviceContext for Normal {}
237
238#[doc(hidden)]
239#[macro_export]
240macro_rules! dev_printk {
241    ($method:ident, $dev:expr, $($f:tt)*) => {
242        {
243            ($dev).$method(core::format_args!($($f)*));
244        }
245    }
246}
247
248/// Prints an emergency-level message (level 0) prefixed with device information.
249///
250/// This level should be used if the system is unusable.
251///
252/// Equivalent to the kernel's `dev_emerg` macro.
253///
254/// Mimics the interface of [`std::print!`]. More information about the syntax is available from
255/// [`core::fmt`] and `alloc::format!`.
256///
257/// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
258///
259/// # Examples
260///
261/// ```
262/// # use kernel::device::Device;
263///
264/// fn example(dev: &Device) {
265///     dev_emerg!(dev, "hello {}\n", "there");
266/// }
267/// ```
268#[macro_export]
269macro_rules! dev_emerg {
270    ($($f:tt)*) => { $crate::dev_printk!(pr_emerg, $($f)*); }
271}
272
273/// Prints an alert-level message (level 1) prefixed with device information.
274///
275/// This level should be used if action must be taken immediately.
276///
277/// Equivalent to the kernel's `dev_alert` macro.
278///
279/// Mimics the interface of [`std::print!`]. More information about the syntax is available from
280/// [`core::fmt`] and `alloc::format!`.
281///
282/// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
283///
284/// # Examples
285///
286/// ```
287/// # use kernel::device::Device;
288///
289/// fn example(dev: &Device) {
290///     dev_alert!(dev, "hello {}\n", "there");
291/// }
292/// ```
293#[macro_export]
294macro_rules! dev_alert {
295    ($($f:tt)*) => { $crate::dev_printk!(pr_alert, $($f)*); }
296}
297
298/// Prints a critical-level message (level 2) prefixed with device information.
299///
300/// This level should be used in critical conditions.
301///
302/// Equivalent to the kernel's `dev_crit` macro.
303///
304/// Mimics the interface of [`std::print!`]. More information about the syntax is available from
305/// [`core::fmt`] and `alloc::format!`.
306///
307/// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
308///
309/// # Examples
310///
311/// ```
312/// # use kernel::device::Device;
313///
314/// fn example(dev: &Device) {
315///     dev_crit!(dev, "hello {}\n", "there");
316/// }
317/// ```
318#[macro_export]
319macro_rules! dev_crit {
320    ($($f:tt)*) => { $crate::dev_printk!(pr_crit, $($f)*); }
321}
322
323/// Prints an error-level message (level 3) prefixed with device information.
324///
325/// This level should be used in error conditions.
326///
327/// Equivalent to the kernel's `dev_err` macro.
328///
329/// Mimics the interface of [`std::print!`]. More information about the syntax is available from
330/// [`core::fmt`] and `alloc::format!`.
331///
332/// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
333///
334/// # Examples
335///
336/// ```
337/// # use kernel::device::Device;
338///
339/// fn example(dev: &Device) {
340///     dev_err!(dev, "hello {}\n", "there");
341/// }
342/// ```
343#[macro_export]
344macro_rules! dev_err {
345    ($($f:tt)*) => { $crate::dev_printk!(pr_err, $($f)*); }
346}
347
348/// Prints a warning-level message (level 4) prefixed with device information.
349///
350/// This level should be used in warning conditions.
351///
352/// Equivalent to the kernel's `dev_warn` macro.
353///
354/// Mimics the interface of [`std::print!`]. More information about the syntax is available from
355/// [`core::fmt`] and `alloc::format!`.
356///
357/// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
358///
359/// # Examples
360///
361/// ```
362/// # use kernel::device::Device;
363///
364/// fn example(dev: &Device) {
365///     dev_warn!(dev, "hello {}\n", "there");
366/// }
367/// ```
368#[macro_export]
369macro_rules! dev_warn {
370    ($($f:tt)*) => { $crate::dev_printk!(pr_warn, $($f)*); }
371}
372
373/// Prints a notice-level message (level 5) prefixed with device information.
374///
375/// This level should be used in normal but significant conditions.
376///
377/// Equivalent to the kernel's `dev_notice` macro.
378///
379/// Mimics the interface of [`std::print!`]. More information about the syntax is available from
380/// [`core::fmt`] and `alloc::format!`.
381///
382/// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
383///
384/// # Examples
385///
386/// ```
387/// # use kernel::device::Device;
388///
389/// fn example(dev: &Device) {
390///     dev_notice!(dev, "hello {}\n", "there");
391/// }
392/// ```
393#[macro_export]
394macro_rules! dev_notice {
395    ($($f:tt)*) => { $crate::dev_printk!(pr_notice, $($f)*); }
396}
397
398/// Prints an info-level message (level 6) prefixed with device information.
399///
400/// This level should be used for informational messages.
401///
402/// Equivalent to the kernel's `dev_info` macro.
403///
404/// Mimics the interface of [`std::print!`]. More information about the syntax is available from
405/// [`core::fmt`] and `alloc::format!`.
406///
407/// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
408///
409/// # Examples
410///
411/// ```
412/// # use kernel::device::Device;
413///
414/// fn example(dev: &Device) {
415///     dev_info!(dev, "hello {}\n", "there");
416/// }
417/// ```
418#[macro_export]
419macro_rules! dev_info {
420    ($($f:tt)*) => { $crate::dev_printk!(pr_info, $($f)*); }
421}
422
423/// Prints a debug-level message (level 7) prefixed with device information.
424///
425/// This level should be used for debug messages.
426///
427/// Equivalent to the kernel's `dev_dbg` macro, except that it doesn't support dynamic debug yet.
428///
429/// Mimics the interface of [`std::print!`]. More information about the syntax is available from
430/// [`core::fmt`] and `alloc::format!`.
431///
432/// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
433///
434/// # Examples
435///
436/// ```
437/// # use kernel::device::Device;
438///
439/// fn example(dev: &Device) {
440///     dev_dbg!(dev, "hello {}\n", "there");
441/// }
442/// ```
443#[macro_export]
444macro_rules! dev_dbg {
445    ($($f:tt)*) => { $crate::dev_printk!(pr_dbg, $($f)*); }
446}