Re: [PATCH 1/3] rust: implement `kernel::sync::Refcount`
From: Gary Guo
Date: Sat Oct 05 2024 - 10:26:26 EST
On Sat, 5 Oct 2024 14:31:06 +0100
Gary Guo <gary@xxxxxxxxxxx> wrote:
> On Sat, 5 Oct 2024 09:40:53 +0200
> Greg KH <gregkh@xxxxxxxxxxxxxxxxxxx> wrote:
>
> > On Fri, Oct 04, 2024 at 04:52:22PM +0100, Gary Guo wrote:
> > > This is a wrapping layer of `include/linux/refcount.h`. Currently only
> > > the most basic operations (read/set/inc/dec/dec_and_test) are implemented,
> > > additional methods can be implemented when they are needed.
> > >
> > > Currently the kernel refcount has already been used in `Arc`, however it
> > > calls into FFI directly.
> > >
> > > Cc: Will Deacon <will@xxxxxxxxxx>
> > > Cc: Peter Zijlstra <peterz@xxxxxxxxxxxxx>
> > > Cc: Boqun Feng <boqun.feng@xxxxxxxxx>
> > > Cc: Mark Rutland <mark.rutland@xxxxxxx>
> > > Signed-off-by: Gary Guo <gary@xxxxxxxxxxx>
> > > ---
> > > rust/helpers/refcount.c | 15 ++++++
> > > rust/kernel/sync.rs | 2 +
> > > rust/kernel/sync/refcount.rs | 94 ++++++++++++++++++++++++++++++++++++
> > > 3 files changed, 111 insertions(+)
> > > create mode 100644 rust/kernel/sync/refcount.rs
> > >
> > > diff --git a/rust/helpers/refcount.c b/rust/helpers/refcount.c
> > > index f47afc148ec3..39649443426b 100644
> > > --- a/rust/helpers/refcount.c
> > > +++ b/rust/helpers/refcount.c
> > > @@ -8,11 +8,26 @@ refcount_t rust_helper_REFCOUNT_INIT(int n)
> > > return (refcount_t)REFCOUNT_INIT(n);
> > > }
> > >
> > > +unsigned int rust_helper_refcount_read(refcount_t *r)
> > > +{
> > > + return refcount_read(r);
> > > +}
> >
> > Reading a refcount is almost always a wrong thing to do (it can change
> > right after you read it), and I don't see any of the later patches in
> > this series use this call, so can you just drop this?
> >
> > thanks,
> >
> > greg k-h
>
> I originally introduced this thinking I can replace Andreas's atomic
> 2->0 operation with a read + set, but ended up couldn't do it.
>
> The refcount read is still useful to determine if the current value is
> 1 -- in fact, `Arc::into_unique_or_drop` could use this rather than
> decrementing the refcount and then incrementing it again (just doing a
> refcount read would be much better codegen-wise than the current
> behaviour). I'll probably make this change in the next version of the
> series.
Actually `into_unique_or_drop` can't use this because it needs to avoid
running destructor when it races with other threads. The semantics for
that function is better reflected with `refcount_dec_not_one`, which
I'll introduce in v2, and I'll drop `read` in v2.
Best,
Gary
>
> It might also be useful for debugging, so we can have a `Debug` impl
> for `Refcount` which prints out the current value. But I didn't
> introduce it due to no user.
>
> Best,
> Gary
>