xref: /linux/rust/kernel/lib.rs (revision 59e6295fac26b8e85c1ea859cdd89fa1e47519d7)
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.87.0.
20 #![feature(unsigned_is_multiple_of)]
21 //
22 // Stable since Rust 1.89.0.
23 #![feature(generic_arg_infer)]
24 //
25 // Expected to become stable.
26 #![feature(arbitrary_self_types)]
27 #![feature(derive_coerce_pointee)]
28 //
29 // To be determined.
30 #![feature(used_with_arg)]
31 //
32 // `feature(file_with_nul)` is stable since Rust 1.92.0. Before Rust 1.89.0, it did not exist, so
33 // enable it conditionally.
34 #![cfg_attr(CONFIG_RUSTC_HAS_FILE_WITH_NUL, feature(file_with_nul))]
35 
36 // Ensure conditional compilation based on the kernel configuration works;
37 // otherwise we may silently break things like initcall handling.
38 #[cfg(not(CONFIG_RUST))]
39 compile_error!("Missing kernel configuration for conditional compilation");
40 
41 // Allow proc-macros to refer to `::kernel` inside the `kernel` crate (this crate).
42 extern crate self as kernel;
43 
44 pub use ffi;
45 
46 pub mod acpi;
47 pub mod alloc;
48 #[cfg(CONFIG_AUXILIARY_BUS)]
49 pub mod auxiliary;
50 pub mod bitfield;
51 pub mod bitmap;
52 pub mod bits;
53 #[cfg(CONFIG_BLOCK)]
54 pub mod block;
55 pub mod bug;
56 pub mod build_assert;
57 pub mod clk;
58 #[cfg(CONFIG_CONFIGFS_FS)]
59 pub mod configfs;
60 pub mod cpu;
61 #[cfg(CONFIG_CPU_FREQ)]
62 pub mod cpufreq;
63 pub mod cpumask;
64 pub mod cred;
65 pub mod debugfs;
66 pub mod device;
67 pub mod device_id;
68 pub mod devres;
69 pub mod dma;
70 pub mod driver;
71 #[cfg(CONFIG_DRM = "y")]
72 pub mod drm;
73 pub mod error;
74 pub mod faux;
75 #[cfg(CONFIG_RUST_FW_LOADER_ABSTRACTIONS)]
76 pub mod firmware;
77 pub mod fmt;
78 pub mod fs;
79 #[cfg(CONFIG_GPU_BUDDY = "y")]
80 pub mod gpu;
81 #[cfg(CONFIG_I2C = "y")]
82 pub mod i2c;
83 pub mod id_pool;
84 #[doc(hidden)]
85 pub mod impl_flags;
86 pub mod init;
87 pub mod interop;
88 pub mod interrupt;
89 pub mod io;
90 pub mod ioctl;
91 pub mod iommu;
92 pub mod iov;
93 pub mod irq;
94 pub mod jump_label;
95 #[cfg(CONFIG_KUNIT)]
96 pub mod kunit;
97 pub mod list;
98 pub mod maple_tree;
99 pub mod miscdevice;
100 pub mod mm;
101 pub mod module;
102 pub mod module_param;
103 #[cfg(CONFIG_NET)]
104 pub mod net;
105 pub mod num;
106 pub mod of;
107 #[cfg(CONFIG_PM_OPP)]
108 pub mod opp;
109 pub mod page;
110 #[cfg(CONFIG_PCI)]
111 pub mod pci;
112 pub mod pid_namespace;
113 pub mod platform;
114 pub mod prelude;
115 pub mod print;
116 pub mod processor;
117 pub mod ptr;
118 #[cfg(CONFIG_RUST_PWM_ABSTRACTIONS)]
119 pub mod pwm;
120 pub mod rbtree;
121 pub mod regulator;
122 pub mod revocable;
123 pub mod safety;
124 pub mod scatterlist;
125 pub mod security;
126 pub mod seq_file;
127 #[cfg(CONFIG_RUST_SERIAL_DEV_BUS_ABSTRACTIONS)]
128 pub mod serdev;
129 pub mod sizes;
130 #[cfg(CONFIG_SOC_BUS)]
131 pub mod soc;
132 #[doc(hidden)]
133 pub mod std_vendor;
134 pub mod str;
135 pub mod sync;
136 pub mod task;
137 pub mod time;
138 pub mod tracepoint;
139 pub mod transmute;
140 pub mod types;
141 pub mod uaccess;
142 #[cfg(CONFIG_USB = "y")]
143 pub mod usb;
144 pub mod workqueue;
145 pub mod xarray;
146 
147 #[doc(hidden)]
148 pub use bindings;
149 pub use macros;
150 pub use module::{
151     InPlaceModule,
152     Module,
153     ModuleMetadata,
154     ThisModule, //
155 };
156 pub use uapi;
157 
158 /// Prefix to appear before log messages printed from within the `kernel` crate.
159 const __LOG_PREFIX: &[u8] = b"rust_kernel\0";
160 
161 /// Dummy module type for `#[vtable]` `impl` blocks within the `kernel` crate (e.g. KUnit tests).
162 // The `allow` is needed since it may be unused (e.g. KUnit tests may be disabled).
163 #[allow(dead_code)]
164 struct LocalModule;
165 
166 impl ModuleMetadata for LocalModule {
167     const NAME: &'static str::CStr = c"rust_kernel";
168 
169     const THIS_MODULE: ThisModule = {
170         // SAFETY: `try_module_get`/`module_put` handle null module pointers gracefully.
171         unsafe { ThisModule::from_ptr(core::ptr::null_mut()) }
172     };
173 }
174 
175 #[cfg(not(testlib))]
176 #[panic_handler]
177 fn panic(info: &core::panic::PanicInfo<'_>) -> ! {
178     pr_emerg!("{}\n", info);
179     // SAFETY: FFI call.
180     unsafe { bindings::BUG() };
181 }
182 
183 /// Produces a pointer to an object from a pointer to one of its fields.
184 ///
185 /// If you encounter a type mismatch due to the [`Opaque`] type, then use [`Opaque::cast_into`] or
186 /// [`Opaque::cast_from`] to resolve the mismatch.
187 ///
188 /// [`Opaque`]: crate::types::Opaque
189 /// [`Opaque::cast_into`]: crate::types::Opaque::cast_into
190 /// [`Opaque::cast_from`]: crate::types::Opaque::cast_from
191 ///
192 /// # Safety
193 ///
194 /// The pointer passed to this macro, and the pointer returned by this macro, must both be in
195 /// bounds of the same allocation.
196 ///
197 /// # Examples
198 ///
199 /// ```
200 /// # use kernel::container_of;
201 /// struct Test {
202 ///     a: u64,
203 ///     b: u32,
204 /// }
205 ///
206 /// let test = Test { a: 10, b: 20 };
207 /// let b_ptr: *const _ = &test.b;
208 /// // SAFETY: The pointer points at the `b` field of a `Test`, so the resulting pointer will be
209 /// // in-bounds of the same allocation as `b_ptr`.
210 /// let test_alias = unsafe { container_of!(b_ptr, Test, b) };
211 /// assert!(core::ptr::eq(&test, test_alias));
212 /// ```
213 #[macro_export]
214 macro_rules! container_of {
215     ($field_ptr:expr, $Container:ty, $($fields:tt)*) => {{
216         let offset: usize = ::core::mem::offset_of!($Container, $($fields)*);
217         let field_ptr = $field_ptr;
218         let container_ptr = field_ptr.byte_sub(offset).cast::<$Container>();
219         $crate::assert_same_type(field_ptr, (&raw const (*container_ptr).$($fields)*).cast_mut());
220         container_ptr
221     }}
222 }
223 
224 /// Helper for [`container_of!`].
225 #[doc(hidden)]
226 pub fn assert_same_type<T>(_: T, _: T) {}
227 
228 /// Helper for `.rs.S` files.
229 #[doc(hidden)]
230 #[macro_export]
231 macro_rules! concat_literals {
232     ($( $asm:literal )* ) => {
233         ::core::concat!($($asm),*)
234     };
235 }
236 
237 /// Wrapper around `asm!` configured for use in the kernel.
238 ///
239 /// Uses a semicolon to avoid parsing ambiguities, even though this does not match native `asm!`
240 /// syntax.
241 // For x86, `asm!` uses intel syntax by default, but we want to use at&t syntax in the kernel.
242 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
243 #[macro_export]
244 macro_rules! asm {
245     ($($asm:expr),* ; $($rest:tt)*) => {
246         ::core::arch::asm!( $($asm)*, options(att_syntax), $($rest)* )
247     };
248 }
249 
250 /// Wrapper around `asm!` configured for use in the kernel.
251 ///
252 /// Uses a semicolon to avoid parsing ambiguities, even though this does not match native `asm!`
253 /// syntax.
254 // For non-x86 arches we just pass through to `asm!`.
255 #[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
256 #[macro_export]
257 macro_rules! asm {
258     ($($asm:expr),* ; $($rest:tt)*) => {
259         ::core::arch::asm!( $($asm)*, $($rest)* )
260     };
261 }
262 
263 /// Gets the C string file name of a [`Location`].
264 ///
265 /// If `Location::file_as_c_str()` is not available, returns a string that warns about it.
266 ///
267 /// [`Location`]: core::panic::Location
268 ///
269 /// # Examples
270 ///
271 /// ```
272 /// # use kernel::file_from_location;
273 ///
274 /// #[track_caller]
275 /// fn foo() {
276 ///     let caller = core::panic::Location::caller();
277 ///
278 ///     // Output:
279 ///     // - A path like "rust/kernel/example.rs" if `file_as_c_str()` is available.
280 ///     // - "<Location::file_as_c_str() not supported>" otherwise.
281 ///     let caller_file = file_from_location(caller);
282 ///
283 ///     // Prints out the message with caller's file name.
284 ///     pr_info!("foo() called in file {caller_file:?}\n");
285 ///
286 ///     # if cfg!(CONFIG_RUSTC_HAS_FILE_WITH_NUL) {
287 ///     #     assert_eq!(Ok(caller.file()), caller_file.to_str());
288 ///     # }
289 /// }
290 ///
291 /// # foo();
292 /// ```
293 #[inline]
294 pub fn file_from_location<'a>(loc: &'a core::panic::Location<'a>) -> &'a core::ffi::CStr {
295     #[cfg(CONFIG_RUSTC_HAS_FILE_AS_C_STR)]
296     {
297         loc.file_as_c_str()
298     }
299 
300     #[cfg(all(CONFIG_RUSTC_HAS_FILE_WITH_NUL, not(CONFIG_RUSTC_HAS_FILE_AS_C_STR)))]
301     {
302         loc.file_with_nul()
303     }
304 
305     #[cfg(not(CONFIG_RUSTC_HAS_FILE_WITH_NUL))]
306     {
307         let _ = loc;
308         c"<Location::file_as_c_str() not supported>"
309     }
310 }
311