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 pub mod mm; 76 #[cfg(CONFIG_NET)] 77 pub mod net; 78 pub mod of; 79 #[cfg(CONFIG_PM_OPP)] 80 pub mod opp; 81 pub mod page; 82 #[cfg(CONFIG_PCI)] 83 pub mod pci; 84 pub mod pid_namespace; 85 pub mod platform; 86 pub mod prelude; 87 pub mod print; 88 pub mod rbtree; 89 pub mod revocable; 90 pub mod security; 91 pub mod seq_file; 92 pub mod sizes; 93 mod static_assert; 94 #[doc(hidden)] 95 pub mod std_vendor; 96 pub mod str; 97 pub mod sync; 98 pub mod task; 99 pub mod time; 100 pub mod tracepoint; 101 pub mod transmute; 102 pub mod types; 103 pub mod uaccess; 104 pub mod workqueue; 105 106 #[doc(hidden)] 107 pub use bindings; 108 pub use macros; 109 pub use uapi; 110 111 /// Prefix to appear before log messages printed from within the `kernel` crate. 112 const __LOG_PREFIX: &[u8] = b"rust_kernel\0"; 113 114 /// The top level entrypoint to implementing a kernel module. 115 /// 116 /// For any teardown or cleanup operations, your type may implement [`Drop`]. 117 pub trait Module: Sized + Sync + Send { 118 /// Called at module initialization time. 119 /// 120 /// Use this method to perform whatever setup or registration your module 121 /// should do. 122 /// 123 /// Equivalent to the `module_init` macro in the C API. 124 fn init(module: &'static ThisModule) -> error::Result<Self>; 125 } 126 127 /// A module that is pinned and initialised in-place. 128 pub trait InPlaceModule: Sync + Send { 129 /// Creates an initialiser for the module. 130 /// 131 /// It is called when the module is loaded. 132 fn init(module: &'static ThisModule) -> impl pin_init::PinInit<Self, error::Error>; 133 } 134 135 impl<T: Module> InPlaceModule for T { 136 fn init(module: &'static ThisModule) -> impl pin_init::PinInit<Self, error::Error> { 137 let initer = move |slot: *mut Self| { 138 let m = <Self as Module>::init(module)?; 139 140 // SAFETY: `slot` is valid for write per the contract with `pin_init_from_closure`. 141 unsafe { slot.write(m) }; 142 Ok(()) 143 }; 144 145 // SAFETY: On success, `initer` always fully initialises an instance of `Self`. 146 unsafe { pin_init::pin_init_from_closure(initer) } 147 } 148 } 149 150 /// Metadata attached to a [`Module`] or [`InPlaceModule`]. 151 pub trait ModuleMetadata { 152 /// The name of the module as specified in the `module!` macro. 153 const NAME: &'static crate::str::CStr; 154 } 155 156 /// Equivalent to `THIS_MODULE` in the C API. 157 /// 158 /// C header: [`include/linux/init.h`](srctree/include/linux/init.h) 159 pub struct ThisModule(*mut bindings::module); 160 161 // SAFETY: `THIS_MODULE` may be used from all threads within a module. 162 unsafe impl Sync for ThisModule {} 163 164 impl ThisModule { 165 /// Creates a [`ThisModule`] given the `THIS_MODULE` pointer. 166 /// 167 /// # Safety 168 /// 169 /// The pointer must be equal to the right `THIS_MODULE`. 170 pub const unsafe fn from_ptr(ptr: *mut bindings::module) -> ThisModule { 171 ThisModule(ptr) 172 } 173 174 /// Access the raw pointer for this module. 175 /// 176 /// It is up to the user to use it correctly. 177 pub const fn as_ptr(&self) -> *mut bindings::module { 178 self.0 179 } 180 } 181 182 #[cfg(not(any(testlib, test)))] 183 #[panic_handler] 184 fn panic(info: &core::panic::PanicInfo<'_>) -> ! { 185 pr_emerg!("{}\n", info); 186 // SAFETY: FFI call. 187 unsafe { bindings::BUG() }; 188 } 189 190 /// Produces a pointer to an object from a pointer to one of its fields. 191 /// 192 /// # Safety 193 /// 194 /// The pointer passed to this macro, and the pointer returned by this macro, must both be in 195 /// bounds of the same allocation. 196 /// 197 /// # Examples 198 /// 199 /// ``` 200 /// # use kernel::container_of; 201 /// struct Test { 202 /// a: u64, 203 /// b: u32, 204 /// } 205 /// 206 /// let test = Test { a: 10, b: 20 }; 207 /// let b_ptr = &test.b; 208 /// // SAFETY: The pointer points at the `b` field of a `Test`, so the resulting pointer will be 209 /// // in-bounds of the same allocation as `b_ptr`. 210 /// let test_alias = unsafe { container_of!(b_ptr, Test, b) }; 211 /// assert!(core::ptr::eq(&test, test_alias)); 212 /// ``` 213 #[macro_export] 214 macro_rules! container_of { 215 ($ptr:expr, $type:ty, $($f:tt)*) => {{ 216 let ptr = $ptr as *const _ as *const u8; 217 let offset: usize = ::core::mem::offset_of!($type, $($f)*); 218 ptr.sub(offset) as *const $type 219 }} 220 } 221 222 /// Helper for `.rs.S` files. 223 #[doc(hidden)] 224 #[macro_export] 225 macro_rules! concat_literals { 226 ($( $asm:literal )* ) => { 227 ::core::concat!($($asm),*) 228 }; 229 } 230 231 /// Wrapper around `asm!` configured for use in the kernel. 232 /// 233 /// Uses a semicolon to avoid parsing ambiguities, even though this does not match native `asm!` 234 /// syntax. 235 // For x86, `asm!` uses intel syntax by default, but we want to use at&t syntax in the kernel. 236 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] 237 #[macro_export] 238 macro_rules! asm { 239 ($($asm:expr),* ; $($rest:tt)*) => { 240 ::core::arch::asm!( $($asm)*, options(att_syntax), $($rest)* ) 241 }; 242 } 243 244 /// Wrapper around `asm!` configured for use in the kernel. 245 /// 246 /// Uses a semicolon to avoid parsing ambiguities, even though this does not match native `asm!` 247 /// syntax. 248 // For non-x86 arches we just pass through to `asm!`. 249 #[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))] 250 #[macro_export] 251 macro_rules! asm { 252 ($($asm:expr),* ; $($rest:tt)*) => { 253 ::core::arch::asm!( $($asm)*, $($rest)* ) 254 }; 255 } 256