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