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