From nobody Sun Feb 8 07:59:49 2026 Received: from mail-yw1-f202.google.com (mail-yw1-f202.google.com [209.85.128.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 07A0784FAB for ; Tue, 2 Apr 2024 13:07:53 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.128.202 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1712063275; cv=none; b=NYpce2fkcQ9141Ze2U3JiOJzj4L52lmXuN/6RaMD6zZL8nKwaIafK2ba9sigGID7uDYv3Sx+2ciLYkIuO2LqXjv98Rcl3bPO63Cbasv6fMymue8glpyS0xj76a+xh+L1j/WSm24a5/SWDgG74bTmQdGOlHVcwNnmRMl7Qb5GTYM= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1712063275; c=relaxed/simple; bh=/9JDOXGk30s1zhUrSl6X9Tci1HrlBOvd/yZB9RRxUxQ=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=HA6Yf771PR3JyoC3gql8bQupSsDko1B5+vistSnxOBZnpal26hQSox8nOSpUOs5UTdyvkMGQ1ahsA1OHZRd6cFpy2QbHVuV2W+2KFhZ9TFpJS0roah5TqMJjyDSuPRtpFR+dXXO/sl6vne/YrCYbapAGxwLTWjoUFstifczL+qM= 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=TOVUduO5; arc=none smtp.client-ip=209.85.128.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="TOVUduO5" Received: by mail-yw1-f202.google.com with SMTP id 00721157ae682-615272125c6so9364767b3.3 for ; Tue, 02 Apr 2024 06:07:53 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1712063273; x=1712668073; 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=uCfbKJeKL+mMpegNJFQm0U53hM3icUzLYitSMM1i5xQ=; b=TOVUduO5YcfmYimBFM4IFFkMvkfiwemchLAw+Q9M/sfO6KssGbySco295j8yd5UmKm 69BlPHrr2SnZTe9UIFdl8NvnD6YQdcr5YVm4PCdIzYJS8LEhDrHePgdDb+t+9vXG+YX+ zQr0aB0e+/sUZ8B+nVUsn6ZWlcceHIt/LyiYKniWdS+Nij65lpsizUGugmWhiIKsM6Ky OOclTovscbv7lmDEKeTmBnHnDyAVURiIaKA7MCmD5Ei3U+q0I0IbiMX0iMfWHdwADILE 9UalMvVZNsfIJClEgLbtJU+VxSkfCI67alsfYb3f7huls/c+HRsYCMjcN1lswRi3/f0d eNRQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1712063273; x=1712668073; 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=uCfbKJeKL+mMpegNJFQm0U53hM3icUzLYitSMM1i5xQ=; b=DoOQxeFb/3ZVGm0BVQWsvyU93lQ+4jkPfT+V2SzKoZ2PSgGs6kNVZ0gOkscKBzJqel gDOMA6R4PhtRMd0vWmTpMb6Q3NfOv2+HGqf+2iKeQQ6740hnZnRt4BAEQ2xCqzN4/5Gz UAxfuvEV46ZFW6B+hFGKA2dMNkYF6IKHQzqm14qNn07wI2BQK6Q+HnXQz/mGbYKvBuci A212IZKGxWa7UpFXOHcrNBKAPqPhSmbBu7BOAjoULq3zAld5BnpqjKqtzDplwB9QYFzl kvkiaCR96YiuLsAaLdm6uuVIyI+i+TxKEYs5BHN/4Mk0TZIxdEMK4rlGoza+ug6pu0E6 j7dQ== X-Forwarded-Encrypted: i=1; AJvYcCXTmwl5D+UfAbIcDB4F5CYDw6TYKuPPgxEo6cM297hMcHDsawhVLo1qpgOV06OHYuLCezuWiVq/XlrIZ1+Pp3nx1wC1pCEsZ/jRd8zE X-Gm-Message-State: AOJu0YxBEtxvVCy8puys6N+tI00/M9CwfNFA0io1Gc59rJkb0wFaE74k MYi6f/ISwVdikF+yMKcrdfm2RAMnyWfTYJU9PbJYCmYpMndc8lU0Nz01hD1lMqtr8PCiWP98eXW MentrZ7O8GNC/rA== X-Google-Smtp-Source: AGHT+IFTNtTzq05jAqkEcUoOP2m9NmtC712kZNLdleaPaLZtBNZULhvOTJfmsV+6eF5xRaLa6BWYI+zX2UdVKTI= X-Received: from aliceryhl2.c.googlers.com ([fda3:e722:ac3:cc00:68:949d:c0a8:572]) (user=aliceryhl job=sendgmr) by 2002:a05:690c:b9c:b0:611:747a:daac with SMTP id ck28-20020a05690c0b9c00b00611747adaacmr3425087ywb.0.1712063273111; Tue, 02 Apr 2024 06:07:53 -0700 (PDT) Date: Tue, 02 Apr 2024 13:07:42 +0000 In-Reply-To: <20240402-arc-for-list-v4-0-54db6440a9a9@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20240402-arc-for-list-v4-0-54db6440a9a9@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=6048; i=aliceryhl@google.com; h=from:subject:message-id; bh=/9JDOXGk30s1zhUrSl6X9Tci1HrlBOvd/yZB9RRxUxQ=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBmDAMixpuDE0siAIZuQRVnjCVfT7h2isQxSwP93 P0Hsav0ZYaJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZgwDIgAKCRAEWL7uWMY5 RlVgD/wI7HslZbYDfwDmdp5pDS8YLnfCI5YgZIepsCEoJG3+rSkjRUfjPeq1XrKtCTBDuS+/jP5 IsGATvF0Lvb+spKZo3r0XV0P93mseg7xVDm7xhtkbfCU0rI4zmHRhBrRPQrjzCLWQi9a55jTRf5 gqhBCVtDg/DJ8zkUvt8IaqWRFl7q/MZj3PdV+KyzT1OyqoS8+fAjYsPBBXWzAsLUbWpu18GYHQA xJMY+MOGcJrOof3oH32lq9rwt4Qmswqx9gxvm6+Pysuzp/Gfatq70s09uTND++mrxmLEU+qfRKx radkwXbP4+2Z8Uljh1wfVlT6yJaBKej3daVOIFyAyKiXJsxNgDJYFW/C2uY5XbZqSx2IF4aISTz tNO6slIj6ue43Gmonmra5ceI6dQX8ZzXEEuQMJF0k4LmsCSpG67SNx5xjKoSuD2HL5svccQmDtG d1xDV0gAliDr0EwVvCxJjdYXdRFuixUSfUyuzhGyIUbUHkB6v8vVullP65xlxazHATn2XIJvxKb ReI0NLruA+OEsAJfpNlhfHUlE+f4PcbBMu1S4tAQCxPhgM/N9XXNUcuY9rM9Ec5BNvVSEgNyzF4 2HXvsEs2BiMVka2rzwWadP93jhGvcb2eJ96RheqS3A5vs2vc8gL11cvY7RhxIjlvUooKq6hGbzd Rqpa2UosUJT0K3g== X-Mailer: b4 0.13-dev-26615 Message-ID: <20240402-arc-for-list-v4-1-54db6440a9a9@google.com> Subject: [PATCH v4 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 [1]. Reviewed-by: Benno Lossin Reviewed-by: Boqun Feng Link: https://lore.kernel.org/r/20240402-linked-list-v1-6-b1c59ba7ae3b@goog= le.com [1] 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, } =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.478.gd926399ef9-goog From nobody Sun Feb 8 07:59:49 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 EDE3F133293 for ; Tue, 2 Apr 2024 13:07:56 +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=1712063278; cv=none; b=OfQksYEWm5ssldZAOCjWei1bRLCtboN3UqdPOdA3Mtbk2Zm+aS+7YOa7qRsGqP3ed+dzgiyEE4HsRyda1zUN+lv3YfJZmIwjXm5cf9s7hMQY9f4EHdvwHxWOZKF7+VxGV5Ir6OlCR83hYyeDdDUmy8l2JkExVuWQSdPQD0eRCTE= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1712063278; c=relaxed/simple; bh=PxWww9p0ux8jd+JTBng4iPUbmo/WqC7WSl9rYFjrBmE=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=sR5ivMe/A23FXF7vbZ/lRDiIMxRE6j6ebv8ix9FMobyux2/KlOG80XKpVF74IGGl0cyITJiz0dWWVgdfqWjsQwTGNY1RoSj3pWsl0jbS7FyhI8K+wtYjQluyJCDCf8sh/7kVjZIGjmUJgdJQ4LIrCDa0hELRMTkX8Gc7+qEGxEg= 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=KSOwag+5; 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="KSOwag+5" Received: by mail-yb1-f202.google.com with SMTP id 3f1490d57ef6-dc6b26ce0bbso9371077276.1 for ; Tue, 02 Apr 2024 06:07:56 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1712063276; x=1712668076; 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=YK0IVBzGw2YL7NaImcW2IKkPiMomILZlbIQFdtxNZRc=; b=KSOwag+5uEFIu8LnIUZz2zwJXh6m78qArTPnQjHSjlZx2PegFcPGLdSuEi7gCN3kDt CpnLFrI7p9sWNiKp830ksXN2Tqvyzc7h472mk8tDT/z6Wmx8ZtiuWPEWGpudTz8MH3sS veFRNB9Zkye+65IZCucmM+oSgQnFFaIPiISzCg2adb59/jULB2hSPqexeGIOiYCOJBBM yI3mzM4uCJBEZYBdVJM/gmNRI0bN8HqmNqoLKw9q2rQJoTbi/Lc9yXn0Ls/xNzmWvk2+ dX5/5cUiVVpOVjpSWbSFa2T+FZvfcNHHjCWx6vVsUOrsU6g3CDxKpTeIO6ylFNTXehPU 9wiQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1712063276; x=1712668076; 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=YK0IVBzGw2YL7NaImcW2IKkPiMomILZlbIQFdtxNZRc=; b=M5xcqR8mGzTrwFRYHvGPlGOZBvBaRRuKA40CPEBXpHOSVMUGjILiJJ5Ef6883nKSFs VqSshcWN2iE4acCpMRX8Z2eaLK1kl3QDTair77ichEU9PEyRvnSOy1RygDHL2mnGz8iA 2pwYL8ZMVYeFimd2701sYq0GPf6wolU9fXSrT9eBiO2pGeRs8vUO0K2poijJH31FW5Is F5d/+3OpnWX5mF2UFnyzA33CsAawwvsPu88joGc++AQxTEaJMHmlcnaWj1LOuv/Rskcn 2RSkPAsBbl8O8AFQxrlWkuMslqDsfNoStVwhAoCymz/QeBD7Acn8VDt9MVXavXKGbcFo Ss2w== X-Forwarded-Encrypted: i=1; AJvYcCX9Y7Gr+AlyOPGITzOLWh+kz9EdWD0GQphurVwk1EU6vVGEdr1Fj1dxg9q85/F0EnTn3QwppfMZx0n1Tl5Wj0pcH4hSTFYACCGNtyLh X-Gm-Message-State: AOJu0YxLq/LZxJapHdiQaTy4BmbG+PKb6IWbsI/z8maO+IFS46Q14z5a hmA7DsDWD4SbWqvEXbbuHRiEcDyNOf6VFXacdEvSsNgSAnadEmZw/xgJPQrq6vFS1yXx9f2mJox HYYRc0PANsL+DbQ== X-Google-Smtp-Source: AGHT+IF/7TWz8RhJGovksUMInwr3/uIEtPnnFR2PdQlpU82yszqL3urfPIBkm64cCgKqtH8UZcQCTWDKraB9HAo= X-Received: from aliceryhl2.c.googlers.com ([fda3:e722:ac3:cc00:68:949d:c0a8:572]) (user=aliceryhl job=sendgmr) by 2002:a05:6902:1601:b0:dca:33b8:38d7 with SMTP id bw1-20020a056902160100b00dca33b838d7mr3956005ybb.11.1712063276019; Tue, 02 Apr 2024 06:07:56 -0700 (PDT) Date: Tue, 02 Apr 2024 13:07:43 +0000 In-Reply-To: <20240402-arc-for-list-v4-0-54db6440a9a9@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20240402-arc-for-list-v4-0-54db6440a9a9@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=3818; i=aliceryhl@google.com; h=from:subject:message-id; bh=PxWww9p0ux8jd+JTBng4iPUbmo/WqC7WSl9rYFjrBmE=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBmDAMjnQQUU7VFbOJ68s6w4F893DduCep4a6HWD eY5S2s02p2JAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZgwDIwAKCRAEWL7uWMY5 RvnND/9Ou7OIhLaUM33tvAUZQnucWJkibYoGR+SICJqUOF/aoIOn71jr+11PoGT5XBaEdO+Yjg0 zATsPm7VsQdy/BB7ioZzttGcd8FQjmWz7ZRotTagEUe3DEwwiPlHze58I9liXvEUrDtRMHkBbC+ el4heWgkp2ESqynmTCsUT3xWACsjj6S7MheF2wPRBP3fRwcW/4DSxYd6RU6sAZ47k2TObo7jsFU 3D7DDeXkjVGrpAowqAJWJ3BZaJYVcEha1vbkV8D8nWalHtqziHLTFl8CHskZKMsu5US1z657vhw INjmVLODp8jMrwwPA3LuUlDEepvBazpY5lc4vIy6Jo0n+zAkhssN7ji2wPCbggcUGiB96zBDTZK SEYm63rnKTCk8838Py+j6aQWvvM/moOLzR0PaFfJ6Iu81QOFkOA8p9qyRSdEaUOOi5/TFrTCiBo H1ATY8x0XsNbPk9/b8EJsw+s/Wuld2dxoV66Y5jeTSl+Piw+JLirBd3QIiQkPlYvZVXgVIidaMe BmITg4qDV4+AJrNziwLKTNNdwlFn+x5VYnk6nrx82nfAoC4uCSILMhfKEocL0O4XkTeiH9/vcVE TWQ0lRs/d7WffnS+Pe5uNRb4atWRcUBCz5yRGzJPf69qBh3BzPFqVU1u84zTxuwh1bYhn8dRhfh 79NYDU8wNjnqkTQ== X-Mailer: b4 0.13-dev-26615 Message-ID: <20240402-arc-for-list-v4-2-54db6440a9a9@google.com> Subject: [PATCH v4 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 [1]. Boqun Feng has authored the examples. Reviewed-by: Benno Lossin Reviewed-by: Boqun Feng Link: https://lore.kernel.org/r/20240402-linked-list-v1-1-b1c59ba7ae3b@goog= le.com [1] Co-developed-by: Boqun Feng Signed-off-by: Boqun Feng Signed-off-by: Alice Ryhl --- rust/kernel/sync/arc.rs | 62 +++++++++++++++++++++++++++++++++++++++++++++= ++++ 1 file changed, 62 insertions(+) diff --git a/rust/kernel/sync/arc.rs b/rust/kernel/sync/arc.rs index 53addb8876c2..30777241d8cf 100644 --- a/rust/kernel/sync/arc.rs +++ b/rust/kernel/sync/arc.rs @@ -290,6 +290,68 @@ 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. + /// + /// # Examples + /// + /// ``` + /// use kernel::sync::{Arc, UniqueArc}; + /// + /// let arc =3D Arc::try_new(42)?; + /// let unique_arc =3D arc.into_unique_or_drop(); + /// + /// // The above conversion should succeed since refcount of `arc` is = 1. + /// assert!(unique_arc.is_some()); + /// + /// assert_eq!(*(unique_arc.unwrap()), 42); + /// + /// # Ok::<(), Error>(()) + /// ``` + /// + /// ``` + /// use kernel::sync::{Arc, UniqueArc}; + /// + /// let arc =3D Arc::try_new(42)?; + /// let another =3D arc.clone(); + /// + /// let unique_arc =3D arc.into_unique_or_drop(); + /// + /// // The above conversion should fail since refcount of `arc` is >1. + /// assert!(unique_arc.is_none()); + /// + /// # Ok::<(), Error>(()) + /// ``` + 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.478.gd926399ef9-goog