Re: [PATCH] fork: clear p->mm when copy_process() fails

From: Peter Zijlstra

Date: Fri Nov 20 2026 - 07:08:39 EST


On Thu, Nov 19, 2026 at 09:04:58AM +0100, David Hildenbrand (Arm) wrote:
> From: Chris Mason <mason@xxxxxxxxxx>
>
> When copy_process() fails after copy_mm(), the error path drops the mm
> reference but leaves p->mm set. Perf and BPF can still reach the
> task, and take a reference on the already freed mm through get_task_mm()
> or bpf_find_vma(), resulting in a use-after-free:
>
> copy_process() PERF_EVENT_IOC_SET_FILTER
> ============== =========================
> perf_event_init_task(p)
> copy_mm(p)
> a later step fails
> mmput(p->mm)
> /* frees the mm */
> perf_event_addr_filters_apply()
> get_task_mm(p)
> /* use-after-free */
>
> Similarly, a BPF program on the task_free LSM hook can call bpf_find_vma(p)
> before the task is freed.
>
> Fix it by clearing p->mm under task_lock() before dropping the reference,
> just like exit_mm() does.
>
> Further, if copy_process() fails before copy_mm(), p->mm is still the
> parent's mm pointer copied by dup_task_struct(), without having taken a
> reference. While nobody can access it concurrently, there is the
> chance that it might get accessed later when a BPF program is attached
> to free_task().
>
> With CONFIG_MEMCG the task is freed after an RCU grace period, so the
> parent might already be gone and p->mm in the child points at something
> that was already freed. So let's just clear p->mm before freeing the
> task. No lock is required as there cannot be concurrent access (and we
> might not even have the lock initialized yet).
>
> This has medium urgency.
>
> Fixes: 375637bc5249 ("perf/core: Introduce address range filtering")
> Fixes: 7c7e3d31e785 ("bpf: Introduce helper bpf_find_vma")
> Reported-by: Sashiko <sashiko-bot@xxxxxxxxxx>
> Closes: https://lore.kernel.org/sashiko-outbox-180866@xxxxxxxxxx/
> Cc: stable@xxxxxxxxxxxxxxx
> Signed-off-by: Chris Mason <mason@xxxxxxxxxx>
> [ david: simplify description and comments ]
> Signed-off-by: David Hildenbrand (Arm) <david@xxxxxxxxxx>
> ---
> I can take this through my tree (rather soonish) unless someone else
> wants to pick this up.

Have at.

Acked-by: Peter Zijlstra (Intel) <peterz@xxxxxxxxxxxxx>