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