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