kernel/
lib.rs

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