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