Re: [PATCH v5 1/2] perf/core: Prevent duplicate sigtrap task work enqueue
From: Sebastian Andrzej Siewior
Date: Thu Nov 19 2026 - 07:09:37 EST
On 2026-11-19 09:51:00 [+0000], Tengda Wu wrote:
> The sigtrap handling in __perf_event_overflow() checks
> event->pending_work before calling task_work_add(), but only sets
> pending_work after the task work has been queued.
>
> This leaves a window where an NMI can interrupt task_work_add()
> and re-enter __perf_event_overflow() for the same event. Since
> pending_work is still zero, the nested invocation can enqueue
> the same pending_task again.
>
> The re-entrant call path looks like this:
>
> __perf_event_overflow()
> task_work_add()
> kasan_record_aux_stack()
> <NMI>
> __perf_event_overflow()
> task_work_add()
>
> The nested invocation may enqueue pending_task before the
> outer invocation does. When the outer invocation resumes, it
> inserts the same task work entry again, potentially creating
> a cycle in the task work list.
>
> As a result, perf_pending_task() may be executed repeatedly,
> leading to unbalanced event reference counting.
The repeated task_work_add() will corrupt the list.
> Fix this by atomically claiming pending_work with
> cmpxchg_acquire() before calling task_work_add(). This ensures
> that only one invocation can enqueue the task work, even when
> another overflow occurs re-entrantly from an NMI.
>
> If task_work_add() fails, clear the claim with
> smp_store_release() to allow a subsequent overflow to retry.
"to revert to previous state".
> In perf_pending_task(), defer clearing pending_work until
> after perf_sigtrap() has completed. Use smp_store_release()
> to ensure that a subsequent overflow cannot re-queue the task
> work before the previous invocation has finished handling it.
>
> Also use smp_load_acquire() when checking pending_work in
> the exclude_kernel warning path to ensure the read is properly
> ordered.
>
> Fixes: c5d93d23a260 ("perf: Enqueue SIGTRAP always via task_work.")
> Signed-off-by: Tengda Wu <wutengda@xxxxxxxxxxxxxxx>
Reviewed-by: Sebastian Andrzej Siewior <bigeasy@xxxxxxxxxxxxx>
Sebastian