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