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