xref: /linux-6.15/rust/kernel/lib.rs (revision ea7e1828)
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(arbitrary_self_types)]
16 #![feature(coerce_unsized)]
17 #![feature(dispatch_from_dyn)]
18 #![feature(inline_const)]
19 #![feature(lint_reasons)]
20 #![feature(unsize)]
21 
22 // Ensure conditional compilation based on the kernel configuration works;
23 // otherwise we may silently break things like initcall handling.
24 #[cfg(not(CONFIG_RUST))]
25 compile_error!("Missing kernel configuration for conditional compilation");
26 
27 // Allow proc-macros to refer to `::kernel` inside the `kernel` crate (this crate).
28 extern crate self as kernel;
29 
30 pub use ffi;
31 
32 pub mod alloc;
33 #[cfg(CONFIG_BLOCK)]
34 pub mod block;
35 mod build_assert;
36 pub mod cred;
37 pub mod device;
38 pub mod driver;
39 pub mod error;
40 #[cfg(CONFIG_RUST_FW_LOADER_ABSTRACTIONS)]
41 pub mod firmware;
42 pub mod fs;
43 pub mod init;
44 pub mod ioctl;
45 pub mod jump_label;
46 #[cfg(CONFIG_KUNIT)]
47 pub mod kunit;
48 pub mod list;
49 pub mod miscdevice;
50 #[cfg(CONFIG_NET)]
51 pub mod net;
52 pub mod page;
53 pub mod pid_namespace;
54 pub mod prelude;
55 pub mod print;
56 pub mod rbtree;
57 pub mod security;
58 pub mod seq_file;
59 pub mod sizes;
60 mod static_assert;
61 #[doc(hidden)]
62 pub mod std_vendor;
63 pub mod str;
64 pub mod sync;
65 pub mod task;
66 pub mod time;
67 pub mod tracepoint;
68 pub mod transmute;
69 pub mod types;
70 pub mod uaccess;
71 pub mod workqueue;
72 
73 #[doc(hidden)]
74 pub use bindings;
75 pub use macros;
76 pub use uapi;
77 
78 #[doc(hidden)]
79 pub use build_error::build_error;
80 
81 /// Prefix to appear before log messages printed from within the `kernel` crate.
82 const __LOG_PREFIX: &[u8] = b"rust_kernel\0";
83 
84 /// The top level entrypoint to implementing a kernel module.
85 ///
86 /// For any teardown or cleanup operations, your type may implement [`Drop`].
87 pub trait Module: Sized + Sync + Send {
88     /// Called at module initialization time.
89     ///
90     /// Use this method to perform whatever setup or registration your module
91     /// should do.
92     ///
93     /// Equivalent to the `module_init` macro in the C API.
94     fn init(module: &'static ThisModule) -> error::Result<Self>;
95 }
96 
97 /// A module that is pinned and initialised in-place.
98 pub trait InPlaceModule: Sync + Send {
99     /// Creates an initialiser for the module.
100     ///
101     /// It is called when the module is loaded.
102     fn init(module: &'static ThisModule) -> impl init::PinInit<Self, error::Error>;
103 }
104 
105 impl<T: Module> InPlaceModule for T {
106     fn init(module: &'static ThisModule) -> impl init::PinInit<Self, error::Error> {
107         let initer = move |slot: *mut Self| {
108             let m = <Self as Module>::init(module)?;
109 
110             // SAFETY: `slot` is valid for write per the contract with `pin_init_from_closure`.
111             unsafe { slot.write(m) };
112             Ok(())
113         };
114 
115         // SAFETY: On success, `initer` always fully initialises an instance of `Self`.
116         unsafe { init::pin_init_from_closure(initer) }
117     }
118 }
119 
120 /// Metadata attached to a [`Module`] or [`InPlaceModule`].
121 pub trait ModuleMetadata {
122     /// The name of the module as specified in the `module!` macro.
123     const NAME: &'static crate::str::CStr;
124 }
125 
126 /// Equivalent to `THIS_MODULE` in the C API.
127 ///
128 /// C header: [`include/linux/init.h`](srctree/include/linux/init.h)
129 pub struct ThisModule(*mut bindings::module);
130 
131 // SAFETY: `THIS_MODULE` may be used from all threads within a module.
132 unsafe impl Sync for ThisModule {}
133 
134 impl ThisModule {
135     /// Creates a [`ThisModule`] given the `THIS_MODULE` pointer.
136     ///
137     /// # Safety
138     ///
139     /// The pointer must be equal to the right `THIS_MODULE`.
140     pub const unsafe fn from_ptr(ptr: *mut bindings::module) -> ThisModule {
141         ThisModule(ptr)
142     }
143 
144     /// Access the raw pointer for this module.
145     ///
146     /// It is up to the user to use it correctly.
147     pub const fn as_ptr(&self) -> *mut bindings::module {
148         self.0
149     }
150 }
151 
152 #[cfg(not(any(testlib, test)))]
153 #[panic_handler]
154 fn panic(info: &core::panic::PanicInfo<'_>) -> ! {
155     pr_emerg!("{}\n", info);
156     // SAFETY: FFI call.
157     unsafe { bindings::BUG() };
158 }
159 
160 /// Produces a pointer to an object from a pointer to one of its fields.
161 ///
162 /// # Safety
163 ///
164 /// The pointer passed to this macro, and the pointer returned by this macro, must both be in
165 /// bounds of the same allocation.
166 ///
167 /// # Examples
168 ///
169 /// ```
170 /// # use kernel::container_of;
171 /// struct Test {
172 ///     a: u64,
173 ///     b: u32,
174 /// }
175 ///
176 /// let test = Test { a: 10, b: 20 };
177 /// let b_ptr = &test.b;
178 /// // SAFETY: The pointer points at the `b` field of a `Test`, so the resulting pointer will be
179 /// // in-bounds of the same allocation as `b_ptr`.
180 /// let test_alias = unsafe { container_of!(b_ptr, Test, b) };
181 /// assert!(core::ptr::eq(&test, test_alias));
182 /// ```
183 #[macro_export]
184 macro_rules! container_of {
185     ($ptr:expr, $type:ty, $($f:tt)*) => {{
186         let ptr = $ptr as *const _ as *const u8;
187         let offset: usize = ::core::mem::offset_of!($type, $($f)*);
188         ptr.sub(offset) as *const $type
189     }}
190 }
191 
192 /// Helper for `.rs.S` files.
193 #[doc(hidden)]
194 #[macro_export]
195 macro_rules! concat_literals {
196     ($( $asm:literal )* ) => {
197         ::core::concat!($($asm),*)
198     };
199 }
200 
201 /// Wrapper around `asm!` configured for use in the kernel.
202 ///
203 /// Uses a semicolon to avoid parsing ambiguities, even though this does not match native `asm!`
204 /// syntax.
205 // For x86, `asm!` uses intel syntax by default, but we want to use at&t syntax in the kernel.
206 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
207 #[macro_export]
208 macro_rules! asm {
209     ($($asm:expr),* ; $($rest:tt)*) => {
210         ::core::arch::asm!( $($asm)*, options(att_syntax), $($rest)* )
211     };
212 }
213 
214 /// Wrapper around `asm!` configured for use in the kernel.
215 ///
216 /// Uses a semicolon to avoid parsing ambiguities, even though this does not match native `asm!`
217 /// syntax.
218 // For non-x86 arches we just pass through to `asm!`.
219 #[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
220 #[macro_export]
221 macro_rules! asm {
222     ($($asm:expr),* ; $($rest:tt)*) => {
223         ::core::arch::asm!( $($asm)*, $($rest)* )
224     };
225 }
226