[PATCH] i2c: core: prevent use-after-free in i2c_get_adapter by removing adapter from IDR earlier
From: Sameeksha Sankpal
Date: Sun Nov 16 2025 - 22:43:08 EST
i2c_del_adapter() currently removes the adapter from i2c_adapter_idr
after device_unregister(&adap->dev). This leaves a window where
i2c_get_adapter() may still find the adapter and call get_device(),
which WARNs because the kobject refcount is already zero.
Fix by removing the adapter from the IDR before unregistering the device.
This prevents new lookups while the device is being torn down.
Reported-by: syzbot+76501d32a94a432940a8@xxxxxxxxxxxxxxxxxxxxxxxxx
Closes: https://syzkaller.appspot.com/bug?extid=76501d32a94a432940a8
Signed-off-by: Sameeksha Sankpal <sameekshasankpal@xxxxxxxxx>
---
drivers/i2c/i2c-core-base.c | 14 ++++++++++----
1 file changed, 10 insertions(+), 4 deletions(-)
diff --git a/drivers/i2c/i2c-core-base.c b/drivers/i2c/i2c-core-base.c
index ae7e9c8b65a6..229158401d54 100644
--- a/drivers/i2c/i2c-core-base.c
+++ b/drivers/i2c/i2c-core-base.c
@@ -1773,6 +1773,15 @@ void i2c_del_adapter(struct i2c_adapter *adap)
__process_removed_adapter);
mutex_unlock(&core_lock);
+ /*
+ * Stop publishing the adapter before tearing down its device/kobject.
+ * Otherwise i2c_get_adapter() may still find it in the IDR and then
+ * get_device() will WARN because the kobject is already at 0.
+ */
+ mutex_lock(&core_lock);
+ idr_remove(&i2c_adapter_idr, adap->nr);
+ mutex_unlock(&core_lock);
+
/* Remove devices instantiated from sysfs */
mutex_lock_nested(&adap->userspace_clients_lock,
i2c_adapter_depth(adap));
@@ -1813,10 +1822,7 @@ void i2c_del_adapter(struct i2c_adapter *adap)
device_unregister(&adap->dev);
wait_for_completion(&adap->dev_released);
- /* free bus id */
- mutex_lock(&core_lock);
- idr_remove(&i2c_adapter_idr, adap->nr);
- mutex_unlock(&core_lock);
+ /* IDR entry already removed above; no new lookups are possible now. */
/* Clear the device structure in case this adapter is ever going to be
added again */
--
2.43.0