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