Message ID | 20221228060346.352362-4-wedsonaf@gmail.com |
---|---|
State | New |
Headers |
Return-Path: <linux-kernel-owner@vger.kernel.org> Delivered-To: ouuuleilei@gmail.com Received: by 2002:a5d:4e01:0:0:0:0:0 with SMTP id p1csp1738539wrt; Tue, 27 Dec 2022 22:05:46 -0800 (PST) X-Google-Smtp-Source: AMrXdXvSI6MI+4T6D+nZxFIfps027bYJ0pyJy3fp9XAv2cAksEWK3TXDt6cIRiIPxK2qOlDks58I X-Received: by 2002:a17:90b:485:b0:223:ffd0:b2a1 with SMTP id bh5-20020a17090b048500b00223ffd0b2a1mr27532378pjb.48.1672207545997; Tue, 27 Dec 2022 22:05:45 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1672207545; cv=none; d=google.com; s=arc-20160816; b=kkaghssERIXf0VcY8Fo3dnyCdJhLWp6yxNWf4iVEMSc9oG+RF7QmlUL9YpFrm4G0ol vPc8DAyTyaJFzFgu1olAu9LxyRQdmeLQXKmFRFCSFNeayZ4cqYzxSzhrM9/Nkt0nSU4s VrGHw79eRR2pNzV6AT5Q2RF5dHYBC/0D/78V4t+2PrCUr5icVuHsgmJfogSgWCfx030Q mp4nUp5BG1eMh+f1Yw4phXKyHJ1YGjGDxUheL9YhjAV5t41vCp2PzwunrSOlokkLVrOZ zQ+8R4fjYfZK6bn7GrdOx/pjbNF/liXpxFKtae03kgo+NTUWcDpxcj9LmLG66pj5/UjY NEtw== 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 :references:in-reply-to:message-id:date:subject:cc:to:from :dkim-signature; bh=NYJ20jftMQ92CUxnJjaaHKdOk3jkOftLaji4+9En0dc=; b=q+D8R7MJHY82m7Zp3m9QSiykhgG0/9T/9drbPJhDv6nOjL2QCpasj7QsJO5A0ZQsp0 P4cX3YrwV14Dam8tK5x5v9bc/BKmYsTOc2VaSBWMaoC5+Vcjw6tvS4NQF48KnyP9GDqM TpYxGx/KqkQn9M15s5d0RLd0IrL/ekBOlrtGoiFyjKyfGj4Q4ThXw00b/o3V5xbZ/2LV 04/OyvMxz2qmI6q5UheT9ZeuXHlEsRX/1IcueAOCQ2t9QfNSbR9uAAeB5P7Tg0gheEmY MXr730tfeUYrJh6il13UoCxl1sTlsOG4w1vdM/sintPKvhf3l4bh15a1BBeP/SS32NnE jwQA== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@gmail.com header.s=20210112 header.b=igz9ApMN; 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=NONE sp=QUARANTINE dis=NONE) header.from=gmail.com Received: from out1.vger.email (out1.vger.email. [2620:137:e000::1:20]) by mx.google.com with ESMTP id on16-20020a17090b1d1000b00225b427da47si18445539pjb.51.2022.12.27.22.05.34; Tue, 27 Dec 2022 22:05:45 -0800 (PST) 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=@gmail.com header.s=20210112 header.b=igz9ApMN; 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=NONE sp=QUARANTINE dis=NONE) header.from=gmail.com Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S230136AbiL1GE6 (ORCPT <rfc822;eddaouddi.ayoub@gmail.com> + 99 others); Wed, 28 Dec 2022 01:04:58 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:59046 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S229583AbiL1GEk (ORCPT <rfc822;linux-kernel@vger.kernel.org>); Wed, 28 Dec 2022 01:04:40 -0500 Received: from mail-wr1-x42a.google.com (mail-wr1-x42a.google.com [IPv6:2a00:1450:4864:20::42a]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 73CBADFAE; Tue, 27 Dec 2022 22:04:39 -0800 (PST) Received: by mail-wr1-x42a.google.com with SMTP id n3so13326896wrc.5; Tue, 27 Dec 2022 22:04:39 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20210112; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:from:to:cc:subject:date :message-id:reply-to; bh=NYJ20jftMQ92CUxnJjaaHKdOk3jkOftLaji4+9En0dc=; b=igz9ApMN93MMMvir8cEZVLhAlEwrT5qCIUt8GTeIg9hE1k033dQeVJAxv9ZNQC/TH4 mSJAMfWRk/P9OLtuX+1Xzbu0cA9hRzElS+i3j2cKO6fbY9xrfflj5Rmno/aV/LRQCak5 QLAw9IWaJ4lRtxWb1kKH/CQ+sJA7yJerLb8ueS3HajQYmSbeHObV9r+oiVt0tflpvPdy /A9LXfLy5OqkMF6JzMfRU8uL1yIFStcEziBi6wGqQl3DPpZhOXLVtDCIP8unUXpxCGOq uDwEUjf/jV1O4xC5JKbHoPFHjVEz/osPp5nWrWohUBBjLKoZDyDeFALPR/Jsvnby3tTH 5u9A== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20210112; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=NYJ20jftMQ92CUxnJjaaHKdOk3jkOftLaji4+9En0dc=; b=3M6/tmOQn6FIQOhT5VDXEOw9PeHIMaTIubIKzTD2pKeFK3FVqXJb2fd5rrn+btC4Q1 T7P/+JNiiofomIx+mNRVyAEvsgyLQzWiE2mIyIS7L4bpjntJq/5Utc5GjhDyo6RVe/bc t/desAQSTSqC+Q2QmsTFLii0z8MI1B+23C7PAFVhfrrNLu1gDoUamiWkU01HmA8cIYTF rNf/PuMTQ/eH1AFtQxc+sTIL22bnKX1/PFHA0pQbrvhTKP+nEthE55jB3Ez2jvSkKmqf T/WIzebdGegwCR8/J9xxuiGDJsYUp9xqfEdIxtTWxYHbFObbHh8CmzuY6Ps2E1vr6rXK eUbg== X-Gm-Message-State: AFqh2kqidosWGstyblvHRkVf20XWJiFrbDWGYIyQyxPoyRa/2ZsWwthU oyjgsyJXNcjucLNkFUIPyvQdsMdp6rGlaA== X-Received: by 2002:adf:ec4f:0:b0:27b:a73e:33ae with SMTP id w15-20020adfec4f000000b0027ba73e33aemr6257770wrn.8.1672207477843; Tue, 27 Dec 2022 22:04:37 -0800 (PST) Received: from wedsonaf-dev.. ([81.2.152.129]) by smtp.googlemail.com with ESMTPSA id x16-20020a5d6510000000b002755e301eeasm12128867wru.100.2022.12.27.22.04.37 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Tue, 27 Dec 2022 22:04:37 -0800 (PST) From: Wedson Almeida Filho <wedsonaf@gmail.com> To: rust-for-linux@vger.kernel.org Cc: Miguel Ojeda <ojeda@kernel.org>, Alex Gaynor <alex.gaynor@gmail.com>, Boqun Feng <boqun.feng@gmail.com>, Gary Guo <gary@garyguo.net>, =?utf-8?q?B?= =?utf-8?q?j=C3=B6rn_Roy_Baron?= <bjorn3_gh@protonmail.com>, linux-kernel@vger.kernel.org, Wedson Almeida Filho <wedsonaf@gmail.com> Subject: [PATCH 4/7] rust: sync: introduce `ArcBorrow` Date: Wed, 28 Dec 2022 06:03:43 +0000 Message-Id: <20221228060346.352362-4-wedsonaf@gmail.com> X-Mailer: git-send-email 2.34.1 In-Reply-To: <20221228060346.352362-1-wedsonaf@gmail.com> References: <20221228060346.352362-1-wedsonaf@gmail.com> MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Spam-Status: No, score=-2.1 required=5.0 tests=BAYES_00,DKIM_SIGNED, DKIM_VALID,DKIM_VALID_AU,DKIM_VALID_EF,FREEMAIL_FROM, RCVD_IN_DNSWL_NONE,SPF_HELO_NONE,SPF_PASS autolearn=ham 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?1753436699680110267?= X-GMAIL-MSGID: =?utf-8?q?1753436699680110267?= |
Series |
[1/7] rust: sync: add `Arc` for ref-counted allocations
|
|
Commit Message
Wedson Almeida Filho
Dec. 28, 2022, 6:03 a.m. UTC
This allows us to create references to a ref-counted allocation without
double-indirection and that still allow us to increment the refcount to
a new `Arc<T>`.
Signed-off-by: Wedson Almeida Filho <wedsonaf@gmail.com>
---
rust/kernel/sync.rs | 2 +-
rust/kernel/sync/arc.rs | 97 +++++++++++++++++++++++++++++++++++++++++
2 files changed, 98 insertions(+), 1 deletion(-)
Comments
On Dec 27, 2022, at 10:03 PM, Wedson Almeida Filho <wedsonaf@gmail.com> wrote: > This allows us to create references to a ref-counted allocation without > double-indirection and that still allow us to increment the refcount to > a new `Arc<T>`. > > Signed-off-by: Wedson Almeida Filho <wedsonaf@gmail.com> > --- > rust/kernel/sync.rs | 2 +- > rust/kernel/sync/arc.rs | 97 +++++++++++++++++++++++++++++++++++++++++ > 2 files changed, 98 insertions(+), 1 deletion(-) > > diff --git a/rust/kernel/sync.rs b/rust/kernel/sync.rs > index 39b379dd548f..5de03ea83ea1 100644 > --- a/rust/kernel/sync.rs > +++ b/rust/kernel/sync.rs > @@ -7,4 +7,4 @@ > > mod arc; > > -pub use arc::Arc; > +pub use arc::{Arc, ArcBorrow}; > diff --git a/rust/kernel/sync/arc.rs b/rust/kernel/sync/arc.rs > index dbc7596cc3ce..f68bfc02c81a 100644 > --- a/rust/kernel/sync/arc.rs > +++ b/rust/kernel/sync/arc.rs > @@ -19,6 +19,7 @@ use crate::{bindings, error::Result, types::Opaque}; > use alloc::boxed::Box; > use core::{ > marker::{PhantomData, Unsize}, > + mem::ManuallyDrop, > ops::Deref, > ptr::NonNull, > }; > @@ -164,6 +165,18 @@ impl<T: ?Sized> Arc<T> { > _p: PhantomData, > } > } > + > + /// Returns an [`ArcBorrow`] from the given [`Arc`]. > + /// > + /// This is useful when the argument of a function call is an [`ArcBorrow`] (e.g., in a method > + /// receiver), but we have an [`Arc`] instead. Getting an [`ArcBorrow`] is free when optimised. > + #[inline] > + pub fn as_arc_borrow(&self) -> ArcBorrow<'_, T> { > + // SAFETY: The constraint that the lifetime of the shared reference must outlive that of > + // the returned `ArcBorrow` ensures that the object remains alive and that no mutable > + // reference can be created. > + unsafe { ArcBorrow::new(self.ptr) } > + } > } > > impl<T: ?Sized> Deref for Arc<T> { > @@ -208,3 +221,87 @@ impl<T: ?Sized> Drop for Arc<T> { > } > } > } > + > +/// A borrowed reference to an [`Arc`] instance. > +/// > +/// For cases when one doesn't ever need to increment the refcount on the allocation, it is simpler > +/// to use just `&T`, which we can trivially get from an `Arc<T>` instance. > +/// > +/// However, when one may need to increment the refcount, it is preferable to use an `ArcBorrow<T>` > +/// over `&Arc<T>` because the latter results in a double-indirection: a pointer (shared reference) > +/// to a pointer (`Arc<T>`) to the object (`T`). An [`ArcBorrow`] eliminates this double > +/// indirection while still allowing one to increment the refcount and getting an `Arc<T>` when/if > +/// needed. > +/// > +/// # Invariants > +/// > +/// There are no mutable references to the underlying [`Arc`], and it remains valid for the > +/// lifetime of the [`ArcBorrow`] instance. > +/// > +/// # Example > +/// > +/// ``` > +/// use crate::sync::{Arc, ArcBorrow}; > +/// > +/// struct Example; > +/// > +/// fn do_something(e: ArcBorrow<'_, Example>) -> Arc<Example> { > +/// e.into() > +/// } > +/// > +/// let obj = Arc::try_new(Example)?; > +/// let cloned = do_something(obj.as_arc_borrow()); > +/// > +/// // Assert that both `obj` and `cloned` point to the same underlying object. > +/// assert!(core::ptr::eq(&*obj, &*cloned)); > +/// ``` > +pub struct ArcBorrow<'a, T: ?Sized + 'a> { > + inner: NonNull<ArcInner<T>>, > + _p: PhantomData<&'a ()>, > +} > + > +impl<T: ?Sized> Clone for ArcBorrow<'_, T> { > + fn clone(&self) -> Self { > + *self > + } > +} > + > +impl<T: ?Sized> Copy for ArcBorrow<'_, T> {} > + > +impl<T: ?Sized> ArcBorrow<'_, T> { > + /// Creates a new [`ArcBorrow`] instance. > + /// > + /// # Safety > + /// > + /// Callers must ensure the following for the lifetime of the returned [`ArcBorrow`] instance: > + /// 1. That `inner` remains valid; > + /// 2. That no mutable references to `inner` are created. > + unsafe fn new(inner: NonNull<ArcInner<T>>) -> Self { > + // INVARIANT: The safety requirements guarantee the invariants. > + Self { > + inner, > + _p: PhantomData, > + } > + } > +} > + > +impl<T: ?Sized> From<ArcBorrow<'_, T>> for Arc<T> { > + fn from(b: ArcBorrow<'_, T>) -> Self { > + // SAFETY: The existence of `b` guarantees that the refcount is non-zero. `ManuallyDrop` > + // guarantees that `drop` isn't called, so it's ok that the temporary `Arc` doesn't own the > + // increment. > + ManuallyDrop::new(unsafe { Arc::from_inner(b.inner) }) > + .deref() > + .clone() The same worries about safety apply here too. You need to make this fallible—try_from is nice enough for that. > + } > +} > + > +impl<T: ?Sized> Deref for ArcBorrow<'_, T> { > + type Target = T; > + > + fn deref(&self) -> &Self::Target { > + // SAFETY: By the type invariant, the underlying object is still alive with no mutable > + // references to it, so it is safe to create a shared reference. > + unsafe { &self.inner.as_ref().data } > + } > +} > -- > 2.34.1 > > — Laine Taffin Altman
Reviewed-by: Alice Ryhl <aliceryhl@google.com> On 12/28/22 07:03, Wedson Almeida Filho wrote: > This allows us to create references to a ref-counted allocation without > double-indirection and that still allow us to increment the refcount to > a new `Arc<T>`. > > Signed-off-by: Wedson Almeida Filho <wedsonaf@gmail.com> > --- > rust/kernel/sync.rs | 2 +- > rust/kernel/sync/arc.rs | 97 +++++++++++++++++++++++++++++++++++++++++ > 2 files changed, 98 insertions(+), 1 deletion(-) > > diff --git a/rust/kernel/sync.rs b/rust/kernel/sync.rs > index 39b379dd548f..5de03ea83ea1 100644 > --- a/rust/kernel/sync.rs > +++ b/rust/kernel/sync.rs > @@ -7,4 +7,4 @@ > > mod arc; > > -pub use arc::Arc; > +pub use arc::{Arc, ArcBorrow}; > diff --git a/rust/kernel/sync/arc.rs b/rust/kernel/sync/arc.rs > index dbc7596cc3ce..f68bfc02c81a 100644 > --- a/rust/kernel/sync/arc.rs > +++ b/rust/kernel/sync/arc.rs > @@ -19,6 +19,7 @@ use crate::{bindings, error::Result, types::Opaque}; > use alloc::boxed::Box; > use core::{ > marker::{PhantomData, Unsize}, > + mem::ManuallyDrop, > ops::Deref, > ptr::NonNull, > }; > @@ -164,6 +165,18 @@ impl<T: ?Sized> Arc<T> { > _p: PhantomData, > } > } > + > + /// Returns an [`ArcBorrow`] from the given [`Arc`]. > + /// > + /// This is useful when the argument of a function call is an [`ArcBorrow`] (e.g., in a method > + /// receiver), but we have an [`Arc`] instead. Getting an [`ArcBorrow`] is free when optimised. > + #[inline] > + pub fn as_arc_borrow(&self) -> ArcBorrow<'_, T> { > + // SAFETY: The constraint that the lifetime of the shared reference must outlive that of > + // the returned `ArcBorrow` ensures that the object remains alive and that no mutable > + // reference can be created. > + unsafe { ArcBorrow::new(self.ptr) } > + } > } > > impl<T: ?Sized> Deref for Arc<T> { > @@ -208,3 +221,87 @@ impl<T: ?Sized> Drop for Arc<T> { > } > } > } > + > +/// A borrowed reference to an [`Arc`] instance. > +/// > +/// For cases when one doesn't ever need to increment the refcount on the allocation, it is simpler > +/// to use just `&T`, which we can trivially get from an `Arc<T>` instance. > +/// > +/// However, when one may need to increment the refcount, it is preferable to use an `ArcBorrow<T>` > +/// over `&Arc<T>` because the latter results in a double-indirection: a pointer (shared reference) > +/// to a pointer (`Arc<T>`) to the object (`T`). An [`ArcBorrow`] eliminates this double > +/// indirection while still allowing one to increment the refcount and getting an `Arc<T>` when/if > +/// needed. > +/// > +/// # Invariants > +/// > +/// There are no mutable references to the underlying [`Arc`], and it remains valid for the > +/// lifetime of the [`ArcBorrow`] instance. > +/// > +/// # Example > +/// > +/// ``` > +/// use crate::sync::{Arc, ArcBorrow}; > +/// > +/// struct Example; > +/// > +/// fn do_something(e: ArcBorrow<'_, Example>) -> Arc<Example> { > +/// e.into() > +/// } > +/// > +/// let obj = Arc::try_new(Example)?; > +/// let cloned = do_something(obj.as_arc_borrow()); > +/// > +/// // Assert that both `obj` and `cloned` point to the same underlying object. > +/// assert!(core::ptr::eq(&*obj, &*cloned)); > +/// ``` > +pub struct ArcBorrow<'a, T: ?Sized + 'a> { > + inner: NonNull<ArcInner<T>>, > + _p: PhantomData<&'a ()>, > +} > + > +impl<T: ?Sized> Clone for ArcBorrow<'_, T> { > + fn clone(&self) -> Self { > + *self > + } > +} > + > +impl<T: ?Sized> Copy for ArcBorrow<'_, T> {} > + > +impl<T: ?Sized> ArcBorrow<'_, T> { > + /// Creates a new [`ArcBorrow`] instance. > + /// > + /// # Safety > + /// > + /// Callers must ensure the following for the lifetime of the returned [`ArcBorrow`] instance: > + /// 1. That `inner` remains valid; > + /// 2. That no mutable references to `inner` are created. > + unsafe fn new(inner: NonNull<ArcInner<T>>) -> Self { > + // INVARIANT: The safety requirements guarantee the invariants. > + Self { > + inner, > + _p: PhantomData, > + } > + } > +} > + > +impl<T: ?Sized> From<ArcBorrow<'_, T>> for Arc<T> { > + fn from(b: ArcBorrow<'_, T>) -> Self { > + // SAFETY: The existence of `b` guarantees that the refcount is non-zero. `ManuallyDrop` > + // guarantees that `drop` isn't called, so it's ok that the temporary `Arc` doesn't own the > + // increment. > + ManuallyDrop::new(unsafe { Arc::from_inner(b.inner) }) > + .deref() > + .clone() > + } > +} > + > +impl<T: ?Sized> Deref for ArcBorrow<'_, T> { > + type Target = T; > + > + fn deref(&self) -> &Self::Target { > + // SAFETY: By the type invariant, the underlying object is still alive with no mutable > + // references to it, so it is safe to create a shared reference. > + unsafe { &self.inner.as_ref().data } > + } > +}
On Wed, 28 Dec 2022 06:03:43 +0000 Wedson Almeida Filho <wedsonaf@gmail.com> wrote: > This allows us to create references to a ref-counted allocation without > double-indirection and that still allow us to increment the refcount to > a new `Arc<T>`. > > Signed-off-by: Wedson Almeida Filho <wedsonaf@gmail.com> > --- > rust/kernel/sync.rs | 2 +- > rust/kernel/sync/arc.rs | 97 +++++++++++++++++++++++++++++++++++++++++ > 2 files changed, 98 insertions(+), 1 deletion(-) > > diff --git a/rust/kernel/sync.rs b/rust/kernel/sync.rs > index 39b379dd548f..5de03ea83ea1 100644 > --- a/rust/kernel/sync.rs > +++ b/rust/kernel/sync.rs > @@ -7,4 +7,4 @@ > > mod arc; > > -pub use arc::Arc; > +pub use arc::{Arc, ArcBorrow}; > diff --git a/rust/kernel/sync/arc.rs b/rust/kernel/sync/arc.rs > index dbc7596cc3ce..f68bfc02c81a 100644 > --- a/rust/kernel/sync/arc.rs > +++ b/rust/kernel/sync/arc.rs > @@ -19,6 +19,7 @@ use crate::{bindings, error::Result, types::Opaque}; > use alloc::boxed::Box; > use core::{ > marker::{PhantomData, Unsize}, > + mem::ManuallyDrop, > ops::Deref, > ptr::NonNull, > }; > @@ -164,6 +165,18 @@ impl<T: ?Sized> Arc<T> { > _p: PhantomData, > } > } > + > + /// Returns an [`ArcBorrow`] from the given [`Arc`]. > + /// > + /// This is useful when the argument of a function call is an [`ArcBorrow`] (e.g., in a method > + /// receiver), but we have an [`Arc`] instead. Getting an [`ArcBorrow`] is free when optimised. > + #[inline] > + pub fn as_arc_borrow(&self) -> ArcBorrow<'_, T> { > + // SAFETY: The constraint that the lifetime of the shared reference must outlive that of > + // the returned `ArcBorrow` ensures that the object remains alive and that no mutable > + // reference can be created. > + unsafe { ArcBorrow::new(self.ptr) } > + } > } > > impl<T: ?Sized> Deref for Arc<T> { > @@ -208,3 +221,87 @@ impl<T: ?Sized> Drop for Arc<T> { > } > } > } > + > +/// A borrowed reference to an [`Arc`] instance. > +/// > +/// For cases when one doesn't ever need to increment the refcount on the allocation, it is simpler > +/// to use just `&T`, which we can trivially get from an `Arc<T>` instance. > +/// > +/// However, when one may need to increment the refcount, it is preferable to use an `ArcBorrow<T>` > +/// over `&Arc<T>` because the latter results in a double-indirection: a pointer (shared reference) > +/// to a pointer (`Arc<T>`) to the object (`T`). An [`ArcBorrow`] eliminates this double > +/// indirection while still allowing one to increment the refcount and getting an `Arc<T>` when/if > +/// needed. > +/// > +/// # Invariants > +/// > +/// There are no mutable references to the underlying [`Arc`], and it remains valid for the > +/// lifetime of the [`ArcBorrow`] instance. > +/// > +/// # Example > +/// > +/// ``` > +/// use crate::sync::{Arc, ArcBorrow}; > +/// > +/// struct Example; > +/// > +/// fn do_something(e: ArcBorrow<'_, Example>) -> Arc<Example> { > +/// e.into() > +/// } > +/// > +/// let obj = Arc::try_new(Example)?; > +/// let cloned = do_something(obj.as_arc_borrow()); > +/// > +/// // Assert that both `obj` and `cloned` point to the same underlying object. > +/// assert!(core::ptr::eq(&*obj, &*cloned)); > +/// ``` > +pub struct ArcBorrow<'a, T: ?Sized + 'a> { > + inner: NonNull<ArcInner<T>>, > + _p: PhantomData<&'a ()>, > +} > + > +impl<T: ?Sized> Clone for ArcBorrow<'_, T> { > + fn clone(&self) -> Self { > + *self > + } > +} > + > +impl<T: ?Sized> Copy for ArcBorrow<'_, T> {} Couldn't this just be derived `Clone` and `Copy`? > + > +impl<T: ?Sized> ArcBorrow<'_, T> { > + /// Creates a new [`ArcBorrow`] instance. > + /// > + /// # Safety > + /// > + /// Callers must ensure the following for the lifetime of the returned [`ArcBorrow`] instance: > + /// 1. That `inner` remains valid; > + /// 2. That no mutable references to `inner` are created. > + unsafe fn new(inner: NonNull<ArcInner<T>>) -> Self { > + // INVARIANT: The safety requirements guarantee the invariants. > + Self { > + inner, > + _p: PhantomData, > + } > + } > +} > + > +impl<T: ?Sized> From<ArcBorrow<'_, T>> for Arc<T> { > + fn from(b: ArcBorrow<'_, T>) -> Self { > + // SAFETY: The existence of `b` guarantees that the refcount is non-zero. `ManuallyDrop` > + // guarantees that `drop` isn't called, so it's ok that the temporary `Arc` doesn't own the > + // increment. > + ManuallyDrop::new(unsafe { Arc::from_inner(b.inner) }) > + .deref() > + .clone() > + } > +} It might be easier to follow if this is jsut `bindings::refcount_inc` followed by `Arc::from_inner`? > + > +impl<T: ?Sized> Deref for ArcBorrow<'_, T> { > + type Target = T; > + > + fn deref(&self) -> &Self::Target { > + // SAFETY: By the type invariant, the underlying object is still alive with no mutable > + // references to it, so it is safe to create a shared reference. > + unsafe { &self.inner.as_ref().data } > + } > +}
On Sat, 31 Dec 2022 at 19:43, Gary Guo <gary@garyguo.net> wrote: > > On Wed, 28 Dec 2022 06:03:43 +0000 > Wedson Almeida Filho <wedsonaf@gmail.com> wrote: > > > This allows us to create references to a ref-counted allocation without > > double-indirection and that still allow us to increment the refcount to > > a new `Arc<T>`. > > > > Signed-off-by: Wedson Almeida Filho <wedsonaf@gmail.com> > > --- > > rust/kernel/sync.rs | 2 +- > > rust/kernel/sync/arc.rs | 97 +++++++++++++++++++++++++++++++++++++++++ > > 2 files changed, 98 insertions(+), 1 deletion(-) > > > > diff --git a/rust/kernel/sync.rs b/rust/kernel/sync.rs > > index 39b379dd548f..5de03ea83ea1 100644 > > --- a/rust/kernel/sync.rs > > +++ b/rust/kernel/sync.rs > > @@ -7,4 +7,4 @@ > > > > mod arc; > > > > -pub use arc::Arc; > > +pub use arc::{Arc, ArcBorrow}; > > diff --git a/rust/kernel/sync/arc.rs b/rust/kernel/sync/arc.rs > > index dbc7596cc3ce..f68bfc02c81a 100644 > > --- a/rust/kernel/sync/arc.rs > > +++ b/rust/kernel/sync/arc.rs > > @@ -19,6 +19,7 @@ use crate::{bindings, error::Result, types::Opaque}; > > use alloc::boxed::Box; > > use core::{ > > marker::{PhantomData, Unsize}, > > + mem::ManuallyDrop, > > ops::Deref, > > ptr::NonNull, > > }; > > @@ -164,6 +165,18 @@ impl<T: ?Sized> Arc<T> { > > _p: PhantomData, > > } > > } > > + > > + /// Returns an [`ArcBorrow`] from the given [`Arc`]. > > + /// > > + /// This is useful when the argument of a function call is an [`ArcBorrow`] (e.g., in a method > > + /// receiver), but we have an [`Arc`] instead. Getting an [`ArcBorrow`] is free when optimised. > > + #[inline] > > + pub fn as_arc_borrow(&self) -> ArcBorrow<'_, T> { > > + // SAFETY: The constraint that the lifetime of the shared reference must outlive that of > > + // the returned `ArcBorrow` ensures that the object remains alive and that no mutable > > + // reference can be created. > > + unsafe { ArcBorrow::new(self.ptr) } > > + } > > } > > > > impl<T: ?Sized> Deref for Arc<T> { > > @@ -208,3 +221,87 @@ impl<T: ?Sized> Drop for Arc<T> { > > } > > } > > } > > + > > +/// A borrowed reference to an [`Arc`] instance. > > +/// > > +/// For cases when one doesn't ever need to increment the refcount on the allocation, it is simpler > > +/// to use just `&T`, which we can trivially get from an `Arc<T>` instance. > > +/// > > +/// However, when one may need to increment the refcount, it is preferable to use an `ArcBorrow<T>` > > +/// over `&Arc<T>` because the latter results in a double-indirection: a pointer (shared reference) > > +/// to a pointer (`Arc<T>`) to the object (`T`). An [`ArcBorrow`] eliminates this double > > +/// indirection while still allowing one to increment the refcount and getting an `Arc<T>` when/if > > +/// needed. > > +/// > > +/// # Invariants > > +/// > > +/// There are no mutable references to the underlying [`Arc`], and it remains valid for the > > +/// lifetime of the [`ArcBorrow`] instance. > > +/// > > +/// # Example > > +/// > > +/// ``` > > +/// use crate::sync::{Arc, ArcBorrow}; > > +/// > > +/// struct Example; > > +/// > > +/// fn do_something(e: ArcBorrow<'_, Example>) -> Arc<Example> { > > +/// e.into() > > +/// } > > +/// > > +/// let obj = Arc::try_new(Example)?; > > +/// let cloned = do_something(obj.as_arc_borrow()); > > +/// > > +/// // Assert that both `obj` and `cloned` point to the same underlying object. > > +/// assert!(core::ptr::eq(&*obj, &*cloned)); > > +/// ``` > > +pub struct ArcBorrow<'a, T: ?Sized + 'a> { > > + inner: NonNull<ArcInner<T>>, > > + _p: PhantomData<&'a ()>, > > +} > > + > > +impl<T: ?Sized> Clone for ArcBorrow<'_, T> { > > + fn clone(&self) -> Self { > > + *self > > + } > > +} > > + > > +impl<T: ?Sized> Copy for ArcBorrow<'_, T> {} > > Couldn't this just be derived `Clone` and `Copy`? Indeed. I'll send a v2 with this. > > > + > > +impl<T: ?Sized> ArcBorrow<'_, T> { > > + /// Creates a new [`ArcBorrow`] instance. > > + /// > > + /// # Safety > > + /// > > + /// Callers must ensure the following for the lifetime of the returned [`ArcBorrow`] instance: > > + /// 1. That `inner` remains valid; > > + /// 2. That no mutable references to `inner` are created. > > + unsafe fn new(inner: NonNull<ArcInner<T>>) -> Self { > > + // INVARIANT: The safety requirements guarantee the invariants. > > + Self { > > + inner, > > + _p: PhantomData, > > + } > > + } > > +} > > + > > +impl<T: ?Sized> From<ArcBorrow<'_, T>> for Arc<T> { > > + fn from(b: ArcBorrow<'_, T>) -> Self { > > + // SAFETY: The existence of `b` guarantees that the refcount is non-zero. `ManuallyDrop` > > + // guarantees that `drop` isn't called, so it's ok that the temporary `Arc` doesn't own the > > + // increment. > > + ManuallyDrop::new(unsafe { Arc::from_inner(b.inner) }) > > + .deref() > > + .clone() > > + } > > +} > > It might be easier to follow if this is jsut `bindings::refcount_inc` > followed by `Arc::from_inner`? I'd prefer to keep the interactions with `refcount_t` in `Arc` only so that we can more easily change it in the future if we so choose. > > + > > +impl<T: ?Sized> Deref for ArcBorrow<'_, T> { > > + type Target = T; > > + > > + fn deref(&self) -> &Self::Target { > > + // SAFETY: By the type invariant, the underlying object is still alive with no mutable > > + // references to it, so it is safe to create a shared reference. > > + unsafe { &self.inner.as_ref().data } > > + } > > +}
Sorry for the drive-by comment, but maybe it saves some work. On 1/4/23 16:29, Wedson Almeida Filho wrote: > On Sat, 31 Dec 2022 at 19:43, Gary Guo <gary@garyguo.net> wrote: >> >> On Wed, 28 Dec 2022 06:03:43 +0000 >> Wedson Almeida Filho <wedsonaf@gmail.com> wrote: >> >>> This allows us to create references to a ref-counted allocation without >>> double-indirection and that still allow us to increment the refcount to >>> a new `Arc<T>`. >>> >>> Signed-off-by: Wedson Almeida Filho <wedsonaf@gmail.com> >>> --- >>> rust/kernel/sync.rs | 2 +- >>> rust/kernel/sync/arc.rs | 97 +++++++++++++++++++++++++++++++++++++++++ >>> 2 files changed, 98 insertions(+), 1 deletion(-) >>> >>> diff --git a/rust/kernel/sync.rs b/rust/kernel/sync.rs >>> index 39b379dd548f..5de03ea83ea1 100644 >>> --- a/rust/kernel/sync.rs >>> +++ b/rust/kernel/sync.rs >>> @@ -7,4 +7,4 @@ >>> >>> mod arc; >>> >>> -pub use arc::Arc; >>> +pub use arc::{Arc, ArcBorrow}; >>> diff --git a/rust/kernel/sync/arc.rs b/rust/kernel/sync/arc.rs >>> index dbc7596cc3ce..f68bfc02c81a 100644 >>> --- a/rust/kernel/sync/arc.rs >>> +++ b/rust/kernel/sync/arc.rs >>> @@ -19,6 +19,7 @@ use crate::{bindings, error::Result, types::Opaque}; >>> use alloc::boxed::Box; >>> use core::{ >>> marker::{PhantomData, Unsize}, >>> + mem::ManuallyDrop, >>> ops::Deref, >>> ptr::NonNull, >>> }; >>> @@ -164,6 +165,18 @@ impl<T: ?Sized> Arc<T> { >>> _p: PhantomData, >>> } >>> } >>> + >>> + /// Returns an [`ArcBorrow`] from the given [`Arc`]. >>> + /// >>> + /// This is useful when the argument of a function call is an [`ArcBorrow`] (e.g., in a method >>> + /// receiver), but we have an [`Arc`] instead. Getting an [`ArcBorrow`] is free when optimised. >>> + #[inline] >>> + pub fn as_arc_borrow(&self) -> ArcBorrow<'_, T> { >>> + // SAFETY: The constraint that the lifetime of the shared reference must outlive that of >>> + // the returned `ArcBorrow` ensures that the object remains alive and that no mutable >>> + // reference can be created. >>> + unsafe { ArcBorrow::new(self.ptr) } >>> + } >>> } >>> >>> impl<T: ?Sized> Deref for Arc<T> { >>> @@ -208,3 +221,87 @@ impl<T: ?Sized> Drop for Arc<T> { >>> } >>> } >>> } >>> + >>> +/// A borrowed reference to an [`Arc`] instance. >>> +/// >>> +/// For cases when one doesn't ever need to increment the refcount on the allocation, it is simpler >>> +/// to use just `&T`, which we can trivially get from an `Arc<T>` instance. >>> +/// >>> +/// However, when one may need to increment the refcount, it is preferable to use an `ArcBorrow<T>` >>> +/// over `&Arc<T>` because the latter results in a double-indirection: a pointer (shared reference) >>> +/// to a pointer (`Arc<T>`) to the object (`T`). An [`ArcBorrow`] eliminates this double >>> +/// indirection while still allowing one to increment the refcount and getting an `Arc<T>` when/if >>> +/// needed. >>> +/// >>> +/// # Invariants >>> +/// >>> +/// There are no mutable references to the underlying [`Arc`], and it remains valid for the >>> +/// lifetime of the [`ArcBorrow`] instance. >>> +/// >>> +/// # Example >>> +/// >>> +/// ``` >>> +/// use crate::sync::{Arc, ArcBorrow}; >>> +/// >>> +/// struct Example; >>> +/// >>> +/// fn do_something(e: ArcBorrow<'_, Example>) -> Arc<Example> { >>> +/// e.into() >>> +/// } >>> +/// >>> +/// let obj = Arc::try_new(Example)?; >>> +/// let cloned = do_something(obj.as_arc_borrow()); >>> +/// >>> +/// // Assert that both `obj` and `cloned` point to the same underlying object. >>> +/// assert!(core::ptr::eq(&*obj, &*cloned)); >>> +/// ``` >>> +pub struct ArcBorrow<'a, T: ?Sized + 'a> { >>> + inner: NonNull<ArcInner<T>>, >>> + _p: PhantomData<&'a ()>, >>> +} >>> + >>> +impl<T: ?Sized> Clone for ArcBorrow<'_, T> { >>> + fn clone(&self) -> Self { >>> + *self >>> + } >>> +} >>> + >>> +impl<T: ?Sized> Copy for ArcBorrow<'_, T> {} >> >> Couldn't this just be derived `Clone` and `Copy`? > > Indeed. I'll send a v2 with this. I'm not sure this is true. Deriving will add the T: Copy and T: Clone bound, which I think is not what you want here. i.e., I assume you want an ArcBorrow to be Copy even if the underlying T is not. See <https://github.com/rust-lang/rust/issues/26925> for the relevant (really long-standing) Rust issue. Cheers, -- Emilio
On Wed, 4 Jan 2023 at 16:06, Emilio Cobos Álvarez <emilio@crisal.io> wrote: > > Sorry for the drive-by comment, but maybe it saves some work. > > On 1/4/23 16:29, Wedson Almeida Filho wrote: > > On Sat, 31 Dec 2022 at 19:43, Gary Guo <gary@garyguo.net> wrote: > >> > >> On Wed, 28 Dec 2022 06:03:43 +0000 > >> Wedson Almeida Filho <wedsonaf@gmail.com> wrote: > >> > >>> This allows us to create references to a ref-counted allocation without > >>> double-indirection and that still allow us to increment the refcount to > >>> a new `Arc<T>`. > >>> > >>> Signed-off-by: Wedson Almeida Filho <wedsonaf@gmail.com> > >>> --- > >>> rust/kernel/sync.rs | 2 +- > >>> rust/kernel/sync/arc.rs | 97 +++++++++++++++++++++++++++++++++++++++++ > >>> 2 files changed, 98 insertions(+), 1 deletion(-) > >>> > >>> diff --git a/rust/kernel/sync.rs b/rust/kernel/sync.rs > >>> index 39b379dd548f..5de03ea83ea1 100644 > >>> --- a/rust/kernel/sync.rs > >>> +++ b/rust/kernel/sync.rs > >>> @@ -7,4 +7,4 @@ > >>> > >>> mod arc; > >>> > >>> -pub use arc::Arc; > >>> +pub use arc::{Arc, ArcBorrow}; > >>> diff --git a/rust/kernel/sync/arc.rs b/rust/kernel/sync/arc.rs > >>> index dbc7596cc3ce..f68bfc02c81a 100644 > >>> --- a/rust/kernel/sync/arc.rs > >>> +++ b/rust/kernel/sync/arc.rs > >>> @@ -19,6 +19,7 @@ use crate::{bindings, error::Result, types::Opaque}; > >>> use alloc::boxed::Box; > >>> use core::{ > >>> marker::{PhantomData, Unsize}, > >>> + mem::ManuallyDrop, > >>> ops::Deref, > >>> ptr::NonNull, > >>> }; > >>> @@ -164,6 +165,18 @@ impl<T: ?Sized> Arc<T> { > >>> _p: PhantomData, > >>> } > >>> } > >>> + > >>> + /// Returns an [`ArcBorrow`] from the given [`Arc`]. > >>> + /// > >>> + /// This is useful when the argument of a function call is an [`ArcBorrow`] (e.g., in a method > >>> + /// receiver), but we have an [`Arc`] instead. Getting an [`ArcBorrow`] is free when optimised. > >>> + #[inline] > >>> + pub fn as_arc_borrow(&self) -> ArcBorrow<'_, T> { > >>> + // SAFETY: The constraint that the lifetime of the shared reference must outlive that of > >>> + // the returned `ArcBorrow` ensures that the object remains alive and that no mutable > >>> + // reference can be created. > >>> + unsafe { ArcBorrow::new(self.ptr) } > >>> + } > >>> } > >>> > >>> impl<T: ?Sized> Deref for Arc<T> { > >>> @@ -208,3 +221,87 @@ impl<T: ?Sized> Drop for Arc<T> { > >>> } > >>> } > >>> } > >>> + > >>> +/// A borrowed reference to an [`Arc`] instance. > >>> +/// > >>> +/// For cases when one doesn't ever need to increment the refcount on the allocation, it is simpler > >>> +/// to use just `&T`, which we can trivially get from an `Arc<T>` instance. > >>> +/// > >>> +/// However, when one may need to increment the refcount, it is preferable to use an `ArcBorrow<T>` > >>> +/// over `&Arc<T>` because the latter results in a double-indirection: a pointer (shared reference) > >>> +/// to a pointer (`Arc<T>`) to the object (`T`). An [`ArcBorrow`] eliminates this double > >>> +/// indirection while still allowing one to increment the refcount and getting an `Arc<T>` when/if > >>> +/// needed. > >>> +/// > >>> +/// # Invariants > >>> +/// > >>> +/// There are no mutable references to the underlying [`Arc`], and it remains valid for the > >>> +/// lifetime of the [`ArcBorrow`] instance. > >>> +/// > >>> +/// # Example > >>> +/// > >>> +/// ``` > >>> +/// use crate::sync::{Arc, ArcBorrow}; > >>> +/// > >>> +/// struct Example; > >>> +/// > >>> +/// fn do_something(e: ArcBorrow<'_, Example>) -> Arc<Example> { > >>> +/// e.into() > >>> +/// } > >>> +/// > >>> +/// let obj = Arc::try_new(Example)?; > >>> +/// let cloned = do_something(obj.as_arc_borrow()); > >>> +/// > >>> +/// // Assert that both `obj` and `cloned` point to the same underlying object. > >>> +/// assert!(core::ptr::eq(&*obj, &*cloned)); > >>> +/// ``` > >>> +pub struct ArcBorrow<'a, T: ?Sized + 'a> { > >>> + inner: NonNull<ArcInner<T>>, > >>> + _p: PhantomData<&'a ()>, > >>> +} > >>> + > >>> +impl<T: ?Sized> Clone for ArcBorrow<'_, T> { > >>> + fn clone(&self) -> Self { > >>> + *self > >>> + } > >>> +} > >>> + > >>> +impl<T: ?Sized> Copy for ArcBorrow<'_, T> {} > >> > >> Couldn't this just be derived `Clone` and `Copy`? > > > > Indeed. I'll send a v2 with this. > > I'm not sure this is true. Deriving will add the T: Copy and T: Clone > bound, which I think is not what you want here. > > i.e., I assume you want an ArcBorrow to be Copy even if the underlying T > is not. > > See <https://github.com/rust-lang/rust/issues/26925> for the relevant > (really long-standing) Rust issue. Thanks for the heads up, Emilio! After trying this out, derive doesn't work. The errors brought me back memories of when I first implemented this over a year ago, though I didn't take the time to try to understand why it was failing. So no v2. The series will remain as is. Cheers > > Cheers, > > -- Emilio
On Wed, 4 Jan 2023 17:06:50 +0100 Emilio Cobos Álvarez <emilio@crisal.io> wrote: > Sorry for the drive-by comment, but maybe it saves some work. > > On 1/4/23 16:29, Wedson Almeida Filho wrote: > > On Sat, 31 Dec 2022 at 19:43, Gary Guo <gary@garyguo.net> wrote: > >> > >> On Wed, 28 Dec 2022 06:03:43 +0000 > >> Wedson Almeida Filho <wedsonaf@gmail.com> wrote: > >>> +pub struct ArcBorrow<'a, T: ?Sized + 'a> { > >>> + inner: NonNull<ArcInner<T>>, > >>> + _p: PhantomData<&'a ()>, > >>> +} > >>> + > >>> +impl<T: ?Sized> Clone for ArcBorrow<'_, T> { > >>> + fn clone(&self) -> Self { > >>> + *self > >>> + } > >>> +} > >>> + > >>> +impl<T: ?Sized> Copy for ArcBorrow<'_, T> {} > >> > >> Couldn't this just be derived `Clone` and `Copy`? > > > > Indeed. I'll send a v2 with this. > > I'm not sure this is true. Deriving will add the T: Copy and T: Clone > bound, which I think is not what you want here. > > i.e., I assume you want an ArcBorrow to be Copy even if the underlying T > is not. Thanks for pointing out, I neglected that. In this case: Reviewed-by: Gary Guo <gary@garyguo.net>
Ops! I fall asleep while waiting for the Copy to derive Copy debate! Reviewed-by: Vincenzo Palazzo <vincenzopalazzodev@gmail.com> On Wed, Dec 28, 2022 at 7:05 AM Wedson Almeida Filho <wedsonaf@gmail.com> wrote: > > This allows us to create references to a ref-counted allocation without > double-indirection and that still allow us to increment the refcount to > a new `Arc<T>`. > > Signed-off-by: Wedson Almeida Filho <wedsonaf@gmail.com> > --- > rust/kernel/sync.rs | 2 +- > rust/kernel/sync/arc.rs | 97 +++++++++++++++++++++++++++++++++++++++++ > 2 files changed, 98 insertions(+), 1 deletion(-) > > diff --git a/rust/kernel/sync.rs b/rust/kernel/sync.rs > index 39b379dd548f..5de03ea83ea1 100644 > --- a/rust/kernel/sync.rs > +++ b/rust/kernel/sync.rs > @@ -7,4 +7,4 @@ > > mod arc; > > -pub use arc::Arc; > +pub use arc::{Arc, ArcBorrow}; > diff --git a/rust/kernel/sync/arc.rs b/rust/kernel/sync/arc.rs > index dbc7596cc3ce..f68bfc02c81a 100644 > --- a/rust/kernel/sync/arc.rs > +++ b/rust/kernel/sync/arc.rs > @@ -19,6 +19,7 @@ use crate::{bindings, error::Result, types::Opaque}; > use alloc::boxed::Box; > use core::{ > marker::{PhantomData, Unsize}, > + mem::ManuallyDrop, > ops::Deref, > ptr::NonNull, > }; > @@ -164,6 +165,18 @@ impl<T: ?Sized> Arc<T> { > _p: PhantomData, > } > } > + > + /// Returns an [`ArcBorrow`] from the given [`Arc`]. > + /// > + /// This is useful when the argument of a function call is an [`ArcBorrow`] (e.g., in a method > + /// receiver), but we have an [`Arc`] instead. Getting an [`ArcBorrow`] is free when optimised. > + #[inline] > + pub fn as_arc_borrow(&self) -> ArcBorrow<'_, T> { > + // SAFETY: The constraint that the lifetime of the shared reference must outlive that of > + // the returned `ArcBorrow` ensures that the object remains alive and that no mutable > + // reference can be created. > + unsafe { ArcBorrow::new(self.ptr) } > + } > } > > impl<T: ?Sized> Deref for Arc<T> { > @@ -208,3 +221,87 @@ impl<T: ?Sized> Drop for Arc<T> { > } > } > } > + > +/// A borrowed reference to an [`Arc`] instance. > +/// > +/// For cases when one doesn't ever need to increment the refcount on the allocation, it is simpler > +/// to use just `&T`, which we can trivially get from an `Arc<T>` instance. > +/// > +/// However, when one may need to increment the refcount, it is preferable to use an `ArcBorrow<T>` > +/// over `&Arc<T>` because the latter results in a double-indirection: a pointer (shared reference) > +/// to a pointer (`Arc<T>`) to the object (`T`). An [`ArcBorrow`] eliminates this double > +/// indirection while still allowing one to increment the refcount and getting an `Arc<T>` when/if > +/// needed. > +/// > +/// # Invariants > +/// > +/// There are no mutable references to the underlying [`Arc`], and it remains valid for the > +/// lifetime of the [`ArcBorrow`] instance. > +/// > +/// # Example > +/// > +/// ``` > +/// use crate::sync::{Arc, ArcBorrow}; > +/// > +/// struct Example; > +/// > +/// fn do_something(e: ArcBorrow<'_, Example>) -> Arc<Example> { > +/// e.into() > +/// } > +/// > +/// let obj = Arc::try_new(Example)?; > +/// let cloned = do_something(obj.as_arc_borrow()); > +/// > +/// // Assert that both `obj` and `cloned` point to the same underlying object. > +/// assert!(core::ptr::eq(&*obj, &*cloned)); > +/// ``` > +pub struct ArcBorrow<'a, T: ?Sized + 'a> { > + inner: NonNull<ArcInner<T>>, > + _p: PhantomData<&'a ()>, > +} > + > +impl<T: ?Sized> Clone for ArcBorrow<'_, T> { > + fn clone(&self) -> Self { > + *self > + } > +} > + > +impl<T: ?Sized> Copy for ArcBorrow<'_, T> {} > + > +impl<T: ?Sized> ArcBorrow<'_, T> { > + /// Creates a new [`ArcBorrow`] instance. > + /// > + /// # Safety > + /// > + /// Callers must ensure the following for the lifetime of the returned [`ArcBorrow`] instance: > + /// 1. That `inner` remains valid; > + /// 2. That no mutable references to `inner` are created. > + unsafe fn new(inner: NonNull<ArcInner<T>>) -> Self { > + // INVARIANT: The safety requirements guarantee the invariants. > + Self { > + inner, > + _p: PhantomData, > + } > + } > +} > + > +impl<T: ?Sized> From<ArcBorrow<'_, T>> for Arc<T> { > + fn from(b: ArcBorrow<'_, T>) -> Self { > + // SAFETY: The existence of `b` guarantees that the refcount is non-zero. `ManuallyDrop` > + // guarantees that `drop` isn't called, so it's ok that the temporary `Arc` doesn't own the > + // increment. > + ManuallyDrop::new(unsafe { Arc::from_inner(b.inner) }) > + .deref() > + .clone() > + } > +} > + > +impl<T: ?Sized> Deref for ArcBorrow<'_, T> { > + type Target = T; > + > + fn deref(&self) -> &Self::Target { > + // SAFETY: By the type invariant, the underlying object is still alive with no mutable > + // references to it, so it is safe to create a shared reference. > + unsafe { &self.inner.as_ref().data } > + } > +} > -- > 2.34.1 >
Hi, On Mon, Jan 16, 2023 at 10:07:36PM +0000, Gary Guo wrote: > On Wed, 4 Jan 2023 17:06:50 +0100 > Emilio Cobos Álvarez <emilio@crisal.io> wrote: > > > Sorry for the drive-by comment, but maybe it saves some work. > > > > On 1/4/23 16:29, Wedson Almeida Filho wrote: > > > On Sat, 31 Dec 2022 at 19:43, Gary Guo <gary@garyguo.net> wrote: > > >> > > >> On Wed, 28 Dec 2022 06:03:43 +0000 > > >> Wedson Almeida Filho <wedsonaf@gmail.com> wrote: > > >>> +pub struct ArcBorrow<'a, T: ?Sized + 'a> { > > >>> + inner: NonNull<ArcInner<T>>, > > >>> + _p: PhantomData<&'a ()>, > > >>> +} > > >>> + > > >>> +impl<T: ?Sized> Clone for ArcBorrow<'_, T> { > > >>> + fn clone(&self) -> Self { > > >>> + *self > > >>> + } > > >>> +} > > >>> + > > >>> +impl<T: ?Sized> Copy for ArcBorrow<'_, T> {} > > >> > > >> Couldn't this just be derived `Clone` and `Copy`? > > > > > > Indeed. I'll send a v2 with this. > > > > I'm not sure this is true. Deriving will add the T: Copy and T: Clone > > bound, which I think is not what you want here. > > > > i.e., I assume you want an ArcBorrow to be Copy even if the underlying T > > is not. > > Thanks for pointing out, I neglected that. > Somehow I run into this code again, and after a few thoughts, I'm wondering: isn't ArcBorrow just &ArcInner<T>? I've tried the following diff, and it seems working. The better parts are 1) #[derive(Clone, Copy)] works and 2) I'm able to remove a few code including one "unsafe" in ArcBorrow::deref(). But sure, more close look is needed. Thoughts? Regards, Boqun > In this case: > > Reviewed-by: Gary Guo <gary@garyguo.net> --------------------------------->8 diff --git a/rust/kernel/sync/arc.rs b/rust/kernel/sync/arc.rs index ff73f9240ca1..48f919878f44 100644 --- a/rust/kernel/sync/arc.rs +++ b/rust/kernel/sync/arc.rs @@ -185,7 +185,7 @@ impl<T: ?Sized> Arc<T> { // SAFETY: The constraint that the lifetime of the shared reference must outlive that of // the returned `ArcBorrow` ensures that the object remains alive and that no mutable // reference can be created. - unsafe { ArcBorrow::new(self.ptr) } + ArcBorrow(unsafe { self.ptr.as_ref() }) } } @@ -298,52 +298,25 @@ impl<T: ?Sized> From<Pin<UniqueArc<T>>> for Arc<T> { /// let obj = Arc::try_new(Example { a: 10, b: 20 })?; /// obj.as_arc_borrow().use_reference(); /// ``` -pub struct ArcBorrow<'a, T: ?Sized + 'a> { - inner: NonNull<ArcInner<T>>, - _p: PhantomData<&'a ()>, -} +#[derive(Clone, Copy)] +pub struct ArcBorrow<'a, T: ?Sized>(&'a ArcInner<T>); // This is to allow [`ArcBorrow`] (and variants) to be used as the type of `self`. impl<T: ?Sized> core::ops::Receiver for ArcBorrow<'_, T> {} // This is to allow `ArcBorrow<U>` to be dispatched on when `ArcBorrow<T>` can be coerced into // `ArcBorrow<U>`. -impl<T: ?Sized + Unsize<U>, U: ?Sized> core::ops::DispatchFromDyn<ArcBorrow<'_, U>> - for ArcBorrow<'_, T> +impl<'a, T: ?Sized + Unsize<U>, U: ?Sized> core::ops::DispatchFromDyn<ArcBorrow<'a, U>> + for ArcBorrow<'a, T> { } -impl<T: ?Sized> Clone for ArcBorrow<'_, T> { - fn clone(&self) -> Self { - *self - } -} - -impl<T: ?Sized> Copy for ArcBorrow<'_, T> {} - -impl<T: ?Sized> ArcBorrow<'_, T> { - /// Creates a new [`ArcBorrow`] instance. - /// - /// # Safety - /// - /// Callers must ensure the following for the lifetime of the returned [`ArcBorrow`] instance: - /// 1. That `inner` remains valid; - /// 2. That no mutable references to `inner` are created. - unsafe fn new(inner: NonNull<ArcInner<T>>) -> Self { - // INVARIANT: The safety requirements guarantee the invariants. - Self { - inner, - _p: PhantomData, - } - } -} - impl<T: ?Sized> From<ArcBorrow<'_, T>> for Arc<T> { fn from(b: ArcBorrow<'_, T>) -> Self { // SAFETY: The existence of `b` guarantees that the refcount is non-zero. `ManuallyDrop` // guarantees that `drop` isn't called, so it's ok that the temporary `Arc` doesn't own the // increment. - ManuallyDrop::new(unsafe { Arc::from_inner(b.inner) }) + ManuallyDrop::new(unsafe { Arc::from_inner(b.0.into()) }) .deref() .clone() } @@ -353,9 +326,7 @@ impl<T: ?Sized> Deref for ArcBorrow<'_, T> { type Target = T; fn deref(&self) -> &Self::Target { - // SAFETY: By the type invariant, the underlying object is still alive with no mutable - // references to it, so it is safe to create a shared reference. - unsafe { &self.inner.as_ref().data } + &self.0.data } }
diff --git a/rust/kernel/sync.rs b/rust/kernel/sync.rs index 39b379dd548f..5de03ea83ea1 100644 --- a/rust/kernel/sync.rs +++ b/rust/kernel/sync.rs @@ -7,4 +7,4 @@ mod arc; -pub use arc::Arc; +pub use arc::{Arc, ArcBorrow}; diff --git a/rust/kernel/sync/arc.rs b/rust/kernel/sync/arc.rs index dbc7596cc3ce..f68bfc02c81a 100644 --- a/rust/kernel/sync/arc.rs +++ b/rust/kernel/sync/arc.rs @@ -19,6 +19,7 @@ use crate::{bindings, error::Result, types::Opaque}; use alloc::boxed::Box; use core::{ marker::{PhantomData, Unsize}, + mem::ManuallyDrop, ops::Deref, ptr::NonNull, }; @@ -164,6 +165,18 @@ impl<T: ?Sized> Arc<T> { _p: PhantomData, } } + + /// Returns an [`ArcBorrow`] from the given [`Arc`]. + /// + /// This is useful when the argument of a function call is an [`ArcBorrow`] (e.g., in a method + /// receiver), but we have an [`Arc`] instead. Getting an [`ArcBorrow`] is free when optimised. + #[inline] + pub fn as_arc_borrow(&self) -> ArcBorrow<'_, T> { + // SAFETY: The constraint that the lifetime of the shared reference must outlive that of + // the returned `ArcBorrow` ensures that the object remains alive and that no mutable + // reference can be created. + unsafe { ArcBorrow::new(self.ptr) } + } } impl<T: ?Sized> Deref for Arc<T> { @@ -208,3 +221,87 @@ impl<T: ?Sized> Drop for Arc<T> { } } } + +/// A borrowed reference to an [`Arc`] instance. +/// +/// For cases when one doesn't ever need to increment the refcount on the allocation, it is simpler +/// to use just `&T`, which we can trivially get from an `Arc<T>` instance. +/// +/// However, when one may need to increment the refcount, it is preferable to use an `ArcBorrow<T>` +/// over `&Arc<T>` because the latter results in a double-indirection: a pointer (shared reference) +/// to a pointer (`Arc<T>`) to the object (`T`). An [`ArcBorrow`] eliminates this double +/// indirection while still allowing one to increment the refcount and getting an `Arc<T>` when/if +/// needed. +/// +/// # Invariants +/// +/// There are no mutable references to the underlying [`Arc`], and it remains valid for the +/// lifetime of the [`ArcBorrow`] instance. +/// +/// # Example +/// +/// ``` +/// use crate::sync::{Arc, ArcBorrow}; +/// +/// struct Example; +/// +/// fn do_something(e: ArcBorrow<'_, Example>) -> Arc<Example> { +/// e.into() +/// } +/// +/// let obj = Arc::try_new(Example)?; +/// let cloned = do_something(obj.as_arc_borrow()); +/// +/// // Assert that both `obj` and `cloned` point to the same underlying object. +/// assert!(core::ptr::eq(&*obj, &*cloned)); +/// ``` +pub struct ArcBorrow<'a, T: ?Sized + 'a> { + inner: NonNull<ArcInner<T>>, + _p: PhantomData<&'a ()>, +} + +impl<T: ?Sized> Clone for ArcBorrow<'_, T> { + fn clone(&self) -> Self { + *self + } +} + +impl<T: ?Sized> Copy for ArcBorrow<'_, T> {} + +impl<T: ?Sized> ArcBorrow<'_, T> { + /// Creates a new [`ArcBorrow`] instance. + /// + /// # Safety + /// + /// Callers must ensure the following for the lifetime of the returned [`ArcBorrow`] instance: + /// 1. That `inner` remains valid; + /// 2. That no mutable references to `inner` are created. + unsafe fn new(inner: NonNull<ArcInner<T>>) -> Self { + // INVARIANT: The safety requirements guarantee the invariants. + Self { + inner, + _p: PhantomData, + } + } +} + +impl<T: ?Sized> From<ArcBorrow<'_, T>> for Arc<T> { + fn from(b: ArcBorrow<'_, T>) -> Self { + // SAFETY: The existence of `b` guarantees that the refcount is non-zero. `ManuallyDrop` + // guarantees that `drop` isn't called, so it's ok that the temporary `Arc` doesn't own the + // increment. + ManuallyDrop::new(unsafe { Arc::from_inner(b.inner) }) + .deref() + .clone() + } +} + +impl<T: ?Sized> Deref for ArcBorrow<'_, T> { + type Target = T; + + fn deref(&self) -> &Self::Target { + // SAFETY: By the type invariant, the underlying object is still alive with no mutable + // references to it, so it is safe to create a shared reference. + unsafe { &self.inner.as_ref().data } + } +}