xref: /linux/rust/kernel/lib.rs (revision b04d17062193dcc0fe5fc87adee5091319a482a0)
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 alloc;
55 #[cfg(CONFIG_BLOCK)]
56 pub mod block;
57 #[doc(hidden)]
58 pub mod build_assert;
59 pub mod cred;
60 pub mod device;
61 pub mod device_id;
62 pub mod devres;
63 pub mod dma;
64 pub mod driver;
65 pub mod error;
66 pub mod faux;
67 #[cfg(CONFIG_RUST_FW_LOADER_ABSTRACTIONS)]
68 pub mod firmware;
69 pub mod fs;
70 pub mod init;
71 pub mod io;
72 pub mod ioctl;
73 pub mod jump_label;
74 #[cfg(CONFIG_KUNIT)]
75 pub mod kunit;
76 pub mod list;
77 pub mod miscdevice;
78 #[cfg(CONFIG_NET)]
79 pub mod net;
80 pub mod of;
81 pub mod page;
82 #[cfg(CONFIG_PCI)]
83 pub mod pci;
84 pub mod pid_namespace;
85 pub mod platform;
86 pub mod prelude;
87 pub mod print;
88 pub mod rbtree;
89 pub mod revocable;
90 pub mod security;
91 pub mod seq_file;
92 pub mod sizes;
93 mod static_assert;
94 #[doc(hidden)]
95 pub mod std_vendor;
96 pub mod str;
97 pub mod sync;
98 pub mod task;
99 pub mod time;
100 pub mod tracepoint;
101 pub mod transmute;
102 pub mod types;
103 pub mod uaccess;
104 pub mod workqueue;
105 pub mod xarray;
106 
107 #[doc(hidden)]
108 pub use bindings;
109 pub use macros;
110 pub use uapi;
111 
112 /// Prefix to appear before log messages printed from within the `kernel` crate.
113 const __LOG_PREFIX: &[u8] = b"rust_kernel\0";
114 
115 /// The top level entrypoint to implementing a kernel module.
116 ///
117 /// For any teardown or cleanup operations, your type may implement [`Drop`].
118 pub trait Module: Sized + Sync + Send {
119     /// Called at module initialization time.
120     ///
121     /// Use this method to perform whatever setup or registration your module
122     /// should do.
123     ///
124     /// Equivalent to the `module_init` macro in the C API.
125     fn init(module: &'static ThisModule) -> error::Result<Self>;
126 }
127 
128 /// A module that is pinned and initialised in-place.
129 pub trait InPlaceModule: Sync + Send {
130     /// Creates an initialiser for the module.
131     ///
132     /// It is called when the module is loaded.
133     fn init(module: &'static ThisModule) -> impl pin_init::PinInit<Self, error::Error>;
134 }
135 
136 impl<T: Module> InPlaceModule for T {
137     fn init(module: &'static ThisModule) -> impl pin_init::PinInit<Self, error::Error> {
138         let initer = move |slot: *mut Self| {
139             let m = <Self as Module>::init(module)?;
140 
141             // SAFETY: `slot` is valid for write per the contract with `pin_init_from_closure`.
142             unsafe { slot.write(m) };
143             Ok(())
144         };
145 
146         // SAFETY: On success, `initer` always fully initialises an instance of `Self`.
147         unsafe { pin_init::pin_init_from_closure(initer) }
148     }
149 }
150 
151 /// Metadata attached to a [`Module`] or [`InPlaceModule`].
152 pub trait ModuleMetadata {
153     /// The name of the module as specified in the `module!` macro.
154     const NAME: &'static crate::str::CStr;
155 }
156 
157 /// Equivalent to `THIS_MODULE` in the C API.
158 ///
159 /// C header: [`include/linux/init.h`](srctree/include/linux/init.h)
160 pub struct ThisModule(*mut bindings::module);
161 
162 // SAFETY: `THIS_MODULE` may be used from all threads within a module.
163 unsafe impl Sync for ThisModule {}
164 
165 impl ThisModule {
166     /// Creates a [`ThisModule`] given the `THIS_MODULE` pointer.
167     ///
168     /// # Safety
169     ///
170     /// The pointer must be equal to the right `THIS_MODULE`.
171     pub const unsafe fn from_ptr(ptr: *mut bindings::module) -> ThisModule {
172         ThisModule(ptr)
173     }
174 
175     /// Access the raw pointer for this module.
176     ///
177     /// It is up to the user to use it correctly.
178     pub const fn as_ptr(&self) -> *mut bindings::module {
179         self.0
180     }
181 }
182 
183 #[cfg(not(any(testlib, test)))]
184 #[panic_handler]
185 fn panic(info: &core::panic::PanicInfo<'_>) -> ! {
186     pr_emerg!("{}\n", info);
187     // SAFETY: FFI call.
188     unsafe { bindings::BUG() };
189 }
190 
191 /// Produces a pointer to an object from a pointer to one of its fields.
192 ///
193 /// # Safety
194 ///
195 /// The pointer passed to this macro, and the pointer returned by this macro, must both be in
196 /// bounds of the same allocation.
197 ///
198 /// # Examples
199 ///
200 /// ```
201 /// # use kernel::container_of;
202 /// struct Test {
203 ///     a: u64,
204 ///     b: u32,
205 /// }
206 ///
207 /// let test = Test { a: 10, b: 20 };
208 /// let b_ptr = &test.b;
209 /// // SAFETY: The pointer points at the `b` field of a `Test`, so the resulting pointer will be
210 /// // in-bounds of the same allocation as `b_ptr`.
211 /// let test_alias = unsafe { container_of!(b_ptr, Test, b) };
212 /// assert!(core::ptr::eq(&test, test_alias));
213 /// ```
214 #[macro_export]
215 macro_rules! container_of {
216     ($ptr:expr, $type:ty, $($f:tt)*) => {{
217         let ptr = $ptr as *const _ as *const u8;
218         let offset: usize = ::core::mem::offset_of!($type, $($f)*);
219         ptr.sub(offset) as *const $type
220     }}
221 }
222 
223 /// Helper for `.rs.S` files.
224 #[doc(hidden)]
225 #[macro_export]
226 macro_rules! concat_literals {
227     ($( $asm:literal )* ) => {
228         ::core::concat!($($asm),*)
229     };
230 }
231 
232 /// Wrapper around `asm!` configured for use in the kernel.
233 ///
234 /// Uses a semicolon to avoid parsing ambiguities, even though this does not match native `asm!`
235 /// syntax.
236 // For x86, `asm!` uses intel syntax by default, but we want to use at&t syntax in the kernel.
237 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
238 #[macro_export]
239 macro_rules! asm {
240     ($($asm:expr),* ; $($rest:tt)*) => {
241         ::core::arch::asm!( $($asm)*, options(att_syntax), $($rest)* )
242     };
243 }
244 
245 /// Wrapper around `asm!` configured for use in the kernel.
246 ///
247 /// Uses a semicolon to avoid parsing ambiguities, even though this does not match native `asm!`
248 /// syntax.
249 // For non-x86 arches we just pass through to `asm!`.
250 #[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
251 #[macro_export]
252 macro_rules! asm {
253     ($($asm:expr),* ; $($rest:tt)*) => {
254         ::core::arch::asm!( $($asm)*, $($rest)* )
255     };
256 }
257