// SPDX-License-Identifier: GPL-2.012//! The `kernel` crate.3//!4//! This crate contains the kernel APIs that have been ported or wrapped for5//! usage by Rust code in the kernel and is shared by all of them.6//!7//! In other words, all the rest of the Rust code in the kernel (e.g. kernel8//! modules written in Rust) depends on [`core`] and this crate.9//!10//! If you need a kernel C API that is not ported or wrapped yet here, then11//! do so first instead of bypassing this crate.1213#![no_std]14//15// Please see https://github.com/Rust-for-Linux/linux/issues/2 for details on16// the unstable features in use.17//18// Stable since Rust 1.79.0.19#![feature(generic_nonzero)]20#![feature(inline_const)]21#![feature(pointer_is_aligned)]22//23// Stable since Rust 1.81.0.24#![feature(lint_reasons)]25//26// Stable since Rust 1.82.0.27#![feature(raw_ref_op)]28//29// Stable since Rust 1.83.0.30#![feature(const_maybe_uninit_as_mut_ptr)]31#![feature(const_mut_refs)]32#![feature(const_option)]33#![feature(const_ptr_write)]34#![feature(const_refs_to_cell)]35//36// Expected to become stable.37#![feature(arbitrary_self_types)]38//39// To be determined.40#![feature(used_with_arg)]41//42// `feature(derive_coerce_pointee)` is expected to become stable. Before Rust43// 1.84.0, it did not exist, so enable the predecessor features.44#![cfg_attr(CONFIG_RUSTC_HAS_COERCE_POINTEE, feature(derive_coerce_pointee))]45#![cfg_attr(not(CONFIG_RUSTC_HAS_COERCE_POINTEE), feature(coerce_unsized))]46#![cfg_attr(not(CONFIG_RUSTC_HAS_COERCE_POINTEE), feature(dispatch_from_dyn))]47#![cfg_attr(not(CONFIG_RUSTC_HAS_COERCE_POINTEE), feature(unsize))]48//49// `feature(file_with_nul)` is expected to become stable. Before Rust 1.89.0, it did not exist, so50// enable it conditionally.51#![cfg_attr(CONFIG_RUSTC_HAS_FILE_WITH_NUL, feature(file_with_nul))]5253// Ensure conditional compilation based on the kernel configuration works;54// otherwise we may silently break things like initcall handling.55#[cfg(not(CONFIG_RUST))]56compile_error!("Missing kernel configuration for conditional compilation");5758// Allow proc-macros to refer to `::kernel` inside the `kernel` crate (this crate).59extern crate self as kernel;6061pub use ffi;6263pub mod acpi;64pub mod alloc;65#[cfg(CONFIG_AUXILIARY_BUS)]66pub mod auxiliary;67pub mod bitmap;68pub mod bits;69#[cfg(CONFIG_BLOCK)]70pub mod block;71pub mod bug;72#[doc(hidden)]73pub mod build_assert;74pub mod clk;75#[cfg(CONFIG_CONFIGFS_FS)]76pub mod configfs;77pub mod cpu;78#[cfg(CONFIG_CPU_FREQ)]79pub mod cpufreq;80pub mod cpumask;81pub mod cred;82pub mod debugfs;83pub mod device;84pub mod device_id;85pub mod devres;86pub mod dma;87pub mod driver;88#[cfg(CONFIG_DRM = "y")]89pub mod drm;90pub mod error;91pub mod faux;92#[cfg(CONFIG_RUST_FW_LOADER_ABSTRACTIONS)]93pub mod firmware;94pub mod fmt;95pub mod fs;96pub mod id_pool;97pub mod init;98pub mod io;99pub mod ioctl;100pub mod iov;101pub mod irq;102pub mod jump_label;103#[cfg(CONFIG_KUNIT)]104pub mod kunit;105pub mod list;106pub mod maple_tree;107pub mod miscdevice;108pub mod mm;109#[cfg(CONFIG_NET)]110pub mod net;111pub mod of;112#[cfg(CONFIG_PM_OPP)]113pub mod opp;114pub mod page;115#[cfg(CONFIG_PCI)]116pub mod pci;117pub mod pid_namespace;118pub mod platform;119pub mod prelude;120pub mod print;121pub mod processor;122pub mod ptr;123pub mod rbtree;124pub mod regulator;125pub mod revocable;126pub mod scatterlist;127pub mod security;128pub mod seq_file;129pub mod sizes;130mod static_assert;131#[doc(hidden)]132pub mod std_vendor;133pub mod str;134pub mod sync;135pub mod task;136pub mod time;137pub mod tracepoint;138pub mod transmute;139pub mod types;140pub mod uaccess;141pub mod workqueue;142pub mod xarray;143144#[doc(hidden)]145pub use bindings;146pub use macros;147pub use uapi;148149/// Prefix to appear before log messages printed from within the `kernel` crate.150const __LOG_PREFIX: &[u8] = b"rust_kernel\0";151152/// The top level entrypoint to implementing a kernel module.153///154/// For any teardown or cleanup operations, your type may implement [`Drop`].155pub trait Module: Sized + Sync + Send {156/// Called at module initialization time.157///158/// Use this method to perform whatever setup or registration your module159/// should do.160///161/// Equivalent to the `module_init` macro in the C API.162fn init(module: &'static ThisModule) -> error::Result<Self>;163}164165/// A module that is pinned and initialised in-place.166pub trait InPlaceModule: Sync + Send {167/// Creates an initialiser for the module.168///169/// It is called when the module is loaded.170fn init(module: &'static ThisModule) -> impl pin_init::PinInit<Self, error::Error>;171}172173impl<T: Module> InPlaceModule for T {174fn init(module: &'static ThisModule) -> impl pin_init::PinInit<Self, error::Error> {175let initer = move |slot: *mut Self| {176let m = <Self as Module>::init(module)?;177178// SAFETY: `slot` is valid for write per the contract with `pin_init_from_closure`.179unsafe { slot.write(m) };180Ok(())181};182183// SAFETY: On success, `initer` always fully initialises an instance of `Self`.184unsafe { pin_init::pin_init_from_closure(initer) }185}186}187188/// Metadata attached to a [`Module`] or [`InPlaceModule`].189pub trait ModuleMetadata {190/// The name of the module as specified in the `module!` macro.191const NAME: &'static crate::str::CStr;192}193194/// Equivalent to `THIS_MODULE` in the C API.195///196/// C header: [`include/linux/init.h`](srctree/include/linux/init.h)197pub struct ThisModule(*mut bindings::module);198199// SAFETY: `THIS_MODULE` may be used from all threads within a module.200unsafe impl Sync for ThisModule {}201202impl ThisModule {203/// Creates a [`ThisModule`] given the `THIS_MODULE` pointer.204///205/// # Safety206///207/// The pointer must be equal to the right `THIS_MODULE`.208pub const unsafe fn from_ptr(ptr: *mut bindings::module) -> ThisModule {209ThisModule(ptr)210}211212/// Access the raw pointer for this module.213///214/// It is up to the user to use it correctly.215pub const fn as_ptr(&self) -> *mut bindings::module {216self.0217}218}219220#[cfg(not(testlib))]221#[panic_handler]222fn panic(info: &core::panic::PanicInfo<'_>) -> ! {223pr_emerg!("{}\n", info);224// SAFETY: FFI call.225unsafe { bindings::BUG() };226}227228/// Produces a pointer to an object from a pointer to one of its fields.229///230/// If you encounter a type mismatch due to the [`Opaque`] type, then use [`Opaque::cast_into`] or231/// [`Opaque::cast_from`] to resolve the mismatch.232///233/// [`Opaque`]: crate::types::Opaque234/// [`Opaque::cast_into`]: crate::types::Opaque::cast_into235/// [`Opaque::cast_from`]: crate::types::Opaque::cast_from236///237/// # Safety238///239/// The pointer passed to this macro, and the pointer returned by this macro, must both be in240/// bounds of the same allocation.241///242/// # Examples243///244/// ```245/// # use kernel::container_of;246/// struct Test {247/// a: u64,248/// b: u32,249/// }250///251/// let test = Test { a: 10, b: 20 };252/// let b_ptr: *const _ = &test.b;253/// // SAFETY: The pointer points at the `b` field of a `Test`, so the resulting pointer will be254/// // in-bounds of the same allocation as `b_ptr`.255/// let test_alias = unsafe { container_of!(b_ptr, Test, b) };256/// assert!(core::ptr::eq(&test, test_alias));257/// ```258#[macro_export]259macro_rules! container_of {260($field_ptr:expr, $Container:ty, $($fields:tt)*) => {{261let offset: usize = ::core::mem::offset_of!($Container, $($fields)*);262let field_ptr = $field_ptr;263let container_ptr = field_ptr.byte_sub(offset).cast::<$Container>();264$crate::assert_same_type(field_ptr, (&raw const (*container_ptr).$($fields)*).cast_mut());265container_ptr266}}267}268269/// Helper for [`container_of!`].270#[doc(hidden)]271pub fn assert_same_type<T>(_: T, _: T) {}272273/// Helper for `.rs.S` files.274#[doc(hidden)]275#[macro_export]276macro_rules! concat_literals {277($( $asm:literal )* ) => {278::core::concat!($($asm),*)279};280}281282/// Wrapper around `asm!` configured for use in the kernel.283///284/// Uses a semicolon to avoid parsing ambiguities, even though this does not match native `asm!`285/// syntax.286// For x86, `asm!` uses intel syntax by default, but we want to use at&t syntax in the kernel.287#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]288#[macro_export]289macro_rules! asm {290($($asm:expr),* ; $($rest:tt)*) => {291::core::arch::asm!( $($asm)*, options(att_syntax), $($rest)* )292};293}294295/// Wrapper around `asm!` configured for use in the kernel.296///297/// Uses a semicolon to avoid parsing ambiguities, even though this does not match native `asm!`298/// syntax.299// For non-x86 arches we just pass through to `asm!`.300#[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]301#[macro_export]302macro_rules! asm {303($($asm:expr),* ; $($rest:tt)*) => {304::core::arch::asm!( $($asm)*, $($rest)* )305};306}307308/// Gets the C string file name of a [`Location`].309///310/// If `Location::file_as_c_str()` is not available, returns a string that warns about it.311///312/// [`Location`]: core::panic::Location313///314/// # Examples315///316/// ```317/// # use kernel::file_from_location;318///319/// #[track_caller]320/// fn foo() {321/// let caller = core::panic::Location::caller();322///323/// // Output:324/// // - A path like "rust/kernel/example.rs" if `file_as_c_str()` is available.325/// // - "<Location::file_as_c_str() not supported>" otherwise.326/// let caller_file = file_from_location(caller);327///328/// // Prints out the message with caller's file name.329/// pr_info!("foo() called in file {caller_file:?}\n");330///331/// # if cfg!(CONFIG_RUSTC_HAS_FILE_WITH_NUL) {332/// # assert_eq!(Ok(caller.file()), caller_file.to_str());333/// # }334/// }335///336/// # foo();337/// ```338#[inline]339pub fn file_from_location<'a>(loc: &'a core::panic::Location<'a>) -> &'a core::ffi::CStr {340#[cfg(CONFIG_RUSTC_HAS_FILE_AS_C_STR)]341{342loc.file_as_c_str()343}344345#[cfg(all(CONFIG_RUSTC_HAS_FILE_WITH_NUL, not(CONFIG_RUSTC_HAS_FILE_AS_C_STR)))]346{347loc.file_with_nul()348}349350#[cfg(not(CONFIG_RUSTC_HAS_FILE_WITH_NUL))]351{352let _ = loc;353c"<Location::file_as_c_str() not supported>"354}355}356357358