xref: /linux/rust/kernel/init.rs (revision 1f9ed172545687e5c04c77490a45896be6d2e459)
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 //! # #![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<Box<Foo>>> = Box::pin_init(foo, GFP_KERNEL);
72 //! ```
73 //!
74 //! For more information see the [`pin_init!`] macro.
75 //!
76 //! ## Using a custom function/macro that returns an initializer
77 //!
78 //! Many types from the kernel supply a function/macro that returns an initializer, because the
79 //! above method only works for types where you can access the fields.
80 //!
81 //! ```rust
82 //! # use kernel::sync::{new_mutex, Arc, Mutex};
83 //! let mtx: Result<Arc<Mutex<usize>>> =
84 //!     Arc::pin_init(new_mutex!(42, "example::mtx"), GFP_KERNEL);
85 //! ```
86 //!
87 //! To declare an init macro/function you just return an [`impl PinInit<T, E>`]:
88 //!
89 //! ```rust
90 //! # use kernel::{sync::Mutex, new_mutex, init::PinInit, try_pin_init};
91 //! #[pin_data]
92 //! struct DriverData {
93 //!     #[pin]
94 //!     status: Mutex<i32>,
95 //!     buffer: Box<[u8; 1_000_000]>,
96 //! }
97 //!
98 //! impl DriverData {
99 //!     fn new() -> impl PinInit<Self, Error> {
100 //!         try_pin_init!(Self {
101 //!             status <- new_mutex!(0, "DriverData::status"),
102 //!             buffer: Box::init(kernel::init::zeroed(), GFP_KERNEL)?,
103 //!         })
104 //!     }
105 //! }
106 //! ```
107 //!
108 //! ## Manual creation of an initializer
109 //!
110 //! Often when working with primitives the previous approaches are not sufficient. That is where
111 //! [`pin_init_from_closure()`] comes in. This `unsafe` function allows you to create a
112 //! [`impl PinInit<T, E>`] directly from a closure. Of course you have to ensure that the closure
113 //! actually does the initialization in the correct way. Here are the things to look out for
114 //! (we are calling the parameter to the closure `slot`):
115 //! - when the closure returns `Ok(())`, then it has completed the initialization successfully, so
116 //!   `slot` now contains a valid bit pattern for the type `T`,
117 //! - when the closure returns `Err(e)`, then the caller may deallocate the memory at `slot`, so
118 //!   you need to take care to clean up anything if your initialization fails mid-way,
119 //! - you may assume that `slot` will stay pinned even after the closure returns until `drop` of
120 //!   `slot` gets called.
121 //!
122 //! ```rust
123 //! # #![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},
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: 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 /// # #![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: 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 /// # 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 /// # Box::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 = Box::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: Box<[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: Box::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::{init::{PinInit, zeroed}, error::Error};
696 /// struct BigBuf {
697 ///     big: Box<[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: Box::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 [`Box<T>`], [`Arc<T>`], [`UniqueArc<T>`] or even the stack (see [`stack_pin_init!`]). Use the
816 /// [`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, Box<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 [`Box<T>`], [`Arc<T>`], [`UniqueArc<T>`] or even the stack (see [`stack_pin_init!`]). Use the
923 /// [`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, Box<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::{error::Error, init::init_array_from_fn};
1080 /// let array: Box<[usize; 1_000]> = Box::init::<Error>(init_array_from_fn(|i| i), GFP_KERNEL).unwrap();
1081 /// assert_eq!(array.len(), 1_000);
1082 /// ```
1083 pub fn init_array_from_fn<I, const N: usize, T, E>(
1084     mut make_init: impl FnMut(usize) -> I,
1085 ) -> impl Init<[T; N], E>
1086 where
1087     I: Init<T, E>,
1088 {
1089     let init = move |slot: *mut [T; N]| {
1090         let slot = slot.cast::<T>();
1091         // Counts the number of initialized elements and when dropped drops that many elements from
1092         // `slot`.
1093         let mut init_count = ScopeGuard::new_with_data(0, |i| {
1094             // We now free every element that has been initialized before.
1095             // SAFETY: The loop initialized exactly the values from 0..i and since we
1096             // return `Err` below, the caller will consider the memory at `slot` as
1097             // uninitialized.
1098             unsafe { ptr::drop_in_place(ptr::slice_from_raw_parts_mut(slot, i)) };
1099         });
1100         for i in 0..N {
1101             let init = make_init(i);
1102             // SAFETY: Since 0 <= `i` < N, it is still in bounds of `[T; N]`.
1103             let ptr = unsafe { slot.add(i) };
1104             // SAFETY: The pointer is derived from `slot` and thus satisfies the `__init`
1105             // requirements.
1106             unsafe { init.__init(ptr) }?;
1107             *init_count += 1;
1108         }
1109         init_count.dismiss();
1110         Ok(())
1111     };
1112     // SAFETY: The initializer above initializes every element of the array. On failure it drops
1113     // any initialized elements and returns `Err`.
1114     unsafe { init_from_closure(init) }
1115 }
1116 
1117 /// Initializes an array by initializing each element via the provided initializer.
1118 ///
1119 /// # Examples
1120 ///
1121 /// ```rust
1122 /// use kernel::{sync::{Arc, Mutex}, init::pin_init_array_from_fn, new_mutex};
1123 /// let array: Arc<[Mutex<usize>; 1_000]> =
1124 ///     Arc::pin_init(pin_init_array_from_fn(|i| new_mutex!(i)), GFP_KERNEL).unwrap();
1125 /// assert_eq!(array.len(), 1_000);
1126 /// ```
1127 pub fn pin_init_array_from_fn<I, const N: usize, T, E>(
1128     mut make_init: impl FnMut(usize) -> I,
1129 ) -> impl PinInit<[T; N], E>
1130 where
1131     I: PinInit<T, E>,
1132 {
1133     let init = move |slot: *mut [T; N]| {
1134         let slot = slot.cast::<T>();
1135         // Counts the number of initialized elements and when dropped drops that many elements from
1136         // `slot`.
1137         let mut init_count = ScopeGuard::new_with_data(0, |i| {
1138             // We now free every element that has been initialized before.
1139             // SAFETY: The loop initialized exactly the values from 0..i and since we
1140             // return `Err` below, the caller will consider the memory at `slot` as
1141             // uninitialized.
1142             unsafe { ptr::drop_in_place(ptr::slice_from_raw_parts_mut(slot, i)) };
1143         });
1144         for i in 0..N {
1145             let init = make_init(i);
1146             // SAFETY: Since 0 <= `i` < N, it is still in bounds of `[T; N]`.
1147             let ptr = unsafe { slot.add(i) };
1148             // SAFETY: The pointer is derived from `slot` and thus satisfies the `__init`
1149             // requirements.
1150             unsafe { init.__pinned_init(ptr) }?;
1151             *init_count += 1;
1152         }
1153         init_count.dismiss();
1154         Ok(())
1155     };
1156     // SAFETY: The initializer above initializes every element of the array. On failure it drops
1157     // any initialized elements and returns `Err`.
1158     unsafe { pin_init_from_closure(init) }
1159 }
1160 
1161 // SAFETY: Every type can be initialized by-value.
1162 unsafe impl<T, E> Init<T, E> for T {
1163     unsafe fn __init(self, slot: *mut T) -> Result<(), E> {
1164         // SAFETY: TODO.
1165         unsafe { slot.write(self) };
1166         Ok(())
1167     }
1168 }
1169 
1170 // SAFETY: Every type can be initialized by-value. `__pinned_init` calls `__init`.
1171 unsafe impl<T, E> PinInit<T, E> for T {
1172     unsafe fn __pinned_init(self, slot: *mut T) -> Result<(), E> {
1173         // SAFETY: TODO.
1174         unsafe { self.__init(slot) }
1175     }
1176 }
1177 
1178 /// Smart pointer that can initialize memory in-place.
1179 pub trait InPlaceInit<T>: Sized {
1180     /// Pinned version of `Self`.
1181     ///
1182     /// If a type already implicitly pins its pointee, `Pin<Self>` is unnecessary. In this case use
1183     /// `Self`, otherwise just use `Pin<Self>`.
1184     type PinnedSelf;
1185 
1186     /// Use the given pin-initializer to pin-initialize a `T` inside of a new smart pointer of this
1187     /// type.
1188     ///
1189     /// If `T: !Unpin` it will not be able to move afterwards.
1190     fn try_pin_init<E>(init: impl PinInit<T, E>, flags: Flags) -> Result<Self::PinnedSelf, E>
1191     where
1192         E: From<AllocError>;
1193 
1194     /// Use the given pin-initializer to pin-initialize a `T` inside of a new smart pointer of this
1195     /// type.
1196     ///
1197     /// If `T: !Unpin` it will not be able to move afterwards.
1198     fn pin_init<E>(init: impl PinInit<T, E>, flags: Flags) -> error::Result<Self::PinnedSelf>
1199     where
1200         Error: From<E>,
1201     {
1202         // SAFETY: We delegate to `init` and only change the error type.
1203         let init = unsafe {
1204             pin_init_from_closure(|slot| init.__pinned_init(slot).map_err(|e| Error::from(e)))
1205         };
1206         Self::try_pin_init(init, flags)
1207     }
1208 
1209     /// Use the given initializer to in-place initialize a `T`.
1210     fn try_init<E>(init: impl Init<T, E>, flags: Flags) -> Result<Self, E>
1211     where
1212         E: From<AllocError>;
1213 
1214     /// Use the given initializer to in-place initialize a `T`.
1215     fn init<E>(init: impl Init<T, E>, flags: Flags) -> error::Result<Self>
1216     where
1217         Error: From<E>,
1218     {
1219         // SAFETY: We delegate to `init` and only change the error type.
1220         let init = unsafe {
1221             init_from_closure(|slot| init.__pinned_init(slot).map_err(|e| Error::from(e)))
1222         };
1223         Self::try_init(init, flags)
1224     }
1225 }
1226 
1227 impl<T> InPlaceInit<T> for Arc<T> {
1228     type PinnedSelf = Self;
1229 
1230     #[inline]
1231     fn try_pin_init<E>(init: impl PinInit<T, E>, flags: Flags) -> Result<Self::PinnedSelf, E>
1232     where
1233         E: From<AllocError>,
1234     {
1235         UniqueArc::try_pin_init(init, flags).map(|u| u.into())
1236     }
1237 
1238     #[inline]
1239     fn try_init<E>(init: impl Init<T, E>, flags: Flags) -> Result<Self, E>
1240     where
1241         E: From<AllocError>,
1242     {
1243         UniqueArc::try_init(init, flags).map(|u| u.into())
1244     }
1245 }
1246 
1247 impl<T> InPlaceInit<T> for Box<T> {
1248     type PinnedSelf = Pin<Self>;
1249 
1250     #[inline]
1251     fn try_pin_init<E>(init: impl PinInit<T, E>, flags: Flags) -> Result<Self::PinnedSelf, E>
1252     where
1253         E: From<AllocError>,
1254     {
1255         <Box<_> as BoxExt<_>>::new_uninit(flags)?.write_pin_init(init)
1256     }
1257 
1258     #[inline]
1259     fn try_init<E>(init: impl Init<T, E>, flags: Flags) -> Result<Self, E>
1260     where
1261         E: From<AllocError>,
1262     {
1263         <Box<_> as BoxExt<_>>::new_uninit(flags)?.write_init(init)
1264     }
1265 }
1266 
1267 impl<T> InPlaceInit<T> for UniqueArc<T> {
1268     type PinnedSelf = Pin<Self>;
1269 
1270     #[inline]
1271     fn try_pin_init<E>(init: impl PinInit<T, E>, flags: Flags) -> Result<Self::PinnedSelf, E>
1272     where
1273         E: From<AllocError>,
1274     {
1275         UniqueArc::new_uninit(flags)?.write_pin_init(init)
1276     }
1277 
1278     #[inline]
1279     fn try_init<E>(init: impl Init<T, E>, flags: Flags) -> Result<Self, E>
1280     where
1281         E: From<AllocError>,
1282     {
1283         UniqueArc::new_uninit(flags)?.write_init(init)
1284     }
1285 }
1286 
1287 /// Smart pointer containing uninitialized memory and that can write a value.
1288 pub trait InPlaceWrite<T> {
1289     /// The type `Self` turns into when the contents are initialized.
1290     type Initialized;
1291 
1292     /// Use the given initializer to write a value into `self`.
1293     ///
1294     /// Does not drop the current value and considers it as uninitialized memory.
1295     fn write_init<E>(self, init: impl Init<T, E>) -> Result<Self::Initialized, E>;
1296 
1297     /// Use the given pin-initializer to write a value into `self`.
1298     ///
1299     /// Does not drop the current value and considers it as uninitialized memory.
1300     fn write_pin_init<E>(self, init: impl PinInit<T, E>) -> Result<Pin<Self::Initialized>, E>;
1301 }
1302 
1303 impl<T> InPlaceWrite<T> for Box<MaybeUninit<T>> {
1304     type Initialized = Box<T>;
1305 
1306     fn write_init<E>(mut self, init: impl Init<T, E>) -> Result<Self::Initialized, E> {
1307         let slot = self.as_mut_ptr();
1308         // SAFETY: When init errors/panics, slot will get deallocated but not dropped,
1309         // slot is valid.
1310         unsafe { init.__init(slot)? };
1311         // SAFETY: All fields have been initialized.
1312         Ok(unsafe { self.assume_init() })
1313     }
1314 
1315     fn write_pin_init<E>(mut self, init: impl PinInit<T, E>) -> Result<Pin<Self::Initialized>, E> {
1316         let slot = self.as_mut_ptr();
1317         // SAFETY: When init errors/panics, slot will get deallocated but not dropped,
1318         // slot is valid and will not be moved, because we pin it later.
1319         unsafe { init.__pinned_init(slot)? };
1320         // SAFETY: All fields have been initialized.
1321         Ok(unsafe { self.assume_init() }.into())
1322     }
1323 }
1324 
1325 impl<T> InPlaceWrite<T> for UniqueArc<MaybeUninit<T>> {
1326     type Initialized = UniqueArc<T>;
1327 
1328     fn write_init<E>(mut self, init: impl Init<T, E>) -> Result<Self::Initialized, E> {
1329         let slot = self.as_mut_ptr();
1330         // SAFETY: When init errors/panics, slot will get deallocated but not dropped,
1331         // slot is valid.
1332         unsafe { init.__init(slot)? };
1333         // SAFETY: All fields have been initialized.
1334         Ok(unsafe { self.assume_init() })
1335     }
1336 
1337     fn write_pin_init<E>(mut self, init: impl PinInit<T, E>) -> Result<Pin<Self::Initialized>, E> {
1338         let slot = self.as_mut_ptr();
1339         // SAFETY: When init errors/panics, slot will get deallocated but not dropped,
1340         // slot is valid and will not be moved, because we pin it later.
1341         unsafe { init.__pinned_init(slot)? };
1342         // SAFETY: All fields have been initialized.
1343         Ok(unsafe { self.assume_init() }.into())
1344     }
1345 }
1346 
1347 /// Trait facilitating pinned destruction.
1348 ///
1349 /// Use [`pinned_drop`] to implement this trait safely:
1350 ///
1351 /// ```rust
1352 /// # use kernel::sync::Mutex;
1353 /// use kernel::macros::pinned_drop;
1354 /// use core::pin::Pin;
1355 /// #[pin_data(PinnedDrop)]
1356 /// struct Foo {
1357 ///     #[pin]
1358 ///     mtx: Mutex<usize>,
1359 /// }
1360 ///
1361 /// #[pinned_drop]
1362 /// impl PinnedDrop for Foo {
1363 ///     fn drop(self: Pin<&mut Self>) {
1364 ///         pr_info!("Foo is being dropped!");
1365 ///     }
1366 /// }
1367 /// ```
1368 ///
1369 /// # Safety
1370 ///
1371 /// This trait must be implemented via the [`pinned_drop`] proc-macro attribute on the impl.
1372 ///
1373 /// [`pinned_drop`]: kernel::macros::pinned_drop
1374 pub unsafe trait PinnedDrop: __internal::HasPinData {
1375     /// Executes the pinned destructor of this type.
1376     ///
1377     /// While this function is marked safe, it is actually unsafe to call it manually. For this
1378     /// reason it takes an additional parameter. This type can only be constructed by `unsafe` code
1379     /// and thus prevents this function from being called where it should not.
1380     ///
1381     /// This extra parameter will be generated by the `#[pinned_drop]` proc-macro attribute
1382     /// automatically.
1383     fn drop(self: Pin<&mut Self>, only_call_from_drop: __internal::OnlyCallFromDrop);
1384 }
1385 
1386 /// Marker trait for types that can be initialized by writing just zeroes.
1387 ///
1388 /// # Safety
1389 ///
1390 /// The bit pattern consisting of only zeroes is a valid bit pattern for this type. In other words,
1391 /// this is not UB:
1392 ///
1393 /// ```rust,ignore
1394 /// let val: Self = unsafe { core::mem::zeroed() };
1395 /// ```
1396 pub unsafe trait Zeroable {}
1397 
1398 /// Create a new zeroed T.
1399 ///
1400 /// The returned initializer will write `0x00` to every byte of the given `slot`.
1401 #[inline]
1402 pub fn zeroed<T: Zeroable>() -> impl Init<T> {
1403     // SAFETY: Because `T: Zeroable`, all bytes zero is a valid bit pattern for `T`
1404     // and because we write all zeroes, the memory is initialized.
1405     unsafe {
1406         init_from_closure(|slot: *mut T| {
1407             slot.write_bytes(0, 1);
1408             Ok(())
1409         })
1410     }
1411 }
1412 
1413 macro_rules! impl_zeroable {
1414     ($($({$($generics:tt)*})? $t:ty, )*) => {
1415         // SAFETY: Safety comments written in the macro invocation.
1416         $(unsafe impl$($($generics)*)? Zeroable for $t {})*
1417     };
1418 }
1419 
1420 impl_zeroable! {
1421     // SAFETY: All primitives that are allowed to be zero.
1422     bool,
1423     char,
1424     u8, u16, u32, u64, u128, usize,
1425     i8, i16, i32, i64, i128, isize,
1426     f32, f64,
1427 
1428     // Note: do not add uninhabited types (such as `!` or `core::convert::Infallible`) to this list;
1429     // creating an instance of an uninhabited type is immediate undefined behavior. For more on
1430     // uninhabited/empty types, consult The Rustonomicon:
1431     // <https://doc.rust-lang.org/stable/nomicon/exotic-sizes.html#empty-types>. The Rust Reference
1432     // also has information on undefined behavior:
1433     // <https://doc.rust-lang.org/stable/reference/behavior-considered-undefined.html>.
1434     //
1435     // SAFETY: These are inhabited ZSTs; there is nothing to zero and a valid value exists.
1436     {<T: ?Sized>} PhantomData<T>, core::marker::PhantomPinned, (),
1437 
1438     // SAFETY: Type is allowed to take any value, including all zeros.
1439     {<T>} MaybeUninit<T>,
1440     // SAFETY: Type is allowed to take any value, including all zeros.
1441     {<T>} Opaque<T>,
1442 
1443     // SAFETY: `T: Zeroable` and `UnsafeCell` is `repr(transparent)`.
1444     {<T: ?Sized + Zeroable>} UnsafeCell<T>,
1445 
1446     // SAFETY: All zeros is equivalent to `None` (option layout optimization guarantee).
1447     Option<NonZeroU8>, Option<NonZeroU16>, Option<NonZeroU32>, Option<NonZeroU64>,
1448     Option<NonZeroU128>, Option<NonZeroUsize>,
1449     Option<NonZeroI8>, Option<NonZeroI16>, Option<NonZeroI32>, Option<NonZeroI64>,
1450     Option<NonZeroI128>, Option<NonZeroIsize>,
1451 
1452     // SAFETY: All zeros is equivalent to `None` (option layout optimization guarantee).
1453     //
1454     // In this case we are allowed to use `T: ?Sized`, since all zeros is the `None` variant.
1455     {<T: ?Sized>} Option<NonNull<T>>,
1456     {<T: ?Sized>} Option<Box<T>>,
1457 
1458     // SAFETY: `null` pointer is valid.
1459     //
1460     // We cannot use `T: ?Sized`, since the VTABLE pointer part of fat pointers is not allowed to be
1461     // null.
1462     //
1463     // When `Pointee` gets stabilized, we could use
1464     // `T: ?Sized where <T as Pointee>::Metadata: Zeroable`
1465     {<T>} *mut T, {<T>} *const T,
1466 
1467     // SAFETY: `null` pointer is valid and the metadata part of these fat pointers is allowed to be
1468     // zero.
1469     {<T>} *mut [T], {<T>} *const [T], *mut str, *const str,
1470 
1471     // SAFETY: `T` is `Zeroable`.
1472     {<const N: usize, T: Zeroable>} [T; N], {<T: Zeroable>} Wrapping<T>,
1473 }
1474 
1475 macro_rules! impl_tuple_zeroable {
1476     ($(,)?) => {};
1477     ($first:ident, $($t:ident),* $(,)?) => {
1478         // SAFETY: All elements are zeroable and padding can be zero.
1479         unsafe impl<$first: Zeroable, $($t: Zeroable),*> Zeroable for ($first, $($t),*) {}
1480         impl_tuple_zeroable!($($t),* ,);
1481     }
1482 }
1483 
1484 impl_tuple_zeroable!(A, B, C, D, E, F, G, H, I, J);
1485