xref: /linux/rust/kernel/lib.rs (revision d53ea977adf913a6e5024323e6b7e02326d4453c)
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 pub mod bits;
66 #[cfg(CONFIG_BLOCK)]
67 pub mod block;
68 pub mod bug;
69 #[doc(hidden)]
70 pub mod build_assert;
71 pub mod clk;
72 #[cfg(CONFIG_CONFIGFS_FS)]
73 pub mod configfs;
74 pub mod cpu;
75 #[cfg(CONFIG_CPU_FREQ)]
76 pub mod cpufreq;
77 pub mod cpumask;
78 pub mod cred;
79 pub mod debugfs;
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 irq;
97 pub mod jump_label;
98 #[cfg(CONFIG_KUNIT)]
99 pub mod kunit;
100 pub mod list;
101 pub mod miscdevice;
102 pub mod mm;
103 #[cfg(CONFIG_NET)]
104 pub mod net;
105 pub mod of;
106 #[cfg(CONFIG_PM_OPP)]
107 pub mod opp;
108 pub mod page;
109 #[cfg(CONFIG_PCI)]
110 pub mod pci;
111 pub mod pid_namespace;
112 pub mod platform;
113 pub mod prelude;
114 pub mod print;
115 pub mod processor;
116 pub mod rbtree;
117 pub mod regulator;
118 pub mod revocable;
119 pub mod security;
120 pub mod seq_file;
121 pub mod sizes;
122 mod static_assert;
123 #[doc(hidden)]
124 pub mod std_vendor;
125 pub mod str;
126 pub mod sync;
127 pub mod task;
128 pub mod time;
129 pub mod tracepoint;
130 pub mod transmute;
131 pub mod types;
132 pub mod uaccess;
133 pub mod workqueue;
134 pub mod xarray;
135 
136 #[doc(hidden)]
137 pub use bindings;
138 pub use macros;
139 pub use uapi;
140 
141 /// Prefix to appear before log messages printed from within the `kernel` crate.
142 const __LOG_PREFIX: &[u8] = b"rust_kernel\0";
143 
144 /// The top level entrypoint to implementing a kernel module.
145 ///
146 /// For any teardown or cleanup operations, your type may implement [`Drop`].
147 pub trait Module: Sized + Sync + Send {
148     /// Called at module initialization time.
149     ///
150     /// Use this method to perform whatever setup or registration your module
151     /// should do.
152     ///
153     /// Equivalent to the `module_init` macro in the C API.
154     fn init(module: &'static ThisModule) -> error::Result<Self>;
155 }
156 
157 /// A module that is pinned and initialised in-place.
158 pub trait InPlaceModule: Sync + Send {
159     /// Creates an initialiser for the module.
160     ///
161     /// It is called when the module is loaded.
162     fn init(module: &'static ThisModule) -> impl pin_init::PinInit<Self, error::Error>;
163 }
164 
165 impl<T: Module> InPlaceModule for T {
166     fn init(module: &'static ThisModule) -> impl pin_init::PinInit<Self, error::Error> {
167         let initer = move |slot: *mut Self| {
168             let m = <Self as Module>::init(module)?;
169 
170             // SAFETY: `slot` is valid for write per the contract with `pin_init_from_closure`.
171             unsafe { slot.write(m) };
172             Ok(())
173         };
174 
175         // SAFETY: On success, `initer` always fully initialises an instance of `Self`.
176         unsafe { pin_init::pin_init_from_closure(initer) }
177     }
178 }
179 
180 /// Metadata attached to a [`Module`] or [`InPlaceModule`].
181 pub trait ModuleMetadata {
182     /// The name of the module as specified in the `module!` macro.
183     const NAME: &'static crate::str::CStr;
184 }
185 
186 /// Equivalent to `THIS_MODULE` in the C API.
187 ///
188 /// C header: [`include/linux/init.h`](srctree/include/linux/init.h)
189 pub struct ThisModule(*mut bindings::module);
190 
191 // SAFETY: `THIS_MODULE` may be used from all threads within a module.
192 unsafe impl Sync for ThisModule {}
193 
194 impl ThisModule {
195     /// Creates a [`ThisModule`] given the `THIS_MODULE` pointer.
196     ///
197     /// # Safety
198     ///
199     /// The pointer must be equal to the right `THIS_MODULE`.
200     pub const unsafe fn from_ptr(ptr: *mut bindings::module) -> ThisModule {
201         ThisModule(ptr)
202     }
203 
204     /// Access the raw pointer for this module.
205     ///
206     /// It is up to the user to use it correctly.
207     pub const fn as_ptr(&self) -> *mut bindings::module {
208         self.0
209     }
210 }
211 
212 #[cfg(not(any(testlib, test)))]
213 #[panic_handler]
214 fn panic(info: &core::panic::PanicInfo<'_>) -> ! {
215     pr_emerg!("{}\n", info);
216     // SAFETY: FFI call.
217     unsafe { bindings::BUG() };
218 }
219 
220 /// Produces a pointer to an object from a pointer to one of its fields.
221 ///
222 /// If you encounter a type mismatch due to the [`Opaque`] type, then use [`Opaque::cast_into`] or
223 /// [`Opaque::cast_from`] to resolve the mismatch.
224 ///
225 /// [`Opaque`]: crate::types::Opaque
226 /// [`Opaque::cast_into`]: crate::types::Opaque::cast_into
227 /// [`Opaque::cast_from`]: crate::types::Opaque::cast_from
228 ///
229 /// # Safety
230 ///
231 /// The pointer passed to this macro, and the pointer returned by this macro, must both be in
232 /// bounds of the same allocation.
233 ///
234 /// # Examples
235 ///
236 /// ```
237 /// # use kernel::container_of;
238 /// struct Test {
239 ///     a: u64,
240 ///     b: u32,
241 /// }
242 ///
243 /// let test = Test { a: 10, b: 20 };
244 /// let b_ptr: *const _ = &test.b;
245 /// // SAFETY: The pointer points at the `b` field of a `Test`, so the resulting pointer will be
246 /// // in-bounds of the same allocation as `b_ptr`.
247 /// let test_alias = unsafe { container_of!(b_ptr, Test, b) };
248 /// assert!(core::ptr::eq(&test, test_alias));
249 /// ```
250 #[macro_export]
251 macro_rules! container_of {
252     ($field_ptr:expr, $Container:ty, $($fields:tt)*) => {{
253         let offset: usize = ::core::mem::offset_of!($Container, $($fields)*);
254         let field_ptr = $field_ptr;
255         let container_ptr = field_ptr.byte_sub(offset).cast::<$Container>();
256         $crate::assert_same_type(field_ptr, (&raw const (*container_ptr).$($fields)*).cast_mut());
257         container_ptr
258     }}
259 }
260 
261 /// Helper for [`container_of!`].
262 #[doc(hidden)]
263 pub fn assert_same_type<T>(_: T, _: T) {}
264 
265 /// Helper for `.rs.S` files.
266 #[doc(hidden)]
267 #[macro_export]
268 macro_rules! concat_literals {
269     ($( $asm:literal )* ) => {
270         ::core::concat!($($asm),*)
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 x86, `asm!` uses intel syntax by default, but we want to use at&t syntax in the kernel.
279 #[cfg(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)*, options(att_syntax), $($rest)* )
284     };
285 }
286 
287 /// Wrapper around `asm!` configured for use in the kernel.
288 ///
289 /// Uses a semicolon to avoid parsing ambiguities, even though this does not match native `asm!`
290 /// syntax.
291 // For non-x86 arches we just pass through to `asm!`.
292 #[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
293 #[macro_export]
294 macro_rules! asm {
295     ($($asm:expr),* ; $($rest:tt)*) => {
296         ::core::arch::asm!( $($asm)*, $($rest)* )
297     };
298 }
299 
300 /// Gets the C string file name of a [`Location`].
301 ///
302 /// If `Location::file_as_c_str()` is not available, returns a string that warns about it.
303 ///
304 /// [`Location`]: core::panic::Location
305 ///
306 /// # Examples
307 ///
308 /// ```
309 /// # use kernel::file_from_location;
310 ///
311 /// #[track_caller]
312 /// fn foo() {
313 ///     let caller = core::panic::Location::caller();
314 ///
315 ///     // Output:
316 ///     // - A path like "rust/kernel/example.rs" if `file_as_c_str()` is available.
317 ///     // - "<Location::file_as_c_str() not supported>" otherwise.
318 ///     let caller_file = file_from_location(caller);
319 ///
320 ///     // Prints out the message with caller's file name.
321 ///     pr_info!("foo() called in file {caller_file:?}\n");
322 ///
323 ///     # if cfg!(CONFIG_RUSTC_HAS_FILE_WITH_NUL) {
324 ///     #     assert_eq!(Ok(caller.file()), caller_file.to_str());
325 ///     # }
326 /// }
327 ///
328 /// # foo();
329 /// ```
330 #[inline]
331 pub fn file_from_location<'a>(loc: &'a core::panic::Location<'a>) -> &'a core::ffi::CStr {
332     #[cfg(CONFIG_RUSTC_HAS_FILE_AS_C_STR)]
333     {
334         loc.file_as_c_str()
335     }
336 
337     #[cfg(all(CONFIG_RUSTC_HAS_FILE_WITH_NUL, not(CONFIG_RUSTC_HAS_FILE_AS_C_STR)))]
338     {
339         loc.file_with_nul()
340     }
341 
342     #[cfg(not(CONFIG_RUSTC_HAS_FILE_WITH_NUL))]
343     {
344         let _ = loc;
345         c"<Location::file_as_c_str() not supported>"
346     }
347 }
348