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