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`. 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. 193 unsafe 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. 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 /// 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. 218 pub 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. 222 pub 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()`. 226 pub struct Core; 227 228 mod private { 229 pub trait Sealed {} 230 231 impl Sealed for super::Core {} 232 impl Sealed for super::Normal {} 233 } 234 235 impl DeviceContext for Core {} 236 impl DeviceContext for Normal {} 237 238 #[doc(hidden)] 239 #[macro_export] 240 macro_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 [`std::format!`]. 256 /// 257 /// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html 258 /// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html 259 /// 260 /// # Examples 261 /// 262 /// ``` 263 /// # use kernel::device::Device; 264 /// 265 /// fn example(dev: &Device) { 266 /// dev_emerg!(dev, "hello {}\n", "there"); 267 /// } 268 /// ``` 269 #[macro_export] 270 macro_rules! dev_emerg { 271 ($($f:tt)*) => { $crate::dev_printk!(pr_emerg, $($f)*); } 272 } 273 274 /// Prints an alert-level message (level 1) prefixed with device information. 275 /// 276 /// This level should be used if action must be taken immediately. 277 /// 278 /// Equivalent to the kernel's `dev_alert` macro. 279 /// 280 /// Mimics the interface of [`std::print!`]. More information about the syntax is available from 281 /// [`core::fmt`] and [`std::format!`]. 282 /// 283 /// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html 284 /// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html 285 /// 286 /// # Examples 287 /// 288 /// ``` 289 /// # use kernel::device::Device; 290 /// 291 /// fn example(dev: &Device) { 292 /// dev_alert!(dev, "hello {}\n", "there"); 293 /// } 294 /// ``` 295 #[macro_export] 296 macro_rules! dev_alert { 297 ($($f:tt)*) => { $crate::dev_printk!(pr_alert, $($f)*); } 298 } 299 300 /// Prints a critical-level message (level 2) prefixed with device information. 301 /// 302 /// This level should be used in critical conditions. 303 /// 304 /// Equivalent to the kernel's `dev_crit` macro. 305 /// 306 /// Mimics the interface of [`std::print!`]. More information about the syntax is available from 307 /// [`core::fmt`] and [`std::format!`]. 308 /// 309 /// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html 310 /// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html 311 /// 312 /// # Examples 313 /// 314 /// ``` 315 /// # use kernel::device::Device; 316 /// 317 /// fn example(dev: &Device) { 318 /// dev_crit!(dev, "hello {}\n", "there"); 319 /// } 320 /// ``` 321 #[macro_export] 322 macro_rules! dev_crit { 323 ($($f:tt)*) => { $crate::dev_printk!(pr_crit, $($f)*); } 324 } 325 326 /// Prints an error-level message (level 3) prefixed with device information. 327 /// 328 /// This level should be used in error conditions. 329 /// 330 /// Equivalent to the kernel's `dev_err` macro. 331 /// 332 /// Mimics the interface of [`std::print!`]. More information about the syntax is available from 333 /// [`core::fmt`] and [`std::format!`]. 334 /// 335 /// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html 336 /// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html 337 /// 338 /// # Examples 339 /// 340 /// ``` 341 /// # use kernel::device::Device; 342 /// 343 /// fn example(dev: &Device) { 344 /// dev_err!(dev, "hello {}\n", "there"); 345 /// } 346 /// ``` 347 #[macro_export] 348 macro_rules! dev_err { 349 ($($f:tt)*) => { $crate::dev_printk!(pr_err, $($f)*); } 350 } 351 352 /// Prints a warning-level message (level 4) prefixed with device information. 353 /// 354 /// This level should be used in warning conditions. 355 /// 356 /// Equivalent to the kernel's `dev_warn` macro. 357 /// 358 /// Mimics the interface of [`std::print!`]. More information about the syntax is available from 359 /// [`core::fmt`] and [`std::format!`]. 360 /// 361 /// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html 362 /// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html 363 /// 364 /// # Examples 365 /// 366 /// ``` 367 /// # use kernel::device::Device; 368 /// 369 /// fn example(dev: &Device) { 370 /// dev_warn!(dev, "hello {}\n", "there"); 371 /// } 372 /// ``` 373 #[macro_export] 374 macro_rules! dev_warn { 375 ($($f:tt)*) => { $crate::dev_printk!(pr_warn, $($f)*); } 376 } 377 378 /// Prints a notice-level message (level 5) prefixed with device information. 379 /// 380 /// This level should be used in normal but significant conditions. 381 /// 382 /// Equivalent to the kernel's `dev_notice` macro. 383 /// 384 /// Mimics the interface of [`std::print!`]. More information about the syntax is available from 385 /// [`core::fmt`] and [`std::format!`]. 386 /// 387 /// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html 388 /// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html 389 /// 390 /// # Examples 391 /// 392 /// ``` 393 /// # use kernel::device::Device; 394 /// 395 /// fn example(dev: &Device) { 396 /// dev_notice!(dev, "hello {}\n", "there"); 397 /// } 398 /// ``` 399 #[macro_export] 400 macro_rules! dev_notice { 401 ($($f:tt)*) => { $crate::dev_printk!(pr_notice, $($f)*); } 402 } 403 404 /// Prints an info-level message (level 6) prefixed with device information. 405 /// 406 /// This level should be used for informational messages. 407 /// 408 /// Equivalent to the kernel's `dev_info` macro. 409 /// 410 /// Mimics the interface of [`std::print!`]. More information about the syntax is available from 411 /// [`core::fmt`] and [`std::format!`]. 412 /// 413 /// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html 414 /// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html 415 /// 416 /// # Examples 417 /// 418 /// ``` 419 /// # use kernel::device::Device; 420 /// 421 /// fn example(dev: &Device) { 422 /// dev_info!(dev, "hello {}\n", "there"); 423 /// } 424 /// ``` 425 #[macro_export] 426 macro_rules! dev_info { 427 ($($f:tt)*) => { $crate::dev_printk!(pr_info, $($f)*); } 428 } 429 430 /// Prints a debug-level message (level 7) prefixed with device information. 431 /// 432 /// This level should be used for debug messages. 433 /// 434 /// Equivalent to the kernel's `dev_dbg` macro, except that it doesn't support dynamic debug yet. 435 /// 436 /// Mimics the interface of [`std::print!`]. More information about the syntax is available from 437 /// [`core::fmt`] and [`std::format!`]. 438 /// 439 /// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html 440 /// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html 441 /// 442 /// # Examples 443 /// 444 /// ``` 445 /// # use kernel::device::Device; 446 /// 447 /// fn example(dev: &Device) { 448 /// dev_dbg!(dev, "hello {}\n", "there"); 449 /// } 450 /// ``` 451 #[macro_export] 452 macro_rules! dev_dbg { 453 ($($f:tt)*) => { $crate::dev_printk!(pr_dbg, $($f)*); } 454 } 455