implement `kernel::sync::Refcount` and convert users
Subsystems (5)
Gary Guo
maintainerv2 cover implement `kernel::sync::Refcount` and convert users
Currently there're two refcount usage in rust/, Arc and block::mq. Arc uses refcount_t with FFI calls directly, and block::mq use Rust atomics and custom refcounting.
This series consolidate them to have a single Refcount which wraps refcount_t and have it used by both.
With the removal of Rust AtomicU64 this would also make the code work for 32-bit systems. See [1] as a previous attempt to fix this issue.
Changes in v2:
- Refcount::read method is dropped
- Refcount::dec_not_one method is added and Arc::into_unique_or_drop
is converted to use it.
- Link to v1: https://lore.kernel.org/rust-for-linux/[email protected]
Gary Guo (3):
rust: implement kernel::sync::Refcount
rust: convert Arc to use Refcount
rust: block: convert block::mq to use Refcount
rust/helpers/refcount.c | 10 +++ rust/kernel/block/mq/operations.rs | 7 +- rust/kernel/block/mq/request.rs | 70 ++++++------------ rust/kernel/sync.rs | 2 + rust/kernel/sync/arc.rs | 64 +++++++---------- rust/kernel/sync/refcount.rs | 109 +++++++++++++++++++++++++++++ 6 files changed, 172 insertions(+), 90 deletions(-) create mode 100644 rust/kernel/sync/refcount.rs
base-commit: 0c5928deada15a8d075516e6e0d9ee19011bb000
Signature · 1 line
2.47.0
Gary Guo
maintainerPATCH v2 1/3 rust: implement `kernel::sync::Refcount`
This is a wrapping layer of include/linux/refcount.h. Currently the kernel refcount has already been used in Arc, however it calls into FFI directly.
--- rust/helpers/refcount.c | 10 ++++ rust/kernel/sync.rs | 2 + rust/kernel/sync/refcount.rs | 97 ++++++++++++++++++++++++++++++++++++ 3 files changed, 109 insertions(+) create mode 100644 rust/kernel/sync/refcount.rs
rust/helpers/refcount.c +10 -0
@@ -7,11 +7,21 @@ refcount_t rust_helper_REFCOUNT_INIT(int n)return (refcount_t )REFCOUNT_INIT (n); } +void rust_helper_refcount_set (refcount_t *r,int n) +{ +refcount_set (r, n); +} +void rust_helper_refcount_inc (refcount_t *r) {refcount_inc (r); } +void rust_helper_refcount_dec (refcount_t *r) +{ +refcount_dec (r); +} +bool rust_helper_refcount_dec_and_test (refcount_t *r) {return refcount_dec_and_test (r);
rust/kernel/sync.rs +2 -0
@@ -12,6 +12,7 @@pub mod lock;mod locked_by;pub mod poll; +mod refcount;pub use arc::{Arc ,ArcBorrow ,UniqueArc };pub use condvar::{new_condvar,CondVar ,CondVarTimeoutResult };
@@ -19,6 +20,7 @@pub use lock::mutex::{new_mutex,Mutex };pub use lock::spinlock::{new_spinlock,SpinLock };pub use locked_by::LockedBy ; +pub use refcount::Refcount ;/// Represents a lockdep class. It's a wrapper around C's `lock_class_key`. #[repr(transparent)]
rust/kernel/sync/refcount.rs new file +97 -0
97 lines not on this page · raw message
Signature · 1 line
2.47.0
Re: [PATCH v2 1/3] rust: implement `kernel::sync::Refcount`
Quoted 6 lines · Gary Guo
This is a wrapping layer of
include/linux/refcount.h. Currently the kernel refcount has already been used inArc, however it calls into FFI directly.Signed-off-by Gary Guo <[email protected]>
Re: [PATCH v2 1/3] rust: implement `kernel::sync::Refcount`
In reply to Gary Guorust/kernel/sync/refcount.rs
Quoted 63 lines · Gary Guo
This is a wrapping layer of
include/linux/refcount.h. Currently the kernel refcount has already been used inArc, however it calls into FFI directly.Signed-off-by Gary Guo <[email protected]>--- rust/helpers/refcount.c | 10 ++++ rust/kernel/sync.rs | 2 + rust/kernel/sync/refcount.rs | 97 ++++++++++++++++++++++++++++++++++++ 3 files changed, 109 insertions(+) create mode 100644 rust/kernel/sync/refcount.rsrust/helpers/refcount.c +10
-0@@ -7,11 +7,21 @@ refcount_t rust_helper_REFCOUNT_INIT(int n)return (refcount_t )REFCOUNT_INIT (n); } +void rust_helper_refcount_set (refcount_t *r,int n) +{ +refcount_set (r, n); +} +void rust_helper_refcount_inc (refcount_t *r) {refcount_inc (r); } +void rust_helper_refcount_dec (refcount_t *r) +{ +refcount_dec (r); +} +bool rust_helper_refcount_dec_and_test (refcount_t *r) {return refcount_dec_and_test (r);rust/kernel/sync.rs +2
-0@@ -12,6 +12,7 @@pub mod lock;mod locked_by;pub mod poll; +mod refcount;pub use arc::{Arc ,ArcBorrow ,UniqueArc };pub use condvar::{new_condvar,CondVar ,CondVarTimeoutResult };@@ -19,6 +20,7 @@pub use lock::mutex::{new_mutex,Mutex };pub use lock::spinlock::{new_spinlock,SpinLock };pub use locked_by::LockedBy ; +pub use refcount::Refcount ;/// Represents a lockdep class. It's a wrapper around C's `lock_class_key`. #[repr(transparent)] rust/kernel/sync/refcount.rs new file +0
-0
Could you add this file into the entry of "ATOMIC INFRASTRUCTURE"? I would also suggest you to add yourself as a reviewer or maintainer in that entry (given your expertise on atomic and related compiler behaviors), but that's totally up to you.
rust/kernel/sync/refcount.rs line 9
Quoted 10 lines
rust/kernel/sync/refcount.rs new file +9
-0@@ -0,0 +1,97 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Atomic reference counting. +//! +//! C header: [`include/linux/refcount.h`](srctree/include/linux/refcount.h) + +use crate ::types::Opaque ; +use core::sync::atomic::AtomicI32 ; +
Could you move this "use" into patch #3, where it gets used?
Regards,
Boqun
[...]
Gary Guo
maintainerPATCH v2 2/3 rust: convert `Arc` to use `Refcount`
In reply to Gary GuoWith Refcount type created, Arc can use Refcount instead of calling into FFI directly.
--- rust/kernel/sync/arc.rs | 64 ++++++++++++++++------------------------- 1 file changed, 25 insertions(+), 39 deletions(-)
rust/kernel/sync/arc.rs +25 -39
@@ -8,7 +8,7 @@//! threads. //! //! It is different from the standard library's [`Arc`] in a few ways: -//! 1. It is backed by the kernel's `refcount_t` type. +//! 1. It is backed by the kernel's [`Refcount`] type. //! 2. It does not support weak references, which allows it to be half the size. //! 3. It saturates the reference count instead of aborting when it goes over a threshold. //! 4. It does not provide a `get_mut` method, so the ref counted object is pinned.
@@ -18,10 +18,10 @@use crate ::{ alloc::{AllocError ,Flags ,KBox }, - bindings, init::{self,InPlaceInit ,Init ,PinInit }, + sync::Refcount , try_init, - types::{ForeignOwnable ,Opaque }, + types::ForeignOwnable , };use core::{ alloc::Layout ,
@@ -141,7 +141,7 @@ pub struct Arc<T: ?Sized> {#[pin_data] #[repr( C )] struct ArcInner <T : ?Sized > { - refcount:Opaque <bindings::refcount_t >, + refcount:Refcount , data:T , }
@@ -153,7 +153,7 @@ impl<T: ?Sized> ArcInner<T> {/// `ptr` must have been returned by a previous call to [`Arc::into_raw`], and the `Arc` must /// not yet have been destroyed. unsafe fn container_of (ptr: *const T ) ->NonNull <ArcInner <T >> { -let refcount_layout =Layout ::new ::<bindings::refcount_t >(); +let refcount_layout =Layout ::new ::<Refcount >();// SAFETY: The caller guarantees that the pointer is valid. let val_layout =Layout ::for_value (unsafe { &*ptr });// SAFETY: We're computing the layout of a real struct that existed when compiling this
@@ -203,8 +203,7 @@ impl<T> Arc<T> {pub fn new (contents:T , flags:Flags ) ->Result <Self ,AllocError > {// INVARIANT: The refcount is initialised to a non-zero value. let value =ArcInner { -// SAFETY: There are no safety requirements for this FFI call. - refcount:Opaque ::new (unsafe { bindings::REFCOUNT_INIT (1 ) }), + refcount:Refcount ::new (1 ), data: contents, };
@@ -285,7 +284,7 @@ pub fn ptr_eq(this: &Self, other: &Self) -> bool {/// use kernel::sync::{Arc, UniqueArc}; /// /// let arc = Arc::new(42, GFP_KERNEL)?; -/// let unique_arc = arc.into_unique_or_drop(); +/// let unique_arc = Arc::into_unique_or_drop(arc); /// /// // The above conversion should succeed since refcount of `arc` is 1. /// assert!(unique_arc.is_some());
@@ -301,35 +300,25 @@ pub fn ptr_eq(this: &Self, other: &Self) -> bool {/// let arc = Arc::new(42, GFP_KERNEL)?; /// let another = arc.clone(); /// -/// let unique_arc = arc.into_unique_or_drop(); +/// let unique_arc = Arc::into_unique_or_drop(arc); /// /// // 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 <Pin <UniqueArc <T >>> { +pub fn into_unique_or_drop (this:Self ) ->Option <Pin <UniqueArc <T >>> {// We will manually manage the refcount in this method, so we disable the destructor. -let me =ManuallyDrop ::new (self); +let this =ManuallyDrop ::new (this);// SAFETY: We own a refcount, so the pointer is still valid. -let refcount =unsafe { me.ptr.as_ref () }.refcount.get (); +let refcount =unsafe { &this.ptr.as_ref ().refcount }; -// If the refcount reaches a non-zero value, then we have destroyed this `Arc` and will -// return without further touching the `Arc`. If the refcount reaches 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 =unsafe { bindings::refcount_dec_and_test (refcount) }; -if is_zero { -// SAFETY: We have exclusive access to the arc, so we can perform 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. +if !refcount.dec_not_one () { +// INVARIANT: If the refcount failed to decrement because it is 1, then we have the +// exclusive ownership, 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), + inner:ManuallyDrop ::into_inner (this), })) }else {None
@@ -380,10 +369,10 @@ fn as_ref(&self) -> &T {impl <T : ?Sized >Clone for Arc <T > {fn clone (&self) ->Self { -// INVARIANT: C `refcount_inc` saturates the refcount, so it cannot overflow to zero. +// INVARIANT: `Refcount` saturates the refcount, so it cannot overflow to zero. // SAFETY: By the type invariant, there is necessarily a reference to the object, so it is // safe to increment the refcount. -unsafe { bindings::refcount_inc (self.ptr.as_ref ().refcount.get ()) }; +unsafe { self.ptr.as_ref ().refcount.inc () };// SAFETY: We just incremented the refcount. This increment is now owned by the new `Arc`. unsafe {Self ::from_inner (self.ptr) }
@@ -392,16 +381,14 @@ fn clone(&self) -> Self {impl <T : ?Sized >Drop for Arc <T > {fn drop (&mut self) { -// SAFETY: By the type invariant, there is necessarily a reference to the object. We cannot -// touch `refcount` after it's decremented to a non-zero value because another thread/CPU -// may concurrently decrement it to zero and free it. It is ok to have a raw pointer to -// freed/invalid memory as long as it is never dereferenced. -let refcount =unsafe { self.ptr.as_ref () }.refcount.get (); -// INVARIANT: If the refcount reaches zero, there are no other instances of `Arc`, and // this instance is being dropped, so the broken invariant is not observable. -// SAFETY: Also by the type invariant, we are allowed to decrement the refcount. -let is_zero =unsafe { bindings::refcount_dec_and_test (refcount) }; +// SAFETY: By the type invariant, there is necessarily a reference to the object. +// NOTE: we cannot touch `refcount` after it's decremented to a non-zero value because +// another thread/CPU may concurrently decrement it to zero and free it. However it is okay +// to have a transient reference to decrement the refcount, see +// https://github.com/rust-lang/rust/issues/55005. +let is_zero =unsafe { self.ptr.as_ref ().refcount.dec_and_test () };if is_zero {// The count reached zero, we must free the memory. //
@@ -650,8 +637,7 @@ pub fn new_uninit(flags: Flags) -> Result<UniqueArc<MaybeUninit<T>>, AllocError>// INVARIANT: The refcount is initialised to a non-zero value. let inner =KBox ::try_init ::<AllocError >(try_init! (ArcInner { -// SAFETY: There are no safety requirements for this FFI call. - refcount:Opaque ::new (unsafe { bindings::REFCOUNT_INIT (1 ) }), + refcount:Refcount ::new (1 ), data <- init::uninit ::<T ,AllocError >(), }?AllocError ), flags,
Signature · 1 line
2.47.0
Alice Ryhl
maintainerRe: [PATCH v2 2/3] rust: convert `Arc` to use `Refcount`
Quoted 5 lines · Gary Guo
With
Refcounttype created,Arccan useRefcountinstead of calling into FFI directly.Signed-off-by Gary Guo <[email protected]>
[...]
Quoted 6 lines
rust/kernel/sync/arc.rs +2
-2-pub fn into_unique_or_drop (self) ->Option <Pin <UniqueArc <T >>> { +pub fn into_unique_or_drop (this:Self ) ->Option <Pin <UniqueArc <T >>> {// We will manually manage the refcount in this method, so we disable the destructor. -let me =ManuallyDrop ::new (self); +let this =ManuallyDrop ::new (this);// SAFETY: We own a refcount, so the pointer is still valid.
rust/kernel/sync/arc.rs pub fn ptr_eq(this: &Self, other: &Self) -> bool { · line 316
Quoted 10 lines
rust/kernel/sync/arc.rs +2
-7-let refcount =unsafe { me.ptr.as_ref () }.refcount.get (); +let refcount =unsafe { &this.ptr.as_ref ().refcount }; -// If the refcount reaches a non-zero value, then we have destroyed this `Arc` and will -// return without further touching the `Arc`. If the refcount reaches 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 =unsafe { bindings::refcount_dec_and_test (refcount) }; +if !refcount.dec_not_one () {
This is wrong. The into_unique_or_drop function must establish an acqrel ordering when a UniqueArc is created, but dec_not_one() does not do so. You need to use refcount_dec_and_test() instead.
Alice
Gary Guo
maintainerRe: [PATCH v2 2/3] rust: convert `Arc` to use `Refcount`
Quoted 26 lines · On Tue, 14 Jan 2025 11:02:25 +0100 Alice Ryhl <[email protected]> wrote:
Quoted 5 lines · Gary Guo
With
Refcounttype created,Arccan useRefcountinstead of calling into FFI directly.Signed-off-by Gary Guo <[email protected]>[...]
Quoted 6 lines
rust/kernel/sync/arc.rs +2
-2-pub fn into_unique_or_drop (self) ->Option <Pin <UniqueArc <T >>> { +pub fn into_unique_or_drop (this:Self ) ->Option <Pin <UniqueArc <T >>> {// We will manually manage the refcount in this method, so we disable the destructor. -let me =ManuallyDrop ::new (self); +let this =ManuallyDrop ::new (this);// SAFETY: We own a refcount, so the pointer is still valid. rust/kernel/sync/arc.rs pub fn ptr_eq(this: &Self, other: &Self) -> bool { · line 316
Quoted 10 lines
rust/kernel/sync/arc.rs +2
-7-let refcount =unsafe { me.ptr.as_ref () }.refcount.get (); +let refcount =unsafe { &this.ptr.as_ref ().refcount }; -// If the refcount reaches a non-zero value, then we have destroyed this `Arc` and will -// return without further touching the `Arc`. If the refcount reaches 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 =unsafe { bindings::refcount_dec_and_test (refcount) }; +if !refcount.dec_not_one () {
Quoted 5 lines
This is wrong. The
into_unique_or_dropfunction must establish an acqrel ordering when a UniqueArc is created, butdec_not_one()does not do so. You need to userefcount_dec_and_test()instead.Alice
Ah, good catch. In this case I think an acquire fence in the unique path would be sufficient? Or would you prefer to use dec_and_test and set?
Best,
Gary
Re: [PATCH v2 2/3] rust: convert `Arc` to use `Refcount`
Quoted 29 lines · Gary Guo
Quoted 26 lines · On Tue, 14 Jan 2025 11:02:25 +0100 Alice Ryhl <[email protected]> wrote:
Quoted 5 lines · Gary Guo
With
Refcounttype created,Arccan useRefcountinstead of calling into FFI directly.Signed-off-by Gary Guo <[email protected]>[...]
Quoted 16 lines
rust/kernel/sync/arc.rs +4
-9-pub fn into_unique_or_drop (self) ->Option <Pin <UniqueArc <T >>> { +pub fn into_unique_or_drop (this:Self ) ->Option <Pin <UniqueArc <T >>> {// We will manually manage the refcount in this method, so we disable the destructor. -let me =ManuallyDrop ::new (self); +let this =ManuallyDrop ::new (this);// SAFETY: We own a refcount, so the pointer is still valid. -let refcount =unsafe { me.ptr.as_ref () }.refcount.get (); +let refcount =unsafe { &this.ptr.as_ref ().refcount }; -// If the refcount reaches a non-zero value, then we have destroyed this `Arc` and will -// return without further touching the `Arc`. If the refcount reaches 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 =unsafe { bindings::refcount_dec_and_test (refcount) }; +if !refcount.dec_not_one () {
Quoted 7 lines
Quoted 5 lines
This is wrong. The
into_unique_or_dropfunction must establish an acqrel ordering when a UniqueArc is created, butdec_not_one()does not do so. You need to userefcount_dec_and_test()instead.Alice
Ah, good catch. In this case I think an acquire fence in the unique
Note that we don't have an acquire fence in LKMM, so you may need to use a smp_mb() here.
Quoted 3 lines
path would be sufficient? Or would you prefer to use
dec_and_testandset?
using dec_and_test() + set should be cheaper than dec_not_one() + smp_mb().
Regards,
Boqun
Quoted 2 lines
Best,
Gary
Alice Ryhl
maintainerRe: [PATCH v2 2/3] rust: convert `Arc` to use `Refcount`
In reply to Gary GuoQuoted 34 lines · Gary Guo
Quoted 30 lines · On Tue, 14 Jan 2025 11:02:25 +0100 Alice Ryhl <[email protected]> wrote:
Quoted 5 lines · Gary Guo
With
Refcounttype created,Arccan useRefcountinstead of calling into FFI directly.Signed-off-by Gary Guo <[email protected]>[...]
Quoted 6 lines
rust/kernel/sync/arc.rs +2
-2-pub fn into_unique_or_drop (self) ->Option <Pin <UniqueArc <T >>> { +pub fn into_unique_or_drop (this:Self ) ->Option <Pin <UniqueArc <T >>> {// We will manually manage the refcount in this method, so we disable the destructor. -let me =ManuallyDrop ::new (self); +let this =ManuallyDrop ::new (this);// SAFETY: We own a refcount, so the pointer is still valid. rust/kernel/sync/arc.rs pub fn ptr_eq(this: &Self, other: &Self) -> bool { · line 316
Quoted 10 lines
rust/kernel/sync/arc.rs +2
-7-let refcount =unsafe { me.ptr.as_ref () }.refcount.get (); +let refcount =unsafe { &this.ptr.as_ref ().refcount }; -// If the refcount reaches a non-zero value, then we have destroyed this `Arc` and will -// return without further touching the `Arc`. If the refcount reaches 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 =unsafe { bindings::refcount_dec_and_test (refcount) }; +if !refcount.dec_not_one () {This is wrong. The
into_unique_or_dropfunction must establish an acqrel ordering when a UniqueArc is created, butdec_not_one()does not do so. You need to userefcount_dec_and_test()instead.
Quoted 5 lines
Quoted 1 line
Alice
Ah, good catch. In this case I think an acquire fence in the unique path would be sufficient? Or would you prefer to use
dec_and_testandset?
The existing approach is what I prefer.
Alice
Gary Guo
maintainerPATCH v2 3/3 rust: block: convert `block::mq` to use `Refcount`
In reply to Gary GuoCurrently there's a custom reference counting in block::mq, which uses AtomicU64 Rust atomics, and this type doesn't exist on some 32-bit architectures. We cannot just change it to use 32-bit atomics, because doing so will make it vulnerable to refcount overflow. So switch it to use the kernel refcount kernel::sync::Refcount instead.
There is an operation needed by block::mq, atomically decreasing refcount from 2 to 0, which is not available through refcount.h, so I exposed Refcount::as_atomic which allows accessing the refcount directly.
--- rust/kernel/block/mq/operations.rs | 7 +-- rust/kernel/block/mq/request.rs | 70 ++++++++++-------------------- rust/kernel/sync/refcount.rs | 12 +++++ 3 files changed, 38 insertions(+), 51 deletions(-)
rust/kernel/block/mq/operations.rs +4 -3
@@ -9,9 +9,10 @@ block::mq::request::RequestDataWrapper, block::mq::Request, error::{from_result, Result}, + sync::Refcount, types::ARef, }; -use core::{marker::PhantomData , sync::atomic::AtomicU64 , sync::atomic::Ordering }; +use core::marker::PhantomData ;/// Implement this trait to interface blk-mq as block devices. ///
@@ -77,7 +78,7 @@ impl<T: Operations> OperationsVTable<T> {let request =unsafe { &*(*bd).rq.cast ::<Request <T >>() };// One refcount for the ARef, one for being in flight - request.wrapper_ref ().refcount ().store (2 ,Ordering ::Relaxed ); + request.wrapper_ref ().refcount ().set (2 );// SAFETY: // - We own a refcount that we took above. We pass that to `ARef`.
@@ -186,7 +187,7 @@ impl<T: Operations> OperationsVTable<T> {// SAFETY: The refcount field is allocated but not initialized, so // it is valid for writes. -unsafe {RequestDataWrapper ::refcount_ptr (pdu.as_ptr ()).write (AtomicU64 ::new (0 )) }; +unsafe {RequestDataWrapper ::refcount_ptr (pdu.as_ptr ()).write (Refcount ::new (0 )) };Ok (0 ) })
rust/kernel/block/mq/request.rs +22 -48
130 lines not on this page · raw message
rust/kernel/sync/refcount.rs +12 -0
@@ -31,6 +31,18 @@ fn as_ptr(&self) -> *mut bindings::refcount_t { self.0 .get () } +/// Get the underlying atomic counter that backs the refcount. +/// +/// NOTE: This will be changed to LKMM atomic in the future. +#[inline] +pub fn as_atomic (&self) -> &AtomicI32 { +let ptr = self.0 .get ()as *const AtomicI32 ; +// SAFETY: `refcount_t` is a transparent wrapper of `atomic_t`, which is an atomic 32-bit +// integer that is layout-wise compatible with `AtomicI32`. All values are valid for +// `refcount_t`, despite some of the values are considered saturated and "bad". +unsafe { &*ptr } + } +/// Set a refcount's value. #[inline] pub fn set (&self, value:i32 ) {
Signature · 1 line
2.47.0