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 // 16 // Please see https://github.com/Rust-for-Linux/linux/issues/2 for details on 17 // the unstable features in use. 18 // 19 // Stable since Rust 1.79.0. 20 #![feature(inline_const)] 21 // 22 // Stable since Rust 1.81.0. 23 #![feature(lint_reasons)] 24 // 25 // Stable since Rust 1.82.0. 26 #![feature(raw_ref_op)] 27 // 28 // Stable since Rust 1.83.0. 29 #![feature(const_maybe_uninit_as_mut_ptr)] 30 #![feature(const_mut_refs)] 31 #![feature(const_ptr_write)] 32 #![feature(const_refs_to_cell)] 33 // 34 // Expected to become stable. 35 #![feature(arbitrary_self_types)] 36 // 37 // `feature(derive_coerce_pointee)` is expected to become stable. Before Rust 38 // 1.84.0, it did not exist, so enable the predecessor features. 39 #![cfg_attr(CONFIG_RUSTC_HAS_COERCE_POINTEE, feature(derive_coerce_pointee))] 40 #![cfg_attr(not(CONFIG_RUSTC_HAS_COERCE_POINTEE), feature(coerce_unsized))] 41 #![cfg_attr(not(CONFIG_RUSTC_HAS_COERCE_POINTEE), feature(dispatch_from_dyn))] 42 #![cfg_attr(not(CONFIG_RUSTC_HAS_COERCE_POINTEE), feature(unsize))] 43 44 // Ensure conditional compilation based on the kernel configuration works; 45 // otherwise we may silently break things like initcall handling. 46 #[cfg(not(CONFIG_RUST))] 47 compile_error!("Missing kernel configuration for conditional compilation"); 48 49 // Allow proc-macros to refer to `::kernel` inside the `kernel` crate (this crate). 50 extern crate self as kernel; 51 52 pub use ffi; 53 54 pub mod alloc; 55 #[cfg(CONFIG_AUXILIARY_BUS)] 56 pub mod auxiliary; 57 pub mod bits; 58 #[cfg(CONFIG_BLOCK)] 59 pub mod block; 60 pub mod bug; 61 #[doc(hidden)] 62 pub mod build_assert; 63 pub mod clk; 64 #[cfg(CONFIG_CONFIGFS_FS)] 65 pub mod configfs; 66 pub mod cpu; 67 #[cfg(CONFIG_CPU_FREQ)] 68 pub mod cpufreq; 69 pub mod cpumask; 70 pub mod cred; 71 pub mod device; 72 pub mod device_id; 73 pub mod devres; 74 pub mod dma; 75 pub mod driver; 76 #[cfg(CONFIG_DRM = "y")] 77 pub mod drm; 78 pub mod error; 79 pub mod faux; 80 #[cfg(CONFIG_RUST_FW_LOADER_ABSTRACTIONS)] 81 pub mod firmware; 82 pub mod fmt; 83 pub mod fs; 84 pub mod init; 85 pub mod io; 86 pub mod ioctl; 87 pub mod jump_label; 88 #[cfg(CONFIG_KUNIT)] 89 pub mod kunit; 90 pub mod list; 91 pub mod miscdevice; 92 pub mod mm; 93 #[cfg(CONFIG_NET)] 94 pub mod net; 95 pub mod of; 96 #[cfg(CONFIG_PM_OPP)] 97 pub mod opp; 98 pub mod page; 99 #[cfg(CONFIG_PCI)] 100 pub mod pci; 101 pub mod pid_namespace; 102 pub mod platform; 103 pub mod prelude; 104 pub mod print; 105 pub mod rbtree; 106 pub mod revocable; 107 pub mod security; 108 pub mod seq_file; 109 pub mod sizes; 110 mod static_assert; 111 #[doc(hidden)] 112 pub mod std_vendor; 113 pub mod str; 114 pub mod sync; 115 pub mod task; 116 pub mod time; 117 pub mod tracepoint; 118 pub mod transmute; 119 pub mod types; 120 pub mod uaccess; 121 pub mod workqueue; 122 pub mod xarray; 123 124 #[doc(hidden)] 125 pub use bindings; 126 pub use macros; 127 pub use uapi; 128 129 /// Prefix to appear before log messages printed from within the `kernel` crate. 130 const __LOG_PREFIX: &[u8] = b"rust_kernel\0"; 131 132 /// The top level entrypoint to implementing a kernel module. 133 /// 134 /// For any teardown or cleanup operations, your type may implement [`Drop`]. 135 pub trait Module: Sized + Sync + Send { 136 /// Called at module initialization time. 137 /// 138 /// Use this method to perform whatever setup or registration your module 139 /// should do. 140 /// 141 /// Equivalent to the `module_init` macro in the C API. 142 fn init(module: &'static ThisModule) -> error::Result<Self>; 143 } 144 145 /// A module that is pinned and initialised in-place. 146 pub trait InPlaceModule: Sync + Send { 147 /// Creates an initialiser for the module. 148 /// 149 /// It is called when the module is loaded. 150 fn init(module: &'static ThisModule) -> impl pin_init::PinInit<Self, error::Error>; 151 } 152 153 impl<T: Module> InPlaceModule for T { 154 fn init(module: &'static ThisModule) -> impl pin_init::PinInit<Self, error::Error> { 155 let initer = move |slot: *mut Self| { 156 let m = <Self as Module>::init(module)?; 157 158 // SAFETY: `slot` is valid for write per the contract with `pin_init_from_closure`. 159 unsafe { slot.write(m) }; 160 Ok(()) 161 }; 162 163 // SAFETY: On success, `initer` always fully initialises an instance of `Self`. 164 unsafe { pin_init::pin_init_from_closure(initer) } 165 } 166 } 167 168 /// Metadata attached to a [`Module`] or [`InPlaceModule`]. 169 pub trait ModuleMetadata { 170 /// The name of the module as specified in the `module!` macro. 171 const NAME: &'static crate::str::CStr; 172 } 173 174 /// Equivalent to `THIS_MODULE` in the C API. 175 /// 176 /// C header: [`include/linux/init.h`](srctree/include/linux/init.h) 177 pub struct ThisModule(*mut bindings::module); 178 179 // SAFETY: `THIS_MODULE` may be used from all threads within a module. 180 unsafe impl Sync for ThisModule {} 181 182 impl ThisModule { 183 /// Creates a [`ThisModule`] given the `THIS_MODULE` pointer. 184 /// 185 /// # Safety 186 /// 187 /// The pointer must be equal to the right `THIS_MODULE`. 188 pub const unsafe fn from_ptr(ptr: *mut bindings::module) -> ThisModule { 189 ThisModule(ptr) 190 } 191 192 /// Access the raw pointer for this module. 193 /// 194 /// It is up to the user to use it correctly. 195 pub const fn as_ptr(&self) -> *mut bindings::module { 196 self.0 197 } 198 } 199 200 #[cfg(not(any(testlib, test)))] 201 #[panic_handler] 202 fn panic(info: &core::panic::PanicInfo<'_>) -> ! { 203 pr_emerg!("{}\n", info); 204 // SAFETY: FFI call. 205 unsafe { bindings::BUG() }; 206 } 207 208 /// Produces a pointer to an object from a pointer to one of its fields. 209 /// 210 /// If you encounter a type mismatch due to the [`Opaque`] type, then use [`Opaque::cast_into`] or 211 /// [`Opaque::cast_from`] to resolve the mismatch. 212 /// 213 /// [`Opaque`]: crate::types::Opaque 214 /// [`Opaque::cast_into`]: crate::types::Opaque::cast_into 215 /// [`Opaque::cast_from`]: crate::types::Opaque::cast_from 216 /// 217 /// # Safety 218 /// 219 /// The pointer passed to this macro, and the pointer returned by this macro, must both be in 220 /// bounds of the same allocation. 221 /// 222 /// # Examples 223 /// 224 /// ``` 225 /// # use kernel::container_of; 226 /// struct Test { 227 /// a: u64, 228 /// b: u32, 229 /// } 230 /// 231 /// let test = Test { a: 10, b: 20 }; 232 /// let b_ptr: *const _ = &test.b; 233 /// // SAFETY: The pointer points at the `b` field of a `Test`, so the resulting pointer will be 234 /// // in-bounds of the same allocation as `b_ptr`. 235 /// let test_alias = unsafe { container_of!(b_ptr, Test, b) }; 236 /// assert!(core::ptr::eq(&test, test_alias)); 237 /// ``` 238 #[macro_export] 239 macro_rules! container_of { 240 ($field_ptr:expr, $Container:ty, $($fields:tt)*) => {{ 241 let offset: usize = ::core::mem::offset_of!($Container, $($fields)*); 242 let field_ptr = $field_ptr; 243 let container_ptr = field_ptr.byte_sub(offset).cast::<$Container>(); 244 $crate::assert_same_type(field_ptr, (&raw const (*container_ptr).$($fields)*).cast_mut()); 245 container_ptr 246 }} 247 } 248 249 /// Helper for [`container_of!`]. 250 #[doc(hidden)] 251 pub fn assert_same_type<T>(_: T, _: T) {} 252 253 /// Helper for `.rs.S` files. 254 #[doc(hidden)] 255 #[macro_export] 256 macro_rules! concat_literals { 257 ($( $asm:literal )* ) => { 258 ::core::concat!($($asm),*) 259 }; 260 } 261 262 /// Wrapper around `asm!` configured for use in the kernel. 263 /// 264 /// Uses a semicolon to avoid parsing ambiguities, even though this does not match native `asm!` 265 /// syntax. 266 // For x86, `asm!` uses intel syntax by default, but we want to use at&t syntax in the kernel. 267 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] 268 #[macro_export] 269 macro_rules! asm { 270 ($($asm:expr),* ; $($rest:tt)*) => { 271 ::core::arch::asm!( $($asm)*, options(att_syntax), $($rest)* ) 272 }; 273 } 274 275 /// Wrapper around `asm!` configured for use in the kernel. 276 /// 277 /// Uses a semicolon to avoid parsing ambiguities, even though this does not match native `asm!` 278 /// syntax. 279 // For non-x86 arches we just pass through to `asm!`. 280 #[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))] 281 #[macro_export] 282 macro_rules! asm { 283 ($($asm:expr),* ; $($rest:tt)*) => { 284 ::core::arch::asm!( $($asm)*, $($rest)* ) 285 }; 286 } 287