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