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, 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(Opaque<bindings::device>);
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`.
get_device(ptr: *mut bindings::device) -> ARef<Self>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 *`.
as_raw(&self) -> *mut bindings::device64     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.
as_ref<'a>(ptr: *mut bindings::device) -> &'a Self76     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
pr_emerg(&self, args: fmt::Arguments<'_>)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
pr_alert(&self, args: fmt::Arguments<'_>)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
pr_crit(&self, args: fmt::Arguments<'_>)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
pr_err(&self, args: fmt::Arguments<'_>)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
pr_warn(&self, args: fmt::Arguments<'_>)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
pr_notice(&self, args: fmt::Arguments<'_>)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
pr_info(&self, args: fmt::Arguments<'_>)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
pr_dbg(&self, args: fmt::Arguments<'_>)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))]
printk(&self, klevel: &[u8], msg: fmt::Arguments<'_>)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.
property_present(&self, name: &CStr) -> bool186     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.
193 unsafe impl crate::types::AlwaysRefCounted for Device {
inc_ref(&self)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 
dec_ref(obj: ptr::NonNull<Self>)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.
206 unsafe 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`.
210 unsafe impl Sync for Device {}
211 
212 #[doc(hidden)]
213 #[macro_export]
214 macro_rules! dev_printk {
215     ($method:ident, $dev:expr, $($f:tt)*) => {
216         {
217             ($dev).$method(core::format_args!($($f)*));
218         }
219     }
220 }
221 
222 /// Prints an emergency-level message (level 0) prefixed with device information.
223 ///
224 /// This level should be used if the system is unusable.
225 ///
226 /// Equivalent to the kernel's `dev_emerg` macro.
227 ///
228 /// Mimics the interface of [`std::print!`]. More information about the syntax is available from
229 /// [`core::fmt`] and `alloc::format!`.
230 ///
231 /// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
232 ///
233 /// # Examples
234 ///
235 /// ```
236 /// # use kernel::device::Device;
237 ///
238 /// fn example(dev: &Device) {
239 ///     dev_emerg!(dev, "hello {}\n", "there");
240 /// }
241 /// ```
242 #[macro_export]
243 macro_rules! dev_emerg {
244     ($($f:tt)*) => { $crate::dev_printk!(pr_emerg, $($f)*); }
245 }
246 
247 /// Prints an alert-level message (level 1) prefixed with device information.
248 ///
249 /// This level should be used if action must be taken immediately.
250 ///
251 /// Equivalent to the kernel's `dev_alert` macro.
252 ///
253 /// Mimics the interface of [`std::print!`]. More information about the syntax is available from
254 /// [`core::fmt`] and `alloc::format!`.
255 ///
256 /// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
257 ///
258 /// # Examples
259 ///
260 /// ```
261 /// # use kernel::device::Device;
262 ///
263 /// fn example(dev: &Device) {
264 ///     dev_alert!(dev, "hello {}\n", "there");
265 /// }
266 /// ```
267 #[macro_export]
268 macro_rules! dev_alert {
269     ($($f:tt)*) => { $crate::dev_printk!(pr_alert, $($f)*); }
270 }
271 
272 /// Prints a critical-level message (level 2) prefixed with device information.
273 ///
274 /// This level should be used in critical conditions.
275 ///
276 /// Equivalent to the kernel's `dev_crit` macro.
277 ///
278 /// Mimics the interface of [`std::print!`]. More information about the syntax is available from
279 /// [`core::fmt`] and `alloc::format!`.
280 ///
281 /// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
282 ///
283 /// # Examples
284 ///
285 /// ```
286 /// # use kernel::device::Device;
287 ///
288 /// fn example(dev: &Device) {
289 ///     dev_crit!(dev, "hello {}\n", "there");
290 /// }
291 /// ```
292 #[macro_export]
293 macro_rules! dev_crit {
294     ($($f:tt)*) => { $crate::dev_printk!(pr_crit, $($f)*); }
295 }
296 
297 /// Prints an error-level message (level 3) prefixed with device information.
298 ///
299 /// This level should be used in error conditions.
300 ///
301 /// Equivalent to the kernel's `dev_err` macro.
302 ///
303 /// Mimics the interface of [`std::print!`]. More information about the syntax is available from
304 /// [`core::fmt`] and `alloc::format!`.
305 ///
306 /// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
307 ///
308 /// # Examples
309 ///
310 /// ```
311 /// # use kernel::device::Device;
312 ///
313 /// fn example(dev: &Device) {
314 ///     dev_err!(dev, "hello {}\n", "there");
315 /// }
316 /// ```
317 #[macro_export]
318 macro_rules! dev_err {
319     ($($f:tt)*) => { $crate::dev_printk!(pr_err, $($f)*); }
320 }
321 
322 /// Prints a warning-level message (level 4) prefixed with device information.
323 ///
324 /// This level should be used in warning conditions.
325 ///
326 /// Equivalent to the kernel's `dev_warn` macro.
327 ///
328 /// Mimics the interface of [`std::print!`]. More information about the syntax is available from
329 /// [`core::fmt`] and `alloc::format!`.
330 ///
331 /// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
332 ///
333 /// # Examples
334 ///
335 /// ```
336 /// # use kernel::device::Device;
337 ///
338 /// fn example(dev: &Device) {
339 ///     dev_warn!(dev, "hello {}\n", "there");
340 /// }
341 /// ```
342 #[macro_export]
343 macro_rules! dev_warn {
344     ($($f:tt)*) => { $crate::dev_printk!(pr_warn, $($f)*); }
345 }
346 
347 /// Prints a notice-level message (level 5) prefixed with device information.
348 ///
349 /// This level should be used in normal but significant conditions.
350 ///
351 /// Equivalent to the kernel's `dev_notice` macro.
352 ///
353 /// Mimics the interface of [`std::print!`]. More information about the syntax is available from
354 /// [`core::fmt`] and `alloc::format!`.
355 ///
356 /// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
357 ///
358 /// # Examples
359 ///
360 /// ```
361 /// # use kernel::device::Device;
362 ///
363 /// fn example(dev: &Device) {
364 ///     dev_notice!(dev, "hello {}\n", "there");
365 /// }
366 /// ```
367 #[macro_export]
368 macro_rules! dev_notice {
369     ($($f:tt)*) => { $crate::dev_printk!(pr_notice, $($f)*); }
370 }
371 
372 /// Prints an info-level message (level 6) prefixed with device information.
373 ///
374 /// This level should be used for informational messages.
375 ///
376 /// Equivalent to the kernel's `dev_info` macro.
377 ///
378 /// Mimics the interface of [`std::print!`]. More information about the syntax is available from
379 /// [`core::fmt`] and `alloc::format!`.
380 ///
381 /// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
382 ///
383 /// # Examples
384 ///
385 /// ```
386 /// # use kernel::device::Device;
387 ///
388 /// fn example(dev: &Device) {
389 ///     dev_info!(dev, "hello {}\n", "there");
390 /// }
391 /// ```
392 #[macro_export]
393 macro_rules! dev_info {
394     ($($f:tt)*) => { $crate::dev_printk!(pr_info, $($f)*); }
395 }
396 
397 /// Prints a debug-level message (level 7) prefixed with device information.
398 ///
399 /// This level should be used for debug messages.
400 ///
401 /// Equivalent to the kernel's `dev_dbg` macro, except that it doesn't support dynamic debug yet.
402 ///
403 /// Mimics the interface of [`std::print!`]. More information about the syntax is available from
404 /// [`core::fmt`] and `alloc::format!`.
405 ///
406 /// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
407 ///
408 /// # Examples
409 ///
410 /// ```
411 /// # use kernel::device::Device;
412 ///
413 /// fn example(dev: &Device) {
414 ///     dev_dbg!(dev, "hello {}\n", "there");
415 /// }
416 /// ```
417 #[macro_export]
418 macro_rules! dev_dbg {
419     ($($f:tt)*) => { $crate::dev_printk!(pr_dbg, $($f)*); }
420 }
421