Skip to contentSkip to conversation

media: mc: Fix potential media_device lifetime race

PATCH New Haotian Zhang 1 participant 1 message Aug 17

Subsystems (2)
lore
Share & tools
lore
#0 lore raw

PATCH 1/1 media: mc: Fix potential media_device lifetime race

__media_device_get() traverses the global media_device_list under media_device_lock and takes a reference on a matching instance with an unconditional kref_get(). media_device_delete() drops the last reference with kref_put() outside the lock, so the refcount can reach zero while the instance is still on the list; if a concurrent allocate() attempts to acquire a reference from such an instance, kref_get() operates on a zero refcount while release() is already in progress. The allocator may then return an instance that release() subsequently frees, leading to a use-after-free.

Use kref_get_unless_zero() in __media_device_get() when acquiring the reference. If the reference count has already dropped to zero, release is in progress, so skip the entry and allocate a fresh instance instead.

Fixes 6e1d824e7a1d ("media: Media Device Allocator API")
---
 drivers/media/mc/mc-dev-allocator.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/media/mc/mc-dev-allocator.c +2 -1
index ae17887dec59..8b97372adc83 100644
@@ -68,7 +68,8 @@ static struct media_device *__media_device_get(struct device *dev,
 		if (mdi->mdev.dev != dev)
 			continue;
 
-		kref_get(&mdi->refcount);
+		if (!kref_get_unless_zero(&mdi->refcount))
+			continue;
 
 		/* get module reference for the media_device owner */
 		if (owner != mdi->owner && !try_module_get(mdi->owner))
Signature · 1 line
2.43.0