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