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