From patchwork Wed Feb 28 13:00:34 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Alice Ryhl X-Patchwork-Id: 207855 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:a05:7300:a81b:b0:108:e6aa:91d0 with SMTP id bq27csp3334772dyb; Wed, 28 Feb 2024 05:11:55 -0800 (PST) X-Forwarded-Encrypted: i=3; AJvYcCXFGj8AusvgYplRFCUmJXj9gTrFvvEpQhDz8SHTvCSk2h03jizMavhKwzyj1mZqywqTbjad5kWFGJMD0LMHPQCwynZuLQ== X-Google-Smtp-Source: AGHT+IEfhVg7o7fcgTQ2HqgtWqEsOZkA9lxCUM8SYAIbyCn3Ws0B2UOhMMNvOty/uZEXmkMc4WQr X-Received: by 2002:a05:6a20:c78f:b0:1a0:e189:8568 with SMTP id hk15-20020a056a20c78f00b001a0e1898568mr3938998pzb.15.1709125915249; Wed, 28 Feb 2024 05:11:55 -0800 (PST) ARC-Seal: i=2; a=rsa-sha256; t=1709125915; cv=pass; d=google.com; s=arc-20160816; b=YyiSYpQlfI8WngoIf1HkbeZQ1pvH/n4Kgdlih63jzejdjtKwF4bmimSdoFY/jqt8x1 Jt71u2WKcwX3WN+7NQjO9Su1QseiMENh7xSEGHtETmcswBqnjbSnl76uR0aG6kPNAtRf XPwAkf6I/1XxYaiIvefD2328ykKZkEOBRSmFDFSN20rWjawQpUerPa3A5qiQ3aZH1Gbs uX0QeTBomrxsNsPBJ1D04/UspbUkEQeLRgFHWuofsycJkwml0elmTFnmKfhyxiHfmmrt 612OCc+l6R07/kas6SibKqGyxJoBoY0RMSQW6HqyowX9nUIKSYFlCvvKpKmFg0VhI8/p yetg== ARC-Message-Signature: i=2; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=arc-20160816; h=cc:to:from:subject:message-id:references:mime-version :list-unsubscribe:list-subscribe:list-id:precedence:in-reply-to:date :dkim-signature; bh=Q3wB+zOphNyP6hUF4yf4aDnoGW0BiDCeUW7QkKdL2gU=; fh=uiz2HCzjZXSFTecY0fR/uKnepY0M3MRI1U1u4ReERu4=; b=WLkX4nBQTYkZyIhMKk/ynyV8LbkHoWsRNmY2dj2Liqr2P5jaMxUdrJwK7gHxcvGGOw hT/9nh+uuP973VOvEaSqPF7TRnytIaerZUNEMcsmw+ju/XonYpvSePf7cCnpTEZUM5Aq KXxI9JdCVbvgjp1Ig3u4hBXds6wFdBXkOPrBExPkwQMKDJy+mvlLiz92ciLEec0XEj6a +6nEowR4vq3VlN4Bn0lvtAq/D5wdhyYO3epompnhcocf00/0VU2N1w/l66uZWuO7ZI3m JL9cEn7lPWuO9lYwy0Maf0YJnH2MI58Q4fwKJZOcfSTXa+d9prO/dgD20ET4pclejuFa iDFw==; dara=google.com ARC-Authentication-Results: i=2; mx.google.com; dkim=pass header.i=@google.com header.s=20230601 header.b=Lx9lCrXp; arc=pass (i=1 spf=pass spfdomain=flex--aliceryhl.bounces.google.com dkim=pass dkdomain=google.com dmarc=pass fromdomain=google.com); spf=pass (google.com: domain of linux-kernel+bounces-85050-ouuuleilei=gmail.com@vger.kernel.org designates 2604:1380:40f1:3f00::1 as permitted sender) smtp.mailfrom="linux-kernel+bounces-85050-ouuuleilei=gmail.com@vger.kernel.org"; dmarc=pass (p=REJECT sp=REJECT dis=NONE) header.from=google.com Received: from sy.mirrors.kernel.org (sy.mirrors.kernel.org. [2604:1380:40f1:3f00::1]) by mx.google.com with ESMTPS id j2-20020a632302000000b005dc905460d6si7370453pgj.315.2024.02.28.05.11.54 for (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Wed, 28 Feb 2024 05:11:55 -0800 (PST) Received-SPF: pass (google.com: domain of linux-kernel+bounces-85050-ouuuleilei=gmail.com@vger.kernel.org designates 2604:1380:40f1:3f00::1 as permitted sender) client-ip=2604:1380:40f1:3f00::1; Authentication-Results: mx.google.com; dkim=pass header.i=@google.com header.s=20230601 header.b=Lx9lCrXp; arc=pass (i=1 spf=pass spfdomain=flex--aliceryhl.bounces.google.com dkim=pass dkdomain=google.com dmarc=pass fromdomain=google.com); spf=pass (google.com: domain of linux-kernel+bounces-85050-ouuuleilei=gmail.com@vger.kernel.org designates 2604:1380:40f1:3f00::1 as permitted sender) smtp.mailfrom="linux-kernel+bounces-85050-ouuuleilei=gmail.com@vger.kernel.org"; dmarc=pass (p=REJECT sp=REJECT dis=NONE) header.from=google.com Received: from smtp.subspace.kernel.org (wormhole.subspace.kernel.org [52.25.139.140]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by sy.mirrors.kernel.org (Postfix) with ESMTPS id 349C2B23899 for ; Wed, 28 Feb 2024 13:01:27 +0000 (UTC) Received: from localhost.localdomain (localhost.localdomain [127.0.0.1]) by smtp.subspace.kernel.org (Postfix) with ESMTP id DFE5F14EFE0; Wed, 28 Feb 2024 13:00:52 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="Lx9lCrXp" Received: from mail-yb1-f201.google.com (mail-yb1-f201.google.com [209.85.219.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 8B32A149E0B for ; Wed, 28 Feb 2024 13:00:47 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.219.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1709125249; cv=none; b=P0gEoX01hUFUmYVbvsWRlvj3vlSWncVgHRgj3N47M4uqo0sC0ux0tqUZbG7yFzTA8263IvVaIrMMwRctJUiyBMt51/uonyUNrqAs626fncYhELnCTAMcAD+l6tAUZwOI+5F/EQTgM5ob/0TSOr4Jty+b/8WGAkMZ7kIIZO0NetE= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1709125249; c=relaxed/simple; bh=2qc0OjZbMyqS455P5x7XgjO6nV3ryL8hVj/+fIZPe98=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=At6fdQ57dpqU+j7ogGyki1FjxQrGurxedexgAzPe0FCw2Q7OcGs1xFsyDaa0y0oGUmGjn2w/gV2XJK24wPtHxaTNN/AcODo7Igt4tNtNhDnL/yOr+ssMqK5NAhITGI2Eu+dMCAQLhTQGVFBb7y1J13NEkd7BZ3XHAhPFA8XCe9A= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=Lx9lCrXp; arc=none smtp.client-ip=209.85.219.201 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com Received: by mail-yb1-f201.google.com with SMTP id 3f1490d57ef6-dc6ade10cb8so1857487276.0 for ; Wed, 28 Feb 2024 05:00:47 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1709125246; x=1709730046; darn=vger.kernel.org; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:from:to:cc:subject:date:message-id:reply-to; bh=Q3wB+zOphNyP6hUF4yf4aDnoGW0BiDCeUW7QkKdL2gU=; b=Lx9lCrXp2HTJ/34cO8hUgOhcQUwnNy+sJp/CwbA9uAzPmEMJkUnK3CaPxyL7g/6TI9 MXxtV5tPWwbDnmBHD1KBMkd0TQHxiXe6bHfFiWvD+xnyl9QB1QGcSCelkcfCHLYKVCt0 JPdLg9xXs6BtfmxYDRp7Cl2OJaYXFk9bwzlxeToPnQSgU7XC6neXeD1ntai4kzBq6CvX YYvG5KBshsIfOgSFTHEYeDsagRV9fPuQllfxcm5IAQkUWZc1ahcNG8DiOHl/G5eboMq5 RnsyCPKjkbakFO+M0+VzJtW4EDSov9NmNwLnM74FET9QwWkM0FKkWQreEbJQEj8i4R2O +WAg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1709125246; x=1709730046; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=Q3wB+zOphNyP6hUF4yf4aDnoGW0BiDCeUW7QkKdL2gU=; b=btEIQoqeM9tGxSORI2yZiA5pHslt28si0cg0ZCyVo5mYlWr5gbdZMY9SijMa1gtuLS 1RPRdoQJdtCbznqZxgrt2n7PHpME6GTOe+vWVjcyIlMsg4eabd29RMhKvodq6NOUUMZN V5VmFdxCNeF5gB7Qk00f3+RDJ6shKCBrBebuZbCm9r1lX1VuzxKojg3FsOwYi+xuXviM SRw+3LTnS/AYUXrlmLKzeFFsSZkxWqH5Sqq9NevswU+XIt/31pfHQkSjTz7GkLdV8I0m GhwV2bP/hJJnmiNr8T6mPnEGwP5bKk3nLYPreI01tAHChP3inoiEXN+Q1kwfInP2hgKH f+jQ== X-Forwarded-Encrypted: i=1; AJvYcCX/rNwgMwmxuMdQyIpO19H2sXADLBY6vR6KG3C7J1Qx0B4ROsf24BI9oZYoXu96y3LNWc4gbPNr6cWmrRpiXntLFfU7QgFLg38x89Qf X-Gm-Message-State: AOJu0YwKarQ7yk3v08A5r/6vhtPFcN9W1AJRs5/d0fkciRDr8zWbvuy4 5OZIw5CRVo/4y2S9WpFtrLnypnXi8pSkASR/6WYcproVcrk7lM/ZNEdlcrGKJ8e5MtMy+ycChg/ dz5A/e6ooqTPqgQ== X-Received: from aliceryhl2.c.googlers.com ([fda3:e722:ac3:cc00:68:949d:c0a8:572]) (user=aliceryhl job=sendgmr) by 2002:a05:6902:124b:b0:dc7:7655:46ce with SMTP id t11-20020a056902124b00b00dc7765546cemr717803ybu.2.1709125246533; Wed, 28 Feb 2024 05:00:46 -0800 (PST) Date: Wed, 28 Feb 2024 13:00:34 +0000 In-Reply-To: <20240228-arc-for-list-v2-0-ae93201426b4@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20240228-arc-for-list-v2-0-ae93201426b4@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=5861; i=aliceryhl@google.com; h=from:subject:message-id; bh=2qc0OjZbMyqS455P5x7XgjO6nV3ryL8hVj/+fIZPe98=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBl3y53emchCaCu7uFgmd7KKQwOA79SoPzWOeKWs 41D6I+qk4yJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZd8udwAKCRAEWL7uWMY5 RuEmD/sFXh4G73vd57SjB4S9hG1Y5Qj7hCC3LTdgCt3aM7beUA3bOnmMfmvlymQ++qSj+tirxrC vn1JM30JqLIJEIBbBCz5YUya1jjCHyDQY5GV1mzrxVo6kvtR1cK3/dHmf0rRBBbqDYFU3y7a94A n8KqlZ8BE6yME8/HUS5FBOQkhiU/X9tBbAL8RFo8afJfk5VyejmDzy2+3N7EORN38ltX9q9/Xgd IFw4SMU7OqOuGaPjKFTo0xin/RCvNQ9an3ZXDao3YbGGjSwPoZPnVoA+PXN07wRu/fuPrxkyWyI x9tFzTSNTmqj9O+JA4rbzywO1QV3ErEijzfJYAOolp7q2l5ztjqrMO5tddCoev2efz0TeYig5qk 2suf3d8jmihvNdD4GeideyqmQMqx9ptn0tiSiI7CeB3lStg4CpVzCZ2ju4bJFK1/fetI1GD5Q1m iEwZnmTdyY95uYchdhYIO8Lnl3PtHuwnNtgFGZxb7FF5QXVzHvnMmwzegscDg0obq6lO6ROzSv5 GSu0lWl5s1dA/mGRqK+rMoaeTVMwI3hqKbaZ8OjEJCKq/5Hhkhe51bMehjQwUsak1GJdRJBF46i nhbKIo8Rj4RF9dOZzvFyGUQu8cbYkw9rb/pWhoKW9MpLvcymZZeFQl+cF5RLnVMOefRYaC4Dw2Z i01fU9dvpVGvS1Q== X-Mailer: b4 0.13-dev-26615 Message-ID: <20240228-arc-for-list-v2-1-ae93201426b4@google.com> Subject: [PATCH v2 1/2] rust: sync: add `ArcBorrow::from_raw` From: Alice Ryhl To: Miguel Ojeda , Alex Gaynor , Wedson Almeida Filho , Boqun Feng , Gary Guo , " =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= " , Benno Lossin , Andreas Hindborg Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, Alice Ryhl X-getmail-retrieved-from-mailbox: INBOX X-GMAIL-THRID: 1792148416073522682 X-GMAIL-MSGID: 1792148416073522682 Allows access to a value in an `Arc` that is currently held as a raw pointer due to use of `Arc::into_raw`, without destroying or otherwise consuming that raw pointer. This is a dependency of the linked list that Rust Binder uses. The linked list uses this method when iterating over the linked list. Signed-off-by: Alice Ryhl --- rust/kernel/sync/arc.rs | 76 +++++++++++++++++++++++++++++++++++++------------ 1 file changed, 58 insertions(+), 18 deletions(-) diff --git a/rust/kernel/sync/arc.rs b/rust/kernel/sync/arc.rs index 7d4c4bf58388..53addb8876c2 100644 --- a/rust/kernel/sync/arc.rs +++ b/rust/kernel/sync/arc.rs @@ -137,6 +137,39 @@ struct ArcInner { data: T, } +impl ArcInner { + /// Converts a pointer to the contents of an [`Arc`] into a pointer to the [`ArcInner`]. + /// + /// # Safety + /// + /// `ptr` must have been returned by a previous call to [`Arc::into_raw`], and the `Arc` must + /// not yet have been destroyed. + unsafe fn container_of(ptr: *const T) -> NonNull> { + let refcount_layout = Layout::new::(); + // SAFETY: The caller guarantees that the pointer is valid. + let val_layout = Layout::for_value(unsafe { &*ptr }); + // SAFETY: We're computing the layout of a real struct that existed when compiling this + // binary, so its layout is not so large that it can trigger arithmetic overflow. + let val_offset = unsafe { refcount_layout.extend(val_layout).unwrap_unchecked().1 }; + + // Pointer casts leave the metadata unchanged. This is okay because the metadata of `T` and + // `ArcInner` is the same since `ArcInner` is a struct with `T` as its last field. + // + // This is documented at: + // . + let ptr = ptr as *const ArcInner; + + // SAFETY: The pointer is in-bounds of an allocation both before and after offsetting the + // pointer, since it originates from a previous call to `Arc::into_raw` on an `Arc` that is + // still valid. + let ptr = unsafe { ptr.byte_sub(val_offset) }; + + // SAFETY: The pointer can't be null since you can't have an `ArcInner` value at the null + // address. + unsafe { NonNull::new_unchecked(ptr.cast_mut()) } + } +} + // This is to allow [`Arc`] (and variants) to be used as the type of `self`. impl core::ops::Receiver for Arc {} @@ -232,27 +265,13 @@ pub fn into_raw(self) -> *const T { /// `ptr` must have been returned by a previous call to [`Arc::into_raw`]. Additionally, it /// must not be called more than once for each previous call to [`Arc::into_raw`]. pub unsafe fn from_raw(ptr: *const T) -> Self { - let refcount_layout = Layout::new::(); - // SAFETY: The caller guarantees that the pointer is valid. - let val_layout = Layout::for_value(unsafe { &*ptr }); - // SAFETY: We're computing the layout of a real struct that existed when compiling this - // binary, so its layout is not so large that it can trigger arithmetic overflow. - let val_offset = unsafe { refcount_layout.extend(val_layout).unwrap_unchecked().1 }; - - // Pointer casts leave the metadata unchanged. This is okay because the metadata of `T` and - // `ArcInner` is the same since `ArcInner` is a struct with `T` as its last field. - // - // This is documented at: - // . - let ptr = ptr as *const ArcInner; - - // SAFETY: The pointer is in-bounds of an allocation both before and after offsetting the - // pointer, since it originates from a previous call to `Arc::into_raw` and is still valid. - let ptr = unsafe { ptr.byte_sub(val_offset) }; + // SAFETY: The caller promises that this pointer originates from a call to `into_raw` on an + // `Arc` that is still valid. + let ptr = unsafe { ArcInner::container_of(ptr) }; // SAFETY: By the safety requirements we know that `ptr` came from `Arc::into_raw`, so the // reference count held then will be owned by the new `Arc` object. - unsafe { Self::from_inner(NonNull::new_unchecked(ptr.cast_mut())) } + unsafe { Self::from_inner(ptr) } } /// Returns an [`ArcBorrow`] from the given [`Arc`]. @@ -453,6 +472,27 @@ unsafe fn new(inner: NonNull>) -> Self { _p: PhantomData, } } + + /// Creates an [`ArcBorrow`] to an [`Arc`] that has previously been deconstructed with + /// [`Arc::into_raw`]. + /// + /// # Safety + /// + /// * The provided pointer must originate from a call to [`Arc::into_raw`]. + /// * For the duration of the lifetime annotated on this `ArcBorrow`, the reference count must + /// not hit zero. + /// * For the duration of the lifetime annotated on this `ArcBorrow`, there must not be a + /// [`UniqueArc`] reference to this value. + pub unsafe fn from_raw(ptr: *const T) -> Self { + // SAFETY: The caller promises that this pointer originates from a call to `into_raw` on an + // `Arc` that is still valid. + let ptr = unsafe { ArcInner::container_of(ptr) }; + + // SAFETY: The caller promises that the value remains valid since the reference count must + // not hit zero, and no mutable reference will be created since that would involve a + // `UniqueArc`. + unsafe { Self::new(ptr) } + } } impl From> for Arc { From patchwork Wed Feb 28 13:00:35 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Alice Ryhl X-Patchwork-Id: 207851 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:a05:7300:a81b:b0:108:e6aa:91d0 with SMTP id bq27csp3327768dyb; Wed, 28 Feb 2024 05:02:08 -0800 (PST) X-Forwarded-Encrypted: i=3; AJvYcCWqBZC3hVDC5ht/CTLgCiSD5e2JDeXgpX/vl+MzbG92VVWWew25UDb0gqzb911OR2joJnPcrMO7iJMFOXN90coolEWECw== X-Google-Smtp-Source: AGHT+IETg0c7Smm/K8pJXUPwBpJulr2iIDe/LZrYiAQEPAefFlZXlrdxiI1TcWQecEJXuVZpXT08 X-Received: by 2002:a92:c80e:0:b0:365:149:d09e with SMTP id v14-20020a92c80e000000b003650149d09emr14673566iln.10.1709125327955; Wed, 28 Feb 2024 05:02:07 -0800 (PST) ARC-Seal: i=2; a=rsa-sha256; t=1709125327; cv=pass; d=google.com; s=arc-20160816; b=iP1c3xKPFeTLb1s51ROVzuRGnOPZVio+FxLaxcvKI945MjyxYgYPspi9wU9jKQcXVg CHuQPtdZaoPpU7yogsNOjtD+cbsz4gVtun2Wrb5Oz0W70UqKbndCLz0Rtu1dQl/NF8ox /IpftwYEKJYDU/ZKDjU7SnydfaFRQ4zBWD6Zf8HL4O3s3KuLdnX6jMILDJrxTDIrz2px FcZVHb5MorRGF/Fb7sDFtizU6aFH+3ObDCEMhYpErr20TA+8x90jI13qoHxwlqVVYXlj E4O0ASH6l+KBwSTHrvLfwbyTLluOB8Cy8CFBn16KL+RcyLDanoFQyp5mgHDkIrlRbIrC fjmw== ARC-Message-Signature: i=2; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=arc-20160816; h=cc:to:from:subject:message-id:references:mime-version :list-unsubscribe:list-subscribe:list-id:precedence:in-reply-to:date :dkim-signature; bh=58MmYrc9jKoQcHyoSO2oYsUT2tLUNZNAYGFscRmlNOo=; fh=DSx+EGDHMyLa1D+LdiqE7NWsSXEGvjJbyUmrBvWMTW8=; b=CdS9k4dIiOC0951E8WjhTTOJVFsZRzZGnCJTEnWhikR/z530wydCwkBypmRE0MT1lX 35haJkUuOonDXK5ef6eH0rctD3AoN1uiGBKvGFi/v/1gZXYFQunP7LHA8ev4Ho4Agwle KSBjwOMznjCgBpEL+9AfoQjvgfWd0HyDyTY6VbDLJa8uhpK7OIrY/Boi38Vm4EHgdsLN ExZ2de5FFsqlU5kR04zpOKHNOhBDPjBpCscnX+nbRRLPRiGgPjDG8hqJnQ2LhG/USqrS q4SRjGJS9rP/4fvZAGkunstOOYvCQLzJGTcqzo6LQjPKe5+r7W/LPmRm5iadKgi72BhK IDlw==; dara=google.com ARC-Authentication-Results: i=2; mx.google.com; dkim=pass header.i=@google.com header.s=20230601 header.b=S+miCPkP; arc=pass (i=1 spf=pass spfdomain=flex--aliceryhl.bounces.google.com dkim=pass dkdomain=google.com dmarc=pass fromdomain=google.com); spf=pass (google.com: domain of linux-kernel+bounces-85051-ouuuleilei=gmail.com@vger.kernel.org designates 139.178.88.99 as permitted sender) smtp.mailfrom="linux-kernel+bounces-85051-ouuuleilei=gmail.com@vger.kernel.org"; dmarc=pass (p=REJECT sp=REJECT dis=NONE) header.from=google.com Received: from sv.mirrors.kernel.org (sv.mirrors.kernel.org. [139.178.88.99]) by mx.google.com with ESMTPS id h2-20020a056e021b8200b003637eb0c936si3112900ili.197.2024.02.28.05.02.07 for (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Wed, 28 Feb 2024 05:02:07 -0800 (PST) Received-SPF: pass (google.com: domain of linux-kernel+bounces-85051-ouuuleilei=gmail.com@vger.kernel.org designates 139.178.88.99 as permitted sender) client-ip=139.178.88.99; Authentication-Results: mx.google.com; dkim=pass header.i=@google.com header.s=20230601 header.b=S+miCPkP; arc=pass (i=1 spf=pass spfdomain=flex--aliceryhl.bounces.google.com dkim=pass dkdomain=google.com dmarc=pass fromdomain=google.com); spf=pass (google.com: domain of linux-kernel+bounces-85051-ouuuleilei=gmail.com@vger.kernel.org designates 139.178.88.99 as permitted sender) smtp.mailfrom="linux-kernel+bounces-85051-ouuuleilei=gmail.com@vger.kernel.org"; dmarc=pass (p=REJECT sp=REJECT dis=NONE) header.from=google.com Received: from smtp.subspace.kernel.org (wormhole.subspace.kernel.org [52.25.139.140]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by sv.mirrors.kernel.org (Postfix) with ESMTPS id AF25A2894F1 for ; Wed, 28 Feb 2024 13:01:36 +0000 (UTC) Received: from localhost.localdomain (localhost.localdomain [127.0.0.1]) by smtp.subspace.kernel.org (Postfix) with ESMTP id 1764F14F992; Wed, 28 Feb 2024 13:00:55 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="S+miCPkP" Received: from mail-yb1-f202.google.com (mail-yb1-f202.google.com [209.85.219.202]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 65DAC14D422 for ; Wed, 28 Feb 2024 13:00:50 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.219.202 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1709125252; cv=none; b=nrqrBHnhvv32CqtLczGCcYBe/gDN93emWSoAo0JrjOaC4W17Yz1KfK1GeBsTuCfq1VCyo/qcB9rvZQLVYi+mXs9F00EdAxnVl4JXKnZ1anUuY1t++o442Svh9ElAVOFNUR6Cz7uOZWoa1UXlEVXsUCSwMQ/BcgJhmln7iGTtUB0= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1709125252; c=relaxed/simple; bh=Nj37dTNA+S1wcq1tppsexfMfgfaLNdIQ1D2ci40uNXw=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=TU86Q15GzvP1PotfOIxOVzy6pAWv+x5eD8ISuYgtO45gHbHXcf6f5ss9jHNnUhK+p8RuL6QU9Q5pIvWX7OYAcMyLUR3JuqoRCvmI+eitXpmK4zMW7hoFirmZTOtkTd58Jr2Ny4oQP4nYK8nhKipUCJHOVWuuYO2kLT/ObwVm6KQ= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=S+miCPkP; arc=none smtp.client-ip=209.85.219.202 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com Received: by mail-yb1-f202.google.com with SMTP id 3f1490d57ef6-dc6ceade361so9923112276.0 for ; Wed, 28 Feb 2024 05:00:50 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1709125249; x=1709730049; darn=vger.kernel.org; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:from:to:cc:subject:date:message-id:reply-to; bh=58MmYrc9jKoQcHyoSO2oYsUT2tLUNZNAYGFscRmlNOo=; b=S+miCPkPK6yqmfN+0CLQdgD2xL+UqFqQBC28VdnTHZ23A3VcR0yJTfnFbtBhUeX8UF whtjI+mJDxyq+oSbG4s9tE3WB76ZjM/vFp4j1hyn8l6HX0TMNyKVe5EDH9BLiAQOMcLx YU3S38fiJ/T0xQKf5itXoUqAsT8ocCIDxxEVU7/6YqaTKouSshIPeYUcIYACC9ZQcn7U SU1NFTIpEB8tGFPCKN3Z62YnN7UUyLoVQ7VwQhfXjg2RHdhKjxL6R52pb5a+IA1clBpD u6S5IjNsBaNPUAQgwmcAoNTtCJMX/BNWqZTH2yZmkhWiwn6HCdK67QWPHM/c6xObCVDt gkdg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1709125249; x=1709730049; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=58MmYrc9jKoQcHyoSO2oYsUT2tLUNZNAYGFscRmlNOo=; b=d2tNn7p9dASxePm9qs2akJ4poYzLOoT96361dEBBETx9UGd5YATjrWS194iRG26aKI RgN0BMqzFJbD7EUM8PRSowHZcljcff60l1mg36RBxshwBQvODhjbhnLO1AvnbuGP4pLI fpGLSs9YesR6ukSghqCIy1j1z2J9cn++uVRmazAhjGLn8R5AqpzR3t1fk6hTHjb4X52k hkh15JTs0c8+s7bBhqsv+AeuXUKuXTgSlKZZywWAyWH9npeKU4QjWFR636S8cS9W6Pe/ FKizVyVoqfRznQM9j7/LKaX4BgHpejILPE+b2OKJVy+hnLA2QpbI2M3AABcBSsCjaPcC lvtA== X-Forwarded-Encrypted: i=1; AJvYcCVtbC29WbIBwGti7IprUAfiCt362xOMDTfUCfEYl7/CN+7FF6OzxsfhB7yqW3erhQfK0Ws3QKX+TbFfYhLHaHwx3UOLRTrocDmZoNCH X-Gm-Message-State: AOJu0YyvsOFa51bVDZZA+MDxrXrqBVz+sH93wKymXfYVoyjBJs/PCDLa 2SbaXN3lPfvuOq0cDtObQzHwjcrzhrc7oZnI6n6diIC6DPBfER3HZeyDqquPdgj4aJeWFVdPKcn SArqUBFXlvkiT9g== X-Received: from aliceryhl2.c.googlers.com ([fda3:e722:ac3:cc00:68:949d:c0a8:572]) (user=aliceryhl job=sendgmr) by 2002:a25:1f04:0:b0:dc7:68b5:4f21 with SMTP id f4-20020a251f04000000b00dc768b54f21mr612409ybf.9.1709125249379; Wed, 28 Feb 2024 05:00:49 -0800 (PST) Date: Wed, 28 Feb 2024 13:00:35 +0000 In-Reply-To: <20240228-arc-for-list-v2-0-ae93201426b4@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20240228-arc-for-list-v2-0-ae93201426b4@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=2504; i=aliceryhl@google.com; h=from:subject:message-id; bh=Nj37dTNA+S1wcq1tppsexfMfgfaLNdIQ1D2ci40uNXw=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBl3y547VYE127NHyhYdMBtASpkMLEEcq2SAKhmD bq3LPrMKZyJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZd8ueAAKCRAEWL7uWMY5 RrIAEACkCyxKP3rlLV9pBCpojwlEa4sTsFFQk5nneY/FauWA18/iVQXIAtRN0jXdwTC5KbYtQc0 TgEzmPSLrvmulGq703bQu5BXBbk1+5/eLIYRUTuKuc+VHHVdqvrFr8xYcNDkyKU8a9wtzy1xrpf fJV6DAfMTzjIsGEyHBdn5WPeW4baDdJH5VTvnUTceipJx/KeMsLbpI9+O5LV/l9AeO2R12svGDs cuyvLGdh5lGqvBq4dWZOAQQ/rh9YQqx0kjBvnmq5SIO4fwdWdDVFw7tMsG04GjJZc1syzfZ5lMW UoE4qEpa9RkDe+qjuKEYp8lnbE2Flep5Xkp2GwT6Jb5T1U7nctoSqXDbiI71ACIFuRaxUyc3iW0 XdM+M4BFxBArn5v3uI2Vt+E91a2Qy6MSMk1IFmlklvMMax69hU6Eg2KK3ZyQ8xj4QDYsC6K9bs7 RXGhegCFMlMNlkN37PQGH8gcjPXeF0I00BeCyhaeUbavoEBaUA89ugLeROc7LxiKrnpNAUEYGYe pV33/ylsz3e/LxKnhXl4bewu2h0W/YPhExKQHaLIiWbwkI14Ge1rS80TxnKoduj15gH3MkD1m1q QNVJaTtx5lSEw088ZDMl9/UQ6FCXz7+2kDq5PEVwn8SkhQJ2i80+n2bQ+ZkEYWx2l90FHTR/bTU ZomqEwmu5LoiAFA== X-Mailer: b4 0.13-dev-26615 Message-ID: <20240228-arc-for-list-v2-2-ae93201426b4@google.com> Subject: [PATCH v2 2/2] rust: sync: add `Arc::into_unique_or_drop` From: Alice Ryhl To: Miguel Ojeda , Alex Gaynor , Wedson Almeida Filho , Boqun Feng , Gary Guo , " =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= " , Benno Lossin , Andreas Hindborg Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, Alice Ryhl X-getmail-retrieved-from-mailbox: INBOX X-GMAIL-THRID: 1792147800256198700 X-GMAIL-MSGID: 1792147800256198700 Decrement the refcount of an `Arc`, but handle the case where it hits zero by taking ownership of the now-unique `Arc`, instead of destroying and deallocating it. This is a dependency of the linked list that Rust Binder uses. The linked list uses this method as part of its `ListArc` abstraction. Signed-off-by: Alice Ryhl --- rust/kernel/sync/arc.rs | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/rust/kernel/sync/arc.rs b/rust/kernel/sync/arc.rs index 53addb8876c2..df2dfe0de83c 100644 --- a/rust/kernel/sync/arc.rs +++ b/rust/kernel/sync/arc.rs @@ -290,6 +290,37 @@ pub fn as_arc_borrow(&self) -> ArcBorrow<'_, T> { pub fn ptr_eq(this: &Self, other: &Self) -> bool { core::ptr::eq(this.ptr.as_ptr(), other.ptr.as_ptr()) } + + /// Converts this [`Arc`] into a [`UniqueArc`], or destroys it if it is not unique. + /// + /// When this destroys the `Arc`, it does so while properly avoiding races. This means that + /// this method will never call the destructor of the value. + pub fn into_unique_or_drop(self) -> Option>> { + // We will manually manage the refcount in this method, so we disable the destructor. + let me = ManuallyDrop::new(self); + // SAFETY: We own a refcount, so the pointer is still valid. + let refcount = unsafe { me.ptr.as_ref() }.refcount.get(); + + // SAFETY: If the refcount reaches a non-zero value, then we have destroyed this `Arc` and + // will return without further touching the `Arc`. If the refcount reaches zero, then there + // are no other arcs, and we can create a `UniqueArc`. + let is_zero = unsafe { bindings::refcount_dec_and_test(refcount) }; + if is_zero { + // SAFETY: We have exclusive access to the arc, so we can perform unsynchronized + // accesses to the refcount. + unsafe { core::ptr::write(refcount, bindings::REFCOUNT_INIT(1)) }; + + // SAFETY: We own one refcount, so we can create a `UniqueArc`. It needs to be pinned, + // since an `Arc` is pinned. + unsafe { + Some(Pin::new_unchecked(UniqueArc { + inner: Arc::from_inner(me.ptr), + })) + } + } else { + None + } + } } impl ForeignOwnable for Arc {