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