Skip to content

Commit e9a17e8

Browse files
Darksonnfbq
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. Signed-off-by: Alice Ryhl <[email protected]> Reviewed-by: Benno Lossin <[email protected]> Link: https://lore.kernel.org/r/[email protected] [boqun: Fix the rustfmt issue reported by Miguel]
1 parent d314fa6 commit e9a17e8

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

rust/kernel/sync/arc.rs

+32
Original file line numberDiff line numberDiff line change
@@ -291,6 +291,38 @@ 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+
pub fn into_unique_or_drop(self) -> Option<Pin<UniqueArc<T>>> {
300+
// We will manually manage the refcount in this method, so we disable the destructor.
301+
let me = ManuallyDrop::new(self);
302+
// SAFETY: We own a refcount, so the pointer is still valid.
303+
let refcount = unsafe { me.ptr.as_ref() }.refcount.get();
304+
305+
// If the refcount reaches a non-zero value, then we have destroyed this `Arc` and will
306+
// return without further touching the `Arc`. If the refcount reaches zero, then there are
307+
// no other arcs, and we can create a `UniqueArc`.
308+
//
309+
// SAFETY: We own a refcount, so the pointer is not dangling.
310+
let is_zero = unsafe { bindings::refcount_dec_and_test(refcount) };
311+
if is_zero {
312+
// SAFETY: We have exclusive access to the arc, so we can perform unsynchronized
313+
// accesses to the refcount.
314+
unsafe { core::ptr::write(refcount, bindings::REFCOUNT_INIT(1)) };
315+
316+
// INVARIANT: We own the only refcount to this arc, so we may create a `UniqueArc`. We
317+
// must pin the `UniqueArc` because the values was previously in an `Arc`, and they pin
318+
// their values.
319+
Some(Pin::from(UniqueArc {
320+
inner: ManuallyDrop::into_inner(me),
321+
}))
322+
} else {
323+
None
324+
}
325+
}
294326
}
295327

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

0 commit comments

Comments
 (0)