From nobody Sun Feb 8 12:58:11 2026 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 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="Lx9lCrXp" 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-Google-Smtp-Source: AGHT+IFiYyFQaewsKgwunqVgN/Q4+dzRP4xv9pcu+Nd9dtD4foHScKE6rWECzsn9S/zEpK+R9YUX8Wd/ckVSDAM= 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 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable 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 Reviewed-by: Benno Lossin --- 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, } =20 +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_ra= w`], and the `Arc` must + /// not yet have been destroyed. + unsafe fn container_of(ptr: *const T) -> NonNull> { + let refcount_layout =3D Layout::new::(); + // SAFETY: The caller guarantees that the pointer is valid. + let val_layout =3D Layout::for_value(unsafe { &*ptr }); + // SAFETY: We're computing the layout of a real struct that existe= d when compiling this + // binary, so its layout is not so large that it can trigger arith= metic overflow. + let val_offset =3D unsafe { refcount_layout.extend(val_layout).unw= rap_unchecked().1 }; + + // Pointer casts leave the metadata unchanged. This is okay becaus= e 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 =3D ptr as *const ArcInner; + + // SAFETY: The pointer is in-bounds of an allocation both before a= nd after offsetting the + // pointer, since it originates from a previous call to `Arc::into= _raw` on an `Arc` that is + // still valid. + let ptr =3D unsafe { ptr.byte_sub(val_offset) }; + + // SAFETY: The pointer can't be null since you can't have an `ArcI= nner` 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 {} =20 @@ -232,27 +265,13 @@ pub fn into_raw(self) -> *const T { /// `ptr` must have been returned by a previous call to [`Arc::into_ra= w`]. 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 =3D Layout::new::(); - // SAFETY: The caller guarantees that the pointer is valid. - let val_layout =3D Layout::for_value(unsafe { &*ptr }); - // SAFETY: We're computing the layout of a real struct that existe= d when compiling this - // binary, so its layout is not so large that it can trigger arith= metic overflow. - let val_offset =3D unsafe { refcount_layout.extend(val_layout).unw= rap_unchecked().1 }; - - // Pointer casts leave the metadata unchanged. This is okay becaus= e 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 =3D ptr as *const ArcInner; - - // SAFETY: The pointer is in-bounds of an allocation both before a= nd after offsetting the - // pointer, since it originates from a previous call to `Arc::into= _raw` and is still valid. - let ptr =3D 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 =3D unsafe { ArcInner::container_of(ptr) }; =20 // 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) } } =20 /// 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 de= constructed with + /// [`Arc::into_raw`]. + /// + /// # Safety + /// + /// * The provided pointer must originate from a call to [`Arc::into_r= aw`]. + /// * 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 =3D 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 th= at would involve a + // `UniqueArc`. + unsafe { Self::new(ptr) } + } } =20 impl From> for Arc { --=20 2.44.0.rc1.240.g4c46232300-goog From nobody Sun Feb 8 12:58:11 2026 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 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="S+miCPkP" 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-Google-Smtp-Source: AGHT+IGKoKzlbJKruBGsjpfwCKBmrzAFn4hmSUJpkOs2Es3HUYosdX9GWxeB7n2Z942JAX1X5RNnM+S3wHhiDuU= 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 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable 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 i= s not unique. + /// + /// When this destroys the `Arc`, it does so while properly avoiding r= aces. 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 disa= ble the destructor. + let me =3D ManuallyDrop::new(self); + // SAFETY: We own a refcount, so the pointer is still valid. + let refcount =3D 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 =3D unsafe { bindings::refcount_dec_and_test(refcount)= }; + if is_zero { + // SAFETY: We have exclusive access to the arc, so we can perf= orm 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 + } + } } =20 impl ForeignOwnable for Arc { --=20 2.44.0.rc1.240.g4c46232300-goog