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