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