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