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