Re: [PATCH] rust: i2c: avoid locking when calling I2cAdapter::inc_ref
From: Nicolás Antinori
Date: Tue Aug 11 2026 - 10:47:56 EST
On Sun Aug 9, 2026 at 10:17 AM -03, Igor Korotin wrote:
> Hello Nicolás
>
> Sorry for the delay.
>
> Yes, worth fixing regardless of real users -- inc_ref taking a lock it
> doesn't need is a real bug, not speculative work.
>
> Instead of adding a separate Rust-only wrapper, please consider splitting
> i2c_get_adapter itself: pull the increment into a helper, export it, and
> call it directly from inc_ref -- no lock, no lookup:
>
> +bool __i2c_adapter_get(struct i2c_adapter *adapter)
> +{
> + if (try_module_get(adapter->owner)) {
> + get_device(&adapter->dev);
> + return true;
> + }
> + return false;
> +}
> +EXPORT_SYMBOL(__i2c_adapter_get);
> +
> struct i2c_adapter *i2c_get_adapter(int nr)
> {
> struct i2c_adapter *adapter;
>
> mutex_lock(&core_lock);
> adapter = idr_find(&i2c_adapter_idr, nr);
> - if (!adapter)
> - goto exit;
> -
> - if (try_module_get(adapter->owner))
> - get_device(&adapter->dev);
> - else
> + if (adapter && !__i2c_adapter_get(adapter))
> adapter = NULL;
> -
> - exit:
> mutex_unlock(&core_lock);
> return adapter;
> }
> EXPORT_SYMBOL(i2c_get_adapter);
Excellent! Thank you for this suggestion and the explanation!
>
> Heads up for v2: Trevor Chan has a patch changing AlwaysRefCounted::inc_ref
> to an associated function (fn inc_ref(obj: &Self)). Not merged yet --
> rebase onto it if it lands first.
I think it is better to wait until Trevor Chan's patch gets merged since
it is in v7 [1] and already has been reviewed by some mantainers. If I send
this fix and gets merged first he will probably have conflicts and have
to send a v8.
I'll keep an eye on the progress of that patch and once it is merged I
am going to send this fix.
Thank you,
Nicolás
[1] https://lore.kernel.org/rust-for-linux/20260628100731.64885-1-trev@xxxxxxxxxxxx/T/#u