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