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