Re: [PATCH v5 1/2] perf/core: Prevent duplicate sigtrap task work enqueue

From: Peter Zijlstra

Date: Wed Nov 25 2026 - 03:27:31 EST


On Mon, Nov 23, 2026 at 09:00:04AM +0100, Sebastian Andrzej Siewior wrote:
> On 2026-11-20 18:49:42 [+0100], Peter Zijlstra wrote:
> > From: Tengda Wu <wutengda@xxxxxxxxxxxxxxx>
> >
> > 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 (software/tracepoint)
> > 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()
> > <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.
> >
> > Fix this by atomically claiming pending_work with cmpxchg_local()
> > 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.
> >
> > Notably: sigtrap events must be per-task, meaning that the there is no
> > concurrency, only re-entrancy.
> >
> > [peterz: clarify and rewrite]
> > Fixes: c5d93d23a260 ("perf: Enqueue SIGTRAP always via task_work.")
> > Signed-off-by: Tengda Wu <wutengda@xxxxxxxxxxxxxxx>
> > Signed-off-by: Peter Zijlstra (Intel) <peterz@xxxxxxxxxxxxx>
>
> This looks good. Shouldn't we insert also
>
> diff --git a/kernel/events/core.c b/kernel/events/core.c
> index e870f12c3ad81..edadc34f065fc 100644
> --- a/kernel/events/core.c
> +++ b/kernel/events/core.c
> @@ -7776,8 +7776,8 @@ static void perf_pending_task(struct callback_head *head)
> rctx = perf_swevent_get_recursion_context();
>
> if (event->pending_work) {
> - event->pending_work = 0;
> perf_sigtrap(event);
> + WRITE_ONCE(event->pending_work, 0);
> local_dec(&event->ctx->nr_no_switch_fast);
> }
> put_event(event);
>
> To ensure the ::pending_work is reset after perf_sigtrap() is done?

task_work_add() can be used while inside task_work; so I do not see why
this would matter.