Received: by 2002:a05:6358:11c7:b0:104:8066:f915 with SMTP id i7csp1280857rwl; Wed, 29 Mar 2023 15:35:47 -0700 (PDT) X-Google-Smtp-Source: AK7set9zst6DKydfWtUds76cR6kxl/ZIHhXpILLI3I3vM8+ED0NBLKohBANek9FoqHnHots9gAtr X-Received: by 2002:a05:6a20:baa5:b0:dc:e183:26cc with SMTP id fb37-20020a056a20baa500b000dce18326ccmr19038125pzb.23.1680129347366; Wed, 29 Mar 2023 15:35:47 -0700 (PDT) ARC-Seal: i=1; a=rsa-sha256; t=1680129347; cv=none; d=google.com; s=arc-20160816; b=wZc6vqh09oH0rIgW8fXgoocUykxnP4DsWETL5Ig5vK2DIEMZOnmwZ8fAVim1Z5HMeq i0N7JALQSQl6YQ2t/11QFbLT5asAil/NnUgfmdnrrcXhS3uxFlJqnNswoZlC17EHw6lc sYbYtMvyRo2UMM+tE4ZsGeL3VreytOD/Q6TtpcSpAGHINKp+pbI3d/toGoHcYmcuJY4N WFX4jONE9Bv4WWFKlvcfFMjH7dYiJulr7AcovNZB+sQ2VEvv8IrZuDW8eIqM+THK20s2 BrYkJXV+8fYMvM8QxMI2+3uqRvPFEuCLqJ9MG/SxnahddNwzxY/dD9Na/EONh0FPoIjm eVxw== 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 Return-Path: Received: from out1.vger.email (out1.vger.email. [2620:137:e000::1:20]) by mx.google.com with ESMTP id y9-20020a62ce09000000b005a72b5eaf96si32803576pfg.152.2023.03.29.15.35.33; Wed, 29 Mar 2023 15:35:47 -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 S231140AbjC2Wek (ORCPT + 99 others); Wed, 29 Mar 2023 18:34:40 -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 Content-Type: text/plain; charset=utf-8 Content-Transfer-Encoding: quoted-printable 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 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 --- rust/kernel/init.rs | 97 +++++++++++++++++++++++++++++++++++------ rust/kernel/sync/arc.rs | 25 ++++++++++- 2 files changed, 108 insertions(+), 14 deletions(-) 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::Mayb= eUninit, ptr}; +use core::{cell::Cell, convert::Infallible, marker::PhantomData, mem::Mayb= eUninit, 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 document= ation 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 document= ation 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 document= ation 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 document= ation 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::pi= n_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 =3D "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::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. /// /// 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 =3D "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 =3D Box::try_new_uninit()?; + let slot =3D 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_un= checked` + 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 =3D Box::try_new_uninit()?; + let slot =3D 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 =3D UniqueArc::try_new_uninit()?; + let slot =3D 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_un= checked`. + 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 =3D UniqueArc::try_new_uninit()?; + let slot =3D 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 pin= ned. + #[inline] + pub fn init(init: impl Init) -> Result + where + Error: From, + { + UniqueArc::init(init).map(|u| u.into()) + } } impl Arc { -- 2.39.2