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