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