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