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