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