[PATCH 1/3] mm: kmemleak: take kmemleak_lock in the disable-time object cleanup

From: Catalin Marinas

Date: Thu Dec 03 2026 - 10:25:28 EST


__kmemleak_do_cleanup() removes objects from object_list and the object
tree without kmemleak_lock, assuming nothing else changes them once
kmemleak is disabled. This is not the case:

- a "clear" written to the debugfs file before cleanup_work has cleared
kmemleak_free_enabled runs the cleanup while frees are still tracked;

- a "clear" written while cleanup_work's own cleanup is still running
starts a second, concurrent cleanup;

- when kmemleak disables itself, e.g. on an __alloc_object() failure, a
kmemleak_free() or kmemleak_alloc() that passed its enabled check
before the flag was cleared can still update the tree and list.

The concurrent updates corrupt the tree and list and lead to a
use-after-free in rb_erase().

Take kmemleak_lock when removing each object in the cleanup.

Fixes: 2abd839aa7e6 ("kmemleak: Do not corrupt the object_list during clean-up")
Reported-by: Weilin Tong <tongweilin@xxxxxxxxxxxxxxxxx>
Link: https://lore.kernel.org/r/149d93f2cfe20d355f4d9882ce2bf99030217772.1793871596.git.tongweilin@xxxxxxxxxxxxxxxxx
Reported-by: Sashiko <sashiko-bot@xxxxxxxxxx>
Closes: https://sashiko.dev/#/bug/linux-d5496447-37ff-43f3-81ed-e1a5616df463
Cc: <stable@xxxxxxxxxxxxxxx>
Signed-off-by: Catalin Marinas <catalin.marinas@xxxxxxx>
---
mm/kmemleak.c | 22 ++++++++++++++++------
1 file changed, 16 insertions(+), 6 deletions(-)

diff --git a/mm/kmemleak.c b/mm/kmemleak.c
index 20c0eb41c873..9c2d01fd4113 100644
--- a/mm/kmemleak.c
+++ b/mm/kmemleak.c
@@ -619,7 +619,7 @@ static struct kmemleak_object *find_and_get_object(unsigned long ptr, int alias)

/*
* Remove an object from its object tree and object_list. Must be called with
- * the kmemleak_lock held _if_ kmemleak is still enabled.
+ * the kmemleak_lock held.
*/
static void __remove_object(struct kmemleak_object *object)
{
@@ -2473,15 +2473,25 @@ static const struct file_operations kmemleak_fops = {

static void __kmemleak_do_cleanup(void)
{
- struct kmemleak_object *object, *tmp;
+ struct kmemleak_object *object;
+ unsigned long flags;
unsigned int cnt = 0;

/*
- * Kmemleak has already been disabled, no need for RCU list traversal
- * or kmemleak_lock held.
+ * Callbacks that passed their enabled checks before kmemleak was
+ * disabled may still be adding or removing objects.
*/
- list_for_each_entry_safe(object, tmp, &object_list, object_list) {
- __remove_object(object);
+ while (true) {
+ raw_spin_lock_irqsave(&kmemleak_lock, flags);
+ object = list_first_entry_or_null(&object_list,
+ struct kmemleak_object,
+ object_list);
+ if (object)
+ __remove_object(object);
+ raw_spin_unlock_irqrestore(&kmemleak_lock, flags);
+
+ if (!object)
+ break;
__delete_object(object);

/* Call cond_resched() once per 64 iterations to avoid soft lockup */