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