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