[PATCH v6.1] rust: types: add `Opaque::pin_init`

From: Benno Lossin
Date: Thu Apr 06 2023 - 02:57:41 EST


Add support for pin-init in combination with `Opaque<T>`, the `pin_init`
function initializes the contents via a user-supplied initializer for
`T`.

Signed-off-by: Benno Lossin <y86-dev@xxxxxxxxxxxxxx>
Cc: Alice Ryhl <aliceryhl@xxxxxxxxxx>
Cc: Andreas Hindborg <a.hindborg@xxxxxxxxxxx>
Cc: Gary Guo <gary@xxxxxxxxxxx>
---
rust/kernel/init.rs | 3 +++
rust/kernel/types.rs | 18 ++++++++++++++++++
2 files changed, 21 insertions(+)

diff --git a/rust/kernel/init.rs b/rust/kernel/init.rs
index ffd539e2f5ef..23d879e53b26 100644
--- a/rust/kernel/init.rs
+++ b/rust/kernel/init.rs
@@ -177,6 +177,9 @@
//! }
//! ```
//!
+//! For more information on how to use [`pin_init_from_closure()`], take a look at the uses inside
+//! the `kernel` crate. The [`sync`] module is a good starting point.
+//!
//! [`sync`]: kernel::sync
//! [pinning]: https://doc.rust-lang.org/std/pin/index.html
//! [structurally pinned fields]:
diff --git a/rust/kernel/types.rs b/rust/kernel/types.rs
index ff2b2fac951d..cf1cbd6a1447 100644
--- a/rust/kernel/types.rs
+++ b/rust/kernel/types.rs
@@ -2,6 +2,7 @@

//! Kernel types.

+use crate::init::{self, PinInit};
use alloc::boxed::Box;
use core::{
cell::UnsafeCell,
@@ -234,6 +235,23 @@ impl<T> Opaque<T> {
Self(MaybeUninit::uninit())
}

+ /// Creates a pin-initializer for `Opaque<T>`.
+ ///
+ /// # Safety
+ ///
+ /// [`PinInit<T, E>`] promises that the [`Pin` `Drop` guarantee] is upheld for the type `T` if
+ /// initialization succeeds. `Opaque` is a wrapper that allows holding uninitialized values of
+ /// `T`, so it does not drop the `T` when it is dropped. When calling this function the caller
+ /// needs to guarantee that:
+ /// - either `T` does not have drop glue ([`core::mem::needs_drop`] retuns `false`),
+ /// - or the caller ensures the drop guarantee manually.
+ ///
+ /// [`Pin` `Drop` guarantee]: https://doc.rust-lang.org/core/pin/index.html#drop-guarantee
+ pub unsafe fn pin_init<E>(init: impl PinInit<T, E>) -> impl PinInit<Self, E> {
+ // SAFETY: `init` initializes the only field of this struct.
+ unsafe { init::pin_init_from_closure(|slot| init.__pinned_init(Self::raw_get(slot))) }
+ }
+
/// Returns a raw pointer to the opaque data.
pub fn get(&self) -> *mut T {
UnsafeCell::raw_get(self.0.as_ptr())
--
2.39.2