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