Skip to content

Commit a0a4e17

Browse files
Darksonnojeda
authored andcommitted
rust: sync: add Arc::into_unique_or_drop
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 <benno.lossin@proton.me> Reviewed-by: Boqun Feng <boqun.feng@gmail.com> Link: https://lore.kernel.org/r/20240402-linked-list-v1-1-b1c59ba7ae3b@google.com [1] Co-developed-by: Boqun Feng <boqun.feng@gmail.com> Signed-off-by: Boqun Feng <boqun.feng@gmail.com> Signed-off-by: Alice Ryhl <aliceryhl@google.com> Link: https://lore.kernel.org/r/20240402-arc-for-list-v4-2-54db6440a9a9@google.com [ Replace `try_new` with `new` in example since we now have the new allocation APIs. - Miguel ] Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
1 parent 51f6af8 commit a0a4e17

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

rust/kernel/sync/arc.rs

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -291,6 +291,68 @@ impl<T: ?Sized> Arc<T> {
291291
pub fn ptr_eq(this: &Self, other: &Self) -> bool {
292292
core::ptr::eq(this.ptr.as_ptr(), other.ptr.as_ptr())
293293
}
294+
295+
/// Converts this [`Arc`] into a [`UniqueArc`], or destroys it if it is not unique.
296+
///
297+
/// When this destroys the `Arc`, it does so while properly avoiding races. This means that
298+
/// this method will never call the destructor of the value.
299+
///
300+
/// # Examples
301+
///
302+
/// ```
303+
/// use kernel::sync::{Arc, UniqueArc};
304+
///
305+
/// let arc = Arc::new(42, GFP_KERNEL)?;
306+
/// let unique_arc = arc.into_unique_or_drop();
307+
///
308+
/// // The above conversion should succeed since refcount of `arc` is 1.
309+
/// assert!(unique_arc.is_some());
310+
///
311+
/// assert_eq!(*(unique_arc.unwrap()), 42);
312+
///
313+
/// # Ok::<(), Error>(())
314+
/// ```
315+
///
316+
/// ```
317+
/// use kernel::sync::{Arc, UniqueArc};
318+
///
319+
/// let arc = Arc::new(42, GFP_KERNEL)?;
320+
/// let another = arc.clone();
321+
///
322+
/// let unique_arc = arc.into_unique_or_drop();
323+
///
324+
/// // The above conversion should fail since refcount of `arc` is >1.
325+
/// assert!(unique_arc.is_none());
326+
///
327+
/// # Ok::<(), Error>(())
328+
/// ```
329+
pub fn into_unique_or_drop(self) -> Option<Pin<UniqueArc<T>>> {
330+
// We will manually manage the refcount in this method, so we disable the destructor.
331+
let me = ManuallyDrop::new(self);
332+
// SAFETY: We own a refcount, so the pointer is still valid.
333+
let refcount = unsafe { me.ptr.as_ref() }.refcount.get();
334+
335+
// If the refcount reaches a non-zero value, then we have destroyed this `Arc` and will
336+
// return without further touching the `Arc`. If the refcount reaches zero, then there are
337+
// no other arcs, and we can create a `UniqueArc`.
338+
//
339+
// SAFETY: We own a refcount, so the pointer is not dangling.
340+
let is_zero = unsafe { bindings::refcount_dec_and_test(refcount) };
341+
if is_zero {
342+
// SAFETY: We have exclusive access to the arc, so we can perform unsynchronized
343+
// accesses to the refcount.
344+
unsafe { core::ptr::write(refcount, bindings::REFCOUNT_INIT(1)) };
345+
346+
// INVARIANT: We own the only refcount to this arc, so we may create a `UniqueArc`. We
347+
// must pin the `UniqueArc` because the values was previously in an `Arc`, and they pin
348+
// their values.
349+
Some(Pin::from(UniqueArc {
350+
inner: ManuallyDrop::into_inner(me),
351+
}))
352+
} else {
353+
None
354+
}
355+
}
294356
}
295357

296358
impl<T: 'static> ForeignOwnable for Arc<T> {

0 commit comments

Comments
 (0)