init.rs 48 KB

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