[PATCH v3 1/6] thermal: core: Fix thermal zone governor cleanup issues

From: Rafael J. Wysocki

Date: Mon Apr 06 2026 - 12:22:21 EST


From: Rafael J. Wysocki <rafael.j.wysocki@xxxxxxxxx>

If thermal_zone_device_register_with_trips() fails after adding
a thermal governor to the thermal zone being registered, the
governor is not removed from it as appropriate which may lead to
a memory leak, so address this by adding the governor cleanup to
the rollback path.

In turn, thermal_zone_device_unregister() calls thermal_set_governor()
without acquiring the thermal zone lock beforehand which may race with
a governor update via sysfs and may lead to a use-after-free in that
case, so address it by placing the cleanup thermal_set_governor()
call after the wait_for_completion() one, which reflects the
registration error path ordering.

Fixes: e33df1d2f3a0 ("thermal: let governors have private data for each thermal zone")
Cc: All applicable <stable@xxxxxxxxxxxxxxx>
Signed-off-by: Rafael J. Wysocki <rafael.j.wysocki@xxxxxxxxx>
---

v2 -> v3: New patch

---
drivers/thermal/thermal_core.c | 9 ++++++---
1 file changed, 6 insertions(+), 3 deletions(-)

--- a/drivers/thermal/thermal_core.c
+++ b/drivers/thermal/thermal_core.c
@@ -1618,7 +1618,7 @@ thermal_zone_device_register_with_trips(
/* Add nodes that are always present via .groups */
result = thermal_zone_create_device_groups(tz);
if (result)
- goto remove_id;
+ goto remove_governor;

result = device_register(&tz->device);
if (result)
@@ -1649,6 +1649,8 @@ unregister:
release_device:
put_device(&tz->device);
wait_for_completion(&tz->removal);
+remove_governor:
+ thermal_set_governor(tz, NULL);
remove_id:
ida_free(&thermal_tz_ida, id);
free_tzp:
@@ -1731,8 +1733,6 @@ void thermal_zone_device_unregister(stru

cancel_delayed_work_sync(&tz->poll_queue);

- thermal_set_governor(tz, NULL);
-
thermal_thresholds_exit(tz);
thermal_remove_hwmon_sysfs(tz);
ida_free(&thermal_tz_ida, tz->id);
@@ -1744,6 +1744,9 @@ void thermal_zone_device_unregister(stru
thermal_notify_tz_delete(tz);

wait_for_completion(&tz->removal);
+
+ thermal_set_governor(tz, NULL);
+
kfree(tz->tzp);
kfree(tz);
}