Skip to contentSkip to conversation

rust: sync: make `AlwaysRefCounted::inc_ref` an associated function

PATCH Superseded Tran Van Tien 3 participants 7 messages Nov 26

Subsystems (20)
DRM drivers VFS USB Driver core +16 more subsystems
lore
Share & tools
lore
#0 lore raw

PATCH 1/1 rust: sync: make `AlwaysRefCounted::inc_ref` an associated function

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.

---
 rust/kernel/auxiliary.rs         |  6 +++---
 rust/kernel/block/mq/request.rs  |  5 +++--
 rust/kernel/cred.rs              |  7 ++++---
 rust/kernel/device.rs            |  7 ++++---
 rust/kernel/device/property.rs   |  8 ++++----
 rust/kernel/dma_buf/dma_fence.rs |  6 +++---
 rust/kernel/drm/device.rs        |  6 +++---
 rust/kernel/drm/gem/mod.rs       |  4 ++--
 rust/kernel/drm/gpuvm/mod.rs     |  6 +++---
 rust/kernel/drm/gpuvm/vm_bo.rs   |  6 +++---
 rust/kernel/fs/file.rs           | 13 +++++++------
 rust/kernel/fwctl.rs             |  4 ++--
 rust/kernel/i2c.rs               | 12 ++++++------
 rust/kernel/mm.rs                | 12 ++++++------
 rust/kernel/mm/mmput_async.rs    |  6 +++---
 rust/kernel/opp.rs               |  6 +++---
 rust/kernel/pci.rs               |  6 +++---
 rust/kernel/pid_namespace.rs     |  7 ++++---
 rust/kernel/platform.rs          |  6 +++---
 rust/kernel/pwm.rs               |  6 +++---
 rust/kernel/serdev.rs            |  5 +++--
 rust/kernel/sync/aref.rs         | 17 ++++++++++++-----
 rust/kernel/task.rs              |  7 ++++---
 rust/kernel/usb.rs               | 12 ++++++------
 24 files changed, 97 insertions(+), 83 deletions(-)
rust/kernel/auxiliary.rs +3 -3
index 9d3de109b..d394b2098 100644
@@ -390,9 +390,9 @@ unsafe impl<Ctx: device::DeviceContext> device::AsBusDevice<Ctx> for Device<Ctx>
 
 // SAFETY: Instances of `Device` are always reference-counted.
 unsafe impl crate::sync::aref::AlwaysRefCounted for Device {
-    fn inc_ref(&self) {
-        // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
-        unsafe { bindings::get_device(self.as_ref().as_raw()) };
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The safety requirements guarantee that `obj` points to a valid object.
+        unsafe { bindings::get_device(core::ptr::addr_of_mut!((*obj.as_ref().as_raw()).dev)) };
     }
 
     unsafe fn dec_ref(obj: NonNull<Self>) {
rust/kernel/block/mq/request.rs +3 -2
index 6115f9aec..7ef0822b2 100644
@@ -240,8 +240,9 @@ unsafe impl<T: Operations> Sync for Request<T> {}
 // keeps the object alive in memory at least until a matching reference count
 // decrement is executed.
 unsafe impl<T: Operations> AlwaysRefCounted for Request<T> {
-    fn inc_ref(&self) {
-        self.wrapper_ref().refcount().inc();
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The safety requirements guarantee that `obj` is valid.
+        unsafe { obj.as_ref().wrapper_ref().refcount().inc() };
     }
 
     unsafe fn dec_ref(obj: core::ptr::NonNull<Self>) {
rust/kernel/cred.rs +4 -3
index ffa156b9d..2a2b2d3b0 100644
@@ -9,6 +9,7 @@
 //! Reference: <https://www.kernel.org/doc/html/latest/security/credentials.html>
 
 use crate::{bindings, sync::aref::AlwaysRefCounted, task::Kuid, types::Opaque};
+use core::ptr::NonNull;
 
 /// Wraps the kernel's `struct cred`.
 ///
@@ -78,9 +79,9 @@ pub fn euid(&self) -> Kuid {
 // SAFETY: The type invariants guarantee that `Credential` is always ref-counted.
 unsafe impl AlwaysRefCounted for Credential {
     #[inline]
-    fn inc_ref(&self) {
-        // SAFETY: The existence of a shared reference means that the refcount is nonzero.
-        unsafe { bindings::get_cred(self.0.get()) };
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The safety requirements guarantee that `obj` points to a valid object.
+        unsafe { bindings::get_cred(obj.as_ref().0.get()) };
     }
 
     #[inline]
rust/kernel/device.rs +4 -3
index 2291d85b6..6212a6c3d 100644
@@ -14,6 +14,7 @@
         Opaque, //
     }, //
 };
+use core::ptr::NonNull;
 use core::{
     marker::PhantomData,
     ptr, //
@@ -436,9 +437,9 @@ pub fn name(&self) -> &CStr {
 
 // SAFETY: Instances of `Device` are always reference-counted.
 unsafe impl crate::sync::aref::AlwaysRefCounted for Device {
-    fn inc_ref(&self) {
-        // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
-        unsafe { bindings::get_device(self.as_raw()) };
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The safety requirements guarantee that `obj` points to a valid object.
+        unsafe { bindings::get_device(obj.as_ref().as_raw()) };
     }
 
     unsafe fn dec_ref(obj: ptr::NonNull<Self>) {
rust/kernel/device/property.rs +4 -4
index 5aead835f..171fabfeb 100644
@@ -4,6 +4,7 @@
 //!
 //! C header: [`include/linux/property.h`](srctree/include/linux/property.h)
 
+use core::ptr::NonNull;
 use core::{mem::MaybeUninit, ptr};
 
 use super::private::Sealed;
@@ -361,10 +362,9 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 
 // SAFETY: Instances of `FwNode` are always reference-counted.
 unsafe impl crate::sync::aref::AlwaysRefCounted for FwNode {
-    fn inc_ref(&self) {
-        // SAFETY: The existence of a shared reference guarantees that the
-        // refcount is non-zero.
-        unsafe { bindings::fwnode_handle_get(self.as_raw()) };
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The safety requirements guarantee that `obj` points to a valid object.
+        unsafe { bindings::fwnode_handle_get(obj.as_ref().as_raw()) };
     }
 
     unsafe fn dec_ref(obj: ptr::NonNull<Self>) {
rust/kernel/dma_buf/dma_fence.rs +3 -3
index 18a43e1bb..ed89e117a 100644
@@ -566,9 +566,9 @@ pub unsafe fn from_raw<'a>(ptr: *mut bindings::dma_fence) -> &'a Self {
 // SAFETY: These implement the C backends refcounting methods which are proven
 // to work correctly.
 unsafe impl AlwaysRefCounted for Fence {
-    fn inc_ref(&self) {
-        // SAFETY: `self.as_raw()` is a pointer to a valid `struct dma_fence`.
-        unsafe { bindings::dma_fence_get(self.as_raw()) }
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: `obj.as_ref().as_raw()` is a pointer to a valid `struct dma_fence`.
+        unsafe { bindings::dma_fence_get(obj.as_ref().as_raw()) }
     }
 
     unsafe fn dec_ref(ptr: NonNull<Self>) {
rust/kernel/drm/device.rs +3 -3
index 6b88ade28..db3df7085 100644
@@ -481,9 +481,9 @@ fn deref(&self) -> &Self::Target {
 // SAFETY: DRM device objects are always reference counted and the get/put functions
 // satisfy the requirements.
 unsafe impl<T: drm::Driver> AlwaysRefCounted for Device<T> {
-    fn inc_ref(&self) {
-        // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
-        unsafe { bindings::drm_dev_get(self.as_raw()) };
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The safety requirements guarantee that `obj` points to a valid object.
+        unsafe { bindings::drm_dev_get(obj.as_ref().as_raw()) };
     }
 
     unsafe fn dec_ref(obj: NonNull<Self>) {
rust/kernel/drm/gem/mod.rs +2 -2
index 85657a39e..e064de8ef 100644
@@ -52,10 +52,10 @@ unsafe impl $( <$( $tparam_id ),+> )? $crate::sync::aref::AlwaysRefCounted for $
             Self: IntoGEMObject,
             $( $( $bind_param : $bind_trait ),+ )?
         {
-            fn inc_ref(&self) {
+            unsafe fn inc_ref(obj: NonNull<Self>){
                 // SAFETY: The existence of a shared reference guarantees that the refcount is
                 // non-zero.
-                unsafe { bindings::drm_gem_object_get(self.as_raw()) };
+                unsafe { bindings::drm_gem_object_get(obj.as_ref().as_raw()) };
             }
 
             unsafe fn dec_ref(obj: core::ptr::NonNull<Self>) {
rust/kernel/drm/gpuvm/mod.rs +3 -3
index d9d43d719..b8ac14d04 100644
@@ -82,9 +82,9 @@ unsafe impl<T: DriverGpuVm> Sync for GpuVm<T> {}
 
 // SAFETY: By type invariants, the allocation is managed by the refcount in `self.vm`.
 unsafe impl<T: DriverGpuVm> AlwaysRefCounted for GpuVm<T> {
-    fn inc_ref(&self) {
-        // SAFETY: By type invariants, the allocation is managed by the refcount in `self.vm`.
-        unsafe { bindings::drm_gpuvm_get(self.vm.get()) };
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: By type invariants, the allocation is managed by the refcount in `obj.vm`.
+        unsafe { bindings::drm_gpuvm_get(obj.vm.get()) };
     }
 
     unsafe fn dec_ref(obj: NonNull<Self>) {
rust/kernel/drm/gpuvm/vm_bo.rs +3 -3
index 5989972da..b46aa9ef3 100644
@@ -30,9 +30,9 @@ unsafe impl<T: DriverGpuVm> Sync for GpuVmBo<T> {}
 
 // SAFETY: By type invariants, the allocation is managed by the refcount in `self.inner`.
 unsafe impl<T: DriverGpuVm> AlwaysRefCounted for GpuVmBo<T> {
-    fn inc_ref(&self) {
-        // SAFETY: By type invariants, the allocation is managed by the refcount in `self.inner`.
-        unsafe { bindings::drm_gpuvm_bo_get(self.inner.get()) };
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: By type invariants, the allocation is managed by the refcount in `obj.inner`.
+        unsafe { bindings::drm_gpuvm_bo_get(obj.inner.get()) };
     }
 
     unsafe fn dec_ref(obj: NonNull<Self>) {
rust/kernel/fs/file.rs +7 -6
index 23ee689bd..c5a2649ae 100644
@@ -16,6 +16,7 @@
     types::{NotThreadSafe, Opaque},
 };
 use core::ptr;
+use core::ptr::NonNull;
 
 /// Primitive type representing the offset within a [`File`].
 ///
@@ -199,9 +200,9 @@ unsafe impl Sync for File {}
 // makes `ARef<File>` own a normal refcount.
 unsafe impl AlwaysRefCounted for File {
     #[inline]
-    fn inc_ref(&self) {
-        // SAFETY: The existence of a shared reference means that the refcount is nonzero.
-        unsafe { bindings::get_file(self.as_ptr()) };
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The safety requirements guarantee that `obj` points to a valid object.
+        unsafe { bindings::get_file(obj.as_ref().as_ptr()) };
     }
 
     #[inline]
@@ -235,9 +236,9 @@ pub struct LocalFile {
 // makes `ARef<LocalFile>` own a normal refcount.
 unsafe impl AlwaysRefCounted for LocalFile {
     #[inline]
-    fn inc_ref(&self) {
-        // SAFETY: The existence of a shared reference means that the refcount is nonzero.
-        unsafe { bindings::get_file(self.as_ptr()) };
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The safety requirements guarantee that `obj` points to a valid object.
+        unsafe { bindings::get_file(obj.as_ref().as_ptr()) };
     }
 
     #[inline]
rust/kernel/fwctl.rs +2 -2
index b7778e4d5..8f1d094b5 100644
@@ -261,9 +261,9 @@ fn as_ref(&self) -> &device::Device {
 // `fwctl_put` decrements it and frees the device when it reaches zero.
 unsafe impl<T: Operations> AlwaysRefCounted for Device<T> {
     #[inline]
-    fn inc_ref(&self) {
+    unsafe fn inc_ref(obj: NonNull<Self>) {
         // SAFETY: `self` holds a live reference.
-        unsafe { bindings::fwctl_get(self.as_raw()) };
+        unsafe { bindings::fwctl_get(obj.as_ref().as_raw()) };
     }
 
     #[inline]
rust/kernel/i2c.rs +6 -6
index b4ff25c83..6ccfe8ff3 100644
@@ -416,9 +416,9 @@ pub fn get(index: i32) -> Result<ARef<Self>> {
 // SAFETY: Instances of `I2cAdapter` are always reference-counted.
 unsafe impl AlwaysRefCounted for I2cAdapter {
     #[inline]
-    fn inc_ref(&self) {
-        // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
-        unsafe { bindings::i2c_get_adapter(self.index()) };
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The safety requirements guarantee that `obj` points to a valid object.
+        unsafe { bindings::i2c_get_adapter(obj.as_ref().index()) };
     }
 
     #[inline]
@@ -493,9 +493,9 @@ unsafe impl<Ctx: device::DeviceContext> device::AsBusDevice<Ctx> for I2cClient<C
 
 // SAFETY: Instances of `I2cClient` are always reference-counted.
 unsafe impl AlwaysRefCounted for I2cClient {
-    fn inc_ref(&self) {
-        // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
-        unsafe { bindings::get_device(self.as_ref().as_raw()) };
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The safety requirements guarantee that `obj` points to a valid object.
+        unsafe { bindings::get_device(obj.as_ref().as_ref().as_raw()) };
     }
 
     unsafe fn dec_ref(obj: NonNull<Self>) {
rust/kernel/mm.rs +6 -6
index 58bc1793f..f5deac0b7 100644
@@ -57,9 +57,9 @@ unsafe impl Sync for Mm {}
 // SAFETY: By the type invariants, this type is always refcounted.
 unsafe impl AlwaysRefCounted for Mm {
     #[inline]
-    fn inc_ref(&self) {
-        // SAFETY: The pointer is valid since self is a reference.
-        unsafe { bindings::mmgrab(self.as_raw()) };
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The pointer is valid since obj is a reference.
+        unsafe { bindings::mmgrab(obj.as_ref().as_raw()) };
     }
 
     #[inline]
@@ -93,9 +93,9 @@ unsafe impl Sync for MmWithUser {}
 // SAFETY: By the type invariants, this type is always refcounted.
 unsafe impl AlwaysRefCounted for MmWithUser {
     #[inline]
-    fn inc_ref(&self) {
-        // SAFETY: The pointer is valid since self is a reference.
-        unsafe { bindings::mmget(self.as_raw()) };
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The pointer is valid since obj is a reference.
+        unsafe { bindings::mmget(obj.as_ref().as_raw()) };
     }
 
     #[inline]
rust/kernel/mm/mmput_async.rs +3 -3
index b8d2f0512..2e490f8ce 100644
@@ -36,9 +36,9 @@ unsafe impl Sync for MmWithUserAsync {}
 // SAFETY: By the type invariants, this type is always refcounted.
 unsafe impl AlwaysRefCounted for MmWithUserAsync {
     #[inline]
-    fn inc_ref(&self) {
-        // SAFETY: The pointer is valid since self is a reference.
-        unsafe { bindings::mmget(self.as_raw()) };
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The safety requirements guarantee that `obj` is valid.
+        unsafe { bindings::mmget(obj.as_ref().as_raw()) };
     }
 
     #[inline]
rust/kernel/opp.rs +3 -3
index 62e446761..651cbc945 100644
@@ -1043,9 +1043,9 @@ unsafe impl Sync for OPP {}
 /// SAFETY: The type invariants guarantee that [`OPP`] is always refcounted.
 unsafe impl AlwaysRefCounted for OPP {
     #[inline]
-    fn inc_ref(&self) {
-        // SAFETY: The existence of a shared reference means that the refcount is nonzero.
-        unsafe { bindings::dev_pm_opp_get(self.0.get()) };
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The safety requirements guarantee that `obj` points to a valid object.
+        unsafe { bindings::dev_pm_opp_get(obj.0.get()) };
     }
 
     #[inline]
rust/kernel/pci.rs +3 -3
index 769d01d23..0fdf7caa5 100644
@@ -512,9 +512,9 @@ impl<'a> crate::dma::Device<'a> for Device<device::Core<'a>> {}
 // SAFETY: Instances of `Device` are always reference-counted.
 unsafe impl crate::sync::aref::AlwaysRefCounted for Device {
     #[inline]
-    fn inc_ref(&self) {
-        // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
-        unsafe { bindings::pci_dev_get(self.as_raw()) };
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The safety requirements guarantee that `obj` points to a valid object.
+        unsafe { bindings::pci_dev_get(obj.as_ref().as_raw()) };
     }
 
     #[inline]
rust/kernel/pid_namespace.rs +4 -3
index 979a9718f..fdc0243f5 100644
@@ -9,6 +9,7 @@
 
 use crate::{bindings, sync::aref::AlwaysRefCounted, types::Opaque};
 use core::ptr;
+use core::ptr::NonNull;
 
 /// Wraps the kernel's `struct pid_namespace`. Thread safe.
 ///
@@ -43,9 +44,9 @@ pub unsafe fn from_ptr<'a>(ptr: *const bindings::pid_namespace) -> &'a Self {
 // SAFETY: Instances of `PidNamespace` are always reference-counted.
 unsafe impl AlwaysRefCounted for PidNamespace {
     #[inline]
-    fn inc_ref(&self) {
-        // SAFETY: The existence of a shared reference means that the refcount is nonzero.
-        unsafe { bindings::get_pid_ns(self.as_ptr()) };
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The safety requirements guarantee that `obj` points to a valid object.
+        unsafe { bindings::get_pid_ns(obj.as_ref().as_ptr()) };
     }
 
     #[inline]
rust/kernel/platform.rs +3 -3
index ac0a012ae..0c166c220 100644
@@ -535,9 +535,9 @@ impl<'a> crate::dma::Device<'a> for Device<device::Core<'a>> {}
 
 // SAFETY: Instances of `Device` are always reference-counted.
 unsafe impl crate::sync::aref::AlwaysRefCounted for Device {
-    fn inc_ref(&self) {
-        // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
-        unsafe { bindings::get_device(self.as_ref().as_raw()) };
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The safety requirements guarantee that `obj` points to a valid object.
+        unsafe { bindings::get_device(core::ptr::addr_of_mut!((*obj.as_ref().as_raw()).dev)) };
     }
 
     unsafe fn dec_ref(obj: NonNull<Self>) {
rust/kernel/pwm.rs +3 -3
index 8aa47304b..f4f9d858e 100644
@@ -629,10 +629,10 @@ pub fn new<'a>(
 // SAFETY: Implements refcounting for `Chip` using the embedded `struct device`.
 unsafe impl<T: PwmOps> AlwaysRefCounted for Chip<T> {
     #[inline]
-    fn inc_ref(&self) {
-        // SAFETY: `self.0.get()` points to a valid `pwm_chip` because `self` exists.
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: `obj.0.get()` points to a valid `pwm_chip` because `self` exists.
         // The embedded `dev` is valid. `get_device` increments its refcount.
-        unsafe { bindings::get_device(&raw mut (*self.0.get()).dev) };
+        unsafe { bindings::get_device(&raw mut (*obj.0.get()).dev) };
     }
 
     #[inline]
rust/kernel/serdev.rs +3 -2
index 17ca504b7..7319a5c4a 100644
@@ -571,8 +571,9 @@ unsafe impl<Ctx: device::DeviceContext> device::AsBusDevice<Ctx> for Device<Ctx>
 
 // SAFETY: Instances of `Device` are always reference-counted.
 unsafe impl AlwaysRefCounted for Device {
-    fn inc_ref(&self) {
-        self.as_ref().inc_ref();
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The safety requirements of this function guarantee that `obj` is valid.
+        unsafe { Device::inc_ref(obj.cast()) };
     }
 
     unsafe fn dec_ref(obj: NonNull<Self>) {
rust/kernel/sync/aref.rs +12 -5
index 9983ee085..0198c042e 100644
@@ -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>);
 
     /// Decrements the reference count on the object.
     ///
@@ -131,7 +135,7 @@ pub unsafe fn from_raw(ptr: NonNull<T>) -> Self {
     ///
     /// # // SAFETY: TODO.
     /// unsafe impl AlwaysRefCounted for Empty {
-    ///     fn inc_ref(&self) {}
+    ///     unsafe fn inc_ref(_obj: NonNull<Self>) {}
     ///     unsafe fn dec_ref(_obj: NonNull<Self>) {}
     /// }
     ///
@@ -150,7 +154,8 @@ pub fn into_raw(me: Self) -> NonNull<T> {
 
 impl<T: AlwaysRefCounted> Clone for ARef<T> {
     fn clone(&self) -> Self {
-        self.inc_ref();
+        // SAFETY: The type invariants guarantee that `self.ptr` is valid.
+        unsafe { T::inc_ref(self.ptr) };
         // SAFETY: We just incremented the refcount above.
         unsafe { Self::from_raw(self.ptr) }
     }
@@ -167,9 +172,11 @@ fn deref(&self) -> &Self::Target {
 
 impl<T: AlwaysRefCounted> From<&T> for ARef<T> {
     fn from(b: &T) -> Self {
-        b.inc_ref();
+        let ptr = NonNull::from(b);
+        // SAFETY: `ptr` comes from a live shared reference.
+        unsafe { T::inc_ref(ptr) };
         // SAFETY: We just incremented the refcount above.
-        unsafe { Self::from_raw(NonNull::from(b)) }
+        unsafe { Self::from_raw(ptr) }
     }
 }
 
rust/kernel/task.rs +4 -3
index 3336df493..c60e6e0cb 100644
@@ -12,6 +12,7 @@
     sync::aref::ARef,
     types::{NotThreadSafe, Opaque},
 };
+use core::ptr::NonNull;
 use core::{
     ops::Deref,
     ptr, //
@@ -349,9 +350,9 @@ pub fn group_leader(&self) -> &Task {
 // SAFETY: The type invariants guarantee that `Task` is always refcounted.
 unsafe impl crate::sync::aref::AlwaysRefCounted for Task {
     #[inline]
-    fn inc_ref(&self) {
-        // SAFETY: The existence of a shared reference means that the refcount is nonzero.
-        unsafe { bindings::get_task_struct(self.as_ptr()) };
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The safety requirements guarantee that `obj` points to a valid object.
+        unsafe { bindings::get_task_struct(obj.as_ref().as_ptr()) };
     }
 
     #[inline]
rust/kernel/usb.rs +6 -6
index 993760ff3..812159a82 100644
@@ -375,11 +375,11 @@ fn as_ref(&self) -> &Device {
 // SAFETY: Instances of `Interface` are always reference-counted.
 unsafe impl AlwaysRefCounted for Interface {
     #[inline]
-    fn inc_ref(&self) {
-        // SAFETY: The invariants of `Interface` guarantee that `self.as_raw()`
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The invariants of `Interface` guarantee that `obj.as_ref().as_raw()`
         // returns a valid `struct usb_interface` pointer, for which we will
         // acquire a new refcount.
-        unsafe { bindings::usb_get_intf(self.as_raw()) };
+        unsafe { bindings::usb_get_intf(obj.as_ref().as_raw()) };
     }
 
     #[inline]
@@ -428,11 +428,11 @@ fn as_raw(&self) -> *mut bindings::usb_device {
 // SAFETY: Instances of `Device` are always reference-counted.
 unsafe impl AlwaysRefCounted for Device {
     #[inline]
-    fn inc_ref(&self) {
-        // SAFETY: The invariants of `Device` guarantee that `self.as_raw()`
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The invariants of `Device` guarantee that `obj.as_raw()`
         // returns a valid `struct usb_device` pointer, for which we will
         // acquire a new refcount.
-        unsafe { bindings::usb_get_dev(self.as_raw()) };
+        unsafe { bindings::usb_get_dev(obj.as_ref().as_raw()) };
     }
 
     #[inline]
Signature · 1 line
2.47.3
#1 lore raw

PATCH v2 1/1 rust: sync: make AlwaysRefCounted::inc_ref an associated function

In-Reply-To: <[email protected]>
References: <[email protected]>

Incrementing a reference count must be a deliberate act, and every inc_ref must be matched by exactly one dec_ref. Making inc_ref an associated function that takes a NonNull<Self> mirrors dec_ref, which is already an associated function because the object is freed when the count reaches zero.

Having one half of the protocol take a reference and the other half a raw pointer makes the pairing harder to review and easier to get wrong.

This was suggested by Benno Lossin.

---

Changes in v2:
- serdev: call get_device() on the embedded struct device instead of recursing into serdev::Device::inc_ref() itself. Reported by Sashiko.
- gpuvm: dereference obj before accessing the vm field. Reported by Sashiko.
- gpuvm/vm_bo: dereference obj before accessing the inner field. Reported by Sashiko.
- opp, pwm: dereference obj before accessing field 0. Reported by Sashiko.
- Group the core::ptr::NonNull imports vertically, as the coding guidelines require. Reported by Sashiko.
- Add #[inline] to inc_ref and to ARef::clone() / ARef::from(). Reported by Sashiko.

Build tested with CONFIG_RUST_DRM_GPUVM, CONFIG_DRM_TYR and CONFIG_RUST_SERIAL_DEV_BUS_ABSTRACTIONS enabled, so that every touched file is actually compiled.

 rust/kernel/auxiliary.rs         |  7 ++++---
 rust/kernel/block/mq/request.rs  |  6 ++++--
 rust/kernel/cred.rs              |  7 ++++---
 rust/kernel/device.rs            |  8 +++++---
 rust/kernel/device/property.rs   |  9 +++++----
 rust/kernel/dma_buf/dma_fence.rs |  7 ++++---
 rust/kernel/drm/device.rs        |  7 ++++---
 rust/kernel/drm/gem/mod.rs       |  5 +++--
 rust/kernel/drm/gpuvm/mod.rs     |  7 ++++---
 rust/kernel/drm/gpuvm/vm_bo.rs   |  7 ++++---
 rust/kernel/fs/file.rs           | 21 ++++++++++++---------
 rust/kernel/fwctl.rs             |  4 ++--
 rust/kernel/i2c.rs               | 13 +++++++------
 rust/kernel/mm.rs                | 12 ++++++------
 rust/kernel/mm/mmput_async.rs    |  6 +++---
 rust/kernel/opp.rs               |  7 ++++---
 rust/kernel/pci.rs               |  6 +++---
 rust/kernel/pid_namespace.rs     | 12 +++++++-----
 rust/kernel/platform.rs          |  7 ++++---
 rust/kernel/pwm.rs               |  6 +++---
 rust/kernel/serdev.rs            |  9 +++++++--
 rust/kernel/sync/aref.rs         | 19 ++++++++++++++-----
 rust/kernel/task.rs              | 11 +++++++----
 rust/kernel/usb.rs               | 12 ++++++------
 24 files changed, 126 insertions(+), 89 deletions(-)
rust/kernel/auxiliary.rs +4 -3
index 9d3de109b..3f499be2f 100644
@@ -390,9 +390,10 @@ unsafe impl<Ctx: device::DeviceContext> device::AsBusDevice<Ctx> for Device<Ctx>
 
 // SAFETY: Instances of `Device` are always reference-counted.
 unsafe impl crate::sync::aref::AlwaysRefCounted for Device {
-    fn inc_ref(&self) {
-        // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
-        unsafe { bindings::get_device(self.as_ref().as_raw()) };
+    #[inline]
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The safety requirements guarantee that `obj` points to a valid object.
+        unsafe { bindings::get_device(core::ptr::addr_of_mut!((*obj.as_ref().as_raw()).dev)) };
     }
 
     unsafe fn dec_ref(obj: NonNull<Self>) {
rust/kernel/block/mq/request.rs +4 -2
index 6115f9aec..4b82885cf 100644
@@ -240,8 +240,10 @@ unsafe impl<T: Operations> Sync for Request<T> {}
 // keeps the object alive in memory at least until a matching reference count
 // decrement is executed.
 unsafe impl<T: Operations> AlwaysRefCounted for Request<T> {
-    fn inc_ref(&self) {
-        self.wrapper_ref().refcount().inc();
+    #[inline]
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The safety requirements guarantee that `obj` is valid.
+        unsafe { obj.as_ref().wrapper_ref().refcount().inc() };
     }
 
     unsafe fn dec_ref(obj: core::ptr::NonNull<Self>) {
rust/kernel/cred.rs +4 -3
index ffa156b9d..2a2b2d3b0 100644
@@ -9,6 +9,7 @@
 //! Reference: <https://www.kernel.org/doc/html/latest/security/credentials.html>
 
 use crate::{bindings, sync::aref::AlwaysRefCounted, task::Kuid, types::Opaque};
+use core::ptr::NonNull;
 
 /// Wraps the kernel's `struct cred`.
 ///
@@ -78,9 +79,9 @@ pub fn euid(&self) -> Kuid {
 // SAFETY: The type invariants guarantee that `Credential` is always ref-counted.
 unsafe impl AlwaysRefCounted for Credential {
     #[inline]
-    fn inc_ref(&self) {
-        // SAFETY: The existence of a shared reference means that the refcount is nonzero.
-        unsafe { bindings::get_cred(self.0.get()) };
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The safety requirements guarantee that `obj` points to a valid object.
+        unsafe { bindings::get_cred(obj.as_ref().0.get()) };
     }
 
     #[inline]
rust/kernel/device.rs +5 -3
index 2291d85b6..0e96f9606 100644
@@ -14,6 +14,7 @@
         Opaque, //
     }, //
 };
+use core::ptr::NonNull;
 use core::{
     marker::PhantomData,
     ptr, //
@@ -436,9 +437,10 @@ pub fn name(&self) -> &CStr {
 
 // SAFETY: Instances of `Device` are always reference-counted.
 unsafe impl crate::sync::aref::AlwaysRefCounted for Device {
-    fn inc_ref(&self) {
-        // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
-        unsafe { bindings::get_device(self.as_raw()) };
+    #[inline]
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The safety requirements guarantee that `obj` points to a valid object.
+        unsafe { bindings::get_device(obj.as_ref().as_raw()) };
     }
 
     unsafe fn dec_ref(obj: ptr::NonNull<Self>) {
rust/kernel/device/property.rs +5 -4
index 5aead835f..fcff7e5a2 100644
@@ -4,6 +4,7 @@
 //!
 //! C header: [`include/linux/property.h`](srctree/include/linux/property.h)
 
+use core::ptr::NonNull;
 use core::{mem::MaybeUninit, ptr};
 
 use super::private::Sealed;
@@ -361,10 +362,10 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 
 // SAFETY: Instances of `FwNode` are always reference-counted.
 unsafe impl crate::sync::aref::AlwaysRefCounted for FwNode {
-    fn inc_ref(&self) {
-        // SAFETY: The existence of a shared reference guarantees that the
-        // refcount is non-zero.
-        unsafe { bindings::fwnode_handle_get(self.as_raw()) };
+    #[inline]
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The safety requirements guarantee that `obj` points to a valid object.
+        unsafe { bindings::fwnode_handle_get(obj.as_ref().as_raw()) };
     }
 
     unsafe fn dec_ref(obj: ptr::NonNull<Self>) {
rust/kernel/dma_buf/dma_fence.rs +4 -3
index 18a43e1bb..cc8add65b 100644
@@ -566,9 +566,10 @@ pub unsafe fn from_raw<'a>(ptr: *mut bindings::dma_fence) -> &'a Self {
 // SAFETY: These implement the C backends refcounting methods which are proven
 // to work correctly.
 unsafe impl AlwaysRefCounted for Fence {
-    fn inc_ref(&self) {
-        // SAFETY: `self.as_raw()` is a pointer to a valid `struct dma_fence`.
-        unsafe { bindings::dma_fence_get(self.as_raw()) }
+    #[inline]
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: `obj.as_ref().as_raw()` is a pointer to a valid `struct dma_fence`.
+        unsafe { bindings::dma_fence_get(obj.as_ref().as_raw()) }
     }
 
     unsafe fn dec_ref(ptr: NonNull<Self>) {
rust/kernel/drm/device.rs +4 -3
index 6b88ade28..4cdb25f30 100644
@@ -481,9 +481,10 @@ fn deref(&self) -> &Self::Target {
 // SAFETY: DRM device objects are always reference counted and the get/put functions
 // satisfy the requirements.
 unsafe impl<T: drm::Driver> AlwaysRefCounted for Device<T> {
-    fn inc_ref(&self) {
-        // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
-        unsafe { bindings::drm_dev_get(self.as_raw()) };
+    #[inline]
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The safety requirements guarantee that `obj` points to a valid object.
+        unsafe { bindings::drm_dev_get(obj.as_ref().as_raw()) };
     }
 
     unsafe fn dec_ref(obj: NonNull<Self>) {
rust/kernel/drm/gem/mod.rs +3 -2
index 85657a39e..e290c3ac9 100644
@@ -52,10 +52,11 @@ unsafe impl $( <$( $tparam_id ),+> )? $crate::sync::aref::AlwaysRefCounted for $
             Self: IntoGEMObject,
             $( $( $bind_param : $bind_trait ),+ )?
         {
-            fn inc_ref(&self) {
+            #[inline]
+            unsafe fn inc_ref(obj: NonNull<Self>){
                 // SAFETY: The existence of a shared reference guarantees that the refcount is
                 // non-zero.
-                unsafe { bindings::drm_gem_object_get(self.as_raw()) };
+                unsafe { bindings::drm_gem_object_get(obj.as_ref().as_raw()) };
             }
 
             unsafe fn dec_ref(obj: core::ptr::NonNull<Self>) {
rust/kernel/drm/gpuvm/mod.rs +4 -3
index d9d43d719..681daeae7 100644
@@ -82,9 +82,10 @@ unsafe impl<T: DriverGpuVm> Sync for GpuVm<T> {}
 
 // SAFETY: By type invariants, the allocation is managed by the refcount in `self.vm`.
 unsafe impl<T: DriverGpuVm> AlwaysRefCounted for GpuVm<T> {
-    fn inc_ref(&self) {
-        // SAFETY: By type invariants, the allocation is managed by the refcount in `self.vm`.
-        unsafe { bindings::drm_gpuvm_get(self.vm.get()) };
+    #[inline]
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The safety requirements guarantee that `obj` points to a valid object.
+        unsafe { bindings::drm_gpuvm_get(obj.as_ref().vm.get()) };
     }
 
     unsafe fn dec_ref(obj: NonNull<Self>) {
rust/kernel/drm/gpuvm/vm_bo.rs +4 -3
index 5989972da..0ffb7cdad 100644
@@ -30,9 +30,10 @@ unsafe impl<T: DriverGpuVm> Sync for GpuVmBo<T> {}
 
 // SAFETY: By type invariants, the allocation is managed by the refcount in `self.inner`.
 unsafe impl<T: DriverGpuVm> AlwaysRefCounted for GpuVmBo<T> {
-    fn inc_ref(&self) {
-        // SAFETY: By type invariants, the allocation is managed by the refcount in `self.inner`.
-        unsafe { bindings::drm_gpuvm_bo_get(self.inner.get()) };
+    #[inline]
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The safety requirements guarantee that `obj` points to a valid object.
+        unsafe { bindings::drm_gpuvm_bo_get(obj.as_ref().inner.get()) };
     }
 
     unsafe fn dec_ref(obj: NonNull<Self>) {
rust/kernel/fs/file.rs +12 -9
index 23ee689bd..b5242e019 100644
@@ -15,7 +15,10 @@
     sync::aref::{ARef, AlwaysRefCounted},
     types::{NotThreadSafe, Opaque},
 };
-use core::ptr;
+use core::ptr::{
+    self,
+    NonNull, //
+};
 
 /// Primitive type representing the offset within a [`File`].
 ///
@@ -199,13 +202,13 @@ unsafe impl Sync for File {}
 // makes `ARef<File>` own a normal refcount.
 unsafe impl AlwaysRefCounted for File {
     #[inline]
-    fn inc_ref(&self) {
-        // SAFETY: The existence of a shared reference means that the refcount is nonzero.
-        unsafe { bindings::get_file(self.as_ptr()) };
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The safety requirements guarantee that `obj` points to a valid object.
+        unsafe { bindings::get_file(obj.as_ref().as_ptr()) };
     }
 
     #[inline]
-    unsafe fn dec_ref(obj: ptr::NonNull<File>) {
+    unsafe fn dec_ref(obj: NonNull<File>) {
         // SAFETY: To call this method, the caller passes us ownership of a normal refcount, so we
         // may drop it. The cast is okay since `File` has the same representation as `struct file`.
         unsafe { bindings::fput(obj.cast().as_ptr()) }
@@ -235,13 +238,13 @@ pub struct LocalFile {
 // makes `ARef<LocalFile>` own a normal refcount.
 unsafe impl AlwaysRefCounted for LocalFile {
     #[inline]
-    fn inc_ref(&self) {
-        // SAFETY: The existence of a shared reference means that the refcount is nonzero.
-        unsafe { bindings::get_file(self.as_ptr()) };
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The safety requirements guarantee that `obj` points to a valid object.
+        unsafe { bindings::get_file(obj.as_ref().as_ptr()) };
     }
 
     #[inline]
-    unsafe fn dec_ref(obj: ptr::NonNull<LocalFile>) {
+    unsafe fn dec_ref(obj: NonNull<LocalFile>) {
         // SAFETY: To call this method, the caller passes us ownership of a normal refcount, so we
         // may drop it. The cast is okay since `LocalFile` has the same representation as
         // `struct file`.
rust/kernel/fwctl.rs +2 -2
index b7778e4d5..8f1d094b5 100644
@@ -261,9 +261,9 @@ fn as_ref(&self) -> &device::Device {
 // `fwctl_put` decrements it and frees the device when it reaches zero.
 unsafe impl<T: Operations> AlwaysRefCounted for Device<T> {
     #[inline]
-    fn inc_ref(&self) {
+    unsafe fn inc_ref(obj: NonNull<Self>) {
         // SAFETY: `self` holds a live reference.
-        unsafe { bindings::fwctl_get(self.as_raw()) };
+        unsafe { bindings::fwctl_get(obj.as_ref().as_raw()) };
     }
 
     #[inline]
rust/kernel/i2c.rs +7 -6
index b4ff25c83..d8d96958d 100644
@@ -416,9 +416,9 @@ pub fn get(index: i32) -> Result<ARef<Self>> {
 // SAFETY: Instances of `I2cAdapter` are always reference-counted.
 unsafe impl AlwaysRefCounted for I2cAdapter {
     #[inline]
-    fn inc_ref(&self) {
-        // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
-        unsafe { bindings::i2c_get_adapter(self.index()) };
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The safety requirements guarantee that `obj` points to a valid object.
+        unsafe { bindings::i2c_get_adapter(obj.as_ref().index()) };
     }
 
     #[inline]
@@ -493,9 +493,10 @@ unsafe impl<Ctx: device::DeviceContext> device::AsBusDevice<Ctx> for I2cClient<C
 
 // SAFETY: Instances of `I2cClient` are always reference-counted.
 unsafe impl AlwaysRefCounted for I2cClient {
-    fn inc_ref(&self) {
-        // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
-        unsafe { bindings::get_device(self.as_ref().as_raw()) };
+    #[inline]
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The safety requirements guarantee that `obj` points to a valid object.
+        unsafe { bindings::get_device(obj.as_ref().as_ref().as_raw()) };
     }
 
     unsafe fn dec_ref(obj: NonNull<Self>) {
rust/kernel/mm.rs +6 -6
index 58bc1793f..f5deac0b7 100644
@@ -57,9 +57,9 @@ unsafe impl Sync for Mm {}
 // SAFETY: By the type invariants, this type is always refcounted.
 unsafe impl AlwaysRefCounted for Mm {
     #[inline]
-    fn inc_ref(&self) {
-        // SAFETY: The pointer is valid since self is a reference.
-        unsafe { bindings::mmgrab(self.as_raw()) };
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The pointer is valid since obj is a reference.
+        unsafe { bindings::mmgrab(obj.as_ref().as_raw()) };
     }
 
     #[inline]
@@ -93,9 +93,9 @@ unsafe impl Sync for MmWithUser {}
 // SAFETY: By the type invariants, this type is always refcounted.
 unsafe impl AlwaysRefCounted for MmWithUser {
     #[inline]
-    fn inc_ref(&self) {
-        // SAFETY: The pointer is valid since self is a reference.
-        unsafe { bindings::mmget(self.as_raw()) };
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The pointer is valid since obj is a reference.
+        unsafe { bindings::mmget(obj.as_ref().as_raw()) };
     }
 
     #[inline]
rust/kernel/mm/mmput_async.rs +3 -3
index b8d2f0512..2e490f8ce 100644
@@ -36,9 +36,9 @@ unsafe impl Sync for MmWithUserAsync {}
 // SAFETY: By the type invariants, this type is always refcounted.
 unsafe impl AlwaysRefCounted for MmWithUserAsync {
     #[inline]
-    fn inc_ref(&self) {
-        // SAFETY: The pointer is valid since self is a reference.
-        unsafe { bindings::mmget(self.as_raw()) };
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The safety requirements guarantee that `obj` is valid.
+        unsafe { bindings::mmget(obj.as_ref().as_raw()) };
     }
 
     #[inline]
rust/kernel/opp.rs +4 -3
index 62e446761..cec86e284 100644
@@ -19,6 +19,7 @@
     sync::aref::{ARef, AlwaysRefCounted},
     types::Opaque,
 };
+use core::ptr::NonNull;
 
 #[cfg(CONFIG_CPU_FREQ)]
 /// Frequency table implementation.
@@ -1043,9 +1044,9 @@ unsafe impl Sync for OPP {}
 /// SAFETY: The type invariants guarantee that [`OPP`] is always refcounted.
 unsafe impl AlwaysRefCounted for OPP {
     #[inline]
-    fn inc_ref(&self) {
-        // SAFETY: The existence of a shared reference means that the refcount is nonzero.
-        unsafe { bindings::dev_pm_opp_get(self.0.get()) };
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The safety requirements guarantee that `obj` points to a valid object.
+        unsafe { bindings::dev_pm_opp_get(obj.as_ref().0.get()) };
     }
 
     #[inline]
rust/kernel/pci.rs +3 -3
index 769d01d23..0fdf7caa5 100644
@@ -512,9 +512,9 @@ impl<'a> crate::dma::Device<'a> for Device<device::Core<'a>> {}
 // SAFETY: Instances of `Device` are always reference-counted.
 unsafe impl crate::sync::aref::AlwaysRefCounted for Device {
     #[inline]
-    fn inc_ref(&self) {
-        // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
-        unsafe { bindings::pci_dev_get(self.as_raw()) };
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The safety requirements guarantee that `obj` points to a valid object.
+        unsafe { bindings::pci_dev_get(obj.as_ref().as_raw()) };
     }
 
     #[inline]
rust/kernel/pid_namespace.rs +7 -5
index 979a9718f..6c625a02c 100644
@@ -8,7 +8,9 @@
 //! [`include/linux/pid.h`](srctree/include/linux/pid.h)
 
 use crate::{bindings, sync::aref::AlwaysRefCounted, types::Opaque};
-use core::ptr;
+use core::ptr::{
+    NonNull, //
+};
 
 /// Wraps the kernel's `struct pid_namespace`. Thread safe.
 ///
@@ -43,13 +45,13 @@ pub unsafe fn from_ptr<'a>(ptr: *const bindings::pid_namespace) -> &'a Self {
 // SAFETY: Instances of `PidNamespace` are always reference-counted.
 unsafe impl AlwaysRefCounted for PidNamespace {
     #[inline]
-    fn inc_ref(&self) {
-        // SAFETY: The existence of a shared reference means that the refcount is nonzero.
-        unsafe { bindings::get_pid_ns(self.as_ptr()) };
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The safety requirements guarantee that `obj` points to a valid object.
+        unsafe { bindings::get_pid_ns(obj.as_ref().as_ptr()) };
     }
 
     #[inline]
-    unsafe fn dec_ref(obj: ptr::NonNull<PidNamespace>) {
+    unsafe fn dec_ref(obj: NonNull<PidNamespace>) {
         // SAFETY: The safety requirements guarantee that the refcount is non-zero.
         unsafe { bindings::put_pid_ns(obj.cast().as_ptr()) }
     }
rust/kernel/platform.rs +4 -3
index ac0a012ae..37e7ec9e7 100644
@@ -535,9 +535,10 @@ impl<'a> crate::dma::Device<'a> for Device<device::Core<'a>> {}
 
 // SAFETY: Instances of `Device` are always reference-counted.
 unsafe impl crate::sync::aref::AlwaysRefCounted for Device {
-    fn inc_ref(&self) {
-        // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
-        unsafe { bindings::get_device(self.as_ref().as_raw()) };
+    #[inline]
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The safety requirements guarantee that `obj` points to a valid object.
+        unsafe { bindings::get_device(core::ptr::addr_of_mut!((*obj.as_ref().as_raw()).dev)) };
     }
 
     unsafe fn dec_ref(obj: NonNull<Self>) {
rust/kernel/pwm.rs +3 -3
index 8aa47304b..aefcf68e2 100644
@@ -629,10 +629,10 @@ pub fn new<'a>(
 // SAFETY: Implements refcounting for `Chip` using the embedded `struct device`.
 unsafe impl<T: PwmOps> AlwaysRefCounted for Chip<T> {
     #[inline]
-    fn inc_ref(&self) {
-        // SAFETY: `self.0.get()` points to a valid `pwm_chip` because `self` exists.
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The safety requirements guarantee that `obj` points to a valid `Chip`.
         // The embedded `dev` is valid. `get_device` increments its refcount.
-        unsafe { bindings::get_device(&raw mut (*self.0.get()).dev) };
+        unsafe { bindings::get_device(&raw mut (*obj.as_ref().0.get()).dev) };
     }
 
     #[inline]
rust/kernel/serdev.rs +7 -2
index 17ca504b7..4e58cd138 100644
@@ -571,8 +571,13 @@ unsafe impl<Ctx: device::DeviceContext> device::AsBusDevice<Ctx> for Device<Ctx>
 
 // SAFETY: Instances of `Device` are always reference-counted.
 unsafe impl AlwaysRefCounted for Device {
-    fn inc_ref(&self) {
-        self.as_ref().inc_ref();
+    #[inline]
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The safety requirements guarantee that `obj` points to a valid
+        // `serdev::Device`, and thus to a valid embedded `struct device`.
+        unsafe {
+            bindings::get_device(&raw mut (*obj.as_ptr().cast::<bindings::serdev_device>()).dev)
+        };
     }
 
     unsafe fn dec_ref(obj: NonNull<Self>) {
rust/kernel/sync/aref.rs +14 -5
index 9983ee085..becd2db78 100644
@@ -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>);
 
     /// Decrements the reference count on the object.
     ///
@@ -131,7 +135,7 @@ pub unsafe fn from_raw(ptr: NonNull<T>) -> Self {
     ///
     /// # // SAFETY: TODO.
     /// unsafe impl AlwaysRefCounted for Empty {
-    ///     fn inc_ref(&self) {}
+    ///     unsafe fn inc_ref(_obj: NonNull<Self>) {}
     ///     unsafe fn dec_ref(_obj: NonNull<Self>) {}
     /// }
     ///
@@ -149,8 +153,10 @@ pub fn into_raw(me: Self) -> NonNull<T> {
 }
 
 impl<T: AlwaysRefCounted> Clone for ARef<T> {
+    #[inline]
     fn clone(&self) -> Self {
-        self.inc_ref();
+        // SAFETY: The type invariants guarantee that `self.ptr` is valid.
+        unsafe { T::inc_ref(self.ptr) };
         // SAFETY: We just incremented the refcount above.
         unsafe { Self::from_raw(self.ptr) }
     }
@@ -166,10 +172,13 @@ fn deref(&self) -> &Self::Target {
 }
 
 impl<T: AlwaysRefCounted> From<&T> for ARef<T> {
+    #[inline]
     fn from(b: &T) -> Self {
-        b.inc_ref();
+        let ptr = NonNull::from(b);
+        // SAFETY: `ptr` comes from a live shared reference.
+        unsafe { T::inc_ref(ptr) };
         // SAFETY: We just incremented the refcount above.
-        unsafe { Self::from_raw(NonNull::from(b)) }
+        unsafe { Self::from_raw(ptr) }
     }
 }
 
rust/kernel/task.rs +7 -4
index 3336df493..76cc236fe 100644
@@ -14,7 +14,10 @@
 };
 use core::{
     ops::Deref,
-    ptr, //
+    ptr::{
+        self,
+        NonNull, //
+    },
 };
 
 /// A sentinel value used for infinite timeouts.
@@ -349,9 +352,9 @@ pub fn group_leader(&self) -> &Task {
 // SAFETY: The type invariants guarantee that `Task` is always refcounted.
 unsafe impl crate::sync::aref::AlwaysRefCounted for Task {
     #[inline]
-    fn inc_ref(&self) {
-        // SAFETY: The existence of a shared reference means that the refcount is nonzero.
-        unsafe { bindings::get_task_struct(self.as_ptr()) };
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The safety requirements guarantee that `obj` points to a valid object.
+        unsafe { bindings::get_task_struct(obj.as_ref().as_ptr()) };
     }
 
     #[inline]
rust/kernel/usb.rs +6 -6
index 993760ff3..812159a82 100644
@@ -375,11 +375,11 @@ fn as_ref(&self) -> &Device {
 // SAFETY: Instances of `Interface` are always reference-counted.
 unsafe impl AlwaysRefCounted for Interface {
     #[inline]
-    fn inc_ref(&self) {
-        // SAFETY: The invariants of `Interface` guarantee that `self.as_raw()`
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The invariants of `Interface` guarantee that `obj.as_ref().as_raw()`
         // returns a valid `struct usb_interface` pointer, for which we will
         // acquire a new refcount.
-        unsafe { bindings::usb_get_intf(self.as_raw()) };
+        unsafe { bindings::usb_get_intf(obj.as_ref().as_raw()) };
     }
 
     #[inline]
@@ -428,11 +428,11 @@ fn as_raw(&self) -> *mut bindings::usb_device {
 // SAFETY: Instances of `Device` are always reference-counted.
 unsafe impl AlwaysRefCounted for Device {
     #[inline]
-    fn inc_ref(&self) {
-        // SAFETY: The invariants of `Device` guarantee that `self.as_raw()`
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The invariants of `Device` guarantee that `obj.as_raw()`
         // returns a valid `struct usb_device` pointer, for which we will
         // acquire a new refcount.
-        unsafe { bindings::usb_get_dev(self.as_raw()) };
+        unsafe { bindings::usb_get_dev(obj.as_ref().as_raw()) };
     }
 
     #[inline]
Signature · 1 line
2.47.3
maintainer
#2 lore raw
In reply to Tran Van Tien
Quoted 30 lines · Tran Van Tien

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.

<cut>

Quoted 5 lines
rust/kernel/sync/aref.rs +0 -0
index 9983ee085..0198c042e 100644

rust/kernel/sync/aref.rs line 56

Quoted 9 lines
rust/kernel/sync/aref.rs +5 -1
@@ -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

#3 lore raw

PATCH v3 1/1 rust: sync: make AlwaysRefCounted::inc_ref an associated function

In reply to Tran Van Tien

In-Reply-To: <[email protected]>
References: <[email protected]>

Incrementing a reference count must be a deliberate act, and every inc_ref must be matched by exactly one dec_ref. Making inc_ref an associated function that takes a NonNull<Self> mirrors dec_ref, which is already an associated function because the object is freed when the count reaches zero.

Having one half of the protocol take a reference and the other half a raw pointer makes the pairing harder to review and easier to get wrong.

This was suggested by Benno Lossin.

---

Changes in v2:
- serdev: call get_device() on the embedded struct device instead of recursing into serdev::Device::inc_ref() itself. Reported by Sashiko.
- gpuvm: dereference obj before accessing the vm field. Reported by Sashiko.
- gpuvm/vm_bo: dereference obj before accessing the inner field. Reported by Sashiko.
- opp, pwm: dereference obj before accessing field 0. Reported by Sashiko.
- Group the core::ptr::NonNull imports vertically, as the coding guidelines require. Reported by Sashiko.
- Add #[inline] to inc_ref and to ARef::clone() / ARef::from(). Reported by Sashiko.

Build tested with CONFIG_RUST_DRM_GPUVM, CONFIG_DRM_TYR and CONFIG_RUST_SERIAL_DEV_BUS_ABSTRACTIONS enabled, so that every touched file is actually compiled.

Changes in v3:
- No code change. Rebased confirmation and coordination only.
- State the base explicitly: this patch applies to the RUST tree listed in MAINTAINERS (git://github.com/Rust-for-Linux/linux.git rust-next) at v7.4-rc4, commit b6a9fa34c, where inc_ref is still a &self method.
- Note the conflict with the in-flight series "rust: rename AlwaysRefCounted to RefCounted" (v22), which touches the same set of files and keeps inc_ref as a &self method on RefCounted. This patch is a different change (making inc_ref an associated function), so the two should be sequenced by the maintainer. I am happy to rebase on top of that series once it lands in rust-next.

 rust/kernel/auxiliary.rs         |  7 ++++---
 rust/kernel/block/mq/request.rs  |  6 ++++--
 rust/kernel/cred.rs              |  7 ++++---
 rust/kernel/device.rs            |  8 +++++---
 rust/kernel/device/property.rs   |  9 +++++----
 rust/kernel/dma_buf/dma_fence.rs |  7 ++++---
 rust/kernel/drm/device.rs        |  7 ++++---
 rust/kernel/drm/gem/mod.rs       |  5 +++--
 rust/kernel/drm/gpuvm/mod.rs     |  7 ++++---
 rust/kernel/drm/gpuvm/vm_bo.rs   |  7 ++++---
 rust/kernel/fs/file.rs           | 21 ++++++++++++---------
 rust/kernel/fwctl.rs             |  4 ++--
 rust/kernel/i2c.rs               | 13 +++++++------
 rust/kernel/mm.rs                | 12 ++++++------
 rust/kernel/mm/mmput_async.rs    |  6 +++---
 rust/kernel/opp.rs               |  7 ++++---
 rust/kernel/pci.rs               |  6 +++---
 rust/kernel/pid_namespace.rs     | 12 +++++++-----
 rust/kernel/platform.rs          |  7 ++++---
 rust/kernel/pwm.rs               |  6 +++---
 rust/kernel/serdev.rs            |  9 +++++++--
 rust/kernel/sync/aref.rs         | 19 ++++++++++++++-----
 rust/kernel/task.rs              | 11 +++++++----
 rust/kernel/usb.rs               | 12 ++++++------
 24 files changed, 126 insertions(+), 89 deletions(-)
rust/kernel/auxiliary.rs +4 -3
index 9d3de109b..3f499be2f 100644
@@ -390,9 +390,10 @@ unsafe impl<Ctx: device::DeviceContext> device::AsBusDevice<Ctx> for Device<Ctx>
 
 // SAFETY: Instances of `Device` are always reference-counted.
 unsafe impl crate::sync::aref::AlwaysRefCounted for Device {
-    fn inc_ref(&self) {
-        // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
-        unsafe { bindings::get_device(self.as_ref().as_raw()) };
+    #[inline]
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The safety requirements guarantee that `obj` points to a valid object.
+        unsafe { bindings::get_device(core::ptr::addr_of_mut!((*obj.as_ref().as_raw()).dev)) };
     }
 
     unsafe fn dec_ref(obj: NonNull<Self>) {
rust/kernel/block/mq/request.rs +4 -2
index 6115f9aec..4b82885cf 100644
@@ -240,8 +240,10 @@ unsafe impl<T: Operations> Sync for Request<T> {}
 // keeps the object alive in memory at least until a matching reference count
 // decrement is executed.
 unsafe impl<T: Operations> AlwaysRefCounted for Request<T> {
-    fn inc_ref(&self) {
-        self.wrapper_ref().refcount().inc();
+    #[inline]
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The safety requirements guarantee that `obj` is valid.
+        unsafe { obj.as_ref().wrapper_ref().refcount().inc() };
     }
 
     unsafe fn dec_ref(obj: core::ptr::NonNull<Self>) {
rust/kernel/cred.rs +4 -3
index ffa156b9d..2a2b2d3b0 100644
@@ -9,6 +9,7 @@
 //! Reference: <https://www.kernel.org/doc/html/latest/security/credentials.html>
 
 use crate::{bindings, sync::aref::AlwaysRefCounted, task::Kuid, types::Opaque};
+use core::ptr::NonNull;
 
 /// Wraps the kernel's `struct cred`.
 ///
@@ -78,9 +79,9 @@ pub fn euid(&self) -> Kuid {
 // SAFETY: The type invariants guarantee that `Credential` is always ref-counted.
 unsafe impl AlwaysRefCounted for Credential {
     #[inline]
-    fn inc_ref(&self) {
-        // SAFETY: The existence of a shared reference means that the refcount is nonzero.
-        unsafe { bindings::get_cred(self.0.get()) };
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The safety requirements guarantee that `obj` points to a valid object.
+        unsafe { bindings::get_cred(obj.as_ref().0.get()) };
     }
 
     #[inline]
rust/kernel/device.rs +5 -3
index 2291d85b6..0e96f9606 100644
@@ -14,6 +14,7 @@
         Opaque, //
     }, //
 };
+use core::ptr::NonNull;
 use core::{
     marker::PhantomData,
     ptr, //
@@ -436,9 +437,10 @@ pub fn name(&self) -> &CStr {
 
 // SAFETY: Instances of `Device` are always reference-counted.
 unsafe impl crate::sync::aref::AlwaysRefCounted for Device {
-    fn inc_ref(&self) {
-        // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
-        unsafe { bindings::get_device(self.as_raw()) };
+    #[inline]
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The safety requirements guarantee that `obj` points to a valid object.
+        unsafe { bindings::get_device(obj.as_ref().as_raw()) };
     }
 
     unsafe fn dec_ref(obj: ptr::NonNull<Self>) {
rust/kernel/device/property.rs +5 -4
index 5aead835f..fcff7e5a2 100644
@@ -4,6 +4,7 @@
 //!
 //! C header: [`include/linux/property.h`](srctree/include/linux/property.h)
 
+use core::ptr::NonNull;
 use core::{mem::MaybeUninit, ptr};
 
 use super::private::Sealed;
@@ -361,10 +362,10 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 
 // SAFETY: Instances of `FwNode` are always reference-counted.
 unsafe impl crate::sync::aref::AlwaysRefCounted for FwNode {
-    fn inc_ref(&self) {
-        // SAFETY: The existence of a shared reference guarantees that the
-        // refcount is non-zero.
-        unsafe { bindings::fwnode_handle_get(self.as_raw()) };
+    #[inline]
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The safety requirements guarantee that `obj` points to a valid object.
+        unsafe { bindings::fwnode_handle_get(obj.as_ref().as_raw()) };
     }
 
     unsafe fn dec_ref(obj: ptr::NonNull<Self>) {
rust/kernel/dma_buf/dma_fence.rs +4 -3
index 18a43e1bb..cc8add65b 100644
@@ -566,9 +566,10 @@ pub unsafe fn from_raw<'a>(ptr: *mut bindings::dma_fence) -> &'a Self {
 // SAFETY: These implement the C backends refcounting methods which are proven
 // to work correctly.
 unsafe impl AlwaysRefCounted for Fence {
-    fn inc_ref(&self) {
-        // SAFETY: `self.as_raw()` is a pointer to a valid `struct dma_fence`.
-        unsafe { bindings::dma_fence_get(self.as_raw()) }
+    #[inline]
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: `obj.as_ref().as_raw()` is a pointer to a valid `struct dma_fence`.
+        unsafe { bindings::dma_fence_get(obj.as_ref().as_raw()) }
     }
 
     unsafe fn dec_ref(ptr: NonNull<Self>) {
rust/kernel/drm/device.rs +4 -3
index 6b88ade28..4cdb25f30 100644
@@ -481,9 +481,10 @@ fn deref(&self) -> &Self::Target {
 // SAFETY: DRM device objects are always reference counted and the get/put functions
 // satisfy the requirements.
 unsafe impl<T: drm::Driver> AlwaysRefCounted for Device<T> {
-    fn inc_ref(&self) {
-        // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
-        unsafe { bindings::drm_dev_get(self.as_raw()) };
+    #[inline]
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The safety requirements guarantee that `obj` points to a valid object.
+        unsafe { bindings::drm_dev_get(obj.as_ref().as_raw()) };
     }
 
     unsafe fn dec_ref(obj: NonNull<Self>) {
rust/kernel/drm/gem/mod.rs +3 -2
index 85657a39e..e290c3ac9 100644
@@ -52,10 +52,11 @@ unsafe impl $( <$( $tparam_id ),+> )? $crate::sync::aref::AlwaysRefCounted for $
             Self: IntoGEMObject,
             $( $( $bind_param : $bind_trait ),+ )?
         {
-            fn inc_ref(&self) {
+            #[inline]
+            unsafe fn inc_ref(obj: NonNull<Self>){
                 // SAFETY: The existence of a shared reference guarantees that the refcount is
                 // non-zero.
-                unsafe { bindings::drm_gem_object_get(self.as_raw()) };
+                unsafe { bindings::drm_gem_object_get(obj.as_ref().as_raw()) };
             }
 
             unsafe fn dec_ref(obj: core::ptr::NonNull<Self>) {
rust/kernel/drm/gpuvm/mod.rs +4 -3
index d9d43d719..681daeae7 100644
@@ -82,9 +82,10 @@ unsafe impl<T: DriverGpuVm> Sync for GpuVm<T> {}
 
 // SAFETY: By type invariants, the allocation is managed by the refcount in `self.vm`.
 unsafe impl<T: DriverGpuVm> AlwaysRefCounted for GpuVm<T> {
-    fn inc_ref(&self) {
-        // SAFETY: By type invariants, the allocation is managed by the refcount in `self.vm`.
-        unsafe { bindings::drm_gpuvm_get(self.vm.get()) };
+    #[inline]
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The safety requirements guarantee that `obj` points to a valid object.
+        unsafe { bindings::drm_gpuvm_get(obj.as_ref().vm.get()) };
     }
 
     unsafe fn dec_ref(obj: NonNull<Self>) {
rust/kernel/drm/gpuvm/vm_bo.rs +4 -3
index 5989972da..0ffb7cdad 100644
@@ -30,9 +30,10 @@ unsafe impl<T: DriverGpuVm> Sync for GpuVmBo<T> {}
 
 // SAFETY: By type invariants, the allocation is managed by the refcount in `self.inner`.
 unsafe impl<T: DriverGpuVm> AlwaysRefCounted for GpuVmBo<T> {
-    fn inc_ref(&self) {
-        // SAFETY: By type invariants, the allocation is managed by the refcount in `self.inner`.
-        unsafe { bindings::drm_gpuvm_bo_get(self.inner.get()) };
+    #[inline]
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The safety requirements guarantee that `obj` points to a valid object.
+        unsafe { bindings::drm_gpuvm_bo_get(obj.as_ref().inner.get()) };
     }
 
     unsafe fn dec_ref(obj: NonNull<Self>) {
rust/kernel/fs/file.rs +12 -9
index 23ee689bd..b5242e019 100644
@@ -15,7 +15,10 @@
     sync::aref::{ARef, AlwaysRefCounted},
     types::{NotThreadSafe, Opaque},
 };
-use core::ptr;
+use core::ptr::{
+    self,
+    NonNull, //
+};
 
 /// Primitive type representing the offset within a [`File`].
 ///
@@ -199,13 +202,13 @@ unsafe impl Sync for File {}
 // makes `ARef<File>` own a normal refcount.
 unsafe impl AlwaysRefCounted for File {
     #[inline]
-    fn inc_ref(&self) {
-        // SAFETY: The existence of a shared reference means that the refcount is nonzero.
-        unsafe { bindings::get_file(self.as_ptr()) };
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The safety requirements guarantee that `obj` points to a valid object.
+        unsafe { bindings::get_file(obj.as_ref().as_ptr()) };
     }
 
     #[inline]
-    unsafe fn dec_ref(obj: ptr::NonNull<File>) {
+    unsafe fn dec_ref(obj: NonNull<File>) {
         // SAFETY: To call this method, the caller passes us ownership of a normal refcount, so we
         // may drop it. The cast is okay since `File` has the same representation as `struct file`.
         unsafe { bindings::fput(obj.cast().as_ptr()) }
@@ -235,13 +238,13 @@ pub struct LocalFile {
 // makes `ARef<LocalFile>` own a normal refcount.
 unsafe impl AlwaysRefCounted for LocalFile {
     #[inline]
-    fn inc_ref(&self) {
-        // SAFETY: The existence of a shared reference means that the refcount is nonzero.
-        unsafe { bindings::get_file(self.as_ptr()) };
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The safety requirements guarantee that `obj` points to a valid object.
+        unsafe { bindings::get_file(obj.as_ref().as_ptr()) };
     }
 
     #[inline]
-    unsafe fn dec_ref(obj: ptr::NonNull<LocalFile>) {
+    unsafe fn dec_ref(obj: NonNull<LocalFile>) {
         // SAFETY: To call this method, the caller passes us ownership of a normal refcount, so we
         // may drop it. The cast is okay since `LocalFile` has the same representation as
         // `struct file`.
rust/kernel/fwctl.rs +2 -2
index b7778e4d5..8f1d094b5 100644
@@ -261,9 +261,9 @@ fn as_ref(&self) -> &device::Device {
 // `fwctl_put` decrements it and frees the device when it reaches zero.
 unsafe impl<T: Operations> AlwaysRefCounted for Device<T> {
     #[inline]
-    fn inc_ref(&self) {
+    unsafe fn inc_ref(obj: NonNull<Self>) {
         // SAFETY: `self` holds a live reference.
-        unsafe { bindings::fwctl_get(self.as_raw()) };
+        unsafe { bindings::fwctl_get(obj.as_ref().as_raw()) };
     }
 
     #[inline]
rust/kernel/i2c.rs +7 -6
index b4ff25c83..d8d96958d 100644
@@ -416,9 +416,9 @@ pub fn get(index: i32) -> Result<ARef<Self>> {
 // SAFETY: Instances of `I2cAdapter` are always reference-counted.
 unsafe impl AlwaysRefCounted for I2cAdapter {
     #[inline]
-    fn inc_ref(&self) {
-        // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
-        unsafe { bindings::i2c_get_adapter(self.index()) };
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The safety requirements guarantee that `obj` points to a valid object.
+        unsafe { bindings::i2c_get_adapter(obj.as_ref().index()) };
     }
 
     #[inline]
@@ -493,9 +493,10 @@ unsafe impl<Ctx: device::DeviceContext> device::AsBusDevice<Ctx> for I2cClient<C
 
 // SAFETY: Instances of `I2cClient` are always reference-counted.
 unsafe impl AlwaysRefCounted for I2cClient {
-    fn inc_ref(&self) {
-        // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
-        unsafe { bindings::get_device(self.as_ref().as_raw()) };
+    #[inline]
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The safety requirements guarantee that `obj` points to a valid object.
+        unsafe { bindings::get_device(obj.as_ref().as_ref().as_raw()) };
     }
 
     unsafe fn dec_ref(obj: NonNull<Self>) {
rust/kernel/mm.rs +6 -6
index 58bc1793f..f5deac0b7 100644
@@ -57,9 +57,9 @@ unsafe impl Sync for Mm {}
 // SAFETY: By the type invariants, this type is always refcounted.
 unsafe impl AlwaysRefCounted for Mm {
     #[inline]
-    fn inc_ref(&self) {
-        // SAFETY: The pointer is valid since self is a reference.
-        unsafe { bindings::mmgrab(self.as_raw()) };
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The pointer is valid since obj is a reference.
+        unsafe { bindings::mmgrab(obj.as_ref().as_raw()) };
     }
 
     #[inline]
@@ -93,9 +93,9 @@ unsafe impl Sync for MmWithUser {}
 // SAFETY: By the type invariants, this type is always refcounted.
 unsafe impl AlwaysRefCounted for MmWithUser {
     #[inline]
-    fn inc_ref(&self) {
-        // SAFETY: The pointer is valid since self is a reference.
-        unsafe { bindings::mmget(self.as_raw()) };
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The pointer is valid since obj is a reference.
+        unsafe { bindings::mmget(obj.as_ref().as_raw()) };
     }
 
     #[inline]
rust/kernel/mm/mmput_async.rs +3 -3
index b8d2f0512..2e490f8ce 100644
@@ -36,9 +36,9 @@ unsafe impl Sync for MmWithUserAsync {}
 // SAFETY: By the type invariants, this type is always refcounted.
 unsafe impl AlwaysRefCounted for MmWithUserAsync {
     #[inline]
-    fn inc_ref(&self) {
-        // SAFETY: The pointer is valid since self is a reference.
-        unsafe { bindings::mmget(self.as_raw()) };
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The safety requirements guarantee that `obj` is valid.
+        unsafe { bindings::mmget(obj.as_ref().as_raw()) };
     }
 
     #[inline]
rust/kernel/opp.rs +4 -3
index 62e446761..cec86e284 100644
@@ -19,6 +19,7 @@
     sync::aref::{ARef, AlwaysRefCounted},
     types::Opaque,
 };
+use core::ptr::NonNull;
 
 #[cfg(CONFIG_CPU_FREQ)]
 /// Frequency table implementation.
@@ -1043,9 +1044,9 @@ unsafe impl Sync for OPP {}
 /// SAFETY: The type invariants guarantee that [`OPP`] is always refcounted.
 unsafe impl AlwaysRefCounted for OPP {
     #[inline]
-    fn inc_ref(&self) {
-        // SAFETY: The existence of a shared reference means that the refcount is nonzero.
-        unsafe { bindings::dev_pm_opp_get(self.0.get()) };
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The safety requirements guarantee that `obj` points to a valid object.
+        unsafe { bindings::dev_pm_opp_get(obj.as_ref().0.get()) };
     }
 
     #[inline]
rust/kernel/pci.rs +3 -3
index 769d01d23..0fdf7caa5 100644
@@ -512,9 +512,9 @@ impl<'a> crate::dma::Device<'a> for Device<device::Core<'a>> {}
 // SAFETY: Instances of `Device` are always reference-counted.
 unsafe impl crate::sync::aref::AlwaysRefCounted for Device {
     #[inline]
-    fn inc_ref(&self) {
-        // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
-        unsafe { bindings::pci_dev_get(self.as_raw()) };
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The safety requirements guarantee that `obj` points to a valid object.
+        unsafe { bindings::pci_dev_get(obj.as_ref().as_raw()) };
     }
 
     #[inline]
rust/kernel/pid_namespace.rs +7 -5
index 979a9718f..6c625a02c 100644
@@ -8,7 +8,9 @@
 //! [`include/linux/pid.h`](srctree/include/linux/pid.h)
 
 use crate::{bindings, sync::aref::AlwaysRefCounted, types::Opaque};
-use core::ptr;
+use core::ptr::{
+    NonNull, //
+};
 
 /// Wraps the kernel's `struct pid_namespace`. Thread safe.
 ///
@@ -43,13 +45,13 @@ pub unsafe fn from_ptr<'a>(ptr: *const bindings::pid_namespace) -> &'a Self {
 // SAFETY: Instances of `PidNamespace` are always reference-counted.
 unsafe impl AlwaysRefCounted for PidNamespace {
     #[inline]
-    fn inc_ref(&self) {
-        // SAFETY: The existence of a shared reference means that the refcount is nonzero.
-        unsafe { bindings::get_pid_ns(self.as_ptr()) };
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The safety requirements guarantee that `obj` points to a valid object.
+        unsafe { bindings::get_pid_ns(obj.as_ref().as_ptr()) };
     }
 
     #[inline]
-    unsafe fn dec_ref(obj: ptr::NonNull<PidNamespace>) {
+    unsafe fn dec_ref(obj: NonNull<PidNamespace>) {
         // SAFETY: The safety requirements guarantee that the refcount is non-zero.
         unsafe { bindings::put_pid_ns(obj.cast().as_ptr()) }
     }
rust/kernel/platform.rs +4 -3
index ac0a012ae..37e7ec9e7 100644
@@ -535,9 +535,10 @@ impl<'a> crate::dma::Device<'a> for Device<device::Core<'a>> {}
 
 // SAFETY: Instances of `Device` are always reference-counted.
 unsafe impl crate::sync::aref::AlwaysRefCounted for Device {
-    fn inc_ref(&self) {
-        // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
-        unsafe { bindings::get_device(self.as_ref().as_raw()) };
+    #[inline]
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The safety requirements guarantee that `obj` points to a valid object.
+        unsafe { bindings::get_device(core::ptr::addr_of_mut!((*obj.as_ref().as_raw()).dev)) };
     }
 
     unsafe fn dec_ref(obj: NonNull<Self>) {
rust/kernel/pwm.rs +3 -3
index 8aa47304b..aefcf68e2 100644
@@ -629,10 +629,10 @@ pub fn new<'a>(
 // SAFETY: Implements refcounting for `Chip` using the embedded `struct device`.
 unsafe impl<T: PwmOps> AlwaysRefCounted for Chip<T> {
     #[inline]
-    fn inc_ref(&self) {
-        // SAFETY: `self.0.get()` points to a valid `pwm_chip` because `self` exists.
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The safety requirements guarantee that `obj` points to a valid `Chip`.
         // The embedded `dev` is valid. `get_device` increments its refcount.
-        unsafe { bindings::get_device(&raw mut (*self.0.get()).dev) };
+        unsafe { bindings::get_device(&raw mut (*obj.as_ref().0.get()).dev) };
     }
 
     #[inline]
rust/kernel/serdev.rs +7 -2
index 17ca504b7..4e58cd138 100644
@@ -571,8 +571,13 @@ unsafe impl<Ctx: device::DeviceContext> device::AsBusDevice<Ctx> for Device<Ctx>
 
 // SAFETY: Instances of `Device` are always reference-counted.
 unsafe impl AlwaysRefCounted for Device {
-    fn inc_ref(&self) {
-        self.as_ref().inc_ref();
+    #[inline]
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The safety requirements guarantee that `obj` points to a valid
+        // `serdev::Device`, and thus to a valid embedded `struct device`.
+        unsafe {
+            bindings::get_device(&raw mut (*obj.as_ptr().cast::<bindings::serdev_device>()).dev)
+        };
     }
 
     unsafe fn dec_ref(obj: NonNull<Self>) {
rust/kernel/sync/aref.rs +14 -5
index 9983ee085..becd2db78 100644
@@ -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>);
 
     /// Decrements the reference count on the object.
     ///
@@ -131,7 +135,7 @@ pub unsafe fn from_raw(ptr: NonNull<T>) -> Self {
     ///
     /// # // SAFETY: TODO.
     /// unsafe impl AlwaysRefCounted for Empty {
-    ///     fn inc_ref(&self) {}
+    ///     unsafe fn inc_ref(_obj: NonNull<Self>) {}
     ///     unsafe fn dec_ref(_obj: NonNull<Self>) {}
     /// }
     ///
@@ -149,8 +153,10 @@ pub fn into_raw(me: Self) -> NonNull<T> {
 }
 
 impl<T: AlwaysRefCounted> Clone for ARef<T> {
+    #[inline]
     fn clone(&self) -> Self {
-        self.inc_ref();
+        // SAFETY: The type invariants guarantee that `self.ptr` is valid.
+        unsafe { T::inc_ref(self.ptr) };
         // SAFETY: We just incremented the refcount above.
         unsafe { Self::from_raw(self.ptr) }
     }
@@ -166,10 +172,13 @@ fn deref(&self) -> &Self::Target {
 }
 
 impl<T: AlwaysRefCounted> From<&T> for ARef<T> {
+    #[inline]
     fn from(b: &T) -> Self {
-        b.inc_ref();
+        let ptr = NonNull::from(b);
+        // SAFETY: `ptr` comes from a live shared reference.
+        unsafe { T::inc_ref(ptr) };
         // SAFETY: We just incremented the refcount above.
-        unsafe { Self::from_raw(NonNull::from(b)) }
+        unsafe { Self::from_raw(ptr) }
     }
 }
 
rust/kernel/task.rs +7 -4
index 3336df493..76cc236fe 100644
@@ -14,7 +14,10 @@
 };
 use core::{
     ops::Deref,
-    ptr, //
+    ptr::{
+        self,
+        NonNull, //
+    },
 };
 
 /// A sentinel value used for infinite timeouts.
@@ -349,9 +352,9 @@ pub fn group_leader(&self) -> &Task {
 // SAFETY: The type invariants guarantee that `Task` is always refcounted.
 unsafe impl crate::sync::aref::AlwaysRefCounted for Task {
     #[inline]
-    fn inc_ref(&self) {
-        // SAFETY: The existence of a shared reference means that the refcount is nonzero.
-        unsafe { bindings::get_task_struct(self.as_ptr()) };
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The safety requirements guarantee that `obj` points to a valid object.
+        unsafe { bindings::get_task_struct(obj.as_ref().as_ptr()) };
     }
 
     #[inline]
rust/kernel/usb.rs +6 -6
index 993760ff3..812159a82 100644
@@ -375,11 +375,11 @@ fn as_ref(&self) -> &Device {
 // SAFETY: Instances of `Interface` are always reference-counted.
 unsafe impl AlwaysRefCounted for Interface {
     #[inline]
-    fn inc_ref(&self) {
-        // SAFETY: The invariants of `Interface` guarantee that `self.as_raw()`
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The invariants of `Interface` guarantee that `obj.as_ref().as_raw()`
         // returns a valid `struct usb_interface` pointer, for which we will
         // acquire a new refcount.
-        unsafe { bindings::usb_get_intf(self.as_raw()) };
+        unsafe { bindings::usb_get_intf(obj.as_ref().as_raw()) };
     }
 
     #[inline]
@@ -428,11 +428,11 @@ fn as_raw(&self) -> *mut bindings::usb_device {
 // SAFETY: Instances of `Device` are always reference-counted.
 unsafe impl AlwaysRefCounted for Device {
     #[inline]
-    fn inc_ref(&self) {
-        // SAFETY: The invariants of `Device` guarantee that `self.as_raw()`
+    unsafe fn inc_ref(obj: NonNull<Self>) {
+        // SAFETY: The invariants of `Device` guarantee that `obj.as_raw()`
         // returns a valid `struct usb_device` pointer, for which we will
         // acquire a new refcount.
-        unsafe { bindings::usb_get_dev(self.as_raw()) };
+        unsafe { bindings::usb_get_dev(obj.as_ref().as_raw()) };
     }
 
     #[inline]
Signature · 1 line
2.47.3
maintainer
#4 lore raw

Re: [PATCH v3] rust: sync: make AlwaysRefCounted::inc_ref an associated function

Quoted 9 lines · Tran Van Tien

In-Reply-To: <[email protected]>
References: <[email protected]>

Incrementing a reference count must be a deliberate act, and every inc_ref must be matched by exactly one dec_ref. Making inc_ref an associated function that takes a NonNull<Self> mirrors dec_ref, which is already an associated function because the object is freed when the count reaches zero.

Quoted 8 lines

Having one half of the protocol take a reference and the other half a raw pointer makes the pairing harder to review and easier to get wrong.

This was suggested by Benno Lossin.

Please consider rate limiting your resend to at most 1 version every 24 hours.

Please consider using the b4 tool [1].

Best regards,
Andreas Hindborg

[1] https://b4.docs.kernel.org/en/latest/

#5 lore raw

Re: [PATCH v3] rust: sync: make AlwaysRefCounted::inc_ref an associated function

In reply to Tran Van Tien
Quoted 12 lines · Tran Van Tien

In-Reply-To: <[email protected]>
References: <[email protected]>

Incrementing a reference count must be a deliberate act, and every inc_ref must be matched by exactly one dec_ref. Making inc_ref an associated function that takes a NonNull<Self> mirrors dec_ref, which is already an associated function because the object is freed when the count reaches zero.

Having one half of the protocol take a reference and the other half a raw pointer makes the pairing harder to review and easier to get wrong.

Quoted 6 lines

This was suggested by Benno Lossin.

--

Hello! There is a patch that implement this [1] with some 'Reviewed-by:' tags.

The last patch is from June, maybe it can be coordinated with Trevor Chan or you to take it over if it needs some updates.

Regards

[1] https://lore.kernel.org/rust-for-linux/[email protected]/

#6 lore raw

Re: [PATCH v3] rust: sync: make AlwaysRefCounted::inc_ref an associated function

In reply to Tran Van Tien

Hi all,

I am withdrawing this series. Sorry for the noise, and for the sending rate in particular.

Andreas is right and I was wrong on the design. Making inc_ref unsafe and taking NonNull<Self> adds a safety contract that is not needed:
leaking a reference is safe, so the function does not have to be unsafe, and the argument should stay &Self. The only change that is actually wanted is that inc_ref becomes an associated function.

That has already been done, and done better than I did it. Trevor's v7 does exactly that, is at v7 after review, and carries Reviewed-by from Alice and Andreas:

https://lore.kernel.org/rust-for-linux/[email protected]/

So there is nothing for this series to add. I will follow Trevor's thread rather than send another revision here.

Thanks to Andreas, Nicolas and the sashiko bot for the reviews.

Tran Van Tien