xref: /linux/rust/kernel/lib.rs (revision 8f2146159b3a24d4fde0479c5e19f31908419004)
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`] 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 //
16 // Please see https://github.com/Rust-for-Linux/linux/issues/2 for details on
17 // the unstable features in use.
18 //
19 // Stable since Rust 1.79.0.
20 #![feature(inline_const)]
21 //
22 // Stable since Rust 1.81.0.
23 #![feature(lint_reasons)]
24 //
25 // Stable since Rust 1.82.0.
26 #![feature(raw_ref_op)]
27 //
28 // Stable since Rust 1.83.0.
29 #![feature(const_maybe_uninit_as_mut_ptr)]
30 #![feature(const_mut_refs)]
31 #![feature(const_ptr_write)]
32 #![feature(const_refs_to_cell)]
33 //
34 // Expected to become stable.
35 #![feature(arbitrary_self_types)]
36 //
37 // `feature(derive_coerce_pointee)` is expected to become stable. Before Rust
38 // 1.84.0, it did not exist, so enable the predecessor features.
39 #![cfg_attr(CONFIG_RUSTC_HAS_COERCE_POINTEE, feature(derive_coerce_pointee))]
40 #![cfg_attr(not(CONFIG_RUSTC_HAS_COERCE_POINTEE), feature(coerce_unsized))]
41 #![cfg_attr(not(CONFIG_RUSTC_HAS_COERCE_POINTEE), feature(dispatch_from_dyn))]
42 #![cfg_attr(not(CONFIG_RUSTC_HAS_COERCE_POINTEE), feature(unsize))]
43 //
44 // `feature(file_with_nul)` is expected to become stable. Before Rust 1.89.0, it did not exist, so
45 // enable it conditionally.
46 #![cfg_attr(CONFIG_RUSTC_HAS_FILE_WITH_NUL, feature(file_with_nul))]
47 
48 // Ensure conditional compilation based on the kernel configuration works;
49 // otherwise we may silently break things like initcall handling.
50 #[cfg(not(CONFIG_RUST))]
51 compile_error!("Missing kernel configuration for conditional compilation");
52 
53 // Allow proc-macros to refer to `::kernel` inside the `kernel` crate (this crate).
54 extern crate self as kernel;
55 
56 pub use ffi;
57 
58 pub mod alloc;
59 #[cfg(CONFIG_AUXILIARY_BUS)]
60 pub mod auxiliary;
61 #[cfg(CONFIG_BLOCK)]
62 pub mod block;
63 #[doc(hidden)]
64 pub mod build_assert;
65 pub mod clk;
66 #[cfg(CONFIG_CONFIGFS_FS)]
67 pub mod configfs;
68 pub mod cpu;
69 #[cfg(CONFIG_CPU_FREQ)]
70 pub mod cpufreq;
71 pub mod cpumask;
72 pub mod cred;
73 pub mod device;
74 pub mod device_id;
75 pub mod devres;
76 pub mod dma;
77 pub mod driver;
78 #[cfg(CONFIG_DRM = "y")]
79 pub mod drm;
80 pub mod error;
81 pub mod faux;
82 #[cfg(CONFIG_RUST_FW_LOADER_ABSTRACTIONS)]
83 pub mod firmware;
84 pub mod fs;
85 pub mod init;
86 pub mod io;
87 pub mod ioctl;
88 pub mod jump_label;
89 #[cfg(CONFIG_KUNIT)]
90 pub mod kunit;
91 pub mod list;
92 pub mod miscdevice;
93 pub mod mm;
94 #[cfg(CONFIG_NET)]
95 pub mod net;
96 pub mod of;
97 #[cfg(CONFIG_PM_OPP)]
98 pub mod opp;
99 pub mod page;
100 #[cfg(CONFIG_PCI)]
101 pub mod pci;
102 pub mod pid_namespace;
103 pub mod platform;
104 pub mod prelude;
105 pub mod print;
106 pub mod rbtree;
107 pub mod revocable;
108 pub mod security;
109 pub mod seq_file;
110 pub mod sizes;
111 mod static_assert;
112 #[doc(hidden)]
113 pub mod std_vendor;
114 pub mod str;
115 pub mod sync;
116 pub mod task;
117 pub mod time;
118 pub mod tracepoint;
119 pub mod transmute;
120 pub mod types;
121 pub mod uaccess;
122 pub mod workqueue;
123 pub mod xarray;
124 
125 #[doc(hidden)]
126 pub use bindings;
127 pub use macros;
128 pub use uapi;
129 
130 /// Prefix to appear before log messages printed from within the `kernel` crate.
131 const __LOG_PREFIX: &[u8] = b"rust_kernel\0";
132 
133 /// The top level entrypoint to implementing a kernel module.
134 ///
135 /// For any teardown or cleanup operations, your type may implement [`Drop`].
136 pub trait Module: Sized + Sync + Send {
137     /// Called at module initialization time.
138     ///
139     /// Use this method to perform whatever setup or registration your module
140     /// should do.
141     ///
142     /// Equivalent to the `module_init` macro in the C API.
143     fn init(module: &'static ThisModule) -> error::Result<Self>;
144 }
145 
146 /// A module that is pinned and initialised in-place.
147 pub trait InPlaceModule: Sync + Send {
148     /// Creates an initialiser for the module.
149     ///
150     /// It is called when the module is loaded.
151     fn init(module: &'static ThisModule) -> impl pin_init::PinInit<Self, error::Error>;
152 }
153 
154 impl<T: Module> InPlaceModule for T {
155     fn init(module: &'static ThisModule) -> impl pin_init::PinInit<Self, error::Error> {
156         let initer = move |slot: *mut Self| {
157             let m = <Self as Module>::init(module)?;
158 
159             // SAFETY: `slot` is valid for write per the contract with `pin_init_from_closure`.
160             unsafe { slot.write(m) };
161             Ok(())
162         };
163 
164         // SAFETY: On success, `initer` always fully initialises an instance of `Self`.
165         unsafe { pin_init::pin_init_from_closure(initer) }
166     }
167 }
168 
169 /// Metadata attached to a [`Module`] or [`InPlaceModule`].
170 pub trait ModuleMetadata {
171     /// The name of the module as specified in the `module!` macro.
172     const NAME: &'static crate::str::CStr;
173 }
174 
175 /// Equivalent to `THIS_MODULE` in the C API.
176 ///
177 /// C header: [`include/linux/init.h`](srctree/include/linux/init.h)
178 pub struct ThisModule(*mut bindings::module);
179 
180 // SAFETY: `THIS_MODULE` may be used from all threads within a module.
181 unsafe impl Sync for ThisModule {}
182 
183 impl ThisModule {
184     /// Creates a [`ThisModule`] given the `THIS_MODULE` pointer.
185     ///
186     /// # Safety
187     ///
188     /// The pointer must be equal to the right `THIS_MODULE`.
189     pub const unsafe fn from_ptr(ptr: *mut bindings::module) -> ThisModule {
190         ThisModule(ptr)
191     }
192 
193     /// Access the raw pointer for this module.
194     ///
195     /// It is up to the user to use it correctly.
196     pub const fn as_ptr(&self) -> *mut bindings::module {
197         self.0
198     }
199 }
200 
201 #[cfg(not(any(testlib, test)))]
202 #[panic_handler]
203 fn panic(info: &core::panic::PanicInfo<'_>) -> ! {
204     pr_emerg!("{}\n", info);
205     // SAFETY: FFI call.
206     unsafe { bindings::BUG() };
207 }
208 
209 /// Produces a pointer to an object from a pointer to one of its fields.
210 ///
211 /// # Safety
212 ///
213 /// The pointer passed to this macro, and the pointer returned by this macro, must both be in
214 /// bounds of the same allocation.
215 ///
216 /// # Examples
217 ///
218 /// ```
219 /// # use kernel::container_of;
220 /// struct Test {
221 ///     a: u64,
222 ///     b: u32,
223 /// }
224 ///
225 /// let test = Test { a: 10, b: 20 };
226 /// let b_ptr: *const _ = &test.b;
227 /// // SAFETY: The pointer points at the `b` field of a `Test`, so the resulting pointer will be
228 /// // in-bounds of the same allocation as `b_ptr`.
229 /// let test_alias = unsafe { container_of!(b_ptr, Test, b) };
230 /// assert!(core::ptr::eq(&test, test_alias));
231 /// ```
232 #[macro_export]
233 macro_rules! container_of {
234     ($field_ptr:expr, $Container:ty, $($fields:tt)*) => {{
235         let offset: usize = ::core::mem::offset_of!($Container, $($fields)*);
236         let field_ptr = $field_ptr;
237         let container_ptr = field_ptr.byte_sub(offset).cast::<$Container>();
238         $crate::assert_same_type(field_ptr, (&raw const (*container_ptr).$($fields)*).cast_mut());
239         container_ptr
240     }}
241 }
242 
243 /// Helper for [`container_of!`].
244 #[doc(hidden)]
245 pub fn assert_same_type<T>(_: T, _: T) {}
246 
247 /// Helper for `.rs.S` files.
248 #[doc(hidden)]
249 #[macro_export]
250 macro_rules! concat_literals {
251     ($( $asm:literal )* ) => {
252         ::core::concat!($($asm),*)
253     };
254 }
255 
256 /// Wrapper around `asm!` configured for use in the kernel.
257 ///
258 /// Uses a semicolon to avoid parsing ambiguities, even though this does not match native `asm!`
259 /// syntax.
260 // For x86, `asm!` uses intel syntax by default, but we want to use at&t syntax in the kernel.
261 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
262 #[macro_export]
263 macro_rules! asm {
264     ($($asm:expr),* ; $($rest:tt)*) => {
265         ::core::arch::asm!( $($asm)*, options(att_syntax), $($rest)* )
266     };
267 }
268 
269 /// Wrapper around `asm!` configured for use in the kernel.
270 ///
271 /// Uses a semicolon to avoid parsing ambiguities, even though this does not match native `asm!`
272 /// syntax.
273 // For non-x86 arches we just pass through to `asm!`.
274 #[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
275 #[macro_export]
276 macro_rules! asm {
277     ($($asm:expr),* ; $($rest:tt)*) => {
278         ::core::arch::asm!( $($asm)*, $($rest)* )
279     };
280 }
281 
282 /// Gets the C string file name of a [`Location`].
283 ///
284 /// If `file_with_nul()` is not available, returns a string that warns about it.
285 ///
286 /// [`Location`]: core::panic::Location
287 ///
288 /// # Examples
289 ///
290 /// ```
291 /// # use kernel::file_from_location;
292 ///
293 /// #[track_caller]
294 /// fn foo() {
295 ///     let caller = core::panic::Location::caller();
296 ///
297 ///     // Output:
298 ///     // - A path like "rust/kernel/example.rs" if file_with_nul() is available.
299 ///     // - "<Location::file_with_nul() not supported>" otherwise.
300 ///     let caller_file = file_from_location(caller);
301 ///
302 ///     // Prints out the message with caller's file name.
303 ///     pr_info!("foo() called in file {caller_file:?}\n");
304 ///
305 ///     # if cfg!(CONFIG_RUSTC_HAS_FILE_WITH_NUL) {
306 ///     #     assert_eq!(Ok(caller.file()), caller_file.to_str());
307 ///     # }
308 /// }
309 ///
310 /// # foo();
311 /// ```
312 #[inline]
313 pub fn file_from_location<'a>(loc: &'a core::panic::Location<'a>) -> &'a core::ffi::CStr {
314     #[cfg(CONFIG_RUSTC_HAS_FILE_WITH_NUL)]
315     {
316         loc.file_with_nul()
317     }
318 
319     #[cfg(not(CONFIG_RUSTC_HAS_FILE_WITH_NUL))]
320     {
321         let _ = loc;
322         c"<Location::file_with_nul() not supported>"
323     }
324 }
325