Forwarded: [PATCH] mm/workingset: fix NULL pointer dereference in lru_gen_test_recent

syzbot
2025-12-07T12:44:50Z

Subject: [PATCH] mm/workingset: fix NULL pointer dereference in lru_gen_test_recent
Author: kartikey406@gmail.com

#syz test: git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git master

Add NULL check for memcg in lru_gen_test_recent() to prevent crash when
mem_cgroup_from_id() returns NULL.

The crash occurs when a folio's shadow entry contains a memcg_id that
no longer maps to a valid memory cgroup. This can happen when:

1. The memory cgroup has been deleted/freed
2. A folio was created without proper memcg association (e.g., during
procmap_query build ID parsing via freader_get_folio)
3. The memcg_id in the shadow entry is invalid or zero

When lru_gen_test_recent() calls mem_cgroup_from_id(), it may return
NULL. The subsequent call to mem_cgroup_lruvec() with a NULL memcg
triggers a crash because the inline function's code calculates
memcg->nodeinfo offset (0x4e00) before the NULL check can execute,
causing a NULL pointer dereference that KASAN detects.

Although mem_cgroup_lruvec() has a NULL check internally, compiler
inlining and optimization causes the offset calculation to occur
first, making the internal check unreachable.

The fix adds an explicit NULL check after mem_cgroup_from_id() and
falls back to root_mem_cgroup, which is consistent with how
mem_cgroup_lruvec() itself handles NULL pointers.

Reproducer triggers this via:
procfs_procmap_ioctl() -> do_procmap_query() -> __build_id_parse() ->
freader_get_folio() -> filemap_add_folio() -> workingset_refault() ->
lru_gen_refault() -> lru_gen_test_recent()

KASAN report:
general protection fault in mem_cgroup_lruvec
RIP: mem_cgroup_lruvec+0xee/0x320 include/linux/memcontrol.h:720
Call Trace:
lru_gen_test_recent+0xee/0x320 mm/workingset.c:275
workingset_refault+0x251/0xca0 mm/workingset.c:546
filemap_add_folio+0x23d/0x610 mm/filemap.c:981

Reported-by: syzbot+e008db2ac01e282550ee@syzkaller.appspotmail.com
Closes: https://syzkaller.appspot.com/bug?extid=e008db2ac01e282550ee
Signed-off-by: Deepanshu Kartikey <kartikey406@gmail.com>
---
mm/workingset.c | 2 ++
1 file changed, 2 insertions(+)

diff --git a/mm/workingset.c b/mm/workingset.c
index e9f05634747a..8b6332cfb4f0 100644
--- a/mm/workingset.c
+++ b/mm/workingset.c
@@ -272,6 +272,8 @@ static bool lru_gen_test_recent(void *shadow, struct lruvec **lruvec,
unpack_shadow(shadow, &memcg_id, &pgdat, token, workingset);

memcg = mem_cgroup_from_id(memcg_id);
+ if (!memcg)
+ memcg = root_mem_cgroup;
*lruvec = mem_cgroup_lruvec(memcg, pgdat);

max_seq = READ_ONCE((*lruvec)->lrugen.max_seq);
--
2.43.0