implement `kernel::sync::Refcount` and convert users
Subsystems (5)
v4 cover implement `kernel::sync::Refcount` and convert users
From: Gary Guo <[email protected]>
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 v4:
- Move justification on why &Refcount is okay when used for reference
coutning into the Refcount::dec_and_test documentation comment.
- Split Arc::into_unique_or_drop signature change into another patch.
- Wording/comment changes
- Link to v3: https://lore.kernel.org/rust-for-linux/[email protected]/
Changes in v3:
- Drop dec_not_one and revert to dec_and_test/set as the former
lacks acquire semantics.
- Move a use statement from patch 1 to correct place (patch 3).
- Update maintainer entry to include refcount.rs and add myself as a
reviewer, as suggested by Boqun.
- Link to v2: https://lore.kernel.org/rust-for-linux/[email protected]
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 (4):
rust: implement kernel::sync::Refcount
rust: convert Arc to use Refcount
rust: block: convert block::mq to use Refcount
MAINTAINERS: update atomic infrastructure entry to include Rust
Gary Guo (5):
rust: implement kernel::sync::Refcount
rust: make Arc::into_unique_or_drop associated function
rust: convert Arc to use Refcount
rust: block: convert block::mq to use Refcount
MAINTAINERS: update atomic infrastructure entry to include Rust
MAINTAINERS | 2 + rust/helpers/refcount.c | 10 +++ rust/kernel/block/mq/operations.rs | 7 +- rust/kernel/block/mq/request.rs | 63 +++++------------ rust/kernel/sync.rs | 2 + rust/kernel/sync/arc.rs | 55 +++++---------- rust/kernel/sync/refcount.rs | 108 +++++++++++++++++++++++++++++ 7 files changed, 161 insertions(+), 86 deletions(-) create mode 100644 rust/kernel/sync/refcount.rs
base-commit: e04c78d86a9699d136910cfc0bdcf01087e3267e
Signature · 1 line
2.49.0
PATCH v4 1/5 rust: implement `kernel::sync::Refcount`
From: Gary Guo <[email protected]>
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 | 86 ++++++++++++++++++++++++++++++++++++ 3 files changed, 98 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
@@ -15,6 +15,7 @@mod locked_by;pub mod poll;pub mod rcu; +mod refcount;pub use arc::{Arc ,ArcBorrow ,UniqueArc };pub use condvar::{new_condvar,CondVar ,CondVarTimeoutResult };
@@ -22,6 +23,7 @@pub use lock::mutex::{new_mutex,Mutex ,MutexGuard };pub use lock::spinlock::{new_spinlock,SpinLock ,SpinLockGuard };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 +86 -0
86 lines not on this page · raw message
Signature · 1 line
2.49.0
Benno Lossin
reviewerRe: [PATCH v4 1/5] rust: implement `kernel::sync::Refcount`
rust/kernel/sync/refcount.rs line 23
Quoted 4 lines · Gary Guo
rust/kernel/sync/refcount.rs new file +4
-0+impl Refcount { +/// Construct a new [`Refcount`] from an initial value. +#[inline] +pub fn new (value:i32 ) ->Self {
Should we really allow users to set a negative value from the get-go? Here a u31 might come in real handy...
rust/kernel/sync/refcount.rs line 35
Quoted 12 lines
rust/kernel/sync/refcount.rs new file +12
-0+// SAFETY: There are no safety requirements for this FFI call. +Self (Opaque ::new (unsafe { bindings::REFCOUNT_INIT (value) })) + } + +#[inline] +fn as_ptr (&self) -> *mut bindings::refcount_t { + self.0 .get () + } + +/// Set a refcount's value. +#[inline] +pub fn set (&self, value:i32 ) {
Same here. We should of course provide a saturate function, but I don't see a reason to set it to another negative value.
---
Cheers,
Benno
Quoted 3 lines
rust/kernel/sync/refcount.rs new file +3
-0+// SAFETY: `self.as_ptr()` is valid. +unsafe { bindings::refcount_set (self.as_ptr (), value) } + }
Gary Guo
maintainerRe: [PATCH v4 1/5] rust: implement `kernel::sync::Refcount`
Quoted 9 lines · On Sun, 22 Jun 2025 23:05:09 +0200 "Benno Lossin" <[email protected]> wrote:
rust/kernel/sync/refcount.rs line 23
Quoted 4 lines · Gary Guo
rust/kernel/sync/refcount.rs new file +4
-0+impl Refcount { +/// Construct a new [`Refcount`] from an initial value. +#[inline] +pub fn new (value:i32 ) ->Self {Should we really allow users to set a negative value from the get-go? Here a
u31might come in real handy...
Quoted 15 lines
rust/kernel/sync/refcount.rs line 35
Quoted 12 lines
rust/kernel/sync/refcount.rs new file +12
-0+// SAFETY: There are no safety requirements for this FFI call. +Self (Opaque ::new (unsafe { bindings::REFCOUNT_INIT (value) })) + } + +#[inline] +fn as_ptr (&self) -> *mut bindings::refcount_t { + self.0 .get () + } + +/// Set a refcount's value. +#[inline] +pub fn set (&self, value:i32 ) {Same here. We should of course provide a
saturatefunction, but I don't see a reason to set it to another negative value.
Well, it's unlikely the caller would want to init/set the value to the saturated range, but given that refcount is effectively a thin wrapper of atomics, user can always obtain the atomics and modify the value.
Also, I did a quick grep of the C refcount API users:
* crypto/algapi.c uses -1 as a special value, and has invocation of refcount_set(..., -1)
* lib/stackdepot.c has a invocation to set the refcount into saturated range directly.
* There're a few cases where runtime values are set, so build_assert will not work for these use cases.
Ultimately I think it should be fine to expose i32 to the user of this API. Use of Refcount to manage resources typically require reasoning on the user side, so unintended error would be caught that way.
Quoted 8 lines
---
Cheers,
BennoQuoted 3 lines
rust/kernel/sync/refcount.rs new file +3
-0+// SAFETY: `self.as_ptr()` is valid. +unsafe { bindings::refcount_set (self.as_ptr (), value) } + }
Best,
Gary
PATCH v4 2/5 rust: make `Arc::into_unique_or_drop` associated function
In reply to Gary GuoFrom: Gary Guo <[email protected]>
Make Arc::into_unique_or_drop to become a mere associated function instead of a method (i.e. removing the self receiver).
It's a general convention for Rust smart pointers to avoid having methods defined on them, because if the pointee type has a method of the same name, then it is shadowed. This is normally for avoiding semver breakage, which isn't an issue for kernel codebase, but it's still generally a good practice to follow this rule, so that ptr.foo() would always be calling a method on the pointee type.
--- rust/kernel/sync/arc.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-)
rust/kernel/sync/arc.rs +6 -6
@@ -320,7 +320,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());
@@ -336,18 +336,18 @@ 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.get ();// 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
@@ -364,7 +364,7 @@ pub fn into_unique_or_drop(self) -> Option<Pin<UniqueArc<T>>> {// 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
Signature · 1 line
2.49.0
Re: [PATCH v4 2/5] rust: make `Arc::into_unique_or_drop` associated function
Quoted 5 lines · Gary Guo
From: Gary Guo <[email protected]>
Make
Arc::into_unique_or_dropto become a mere associated function instead of a method (i.e. removing theselfreceiver).
Quoted 8 lines
It's a general convention for Rust smart pointers to avoid having methods defined on them, because if the pointee type has a method of the same name, then it is shadowed. This is normally for avoiding semver breakage, which isn't an issue for kernel codebase, but it's still generally a good practice to follow this rule, so that
ptr.foo()would always be calling a method on the pointee type.Signed-off-by Gary Guo <[email protected]>
---
Cheers,
Benno
Quoted 3 lines
--- rust/kernel/sync/arc.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-)
PATCH v4 3/5 rust: convert `Arc` to use `Refcount`
In reply to Gary GuoFrom: Gary Guo <[email protected]>
With Refcount type created, Arc can use Refcount instead of calling into FFI directly.
--- rust/kernel/sync/arc.rs | 45 +++++++++++------------------------- rust/kernel/sync/refcount.rs | 8 +++++++ 2 files changed, 22 insertions(+), 31 deletions(-)
rust/kernel/sync/arc.rs +14 -31
@@ -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::InPlaceInit , + sync::Refcount , try_init, - types::{ForeignOwnable ,Opaque }, + types::ForeignOwnable , };use core::{ alloc::Layout ,
@@ -144,7 +144,7 @@ pub struct Arc<T: ?Sized> {#[pin_data] #[repr( C )] pub struct ArcInner <T : ?Sized > { - refcount:Opaque <bindings::refcount_t >, + refcount:Refcount , data:T , }
@@ -156,7 +156,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
@@ -228,8 +228,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, };
@@ -347,18 +346,13 @@ 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 this =ManuallyDrop ::new (this);// SAFETY: We own a refcount, so the pointer is still valid. -let refcount =unsafe { this.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 )) }; +if refcount.dec_and_test () { + refcount.set (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
@@ -428,14 +422,10 @@ fn as_ref(&self) -> &T {impl <T : ?Sized >Clone for Arc <T > {fn clone (&self) ->Self { -// SAFETY: By the type invariant, there is necessarily a reference to the object, so it is -// safe to dereference it. -let refcount =unsafe { self.ptr.as_ref () }.refcount.get (); - -// 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 (refcount) }; +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) }
@@ -444,16 +434,10 @@ 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. +let is_zero =unsafe { self.ptr.as_ref ().refcount.dec_and_test () };if is_zero {// The count reached zero, we must free the memory. //
@@ -747,8 +731,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 <- pin_init::uninit ::<T ,AllocError >(), }?AllocError ), flags,
rust/kernel/sync/refcount.rs +8 -0
@@ -71,6 +71,14 @@ pub fn dec(&self) {/// must come after. /// /// Returns true if the resulting refcount is 0, false otherwise. +/// +/// # Notes +/// +/// A common pattern of using `Refcount` is to free memory when the reference count reaches +/// zero. This means that the reference to `Refcount` could become invalid after calling this +/// function. This is fine as long as the reference to `Refcount` is no longer used when this +/// function returns `false`. It is not necessary to use raw pointers in this scenario, see +/// https://github.com/rust-lang/rust/issues/55005. #[inline] #[must_use = "use `dec` instead if you do not need to test if it is 0" ] pub fn dec_and_test (&self) ->bool {
Signature · 1 line
2.49.0
Benno Lossin
reviewerRe: [PATCH v4 3/5] rust: convert `Arc` to use `Refcount`
Quoted 4 lines · Gary Guo
rust/kernel/sync/arc.rs +0
-0@@ -428,14 +422,10 @@ fn as_ref(&self) -> &T {impl <T : ?Sized >Clone for Arc <T > {fn clone (&self) ->Self {
rust/kernel/sync/arc.rs fn as_ref(&self) -> &T { · line 428
Quoted 10 lines
rust/kernel/sync/arc.rs +2
-6-// SAFETY: By the type invariant, there is necessarily a reference to the object, so it is -// safe to dereference it. -let refcount =unsafe { self.ptr.as_ref () }.refcount.get (); - -// 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 (refcount) }; +unsafe { self.ptr.as_ref ().refcount.inc () };
The .refcount.inc() can be outside of the unsafe block.
Quoted 9 lines
rust/kernel/sync/arc.rs +0
-2// SAFETY: We just incremented the refcount. This increment is now owned by the new `Arc`. unsafe {Self ::from_inner (self.ptr) }@@ -444,16 +434,10 @@ 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
rust/kernel/sync/arc.rs fn clone(&self) -> Self { · line 440
Quoted 10 lines
rust/kernel/sync/arc.rs +2
-6-// 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. +let is_zero =unsafe { self.ptr.as_ref ().refcount.dec_and_test () };
Ditto.
Quoted 19 lines
rust/kernel/sync/arc.rs +1
-2if is_zero {// The count reached zero, we must free the memory. // @@ -747,8 +731,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 <- pin_init::uninit ::<T ,AllocError >(), }?AllocError ), flags,rust/kernel/sync/refcount.rs +0
-0@@ -71,6 +71,14 @@ pub fn dec(&self) {/// must come after.
rust/kernel/sync/refcount.rs pub fn dec(&self) { · line 81
Quoted 10 lines
rust/kernel/sync/refcount.rs +8
-0/// /// Returns true if the resulting refcount is 0, false otherwise. +/// +/// # Notes +/// +/// A common pattern of using `Refcount` is to free memory when the reference count reaches +/// zero. This means that the reference to `Refcount` could become invalid after calling this +/// function. This is fine as long as the reference to `Refcount` is no longer used when this +/// function returns `false`. It is not necessary to use raw pointers in this scenario, see +/// https://github.com/rust-lang/rust/issues/55005.
This should be in patch 1?
---
Cheers,
Benno
Quoted 3 lines
rust/kernel/sync/refcount.rs +0
-0#[inline] #[must_use = "use `dec` instead if you do not need to test if it is 0" ] pub fn dec_and_test (&self) ->bool {
kernel test robot
build botRe: [PATCH v4 3/5] rust: convert `Arc` to use `Refcount`
In reply to Gary Guokernel test robot noticed the following build warnings:
Hi Gary,
kernel test robot noticed the following build warnings:
[auto build test WARNING on e04c78d86a9699d136910cfc0bdcf01087e3267e]
url: https://github.com/intel-lab-lkp/linux/commits/Gary-Guo/rust-implement-kernel-sync-Refcount/20250622-210132 base: e04c78d86a9699d136910cfc0bdcf01087e3267e patch link: https://lore.kernel.org/r/20250622125802.3224264-4-gary%40kernel.org patch subject: [PATCH v4 3/5] rust: convert `Arc` to use `Refcount` config: x86_64-rhel-9.4-rust (https://download.01.org/0day-ci/archive/20250623/[email protected]/config) compiler: clang version 18.1.8 (https://github.com/llvm/llvm-project 3b5b5c1ec4a3095ab096dd780e84d7ab81f3d7ff) rustc: rustc 1.78.0 (9b00956e5 2024-04-29) reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20250623/[email protected]/reproduce)
If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/
All warnings (new ones prefixed by >>):
>> warning: this URL is not a hyperlink
--> rust/kernel/sync/refcount.rs:81:9
|
81 | /// https://github.com/rust-lang/rust/issues/55005.
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use an automatic link instead: <https://github.com/rust-lang/rust/issues/55005.>
|
= note: bare URLs are not automatically turned into clickable links = note: #[warn(rustdoc::bare_urls)] on by default
Signature · 2 lines
0-DAY CI Kernel Test Service https://github.com/intel/lkp-tests/wiki
PATCH v4 4/5 rust: block: convert `block::mq` to use `Refcount`
In reply to Gary GuoFrom: Gary Guo <[email protected]>
Currently 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 | 63 ++++++++---------------------- rust/kernel/sync/refcount.rs | 14 +++++++ 3 files changed, 34 insertions(+), 50 deletions(-)
rust/kernel/block/mq/operations.rs +4 -3
@@ -10,9 +10,10 @@ block::mq::Request, error::{from_result, Result}, prelude::*, + 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. ///
@@ -78,7 +79,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`.
@@ -187,7 +188,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 +16 -47
120 lines not on this page · raw message
rust/kernel/sync/refcount.rs +14 -0
@@ -4,6 +4,8 @@//! //! C header: [`include/linux/refcount.h`](srctree/include/linux/refcount.h) +use core::sync::atomic::AtomicI32 ; +use crate ::types::Opaque ;/// Atomic reference counter.
@@ -30,6 +32,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 ().cast (); +// 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 being considered saturated and "bad". +unsafe { &*ptr } + } +/// Set a refcount's value. #[inline] pub fn set (&self, value:i32 ) {
Signature · 1 line
2.49.0
PATCH v4 5/5 MAINTAINERS: update atomic infrastructure entry to include Rust
In reply to Gary GuoFrom: Gary Guo <[email protected]>
I would like to help review atomic related patches, especially Rust related ones, hence add myself as an reviewer.
--- MAINTAINERS | 2 ++ 1 file changed, 2 insertions(+)
MAINTAINERS +2 -0
@@ -3896,12 +3896,14 @@ M: Will Deacon <[email protected]> M: Peter Zijlstra <[email protected]> R: Boqun Feng <[email protected]> R: Mark Rutland <[email protected]> +R: Gary Guo <[email protected]> L: [email protected] S: Maintained F: Documentation/atomic_*.txt F: arch/*/include/asm/atomic*.h F: include/*/atomic*.h F: include/linux/refcount.h +F: rust/kernel/sync/refcount.rs F: scripts/atomic/ ATTO EXPRESSSAS SAS/SATA RAID SCSI DRIVER
Signature · 1 line
2.49.0