Received: by 2002:a05:6358:11c7:b0:104:8066:f915 with SMTP id i7csp1962224rwl; Sat, 8 Apr 2023 05:28:03 -0700 (PDT) X-Google-Smtp-Source: AKy350aPoGPrvwmtrSly90BMmjnATYQYPV98ia2udjtmvUg0v3hmKv+sW7+MZ4fHKLwSLtaVih63 X-Received: by 2002:a17:90b:1d89:b0:23f:29a:5554 with SMTP id pf9-20020a17090b1d8900b0023f029a5554mr5571885pjb.48.1680956883138; Sat, 08 Apr 2023 05:28:03 -0700 (PDT) ARC-Seal: i=1; a=rsa-sha256; t=1680956883; cv=none; d=google.com; s=arc-20160816; b=oE5hiR8NnfOqf9PNojhTc6XyUjsG5eCiKNEj+EusaPh2ZSKvVgjYh3e4JDP6A/esrP 8pDI/lI8kqmHhj/nhZvEDArxNIxIpDGtH5XPl+UT2Kv2PYm8ZOWTyZsCQTQde4botZnl e4w6WAkIobm2kZKcsQ+BV/AXtZMdExhH1Y1NSj/tv2JZsLDeN4jy3t6xzGi9gPQbOmbc KJ60upLV0DpwT1L3VdFodNc8HtApIPoEAfrVtmQQCcpn4j5HOcb31eNLmwUTZrU/KP6q UAUlrJ7J8dr8bIN7ZqsSJdcH69V4QTe3bfMuNCgNGlymwEK3bBZWSqO1Wx74mQHEjXWp fuiA== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=arc-20160816; h=list-id:precedence:content-transfer-encoding:mime-version :feedback-id:references:in-reply-to:message-id:subject:cc:from:to :dkim-signature:date; bh=hihuEoqXcXK159Nac/9KFKLP5s288mJML8r+SohUUyw=; b=JGsKGEv9kcAbZg8K1GN2x7caLnpjNMXhAh4svkkdCPi670PL/n7uvH9ZTSQRbGHbxw QuOys+h/IS5GqXL/ZqUHYkhTjScItwHFIC8fjW+RHe8pMoC6IWJXsU8N+W1xHPIBc/Qk 3K30yeSUfwVcdrnvtJ8lkBuAGpf27agBkFy2ezIkDIXt/imiDF05xamLcM5Vvyv/2bPk pgTi7F8CHLSmKAcbHN1HbZuCd5WipC9LtINAhD7d5y+RuIZCeOx/iLA5/vWYjra4LyJd zNua6d7vEbow6Gb6PNNp6a4CJr8uXbXNRg0R9xpAo4qHA0apfsbStYoU19b/89EsF8pR M/vg== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@protonmail.com header.s=protonmail3 header.b=E9m2cS7K; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=QUARANTINE sp=QUARANTINE dis=NONE) header.from=protonmail.com Return-Path: Received: from out1.vger.email (out1.vger.email. [2620:137:e000::1:20]) by mx.google.com with ESMTP id l9-20020a654c49000000b0050c0763b32csi5584777pgr.233.2023.04.08.05.27.52; Sat, 08 Apr 2023 05:28:03 -0700 (PDT) Received-SPF: pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) client-ip=2620:137:e000::1:20; Authentication-Results: mx.google.com; dkim=pass header.i=@protonmail.com header.s=protonmail3 header.b=E9m2cS7K; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=QUARANTINE sp=QUARANTINE dis=NONE) header.from=protonmail.com Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S231330AbjDHM1S (ORCPT + 99 others); Sat, 8 Apr 2023 08:27:18 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:34950 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S230170AbjDHM1D (ORCPT ); Sat, 8 Apr 2023 08:27:03 -0400 Received: from mail-4322.protonmail.ch (mail-4322.protonmail.ch [185.70.43.22]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id ADB1910265 for ; Sat, 8 Apr 2023 05:26:41 -0700 (PDT) Date: Sat, 08 Apr 2023 12:26:07 +0000 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=protonmail.com; s=protonmail3; t=1680956777; x=1681215977; bh=hihuEoqXcXK159Nac/9KFKLP5s288mJML8r+SohUUyw=; h=Date:To:From:Cc:Subject:Message-ID:In-Reply-To:References: Feedback-ID:From:To:Cc:Date:Subject:Reply-To:Feedback-ID: Message-ID:BIMI-Selector; b=E9m2cS7KV4pzayV0x3UFSvXPwkPuFOTxjf7VrrKJfjKfc5yeqyVMQWDNad9sjEPY9 i/i2imYoUtt/QcDo11eGzwWdZUdnDl0soDYK46iLcqqVeH+8eaqt1UvAQ94r7IqoK3 7P89MfdrRCaZuMPErjTSYaKtl3q+gAcM6VcpfjrrLzZe8JpZRG9KUuaSIDMRmxvCRp f2D+ZjWeYsAh00Lc8dDvNxDVAOOAR9BLCFo7iRRNPJgaItKKiaG9i5qrrLPLF/0rMh dD/7nlchIqDKhrJsFcULPcuvnlR6opkX0labJxtn1//wWyPkP6Ow/KETN0IdksbXb+ AGwNNy0NmLN0g== To: Miguel Ojeda , Alex Gaynor , Wedson Almeida Filho , Boqun Feng , Gary Guo , =?utf-8?Q?Bj=C3=B6rn_Roy_Baron?= , Alice Ryhl , Andreas Hindborg From: Benno Lossin Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, patches@lists.linux.dev, Benno Lossin , Alice Ryhl , Andreas Hindborg Subject: [PATCH v7 10/15] rust: init: add `stack_pin_init!` macro Message-ID: <20230408122429.1103522-11-y86-dev@protonmail.com> In-Reply-To: <20230408122429.1103522-1-y86-dev@protonmail.com> References: <20230408122429.1103522-1-y86-dev@protonmail.com> Feedback-ID: 40624463:user:proton MIME-Version: 1.0 Content-Type: text/plain; charset=utf-8 Content-Transfer-Encoding: quoted-printable X-Spam-Status: No, score=-0.2 required=5.0 tests=DKIM_SIGNED,DKIM_VALID, DKIM_VALID_AU,DKIM_VALID_EF,FREEMAIL_FROM,RCVD_IN_MSPIKE_H2, SPF_HELO_PASS,SPF_PASS autolearn=unavailable autolearn_force=no version=3.4.6 X-Spam-Checker-Version: SpamAssassin 3.4.6 (2021-04-09) on lindbergh.monkeyblade.net Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org The `stack_pin_init!` macro allows pin-initializing a value on the stack. It accepts a `impl PinInit` to initialize a `T`. It allows propagating any errors via `?` or handling it normally via `match`. Signed-off-by: Benno Lossin Reviewed-by: Alice Ryhl Reviewed-by: Andreas Hindborg Reviewed-by: Gary Guo --- rust/kernel/init.rs | 140 +++++++++++++++++++++++++++++++-- rust/kernel/init/__internal.rs | 57 ++++++++++++++ 2 files changed, 191 insertions(+), 6 deletions(-) diff --git a/rust/kernel/init.rs b/rust/kernel/init.rs index 37e8159df24d..99751375e7c8 100644 --- a/rust/kernel/init.rs +++ b/rust/kernel/init.rs @@ -12,7 +12,8 @@ //! //! To initialize a `struct` with an in-place constructor you will need tw= o things: //! - an in-place constructor, -//! - a memory location that can hold your `struct`. +//! - a memory location that can hold your `struct` (this can be the [stac= k], an [`Arc`], +//! [`UniqueArc`], [`Box`] or any other smart pointer that impleme= nts [`InPlaceInit`]). //! //! To get an in-place constructor there are generally three options: //! - directly creating an in-place constructor using the [`pin_init!`] ma= cro, @@ -180,6 +181,7 @@ //! [pinning]: https://doc.rust-lang.org/std/pin/index.html //! [structurally pinned fields]: //! https://doc.rust-lang.org/std/pin/index.html#pinning-is-structural= -for-field +//! [stack]: crate::stack_pin_init //! [`Arc`]: crate::sync::Arc //! [`impl PinInit`]: PinInit //! [`impl PinInit`]: PinInit @@ -202,6 +204,132 @@ pub mod __internal; #[doc(hidden)] pub mod macros; +/// Initialize and pin a type directly on the stack. +/// +/// # Examples +/// +/// ```rust +/// # #![allow(clippy::disallowed_names, clippy::new_ret_no_self)] +/// # use kernel::{init, pin_init, stack_pin_init, init::*, sync::Mutex, n= ew_mutex}; +/// # use macros::pin_data; +/// # use core::pin::Pin; +/// #[pin_data] +/// struct Foo { +/// #[pin] +/// a: Mutex, +/// b: Bar, +/// } +/// +/// #[pin_data] +/// struct Bar { +/// x: u32, +/// } +/// +/// stack_pin_init!(let foo =3D pin_init!(Foo { +/// a <- new_mutex!(42), +/// b: Bar { +/// x: 64, +/// }, +/// })); +/// let foo: Pin<&mut Foo> =3D foo; +/// pr_info!("a: {}", &*foo.a.lock()); +/// ``` +/// +/// # Syntax +/// +/// A normal `let` binding with optional type annotation. The expression i= s expected to implement +/// [`PinInit`]/[`Init`] with the error type [`Infallible`]. If you want t= o use a different error +/// type, then use [`stack_try_pin_init!`]. +#[macro_export] +macro_rules! stack_pin_init { + (let $var:ident $(: $t:ty)? =3D $val:expr) =3D> { + let val =3D $val; + let mut $var =3D ::core::pin::pin!($crate::init::__internal::Stack= Init$(::<$t>)?::uninit()); + let mut $var =3D match $crate::init::__internal::StackInit::init($= var, val) { + Ok(res) =3D> res, + Err(x) =3D> { + let x: ::core::convert::Infallible =3D x; + match x {} + } + }; + }; +} + +/// Initialize and pin a type directly on the stack. +/// +/// # Examples +/// +/// ```rust +/// # #![allow(clippy::disallowed_names, clippy::new_ret_no_self)] +/// # use kernel::{init, pin_init, stack_try_pin_init, init::*, sync::Mute= x, new_mutex}; +/// # use macros::pin_data; +/// # use core::{alloc::AllocError, pin::Pin}; +/// #[pin_data] +/// struct Foo { +/// #[pin] +/// a: Mutex, +/// b: Box, +/// } +/// +/// struct Bar { +/// x: u32, +/// } +/// +/// stack_try_pin_init!(let foo: Result, AllocError> =3D pin= _init!(Foo { +/// a <- new_mutex!(42), +/// b: Box::try_new(Bar { +/// x: 64, +/// })?, +/// })); +/// let foo =3D foo.unwrap(); +/// pr_info!("a: {}", &*foo.a.lock()); +/// ``` +/// +/// ```rust +/// # #![allow(clippy::disallowed_names, clippy::new_ret_no_self)] +/// # use kernel::{init, pin_init, stack_try_pin_init, init::*, sync::Mute= x, new_mutex}; +/// # use macros::pin_data; +/// # use core::{alloc::AllocError, pin::Pin}; +/// #[pin_data] +/// struct Foo { +/// #[pin] +/// a: Mutex, +/// b: Box, +/// } +/// +/// struct Bar { +/// x: u32, +/// } +/// +/// stack_try_pin_init!(let foo: Pin<&mut Foo> =3D? pin_init!(Foo { +/// a <- new_mutex!(42), +/// b: Box::try_new(Bar { +/// x: 64, +/// })?, +/// })); +/// pr_info!("a: {}", &*foo.a.lock()); +/// # Ok::<_, AllocError>(()) +/// ``` +/// +/// # Syntax +/// +/// A normal `let` binding with optional type annotation. The expression i= s expected to implement +/// [`PinInit`]/[`Init`]. This macro assigns a result to the given variabl= e, adding a `?` after the +/// `=3D` will propagate this error. +#[macro_export] +macro_rules! stack_try_pin_init { + (let $var:ident $(: $t:ty)? =3D $val:expr) =3D> { + let val =3D $val; + let mut $var =3D ::core::pin::pin!($crate::init::__internal::Stack= Init$(::<$t>)?::uninit()); + let mut $var =3D $crate::init::__internal::StackInit::init($var, v= al); + }; + (let $var:ident $(: $t:ty)? =3D? $val:expr) =3D> { + let val =3D $val; + let mut $var =3D ::core::pin::pin!($crate::init::__internal::Stack= Init$(::<$t>)?::uninit()); + let mut $var =3D $crate::init::__internal::StackInit::init($var, v= al)?; + }; +} + /// Construct an in-place, pinned initializer for `struct`s. /// /// This macro defaults the error to [`Infallible`]. If you need [`Error`]= , then use @@ -913,8 +1041,8 @@ macro_rules! try_init { /// A pin-initializer for the type `T`. /// /// To use this initializer, you will need a suitable memory location that= can hold a `T`. This can -/// be [`Box`], [`Arc`], [`UniqueArc`]. Use the [`InPlaceInit::pi= n_init`] function of a -/// smart pointer like [`Arc`] on this. +/// be [`Box`], [`Arc`], [`UniqueArc`] or even the stack (see [`s= tack_pin_init!`]). Use the +/// [`InPlaceInit::pin_init`] function of a smart pointer like [`Arc`] = on this. /// /// Also see the [module description](self). /// @@ -949,9 +1077,9 @@ pub unsafe trait PinInit:= Sized { /// An initializer for `T`. /// /// To use this initializer, you will need a suitable memory location that= can hold a `T`. This can -/// be [`Box`], [`Arc`], [`UniqueArc`]. Use the [`InPlaceInit::in= it`] function of a smart -/// pointer like [`Arc`] on this. Because [`PinInit`] is a super = trait, you can -/// use every function that takes it as well. +/// be [`Box`], [`Arc`], [`UniqueArc`] or even the stack (see [`s= tack_pin_init!`]). Use the +/// [`InPlaceInit::init`] function of a smart pointer like [`Arc`] on t= his. Because +/// [`PinInit`] is a super trait, you can use every function that ta= kes it as well. /// /// Also see the [module description](self). /// diff --git a/rust/kernel/init/__internal.rs b/rust/kernel/init/__internal.r= s index 2445763ba97a..2e643fb2e651 100644 --- a/rust/kernel/init/__internal.rs +++ b/rust/kernel/init/__internal.rs @@ -112,6 +112,63 @@ unsafe impl HasInitData for T { } } +/// Stack initializer helper type. Use [`stack_pin_init`] instead of this = primitive. +/// +/// # Invariants +/// +/// If `self.is_init` is true, then `self.value` is initialized. +/// +/// [`stack_pin_init`]: kernel::stack_pin_init +pub struct StackInit { + value: MaybeUninit, + is_init: bool, +} + +impl Drop for StackInit { + #[inline] + fn drop(&mut self) { + if self.is_init { + // SAFETY: As we are being dropped, we only call this once. An= d since `self.is_init` is + // true, `self.value` is initialized. + unsafe { self.value.assume_init_drop() }; + } + } +} + +impl StackInit { + /// Creates a new [`StackInit`] that is uninitialized. Use [`stack_= pin_init`] instead of this + /// primitive. + /// + /// [`stack_pin_init`]: kernel::stack_pin_init + #[inline] + pub fn uninit() -> Self { + Self { + value: MaybeUninit::uninit(), + is_init: false, + } + } + + /// Initializes the contents and returns the result. + #[inline] + pub fn init(self: Pin<&mut Self>, init: impl PinInit) -> Resu= lt, E> { + // SAFETY: We never move out of `this`. + let this =3D unsafe { Pin::into_inner_unchecked(self) }; + // The value is currently initialized, so it needs to be dropped b= efore we can reuse + // the memory (this is a safety guarantee of `Pin`). + if this.is_init { + this.is_init =3D false; + // SAFETY: `this.is_init` was true and therefore `this.value` = is initialized. + unsafe { this.value.assume_init_drop() }; + } + // SAFETY: The memory slot is valid and this type ensures that it = will stay pinned. + unsafe { init.__pinned_init(this.value.as_mut_ptr())? }; + // INVARIANT: `this.value` is initialized above. + this.is_init =3D true; + // SAFETY: The slot is now pinned, since we will never give access= to `&mut T`. + Ok(unsafe { Pin::new_unchecked(this.value.assume_init_mut()) }) + } +} + /// When a value of this type is dropped, it drops a `T`. /// /// Can be forgotton to prevent the drop. -- 2.39.2