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