xref: /linux/rust/kernel/init.rs (revision 2e704f1883f5dd2f1380944c7d969c817fcd189e)
1 // SPDX-License-Identifier: Apache-2.0 OR MIT
2 
3 //! API to safely and fallibly initialize pinned `struct`s using in-place constructors.
4 //!
5 //! It also allows in-place initialization of big `struct`s that would otherwise produce a stack
6 //! overflow.
7 //!
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 Rust's way of ensuring data does not move.
10 //!
11 //! # Overview
12 //!
13 //! To initialize a `struct` with an in-place constructor you will need two things:
14 //! - an in-place constructor,
15 //! - a memory location that can hold your `struct` (this can be the [stack], an [`Arc<T>`],
16 //!   [`UniqueArc<T>`], [`Box<T>`] or any other smart pointer that implements [`InPlaceInit`]).
17 //!
18 //! To get an in-place constructor there are generally three options:
19 //! - directly creating an in-place constructor using the [`pin_init!`] macro,
20 //! - a custom function/macro returning an in-place constructor provided by someone else,
21 //! - using the unsafe function [`pin_init_from_closure()`] to manually create an initializer.
22 //!
23 //! Aside from pinned initialization, this API also supports in-place construction without pinning,
24 //! the macros/types/functions are generally named like the pinned variants without the `pin`
25 //! prefix.
26 //!
27 //! # Examples
28 //!
29 //! ## Using the [`pin_init!`] macro
30 //!
31 //! If you want to use [`PinInit`], then you will have to annotate your `struct` with
32 //! `#[`[`pin_data`]`]`. It is a macro that uses `#[pin]` as a marker for
33 //! [structurally pinned fields]. After doing this, you can then create an in-place constructor via
34 //! [`pin_init!`]. The syntax is almost the same as normal `struct` initializers. The difference is
35 //! that you need to write `<-` instead of `:` for fields that you want to initialize in-place.
36 //!
37 //! ```rust
38 //! # #![allow(clippy::disallowed_names, clippy::new_ret_no_self)]
39 //! use kernel::{prelude::*, sync::Mutex, new_mutex};
40 //! # use core::pin::Pin;
41 //! #[pin_data]
42 //! struct Foo {
43 //!     #[pin]
44 //!     a: Mutex<usize>,
45 //!     b: u32,
46 //! }
47 //!
48 //! let foo = pin_init!(Foo {
49 //!     a <- new_mutex!(42, "Foo::a"),
50 //!     b: 24,
51 //! });
52 //! ```
53 //!
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 a `Foo`:
56 //!
57 //! ```rust
58 //! # #![allow(clippy::disallowed_names, clippy::new_ret_no_self)]
59 //! # use kernel::{prelude::*, sync::Mutex, new_mutex};
60 //! # use core::pin::Pin;
61 //! # #[pin_data]
62 //! # struct Foo {
63 //! #     #[pin]
64 //! #     a: Mutex<usize>,
65 //! #     b: u32,
66 //! # }
67 //! # let foo = pin_init!(Foo {
68 //! #     a <- new_mutex!(42, "Foo::a"),
69 //! #     b: 24,
70 //! # });
71 //! let foo: Result<Pin<Box<Foo>>> = Box::pin_init(foo);
72 //! ```
73 //!
74 //! For more information see the [`pin_init!`] macro.
75 //!
76 //! ## Using a custom function/macro that returns an initializer
77 //!
78 //! Many types from the kernel supply a function/macro that returns an initializer, because the
79 //! above method only works for types where you can access the fields.
80 //!
81 //! ```rust
82 //! # use kernel::{new_mutex, sync::{Arc, Mutex}};
83 //! let mtx: Result<Arc<Mutex<usize>>> = Arc::pin_init(new_mutex!(42, "example::mtx"));
84 //! ```
85 //!
86 //! To declare an init macro/function you just return an [`impl PinInit<T, E>`]:
87 //!
88 //! ```rust
89 //! # #![allow(clippy::disallowed_names, clippy::new_ret_no_self)]
90 //! # use kernel::{sync::Mutex, prelude::*, new_mutex, init::PinInit, try_pin_init};
91 //! #[pin_data]
92 //! struct DriverData {
93 //!     #[pin]
94 //!     status: Mutex<i32>,
95 //!     buffer: Box<[u8; 1_000_000]>,
96 //! }
97 //!
98 //! impl DriverData {
99 //!     fn new() -> impl PinInit<Self, Error> {
100 //!         try_pin_init!(Self {
101 //!             status <- new_mutex!(0, "DriverData::status"),
102 //!             buffer: Box::init(kernel::init::zeroed())?,
103 //!         })
104 //!     }
105 //! }
106 //! ```
107 //!
108 //! ## Manual creation of an initializer
109 //!
110 //! Often when working with primitives the previous approaches are not sufficient. That is where
111 //! [`pin_init_from_closure()`] comes in. This `unsafe` function allows you to create a
112 //! [`impl PinInit<T, E>`] directly from a closure. Of course you have to ensure that the closure
113 //! actually does the initialization in the correct way. Here are the things to look out for
114 //! (we are calling the parameter to the closure `slot`):
115 //! - when the closure returns `Ok(())`, then it has completed the initialization successfully, so
116 //!   `slot` now contains a valid bit pattern for the type `T`,
117 //! - when the closure returns `Err(e)`, then the caller may deallocate the memory at `slot`, so
118 //!   you need to take care to clean up anything if your initialization fails mid-way,
119 //! - you may assume that `slot` will stay pinned even after the closure returns until `drop` of
120 //!   `slot` gets called.
121 //!
122 //! ```rust
123 //! use kernel::{prelude::*, init};
124 //! use core::{ptr::addr_of_mut, marker::PhantomPinned, pin::Pin};
125 //! # mod bindings {
126 //! #     pub struct foo;
127 //! #     pub unsafe fn init_foo(_ptr: *mut foo) {}
128 //! #     pub unsafe fn destroy_foo(_ptr: *mut foo) {}
129 //! #     pub unsafe fn enable_foo(_ptr: *mut foo, _flags: u32) -> i32 { 0 }
130 //! # }
131 //! /// # Invariants
132 //! ///
133 //! /// `foo` is always initialized
134 //! #[pin_data(PinnedDrop)]
135 //! pub struct RawFoo {
136 //!     #[pin]
137 //!     foo: Opaque<bindings::foo>,
138 //!     #[pin]
139 //!     _p: PhantomPinned,
140 //! }
141 //!
142 //! impl RawFoo {
143 //!     pub fn new(flags: u32) -> impl PinInit<Self, Error> {
144 //!         // SAFETY:
145 //!         // - when the closure returns `Ok(())`, then it has successfully initialized and
146 //!         //   enabled `foo`,
147 //!         // - when it returns `Err(e)`, then it has cleaned up before
148 //!         unsafe {
149 //!             init::pin_init_from_closure(move |slot: *mut Self| {
150 //!                 // `slot` contains uninit memory, avoid creating a reference.
151 //!                 let foo = addr_of_mut!((*slot).foo);
152 //!
153 //!                 // Initialize the `foo`
154 //!                 bindings::init_foo(Opaque::raw_get(foo));
155 //!
156 //!                 // Try to enable it.
157 //!                 let err = bindings::enable_foo(Opaque::raw_get(foo), flags);
158 //!                 if err != 0 {
159 //!                     // Enabling has failed, first clean up the foo and then return the error.
160 //!                     bindings::destroy_foo(Opaque::raw_get(foo));
161 //!                     return Err(Error::from_kernel_errno(err));
162 //!                 }
163 //!
164 //!                 // All fields of `RawFoo` have been initialized, since `_p` is a ZST.
165 //!                 Ok(())
166 //!             })
167 //!         }
168 //!     }
169 //! }
170 //!
171 //! #[pinned_drop]
172 //! impl PinnedDrop for RawFoo {
173 //!     fn drop(self: Pin<&mut Self>) {
174 //!         // SAFETY: Since `foo` is initialized, destroying is safe.
175 //!         unsafe { bindings::destroy_foo(self.foo.get()) };
176 //!     }
177 //! }
178 //! ```
179 //!
180 //! For the special case where initializing a field is a single FFI-function call that cannot fail,
181 //! there exist the helper function [`Opaque::ffi_init`]. This function initialize a single
182 //! [`Opaque`] field by just delegating to the supplied closure. You can use these in combination
183 //! with [`pin_init!`].
184 //!
185 //! For more information on how to use [`pin_init_from_closure()`], take a look at the uses inside
186 //! the `kernel` crate. The [`sync`] module is a good starting point.
187 //!
188 //! [`sync`]: kernel::sync
189 //! [pinning]: https://doc.rust-lang.org/std/pin/index.html
190 //! [structurally pinned fields]:
191 //!     https://doc.rust-lang.org/std/pin/index.html#pinning-is-structural-for-field
192 //! [stack]: crate::stack_pin_init
193 //! [`Arc<T>`]: crate::sync::Arc
194 //! [`impl PinInit<Foo>`]: PinInit
195 //! [`impl PinInit<T, E>`]: PinInit
196 //! [`impl Init<T, E>`]: Init
197 //! [`Opaque`]: kernel::types::Opaque
198 //! [`Opaque::ffi_init`]: kernel::types::Opaque::ffi_init
199 //! [`pin_data`]: ::macros::pin_data
200 //! [`pin_init!`]: crate::pin_init!
201 
202 use crate::{
203     error::{self, Error},
204     sync::UniqueArc,
205     types::{Opaque, ScopeGuard},
206 };
207 use alloc::boxed::Box;
208 use core::{
209     alloc::AllocError,
210     cell::UnsafeCell,
211     convert::Infallible,
212     marker::PhantomData,
213     mem::MaybeUninit,
214     num::*,
215     pin::Pin,
216     ptr::{self, NonNull},
217 };
218 
219 #[doc(hidden)]
220 pub mod __internal;
221 #[doc(hidden)]
222 pub mod macros;
223 
224 /// Initialize and pin a type directly on the stack.
225 ///
226 /// # Examples
227 ///
228 /// ```rust
229 /// # #![allow(clippy::disallowed_names, clippy::new_ret_no_self)]
230 /// # use kernel::{init, pin_init, stack_pin_init, init::*, sync::Mutex, new_mutex};
231 /// # use macros::pin_data;
232 /// # use core::pin::Pin;
233 /// #[pin_data]
234 /// struct Foo {
235 ///     #[pin]
236 ///     a: Mutex<usize>,
237 ///     b: Bar,
238 /// }
239 ///
240 /// #[pin_data]
241 /// struct Bar {
242 ///     x: u32,
243 /// }
244 ///
245 /// stack_pin_init!(let foo = pin_init!(Foo {
246 ///     a <- new_mutex!(42),
247 ///     b: Bar {
248 ///         x: 64,
249 ///     },
250 /// }));
251 /// let foo: Pin<&mut Foo> = foo;
252 /// pr_info!("a: {}", &*foo.a.lock());
253 /// ```
254 ///
255 /// # Syntax
256 ///
257 /// A normal `let` binding with optional type annotation. The expression is expected to implement
258 /// [`PinInit`]/[`Init`] with the error type [`Infallible`]. If you want to use a different error
259 /// type, then use [`stack_try_pin_init!`].
260 ///
261 /// [`stack_try_pin_init!`]: crate::stack_try_pin_init!
262 #[macro_export]
263 macro_rules! stack_pin_init {
264     (let $var:ident $(: $t:ty)? = $val:expr) => {
265         let val = $val;
266         let mut $var = ::core::pin::pin!($crate::init::__internal::StackInit$(::<$t>)?::uninit());
267         let mut $var = match $crate::init::__internal::StackInit::init($var, val) {
268             Ok(res) => res,
269             Err(x) => {
270                 let x: ::core::convert::Infallible = x;
271                 match x {}
272             }
273         };
274     };
275 }
276 
277 /// Initialize and pin a type directly on the stack.
278 ///
279 /// # Examples
280 ///
281 /// ```rust
282 /// # #![allow(clippy::disallowed_names, clippy::new_ret_no_self)]
283 /// # use kernel::{init, pin_init, stack_try_pin_init, init::*, sync::Mutex, new_mutex};
284 /// # use macros::pin_data;
285 /// # use core::{alloc::AllocError, pin::Pin};
286 /// #[pin_data]
287 /// struct Foo {
288 ///     #[pin]
289 ///     a: Mutex<usize>,
290 ///     b: Box<Bar>,
291 /// }
292 ///
293 /// struct Bar {
294 ///     x: u32,
295 /// }
296 ///
297 /// stack_try_pin_init!(let foo: Result<Pin<&mut Foo>, AllocError> = pin_init!(Foo {
298 ///     a <- new_mutex!(42),
299 ///     b: Box::try_new(Bar {
300 ///         x: 64,
301 ///     })?,
302 /// }));
303 /// let foo = foo.unwrap();
304 /// pr_info!("a: {}", &*foo.a.lock());
305 /// ```
306 ///
307 /// ```rust
308 /// # #![allow(clippy::disallowed_names, clippy::new_ret_no_self)]
309 /// # use kernel::{init, pin_init, stack_try_pin_init, init::*, sync::Mutex, new_mutex};
310 /// # use macros::pin_data;
311 /// # use core::{alloc::AllocError, pin::Pin};
312 /// #[pin_data]
313 /// struct Foo {
314 ///     #[pin]
315 ///     a: Mutex<usize>,
316 ///     b: Box<Bar>,
317 /// }
318 ///
319 /// struct Bar {
320 ///     x: u32,
321 /// }
322 ///
323 /// stack_try_pin_init!(let foo: Pin<&mut Foo> =? pin_init!(Foo {
324 ///     a <- new_mutex!(42),
325 ///     b: Box::try_new(Bar {
326 ///         x: 64,
327 ///     })?,
328 /// }));
329 /// pr_info!("a: {}", &*foo.a.lock());
330 /// # Ok::<_, AllocError>(())
331 /// ```
332 ///
333 /// # Syntax
334 ///
335 /// A normal `let` binding with optional type annotation. The expression is expected to implement
336 /// [`PinInit`]/[`Init`]. This macro assigns a result to the given variable, adding a `?` after the
337 /// `=` will propagate this error.
338 #[macro_export]
339 macro_rules! stack_try_pin_init {
340     (let $var:ident $(: $t:ty)? = $val:expr) => {
341         let val = $val;
342         let mut $var = ::core::pin::pin!($crate::init::__internal::StackInit$(::<$t>)?::uninit());
343         let mut $var = $crate::init::__internal::StackInit::init($var, val);
344     };
345     (let $var:ident $(: $t:ty)? =? $val:expr) => {
346         let val = $val;
347         let mut $var = ::core::pin::pin!($crate::init::__internal::StackInit$(::<$t>)?::uninit());
348         let mut $var = $crate::init::__internal::StackInit::init($var, val)?;
349     };
350 }
351 
352 /// Construct an in-place, pinned initializer for `struct`s.
353 ///
354 /// This macro defaults the error to [`Infallible`]. If you need [`Error`], then use
355 /// [`try_pin_init!`].
356 ///
357 /// The syntax is almost identical to that of a normal `struct` initializer:
358 ///
359 /// ```rust
360 /// # #![allow(clippy::disallowed_names, clippy::new_ret_no_self)]
361 /// # use kernel::{init, pin_init, macros::pin_data, init::*};
362 /// # use core::pin::Pin;
363 /// #[pin_data]
364 /// struct Foo {
365 ///     a: usize,
366 ///     b: Bar,
367 /// }
368 ///
369 /// #[pin_data]
370 /// struct Bar {
371 ///     x: u32,
372 /// }
373 ///
374 /// # fn demo() -> impl PinInit<Foo> {
375 /// let a = 42;
376 ///
377 /// let initializer = pin_init!(Foo {
378 ///     a,
379 ///     b: Bar {
380 ///         x: 64,
381 ///     },
382 /// });
383 /// # initializer }
384 /// # Box::pin_init(demo()).unwrap();
385 /// ```
386 ///
387 /// Arbitrary Rust expressions can be used to set the value of a variable.
388 ///
389 /// The fields are initialized in the order that they appear in the initializer. So it is possible
390 /// to read already initialized fields using raw pointers.
391 ///
392 /// IMPORTANT: You are not allowed to create references to fields of the struct inside of the
393 /// initializer.
394 ///
395 /// # Init-functions
396 ///
397 /// When working with this API it is often desired to let others construct your types without
398 /// giving access to all fields. This is where you would normally write a plain function `new`
399 /// that would return a new instance of your type. With this API that is also possible.
400 /// However, there are a few extra things to keep in mind.
401 ///
402 /// To create an initializer function, simply declare it like this:
403 ///
404 /// ```rust
405 /// # #![allow(clippy::disallowed_names, clippy::new_ret_no_self)]
406 /// # use kernel::{init, pin_init, prelude::*, init::*};
407 /// # use core::pin::Pin;
408 /// # #[pin_data]
409 /// # struct Foo {
410 /// #     a: usize,
411 /// #     b: Bar,
412 /// # }
413 /// # #[pin_data]
414 /// # struct Bar {
415 /// #     x: u32,
416 /// # }
417 /// impl Foo {
418 ///     fn new() -> impl PinInit<Self> {
419 ///         pin_init!(Self {
420 ///             a: 42,
421 ///             b: Bar {
422 ///                 x: 64,
423 ///             },
424 ///         })
425 ///     }
426 /// }
427 /// ```
428 ///
429 /// Users of `Foo` can now create it like this:
430 ///
431 /// ```rust
432 /// # #![allow(clippy::disallowed_names, clippy::new_ret_no_self)]
433 /// # use kernel::{init, pin_init, macros::pin_data, init::*};
434 /// # use core::pin::Pin;
435 /// # #[pin_data]
436 /// # struct Foo {
437 /// #     a: usize,
438 /// #     b: Bar,
439 /// # }
440 /// # #[pin_data]
441 /// # struct Bar {
442 /// #     x: u32,
443 /// # }
444 /// # impl Foo {
445 /// #     fn new() -> impl PinInit<Self> {
446 /// #         pin_init!(Self {
447 /// #             a: 42,
448 /// #             b: Bar {
449 /// #                 x: 64,
450 /// #             },
451 /// #         })
452 /// #     }
453 /// # }
454 /// let foo = Box::pin_init(Foo::new());
455 /// ```
456 ///
457 /// They can also easily embed it into their own `struct`s:
458 ///
459 /// ```rust
460 /// # #![allow(clippy::disallowed_names, clippy::new_ret_no_self)]
461 /// # use kernel::{init, pin_init, macros::pin_data, init::*};
462 /// # use core::pin::Pin;
463 /// # #[pin_data]
464 /// # struct Foo {
465 /// #     a: usize,
466 /// #     b: Bar,
467 /// # }
468 /// # #[pin_data]
469 /// # struct Bar {
470 /// #     x: u32,
471 /// # }
472 /// # impl Foo {
473 /// #     fn new() -> impl PinInit<Self> {
474 /// #         pin_init!(Self {
475 /// #             a: 42,
476 /// #             b: Bar {
477 /// #                 x: 64,
478 /// #             },
479 /// #         })
480 /// #     }
481 /// # }
482 /// #[pin_data]
483 /// struct FooContainer {
484 ///     #[pin]
485 ///     foo1: Foo,
486 ///     #[pin]
487 ///     foo2: Foo,
488 ///     other: u32,
489 /// }
490 ///
491 /// impl FooContainer {
492 ///     fn new(other: u32) -> impl PinInit<Self> {
493 ///         pin_init!(Self {
494 ///             foo1 <- Foo::new(),
495 ///             foo2 <- Foo::new(),
496 ///             other,
497 ///         })
498 ///     }
499 /// }
500 /// ```
501 ///
502 /// Here we see that when using `pin_init!` with `PinInit`, one needs to write `<-` instead of `:`.
503 /// This signifies that the given field is initialized in-place. As with `struct` initializers, just
504 /// writing the field (in this case `other`) without `:` or `<-` means `other: other,`.
505 ///
506 /// # Syntax
507 ///
508 /// As already mentioned in the examples above, inside of `pin_init!` a `struct` initializer with
509 /// the following modifications is expected:
510 /// - Fields that you want to initialize in-place have to use `<-` instead of `:`.
511 /// - In front of the initializer you can write `&this in` to have access to a [`NonNull<Self>`]
512 ///   pointer named `this` inside of the initializer.
513 /// - Using struct update syntax one can place `..Zeroable::zeroed()` at the very end of the
514 ///   struct, this initializes every field with 0 and then runs all initializers specified in the
515 ///   body. This can only be done if [`Zeroable`] is implemented for the struct.
516 ///
517 /// For instance:
518 ///
519 /// ```rust
520 /// # use kernel::pin_init;
521 /// # use macros::{Zeroable, pin_data};
522 /// # use core::{ptr::addr_of_mut, marker::PhantomPinned};
523 /// #[pin_data]
524 /// #[derive(Zeroable)]
525 /// struct Buf {
526 ///     // `ptr` points into `buf`.
527 ///     ptr: *mut u8,
528 ///     buf: [u8; 64],
529 ///     #[pin]
530 ///     pin: PhantomPinned,
531 /// }
532 /// pin_init!(&this in Buf {
533 ///     buf: [0; 64],
534 ///     ptr: unsafe { addr_of_mut!((*this.as_ptr()).buf).cast() },
535 ///     pin: PhantomPinned,
536 /// });
537 /// pin_init!(Buf {
538 ///     buf: [1; 64],
539 ///     ..Zeroable::zeroed()
540 /// });
541 /// ```
542 ///
543 /// [`try_pin_init!`]: kernel::try_pin_init
544 /// [`NonNull<Self>`]: core::ptr::NonNull
545 // For a detailed example of how this macro works, see the module documentation of the hidden
546 // module `__internal` inside of `init/__internal.rs`.
547 #[macro_export]
548 macro_rules! pin_init {
549     ($(&$this:ident in)? $t:ident $(::<$($generics:ty),* $(,)?>)? {
550         $($fields:tt)*
551     }) => {
552         $crate::__init_internal!(
553             @this($($this)?),
554             @typ($t $(::<$($generics),*>)?),
555             @fields($($fields)*),
556             @error(::core::convert::Infallible),
557             @data(PinData, use_data),
558             @has_data(HasPinData, __pin_data),
559             @construct_closure(pin_init_from_closure),
560             @munch_fields($($fields)*),
561         )
562     };
563 }
564 
565 /// Construct an in-place, fallible pinned initializer for `struct`s.
566 ///
567 /// If the initialization can complete without error (or [`Infallible`]), then use [`pin_init!`].
568 ///
569 /// You can use the `?` operator or use `return Err(err)` inside the initializer to stop
570 /// initialization and return the error.
571 ///
572 /// IMPORTANT: if you have `unsafe` code inside of the initializer you have to ensure that when
573 /// initialization fails, the memory can be safely deallocated without any further modifications.
574 ///
575 /// This macro defaults the error to [`Error`].
576 ///
577 /// The syntax is identical to [`pin_init!`] with the following exception: you can append `? $type`
578 /// after the `struct` initializer to specify the error type you want to use.
579 ///
580 /// # Examples
581 ///
582 /// ```rust
583 /// # #![feature(new_uninit)]
584 /// use kernel::{init::{self, PinInit}, error::Error};
585 /// #[pin_data]
586 /// struct BigBuf {
587 ///     big: Box<[u8; 1024 * 1024 * 1024]>,
588 ///     small: [u8; 1024 * 1024],
589 ///     ptr: *mut u8,
590 /// }
591 ///
592 /// impl BigBuf {
593 ///     fn new() -> impl PinInit<Self, Error> {
594 ///         try_pin_init!(Self {
595 ///             big: Box::init(init::zeroed())?,
596 ///             small: [0; 1024 * 1024],
597 ///             ptr: core::ptr::null_mut(),
598 ///         }? Error)
599 ///     }
600 /// }
601 /// ```
602 // For a detailed example of how this macro works, see the module documentation of the hidden
603 // module `__internal` inside of `init/__internal.rs`.
604 #[macro_export]
605 macro_rules! try_pin_init {
606     ($(&$this:ident in)? $t:ident $(::<$($generics:ty),* $(,)?>)? {
607         $($fields:tt)*
608     }) => {
609         $crate::__init_internal!(
610             @this($($this)?),
611             @typ($t $(::<$($generics),*>)? ),
612             @fields($($fields)*),
613             @error($crate::error::Error),
614             @data(PinData, use_data),
615             @has_data(HasPinData, __pin_data),
616             @construct_closure(pin_init_from_closure),
617             @munch_fields($($fields)*),
618         )
619     };
620     ($(&$this:ident in)? $t:ident $(::<$($generics:ty),* $(,)?>)? {
621         $($fields:tt)*
622     }? $err:ty) => {
623         $crate::__init_internal!(
624             @this($($this)?),
625             @typ($t $(::<$($generics),*>)? ),
626             @fields($($fields)*),
627             @error($err),
628             @data(PinData, use_data),
629             @has_data(HasPinData, __pin_data),
630             @construct_closure(pin_init_from_closure),
631             @munch_fields($($fields)*),
632         )
633     };
634 }
635 
636 /// Construct an in-place initializer for `struct`s.
637 ///
638 /// This macro defaults the error to [`Infallible`]. If you need [`Error`], then use
639 /// [`try_init!`].
640 ///
641 /// The syntax is identical to [`pin_init!`] and its safety caveats also apply:
642 /// - `unsafe` code must guarantee either full initialization or return an error and allow
643 ///   deallocation of the memory.
644 /// - the fields are initialized in the order given in the initializer.
645 /// - no references to fields are allowed to be created inside of the initializer.
646 ///
647 /// This initializer is for initializing data in-place that might later be moved. If you want to
648 /// pin-initialize, use [`pin_init!`].
649 ///
650 /// [`try_init!`]: crate::try_init!
651 // For a detailed example of how this macro works, see the module documentation of the hidden
652 // module `__internal` inside of `init/__internal.rs`.
653 #[macro_export]
654 macro_rules! init {
655     ($(&$this:ident in)? $t:ident $(::<$($generics:ty),* $(,)?>)? {
656         $($fields:tt)*
657     }) => {
658         $crate::__init_internal!(
659             @this($($this)?),
660             @typ($t $(::<$($generics),*>)?),
661             @fields($($fields)*),
662             @error(::core::convert::Infallible),
663             @data(InitData, /*no use_data*/),
664             @has_data(HasInitData, __init_data),
665             @construct_closure(init_from_closure),
666             @munch_fields($($fields)*),
667         )
668     }
669 }
670 
671 /// Construct an in-place fallible initializer for `struct`s.
672 ///
673 /// This macro defaults the error to [`Error`]. If you need [`Infallible`], then use
674 /// [`init!`].
675 ///
676 /// The syntax is identical to [`try_pin_init!`]. If you want to specify a custom error,
677 /// append `? $type` after the `struct` initializer.
678 /// The safety caveats from [`try_pin_init!`] also apply:
679 /// - `unsafe` code must guarantee either full initialization or return an error and allow
680 ///   deallocation of the memory.
681 /// - the fields are initialized in the order given in the initializer.
682 /// - no references to fields are allowed to be created inside of the initializer.
683 ///
684 /// # Examples
685 ///
686 /// ```rust
687 /// use kernel::{init::PinInit, error::Error, InPlaceInit};
688 /// struct BigBuf {
689 ///     big: Box<[u8; 1024 * 1024 * 1024]>,
690 ///     small: [u8; 1024 * 1024],
691 /// }
692 ///
693 /// impl BigBuf {
694 ///     fn new() -> impl Init<Self, Error> {
695 ///         try_init!(Self {
696 ///             big: Box::init(zeroed())?,
697 ///             small: [0; 1024 * 1024],
698 ///         }? Error)
699 ///     }
700 /// }
701 /// ```
702 // For a detailed example of how this macro works, see the module documentation of the hidden
703 // module `__internal` inside of `init/__internal.rs`.
704 #[macro_export]
705 macro_rules! try_init {
706     ($(&$this:ident in)? $t:ident $(::<$($generics:ty),* $(,)?>)? {
707         $($fields:tt)*
708     }) => {
709         $crate::__init_internal!(
710             @this($($this)?),
711             @typ($t $(::<$($generics),*>)?),
712             @fields($($fields)*),
713             @error($crate::error::Error),
714             @data(InitData, /*no use_data*/),
715             @has_data(HasInitData, __init_data),
716             @construct_closure(init_from_closure),
717             @munch_fields($($fields)*),
718         )
719     };
720     ($(&$this:ident in)? $t:ident $(::<$($generics:ty),* $(,)?>)? {
721         $($fields:tt)*
722     }? $err:ty) => {
723         $crate::__init_internal!(
724             @this($($this)?),
725             @typ($t $(::<$($generics),*>)?),
726             @fields($($fields)*),
727             @error($err),
728             @data(InitData, /*no use_data*/),
729             @has_data(HasInitData, __init_data),
730             @construct_closure(init_from_closure),
731             @munch_fields($($fields)*),
732         )
733     };
734 }
735 
736 /// A pin-initializer for the type `T`.
737 ///
738 /// To use this initializer, you will need a suitable memory location that can hold a `T`. This can
739 /// be [`Box<T>`], [`Arc<T>`], [`UniqueArc<T>`] or even the stack (see [`stack_pin_init!`]). Use the
740 /// [`InPlaceInit::pin_init`] function of a smart pointer like [`Arc<T>`] on this.
741 ///
742 /// Also see the [module description](self).
743 ///
744 /// # Safety
745 ///
746 /// When implementing this type you will need to take great care. Also there are probably very few
747 /// cases where a manual implementation is necessary. Use [`pin_init_from_closure`] where possible.
748 ///
749 /// The [`PinInit::__pinned_init`] function
750 /// - returns `Ok(())` if it initialized every field of `slot`,
751 /// - returns `Err(err)` if it encountered an error and then cleaned `slot`, this means:
752 ///     - `slot` can be deallocated without UB occurring,
753 ///     - `slot` does not need to be dropped,
754 ///     - `slot` is not partially initialized.
755 /// - while constructing the `T` at `slot` it upholds the pinning invariants of `T`.
756 ///
757 /// [`Arc<T>`]: crate::sync::Arc
758 /// [`Arc::pin_init`]: crate::sync::Arc::pin_init
759 #[must_use = "An initializer must be used in order to create its value."]
760 pub unsafe trait PinInit<T: ?Sized, E = Infallible>: Sized {
761     /// Initializes `slot`.
762     ///
763     /// # Safety
764     ///
765     /// - `slot` is a valid pointer to uninitialized memory.
766     /// - the caller does not touch `slot` when `Err` is returned, they are only permitted to
767     ///   deallocate.
768     /// - `slot` will not move until it is dropped, i.e. it will be pinned.
769     unsafe fn __pinned_init(self, slot: *mut T) -> Result<(), E>;
770 }
771 
772 /// An initializer for `T`.
773 ///
774 /// To use this initializer, you will need a suitable memory location that can hold a `T`. This can
775 /// be [`Box<T>`], [`Arc<T>`], [`UniqueArc<T>`] or even the stack (see [`stack_pin_init!`]). Use the
776 /// [`InPlaceInit::init`] function of a smart pointer like [`Arc<T>`] on this. Because
777 /// [`PinInit<T, E>`] is a super trait, you can use every function that takes it as well.
778 ///
779 /// Also see the [module description](self).
780 ///
781 /// # Safety
782 ///
783 /// When implementing this type you will need to take great care. Also there are probably very few
784 /// cases where a manual implementation is necessary. Use [`init_from_closure`] where possible.
785 ///
786 /// The [`Init::__init`] function
787 /// - returns `Ok(())` if it initialized every field of `slot`,
788 /// - returns `Err(err)` if it encountered an error and then cleaned `slot`, this means:
789 ///     - `slot` can be deallocated without UB occurring,
790 ///     - `slot` does not need to be dropped,
791 ///     - `slot` is not partially initialized.
792 /// - while constructing the `T` at `slot` it upholds the pinning invariants of `T`.
793 ///
794 /// The `__pinned_init` function from the supertrait [`PinInit`] needs to execute the exact same
795 /// code as `__init`.
796 ///
797 /// Contrary to its supertype [`PinInit<T, E>`] the caller is allowed to
798 /// move the pointee after initialization.
799 ///
800 /// [`Arc<T>`]: crate::sync::Arc
801 #[must_use = "An initializer must be used in order to create its value."]
802 pub unsafe trait Init<T: ?Sized, E = Infallible>: Sized {
803     /// Initializes `slot`.
804     ///
805     /// # Safety
806     ///
807     /// - `slot` is a valid pointer to uninitialized memory.
808     /// - the caller does not touch `slot` when `Err` is returned, they are only permitted to
809     ///   deallocate.
810     unsafe fn __init(self, slot: *mut T) -> Result<(), E>;
811 }
812 
813 // SAFETY: Every in-place initializer can also be used as a pin-initializer.
814 unsafe impl<T: ?Sized, E, I> PinInit<T, E> for I
815 where
816     I: Init<T, E>,
817 {
818     unsafe fn __pinned_init(self, slot: *mut T) -> Result<(), E> {
819         // SAFETY: `__init` meets the same requirements as `__pinned_init`, except that it does not
820         // require `slot` to not move after init.
821         unsafe { self.__init(slot) }
822     }
823 }
824 
825 /// Creates a new [`PinInit<T, E>`] from the given closure.
826 ///
827 /// # Safety
828 ///
829 /// The closure:
830 /// - returns `Ok(())` if it initialized every field of `slot`,
831 /// - returns `Err(err)` if it encountered an error and then cleaned `slot`, this means:
832 ///     - `slot` can be deallocated without UB occurring,
833 ///     - `slot` does not need to be dropped,
834 ///     - `slot` is not partially initialized.
835 /// - may assume that the `slot` does not move if `T: !Unpin`,
836 /// - while constructing the `T` at `slot` it upholds the pinning invariants of `T`.
837 #[inline]
838 pub const unsafe fn pin_init_from_closure<T: ?Sized, E>(
839     f: impl FnOnce(*mut T) -> Result<(), E>,
840 ) -> impl PinInit<T, E> {
841     __internal::InitClosure(f, PhantomData)
842 }
843 
844 /// Creates a new [`Init<T, E>`] from the given closure.
845 ///
846 /// # Safety
847 ///
848 /// The closure:
849 /// - returns `Ok(())` if it initialized every field of `slot`,
850 /// - returns `Err(err)` if it encountered an error and then cleaned `slot`, this means:
851 ///     - `slot` can be deallocated without UB occurring,
852 ///     - `slot` does not need to be dropped,
853 ///     - `slot` is not partially initialized.
854 /// - the `slot` may move after initialization.
855 /// - while constructing the `T` at `slot` it upholds the pinning invariants of `T`.
856 #[inline]
857 pub const unsafe fn init_from_closure<T: ?Sized, E>(
858     f: impl FnOnce(*mut T) -> Result<(), E>,
859 ) -> impl Init<T, E> {
860     __internal::InitClosure(f, PhantomData)
861 }
862 
863 /// An initializer that leaves the memory uninitialized.
864 ///
865 /// The initializer is a no-op. The `slot` memory is not changed.
866 #[inline]
867 pub fn uninit<T, E>() -> impl Init<MaybeUninit<T>, E> {
868     // SAFETY: The memory is allowed to be uninitialized.
869     unsafe { init_from_closure(|_| Ok(())) }
870 }
871 
872 /// Initializes an array by initializing each element via the provided initializer.
873 ///
874 /// # Examples
875 ///
876 /// ```rust
877 /// use kernel::{error::Error, init::init_array_from_fn};
878 /// let array: Box<[usize; 1_000]>= Box::init::<Error>(init_array_from_fn(|i| i)).unwrap();
879 /// assert_eq!(array.len(), 1_000);
880 /// ```
881 pub fn init_array_from_fn<I, const N: usize, T, E>(
882     mut make_init: impl FnMut(usize) -> I,
883 ) -> impl Init<[T; N], E>
884 where
885     I: Init<T, E>,
886 {
887     let init = move |slot: *mut [T; N]| {
888         let slot = slot.cast::<T>();
889         // Counts the number of initialized elements and when dropped drops that many elements from
890         // `slot`.
891         let mut init_count = ScopeGuard::new_with_data(0, |i| {
892             // We now free every element that has been initialized before:
893             // SAFETY: The loop initialized exactly the values from 0..i and since we
894             // return `Err` below, the caller will consider the memory at `slot` as
895             // uninitialized.
896             unsafe { ptr::drop_in_place(ptr::slice_from_raw_parts_mut(slot, i)) };
897         });
898         for i in 0..N {
899             let init = make_init(i);
900             // SAFETY: Since 0 <= `i` < N, it is still in bounds of `[T; N]`.
901             let ptr = unsafe { slot.add(i) };
902             // SAFETY: The pointer is derived from `slot` and thus satisfies the `__init`
903             // requirements.
904             unsafe { init.__init(ptr) }?;
905             *init_count += 1;
906         }
907         init_count.dismiss();
908         Ok(())
909     };
910     // SAFETY: The initializer above initializes every element of the array. On failure it drops
911     // any initialized elements and returns `Err`.
912     unsafe { init_from_closure(init) }
913 }
914 
915 /// Initializes an array by initializing each element via the provided initializer.
916 ///
917 /// # Examples
918 ///
919 /// ```rust
920 /// use kernel::{sync::{Arc, Mutex}, init::pin_init_array_from_fn, new_mutex};
921 /// let array: Arc<[Mutex<usize>; 1_000]>=
922 ///     Arc::pin_init(pin_init_array_from_fn(|i| new_mutex!(i))).unwrap();
923 /// assert_eq!(array.len(), 1_000);
924 /// ```
925 pub fn pin_init_array_from_fn<I, const N: usize, T, E>(
926     mut make_init: impl FnMut(usize) -> I,
927 ) -> impl PinInit<[T; N], E>
928 where
929     I: PinInit<T, E>,
930 {
931     let init = move |slot: *mut [T; N]| {
932         let slot = slot.cast::<T>();
933         // Counts the number of initialized elements and when dropped drops that many elements from
934         // `slot`.
935         let mut init_count = ScopeGuard::new_with_data(0, |i| {
936             // We now free every element that has been initialized before:
937             // SAFETY: The loop initialized exactly the values from 0..i and since we
938             // return `Err` below, the caller will consider the memory at `slot` as
939             // uninitialized.
940             unsafe { ptr::drop_in_place(ptr::slice_from_raw_parts_mut(slot, i)) };
941         });
942         for i in 0..N {
943             let init = make_init(i);
944             // SAFETY: Since 0 <= `i` < N, it is still in bounds of `[T; N]`.
945             let ptr = unsafe { slot.add(i) };
946             // SAFETY: The pointer is derived from `slot` and thus satisfies the `__init`
947             // requirements.
948             unsafe { init.__pinned_init(ptr) }?;
949             *init_count += 1;
950         }
951         init_count.dismiss();
952         Ok(())
953     };
954     // SAFETY: The initializer above initializes every element of the array. On failure it drops
955     // any initialized elements and returns `Err`.
956     unsafe { pin_init_from_closure(init) }
957 }
958 
959 // SAFETY: Every type can be initialized by-value.
960 unsafe impl<T, E> Init<T, E> for T {
961     unsafe fn __init(self, slot: *mut T) -> Result<(), E> {
962         unsafe { slot.write(self) };
963         Ok(())
964     }
965 }
966 
967 /// Smart pointer that can initialize memory in-place.
968 pub trait InPlaceInit<T>: Sized {
969     /// Use the given pin-initializer to pin-initialize a `T` inside of a new smart pointer of this
970     /// type.
971     ///
972     /// If `T: !Unpin` it will not be able to move afterwards.
973     fn try_pin_init<E>(init: impl PinInit<T, E>) -> Result<Pin<Self>, E>
974     where
975         E: From<AllocError>;
976 
977     /// Use the given pin-initializer to pin-initialize a `T` inside of a new smart pointer of this
978     /// type.
979     ///
980     /// If `T: !Unpin` it will not be able to move afterwards.
981     fn pin_init<E>(init: impl PinInit<T, E>) -> error::Result<Pin<Self>>
982     where
983         Error: From<E>,
984     {
985         // SAFETY: We delegate to `init` and only change the error type.
986         let init = unsafe {
987             pin_init_from_closure(|slot| init.__pinned_init(slot).map_err(|e| Error::from(e)))
988         };
989         Self::try_pin_init(init)
990     }
991 
992     /// Use the given initializer to in-place initialize a `T`.
993     fn try_init<E>(init: impl Init<T, E>) -> Result<Self, E>
994     where
995         E: From<AllocError>;
996 
997     /// Use the given initializer to in-place initialize a `T`.
998     fn init<E>(init: impl Init<T, E>) -> error::Result<Self>
999     where
1000         Error: From<E>,
1001     {
1002         // SAFETY: We delegate to `init` and only change the error type.
1003         let init = unsafe {
1004             init_from_closure(|slot| init.__pinned_init(slot).map_err(|e| Error::from(e)))
1005         };
1006         Self::try_init(init)
1007     }
1008 }
1009 
1010 impl<T> InPlaceInit<T> for Box<T> {
1011     #[inline]
1012     fn try_pin_init<E>(init: impl PinInit<T, E>) -> Result<Pin<Self>, E>
1013     where
1014         E: From<AllocError>,
1015     {
1016         let mut this = Box::try_new_uninit()?;
1017         let slot = this.as_mut_ptr();
1018         // SAFETY: When init errors/panics, slot will get deallocated but not dropped,
1019         // slot is valid and will not be moved, because we pin it later.
1020         unsafe { init.__pinned_init(slot)? };
1021         // SAFETY: All fields have been initialized.
1022         Ok(unsafe { this.assume_init() }.into())
1023     }
1024 
1025     #[inline]
1026     fn try_init<E>(init: impl Init<T, E>) -> Result<Self, E>
1027     where
1028         E: From<AllocError>,
1029     {
1030         let mut this = Box::try_new_uninit()?;
1031         let slot = this.as_mut_ptr();
1032         // SAFETY: When init errors/panics, slot will get deallocated but not dropped,
1033         // slot is valid.
1034         unsafe { init.__init(slot)? };
1035         // SAFETY: All fields have been initialized.
1036         Ok(unsafe { this.assume_init() })
1037     }
1038 }
1039 
1040 impl<T> InPlaceInit<T> for UniqueArc<T> {
1041     #[inline]
1042     fn try_pin_init<E>(init: impl PinInit<T, E>) -> Result<Pin<Self>, E>
1043     where
1044         E: From<AllocError>,
1045     {
1046         let mut this = UniqueArc::try_new_uninit()?;
1047         let slot = this.as_mut_ptr();
1048         // SAFETY: When init errors/panics, slot will get deallocated but not dropped,
1049         // slot is valid and will not be moved, because we pin it later.
1050         unsafe { init.__pinned_init(slot)? };
1051         // SAFETY: All fields have been initialized.
1052         Ok(unsafe { this.assume_init() }.into())
1053     }
1054 
1055     #[inline]
1056     fn try_init<E>(init: impl Init<T, E>) -> Result<Self, E>
1057     where
1058         E: From<AllocError>,
1059     {
1060         let mut this = UniqueArc::try_new_uninit()?;
1061         let slot = this.as_mut_ptr();
1062         // SAFETY: When init errors/panics, slot will get deallocated but not dropped,
1063         // slot is valid.
1064         unsafe { init.__init(slot)? };
1065         // SAFETY: All fields have been initialized.
1066         Ok(unsafe { this.assume_init() })
1067     }
1068 }
1069 
1070 /// Trait facilitating pinned destruction.
1071 ///
1072 /// Use [`pinned_drop`] to implement this trait safely:
1073 ///
1074 /// ```rust
1075 /// # use kernel::sync::Mutex;
1076 /// use kernel::macros::pinned_drop;
1077 /// use core::pin::Pin;
1078 /// #[pin_data(PinnedDrop)]
1079 /// struct Foo {
1080 ///     #[pin]
1081 ///     mtx: Mutex<usize>,
1082 /// }
1083 ///
1084 /// #[pinned_drop]
1085 /// impl PinnedDrop for Foo {
1086 ///     fn drop(self: Pin<&mut Self>) {
1087 ///         pr_info!("Foo is being dropped!");
1088 ///     }
1089 /// }
1090 /// ```
1091 ///
1092 /// # Safety
1093 ///
1094 /// This trait must be implemented via the [`pinned_drop`] proc-macro attribute on the impl.
1095 ///
1096 /// [`pinned_drop`]: kernel::macros::pinned_drop
1097 pub unsafe trait PinnedDrop: __internal::HasPinData {
1098     /// Executes the pinned destructor of this type.
1099     ///
1100     /// While this function is marked safe, it is actually unsafe to call it manually. For this
1101     /// reason it takes an additional parameter. This type can only be constructed by `unsafe` code
1102     /// and thus prevents this function from being called where it should not.
1103     ///
1104     /// This extra parameter will be generated by the `#[pinned_drop]` proc-macro attribute
1105     /// automatically.
1106     fn drop(self: Pin<&mut Self>, only_call_from_drop: __internal::OnlyCallFromDrop);
1107 }
1108 
1109 /// Marker trait for types that can be initialized by writing just zeroes.
1110 ///
1111 /// # Safety
1112 ///
1113 /// The bit pattern consisting of only zeroes is a valid bit pattern for this type. In other words,
1114 /// this is not UB:
1115 ///
1116 /// ```rust,ignore
1117 /// let val: Self = unsafe { core::mem::zeroed() };
1118 /// ```
1119 pub unsafe trait Zeroable {}
1120 
1121 /// Create a new zeroed T.
1122 ///
1123 /// The returned initializer will write `0x00` to every byte of the given `slot`.
1124 #[inline]
1125 pub fn zeroed<T: Zeroable>() -> impl Init<T> {
1126     // SAFETY: Because `T: Zeroable`, all bytes zero is a valid bit pattern for `T`
1127     // and because we write all zeroes, the memory is initialized.
1128     unsafe {
1129         init_from_closure(|slot: *mut T| {
1130             slot.write_bytes(0, 1);
1131             Ok(())
1132         })
1133     }
1134 }
1135 
1136 macro_rules! impl_zeroable {
1137     ($($({$($generics:tt)*})? $t:ty, )*) => {
1138         $(unsafe impl$($($generics)*)? Zeroable for $t {})*
1139     };
1140 }
1141 
1142 impl_zeroable! {
1143     // SAFETY: All primitives that are allowed to be zero.
1144     bool,
1145     char,
1146     u8, u16, u32, u64, u128, usize,
1147     i8, i16, i32, i64, i128, isize,
1148     f32, f64,
1149 
1150     // SAFETY: These are ZSTs, there is nothing to zero.
1151     {<T: ?Sized>} PhantomData<T>, core::marker::PhantomPinned, Infallible, (),
1152 
1153     // SAFETY: Type is allowed to take any value, including all zeros.
1154     {<T>} MaybeUninit<T>,
1155     // SAFETY: Type is allowed to take any value, including all zeros.
1156     {<T>} Opaque<T>,
1157 
1158     // SAFETY: `T: Zeroable` and `UnsafeCell` is `repr(transparent)`.
1159     {<T: ?Sized + Zeroable>} UnsafeCell<T>,
1160 
1161     // SAFETY: All zeros is equivalent to `None` (option layout optimization guarantee).
1162     Option<NonZeroU8>, Option<NonZeroU16>, Option<NonZeroU32>, Option<NonZeroU64>,
1163     Option<NonZeroU128>, Option<NonZeroUsize>,
1164     Option<NonZeroI8>, Option<NonZeroI16>, Option<NonZeroI32>, Option<NonZeroI64>,
1165     Option<NonZeroI128>, Option<NonZeroIsize>,
1166 
1167     // SAFETY: All zeros is equivalent to `None` (option layout optimization guarantee).
1168     //
1169     // In this case we are allowed to use `T: ?Sized`, since all zeros is the `None` variant.
1170     {<T: ?Sized>} Option<NonNull<T>>,
1171     {<T: ?Sized>} Option<Box<T>>,
1172 
1173     // SAFETY: `null` pointer is valid.
1174     //
1175     // We cannot use `T: ?Sized`, since the VTABLE pointer part of fat pointers is not allowed to be
1176     // null.
1177     //
1178     // When `Pointee` gets stabilized, we could use
1179     // `T: ?Sized where <T as Pointee>::Metadata: Zeroable`
1180     {<T>} *mut T, {<T>} *const T,
1181 
1182     // SAFETY: `null` pointer is valid and the metadata part of these fat pointers is allowed to be
1183     // zero.
1184     {<T>} *mut [T], {<T>} *const [T], *mut str, *const str,
1185 
1186     // SAFETY: `T` is `Zeroable`.
1187     {<const N: usize, T: Zeroable>} [T; N], {<T: Zeroable>} Wrapping<T>,
1188 }
1189 
1190 macro_rules! impl_tuple_zeroable {
1191     ($(,)?) => {};
1192     ($first:ident, $($t:ident),* $(,)?) => {
1193         // SAFETY: All elements are zeroable and padding can be zero.
1194         unsafe impl<$first: Zeroable, $($t: Zeroable),*> Zeroable for ($first, $($t),*) {}
1195         impl_tuple_zeroable!($($t),* ,);
1196     }
1197 }
1198 
1199 impl_tuple_zeroable!(A, B, C, D, E, F, G, H, I, J);
1200