From nobody Sun Feb 8 05:47:59 2026 Received: from mail-lf1-f74.google.com (mail-lf1-f74.google.com [209.85.167.74]) (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 A585D482D8 for ; Mon, 11 Mar 2024 16:08:32 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.167.74 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1710173315; cv=none; b=YzzUmT2WP/HwB5Mm9gizSmX7KNfPhLCncVwLhVlmU75npoDv3BdjCVTlzWIwXVQQxTbi7bkC4kfr9cMcJ0aY3ZPMPBL2l8t0PhSB9Uh4gHV/YaxqSL2iPJu8GLNNBdqVKhjnuyYn/LTpNZC49zSMeXVIZfNqLXpAtniael+haNc= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1710173315; c=relaxed/simple; bh=ybA3FjhWRG2ya5jZUlRwyys2swjjPxYnMn1ICqlxh7I=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=geT4sHkFWAxU+tge1N6ypgYsA5j0iEb30oMyfsP21KwEAmFApnh7GYC1snmtbq1uetrEjsyLylaq/hU6tR0H/j/wO0jFPIquXYfpVG0/YuL/gREaZKg5C1GtyN4IRCO7pcZMXMBYw8VXU3PFzDT5DQQj0zL0n9zHOVM/BtOxV1Y= 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=1AeZNPo7; arc=none smtp.client-ip=209.85.167.74 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="1AeZNPo7" Received: by mail-lf1-f74.google.com with SMTP id 2adb3069b0e04-5131aa087beso2687262e87.2 for ; Mon, 11 Mar 2024 09:08:32 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1710173311; x=1710778111; 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=WFhOHi9YbCrBYkKkhUSEcENknoxhZ94xXZCXy/0AOz0=; b=1AeZNPo7FPxcqkn6TYNRG/ihfUavljJTOq17SmbDKj+6gqk+oIYUVZVGMJNwhbpSgK ck3r3YB7tpxSdsw6yHA6OlRR3WHUrmIHrLH/r2kDff9rkEACHlg6EcwqTLL7ZdmBZLMG +supYnLiXM8fMcO4OC+eGPJ5XrJnK33C9aPOXWpQAG9rYURBR2OyY1+WPDFzHjd4YOQK 8SDTGcz3PULLHiZfKGy3cUiNPOmu1nyoj+1lydUnf93k+G3znFZp3PP1wXhSd4sJf22x wJvTg5mqJS7YUJGur3TBu6KFVYS068Oandouv7zdFhFerHlCGFgTpjzIteBg/eRBwf5I L3+Q== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1710173311; x=1710778111; 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=WFhOHi9YbCrBYkKkhUSEcENknoxhZ94xXZCXy/0AOz0=; b=JylILaes4bAnORcEw8kroiTU7mzHdVH7983HgoDcDqOkEKnqswc5OeYDJHyL7Lh2m0 DP96EIzlfJt3PcLD8FMQ5LYZnxCsveSwLiHdaWkJihYRx2doMiQLjOGHaJMphOzpJ/tZ Tty6MbJDfh4TEDrEzDobIhlDhHy0ui1rGwZu2iff9bo8qhKK3ukXtRU0BMdOqfB1Rm/1 VheXSVt8nkyk7/voUsziMG8sqSWJEbBjegCItlR6K+TsXHmGjUVfbPdLUqWyIswLGdUg lPAVVfjfPeUGhWc9VvauS3CR/AXj8oDZ4eaHFpNtfquif598E1bpHMtwCdBd29M3GmmS PgdQ== X-Forwarded-Encrypted: i=1; AJvYcCXu7FZLBQvcRWe0a6F7Emf5QjN+DMrzvMHiLBPNd5Fv0/BmFBL2P74UdkNJ/yXDiRRY5JnwrKE+Z8ubJCmyd0ceGWYW9QOwQ3k7lR/q X-Gm-Message-State: AOJu0Ywi2rLcheE66jxaTJRH48gOlZn1XPm4ftJH4Sy5uFRYRHhc4zuf Azg5Dr48TDX9O7rkIPkKeFp3pysCS1kHbUr6jMohWiGhzPo1IRlGeVj3zBeMh6K8zxrNT8pBkTU Hw/2xzCHMOlwBFg== X-Google-Smtp-Source: AGHT+IGcDgFawbpWrrBjGYWqlnWAXrsjov+pfSEbwfdjCV216E2thxSNwmF6c6IrtVLGlqxKSsuc9RKcq1uS7FI= X-Received: from aliceryhl2.c.googlers.com ([fda3:e722:ac3:cc00:68:949d:c0a8:572]) (user=aliceryhl job=sendgmr) by 2002:ac2:4bd5:0:b0:513:b230:e774 with SMTP id o21-20020ac24bd5000000b00513b230e774mr1423lfq.8.1710173310685; Mon, 11 Mar 2024 09:08:30 -0700 (PDT) Date: Mon, 11 Mar 2024 16:08:18 +0000 In-Reply-To: <20240311-arc-for-list-v3-0-cba1883c62eb@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20240311-arc-for-list-v3-0-cba1883c62eb@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=5909; i=aliceryhl@google.com; h=from:subject:message-id; bh=ybA3FjhWRG2ya5jZUlRwyys2swjjPxYnMn1ICqlxh7I=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBl7yx3gMm5R8xT/QFPz2PbANYf5w80xX5dYYrxT g+p894IqJOJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZe8sdwAKCRAEWL7uWMY5 RqBnD/9lqiT6PeQB9SLi7y4MtszT2eMPC30lbqZRgfhj93k+GNQS+jACVasQudD4EYUKKF6Y8Rl Lw4QMzqRKbo0w7SXwrXAipuh8iT7AhZhojf3LjhTP6FbqbN9r4kTa+oCK4YCgE8j9ndk2pIn/IT BM914Inc49LOI1OrgU0ES5ZNgLNjAY4pq8JJXHMDI/yJvo1e7WOBWqN+NctfnKeXv1VWUVKsjea VEj9iwwcFjqxY+atl1cGrnrOfpeOVRkP0rhM5hd69LvfLN+69sUh1wWyKpH0OwCT8REqGILPfDn SPvW/1JsiSwdHeFRsBTUmid25TF/5bTpJt9vgCMhKMzdECCy85EeT1mjZXChGl1V8tO977P17yM dEXI6hKuIdbNtjambKo33N4N+5mwCqTCX17vvzFtCDTeLiZ71w5zTDZmc8xLcjWPRt7GRAnCb0+ OzzBQSC9I/4/eto8G6F+1PftrVWNvakSLt74Bnv5XPZF6LpMXiKuNwUNTb+0mIJRCkTmxxZbd48 qK7l67tDfP6utSJIhAOQYpOM9OMBbD55PJvu4wAuhoi6YJCTGIjRGm15mdNsUrPz23jd8DW4/ND 7fdOG3ppAWZ4swQjUDh6Dd07sq1TrZhbdljw4IEr1zfTs2bO72UJmgzm22kNbySSR4dzrS/jrPZ +GAxCXclUJOTcZg== X-Mailer: b4 0.13-dev-26615 Message-ID: <20240311-arc-for-list-v3-1-cba1883c62eb@google.com> Subject: [PATCH v3 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. Reviewed-by: Benno Lossin Signed-off-by: Alice Ryhl Reviewed-by: Boqun Feng --- 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.278.ge034bb2e1d-goog From nobody Sun Feb 8 05:47:59 2026 Received: from mail-yw1-f201.google.com (mail-yw1-f201.google.com [209.85.128.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 8BFDE4AEC9 for ; Mon, 11 Mar 2024 16:08:34 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.128.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1710173316; cv=none; b=GPglrGl6rxI+7rb/co0yhptxrOl1UYPM2iMBDnUx3m5KMw1LhNFzoIsbcF3pfpsipVgC++5Twpie4Ly4TV3WB3M3cI6bAmrEFegxbLhz8dJYGwpru0YszqDxID1srqa+zlw+vvbgh+9WRZ1UayS+DvlElxT+u1NroKIexpvoft8= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1710173316; c=relaxed/simple; bh=dTDELu132/83Pc9WB78HCpiSQH+OEDNxB/Dz/kqP3EE=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=ui61fPZ8C2CuPs9E268kDRo679bpixk7cGtF2RSlLXT2bo8enpcWpJpEKjx/ms6O0n+17Vvfc9TlSgSLurXma3t5wtRPd1SsxokKELPywTSy1OhiRWNiNutfuae8JUuVQhiLYbyUyzRYnGq+jXTGv0GN7646QxnQF1ztJ3UB410= 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=IhD3P0vG; arc=none smtp.client-ip=209.85.128.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="IhD3P0vG" Received: by mail-yw1-f201.google.com with SMTP id 00721157ae682-60a0815e3f9so43432857b3.2 for ; Mon, 11 Mar 2024 09:08:34 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1710173313; x=1710778113; 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=9adI/6of+7s/Nl97N1SnFVT87VG5FRlJB2WqXNujaws=; b=IhD3P0vGZ09yXmlWGILPApF5DxaLVd5YhGycri+F8PrAATWU1J8R7OAP83wwXDPMOm tdj/D3WfqMeljVWmhrTubS5NB1NGWJs9uBSQ7TxV+j8Ai3nMXrNXGCt2PWQ9XTGs1FTh Xd3MYoDcoNLaAE9cjIzRir6UhRGIgU8jObxWMsN8OO/tyqksOi6EW6bHIrUMLJG2xnTR cdL2N4krejGbrDUWvwtpBKPdbbaIA+k0UDBUstfFyLipAbvR7BIizQznx/x5aOSwMFth vLMykL61baJlaLDMz/AoPVRZr05liwyMEBVCZrbPZcMG2qnfXpzmbkZ5z0aZEGvqkYr7 aibQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1710173313; x=1710778113; 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=9adI/6of+7s/Nl97N1SnFVT87VG5FRlJB2WqXNujaws=; b=RWcv0ZnyGKQ7hP8dlR14XjVpWIAKaT3yTuMmWLAGKyVuYJeRGKUHw48ohRjwQvdRN/ LSvDDPt2kw8hxCyYjBXlilyDt3XgFR8ZebpxJ4q0LwkEH4CXof7ZZSsE6t9Sq732ra04 CKTAMz93ltk8GXbZXKN7DkHfm8i0IqBm2P1lZTGyJuRd11Rlrf3WKuER1XpFTPZMVH76 FPjxUEv6qJINMVVsPHt9lhlW/ysTWndHWc6VdikqP3riEW3gdCJCqD7WkC1mC9snkBwP YbzqHfzkV7mz+3UTJ7OMWeXs8HnxOrvhJrDdm7cnL+vzX6RegA1yquiOfyVC4fzitcBM /sXA== X-Forwarded-Encrypted: i=1; AJvYcCWCXHopyZZgF041wHYBauVUfEJFsD4XHM6XaBU/U6nKyGRRp7fODDYGG8aLITyHA+DpKgi5MIALN9C1Wf6dXJWlCbBr0c8lMraT2dII X-Gm-Message-State: AOJu0YwqLmxmbyplKip1y3mVD518zWDq704COJ/yKiIJyfXZLWLK3nZE fX5ykAaUeveLNg02YTQ2Worv8RPYIlssuMyPiLL+i+OfAwLs5fFDOSyghZPfvJE0Pu38ADia6+m vQvqv6Yyg+/vB5g== X-Google-Smtp-Source: AGHT+IH2hwZr0/kJVCqZwby3h4TiRwSNTMIgyj2LYQsxATqZ3+UaW49B80uGXpdLy52ed1L0jMT3Fayby6VaSXY= X-Received: from aliceryhl2.c.googlers.com ([fda3:e722:ac3:cc00:68:949d:c0a8:572]) (user=aliceryhl job=sendgmr) by 2002:a0d:d5c6:0:b0:608:398c:33bf with SMTP id x189-20020a0dd5c6000000b00608398c33bfmr146783ywd.8.1710173313704; Mon, 11 Mar 2024 09:08:33 -0700 (PDT) Date: Mon, 11 Mar 2024 16:08:19 +0000 In-Reply-To: <20240311-arc-for-list-v3-0-cba1883c62eb@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20240311-arc-for-list-v3-0-cba1883c62eb@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=2578; i=aliceryhl@google.com; h=from:subject:message-id; bh=dTDELu132/83Pc9WB78HCpiSQH+OEDNxB/Dz/kqP3EE=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBl7yx4oLnnXqRdNuQvjnTuAOP/so9X0itV5HLJl I/VeRdBlgqJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZe8seAAKCRAEWL7uWMY5 RgIWD/9X+MWLobKJpl8KfMnRimQ3J1q3W6wzBE14KOjhM34LNyL9dlkAm/gkD6shGT+FQcg+yko 3Nnd8YYpR3smNN3GNNvi4baNHCOEi6Jzuf9vJXOSxkYxnP3xLwgVgwSL7L6z5dzpIBHjkKPMKYU FCYB55UlxmTiNemYtIMGjZaRX5K68VxTMmUZ34Ra2aOGelVynHFyQaxcoD4tSqD0dGxnt/p6L7d X9/i5lLEJ4hCLJY+gD3vLwmBMLAvmVg4LJwohpkRLle3xKmKlyeaG8vwlo5rAlH0rcRD6KRbbu1 XZxiCwP5EAR9DkyVE0Bj2kaDqvA6YgIhWgxcVK6PBlqfTAHL5S9qdOEdKSg+k9t7SwaIFNBLtdQ duoYjplnNLrHdEkFHtfxZVQerD5M92rFHyERyCqUk6lnh2F8Gu/1rY4YNO1DSqvQay5dMB5fZef 1yFxpgeBoz7X3rL5Ddod7rd87/53OB444EfVPQ33TUp6YnWMjWxVKD3JNr451zc0+pHoGuH3pSA 2ouHu/53HSkcNOBJt0C461LD2A88FYAbL0h/6ucyjKGjCFOTcyNXISfT5p+j+ZexgAHarUUAK/t JH1b56hWiyf7sxpZuhUfUfHb8WGbKqQVtigtZEdcZ0okFtkzEBGfSnMvSKiYk7ds8QB68rGFVkh +ocS26/k/mz51ow== X-Mailer: b4 0.13-dev-26615 Message-ID: <20240311-arc-for-list-v3-2-cba1883c62eb@google.com> Subject: [PATCH v3 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 Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin Reviewed-by: Boqun Feng --- rust/kernel/sync/arc.rs | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/rust/kernel/sync/arc.rs b/rust/kernel/sync/arc.rs index 53addb8876c2..ef8b520f65a8 100644 --- a/rust/kernel/sync/arc.rs +++ b/rust/kernel/sync/arc.rs @@ -290,6 +290,36 @@ 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(); + + // If the refcount reaches a non-zero value, then we have destroye= d this `Arc` and will + // return without further touching the `Arc`. If the refcount reac= hes zero, then there are + // no other arcs, and we can create a `UniqueArc`. + // + // SAFETY: We own a refcount, so the pointer is not dangling. + 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)= ) }; + + // INVARIANT: We own the only refcount to this arc, so we may = create a `UniqueArc`. We + // must pin the `UniqueArc` because the values was previously = in an `Arc`, and they pin + // their values. + Some(Pin::from(UniqueArc { inner: ManuallyDrop::into_inner(me)= })) + } else { + None + } + } } =20 impl ForeignOwnable for Arc { --=20 2.44.0.278.ge034bb2e1d-goog