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