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