Re: [PATCH v5 1/2] perf/core: Prevent duplicate sigtrap task work enqueue
From: Sebastian Andrzej Siewior
Date: Mon Nov 23 2026 - 03:03:45 EST
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?
Sebastian