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.87.0.
20#![feature(unsigned_is_multiple_of)]
21//
22// Stable since Rust 1.89.0.
23#![feature(generic_arg_infer)]
24//
25// Expected to become stable.
26#![feature(arbitrary_self_types)]
27#![feature(derive_coerce_pointee)]
28//
29// To be determined.
30#![feature(used_with_arg)]
31//
32// For documentation purpose only.
33#![feature(doc_notable_trait)]
34//
35// `feature(file_with_nul)` is stable since Rust 1.92.0. Before Rust 1.89.0, it did not exist, so
36// enable it conditionally.
37#![cfg_attr(CONFIG_RUSTC_HAS_FILE_WITH_NUL, feature(file_with_nul))]
38
39// Ensure conditional compilation based on the kernel configuration works;
40// otherwise we may silently break things like initcall handling.
41#[cfg(not(CONFIG_RUST))]
42compile_error!("Missing kernel configuration for conditional compilation");
43
44// Allow proc-macros to refer to `::kernel` inside the `kernel` crate (this crate).
45extern crate self as kernel;
46
47pub use ffi;
48
49pub mod acpi;
50pub mod alloc;
51#[cfg(CONFIG_AUXILIARY_BUS)]
52pub mod auxiliary;
53pub mod bitfield;
54pub mod bitmap;
55pub mod bits;
56#[cfg(CONFIG_BLOCK)]
57pub mod block;
58pub mod bug;
59pub mod build_assert;
60pub mod clk;
61#[cfg(CONFIG_CONFIGFS_FS)]
62pub mod configfs;
63pub mod cpu;
64#[cfg(CONFIG_CPU_FREQ)]
65pub mod cpufreq;
66pub mod cpumask;
67pub mod cred;
68pub mod debugfs;
69pub mod device;
70pub mod device_id;
71pub mod devres;
72pub mod dma;
73#[cfg(CONFIG_DMA_SHARED_BUFFER)]
74pub mod dma_buf;
75pub mod driver;
76#[cfg(CONFIG_DRM = "y")]
77pub mod drm;
78pub mod error;
79pub mod faux;
80#[cfg(CONFIG_RUST_FW_LOADER_ABSTRACTIONS)]
81pub mod firmware;
82pub mod fmt;
83pub mod fs;
84#[cfg(CONFIG_RUST_FWCTL_ABSTRACTIONS)]
85pub mod fwctl;
86#[cfg(CONFIG_GPU_BUDDY = "y")]
87pub mod gpu;
88#[cfg(CONFIG_I2C = "y")]
89pub mod i2c;
90pub mod id_pool;
91#[doc(hidden)]
92pub mod impl_flags;
93pub mod init;
94pub mod interop;
95pub mod interrupt;
96pub mod io;
97pub mod ioctl;
98pub mod iommu;
99pub mod iov;
100pub mod irq;
101pub mod jump_label;
102#[cfg(CONFIG_RUST_KCSAN_KUNIT_TEST)]
103mod kcsan_test;
104#[cfg(CONFIG_KUNIT)]
105pub mod kunit;
106pub mod list;
107pub mod maple_tree;
108pub mod mem;
109pub mod miscdevice;
110pub mod mm;
111pub mod module;
112pub mod module_param;
113#[cfg(CONFIG_NET)]
114pub mod net;
115pub mod num;
116pub mod of;
117#[cfg(CONFIG_PM_OPP)]
118pub mod opp;
119pub mod page;
120#[cfg(CONFIG_PCI)]
121pub mod pci;
122pub mod pid_namespace;
123pub mod platform;
124pub mod prelude;
125pub mod print;
126pub mod processor;
127pub mod ptr;
128#[cfg(CONFIG_RUST_PWM_ABSTRACTIONS)]
129pub mod pwm;
130pub mod ratelimit;
131pub mod rbtree;
132pub mod regulator;
133pub mod revocable;
134#[cfg(CONFIG_XARRAY_RUST)]
135pub mod rxarray;
136pub mod safety;
137pub mod scatterlist;
138pub mod security;
139pub mod seq_file;
140#[cfg(CONFIG_RUST_SERIAL_DEV_BUS_ABSTRACTIONS)]
141pub mod serdev;
142pub mod sizes;
143#[cfg(CONFIG_SOC_BUS)]
144pub mod soc;
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 module::{
164    InPlaceModule,
165    Module,
166    ModuleMetadata,
167    ThisModule, //
168};
169pub use uapi;
170
171/// Prefix to appear before log messages printed from within the `kernel` crate.
172const __LOG_PREFIX: &[u8] = b"rust_kernel\0";
173
174/// Dummy module type for `#[vtable]` `impl` blocks within the `kernel` crate (e.g. KUnit tests).
175// The `allow` is needed since it may be unused (e.g. KUnit tests may be disabled).
176#[allow(dead_code)]
177struct LocalModule;
178
179impl ModuleMetadata for LocalModule {
180    const NAME: &'static str::CStr = c"rust_kernel";
181
182    const THIS_MODULE: ThisModule = {
183        // SAFETY: `try_module_get`/`module_put` handle null module pointers gracefully.
184        unsafe { ThisModule::from_ptr(core::ptr::null_mut()) }
185    };
186}
187
188#[cfg(not(testlib))]
189#[inline]
190fn bug_on_panic(info: &core::panic::PanicInfo<'_>) -> ! {
191    pr_emerg!("{}\n", info);
192    // SAFETY: FFI call.
193    unsafe { bindings::BUG() };
194}
195
196#[cfg(all(not(testlib), not(CONFIG_KUNIT = "y")))]
197#[panic_handler]
198fn panic(info: &core::panic::PanicInfo<'_>) -> ! {
199    bug_on_panic(info);
200}
201
202#[cfg(all(not(testlib), CONFIG_KUNIT = "y"))]
203#[panic_handler]
204fn panic(info: &core::panic::PanicInfo<'_>) -> ! {
205    // SAFETY: This function is safe to call even if CONFIG_KUNIT=n. If a null pointer is returned,
206    // the panic is handled same as if CONFIG_KUNIT=n.
207    let kunit_test = unsafe { ::bindings::kunit_get_current_test() };
208    if kunit_test.is_null() {
209        bug_on_panic(info);
210    } else {
211        // SAFETY: We are in the else branch of kunit_test.is_null() condition, meaning that
212        // `::bindings::kunit_get_current_test()` returned a kunit struct successfully.
213        let test_attributes = unsafe { (*kunit_test).attr };
214        if test_attributes.is_null() {
215            use crate::str::CStrExt as _;
216            // SAFETY: Test name should be set by KUnit framework at this stage.
217            let test_str = unsafe { str::CStr::from_char_ptr((*kunit_test).name.cast()) };
218            pr_emerg!("Test case {} has no attributes\n", test_str);
219            bug_on_panic(info);
220        }
221        // SAFETY: We already tested that test_attributes.is_null() is false, meaning that it is
222        // safe to retrieve its attributes.
223        else if unsafe { (*test_attributes).rust_should_panic } {
224            // SAFETY: We are in the else branch of kunit_test.is_null() condition, meaning that
225            // `::bindings::kunit_get_current_test()` returned a kunit struct successfully.
226            unsafe {
227                bindings::__kunit_abort(kunit_test);
228            };
229        } else {
230            bug_on_panic(info);
231        }
232    }
233}
234
235/// Produces a pointer to an object from a pointer to one of its fields.
236///
237/// If you encounter a type mismatch due to the [`Opaque`] type, then use [`Opaque::cast_into`] or
238/// [`Opaque::cast_from`] to resolve the mismatch.
239///
240/// [`Opaque`]: crate::types::Opaque
241/// [`Opaque::cast_into`]: crate::types::Opaque::cast_into
242/// [`Opaque::cast_from`]: crate::types::Opaque::cast_from
243///
244/// # Safety
245///
246/// The pointer passed to this macro, and the pointer returned by this macro, must both be in
247/// bounds of the same allocation.
248///
249/// # Examples
250///
251/// ```
252/// # use kernel::container_of;
253/// struct Test {
254///     a: u64,
255///     b: u32,
256/// }
257///
258/// let test = Test { a: 10, b: 20 };
259/// let b_ptr: *const _ = &test.b;
260/// // SAFETY: The pointer points at the `b` field of a `Test`, so the resulting pointer will be
261/// // in-bounds of the same allocation as `b_ptr`.
262/// let test_alias = unsafe { container_of!(b_ptr, Test, b) };
263/// assert!(core::ptr::eq(&test, test_alias));
264/// ```
265#[macro_export]
266macro_rules! container_of {
267    ($field_ptr:expr, $Container:ty, $($fields:tt)*) => {{
268        let offset: usize = ::core::mem::offset_of!($Container, $($fields)*);
269        let field_ptr = $field_ptr;
270        let container_ptr = field_ptr.byte_sub(offset).cast::<$Container>();
271        $crate::assert_same_type(field_ptr, (&raw const (*container_ptr).$($fields)*).cast_mut());
272        container_ptr
273    }}
274}
275
276/// Helper for [`container_of!`].
277#[doc(hidden)]
278pub fn assert_same_type<T>(_: T, _: T) {}
279
280/// Helper for `.rs.S` files.
281#[doc(hidden)]
282#[macro_export]
283macro_rules! concat_literals {
284    ($( $asm:literal )* ) => {
285        ::core::concat!($($asm),*)
286    };
287}
288
289/// Wrapper around `asm!` configured for use in the kernel.
290///
291/// Uses a semicolon to avoid parsing ambiguities, even though this does not match native `asm!`
292/// syntax.
293// For x86, `asm!` uses intel syntax by default, but we want to use at&t syntax in the kernel.
294#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
295#[macro_export]
296macro_rules! asm {
297    ($($asm:expr),* ; $($rest:tt)*) => {
298        ::core::arch::asm!( $($asm)*, options(att_syntax), $($rest)* )
299    };
300}
301
302/// Wrapper around `asm!` configured for use in the kernel.
303///
304/// Uses a semicolon to avoid parsing ambiguities, even though this does not match native `asm!`
305/// syntax.
306// For non-x86 arches we just pass through to `asm!`.
307#[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
308#[macro_export]
309macro_rules! asm {
310    ($($asm:expr),* ; $($rest:tt)*) => {
311        ::core::arch::asm!( $($asm)*, $($rest)* )
312    };
313}
314
315/// Gets the C string file name of a [`Location`].
316///
317/// If `Location::file_as_c_str()` is not available, returns a string that warns about it.
318///
319/// [`Location`]: core::panic::Location
320///
321/// # Examples
322///
323/// ```
324/// # use kernel::file_from_location;
325///
326/// #[track_caller]
327/// fn foo() {
328///     let caller = core::panic::Location::caller();
329///
330///     // Output:
331///     // - A path like "rust/kernel/example.rs" if `file_as_c_str()` is available.
332///     // - "<Location::file_as_c_str() not supported>" otherwise.
333///     let caller_file = file_from_location(caller);
334///
335///     // Prints out the message with caller's file name.
336///     pr_info!("foo() called in file {caller_file:?}\n");
337///
338///     # if cfg!(CONFIG_RUSTC_HAS_FILE_WITH_NUL) {
339///     #     assert_eq!(Ok(caller.file()), caller_file.to_str());
340///     # }
341/// }
342///
343/// # foo();
344/// ```
345#[inline]
346pub fn file_from_location<'a>(loc: &'a core::panic::Location<'a>) -> &'a core::ffi::CStr {
347    #[cfg(CONFIG_RUSTC_HAS_FILE_AS_C_STR)]
348    {
349        loc.file_as_c_str()
350    }
351
352    #[cfg(all(CONFIG_RUSTC_HAS_FILE_WITH_NUL, not(CONFIG_RUSTC_HAS_FILE_AS_C_STR)))]
353    {
354        loc.file_with_nul()
355    }
356
357    #[cfg(not(CONFIG_RUSTC_HAS_FILE_WITH_NUL))]
358    {
359        let _ = loc;
360        c"<Location::file_as_c_str() not supported>"
361    }
362}