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