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