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