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