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`] 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.
16 // Please see https://github.com/Rust-for-Linux/linux/issues/2 for details on
17 // the unstable features in use.
19 // Stable since Rust 1.79.0.
20 #![feature(inline_const)]
22 // Stable since Rust 1.81.0.
23 #![feature(lint_reasons)]
25 // Stable since Rust 1.82.0.
26 #![feature(raw_ref_op)]
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)]
34 // Expected to become stable.
35 #![feature(arbitrary_self_types)]
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))]
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");
49 // Allow proc-macros to refer to `::kernel` inside the `kernel` crate (this crate).
50 extern crate self as kernel;
55 #[cfg(CONFIG_AUXILIARY_BUS)]
62 #[cfg(CONFIG_CONFIGFS_FS)]
65 #[cfg(CONFIG_CPU_FREQ)]
74 #[cfg(CONFIG_DRM = "y")]
78 #[cfg(CONFIG_RUST_FW_LOADER_ABSTRACTIONS)]
98 pub mod pid_namespace;
126 /// Prefix to appear before log messages printed from within the `kernel` crate.
127 const __LOG_PREFIX: &[u8] = b"rust_kernel\0";
129 /// The top level entrypoint to implementing a kernel module.
131 /// For any teardown or cleanup operations, your type may implement [`Drop`].
132 pub trait Module: Sized + Sync + Send {
133 /// Called at module initialization time.
135 /// Use this method to perform whatever setup or registration your module
138 /// Equivalent to the `module_init` macro in the C API.
139 fn init(module: &'static ThisModule) -> error::Result<Self>;
142 /// A module that is pinned and initialised in-place.
143 pub trait InPlaceModule: Sync + Send {
144 /// Creates an initialiser for the module.
146 /// It is called when the module is loaded.
147 fn init(module: &'static ThisModule) -> impl pin_init::PinInit<Self, error::Error>;
150 impl<T: Module> InPlaceModule for T {
151 fn init(module: &'static ThisModule) -> impl pin_init::PinInit<Self, error::Error> {
152 let initer = move |slot: *mut Self| {
153 let m = <Self as Module>::init(module)?;
155 // SAFETY: `slot` is valid for write per the contract with `pin_init_from_closure`.
156 unsafe { slot.write(m) };
160 // SAFETY: On success, `initer` always fully initialises an instance of `Self`.
161 unsafe { pin_init::pin_init_from_closure(initer) }
165 /// Metadata attached to a [`Module`] or [`InPlaceModule`].
166 pub trait ModuleMetadata {
167 /// The name of the module as specified in the `module!` macro.
168 const NAME: &'static crate::str::CStr;
171 /// Equivalent to `THIS_MODULE` in the C API.
173 /// C header: [`include/linux/init.h`](srctree/include/linux/init.h)
174 pub struct ThisModule(*mut bindings::module);
176 // SAFETY: `THIS_MODULE` may be used from all threads within a module.
177 unsafe impl Sync for ThisModule {}
180 /// Creates a [`ThisModule`] given the `THIS_MODULE` pointer.
184 /// The pointer must be equal to the right `THIS_MODULE`.
185 pub const unsafe fn from_ptr(ptr: *mut bindings::module) -> ThisModule {
189 /// Access the raw pointer for this module.
191 /// It is up to the user to use it correctly.
192 pub const fn as_ptr(&self) -> *mut bindings::module {
197 #[cfg(not(any(testlib, test)))]
199 fn panic(info: &core::panic::PanicInfo<'_>) -> ! {
200 pr_emerg!("{}\n", info);
202 unsafe { bindings::BUG() };
205 /// Produces a pointer to an object from a pointer to one of its fields.
209 /// The pointer passed to this macro, and the pointer returned by this macro, must both be in
210 /// bounds of the same allocation.
215 /// # use kernel::container_of;
221 /// let test = Test { a: 10, b: 20 };
222 /// let b_ptr: *const _ = &test.b;
223 /// // SAFETY: The pointer points at the `b` field of a `Test`, so the resulting pointer will be
224 /// // in-bounds of the same allocation as `b_ptr`.
225 /// let test_alias = unsafe { container_of!(b_ptr, Test, b) };
226 /// assert!(core::ptr::eq(&test, test_alias));
229 macro_rules! container_of {
230 ($field_ptr:expr, $Container:ty, $($fields:tt)*) => {{
231 let offset: usize = ::core::mem::offset_of!($Container, $($fields)*);
232 let field_ptr = $field_ptr;
233 let container_ptr = field_ptr.byte_sub(offset).cast::<$Container>();
234 $crate::assert_same_type(field_ptr, (&raw const (*container_ptr).$($fields)*).cast_mut());
239 /// Helper for [`container_of!`].
241 pub fn assert_same_type<T>(_: T, _: T) {}
243 /// Helper for `.rs.S` files.
246 macro_rules! concat_literals {
247 ($( $asm:literal )* ) => {
248 ::core::concat!($($asm),*)
252 /// Wrapper around `asm!` configured for use in the kernel.
254 /// Uses a semicolon to avoid parsing ambiguities, even though this does not match native `asm!`
256 // For x86, `asm!` uses intel syntax by default, but we want to use at&t syntax in the kernel.
257 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
260 ($($asm:expr),* ; $($rest:tt)*) => {
261 ::core::arch::asm!( $($asm)*, options(att_syntax), $($rest)* )
265 /// Wrapper around `asm!` configured for use in the kernel.
267 /// Uses a semicolon to avoid parsing ambiguities, even though this does not match native `asm!`
269 // For non-x86 arches we just pass through to `asm!`.
270 #[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
273 ($($asm:expr),* ; $($rest:tt)*) => {
274 ::core::arch::asm!( $($asm)*, $($rest)* )