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] 15 #![feature(allocator_api)] 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))] 21 compile_error!("Missing kernel configuration for conditional compilation"); 22 23 #[cfg(not(test))] 24 #[cfg(not(testlib))] 25 mod allocator; 26 pub mod error; 27 pub mod prelude; 28 pub mod print; 29 mod static_assert; 30 #[doc(hidden)] 31 pub mod std_vendor; 32 pub mod str; 33 34 #[doc(hidden)] 35 pub use bindings; 36 pub use macros; 37 38 /// Prefix to appear before log messages printed from within the `kernel` crate. 39 const __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`]. 44 pub 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` 57 pub struct ThisModule(*mut bindings::module); 58 59 // SAFETY: `THIS_MODULE` may be used from all threads within a module. 60 unsafe impl Sync for ThisModule {} 61 62 impl 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] 75 fn 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 } 83