Skip to main content

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