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