]> git.ipfire.org Git - thirdparty/kernel/linux.git/commitdiff
rust: i2c: fix I2cAdapter refcounts double increment
authorNicolás Antinori <nico.antinori.7@gmail.com>
Sun, 31 May 2026 18:23:07 +0000 (15:23 -0300)
committerIgor Korotin <igor.korotin@linux.dev>
Sat, 6 Jun 2026 14:19:27 +0000 (15:19 +0100)
When `I2cAdapter::get` executes, it first calls
`bindings::i2c_get_adapter()` which increments the device and module
reference counts. It then takes a reference to the raw pointer and
converts it to an `ARef` via `.into()`.

The implementation of `From<&T> for ARef<T>` where `T: AlwaysRefCounted`
unconditionally calls `T::inc_ref()`. This leads to a second increment
to the reference counts.

Since the returned `ARef` will only release a single reference when
dropped via `dec_ref()`, this leaks one device and module reference count
on every call.

This fix was suggested by sashiko.dev.

Link: https://sashiko.dev/#/patchset/20260521190937.248904-1-nico.antinori.7@gmail.com
Signed-off-by: Nicolás Antinori <nico.antinori.7@gmail.com>
Reviewed-by: Igor Korotin <igor.korotin@linux.dev>
Signed-off-by: Igor Korotin <igor.korotin@linux.dev>
rust/kernel/i2c.rs

index 7b908f0c5a58d2d692cc09e3717f21321d3006c8..c084a45b1916ce552a09ccf99a6c9de5d91bbcd1 100644 (file)
@@ -405,7 +405,9 @@ impl I2cAdapter {
 
         // SAFETY: `adapter` is non-null and points to a live `i2c_adapter`.
         // `I2cAdapter` is #[repr(transparent)], so this cast is valid.
-        Ok(unsafe { (&*adapter.as_ptr().cast::<I2cAdapter<device::Normal>>()).into() })
+        // `i2c_get_adapter` returned the adapter with an incremented refcount, which we pass to
+        // the `ARef`.
+        Ok(unsafe { ARef::from_raw(adapter.cast::<I2cAdapter<device::Normal>>()) })
     }
 }