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;
103pub mod init;
104pub mod io;
105pub mod ioctl;
106pub mod iommu;
107pub mod iov;
108pub mod irq;
109pub mod jump_label;
110#[cfg(CONFIG_KUNIT)]
111pub mod kunit;
112pub mod list;
113pub mod maple_tree;
114pub mod miscdevice;
115pub mod mm;
116pub mod module_param;
117#[cfg(CONFIG_NET)]
118pub mod net;
119pub mod num;
120pub mod of;
121#[cfg(CONFIG_PM_OPP)]
122pub mod opp;
123pub mod page;
124#[cfg(CONFIG_PCI)]
125pub mod pci;
126pub mod pid_namespace;
127pub mod platform;
128pub mod prelude;
129pub mod print;
130pub mod processor;
131pub mod ptr;
132#[cfg(CONFIG_RUST_PWM_ABSTRACTIONS)]
133pub mod pwm;
134pub mod rbtree;
135pub mod regulator;
136pub mod revocable;
137pub mod scatterlist;
138pub mod security;
139pub mod seq_file;
140pub mod sizes;
141pub mod slice;
142#[cfg(CONFIG_SOC_BUS)]
143pub mod soc;
144mod static_assert;
145#[doc(hidden)]
146pub mod std_vendor;
147pub mod str;
148pub mod sync;
149pub mod task;
150pub mod time;
151pub mod tracepoint;
152pub mod transmute;
153pub mod types;
154pub mod uaccess;
155#[cfg(CONFIG_USB = "y")]
156pub mod usb;
157pub mod workqueue;
158pub mod xarray;
159
160#[doc(hidden)]
161pub use bindings;
162pub use macros;
163pub use uapi;
164
165/// Prefix to appear before log messages printed from within the `kernel` crate.
166const __LOG_PREFIX: &[u8] = b"rust_kernel\0";
167
168/// The top level entrypoint to implementing a kernel module.
169///
170/// For any teardown or cleanup operations, your type may implement [`Drop`].
171pub trait Module: Sized + Sync + Send {
172    /// Called at module initialization time.
173    ///
174    /// Use this method to perform whatever setup or registration your module
175    /// should do.
176    ///
177    /// Equivalent to the `module_init` macro in the C API.
178    fn init(module: &'static ThisModule) -> error::Result<Self>;
179}
180
181/// A module that is pinned and initialised in-place.
182pub trait InPlaceModule: Sync + Send {
183    /// Creates an initialiser for the module.
184    ///
185    /// It is called when the module is loaded.
186    fn init(module: &'static ThisModule) -> impl pin_init::PinInit<Self, error::Error>;
187}
188
189impl<T: Module> InPlaceModule for T {
190    fn init(module: &'static ThisModule) -> impl pin_init::PinInit<Self, error::Error> {
191        let initer = move |slot: *mut Self| {
192            let m = <Self as Module>::init(module)?;
193
194            // SAFETY: `slot` is valid for write per the contract with `pin_init_from_closure`.
195            unsafe { slot.write(m) };
196            Ok(())
197        };
198
199        // SAFETY: On success, `initer` always fully initialises an instance of `Self`.
200        unsafe { pin_init::pin_init_from_closure(initer) }
201    }
202}
203
204/// Metadata attached to a [`Module`] or [`InPlaceModule`].
205pub trait ModuleMetadata {
206    /// The name of the module as specified in the `module!` macro.
207    const NAME: &'static crate::str::CStr;
208}
209
210/// Equivalent to `THIS_MODULE` in the C API.
211///
212/// C header: [`include/linux/init.h`](srctree/include/linux/init.h)
213pub struct ThisModule(*mut bindings::module);
214
215// SAFETY: `THIS_MODULE` may be used from all threads within a module.
216unsafe impl Sync for ThisModule {}
217
218impl ThisModule {
219    /// Creates a [`ThisModule`] given the `THIS_MODULE` pointer.
220    ///
221    /// # Safety
222    ///
223    /// The pointer must be equal to the right `THIS_MODULE`.
224    pub const unsafe fn from_ptr(ptr: *mut bindings::module) -> ThisModule {
225        ThisModule(ptr)
226    }
227
228    /// Access the raw pointer for this module.
229    ///
230    /// It is up to the user to use it correctly.
231    pub const fn as_ptr(&self) -> *mut bindings::module {
232        self.0
233    }
234}
235
236#[cfg(not(testlib))]
237#[panic_handler]
238fn panic(info: &core::panic::PanicInfo<'_>) -> ! {
239    pr_emerg!("{}\n", info);
240    // SAFETY: FFI call.
241    unsafe { bindings::BUG() };
242}
243
244/// Produces a pointer to an object from a pointer to one of its fields.
245///
246/// If you encounter a type mismatch due to the [`Opaque`] type, then use [`Opaque::cast_into`] or
247/// [`Opaque::cast_from`] to resolve the mismatch.
248///
249/// [`Opaque`]: crate::types::Opaque
250/// [`Opaque::cast_into`]: crate::types::Opaque::cast_into
251/// [`Opaque::cast_from`]: crate::types::Opaque::cast_from
252///
253/// # Safety
254///
255/// The pointer passed to this macro, and the pointer returned by this macro, must both be in
256/// bounds of the same allocation.
257///
258/// # Examples
259///
260/// ```
261/// # use kernel::container_of;
262/// struct Test {
263///     a: u64,
264///     b: u32,
265/// }
266///
267/// let test = Test { a: 10, b: 20 };
268/// let b_ptr: *const _ = &test.b;
269/// // SAFETY: The pointer points at the `b` field of a `Test`, so the resulting pointer will be
270/// // in-bounds of the same allocation as `b_ptr`.
271/// let test_alias = unsafe { container_of!(b_ptr, Test, b) };
272/// assert!(core::ptr::eq(&test, test_alias));
273/// ```
274#[macro_export]
275macro_rules! container_of {
276    ($field_ptr:expr, $Container:ty, $($fields:tt)*) => {{
277        let offset: usize = ::core::mem::offset_of!($Container, $($fields)*);
278        let field_ptr = $field_ptr;
279        let container_ptr = field_ptr.byte_sub(offset).cast::<$Container>();
280        $crate::assert_same_type(field_ptr, (&raw const (*container_ptr).$($fields)*).cast_mut());
281        container_ptr
282    }}
283}
284
285/// Helper for [`container_of!`].
286#[doc(hidden)]
287pub fn assert_same_type<T>(_: T, _: T) {}
288
289/// Helper for `.rs.S` files.
290#[doc(hidden)]
291#[macro_export]
292macro_rules! concat_literals {
293    ($( $asm:literal )* ) => {
294        ::core::concat!($($asm),*)
295    };
296}
297
298/// Wrapper around `asm!` configured for use in the kernel.
299///
300/// Uses a semicolon to avoid parsing ambiguities, even though this does not match native `asm!`
301/// syntax.
302// For x86, `asm!` uses intel syntax by default, but we want to use at&t syntax in the kernel.
303#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
304#[macro_export]
305macro_rules! asm {
306    ($($asm:expr),* ; $($rest:tt)*) => {
307        ::core::arch::asm!( $($asm)*, options(att_syntax), $($rest)* )
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 non-x86 arches we just pass through to `asm!`.
316#[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
317#[macro_export]
318macro_rules! asm {
319    ($($asm:expr),* ; $($rest:tt)*) => {
320        ::core::arch::asm!( $($asm)*, $($rest)* )
321    };
322}
323
324/// Gets the C string file name of a [`Location`].
325///
326/// If `Location::file_as_c_str()` is not available, returns a string that warns about it.
327///
328/// [`Location`]: core::panic::Location
329///
330/// # Examples
331///
332/// ```
333/// # use kernel::file_from_location;
334///
335/// #[track_caller]
336/// fn foo() {
337///     let caller = core::panic::Location::caller();
338///
339///     // Output:
340///     // - A path like "rust/kernel/example.rs" if `file_as_c_str()` is available.
341///     // - "<Location::file_as_c_str() not supported>" otherwise.
342///     let caller_file = file_from_location(caller);
343///
344///     // Prints out the message with caller's file name.
345///     pr_info!("foo() called in file {caller_file:?}\n");
346///
347///     # if cfg!(CONFIG_RUSTC_HAS_FILE_WITH_NUL) {
348///     #     assert_eq!(Ok(caller.file()), caller_file.to_str());
349///     # }
350/// }
351///
352/// # foo();
353/// ```
354#[inline]
355pub fn file_from_location<'a>(loc: &'a core::panic::Location<'a>) -> &'a core::ffi::CStr {
356    #[cfg(CONFIG_RUSTC_HAS_FILE_AS_C_STR)]
357    {
358        loc.file_as_c_str()
359    }
360
361    #[cfg(all(CONFIG_RUSTC_HAS_FILE_WITH_NUL, not(CONFIG_RUSTC_HAS_FILE_AS_C_STR)))]
362    {
363        loc.file_with_nul()
364    }
365
366    #[cfg(not(CONFIG_RUSTC_HAS_FILE_WITH_NUL))]
367    {
368        let _ = loc;
369        c"<Location::file_as_c_str() not supported>"
370    }
371}