A pagemap file holds an mm_count reference, not an mm_users reference. Unlike pagemap_read(), do_pagemap_scan() does not acquire a live-MM reference before walking the page tables. Its mmap read lock does not exclude the first phase of exit_mmap(), which also unmaps VMAs under the read lock. A process retaining a pagemap descriptor can therefore race the final mmput() and access resources that have already been released. In particular, a concurrent last userfaultfd close can free a context still reachable through a dying MM's VMAs, and unmap_vmas() can free a shared HugeTLB VMA's lock while the page walker is entering down_read(). KASAN reports both a userfaultfd context read-after-free and a HugeTLB rwsem write-after-free with unprivileged, read-only PAGEMAP_SCAN requests. Acquire mmget_not_zero() after validating the ioctl arguments and keep the reference for the entire scan, including across mmap lock drops and MMU-notifier operations. Return -ESRCH if the MM is already dead, as PROCMAP_QUERY does. Balance the reference on the bounce-buffer allocation failure path and at the common exit. The pagemap file continues to hold only its existing mm_count reference between operations. Fixes: 52526ca7fdb9 ("fs/proc/task_mmu: implement IOCTL to get and optionally clear info about PTEs") Cc: Signed-off-by: Kyle Zeng --- I have a reproducer for this issue. fs/proc/task_mmu.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/fs/proc/task_mmu.c b/fs/proc/task_mmu.c index 5c54aebe2118..d2cee8dcba58 100644 --- a/fs/proc/task_mmu.c +++ b/fs/proc/task_mmu.c @@ -3235,11 +3235,14 @@ static long do_pagemap_scan(struct mm_struct *mm, unsigned long uarg) if (ret) return ret; + if (!mmget_not_zero(mm)) + return -ESRCH; + p.masks_of_interest = p.arg.category_mask | p.arg.category_anyof_mask | p.arg.return_mask; ret = pagemap_scan_init_bounce_buffer(&p); if (ret) - return ret; + goto out_mm; for (walk_start = p.arg.start; walk_start < p.arg.end; walk_start = p.arg.walk_end) { @@ -3294,6 +3297,8 @@ static long do_pagemap_scan(struct mm_struct *mm, unsigned long uarg) ret = -EFAULT; kfree(p.vec_buf); +out_mm: + mmput(mm); return ret; }