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