[v2,4/5] rust: init: add common init-helper functions for `Opaque`
Commit Message
Add helper functions to more easily initialize `Opaque<T>` via FFI.
These functions take a function pointer to the FFI-initialization
function and take between 0-4 other arguments. It then returns an
initializer that uses the FFI function along with the given arguments to
initialize an `Opaque<T>`.
Signed-off-by: Benno Lossin <y86-dev@protonmail.com>
---
rust/kernel/init.rs | 1 +
rust/kernel/init/common.rs | 42 ++++++++++++++++++++++++++++++++++++++
2 files changed, 43 insertions(+)
create mode 100644 rust/kernel/init/common.rs
--
2.39.2
Comments
On 21.03.23 21:06, Boqun Feng wrote:
> I wonder whether it's better to make these as methods of Opaque<T>, i.e.
>
> impl<T> Opaque<T> {
> pub unsafe fn ffi_init(...) -> impl PinInit<Self> {
> ...
> }
> ...
> }
>
> then it's a little more obvious to users that these methods are for
> Opaque type pin init.
>
> Thoughts?
That would work, will add it to v3.
Cheers,
Benno
@@ -207,6 +207,7 @@ use core::{
ptr,
};
+pub mod common;
#[doc(hidden)]
pub mod macros;
new file mode 100644
@@ -0,0 +1,42 @@
+// SPDX-License-Identifier: Apache-2.0 OR MIT
+
+//! Module containing common kernel initializer functions.
+
+use crate::{
+ init::{self, PinInit},
+ types::Opaque,
+};
+
+macro_rules! create_func {
+ ($name:ident $(, $arg_name:ident: $arg_typ:ident)*) => {
+ /// Create an initializer using the given initializer function from C.
+ ///
+ /// # Safety
+ ///
+ /// The given function **must** under all circumstances initialize the memory location to a
+ /// valid `T`. If it fails to do so it results in UB.
+ ///
+ /// If any parameters are given, those need to be valid for the function. Valid means that
+ /// calling the function with those parameters complies with the above requirement **and**
+ /// every other requirement on the function itself.
+ pub unsafe fn $name<T $(, $arg_typ)*>(
+ init_func: unsafe extern "C" fn(*mut T $(, $arg_name: $arg_typ)*),
+ $($arg_name: $arg_typ,)*
+ ) -> impl PinInit<Opaque<T>> {
+ // SAFETY: The safety contract of this function ensures that `init_func` fully
+ // initializes `slot`.
+ unsafe {
+ init::pin_init_from_closure(move |slot| {
+ init_func(Opaque::raw_get(slot) $(, $arg_name)*);
+ Ok(())
+ })
+ }
+ }
+ }
+}
+
+create_func!(ffi_init);
+create_func!(ffi_init1, arg1: A1);
+create_func!(ffi_init2, arg1: A1, arg2: A2);
+create_func!(ffi_init3, arg1: A1, arg2: A2, arg3: A3);
+create_func!(ffi_init4, arg1: A1, arg2: A2, arg3: A3, arg4: A4);