From: Alice Ryhl Date: Tue, 1 Oct 2024 08:22:21 +0000 (+0000) Subject: rust: types: add Opaque::try_ffi_init X-Git-Tag: v6.13-rc1~28^2~73 X-Git-Url: http://git.ipfire.org/?a=commitdiff_plain;h=a69dc41a4211b0da311ae3a3b79dd4497c9dfb60;p=thirdparty%2Fkernel%2Flinux.git rust: types: add Opaque::try_ffi_init This will be used by the miscdevice abstractions, as the C function `misc_register` is fallible. Signed-off-by: Alice Ryhl Reviewed-by: Benno Lossin Reviewed-by: Fiona Behrens Link: https://lore.kernel.org/r/20241001-b4-miscdevice-v2-1-330d760041fa@google.com Signed-off-by: Greg Kroah-Hartman --- diff --git a/rust/kernel/types.rs b/rust/kernel/types.rs index 9e7ca066355cd..070d03152937f 100644 --- a/rust/kernel/types.rs +++ b/rust/kernel/types.rs @@ -299,6 +299,22 @@ impl Opaque { } } + /// Creates a fallible pin-initializer from the given initializer closure. + /// + /// The returned initializer calls the given closure with the pointer to the inner `T` of this + /// `Opaque`. Since this memory is uninitialized, the closure is not allowed to read from it. + /// + /// This function is safe, because the `T` inside of an `Opaque` is allowed to be + /// uninitialized. Additionally, access to the inner `T` requires `unsafe`, so the caller needs + /// to verify at that point that the inner value is valid. + pub fn try_ffi_init( + init_func: impl FnOnce(*mut T) -> Result<(), E>, + ) -> impl PinInit { + // SAFETY: We contain a `MaybeUninit`, so it is OK for the `init_func` to not fully + // initialize the `T`. + unsafe { init::pin_init_from_closure::<_, E>(move |slot| init_func(Self::raw_get(slot))) } + } + /// Returns a raw pointer to the opaque data. pub const fn get(&self) -> *mut T { UnsafeCell::get(&self.value).cast::()