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.79.0. 20 #![feature(generic_nonzero)] 21 #![feature(inline_const)] 22 #![feature(pointer_is_aligned)] 23 // 24 // Stable since Rust 1.80.0. 25 #![feature(slice_flatten)] 26 // 27 // Stable since Rust 1.81.0. 28 #![feature(lint_reasons)] 29 // 30 // Stable since Rust 1.82.0. 31 #![feature(raw_ref_op)] 32 // 33 // Stable since Rust 1.83.0. 34 #![feature(const_maybe_uninit_as_mut_ptr)] 35 #![feature(const_mut_refs)] 36 #![feature(const_option)] 37 #![feature(const_ptr_write)] 38 #![feature(const_refs_to_cell)] 39 // 40 // Expected to become stable. 41 #![feature(arbitrary_self_types)] 42 // 43 // To be determined. 44 #![feature(used_with_arg)] 45 // 46 // `feature(derive_coerce_pointee)` is expected to become stable. Before Rust 47 // 1.84.0, it did not exist, so enable the predecessor features. 48 #![cfg_attr(CONFIG_RUSTC_HAS_COERCE_POINTEE, feature(derive_coerce_pointee))] 49 #![cfg_attr(not(CONFIG_RUSTC_HAS_COERCE_POINTEE), feature(coerce_unsized))] 50 #![cfg_attr(not(CONFIG_RUSTC_HAS_COERCE_POINTEE), feature(dispatch_from_dyn))] 51 #![cfg_attr(not(CONFIG_RUSTC_HAS_COERCE_POINTEE), feature(unsize))] 52 // 53 // `feature(file_with_nul)` is expected to become stable. Before Rust 1.89.0, it did not exist, so 54 // enable it conditionally. 55 #![cfg_attr(CONFIG_RUSTC_HAS_FILE_WITH_NUL, feature(file_with_nul))] 56 57 // Ensure conditional compilation based on the kernel configuration works; 58 // otherwise we may silently break things like initcall handling. 59 #[cfg(not(CONFIG_RUST))] 60 compile_error!("Missing kernel configuration for conditional compilation"); 61 62 // Allow proc-macros to refer to `::kernel` inside the `kernel` crate (this crate). 63 extern crate self as kernel; 64 65 pub use ffi; 66 67 pub mod acpi; 68 pub mod alloc; 69 #[cfg(CONFIG_AUXILIARY_BUS)] 70 pub mod auxiliary; 71 pub mod bitmap; 72 pub mod bits; 73 #[cfg(CONFIG_BLOCK)] 74 pub mod block; 75 pub mod bug; 76 #[doc(hidden)] 77 pub mod build_assert; 78 pub mod clk; 79 #[cfg(CONFIG_CONFIGFS_FS)] 80 pub mod configfs; 81 pub mod cpu; 82 #[cfg(CONFIG_CPU_FREQ)] 83 pub mod cpufreq; 84 pub mod cpumask; 85 pub mod cred; 86 pub mod debugfs; 87 pub mod device; 88 pub mod device_id; 89 pub mod devres; 90 pub mod dma; 91 pub mod driver; 92 #[cfg(CONFIG_DRM = "y")] 93 pub mod drm; 94 pub mod error; 95 pub mod faux; 96 #[cfg(CONFIG_RUST_FW_LOADER_ABSTRACTIONS)] 97 pub mod firmware; 98 pub mod fmt; 99 pub mod fs; 100 #[cfg(CONFIG_I2C = "y")] 101 pub mod i2c; 102 pub mod id_pool; 103 pub mod init; 104 pub mod io; 105 pub mod ioctl; 106 pub mod iov; 107 pub mod irq; 108 pub mod jump_label; 109 #[cfg(CONFIG_KUNIT)] 110 pub mod kunit; 111 pub mod list; 112 pub mod maple_tree; 113 pub mod miscdevice; 114 pub mod mm; 115 #[cfg(CONFIG_NET)] 116 pub mod net; 117 pub mod num; 118 pub mod of; 119 #[cfg(CONFIG_PM_OPP)] 120 pub mod opp; 121 pub mod page; 122 #[cfg(CONFIG_PCI)] 123 pub mod pci; 124 pub mod pid_namespace; 125 pub mod platform; 126 pub mod prelude; 127 pub mod print; 128 pub mod processor; 129 pub mod ptr; 130 #[cfg(CONFIG_RUST_PWM_ABSTRACTIONS)] 131 pub mod pwm; 132 pub mod rbtree; 133 pub mod regulator; 134 pub mod revocable; 135 pub mod scatterlist; 136 pub mod security; 137 pub mod seq_file; 138 pub mod sizes; 139 pub mod slice; 140 mod static_assert; 141 #[doc(hidden)] 142 pub mod std_vendor; 143 pub mod str; 144 pub mod sync; 145 pub mod task; 146 pub mod time; 147 pub mod tracepoint; 148 pub mod transmute; 149 pub mod types; 150 pub mod uaccess; 151 pub mod workqueue; 152 pub mod xarray; 153 154 #[doc(hidden)] 155 pub use bindings; 156 pub use macros; 157 pub use uapi; 158 159 /// Prefix to appear before log messages printed from within the `kernel` crate. 160 const __LOG_PREFIX: &[u8] = b"rust_kernel\0"; 161 162 /// The top level entrypoint to implementing a kernel module. 163 /// 164 /// For any teardown or cleanup operations, your type may implement [`Drop`]. 165 pub trait Module: Sized + Sync + Send { 166 /// Called at module initialization time. 167 /// 168 /// Use this method to perform whatever setup or registration your module 169 /// should do. 170 /// 171 /// Equivalent to the `module_init` macro in the C API. 172 fn init(module: &'static ThisModule) -> error::Result<Self>; 173 } 174 175 /// A module that is pinned and initialised in-place. 176 pub trait InPlaceModule: Sync + Send { 177 /// Creates an initialiser for the module. 178 /// 179 /// It is called when the module is loaded. 180 fn init(module: &'static ThisModule) -> impl pin_init::PinInit<Self, error::Error>; 181 } 182 183 impl<T: Module> InPlaceModule for T { 184 fn init(module: &'static ThisModule) -> impl pin_init::PinInit<Self, error::Error> { 185 let initer = move |slot: *mut Self| { 186 let m = <Self as Module>::init(module)?; 187 188 // SAFETY: `slot` is valid for write per the contract with `pin_init_from_closure`. 189 unsafe { slot.write(m) }; 190 Ok(()) 191 }; 192 193 // SAFETY: On success, `initer` always fully initialises an instance of `Self`. 194 unsafe { pin_init::pin_init_from_closure(initer) } 195 } 196 } 197 198 /// Metadata attached to a [`Module`] or [`InPlaceModule`]. 199 pub trait ModuleMetadata { 200 /// The name of the module as specified in the `module!` macro. 201 const NAME: &'static crate::str::CStr; 202 } 203 204 /// Equivalent to `THIS_MODULE` in the C API. 205 /// 206 /// C header: [`include/linux/init.h`](srctree/include/linux/init.h) 207 pub struct ThisModule(*mut bindings::module); 208 209 // SAFETY: `THIS_MODULE` may be used from all threads within a module. 210 unsafe impl Sync for ThisModule {} 211 212 impl ThisModule { 213 /// Creates a [`ThisModule`] given the `THIS_MODULE` pointer. 214 /// 215 /// # Safety 216 /// 217 /// The pointer must be equal to the right `THIS_MODULE`. 218 pub const unsafe fn from_ptr(ptr: *mut bindings::module) -> ThisModule { 219 ThisModule(ptr) 220 } 221 222 /// Access the raw pointer for this module. 223 /// 224 /// It is up to the user to use it correctly. 225 pub const fn as_ptr(&self) -> *mut bindings::module { 226 self.0 227 } 228 } 229 230 #[cfg(not(testlib))] 231 #[panic_handler] 232 fn panic(info: &core::panic::PanicInfo<'_>) -> ! { 233 pr_emerg!("{}\n", info); 234 // SAFETY: FFI call. 235 unsafe { bindings::BUG() }; 236 } 237 238 /// Produces a pointer to an object from a pointer to one of its fields. 239 /// 240 /// If you encounter a type mismatch due to the [`Opaque`] type, then use [`Opaque::cast_into`] or 241 /// [`Opaque::cast_from`] to resolve the mismatch. 242 /// 243 /// [`Opaque`]: crate::types::Opaque 244 /// [`Opaque::cast_into`]: crate::types::Opaque::cast_into 245 /// [`Opaque::cast_from`]: crate::types::Opaque::cast_from 246 /// 247 /// # Safety 248 /// 249 /// The pointer passed to this macro, and the pointer returned by this macro, must both be in 250 /// bounds of the same allocation. 251 /// 252 /// # Examples 253 /// 254 /// ``` 255 /// # use kernel::container_of; 256 /// struct Test { 257 /// a: u64, 258 /// b: u32, 259 /// } 260 /// 261 /// let test = Test { a: 10, b: 20 }; 262 /// let b_ptr: *const _ = &test.b; 263 /// // SAFETY: The pointer points at the `b` field of a `Test`, so the resulting pointer will be 264 /// // in-bounds of the same allocation as `b_ptr`. 265 /// let test_alias = unsafe { container_of!(b_ptr, Test, b) }; 266 /// assert!(core::ptr::eq(&test, test_alias)); 267 /// ``` 268 #[macro_export] 269 macro_rules! container_of { 270 ($field_ptr:expr, $Container:ty, $($fields:tt)*) => {{ 271 let offset: usize = ::core::mem::offset_of!($Container, $($fields)*); 272 let field_ptr = $field_ptr; 273 let container_ptr = field_ptr.byte_sub(offset).cast::<$Container>(); 274 $crate::assert_same_type(field_ptr, (&raw const (*container_ptr).$($fields)*).cast_mut()); 275 container_ptr 276 }} 277 } 278 279 /// Helper for [`container_of!`]. 280 #[doc(hidden)] 281 pub fn assert_same_type<T>(_: T, _: T) {} 282 283 /// Helper for `.rs.S` files. 284 #[doc(hidden)] 285 #[macro_export] 286 macro_rules! concat_literals { 287 ($( $asm:literal )* ) => { 288 ::core::concat!($($asm),*) 289 }; 290 } 291 292 /// Wrapper around `asm!` configured for use in the kernel. 293 /// 294 /// Uses a semicolon to avoid parsing ambiguities, even though this does not match native `asm!` 295 /// syntax. 296 // For x86, `asm!` uses intel syntax by default, but we want to use at&t syntax in the kernel. 297 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] 298 #[macro_export] 299 macro_rules! asm { 300 ($($asm:expr),* ; $($rest:tt)*) => { 301 ::core::arch::asm!( $($asm)*, options(att_syntax), $($rest)* ) 302 }; 303 } 304 305 /// Wrapper around `asm!` configured for use in the kernel. 306 /// 307 /// Uses a semicolon to avoid parsing ambiguities, even though this does not match native `asm!` 308 /// syntax. 309 // For non-x86 arches we just pass through to `asm!`. 310 #[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))] 311 #[macro_export] 312 macro_rules! asm { 313 ($($asm:expr),* ; $($rest:tt)*) => { 314 ::core::arch::asm!( $($asm)*, $($rest)* ) 315 }; 316 } 317 318 /// Gets the C string file name of a [`Location`]. 319 /// 320 /// If `Location::file_as_c_str()` is not available, returns a string that warns about it. 321 /// 322 /// [`Location`]: core::panic::Location 323 /// 324 /// # Examples 325 /// 326 /// ``` 327 /// # use kernel::file_from_location; 328 /// 329 /// #[track_caller] 330 /// fn foo() { 331 /// let caller = core::panic::Location::caller(); 332 /// 333 /// // Output: 334 /// // - A path like "rust/kernel/example.rs" if `file_as_c_str()` is available. 335 /// // - "<Location::file_as_c_str() not supported>" otherwise. 336 /// let caller_file = file_from_location(caller); 337 /// 338 /// // Prints out the message with caller's file name. 339 /// pr_info!("foo() called in file {caller_file:?}\n"); 340 /// 341 /// # if cfg!(CONFIG_RUSTC_HAS_FILE_WITH_NUL) { 342 /// # assert_eq!(Ok(caller.file()), caller_file.to_str()); 343 /// # } 344 /// } 345 /// 346 /// # foo(); 347 /// ``` 348 #[inline] 349 pub fn file_from_location<'a>(loc: &'a core::panic::Location<'a>) -> &'a core::ffi::CStr { 350 #[cfg(CONFIG_RUSTC_HAS_FILE_AS_C_STR)] 351 { 352 loc.file_as_c_str() 353 } 354 355 #[cfg(all(CONFIG_RUSTC_HAS_FILE_WITH_NUL, not(CONFIG_RUSTC_HAS_FILE_AS_C_STR)))] 356 { 357 loc.file_with_nul() 358 } 359 360 #[cfg(not(CONFIG_RUSTC_HAS_FILE_WITH_NUL))] 361 { 362 let _ = loc; 363 c"<Location::file_as_c_str() not supported>" 364 } 365 } 366