From patchwork Wed Mar 29 22:33:18 2023 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: y86-dev X-Patchwork-Id: 76840 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:a59:b0ea:0:b0:3b6:4342:cba0 with SMTP id b10csp729505vqo; Wed, 29 Mar 2023 15:36:16 -0700 (PDT) X-Google-Smtp-Source: AKy350b8yGjf7it/s6HGbEWEeBGhuhc72R9aEiMtexxShNIj6mQPJpxZTQ/O3DLGwamnXDjfrK6h X-Received: by 2002:a17:902:f90e:b0:1a1:d949:a54a with SMTP id kw14-20020a170902f90e00b001a1d949a54amr16089819plb.58.1680129375756; Wed, 29 Mar 2023 15:36:15 -0700 (PDT) ARC-Seal: i=1; a=rsa-sha256; t=1680129375; cv=none; d=google.com; s=arc-20160816; b=eI8K6TIz61qNqFBj6iETc1ssDUustPRhesgqe1DnHCpztzF8MgDO1XneLkIqHpJxPf 7LdQnGEccFvMUcZ86/Zo/o3d6vcpq1Wo0cpdLUxjoDuxlZCwDaPl+JFxu0bWv7j+4Hvd i6nSCbJLAYUjZ10WxRDs457Ti/7BT048YnWAUpl/jRKsvttGmKOMv/M5ORxzIcYHCWUd hPzX44LBVjuCiLfWT7/VF7wUSs2g0I6rmIUqqJ+ul4mQXrmUDL0ZachPgT+737XQ8i+o lPONPqzvd0QmA0corPwvO7Uyk/HgwaCDP3i3YLXtnXU8nMePEAXgJDTgqJo/q5WACzCu QMNA== 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=+Jgo8YMLidWi9F/tttnsA/dAW+fcatX0DCsuPc2iOP8=; b=No61cI1qvWHZHAsK+CV2Ix/bSPP4Kgk7mno4fbtyN15mGkHT0xwUYuw5ySMCGAFNjg GouYfQY1hBTApCCyWViDqLUxrBnbAGQJIEdtHIie0KuL3Z+uL2Yae7ZaTBeeyKLz1V9y jpg2qrV73zdPk9G0yDMgaFgp/+CmC5bZasR7lumh/N8vqyjSifK79drNOO4bJkWYffQd LyrjYkhKgdo7V/L5nETOG5sk9h5doqZiAxJ+KjHGuFutl79ryuivYg5UYfOrn5U5BW1B DoB3OHYbE27OsRgDN0WgTqTL9V6gFJknN38ff8nefuVpQSTySykiQk4t49HlnjY9ctkY 7UMA== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@protonmail.com header.s=protonmail3 header.b=WxNvUDrX; 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 i9-20020a170902c94900b001a1e4051da5si21797329pla.498.2023.03.29.15.36.01; Wed, 29 Mar 2023 15:36:15 -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=WxNvUDrX; 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 S231146AbjC2Wel (ORCPT + 99 others); Wed, 29 Mar 2023 18:34:41 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:50054 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S230414AbjC2Wec (ORCPT ); Wed, 29 Mar 2023 18:34:32 -0400 Received: from mail-0301.mail-europe.com (mail-0301.mail-europe.com [188.165.51.139]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 19C5165A6 for ; Wed, 29 Mar 2023 15:33:58 -0700 (PDT) Date: Wed, 29 Mar 2023 22:33:18 +0000 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=protonmail.com; s=protonmail3; t=1680129209; x=1680388409; bh=+Jgo8YMLidWi9F/tttnsA/dAW+fcatX0DCsuPc2iOP8=; 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=WxNvUDrX3yHHzIhQch5hrDo1Gpugmjzl3wEk73FYRTDYV5m+BvQjawfkqaKrHbaNf Iu+GcCh5ef1qF0WveOxPzTGSoSdhb+ah8UNPXjB38Ig6/pB2vPdEkMpFk1b+DFwS9F Cw6y3Sozfy9u905yezyC2HLQGmBBjIc1BBIWRRpxHOfp408PxCFiE1KuUsZKrWVnYj bYBcAAMT+8gMkvleDq0/0XVXiAuhhDEO84x5mCJktsephHh+/pQWLOkNxtnV/4l+yL AvqSQIzZ6pbEfvHYQ8zFTCx3UUy7Xq6B6A+lbu289IavnjwZ3HH0anVWnRsUa2pLIA SW43lBEoskCDQ== 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 Subject: [PATCH v3 06/13] rust: init/sync: add `InPlaceInit` trait to pin-initialize smart pointers Message-ID: <20230329223239.138757-7-y86-dev@protonmail.com> In-Reply-To: <20230329223239.138757-1-y86-dev@protonmail.com> References: <20230329223239.138757-1-y86-dev@protonmail.com> Feedback-ID: 40624463:user:proton MIME-Version: 1.0 X-Spam-Status: No, score=-0.9 required=5.0 tests=DKIM_SIGNED,DKIM_VALID, DKIM_VALID_AU,DKIM_VALID_EF,FREEMAIL_FROM,RCVD_IN_DNSWL_LOW, SPF_HELO_NONE,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?1761743339986957709?= X-GMAIL-MSGID: =?utf-8?q?1761743339986957709?= From: Benno Lossin The `InPlaceInit` trait that provides two functions, for initializing using `PinInit` and `Init`. It is implemented by `Arc`, `UniqueArc` and `Box`. Signed-off-by: Benno Lossin Reviewed-by: Andreas Hindborg Reviewed-by: Alice Ryhl --- rust/kernel/init.rs | 97 +++++++++++++++++++++++++++++++++++------ rust/kernel/sync/arc.rs | 25 ++++++++++- 2 files changed, 108 insertions(+), 14 deletions(-) -- 2.39.2 diff --git a/rust/kernel/init.rs b/rust/kernel/init.rs index 85e8d5f41b60..3d89c7e3bdb5 100644 --- a/rust/kernel/init.rs +++ b/rust/kernel/init.rs @@ -114,10 +114,13 @@ //! [`impl Init`]: Init //! [`Opaque`]: kernel::types::Opaque //! [`pin_data`]: ::macros::pin_data -//! [`UniqueArc`]: kernel::sync::UniqueArc +use crate::{ + error::{self, Error}, + sync::UniqueArc, +}; use alloc::boxed::Box; -use core::{cell::Cell, convert::Infallible, marker::PhantomData, mem::MaybeUninit, ptr}; +use core::{cell::Cell, convert::Infallible, marker::PhantomData, mem::MaybeUninit, pin::Pin, ptr}; #[doc(hidden)] pub mod __internal; @@ -309,7 +312,6 @@ pub mod macros; /// /// [`try_pin_init!`]: kernel::try_pin_init /// [`NonNull`]: core::ptr::NonNull -/// [`Error`]: kernel::error::Error // For a detailed example of how this macro works, see the module documentation of the hidden // module `__internal` inside of `init/__internal.rs`. #[macro_export] @@ -366,8 +368,6 @@ macro_rules! pin_init { /// } /// } /// ``` -/// -/// [`Error`]: kernel::error::Error // For a detailed example of how this macro works, see the module documentation of the hidden // module `__internal` inside of `init/__internal.rs`. #[macro_export] @@ -589,8 +589,6 @@ macro_rules! try_pin_init { /// /// This initializer is for initializing data in-place that might later be moved. If you want to /// pin-initialize, use [`pin_init!`]. -/// -/// [`Error`]: kernel::error::Error // For a detailed example of how this macro works, see the module documentation of the hidden // module `__internal` inside of `init/__internal.rs`. #[macro_export] @@ -641,8 +639,6 @@ macro_rules! init { /// } /// } /// ``` -/// -/// [`Error`]: kernel::error::Error // For a detailed example of how this macro works, see the module documentation of the hidden // module `__internal` inside of `init/__internal.rs`. #[macro_export] @@ -848,7 +844,8 @@ macro_rules! try_init { /// A pinned 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`]. +/// be [`Box`], [`Arc`], [`UniqueArc`]. Use the [`InPlaceInit::pin_init`] function of a +/// smart pointer like [`Arc`] on this. /// /// Also see the [module description](self). /// @@ -867,7 +864,6 @@ macro_rules! try_init { /// /// [`Arc`]: crate::sync::Arc /// [`Arc::pin_init`]: crate::sync::Arc::pin_init -/// [`UniqueArc`]: kernel::sync::UniqueArc #[must_use = "An initializer must be used in order to create its value."] pub unsafe trait PinInit: Sized { /// Initializes `slot`. @@ -884,7 +880,8 @@ 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`]. Because [`PinInit`] is a super trait, you 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. /// /// Also see the [module description](self). @@ -909,7 +906,6 @@ pub unsafe trait PinInit: Sized { /// move the pointee after initialization. /// /// [`Arc`]: crate::sync::Arc -/// [`UniqueArc`]: kernel::sync::UniqueArc #[must_use = "An initializer must be used in order to create its value."] pub unsafe trait Init: PinInit { /// Initializes `slot`. @@ -1014,3 +1010,78 @@ unsafe impl Init for T { Ok(()) } } + +/// Smart pointer that can initialize memory in-place. +pub trait InPlaceInit: Sized { + /// Use the given initializer to in-place initialize a `T`. + /// + /// If `T: !Unpin` it will not be able to move afterwards. + fn pin_init(init: impl PinInit) -> error::Result> + where + Error: From; + + /// Use the given initializer to in-place initialize a `T`. + fn init(init: impl Init) -> error::Result + where + Error: From; +} + +impl InPlaceInit for Box { + #[inline] + fn pin_init(init: impl PinInit) -> error::Result> + where + Error: From, + { + let mut this = Box::try_new_uninit()?; + let slot = this.as_mut_ptr(); + // SAFETY: When init errors/panics, slot will get deallocated but not dropped, + // slot is valid and will not be moved because of the `Pin::new_unchecked` + unsafe { init.__pinned_init(slot)? }; + // SAFETY: All fields have been initialized. + Ok(unsafe { Pin::new_unchecked(this.assume_init()) }) + } + + #[inline] + fn init(init: impl Init) -> error::Result + where + Error: From, + { + let mut this = Box::try_new_uninit()?; + let slot = this.as_mut_ptr(); + // SAFETY: When init errors/panics, slot will get deallocated but not dropped, + // slot is valid + unsafe { init.__init(slot)? }; + // SAFETY: All fields have been initialized. + Ok(unsafe { this.assume_init() }) + } +} + +impl InPlaceInit for UniqueArc { + #[inline] + fn pin_init(init: impl PinInit) -> error::Result> + where + Error: From, + { + let mut this = UniqueArc::try_new_uninit()?; + let slot = this.as_mut_ptr(); + // SAFETY: When init errors/panics, slot will get deallocated but not dropped, + // slot is valid and will not be moved because of the `Pin::new_unchecked`. + unsafe { init.__pinned_init(slot)? }; + // SAFETY: All fields have been initialized. + Ok(unsafe { Pin::new_unchecked(this.assume_init()) }) + } + + #[inline] + fn init(init: impl Init) -> error::Result + where + Error: From, + { + let mut this = UniqueArc::try_new_uninit()?; + let slot = this.as_mut_ptr(); + // SAFETY: When init errors/panics, slot will get deallocated but not dropped, + // slot is valid. + unsafe { init.__init(slot)? }; + // SAFETY: All fields have been initialized. + Ok(unsafe { this.assume_init() }) + } +} diff --git a/rust/kernel/sync/arc.rs b/rust/kernel/sync/arc.rs index 16ec174637b2..77a3833cc265 100644 --- a/rust/kernel/sync/arc.rs +++ b/rust/kernel/sync/arc.rs @@ -17,7 +17,8 @@ use crate::{ bindings, - error::Result, + error::{Error, Result}, + init::{InPlaceInit, Init, PinInit}, types::{ForeignOwnable, Opaque}, }; use alloc::boxed::Box; @@ -163,6 +164,28 @@ impl Arc { // `Arc` object. Ok(unsafe { Self::from_inner(Box::leak(inner).into()) }) } + + /// Use the given initializer to in-place initialize a `T`. + /// + /// If `T: !Unpin` it will not be able to move afterwards. + #[inline] + pub fn pin_init(init: impl PinInit) -> Result + where + Error: From, + { + UniqueArc::pin_init(init).map(|u| u.into()) + } + + /// Use the given initializer to in-place initialize a `T`. + /// + /// This is equivalent to [`pin_init`], since an [`Arc`] is always pinned. + #[inline] + pub fn init(init: impl Init) -> Result + where + Error: From, + { + UniqueArc::init(init).map(|u| u.into()) + } } impl Arc {