From patchwork Fri Mar 31 21:53:51 2023 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: y86-dev X-Patchwork-Id: 78002 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:a59:b0ea:0:b0:3b6:4342:cba0 with SMTP id b10csp868501vqo; Fri, 31 Mar 2023 15:08:02 -0700 (PDT) X-Google-Smtp-Source: AKy350ZLm4uPR1Gk7YvBvrXaf3N/TVo+h57lpjDrq/gmoCmmmaW7/kLXpBoADDfwSIrd4dmu6deq X-Received: by 2002:a17:906:27c4:b0:931:c2f0:9437 with SMTP id k4-20020a17090627c400b00931c2f09437mr30361281ejc.8.1680300482709; Fri, 31 Mar 2023 15:08:02 -0700 (PDT) ARC-Seal: i=1; a=rsa-sha256; t=1680300482; cv=none; d=google.com; s=arc-20160816; b=jjKyH6nLywbAGCno90sZ/4jAxlugk6OMFsLRxbic334n5TTdQ8PqC+TF0o4Ze3Ny6Z 89KYfGLbDi1suLp2sQ+j1V+CRsGU0sJl64r6Lt0teB4UUhZiv92zEXkvfb1ckGQZkMQX cWaRRV/8xZuCacLuWyHqc26UbsC06u1nGNhqodpgZBgS2097w6vKrDyb18FFgfEtju2B 3kGGiInmdIU7TrIcbkvVhfjAtbQ2ZZqv12FH1C20J6MAramOGjVhZpyP+ZClMjI28IKR 6AhDOKdTorlH7F8YkGFhmpU0C6oc090uyjYx3RKSjziRzWVGGIoVUN0rdtvo2KL1u2Xs fYAg== 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:message-id:subject:cc:from:to:dkim-signature:date; bh=sr2JvwCQdmMvlR7/qpZ4bQwbcN/uY8dZ+qqwZJYCJHk=; b=s4lPs4uhVzUJFIv+RdTXyQnMO27YhTPuHW6mxCeHIwP9eXFr7N1usu78zATFZV3V2h Q1jiqkvi13sOKlM10Le9W0xggth+yKW5+Gboq4zlkWMPFsanJa56xn68wSaUI7v9RiGL xHp5NpIMNzrz6HzA50vxZ+yLtLxI1TdNOcqQpkhSu8AAVGwaMuFiAnpb2ew4KMXhangw ejqVLl14dCJzb7MQHeXH366oauYjXbxlqmHA1+a7pYjX/pdH0jQJgvuKF6pTttCN8CtQ 8OcJFs1IpOmwEZkM0dwjFOv/3cVcetmnn9D6fPiRmIuOFqRd4PF+6XyM39P5Pv8gDiLs ZLlQ== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@protonmail.com header.s=protonmail3 header.b=hMiLXroT; 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: from out1.vger.email (out1.vger.email. [2620:137:e000::1:20]) by mx.google.com with ESMTP id v15-20020a170906564f00b0093fa751d442si2711055ejr.24.2023.03.31.15.07.39; Fri, 31 Mar 2023 15:08:02 -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=hMiLXroT; 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 S233179AbjCaV4h (ORCPT + 99 others); Fri, 31 Mar 2023 17:56:37 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:46790 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S233231AbjCaV4c (ORCPT ); Fri, 31 Mar 2023 17:56:32 -0400 Received: from mail-41103.protonmail.ch (mail-41103.protonmail.ch [185.70.41.103]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id D8F3D21ABA for ; Fri, 31 Mar 2023 14:55:58 -0700 (PDT) Date: Fri, 31 Mar 2023 21:53:51 +0000 Authentication-Results: mail-41103.protonmail.ch; dkim=pass (2048-bit key) header.d=protonmail.com header.i=@protonmail.com header.b="hMiLXroT" DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=protonmail.com; s=protonmail3; t=1680299645; x=1680558845; bh=sr2JvwCQdmMvlR7/qpZ4bQwbcN/uY8dZ+qqwZJYCJHk=; h=Date:To:From:Cc:Subject:Message-ID:Feedback-ID:From:To:Cc:Date: Subject:Reply-To:Feedback-ID:Message-ID:BIMI-Selector; b=hMiLXroTIFFAz5EJ8MA6SeSM1L2VB6VfiLs7V2lXWsY0ii+BdM7PlmBNayeFk8LVx Y4LS4MuI23KoTGP3FQ3Ir2VazfBs6q7EUogHVabF1HEy9mA7Dwz6gg2GLGGcXQ6b83 7OoBjlqSdnArgA6Kh3ddRWCCXjFceronO95l3FxKn76+LlBecx3DrSKHoEJ9u/Jz1e MFrTlBt2/HJYeacwYoaIZ6pYFHyYP8/k/i31FEJWRiD6YTVnQGJgUUQk1NtPxwc48d b1/GTaVFSD10CqP2/OAiLp9/eh1D4iuZ+GBMegfn3M20QIc9Op1ELnJewNuInBSg+G nRpN2FDRdVtOw== To: Miguel Ojeda , Alex Gaynor , Wedson Almeida Filho , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Alice Ryhl From: y86-dev@protonmail.com Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, patches@lists.linux.dev, Benno Lossin , Alice Ryhl , Andreas Hindborg Subject: [PATCH v4 10/15] rust: init: add `stack_pin_init!` macro Message-ID: <20230331215053.585759-11-y86-dev@protonmail.com> Feedback-ID: 40624463:user:proton MIME-Version: 1.0 X-Spam-Status: No, score=-0.2 required=5.0 tests=DKIM_SIGNED,DKIM_VALID, DKIM_VALID_AU,DKIM_VALID_EF,FREEMAIL_FROM,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 X-getmail-retrieved-from-mailbox: =?utf-8?q?INBOX?= X-GMAIL-THRID: =?utf-8?q?1761922759205300636?= X-GMAIL-MSGID: =?utf-8?q?1761922759205300636?= From: Benno Lossin 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 Cc: Alice Ryhl Cc: Andreas Hindborg Cc: Gary Guo --- rust/kernel/init.rs | 146 +++++++++++++++++++++++++++++++-- rust/kernel/init/__internal.rs | 50 +++++++++++ 2 files changed, 190 insertions(+), 6 deletions(-) -- 2.39.2 diff --git a/rust/kernel/init.rs b/rust/kernel/init.rs index a507536f1724..5661f30bb0e4 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 two 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 [stack], an [`Arc`], +//! [`UniqueArc`], [`Box`] or any other smart pointer that implements [`InPlaceInit`]). //! //! To get an in-place constructor there are generally three options: //! - directly creating an in-place constructor using the [`pin_init!`] macro, @@ -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,138 @@ 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, new_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 = pin_init!(Foo { +/// a <- new_mutex!(42), +/// b: Bar { +/// x: 64, +/// }, +/// })); +/// let foo: Pin<&mut Foo> = foo; +/// pr_info!("a: {}", &*foo.a.lock()); +/// ``` +/// +/// # Syntax +/// +/// A normal `let` binding with optional type annotation. The expression is expected to implement +/// [`PinInit`]/[`Init`] with the error type [`Infallible`]. If you want to use a different error +/// type, then use [`stack_try_pin_init!`]. +#[macro_export] +macro_rules! stack_pin_init { + (let $var:ident $(: $t:ty)? = $val:expr) => { + let mut $var = ::core::pin::pin!($crate::init::__internal::StackInit$(::<$t>)?::uninit()); + let mut $var = { + let val = $val; + match $crate::init::__internal::StackInit::init($var, val) { + Ok(res) => res, + Err(x) => { + let x: ::core::convert::Infallible = 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::Mutex, 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> = pin_init!(Foo { +/// a <- new_mutex!(42), +/// b: Box::try_new(Bar { +/// x: 64, +/// })?, +/// })); +/// let foo = 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::Mutex, 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> =? 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 is expected to implement +/// [`PinInit`]/[`Init`]. This macro assigns a result to the given variable, adding a `?` after the +/// `=` will propagate this error. +#[macro_export] +macro_rules! stack_try_pin_init { + (let $var:ident $(: $t:ty)? = $val:expr) => { + let mut $var = ::core::pin::pin!($crate::init::__internal::StackInit$(::<$t>)?::uninit()); + let mut $var = { + let val = $val; + $crate::init::__internal::StackInit::init($var, val) + }; + }; + (let $var:ident $(: $t:ty)? =? $val:expr) => { + let mut $var = ::core::pin::pin!($crate::init::__internal::StackInit$(::<$t>)?::uninit()); + let mut $var = { + let val = $val; + $crate::init::__internal::StackInit::init($var, val)? + }; + }; +} + /// Construct an in-place, pinned initializer for `struct`s. /// /// This macro defaults the error to [`Infallible`]. If you need [`Error`], then use @@ -916,8 +1050,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::pin_init`] function of a -/// smart pointer like [`Arc`] on this. +/// be [`Box`], [`Arc`], [`UniqueArc`] or even the stack (see [`stack_pin_init!`]). Use the +/// [`InPlaceInit::pin_init`] function of a smart pointer like [`Arc`] on this. /// /// Also see the [module description](self). /// @@ -952,9 +1086,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::init`] 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 [`stack_pin_init!`]). Use the +/// [`InPlaceInit::init`] 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. /// /// Also see the [module description](self). /// diff --git a/rust/kernel/init/__internal.rs b/rust/kernel/init/__internal.rs index 4d13d0ef3b5e..5f753ff324b2 100644 --- a/rust/kernel/init/__internal.rs +++ b/rust/kernel/init/__internal.rs @@ -124,6 +124,56 @@ unsafe impl HasInitData for T { } } +/// Stack initializer helper type. Use [`stack_pin_init`] instead of this primitive. +/// +/// # Invariants +/// +/// If `self.1` is true, then `self.0` is initialized. +/// +/// [`stack_pin_init`]: kernel::stack_pin_init +pub struct StackInit(MaybeUninit, bool); + +impl Drop for StackInit { + #[inline] + fn drop(&mut self) { + if self.1 { + // SAFETY: As we are being dropped, we only call this once. And since `self.1 == true`, + // `self.0` has to be initialized. + unsafe { self.0.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(MaybeUninit::uninit(), false) + } + + /// Initializes the contents and returns the result. + #[inline] + pub fn init(self: Pin<&mut Self>, init: impl PinInit) -> Result, E> { + // SAFETY: We never move out of `this`. + let this = unsafe { Pin::into_inner_unchecked(self) }; + // The value is currently initialized, so it needs to be dropped before we can reuse + // the memory (this is a safety guarantee of `Pin`). + if this.1 { + // SAFETY: `this.1` is true and we set it to false after this. + unsafe { this.0.assume_init_drop() }; + this.1 = false; + } + // SAFETY: The memory slot is valid and this type ensures that it will stay pinned. + unsafe { init.__pinned_init(this.0.as_mut_ptr())? }; + this.1 = true; + // SAFETY: The slot is now pinned, since we will never give access to `&mut T`. + Ok(unsafe { Pin::new_unchecked(this.0.assume_init_mut()) }) + } +} + /// When a value of this type is dropped, it drops a `T`. /// /// Can be forgotton to prevent the drop.