Message ID | 20230329223239.138757-13-y86-dev@protonmail.com |
---|---|
State | New |
Headers |
Return-Path: <linux-kernel-owner@vger.kernel.org> Delivered-To: ouuuleilei@gmail.com Received: by 2002:a59:b0ea:0:b0:3b6:4342:cba0 with SMTP id b10csp742521vqo; Wed, 29 Mar 2023 16:07:02 -0700 (PDT) X-Google-Smtp-Source: AKy350YWBuA/siuXFqLzCGbj+Co+ndbHVniGqvr43USOveTOy6ICD71QUjZrVz9Hs73tt2sPKaWz X-Received: by 2002:a17:906:3505:b0:908:6a98:5b48 with SMTP id r5-20020a170906350500b009086a985b48mr18245386eja.40.1680131221976; Wed, 29 Mar 2023 16:07:01 -0700 (PDT) ARC-Seal: i=1; a=rsa-sha256; t=1680131221; cv=none; d=google.com; s=arc-20160816; b=0tyVr3LFOSeCvj673rHfeFt0Nfg0UwP8f7tOpB+ywvhYn9UqsXUaxsuzAasHwFRkDL O+cjcM5Y4AkXPaT6b9ZtzRO25uqN/plV/a4TXr7x+s5sS2wjlgseiCePah6aYfoGRXsg tl1ukguIGqxKMEgqAHv6VSmxtJWgDPQANKGmPk5AvqljhMcJDB2gQ1bOvvmUA/BTbtmL QcfWKkCL3779OicIK2G6pTSS0BKB/4RIGppVM5dGLAbkYPAiqpnBlbU5ln0FKB3BtosE vojQN9e/qRIaYTD1ogqlLWZhEGucZmz46graTUeM3+stYZuqXLzq+c0UVooSeCG2i6r1 qxxg== 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=sxLceGSRcRRyUDLrAQ3TsPyF0muTqsPNCkcHAqeAS3Y=; b=K6aKTkaZwHdnJUesDSTCRASHW2oc8NDsgXuXeD7mvy1BwyxMOHqTrj3lu897vdDjKk foDJnYlh2LI5gqhEC2bN8lIqZfWo2FTJIFvHbhSaUA2p8GEn1RSv+kdEGkjuRXTRa0hM og8GWoxlFoapdZL+WYnafBEuYUaZuVwaRk0Ii9c9YF/asEYPxadobzff5hm6kpYnWbVS V/pH//fuH4FO1S5UMMnd0eoIL1GeW1Rc1iWZFErmwcgsMu3jOucthQd0qeRH48ODeiCc QfYd/II/hfVTQD+AKgyTG5w8cBuddnb1lwA9vikGKgAJCGNt9/bdakjazxeGxK2Id0Ib UJkg== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@protonmail.com header.s=protonmail3 header.b=Zwb1MUx0; 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 x13-20020aa7d6cd000000b004bd1a7dba86si33118980edr.410.2023.03.29.16.06.36; Wed, 29 Mar 2023 16:07:01 -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=Zwb1MUx0; 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 S230394AbjC2We7 (ORCPT <rfc822;rua109.linux@gmail.com> + 99 others); Wed, 29 Mar 2023 18:34:59 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:50724 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S229955AbjC2Wed (ORCPT <rfc822;linux-kernel@vger.kernel.org>); Wed, 29 Mar 2023 18:34:33 -0400 Received: from mail-4316.protonmail.ch (mail-4316.protonmail.ch [185.70.43.16]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 69BC36A47; Wed, 29 Mar 2023 15:34:01 -0700 (PDT) Date: Wed, 29 Mar 2023 22:33:49 +0000 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=protonmail.com; s=protonmail3; t=1680129238; x=1680388438; bh=sxLceGSRcRRyUDLrAQ3TsPyF0muTqsPNCkcHAqeAS3Y=; h=Date:To:From:Cc:Subject:Message-ID:Feedback-ID:From:To:Cc:Date: Subject:Reply-To:Feedback-ID:Message-ID:BIMI-Selector; b=Zwb1MUx0yFoVE9sf9Mb1tWUXfmh2qVpyjWSLpofWZdfMidwMRgbwK6j4js7H30ZOn blYDhGfDJAyc8p99nIdH+KopD/vrdi+3JUmIDevsR2jEkgvPTq1wDmTlhoEAL1gPgh MQipP6aGvkNdpzcpVvTWmfiCN57Bemt5dm/ayMF7HV5c29RF+ldIsAgWYuQJQSHcO+ QW0HjHotWaWJ3MbboE6J2l3a1dPFzqIiOhfjlCOrJlf9kILO1YsXSVuBIND185TWLU n5qo/ZQzDtNp0RouDoSeKI0FvS82yN0SfU5MLppM08yhy3jsk4aEyrPOjdJojGsnim vTlaZqNbEYA5g== To: Miguel Ojeda <ojeda@kernel.org>, Alex Gaynor <alex.gaynor@gmail.com>, Wedson Almeida Filho <wedsonaf@gmail.com>, Boqun Feng <boqun.feng@gmail.com>, Gary Guo <gary@garyguo.net>, =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= <bjorn3_gh@protonmail.com>, Alice Ryhl <alice@ryhl.io> From: y86-dev@protonmail.com Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, patches@lists.linux.dev Subject: [PATCH v3 12/13] rust: sync: reduce stack usage of `UniqueArc::try_new_uninit` Message-ID: <20230329223239.138757-13-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: <linux-kernel.vger.kernel.org> X-Mailing-List: linux-kernel@vger.kernel.org X-getmail-retrieved-from-mailbox: =?utf-8?q?INBOX?= X-GMAIL-THRID: =?utf-8?q?1761745275948603791?= X-GMAIL-MSGID: =?utf-8?q?1761745275948603791?= |
Series |
Rust pin-init API for pinned initialization of structs
|
|
Commit Message
y86-dev
March 29, 2023, 10:33 p.m. UTC
From: Benno Lossin <y86-dev@protonmail.com> `UniqueArc::try_new_uninit` calls `Arc::try_new(MaybeUninit::uninit())`. This results in the uninitialized memory being placed on the stack, which may be arbitrarily large due to the generic `T` and thus could cause a stack overflow for large types. Change the implementation to use the pin-init API which enables in-place initialization. In particular it avoids having to first construct and then move the uninitialized memory from the stack into the final location. Signed-off-by: Benno Lossin <y86-dev@protonmail.com> --- rust/kernel/lib.rs | 1 - rust/kernel/sync/arc.rs | 14 ++++++++++++-- 2 files changed, 12 insertions(+), 3 deletions(-) -- 2.39.2
Comments
On Wed, 29 Mar 2023 22:33:49 +0000 y86-dev@protonmail.com wrote: > From: Benno Lossin <y86-dev@protonmail.com> > > `UniqueArc::try_new_uninit` calls `Arc::try_new(MaybeUninit::uninit())`. > This results in the uninitialized memory being placed on the stack, > which may be arbitrarily large due to the generic `T` and thus could > cause a stack overflow for large types. > > Change the implementation to use the pin-init API which enables in-place > initialization. In particular it avoids having to first construct and > then move the uninitialized memory from the stack into the final location. > > Signed-off-by: Benno Lossin <y86-dev@protonmail.com> Reviewed-by: Gary Guo <gary@garyguo.net> > --- > rust/kernel/lib.rs | 1 - > rust/kernel/sync/arc.rs | 14 ++++++++++++-- > 2 files changed, 12 insertions(+), 3 deletions(-) > > diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs > index 3e2777d26ff5..d9df77132fa2 100644 > --- a/rust/kernel/lib.rs > +++ b/rust/kernel/lib.rs > @@ -27,7 +27,6 @@ > #[cfg(not(CONFIG_RUST))] > compile_error!("Missing kernel configuration for conditional compilation"); > > -#[allow(unused_extern_crates)] > // Allow proc-macros to refer to `::kernel` inside the `kernel` crate (this crate). > extern crate self as kernel; > > diff --git a/rust/kernel/sync/arc.rs b/rust/kernel/sync/arc.rs > index 77a3833cc265..4ed6329a5e5f 100644 > --- a/rust/kernel/sync/arc.rs > +++ b/rust/kernel/sync/arc.rs > @@ -18,6 +18,7 @@ > use crate::{ > bindings, > error::{Error, Result}, > + init, > init::{InPlaceInit, Init, PinInit}, > types::{ForeignOwnable, Opaque}, > }; > @@ -29,6 +30,7 @@ use core::{ > pin::Pin, > ptr::NonNull, > }; > +use macros::pin_data; > > /// A reference-counted pointer to an instance of `T`. > /// > @@ -121,6 +123,7 @@ pub struct Arc<T: ?Sized> { > _p: PhantomData<ArcInner<T>>, > } > > +#[pin_data] > #[repr(C)] > struct ArcInner<T: ?Sized> { > refcount: Opaque<bindings::refcount_t>, > @@ -501,9 +504,16 @@ impl<T> UniqueArc<T> { > > /// Tries to allocate a new [`UniqueArc`] instance whose contents are not initialised yet. > pub fn try_new_uninit() -> Result<UniqueArc<MaybeUninit<T>>> { > - Ok(UniqueArc::<MaybeUninit<T>> { > + // INVARIANT: The refcount is initialised to a non-zero value. > + let inner = Box::init(init!(ArcInner { > + // SAFETY: There are no safety requirements for this FFI call. > + refcount: Opaque::new(unsafe { bindings::REFCOUNT_INIT(1) }), > + data <- init::uninit(), > + }))?; > + Ok(UniqueArc { > // INVARIANT: The newly-created object has a ref-count of 1. > - inner: Arc::try_new(MaybeUninit::uninit())?, > + // SAFETY: The pointer from the `Box` is valid. > + inner: unsafe { Arc::from_inner(Box::leak(inner).into()) }, > }) > } > } > -- > 2.39.2 > >
From: y86-dev@protonmail.com > Sent: 29 March 2023 23:34 > > `UniqueArc::try_new_uninit` calls `Arc::try_new(MaybeUninit::uninit())`. > This results in the uninitialized memory being placed on the stack, > which may be arbitrarily large due to the generic `T` and thus could > cause a stack overflow for large types. Does that mean rust is using (the equivalent of) alloca() ? That is banned for C code in the kernel for any sizes. David - Registered Address Lakeside, Bramley Road, Mount Farm, Milton Keynes, MK1 1PT, UK Registration No: 1397386 (Wales)
On 30.03.23 16:58, David Laight wrote: > From: y86-dev@protonmail.com >> Sent: 29 March 2023 23:34 >> >> `UniqueArc::try_new_uninit` calls `Arc::try_new(MaybeUninit::uninit())`. >> This results in the uninitialized memory being placed on the stack, >> which may be arbitrarily large due to the generic `T` and thus could >> cause a stack overflow for large types. > > Does that mean rust is using (the equivalent of) alloca() ? No, the compiler knows the size of `T` statically (this is a requirement for calling `MaybeUninit::uninit()`). It would simply reserve stack space for a stack variable (like the C compiler would also do) and since the type is generic and user-specified, it could be larger than the stack size. The problem is that the Rust compiler does not optimize the stack variable away. This fix avoids creating a stack variable in the first place. -- Cheers, Benno > > That is banned for C code in the kernel for any sizes. > > David > > - > Registered Address Lakeside, Bramley Road, Mount Farm, Milton Keynes, MK1 1PT, UK > Registration No: 1397386 (Wales)
On 3/30/23 00:33, y86-dev@protonmail.com wrote: > From: Benno Lossin <y86-dev@protonmail.com> > > `UniqueArc::try_new_uninit` calls `Arc::try_new(MaybeUninit::uninit())`. > This results in the uninitialized memory being placed on the stack, > which may be arbitrarily large due to the generic `T` and thus could > cause a stack overflow for large types. > > Change the implementation to use the pin-init API which enables in-place > initialization. In particular it avoids having to first construct and > then move the uninitialized memory from the stack into the final location. > > Signed-off-by: Benno Lossin <y86-dev@protonmail.com> Reviewed-by: Alice Ryhl <aliceryhl@google.com>
y86-dev@protonmail.com writes: > From: Benno Lossin <y86-dev@protonmail.com> > > `UniqueArc::try_new_uninit` calls `Arc::try_new(MaybeUninit::uninit())`. > This results in the uninitialized memory being placed on the stack, > which may be arbitrarily large due to the generic `T` and thus could > cause a stack overflow for large types. > > Change the implementation to use the pin-init API which enables in-place > initialization. In particular it avoids having to first construct and > then move the uninitialized memory from the stack into the final location. > > Signed-off-by: Benno Lossin <y86-dev@protonmail.com> > --- Reviewed-by Andreas Hindborg <a.hindborg@samsung.com> > rust/kernel/lib.rs | 1 - > rust/kernel/sync/arc.rs | 14 ++++++++++++-- > 2 files changed, 12 insertions(+), 3 deletions(-) > > diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs > index 3e2777d26ff5..d9df77132fa2 100644 > --- a/rust/kernel/lib.rs > +++ b/rust/kernel/lib.rs > @@ -27,7 +27,6 @@ > #[cfg(not(CONFIG_RUST))] > compile_error!("Missing kernel configuration for conditional compilation"); > > -#[allow(unused_extern_crates)] > // Allow proc-macros to refer to `::kernel` inside the `kernel` crate (this crate). > extern crate self as kernel; > > diff --git a/rust/kernel/sync/arc.rs b/rust/kernel/sync/arc.rs > index 77a3833cc265..4ed6329a5e5f 100644 > --- a/rust/kernel/sync/arc.rs > +++ b/rust/kernel/sync/arc.rs > @@ -18,6 +18,7 @@ > use crate::{ > bindings, > error::{Error, Result}, > + init, > init::{InPlaceInit, Init, PinInit}, > types::{ForeignOwnable, Opaque}, > }; > @@ -29,6 +30,7 @@ use core::{ > pin::Pin, > ptr::NonNull, > }; > +use macros::pin_data; > > /// A reference-counted pointer to an instance of `T`. > /// > @@ -121,6 +123,7 @@ pub struct Arc<T: ?Sized> { > _p: PhantomData<ArcInner<T>>, > } > > +#[pin_data] > #[repr(C)] > struct ArcInner<T: ?Sized> { > refcount: Opaque<bindings::refcount_t>, > @@ -501,9 +504,16 @@ impl<T> UniqueArc<T> { > > /// Tries to allocate a new [`UniqueArc`] instance whose contents are not initialised yet. > pub fn try_new_uninit() -> Result<UniqueArc<MaybeUninit<T>>> { > - Ok(UniqueArc::<MaybeUninit<T>> { > + // INVARIANT: The refcount is initialised to a non-zero value. > + let inner = Box::init(init!(ArcInner { > + // SAFETY: There are no safety requirements for this FFI call. > + refcount: Opaque::new(unsafe { bindings::REFCOUNT_INIT(1) }), > + data <- init::uninit(), > + }))?; > + Ok(UniqueArc { > // INVARIANT: The newly-created object has a ref-count of 1. > - inner: Arc::try_new(MaybeUninit::uninit())?, > + // SAFETY: The pointer from the `Box` is valid. > + inner: unsafe { Arc::from_inner(Box::leak(inner).into()) }, > }) > } > }
diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index 3e2777d26ff5..d9df77132fa2 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -27,7 +27,6 @@ #[cfg(not(CONFIG_RUST))] compile_error!("Missing kernel configuration for conditional compilation"); -#[allow(unused_extern_crates)] // Allow proc-macros to refer to `::kernel` inside the `kernel` crate (this crate). extern crate self as kernel; diff --git a/rust/kernel/sync/arc.rs b/rust/kernel/sync/arc.rs index 77a3833cc265..4ed6329a5e5f 100644 --- a/rust/kernel/sync/arc.rs +++ b/rust/kernel/sync/arc.rs @@ -18,6 +18,7 @@ use crate::{ bindings, error::{Error, Result}, + init, init::{InPlaceInit, Init, PinInit}, types::{ForeignOwnable, Opaque}, }; @@ -29,6 +30,7 @@ use core::{ pin::Pin, ptr::NonNull, }; +use macros::pin_data; /// A reference-counted pointer to an instance of `T`. /// @@ -121,6 +123,7 @@ pub struct Arc<T: ?Sized> { _p: PhantomData<ArcInner<T>>, } +#[pin_data] #[repr(C)] struct ArcInner<T: ?Sized> { refcount: Opaque<bindings::refcount_t>, @@ -501,9 +504,16 @@ impl<T> UniqueArc<T> { /// Tries to allocate a new [`UniqueArc`] instance whose contents are not initialised yet. pub fn try_new_uninit() -> Result<UniqueArc<MaybeUninit<T>>> { - Ok(UniqueArc::<MaybeUninit<T>> { + // INVARIANT: The refcount is initialised to a non-zero value. + let inner = Box::init(init!(ArcInner { + // SAFETY: There are no safety requirements for this FFI call. + refcount: Opaque::new(unsafe { bindings::REFCOUNT_INIT(1) }), + data <- init::uninit(), + }))?; + Ok(UniqueArc { // INVARIANT: The newly-created object has a ref-count of 1. - inner: Arc::try_new(MaybeUninit::uninit())?, + // SAFETY: The pointer from the `Box` is valid. + inner: unsafe { Arc::from_inner(Box::leak(inner).into()) }, }) } }