xref: /linux/rust/kernel/init.rs (revision 97de919d574e6a22f0d43a169b96274f1862e770)
1 // SPDX-License-Identifier: Apache-2.0 OR MIT
2 
3 //! API to safely and fallibly initialize pinned `struct`s using in-place constructors.
4 //!
5 //! It also allows in-place initialization of big `struct`s that would otherwise produce a stack
6 //! overflow.
7 //!
8 //! Most `struct`s from the [`sync`] module need to be pinned, because they contain self-referential
9 //! `struct`s from C. [Pinning][pinning] is Rust's way of ensuring data does not move.
10 //!
11 //! # Overview
12 //!
13 //! To initialize a `struct` with an in-place constructor you will need two things:
14 //! - an in-place constructor,
15 //! - a memory location that can hold your `struct` (this can be the [stack], an [`Arc<T>`],
16 //!   [`UniqueArc<T>`], [`Box<T>`] or any other smart pointer that implements [`InPlaceInit`]).
17 //!
18 //! To get an in-place constructor there are generally three options:
19 //! - directly creating an in-place constructor using the [`pin_init!`] macro,
20 //! - a custom function/macro returning an in-place constructor provided by someone else,
21 //! - using the unsafe function [`pin_init_from_closure()`] to manually create an initializer.
22 //!
23 //! Aside from pinned initialization, this API also supports in-place construction without pinning,
24 //! the macros/types/functions are generally named like the pinned variants without the `pin`
25 //! prefix.
26 //!
27 //! # Examples
28 //!
29 //! ## Using the [`pin_init!`] macro
30 //!
31 //! If you want to use [`PinInit`], then you will have to annotate your `struct` with
32 //! `#[`[`pin_data`]`]`. It is a macro that uses `#[pin]` as a marker for
33 //! [structurally pinned fields]. After doing this, you can then create an in-place constructor via
34 //! [`pin_init!`]. The syntax is almost the same as normal `struct` initializers. The difference is
35 //! that you need to write `<-` instead of `:` for fields that you want to initialize in-place.
36 //!
37 //! ```rust
38 //! # #![allow(clippy::disallowed_names, clippy::new_ret_no_self)]
39 //! use kernel::{prelude::*, sync::Mutex, new_mutex};
40 //! # use core::pin::Pin;
41 //! #[pin_data]
42 //! struct Foo {
43 //!     #[pin]
44 //!     a: Mutex<usize>,
45 //!     b: u32,
46 //! }
47 //!
48 //! let foo = pin_init!(Foo {
49 //!     a <- new_mutex!(42, "Foo::a"),
50 //!     b: 24,
51 //! });
52 //! ```
53 //!
54 //! `foo` now is of the type [`impl PinInit<Foo>`]. We can now use any smart pointer that we like
55 //! (or just the stack) to actually initialize a `Foo`:
56 //!
57 //! ```rust
58 //! # #![allow(clippy::disallowed_names, clippy::new_ret_no_self)]
59 //! # use kernel::{prelude::*, sync::Mutex, new_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);
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::{new_mutex, sync::{Arc, Mutex}};
83 //! let mtx: Result<Arc<Mutex<usize>>> = Arc::pin_init(new_mutex!(42, "example::mtx"));
84 //! ```
85 //!
86 //! To declare an init macro/function you just return an [`impl PinInit<T, E>`]:
87 //!
88 //! ```rust
89 //! # #![allow(clippy::disallowed_names, clippy::new_ret_no_self)]
90 //! # use kernel::{sync::Mutex, prelude::*, 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())?,
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 //! use kernel::{prelude::*, init};
124 //! use core::{ptr::addr_of_mut, marker::PhantomPinned, pin::Pin};
125 //! # mod bindings {
126 //! #     pub struct foo;
127 //! #     pub unsafe fn init_foo(_ptr: *mut foo) {}
128 //! #     pub unsafe fn destroy_foo(_ptr: *mut foo) {}
129 //! #     pub unsafe fn enable_foo(_ptr: *mut foo, _flags: u32) -> i32 { 0 }
130 //! # }
131 //! /// # Invariants
132 //! ///
133 //! /// `foo` is always initialized
134 //! #[pin_data(PinnedDrop)]
135 //! pub struct RawFoo {
136 //!     #[pin]
137 //!     foo: Opaque<bindings::foo>,
138 //!     #[pin]
139 //!     _p: PhantomPinned,
140 //! }
141 //!
142 //! impl RawFoo {
143 //!     pub fn new(flags: u32) -> impl PinInit<Self, Error> {
144 //!         // SAFETY:
145 //!         // - when the closure returns `Ok(())`, then it has successfully initialized and
146 //!         //   enabled `foo`,
147 //!         // - when it returns `Err(e)`, then it has cleaned up before
148 //!         unsafe {
149 //!             init::pin_init_from_closure(move |slot: *mut Self| {
150 //!                 // `slot` contains uninit memory, avoid creating a reference.
151 //!                 let foo = addr_of_mut!((*slot).foo);
152 //!
153 //!                 // Initialize the `foo`
154 //!                 bindings::init_foo(Opaque::raw_get(foo));
155 //!
156 //!                 // Try to enable it.
157 //!                 let err = bindings::enable_foo(Opaque::raw_get(foo), flags);
158 //!                 if err != 0 {
159 //!                     // Enabling has failed, first clean up the foo and then return the error.
160 //!                     bindings::destroy_foo(Opaque::raw_get(foo));
161 //!                     return Err(Error::from_kernel_errno(err));
162 //!                 }
163 //!
164 //!                 // All fields of `RawFoo` have been initialized, since `_p` is a ZST.
165 //!                 Ok(())
166 //!             })
167 //!         }
168 //!     }
169 //! }
170 //!
171 //! #[pinned_drop]
172 //! impl PinnedDrop for RawFoo {
173 //!     fn drop(self: Pin<&mut Self>) {
174 //!         // SAFETY: Since `foo` is initialized, destroying is safe.
175 //!         unsafe { bindings::destroy_foo(self.foo.get()) };
176 //!     }
177 //! }
178 //! ```
179 //!
180 //! For the special case where initializing a field is a single FFI-function call that cannot fail,
181 //! there exist the helper function [`Opaque::ffi_init`]. This function initialize a single
182 //! [`Opaque`] field by just delegating to the supplied closure. You can use these in combination
183 //! with [`pin_init!`].
184 //!
185 //! For more information on how to use [`pin_init_from_closure()`], take a look at the uses inside
186 //! the `kernel` crate. The [`sync`] module is a good starting point.
187 //!
188 //! [`sync`]: kernel::sync
189 //! [pinning]: https://doc.rust-lang.org/std/pin/index.html
190 //! [structurally pinned fields]:
191 //!     https://doc.rust-lang.org/std/pin/index.html#pinning-is-structural-for-field
192 //! [stack]: crate::stack_pin_init
193 //! [`Arc<T>`]: crate::sync::Arc
194 //! [`impl PinInit<Foo>`]: PinInit
195 //! [`impl PinInit<T, E>`]: PinInit
196 //! [`impl Init<T, E>`]: Init
197 //! [`Opaque`]: kernel::types::Opaque
198 //! [`Opaque::ffi_init`]: kernel::types::Opaque::ffi_init
199 //! [`pin_data`]: ::macros::pin_data
200 //! [`pin_init!`]: crate::pin_init!
201 
202 use crate::{
203     error::{self, Error},
204     sync::UniqueArc,
205 };
206 use alloc::boxed::Box;
207 use core::{
208     alloc::AllocError,
209     convert::Infallible,
210     marker::PhantomData,
211     mem::MaybeUninit,
212     num::*,
213     pin::Pin,
214     ptr::{self, NonNull},
215 };
216 
217 #[doc(hidden)]
218 pub mod __internal;
219 #[doc(hidden)]
220 pub mod macros;
221 
222 /// Initialize and pin a type directly on the stack.
223 ///
224 /// # Examples
225 ///
226 /// ```rust
227 /// # #![allow(clippy::disallowed_names, clippy::new_ret_no_self)]
228 /// # use kernel::{init, pin_init, stack_pin_init, init::*, sync::Mutex, new_mutex};
229 /// # use macros::pin_data;
230 /// # use core::pin::Pin;
231 /// #[pin_data]
232 /// struct Foo {
233 ///     #[pin]
234 ///     a: Mutex<usize>,
235 ///     b: Bar,
236 /// }
237 ///
238 /// #[pin_data]
239 /// struct Bar {
240 ///     x: u32,
241 /// }
242 ///
243 /// stack_pin_init!(let foo = pin_init!(Foo {
244 ///     a <- new_mutex!(42),
245 ///     b: Bar {
246 ///         x: 64,
247 ///     },
248 /// }));
249 /// let foo: Pin<&mut Foo> = foo;
250 /// pr_info!("a: {}", &*foo.a.lock());
251 /// ```
252 ///
253 /// # Syntax
254 ///
255 /// A normal `let` binding with optional type annotation. The expression is expected to implement
256 /// [`PinInit`]/[`Init`] with the error type [`Infallible`]. If you want to use a different error
257 /// type, then use [`stack_try_pin_init!`].
258 ///
259 /// [`stack_try_pin_init!`]: crate::stack_try_pin_init!
260 #[macro_export]
261 macro_rules! stack_pin_init {
262     (let $var:ident $(: $t:ty)? = $val:expr) => {
263         let val = $val;
264         let mut $var = ::core::pin::pin!($crate::init::__internal::StackInit$(::<$t>)?::uninit());
265         let mut $var = match $crate::init::__internal::StackInit::init($var, val) {
266             Ok(res) => res,
267             Err(x) => {
268                 let x: ::core::convert::Infallible = x;
269                 match x {}
270             }
271         };
272     };
273 }
274 
275 /// Initialize and pin a type directly on the stack.
276 ///
277 /// # Examples
278 ///
279 /// ```rust
280 /// # #![allow(clippy::disallowed_names, clippy::new_ret_no_self)]
281 /// # use kernel::{init, pin_init, stack_try_pin_init, init::*, sync::Mutex, new_mutex};
282 /// # use macros::pin_data;
283 /// # use core::{alloc::AllocError, pin::Pin};
284 /// #[pin_data]
285 /// struct Foo {
286 ///     #[pin]
287 ///     a: Mutex<usize>,
288 ///     b: Box<Bar>,
289 /// }
290 ///
291 /// struct Bar {
292 ///     x: u32,
293 /// }
294 ///
295 /// stack_try_pin_init!(let foo: Result<Pin<&mut Foo>, AllocError> = pin_init!(Foo {
296 ///     a <- new_mutex!(42),
297 ///     b: Box::try_new(Bar {
298 ///         x: 64,
299 ///     })?,
300 /// }));
301 /// let foo = foo.unwrap();
302 /// pr_info!("a: {}", &*foo.a.lock());
303 /// ```
304 ///
305 /// ```rust
306 /// # #![allow(clippy::disallowed_names, clippy::new_ret_no_self)]
307 /// # use kernel::{init, pin_init, stack_try_pin_init, init::*, sync::Mutex, new_mutex};
308 /// # use macros::pin_data;
309 /// # use core::{alloc::AllocError, pin::Pin};
310 /// #[pin_data]
311 /// struct Foo {
312 ///     #[pin]
313 ///     a: Mutex<usize>,
314 ///     b: Box<Bar>,
315 /// }
316 ///
317 /// struct Bar {
318 ///     x: u32,
319 /// }
320 ///
321 /// stack_try_pin_init!(let foo: Pin<&mut Foo> =? pin_init!(Foo {
322 ///     a <- new_mutex!(42),
323 ///     b: Box::try_new(Bar {
324 ///         x: 64,
325 ///     })?,
326 /// }));
327 /// pr_info!("a: {}", &*foo.a.lock());
328 /// # Ok::<_, AllocError>(())
329 /// ```
330 ///
331 /// # Syntax
332 ///
333 /// A normal `let` binding with optional type annotation. The expression is expected to implement
334 /// [`PinInit`]/[`Init`]. This macro assigns a result to the given variable, adding a `?` after the
335 /// `=` will propagate this error.
336 #[macro_export]
337 macro_rules! stack_try_pin_init {
338     (let $var:ident $(: $t:ty)? = $val:expr) => {
339         let val = $val;
340         let mut $var = ::core::pin::pin!($crate::init::__internal::StackInit$(::<$t>)?::uninit());
341         let mut $var = $crate::init::__internal::StackInit::init($var, val);
342     };
343     (let $var:ident $(: $t:ty)? =? $val:expr) => {
344         let val = $val;
345         let mut $var = ::core::pin::pin!($crate::init::__internal::StackInit$(::<$t>)?::uninit());
346         let mut $var = $crate::init::__internal::StackInit::init($var, val)?;
347     };
348 }
349 
350 /// Construct an in-place, pinned initializer for `struct`s.
351 ///
352 /// This macro defaults the error to [`Infallible`]. If you need [`Error`], then use
353 /// [`try_pin_init!`].
354 ///
355 /// The syntax is almost identical to that of a normal `struct` initializer:
356 ///
357 /// ```rust
358 /// # #![allow(clippy::disallowed_names, clippy::new_ret_no_self)]
359 /// # use kernel::{init, pin_init, macros::pin_data, init::*};
360 /// # use core::pin::Pin;
361 /// #[pin_data]
362 /// struct Foo {
363 ///     a: usize,
364 ///     b: Bar,
365 /// }
366 ///
367 /// #[pin_data]
368 /// struct Bar {
369 ///     x: u32,
370 /// }
371 ///
372 /// # fn demo() -> impl PinInit<Foo> {
373 /// let a = 42;
374 ///
375 /// let initializer = pin_init!(Foo {
376 ///     a,
377 ///     b: Bar {
378 ///         x: 64,
379 ///     },
380 /// });
381 /// # initializer }
382 /// # Box::pin_init(demo()).unwrap();
383 /// ```
384 ///
385 /// Arbitrary Rust expressions can be used to set the value of a variable.
386 ///
387 /// The fields are initialized in the order that they appear in the initializer. So it is possible
388 /// to read already initialized fields using raw pointers.
389 ///
390 /// IMPORTANT: You are not allowed to create references to fields of the struct inside of the
391 /// initializer.
392 ///
393 /// # Init-functions
394 ///
395 /// When working with this API it is often desired to let others construct your types without
396 /// giving access to all fields. This is where you would normally write a plain function `new`
397 /// that would return a new instance of your type. With this API that is also possible.
398 /// However, there are a few extra things to keep in mind.
399 ///
400 /// To create an initializer function, simply declare it like this:
401 ///
402 /// ```rust
403 /// # #![allow(clippy::disallowed_names, clippy::new_ret_no_self)]
404 /// # use kernel::{init, pin_init, prelude::*, init::*};
405 /// # use core::pin::Pin;
406 /// # #[pin_data]
407 /// # struct Foo {
408 /// #     a: usize,
409 /// #     b: Bar,
410 /// # }
411 /// # #[pin_data]
412 /// # struct Bar {
413 /// #     x: u32,
414 /// # }
415 /// impl Foo {
416 ///     fn new() -> impl PinInit<Self> {
417 ///         pin_init!(Self {
418 ///             a: 42,
419 ///             b: Bar {
420 ///                 x: 64,
421 ///             },
422 ///         })
423 ///     }
424 /// }
425 /// ```
426 ///
427 /// Users of `Foo` can now create it like this:
428 ///
429 /// ```rust
430 /// # #![allow(clippy::disallowed_names, clippy::new_ret_no_self)]
431 /// # use kernel::{init, pin_init, macros::pin_data, init::*};
432 /// # use core::pin::Pin;
433 /// # #[pin_data]
434 /// # struct Foo {
435 /// #     a: usize,
436 /// #     b: Bar,
437 /// # }
438 /// # #[pin_data]
439 /// # struct Bar {
440 /// #     x: u32,
441 /// # }
442 /// # impl Foo {
443 /// #     fn new() -> impl PinInit<Self> {
444 /// #         pin_init!(Self {
445 /// #             a: 42,
446 /// #             b: Bar {
447 /// #                 x: 64,
448 /// #             },
449 /// #         })
450 /// #     }
451 /// # }
452 /// let foo = Box::pin_init(Foo::new());
453 /// ```
454 ///
455 /// They can also easily embed it into their own `struct`s:
456 ///
457 /// ```rust
458 /// # #![allow(clippy::disallowed_names, clippy::new_ret_no_self)]
459 /// # use kernel::{init, pin_init, macros::pin_data, init::*};
460 /// # use core::pin::Pin;
461 /// # #[pin_data]
462 /// # struct Foo {
463 /// #     a: usize,
464 /// #     b: Bar,
465 /// # }
466 /// # #[pin_data]
467 /// # struct Bar {
468 /// #     x: u32,
469 /// # }
470 /// # impl Foo {
471 /// #     fn new() -> impl PinInit<Self> {
472 /// #         pin_init!(Self {
473 /// #             a: 42,
474 /// #             b: Bar {
475 /// #                 x: 64,
476 /// #             },
477 /// #         })
478 /// #     }
479 /// # }
480 /// #[pin_data]
481 /// struct FooContainer {
482 ///     #[pin]
483 ///     foo1: Foo,
484 ///     #[pin]
485 ///     foo2: Foo,
486 ///     other: u32,
487 /// }
488 ///
489 /// impl FooContainer {
490 ///     fn new(other: u32) -> impl PinInit<Self> {
491 ///         pin_init!(Self {
492 ///             foo1 <- Foo::new(),
493 ///             foo2 <- Foo::new(),
494 ///             other,
495 ///         })
496 ///     }
497 /// }
498 /// ```
499 ///
500 /// Here we see that when using `pin_init!` with `PinInit`, one needs to write `<-` instead of `:`.
501 /// This signifies that the given field is initialized in-place. As with `struct` initializers, just
502 /// writing the field (in this case `other`) without `:` or `<-` means `other: other,`.
503 ///
504 /// # Syntax
505 ///
506 /// As already mentioned in the examples above, inside of `pin_init!` a `struct` initializer with
507 /// the following modifications is expected:
508 /// - Fields that you want to initialize in-place have to use `<-` instead of `:`.
509 /// - In front of the initializer you can write `&this in` to have access to a [`NonNull<Self>`]
510 ///   pointer named `this` inside of the initializer.
511 ///
512 /// For instance:
513 ///
514 /// ```rust
515 /// # use kernel::pin_init;
516 /// # use macros::pin_data;
517 /// # use core::{ptr::addr_of_mut, marker::PhantomPinned};
518 /// #[pin_data]
519 /// struct Buf {
520 ///     // `ptr` points into `buf`.
521 ///     ptr: *mut u8,
522 ///     buf: [u8; 64],
523 ///     #[pin]
524 ///     pin: PhantomPinned,
525 /// }
526 /// pin_init!(&this in Buf {
527 ///     buf: [0; 64],
528 ///     ptr: unsafe { addr_of_mut!((*this.as_ptr()).buf).cast() },
529 ///     pin: PhantomPinned,
530 /// });
531 /// ```
532 ///
533 /// [`try_pin_init!`]: kernel::try_pin_init
534 /// [`NonNull<Self>`]: core::ptr::NonNull
535 // For a detailed example of how this macro works, see the module documentation of the hidden
536 // module `__internal` inside of `init/__internal.rs`.
537 #[macro_export]
538 macro_rules! pin_init {
539     ($(&$this:ident in)? $t:ident $(::<$($generics:ty),* $(,)?>)? {
540         $($fields:tt)*
541     }) => {
542         $crate::__init_internal!(
543             @this($($this)?),
544             @typ($t $(::<$($generics),*>)?),
545             @fields($($fields)*),
546             @error(::core::convert::Infallible),
547             @data(PinData, use_data),
548             @has_data(HasPinData, __pin_data),
549             @construct_closure(pin_init_from_closure),
550         )
551     };
552 }
553 
554 /// Construct an in-place, fallible pinned initializer for `struct`s.
555 ///
556 /// If the initialization can complete without error (or [`Infallible`]), then use [`pin_init!`].
557 ///
558 /// You can use the `?` operator or use `return Err(err)` inside the initializer to stop
559 /// initialization and return the error.
560 ///
561 /// IMPORTANT: if you have `unsafe` code inside of the initializer you have to ensure that when
562 /// initialization fails, the memory can be safely deallocated without any further modifications.
563 ///
564 /// This macro defaults the error to [`Error`].
565 ///
566 /// The syntax is identical to [`pin_init!`] with the following exception: you can append `? $type`
567 /// after the `struct` initializer to specify the error type you want to use.
568 ///
569 /// # Examples
570 ///
571 /// ```rust
572 /// # #![feature(new_uninit)]
573 /// use kernel::{init::{self, PinInit}, error::Error};
574 /// #[pin_data]
575 /// struct BigBuf {
576 ///     big: Box<[u8; 1024 * 1024 * 1024]>,
577 ///     small: [u8; 1024 * 1024],
578 ///     ptr: *mut u8,
579 /// }
580 ///
581 /// impl BigBuf {
582 ///     fn new() -> impl PinInit<Self, Error> {
583 ///         try_pin_init!(Self {
584 ///             big: Box::init(init::zeroed())?,
585 ///             small: [0; 1024 * 1024],
586 ///             ptr: core::ptr::null_mut(),
587 ///         }? Error)
588 ///     }
589 /// }
590 /// ```
591 // For a detailed example of how this macro works, see the module documentation of the hidden
592 // module `__internal` inside of `init/__internal.rs`.
593 #[macro_export]
594 macro_rules! try_pin_init {
595     ($(&$this:ident in)? $t:ident $(::<$($generics:ty),* $(,)?>)? {
596         $($fields:tt)*
597     }) => {
598         $crate::__init_internal!(
599             @this($($this)?),
600             @typ($t $(::<$($generics),*>)? ),
601             @fields($($fields)*),
602             @error($crate::error::Error),
603             @data(PinData, use_data),
604             @has_data(HasPinData, __pin_data),
605             @construct_closure(pin_init_from_closure),
606         )
607     };
608     ($(&$this:ident in)? $t:ident $(::<$($generics:ty),* $(,)?>)? {
609         $($fields:tt)*
610     }? $err:ty) => {
611         $crate::__init_internal!(
612             @this($($this)?),
613             @typ($t $(::<$($generics),*>)? ),
614             @fields($($fields)*),
615             @error($err),
616             @data(PinData, use_data),
617             @has_data(HasPinData, __pin_data),
618             @construct_closure(pin_init_from_closure),
619         )
620     };
621 }
622 
623 /// Construct an in-place initializer for `struct`s.
624 ///
625 /// This macro defaults the error to [`Infallible`]. If you need [`Error`], then use
626 /// [`try_init!`].
627 ///
628 /// The syntax is identical to [`pin_init!`] and its safety caveats also apply:
629 /// - `unsafe` code must guarantee either full initialization or return an error and allow
630 ///   deallocation of the memory.
631 /// - the fields are initialized in the order given in the initializer.
632 /// - no references to fields are allowed to be created inside of the initializer.
633 ///
634 /// This initializer is for initializing data in-place that might later be moved. If you want to
635 /// pin-initialize, use [`pin_init!`].
636 ///
637 /// [`try_init!`]: crate::try_init!
638 // For a detailed example of how this macro works, see the module documentation of the hidden
639 // module `__internal` inside of `init/__internal.rs`.
640 #[macro_export]
641 macro_rules! init {
642     ($(&$this:ident in)? $t:ident $(::<$($generics:ty),* $(,)?>)? {
643         $($fields:tt)*
644     }) => {
645         $crate::__init_internal!(
646             @this($($this)?),
647             @typ($t $(::<$($generics),*>)?),
648             @fields($($fields)*),
649             @error(::core::convert::Infallible),
650             @data(InitData, /*no use_data*/),
651             @has_data(HasInitData, __init_data),
652             @construct_closure(init_from_closure),
653         )
654     }
655 }
656 
657 /// Construct an in-place fallible initializer for `struct`s.
658 ///
659 /// This macro defaults the error to [`Error`]. If you need [`Infallible`], then use
660 /// [`init!`].
661 ///
662 /// The syntax is identical to [`try_pin_init!`]. If you want to specify a custom error,
663 /// append `? $type` after the `struct` initializer.
664 /// The safety caveats from [`try_pin_init!`] also apply:
665 /// - `unsafe` code must guarantee either full initialization or return an error and allow
666 ///   deallocation of the memory.
667 /// - the fields are initialized in the order given in the initializer.
668 /// - no references to fields are allowed to be created inside of the initializer.
669 ///
670 /// # Examples
671 ///
672 /// ```rust
673 /// use kernel::{init::PinInit, error::Error, InPlaceInit};
674 /// struct BigBuf {
675 ///     big: Box<[u8; 1024 * 1024 * 1024]>,
676 ///     small: [u8; 1024 * 1024],
677 /// }
678 ///
679 /// impl BigBuf {
680 ///     fn new() -> impl Init<Self, Error> {
681 ///         try_init!(Self {
682 ///             big: Box::init(zeroed())?,
683 ///             small: [0; 1024 * 1024],
684 ///         }? Error)
685 ///     }
686 /// }
687 /// ```
688 // For a detailed example of how this macro works, see the module documentation of the hidden
689 // module `__internal` inside of `init/__internal.rs`.
690 #[macro_export]
691 macro_rules! try_init {
692     ($(&$this:ident in)? $t:ident $(::<$($generics:ty),* $(,)?>)? {
693         $($fields:tt)*
694     }) => {
695         $crate::__init_internal!(
696             @this($($this)?),
697             @typ($t $(::<$($generics),*>)?),
698             @fields($($fields)*),
699             @error($crate::error::Error),
700             @data(InitData, /*no use_data*/),
701             @has_data(HasInitData, __init_data),
702             @construct_closure(init_from_closure),
703         )
704     };
705     ($(&$this:ident in)? $t:ident $(::<$($generics:ty),* $(,)?>)? {
706         $($fields:tt)*
707     }? $err:ty) => {
708         $crate::__init_internal!(
709             @this($($this)?),
710             @typ($t $(::<$($generics),*>)?),
711             @fields($($fields)*),
712             @error($err),
713             @data(InitData, /*no use_data*/),
714             @has_data(HasInitData, __init_data),
715             @construct_closure(init_from_closure),
716         )
717     };
718 }
719 
720 /// A pin-initializer for the type `T`.
721 ///
722 /// To use this initializer, you will need a suitable memory location that can hold a `T`. This can
723 /// be [`Box<T>`], [`Arc<T>`], [`UniqueArc<T>`] or even the stack (see [`stack_pin_init!`]). Use the
724 /// [`InPlaceInit::pin_init`] function of a smart pointer like [`Arc<T>`] on this.
725 ///
726 /// Also see the [module description](self).
727 ///
728 /// # Safety
729 ///
730 /// When implementing this type you will need to take great care. Also there are probably very few
731 /// cases where a manual implementation is necessary. Use [`pin_init_from_closure`] where possible.
732 ///
733 /// The [`PinInit::__pinned_init`] function
734 /// - returns `Ok(())` if it initialized every field of `slot`,
735 /// - returns `Err(err)` if it encountered an error and then cleaned `slot`, this means:
736 ///     - `slot` can be deallocated without UB occurring,
737 ///     - `slot` does not need to be dropped,
738 ///     - `slot` is not partially initialized.
739 /// - while constructing the `T` at `slot` it upholds the pinning invariants of `T`.
740 ///
741 /// [`Arc<T>`]: crate::sync::Arc
742 /// [`Arc::pin_init`]: crate::sync::Arc::pin_init
743 #[must_use = "An initializer must be used in order to create its value."]
744 pub unsafe trait PinInit<T: ?Sized, E = Infallible>: Sized {
745     /// Initializes `slot`.
746     ///
747     /// # Safety
748     ///
749     /// - `slot` is a valid pointer to uninitialized memory.
750     /// - the caller does not touch `slot` when `Err` is returned, they are only permitted to
751     ///   deallocate.
752     /// - `slot` will not move until it is dropped, i.e. it will be pinned.
753     unsafe fn __pinned_init(self, slot: *mut T) -> Result<(), E>;
754 }
755 
756 /// An initializer for `T`.
757 ///
758 /// To use this initializer, you will need a suitable memory location that can hold a `T`. This can
759 /// be [`Box<T>`], [`Arc<T>`], [`UniqueArc<T>`] or even the stack (see [`stack_pin_init!`]). Use the
760 /// [`InPlaceInit::init`] function of a smart pointer like [`Arc<T>`] on this. Because
761 /// [`PinInit<T, E>`] is a super trait, you can use every function that takes it as well.
762 ///
763 /// Also see the [module description](self).
764 ///
765 /// # Safety
766 ///
767 /// When implementing this type you will need to take great care. Also there are probably very few
768 /// cases where a manual implementation is necessary. Use [`init_from_closure`] where possible.
769 ///
770 /// The [`Init::__init`] function
771 /// - returns `Ok(())` if it initialized every field of `slot`,
772 /// - returns `Err(err)` if it encountered an error and then cleaned `slot`, this means:
773 ///     - `slot` can be deallocated without UB occurring,
774 ///     - `slot` does not need to be dropped,
775 ///     - `slot` is not partially initialized.
776 /// - while constructing the `T` at `slot` it upholds the pinning invariants of `T`.
777 ///
778 /// The `__pinned_init` function from the supertrait [`PinInit`] needs to execute the exact same
779 /// code as `__init`.
780 ///
781 /// Contrary to its supertype [`PinInit<T, E>`] the caller is allowed to
782 /// move the pointee after initialization.
783 ///
784 /// [`Arc<T>`]: crate::sync::Arc
785 #[must_use = "An initializer must be used in order to create its value."]
786 pub unsafe trait Init<T: ?Sized, E = Infallible>: Sized {
787     /// Initializes `slot`.
788     ///
789     /// # Safety
790     ///
791     /// - `slot` is a valid pointer to uninitialized memory.
792     /// - the caller does not touch `slot` when `Err` is returned, they are only permitted to
793     ///   deallocate.
794     unsafe fn __init(self, slot: *mut T) -> Result<(), E>;
795 }
796 
797 // SAFETY: Every in-place initializer can also be used as a pin-initializer.
798 unsafe impl<T: ?Sized, E, I> PinInit<T, E> for I
799 where
800     I: Init<T, E>,
801 {
802     unsafe fn __pinned_init(self, slot: *mut T) -> Result<(), E> {
803         // SAFETY: `__init` meets the same requirements as `__pinned_init`, except that it does not
804         // require `slot` to not move after init.
805         unsafe { self.__init(slot) }
806     }
807 }
808 
809 /// Creates a new [`PinInit<T, E>`] from the given closure.
810 ///
811 /// # Safety
812 ///
813 /// The closure:
814 /// - returns `Ok(())` if it initialized every field of `slot`,
815 /// - returns `Err(err)` if it encountered an error and then cleaned `slot`, this means:
816 ///     - `slot` can be deallocated without UB occurring,
817 ///     - `slot` does not need to be dropped,
818 ///     - `slot` is not partially initialized.
819 /// - may assume that the `slot` does not move if `T: !Unpin`,
820 /// - while constructing the `T` at `slot` it upholds the pinning invariants of `T`.
821 #[inline]
822 pub const unsafe fn pin_init_from_closure<T: ?Sized, E>(
823     f: impl FnOnce(*mut T) -> Result<(), E>,
824 ) -> impl PinInit<T, E> {
825     __internal::InitClosure(f, PhantomData)
826 }
827 
828 /// Creates a new [`Init<T, E>`] from the given closure.
829 ///
830 /// # Safety
831 ///
832 /// The closure:
833 /// - returns `Ok(())` if it initialized every field of `slot`,
834 /// - returns `Err(err)` if it encountered an error and then cleaned `slot`, this means:
835 ///     - `slot` can be deallocated without UB occurring,
836 ///     - `slot` does not need to be dropped,
837 ///     - `slot` is not partially initialized.
838 /// - the `slot` may move after initialization.
839 /// - while constructing the `T` at `slot` it upholds the pinning invariants of `T`.
840 #[inline]
841 pub const unsafe fn init_from_closure<T: ?Sized, E>(
842     f: impl FnOnce(*mut T) -> Result<(), E>,
843 ) -> impl Init<T, E> {
844     __internal::InitClosure(f, PhantomData)
845 }
846 
847 /// An initializer that leaves the memory uninitialized.
848 ///
849 /// The initializer is a no-op. The `slot` memory is not changed.
850 #[inline]
851 pub fn uninit<T, E>() -> impl Init<MaybeUninit<T>, E> {
852     // SAFETY: The memory is allowed to be uninitialized.
853     unsafe { init_from_closure(|_| Ok(())) }
854 }
855 
856 // SAFETY: Every type can be initialized by-value.
857 unsafe impl<T, E> Init<T, E> for T {
858     unsafe fn __init(self, slot: *mut T) -> Result<(), E> {
859         unsafe { slot.write(self) };
860         Ok(())
861     }
862 }
863 
864 /// Smart pointer that can initialize memory in-place.
865 pub trait InPlaceInit<T>: Sized {
866     /// Use the given pin-initializer to pin-initialize a `T` inside of a new smart pointer of this
867     /// type.
868     ///
869     /// If `T: !Unpin` it will not be able to move afterwards.
870     fn try_pin_init<E>(init: impl PinInit<T, E>) -> Result<Pin<Self>, E>
871     where
872         E: From<AllocError>;
873 
874     /// Use the given pin-initializer to pin-initialize a `T` inside of a new smart pointer of this
875     /// type.
876     ///
877     /// If `T: !Unpin` it will not be able to move afterwards.
878     fn pin_init<E>(init: impl PinInit<T, E>) -> error::Result<Pin<Self>>
879     where
880         Error: From<E>,
881     {
882         // SAFETY: We delegate to `init` and only change the error type.
883         let init = unsafe {
884             pin_init_from_closure(|slot| init.__pinned_init(slot).map_err(|e| Error::from(e)))
885         };
886         Self::try_pin_init(init)
887     }
888 
889     /// Use the given initializer to in-place initialize a `T`.
890     fn try_init<E>(init: impl Init<T, E>) -> Result<Self, E>
891     where
892         E: From<AllocError>;
893 
894     /// Use the given initializer to in-place initialize a `T`.
895     fn init<E>(init: impl Init<T, E>) -> error::Result<Self>
896     where
897         Error: From<E>,
898     {
899         // SAFETY: We delegate to `init` and only change the error type.
900         let init = unsafe {
901             init_from_closure(|slot| init.__pinned_init(slot).map_err(|e| Error::from(e)))
902         };
903         Self::try_init(init)
904     }
905 }
906 
907 impl<T> InPlaceInit<T> for Box<T> {
908     #[inline]
909     fn try_pin_init<E>(init: impl PinInit<T, E>) -> Result<Pin<Self>, E>
910     where
911         E: From<AllocError>,
912     {
913         let mut this = Box::try_new_uninit()?;
914         let slot = this.as_mut_ptr();
915         // SAFETY: When init errors/panics, slot will get deallocated but not dropped,
916         // slot is valid and will not be moved, because we pin it later.
917         unsafe { init.__pinned_init(slot)? };
918         // SAFETY: All fields have been initialized.
919         Ok(unsafe { this.assume_init() }.into())
920     }
921 
922     #[inline]
923     fn try_init<E>(init: impl Init<T, E>) -> Result<Self, E>
924     where
925         E: From<AllocError>,
926     {
927         let mut this = Box::try_new_uninit()?;
928         let slot = this.as_mut_ptr();
929         // SAFETY: When init errors/panics, slot will get deallocated but not dropped,
930         // slot is valid.
931         unsafe { init.__init(slot)? };
932         // SAFETY: All fields have been initialized.
933         Ok(unsafe { this.assume_init() })
934     }
935 }
936 
937 impl<T> InPlaceInit<T> for UniqueArc<T> {
938     #[inline]
939     fn try_pin_init<E>(init: impl PinInit<T, E>) -> Result<Pin<Self>, E>
940     where
941         E: From<AllocError>,
942     {
943         let mut this = UniqueArc::try_new_uninit()?;
944         let slot = this.as_mut_ptr();
945         // SAFETY: When init errors/panics, slot will get deallocated but not dropped,
946         // slot is valid and will not be moved, because we pin it later.
947         unsafe { init.__pinned_init(slot)? };
948         // SAFETY: All fields have been initialized.
949         Ok(unsafe { this.assume_init() }.into())
950     }
951 
952     #[inline]
953     fn try_init<E>(init: impl Init<T, E>) -> Result<Self, E>
954     where
955         E: From<AllocError>,
956     {
957         let mut this = UniqueArc::try_new_uninit()?;
958         let slot = this.as_mut_ptr();
959         // SAFETY: When init errors/panics, slot will get deallocated but not dropped,
960         // slot is valid.
961         unsafe { init.__init(slot)? };
962         // SAFETY: All fields have been initialized.
963         Ok(unsafe { this.assume_init() })
964     }
965 }
966 
967 /// Trait facilitating pinned destruction.
968 ///
969 /// Use [`pinned_drop`] to implement this trait safely:
970 ///
971 /// ```rust
972 /// # use kernel::sync::Mutex;
973 /// use kernel::macros::pinned_drop;
974 /// use core::pin::Pin;
975 /// #[pin_data(PinnedDrop)]
976 /// struct Foo {
977 ///     #[pin]
978 ///     mtx: Mutex<usize>,
979 /// }
980 ///
981 /// #[pinned_drop]
982 /// impl PinnedDrop for Foo {
983 ///     fn drop(self: Pin<&mut Self>) {
984 ///         pr_info!("Foo is being dropped!");
985 ///     }
986 /// }
987 /// ```
988 ///
989 /// # Safety
990 ///
991 /// This trait must be implemented via the [`pinned_drop`] proc-macro attribute on the impl.
992 ///
993 /// [`pinned_drop`]: kernel::macros::pinned_drop
994 pub unsafe trait PinnedDrop: __internal::HasPinData {
995     /// Executes the pinned destructor of this type.
996     ///
997     /// While this function is marked safe, it is actually unsafe to call it manually. For this
998     /// reason it takes an additional parameter. This type can only be constructed by `unsafe` code
999     /// and thus prevents this function from being called where it should not.
1000     ///
1001     /// This extra parameter will be generated by the `#[pinned_drop]` proc-macro attribute
1002     /// automatically.
1003     fn drop(self: Pin<&mut Self>, only_call_from_drop: __internal::OnlyCallFromDrop);
1004 }
1005 
1006 /// Marker trait for types that can be initialized by writing just zeroes.
1007 ///
1008 /// # Safety
1009 ///
1010 /// The bit pattern consisting of only zeroes is a valid bit pattern for this type. In other words,
1011 /// this is not UB:
1012 ///
1013 /// ```rust,ignore
1014 /// let val: Self = unsafe { core::mem::zeroed() };
1015 /// ```
1016 pub unsafe trait Zeroable {}
1017 
1018 /// Create a new zeroed T.
1019 ///
1020 /// The returned initializer will write `0x00` to every byte of the given `slot`.
1021 #[inline]
1022 pub fn zeroed<T: Zeroable>() -> impl Init<T> {
1023     // SAFETY: Because `T: Zeroable`, all bytes zero is a valid bit pattern for `T`
1024     // and because we write all zeroes, the memory is initialized.
1025     unsafe {
1026         init_from_closure(|slot: *mut T| {
1027             slot.write_bytes(0, 1);
1028             Ok(())
1029         })
1030     }
1031 }
1032 
1033 macro_rules! impl_zeroable {
1034     ($($({$($generics:tt)*})? $t:ty, )*) => {
1035         $(unsafe impl$($($generics)*)? Zeroable for $t {})*
1036     };
1037 }
1038 
1039 impl_zeroable! {
1040     // SAFETY: All primitives that are allowed to be zero.
1041     bool,
1042     char,
1043     u8, u16, u32, u64, u128, usize,
1044     i8, i16, i32, i64, i128, isize,
1045     f32, f64,
1046 
1047     // SAFETY: These are ZSTs, there is nothing to zero.
1048     {<T: ?Sized>} PhantomData<T>, core::marker::PhantomPinned, Infallible, (),
1049 
1050     // SAFETY: Type is allowed to take any value, including all zeros.
1051     {<T>} MaybeUninit<T>,
1052 
1053     // SAFETY: All zeros is equivalent to `None` (option layout optimization guarantee).
1054     Option<NonZeroU8>, Option<NonZeroU16>, Option<NonZeroU32>, Option<NonZeroU64>,
1055     Option<NonZeroU128>, Option<NonZeroUsize>,
1056     Option<NonZeroI8>, Option<NonZeroI16>, Option<NonZeroI32>, Option<NonZeroI64>,
1057     Option<NonZeroI128>, Option<NonZeroIsize>,
1058 
1059     // SAFETY: All zeros is equivalent to `None` (option layout optimization guarantee).
1060     //
1061     // In this case we are allowed to use `T: ?Sized`, since all zeros is the `None` variant.
1062     {<T: ?Sized>} Option<NonNull<T>>,
1063     {<T: ?Sized>} Option<Box<T>>,
1064 
1065     // SAFETY: `null` pointer is valid.
1066     //
1067     // We cannot use `T: ?Sized`, since the VTABLE pointer part of fat pointers is not allowed to be
1068     // null.
1069     //
1070     // When `Pointee` gets stabilized, we could use
1071     // `T: ?Sized where <T as Pointee>::Metadata: Zeroable`
1072     {<T>} *mut T, {<T>} *const T,
1073 
1074     // SAFETY: `null` pointer is valid and the metadata part of these fat pointers is allowed to be
1075     // zero.
1076     {<T>} *mut [T], {<T>} *const [T], *mut str, *const str,
1077 
1078     // SAFETY: `T` is `Zeroable`.
1079     {<const N: usize, T: Zeroable>} [T; N], {<T: Zeroable>} Wrapping<T>,
1080 }
1081 
1082 macro_rules! impl_tuple_zeroable {
1083     ($(,)?) => {};
1084     ($first:ident, $($t:ident),* $(,)?) => {
1085         // SAFETY: All elements are zeroable and padding can be zero.
1086         unsafe impl<$first: Zeroable, $($t: Zeroable),*> Zeroable for ($first, $($t),*) {}
1087         impl_tuple_zeroable!($($t),* ,);
1088     }
1089 }
1090 
1091 impl_tuple_zeroable!(A, B, C, D, E, F, G, H, I, J);
1092