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