Re: [PATCH] rust: sync: make `AlwaysRefCounted::inc_ref` an associated function
From: Andreas Hindborg
Date: Thu Nov 26 2026 - 05:36:39 EST
"Tran Van Tien" <7enlab@xxxxxxxxx> writes:
> `AlwaysRefCounted::inc_ref` is currently a method taking `&self`, which
> makes it easy to increment the reference count by accident on any value
> that happens to be in scope. Incrementing the refcount should be a
> deliberate act: every successful call must be paired with exactly one
> `dec_ref`, and getting that wrong leaks the object or frees it early.
>
> `dec_ref` is already an associated function taking `NonNull<Self>` for
> the same reason. Align `inc_ref` with it so that the two halves of the
> refcount protocol have the same shape, and so that a call site has to
> name the type explicitly.
>
> Callers that legitimately need to increment the refcount now obtain a
> `NonNull` first, which also makes the safety requirement explicit: the
> pointer must be valid.
>
> This is a mechanical conversion of the trait and of all 27
> implementations in-tree. `ARef::clone` and `From<&T> for ARef<T>`
> already hold a `NonNull`, so they pass it directly. `serdev::Device`
> forwards to the inner `device::Device` implementation. `Fence`,
> `FwNode`, `GpuVm`, `I2cAdapter`, `I2cClient`, `Request`, `Mm`,
> `MmWithUser`, `MmWithUserAsync`, `OPP`, `Chip`, `Credential`,
> `PidNamespace`, `Task`, `LocalFile`, `File`, and `Device` (platform,
> pci, usb, auxiliary, drm) each take the raw pointer through a shared
> reference.
>
> All 27 implementations are converted; no behaviour changes.
>
> Suggested-by: Benno Lossin <lossin@xxxxxxxxxx>
> Link: https://github.com/Rust-for-Linux/linux/issues/1177
> Signed-off-by: Tran Van Tien <7enlab@xxxxxxxxx>
<cut>
> diff --git a/rust/kernel/sync/aref.rs b/rust/kernel/sync/aref.rs
> index 9983ee085..0198c042e 100644
> --- a/rust/kernel/sync/aref.rs
> +++ b/rust/kernel/sync/aref.rs
> @@ -49,7 +49,11 @@
> /// alive.)
> pub unsafe trait AlwaysRefCounted {
> /// Increments the reference count on the object.
> - fn inc_ref(&self);
> + ///
> + /// # Safety
> + ///
> + /// Callers must ensure that `obj` points to a valid object of this type.
> + unsafe fn inc_ref(obj: NonNull<Self>);
I do not think we should make this unsafe. Leaking is safe. I also I
don't think there is any reason to make this take `NonNull`. You can
make it an associated function that takes `this: &Self`.
Best regards,
Andreas Hindborg