Re: [PATCH v3 1/4] rust: implement `kernel::sync::Refcount`

From: Gary Guo
Date: Fri Feb 21 2025 - 11:19:52 EST


On Wed, 19 Feb 2025 17:12:19 -0500
Tamir Duberstein <tamird@xxxxxxxxx> wrote:

> On Wed, Feb 19, 2025 at 3:17 PM Gary Guo <gary@xxxxxxxxxxx> wrote:
> >
> > 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.
> >
> > Reviewed-by: Alice Ryhl <aliceryhl@xxxxxxxxxx>
> > Reviewed-by: Boqun Feng <boqun.feng@xxxxxxxxx>
> > Signed-off-by: Gary Guo <gary@xxxxxxxxxxx>
> > ---
> > 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
> >
>
> <snip>
>
> > + /// Decrement a refcount.
> > + ///
> > + /// It will `WARN` on underflow and fail to decrement when saturated.
> > + ///
> > + /// Provides release memory ordering, such that prior loads and stores are done
> > + /// before.
> > + #[inline]
> > + pub fn dec(&self) {
> > + // SAFETY: `self.as_ptr()` is valid.
> > + unsafe { bindings::refcount_dec(self.as_ptr()) }
> > + }
> > +
> > + /// Decrement a refcount and test if it is 0.
> > + ///
> > + /// It will `WARN` on underflow and fail to decrement when saturated.
> > + ///
> > + /// Provides release memory ordering, such that prior loads and stores are done
> > + /// before, and provides an acquire ordering on success such that memory deallocation
> > + /// must come after.
> > + ///
> > + /// Returns true if the resulting refcount is 0, false otherwise.
> > + #[inline]
> > + #[must_use = "use `dec` instead you do not need to test if it is 0"]
>
> The word "if" seems to be missing?

Ack

>
> The C function comment includes this bit:
>
> * Use of this function is not recommended for the normal reference counting
> * use case in which references are taken and released one at a time. In these
> * cases, refcount_dec(), or one of its variants, should instead be used to
> * decrement a reference count.
>
> Do we need to include this warning?

I think you're referring to refcount_sub_and_test? This is
refcount_dec_and_test.

Best,
Gary

>
>
> [...]