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