[<prev] [next>] [<thread-prev] [thread-next>] [day] [month] [year] [list]
Message-ID: <20240917222739.1298275-5-a.hindborg@kernel.org>
Date: Wed, 18 Sep 2024 00:27:28 +0200
From: Andreas Hindborg <a.hindborg@...nel.org>
To: Miguel Ojeda <ojeda@...nel.org>,
Alex Gaynor <alex.gaynor@...il.com>,
Anna-Maria Behnsen <anna-maria@...utronix.de>,
Frederic Weisbecker <frederic@...nel.org>,
Thomas Gleixner <tglx@...utronix.de>
Cc: Andreas Hindborg <a.hindborg@...nel.org>,
Boqun Feng <boqun.feng@...il.com>,
Gary Guo <gary@...yguo.net>,
Björn Roy Baron <bjorn3_gh@...tonmail.com>,
Benno Lossin <benno.lossin@...ton.me>,
Alice Ryhl <aliceryhl@...gle.com>,
rust-for-linux@...r.kernel.org,
linux-kernel@...r.kernel.org
Subject: [PATCH v2 04/14] rust: sync: add `Arc::clone_from_raw`
Add a method to clone an arc from a pointer to the data managed by the
`Arc`.
Signed-off-by: Andreas Hindborg <a.hindborg@...nel.org>
---
rust/kernel/sync/arc.rs | 20 ++++++++++++++++++++
1 file changed, 20 insertions(+)
diff --git a/rust/kernel/sync/arc.rs b/rust/kernel/sync/arc.rs
index a57ea3e2b44c..2c95712d12a2 100644
--- a/rust/kernel/sync/arc.rs
+++ b/rust/kernel/sync/arc.rs
@@ -282,6 +282,26 @@ pub unsafe fn from_raw(ptr: *const T) -> Self {
unsafe { Self::from_inner(ptr) }
}
+ /// Clones an [`Arc`] instance from a pointer to the contained data.
+ ///
+ /// # Safety
+ ///
+ /// `ptr` must point to an allocation that is contained within a live [`Arc<T>`].
+ pub unsafe fn clone_from_raw(ptr: *const T) -> Self {
+ // SAFETY: The caller promises that this pointer points to data
+ // contained in an `Arc` that is still valid.
+ let inner = unsafe { ArcInner::container_of(ptr).as_ref() };
+
+ // INVARIANT: C `refcount_inc` saturates the refcount, so it cannot
+ // overflow to zero. SAFETY: By the function safety requirement, there
+ // is necessarily a reference to the object, so it is safe to increment
+ // the refcount.
+ unsafe { bindings::refcount_inc(inner.refcount.get()) };
+
+ // SAFETY: We just incremented the refcount. This increment is now owned by the new `Arc`.
+ unsafe { Self::from_inner(inner.into()) }
+ }
+
/// 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
--
2.46.0
Powered by blists - more mailing lists