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