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