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