1 // SPDX-License-Identifier: GPL-2.0
3 //! The `kernel` crate.
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.
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.
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.
15 #![feature(arbitrary_self_types)]
16 #![feature(coerce_unsized)]
17 #![feature(dispatch_from_dyn)]
18 #![feature(inline_const)]
19 #![feature(lint_reasons)]
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");
27 // Allow proc-macros to refer to `::kernel` inside the `kernel` crate (this crate).
28 extern crate self as kernel;
39 #[cfg(CONFIG_RUST_FW_LOADER_ABSTRACTIONS)]
52 pub mod pid_namespace;
78 pub use build_error::build_error;
80 /// Prefix to appear before log messages printed from within the `kernel` crate.
81 const __LOG_PREFIX: &[u8] = b"rust_kernel\0";
83 /// The top level entrypoint to implementing a kernel module.
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.
89 /// Use this method to perform whatever setup or registration your module
92 /// Equivalent to the `module_init` macro in the C API.
93 fn init(module: &'static ThisModule) -> error::Result<Self>;
96 /// A module that is pinned and initialised in-place.
97 pub trait InPlaceModule: Sync + Send {
98 /// Creates an initialiser for the module.
100 /// It is called when the module is loaded.
101 fn init(module: &'static ThisModule) -> impl init::PinInit<Self, error::Error>;
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)?;
109 // SAFETY: `slot` is valid for write per the contract with `pin_init_from_closure`.
110 unsafe { slot.write(m) };
114 // SAFETY: On success, `initer` always fully initialises an instance of `Self`.
115 unsafe { init::pin_init_from_closure(initer) }
119 /// Equivalent to `THIS_MODULE` in the C API.
121 /// C header: [`include/linux/init.h`](srctree/include/linux/init.h)
122 pub struct ThisModule(*mut bindings::module);
124 // SAFETY: `THIS_MODULE` may be used from all threads within a module.
125 unsafe impl Sync for ThisModule {}
128 /// Creates a [`ThisModule`] given the `THIS_MODULE` pointer.
132 /// The pointer must be equal to the right `THIS_MODULE`.
133 pub const unsafe fn from_ptr(ptr: *mut bindings::module) -> ThisModule {
137 /// Access the raw pointer for this module.
139 /// It is up to the user to use it correctly.
140 pub const fn as_ptr(&self) -> *mut bindings::module {
145 #[cfg(not(any(testlib, test)))]
147 fn panic(info: &core::panic::PanicInfo<'_>) -> ! {
148 pr_emerg!("{}\n", info);
150 unsafe { bindings::BUG() };
153 /// Produces a pointer to an object from a pointer to one of its fields.
157 /// The pointer passed to this macro, and the pointer returned by this macro, must both be in
158 /// bounds of the same allocation.
163 /// # use kernel::container_of;
169 /// let test = Test { a: 10, b: 20 };
170 /// let b_ptr = &test.b;
171 /// // SAFETY: The pointer points at the `b` field of a `Test`, so the resulting pointer will be
172 /// // in-bounds of the same allocation as `b_ptr`.
173 /// let test_alias = unsafe { container_of!(b_ptr, Test, b) };
174 /// assert!(core::ptr::eq(&test, test_alias));
177 macro_rules! container_of {
178 ($ptr:expr, $type:ty, $($f:tt)*) => {{
179 let ptr = $ptr as *const _ as *const u8;
180 let offset: usize = ::core::mem::offset_of!($type, $($f)*);
181 ptr.sub(offset) as *const $type
185 /// Helper for `.rs.S` files.
188 macro_rules! concat_literals {
189 ($( $asm:literal )* ) => {
190 ::core::concat!($($asm),*)
194 /// Wrapper around `asm!` configured for use in the kernel.
196 /// Uses a semicolon to avoid parsing ambiguities, even though this does not match native `asm!`
198 // For x86, `asm!` uses intel syntax by default, but we want to use at&t syntax in the kernel.
199 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
202 ($($asm:expr),* ; $($rest:tt)*) => {
203 ::core::arch::asm!( $($asm)*, options(att_syntax), $($rest)* )
207 /// Wrapper around `asm!` configured for use in the kernel.
209 /// Uses a semicolon to avoid parsing ambiguities, even though this does not match native `asm!`
211 // For non-x86 arches we just pass through to `asm!`.
212 #[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
215 ($($asm:expr),* ; $($rest:tt)*) => {
216 ::core::arch::asm!( $($asm)*, $($rest)* )