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