xref: /linux-6.15/rust/kernel/lib.rs (revision ce30d94e)
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 mod io;
83 pub use macros;
84 pub use uapi;
85 
86 #[doc(hidden)]
87 pub use build_error::build_error;
88 
89 /// Prefix to appear before log messages printed from within the `kernel` crate.
90 const __LOG_PREFIX: &[u8] = b"rust_kernel\0";
91 
92 /// The top level entrypoint to implementing a kernel module.
93 ///
94 /// For any teardown or cleanup operations, your type may implement [`Drop`].
95 pub trait Module: Sized + Sync + Send {
96     /// Called at module initialization time.
97     ///
98     /// Use this method to perform whatever setup or registration your module
99     /// should do.
100     ///
101     /// Equivalent to the `module_init` macro in the C API.
102     fn init(module: &'static ThisModule) -> error::Result<Self>;
103 }
104 
105 /// A module that is pinned and initialised in-place.
106 pub trait InPlaceModule: Sync + Send {
107     /// Creates an initialiser for the module.
108     ///
109     /// It is called when the module is loaded.
110     fn init(module: &'static ThisModule) -> impl init::PinInit<Self, error::Error>;
111 }
112 
113 impl<T: Module> InPlaceModule for T {
114     fn init(module: &'static ThisModule) -> impl init::PinInit<Self, error::Error> {
115         let initer = move |slot: *mut Self| {
116             let m = <Self as Module>::init(module)?;
117 
118             // SAFETY: `slot` is valid for write per the contract with `pin_init_from_closure`.
119             unsafe { slot.write(m) };
120             Ok(())
121         };
122 
123         // SAFETY: On success, `initer` always fully initialises an instance of `Self`.
124         unsafe { init::pin_init_from_closure(initer) }
125     }
126 }
127 
128 /// Metadata attached to a [`Module`] or [`InPlaceModule`].
129 pub trait ModuleMetadata {
130     /// The name of the module as specified in the `module!` macro.
131     const NAME: &'static crate::str::CStr;
132 }
133 
134 /// Equivalent to `THIS_MODULE` in the C API.
135 ///
136 /// C header: [`include/linux/init.h`](srctree/include/linux/init.h)
137 pub struct ThisModule(*mut bindings::module);
138 
139 // SAFETY: `THIS_MODULE` may be used from all threads within a module.
140 unsafe impl Sync for ThisModule {}
141 
142 impl ThisModule {
143     /// Creates a [`ThisModule`] given the `THIS_MODULE` pointer.
144     ///
145     /// # Safety
146     ///
147     /// The pointer must be equal to the right `THIS_MODULE`.
148     pub const unsafe fn from_ptr(ptr: *mut bindings::module) -> ThisModule {
149         ThisModule(ptr)
150     }
151 
152     /// Access the raw pointer for this module.
153     ///
154     /// It is up to the user to use it correctly.
155     pub const fn as_ptr(&self) -> *mut bindings::module {
156         self.0
157     }
158 }
159 
160 #[cfg(not(any(testlib, test)))]
161 #[panic_handler]
162 fn panic(info: &core::panic::PanicInfo<'_>) -> ! {
163     pr_emerg!("{}\n", info);
164     // SAFETY: FFI call.
165     unsafe { bindings::BUG() };
166 }
167 
168 /// Produces a pointer to an object from a pointer to one of its fields.
169 ///
170 /// # Safety
171 ///
172 /// The pointer passed to this macro, and the pointer returned by this macro, must both be in
173 /// bounds of the same allocation.
174 ///
175 /// # Examples
176 ///
177 /// ```
178 /// # use kernel::container_of;
179 /// struct Test {
180 ///     a: u64,
181 ///     b: u32,
182 /// }
183 ///
184 /// let test = Test { a: 10, b: 20 };
185 /// let b_ptr = &test.b;
186 /// // SAFETY: The pointer points at the `b` field of a `Test`, so the resulting pointer will be
187 /// // in-bounds of the same allocation as `b_ptr`.
188 /// let test_alias = unsafe { container_of!(b_ptr, Test, b) };
189 /// assert!(core::ptr::eq(&test, test_alias));
190 /// ```
191 #[macro_export]
192 macro_rules! container_of {
193     ($ptr:expr, $type:ty, $($f:tt)*) => {{
194         let ptr = $ptr as *const _ as *const u8;
195         let offset: usize = ::core::mem::offset_of!($type, $($f)*);
196         ptr.sub(offset) as *const $type
197     }}
198 }
199 
200 /// Helper for `.rs.S` files.
201 #[doc(hidden)]
202 #[macro_export]
203 macro_rules! concat_literals {
204     ($( $asm:literal )* ) => {
205         ::core::concat!($($asm),*)
206     };
207 }
208 
209 /// Wrapper around `asm!` configured for use in the kernel.
210 ///
211 /// Uses a semicolon to avoid parsing ambiguities, even though this does not match native `asm!`
212 /// syntax.
213 // For x86, `asm!` uses intel syntax by default, but we want to use at&t syntax in the kernel.
214 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
215 #[macro_export]
216 macro_rules! asm {
217     ($($asm:expr),* ; $($rest:tt)*) => {
218         ::core::arch::asm!( $($asm)*, options(att_syntax), $($rest)* )
219     };
220 }
221 
222 /// Wrapper around `asm!` configured for use in the kernel.
223 ///
224 /// Uses a semicolon to avoid parsing ambiguities, even though this does not match native `asm!`
225 /// syntax.
226 // For non-x86 arches we just pass through to `asm!`.
227 #[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
228 #[macro_export]
229 macro_rules! asm {
230     ($($asm:expr),* ; $($rest:tt)*) => {
231         ::core::arch::asm!( $($asm)*, $($rest)* )
232     };
233 }
234