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