Skip to contentSkip to conversation

cpuidle: coupled: Fix use-after-free on device unregister

PATCH Superseded Mao Weiming 1 participant 1 message May 19

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

PATCH v2 1/1 cpuidle: coupled: Fix use-after-free on device unregister

This issue was found by code review of drivers/cpuidle/coupled.c, not from a crash report.

cpuidle_coupled_unregister_device() has had its refcount check inverted ever since the function was added:

	if (--coupled->refcnt)
		kfree(coupled);
	dev->coupled = NULL;

A struct cpuidle_coupled is shared by every CPU in a coupled set. cpuidle_coupled_register_device() either allocates a new instance with refcnt = 1, or reuses an existing one and bumps refcnt. The struct must therefore only be freed once refcnt drops back to zero. The current code does the exact opposite:

- With N >= 2 CPUs in the set, the first CPU to unregister decrements refcnt from N to N-1, the condition becomes true, and the struct is kfree()'d while the remaining N-1 CPUs still hold dev->coupled pointers to that memory.

- When the last CPU finally unregisters, refcnt becomes 0, the condition is false, and the struct is leaked.

Subsequent unregister calls in the same loop then dereference and decrement coupled->refcnt on the freed object, and any CPU hotplug callback racing into coupled_cpu_online() / coupled_cpu_up_prepare() between the kfree() and the final dev->coupled = NULL assignment will also touch the dangling pointer.

Fix it by freeing the struct only when refcnt reaches zero, matching the kerneldoc above the function and the symmetric increment in cpuidle_coupled_register_device().

Fixes 4126c0197bc8 ("cpuidle: add support for states that affect multiple cpus")

---
Changes since v1:
- Use full name "Mao Weiming" in the patch's From: and Signed-off-by:
trailers to match the email's From: header.
- No code or commit-message changes.

v1: https://lore.kernel.org/all/[email protected]/

 drivers/cpuidle/coupled.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/cpuidle/coupled.c +1 -1
index fb91a9e0e3c2..25d8a6b27a51 100644
@@ -687,7 +687,7 @@ void cpuidle_coupled_unregister_device(struct cpuidle_device *dev)
 	if (cpumask_empty(&dev->coupled_cpus))
 		return;
 
-	if (--coupled->refcnt)
+	if (!--coupled->refcnt)
 		kfree(coupled);
 	dev->coupled = NULL;
 }
Signature · 1 line
2.25.1