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