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