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