rust: add `build_error` crate
[linux-block.git] / rust / kernel / lib.rs
CommitLineData
247b365d
WAF
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`], [`alloc`] 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]
76e2c2d9 15#![feature(allocator_api)]
247b365d
WAF
16#![feature(core_ffi_c)]
17
18// Ensure conditional compilation based on the kernel configuration works;
19// otherwise we may silently break things like initcall handling.
20#[cfg(not(CONFIG_RUST))]
21compile_error!("Missing kernel configuration for conditional compilation");
22
23#[cfg(not(test))]
24#[cfg(not(testlib))]
25mod allocator;
26pub mod error;
27pub mod prelude;
28pub mod print;
ef9e3797 29mod static_assert;
bee16889
NM
30#[doc(hidden)]
31pub mod std_vendor;
247b365d
WAF
32pub mod str;
33
34#[doc(hidden)]
35pub use bindings;
36pub use macros;
37
38/// Prefix to appear before log messages printed from within the `kernel` crate.
39const __LOG_PREFIX: &[u8] = b"rust_kernel\0";
40
41/// The top level entrypoint to implementing a kernel module.
42///
43/// For any teardown or cleanup operations, your type may implement [`Drop`].
44pub trait Module: Sized + Sync {
45 /// Called at module initialization time.
46 ///
47 /// Use this method to perform whatever setup or registration your module
48 /// should do.
49 ///
50 /// Equivalent to the `module_init` macro in the C API.
51 fn init(module: &'static ThisModule) -> error::Result<Self>;
52}
53
54/// Equivalent to `THIS_MODULE` in the C API.
55///
56/// C header: `include/linux/export.h`
57pub struct ThisModule(*mut bindings::module);
58
59// SAFETY: `THIS_MODULE` may be used from all threads within a module.
60unsafe impl Sync for ThisModule {}
61
62impl ThisModule {
63 /// Creates a [`ThisModule`] given the `THIS_MODULE` pointer.
64 ///
65 /// # Safety
66 ///
67 /// The pointer must be equal to the right `THIS_MODULE`.
68 pub const unsafe fn from_ptr(ptr: *mut bindings::module) -> ThisModule {
69 ThisModule(ptr)
70 }
71}
72
73#[cfg(not(any(testlib, test)))]
74#[panic_handler]
75fn panic(info: &core::panic::PanicInfo<'_>) -> ! {
76 pr_emerg!("{}\n", info);
77 // SAFETY: FFI call.
78 unsafe { bindings::BUG() };
79 // Bindgen currently does not recognize `__noreturn` so `BUG` returns `()`
80 // instead of `!`. See <https://github.com/rust-lang/rust-bindgen/issues/2094>.
81 loop {}
82}