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