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