~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

TOMOYO Linux Cross Reference
Linux/rust/kernel/init.rs

Version: ~ [ linux-6.12-rc7 ] ~ [ linux-6.11.7 ] ~ [ linux-6.10.14 ] ~ [ linux-6.9.12 ] ~ [ linux-6.8.12 ] ~ [ linux-6.7.12 ] ~ [ linux-6.6.60 ] ~ [ linux-6.5.13 ] ~ [ linux-6.4.16 ] ~ [ linux-6.3.13 ] ~ [ linux-6.2.16 ] ~ [ linux-6.1.116 ] ~ [ linux-6.0.19 ] ~ [ linux-5.19.17 ] ~ [ linux-5.18.19 ] ~ [ linux-5.17.15 ] ~ [ linux-5.16.20 ] ~ [ linux-5.15.171 ] ~ [ linux-5.14.21 ] ~ [ linux-5.13.19 ] ~ [ linux-5.12.19 ] ~ [ linux-5.11.22 ] ~ [ linux-5.10.229 ] ~ [ linux-5.9.16 ] ~ [ linux-5.8.18 ] ~ [ linux-5.7.19 ] ~ [ linux-5.6.19 ] ~ [ linux-5.5.19 ] ~ [ linux-5.4.285 ] ~ [ linux-5.3.18 ] ~ [ linux-5.2.21 ] ~ [ linux-5.1.21 ] ~ [ linux-5.0.21 ] ~ [ linux-4.20.17 ] ~ [ linux-4.19.323 ] ~ [ linux-4.18.20 ] ~ [ linux-4.17.19 ] ~ [ linux-4.16.18 ] ~ [ linux-4.15.18 ] ~ [ linux-4.14.336 ] ~ [ linux-4.13.16 ] ~ [ linux-4.12.14 ] ~ [ linux-4.11.12 ] ~ [ linux-4.10.17 ] ~ [ linux-4.9.337 ] ~ [ linux-4.4.302 ] ~ [ linux-3.10.108 ] ~ [ linux-2.6.32.71 ] ~ [ linux-2.6.0 ] ~ [ linux-2.4.37.11 ] ~ [ unix-v6-master ] ~ [ ccs-tools-1.8.12 ] ~ [ policy-sample ] ~
Architecture: ~ [ i386 ] ~ [ alpha ] ~ [ m68k ] ~ [ mips ] ~ [ ppc ] ~ [ sparc ] ~ [ sparc64 ] ~

Diff markup

Differences between /rust/kernel/init.rs (Version linux-6.12-rc7) and /rust/kernel/init.rs (Version linux-6.7.12)


  1 // SPDX-License-Identifier: Apache-2.0 OR MIT       1 // SPDX-License-Identifier: Apache-2.0 OR MIT
  2                                                     2 
  3 //! API to safely and fallibly initialize pinn      3 //! API to safely and fallibly initialize pinned `struct`s using in-place constructors.
  4 //!                                                 4 //!
  5 //! It also allows in-place initialization of       5 //! It also allows in-place initialization of big `struct`s that would otherwise produce a stack
  6 //! overflow.                                       6 //! overflow.
  7 //!                                                 7 //!
  8 //! Most `struct`s from the [`sync`] module ne      8 //! Most `struct`s from the [`sync`] module need to be pinned, because they contain self-referential
  9 //! `struct`s from C. [Pinning][pinning] is Ru      9 //! `struct`s from C. [Pinning][pinning] is Rust's way of ensuring data does not move.
 10 //!                                                10 //!
 11 //! # Overview                                     11 //! # Overview
 12 //!                                                12 //!
 13 //! To initialize a `struct` with an in-place      13 //! To initialize a `struct` with an in-place constructor you will need two things:
 14 //! - an in-place constructor,                     14 //! - an in-place constructor,
 15 //! - a memory location that can hold your `st     15 //! - a memory location that can hold your `struct` (this can be the [stack], an [`Arc<T>`],
 16 //!   [`UniqueArc<T>`], [`Box<T>`] or any othe     16 //!   [`UniqueArc<T>`], [`Box<T>`] or any other smart pointer that implements [`InPlaceInit`]).
 17 //!                                                17 //!
 18 //! To get an in-place constructor there are g     18 //! To get an in-place constructor there are generally three options:
 19 //! - directly creating an in-place constructo     19 //! - directly creating an in-place constructor using the [`pin_init!`] macro,
 20 //! - a custom function/macro returning an in-     20 //! - a custom function/macro returning an in-place constructor provided by someone else,
 21 //! - using the unsafe function [`pin_init_fro     21 //! - using the unsafe function [`pin_init_from_closure()`] to manually create an initializer.
 22 //!                                                22 //!
 23 //! Aside from pinned initialization, this API     23 //! Aside from pinned initialization, this API also supports in-place construction without pinning,
 24 //! the macros/types/functions are generally n     24 //! the macros/types/functions are generally named like the pinned variants without the `pin`
 25 //! prefix.                                        25 //! prefix.
 26 //!                                                26 //!
 27 //! # Examples                                     27 //! # Examples
 28 //!                                                28 //!
 29 //! ## Using the [`pin_init!`] macro               29 //! ## Using the [`pin_init!`] macro
 30 //!                                                30 //!
 31 //! If you want to use [`PinInit`], then you w     31 //! If you want to use [`PinInit`], then you will have to annotate your `struct` with
 32 //! `#[`[`pin_data`]`]`. It is a macro that us     32 //! `#[`[`pin_data`]`]`. It is a macro that uses `#[pin]` as a marker for
 33 //! [structurally pinned fields]. After doing      33 //! [structurally pinned fields]. After doing this, you can then create an in-place constructor via
 34 //! [`pin_init!`]. The syntax is almost the sa     34 //! [`pin_init!`]. The syntax is almost the same as normal `struct` initializers. The difference is
 35 //! that you need to write `<-` instead of `:`     35 //! that you need to write `<-` instead of `:` for fields that you want to initialize in-place.
 36 //!                                                36 //!
 37 //! ```rust                                        37 //! ```rust
 38 //! # #![allow(clippy::disallowed_names)]          38 //! # #![allow(clippy::disallowed_names)]
 39 //! use kernel::sync::{new_mutex, Mutex};      !!  39 //! use kernel::{prelude::*, sync::Mutex, new_mutex};
 40 //! # use core::pin::Pin;                          40 //! # use core::pin::Pin;
 41 //! #[pin_data]                                    41 //! #[pin_data]
 42 //! struct Foo {                                   42 //! struct Foo {
 43 //!     #[pin]                                     43 //!     #[pin]
 44 //!     a: Mutex<usize>,                           44 //!     a: Mutex<usize>,
 45 //!     b: u32,                                    45 //!     b: u32,
 46 //! }                                              46 //! }
 47 //!                                                47 //!
 48 //! let foo = pin_init!(Foo {                      48 //! let foo = pin_init!(Foo {
 49 //!     a <- new_mutex!(42, "Foo::a"),             49 //!     a <- new_mutex!(42, "Foo::a"),
 50 //!     b: 24,                                     50 //!     b: 24,
 51 //! });                                            51 //! });
 52 //! ```                                            52 //! ```
 53 //!                                                53 //!
 54 //! `foo` now is of the type [`impl PinInit<Fo     54 //! `foo` now is of the type [`impl PinInit<Foo>`]. We can now use any smart pointer that we like
 55 //! (or just the stack) to actually initialize     55 //! (or just the stack) to actually initialize a `Foo`:
 56 //!                                                56 //!
 57 //! ```rust                                        57 //! ```rust
 58 //! # #![allow(clippy::disallowed_names)]          58 //! # #![allow(clippy::disallowed_names)]
 59 //! # use kernel::sync::{new_mutex, Mutex};    !!  59 //! # use kernel::{prelude::*, sync::Mutex, new_mutex};
 60 //! # use core::pin::Pin;                          60 //! # use core::pin::Pin;
 61 //! # #[pin_data]                                  61 //! # #[pin_data]
 62 //! # struct Foo {                                 62 //! # struct Foo {
 63 //! #     #[pin]                                   63 //! #     #[pin]
 64 //! #     a: Mutex<usize>,                         64 //! #     a: Mutex<usize>,
 65 //! #     b: u32,                                  65 //! #     b: u32,
 66 //! # }                                            66 //! # }
 67 //! # let foo = pin_init!(Foo {                    67 //! # let foo = pin_init!(Foo {
 68 //! #     a <- new_mutex!(42, "Foo::a"),           68 //! #     a <- new_mutex!(42, "Foo::a"),
 69 //! #     b: 24,                                   69 //! #     b: 24,
 70 //! # });                                          70 //! # });
 71 //! let foo: Result<Pin<Box<Foo>>> = Box::pin_ !!  71 //! let foo: Result<Pin<Box<Foo>>> = Box::pin_init(foo);
 72 //! ```                                            72 //! ```
 73 //!                                                73 //!
 74 //! For more information see the [`pin_init!`]     74 //! For more information see the [`pin_init!`] macro.
 75 //!                                                75 //!
 76 //! ## Using a custom function/macro that retu     76 //! ## Using a custom function/macro that returns an initializer
 77 //!                                                77 //!
 78 //! Many types from the kernel supply a functi     78 //! Many types from the kernel supply a function/macro that returns an initializer, because the
 79 //! above method only works for types where yo     79 //! above method only works for types where you can access the fields.
 80 //!                                                80 //!
 81 //! ```rust                                        81 //! ```rust
 82 //! # use kernel::sync::{new_mutex, Arc, Mutex !!  82 //! # use kernel::{new_mutex, sync::{Arc, Mutex}};
 83 //! let mtx: Result<Arc<Mutex<usize>>> =       !!  83 //! let mtx: Result<Arc<Mutex<usize>>> = Arc::pin_init(new_mutex!(42, "example::mtx"));
 84 //!     Arc::pin_init(new_mutex!(42, "example: << 
 85 //! ```                                            84 //! ```
 86 //!                                                85 //!
 87 //! To declare an init macro/function you just     86 //! To declare an init macro/function you just return an [`impl PinInit<T, E>`]:
 88 //!                                                87 //!
 89 //! ```rust                                        88 //! ```rust
 90 //! # #![allow(clippy::disallowed_names)]          89 //! # #![allow(clippy::disallowed_names)]
 91 //! # use kernel::{sync::Mutex, new_mutex, ini !!  90 //! # use kernel::{sync::Mutex, prelude::*, new_mutex, init::PinInit, try_pin_init};
 92 //! #[pin_data]                                    91 //! #[pin_data]
 93 //! struct DriverData {                            92 //! struct DriverData {
 94 //!     #[pin]                                     93 //!     #[pin]
 95 //!     status: Mutex<i32>,                        94 //!     status: Mutex<i32>,
 96 //!     buffer: Box<[u8; 1_000_000]>,              95 //!     buffer: Box<[u8; 1_000_000]>,
 97 //! }                                              96 //! }
 98 //!                                                97 //!
 99 //! impl DriverData {                              98 //! impl DriverData {
100 //!     fn new() -> impl PinInit<Self, Error>      99 //!     fn new() -> impl PinInit<Self, Error> {
101 //!         try_pin_init!(Self {                  100 //!         try_pin_init!(Self {
102 //!             status <- new_mutex!(0, "Drive    101 //!             status <- new_mutex!(0, "DriverData::status"),
103 //!             buffer: Box::init(kernel::init !! 102 //!             buffer: Box::init(kernel::init::zeroed())?,
104 //!         })                                    103 //!         })
105 //!     }                                         104 //!     }
106 //! }                                             105 //! }
107 //! ```                                           106 //! ```
108 //!                                               107 //!
109 //! ## Manual creation of an initializer          108 //! ## Manual creation of an initializer
110 //!                                               109 //!
111 //! Often when working with primitives the pre    110 //! Often when working with primitives the previous approaches are not sufficient. That is where
112 //! [`pin_init_from_closure()`] comes in. This    111 //! [`pin_init_from_closure()`] comes in. This `unsafe` function allows you to create a
113 //! [`impl PinInit<T, E>`] directly from a clo    112 //! [`impl PinInit<T, E>`] directly from a closure. Of course you have to ensure that the closure
114 //! actually does the initialization in the co    113 //! actually does the initialization in the correct way. Here are the things to look out for
115 //! (we are calling the parameter to the closu    114 //! (we are calling the parameter to the closure `slot`):
116 //! - when the closure returns `Ok(())`, then     115 //! - when the closure returns `Ok(())`, then it has completed the initialization successfully, so
117 //!   `slot` now contains a valid bit pattern     116 //!   `slot` now contains a valid bit pattern for the type `T`,
118 //! - when the closure returns `Err(e)`, then     117 //! - when the closure returns `Err(e)`, then the caller may deallocate the memory at `slot`, so
119 //!   you need to take care to clean up anythi    118 //!   you need to take care to clean up anything if your initialization fails mid-way,
120 //! - you may assume that `slot` will stay pin    119 //! - you may assume that `slot` will stay pinned even after the closure returns until `drop` of
121 //!   `slot` gets called.                         120 //!   `slot` gets called.
122 //!                                               121 //!
123 //! ```rust                                       122 //! ```rust
124 //! # #![allow(unreachable_pub, clippy::disall    123 //! # #![allow(unreachable_pub, clippy::disallowed_names)]
125 //! use kernel::{init, types::Opaque};         !! 124 //! use kernel::{prelude::*, init, types::Opaque};
126 //! use core::{ptr::addr_of_mut, marker::Phant    125 //! use core::{ptr::addr_of_mut, marker::PhantomPinned, pin::Pin};
127 //! # mod bindings {                              126 //! # mod bindings {
128 //! #     #![allow(non_camel_case_types)]         127 //! #     #![allow(non_camel_case_types)]
129 //! #     pub struct foo;                         128 //! #     pub struct foo;
130 //! #     pub unsafe fn init_foo(_ptr: *mut fo    129 //! #     pub unsafe fn init_foo(_ptr: *mut foo) {}
131 //! #     pub unsafe fn destroy_foo(_ptr: *mut    130 //! #     pub unsafe fn destroy_foo(_ptr: *mut foo) {}
132 //! #     pub unsafe fn enable_foo(_ptr: *mut     131 //! #     pub unsafe fn enable_foo(_ptr: *mut foo, _flags: u32) -> i32 { 0 }
133 //! # }                                           132 //! # }
134 //! # // `Error::from_errno` is `pub(crate)` i    133 //! # // `Error::from_errno` is `pub(crate)` in the `kernel` crate, thus provide a workaround.
135 //! # trait FromErrno {                           134 //! # trait FromErrno {
136 //! #     fn from_errno(errno: core::ffi::c_in    135 //! #     fn from_errno(errno: core::ffi::c_int) -> Error {
137 //! #         // Dummy error that can be const    136 //! #         // Dummy error that can be constructed outside the `kernel` crate.
138 //! #         Error::from(core::fmt::Error)       137 //! #         Error::from(core::fmt::Error)
139 //! #     }                                       138 //! #     }
140 //! # }                                           139 //! # }
141 //! # impl FromErrno for Error {}                 140 //! # impl FromErrno for Error {}
142 //! /// # Invariants                              141 //! /// # Invariants
143 //! ///                                           142 //! ///
144 //! /// `foo` is always initialized               143 //! /// `foo` is always initialized
145 //! #[pin_data(PinnedDrop)]                       144 //! #[pin_data(PinnedDrop)]
146 //! pub struct RawFoo {                           145 //! pub struct RawFoo {
147 //!     #[pin]                                    146 //!     #[pin]
148 //!     foo: Opaque<bindings::foo>,               147 //!     foo: Opaque<bindings::foo>,
149 //!     #[pin]                                    148 //!     #[pin]
150 //!     _p: PhantomPinned,                        149 //!     _p: PhantomPinned,
151 //! }                                             150 //! }
152 //!                                               151 //!
153 //! impl RawFoo {                                 152 //! impl RawFoo {
154 //!     pub fn new(flags: u32) -> impl PinInit    153 //!     pub fn new(flags: u32) -> impl PinInit<Self, Error> {
155 //!         // SAFETY:                            154 //!         // SAFETY:
156 //!         // - when the closure returns `Ok(    155 //!         // - when the closure returns `Ok(())`, then it has successfully initialized and
157 //!         //   enabled `foo`,                   156 //!         //   enabled `foo`,
158 //!         // - when it returns `Err(e)`, the    157 //!         // - when it returns `Err(e)`, then it has cleaned up before
159 //!         unsafe {                              158 //!         unsafe {
160 //!             init::pin_init_from_closure(mo    159 //!             init::pin_init_from_closure(move |slot: *mut Self| {
161 //!                 // `slot` contains uninit     160 //!                 // `slot` contains uninit memory, avoid creating a reference.
162 //!                 let foo = addr_of_mut!((*s    161 //!                 let foo = addr_of_mut!((*slot).foo);
163 //!                                               162 //!
164 //!                 // Initialize the `foo`       163 //!                 // Initialize the `foo`
165 //!                 bindings::init_foo(Opaque:    164 //!                 bindings::init_foo(Opaque::raw_get(foo));
166 //!                                               165 //!
167 //!                 // Try to enable it.          166 //!                 // Try to enable it.
168 //!                 let err = bindings::enable    167 //!                 let err = bindings::enable_foo(Opaque::raw_get(foo), flags);
169 //!                 if err != 0 {                 168 //!                 if err != 0 {
170 //!                     // Enabling has failed    169 //!                     // Enabling has failed, first clean up the foo and then return the error.
171 //!                     bindings::destroy_foo(    170 //!                     bindings::destroy_foo(Opaque::raw_get(foo));
172 //!                     return Err(Error::from    171 //!                     return Err(Error::from_errno(err));
173 //!                 }                             172 //!                 }
174 //!                                               173 //!
175 //!                 // All fields of `RawFoo`     174 //!                 // All fields of `RawFoo` have been initialized, since `_p` is a ZST.
176 //!                 Ok(())                        175 //!                 Ok(())
177 //!             })                                176 //!             })
178 //!         }                                     177 //!         }
179 //!     }                                         178 //!     }
180 //! }                                             179 //! }
181 //!                                               180 //!
182 //! #[pinned_drop]                                181 //! #[pinned_drop]
183 //! impl PinnedDrop for RawFoo {                  182 //! impl PinnedDrop for RawFoo {
184 //!     fn drop(self: Pin<&mut Self>) {           183 //!     fn drop(self: Pin<&mut Self>) {
185 //!         // SAFETY: Since `foo` is initiali    184 //!         // SAFETY: Since `foo` is initialized, destroying is safe.
186 //!         unsafe { bindings::destroy_foo(sel    185 //!         unsafe { bindings::destroy_foo(self.foo.get()) };
187 //!     }                                         186 //!     }
188 //! }                                             187 //! }
189 //! ```                                           188 //! ```
190 //!                                               189 //!
191 //! For the special case where initializing a     190 //! For the special case where initializing a field is a single FFI-function call that cannot fail,
192 //! there exist the helper function [`Opaque::    191 //! there exist the helper function [`Opaque::ffi_init`]. This function initialize a single
193 //! [`Opaque`] field by just delegating to the    192 //! [`Opaque`] field by just delegating to the supplied closure. You can use these in combination
194 //! with [`pin_init!`].                           193 //! with [`pin_init!`].
195 //!                                               194 //!
196 //! For more information on how to use [`pin_i    195 //! For more information on how to use [`pin_init_from_closure()`], take a look at the uses inside
197 //! the `kernel` crate. The [`sync`] module is    196 //! the `kernel` crate. The [`sync`] module is a good starting point.
198 //!                                               197 //!
199 //! [`sync`]: kernel::sync                        198 //! [`sync`]: kernel::sync
200 //! [pinning]: https://doc.rust-lang.org/std/p    199 //! [pinning]: https://doc.rust-lang.org/std/pin/index.html
201 //! [structurally pinned fields]:                 200 //! [structurally pinned fields]:
202 //!     https://doc.rust-lang.org/std/pin/inde    201 //!     https://doc.rust-lang.org/std/pin/index.html#pinning-is-structural-for-field
203 //! [stack]: crate::stack_pin_init                202 //! [stack]: crate::stack_pin_init
204 //! [`Arc<T>`]: crate::sync::Arc                  203 //! [`Arc<T>`]: crate::sync::Arc
205 //! [`impl PinInit<Foo>`]: PinInit                204 //! [`impl PinInit<Foo>`]: PinInit
206 //! [`impl PinInit<T, E>`]: PinInit               205 //! [`impl PinInit<T, E>`]: PinInit
207 //! [`impl Init<T, E>`]: Init                     206 //! [`impl Init<T, E>`]: Init
208 //! [`Opaque`]: kernel::types::Opaque             207 //! [`Opaque`]: kernel::types::Opaque
209 //! [`Opaque::ffi_init`]: kernel::types::Opaqu    208 //! [`Opaque::ffi_init`]: kernel::types::Opaque::ffi_init
210 //! [`pin_data`]: ::macros::pin_data              209 //! [`pin_data`]: ::macros::pin_data
211 //! [`pin_init!`]: crate::pin_init!               210 //! [`pin_init!`]: crate::pin_init!
212                                                   211 
213 use crate::{                                      212 use crate::{
214     alloc::{box_ext::BoxExt, AllocError, Flags << 
215     error::{self, Error},                         213     error::{self, Error},
216     sync::Arc,                                 << 
217     sync::UniqueArc,                              214     sync::UniqueArc,
218     types::{Opaque, ScopeGuard},                  215     types::{Opaque, ScopeGuard},
219 };                                                216 };
220 use alloc::boxed::Box;                            217 use alloc::boxed::Box;
221 use core::{                                       218 use core::{
                                                   >> 219     alloc::AllocError,
222     cell::UnsafeCell,                             220     cell::UnsafeCell,
223     convert::Infallible,                          221     convert::Infallible,
224     marker::PhantomData,                          222     marker::PhantomData,
225     mem::MaybeUninit,                             223     mem::MaybeUninit,
226     num::*,                                       224     num::*,
227     pin::Pin,                                     225     pin::Pin,
228     ptr::{self, NonNull},                         226     ptr::{self, NonNull},
229 };                                                227 };
230                                                   228 
231 #[doc(hidden)]                                    229 #[doc(hidden)]
232 pub mod __internal;                               230 pub mod __internal;
233 #[doc(hidden)]                                    231 #[doc(hidden)]
234 pub mod macros;                                   232 pub mod macros;
235                                                   233 
236 /// Initialize and pin a type directly on the     234 /// Initialize and pin a type directly on the stack.
237 ///                                               235 ///
238 /// # Examples                                    236 /// # Examples
239 ///                                               237 ///
240 /// ```rust                                       238 /// ```rust
241 /// # #![allow(clippy::disallowed_names)]         239 /// # #![allow(clippy::disallowed_names)]
242 /// # use kernel::{init, macros::pin_data, pin    240 /// # use kernel::{init, macros::pin_data, pin_init, stack_pin_init, init::*, sync::Mutex, new_mutex};
243 /// # use core::pin::Pin;                         241 /// # use core::pin::Pin;
244 /// #[pin_data]                                   242 /// #[pin_data]
245 /// struct Foo {                                  243 /// struct Foo {
246 ///     #[pin]                                    244 ///     #[pin]
247 ///     a: Mutex<usize>,                          245 ///     a: Mutex<usize>,
248 ///     b: Bar,                                   246 ///     b: Bar,
249 /// }                                             247 /// }
250 ///                                               248 ///
251 /// #[pin_data]                                   249 /// #[pin_data]
252 /// struct Bar {                                  250 /// struct Bar {
253 ///     x: u32,                                   251 ///     x: u32,
254 /// }                                             252 /// }
255 ///                                               253 ///
256 /// stack_pin_init!(let foo = pin_init!(Foo {     254 /// stack_pin_init!(let foo = pin_init!(Foo {
257 ///     a <- new_mutex!(42),                      255 ///     a <- new_mutex!(42),
258 ///     b: Bar {                                  256 ///     b: Bar {
259 ///         x: 64,                                257 ///         x: 64,
260 ///     },                                        258 ///     },
261 /// }));                                          259 /// }));
262 /// let foo: Pin<&mut Foo> = foo;                 260 /// let foo: Pin<&mut Foo> = foo;
263 /// pr_info!("a: {}", &*foo.a.lock());            261 /// pr_info!("a: {}", &*foo.a.lock());
264 /// ```                                           262 /// ```
265 ///                                               263 ///
266 /// # Syntax                                      264 /// # Syntax
267 ///                                               265 ///
268 /// A normal `let` binding with optional type     266 /// A normal `let` binding with optional type annotation. The expression is expected to implement
269 /// [`PinInit`]/[`Init`] with the error type [    267 /// [`PinInit`]/[`Init`] with the error type [`Infallible`]. If you want to use a different error
270 /// type, then use [`stack_try_pin_init!`].       268 /// type, then use [`stack_try_pin_init!`].
271 ///                                               269 ///
272 /// [`stack_try_pin_init!`]: crate::stack_try_    270 /// [`stack_try_pin_init!`]: crate::stack_try_pin_init!
273 #[macro_export]                                   271 #[macro_export]
274 macro_rules! stack_pin_init {                     272 macro_rules! stack_pin_init {
275     (let $var:ident $(: $t:ty)? = $val:expr) =    273     (let $var:ident $(: $t:ty)? = $val:expr) => {
276         let val = $val;                           274         let val = $val;
277         let mut $var = ::core::pin::pin!($crat    275         let mut $var = ::core::pin::pin!($crate::init::__internal::StackInit$(::<$t>)?::uninit());
278         let mut $var = match $crate::init::__i    276         let mut $var = match $crate::init::__internal::StackInit::init($var, val) {
279             Ok(res) => res,                       277             Ok(res) => res,
280             Err(x) => {                           278             Err(x) => {
281                 let x: ::core::convert::Infall    279                 let x: ::core::convert::Infallible = x;
282                 match x {}                        280                 match x {}
283             }                                     281             }
284         };                                        282         };
285     };                                            283     };
286 }                                                 284 }
287                                                   285 
288 /// Initialize and pin a type directly on the     286 /// Initialize and pin a type directly on the stack.
289 ///                                               287 ///
290 /// # Examples                                    288 /// # Examples
291 ///                                               289 ///
292 /// ```rust,ignore                                290 /// ```rust,ignore
293 /// # #![allow(clippy::disallowed_names)]         291 /// # #![allow(clippy::disallowed_names)]
294 /// # use kernel::{init, pin_init, stack_try_p    292 /// # use kernel::{init, pin_init, stack_try_pin_init, init::*, sync::Mutex, new_mutex};
295 /// # use macros::pin_data;                       293 /// # use macros::pin_data;
296 /// # use core::{alloc::AllocError, pin::Pin};    294 /// # use core::{alloc::AllocError, pin::Pin};
297 /// #[pin_data]                                   295 /// #[pin_data]
298 /// struct Foo {                                  296 /// struct Foo {
299 ///     #[pin]                                    297 ///     #[pin]
300 ///     a: Mutex<usize>,                          298 ///     a: Mutex<usize>,
301 ///     b: Box<Bar>,                              299 ///     b: Box<Bar>,
302 /// }                                             300 /// }
303 ///                                               301 ///
304 /// struct Bar {                                  302 /// struct Bar {
305 ///     x: u32,                                   303 ///     x: u32,
306 /// }                                             304 /// }
307 ///                                               305 ///
308 /// stack_try_pin_init!(let foo: Result<Pin<&m    306 /// stack_try_pin_init!(let foo: Result<Pin<&mut Foo>, AllocError> = pin_init!(Foo {
309 ///     a <- new_mutex!(42),                      307 ///     a <- new_mutex!(42),
310 ///     b: Box::new(Bar {                      !! 308 ///     b: Box::try_new(Bar {
311 ///         x: 64,                                309 ///         x: 64,
312 ///     }, GFP_KERNEL)?,                       !! 310 ///     })?,
313 /// }));                                          311 /// }));
314 /// let foo = foo.unwrap();                       312 /// let foo = foo.unwrap();
315 /// pr_info!("a: {}", &*foo.a.lock());            313 /// pr_info!("a: {}", &*foo.a.lock());
316 /// ```                                           314 /// ```
317 ///                                               315 ///
318 /// ```rust,ignore                                316 /// ```rust,ignore
319 /// # #![allow(clippy::disallowed_names)]         317 /// # #![allow(clippy::disallowed_names)]
320 /// # use kernel::{init, pin_init, stack_try_p    318 /// # use kernel::{init, pin_init, stack_try_pin_init, init::*, sync::Mutex, new_mutex};
321 /// # use macros::pin_data;                       319 /// # use macros::pin_data;
322 /// # use core::{alloc::AllocError, pin::Pin};    320 /// # use core::{alloc::AllocError, pin::Pin};
323 /// #[pin_data]                                   321 /// #[pin_data]
324 /// struct Foo {                                  322 /// struct Foo {
325 ///     #[pin]                                    323 ///     #[pin]
326 ///     a: Mutex<usize>,                          324 ///     a: Mutex<usize>,
327 ///     b: Box<Bar>,                              325 ///     b: Box<Bar>,
328 /// }                                             326 /// }
329 ///                                               327 ///
330 /// struct Bar {                                  328 /// struct Bar {
331 ///     x: u32,                                   329 ///     x: u32,
332 /// }                                             330 /// }
333 ///                                               331 ///
334 /// stack_try_pin_init!(let foo: Pin<&mut Foo>    332 /// stack_try_pin_init!(let foo: Pin<&mut Foo> =? pin_init!(Foo {
335 ///     a <- new_mutex!(42),                      333 ///     a <- new_mutex!(42),
336 ///     b: Box::new(Bar {                      !! 334 ///     b: Box::try_new(Bar {
337 ///         x: 64,                                335 ///         x: 64,
338 ///     }, GFP_KERNEL)?,                       !! 336 ///     })?,
339 /// }));                                          337 /// }));
340 /// pr_info!("a: {}", &*foo.a.lock());            338 /// pr_info!("a: {}", &*foo.a.lock());
341 /// # Ok::<_, AllocError>(())                     339 /// # Ok::<_, AllocError>(())
342 /// ```                                           340 /// ```
343 ///                                               341 ///
344 /// # Syntax                                      342 /// # Syntax
345 ///                                               343 ///
346 /// A normal `let` binding with optional type     344 /// A normal `let` binding with optional type annotation. The expression is expected to implement
347 /// [`PinInit`]/[`Init`]. This macro assigns a    345 /// [`PinInit`]/[`Init`]. This macro assigns a result to the given variable, adding a `?` after the
348 /// `=` will propagate this error.                346 /// `=` will propagate this error.
349 #[macro_export]                                   347 #[macro_export]
350 macro_rules! stack_try_pin_init {                 348 macro_rules! stack_try_pin_init {
351     (let $var:ident $(: $t:ty)? = $val:expr) =    349     (let $var:ident $(: $t:ty)? = $val:expr) => {
352         let val = $val;                           350         let val = $val;
353         let mut $var = ::core::pin::pin!($crat    351         let mut $var = ::core::pin::pin!($crate::init::__internal::StackInit$(::<$t>)?::uninit());
354         let mut $var = $crate::init::__interna    352         let mut $var = $crate::init::__internal::StackInit::init($var, val);
355     };                                            353     };
356     (let $var:ident $(: $t:ty)? =? $val:expr)     354     (let $var:ident $(: $t:ty)? =? $val:expr) => {
357         let val = $val;                           355         let val = $val;
358         let mut $var = ::core::pin::pin!($crat    356         let mut $var = ::core::pin::pin!($crate::init::__internal::StackInit$(::<$t>)?::uninit());
359         let mut $var = $crate::init::__interna    357         let mut $var = $crate::init::__internal::StackInit::init($var, val)?;
360     };                                            358     };
361 }                                                 359 }
362                                                   360 
363 /// Construct an in-place, pinned initializer     361 /// Construct an in-place, pinned initializer for `struct`s.
364 ///                                               362 ///
365 /// This macro defaults the error to [`Infalli    363 /// This macro defaults the error to [`Infallible`]. If you need [`Error`], then use
366 /// [`try_pin_init!`].                            364 /// [`try_pin_init!`].
367 ///                                               365 ///
368 /// The syntax is almost identical to that of     366 /// The syntax is almost identical to that of a normal `struct` initializer:
369 ///                                               367 ///
370 /// ```rust                                       368 /// ```rust
371 /// # #![allow(clippy::disallowed_names)]         369 /// # #![allow(clippy::disallowed_names)]
372 /// # use kernel::{init, pin_init, macros::pin    370 /// # use kernel::{init, pin_init, macros::pin_data, init::*};
373 /// # use core::pin::Pin;                         371 /// # use core::pin::Pin;
374 /// #[pin_data]                                   372 /// #[pin_data]
375 /// struct Foo {                                  373 /// struct Foo {
376 ///     a: usize,                                 374 ///     a: usize,
377 ///     b: Bar,                                   375 ///     b: Bar,
378 /// }                                             376 /// }
379 ///                                               377 ///
380 /// #[pin_data]                                   378 /// #[pin_data]
381 /// struct Bar {                                  379 /// struct Bar {
382 ///     x: u32,                                   380 ///     x: u32,
383 /// }                                             381 /// }
384 ///                                               382 ///
385 /// # fn demo() -> impl PinInit<Foo> {            383 /// # fn demo() -> impl PinInit<Foo> {
386 /// let a = 42;                                   384 /// let a = 42;
387 ///                                               385 ///
388 /// let initializer = pin_init!(Foo {             386 /// let initializer = pin_init!(Foo {
389 ///     a,                                        387 ///     a,
390 ///     b: Bar {                                  388 ///     b: Bar {
391 ///         x: 64,                                389 ///         x: 64,
392 ///     },                                        390 ///     },
393 /// });                                           391 /// });
394 /// # initializer }                               392 /// # initializer }
395 /// # Box::pin_init(demo(), GFP_KERNEL).unwrap !! 393 /// # Box::pin_init(demo()).unwrap();
396 /// ```                                           394 /// ```
397 ///                                               395 ///
398 /// Arbitrary Rust expressions can be used to     396 /// Arbitrary Rust expressions can be used to set the value of a variable.
399 ///                                               397 ///
400 /// The fields are initialized in the order th    398 /// The fields are initialized in the order that they appear in the initializer. So it is possible
401 /// to read already initialized fields using r    399 /// to read already initialized fields using raw pointers.
402 ///                                               400 ///
403 /// IMPORTANT: You are not allowed to create r    401 /// IMPORTANT: You are not allowed to create references to fields of the struct inside of the
404 /// initializer.                                  402 /// initializer.
405 ///                                               403 ///
406 /// # Init-functions                              404 /// # Init-functions
407 ///                                               405 ///
408 /// When working with this API it is often des    406 /// When working with this API it is often desired to let others construct your types without
409 /// giving access to all fields. This is where    407 /// giving access to all fields. This is where you would normally write a plain function `new`
410 /// that would return a new instance of your t    408 /// that would return a new instance of your type. With this API that is also possible.
411 /// However, there are a few extra things to k    409 /// However, there are a few extra things to keep in mind.
412 ///                                               410 ///
413 /// To create an initializer function, simply     411 /// To create an initializer function, simply declare it like this:
414 ///                                               412 ///
415 /// ```rust                                       413 /// ```rust
416 /// # #![allow(clippy::disallowed_names)]         414 /// # #![allow(clippy::disallowed_names)]
417 /// # use kernel::{init, pin_init, init::*};   !! 415 /// # use kernel::{init, pin_init, prelude::*, init::*};
418 /// # use core::pin::Pin;                         416 /// # use core::pin::Pin;
419 /// # #[pin_data]                                 417 /// # #[pin_data]
420 /// # struct Foo {                                418 /// # struct Foo {
421 /// #     a: usize,                               419 /// #     a: usize,
422 /// #     b: Bar,                                 420 /// #     b: Bar,
423 /// # }                                           421 /// # }
424 /// # #[pin_data]                                 422 /// # #[pin_data]
425 /// # struct Bar {                                423 /// # struct Bar {
426 /// #     x: u32,                                 424 /// #     x: u32,
427 /// # }                                           425 /// # }
428 /// impl Foo {                                    426 /// impl Foo {
429 ///     fn new() -> impl PinInit<Self> {          427 ///     fn new() -> impl PinInit<Self> {
430 ///         pin_init!(Self {                      428 ///         pin_init!(Self {
431 ///             a: 42,                            429 ///             a: 42,
432 ///             b: Bar {                          430 ///             b: Bar {
433 ///                 x: 64,                        431 ///                 x: 64,
434 ///             },                                432 ///             },
435 ///         })                                    433 ///         })
436 ///     }                                         434 ///     }
437 /// }                                             435 /// }
438 /// ```                                           436 /// ```
439 ///                                               437 ///
440 /// Users of `Foo` can now create it like this    438 /// Users of `Foo` can now create it like this:
441 ///                                               439 ///
442 /// ```rust                                       440 /// ```rust
443 /// # #![allow(clippy::disallowed_names)]         441 /// # #![allow(clippy::disallowed_names)]
444 /// # use kernel::{init, pin_init, macros::pin    442 /// # use kernel::{init, pin_init, macros::pin_data, init::*};
445 /// # use core::pin::Pin;                         443 /// # use core::pin::Pin;
446 /// # #[pin_data]                                 444 /// # #[pin_data]
447 /// # struct Foo {                                445 /// # struct Foo {
448 /// #     a: usize,                               446 /// #     a: usize,
449 /// #     b: Bar,                                 447 /// #     b: Bar,
450 /// # }                                           448 /// # }
451 /// # #[pin_data]                                 449 /// # #[pin_data]
452 /// # struct Bar {                                450 /// # struct Bar {
453 /// #     x: u32,                                 451 /// #     x: u32,
454 /// # }                                           452 /// # }
455 /// # impl Foo {                                  453 /// # impl Foo {
456 /// #     fn new() -> impl PinInit<Self> {        454 /// #     fn new() -> impl PinInit<Self> {
457 /// #         pin_init!(Self {                    455 /// #         pin_init!(Self {
458 /// #             a: 42,                          456 /// #             a: 42,
459 /// #             b: Bar {                        457 /// #             b: Bar {
460 /// #                 x: 64,                      458 /// #                 x: 64,
461 /// #             },                              459 /// #             },
462 /// #         })                                  460 /// #         })
463 /// #     }                                       461 /// #     }
464 /// # }                                           462 /// # }
465 /// let foo = Box::pin_init(Foo::new(), GFP_KE !! 463 /// let foo = Box::pin_init(Foo::new());
466 /// ```                                           464 /// ```
467 ///                                               465 ///
468 /// They can also easily embed it into their o    466 /// They can also easily embed it into their own `struct`s:
469 ///                                               467 ///
470 /// ```rust                                       468 /// ```rust
471 /// # #![allow(clippy::disallowed_names)]         469 /// # #![allow(clippy::disallowed_names)]
472 /// # use kernel::{init, pin_init, macros::pin    470 /// # use kernel::{init, pin_init, macros::pin_data, init::*};
473 /// # use core::pin::Pin;                         471 /// # use core::pin::Pin;
474 /// # #[pin_data]                                 472 /// # #[pin_data]
475 /// # struct Foo {                                473 /// # struct Foo {
476 /// #     a: usize,                               474 /// #     a: usize,
477 /// #     b: Bar,                                 475 /// #     b: Bar,
478 /// # }                                           476 /// # }
479 /// # #[pin_data]                                 477 /// # #[pin_data]
480 /// # struct Bar {                                478 /// # struct Bar {
481 /// #     x: u32,                                 479 /// #     x: u32,
482 /// # }                                           480 /// # }
483 /// # impl Foo {                                  481 /// # impl Foo {
484 /// #     fn new() -> impl PinInit<Self> {        482 /// #     fn new() -> impl PinInit<Self> {
485 /// #         pin_init!(Self {                    483 /// #         pin_init!(Self {
486 /// #             a: 42,                          484 /// #             a: 42,
487 /// #             b: Bar {                        485 /// #             b: Bar {
488 /// #                 x: 64,                      486 /// #                 x: 64,
489 /// #             },                              487 /// #             },
490 /// #         })                                  488 /// #         })
491 /// #     }                                       489 /// #     }
492 /// # }                                           490 /// # }
493 /// #[pin_data]                                   491 /// #[pin_data]
494 /// struct FooContainer {                         492 /// struct FooContainer {
495 ///     #[pin]                                    493 ///     #[pin]
496 ///     foo1: Foo,                                494 ///     foo1: Foo,
497 ///     #[pin]                                    495 ///     #[pin]
498 ///     foo2: Foo,                                496 ///     foo2: Foo,
499 ///     other: u32,                               497 ///     other: u32,
500 /// }                                             498 /// }
501 ///                                               499 ///
502 /// impl FooContainer {                           500 /// impl FooContainer {
503 ///     fn new(other: u32) -> impl PinInit<Sel    501 ///     fn new(other: u32) -> impl PinInit<Self> {
504 ///         pin_init!(Self {                      502 ///         pin_init!(Self {
505 ///             foo1 <- Foo::new(),               503 ///             foo1 <- Foo::new(),
506 ///             foo2 <- Foo::new(),               504 ///             foo2 <- Foo::new(),
507 ///             other,                            505 ///             other,
508 ///         })                                    506 ///         })
509 ///     }                                         507 ///     }
510 /// }                                             508 /// }
511 /// ```                                           509 /// ```
512 ///                                               510 ///
513 /// Here we see that when using `pin_init!` wi    511 /// Here we see that when using `pin_init!` with `PinInit`, one needs to write `<-` instead of `:`.
514 /// This signifies that the given field is ini    512 /// This signifies that the given field is initialized in-place. As with `struct` initializers, just
515 /// writing the field (in this case `other`) w    513 /// writing the field (in this case `other`) without `:` or `<-` means `other: other,`.
516 ///                                               514 ///
517 /// # Syntax                                      515 /// # Syntax
518 ///                                               516 ///
519 /// As already mentioned in the examples above    517 /// As already mentioned in the examples above, inside of `pin_init!` a `struct` initializer with
520 /// the following modifications is expected:      518 /// the following modifications is expected:
521 /// - Fields that you want to initialize in-pl    519 /// - Fields that you want to initialize in-place have to use `<-` instead of `:`.
522 /// - In front of the initializer you can writ    520 /// - In front of the initializer you can write `&this in` to have access to a [`NonNull<Self>`]
523 ///   pointer named `this` inside of the initi    521 ///   pointer named `this` inside of the initializer.
524 /// - Using struct update syntax one can place    522 /// - Using struct update syntax one can place `..Zeroable::zeroed()` at the very end of the
525 ///   struct, this initializes every field wit    523 ///   struct, this initializes every field with 0 and then runs all initializers specified in the
526 ///   body. This can only be done if [`Zeroabl    524 ///   body. This can only be done if [`Zeroable`] is implemented for the struct.
527 ///                                               525 ///
528 /// For instance:                                 526 /// For instance:
529 ///                                               527 ///
530 /// ```rust                                       528 /// ```rust
531 /// # use kernel::{macros::{Zeroable, pin_data    529 /// # use kernel::{macros::{Zeroable, pin_data}, pin_init};
532 /// # use core::{ptr::addr_of_mut, marker::Pha    530 /// # use core::{ptr::addr_of_mut, marker::PhantomPinned};
533 /// #[pin_data]                                   531 /// #[pin_data]
534 /// #[derive(Zeroable)]                           532 /// #[derive(Zeroable)]
535 /// struct Buf {                                  533 /// struct Buf {
536 ///     // `ptr` points into `buf`.               534 ///     // `ptr` points into `buf`.
537 ///     ptr: *mut u8,                             535 ///     ptr: *mut u8,
538 ///     buf: [u8; 64],                            536 ///     buf: [u8; 64],
539 ///     #[pin]                                    537 ///     #[pin]
540 ///     pin: PhantomPinned,                       538 ///     pin: PhantomPinned,
541 /// }                                             539 /// }
542 /// pin_init!(&this in Buf {                      540 /// pin_init!(&this in Buf {
543 ///     buf: [0; 64],                             541 ///     buf: [0; 64],
544 ///     ptr: unsafe { addr_of_mut!((*this.as_p    542 ///     ptr: unsafe { addr_of_mut!((*this.as_ptr()).buf).cast() },
545 ///     pin: PhantomPinned,                       543 ///     pin: PhantomPinned,
546 /// });                                           544 /// });
547 /// pin_init!(Buf {                               545 /// pin_init!(Buf {
548 ///     buf: [1; 64],                             546 ///     buf: [1; 64],
549 ///     ..Zeroable::zeroed()                      547 ///     ..Zeroable::zeroed()
550 /// });                                           548 /// });
551 /// ```                                           549 /// ```
552 ///                                               550 ///
553 /// [`try_pin_init!`]: kernel::try_pin_init       551 /// [`try_pin_init!`]: kernel::try_pin_init
554 /// [`NonNull<Self>`]: core::ptr::NonNull         552 /// [`NonNull<Self>`]: core::ptr::NonNull
555 // For a detailed example of how this macro wo    553 // For a detailed example of how this macro works, see the module documentation of the hidden
556 // module `__internal` inside of `init/__inter    554 // module `__internal` inside of `init/__internal.rs`.
557 #[macro_export]                                   555 #[macro_export]
558 macro_rules! pin_init {                           556 macro_rules! pin_init {
559     ($(&$this:ident in)? $t:ident $(::<$($gene    557     ($(&$this:ident in)? $t:ident $(::<$($generics:ty),* $(,)?>)? {
560         $($fields:tt)*                            558         $($fields:tt)*
561     }) => {                                       559     }) => {
562         $crate::__init_internal!(                 560         $crate::__init_internal!(
563             @this($($this)?),                     561             @this($($this)?),
564             @typ($t $(::<$($generics),*>)?),      562             @typ($t $(::<$($generics),*>)?),
565             @fields($($fields)*),                 563             @fields($($fields)*),
566             @error(::core::convert::Infallible    564             @error(::core::convert::Infallible),
567             @data(PinData, use_data),             565             @data(PinData, use_data),
568             @has_data(HasPinData, __pin_data),    566             @has_data(HasPinData, __pin_data),
569             @construct_closure(pin_init_from_c    567             @construct_closure(pin_init_from_closure),
570             @munch_fields($($fields)*),           568             @munch_fields($($fields)*),
571         )                                         569         )
572     };                                            570     };
573 }                                                 571 }
574                                                   572 
575 /// Construct an in-place, fallible pinned ini    573 /// Construct an in-place, fallible pinned initializer for `struct`s.
576 ///                                               574 ///
577 /// If the initialization can complete without    575 /// If the initialization can complete without error (or [`Infallible`]), then use [`pin_init!`].
578 ///                                               576 ///
579 /// You can use the `?` operator or use `retur    577 /// You can use the `?` operator or use `return Err(err)` inside the initializer to stop
580 /// initialization and return the error.          578 /// initialization and return the error.
581 ///                                               579 ///
582 /// IMPORTANT: if you have `unsafe` code insid    580 /// IMPORTANT: if you have `unsafe` code inside of the initializer you have to ensure that when
583 /// initialization fails, the memory can be sa    581 /// initialization fails, the memory can be safely deallocated without any further modifications.
584 ///                                               582 ///
585 /// This macro defaults the error to [`Error`]    583 /// This macro defaults the error to [`Error`].
586 ///                                               584 ///
587 /// The syntax is identical to [`pin_init!`] w    585 /// The syntax is identical to [`pin_init!`] with the following exception: you can append `? $type`
588 /// after the `struct` initializer to specify     586 /// after the `struct` initializer to specify the error type you want to use.
589 ///                                               587 ///
590 /// # Examples                                    588 /// # Examples
591 ///                                               589 ///
592 /// ```rust                                       590 /// ```rust
593 /// # #![feature(new_uninit)]                     591 /// # #![feature(new_uninit)]
594 /// use kernel::{init::{self, PinInit}, error:    592 /// use kernel::{init::{self, PinInit}, error::Error};
595 /// #[pin_data]                                   593 /// #[pin_data]
596 /// struct BigBuf {                               594 /// struct BigBuf {
597 ///     big: Box<[u8; 1024 * 1024 * 1024]>,       595 ///     big: Box<[u8; 1024 * 1024 * 1024]>,
598 ///     small: [u8; 1024 * 1024],                 596 ///     small: [u8; 1024 * 1024],
599 ///     ptr: *mut u8,                             597 ///     ptr: *mut u8,
600 /// }                                             598 /// }
601 ///                                               599 ///
602 /// impl BigBuf {                                 600 /// impl BigBuf {
603 ///     fn new() -> impl PinInit<Self, Error>     601 ///     fn new() -> impl PinInit<Self, Error> {
604 ///         try_pin_init!(Self {                  602 ///         try_pin_init!(Self {
605 ///             big: Box::init(init::zeroed(), !! 603 ///             big: Box::init(init::zeroed())?,
606 ///             small: [0; 1024 * 1024],          604 ///             small: [0; 1024 * 1024],
607 ///             ptr: core::ptr::null_mut(),       605 ///             ptr: core::ptr::null_mut(),
608 ///         }? Error)                             606 ///         }? Error)
609 ///     }                                         607 ///     }
610 /// }                                             608 /// }
611 /// ```                                           609 /// ```
612 // For a detailed example of how this macro wo    610 // For a detailed example of how this macro works, see the module documentation of the hidden
613 // module `__internal` inside of `init/__inter    611 // module `__internal` inside of `init/__internal.rs`.
614 #[macro_export]                                   612 #[macro_export]
615 macro_rules! try_pin_init {                       613 macro_rules! try_pin_init {
616     ($(&$this:ident in)? $t:ident $(::<$($gene    614     ($(&$this:ident in)? $t:ident $(::<$($generics:ty),* $(,)?>)? {
617         $($fields:tt)*                            615         $($fields:tt)*
618     }) => {                                       616     }) => {
619         $crate::__init_internal!(                 617         $crate::__init_internal!(
620             @this($($this)?),                     618             @this($($this)?),
621             @typ($t $(::<$($generics),*>)? ),     619             @typ($t $(::<$($generics),*>)? ),
622             @fields($($fields)*),                 620             @fields($($fields)*),
623             @error($crate::error::Error),         621             @error($crate::error::Error),
624             @data(PinData, use_data),             622             @data(PinData, use_data),
625             @has_data(HasPinData, __pin_data),    623             @has_data(HasPinData, __pin_data),
626             @construct_closure(pin_init_from_c    624             @construct_closure(pin_init_from_closure),
627             @munch_fields($($fields)*),           625             @munch_fields($($fields)*),
628         )                                         626         )
629     };                                            627     };
630     ($(&$this:ident in)? $t:ident $(::<$($gene    628     ($(&$this:ident in)? $t:ident $(::<$($generics:ty),* $(,)?>)? {
631         $($fields:tt)*                            629         $($fields:tt)*
632     }? $err:ty) => {                              630     }? $err:ty) => {
633         $crate::__init_internal!(                 631         $crate::__init_internal!(
634             @this($($this)?),                     632             @this($($this)?),
635             @typ($t $(::<$($generics),*>)? ),     633             @typ($t $(::<$($generics),*>)? ),
636             @fields($($fields)*),                 634             @fields($($fields)*),
637             @error($err),                         635             @error($err),
638             @data(PinData, use_data),             636             @data(PinData, use_data),
639             @has_data(HasPinData, __pin_data),    637             @has_data(HasPinData, __pin_data),
640             @construct_closure(pin_init_from_c    638             @construct_closure(pin_init_from_closure),
641             @munch_fields($($fields)*),           639             @munch_fields($($fields)*),
642         )                                         640         )
643     };                                            641     };
644 }                                                 642 }
645                                                   643 
646 /// Construct an in-place initializer for `str    644 /// Construct an in-place initializer for `struct`s.
647 ///                                               645 ///
648 /// This macro defaults the error to [`Infalli    646 /// This macro defaults the error to [`Infallible`]. If you need [`Error`], then use
649 /// [`try_init!`].                                647 /// [`try_init!`].
650 ///                                               648 ///
651 /// The syntax is identical to [`pin_init!`] a    649 /// The syntax is identical to [`pin_init!`] and its safety caveats also apply:
652 /// - `unsafe` code must guarantee either full    650 /// - `unsafe` code must guarantee either full initialization or return an error and allow
653 ///   deallocation of the memory.                 651 ///   deallocation of the memory.
654 /// - the fields are initialized in the order     652 /// - the fields are initialized in the order given in the initializer.
655 /// - no references to fields are allowed to b    653 /// - no references to fields are allowed to be created inside of the initializer.
656 ///                                               654 ///
657 /// This initializer is for initializing data     655 /// This initializer is for initializing data in-place that might later be moved. If you want to
658 /// pin-initialize, use [`pin_init!`].            656 /// pin-initialize, use [`pin_init!`].
659 ///                                               657 ///
660 /// [`try_init!`]: crate::try_init!               658 /// [`try_init!`]: crate::try_init!
661 // For a detailed example of how this macro wo    659 // For a detailed example of how this macro works, see the module documentation of the hidden
662 // module `__internal` inside of `init/__inter    660 // module `__internal` inside of `init/__internal.rs`.
663 #[macro_export]                                   661 #[macro_export]
664 macro_rules! init {                               662 macro_rules! init {
665     ($(&$this:ident in)? $t:ident $(::<$($gene    663     ($(&$this:ident in)? $t:ident $(::<$($generics:ty),* $(,)?>)? {
666         $($fields:tt)*                            664         $($fields:tt)*
667     }) => {                                       665     }) => {
668         $crate::__init_internal!(                 666         $crate::__init_internal!(
669             @this($($this)?),                     667             @this($($this)?),
670             @typ($t $(::<$($generics),*>)?),      668             @typ($t $(::<$($generics),*>)?),
671             @fields($($fields)*),                 669             @fields($($fields)*),
672             @error(::core::convert::Infallible    670             @error(::core::convert::Infallible),
673             @data(InitData, /*no use_data*/),     671             @data(InitData, /*no use_data*/),
674             @has_data(HasInitData, __init_data    672             @has_data(HasInitData, __init_data),
675             @construct_closure(init_from_closu    673             @construct_closure(init_from_closure),
676             @munch_fields($($fields)*),           674             @munch_fields($($fields)*),
677         )                                         675         )
678     }                                             676     }
679 }                                                 677 }
680                                                   678 
681 /// Construct an in-place fallible initializer    679 /// Construct an in-place fallible initializer for `struct`s.
682 ///                                               680 ///
683 /// This macro defaults the error to [`Error`]    681 /// This macro defaults the error to [`Error`]. If you need [`Infallible`], then use
684 /// [`init!`].                                    682 /// [`init!`].
685 ///                                               683 ///
686 /// The syntax is identical to [`try_pin_init!    684 /// The syntax is identical to [`try_pin_init!`]. If you want to specify a custom error,
687 /// append `? $type` after the `struct` initia    685 /// append `? $type` after the `struct` initializer.
688 /// The safety caveats from [`try_pin_init!`]     686 /// The safety caveats from [`try_pin_init!`] also apply:
689 /// - `unsafe` code must guarantee either full    687 /// - `unsafe` code must guarantee either full initialization or return an error and allow
690 ///   deallocation of the memory.                 688 ///   deallocation of the memory.
691 /// - the fields are initialized in the order     689 /// - the fields are initialized in the order given in the initializer.
692 /// - no references to fields are allowed to b    690 /// - no references to fields are allowed to be created inside of the initializer.
693 ///                                               691 ///
694 /// # Examples                                    692 /// # Examples
695 ///                                               693 ///
696 /// ```rust                                       694 /// ```rust
697 /// use kernel::{init::{PinInit, zeroed}, erro    695 /// use kernel::{init::{PinInit, zeroed}, error::Error};
698 /// struct BigBuf {                               696 /// struct BigBuf {
699 ///     big: Box<[u8; 1024 * 1024 * 1024]>,       697 ///     big: Box<[u8; 1024 * 1024 * 1024]>,
700 ///     small: [u8; 1024 * 1024],                 698 ///     small: [u8; 1024 * 1024],
701 /// }                                             699 /// }
702 ///                                               700 ///
703 /// impl BigBuf {                                 701 /// impl BigBuf {
704 ///     fn new() -> impl Init<Self, Error> {      702 ///     fn new() -> impl Init<Self, Error> {
705 ///         try_init!(Self {                      703 ///         try_init!(Self {
706 ///             big: Box::init(zeroed(), GFP_K !! 704 ///             big: Box::init(zeroed())?,
707 ///             small: [0; 1024 * 1024],          705 ///             small: [0; 1024 * 1024],
708 ///         }? Error)                             706 ///         }? Error)
709 ///     }                                         707 ///     }
710 /// }                                             708 /// }
711 /// ```                                           709 /// ```
712 // For a detailed example of how this macro wo    710 // For a detailed example of how this macro works, see the module documentation of the hidden
713 // module `__internal` inside of `init/__inter    711 // module `__internal` inside of `init/__internal.rs`.
714 #[macro_export]                                   712 #[macro_export]
715 macro_rules! try_init {                           713 macro_rules! try_init {
716     ($(&$this:ident in)? $t:ident $(::<$($gene    714     ($(&$this:ident in)? $t:ident $(::<$($generics:ty),* $(,)?>)? {
717         $($fields:tt)*                            715         $($fields:tt)*
718     }) => {                                       716     }) => {
719         $crate::__init_internal!(                 717         $crate::__init_internal!(
720             @this($($this)?),                     718             @this($($this)?),
721             @typ($t $(::<$($generics),*>)?),      719             @typ($t $(::<$($generics),*>)?),
722             @fields($($fields)*),                 720             @fields($($fields)*),
723             @error($crate::error::Error),         721             @error($crate::error::Error),
724             @data(InitData, /*no use_data*/),     722             @data(InitData, /*no use_data*/),
725             @has_data(HasInitData, __init_data    723             @has_data(HasInitData, __init_data),
726             @construct_closure(init_from_closu    724             @construct_closure(init_from_closure),
727             @munch_fields($($fields)*),           725             @munch_fields($($fields)*),
728         )                                         726         )
729     };                                            727     };
730     ($(&$this:ident in)? $t:ident $(::<$($gene    728     ($(&$this:ident in)? $t:ident $(::<$($generics:ty),* $(,)?>)? {
731         $($fields:tt)*                            729         $($fields:tt)*
732     }? $err:ty) => {                              730     }? $err:ty) => {
733         $crate::__init_internal!(                 731         $crate::__init_internal!(
734             @this($($this)?),                     732             @this($($this)?),
735             @typ($t $(::<$($generics),*>)?),      733             @typ($t $(::<$($generics),*>)?),
736             @fields($($fields)*),                 734             @fields($($fields)*),
737             @error($err),                         735             @error($err),
738             @data(InitData, /*no use_data*/),     736             @data(InitData, /*no use_data*/),
739             @has_data(HasInitData, __init_data    737             @has_data(HasInitData, __init_data),
740             @construct_closure(init_from_closu    738             @construct_closure(init_from_closure),
741             @munch_fields($($fields)*),           739             @munch_fields($($fields)*),
742         )                                         740         )
743     };                                            741     };
744 }                                                 742 }
745                                                   743 
746 /// Asserts that a field on a struct using `#[ << 
747 /// structurally pinned.                       << 
748 ///                                            << 
749 /// # Example                                  << 
750 ///                                            << 
751 /// This will succeed:                         << 
752 /// ```                                        << 
753 /// use kernel::assert_pinned;                 << 
754 /// #[pin_data]                                << 
755 /// struct MyStruct {                          << 
756 ///     #[pin]                                 << 
757 ///     some_field: u64,                       << 
758 /// }                                          << 
759 ///                                            << 
760 /// assert_pinned!(MyStruct, some_field, u64); << 
761 /// ```                                        << 
762 ///                                            << 
763 /// This will fail:                            << 
764 // TODO: replace with `compile_fail` when supp << 
765 /// ```ignore                                  << 
766 /// use kernel::assert_pinned;                 << 
767 /// #[pin_data]                                << 
768 /// struct MyStruct {                          << 
769 ///     some_field: u64,                       << 
770 /// }                                          << 
771 ///                                            << 
772 /// assert_pinned!(MyStruct, some_field, u64); << 
773 /// ```                                        << 
774 ///                                            << 
775 /// Some uses of the macro may trigger the `ca << 
776 /// work around this, you may pass the `inline << 
777 /// only be used when the macro is invoked fro << 
778 /// ```                                        << 
779 /// use kernel::assert_pinned;                 << 
780 /// #[pin_data]                                << 
781 /// struct Foo<T> {                            << 
782 ///     #[pin]                                 << 
783 ///     elem: T,                               << 
784 /// }                                          << 
785 ///                                            << 
786 /// impl<T> Foo<T> {                           << 
787 ///     fn project(self: Pin<&mut Self>) -> Pi << 
788 ///         assert_pinned!(Foo<T>, elem, T, in << 
789 ///                                            << 
790 ///         // SAFETY: The field is structural << 
791 ///         unsafe { self.map_unchecked_mut(|m << 
792 ///     }                                      << 
793 /// }                                          << 
794 /// ```                                        << 
795 #[macro_export]                                << 
796 macro_rules! assert_pinned {                   << 
797     ($ty:ty, $field:ident, $field_ty:ty, inlin << 
798         let _ = move |ptr: *mut $field_ty| {   << 
799             // SAFETY: This code is unreachabl << 
800             let data = unsafe { <$ty as $crate << 
801             let init = $crate::init::__interna << 
802             // SAFETY: This code is unreachabl << 
803             unsafe { data.$field(ptr, init) }. << 
804         };                                     << 
805     };                                         << 
806                                                << 
807     ($ty:ty, $field:ident, $field_ty:ty) => {  << 
808         const _: () = {                        << 
809             $crate::assert_pinned!($ty, $field << 
810         };                                     << 
811     };                                         << 
812 }                                              << 
813                                                << 
814 /// A pin-initializer for the type `T`.           744 /// A pin-initializer for the type `T`.
815 ///                                               745 ///
816 /// To use this initializer, you will need a s    746 /// To use this initializer, you will need a suitable memory location that can hold a `T`. This can
817 /// be [`Box<T>`], [`Arc<T>`], [`UniqueArc<T>`    747 /// be [`Box<T>`], [`Arc<T>`], [`UniqueArc<T>`] or even the stack (see [`stack_pin_init!`]). Use the
818 /// [`InPlaceInit::pin_init`] function of a sm    748 /// [`InPlaceInit::pin_init`] function of a smart pointer like [`Arc<T>`] on this.
819 ///                                               749 ///
820 /// Also see the [module description](self).      750 /// Also see the [module description](self).
821 ///                                               751 ///
822 /// # Safety                                      752 /// # Safety
823 ///                                               753 ///
824 /// When implementing this trait you will need !! 754 /// When implementing this type you will need to take great care. Also there are probably very few
825 /// cases where a manual implementation is nec    755 /// cases where a manual implementation is necessary. Use [`pin_init_from_closure`] where possible.
826 ///                                               756 ///
827 /// The [`PinInit::__pinned_init`] function:   !! 757 /// The [`PinInit::__pinned_init`] function
828 /// - returns `Ok(())` if it initialized every    758 /// - returns `Ok(())` if it initialized every field of `slot`,
829 /// - returns `Err(err)` if it encountered an     759 /// - returns `Err(err)` if it encountered an error and then cleaned `slot`, this means:
830 ///     - `slot` can be deallocated without UB    760 ///     - `slot` can be deallocated without UB occurring,
831 ///     - `slot` does not need to be dropped,     761 ///     - `slot` does not need to be dropped,
832 ///     - `slot` is not partially initialized.    762 ///     - `slot` is not partially initialized.
833 /// - while constructing the `T` at `slot` it     763 /// - while constructing the `T` at `slot` it upholds the pinning invariants of `T`.
834 ///                                               764 ///
835 /// [`Arc<T>`]: crate::sync::Arc                  765 /// [`Arc<T>`]: crate::sync::Arc
836 /// [`Arc::pin_init`]: crate::sync::Arc::pin_i    766 /// [`Arc::pin_init`]: crate::sync::Arc::pin_init
837 #[must_use = "An initializer must be used in o    767 #[must_use = "An initializer must be used in order to create its value."]
838 pub unsafe trait PinInit<T: ?Sized, E = Infall    768 pub unsafe trait PinInit<T: ?Sized, E = Infallible>: Sized {
839     /// Initializes `slot`.                       769     /// Initializes `slot`.
840     ///                                           770     ///
841     /// # Safety                                  771     /// # Safety
842     ///                                           772     ///
843     /// - `slot` is a valid pointer to uniniti    773     /// - `slot` is a valid pointer to uninitialized memory.
844     /// - the caller does not touch `slot` whe    774     /// - the caller does not touch `slot` when `Err` is returned, they are only permitted to
845     ///   deallocate.                             775     ///   deallocate.
846     /// - `slot` will not move until it is dro    776     /// - `slot` will not move until it is dropped, i.e. it will be pinned.
847     unsafe fn __pinned_init(self, slot: *mut T    777     unsafe fn __pinned_init(self, slot: *mut T) -> Result<(), E>;
848                                                   778 
849     /// First initializes the value using `sel    779     /// First initializes the value using `self` then calls the function `f` with the initialized
850     /// value.                                    780     /// value.
851     ///                                           781     ///
852     /// If `f` returns an error the value is d    782     /// If `f` returns an error the value is dropped and the initializer will forward the error.
853     ///                                           783     ///
854     /// # Examples                                784     /// # Examples
855     ///                                           785     ///
856     /// ```rust                                   786     /// ```rust
857     /// # #![allow(clippy::disallowed_names)]     787     /// # #![allow(clippy::disallowed_names)]
858     /// use kernel::{types::Opaque, init::pin_    788     /// use kernel::{types::Opaque, init::pin_init_from_closure};
859     /// #[repr(C)]                                789     /// #[repr(C)]
860     /// struct RawFoo([u8; 16]);                  790     /// struct RawFoo([u8; 16]);
861     /// extern {                                  791     /// extern {
862     ///     fn init_foo(_: *mut RawFoo);          792     ///     fn init_foo(_: *mut RawFoo);
863     /// }                                         793     /// }
864     ///                                           794     ///
865     /// #[pin_data]                               795     /// #[pin_data]
866     /// struct Foo {                              796     /// struct Foo {
867     ///     #[pin]                                797     ///     #[pin]
868     ///     raw: Opaque<RawFoo>,                  798     ///     raw: Opaque<RawFoo>,
869     /// }                                         799     /// }
870     ///                                           800     ///
871     /// impl Foo {                                801     /// impl Foo {
872     ///     fn setup(self: Pin<&mut Self>) {      802     ///     fn setup(self: Pin<&mut Self>) {
873     ///         pr_info!("Setting up foo");       803     ///         pr_info!("Setting up foo");
874     ///     }                                     804     ///     }
875     /// }                                         805     /// }
876     ///                                           806     ///
877     /// let foo = pin_init!(Foo {                 807     /// let foo = pin_init!(Foo {
878     ///     raw <- unsafe {                       808     ///     raw <- unsafe {
879     ///         Opaque::ffi_init(|s| {            809     ///         Opaque::ffi_init(|s| {
880     ///             init_foo(s);                  810     ///             init_foo(s);
881     ///         })                                811     ///         })
882     ///     },                                    812     ///     },
883     /// }).pin_chain(|foo| {                      813     /// }).pin_chain(|foo| {
884     ///     foo.setup();                          814     ///     foo.setup();
885     ///     Ok(())                                815     ///     Ok(())
886     /// });                                       816     /// });
887     /// ```                                       817     /// ```
888     fn pin_chain<F>(self, f: F) -> ChainPinIni    818     fn pin_chain<F>(self, f: F) -> ChainPinInit<Self, F, T, E>
889     where                                         819     where
890         F: FnOnce(Pin<&mut T>) -> Result<(), E    820         F: FnOnce(Pin<&mut T>) -> Result<(), E>,
891     {                                             821     {
892         ChainPinInit(self, f, PhantomData)        822         ChainPinInit(self, f, PhantomData)
893     }                                             823     }
894 }                                                 824 }
895                                                   825 
896 /// An initializer returned by [`PinInit::pin_    826 /// An initializer returned by [`PinInit::pin_chain`].
897 pub struct ChainPinInit<I, F, T: ?Sized, E>(I,    827 pub struct ChainPinInit<I, F, T: ?Sized, E>(I, F, __internal::Invariant<(E, Box<T>)>);
898                                                   828 
899 // SAFETY: The `__pinned_init` function is imp    829 // SAFETY: The `__pinned_init` function is implemented such that it
900 // - returns `Ok(())` on successful initializa    830 // - returns `Ok(())` on successful initialization,
901 // - returns `Err(err)` on error and in this c    831 // - returns `Err(err)` on error and in this case `slot` will be dropped.
902 // - considers `slot` pinned.                     832 // - considers `slot` pinned.
903 unsafe impl<T: ?Sized, E, I, F> PinInit<T, E>     833 unsafe impl<T: ?Sized, E, I, F> PinInit<T, E> for ChainPinInit<I, F, T, E>
904 where                                             834 where
905     I: PinInit<T, E>,                             835     I: PinInit<T, E>,
906     F: FnOnce(Pin<&mut T>) -> Result<(), E>,      836     F: FnOnce(Pin<&mut T>) -> Result<(), E>,
907 {                                                 837 {
908     unsafe fn __pinned_init(self, slot: *mut T    838     unsafe fn __pinned_init(self, slot: *mut T) -> Result<(), E> {
909         // SAFETY: All requirements fulfilled     839         // SAFETY: All requirements fulfilled since this function is `__pinned_init`.
910         unsafe { self.0.__pinned_init(slot)? }    840         unsafe { self.0.__pinned_init(slot)? };
911         // SAFETY: The above call initialized     841         // SAFETY: The above call initialized `slot` and we still have unique access.
912         let val = unsafe { &mut *slot };          842         let val = unsafe { &mut *slot };
913         // SAFETY: `slot` is considered pinned    843         // SAFETY: `slot` is considered pinned.
914         let val = unsafe { Pin::new_unchecked(    844         let val = unsafe { Pin::new_unchecked(val) };
915         // SAFETY: `slot` was initialized abov !! 845         (self.1)(val).map_err(|e| {
916         (self.1)(val).inspect_err(|_| unsafe { !! 846             // SAFETY: `slot` was initialized above.
                                                   >> 847             unsafe { core::ptr::drop_in_place(slot) };
                                                   >> 848             e
                                                   >> 849         })
917     }                                             850     }
918 }                                                 851 }
919                                                   852 
920 /// An initializer for `T`.                       853 /// An initializer for `T`.
921 ///                                               854 ///
922 /// To use this initializer, you will need a s    855 /// To use this initializer, you will need a suitable memory location that can hold a `T`. This can
923 /// be [`Box<T>`], [`Arc<T>`], [`UniqueArc<T>`    856 /// be [`Box<T>`], [`Arc<T>`], [`UniqueArc<T>`] or even the stack (see [`stack_pin_init!`]). Use the
924 /// [`InPlaceInit::init`] function of a smart     857 /// [`InPlaceInit::init`] function of a smart pointer like [`Arc<T>`] on this. Because
925 /// [`PinInit<T, E>`] is a super trait, you ca    858 /// [`PinInit<T, E>`] is a super trait, you can use every function that takes it as well.
926 ///                                               859 ///
927 /// Also see the [module description](self).      860 /// Also see the [module description](self).
928 ///                                               861 ///
929 /// # Safety                                      862 /// # Safety
930 ///                                               863 ///
931 /// When implementing this trait you will need !! 864 /// When implementing this type you will need to take great care. Also there are probably very few
932 /// cases where a manual implementation is nec    865 /// cases where a manual implementation is necessary. Use [`init_from_closure`] where possible.
933 ///                                               866 ///
934 /// The [`Init::__init`] function:             !! 867 /// The [`Init::__init`] function
935 /// - returns `Ok(())` if it initialized every    868 /// - returns `Ok(())` if it initialized every field of `slot`,
936 /// - returns `Err(err)` if it encountered an     869 /// - returns `Err(err)` if it encountered an error and then cleaned `slot`, this means:
937 ///     - `slot` can be deallocated without UB    870 ///     - `slot` can be deallocated without UB occurring,
938 ///     - `slot` does not need to be dropped,     871 ///     - `slot` does not need to be dropped,
939 ///     - `slot` is not partially initialized.    872 ///     - `slot` is not partially initialized.
940 /// - while constructing the `T` at `slot` it     873 /// - while constructing the `T` at `slot` it upholds the pinning invariants of `T`.
941 ///                                               874 ///
942 /// The `__pinned_init` function from the supe    875 /// The `__pinned_init` function from the supertrait [`PinInit`] needs to execute the exact same
943 /// code as `__init`.                             876 /// code as `__init`.
944 ///                                               877 ///
945 /// Contrary to its supertype [`PinInit<T, E>`    878 /// Contrary to its supertype [`PinInit<T, E>`] the caller is allowed to
946 /// move the pointee after initialization.        879 /// move the pointee after initialization.
947 ///                                               880 ///
948 /// [`Arc<T>`]: crate::sync::Arc                  881 /// [`Arc<T>`]: crate::sync::Arc
949 #[must_use = "An initializer must be used in o    882 #[must_use = "An initializer must be used in order to create its value."]
950 pub unsafe trait Init<T: ?Sized, E = Infallibl    883 pub unsafe trait Init<T: ?Sized, E = Infallible>: PinInit<T, E> {
951     /// Initializes `slot`.                       884     /// Initializes `slot`.
952     ///                                           885     ///
953     /// # Safety                                  886     /// # Safety
954     ///                                           887     ///
955     /// - `slot` is a valid pointer to uniniti    888     /// - `slot` is a valid pointer to uninitialized memory.
956     /// - the caller does not touch `slot` whe    889     /// - the caller does not touch `slot` when `Err` is returned, they are only permitted to
957     ///   deallocate.                             890     ///   deallocate.
958     unsafe fn __init(self, slot: *mut T) -> Re    891     unsafe fn __init(self, slot: *mut T) -> Result<(), E>;
959                                                   892 
960     /// First initializes the value using `sel    893     /// First initializes the value using `self` then calls the function `f` with the initialized
961     /// value.                                    894     /// value.
962     ///                                           895     ///
963     /// If `f` returns an error the value is d    896     /// If `f` returns an error the value is dropped and the initializer will forward the error.
964     ///                                           897     ///
965     /// # Examples                                898     /// # Examples
966     ///                                           899     ///
967     /// ```rust                                   900     /// ```rust
968     /// # #![allow(clippy::disallowed_names)]     901     /// # #![allow(clippy::disallowed_names)]
969     /// use kernel::{types::Opaque, init::{sel    902     /// use kernel::{types::Opaque, init::{self, init_from_closure}};
970     /// struct Foo {                              903     /// struct Foo {
971     ///     buf: [u8; 1_000_000],                 904     ///     buf: [u8; 1_000_000],
972     /// }                                         905     /// }
973     ///                                           906     ///
974     /// impl Foo {                                907     /// impl Foo {
975     ///     fn setup(&mut self) {                 908     ///     fn setup(&mut self) {
976     ///         pr_info!("Setting up foo");       909     ///         pr_info!("Setting up foo");
977     ///     }                                     910     ///     }
978     /// }                                         911     /// }
979     ///                                           912     ///
980     /// let foo = init!(Foo {                     913     /// let foo = init!(Foo {
981     ///     buf <- init::zeroed()                 914     ///     buf <- init::zeroed()
982     /// }).chain(|foo| {                          915     /// }).chain(|foo| {
983     ///     foo.setup();                          916     ///     foo.setup();
984     ///     Ok(())                                917     ///     Ok(())
985     /// });                                       918     /// });
986     /// ```                                       919     /// ```
987     fn chain<F>(self, f: F) -> ChainInit<Self,    920     fn chain<F>(self, f: F) -> ChainInit<Self, F, T, E>
988     where                                         921     where
989         F: FnOnce(&mut T) -> Result<(), E>,       922         F: FnOnce(&mut T) -> Result<(), E>,
990     {                                             923     {
991         ChainInit(self, f, PhantomData)           924         ChainInit(self, f, PhantomData)
992     }                                             925     }
993 }                                                 926 }
994                                                   927 
995 /// An initializer returned by [`Init::chain`]    928 /// An initializer returned by [`Init::chain`].
996 pub struct ChainInit<I, F, T: ?Sized, E>(I, F,    929 pub struct ChainInit<I, F, T: ?Sized, E>(I, F, __internal::Invariant<(E, Box<T>)>);
997                                                   930 
998 // SAFETY: The `__init` function is implemente    931 // SAFETY: The `__init` function is implemented such that it
999 // - returns `Ok(())` on successful initializa    932 // - returns `Ok(())` on successful initialization,
1000 // - returns `Err(err)` on error and in this     933 // - returns `Err(err)` on error and in this case `slot` will be dropped.
1001 unsafe impl<T: ?Sized, E, I, F> Init<T, E> fo    934 unsafe impl<T: ?Sized, E, I, F> Init<T, E> for ChainInit<I, F, T, E>
1002 where                                            935 where
1003     I: Init<T, E>,                               936     I: Init<T, E>,
1004     F: FnOnce(&mut T) -> Result<(), E>,          937     F: FnOnce(&mut T) -> Result<(), E>,
1005 {                                                938 {
1006     unsafe fn __init(self, slot: *mut T) -> R    939     unsafe fn __init(self, slot: *mut T) -> Result<(), E> {
1007         // SAFETY: All requirements fulfilled    940         // SAFETY: All requirements fulfilled since this function is `__init`.
1008         unsafe { self.0.__pinned_init(slot)?     941         unsafe { self.0.__pinned_init(slot)? };
1009         // SAFETY: The above call initialized    942         // SAFETY: The above call initialized `slot` and we still have unique access.
1010         (self.1)(unsafe { &mut *slot }).inspe !! 943         (self.1)(unsafe { &mut *slot }).map_err(|e| {
1011             // SAFETY: `slot` was initialized    944             // SAFETY: `slot` was initialized above.
1012             unsafe { core::ptr::drop_in_place !! 945             unsafe { core::ptr::drop_in_place(slot) };
                                                   >> 946             e
                                                   >> 947         })
1013     }                                            948     }
1014 }                                                949 }
1015                                                  950 
1016 // SAFETY: `__pinned_init` behaves exactly th    951 // SAFETY: `__pinned_init` behaves exactly the same as `__init`.
1017 unsafe impl<T: ?Sized, E, I, F> PinInit<T, E>    952 unsafe impl<T: ?Sized, E, I, F> PinInit<T, E> for ChainInit<I, F, T, E>
1018 where                                            953 where
1019     I: Init<T, E>,                               954     I: Init<T, E>,
1020     F: FnOnce(&mut T) -> Result<(), E>,          955     F: FnOnce(&mut T) -> Result<(), E>,
1021 {                                                956 {
1022     unsafe fn __pinned_init(self, slot: *mut     957     unsafe fn __pinned_init(self, slot: *mut T) -> Result<(), E> {
1023         // SAFETY: `__init` has less strict r    958         // SAFETY: `__init` has less strict requirements compared to `__pinned_init`.
1024         unsafe { self.__init(slot) }             959         unsafe { self.__init(slot) }
1025     }                                            960     }
1026 }                                                961 }
1027                                                  962 
1028 /// Creates a new [`PinInit<T, E>`] from the     963 /// Creates a new [`PinInit<T, E>`] from the given closure.
1029 ///                                              964 ///
1030 /// # Safety                                     965 /// # Safety
1031 ///                                              966 ///
1032 /// The closure:                                 967 /// The closure:
1033 /// - returns `Ok(())` if it initialized ever    968 /// - returns `Ok(())` if it initialized every field of `slot`,
1034 /// - returns `Err(err)` if it encountered an    969 /// - returns `Err(err)` if it encountered an error and then cleaned `slot`, this means:
1035 ///     - `slot` can be deallocated without U    970 ///     - `slot` can be deallocated without UB occurring,
1036 ///     - `slot` does not need to be dropped,    971 ///     - `slot` does not need to be dropped,
1037 ///     - `slot` is not partially initialized    972 ///     - `slot` is not partially initialized.
1038 /// - may assume that the `slot` does not mov    973 /// - may assume that the `slot` does not move if `T: !Unpin`,
1039 /// - while constructing the `T` at `slot` it    974 /// - while constructing the `T` at `slot` it upholds the pinning invariants of `T`.
1040 #[inline]                                        975 #[inline]
1041 pub const unsafe fn pin_init_from_closure<T:     976 pub const unsafe fn pin_init_from_closure<T: ?Sized, E>(
1042     f: impl FnOnce(*mut T) -> Result<(), E>,     977     f: impl FnOnce(*mut T) -> Result<(), E>,
1043 ) -> impl PinInit<T, E> {                        978 ) -> impl PinInit<T, E> {
1044     __internal::InitClosure(f, PhantomData)      979     __internal::InitClosure(f, PhantomData)
1045 }                                                980 }
1046                                                  981 
1047 /// Creates a new [`Init<T, E>`] from the giv    982 /// Creates a new [`Init<T, E>`] from the given closure.
1048 ///                                              983 ///
1049 /// # Safety                                     984 /// # Safety
1050 ///                                              985 ///
1051 /// The closure:                                 986 /// The closure:
1052 /// - returns `Ok(())` if it initialized ever    987 /// - returns `Ok(())` if it initialized every field of `slot`,
1053 /// - returns `Err(err)` if it encountered an    988 /// - returns `Err(err)` if it encountered an error and then cleaned `slot`, this means:
1054 ///     - `slot` can be deallocated without U    989 ///     - `slot` can be deallocated without UB occurring,
1055 ///     - `slot` does not need to be dropped,    990 ///     - `slot` does not need to be dropped,
1056 ///     - `slot` is not partially initialized    991 ///     - `slot` is not partially initialized.
1057 /// - the `slot` may move after initializatio    992 /// - the `slot` may move after initialization.
1058 /// - while constructing the `T` at `slot` it    993 /// - while constructing the `T` at `slot` it upholds the pinning invariants of `T`.
1059 #[inline]                                        994 #[inline]
1060 pub const unsafe fn init_from_closure<T: ?Siz    995 pub const unsafe fn init_from_closure<T: ?Sized, E>(
1061     f: impl FnOnce(*mut T) -> Result<(), E>,     996     f: impl FnOnce(*mut T) -> Result<(), E>,
1062 ) -> impl Init<T, E> {                           997 ) -> impl Init<T, E> {
1063     __internal::InitClosure(f, PhantomData)      998     __internal::InitClosure(f, PhantomData)
1064 }                                                999 }
1065                                                  1000 
1066 /// An initializer that leaves the memory uni    1001 /// An initializer that leaves the memory uninitialized.
1067 ///                                              1002 ///
1068 /// The initializer is a no-op. The `slot` me    1003 /// The initializer is a no-op. The `slot` memory is not changed.
1069 #[inline]                                        1004 #[inline]
1070 pub fn uninit<T, E>() -> impl Init<MaybeUnini    1005 pub fn uninit<T, E>() -> impl Init<MaybeUninit<T>, E> {
1071     // SAFETY: The memory is allowed to be un    1006     // SAFETY: The memory is allowed to be uninitialized.
1072     unsafe { init_from_closure(|_| Ok(())) }     1007     unsafe { init_from_closure(|_| Ok(())) }
1073 }                                                1008 }
1074                                                  1009 
1075 /// Initializes an array by initializing each    1010 /// Initializes an array by initializing each element via the provided initializer.
1076 ///                                              1011 ///
1077 /// # Examples                                   1012 /// # Examples
1078 ///                                              1013 ///
1079 /// ```rust                                      1014 /// ```rust
1080 /// use kernel::{error::Error, init::init_arr    1015 /// use kernel::{error::Error, init::init_array_from_fn};
1081 /// let array: Box<[usize; 1_000]> = Box::ini !! 1016 /// let array: Box<[usize; 1_000]>= Box::init::<Error>(init_array_from_fn(|i| i)).unwrap();
1082 /// assert_eq!(array.len(), 1_000);              1017 /// assert_eq!(array.len(), 1_000);
1083 /// ```                                          1018 /// ```
1084 pub fn init_array_from_fn<I, const N: usize,     1019 pub fn init_array_from_fn<I, const N: usize, T, E>(
1085     mut make_init: impl FnMut(usize) -> I,       1020     mut make_init: impl FnMut(usize) -> I,
1086 ) -> impl Init<[T; N], E>                        1021 ) -> impl Init<[T; N], E>
1087 where                                            1022 where
1088     I: Init<T, E>,                               1023     I: Init<T, E>,
1089 {                                                1024 {
1090     let init = move |slot: *mut [T; N]| {        1025     let init = move |slot: *mut [T; N]| {
1091         let slot = slot.cast::<T>();             1026         let slot = slot.cast::<T>();
1092         // Counts the number of initialized e    1027         // Counts the number of initialized elements and when dropped drops that many elements from
1093         // `slot`.                               1028         // `slot`.
1094         let mut init_count = ScopeGuard::new_    1029         let mut init_count = ScopeGuard::new_with_data(0, |i| {
1095             // We now free every element that !! 1030             // We now free every element that has been initialized before:
1096             // SAFETY: The loop initialized e    1031             // SAFETY: The loop initialized exactly the values from 0..i and since we
1097             // return `Err` below, the caller    1032             // return `Err` below, the caller will consider the memory at `slot` as
1098             // uninitialized.                    1033             // uninitialized.
1099             unsafe { ptr::drop_in_place(ptr::    1034             unsafe { ptr::drop_in_place(ptr::slice_from_raw_parts_mut(slot, i)) };
1100         });                                      1035         });
1101         for i in 0..N {                          1036         for i in 0..N {
1102             let init = make_init(i);             1037             let init = make_init(i);
1103             // SAFETY: Since 0 <= `i` < N, it    1038             // SAFETY: Since 0 <= `i` < N, it is still in bounds of `[T; N]`.
1104             let ptr = unsafe { slot.add(i) };    1039             let ptr = unsafe { slot.add(i) };
1105             // SAFETY: The pointer is derived    1040             // SAFETY: The pointer is derived from `slot` and thus satisfies the `__init`
1106             // requirements.                     1041             // requirements.
1107             unsafe { init.__init(ptr) }?;        1042             unsafe { init.__init(ptr) }?;
1108             *init_count += 1;                    1043             *init_count += 1;
1109         }                                        1044         }
1110         init_count.dismiss();                    1045         init_count.dismiss();
1111         Ok(())                                   1046         Ok(())
1112     };                                           1047     };
1113     // SAFETY: The initializer above initiali    1048     // SAFETY: The initializer above initializes every element of the array. On failure it drops
1114     // any initialized elements and returns `    1049     // any initialized elements and returns `Err`.
1115     unsafe { init_from_closure(init) }           1050     unsafe { init_from_closure(init) }
1116 }                                                1051 }
1117                                                  1052 
1118 /// Initializes an array by initializing each    1053 /// Initializes an array by initializing each element via the provided initializer.
1119 ///                                              1054 ///
1120 /// # Examples                                   1055 /// # Examples
1121 ///                                              1056 ///
1122 /// ```rust                                      1057 /// ```rust
1123 /// use kernel::{sync::{Arc, Mutex}, init::pi    1058 /// use kernel::{sync::{Arc, Mutex}, init::pin_init_array_from_fn, new_mutex};
1124 /// let array: Arc<[Mutex<usize>; 1_000]> =   !! 1059 /// let array: Arc<[Mutex<usize>; 1_000]>=
1125 ///     Arc::pin_init(pin_init_array_from_fn( !! 1060 ///     Arc::pin_init(pin_init_array_from_fn(|i| new_mutex!(i))).unwrap();
1126 /// assert_eq!(array.len(), 1_000);              1061 /// assert_eq!(array.len(), 1_000);
1127 /// ```                                          1062 /// ```
1128 pub fn pin_init_array_from_fn<I, const N: usi    1063 pub fn pin_init_array_from_fn<I, const N: usize, T, E>(
1129     mut make_init: impl FnMut(usize) -> I,       1064     mut make_init: impl FnMut(usize) -> I,
1130 ) -> impl PinInit<[T; N], E>                     1065 ) -> impl PinInit<[T; N], E>
1131 where                                            1066 where
1132     I: PinInit<T, E>,                            1067     I: PinInit<T, E>,
1133 {                                                1068 {
1134     let init = move |slot: *mut [T; N]| {        1069     let init = move |slot: *mut [T; N]| {
1135         let slot = slot.cast::<T>();             1070         let slot = slot.cast::<T>();
1136         // Counts the number of initialized e    1071         // Counts the number of initialized elements and when dropped drops that many elements from
1137         // `slot`.                               1072         // `slot`.
1138         let mut init_count = ScopeGuard::new_    1073         let mut init_count = ScopeGuard::new_with_data(0, |i| {
1139             // We now free every element that !! 1074             // We now free every element that has been initialized before:
1140             // SAFETY: The loop initialized e    1075             // SAFETY: The loop initialized exactly the values from 0..i and since we
1141             // return `Err` below, the caller    1076             // return `Err` below, the caller will consider the memory at `slot` as
1142             // uninitialized.                    1077             // uninitialized.
1143             unsafe { ptr::drop_in_place(ptr::    1078             unsafe { ptr::drop_in_place(ptr::slice_from_raw_parts_mut(slot, i)) };
1144         });                                      1079         });
1145         for i in 0..N {                          1080         for i in 0..N {
1146             let init = make_init(i);             1081             let init = make_init(i);
1147             // SAFETY: Since 0 <= `i` < N, it    1082             // SAFETY: Since 0 <= `i` < N, it is still in bounds of `[T; N]`.
1148             let ptr = unsafe { slot.add(i) };    1083             let ptr = unsafe { slot.add(i) };
1149             // SAFETY: The pointer is derived    1084             // SAFETY: The pointer is derived from `slot` and thus satisfies the `__init`
1150             // requirements.                     1085             // requirements.
1151             unsafe { init.__pinned_init(ptr)     1086             unsafe { init.__pinned_init(ptr) }?;
1152             *init_count += 1;                    1087             *init_count += 1;
1153         }                                        1088         }
1154         init_count.dismiss();                    1089         init_count.dismiss();
1155         Ok(())                                   1090         Ok(())
1156     };                                           1091     };
1157     // SAFETY: The initializer above initiali    1092     // SAFETY: The initializer above initializes every element of the array. On failure it drops
1158     // any initialized elements and returns `    1093     // any initialized elements and returns `Err`.
1159     unsafe { pin_init_from_closure(init) }       1094     unsafe { pin_init_from_closure(init) }
1160 }                                                1095 }
1161                                                  1096 
1162 // SAFETY: Every type can be initialized by-v    1097 // SAFETY: Every type can be initialized by-value.
1163 unsafe impl<T, E> Init<T, E> for T {             1098 unsafe impl<T, E> Init<T, E> for T {
1164     unsafe fn __init(self, slot: *mut T) -> R    1099     unsafe fn __init(self, slot: *mut T) -> Result<(), E> {
1165         unsafe { slot.write(self) };             1100         unsafe { slot.write(self) };
1166         Ok(())                                   1101         Ok(())
1167     }                                            1102     }
1168 }                                                1103 }
1169                                                  1104 
1170 // SAFETY: Every type can be initialized by-v    1105 // SAFETY: Every type can be initialized by-value. `__pinned_init` calls `__init`.
1171 unsafe impl<T, E> PinInit<T, E> for T {          1106 unsafe impl<T, E> PinInit<T, E> for T {
1172     unsafe fn __pinned_init(self, slot: *mut     1107     unsafe fn __pinned_init(self, slot: *mut T) -> Result<(), E> {
1173         unsafe { self.__init(slot) }             1108         unsafe { self.__init(slot) }
1174     }                                            1109     }
1175 }                                                1110 }
1176                                                  1111 
1177 /// Smart pointer that can initialize memory     1112 /// Smart pointer that can initialize memory in-place.
1178 pub trait InPlaceInit<T>: Sized {                1113 pub trait InPlaceInit<T>: Sized {
1179     /// Pinned version of `Self`.             << 
1180     ///                                       << 
1181     /// If a type already implicitly pins its << 
1182     /// `Self`, otherwise just use `Pin<Self> << 
1183     type PinnedSelf;                          << 
1184                                               << 
1185     /// Use the given pin-initializer to pin-    1114     /// Use the given pin-initializer to pin-initialize a `T` inside of a new smart pointer of this
1186     /// type.                                    1115     /// type.
1187     ///                                          1116     ///
1188     /// If `T: !Unpin` it will not be able to    1117     /// If `T: !Unpin` it will not be able to move afterwards.
1189     fn try_pin_init<E>(init: impl PinInit<T,  !! 1118     fn try_pin_init<E>(init: impl PinInit<T, E>) -> Result<Pin<Self>, E>
1190     where                                        1119     where
1191         E: From<AllocError>;                     1120         E: From<AllocError>;
1192                                                  1121 
1193     /// Use the given pin-initializer to pin-    1122     /// Use the given pin-initializer to pin-initialize a `T` inside of a new smart pointer of this
1194     /// type.                                    1123     /// type.
1195     ///                                          1124     ///
1196     /// If `T: !Unpin` it will not be able to    1125     /// If `T: !Unpin` it will not be able to move afterwards.
1197     fn pin_init<E>(init: impl PinInit<T, E>,  !! 1126     fn pin_init<E>(init: impl PinInit<T, E>) -> error::Result<Pin<Self>>
1198     where                                        1127     where
1199         Error: From<E>,                          1128         Error: From<E>,
1200     {                                            1129     {
1201         // SAFETY: We delegate to `init` and     1130         // SAFETY: We delegate to `init` and only change the error type.
1202         let init = unsafe {                      1131         let init = unsafe {
1203             pin_init_from_closure(|slot| init    1132             pin_init_from_closure(|slot| init.__pinned_init(slot).map_err(|e| Error::from(e)))
1204         };                                       1133         };
1205         Self::try_pin_init(init, flags)       !! 1134         Self::try_pin_init(init)
1206     }                                            1135     }
1207                                                  1136 
1208     /// Use the given initializer to in-place    1137     /// Use the given initializer to in-place initialize a `T`.
1209     fn try_init<E>(init: impl Init<T, E>, fla !! 1138     fn try_init<E>(init: impl Init<T, E>) -> Result<Self, E>
1210     where                                        1139     where
1211         E: From<AllocError>;                     1140         E: From<AllocError>;
1212                                                  1141 
1213     /// Use the given initializer to in-place    1142     /// Use the given initializer to in-place initialize a `T`.
1214     fn init<E>(init: impl Init<T, E>, flags:  !! 1143     fn init<E>(init: impl Init<T, E>) -> error::Result<Self>
1215     where                                        1144     where
1216         Error: From<E>,                          1145         Error: From<E>,
1217     {                                            1146     {
1218         // SAFETY: We delegate to `init` and     1147         // SAFETY: We delegate to `init` and only change the error type.
1219         let init = unsafe {                      1148         let init = unsafe {
1220             init_from_closure(|slot| init.__p    1149             init_from_closure(|slot| init.__pinned_init(slot).map_err(|e| Error::from(e)))
1221         };                                       1150         };
1222         Self::try_init(init, flags)           !! 1151         Self::try_init(init)
1223     }                                         << 
1224 }                                             << 
1225                                               << 
1226 impl<T> InPlaceInit<T> for Arc<T> {           << 
1227     type PinnedSelf = Self;                   << 
1228                                               << 
1229     #[inline]                                 << 
1230     fn try_pin_init<E>(init: impl PinInit<T,  << 
1231     where                                     << 
1232         E: From<AllocError>,                  << 
1233     {                                         << 
1234         UniqueArc::try_pin_init(init, flags). << 
1235     }                                         << 
1236                                               << 
1237     #[inline]                                 << 
1238     fn try_init<E>(init: impl Init<T, E>, fla << 
1239     where                                     << 
1240         E: From<AllocError>,                  << 
1241     {                                         << 
1242         UniqueArc::try_init(init, flags).map( << 
1243     }                                            1152     }
1244 }                                                1153 }
1245                                                  1154 
1246 impl<T> InPlaceInit<T> for Box<T> {              1155 impl<T> InPlaceInit<T> for Box<T> {
1247     type PinnedSelf = Pin<Self>;              << 
1248                                               << 
1249     #[inline]                                    1156     #[inline]
1250     fn try_pin_init<E>(init: impl PinInit<T,  !! 1157     fn try_pin_init<E>(init: impl PinInit<T, E>) -> Result<Pin<Self>, E>
1251     where                                        1158     where
1252         E: From<AllocError>,                     1159         E: From<AllocError>,
1253     {                                            1160     {
1254         <Box<_> as BoxExt<_>>::new_uninit(fla !! 1161         let mut this = Box::try_new_uninit()?;
                                                   >> 1162         let slot = this.as_mut_ptr();
                                                   >> 1163         // SAFETY: When init errors/panics, slot will get deallocated but not dropped,
                                                   >> 1164         // slot is valid and will not be moved, because we pin it later.
                                                   >> 1165         unsafe { init.__pinned_init(slot)? };
                                                   >> 1166         // SAFETY: All fields have been initialized.
                                                   >> 1167         Ok(unsafe { this.assume_init() }.into())
1255     }                                            1168     }
1256                                                  1169 
1257     #[inline]                                    1170     #[inline]
1258     fn try_init<E>(init: impl Init<T, E>, fla !! 1171     fn try_init<E>(init: impl Init<T, E>) -> Result<Self, E>
1259     where                                        1172     where
1260         E: From<AllocError>,                     1173         E: From<AllocError>,
1261     {                                            1174     {
1262         <Box<_> as BoxExt<_>>::new_uninit(fla !! 1175         let mut this = Box::try_new_uninit()?;
                                                   >> 1176         let slot = this.as_mut_ptr();
                                                   >> 1177         // SAFETY: When init errors/panics, slot will get deallocated but not dropped,
                                                   >> 1178         // slot is valid.
                                                   >> 1179         unsafe { init.__init(slot)? };
                                                   >> 1180         // SAFETY: All fields have been initialized.
                                                   >> 1181         Ok(unsafe { this.assume_init() })
1263     }                                            1182     }
1264 }                                                1183 }
1265                                                  1184 
1266 impl<T> InPlaceInit<T> for UniqueArc<T> {        1185 impl<T> InPlaceInit<T> for UniqueArc<T> {
1267     type PinnedSelf = Pin<Self>;              << 
1268                                               << 
1269     #[inline]                                 << 
1270     fn try_pin_init<E>(init: impl PinInit<T,  << 
1271     where                                     << 
1272         E: From<AllocError>,                  << 
1273     {                                         << 
1274         UniqueArc::new_uninit(flags)?.write_p << 
1275     }                                         << 
1276                                               << 
1277     #[inline]                                    1186     #[inline]
1278     fn try_init<E>(init: impl Init<T, E>, fla !! 1187     fn try_pin_init<E>(init: impl PinInit<T, E>) -> Result<Pin<Self>, E>
1279     where                                        1188     where
1280         E: From<AllocError>,                     1189         E: From<AllocError>,
1281     {                                            1190     {
1282         UniqueArc::new_uninit(flags)?.write_i !! 1191         let mut this = UniqueArc::try_new_uninit()?;
1283     }                                         !! 1192         let slot = this.as_mut_ptr();
1284 }                                             << 
1285                                               << 
1286 /// Smart pointer containing uninitialized me << 
1287 pub trait InPlaceWrite<T> {                   << 
1288     /// The type `Self` turns into when the c << 
1289     type Initialized;                         << 
1290                                               << 
1291     /// Use the given initializer to write a  << 
1292     ///                                       << 
1293     /// Does not drop the current value and c << 
1294     fn write_init<E>(self, init: impl Init<T, << 
1295                                               << 
1296     /// Use the given pin-initializer to writ << 
1297     ///                                       << 
1298     /// Does not drop the current value and c << 
1299     fn write_pin_init<E>(self, init: impl Pin << 
1300 }                                             << 
1301                                               << 
1302 impl<T> InPlaceWrite<T> for Box<MaybeUninit<T << 
1303     type Initialized = Box<T>;                << 
1304                                               << 
1305     fn write_init<E>(mut self, init: impl Ini << 
1306         let slot = self.as_mut_ptr();         << 
1307         // SAFETY: When init errors/panics, s << 
1308         // slot is valid.                     << 
1309         unsafe { init.__init(slot)? };        << 
1310         // SAFETY: All fields have been initi << 
1311         Ok(unsafe { self.assume_init() })     << 
1312     }                                         << 
1313                                               << 
1314     fn write_pin_init<E>(mut self, init: impl << 
1315         let slot = self.as_mut_ptr();         << 
1316         // SAFETY: When init errors/panics, s    1193         // SAFETY: When init errors/panics, slot will get deallocated but not dropped,
1317         // slot is valid and will not be move    1194         // slot is valid and will not be moved, because we pin it later.
1318         unsafe { init.__pinned_init(slot)? };    1195         unsafe { init.__pinned_init(slot)? };
1319         // SAFETY: All fields have been initi    1196         // SAFETY: All fields have been initialized.
1320         Ok(unsafe { self.assume_init() }.into !! 1197         Ok(unsafe { this.assume_init() }.into())
1321     }                                            1198     }
1322 }                                             << 
1323                                                  1199 
1324 impl<T> InPlaceWrite<T> for UniqueArc<MaybeUn !! 1200     #[inline]
1325     type Initialized = UniqueArc<T>;          !! 1201     fn try_init<E>(init: impl Init<T, E>) -> Result<Self, E>
1326                                               !! 1202     where
1327     fn write_init<E>(mut self, init: impl Ini !! 1203         E: From<AllocError>,
1328         let slot = self.as_mut_ptr();         !! 1204     {
                                                   >> 1205         let mut this = UniqueArc::try_new_uninit()?;
                                                   >> 1206         let slot = this.as_mut_ptr();
1329         // SAFETY: When init errors/panics, s    1207         // SAFETY: When init errors/panics, slot will get deallocated but not dropped,
1330         // slot is valid.                        1208         // slot is valid.
1331         unsafe { init.__init(slot)? };           1209         unsafe { init.__init(slot)? };
1332         // SAFETY: All fields have been initi    1210         // SAFETY: All fields have been initialized.
1333         Ok(unsafe { self.assume_init() })     !! 1211         Ok(unsafe { this.assume_init() })
1334     }                                         << 
1335                                               << 
1336     fn write_pin_init<E>(mut self, init: impl << 
1337         let slot = self.as_mut_ptr();         << 
1338         // SAFETY: When init errors/panics, s << 
1339         // slot is valid and will not be move << 
1340         unsafe { init.__pinned_init(slot)? }; << 
1341         // SAFETY: All fields have been initi << 
1342         Ok(unsafe { self.assume_init() }.into << 
1343     }                                            1212     }
1344 }                                                1213 }
1345                                                  1214 
1346 /// Trait facilitating pinned destruction.       1215 /// Trait facilitating pinned destruction.
1347 ///                                              1216 ///
1348 /// Use [`pinned_drop`] to implement this tra    1217 /// Use [`pinned_drop`] to implement this trait safely:
1349 ///                                              1218 ///
1350 /// ```rust                                      1219 /// ```rust
1351 /// # use kernel::sync::Mutex;                   1220 /// # use kernel::sync::Mutex;
1352 /// use kernel::macros::pinned_drop;             1221 /// use kernel::macros::pinned_drop;
1353 /// use core::pin::Pin;                          1222 /// use core::pin::Pin;
1354 /// #[pin_data(PinnedDrop)]                      1223 /// #[pin_data(PinnedDrop)]
1355 /// struct Foo {                                 1224 /// struct Foo {
1356 ///     #[pin]                                   1225 ///     #[pin]
1357 ///     mtx: Mutex<usize>,                       1226 ///     mtx: Mutex<usize>,
1358 /// }                                            1227 /// }
1359 ///                                              1228 ///
1360 /// #[pinned_drop]                               1229 /// #[pinned_drop]
1361 /// impl PinnedDrop for Foo {                    1230 /// impl PinnedDrop for Foo {
1362 ///     fn drop(self: Pin<&mut Self>) {          1231 ///     fn drop(self: Pin<&mut Self>) {
1363 ///         pr_info!("Foo is being dropped!")    1232 ///         pr_info!("Foo is being dropped!");
1364 ///     }                                        1233 ///     }
1365 /// }                                            1234 /// }
1366 /// ```                                          1235 /// ```
1367 ///                                              1236 ///
1368 /// # Safety                                     1237 /// # Safety
1369 ///                                              1238 ///
1370 /// This trait must be implemented via the [`    1239 /// This trait must be implemented via the [`pinned_drop`] proc-macro attribute on the impl.
1371 ///                                              1240 ///
1372 /// [`pinned_drop`]: kernel::macros::pinned_d    1241 /// [`pinned_drop`]: kernel::macros::pinned_drop
1373 pub unsafe trait PinnedDrop: __internal::HasP    1242 pub unsafe trait PinnedDrop: __internal::HasPinData {
1374     /// Executes the pinned destructor of thi    1243     /// Executes the pinned destructor of this type.
1375     ///                                          1244     ///
1376     /// While this function is marked safe, i    1245     /// While this function is marked safe, it is actually unsafe to call it manually. For this
1377     /// reason it takes an additional paramet    1246     /// reason it takes an additional parameter. This type can only be constructed by `unsafe` code
1378     /// and thus prevents this function from     1247     /// and thus prevents this function from being called where it should not.
1379     ///                                          1248     ///
1380     /// This extra parameter will be generate    1249     /// This extra parameter will be generated by the `#[pinned_drop]` proc-macro attribute
1381     /// automatically.                           1250     /// automatically.
1382     fn drop(self: Pin<&mut Self>, only_call_f    1251     fn drop(self: Pin<&mut Self>, only_call_from_drop: __internal::OnlyCallFromDrop);
1383 }                                                1252 }
1384                                                  1253 
1385 /// Marker trait for types that can be initia    1254 /// Marker trait for types that can be initialized by writing just zeroes.
1386 ///                                              1255 ///
1387 /// # Safety                                     1256 /// # Safety
1388 ///                                              1257 ///
1389 /// The bit pattern consisting of only zeroes    1258 /// The bit pattern consisting of only zeroes is a valid bit pattern for this type. In other words,
1390 /// this is not UB:                              1259 /// this is not UB:
1391 ///                                              1260 ///
1392 /// ```rust,ignore                               1261 /// ```rust,ignore
1393 /// let val: Self = unsafe { core::mem::zeroe    1262 /// let val: Self = unsafe { core::mem::zeroed() };
1394 /// ```                                          1263 /// ```
1395 pub unsafe trait Zeroable {}                     1264 pub unsafe trait Zeroable {}
1396                                                  1265 
1397 /// Create a new zeroed T.                       1266 /// Create a new zeroed T.
1398 ///                                              1267 ///
1399 /// The returned initializer will write `0x00    1268 /// The returned initializer will write `0x00` to every byte of the given `slot`.
1400 #[inline]                                        1269 #[inline]
1401 pub fn zeroed<T: Zeroable>() -> impl Init<T>     1270 pub fn zeroed<T: Zeroable>() -> impl Init<T> {
1402     // SAFETY: Because `T: Zeroable`, all byt    1271     // SAFETY: Because `T: Zeroable`, all bytes zero is a valid bit pattern for `T`
1403     // and because we write all zeroes, the m    1272     // and because we write all zeroes, the memory is initialized.
1404     unsafe {                                     1273     unsafe {
1405         init_from_closure(|slot: *mut T| {       1274         init_from_closure(|slot: *mut T| {
1406             slot.write_bytes(0, 1);              1275             slot.write_bytes(0, 1);
1407             Ok(())                               1276             Ok(())
1408         })                                       1277         })
1409     }                                            1278     }
1410 }                                                1279 }
1411                                                  1280 
1412 macro_rules! impl_zeroable {                     1281 macro_rules! impl_zeroable {
1413     ($($({$($generics:tt)*})? $t:ty, )*) => {    1282     ($($({$($generics:tt)*})? $t:ty, )*) => {
1414         $(unsafe impl$($($generics)*)? Zeroab    1283         $(unsafe impl$($($generics)*)? Zeroable for $t {})*
1415     };                                           1284     };
1416 }                                                1285 }
1417                                                  1286 
1418 impl_zeroable! {                                 1287 impl_zeroable! {
1419     // SAFETY: All primitives that are allowe    1288     // SAFETY: All primitives that are allowed to be zero.
1420     bool,                                        1289     bool,
1421     char,                                        1290     char,
1422     u8, u16, u32, u64, u128, usize,              1291     u8, u16, u32, u64, u128, usize,
1423     i8, i16, i32, i64, i128, isize,              1292     i8, i16, i32, i64, i128, isize,
1424     f32, f64,                                    1293     f32, f64,
1425                                                  1294 
1426     // Note: do not add uninhabited types (su !! 1295     // SAFETY: These are ZSTs, there is nothing to zero.
1427     // creating an instance of an uninhabited !! 1296     {<T: ?Sized>} PhantomData<T>, core::marker::PhantomPinned, Infallible, (),
1428     // uninhabited/empty types, consult The R << 
1429     // <https://doc.rust-lang.org/stable/nomi << 
1430     // also has information on undefined beha << 
1431     // <https://doc.rust-lang.org/stable/refe << 
1432     //                                        << 
1433     // SAFETY: These are inhabited ZSTs; ther << 
1434     {<T: ?Sized>} PhantomData<T>, core::marke << 
1435                                                  1297 
1436     // SAFETY: Type is allowed to take any va    1298     // SAFETY: Type is allowed to take any value, including all zeros.
1437     {<T>} MaybeUninit<T>,                        1299     {<T>} MaybeUninit<T>,
1438     // SAFETY: Type is allowed to take any va    1300     // SAFETY: Type is allowed to take any value, including all zeros.
1439     {<T>} Opaque<T>,                             1301     {<T>} Opaque<T>,
1440                                                  1302 
1441     // SAFETY: `T: Zeroable` and `UnsafeCell`    1303     // SAFETY: `T: Zeroable` and `UnsafeCell` is `repr(transparent)`.
1442     {<T: ?Sized + Zeroable>} UnsafeCell<T>,      1304     {<T: ?Sized + Zeroable>} UnsafeCell<T>,
1443                                                  1305 
1444     // SAFETY: All zeros is equivalent to `No    1306     // SAFETY: All zeros is equivalent to `None` (option layout optimization guarantee).
1445     Option<NonZeroU8>, Option<NonZeroU16>, Op    1307     Option<NonZeroU8>, Option<NonZeroU16>, Option<NonZeroU32>, Option<NonZeroU64>,
1446     Option<NonZeroU128>, Option<NonZeroUsize>    1308     Option<NonZeroU128>, Option<NonZeroUsize>,
1447     Option<NonZeroI8>, Option<NonZeroI16>, Op    1309     Option<NonZeroI8>, Option<NonZeroI16>, Option<NonZeroI32>, Option<NonZeroI64>,
1448     Option<NonZeroI128>, Option<NonZeroIsize>    1310     Option<NonZeroI128>, Option<NonZeroIsize>,
1449                                                  1311 
1450     // SAFETY: All zeros is equivalent to `No    1312     // SAFETY: All zeros is equivalent to `None` (option layout optimization guarantee).
1451     //                                           1313     //
1452     // In this case we are allowed to use `T:    1314     // In this case we are allowed to use `T: ?Sized`, since all zeros is the `None` variant.
1453     {<T: ?Sized>} Option<NonNull<T>>,            1315     {<T: ?Sized>} Option<NonNull<T>>,
1454     {<T: ?Sized>} Option<Box<T>>,                1316     {<T: ?Sized>} Option<Box<T>>,
1455                                                  1317 
1456     // SAFETY: `null` pointer is valid.          1318     // SAFETY: `null` pointer is valid.
1457     //                                           1319     //
1458     // We cannot use `T: ?Sized`, since the V    1320     // We cannot use `T: ?Sized`, since the VTABLE pointer part of fat pointers is not allowed to be
1459     // null.                                     1321     // null.
1460     //                                           1322     //
1461     // When `Pointee` gets stabilized, we cou    1323     // When `Pointee` gets stabilized, we could use
1462     // `T: ?Sized where <T as Pointee>::Metad    1324     // `T: ?Sized where <T as Pointee>::Metadata: Zeroable`
1463     {<T>} *mut T, {<T>} *const T,                1325     {<T>} *mut T, {<T>} *const T,
1464                                                  1326 
1465     // SAFETY: `null` pointer is valid and th    1327     // SAFETY: `null` pointer is valid and the metadata part of these fat pointers is allowed to be
1466     // zero.                                     1328     // zero.
1467     {<T>} *mut [T], {<T>} *const [T], *mut st    1329     {<T>} *mut [T], {<T>} *const [T], *mut str, *const str,
1468                                                  1330 
1469     // SAFETY: `T` is `Zeroable`.                1331     // SAFETY: `T` is `Zeroable`.
1470     {<const N: usize, T: Zeroable>} [T; N], {    1332     {<const N: usize, T: Zeroable>} [T; N], {<T: Zeroable>} Wrapping<T>,
1471 }                                                1333 }
1472                                                  1334 
1473 macro_rules! impl_tuple_zeroable {               1335 macro_rules! impl_tuple_zeroable {
1474     ($(,)?) => {};                               1336     ($(,)?) => {};
1475     ($first:ident, $($t:ident),* $(,)?) => {     1337     ($first:ident, $($t:ident),* $(,)?) => {
1476         // SAFETY: All elements are zeroable     1338         // SAFETY: All elements are zeroable and padding can be zero.
1477         unsafe impl<$first: Zeroable, $($t: Z    1339         unsafe impl<$first: Zeroable, $($t: Zeroable),*> Zeroable for ($first, $($t),*) {}
1478         impl_tuple_zeroable!($($t),* ,);         1340         impl_tuple_zeroable!($($t),* ,);
1479     }                                            1341     }
1480 }                                                1342 }
1481                                                  1343 
1482 impl_tuple_zeroable!(A, B, C, D, E, F, G, H,     1344 impl_tuple_zeroable!(A, B, C, D, E, F, G, H, I, J);
                                                      

~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

kernel.org | git.kernel.org | LWN.net | Project Home | SVN repository | Mail admin

Linux® is a registered trademark of Linus Torvalds in the United States and other countries.
TOMOYO® is a registered trademark of NTT DATA CORPORATION.

sflogo.php