1 // SPDX-License-Identifier: GPL-2.0
3 //! Generic devices that are part of the kernel's driver model.
5 //! C header: [`include/linux/device.h`](srctree/include/linux/device.h)
16 /// A reference-counted device.
18 /// This structure represents the Rust abstraction for a C `struct device`. This implementation
19 /// abstracts the usage of an already existing C `struct device` within Rust code that we get
20 /// passed from the C side.
22 /// An instance of this abstraction can be obtained temporarily or permanent.
24 /// A temporary one is bound to the lifetime of the C `struct device` pointer used for creation.
25 /// A permanent instance is always reference-counted and hence not restricted by any lifetime
28 /// For subsystems it is recommended to create a permanent instance to wrap into a subsystem
29 /// specific device structure (e.g. `pci::Device`). This is useful for passing it to drivers in
30 /// `T::probe()`, such that a driver can store the `ARef<Device>` (equivalent to storing a
31 /// `struct device` pointer in a C driver) for arbitrary purposes, e.g. allocating DMA coherent
36 /// A `Device` instance represents a valid `struct device` created by the C portion of the kernel.
38 /// Instances of this type are always reference-counted, that is, a call to `get_device` ensures
39 /// that the allocation remains valid at least until the matching call to `put_device`.
41 /// `bindings::device::release` is valid to be called from any thread, hence `ARef<Device>` can be
42 /// dropped from any thread.
44 pub struct Device(Opaque<bindings::device>);
47 /// Creates a new reference-counted abstraction instance of an existing `struct device` pointer.
51 /// Callers must ensure that `ptr` is valid, non-null, and has a non-zero reference count,
52 /// i.e. it must be ensured that the reference count of the C `struct device` `ptr` points to
53 /// can't drop to zero, for the duration of this function call.
55 /// It must also be ensured that `bindings::device::release` can be called from any thread.
56 /// While not officially documented, this should be the case for any `struct device`.
57 pub unsafe fn get_device(ptr: *mut bindings::device) -> ARef<Self> {
58 // SAFETY: By the safety requirements ptr is valid
59 unsafe { Self::as_ref(ptr) }.into()
62 /// Obtain the raw `struct device *`.
63 pub(crate) fn as_raw(&self) -> *mut bindings::device {
67 /// Convert a raw C `struct device` pointer to a `&'a Device`.
71 /// Callers must ensure that `ptr` is valid, non-null, and has a non-zero reference count,
72 /// i.e. it must be ensured that the reference count of the C `struct device` `ptr` points to
73 /// can't drop to zero, for the duration of this function call and the entire duration when the
74 /// returned reference exists.
75 pub unsafe fn as_ref<'a>(ptr: *mut bindings::device) -> &'a Self {
76 // SAFETY: Guaranteed by the safety requirements of the function.
77 unsafe { &*ptr.cast() }
80 /// Prints an emergency-level message (level 0) prefixed with device information.
82 /// More details are available from [`dev_emerg`].
84 /// [`dev_emerg`]: crate::dev_emerg
85 pub fn pr_emerg(&self, args: fmt::Arguments<'_>) {
86 // SAFETY: `klevel` is null-terminated, uses one of the kernel constants.
87 unsafe { self.printk(bindings::KERN_EMERG, args) };
90 /// Prints an alert-level message (level 1) prefixed with device information.
92 /// More details are available from [`dev_alert`].
94 /// [`dev_alert`]: crate::dev_alert
95 pub fn pr_alert(&self, args: fmt::Arguments<'_>) {
96 // SAFETY: `klevel` is null-terminated, uses one of the kernel constants.
97 unsafe { self.printk(bindings::KERN_ALERT, args) };
100 /// Prints a critical-level message (level 2) prefixed with device information.
102 /// More details are available from [`dev_crit`].
104 /// [`dev_crit`]: crate::dev_crit
105 pub fn pr_crit(&self, args: fmt::Arguments<'_>) {
106 // SAFETY: `klevel` is null-terminated, uses one of the kernel constants.
107 unsafe { self.printk(bindings::KERN_CRIT, args) };
110 /// Prints an error-level message (level 3) prefixed with device information.
112 /// More details are available from [`dev_err`].
114 /// [`dev_err`]: crate::dev_err
115 pub fn pr_err(&self, args: fmt::Arguments<'_>) {
116 // SAFETY: `klevel` is null-terminated, uses one of the kernel constants.
117 unsafe { self.printk(bindings::KERN_ERR, args) };
120 /// Prints a warning-level message (level 4) prefixed with device information.
122 /// More details are available from [`dev_warn`].
124 /// [`dev_warn`]: crate::dev_warn
125 pub fn pr_warn(&self, args: fmt::Arguments<'_>) {
126 // SAFETY: `klevel` is null-terminated, uses one of the kernel constants.
127 unsafe { self.printk(bindings::KERN_WARNING, args) };
130 /// Prints a notice-level message (level 5) prefixed with device information.
132 /// More details are available from [`dev_notice`].
134 /// [`dev_notice`]: crate::dev_notice
135 pub fn pr_notice(&self, args: fmt::Arguments<'_>) {
136 // SAFETY: `klevel` is null-terminated, uses one of the kernel constants.
137 unsafe { self.printk(bindings::KERN_NOTICE, args) };
140 /// Prints an info-level message (level 6) prefixed with device information.
142 /// More details are available from [`dev_info`].
144 /// [`dev_info`]: crate::dev_info
145 pub fn pr_info(&self, args: fmt::Arguments<'_>) {
146 // SAFETY: `klevel` is null-terminated, uses one of the kernel constants.
147 unsafe { self.printk(bindings::KERN_INFO, args) };
150 /// Prints a debug-level message (level 7) prefixed with device information.
152 /// More details are available from [`dev_dbg`].
154 /// [`dev_dbg`]: crate::dev_dbg
155 pub fn pr_dbg(&self, args: fmt::Arguments<'_>) {
156 if cfg!(debug_assertions) {
157 // SAFETY: `klevel` is null-terminated, uses one of the kernel constants.
158 unsafe { self.printk(bindings::KERN_DEBUG, args) };
162 /// Prints the provided message to the console.
166 /// Callers must ensure that `klevel` is null-terminated; in particular, one of the
167 /// `KERN_*`constants, for example, `KERN_CRIT`, `KERN_ALERT`, etc.
168 #[cfg_attr(not(CONFIG_PRINTK), allow(unused_variables))]
169 unsafe fn printk(&self, klevel: &[u8], msg: fmt::Arguments<'_>) {
170 // SAFETY: `klevel` is null-terminated and one of the kernel constants. `self.as_raw`
171 // is valid because `self` is valid. The "%pA" format string expects a pointer to
172 // `fmt::Arguments`, which is what we're passing as the last argument.
173 #[cfg(CONFIG_PRINTK)]
175 bindings::_dev_printk(
176 klevel as *const _ as *const core::ffi::c_char,
178 c_str!("%pA").as_char_ptr(),
179 &msg as *const _ as *const core::ffi::c_void,
185 // SAFETY: Instances of `Device` are always reference-counted.
186 unsafe impl crate::types::AlwaysRefCounted for Device {
188 // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
189 unsafe { bindings::get_device(self.as_raw()) };
192 unsafe fn dec_ref(obj: ptr::NonNull<Self>) {
193 // SAFETY: The safety requirements guarantee that the refcount is non-zero.
194 unsafe { bindings::put_device(obj.cast().as_ptr()) }
198 // SAFETY: As by the type invariant `Device` can be sent to any thread.
199 unsafe impl Send for Device {}
201 // SAFETY: `Device` can be shared among threads because all immutable methods are protected by the
202 // synchronization in `struct device`.
203 unsafe impl Sync for Device {}
207 macro_rules! dev_printk {
208 ($method:ident, $dev:expr, $($f:tt)*) => {
210 ($dev).$method(core::format_args!($($f)*));
215 /// Prints an emergency-level message (level 0) prefixed with device information.
217 /// This level should be used if the system is unusable.
219 /// Equivalent to the kernel's `dev_emerg` macro.
221 /// Mimics the interface of [`std::print!`]. More information about the syntax is available from
222 /// [`core::fmt`] and `alloc::format!`.
224 /// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
229 /// # use kernel::device::Device;
231 /// fn example(dev: &Device) {
232 /// dev_emerg!(dev, "hello {}\n", "there");
236 macro_rules! dev_emerg {
237 ($($f:tt)*) => { $crate::dev_printk!(pr_emerg, $($f)*); }
240 /// Prints an alert-level message (level 1) prefixed with device information.
242 /// This level should be used if action must be taken immediately.
244 /// Equivalent to the kernel's `dev_alert` macro.
246 /// Mimics the interface of [`std::print!`]. More information about the syntax is available from
247 /// [`core::fmt`] and `alloc::format!`.
249 /// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
254 /// # use kernel::device::Device;
256 /// fn example(dev: &Device) {
257 /// dev_alert!(dev, "hello {}\n", "there");
261 macro_rules! dev_alert {
262 ($($f:tt)*) => { $crate::dev_printk!(pr_alert, $($f)*); }
265 /// Prints a critical-level message (level 2) prefixed with device information.
267 /// This level should be used in critical conditions.
269 /// Equivalent to the kernel's `dev_crit` macro.
271 /// Mimics the interface of [`std::print!`]. More information about the syntax is available from
272 /// [`core::fmt`] and `alloc::format!`.
274 /// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
279 /// # use kernel::device::Device;
281 /// fn example(dev: &Device) {
282 /// dev_crit!(dev, "hello {}\n", "there");
286 macro_rules! dev_crit {
287 ($($f:tt)*) => { $crate::dev_printk!(pr_crit, $($f)*); }
290 /// Prints an error-level message (level 3) prefixed with device information.
292 /// This level should be used in error conditions.
294 /// Equivalent to the kernel's `dev_err` macro.
296 /// Mimics the interface of [`std::print!`]. More information about the syntax is available from
297 /// [`core::fmt`] and `alloc::format!`.
299 /// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
304 /// # use kernel::device::Device;
306 /// fn example(dev: &Device) {
307 /// dev_err!(dev, "hello {}\n", "there");
311 macro_rules! dev_err {
312 ($($f:tt)*) => { $crate::dev_printk!(pr_err, $($f)*); }
315 /// Prints a warning-level message (level 4) prefixed with device information.
317 /// This level should be used in warning conditions.
319 /// Equivalent to the kernel's `dev_warn` macro.
321 /// Mimics the interface of [`std::print!`]. More information about the syntax is available from
322 /// [`core::fmt`] and `alloc::format!`.
324 /// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
329 /// # use kernel::device::Device;
331 /// fn example(dev: &Device) {
332 /// dev_warn!(dev, "hello {}\n", "there");
336 macro_rules! dev_warn {
337 ($($f:tt)*) => { $crate::dev_printk!(pr_warn, $($f)*); }
340 /// Prints a notice-level message (level 5) prefixed with device information.
342 /// This level should be used in normal but significant conditions.
344 /// Equivalent to the kernel's `dev_notice` macro.
346 /// Mimics the interface of [`std::print!`]. More information about the syntax is available from
347 /// [`core::fmt`] and `alloc::format!`.
349 /// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
354 /// # use kernel::device::Device;
356 /// fn example(dev: &Device) {
357 /// dev_notice!(dev, "hello {}\n", "there");
361 macro_rules! dev_notice {
362 ($($f:tt)*) => { $crate::dev_printk!(pr_notice, $($f)*); }
365 /// Prints an info-level message (level 6) prefixed with device information.
367 /// This level should be used for informational messages.
369 /// Equivalent to the kernel's `dev_info` macro.
371 /// Mimics the interface of [`std::print!`]. More information about the syntax is available from
372 /// [`core::fmt`] and `alloc::format!`.
374 /// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
379 /// # use kernel::device::Device;
381 /// fn example(dev: &Device) {
382 /// dev_info!(dev, "hello {}\n", "there");
386 macro_rules! dev_info {
387 ($($f:tt)*) => { $crate::dev_printk!(pr_info, $($f)*); }
390 /// Prints a debug-level message (level 7) prefixed with device information.
392 /// This level should be used for debug messages.
394 /// Equivalent to the kernel's `dev_dbg` macro, except that it doesn't support dynamic debug yet.
396 /// Mimics the interface of [`std::print!`]. More information about the syntax is available from
397 /// [`core::fmt`] and `alloc::format!`.
399 /// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
404 /// # use kernel::device::Device;
406 /// fn example(dev: &Device) {
407 /// dev_dbg!(dev, "hello {}\n", "there");
411 macro_rules! dev_dbg {
412 ($($f:tt)*) => { $crate::dev_printk!(pr_dbg, $($f)*); }