[PATCH] thermal/of: fix device node refcount leak in thermal_of_cm_lookup()

Weigang He posted 1 patch 3 weeks, 1 day ago
drivers/thermal/thermal_of.c | 9 +++++++--
1 file changed, 7 insertions(+), 2 deletions(-)
[PATCH] thermal/of: fix device node refcount leak in thermal_of_cm_lookup()
Posted by Weigang He 3 weeks, 1 day ago
of_parse_phandle() returns a device_node pointer with refcount
incremented. The caller must use of_node_put() when done.

thermal_of_cm_lookup() acquires a reference to tr_np via
of_parse_phandle() but fails to release it on multiple paths:
  - When tr_np != trip->priv (continue path)
  - When thermal_of_get_cooling_spec() returns true (early return)
  - At the end of each loop iteration

Add the missing of_node_put() calls on all paths to prevent the
reference count leak.

Fixes: 423de5b5bc5b ("thermal/of: Fix cdev lookup in thermal_of_should_bind()")
Cc: stable@vger.kernel.org
Signed-off-by: Weigang He <geoffreyhe2@gmail.com>
---
 drivers/thermal/thermal_of.c | 9 +++++++--
 1 file changed, 7 insertions(+), 2 deletions(-)

diff --git a/drivers/thermal/thermal_of.c b/drivers/thermal/thermal_of.c
index 1a51a4d240ff6..ef3e5d4e3b6e8 100644
--- a/drivers/thermal/thermal_of.c
+++ b/drivers/thermal/thermal_of.c
@@ -284,8 +284,10 @@ static bool thermal_of_cm_lookup(struct device_node *cm_np,
 		int count, i;
 
 		tr_np = of_parse_phandle(child, "trip", 0);
-		if (tr_np != trip->priv)
+		if (tr_np != trip->priv) {
+			of_node_put(tr_np);
 			continue;
+		}
 
 		/* The trip has been found, look up the cdev. */
 		count = of_count_phandle_with_args(child, "cooling-device",
@@ -294,9 +296,12 @@ static bool thermal_of_cm_lookup(struct device_node *cm_np,
 			pr_err("Add a cooling_device property with at least one device\n");
 
 		for (i = 0; i < count; i++) {
-			if (thermal_of_get_cooling_spec(child, i, cdev, c))
+			if (thermal_of_get_cooling_spec(child, i, cdev, c)) {
+				of_node_put(tr_np);
 				return true;
+			}
 		}
+		of_node_put(tr_np);
 	}
 
 	return false;
-- 
2.34.1
Re: [PATCH] thermal/of: fix device node refcount leak in thermal_of_cm_lookup()
Posted by Markus Elfring 2 weeks, 6 days ago
…
> Add the missing of_node_put() calls on all paths to prevent the

How do you think about to use an attribute like “__free(device_node)” instead?
https://elixir.bootlin.com/linux/v6.19-rc5/source/include/linux/of.h#L138
https://elixir.bootlin.com/linux/v6.19-rc5/source/drivers/thermal/thermal_of.c#L277-L303


Was such an improvable implementation detail detected by any known source code
analysis approaches?


> reference count leak.

Would you like to use this term also in the summary phrase?

Regards,
Markus