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