Skip to contentSkip to conversation

perf/core: Fix sigtrap task_work races

PATCH In review Tengda Wu 4 participants 34 messages Nov 19 – Nov 24 perf events

lore
Share & tools
lore
author
#1 lore raw

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

In reply to Tengda Wu

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.

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.

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.")
---
 kernel/events/core.c | 39 ++++++++++++++++++++++++++-------------
 1 file changed, 26 insertions(+), 13 deletions(-)
kernel/events/core.c +26 -13
index 614f9f0e6500..857230b023ae 100644
@@ -7775,10 +7775,14 @@ static void perf_pending_task(struct callback_head *head)
 	 */
 	rctx = perf_swevent_get_recursion_context();
 
-	if (event->pending_work) {
-		event->pending_work = 0;
+	if (smp_load_acquire(&event->pending_work)) {
 		perf_sigtrap(event);
 		local_dec(&event->ctx->nr_no_switch_fast);
+		/*
+		 * Ensure the pending work is fully handled before allowing
+		 * another overflow to queue it. See __perf_event_overflow().
+		 */
+		smp_store_release(&event->pending_work, 0);
 	}
 	put_event(event);
 
@@ -10950,16 +10954,25 @@ static int __perf_event_overflow(struct perf_event *event,
 
 		notify_mode = in_nmi() ? TWA_NMI_CURRENT : TWA_RESUME;
 
-		if (!event->pending_work &&
-		    !task_work_add(current, &event->pending_task, notify_mode)) {
-			event->pending_work = pending_id;
-			local_inc(&event->ctx->nr_no_switch_fast);
-			WARN_ON_ONCE(!atomic_long_inc_not_zero(&event->refcount));
-
-			event->pending_addr = 0;
-			if (valid_sample && (data->sample_flags & PERF_SAMPLE_ADDR))
-				event->pending_addr = data->addr;
-
+		/*
+		 * Claim pending_work before queueing the task work to prevent
+		 * another overflow from queueing it concurrently.
+		 */
+		if (cmpxchg_acquire(&event->pending_work, 0, pending_id) == 0) {
+			if (!task_work_add(current, &event->pending_task, notify_mode)) {
+				local_inc(&event->ctx->nr_no_switch_fast);
+				WARN_ON_ONCE(!atomic_long_inc_not_zero(&event->refcount));
+
+				event->pending_addr = 0;
+				if (valid_sample && (data->sample_flags & PERF_SAMPLE_ADDR))
+					event->pending_addr = data->addr;
+			} else {
+				/*
+				 * Publish the failed queueing attempt so
+				 * a subsequent overflow can retry.
+				 */
+				smp_store_release(&event->pending_work, 0);
+			}
 		} else if (event->attr.exclude_kernel && valid_sample) {
 			/*
 			 * Should not be able to return to user space without
@@ -10973,7 +10986,7 @@ static int __perf_event_overflow(struct perf_event *event,
 			 *     To approximate progress (with false negatives),
 			 *     check 32-bit hash of the current IP.
 			 */
-			WARN_ON_ONCE(event->pending_work != pending_id);
+			WARN_ON_ONCE(smp_load_acquire(&event->pending_work) != pending_id);
 		}
 	}
 
Signature · 1 line
2.34.1

Tengda Wu

author
#0 lore raw

v5 cover perf/core: Fix sigtrap task_work races

Two fixes for sigtrap task_work handling since the switch to always enqueue SIGTRAP via task_work.

The warning splats and PoCs for both patches are too long to inline in the commit messages, so they are provided as separate replies at the following links:

Patch 1: https://lore.kernel.org/all/[email protected]/
Patch 2: https://lore.kernel.org/all/[email protected]/

Patch 1 fixes a re-entrancy race in __perf_event_overflow(): pending_work was set only after task_work_add(), so an NMI could re-enter and enqueue the same pending_task twice, creating a cycle in the task work list and unbalancing the event refcount. Claim pending_work before enqueuing, and clear it if the enqueue fails.

Patch 2 fixes a WARN_ON_ONCE() in perf_sigtrap() triggered by the context fast-swap path swapping ctx->task while a sigtrap event has pending task work. SIGTRAP is targeted at ctx->task, so exclude sigtrap events from fast-swap alongside inherit+sample-read events.

Changelog
=========
v4 -> v5:
- v4: https://lore.kernel.org/all/[email protected]/
- Roll back patch 2 to v3 to avoid the fast swap isolation omission in

    the nr_no_switch_fast 1->0 scenario. (Shashiko)

v3 -> v4:
- v3: https://lore.kernel.org/all/[email protected]/
- Patch 1: Use acquire/release pairs for pending_work updates (Sebastian)
- Patch 2: Remove redundant nr_no_switch_fast updates (Sebastian)
v2 -> v3:
- v2: https://lore.kernel.org/all/[email protected]/
- Added Patch 2 to fix WARN_ON_ONCE() in perf_sigtrap()
v1 -> v2:
- v1: https://lore.kernel.org/all/[email protected]/
- Drop the redundant event->pending_work assignment. (Sashiko)

Tengda Wu (2):
perf/core: Prevent duplicate sigtrap task work enqueue perf/core: Disable context fast-swap for sigtrap events

 include/linux/perf_event.h |  6 ++---
 kernel/events/core.c       | 48 ++++++++++++++++++++++++++------------
 2 files changed, 35 insertions(+), 19 deletions(-)
Signature · 1 line
2.34.1
author
#19 lore raw

PATCH v5 2/2 perf/core: Disable context fast-swap for sigtrap events

perf_sigtrap() contains:

	WARN_ON_ONCE(event->ctx->task != current)

The warning assumes that an event's ctx->task always matches the task that ends up running the pending task_work. That assumption can be broken by the context fast-swap path.

The failure sequence is:

1. A -> B switch, perf_event_context_sched_out() takes the fast path and does WRITE_ONCE(ctx->task, next) / WRITE_ONCE(next_ctx->task, task). An NMI then hits while the context is swapped, and __perf_event_overflow() queues pending task_work on the *current* task (A), even though the event now belongs to B's swapped-in context view.

2. B -> A switch. Because A now has pending task_work, nr_no_switch_fast is non-zero, so the slow path is taken and ctx->task is *not* swapped back.

3. A returns to user mode, task_work runs perf_pending_task() -> perf_sigtrap(), and event->ctx->task no longer equals current, tripping the WARN_ON_ONCE().

The context fast-swap path was already excluded for events that need stable task association (inherit + sample read). sigtrap events have the same requirement: the SIGTRAP is targeted at ctx->task and must not be delivered after ctx->task has been swapped to another task.

Fix this by also excluding events with attr->sigtrap from the fast-swap path, i.e. bump nr_no_switch_fast for sigtrap events in list_add_event()/list_del_event(), and update the comment describing the invariant accordingly.

Fixes c5d93d23a260 ("perf: Enqueue SIGTRAP always via task_work.")
---
 include/linux/perf_event.h | 6 ++----
 kernel/events/core.c       | 9 +++++++--
 2 files changed, 9 insertions(+), 6 deletions(-)
include/linux/perf_event.h +2 -4
index e1e11500df09..d2eb22cc5b71 100644
@@ -1067,10 +1067,8 @@ struct perf_event_context {
 	 * should be avoided.
 	 *
 	 * Sum (event->pending_work + events with
-	 *    (attr->inherit && (attr->sample_type & PERF_SAMPLE_READ)))
-	 *
-	 * The SIGTRAP is targeted at ctx->task, as such it won't do changing
-	 * that until the signal is delivered.
+	 *    (attr->inherit && (attr->sample_type & PERF_SAMPLE_READ)) +
+	 *    events with attr->sigtrap)
 	 */
 	local_t				nr_no_switch_fast;
 };
kernel/events/core.c +7 -2
index 857230b023ae..094b42ed6462 100644
@@ -2009,7 +2009,7 @@ list_add_event(struct perf_event *event, struct perf_event_context *ctx)
 		ctx->nr_user++;
 	if (event->attr.inherit_stat)
 		ctx->nr_stat++;
-	if (has_inherit_and_sample_read(&event->attr))
+	if (has_inherit_and_sample_read(&event->attr) || event->attr.sigtrap)
 		local_inc(&ctx->nr_no_switch_fast);
 
 	if (event->state > PERF_EVENT_STATE_OFF)
@@ -2235,7 +2235,7 @@ list_del_event(struct perf_event *event, struct perf_event_context *ctx)
 		ctx->nr_user--;
 	if (event->attr.inherit_stat)
 		ctx->nr_stat--;
-	if (has_inherit_and_sample_read(&event->attr))
+	if (has_inherit_and_sample_read(&event->attr) || event->attr.sigtrap)
 		local_dec(&ctx->nr_no_switch_fast);
 
 	list_del_rcu(&event->event_entry);
@@ -3841,6 +3841,11 @@ perf_event_context_sched_out(struct task_struct *task, struct task_struct *next)
 				 * SAMPLE_READ events they should be switched
 				 * out using the slow path so that they are
 				 * treated as if they were distinct contexts.
+				 *
+				 * A context holding a sigtrap event must also
+				 * take the slow path, even when nothing is
+				 * pending, since the sigtrap delivery relies on
+				 * the ctx->task relation as well.
 				 */
 				raw_spin_unlock(&next_ctx->lock);
 				rcu_read_unlock();
Signature · 1 line
2.34.1
#2 lore raw

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

In reply to Tengda Wu
Sashiko has reviewed this patch and found no issues.
Quoted 15 lines

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>
Quoted 6 lines

[ ... ]
the exclude_kernel warning path to ensure the read is properly ordered.

Fixes c5d93d23a260 ("perf: Enqueue SIGTRAP always via task_work.")

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
#20 lore raw

Re: [PATCH v5 2/2] perf/core: Disable context fast-swap for sigtrap events

In reply to Tengda Wu
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] perf/core: non-SMP-atomic local_t race on ctx->nr_no_switch_fast --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] perf/core: non-SMP-atomic local_t race on ctx->nr_no_switch_fast
--

commit 5e829db733e2fe49cdac7cb99bb9428db1c83359
Author: Tengda Wu <[email protected]>

perf/core: Disable context fast-swap for sigtrap events

This commit excludes sigtrap events from the context fast-swap path by incrementing and decrementing ctx->nr_no_switch_fast when adding and removing events with attr.sigtrap set.

Quoted 14 lines
kernel/events/core.c +1 -1
index da86bc6e8be94..483ba8704d418 100644
@@ -1999,7 +1999,7 @@ list_add_event(struct perf_event *event, struct perf_event_context *ctx)
 		ctx->nr_user++;
 	if (event->attr.inherit_stat)
 		ctx->nr_stat++;
-	if (has_inherit_and_sample_read(&event->attr))
+	if (has_inherit_and_sample_read(&event->attr) || event->attr.sigtrap)
 		local_inc(&ctx->nr_no_switch_fast);
 
 	if (event->state > PERF_EVENT_STATE_OFF)

kernel/events/core.c list_del_event(struct perf_event *event, struct perf_event_context *ctx) · line 2229

Quoted 6 lines
kernel/events/core.c +1 -1
@@ -2225,7 +2225,7 @@ list_del_event(struct perf_event *event, struct perf_event_context *ctx)
 		ctx->nr_user--;
 	if (event->attr.inherit_stat)
 		ctx->nr_stat--;
-	if (has_inherit_and_sample_read(&event->attr))
+	if (has_inherit_and_sample_read(&event->attr) || event->attr.sigtrap)
 		local_dec(&ctx->nr_no_switch_fast);

[Severity: Medium]
Can concurrent local_inc() and local_dec() calls on ctx->nr_no_switch_fast from different CPUs race and lose updates?

ctx->nr_no_switch_fast is a local_t, so local_inc() and local_dec() are only atomic on a single CPU (for example, unlocked inc/dec on x86). When installing a disabled sigtrap event into a non-empty task context, perf_install_in_context() runs add_event_to_ctx() directly on the installer CPU under ctx->lock without an IPI, while an already-active sigtrap event in that context can update ctx->nr_no_switch_fast on the target task's CPU without holding ctx->lock:

CPU0 CPU1 (running ctx->task)
perf_install_in_context()
raw_spin_lock(&ctx->lock)
add_event_to_ctx()

    list_add_event()
      local_inc(&ctx->nr_no_switch_fast)
                                  __perf_event_overflow()
                                    local_inc(&ctx->nr_no_switch_fast)
                                      <-- non-SMP-atomic RMW race
                                  ...
                                  perf_pending_task()
                                    local_dec(&ctx->nr_no_switch_fast)

A similar cross-CPU race is possible between list_del_event() in perf_remove_from_context() (when !ctx->is_active) and perf_pending_task(). A lost increment allows ctx->nr_no_switch_fast to drop to 0 while a sigtrap event or pending task_work is still present, re-enabling the context fast-swap path and hitting WARN_ON_ONCE(event->ctx->task != current) in perf_sigtrap().

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
author
#21 lore raw

Re: [PATCH v5 2/2] perf/core: Disable context fast-swap for sigtrap events

Quoted 61 lines · On 2026/11/19 18:03, [email protected] wrote:

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] perf/core: non-SMP-atomic local_t race on ctx->nr_no_switch_fast
--

commit 5e829db733e2fe49cdac7cb99bb9428db1c83359
Author: Tengda Wu <[email protected]>

perf/core: Disable context fast-swap for sigtrap events

This commit excludes sigtrap events from the context fast-swap path by incrementing and decrementing ctx->nr_no_switch_fast when adding and removing events with attr.sigtrap set.

Quoted 14 lines
kernel/events/core.c +1 -1
index da86bc6e8be94..483ba8704d418 100644
@@ -1999,7 +1999,7 @@ list_add_event(struct perf_event *event, struct perf_event_context *ctx)
 		ctx->nr_user++;
 	if (event->attr.inherit_stat)
 		ctx->nr_stat++;
-	if (has_inherit_and_sample_read(&event->attr))
+	if (has_inherit_and_sample_read(&event->attr) || event->attr.sigtrap)
 		local_inc(&ctx->nr_no_switch_fast);
 
 	if (event->state > PERF_EVENT_STATE_OFF)

kernel/events/core.c list_del_event(struct perf_event *event, struct perf_event_context *ctx) · line 2229

Quoted 6 lines
kernel/events/core.c +1 -1
@@ -2225,7 +2225,7 @@ list_del_event(struct perf_event *event, struct perf_event_context *ctx)
 		ctx->nr_user--;
 	if (event->attr.inherit_stat)
 		ctx->nr_stat--;
-	if (has_inherit_and_sample_read(&event->attr))
+	if (has_inherit_and_sample_read(&event->attr) || event->attr.sigtrap)
 		local_dec(&ctx->nr_no_switch_fast);

[Severity: Medium]
Can concurrent local_inc() and local_dec() calls on ctx->nr_no_switch_fast from different CPUs race and lose updates?

ctx->nr_no_switch_fast is a local_t, so local_inc() and local_dec() are only atomic on a single CPU (for example, unlocked inc/dec on x86). When installing a disabled sigtrap event into a non-empty task context, perf_install_in_context() runs add_event_to_ctx() directly on the installer CPU under ctx->lock without an IPI, while an already-active sigtrap event in that context can update ctx->nr_no_switch_fast on the target task's CPU without holding ctx->lock:

CPU0 CPU1 (running ctx->task)
perf_install_in_context()
raw_spin_lock(&ctx->lock)
add_event_to_ctx()

    list_add_event()
      local_inc(&ctx->nr_no_switch_fast)
                                  __perf_event_overflow()
                                    local_inc(&ctx->nr_no_switch_fast)
                                      <-- non-SMP-atomic RMW race
                                  ...
                                  perf_pending_task()
                                    local_dec(&ctx->nr_no_switch_fast)
Quoted 7 lines

A similar cross-CPU race is possible between list_del_event() in perf_remove_from_context() (when !ctx->is_active) and perf_pending_task(). A lost increment allows ctx->nr_no_switch_fast to drop to 0 while a sigtrap event or pending task_work is still present, re-enabling the context fast-swap path and hitting WARN_ON_ONCE(event->ctx->task != current) in perf_sigtrap().

Same as this:

https://lore.kernel.org/all/[email protected]/

It is a pre-existing issue, so a separate patch will be submitted and it will not be fixed within this patch series.

Thanks,
Tengda

Reviewed-by on v5 1/2
#3 lore raw

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

In reply to Tengda Wu
Quoted 18 lines · Tengda Wu

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()
Quoted 7 lines

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.

Quoted 7 lines

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".

Quoted 11 lines

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.")

Sebastian

Reviewed-by on v5 2/2
#22 lore raw

Re: [PATCH v5 2/2] perf/core: Disable context fast-swap for sigtrap events

In reply to Tengda Wu
Quoted 30 lines · Tengda Wu

perf_sigtrap() contains:

	WARN_ON_ONCE(event->ctx->task != current)

The warning assumes that an event's ctx->task always matches the task that ends up running the pending task_work. That assumption can be broken by the context fast-swap path.

The failure sequence is:

1. A -> B switch, perf_event_context_sched_out() takes the fast path and does WRITE_ONCE(ctx->task, next) / WRITE_ONCE(next_ctx->task, task). An NMI then hits while the context is swapped, and __perf_event_overflow() queues pending task_work on the *current* task (A), even though the event now belongs to B's swapped-in context view.

2. B -> A switch. Because A now has pending task_work, nr_no_switch_fast is non-zero, so the slow path is taken and ctx->task is *not* swapped back.

3. A returns to user mode, task_work runs perf_pending_task() -> perf_sigtrap(), and event->ctx->task no longer equals current, tripping the WARN_ON_ONCE().

The context fast-swap path was already excluded for events that need stable task association (inherit + sample read). sigtrap events have the same requirement: the SIGTRAP is targeted at ctx->task and must not be delivered after ctx->task has been swapped to another task.

Quoted 7 lines

Fix this by also excluding events with attr->sigtrap from the fast-swap path, i.e. bump nr_no_switch_fast for sigtrap events in list_add_event()/list_del_event(), and update the comment describing the invariant accordingly.

Fixes c5d93d23a260 ("perf: Enqueue SIGTRAP always via task_work.")

This makes sense. How did you run into this? Is it possible to make a testcase out of it?

Sebastian

author
#23 lore raw

Re: [PATCH v5 2/2] perf/core: Disable context fast-swap for sigtrap events

Quoted 39 lines · Sebastian Andrzej Siewior
Quoted 30 lines · Tengda Wu

perf_sigtrap() contains:

	WARN_ON_ONCE(event->ctx->task != current)

The warning assumes that an event's ctx->task always matches the task that ends up running the pending task_work. That assumption can be broken by the context fast-swap path.

The failure sequence is:

1. A -> B switch, perf_event_context_sched_out() takes the fast path and does WRITE_ONCE(ctx->task, next) / WRITE_ONCE(next_ctx->task, task). An NMI then hits while the context is swapped, and __perf_event_overflow() queues pending task_work on the *current* task (A), even though the event now belongs to B's swapped-in context view.

2. B -> A switch. Because A now has pending task_work, nr_no_switch_fast is non-zero, so the slow path is taken and ctx->task is *not* swapped back.

3. A returns to user mode, task_work runs perf_pending_task() -> perf_sigtrap(), and event->ctx->task no longer equals current, tripping the WARN_ON_ONCE().

The context fast-swap path was already excluded for events that need stable task association (inherit + sample read). sigtrap events have the same requirement: the SIGTRAP is targeted at ctx->task and must not be delivered after ctx->task has been swapped to another task.

Quoted 7 lines

Fix this by also excluding events with attr->sigtrap from the fast-swap path, i.e. bump nr_no_switch_fast for sigtrap events in list_add_event()/list_del_event(), and update the comment describing the invariant accordingly.

Fixes c5d93d23a260 ("perf: Enqueue SIGTRAP always via task_work.")
Quoted 6 lines

This makes sense. How did you run into this? Is it possible to make a testcase out of it?

Sebastian

There is a test case, see this:
https://lore.kernel.org/all/[email protected]/

Thanks,
Tengda

author
#25 lore raw

Re: [PATCH v5 2/2] perf/core: Disable context fast-swap for sigtrap events

Quoted 9 lines · Sebastian Andrzej Siewior
Quoted 2 lines · Tengda Wu

There is a test case, see this:
https://lore.kernel.org/all/[email protected]/

Now I remember. Would it make sense to include it to
tools/testing/selftests/perf_events/sigtrap_threads.c

?

Well, because the trigger window is very short, it is not easy to reproduce. The test case I provided above must be stress-tested through multiple rounds of a while loop. Is it inappropriate to put this kind of test, which requires a while loop and has a certain degree of randomness, into deterministic test cases like sigtrap_threads.c?

Thanks,
Tengda

#26 lore raw

Re: [PATCH v5 2/2] perf/core: Disable context fast-swap for sigtrap events

Quoted 5 lines · Tengda Wu

Well, because the trigger window is very short, it is not easy to reproduce. The test case I provided above must be stress-tested through multiple rounds of a while loop. Is it inappropriate to put this kind of test, which requires a while loop and has a certain degree of randomness, into deterministic test cases like sigtrap_threads.c?

Then maybe not. I would have to run it myself to be able to judge it. However this thread has a reference to the test case should someone need it in a few years…

Quoted 2 lines

Thanks,
Tengda

Sebastian

author
#27 lore raw

Re: [PATCH v5 2/2] perf/core: Disable context fast-swap for sigtrap events

Quoted 7 lines · Sebastian Andrzej Siewior
Quoted 5 lines · Tengda Wu

Well, because the trigger window is very short, it is not easy to reproduce. The test case I provided above must be stress-tested through multiple rounds of a while loop. Is it inappropriate to put this kind of test, which requires a while loop and has a certain degree of randomness, into deterministic test cases like sigtrap_threads.c?

Quoted 8 lines

Then maybe not. I would have to run it myself to be able to judge it. However this thread has a reference to the test case should someone need it in a few years…

Quoted 2 lines

Thanks,
Tengda

Sebastian

Yeah, thanks for the clarification. I'll leave it as-is then.

Best regards,
Tengda

maintainer
#4 lore raw

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

In reply to Tengda Wu
Quoted 34 lines · Tengda Wu

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.

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.

Quoted 8 lines

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.

I am confused by the use of smp_*() and cmpxchg() here. Where is the multi-cpu scenario?

#5 lore raw

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

Quoted 6 lines · Peter Zijlstra
Quoted 3 lines

Also use smp_load_acquire() when checking pending_work in the exclude_kernel warning path to ensure the read is properly ordered.

I am confused by the use of smp_*() and cmpxchg() here. Where is the multi-cpu scenario?

The same event is used in process context and NMI

|        perf-tc1-7647    [001] d..6.   114.513688: __perf_event_overflow: ffff888100d68540
|        perf-tc1-7647    [001] d.Z2.   114.513703: __perf_event_overflow: ffff888100d68540

I don't see how to deal with this without cmpxchg. And the same event is also used by other task

| perf-tc1-7657 [001] d.Z2. 114.598356: __perf_event_overflow: ffff888100d68540

which makes me thing that it could be pinned to another CPU (unless there is something that impossible and it is strictly per-CPU).

The smp load/store macros is my fault as it looked better to do this than plain stores (given that we have the cmpxchg already).

Sebastian

maintainer
#6 lore raw

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

Quoted 8 lines · Sebastian Andrzej Siewior
Quoted 6 lines · Peter Zijlstra
Quoted 3 lines

Also use smp_load_acquire() when checking pending_work in the exclude_kernel warning path to ensure the read is properly ordered.

I am confused by the use of smp_*() and cmpxchg() here. Where is the multi-cpu scenario?

Quoted 6 lines

The same event is used in process context and NMI

|        perf-tc1-7647    [001] d..6.   114.513688: __perf_event_overflow: ffff888100d68540
|        perf-tc1-7647    [001] d.Z2.   114.513703: __perf_event_overflow: ffff888100d68540

I don't see how to deal with this without cmpxchg. And the same event is also used by other task

You can do CMPXCHG (without the LOCK) prefix; the helper is called cmpxchg_local().

Quoted 7 lines

| perf-tc1-7657 [001] d.Z2. 114.598356: __perf_event_overflow: ffff888100d68540

which makes me thing that it could be pinned to another CPU (unless there is something that impossible and it is strictly per-CPU).

The smp load/store macros is my fault as it looked better to do this than plain stores (given that we have the cmpxchg already).

It is confusing as all heck. This is all task-local, and a task can only ever run on one CPU at the time.

#7 lore raw

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

Quoted 21 lines · Peter Zijlstra
Quoted 8 lines · Sebastian Andrzej Siewior
Quoted 6 lines · Peter Zijlstra
Quoted 3 lines

Also use smp_load_acquire() when checking pending_work in the exclude_kernel warning path to ensure the read is properly ordered.

I am confused by the use of smp_*() and cmpxchg() here. Where is the multi-cpu scenario?

Quoted 6 lines

The same event is used in process context and NMI

|        perf-tc1-7647    [001] d..6.   114.513688: __perf_event_overflow: ffff888100d68540
|        perf-tc1-7647    [001] d.Z2.   114.513703: __perf_event_overflow: ffff888100d68540

I don't see how to deal with this without cmpxchg. And the same event is also used by other task

You can do CMPXCHG (without the LOCK) prefix; the helper is called cmpxchg_local().

Quoted 2 lines

| perf-tc1-7657 [001] d.Z2. 114.598356: __perf_event_overflow: ffff888100d68540

Quoted 8 lines
Quoted 5 lines

which makes me thing that it could be pinned to another CPU (unless there is something that impossible and it is strictly per-CPU).

The smp load/store macros is my fault as it looked better to do this than plain stores (given that we have the cmpxchg already).

It is confusing as all heck. This is all task-local, and a task can only ever run on one CPU at the time.

Given the two pids I was assuming (!knowing) that two CPUs could be involved.

So you are saying cmpxchg_local() and a plain assign/WRITE_ONCE rather than the smp.* given that this is all task local.

Sebastian

maintainer
#8 lore raw

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

Quoted 28 lines · Sebastian Andrzej Siewior
Quoted 27 lines · Peter Zijlstra
Quoted 8 lines · Sebastian Andrzej Siewior
Quoted 6 lines · Peter Zijlstra
Quoted 3 lines

Also use smp_load_acquire() when checking pending_work in the exclude_kernel warning path to ensure the read is properly ordered.

I am confused by the use of smp_*() and cmpxchg() here. Where is the multi-cpu scenario?

Quoted 6 lines

The same event is used in process context and NMI

|        perf-tc1-7647    [001] d..6.   114.513688: __perf_event_overflow: ffff888100d68540
|        perf-tc1-7647    [001] d.Z2.   114.513703: __perf_event_overflow: ffff888100d68540

I don't see how to deal with this without cmpxchg. And the same event is also used by other task

You can do CMPXCHG (without the LOCK) prefix; the helper is called cmpxchg_local().

Quoted 7 lines

| perf-tc1-7657 [001] d.Z2. 114.598356: __perf_event_overflow: ffff888100d68540

which makes me thing that it could be pinned to another CPU (unless there is something that impossible and it is strictly per-CPU).

The smp load/store macros is my fault as it looked better to do this than plain stores (given that we have the cmpxchg already).

Quoted 8 lines
Quoted 2 lines

It is confusing as all heck. This is all task-local, and a task can only ever run on one CPU at the time.

Given the two pids I was assuming (!knowing) that two CPUs could be involved.

So you are saying cmpxchg_local() and a plain assign/WRITE_ONCE rather than the smp.* given that this is all task local.

Well, from what I can remember, only task bound self-monitoring events can signal, and the whole task_work is per necessity task local. Which makes it all local.

It is indeed {READ,WRITE}_ONCE() combined with barrier() if you really need to beat the compiler into submission.

But let me go try and read this Changelog in more detail.

maintainer
#9 lore raw

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

In reply to Tengda Wu
Quoted 9 lines · Tengda Wu

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.

Quoted 8 lines

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()

How? If an event is NMI driven, it will only ever cause an overflow from NMI context.

If it is not, then the same event will not trigger from NMI.

Some key ingredient is missing here. Is this some software event that is missing recursion checks?

maintainer
#11 lore raw

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

Quoted 6 lines · Sebastian Andrzej Siewior
Quoted 2 lines · Peter Zijlstra

Some key ingredient is missing here. Is this some software event that is missing recursion checks?

If you navigate to

	https://lore.kernel.org/all/[email protected]/

and /PoC then you find what I used for testing.

Right, it had to be a tracepoint :/ Let me go puzzle.

maintainer
#12 lore raw

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

Quoted 9 lines · Peter Zijlstra
Quoted 6 lines · Sebastian Andrzej Siewior
Quoted 2 lines · Peter Zijlstra

Some key ingredient is missing here. Is this some software event that is missing recursion checks?

If you navigate to

	https://lore.kernel.org/all/[email protected]/

and /PoC then you find what I used for testing.

Right, it had to be a tracepoint :/ Let me go puzzle.

Argh, yes. The recursion is per context {task,bh,irq,nmi} which isn't sufficient for this case.

Also, sending signals on software events seems utterly insane. But I don't support we can go limit that now :-(

maintainer
#28 lore raw

Re: [PATCH v5 2/2] perf/core: Disable context fast-swap for sigtrap events

In reply to Tengda Wu
Quoted 30 lines · Tengda Wu

perf_sigtrap() contains:

	WARN_ON_ONCE(event->ctx->task != current)

The warning assumes that an event's ctx->task always matches the task that ends up running the pending task_work. That assumption can be broken by the context fast-swap path.

The failure sequence is:

1. A -> B switch, perf_event_context_sched_out() takes the fast path and does WRITE_ONCE(ctx->task, next) / WRITE_ONCE(next_ctx->task, task). An NMI then hits while the context is swapped, and __perf_event_overflow() queues pending task_work on the *current* task (A), even though the event now belongs to B's swapped-in context view.

2. B -> A switch. Because A now has pending task_work, nr_no_switch_fast is non-zero, so the slow path is taken and ctx->task is *not* swapped back.

3. A returns to user mode, task_work runs perf_pending_task() -> perf_sigtrap(), and event->ctx->task no longer equals current, tripping the WARN_ON_ONCE().

The context fast-swap path was already excluded for events that need stable task association (inherit + sample read). sigtrap events have the same requirement: the SIGTRAP is targeted at ctx->task and must not be delivered after ctx->task has been swapped to another task.

Quoted 4 lines

Fix this by also excluding events with attr->sigtrap from the fast-swap path, i.e. bump nr_no_switch_fast for sigtrap events in list_add_event()/list_del_event(), and update the comment describing the invariant accordingly.

This patch cannot be right, because it leaves in place the existing sigtrap / nr_no_switch_fast bits.

Also, this is very sad; it might be better to try and fix up the special case where the NMI hits the middle of context switch.

#29 lore raw

Re: [PATCH v5 2/2] perf/core: Disable context fast-swap for sigtrap events

Quoted 2 lines · Peter Zijlstra

This patch cannot be right, because it leaves in place the existing sigtrap / nr_no_switch_fast bits.

I said the same thing and then sashiko came with

	https://lore.kernel.org/all/[email protected]/
| [Severity: Medium]
| Can ctx->nr_no_switch_fast drop to zero while event->pending_task is still
| queued if the sigtrap event is detached before perf_pending_task() runs?
| 
| Detaching an event does not cancel or flush event->pending_task; instead,
| pending_task holds a reference to the event until the task returns to user
| space.  When a parent event with attr.inherit and attr.sigtrap is closed while
| a child event has pending_task queued, perf_event_release_kernel() detaches the
| child events from their cloned contexts without uncloning them:
| 
| CPU0 (task A)                     CPU1
| __perf_event_overflow(child_A)
|   task_work_add(A, &child_A->pending_task)
|                                   perf_event_release_kernel(parent)
|                                     perf_remove_from_context(child_A, ...)
|                                       list_del_event(child_A, ctx_A)
|                                         local_dec(&ctx_A->nr_no_switch_fast)
|                                     perf_remove_from_context(child_B, ...)
|                                       list_del_event(child_B, ctx_B)
|                                         local_dec(&ctx_B->nr_no_switch_fast)
| schedule() (A -> B)
|   perf_event_context_sched_out(A, B)
|     /* context_equiv(ctx_A, ctx_B) && nr_no_switch_fast == 0 */
|     WRITE_ONCE(ctx_A->task, B)
| ...
| perf_pending_task(&child_A->pending_task)
|   perf_sigtrap(child_A)
|     WARN_ON_ONCE(event->ctx->task != current)  <-- trips WARN, drops SIGTRAP
| 
| Keeping the increment in __perf_event_overflow() and decrement in
| perf_pending_task() alongside list_add_event() and list_del_event() would keep
| nr_no_switch_fast elevated until pending_task completes.  Note that because
| list_add_event() and list_del_event() can run on a remote CPU under ctx->lock
| while __perf_event_overflow() or perf_pending_task() runs on ctx->task's CPU
| without ctx->lock, nr_no_switch_fast would also need to be atomic_t rather than
| CPU-local local_t.

Sebastian

#13 lore raw

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

In reply to Peter Zijlstra
Quoted 2 lines · Peter Zijlstra

Also, sending signals on software events seems utterly insane. But I don't support we can go limit that now :-(

Tengda: Is this an actual valid use case that you have here or did an AI figured out that this broken?

Sebastian

maintainer
#30 lore raw

Re: [PATCH v5 2/2] perf/core: Disable context fast-swap for sigtrap events

In reply to Tengda Wu
Quoted 21 lines · Tengda Wu

perf_sigtrap() contains:

	WARN_ON_ONCE(event->ctx->task != current)

The warning assumes that an event's ctx->task always matches the task that ends up running the pending task_work. That assumption can be broken by the context fast-swap path.

The failure sequence is:

1. A -> B switch, perf_event_context_sched_out() takes the fast path and does WRITE_ONCE(ctx->task, next) / WRITE_ONCE(next_ctx->task, task). An NMI then hits while the context is swapped, and __perf_event_overflow() queues pending task_work on the *current* task (A), even though the event now belongs to B's swapped-in context view.

2. B -> A switch. Because A now has pending task_work, nr_no_switch_fast is non-zero, so the slow path is taken and ctx->task is *not* swapped back.

Quoted 8 lines

3. A returns to user mode, task_work runs perf_pending_task() -> perf_sigtrap(), and event->ctx->task no longer equals current, tripping the WARN_ON_ONCE().

The context fast-swap path was already excluded for events that need stable task association (inherit + sample read). sigtrap events have the same requirement: the SIGTRAP is targeted at ctx->task and must not be delivered after ctx->task has been swapped to another task.

Oh gawd, let me guess, another one of those tracepoint events, right?

Must be someone that doesn't respect perf_ctx_disable(). Fixing that will close this hole.

maintainer
#31 lore raw

Re: [PATCH v5 2/2] perf/core: Disable context fast-swap for sigtrap events

Quoted 31 lines · Peter Zijlstra
Quoted 21 lines · Tengda Wu

perf_sigtrap() contains:

	WARN_ON_ONCE(event->ctx->task != current)

The warning assumes that an event's ctx->task always matches the task that ends up running the pending task_work. That assumption can be broken by the context fast-swap path.

The failure sequence is:

1. A -> B switch, perf_event_context_sched_out() takes the fast path and does WRITE_ONCE(ctx->task, next) / WRITE_ONCE(next_ctx->task, task). An NMI then hits while the context is swapped, and __perf_event_overflow() queues pending task_work on the *current* task (A), even though the event now belongs to B's swapped-in context view.

2. B -> A switch. Because A now has pending task_work, nr_no_switch_fast is non-zero, so the slow path is taken and ctx->task is *not* swapped back.

Quoted 8 lines

3. A returns to user mode, task_work runs perf_pending_task() -> perf_sigtrap(), and event->ctx->task no longer equals current, tripping the WARN_ON_ONCE().

The context fast-swap path was already excluded for events that need stable task association (inherit + sample read). sigtrap events have the same requirement: the SIGTRAP is targeted at ctx->task and must not be delivered after ctx->task has been swapped to another task.

Quoted 4 lines

Oh gawd, let me guess, another one of those tracepoint events, right?

Must be someone that doesn't respect perf_ctx_disable(). Fixing that will close this hole.

Here, does this work?

The clue is right in perf_event_context_sched_out():

                          perf_ctx_disable(ctx, 0);

                          /* PMIs are disabled; ctx->nr_no_switch_fast is stable. */
                          if (local_read(&ctx->nr_no_switch_fast) ||
                              local_read(&next_ctx->nr_no_switch_fast)) {

There must be no overflow after perf_ctx_disable().

include/linux/perf_event.h +1 -0
@@ -1236,6 +1236,7 @@ extern const struct perf_event_attr *per
 extern void perf_event_print_debug(void);
 extern void perf_pmu_disable(struct pmu *pmu);
 extern void perf_pmu_enable(struct pmu *pmu);
+extern bool perf_pmu_enabled(struct pmu *pmu);
 extern void perf_sched_cb_dec(struct pmu *pmu);
 extern void perf_sched_cb_inc(struct pmu *pmu);
 extern int perf_event_task_disable(void);
kernel/events/core.c +12 -0
@@ -1366,6 +1366,12 @@ void perf_pmu_enable(struct pmu *pmu)
 		pmu->pmu_enable(pmu);
 }
 
+bool perf_pmu_enabled(struct pmu *pmu)
+{
+	int *count = &this_cpc(pmu)->pmu_disable_count;
+	return *count == 0;
+}
+
 static void perf_assert_pmu_disabled(struct pmu *pmu)
 {
 	int *count = &this_cpc(pmu)->pmu_disable_count;
@@ -11151,6 +11157,9 @@ static int perf_swevent_match(struct per
 				struct perf_sample_data *data,
 				struct pt_regs *regs)
 {
+	if (!perf_pmu_enabled(event->pmu))
+		return 0;
+
 	if (event->attr.type != type)
 		return 0;
 
@@ -11531,6 +11540,9 @@ static int perf_tp_event_match(struct pe
 				struct perf_raw_record *raw,
 				struct pt_regs *regs)
 {
+	if (!perf_pmu_enabled(event->pmu))
+		return 0;
+
 	if (event->hw.state & PERF_HES_STOPPED)
 		return 0;
 	/*
maintainer
#14 lore raw

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

In reply to Sebastian Andrzej Siewior
Quoted 6 lines · Sebastian Andrzej Siewior
Quoted 2 lines · Peter Zijlstra

Also, sending signals on software events seems utterly insane. But I don't support we can go limit that now :-(

Tengda: Is this an actual valid use case that you have here or did an AI figured out that this broken?

I *think* the below is sufficient.

- sigtrap implies a per-task event; task_work is local to the current task (+- the context switch thing from 2/2).

- task_work_run() is written such that the work handler can do task_work_add(), therefore the early clear in the handler doesn't matter.

And while recursive software events are tedious, I think the below fix is simple enough to not worry about too much.

---
Subject: perf/core: Prevent duplicate sigtrap task work enqueue
From: Tengda Wu <[email protected]>
Date: Thu, 19 Nov 2026 09:51:00 +0000

From: Tengda Wu <[email protected]>

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.")
---
 kernel/events/core.c |   24 +++++++++++++++---------
 1 file changed, 15 insertions(+), 9 deletions(-)
kernel/events/core.c +15 -9
@@ -10950,16 +10950,22 @@ static int __perf_event_overflow(struct
 
 		notify_mode = in_nmi() ? TWA_NMI_CURRENT : TWA_RESUME;
 
-		if (!event->pending_work &&
-		    !task_work_add(current, &event->pending_task, notify_mode)) {
-			event->pending_work = pending_id;
-			local_inc(&event->ctx->nr_no_switch_fast);
-			WARN_ON_ONCE(!atomic_long_inc_not_zero(&event->refcount));
-
-			event->pending_addr = 0;
-			if (valid_sample && (data->sample_flags & PERF_SAMPLE_ADDR))
-				event->pending_addr = data->addr;
+		/*
+		 * Software events can nest and attempt this recursively;
+		 * claim the pending_work before task_work_add() recurses.
+		 */
+		if (cmpxchg_local(&event->pending_work, 0, 1) == 0) {
+			if (!task_work_add(current, &event->pending_task, notify_mode)) {
+				event->pending_work = pending_id;
+				local_inc(&event->ctx->nr_no_switch_fast);
+				WARN_ON_ONCE(!atomic_long_inc_not_zero(&event->refcount));
 
+				event->pending_addr = 0;
+				if (valid_sample && (data->sample_flags & PERF_SAMPLE_ADDR))
+					event->pending_addr = data->addr;
+			} else {
+				event->pending_work = 0;
+			}
 		} else if (event->attr.exclude_kernel && valid_sample) {
 			/*
 			 * Should not be able to return to user space without
author
#17 lore raw

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

In reply to Sebastian Andrzej Siewior
Quoted 8 lines · Sebastian Andrzej Siewior
Quoted 2 lines · Peter Zijlstra

Also, sending signals on software events seems utterly insane. But I don't support we can go limit that now :-(

Tengda: Is this an actual valid use case that you have here or did an AI figured out that this broken?

Sebastian

Sorry for the late reply. No AI involved, this was produced by running syzkaller. I've turned it into C code.

Tengda

author
#15 lore raw

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

In reply to Peter Zijlstra
Quoted 92 lines · Peter Zijlstra
Quoted 6 lines · Sebastian Andrzej Siewior
Quoted 2 lines · Peter Zijlstra

Also, sending signals on software events seems utterly insane. But I don't support we can go limit that now :-(

Tengda: Is this an actual valid use case that you have here or did an AI figured out that this broken?

I *think* the below is sufficient.

- sigtrap implies a per-task event; task_work is local to the current task (+- the context switch thing from 2/2).

- task_work_run() is written such that the work handler can do task_work_add(), therefore the early clear in the handler doesn't matter.

And while recursive software events are tedious, I think the below fix is simple enough to not worry about too much.

---
Subject: perf/core: Prevent duplicate sigtrap task work enqueue
From: Tengda Wu <[email protected]>
Date: Thu, 19 Nov 2026 09:51:00 +0000

From: Tengda Wu <[email protected]>

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.")
---
 kernel/events/core.c |   24 +++++++++++++++---------
 1 file changed, 15 insertions(+), 9 deletions(-)
kernel/events/core.c +9 -9
@@ -10950,16 +10950,22 @@ static int __perf_event_overflow(struct
 
 		notify_mode = in_nmi() ? TWA_NMI_CURRENT : TWA_RESUME;
 
-		if (!event->pending_work &&
-		    !task_work_add(current, &event->pending_task, notify_mode)) {
-			event->pending_work = pending_id;
-			local_inc(&event->ctx->nr_no_switch_fast);
-			WARN_ON_ONCE(!atomic_long_inc_not_zero(&event->refcount));
-
-			event->pending_addr = 0;
-			if (valid_sample && (data->sample_flags & PERF_SAMPLE_ADDR))
-				event->pending_addr = data->addr;
+		/*
+		 * Software events can nest and attempt this recursively;
+		 * claim the pending_work before task_work_add() recurses.
+		 */
+		if (cmpxchg_local(&event->pending_work, 0, 1) == 0) {
+			if (!task_work_add(current, &event->pending_task, notify_mode)) {
+				event->pending_work = pending_id;
+				local_inc(&event->ctx->nr_no_switch_fast);
+				WARN_ON_ONCE(!atomic_long_inc_not_zero(&event->refcount));

kernel/events/core.c static int __perf_event_overflow(struct · line 10971

Quoted 10 lines
kernel/events/core.c +6 -0
 
+				event->pending_addr = 0;
+				if (valid_sample && (data->sample_flags & PERF_SAMPLE_ADDR))
+					event->pending_addr = data->addr;
+			} else {
+				event->pending_work = 0;
+			}
 		} else if (event->attr.exclude_kernel && valid_sample) {
 			/*
 			 * Should not be able to return to user space without

Hmm, this is basically similar to my original version, and I re-tested with this and it's fine. LGTM.

Thanks,
Tengda

author
#32 lore raw

Re: [PATCH v5 2/2] perf/core: Disable context fast-swap for sigtrap events

In reply to Peter Zijlstra
Quoted 86 lines · Peter Zijlstra
Quoted 31 lines · Peter Zijlstra
Quoted 21 lines · Tengda Wu

perf_sigtrap() contains:

	WARN_ON_ONCE(event->ctx->task != current)

The warning assumes that an event's ctx->task always matches the task that ends up running the pending task_work. That assumption can be broken by the context fast-swap path.

The failure sequence is:

1. A -> B switch, perf_event_context_sched_out() takes the fast path and does WRITE_ONCE(ctx->task, next) / WRITE_ONCE(next_ctx->task, task). An NMI then hits while the context is swapped, and __perf_event_overflow() queues pending task_work on the *current* task (A), even though the event now belongs to B's swapped-in context view.

2. B -> A switch. Because A now has pending task_work, nr_no_switch_fast is non-zero, so the slow path is taken and ctx->task is *not* swapped back.

Quoted 8 lines

3. A returns to user mode, task_work runs perf_pending_task() -> perf_sigtrap(), and event->ctx->task no longer equals current, tripping the WARN_ON_ONCE().

The context fast-swap path was already excluded for events that need stable task association (inherit + sample read). sigtrap events have the same requirement: the SIGTRAP is targeted at ctx->task and must not be delivered after ctx->task has been swapped to another task.

Quoted 4 lines

Oh gawd, let me guess, another one of those tracepoint events, right?

Must be someone that doesn't respect perf_ctx_disable(). Fixing that will close this hole.

Here, does this work?

The clue is right in perf_event_context_sched_out():

                          perf_ctx_disable(ctx, 0);

                          /* PMIs are disabled; ctx->nr_no_switch_fast is stable. */
                          if (local_read(&ctx->nr_no_switch_fast) ||
                              local_read(&next_ctx->nr_no_switch_fast)) {

There must be no overflow after perf_ctx_disable().

include/linux/perf_event.h +1 -0
@@ -1236,6 +1236,7 @@ extern const struct perf_event_attr *per
 extern void perf_event_print_debug(void);
 extern void perf_pmu_disable(struct pmu *pmu);
 extern void perf_pmu_enable(struct pmu *pmu);
+extern bool perf_pmu_enabled(struct pmu *pmu);
 extern void perf_sched_cb_dec(struct pmu *pmu);
 extern void perf_sched_cb_inc(struct pmu *pmu);
 extern int perf_event_task_disable(void);
kernel/events/core.c +9 -0
@@ -1366,6 +1366,12 @@ void perf_pmu_enable(struct pmu *pmu)
 		pmu->pmu_enable(pmu);
 }
 
+bool perf_pmu_enabled(struct pmu *pmu)
+{
+	int *count = &this_cpc(pmu)->pmu_disable_count;
+	return *count == 0;
+}
+
 static void perf_assert_pmu_disabled(struct pmu *pmu)
 {
 	int *count = &this_cpc(pmu)->pmu_disable_count;
@@ -11151,6 +11157,9 @@ static int perf_swevent_match(struct per
 				struct perf_sample_data *data,
 				struct pt_regs *regs)
 {
+	if (!perf_pmu_enabled(event->pmu))
+		return 0;
+
 	if (event->attr.type != type)
 		return 0;
 

kernel/events/core.c static int perf_tp_event_match(struct pe · line 11548

Quoted 9 lines
kernel/events/core.c +3 -0
@@ -11531,6 +11540,9 @@ static int perf_tp_event_match(struct pe
 				struct perf_raw_record *raw,
 				struct pt_regs *regs)
 {
+	if (!perf_pmu_enabled(event->pmu))
+		return 0;
+
 	if (event->hw.state & PERF_HES_STOPPED)
 		return 0;
 	/*

This patch does not fix the issue; it can still be reproduced after testing. The PoC is still the one mentioned in the cover letter:

https://lore.kernel.org/all/[email protected]/

[  191.663702] ------------[ cut here ]------------
[  191.663827] WARNING: kernel/events/core.c:7679 at perf_pending_task+0x2e4/0x370, CPU#1: fastswap/1419
[  191.667014] Modules linked in:
[  191.667731] CPU: 1 UID: 0 PID: 1419 Comm: fastswap Not tainted 7.4.0-rc2-next-20261113+ #10 PREEMPT(lazy) 
[  191.669103] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS rel-1.15.0-0-g2dd4b9b3f840-prebuilt.qemu.org 04/4
[  191.670736] RIP: 0010:perf_pending_task+0x2e4/0x370
[  191.671441] Code: 4c 8b ab c8 fe ff ff 49 ff 8d e8 00 00 00 e9 02 fe ff ff 4c 89 ef e8 6b f9 24 00 e9 b1 fd ff ff e8 c1 9
[  191.674022] RSP: 0000:ffff88810ff9fe08 EFLAGS: 00010202
[  191.674782] RAX: ffff88811844ed80 RBX: ffff888107575f98 RCX: 0000000000000000
[  191.675791] RDX: 1ffff11020eaeb95 RSI: 0000000000000004 RDI: ffff888107575ca8
[  191.676792] RBP: ffff888107575c00 R08: 0000000000000001 R09: ffffed1021ff3fbf
[  191.677800] R10: 0000000000000003 R11: ffffe8ffffc832a0 R12: 0000000000000000
[  191.678803] R13: ffff888105b19200 R14: ffff888107575e60 R15: ffff888118928000
[  191.679809] FS:  00007f39079c6600(0000) GS:ffff88826fd58000(0000) knlGS:0000000000000000
[  191.680939] CS:  0010 DS: 0000 ES: 0000 CR0: 0000000080050033
[  191.681768] CR2: 00007f3907145000 CR3: 000000010fe7a006 CR4: 0000000000170ef0
[  191.682774] Call Trace:
[  191.683139]  <TASK>
[  191.683525]  task_work_run+0x13d/0x200
[  191.684111]  ? __pfx_task_work_run+0x10/0x10
[  191.684750]  irqentry_exit+0x3a8/0x700
[  191.685291]  asm_exc_page_fault+0x26/0x30
[  191.685884] RIP: 0033:0x00000000d25df49d
[  191.686560] Code: c6 bf 2a 01 00 00 b8 00 00 00 00 e8 14 fe ff ff c9 c3 55 48 89 e5 89 7d fc 48 89 75 f0 48 89 55 e8 8b d
[  191.689089] RSP: 002b:00007ffd422628b0 EFLAGS: 00010202
[  191.689842] RAX: 000000000000002c RBX: 0000000000000001 RCX: 00007f390789cd13
[  191.690847] RDX: 00007ffd422628c0 RSI: 00007ffd422629f0 RDI: 0000000000000005
[  191.691849] RBP: 00007ffd422628b0 R08: 0000000000000000 R09: 00007ffd42262c27
[  191.692857] R10: 00007f39079c68d0 R11: 0000000000000246 R12: 00007ffd422631b8
[  191.693857] R13: 0000000000401a8a R14: 00007f39079ffaa0 R15: 0000000000403e08
[  191.694866]  </TASK>
[  191.695196] ---[ end trace 0000000000000000 ]---

Thanks,
Tengda

#18 lore raw

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

In reply to Tengda Wu
Quoted 3 lines · Tengda Wu

Sorry for the late reply. No AI involved, this was produced by running syzkaller. I've turned it into C code.

Thank you for clarifying.

Quoted 1 line

Tengda

Sebastian

#16 lore raw

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

In reply to Peter Zijlstra
Quoted 32 lines · Peter Zijlstra

From: Tengda Wu <[email protected]>

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.

Quoted 7 lines

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.")

This looks good. Shouldn't we insert also

kernel/events/core.c +1 -1
index e870f12c3ad81..edadc34f065fc 100644
@@ -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

author
#33 lore raw

Re: [PATCH v5 2/2] perf/core: Disable context fast-swap for sigtrap events

In reply to Tengda Wu
Quoted 128 lines · Tengda Wu
Quoted 86 lines · Peter Zijlstra
Quoted 31 lines · Peter Zijlstra
Quoted 21 lines · Tengda Wu

perf_sigtrap() contains:

	WARN_ON_ONCE(event->ctx->task != current)

The warning assumes that an event's ctx->task always matches the task that ends up running the pending task_work. That assumption can be broken by the context fast-swap path.

The failure sequence is:

1. A -> B switch, perf_event_context_sched_out() takes the fast path and does WRITE_ONCE(ctx->task, next) / WRITE_ONCE(next_ctx->task, task). An NMI then hits while the context is swapped, and __perf_event_overflow() queues pending task_work on the *current* task (A), even though the event now belongs to B's swapped-in context view.

2. B -> A switch. Because A now has pending task_work, nr_no_switch_fast is non-zero, so the slow path is taken and ctx->task is *not* swapped back.

Quoted 8 lines

3. A returns to user mode, task_work runs perf_pending_task() -> perf_sigtrap(), and event->ctx->task no longer equals current, tripping the WARN_ON_ONCE().

The context fast-swap path was already excluded for events that need stable task association (inherit + sample read). sigtrap events have the same requirement: the SIGTRAP is targeted at ctx->task and must not be delivered after ctx->task has been swapped to another task.

Quoted 4 lines

Oh gawd, let me guess, another one of those tracepoint events, right?

Must be someone that doesn't respect perf_ctx_disable(). Fixing that will close this hole.

Here, does this work?

The clue is right in perf_event_context_sched_out():

                          perf_ctx_disable(ctx, 0);

                          /* PMIs are disabled; ctx->nr_no_switch_fast is stable. */
                          if (local_read(&ctx->nr_no_switch_fast) ||
                              local_read(&next_ctx->nr_no_switch_fast)) {

There must be no overflow after perf_ctx_disable().

include/linux/perf_event.h +1 -0
@@ -1236,6 +1236,7 @@ extern const struct perf_event_attr *per
 extern void perf_event_print_debug(void);
 extern void perf_pmu_disable(struct pmu *pmu);
 extern void perf_pmu_enable(struct pmu *pmu);
+extern bool perf_pmu_enabled(struct pmu *pmu);
 extern void perf_sched_cb_dec(struct pmu *pmu);
 extern void perf_sched_cb_inc(struct pmu *pmu);
 extern int perf_event_task_disable(void);
kernel/events/core.c +9 -0
@@ -1366,6 +1366,12 @@ void perf_pmu_enable(struct pmu *pmu)
 		pmu->pmu_enable(pmu);
 }
 
+bool perf_pmu_enabled(struct pmu *pmu)
+{
+	int *count = &this_cpc(pmu)->pmu_disable_count;
+	return *count == 0;
+}
+
 static void perf_assert_pmu_disabled(struct pmu *pmu)
 {
 	int *count = &this_cpc(pmu)->pmu_disable_count;
@@ -11151,6 +11157,9 @@ static int perf_swevent_match(struct per
 				struct perf_sample_data *data,
 				struct pt_regs *regs)
 {
+	if (!perf_pmu_enabled(event->pmu))
+		return 0;
+
 	if (event->attr.type != type)
 		return 0;
 

kernel/events/core.c static int perf_tp_event_match(struct pe · line 11548

Quoted 9 lines
kernel/events/core.c +3 -0
@@ -11531,6 +11540,9 @@ static int perf_tp_event_match(struct pe
 				struct perf_raw_record *raw,
 				struct pt_regs *regs)
 {
+	if (!perf_pmu_enabled(event->pmu))
+		return 0;
+
 	if (event->hw.state & PERF_HES_STOPPED)
 		return 0;
 	/*

This patch does not fix the issue; it can still be reproduced after testing. The PoC is still the one mentioned in the cover letter:

https://lore.kernel.org/all/[email protected]/

[  191.663702] ------------[ cut here ]------------
[  191.663827] WARNING: kernel/events/core.c:7679 at perf_pending_task+0x2e4/0x370, CPU#1: fastswap/1419
[  191.667014] Modules linked in:
[  191.667731] CPU: 1 UID: 0 PID: 1419 Comm: fastswap Not tainted 7.4.0-rc2-next-20261113+ #10 PREEMPT(lazy) 
[  191.669103] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS rel-1.15.0-0-g2dd4b9b3f840-prebuilt.qemu.org 04/4
[  191.670736] RIP: 0010:perf_pending_task+0x2e4/0x370
[  191.671441] Code: 4c 8b ab c8 fe ff ff 49 ff 8d e8 00 00 00 e9 02 fe ff ff 4c 89 ef e8 6b f9 24 00 e9 b1 fd ff ff e8 c1 9
[  191.674022] RSP: 0000:ffff88810ff9fe08 EFLAGS: 00010202
[  191.674782] RAX: ffff88811844ed80 RBX: ffff888107575f98 RCX: 0000000000000000
[  191.675791] RDX: 1ffff11020eaeb95 RSI: 0000000000000004 RDI: ffff888107575ca8
[  191.676792] RBP: ffff888107575c00 R08: 0000000000000001 R09: ffffed1021ff3fbf
[  191.677800] R10: 0000000000000003 R11: ffffe8ffffc832a0 R12: 0000000000000000
[  191.678803] R13: ffff888105b19200 R14: ffff888107575e60 R15: ffff888118928000
[  191.679809] FS:  00007f39079c6600(0000) GS:ffff88826fd58000(0000) knlGS:0000000000000000
[  191.680939] CS:  0010 DS: 0000 ES: 0000 CR0: 0000000080050033
[  191.681768] CR2: 00007f3907145000 CR3: 000000010fe7a006 CR4: 0000000000170ef0
[  191.682774] Call Trace:
[  191.683139]  <TASK>
[  191.683525]  task_work_run+0x13d/0x200
[  191.684111]  ? __pfx_task_work_run+0x10/0x10
[  191.684750]  irqentry_exit+0x3a8/0x700
[  191.685291]  asm_exc_page_fault+0x26/0x30
[  191.685884] RIP: 0033:0x00000000d25df49d
[  191.686560] Code: c6 bf 2a 01 00 00 b8 00 00 00 00 e8 14 fe ff ff c9 c3 55 48 89 e5 89 7d fc 48 89 75 f0 48 89 55 e8 8b d
Quoted 9 lines
[  191.689089] RSP: 002b:00007ffd422628b0 EFLAGS: 00010202
[  191.689842] RAX: 000000000000002c RBX: 0000000000000001 RCX: 00007f390789cd13
[  191.690847] RDX: 00007ffd422628c0 RSI: 00007ffd422629f0 RDI: 0000000000000005
[  191.691849] RBP: 00007ffd422628b0 R08: 0000000000000000 R09: 00007ffd42262c27
[  191.692857] R10: 00007f39079c68d0 R11: 0000000000000246 R12: 00007ffd422631b8
[  191.693857] R13: 0000000000401a8a R14: 00007f39079ffaa0 R15: 0000000000403e08
[  191.694866]  </TASK>
[  191.695196] ---[ end trace 0000000000000000 ]---

The above stack is after sched_out, and the capture site was a bit late, so I added a WARN_ON_ONCE(event->ctx->task != current) below task_work_add to print the stack earlier, as shown below:

[   57.366257] ------------[ cut here ]------------
[   57.366368] WARNING: kernel/events/core.c:10965 at __perf_event_overflow+0xad6/0xc20, CPU#1: fastswap/148
[   57.368635] Modules linked in:
[   57.369116] CPU: 1 UID: 0 PID: 148 Comm: fastswap Not tainted 7.4.0-rc2-next-20261113+ #11 PREEMPT(lazy) 
[   57.370503] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS rel-1.15.0-0-g2dd4b9b3f840-prebuilt.qemu.org 04/4
[   57.372147] RIP: 0010:__perf_event_overflow+0xad6/0xc20
[   57.372921] Code: ff ff 4c 89 4c 24 10 e8 08 e0 23 00 4c 8b 4c 24 10 e9 02 f9 ff ff 4c 89 cf e8 c6 df 23 00 e9 c8 f9 ff 2
[   57.375581] RSP: 0018:ffff88810f197548 EFLAGS: 00010006
[   57.376346] RAX: ffff8881107ce800 RBX: 0000000000000000 RCX: 1ffff110220f9d10
[   57.377376] RDX: ffff88810f189240 RSI: ffffffff84cd9e00 RDI: ffff8881107ce880
[   57.378403] RBP: ffff888114a29e0c R08: 0000000000000001 R09: ffffed1021e31248
[   57.379438] R10: ffff88810f189247 R11: ffffffff8480b32f R12: ffff8881f70b33c0
[   57.380472] R13: ffff888114a2a068 R14: ffff888114a29cc0 R15: ffff888114a2a004
[   57.381502] FS:  00007fd2c51cd600(0000) GS:ffff88826fd58000(0000) knlGS:0000000000000000
[   57.382668] CS:  0010 DS: 0000 ES: 0000 CR0: 0000000080050033
[   57.383518] CR2: 00007ffc3d2d0128 CR3: 000000010f172003 CR4: 0000000000170ef0
[   57.384561] Call Trace:
[   57.384941]  <TASK>
[   57.385276]  ? __pfx___perf_event_overflow+0x10/0x10
[   57.386018]  ? perf_swevent_set_period+0x131/0x1c0
[   57.386738]  ? __pfx_perf_swevent_set_period+0x10/0x10
[   57.387505]  ? __pfx___rmqueue_pcplist+0x10/0x10
[   57.388194]  perf_swevent_event+0x1d0/0x390
[   57.388824]  perf_tp_event+0x326/0x7b0
[   57.389398]  ? perf_tp_event_match+0x69/0x300
[   57.390052]  ? perf_trace_buf_update+0x21/0x150
[   57.390737]  ? perf_tp_event+0x15d/0x7b0
[   57.391325]  ? __pfx_perf_tp_event+0x10/0x10
[   57.391975]  ? __pfx_perf_tp_event+0x10/0x10
[   57.392621]  ? __pfx_get_page_from_freelist+0x10/0x10
[   57.393375]  ? idr_alloc_u32+0x192/0x2d0
[   57.393965]  ? __pfx_idr_alloc_u32+0x10/0x10
[   57.394609]  ? __alloc_frozen_pages_noprof+0x320/0x2980
[   57.395387]  ? idr_replace+0x127/0x140
[   57.395947]  ? __pfx_idr_replace+0x10/0x10
[   57.396565]  ? _raw_spin_lock+0x8a/0xe0
[   57.397143]  perf_trace_msr_trace_class+0x28e/0x450
[   57.397875]  ? __pfx_perf_trace_msr_trace_class+0x10/0x10
[   57.398673]  ? __pfx_perf_trace_msr_trace_class+0x10/0x10
[   57.399472]  do_trace_write_msr+0xaa/0xe0
[   57.400074]  __intel_pmu_enable_all.constprop.0+0x1db/0x350
[   57.400901]  __perf_event_task_sched_out+0x75b/0x1050
[   57.401653]  ? psi_group_change+0x4cc/0x960
[   57.402278]  ? __pfx___perf_event_task_sched_out+0x10/0x10
[   57.403089]  ? psi_task_switch+0x361/0x7e0
[   57.403703]  __schedule+0x180d/0x3e20
[   57.404254]  ? __pfx___schedule+0x10/0x10
[   57.404855]  ? __pfx___do_wait+0x10/0x10
[   57.405445]  ? __pfx__raw_spin_lock+0x10/0x10
[   57.406091]  schedule+0x78/0x1f0
[   57.406595]  do_wait+0x11c/0x3d0
[   57.407094]  kernel_wait4+0xf5/0x1c0
[   57.407644]  ? __pfx_kernel_wait4+0x10/0x10
[   57.408272]  ? __pfx_child_wait_callback+0x10/0x10
[   57.408989]  ? __pfx___css_rstat_updated+0x10/0x10
[   57.409710]  __do_sys_wait4+0xea/0x100
[   57.410279]  ? __pfx___do_sys_wait4+0x10/0x10
[   57.410938]  ? count_memcg_events+0x273/0x410
[   57.411600]  ? handle_mm_fault+0x2f9/0x570
[   57.412213]  ? fpregs_assert_state_consistent+0x9c/0x110
[   57.412999]  ? irqentry_exit+0x43/0x700
[   57.413583]  do_syscall_64+0x8f/0x470
[   57.414137]  entry_SYSCALL_64_after_hwframe+0x76/0x7e
[   57.414890] RIP: 0033:0x000000001638030e

From the stack, we can see:

perf_event_context_sched_out

        // fast path
        perf_ctx_enable(ctx, 0);
                perf_pmu_enable
                        if (!--(*count))  // equals 0
                                pmu->pmu_enable(pmu);
                                        __intel_pmu_enable_all.constprop
                                                do_trace_write_msr
                                                        perf_tp_event

In perf_tp_event():

        if (perf_tp_event_match(event, &raw, regs)) {
                if (!perf_pmu_enabled(event->pmu)) return 0; // not satisfied, continue downward
                perf_swevent_event
                        __perf_event_overflow
                                task_work_add  // event->ctx->task mismatches 'current'
        }

Because pmu_disable_count is already 0, the subsequent perf_tp_event_match() cannot block it via perf_pmu_enabled(), so the problem can be reproduced.

Maybe my original nr_no_switch_fast approach is still worth considering. -- it would account for sigtrap events at attach time and keep them off the fast path entirely, rather than trying to filter the overflow after the swap has already happened.

Thanks,
Tengda