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