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