[PATCH] mm: huge_memory: Fix kobject cleanup in thpsize_create error

From: Hongling Zeng

Date: Sat Jul 11 2026 - 04:47:23 EST


When kobject_init_and_add() fails, the kobject API requires calling
kobject_put() to properly clean up the memory, not direct kfree().

According to the kobject API documentation, kobject_init_and_add()
calls kobject_init() internally. If the subsequent kobject_add()
fails, the kobject has still been initialized and must be cleaned up
via the reference count mechanism (kobject_put), not direct kfree().

Direct kfree() leaves the kobject's internal state (including the
reference count and kset membership) uncleaned, which can cause:
- Memory leaks of kobject internal structures
- Potential use-after-free if there are pending references
- Inconsistent state with the rest of the error handling code

This fix matches the pattern used elsewhere in the kernel and in the
same function (err_put label) which correctly uses kobject_put().

Fixes: 3485b88390b0 ("mm: thp: introduce multi-size THP sysfs interface")
Cc: stable@xxxxxxxxxxxxxxx
Signed-off-by: Hongling Zeng <zenghongling@xxxxxxxxxx>
---
mm/huge_memory.c | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/mm/huge_memory.c b/mm/huge_memory.c
index 2bccb0a53a0a..7aeb17d60ac7 100644
--- a/mm/huge_memory.c
+++ b/mm/huge_memory.c
@@ -819,7 +819,7 @@ static struct thpsize *thpsize_create(int order, struct kobject *parent)
ret = kobject_init_and_add(&thpsize->kobj, &thpsize_ktype, parent,
"hugepages-%lukB", size);
if (ret) {
- kfree(thpsize);
+ kobject_put(&thpsize->kobj);
goto err;
}

--
2.25.1