1 // SPDX-License-Identifier: GPL-2.0 2 3 //! The `kernel` crate. 4 //! 5 //! This crate contains the kernel APIs that have been ported or wrapped for 6 //! usage by Rust code in the kernel and is shared by all of them. 7 //! 8 //! In other words, all the rest of the Rust code in the kernel (e.g. kernel 9 //! modules written in Rust) depends on [`core`] and this crate. 10 //! 11 //! If you need a kernel C API that is not ported or wrapped yet here, then 12 //! do so first instead of bypassing this crate. 13 14 #![no_std] 15 // 16 // Please see https://github.com/Rust-for-Linux/linux/issues/2 for details on 17 // the unstable features in use. 18 // 19 // Stable since Rust 1.87.0. 20 #![feature(unsigned_is_multiple_of)] 21 // 22 // Stable since Rust 1.89.0. 23 #![feature(generic_arg_infer)] 24 // 25 // Expected to become stable. 26 #![feature(arbitrary_self_types)] 27 #![feature(derive_coerce_pointee)] 28 // 29 // To be determined. 30 #![feature(used_with_arg)] 31 // 32 // `feature(file_with_nul)` is stable since Rust 1.92.0. Before Rust 1.89.0, it did not exist, so 33 // enable it conditionally. 34 #![cfg_attr(CONFIG_RUSTC_HAS_FILE_WITH_NUL, feature(file_with_nul))] 35 36 // Ensure conditional compilation based on the kernel configuration works; 37 // otherwise we may silently break things like initcall handling. 38 #[cfg(not(CONFIG_RUST))] 39 compile_error!("Missing kernel configuration for conditional compilation"); 40 41 // Allow proc-macros to refer to `::kernel` inside the `kernel` crate (this crate). 42 extern crate self as kernel; 43 44 pub use ffi; 45 46 pub mod acpi; 47 pub mod alloc; 48 #[cfg(CONFIG_AUXILIARY_BUS)] 49 pub mod auxiliary; 50 pub mod bitfield; 51 pub mod bitmap; 52 pub mod bits; 53 #[cfg(CONFIG_BLOCK)] 54 pub mod block; 55 pub mod bug; 56 pub mod build_assert; 57 pub mod clk; 58 #[cfg(CONFIG_CONFIGFS_FS)] 59 pub mod configfs; 60 pub mod cpu; 61 #[cfg(CONFIG_CPU_FREQ)] 62 pub mod cpufreq; 63 pub mod cpumask; 64 pub mod cred; 65 pub mod debugfs; 66 pub mod device; 67 pub mod device_id; 68 pub mod devres; 69 pub mod dma; 70 pub mod driver; 71 #[cfg(CONFIG_DRM = "y")] 72 pub mod drm; 73 pub mod error; 74 pub mod faux; 75 #[cfg(CONFIG_RUST_FW_LOADER_ABSTRACTIONS)] 76 pub mod firmware; 77 pub mod fmt; 78 pub mod fs; 79 #[cfg(CONFIG_RUST_FWCTL_ABSTRACTIONS)] 80 pub mod fwctl; 81 #[cfg(CONFIG_GPU_BUDDY = "y")] 82 pub mod gpu; 83 #[cfg(CONFIG_I2C = "y")] 84 pub mod i2c; 85 pub mod id_pool; 86 #[doc(hidden)] 87 pub mod impl_flags; 88 pub mod init; 89 pub mod interop; 90 pub mod interrupt; 91 pub mod io; 92 pub mod ioctl; 93 pub mod iommu; 94 pub mod iov; 95 pub mod irq; 96 pub mod jump_label; 97 #[cfg(CONFIG_KUNIT)] 98 pub mod kunit; 99 pub mod list; 100 pub mod maple_tree; 101 pub mod mem; 102 pub mod miscdevice; 103 pub mod mm; 104 pub mod module; 105 pub mod module_param; 106 #[cfg(CONFIG_NET)] 107 pub mod net; 108 pub mod num; 109 pub mod of; 110 #[cfg(CONFIG_PM_OPP)] 111 pub mod opp; 112 pub mod page; 113 #[cfg(CONFIG_PCI)] 114 pub mod pci; 115 pub mod pid_namespace; 116 pub mod platform; 117 pub mod prelude; 118 pub mod print; 119 pub mod processor; 120 pub mod ptr; 121 #[cfg(CONFIG_RUST_PWM_ABSTRACTIONS)] 122 pub mod pwm; 123 pub mod ratelimit; 124 pub mod rbtree; 125 pub mod regulator; 126 pub mod revocable; 127 pub mod safety; 128 pub mod scatterlist; 129 pub mod security; 130 pub mod seq_file; 131 #[cfg(CONFIG_RUST_SERIAL_DEV_BUS_ABSTRACTIONS)] 132 pub mod serdev; 133 pub mod sizes; 134 #[cfg(CONFIG_SOC_BUS)] 135 pub mod soc; 136 #[doc(hidden)] 137 pub mod std_vendor; 138 pub mod str; 139 pub mod sync; 140 pub mod task; 141 pub mod time; 142 pub mod tracepoint; 143 pub mod transmute; 144 pub mod types; 145 pub mod uaccess; 146 #[cfg(CONFIG_USB = "y")] 147 pub mod usb; 148 pub mod workqueue; 149 pub mod xarray; 150 151 #[doc(hidden)] 152 pub use bindings; 153 pub use macros; 154 pub use module::{ 155 InPlaceModule, 156 Module, 157 ModuleMetadata, 158 ThisModule, // 159 }; 160 pub use uapi; 161 162 /// Prefix to appear before log messages printed from within the `kernel` crate. 163 const __LOG_PREFIX: &[u8] = b"rust_kernel\0"; 164 165 /// Dummy module type for `#[vtable]` `impl` blocks within the `kernel` crate (e.g. KUnit tests). 166 // The `allow` is needed since it may be unused (e.g. KUnit tests may be disabled). 167 #[allow(dead_code)] 168 struct LocalModule; 169 170 impl ModuleMetadata for LocalModule { 171 const NAME: &'static str::CStr = c"rust_kernel"; 172 173 const THIS_MODULE: ThisModule = { 174 // SAFETY: `try_module_get`/`module_put` handle null module pointers gracefully. 175 unsafe { ThisModule::from_ptr(core::ptr::null_mut()) } 176 }; 177 } 178 179 #[cfg(not(testlib))] 180 #[panic_handler] 181 fn panic(info: &core::panic::PanicInfo<'_>) -> ! { 182 pr_emerg!("{}\n", info); 183 // SAFETY: FFI call. 184 unsafe { bindings::BUG() }; 185 } 186 187 /// Produces a pointer to an object from a pointer to one of its fields. 188 /// 189 /// If you encounter a type mismatch due to the [`Opaque`] type, then use [`Opaque::cast_into`] or 190 /// [`Opaque::cast_from`] to resolve the mismatch. 191 /// 192 /// [`Opaque`]: crate::types::Opaque 193 /// [`Opaque::cast_into`]: crate::types::Opaque::cast_into 194 /// [`Opaque::cast_from`]: crate::types::Opaque::cast_from 195 /// 196 /// # Safety 197 /// 198 /// The pointer passed to this macro, and the pointer returned by this macro, must both be in 199 /// bounds of the same allocation. 200 /// 201 /// # Examples 202 /// 203 /// ``` 204 /// # use kernel::container_of; 205 /// struct Test { 206 /// a: u64, 207 /// b: u32, 208 /// } 209 /// 210 /// let test = Test { a: 10, b: 20 }; 211 /// let b_ptr: *const _ = &test.b; 212 /// // SAFETY: The pointer points at the `b` field of a `Test`, so the resulting pointer will be 213 /// // in-bounds of the same allocation as `b_ptr`. 214 /// let test_alias = unsafe { container_of!(b_ptr, Test, b) }; 215 /// assert!(core::ptr::eq(&test, test_alias)); 216 /// ``` 217 #[macro_export] 218 macro_rules! container_of { 219 ($field_ptr:expr, $Container:ty, $($fields:tt)*) => {{ 220 let offset: usize = ::core::mem::offset_of!($Container, $($fields)*); 221 let field_ptr = $field_ptr; 222 let container_ptr = field_ptr.byte_sub(offset).cast::<$Container>(); 223 $crate::assert_same_type(field_ptr, (&raw const (*container_ptr).$($fields)*).cast_mut()); 224 container_ptr 225 }} 226 } 227 228 /// Helper for [`container_of!`]. 229 #[doc(hidden)] 230 pub fn assert_same_type<T>(_: T, _: T) {} 231 232 /// Helper for `.rs.S` files. 233 #[doc(hidden)] 234 #[macro_export] 235 macro_rules! concat_literals { 236 ($( $asm:literal )* ) => { 237 ::core::concat!($($asm),*) 238 }; 239 } 240 241 /// Wrapper around `asm!` configured for use in the kernel. 242 /// 243 /// Uses a semicolon to avoid parsing ambiguities, even though this does not match native `asm!` 244 /// syntax. 245 // For x86, `asm!` uses intel syntax by default, but we want to use at&t syntax in the kernel. 246 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] 247 #[macro_export] 248 macro_rules! asm { 249 ($($asm:expr),* ; $($rest:tt)*) => { 250 ::core::arch::asm!( $($asm)*, options(att_syntax), $($rest)* ) 251 }; 252 } 253 254 /// Wrapper around `asm!` configured for use in the kernel. 255 /// 256 /// Uses a semicolon to avoid parsing ambiguities, even though this does not match native `asm!` 257 /// syntax. 258 // For non-x86 arches we just pass through to `asm!`. 259 #[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))] 260 #[macro_export] 261 macro_rules! asm { 262 ($($asm:expr),* ; $($rest:tt)*) => { 263 ::core::arch::asm!( $($asm)*, $($rest)* ) 264 }; 265 } 266 267 /// Gets the C string file name of a [`Location`]. 268 /// 269 /// If `Location::file_as_c_str()` is not available, returns a string that warns about it. 270 /// 271 /// [`Location`]: core::panic::Location 272 /// 273 /// # Examples 274 /// 275 /// ``` 276 /// # use kernel::file_from_location; 277 /// 278 /// #[track_caller] 279 /// fn foo() { 280 /// let caller = core::panic::Location::caller(); 281 /// 282 /// // Output: 283 /// // - A path like "rust/kernel/example.rs" if `file_as_c_str()` is available. 284 /// // - "<Location::file_as_c_str() not supported>" otherwise. 285 /// let caller_file = file_from_location(caller); 286 /// 287 /// // Prints out the message with caller's file name. 288 /// pr_info!("foo() called in file {caller_file:?}\n"); 289 /// 290 /// # if cfg!(CONFIG_RUSTC_HAS_FILE_WITH_NUL) { 291 /// # assert_eq!(Ok(caller.file()), caller_file.to_str()); 292 /// # } 293 /// } 294 /// 295 /// # foo(); 296 /// ``` 297 #[inline] 298 pub fn file_from_location<'a>(loc: &'a core::panic::Location<'a>) -> &'a core::ffi::CStr { 299 #[cfg(CONFIG_RUSTC_HAS_FILE_AS_C_STR)] 300 { 301 loc.file_as_c_str() 302 } 303 304 #[cfg(all(CONFIG_RUSTC_HAS_FILE_WITH_NUL, not(CONFIG_RUSTC_HAS_FILE_AS_C_STR)))] 305 { 306 loc.file_with_nul() 307 } 308 309 #[cfg(not(CONFIG_RUSTC_HAS_FILE_WITH_NUL))] 310 { 311 let _ = loc; 312 c"<Location::file_as_c_str() not supported>" 313 } 314 } 315