init.rs 50 KB

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