mirror of https://lore.kernel.org/lkml/
 help / color / mirror / Atom feed
* [PATCH v1 00/13] perf fixes: off-cpu, stat, tool PMU, bperf, and bpf-filter fixes
@ 2026-11-23  7:19 Ian Rogers
  2026-11-23  7:19 ` [PATCH v1 01/13] perf off-cpu: Bound callchain length in off_cpu_write() Ian Rogers
                   ` (12 more replies)
  0 siblings, 13 replies; 15+ messages in thread
From: Ian Rogers @ 2026-11-23  7:19 UTC (permalink / raw)
  To: Peter Zijlstra, Ingo Molnar, Arnaldo Carvalho de Melo,
	Namhyung Kim, Jiri Olsa, Ian Rogers, Adrian Hunter, James Clark
  Cc: Howard Chu, Thomas Falcon, Song Liu, linux-perf-users, linux-kernel

This series collects standalone bug fixes across perf off-cpu, libperf
evlist, perf stat, the tool PMU, bperf (--bpf-counters), and perf
bpf-filter:

1. 'perf off-cpu' fixes (patches 1-2):
   - Zero the stack trace buffer before lookup and bound callchain
     length by MAX_STACKS in off_cpu_write() so full 32-frame stacks do
     not read and write past off_cpu_raw.
   - Fix swapped PID and TID packing in direct off_cpu_dump() BPF
     samples so multi-threaded direct off-CPU samples match
     off_cpu_write() and __set_offcpu_sample().

2. 'libperf', 'perf stat', 'tool' PMU, and '--bpf-counters' fixes
   (patches 3-9):
   - Drop any existing per-evsel CPU map and re-propagate all evsels in
     perf_evlist__go_system_wide() so evlist->all_cpus is rebuilt
     without retaining the "any CPU" (-1) placeholder.
   - Assign unique synthetic IDs to non-perf_event_open events (tool,
     hwmon, drm, retire_lat) for 'perf stat record' so counts are not
     all attributed to ID 0.
   - Serialize and restore per-evsel 'cpus' (rather than 'pmu_cpus')
     across 'perf stat record' and 'perf stat report', retaining
     backward compatibility for older perf.data files.
   - Return false for PERF_PMU_TYPE_TOOL in perf_pmu__is_software() and
     guard group leader handling so grouping tool PMU events with kernel
     PMU events does not hit BUG_ON() in get_group_fd() or fail in
     evsel__read_group().
   - Enable enable_on_exec tool PMU events in evlist__start_workload()
     so workload runs do not report 0 for duration_time, user_time, or
     system_time.
   - Compute enabled time in the wait4 rusage fallback for exited
     user_time and system_time events (e.g. with -D delay).
   - Restrict bperf (--bpf-counters / :b) to compatible counters and fix
     mixed, hybrid, cgroup, and repeat (-r) counter lifecycle bugs.

3. 'perf bpf-filter' and tracepoint filter fixes (patches 10-13):
   - Attach unpinned BPF sample filters via PERF_EVENT_IOC_SET_BPF
     instead of bpf_program__attach_perf_event_opts() to fix the
     bpf_link memory/FD leak reported by LeakSanitizer.
   - Deep-copy evsel->bpf_filters in evsel__clone() (fixing
     --for-each-cgroup) and release runtime BPF filter state in
     evsel__close() (fixing 'perf stat -r' repeat runs).
   - Add SEC("tracepoint") perf_tp_sample_filter for
     PERF_TYPE_TRACEPOINT events (with !CONFIG_CGROUPS CO-RE guards and
     selective pinning) so context-independent BPF filter terms (uid,
     gid, tid, pid, cpu, time, cgroup) do not fail with -EINVAL.
   - Route tracepoint --filter strings to BPF filters only when
     referencing non-field BPF terms (with tracefs format fallback when
     built with NO_LIBTRACEEVENT=1) and reject ambiguous mixed filters.

Notes on prior postings:
- Patch 3 was previously posted unchanged as patch 4/4 in
  https://lore.kernel.org/linux-perf-users/20261027170415.2815859-4-irogers@google.com/
  (patches 1-3 of that series were applied to perf-tools-next).
- Patches 10, 12, and 13 are extracted from the front of the earlier
  lock_held() v7 series, with patch 12/13 split into two commits and
  updated with !CONFIG_CGROUPS CO-RE guards and NO_LIBTRACEEVENT=1
  support.

Ian Rogers (13):
  perf off-cpu: Bound callchain length in off_cpu_write()
  perf off-cpu: Fix swapped PID and TID in direct off_cpu_dump() samples
  libperf evlist: Recompute CPU map when an evsel goes system wide
  perf stat: Give non-perf_event_open events unique IDs for stat record
  perf stat: Preserve per-evsel CPU maps across stat record and report
  perf pmu: Don't treat tool PMU as a kernel software PMU for event
    grouping
  perf evlist: Enable tool PMU events when starting a workload
  perf stat: Respect the enabled time of exited user_time/system_time
    events
  perf stat: Fix --bpf-counters with non-bperf, hybrid, and mixed events
  perf bpf-filter: Fix bpf_link leak by using PERF_EVENT_IOC_SET_BPF
  perf bpf-filter: Copy bpf_filters in evsel__clone() and close on
    evsel__close()
  perf bpf-filter: Support BPF sample filters on tracepoint events
  perf parse-events: Route non-field tracepoint filter terms to BPF
    filter

 tools/lib/perf/evlist.c                      |  12 +-
 tools/perf/Documentation/perf-record.txt     |  14 +-
 tools/perf/builtin-stat.c                    |  37 ++-
 tools/perf/tests/event_update.c              |  43 +++-
 tools/perf/tests/shell/stat.sh               |  16 ++
 tools/perf/util/bpf-filter.c                 | 225 ++++++++++++++++---
 tools/perf/util/bpf-filter.h                 |  10 +
 tools/perf/util/bpf_counter.c                | 115 +++++++---
 tools/perf/util/bpf_counter.h                |  14 ++
 tools/perf/util/bpf_counter_cgroup.c         | 145 ++++++++----
 tools/perf/util/bpf_off_cpu.c                |   4 +-
 tools/perf/util/bpf_skel/off_cpu.bpf.c       |   2 +-
 tools/perf/util/bpf_skel/sample_filter.bpf.c | 101 +++++++++
 tools/perf/util/evlist.c                     |  34 ++-
 tools/perf/util/evsel.c                      | 150 ++++++++++---
 tools/perf/util/evsel.h                      |   2 +-
 tools/perf/util/header.c                     |   5 +
 tools/perf/util/parse-events.c               | 179 +++++++++++++--
 tools/perf/util/pmu.c                        |   2 +-
 tools/perf/util/stat.c                       |  18 ++
 tools/perf/util/synthetic-events.c           |   7 +-
 tools/perf/util/tool_pmu.c                   |  30 ++-
 tools/perf/util/tool_pmu.h                   |   2 +
 tools/perf/util/tp_pmu.c                     |  55 +++++
 tools/perf/util/tp_pmu.h                     |   1 +
 25 files changed, 1057 insertions(+), 166 deletions(-)

-- 
2.56.1.750.gf70dc682cf-goog


^ permalink raw reply	[flat|nested] 15+ messages in thread

* [PATCH v1 01/13] perf off-cpu: Bound callchain length in off_cpu_write()
  2026-11-23  7:19 [PATCH v1 00/13] perf fixes: off-cpu, stat, tool PMU, bperf, and bpf-filter fixes Ian Rogers
@ 2026-11-23  7:19 ` Ian Rogers
  2026-11-23  7:19 ` [PATCH v1 02/13] perf off-cpu: Fix swapped PID and TID in direct off_cpu_dump() samples Ian Rogers
                   ` (11 subsequent siblings)
  12 siblings, 0 replies; 15+ messages in thread
From: Ian Rogers @ 2026-11-23  7:19 UTC (permalink / raw)
  To: Peter Zijlstra, Ingo Molnar, Arnaldo Carvalho de Melo,
	Namhyung Kim, Jiri Olsa, Ian Rogers, Adrian Hunter, James Clark
  Cc: Howard Chu, Thomas Falcon, Song Liu, linux-perf-users, linux-kernel

off_cpu_raw has MAX_STACKS + 5 entries and bpf_map_lookup_elem() copies
up to MAX_STACKS frames into &off_cpu_raw[i + 2] (with i == 2, occupying
indices 4..35). When a stack trace fills all MAX_STACKS frames, the
unbounded while (off_cpu_raw[i + 2 + len]) loop reads off_cpu_raw[36]
(which holds the previous sample's cgroup_id) and then reads and writes
past the end of off_cpu_raw. Zero the stack buffer before lookup in case
bpf_map_lookup_elem() fails and bound len by MAX_STACKS.

Fixes: 74069a01609e ("perf record --off-cpu: Dump the remaining PERF_SAMPLE_ in sample_type from BPF's stack trace map")
Signed-off-by: Ian Rogers <irogers@google.com>
---
 tools/perf/util/bpf_off_cpu.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/tools/perf/util/bpf_off_cpu.c b/tools/perf/util/bpf_off_cpu.c
index 71933a71c8d1..a3fdbc3c907f 100644
--- a/tools/perf/util/bpf_off_cpu.c
+++ b/tools/perf/util/bpf_off_cpu.c
@@ -399,10 +399,10 @@ int off_cpu_write(struct perf_session *session)
 
 			/* off_cpu_raw[i] is callchain->nr (updated later) */
 			off_cpu_raw[i + 1] = PERF_CONTEXT_USER;
-			off_cpu_raw[i + 2] = 0;
+			memset(&off_cpu_raw[i + 2], 0, MAX_STACKS * sizeof(u64));
 
 			bpf_map_lookup_elem(stack, &key.stack_id, &off_cpu_raw[i + 2]);
-			while (off_cpu_raw[i + 2 + len])
+			while (len < MAX_STACKS && off_cpu_raw[i + 2 + len])
 				len++;
 
 			off_cpu_raw[i] = len + 1;
-- 
2.56.1.750.gf70dc682cf-goog


^ permalink raw reply	[flat|nested] 15+ messages in thread

* [PATCH v1 02/13] perf off-cpu: Fix swapped PID and TID in direct off_cpu_dump() samples
  2026-11-23  7:19 [PATCH v1 00/13] perf fixes: off-cpu, stat, tool PMU, bperf, and bpf-filter fixes Ian Rogers
  2026-11-23  7:19 ` [PATCH v1 01/13] perf off-cpu: Bound callchain length in off_cpu_write() Ian Rogers
@ 2026-11-23  7:19 ` Ian Rogers
  2026-11-23  7:19 ` [PATCH v1 03/13] libperf evlist: Recompute CPU map when an evsel goes system wide Ian Rogers
                   ` (10 subsequent siblings)
  12 siblings, 0 replies; 15+ messages in thread
From: Ian Rogers @ 2026-11-23  7:19 UTC (permalink / raw)
  To: Peter Zijlstra, Ingo Molnar, Arnaldo Carvalho de Melo,
	Namhyung Kim, Jiri Olsa, Ian Rogers, Adrian Hunter, James Clark
  Cc: Howard Chu, Thomas Falcon, Song Liu, linux-perf-users, linux-kernel

__set_offcpu_sample() unpacks the first u64 of an off-cpu raw sample as
p32[0] = data->pid (process TGID) and p32[1] = data->tid (thread PID),
matching off_cpu_write() which packs (u64)key.pid << 32 | key.tgid on
little-endian hosts (and kernel BPF matches host endianness). However,
off_cpu_dump() packed (u64)key->tgid << 32 | key->pid, swapping PID and
TID for multi-threaded direct off-cpu samples exceeding the threshold.
Pack (u64)key->pid << 32 | key->tgid to match off_cpu_write() and
__set_offcpu_sample().

Fixes: d6948f2af24e ("perf record --off-cpu: Dump off-cpu samples in BPF")
Signed-off-by: Ian Rogers <irogers@google.com>
---
 tools/perf/util/bpf_skel/off_cpu.bpf.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/tools/perf/util/bpf_skel/off_cpu.bpf.c b/tools/perf/util/bpf_skel/off_cpu.bpf.c
index 72763bb8d1de..eeb2cb8ac0d8 100644
--- a/tools/perf/util/bpf_skel/off_cpu.bpf.c
+++ b/tools/perf/util/bpf_skel/off_cpu.bpf.c
@@ -236,7 +236,7 @@ static int off_cpu_dump(void *ctx, struct offcpu_data *data, struct offcpu_key *
 {
 	int n = 0, len = 0;
 
-	data->array[n++] = (u64)key->tgid << 32 | key->pid;
+	data->array[n++] = (u64)key->pid << 32 | key->tgid;
 	data->array[n++] = delta;
 
 	/* data->array[n] is callchain->nr (updated later) */
-- 
2.56.1.750.gf70dc682cf-goog


^ permalink raw reply	[flat|nested] 15+ messages in thread

* [PATCH v1 03/13] libperf evlist: Recompute CPU map when an evsel goes system wide
  2026-11-23  7:19 [PATCH v1 00/13] perf fixes: off-cpu, stat, tool PMU, bperf, and bpf-filter fixes Ian Rogers
  2026-11-23  7:19 ` [PATCH v1 01/13] perf off-cpu: Bound callchain length in off_cpu_write() Ian Rogers
  2026-11-23  7:19 ` [PATCH v1 02/13] perf off-cpu: Fix swapped PID and TID in direct off_cpu_dump() samples Ian Rogers
@ 2026-11-23  7:19 ` Ian Rogers
  2026-11-23  7:19 ` [PATCH v1 04/13] perf stat: Give non-perf_event_open events unique IDs for stat record Ian Rogers
                   ` (9 subsequent siblings)
  12 siblings, 0 replies; 15+ messages in thread
From: Ian Rogers @ 2026-11-23  7:19 UTC (permalink / raw)
  To: Peter Zijlstra, Ingo Molnar, Arnaldo Carvalho de Melo,
	Namhyung Kim, Jiri Olsa, Ian Rogers, Adrian Hunter, James Clark
  Cc: Howard Chu, Thomas Falcon, Song Liu, linux-perf-users, linux-kernel

perf_evlist__go_system_wide() marks the evsel as system wide and then
propagates the evlist's maps to it. __perf_evlist__propagate_maps()
only assigns the PMU CPUs to evsel->cpus if the map is empty, but an
evsel added after the evlist's maps were created already has the user
requested CPUs propagated (e.g. the "any CPU" map of -1 in per-thread
or workload mode). Going system wide then leaves the evsel opened on
the wrong CPUs.

Drop the existing CPU map before propagating so the evsel is given all
of its PMU's CPUs, as is expected for a system wide event. Propagate the
maps of all evsels, rather than just the one going system wide, so that
evlist->all_cpus is rebuilt. Otherwise the evsel's previous CPUs, such
as the "any CPU" -1, remain in evlist->all_cpus and may cause per-thread
rather than per-CPU mmaps to be used.

Fixes: 811082e4b668 ("perf parse-events: Support user CPUs mixed with threads/processes")
Reviewed-by: James Clark <james.clark@linaro.org>
Signed-off-by: Ian Rogers <irogers@google.com>
---
 tools/lib/perf/evlist.c | 12 ++++++++++--
 1 file changed, 10 insertions(+), 2 deletions(-)

diff --git a/tools/lib/perf/evlist.c b/tools/lib/perf/evlist.c
index c1c5b0684eed..c6ce56b46ac1 100644
--- a/tools/lib/perf/evlist.c
+++ b/tools/lib/perf/evlist.c
@@ -835,7 +835,15 @@ void perf_evlist__go_system_wide(struct perf_evlist *evlist, struct perf_evsel *
 {
 	if (!evsel->system_wide) {
 		evsel->system_wide = true;
-		if (evlist->needs_map_propagation)
-			__perf_evlist__propagate_maps(evlist, evsel);
+		if (evlist->needs_map_propagation) {
+			perf_cpu_map__put(evsel->cpus);
+			evsel->cpus = NULL;
+			/*
+			 * Propagate the maps of all evsels, rather than just
+			 * this one, so that evlist->all_cpus is rebuilt and
+			 * doesn't retain this evsel's previous CPUs.
+			 */
+			perf_evlist__propagate_maps(evlist);
+		}
 	}
 }
-- 
2.56.1.750.gf70dc682cf-goog


^ permalink raw reply	[flat|nested] 15+ messages in thread

* [PATCH v1 04/13] perf stat: Give non-perf_event_open events unique IDs for stat record
  2026-11-23  7:19 [PATCH v1 00/13] perf fixes: off-cpu, stat, tool PMU, bperf, and bpf-filter fixes Ian Rogers
                   ` (2 preceding siblings ...)
  2026-11-23  7:19 ` [PATCH v1 03/13] libperf evlist: Recompute CPU map when an evsel goes system wide Ian Rogers
@ 2026-11-23  7:19 ` Ian Rogers
  2026-11-23  7:19 ` [PATCH v1 05/13] perf stat: Preserve per-evsel CPU maps across stat record and report Ian Rogers
                   ` (8 subsequent siblings)
  12 siblings, 0 replies; 15+ messages in thread
From: Ian Rogers @ 2026-11-23  7:19 UTC (permalink / raw)
  To: Peter Zijlstra, Ingo Molnar, Arnaldo Carvalho de Melo,
	Namhyung Kim, Jiri Olsa, Ian Rogers, Adrian Hunter, James Clark
  Cc: Howard Chu, Thomas Falcon, Song Liu, linux-perf-users, linux-kernel

store_evsel_ids() skips tool, hwmon, DRM and retire latency events as
there is no perf event file descriptor to read an ID from. Their
perf_sample_id entries are left with an ID of 0, so the stat events
written by perf stat record all have an ID of 0. When reading the file,
evlist__id2evsel() maps an ID of 0 to the first evsel, so the counts of
all such events are attributed to the first evsel and the other events
are reported as not counted. For example:

  $ perf stat record -e duration_time,num_cpus,task-clock true
  $ perf stat report
                28      duration_time
     <not counted>      num_cpus
              0.84 msec task-clock

Give each CPU and thread of these events a unique synthetic ID. Kernel
IDs count up from 1, so the synthetic IDs count down from the largest
ID to be as far from them as possible; reaching them would need ~2^63
perf events to have been created. As a further guard, skip any ID that
is already in use by the evlist.

Fixes: d53b4996584b ("perf evsel: Skip store_evsel_ids for non-perf-event PMUs")
Signed-off-by: Ian Rogers <irogers@google.com>
---
 tools/perf/util/evsel.c | 42 ++++++++++++++++++++++++++++++++++++++---
 1 file changed, 39 insertions(+), 3 deletions(-)

diff --git a/tools/perf/util/evsel.c b/tools/perf/util/evsel.c
index 737a8680aaae..1f96c170d277 100644
--- a/tools/perf/util/evsel.c
+++ b/tools/perf/util/evsel.c
@@ -4727,15 +4727,51 @@ struct perf_env *evsel__env(struct evsel *evsel)
 	return session ? perf_session__env(session) : NULL;
 }
 
+/*
+ * Get an ID for an event not opened with perf_event_open, such as a tool PMU
+ * event. Kernel assigned IDs count up from 1, so count down from the largest
+ * ID to keep as far away from them as possible. Reaching the kernel's IDs
+ * would need ~2^63 perf events to have been created, but also skip any ID
+ * already in use by the evlist.
+ */
+static u64 evlist__next_synthetic_id(struct evlist *evlist)
+{
+	static u64 next_synthetic_id = ~0ULL;
+	u64 id;
+
+	do {
+		id = next_synthetic_id--;
+	} while (evlist__id2sid(evlist, id));
+
+	return id;
+}
+
 static int store_evsel_ids(struct evsel *evsel, struct evlist *evlist)
 {
 	int cpu_map_idx, thread;
 
-	if (evsel__is_retire_lat(evsel))
-		return 0;
+	if (evsel__is_retire_lat(evsel) ||
+	    perf_pmu__kind(evsel->pmu) != PERF_PMU_KIND_PE) {
+		struct xyarray *sample_id = evsel->core.sample_id;
 
-	if (perf_pmu__kind(evsel->pmu) != PERF_PMU_KIND_PE)
+		if (!sample_id)
+			return 0;
+
+		/*
+		 * There's no perf event to read an ID from. Give each
+		 * CPU/thread a unique synthetic ID, otherwise all such events
+		 * have ID 0 and stat events written by perf stat record are
+		 * attributed to the first evsel.
+		 */
+		for (cpu_map_idx = 0; cpu_map_idx < xyarray__max_x(sample_id); cpu_map_idx++) {
+			for (thread = 0; thread < xyarray__max_y(sample_id); thread++) {
+				perf_evlist__id_add(evlist__core(evlist), &evsel->core,
+						    cpu_map_idx, thread,
+						    evlist__next_synthetic_id(evlist));
+			}
+		}
 		return 0;
+	}
 
 	for (cpu_map_idx = 0; cpu_map_idx < xyarray__max_x(evsel->core.fd); cpu_map_idx++) {
 		for (thread = 0; thread < xyarray__max_y(evsel->core.fd);
-- 
2.56.1.750.gf70dc682cf-goog


^ permalink raw reply	[flat|nested] 15+ messages in thread

* [PATCH v1 05/13] perf stat: Preserve per-evsel CPU maps across stat record and report
  2026-11-23  7:19 [PATCH v1 00/13] perf fixes: off-cpu, stat, tool PMU, bperf, and bpf-filter fixes Ian Rogers
                   ` (3 preceding siblings ...)
  2026-11-23  7:19 ` [PATCH v1 04/13] perf stat: Give non-perf_event_open events unique IDs for stat record Ian Rogers
@ 2026-11-23  7:19 ` Ian Rogers
  2026-11-23 17:12   ` Athira Rajeev
  2026-11-23  7:19 ` [PATCH v1 06/13] perf pmu: Don't treat tool PMU as a kernel software PMU for event grouping Ian Rogers
                   ` (7 subsequent siblings)
  12 siblings, 1 reply; 15+ messages in thread
From: Ian Rogers @ 2026-11-23  7:19 UTC (permalink / raw)
  To: Peter Zijlstra, Ingo Molnar, Arnaldo Carvalho de Melo,
	Namhyung Kim, Jiri Olsa, Ian Rogers, Adrian Hunter, James Clark
  Cc: Howard Chu, Thomas Falcon, Song Liu, linux-perf-users, linux-kernel

Commit 6d765f5f7ec6 ("libperf evsel: Rename own_cpus to pmu_cpus") and
commit 811082e4b668 ("perf parse-events: Support user CPUs mixed with
threads/processes") separated an evsel's PMU cpumask (pmu_cpus) from the
actual CPUs on which the event is opened (cpus) and taught
__perf_evlist__propagate_maps() to collapse evsel->cpus to the "any CPU"
(-1) map when user_requested_cpus is -1 and !evsel->requires_cpu.

However, perf_event__synthesize_event_update_cpus() continued to
serialize evsel->core.pmu_cpus instead of evsel->core.cpus, and
perf_event__process_event_update() only populated evsel->core.pmu_cpus
without setting evsel->core.cpus or evsel->core.requires_cpu. This broke
perf stat record/report (and perf script) in two ways:

1. When recording an event opened per-CPU alongside a workload target
   (where user_requested_cpus is -1), such as an event with a cpu= term,
   an uncore counter, --bpf-counters, or a BPF-filtered counter,
   PERF_RECORD_STAT events are written with concrete CPU numbers, but
   perf stat report's perf_evlist__set_maps() collapses evsel->cpus to
   -1 and fails with:

     $ perf stat record -e 'task-clock/cpu=0/,task-clock' -- true
     $ perf stat report
     Invalid CPU 0 for event task-clock/cpu=0/.

2. In system-wide mode (-a), per-evsel CPU restrictions such as cpu=0
   were overwritten by the full PMU cpumask during report, causing
   perf stat report -A to report bogus <not counted> entries on every
   other CPU.

Fix perf_event__synthesize_event_update_cpus() to serialize
evsel->core.cpus, and update perf_event__process_event_update() to
populate evsel->core.cpus and set requires_cpu when the recorded CPU map
does not use the "any CPU" (-1) placeholder. For backward compatibility
with data files recorded by older perf binaries that wrote pmu_cpus for
per-task (-1) counters, fall back to the "any CPU" map in
perf_event__process_stat_event() if a -1 CPU stat event arrives for an
evsel without -1 in its CPU map.

Update the event_update unit test and stat.sh record/report/script tests
to cover per-evsel CPU maps on workload targets.

Fixes: 6d765f5f7ec6 ("libperf evsel: Rename own_cpus to pmu_cpus")
Fixes: 811082e4b668 ("perf parse-events: Support user CPUs mixed with threads/processes")
Signed-off-by: Ian Rogers <irogers@google.com>
---
 tools/perf/tests/event_update.c    | 43 ++++++++++++++++++++++++++----
 tools/perf/tests/shell/stat.sh     | 16 +++++++++++
 tools/perf/util/evsel.c            |  2 +-
 tools/perf/util/header.c           |  5 ++++
 tools/perf/util/stat.c             | 18 +++++++++++++
 tools/perf/util/synthetic-events.c |  7 +++--
 6 files changed, 83 insertions(+), 8 deletions(-)

diff --git a/tools/perf/tests/event_update.c b/tools/perf/tests/event_update.c
index 220cc0347747..bacf3c44c8e2 100644
--- a/tools/perf/tests/event_update.c
+++ b/tools/perf/tests/event_update.c
@@ -1,6 +1,7 @@
 // SPDX-License-Identifier: GPL-2.0
 #include <linux/compiler.h>
 #include <perf/cpumap.h>
+#include <perf/evlist.h>
 #include <string.h>
 #include "cpumap.h"
 #include "evlist.h"
@@ -58,13 +59,20 @@ static int process_event_name(const struct perf_tool *tool,
 	return 0;
 }
 
-static int process_event_cpus(const struct perf_tool *tool __maybe_unused,
+struct event_cpus {
+	struct perf_tool tool;
+	struct evlist *evlist;
+};
+
+static int process_event_cpus(const struct perf_tool *tool,
 			      union perf_event *event,
 			      struct perf_sample *sample __maybe_unused,
 			      struct machine *machine __maybe_unused)
 {
+	struct event_cpus *tmp = container_of(tool, struct event_cpus, tool);
 	struct perf_record_event_update *ev = (struct perf_record_event_update *)event;
-	struct perf_cpu_map *map;
+	struct perf_cpu_map *map, *any_cpu;
+	struct evsel *evsel;
 
 	map = cpu_map__new_data(&ev->cpus.cpus);
 
@@ -75,6 +83,26 @@ static int process_event_cpus(const struct perf_tool *tool __maybe_unused,
 	TEST_ASSERT_VAL("wrong cpus", perf_cpu_map__cpu(map, 1).cpu == 2);
 	TEST_ASSERT_VAL("wrong cpus", perf_cpu_map__cpu(map, 2).cpu == 3);
 	perf_cpu_map__put(map);
+
+	evsel = evlist__first(tmp->evlist);
+	perf_cpu_map__put(evsel->core.cpus);
+	evsel->core.cpus = NULL;
+	perf_cpu_map__put(evsel->core.pmu_cpus);
+	evsel->core.pmu_cpus = NULL;
+	evsel->core.requires_cpu = false;
+
+	TEST_ASSERT_VAL("failed to process attr update cpus",
+			!perf_event__process_event_update(tool, event, &tmp->evlist));
+
+	any_cpu = perf_cpu_map__new_any_cpu();
+	TEST_ASSERT_VAL("failed to allocate any_cpu map", any_cpu);
+	perf_evlist__set_maps(evlist__core(tmp->evlist), any_cpu, NULL);
+	perf_cpu_map__put(any_cpu);
+
+	TEST_ASSERT_VAL("wrong processed cpus", perf_cpu_map__nr(evsel->core.cpus) == 3);
+	TEST_ASSERT_VAL("wrong processed cpus", perf_cpu_map__cpu(evsel->core.cpus, 0).cpu == 1);
+	TEST_ASSERT_VAL("wrong processed cpus", perf_cpu_map__cpu(evsel->core.cpus, 1).cpu == 2);
+	TEST_ASSERT_VAL("wrong processed cpus", perf_cpu_map__cpu(evsel->core.cpus, 2).cpu == 3);
 	return 0;
 }
 
@@ -82,6 +110,7 @@ static int test__event_update(struct test_suite *test __maybe_unused, int subtes
 {
 	struct evsel *evsel;
 	struct event_name tmp;
+	struct event_cpus tmp_cpus;
 	struct target target = {};
 	struct evlist *evlist = evlist__new_default(&target, /*sample_callchains=*/false);
 
@@ -111,11 +140,15 @@ static int test__event_update(struct test_suite *test __maybe_unused, int subtes
 	TEST_ASSERT_VAL("failed to synthesize attr update name",
 			!perf_event__synthesize_event_update_name(&tmp.tool, evsel, process_event_name));
 
-	perf_cpu_map__put(evsel->core.pmu_cpus);
-	evsel->core.pmu_cpus = perf_cpu_map__new("1,2,3");
+	perf_cpu_map__put(evsel->core.cpus);
+	evsel->core.cpus = perf_cpu_map__new("1,2,3");
+
+	perf_tool__init(&tmp_cpus.tool, /*ordered_events=*/false);
+	tmp_cpus.evlist = evlist;
 
 	TEST_ASSERT_VAL("failed to synthesize attr update cpus",
-			!perf_event__synthesize_event_update_cpus(&tmp.tool, evsel, process_event_cpus));
+			!perf_event__synthesize_event_update_cpus(&tmp_cpus.tool, evsel,
+								  process_event_cpus));
 
 	evlist__put(evlist);
 	return 0;
diff --git a/tools/perf/tests/shell/stat.sh b/tools/perf/tests/shell/stat.sh
index ac9e031831da..43a158ee3609 100755
--- a/tools/perf/tests/shell/stat.sh
+++ b/tools/perf/tests/shell/stat.sh
@@ -77,6 +77,14 @@ test_stat_record_report() {
     err=1
     return
   fi
+  cpu=$(sed 's/[-,].*//' /sys/devices/system/cpu/online)
+  if ! perf stat record -e "task-clock/cpu=${cpu}/,task-clock" -o - true | \
+    perf stat report -i - 2>&1 | grep -E -q "task-clock/cpu=${cpu}/"
+  then
+    echo "stat record and report test [Failed per-evsel CPU]"
+    err=1
+    return
+  fi
   echo "stat record and report test [Success]"
 }
 
@@ -89,6 +97,14 @@ test_stat_record_script() {
     err=1
     return
   fi
+  cpu=$(sed 's/[-,].*//' /sys/devices/system/cpu/online)
+  if ! perf stat record -e "task-clock/cpu=${cpu}/,task-clock" -o - true | \
+    perf script -i - 2>&1 | grep -E -q "task-clock/cpu=${cpu}/"
+  then
+    echo "stat record and script test [Failed per-evsel CPU]"
+    err=1
+    return
+  fi
   echo "stat record and script test [Success]"
 }
 
diff --git a/tools/perf/util/evsel.c b/tools/perf/util/evsel.c
index 1f96c170d277..64daef4cc345 100644
--- a/tools/perf/util/evsel.c
+++ b/tools/perf/util/evsel.c
@@ -1822,7 +1822,7 @@ void evsel__config(struct evsel *evsel, const struct record_opts *opts,
 		attr->exclude_user   = 1;
 	}
 
-	if (evsel->core.pmu_cpus || evsel->unit)
+	if (evsel->core.cpus || evsel->core.pmu_cpus || evsel->unit)
 		evsel->core.attr.read_format |= PERF_FORMAT_ID;
 
 	/*
diff --git a/tools/perf/util/header.c b/tools/perf/util/header.c
index 9eec6deee190..e9af99b8c0f8 100644
--- a/tools/perf/util/header.c
+++ b/tools/perf/util/header.c
@@ -5962,6 +5962,11 @@ int perf_event__process_event_update(const struct perf_tool *tool __maybe_unused
 		if (map) {
 			perf_cpu_map__put(evsel->core.pmu_cpus);
 			evsel->core.pmu_cpus = map;
+			if (!evsel->counts) {
+				perf_cpu_map__put(evsel->core.cpus);
+				evsel->core.cpus = perf_cpu_map__get(map);
+				evsel->core.requires_cpu = !perf_cpu_map__has_any_cpu(map);
+			}
 		} else
 			pr_err("failed to get event_update cpus\n");
 		break;
diff --git a/tools/perf/util/stat.c b/tools/perf/util/stat.c
index 6da3dbbde0e2..429bfc339308 100644
--- a/tools/perf/util/stat.c
+++ b/tools/perf/util/stat.c
@@ -8,6 +8,7 @@
 
 #include <linux/err.h>
 #include <linux/zalloc.h>
+#include <perf/cpumap.h>
 
 #include "counts.h"
 #include "cpumap.h"
@@ -674,6 +675,23 @@ int perf_event__process_stat_event(const struct perf_tool *tool __maybe_unused,
 		return -EINVAL;
 	}
 	cpu_map_idx = perf_cpu_map__idx(evsel__cpus(counter), (struct perf_cpu){.cpu = st->cpu});
+	if (cpu_map_idx == -1 && (s32)st->cpu == -1 && counter->counts &&
+	    evsel__nr_cpus(counter) > 0) {
+		/*
+		 * Older perf tools wrote pmu_cpus instead of cpus in
+		 * PERF_EVENT_UPDATE__CPUS, leaving per-task counters with a
+		 * CPU list instead of the "any CPU" (-1) map used by their
+		 * PERF_RECORD_STAT events.
+		 */
+		struct perf_cpu_map *any_cpu = perf_cpu_map__new_any_cpu();
+
+		if (any_cpu) {
+			perf_cpu_map__put(counter->core.cpus);
+			counter->core.cpus = any_cpu;
+			counter->core.requires_cpu = false;
+			cpu_map_idx = 0;
+		}
+	}
 	if (cpu_map_idx == -1) {
 		pr_err("Invalid CPU %d for event %s.\n", st->cpu, evsel__name(counter));
 		return -EINVAL;
diff --git a/tools/perf/util/synthetic-events.c b/tools/perf/util/synthetic-events.c
index 3c8d29f27fd9..b87d15a5be6a 100644
--- a/tools/perf/util/synthetic-events.c
+++ b/tools/perf/util/synthetic-events.c
@@ -2234,10 +2234,13 @@ int perf_event__synthesize_event_update_name(const struct perf_tool *tool, struc
 int perf_event__synthesize_event_update_cpus(const struct perf_tool *tool, struct evsel *evsel,
 					     perf_event__handler_t process)
 {
-	struct synthesize_cpu_map_data syn_data = { .map = evsel->core.pmu_cpus };
+	struct synthesize_cpu_map_data syn_data = { .map = evsel->core.cpus };
 	struct perf_record_event_update *ev;
 	int err;
 
+	if (!evsel->core.cpus)
+		return 0;
+
 	ev = cpu_map_data__alloc(&syn_data, sizeof(struct perf_event_header) + 2 * sizeof(u64));
 	if (!ev)
 		return -ENOMEM;
@@ -2315,7 +2318,7 @@ int perf_event__synthesize_extra_attr(const struct perf_tool *tool, struct evlis
 			}
 		}
 
-		if (evsel->core.pmu_cpus) {
+		if (evsel->core.cpus) {
 			err = perf_event__synthesize_event_update_cpus(tool, evsel, process);
 			if (err < 0) {
 				pr_err("Couldn't synthesize evsel cpus.\n");
-- 
2.56.1.750.gf70dc682cf-goog


^ permalink raw reply	[flat|nested] 15+ messages in thread

* [PATCH v1 06/13] perf pmu: Don't treat tool PMU as a kernel software PMU for event grouping
  2026-11-23  7:19 [PATCH v1 00/13] perf fixes: off-cpu, stat, tool PMU, bperf, and bpf-filter fixes Ian Rogers
                   ` (4 preceding siblings ...)
  2026-11-23  7:19 ` [PATCH v1 05/13] perf stat: Preserve per-evsel CPU maps across stat record and report Ian Rogers
@ 2026-11-23  7:19 ` Ian Rogers
  2026-11-23  7:19 ` [PATCH v1 07/13] perf evlist: Enable tool PMU events when starting a workload Ian Rogers
                   ` (6 subsequent siblings)
  12 siblings, 0 replies; 15+ messages in thread
From: Ian Rogers @ 2026-11-23  7:19 UTC (permalink / raw)
  To: Peter Zijlstra, Ingo Molnar, Arnaldo Carvalho de Melo,
	Namhyung Kim, Jiri Olsa, Ian Rogers, Adrian Hunter, James Clark
  Cc: Howard Chu, Thomas Falcon, Song Liu, linux-perf-users, linux-kernel

perf_pmu__is_software() identifies kernel software PMUs (such as
PERF_TYPE_SOFTWARE, PERF_TYPE_TRACEPOINT, and PERF_TYPE_BREAKPOINT) whose
events can share a perf_event_open() group_fd with a hardware PMU event.
Userspace-implemented PMUs like the tool, hwmon, and drm PMUs do not open
perf_event file descriptors (leaving FD(leader, ...) == -1), so keeping a
userspace PMU event grouped with a kernel PMU event hits BUG_ON(fd == -1
&& leader->supported) in get_group_fd() (e.g. '{duration_time,cycles}' or
'{duration_time,task-clock}') or fails in evsel__read_group() (e.g.
'{cycles,duration_time}' or '{task-clock,duration_time}').

Return false for PERF_PMU_TYPE_TOOL in perf_pmu__is_software(), matching
hwmon and drm PMUs, and ensure evsel__compute_group_pmu_name() only
substitutes perf_event_open PMU names for software and AUX events so
'{duration_time,task-clock}' does not adopt the tool PMU's group name
while preserving same-PMU userspace groups such as '{hwmon_a/e1/,
hwmon_a/e2/}' and '{duration_time,user_time}'. Also check the group
leader's attr.disabled in evsel__tool_pmu_open() and guard get_group_fd()
and evsel__group_read_nr_members() against non-perf_event_open PMUs.

Fixes: 240505b2d0ad ("perf tool_pmu: Factor tool events into their own PMU")
Signed-off-by: Ian Rogers <irogers@google.com>
---
 tools/perf/builtin-stat.c      |  7 +++-
 tools/perf/util/evsel.c        | 76 +++++++++++++++++++++++++++-------
 tools/perf/util/parse-events.c | 24 +++++++----
 tools/perf/util/pmu.c          |  2 +-
 tools/perf/util/tool_pmu.c     |  6 ++-
 5 files changed, 87 insertions(+), 28 deletions(-)

diff --git a/tools/perf/builtin-stat.c b/tools/perf/builtin-stat.c
index 37752d6bfef4..4fe4da20aae8 100644
--- a/tools/perf/builtin-stat.c
+++ b/tools/perf/builtin-stat.c
@@ -721,7 +721,9 @@ static int create_perf_stat_counter(struct evsel *evsel,
 	 * the group read (for leader) and ID retrieval for all
 	 * members.
 	 */
-	if (leader->core.nr_members > 1)
+	if (leader->core.nr_members > 1 &&
+	    !evsel__is_non_perf_event_open_pmu(leader) &&
+	    !evsel__is_non_perf_event_open_pmu(evsel))
 		attr->read_format |= PERF_FORMAT_ID|PERF_FORMAT_GROUP;
 
 	attr->inherit = !config->no_inherit && list_empty(&evsel->bpf_counter_list);
@@ -750,7 +752,8 @@ static int create_perf_stat_counter(struct evsel *evsel,
 	 * either manually by us or by kernel via enable_on_exec
 	 * set later.
 	 */
-	if (evsel__is_group_leader(evsel)) {
+	if (evsel__is_group_leader(evsel) ||
+	    evsel__is_non_perf_event_open_pmu(leader)) {
 		attr->disabled = 1;
 
 		if (target__enable_on_exec(&target))
diff --git a/tools/perf/util/evsel.c b/tools/perf/util/evsel.c
index 64daef4cc345..babeccfbecb5 100644
--- a/tools/perf/util/evsel.c
+++ b/tools/perf/util/evsel.c
@@ -430,7 +430,8 @@ void evsel__set_sample_id(struct evsel *evsel,
 
 bool evsel__is_non_perf_event_open_pmu(const struct evsel *evsel)
 {
-	return evsel->pmu && evsel->pmu->type > PERF_PMU_TYPE_PE_END;
+	return evsel->pmu && evsel->pmu->type > PERF_PMU_TYPE_PE_END &&
+	       !perf_pmu__is_fake(evsel->pmu);
 }
 
 /**
@@ -1916,13 +1917,33 @@ int evsel__enable_cpu(struct evsel *evsel, int cpu_map_idx)
 			if (evsel__is_non_perf_event_open_pmu(evsel) ||
 			    evsel__is_non_perf_event_open_pmu(member)) {
 				/*
-				 * In a mixed PMU group, userspace PMUs are not
-				 * grouped in the kernel (opened with group_fd = -1)
-				 * and are skipped by the kernel when enabling the
-				 * group leader. We must manually enable them in
-				 * userspace.
+				 * Userspace PMUs are not grouped in the kernel
+				 * (opened with group_fd = -1) and may have
+				 * different CPU maps (e.g. duration_time sets
+				 * reads_only_on_cpu_idx0 while user_time has
+				 * all CPUs). Enable matching member CPUs.
 				 */
-				int mem_err = evsel__enable_cpu(member, cpu_map_idx);
+				int mem_err = 0;
+
+				if (evsel->core.reads_only_on_cpu_idx0) {
+					if (cpu_map_idx == 0) {
+						int nr = perf_cpu_map__nr(member->core.cpus);
+
+						for (int m = 0; m < nr && !mem_err; m++)
+							mem_err = evsel__enable_cpu(member, m);
+					}
+				} else if (member->core.reads_only_on_cpu_idx0) {
+					if (cpu_map_idx == 0 &&
+					    perf_cpu_map__nr(member->core.cpus) > 0)
+						mem_err = evsel__enable_cpu(member, 0);
+				} else {
+					struct perf_cpu cpu = perf_cpu_map__cpu(evsel->core.cpus,
+										cpu_map_idx);
+					int mem_idx = perf_cpu_map__idx(member->core.cpus, cpu);
+
+					if (mem_idx >= 0)
+						mem_err = evsel__enable_cpu(member, mem_idx);
+				}
 
 				if (mem_err)
 					return mem_err;
@@ -1986,12 +2007,33 @@ int evsel__disable_cpu(struct evsel *evsel, int cpu_map_idx)
 			if (evsel__is_non_perf_event_open_pmu(evsel) ||
 			    evsel__is_non_perf_event_open_pmu(member)) {
 				/*
-				 * In a mixed PMU group, userspace PMUs are not
-				 * grouped in the kernel and are skipped by the
-				 * kernel when disabling the group leader. We must
-				 * manually disable them in userspace.
+				 * Userspace PMUs are not grouped in the kernel
+				 * and may have different CPU maps (e.g.
+				 * duration_time sets reads_only_on_cpu_idx0
+				 * while user_time has all CPUs). Disable
+				 * matching member CPUs.
 				 */
-				int mem_err = evsel__disable_cpu(member, cpu_map_idx);
+				int mem_err = 0;
+
+				if (evsel->core.reads_only_on_cpu_idx0) {
+					if (cpu_map_idx == 0) {
+						int nr = perf_cpu_map__nr(member->core.cpus);
+
+						for (int m = 0; m < nr && !mem_err; m++)
+							mem_err = evsel__disable_cpu(member, m);
+					}
+				} else if (member->core.reads_only_on_cpu_idx0) {
+					if (cpu_map_idx == 0 &&
+					    perf_cpu_map__nr(member->core.cpus) > 0)
+						mem_err = evsel__disable_cpu(member, 0);
+				} else {
+					struct perf_cpu cpu = perf_cpu_map__cpu(evsel->core.cpus,
+										cpu_map_idx);
+					int mem_idx = perf_cpu_map__idx(member->core.cpus, cpu);
+
+					if (mem_idx >= 0)
+						mem_err = evsel__disable_cpu(member, mem_idx);
+				}
 
 				if (mem_err)
 					return mem_err;
@@ -2167,7 +2209,8 @@ static bool evsel__group_has_tpebs(struct evsel *leader)
 	struct evsel *evsel;
 
 	for_each_group_evsel(evsel, leader) {
-		if (evsel__is_retire_lat(evsel))
+		if (evsel__is_retire_lat(evsel) ||
+		    evsel__is_non_perf_event_open_pmu(evsel))
 			return true;
 	}
 	return false;
@@ -2179,7 +2222,8 @@ static u64 evsel__group_read_nr_members(struct evsel *leader)
 	struct evsel *evsel;
 
 	for_each_group_evsel(evsel, leader) {
-		if (evsel__is_retire_lat(evsel))
+		if (evsel__is_retire_lat(evsel) ||
+		    evsel__is_non_perf_event_open_pmu(evsel))
 			nr--;
 	}
 	return nr;
@@ -2367,7 +2411,9 @@ static int get_group_fd(struct evsel *evsel, int cpu_map_idx, int thread)
 	struct evsel *leader = evsel__leader(evsel);
 	int fd;
 
-	if (!evsel->supported || evsel__is_group_leader(evsel))
+	if (!evsel->supported || evsel__is_group_leader(evsel) ||
+	    evsel__is_non_perf_event_open_pmu(leader) ||
+	    evsel__is_non_perf_event_open_pmu(evsel))
 		return -1;
 
 	/*
diff --git a/tools/perf/util/parse-events.c b/tools/perf/util/parse-events.c
index ca13fcc05db0..ba3e5015058c 100644
--- a/tools/perf/util/parse-events.c
+++ b/tools/perf/util/parse-events.c
@@ -2027,13 +2027,17 @@ static int evsel__compute_group_pmu_name(struct evsel *evsel,
 	group_pmu_name = pmu->name;
 	/*
 	 * Software events may be in a group with other uncore PMU events. Use
-	 * the pmu_name of the first non-software event to avoid breaking the
-	 * software event out of the group.
+	 * the pmu_name of the first non-software perf_event_open PMU event to
+	 * avoid breaking the software event out of the group. Userspace PMUs
+	 * (tool, hwmon, drm, bpf) do not open perf_event file descriptors and
+	 * cannot share a kernel group_fd.
 	 *
 	 * Aux event leaders, like intel_pt, expect a group with events from
 	 * other PMUs, so substitute the AUX event's PMU in this case.
 	 */
-	if (perf_pmu__is_software(pmu) || evsel__is_aux_event(leader)) {
+	if ((perf_pmu__kind(pmu) == PERF_PMU_KIND_PE ||
+	     perf_pmu__kind(pmu) == PERF_PMU_KIND_FAKE) &&
+	    (perf_pmu__is_software(pmu) || evsel__is_aux_event(leader))) {
 		struct perf_pmu *leader_pmu = evsel__find_pmu(leader);
 
 		if (!leader_pmu) {
@@ -2042,11 +2046,13 @@ static int evsel__compute_group_pmu_name(struct evsel *evsel,
 		}
 		/*
 		 * Starting with the leader, find the first event with a named
-		 * non-software PMU. for_each_group_(member|evsel) isn't used as
-		 * the list isn't yet sorted putting evsel's in the same group
-		 * together.
+		 * non-software perf_event_open PMU. for_each_group_(member|evsel)
+		 * isn't used as the list isn't yet sorted putting evsel's in
+		 * the same group together.
 		 */
-		if (leader_pmu && !perf_pmu__is_software(leader_pmu)) {
+		if (leader_pmu && !perf_pmu__is_software(leader_pmu) &&
+		    (perf_pmu__kind(leader_pmu) == PERF_PMU_KIND_PE ||
+		     perf_pmu__kind(leader_pmu) == PERF_PMU_KIND_FAKE)) {
 			group_pmu_name = leader_pmu->name;
 		} else if (leader->core.nr_members > 1) {
 			list_for_each_entry(pos, head, core.node) {
@@ -2059,7 +2065,9 @@ static int evsel__compute_group_pmu_name(struct evsel *evsel,
 					/* As with determining pmu above. */
 					pos_pmu = perf_pmus__scan_core(NULL);
 				}
-				if (pos_pmu && !perf_pmu__is_software(pos_pmu)) {
+				if (pos_pmu && !perf_pmu__is_software(pos_pmu) &&
+				    (perf_pmu__kind(pos_pmu) == PERF_PMU_KIND_PE ||
+				     perf_pmu__kind(pos_pmu) == PERF_PMU_KIND_FAKE)) {
 					group_pmu_name = pos_pmu->name;
 					break;
 				}
diff --git a/tools/perf/util/pmu.c b/tools/perf/util/pmu.c
index 1ae8bcf71c68..ab91dac5d226 100644
--- a/tools/perf/util/pmu.c
+++ b/tools/perf/util/pmu.c
@@ -2461,7 +2461,7 @@ bool perf_pmu__is_software(const struct perf_pmu *pmu)
 	case PERF_TYPE_HW_CACHE:	return false;
 	case PERF_TYPE_RAW:		return false;
 	case PERF_TYPE_BREAKPOINT:	return true;
-	case PERF_PMU_TYPE_TOOL:	return true;
+	case PERF_PMU_TYPE_TOOL:	return false;
 	default: break;
 	}
 	for (size_t i = 0; i < ARRAY_SIZE(known_sw_pmus); i++) {
diff --git a/tools/perf/util/tool_pmu.c b/tools/perf/util/tool_pmu.c
index d2f7591747d9..a62a7cb390ae 100644
--- a/tools/perf/util/tool_pmu.c
+++ b/tools/perf/util/tool_pmu.c
@@ -272,7 +272,8 @@ int evsel__tool_pmu_open(struct evsel *evsel,
 		if (evsel->core.attr.sample_period) /* no sampling */
 			return -EINVAL;
 		evsel->duration_time.accumulated_time = 0;
-		if (evsel->core.attr.disabled) {
+		if (evsel->core.attr.disabled ||
+		    evsel__leader(evsel)->core.attr.disabled) {
 			evsel->disabled = true;
 			evsel->duration_time.start_time = INVALID_START_TIME;
 		} else {
@@ -321,7 +322,8 @@ int evsel__tool_pmu_open(struct evsel *evsel,
 					evsel->process_time.accumulated_times, idx, thread);
 				*accumulated_time = 0;
 
-				if (evsel->core.attr.disabled) {
+				if (evsel->core.attr.disabled ||
+				    evsel__leader(evsel)->core.attr.disabled) {
 					evsel->disabled = true;
 					*start_time = INVALID_START_TIME;
 				} else {
-- 
2.56.1.750.gf70dc682cf-goog


^ permalink raw reply	[flat|nested] 15+ messages in thread

* [PATCH v1 07/13] perf evlist: Enable tool PMU events when starting a workload
  2026-11-23  7:19 [PATCH v1 00/13] perf fixes: off-cpu, stat, tool PMU, bperf, and bpf-filter fixes Ian Rogers
                   ` (5 preceding siblings ...)
  2026-11-23  7:19 ` [PATCH v1 06/13] perf pmu: Don't treat tool PMU as a kernel software PMU for event grouping Ian Rogers
@ 2026-11-23  7:19 ` Ian Rogers
  2026-11-23  7:19 ` [PATCH v1 08/13] perf stat: Respect the enabled time of exited user_time/system_time events Ian Rogers
                   ` (5 subsequent siblings)
  12 siblings, 0 replies; 15+ messages in thread
From: Ian Rogers @ 2026-11-23  7:19 UTC (permalink / raw)
  To: Peter Zijlstra, Ingo Molnar, Arnaldo Carvalho de Melo,
	Namhyung Kim, Jiri Olsa, Ian Rogers, Adrian Hunter, James Clark
  Cc: Howard Chu, Thomas Falcon, Song Liu, linux-perf-users, linux-kernel

When perf stat runs a workload, group leaders are opened disabled with
enable_on_exec set so that the kernel enables them when the workload
execs. Since tool PMU events were made to respect enable/disable they
are opened disabled too, but there is no kernel event to be enabled on
exec, so they are never enabled and count 0. For example:

  $ perf stat -e duration_time,user_time,task-clock -- perf test -w noploop
                 0      duration_time
                 0      user_time
          1,013.74 msec task-clock

Enable tool PMU events that are set to enable on exec when the workload
is started.

Fixes: 0b18bced5444 ("perf tool_pmu: Make tool PMU events respect enable/disable")
Signed-off-by: Ian Rogers <irogers@google.com>
---
 tools/perf/util/evlist.c | 15 +++++++++++++++
 tools/perf/util/evsel.c  | 14 ++++++++++++++
 2 files changed, 29 insertions(+)

diff --git a/tools/perf/util/evlist.c b/tools/perf/util/evlist.c
index c2402e4791b6..ec26064183b6 100644
--- a/tools/perf/util/evlist.c
+++ b/tools/perf/util/evlist.c
@@ -69,6 +69,7 @@
 #include "string2.h"
 #include "target.h"
 #include "thread_map.h"
+#include "tool_pmu.h"
 #include "units.h"
 #include "util.h"
 
@@ -1909,6 +1910,20 @@ int evlist__start_workload(struct evlist *evlist)
 	if (evlist__workload_cork_fd(evlist) >= 0) {
 		char bf = 0;
 		int ret;
+		struct evsel *pos;
+
+		/*
+		 * Tool PMU events aren't opened with perf_event_open and so
+		 * aren't enabled by the kernel on exec. Enable them as the
+		 * workload is started.
+		 */
+		evlist__for_each_entry(evlist, pos) {
+			if (evsel__is_tool(pos) &&
+			    (pos->core.attr.enable_on_exec ||
+			     evsel__leader(pos)->core.attr.enable_on_exec) &&
+			    pos->core.fd && pos->supported)
+				evsel__enable(pos);
+		}
 		/*
 		 * Remove the cork, let it rip!
 		 */
diff --git a/tools/perf/util/evsel.c b/tools/perf/util/evsel.c
index babeccfbecb5..d89087e295dc 100644
--- a/tools/perf/util/evsel.c
+++ b/tools/perf/util/evsel.c
@@ -1914,6 +1914,8 @@ int evsel__enable_cpu(struct evsel *evsel, int cpu_map_idx)
 		struct evsel *member;
 
 		for_each_group_member(member, evsel) {
+			if (!member->core.fd)
+				continue;
 			if (evsel__is_non_perf_event_open_pmu(evsel) ||
 			    evsel__is_non_perf_event_open_pmu(member)) {
 				/*
@@ -1969,6 +1971,11 @@ int evsel__enable(struct evsel *evsel)
 		struct evsel *member;
 
 		for_each_group_member(member, evsel) {
+			if (!member->core.fd) {
+				if (evsel__is_retire_lat(member))
+					member->disabled = false;
+				continue;
+			}
 			if (evsel__is_non_perf_event_open_pmu(evsel) ||
 			    evsel__is_non_perf_event_open_pmu(member)) {
 				/*
@@ -2004,6 +2011,8 @@ int evsel__disable_cpu(struct evsel *evsel, int cpu_map_idx)
 		struct evsel *member;
 
 		for_each_group_member(member, evsel) {
+			if (!member->core.fd)
+				continue;
 			if (evsel__is_non_perf_event_open_pmu(evsel) ||
 			    evsel__is_non_perf_event_open_pmu(member)) {
 				/*
@@ -2065,6 +2074,11 @@ int evsel__disable(struct evsel *evsel)
 		struct evsel *member;
 
 		for_each_group_member(member, evsel) {
+			if (!member->core.fd) {
+				if (evsel__is_retire_lat(member))
+					member->disabled = true;
+				continue;
+			}
 			if (evsel__is_non_perf_event_open_pmu(evsel) ||
 			    evsel__is_non_perf_event_open_pmu(member)) {
 				/*
-- 
2.56.1.750.gf70dc682cf-goog


^ permalink raw reply	[flat|nested] 15+ messages in thread

* [PATCH v1 08/13] perf stat: Respect the enabled time of exited user_time/system_time events
  2026-11-23  7:19 [PATCH v1 00/13] perf fixes: off-cpu, stat, tool PMU, bperf, and bpf-filter fixes Ian Rogers
                   ` (6 preceding siblings ...)
  2026-11-23  7:19 ` [PATCH v1 07/13] perf evlist: Enable tool PMU events when starting a workload Ian Rogers
@ 2026-11-23  7:19 ` Ian Rogers
  2026-11-23  7:19 ` [PATCH v1 09/13] perf stat: Fix --bpf-counters with non-bperf, hybrid, and mixed events Ian Rogers
                   ` (4 subsequent siblings)
  12 siblings, 0 replies; 15+ messages in thread
From: Ian Rogers @ 2026-11-23  7:19 UTC (permalink / raw)
  To: Peter Zijlstra, Ingo Molnar, Arnaldo Carvalho de Melo,
	Namhyung Kim, Jiri Olsa, Ian Rogers, Adrian Hunter, James Clark
  Cc: Howard Chu, Thomas Falcon, Song Liu, linux-perf-users, linux-kernel

When a workload has exited and been reaped by wait4, user_time and
system_time can no longer be read from /proc/<pid>/stat and perf stat
falls back to using the rusage values from wait4. These are the totals
for the whole run of the workload and ignore when the event was enabled,
such as after a delay. For example:

  $ perf stat -D 500 -e duration_time,user_time,task-clock -- perf test -w noploop
       524,466,208      duration_time
     1,004,578,000      user_time
            522.86 msec task-clock

Add evsel__tool_pmu_exited_process_time() to compute the time the event
was enabled for from the process's total time, the start time when it
was last enabled and the accumulated time, and use it for the rusage
fallback.

Fixes: 0b18bced5444 ("perf tool_pmu: Make tool PMU events respect enable/disable")
Signed-off-by: Ian Rogers <irogers@google.com>
---
 tools/perf/builtin-stat.c  |  3 +++
 tools/perf/util/tool_pmu.c | 24 ++++++++++++++++++++++++
 tools/perf/util/tool_pmu.h |  2 ++
 3 files changed, 29 insertions(+)

diff --git a/tools/perf/builtin-stat.c b/tools/perf/builtin-stat.c
index 4fe4da20aae8..964bf0864796 100644
--- a/tools/perf/builtin-stat.c
+++ b/tools/perf/builtin-stat.c
@@ -302,6 +302,9 @@ static int read_single_counter(struct evsel *counter, int cpu_map_idx, int threa
 		else
 			val = ru_stats.ru_stime_usec_stat.mean;
 
+		/* Only count the time the event was enabled, such as after a delay. */
+		val = evsel__tool_pmu_exited_process_time(counter, cpu_map_idx, thread, val);
+
 		count->val = val;
 		if (old_count) {
 			count->run = old_count->run + 1;
diff --git a/tools/perf/util/tool_pmu.c b/tools/perf/util/tool_pmu.c
index a62a7cb390ae..24ff27099d32 100644
--- a/tools/perf/util/tool_pmu.c
+++ b/tools/perf/util/tool_pmu.c
@@ -13,9 +13,11 @@
 #include <api/fs/fs.h>
 #include <api/io.h>
 #include <internal/threadmap.h>
+#include <internal/xyarray.h>
 #include <perf/threadmap.h>
 #include <fcntl.h>
 #include <strings.h>
+#include <unistd.h>
 
 #define INVALID_START_TIME ~0ULL
 
@@ -709,6 +711,28 @@ int evsel__tool_pmu_read(struct evsel *evsel, int cpu_map_idx, int thread)
 	return 0;
 }
 
+/*
+ * When the process has exited its user or system time can no longer be read
+ * from /proc. Given the process's total time, such as from wait4, compute the
+ * time the event was enabled for.
+ */
+u64 evsel__tool_pmu_exited_process_time(struct evsel *evsel, int cpu_map_idx, int thread,
+					u64 total_ns)
+{
+	u64 ns_per_tick = 1000000000ULL / sysconf(_SC_CLK_TCK);
+	__u64 start_time = *(__u64 *)xyarray__entry(evsel->process_time.start_times,
+						    cpu_map_idx, thread);
+	__u64 accumulated = *(__u64 *)xyarray__entry(evsel->process_time.accumulated_times,
+						     cpu_map_idx, thread);
+	u64 val = accumulated * ns_per_tick;
+
+	if (!evsel->disabled && start_time != INVALID_START_TIME &&
+	    total_ns >= start_time * ns_per_tick)
+		val += total_ns - start_time * ns_per_tick;
+
+	return val;
+}
+
 struct perf_pmu *tool_pmu__new(void)
 {
 	struct perf_pmu *tool = zalloc(sizeof(struct perf_pmu));
diff --git a/tools/perf/util/tool_pmu.h b/tools/perf/util/tool_pmu.h
index f66d24cf3502..137b0a06a852 100644
--- a/tools/perf/util/tool_pmu.h
+++ b/tools/perf/util/tool_pmu.h
@@ -61,6 +61,8 @@ int evsel__tool_pmu_enable(struct evsel *evsel);
 int evsel__tool_pmu_disable_cpu(struct evsel *evsel, int cpu_map_idx);
 int evsel__tool_pmu_disable(struct evsel *evsel);
 int evsel__tool_pmu_read(struct evsel *evsel, int cpu_map_idx, int thread);
+u64 evsel__tool_pmu_exited_process_time(struct evsel *evsel, int cpu_map_idx, int thread,
+					u64 total_ns);
 
 struct perf_pmu *tool_pmu__new(void);
 
-- 
2.56.1.750.gf70dc682cf-goog


^ permalink raw reply	[flat|nested] 15+ messages in thread

* [PATCH v1 09/13] perf stat: Fix --bpf-counters with non-bperf, hybrid, and mixed events
  2026-11-23  7:19 [PATCH v1 00/13] perf fixes: off-cpu, stat, tool PMU, bperf, and bpf-filter fixes Ian Rogers
                   ` (7 preceding siblings ...)
  2026-11-23  7:19 ` [PATCH v1 08/13] perf stat: Respect the enabled time of exited user_time/system_time events Ian Rogers
@ 2026-11-23  7:19 ` Ian Rogers
  2026-11-23  7:19 ` [PATCH v1 10/13] perf bpf-filter: Fix bpf_link leak by using PERF_EVENT_IOC_SET_BPF Ian Rogers
                   ` (3 subsequent siblings)
  12 siblings, 0 replies; 15+ messages in thread
From: Ian Rogers @ 2026-11-23  7:19 UTC (permalink / raw)
  To: Peter Zijlstra, Ingo Molnar, Arnaldo Carvalho de Melo,
	Namhyung Kim, Jiri Olsa, Ian Rogers, Adrian Hunter, James Clark
  Cc: Howard Chu, Thomas Falcon, Song Liu, linux-perf-users, linux-kernel

When `perf stat` runs with `--bpf-counters` (`target.use_bpf`), the `:b`
event modifier (`evsel->bpf_counter`), or `stat.bpf-counter-events`,
`bpf_counter__load()` unconditionally assigns `bperf_ops` (or
`bperf_cgrp_ops` for `--for-each-cgroup`) and `__run_perf_stat()` skips
`create_perf_stat_counter()` whenever `target.use_bpf` is set. This
causes several failures when events that cannot be read through bperf's
shared per-CPU `PERF_EVENT_ARRAY` are present:

1. Non-`perf_event_open` PMU events (`tool` events such as
   `duration_time` and `user_time`, `bpf`, `hwmon`, and `drm` PMUs),
   uncore PMUs, and retirement latency (`:R`) events have no CPU-local
   `perf_event` file descriptor for `bpf_perf_event_read_value()`, so
   bperf either reads 0, leaves `tool` state uninitialized (reading
   system uptime for `duration_time` on secondary cgroups or
   dereferencing NULL `process_time` xyarrays), or skips opening them.
2. Events with tracepoint, address, or BPF filters (`evsel->filter` or
   `evsel->bpf_filters`) and `-G` cgroup events share bperf's global
   pinned `/sys/fs/bpf/perf_attr_map` keyed solely on
   `struct perf_event_attr`, ignoring filters/cgroups or skipping
   `perf_bpf_filter__prepare()` in `evlist__apply_filters()`.
3. Grouped events under `--bpf-counters` (such as `Default` topdown
   metric groups) fail `bperf_check_target()` instead of falling back to
   regular grouped counters.
4. On hybrid systems, `-C <cpus>` can leave one PMU's `evsel->core.cpus`
   empty (hitting `assert()` in `bperf_reload_leader_program()` or
   dereferencing NULL `evsel->core.fd` in `store_evsel_ids()`) or give
   different hybrid evsels different CPU counts (clobbering the
   file-static `filter_entry_cnt` in `bpf_counter.c`).
5. In mixed sessions (`!all_counters_use_bpf`), `__evlist__disable()`
   and `__evlist__enable()` run `PERF_EVENT_IOC_DISABLE` / `ENABLE` on
   `evsel->core.fd` of the session that loaded `bperf_leader`, disabling
   the globally shared hardware PMCs for concurrent and repeat (`-r`)
   runs. Repeat runs also leaked `bperf_follower` `fexit` links and
   leader FDs, and left `bperf_cgrp` `cgrp_readings` accumulating across
   runs.

Fix these issues by:
- Adding `bpf_counter__can_use_bperf()` and
  `bpf_counter__can_use_bperf_cgrp()` to restrict `bperf` to compatible
  counters and fall back cleanly otherwise, rejecting explicit `:b` on
  grouped events before `evlist__create_maps()` splits mismatched group
  CPU maps, and leaving `tool` PMU events out of `bperf_cgrp_ops` so
  they open, toggle (`-D`), and reset (`-r`) through the regular tool
  PMU paths.
- Gating the `create_perf_stat_counter()` loop on `!all_counters_use_bpf`
  instead of `!target.use_bpf`, resetting `all_counters_use_bpf` on each
  run, and only setting `requires_cpu` on counters that will use bperf.
- Skipping `evsel__is_bperf()` counters in `evlist__is_enabled()`,
  `__evlist__disable()`, and `__evlist__enable()`, and guarding NULL
  `evsel->core.fd` in `evlist__apply_filters()` and `store_evsel_ids()`.
- Reading per-evsel `accum_readings` map max entries instead of a global
  `filter_entry_cnt`, clearing `evsel->leader_skel` before freeing it,
  storing `skel->links.fexit_XXX`, closing `cgrp_switch` on teardown,
  and resetting follower / `bperf_cgrp` / `bpf_prog_profiler` state on
  repeat loads.

Fixes: 7fac83aaf2ee ("perf stat: Introduce 'bperf' to share hardware PMCs with BPF")
Signed-off-by: Ian Rogers <irogers@google.com>
---
 tools/perf/builtin-stat.c            |  27 ++++-
 tools/perf/util/bpf_counter.c        | 115 ++++++++++++++++-----
 tools/perf/util/bpf_counter.h        |  14 +++
 tools/perf/util/bpf_counter_cgroup.c | 145 ++++++++++++++++++++-------
 tools/perf/util/evlist.c             |  17 +++-
 tools/perf/util/evsel.c              |   8 +-
 6 files changed, 254 insertions(+), 72 deletions(-)

diff --git a/tools/perf/builtin-stat.c b/tools/perf/builtin-stat.c
index 964bf0864796..267808e23e69 100644
--- a/tools/perf/builtin-stat.c
+++ b/tools/perf/builtin-stat.c
@@ -802,6 +802,8 @@ static int __run_perf_stat(int argc, const char **argv, int run_idx)
 		child_pid = evlist__workload_pid(evsel_list);
 	}
 
+	all_counters_use_bpf = true;
+
 	evlist__for_each_entry(evsel_list, counter) {
 		counter->reset_group = false;
 		if (bpf_counter__load(counter, &target)) {
@@ -818,7 +820,7 @@ static int __run_perf_stat(int argc, const char **argv, int run_idx)
 	 * bperf calls evsel__open_per_cpu() in bperf__load(), so
 	 * no need to call it again here.
 	 */
-	if (!target.use_bpf) {
+	if (!all_counters_use_bpf) {
 		evlist__for_each_cpu(evlist_cpu_itr, evsel_list) {
 			counter = evlist_cpu_itr.evsel;
 
@@ -2908,6 +2910,15 @@ int cmd_stat(int argc, const char **argv)
 			goto out;
 		}
 
+		if (target.use_bpf) {
+			evlist__for_each_entry(evsel_list, counter) {
+				if (!bpf_counter__can_use_bperf_cgrp(counter)) {
+					target.use_bpf = false;
+					break;
+				}
+			}
+		}
+
 		if (evlist__expand_cgroup(evsel_list, stat_config.cgroup_list,
 					  !target.use_bpf) < 0) {
 			parse_options_usage(stat_usage, stat_options,
@@ -2927,6 +2938,18 @@ int cmd_stat(int argc, const char **argv)
 	evlist__warn_user_requested_cpus(evsel_list, target.cpu_list);
 
 	evlist__for_each_entry(evsel_list, counter) {
+		bool needs_bperf_cpu =
+			(counter->bpf_counter || target.use_bpf ||
+			 evsel__match_bpf_counter_events(evsel__name(counter))) &&
+			(stat_config.cgroup_list ?
+			 (target.use_bpf && !evsel__is_non_perf_event_open_pmu(counter)) :
+			 bpf_counter__can_use_bperf(counter));
+
+		if (counter->bpf_counter && counter->core.leader->nr_members > 1) {
+			pr_err("bpf managed perf events do not yet support groups.\n");
+			goto out;
+		}
+
 		/*
 		 * Setup BPF counters to require CPUs as any(-1) isn't
 		 * supported. evlist__create_maps below will propagate this
@@ -2934,7 +2957,7 @@ int cmd_stat(int argc, const char **argv)
 		 * set up, and this change must happen early, so directly use
 		 * the bpf_counter variable and target information.
 		 */
-		if ((counter->bpf_counter || target.use_bpf) && !target__has_cpu(&target))
+		if (needs_bperf_cpu && !target__has_cpu(&target))
 			counter->core.requires_cpu = true;
 	}
 
diff --git a/tools/perf/util/bpf_counter.c b/tools/perf/util/bpf_counter.c
index 9362e45e17ce..d2ab19ec4366 100644
--- a/tools/perf/util/bpf_counter.c
+++ b/tools/perf/util/bpf_counter.c
@@ -4,6 +4,7 @@
 
 #include <assert.h>
 #include <limits.h>
+#include <stdbool.h>
 #include <unistd.h>
 #include <sys/file.h>
 #include <sys/resource.h>
@@ -22,7 +23,9 @@
 #include "debug.h"
 #include "evsel.h"
 #include "evlist.h"
+#include "pmu.h"
 #include "target.h"
+#include "tool_pmu.h"
 #include "cgroup.h"
 #include "cpumap.h"
 #include "thread_map.h"
@@ -230,6 +233,9 @@ static int bpf_program_profiler__load(struct evsel *evsel, struct target *target
 	u32 prog_id;
 	int ret;
 
+	if (!list_empty(&evsel->bpf_counter_list))
+		bpf_program_profiler__destroy(evsel);
+
 	bpf_str_ = bpf_str = strdup(target->bpf_str);
 	if (!bpf_str)
 		return -1;
@@ -240,6 +246,7 @@ static int bpf_program_profiler__load(struct evsel *evsel, struct target *target
 		    (*p != '\0' && *p != ',')) {
 			pr_err("Failed to parse bpf prog ids %s\n",
 			       target->bpf_str);
+			bpf_program_profiler__destroy(evsel);
 			free(bpf_str_);
 			return -1;
 		}
@@ -454,8 +461,6 @@ static int bperf_check_target(struct evsel *evsel,
 	return 0;
 }
 
-static __u32 filter_entry_cnt;
-
 static int bperf_reload_leader_program(struct evsel *evsel, int attr_map_fd,
 				       struct perf_event_attr_map_entry *entry)
 {
@@ -505,6 +510,7 @@ static int bperf_reload_leader_program(struct evsel *evsel, int attr_map_fd,
 	perf_thread_map__put(threads);
 
 out:
+	evsel->leader_skel = NULL;
 	bperf_leader_bpf__destroy(skel);
 	bpf_link__destroy(link);
 	return err;
@@ -523,19 +529,38 @@ static int bperf_attach_follower_program(struct bperf_follower_bpf *skel,
 		err = bperf_follower_bpf__attach(skel);
 	else {
 		link = bpf_program__attach(skel->progs.fexit_XXX);
-		if (IS_ERR(link))
-			err = PTR_ERR(link);
+		err = libbpf_get_error(link);
+		if (!err)
+			skel->links.fexit_XXX = link;
 	}
 
 	return err;
 }
 
+static int bperf__destroy(struct evsel *evsel)
+{
+	bperf_follower_bpf__destroy(evsel->follower_skel);
+	evsel->follower_skel = NULL;
+	if (evsel->bperf_leader_prog_fd >= 0) {
+		close(evsel->bperf_leader_prog_fd);
+		evsel->bperf_leader_prog_fd = -1;
+	}
+	if (evsel->bperf_leader_link_fd >= 0) {
+		close(evsel->bperf_leader_link_fd);
+		evsel->bperf_leader_link_fd = -1;
+	}
+	return 0;
+}
+
 static int bperf__load(struct evsel *evsel, struct target *target)
 {
 	struct perf_event_attr_map_entry entry = {0xffffffff, 0xffffffff};
 	int attr_map_fd, diff_map_fd = -1, err;
 	enum bperf_filter_type filter_type;
-	__u32 i;
+	__u32 filter_entry_cnt, i;
+
+	if (evsel->follower_skel)
+		bperf__destroy(evsel);
 
 	if (bperf_check_target(evsel, target, &filter_type, &filter_entry_cnt))
 		return -1;
@@ -641,10 +666,18 @@ static int bperf__load(struct evsel *evsel, struct target *target)
 					    target->inherit);
 
 out:
-	if (err && evsel->bperf_leader_link_fd >= 0)
-		close(evsel->bperf_leader_link_fd);
-	if (err && evsel->bperf_leader_prog_fd >= 0)
-		close(evsel->bperf_leader_prog_fd);
+	if (err) {
+		bperf_follower_bpf__destroy(evsel->follower_skel);
+		evsel->follower_skel = NULL;
+		if (evsel->bperf_leader_link_fd >= 0) {
+			close(evsel->bperf_leader_link_fd);
+			evsel->bperf_leader_link_fd = -1;
+		}
+		if (evsel->bperf_leader_prog_fd >= 0) {
+			close(evsel->bperf_leader_prog_fd);
+			evsel->bperf_leader_prog_fd = -1;
+		}
+	}
 	if (diff_map_fd >= 0)
 		close(diff_map_fd);
 
@@ -697,11 +730,13 @@ static int bperf__read(struct evsel *evsel)
 	struct bpf_perf_event_value values[num_cpu_bpf];
 	struct perf_counts_values *counts;
 	int reading_map_fd, err = 0;
+	__u32 entry_cnt;
 
 	bperf_sync_counters(evsel);
 	reading_map_fd = bpf_map__fd(skel->maps.accum_readings);
+	entry_cnt = bpf_map__max_entries(skel->maps.accum_readings);
 
-	for (__u32 i = 0; i < filter_entry_cnt; i++) {
+	for (__u32 i = 0; i < entry_cnt; i++) {
 		struct perf_cpu entry;
 		__u32 cpu;
 
@@ -750,14 +785,6 @@ static int bperf__read(struct evsel *evsel)
 	return err;
 }
 
-static int bperf__destroy(struct evsel *evsel)
-{
-	bperf_follower_bpf__destroy(evsel->follower_skel);
-	close(evsel->bperf_leader_prog_fd);
-	close(evsel->bperf_leader_link_fd);
-	return 0;
-}
-
 /*
  * bperf: share hardware PMCs with BPF
  *
@@ -856,18 +883,56 @@ int bpf_counter__install_pe(struct evsel *evsel, int cpu_map_idx, int fd)
 	return evsel->bpf_counter_ops->install_pe(evsel, cpu_map_idx, fd);
 }
 
+bool bpf_counter__can_use_bperf(const struct evsel *evsel)
+{
+	return !evsel__is_non_perf_event_open_pmu(evsel) &&
+	       !evsel__is_retire_lat(evsel) &&
+	       !evsel->core.is_pmu_uncore &&
+	       !(evsel->pmu && evsel->pmu->is_uncore) &&
+	       !evsel->cgrp &&
+	       !evsel->filter &&
+	       list_empty(&evsel->bpf_filters) &&
+	       evsel->core.leader->nr_members <= 1;
+}
+
+bool bpf_counter__can_use_bperf_cgrp(const struct evsel *evsel)
+{
+	if (evsel__is_tool(evsel)) {
+		enum tool_pmu_event ev = evsel__tool_event(evsel);
+
+		return ev != TOOL_PMU__EVENT_USER_TIME &&
+		       ev != TOOL_PMU__EVENT_SYSTEM_TIME;
+	}
+
+	return !evsel__is_non_perf_event_open_pmu(evsel) &&
+	       !evsel__is_retire_lat(evsel) &&
+	       !evsel->core.is_pmu_uncore &&
+	       !(evsel->pmu && evsel->pmu->is_uncore) &&
+	       !evsel->filter &&
+	       list_empty(&evsel->bpf_filters);
+}
+
 int bpf_counter__load(struct evsel *evsel, struct target *target)
 {
-	if (target->bpf_str)
+	if (target->bpf_str) {
 		evsel->bpf_counter_ops = &bpf_program_profiler_ops;
-	else if (cgrp_event_expanded && target->use_bpf)
-		evsel->bpf_counter_ops = &bperf_cgrp_ops;
-	else if (target->use_bpf || evsel->bpf_counter ||
-		 evsel__match_bpf_counter_events(evsel->name))
+	} else if (cgrp_event_expanded && target->use_bpf) {
+		if (!evsel__is_tool(evsel))
+			evsel->bpf_counter_ops = &bperf_cgrp_ops;
+	} else if ((target->use_bpf || evsel->bpf_counter ||
+		    evsel__match_bpf_counter_events(evsel__name(evsel))) &&
+		   bpf_counter__can_use_bperf(evsel) &&
+		   !perf_cpu_map__has_any_cpu_or_is_empty(evsel->core.cpus)) {
 		evsel->bpf_counter_ops = &bperf_ops;
+	}
+
+	if (evsel->bpf_counter_ops) {
+		int err = evsel->bpf_counter_ops->load(evsel, target);
 
-	if (evsel->bpf_counter_ops)
-		return evsel->bpf_counter_ops->load(evsel, target);
+		if (err)
+			bpf_counter__destroy(evsel);
+		return err;
+	}
 	return 0;
 }
 
diff --git a/tools/perf/util/bpf_counter.h b/tools/perf/util/bpf_counter.h
index 658d8e7d507e..08056254264e 100644
--- a/tools/perf/util/bpf_counter.h
+++ b/tools/perf/util/bpf_counter.h
@@ -2,6 +2,8 @@
 #ifndef __PERF_BPF_COUNTER_H
 #define __PERF_BPF_COUNTER_H 1
 
+#include <stdbool.h>
+
 struct evsel;
 struct target;
 
@@ -30,6 +32,8 @@ int bpf_counter__disable(struct evsel *evsel);
 int bpf_counter__read(struct evsel *evsel);
 void bpf_counter__destroy(struct evsel *evsel);
 int bpf_counter__install_pe(struct evsel *evsel, int cpu_map_idx, int fd);
+bool bpf_counter__can_use_bperf(const struct evsel *evsel);
+bool bpf_counter__can_use_bperf_cgrp(const struct evsel *evsel);
 
 int bperf_trigger_reading(int prog_fd, int cpu);
 void set_max_rlimit(void);
@@ -70,6 +74,16 @@ static inline int bpf_counter__install_pe(struct evsel *evsel __maybe_unused,
 	return 0;
 }
 
+static inline bool bpf_counter__can_use_bperf(const struct evsel *evsel __maybe_unused)
+{
+	return false;
+}
+
+static inline bool bpf_counter__can_use_bperf_cgrp(const struct evsel *evsel __maybe_unused)
+{
+	return false;
+}
+
 #endif /* HAVE_BPF_SKEL */
 
 #endif /* __PERF_BPF_COUNTER_H */
diff --git a/tools/perf/util/bpf_counter_cgroup.c b/tools/perf/util/bpf_counter_cgroup.c
index 4e5f4b9dd442..3b99b011b228 100644
--- a/tools/perf/util/bpf_counter_cgroup.c
+++ b/tools/perf/util/bpf_counter_cgroup.c
@@ -6,6 +6,8 @@
 #include <assert.h>
 #include <errno.h>
 #include <limits.h>
+#include <stdbool.h>
+#include <stdlib.h>
 #include <unistd.h>
 #include <sys/file.h>
 #include <sys/time.h>
@@ -14,6 +16,7 @@
 #include <linux/perf_event.h>
 #include <api/fs/fs.h>
 #include <bpf/bpf.h>
+#include <bpf/libbpf.h>
 #include <perf/bpf_perf.h>
 
 #include "affinity.h"
@@ -23,7 +26,9 @@
 #include "debug.h"
 #include "evsel.h"
 #include "evlist.h"
+#include "pmu.h"
 #include "target.h"
+#include "tool_pmu.h"
 #include "cpumap.h"
 #include "thread_map.h"
 
@@ -39,7 +44,9 @@ static struct perf_event_attr cgrp_switch_attr = {
 };
 
 static struct evsel *cgrp_switch;
+static struct evsel *bperf_cgrp_leader;
 static struct bperf_cgroup_bpf *skel;
+static bool bperf_loaded;
 
 #define FD(evt, cpu) (*(int *)xyarray__entry(evt->core.fd, cpu, 0))
 
@@ -150,25 +157,31 @@ static int bperf_load_program(struct evlist *evlist)
 
 	evlist__for_each_entry(evlist, evsel) {
 		if (cgrp == NULL || evsel->cgrp == leader_cgrp) {
-			unsigned int j;
-
 			leader_cgrp = evsel->cgrp;
-			evsel->cgrp = NULL;
 
-			/* open single copy of the events w/o cgroup */
-			err = evsel__open_per_cpu(evsel, evsel->core.cpus, -1);
-			if (err == 0)
-				evsel->supported = true;
+			if (!evsel__is_tool(evsel) &&
+			    !perf_cpu_map__has_any_cpu_or_is_empty(evsel->core.cpus)) {
+				unsigned int j;
 
-			map_fd = bpf_map__fd(skel->maps.events);
-			perf_cpu_map__for_each_cpu(cpu, j, evsel->core.cpus) {
-				int fd = FD(evsel, j);
-				__u32 idx = evsel->core.idx * total_cpus + cpu.cpu;
+				evsel->cgrp = NULL;
 
-				bpf_map_update_elem(map_fd, &idx, &fd, BPF_ANY);
-			}
+				/* open single copy of the events w/o cgroup */
+				err = evsel__open_per_cpu(evsel, evsel->core.cpus, -1);
+				if (err == 0) {
+					evsel->supported = true;
+					map_fd = bpf_map__fd(skel->maps.events);
+					perf_cpu_map__for_each_cpu(cpu, j, evsel->core.cpus) {
+						int fd = FD(evsel, j);
+						__u32 idx = evsel->core.idx * total_cpus + cpu.cpu;
 
-			evsel->cgrp = leader_cgrp;
+						bpf_map_update_elem(map_fd, &idx, &fd, BPF_ANY);
+					}
+				} else {
+					evsel->supported = false;
+				}
+
+				evsel->cgrp = leader_cgrp;
+			}
 		}
 
 		if (evsel->cgrp == cgrp)
@@ -200,6 +213,8 @@ static int bperf_load_program(struct evlist *evlist)
 		int num_events = evlist__nr_entries(evlist) / nr_cgroups;
 
 		evlist__for_each_entry(evlist, evsel) {
+			if (evsel__is_tool(evsel))
+				continue;
 			leader = evlist__find_evsel(evlist, evsel->core.idx % num_events);
 			if (leader)
 				evsel->supported = leader->supported;
@@ -219,21 +234,81 @@ static int bperf_load_program(struct evlist *evlist)
 	}
 
 out:
+	if (err) {
+		bperf_cgroup_bpf__destroy(skel);
+		skel = NULL;
+		if (cgrp_switch) {
+			evsel__close(cgrp_switch);
+			evsel__put(cgrp_switch);
+			cgrp_switch = NULL;
+		}
+	}
+	return err;
+}
+
+/*
+ * trigger the leader prog on each cpu, so the cgrp_reading map could get
+ * the latest results.
+ */
+static int bperf_cgrp__sync_counters(struct evlist *evlist)
+{
+	struct perf_cpu cpu;
+	unsigned int idx;
+	int prog_fd = bpf_program__fd(skel->progs.trigger_read);
+
+	perf_cpu_map__for_each_cpu(cpu, idx, evlist__core(evlist)->all_cpus)
+		bperf_trigger_reading(prog_fd, cpu.cpu);
+
+	return 0;
+}
+
+static int bperf_cgrp__reset_readings(struct evlist *evlist)
+{
+	int nr_cpus = libbpf_num_possible_cpus();
+	int total_cpus = cpu__max_cpu().cpu;
+	struct bpf_perf_event_value *values;
+	int reading_map_fd, err = 0;
+	__u32 nr_entries = evlist__nr_entries(evlist);
+
+	if (nr_cpus > total_cpus)
+		total_cpus = nr_cpus;
+	if (total_cpus <= 0)
+		return -EINVAL;
+
+	skel->bss->enabled = 0;
+	bperf_cgrp__sync_counters(evlist);
+
+	values = calloc(total_cpus, sizeof(*values));
+	if (!values)
+		return -ENOMEM;
+
+	reading_map_fd = bpf_map__fd(skel->maps.cgrp_readings);
+	for (__u32 idx = 0; idx < nr_entries; idx++) {
+		err = bpf_map_update_elem(reading_map_fd, &idx, values, BPF_ANY);
+		if (err)
+			break;
+	}
+
+	free(values);
 	return err;
 }
 
 static int bperf_cgrp__load(struct evsel *evsel,
 			    struct target *target __maybe_unused)
 {
-	static bool bperf_loaded = false;
-
 	evsel->bperf_leader_prog_fd = -1;
 	evsel->bperf_leader_link_fd = -1;
 
-	if (!bperf_loaded && bperf_load_program(evsel->evlist))
-		return -1;
+	if (!bperf_loaded) {
+		if (bperf_load_program(evsel->evlist))
+			return -1;
+		bperf_loaded = true;
+		bperf_cgrp_leader = evsel;
+	} else if (evsel == bperf_cgrp_leader) {
+		if (bperf_cgrp__reset_readings(evsel->evlist))
+			return -1;
+	}
 
-	bperf_loaded = true;
 	/* just to bypass bpf_counter_skip() */
 	evsel->follower_skel = (struct bperf_follower_bpf *)skel;
 
@@ -248,25 +323,9 @@ static int bperf_cgrp__install_pe(struct evsel *evsel __maybe_unused,
 	return 0;
 }
 
-/*
- * trigger the leader prog on each cpu, so the cgrp_reading map could get
- * the latest results.
- */
-static int bperf_cgrp__sync_counters(struct evlist *evlist)
-{
-	struct perf_cpu cpu;
-	unsigned int idx;
-	int prog_fd = bpf_program__fd(skel->progs.trigger_read);
-
-	perf_cpu_map__for_each_cpu(cpu, idx, evlist__core(evlist)->all_cpus)
-		bperf_trigger_reading(prog_fd, cpu.cpu);
-
-	return 0;
-}
-
 static int bperf_cgrp__enable(struct evsel *evsel)
 {
-	if (evsel->core.idx)
+	if (evsel != bperf_cgrp_leader)
 		return 0;
 
 	bperf_cgrp__sync_counters(evsel->evlist);
@@ -277,7 +336,7 @@ static int bperf_cgrp__enable(struct evsel *evsel)
 
 static int bperf_cgrp__disable(struct evsel *evsel)
 {
-	if (evsel->core.idx)
+	if (evsel != bperf_cgrp_leader)
 		return 0;
 
 	bperf_cgrp__sync_counters(evsel->evlist);
@@ -294,7 +353,7 @@ static int bperf_cgrp__read(struct evsel *evsel)
 	struct bpf_perf_event_value *values;
 	int reading_map_fd, err = 0;
 
-	if (evsel->core.idx)
+	if (evsel != bperf_cgrp_leader)
 		return 0;
 
 	bperf_cgrp__sync_counters(evsel->evlist);
@@ -310,6 +369,9 @@ static int bperf_cgrp__read(struct evsel *evsel)
 		unsigned int i;
 		struct perf_cpu cpu;
 
+		if (evsel__is_tool(evsel))
+			continue;
+
 		err = bpf_map_lookup_elem(reading_map_fd, &idx, values);
 		if (err) {
 			pr_err("bpf map lookup failed: idx=%u, event=%s, cgrp=%s\n",
@@ -332,11 +394,16 @@ static int bperf_cgrp__read(struct evsel *evsel)
 
 static int bperf_cgrp__destroy(struct evsel *evsel)
 {
-	if (evsel->core.idx)
+	if (evsel != bperf_cgrp_leader)
 		return 0;
 
 	bperf_cgroup_bpf__destroy(skel);
+	skel = NULL;
+	evsel__close(cgrp_switch);
 	evsel__put(cgrp_switch);  // it'll destroy on_switch progs too
+	cgrp_switch = NULL;
+	bperf_cgrp_leader = NULL;
+	bperf_loaded = false;
 
 	return 0;
 }
diff --git a/tools/perf/util/evlist.c b/tools/perf/util/evlist.c
index ec26064183b6..638d501a7531 100644
--- a/tools/perf/util/evlist.c
+++ b/tools/perf/util/evlist.c
@@ -754,7 +754,7 @@ static bool evlist__is_enabled(struct evlist *evlist)
 	struct evsel *pos;
 
 	evlist__for_each_entry(evlist, pos) {
-		if (!pos->core.fd)
+		if (!pos->core.fd || evsel__is_bperf(pos))
 			continue;
 		if (!evsel__is_group_leader(pos) && !pos->merged_hybrid_group)
 			continue;
@@ -782,7 +782,8 @@ static void __evlist__disable(struct evlist *evlist, char *evsel_name, bool excl
 			if (!match)
 				continue;
 			if (pos->disabled || (!evsel__is_group_leader(pos) &&
-					      !pos->merged_hybrid_group) || !pos->core.fd)
+					      !pos->merged_hybrid_group) ||
+			    !pos->core.fd || evsel__is_bperf(pos))
 				continue;
 			if (excl_dummy && evsel__is_dummy_event(pos))
 				continue;
@@ -802,7 +803,8 @@ static void __evlist__disable(struct evlist *evlist, char *evsel_name, bool excl
 			match = !evsel__strcmp(evsel__leader(pos), evsel_name);
 		if (!match)
 			continue;
-		if ((!evsel__is_group_leader(pos) && !pos->merged_hybrid_group) || !pos->core.fd)
+		if ((!evsel__is_group_leader(pos) && !pos->merged_hybrid_group) ||
+		    !pos->core.fd || evsel__is_bperf(pos))
 			continue;
 		if (excl_dummy && evsel__is_dummy_event(pos))
 			continue;
@@ -847,7 +849,8 @@ static void __evlist__enable(struct evlist *evlist, char *evsel_name, bool excl_
 			match = !evsel__strcmp(evsel__leader(pos), evsel_name);
 		if (!match)
 			continue;
-		if ((!evsel__is_group_leader(pos) && !pos->merged_hybrid_group) || !pos->core.fd)
+		if ((!evsel__is_group_leader(pos) && !pos->merged_hybrid_group) ||
+		    !pos->core.fd || evsel__is_bperf(pos))
 			continue;
 		if (excl_dummy && evsel__is_dummy_event(pos))
 			continue;
@@ -859,7 +862,8 @@ static void __evlist__enable(struct evlist *evlist, char *evsel_name, bool excl_
 			match = !evsel__strcmp(evsel__leader(pos), evsel_name);
 		if (!match)
 			continue;
-		if ((!evsel__is_group_leader(pos) && !pos->merged_hybrid_group) || !pos->core.fd)
+		if ((!evsel__is_group_leader(pos) && !pos->merged_hybrid_group) ||
+		    !pos->core.fd || evsel__is_bperf(pos))
 			continue;
 		if (excl_dummy && evsel__is_dummy_event(pos))
 			continue;
@@ -1403,6 +1407,9 @@ int evlist__apply_filters(struct evlist *evlist, struct evsel **err_evsel,
 	int err = 0;
 
 	evlist__for_each_entry(evlist, evsel) {
+		if (!evsel->core.fd)
+			continue;
+
 		/*
 		 * filters only work for tracepoint event, which doesn't have cpu limit.
 		 * So evlist and evsel should always be same.
diff --git a/tools/perf/util/evsel.c b/tools/perf/util/evsel.c
index d89087e295dc..e0f3ca79c9cc 100644
--- a/tools/perf/util/evsel.c
+++ b/tools/perf/util/evsel.c
@@ -477,6 +477,8 @@ static void evsel__init(struct evsel *evsel,
 	evsel->alternate_hw_config = PERF_COUNT_HW_MAX;
 	evsel->script_output_type = -1; // FIXME: OUTPUT_TYPE_UNSET, see builtin-script.c
 	evsel->probe_type = PROBE__UNKNOWN;
+	evsel->bperf_leader_prog_fd = -1;
+	evsel->bperf_leader_link_fd = -1;
 }
 
 struct evsel *evsel__new_idx(struct perf_event_attr *attr, int idx)
@@ -557,6 +559,7 @@ struct evsel *evsel__clone(struct evsel *orig)
 	evsel->core.requires_cpu = orig->core.requires_cpu;
 	evsel->core.is_pmu_core = orig->core.is_pmu_core;
 	evsel->core.is_pmu_uncore = orig->core.is_pmu_uncore;
+	evsel->core.reads_only_on_cpu_idx0 = orig->core.reads_only_on_cpu_idx0;
 
 	if (orig->name) {
 		evsel->name = strdup(orig->name);
@@ -4810,7 +4813,7 @@ static int store_evsel_ids(struct evsel *evsel, struct evlist *evlist)
 {
 	int cpu_map_idx, thread;
 
-	if (evsel__is_retire_lat(evsel) ||
+	if (evsel__is_retire_lat(evsel) || evsel__is_bperf(evsel) ||
 	    perf_pmu__kind(evsel->pmu) != PERF_PMU_KIND_PE) {
 		struct xyarray *sample_id = evsel->core.sample_id;
 
@@ -4833,6 +4836,9 @@ static int store_evsel_ids(struct evsel *evsel, struct evlist *evlist)
 		return 0;
 	}
 
+	if (!evsel->core.fd)
+		return 0;
+
 	for (cpu_map_idx = 0; cpu_map_idx < xyarray__max_x(evsel->core.fd); cpu_map_idx++) {
 		for (thread = 0; thread < xyarray__max_y(evsel->core.fd);
 		     thread++) {
-- 
2.56.1.750.gf70dc682cf-goog


^ permalink raw reply	[flat|nested] 15+ messages in thread

* [PATCH v1 10/13] perf bpf-filter: Fix bpf_link leak by using PERF_EVENT_IOC_SET_BPF
  2026-11-23  7:19 [PATCH v1 00/13] perf fixes: off-cpu, stat, tool PMU, bperf, and bpf-filter fixes Ian Rogers
                   ` (8 preceding siblings ...)
  2026-11-23  7:19 ` [PATCH v1 09/13] perf stat: Fix --bpf-counters with non-bperf, hybrid, and mixed events Ian Rogers
@ 2026-11-23  7:19 ` Ian Rogers
  2026-11-23  7:19 ` [PATCH v1 11/13] perf bpf-filter: Copy bpf_filters in evsel__clone() and close on evsel__close() Ian Rogers
                   ` (2 subsequent siblings)
  12 siblings, 0 replies; 15+ messages in thread
From: Ian Rogers @ 2026-11-23  7:19 UTC (permalink / raw)
  To: Peter Zijlstra, Ingo Molnar, Arnaldo Carvalho de Melo,
	Namhyung Kim, Jiri Olsa, Ian Rogers, Adrian Hunter, James Clark
  Cc: Howard Chu, Thomas Falcon, Song Liu, linux-perf-users, linux-kernel

In perf_bpf_filter__prepare(), the unpinned filter path attaches
skel->progs.perf_sample_filter to each FD(evsel, x, y) using
bpf_program__attach_perf_event_opts() and ignores the returned
struct bpf_link *, leaking the allocated struct bpf_link_perf and its
BPF_PERF_EVENT link fd.

Furthermore, bpf_program__attach_perf_event_opts() is designed for
callers that transfer ownership of the perf_event fd to the returned
bpf_link: when bpf_link__destroy() is called, bpf_link_perf_detach()
unconditionally disables and closes perf_link->perf_event_fd. Because
evsel->core.fd owns FD(evsel, x, y) and closes them in evlist__close(),
destroying the returned bpf_link would double-close the perf_event file
descriptors.

Fix this by attaching the program directly with
ioctl(FD(evsel, x, y), PERF_EVENT_IOC_SET_BPF, fd), matching the pinned
filter path right above it in perf_bpf_filter__prepare(). In the
kernel, PERF_EVENT_IOC_SET_BPF takes a reference on the BPF program and
_free_event() -> perf_event_free_bpf_prog() automatically detaches and
releases it when the perf_event fd is closed. This also avoids enabling
the event prematurely, allowing pe_opts (.dont_enable = true) and the
LIBBPF_CURRENT_VERSION_GEQ(1, 7) guard to be dropped.

Before (built with EXTRA_CFLAGS="-fsanitize=address"):
  # perf record -e cycles --filter 'period > 1000' -- true
  [ perf record: Woken up 1 times to write data ]
  [ perf record: Captured and wrote 0.024 MB perf.data ]

  =================================================================
  ==51328==ERROR: LeakSanitizer: detected memory leaks

  Direct leak of 1568 byte(s) in 28 object(s) allocated from:
      #0 0x7ffbe76ef24f in calloc (/lib64/libasan.so.8+0xef24f)
      #1 0x625df7 in bpf_program__attach_perf_event_opts (tools/perf/perf+0x625df7)
      #2 0xbeddc0 in perf_bpf_filter__prepare util/bpf-filter.c:507
      #3 0x8f3def in evlist__apply_filters util/evlist.c:1421
      #4 0x44bbcf in record__open tools/perf/builtin-record.c:1469
      #5 0x453f9e in __cmd_record tools/perf/builtin-record.c:2594
      #6 0x45dadb in cmd_record tools/perf/builtin-record.c:4427
      #7 0x5df56b in run_builtin tools/perf/perf.c:383
      #8 0x5dfa0e in handle_internal_command tools/perf/perf.c:436
      #9 0x5dfddc in run_argv tools/perf/perf.c:480
      #10 0x5e0333 in main tools/perf/perf.c:581

  SUMMARY: AddressSanitizer: 1568 byte(s) leaked in 28 allocation(s).

After (built with EXTRA_CFLAGS="-fsanitize=address"):
  # perf record -e cycles --filter 'period > 1000' -- true
  [ perf record: Woken up 1 times to write data ]
  [ perf record: Captured and wrote 0.024 MB perf.data ]

Reported-by: Namhyung Kim <namhyung@kernel.org>
Closes: https://lore.kernel.org/linux-perf-users/20261020053226.55936-1-namhyung@kernel.org/
Fixes: 56ec9457a4a2 ("perf bpf filter: Implement event sample filtering")
Signed-off-by: Ian Rogers <irogers@google.com>
---
 tools/perf/util/bpf-filter.c | 18 +++++-------------
 1 file changed, 5 insertions(+), 13 deletions(-)

diff --git a/tools/perf/util/bpf-filter.c b/tools/perf/util/bpf-filter.c
index 72e83ac1d6a4..506414e5c407 100644
--- a/tools/perf/util/bpf-filter.c
+++ b/tools/perf/util/bpf-filter.c
@@ -40,6 +40,7 @@
  * The 'dropped' map is to keep how many samples it dropped by the filter and
  * it will be reported as lost samples.
  */
+#include <errno.h>
 #include <stdlib.h>
 #include <fcntl.h>
 #include <sys/ioctl.h>
@@ -423,16 +424,8 @@ int perf_bpf_filter__prepare(struct evsel *evsel, struct target *target)
 {
 	int i, x, y, fd, ret;
 	struct sample_filter_bpf *skel = NULL;
-	struct bpf_program *prog;
-	struct bpf_link *link;
 	struct perf_bpf_filter_entry *entry;
 	bool needs_idx_hash = !target__has_cpu(target);
-#if LIBBPF_CURRENT_VERSION_GEQ(1, 7)
-	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts,
-			    .dont_enable = true);
-#else
-	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
-#endif
 
 	entry = calloc(MAX_FILTERS, sizeof(*entry));
 	if (entry == NULL)
@@ -501,14 +494,13 @@ int perf_bpf_filter__prepare(struct evsel *evsel, struct target *target)
 		goto err;
 	}
 
-	prog = skel->progs.perf_sample_filter;
+	fd = bpf_program__fd(skel->progs.perf_sample_filter);
 	for (x = 0; x < xyarray__max_x(evsel->core.fd); x++) {
 		for (y = 0; y < xyarray__max_y(evsel->core.fd); y++) {
-			link = bpf_program__attach_perf_event_opts(prog, FD(evsel, x, y),
-								   &pe_opts);
-			if (IS_ERR(link)) {
+			ret = ioctl(FD(evsel, x, y), PERF_EVENT_IOC_SET_BPF, fd);
+			if (ret < 0) {
+				ret = -errno;
 				pr_err("Failed to attach perf sample-filter program\n");
-				ret = PTR_ERR(link);
 				goto err;
 			}
 		}
-- 
2.56.1.750.gf70dc682cf-goog


^ permalink raw reply	[flat|nested] 15+ messages in thread

* [PATCH v1 11/13] perf bpf-filter: Copy bpf_filters in evsel__clone() and close on evsel__close()
  2026-11-23  7:19 [PATCH v1 00/13] perf fixes: off-cpu, stat, tool PMU, bperf, and bpf-filter fixes Ian Rogers
                   ` (9 preceding siblings ...)
  2026-11-23  7:19 ` [PATCH v1 10/13] perf bpf-filter: Fix bpf_link leak by using PERF_EVENT_IOC_SET_BPF Ian Rogers
@ 2026-11-23  7:19 ` Ian Rogers
  2026-11-23  7:19 ` [PATCH v1 12/13] perf bpf-filter: Support BPF sample filters on tracepoint events Ian Rogers
  2026-11-23  7:19 ` [PATCH v1 13/13] perf parse-events: Route non-field tracepoint filter terms to BPF filter Ian Rogers
  12 siblings, 0 replies; 15+ messages in thread
From: Ian Rogers @ 2026-11-23  7:19 UTC (permalink / raw)
  To: Peter Zijlstra, Ingo Molnar, Arnaldo Carvalho de Melo,
	Namhyung Kim, Jiri Olsa, Ian Rogers, Adrian Hunter, James Clark
  Cc: Howard Chu, Thomas Falcon, Song Liu, linux-perf-users, linux-kernel

evsel__clone() copies evsel->filter for tracepoint/hardware filters, but
left evsel->bpf_filters empty on cloned evsels. When --for-each-cgroup
clones template evsels per cgroup, the cloned evsels lost their parsed
BPF filter expressions and ran unfiltered. Add perf_bpf_filter__copy() to
deep-copy the BPF filter expression list (including OR-group children,
which perf_bpf_filter__destroy() also leaked).

In addition, separate runtime skeleton/pinned-map teardown into
perf_bpf_filter__close() (without freeing the parsed filter expressions
or another evsel's pinned_filters entries) and call it in evsel__close()
so repeated runs (such as 'perf stat -r N') release the closed FDs' BPF
filter state and attach cleanly on subsequent runs.

Fixes: 56ec9457a4a2 ("perf bpf filter: Implement event sample filtering")
Signed-off-by: Ian Rogers <irogers@google.com>
---
 tools/perf/util/bpf-filter.c | 57 ++++++++++++++++++++++++++++++++++--
 tools/perf/util/bpf-filter.h | 10 +++++++
 tools/perf/util/evlist.c     |  2 ++
 tools/perf/util/evsel.c      |  4 +++
 4 files changed, 70 insertions(+), 3 deletions(-)

diff --git a/tools/perf/util/bpf-filter.c b/tools/perf/util/bpf-filter.c
index 506414e5c407..affb75e7ff85 100644
--- a/tools/perf/util/bpf-filter.c
+++ b/tools/perf/util/bpf-filter.c
@@ -515,6 +515,8 @@ int perf_bpf_filter__prepare(struct evsel *evsel, struct target *target)
 		struct pinned_filter_idx *pfi, *tmp;
 
 		list_for_each_entry_safe(pfi, tmp, &pinned_filters, list) {
+			if (pfi->evsel != evsel)
+				continue;
 			destroy_idx_hash(pfi);
 			list_del(&pfi->list);
 			free(pfi);
@@ -524,22 +526,71 @@ int perf_bpf_filter__prepare(struct evsel *evsel, struct target *target)
 	return ret;
 }
 
-int perf_bpf_filter__destroy(struct evsel *evsel)
+static void free_filter_expr_list(struct list_head *head)
 {
 	struct perf_bpf_filter_expr *expr, *tmp;
-	struct pinned_filter_idx *pfi, *pos;
+	struct perf_bpf_filter_expr *grp, *gtmp;
 
-	list_for_each_entry_safe(expr, tmp, &evsel->bpf_filters, list) {
+	list_for_each_entry_safe(expr, tmp, head, list) {
+		list_for_each_entry_safe(grp, gtmp, &expr->groups, list) {
+			list_del(&grp->list);
+			free(grp);
+		}
 		list_del(&expr->list);
 		free(expr);
 	}
+}
+
+int perf_bpf_filter__copy(struct list_head *dst, const struct list_head *src)
+{
+	const struct perf_bpf_filter_expr *expr, *grp;
+
+	list_for_each_entry(expr, src, list) {
+		struct perf_bpf_filter_expr *copy;
+
+		copy = perf_bpf_filter_expr__new(expr->term, expr->part,
+						 expr->op, expr->val);
+		if (!copy)
+			goto err;
+		list_add_tail(&copy->list, dst);
+
+		list_for_each_entry(grp, &expr->groups, list) {
+			struct perf_bpf_filter_expr *gcopy;
+
+			gcopy = perf_bpf_filter_expr__new(grp->term, grp->part,
+							  grp->op, grp->val);
+			if (!gcopy)
+				goto err;
+			list_add_tail(&gcopy->list, &copy->groups);
+		}
+	}
+	return 0;
+
+err:
+	free_filter_expr_list(dst);
+	return -ENOMEM;
+}
+
+void perf_bpf_filter__close(struct evsel *evsel)
+{
+	struct pinned_filter_idx *pfi, *pos;
+
 	sample_filter_bpf__destroy(evsel->bpf_skel);
+	evsel->bpf_skel = NULL;
 
 	list_for_each_entry_safe(pfi, pos, &pinned_filters, list) {
+		if (pfi->evsel != evsel)
+			continue;
 		destroy_idx_hash(pfi);
 		list_del(&pfi->list);
 		free(pfi);
 	}
+}
+
+int perf_bpf_filter__destroy(struct evsel *evsel)
+{
+	free_filter_expr_list(&evsel->bpf_filters);
+	perf_bpf_filter__close(evsel);
 	return 0;
 }
 
diff --git a/tools/perf/util/bpf-filter.h b/tools/perf/util/bpf-filter.h
index 818c554b91b2..cf016174bc5b 100644
--- a/tools/perf/util/bpf-filter.h
+++ b/tools/perf/util/bpf-filter.h
@@ -28,7 +28,9 @@ struct perf_bpf_filter_expr *perf_bpf_filter_expr__new(enum perf_bpf_filter_term
 						       enum perf_bpf_filter_op op,
 						       unsigned long val);
 int perf_bpf_filter__parse(struct list_head *expr_head, const char *str);
+int perf_bpf_filter__copy(struct list_head *dst, const struct list_head *src);
 int perf_bpf_filter__prepare(struct evsel *evsel, struct target *target);
+void perf_bpf_filter__close(struct evsel *evsel);
 int perf_bpf_filter__destroy(struct evsel *evsel);
 u64 perf_bpf_filter__lost_count(struct evsel *evsel);
 int perf_bpf_filter__pin(void);
@@ -45,11 +47,19 @@ static inline int perf_bpf_filter__parse(struct list_head *expr_head __maybe_unu
 		"\tPlease make sure to build with libbpf and BPF skeleton.\n");
 	return -EOPNOTSUPP;
 }
+static inline int perf_bpf_filter__copy(struct list_head *dst __maybe_unused,
+					const struct list_head *src __maybe_unused)
+{
+	return 0;
+}
 static inline int perf_bpf_filter__prepare(struct evsel *evsel __maybe_unused,
 					   struct target *target __maybe_unused)
 {
 	return -EOPNOTSUPP;
 }
+static inline void perf_bpf_filter__close(struct evsel *evsel __maybe_unused)
+{
+}
 static inline int perf_bpf_filter__destroy(struct evsel *evsel __maybe_unused)
 {
 	return -EOPNOTSUPP;
diff --git a/tools/perf/util/evlist.c b/tools/perf/util/evlist.c
index 638d501a7531..5bcb5d0905ea 100644
--- a/tools/perf/util/evlist.c
+++ b/tools/perf/util/evlist.c
@@ -1708,6 +1708,8 @@ void evlist__close(struct evlist *evlist)
 	}
 
 	evlist__for_each_entry_reverse(evlist, evsel) {
+		if (!evsel__is_bpf(evsel))
+			perf_bpf_filter__close(evsel);
 		perf_evsel__free_fd(&evsel->core);
 		perf_evsel__free_id(&evsel->core);
 	}
diff --git a/tools/perf/util/evsel.c b/tools/perf/util/evsel.c
index e0f3ca79c9cc..f36c9b746c84 100644
--- a/tools/perf/util/evsel.c
+++ b/tools/perf/util/evsel.c
@@ -581,6 +581,8 @@ struct evsel *evsel__clone(struct evsel *orig)
 		if (evsel->filter == NULL)
 			goto out_err;
 	}
+	if (perf_bpf_filter__copy(&evsel->bpf_filters, &orig->bpf_filters) < 0)
+		goto out_err;
 	if (orig->metric_id) {
 		evsel->metric_id = strdup(orig->metric_id);
 		if (evsel->metric_id == NULL)
@@ -3261,6 +3263,8 @@ void evsel__close(struct evsel *evsel)
 {
 	if (evsel__is_retire_lat(evsel))
 		evsel__tpebs_close(evsel);
+	if (!evsel__is_bpf(evsel))
+		perf_bpf_filter__close(evsel);
 	perf_evsel__close(&evsel->core);
 	perf_evsel__free_id(&evsel->core);
 }
-- 
2.56.1.750.gf70dc682cf-goog


^ permalink raw reply	[flat|nested] 15+ messages in thread

* [PATCH v1 12/13] perf bpf-filter: Support BPF sample filters on tracepoint events
  2026-11-23  7:19 [PATCH v1 00/13] perf fixes: off-cpu, stat, tool PMU, bperf, and bpf-filter fixes Ian Rogers
                   ` (10 preceding siblings ...)
  2026-11-23  7:19 ` [PATCH v1 11/13] perf bpf-filter: Copy bpf_filters in evsel__clone() and close on evsel__close() Ian Rogers
@ 2026-11-23  7:19 ` Ian Rogers
  2026-11-23  7:19 ` [PATCH v1 13/13] perf parse-events: Route non-field tracepoint filter terms to BPF filter Ian Rogers
  12 siblings, 0 replies; 15+ messages in thread
From: Ian Rogers @ 2026-11-23  7:19 UTC (permalink / raw)
  To: Peter Zijlstra, Ingo Molnar, Arnaldo Carvalho de Melo,
	Namhyung Kim, Jiri Olsa, Ian Rogers, Adrian Hunter, James Clark
  Cc: Howard Chu, Thomas Falcon, Song Liu, linux-perf-users, linux-kernel

Commit 466db4275edd ("perf parse-events: Add parse_uid_filter helper")
updated set_filter() to route non-tracepoint filter terms (such as uid
and gid) on PERF_TYPE_TRACEPOINT events to evsel->bpf_filters instead
of the ftrace tracepoint predicate filter.

However, in the kernel's __perf_event_set_bpf_prog()
(kernel/events/core.c), attaching a BPF program to a perf_event fd
branches on perf_event_is_tracing(event):
- Non-tracing events (hardware PMU, software events, breakpoints) call
  perf_event_set_bpf_handler(), which requires BPF_PROG_TYPE_PERF_EVENT
  (SEC("perf_event")).
- Tracepoint events (event->pmu == &perf_tracepoint) reject
  BPF_PROG_TYPE_PERF_EVENT with -EINVAL and instead require
  BPF_PROG_TYPE_TRACEPOINT (SEC("tracepoint")), which is attached to
  event->tp_event->prog_array and executed in
  perf_trace_run_bpf_submit() before perf_tp_event(), dropping the
  sample if the BPF program returns 0. Furthermore, the
  bpf_cast_to_kern_ctx() kfunc is only permitted in
  BPF_PROG_TYPE_PERF_EVENT programs.

Add SEC("tracepoint") int perf_tp_sample_filter(void *ctx) in
sample_filter.bpf.c to evaluate context-independent filter terms (uid,
gid, tid, cpu, time, cgroup) using BPF helpers without calling
bpf_cast_to_kern_ctx(), guarding bpf_get_current_cgroup_id() with CO-RE
for !CONFIG_CGROUPS kernels. When preparing a BPF filter on a
PERF_TYPE_TRACEPOINT evsel, autoload perf_tp_sample_filter instead of
perf_sample_filter and attach it once to the shared trace_event_call.
Check CAP_SYS_ADMIN || (CAP_BPF && CAP_PERFMON) when deciding whether
the caller can load BPF filter programs directly.

Because perf_bpf_filter__pin() and perf_bpf_filter__unpin() only load
perf_sample_filter and disable autoload on perf_tp_sample_filter,
introduce pin_filter_object() and unpin_filter_object() to pin/unpin the
maps and only the loaded perf_sample_filter program.

Fixes: 466db4275edd ("perf parse-events: Add parse_uid_filter helper")
Signed-off-by: Ian Rogers <irogers@google.com>
---
 tools/perf/util/bpf-filter.c                 | 158 ++++++++++++++++---
 tools/perf/util/bpf_skel/sample_filter.bpf.c | 101 ++++++++++++
 2 files changed, 238 insertions(+), 21 deletions(-)

diff --git a/tools/perf/util/bpf-filter.c b/tools/perf/util/bpf-filter.c
index affb75e7ff85..0a07429642be 100644
--- a/tools/perf/util/bpf-filter.c
+++ b/tools/perf/util/bpf-filter.c
@@ -41,8 +41,10 @@
  * it will be reported as lost samples.
  */
 #include <errno.h>
+#include <stdio.h>
 #include <stdlib.h>
 #include <fcntl.h>
+#include <unistd.h>
 #include <sys/ioctl.h>
 #include <sys/stat.h>
 
@@ -120,19 +122,36 @@ static const struct perf_sample_info *get_sample_info(enum perf_bpf_filter_term
 	return NULL;
 }
 
+static bool can_load_bpf_filter(void)
+{
+	return perf_cap__capable(CAP_SYS_ADMIN) ||
+	       (perf_cap__capable(CAP_BPF) && perf_cap__capable(CAP_PERFMON));
+}
+
 static int check_sample_flags(struct evsel *evsel, struct perf_bpf_filter_expr *expr)
 {
 	const struct perf_sample_info *info;
 
-	if (expr->term >= PBF_TERM_SAMPLE_START && expr->term <= PBF_TERM_SAMPLE_END &&
-	    (evsel->core.attr.sample_type & (1 << (expr->term - PBF_TERM_SAMPLE_START))))
-		return 0;
-
 	if (expr->term == PBF_TERM_UID || expr->term == PBF_TERM_GID) {
 		/* Not dependent on the sample_type as computed from a BPF helper. */
 		return 0;
 	}
 
+	if (evsel->core.attr.type == PERF_TYPE_TRACEPOINT) {
+		if (expr->term == PBF_TERM_TID || expr->term == PBF_TERM_CPU ||
+		    expr->term == PBF_TERM_TIME || expr->term == PBF_TERM_CGROUP)
+			return 0;
+		if (expr->op != PBF_OP_GROUP_BEGIN) {
+			pr_err("Error: %s tracepoint event does not support BPF sample term %d\n",
+			       evsel__name(evsel), expr->term);
+			return -1;
+		}
+	}
+
+	if (expr->term >= PBF_TERM_SAMPLE_START && expr->term <= PBF_TERM_SAMPLE_END &&
+	    (evsel->core.attr.sample_type & (1 << (expr->term - PBF_TERM_SAMPLE_START))))
+		return 0;
+
 	if (expr->op == PBF_OP_GROUP_BEGIN) {
 		struct perf_bpf_filter_expr *group;
 
@@ -426,6 +445,11 @@ int perf_bpf_filter__prepare(struct evsel *evsel, struct target *target)
 	struct sample_filter_bpf *skel = NULL;
 	struct perf_bpf_filter_entry *entry;
 	bool needs_idx_hash = !target__has_cpu(target);
+	bool is_tracepoint = (evsel->core.attr.type == PERF_TYPE_TRACEPOINT);
+	bool can_load = can_load_bpf_filter();
+
+	if (evsel->bpf_skel)
+		return 0;
 
 	entry = calloc(MAX_FILTERS, sizeof(*entry));
 	if (entry == NULL)
@@ -437,7 +461,13 @@ int perf_bpf_filter__prepare(struct evsel *evsel, struct target *target)
 		goto err;
 	}
 
-	if (needs_idx_hash && geteuid() != 0) {
+	if (is_tracepoint && !can_load) {
+		pr_err("Error: Tracepoint BPF filter requires CAP_BPF and CAP_PERFMON (or CAP_SYS_ADMIN)\n");
+		ret = -EPERM;
+		goto err;
+	}
+
+	if (needs_idx_hash && !can_load) {
 		int zero = 0;
 
 		/* The filters map is shared among other processes */
@@ -477,8 +507,17 @@ int perf_bpf_filter__prepare(struct evsel *evsel, struct target *target)
 		return 0;
 	}
 
-	skel = sample_filter_bpf__open_and_load();
+	skel = sample_filter_bpf__open();
 	if (!skel) {
+		ret = -errno;
+		pr_err("Failed to open perf sample-filter BPF skeleton\n");
+		goto err;
+	}
+
+	bpf_program__set_autoload(skel->progs.perf_sample_filter, !is_tracepoint);
+	bpf_program__set_autoload(skel->progs.perf_tp_sample_filter, is_tracepoint);
+
+	if (sample_filter_bpf__load(skel) < 0) {
 		ret = -errno;
 		pr_err("Failed to load perf sample-filter BPF skeleton\n");
 		goto err;
@@ -494,14 +533,32 @@ int perf_bpf_filter__prepare(struct evsel *evsel, struct target *target)
 		goto err;
 	}
 
-	fd = bpf_program__fd(skel->progs.perf_sample_filter);
-	for (x = 0; x < xyarray__max_x(evsel->core.fd); x++) {
-		for (y = 0; y < xyarray__max_y(evsel->core.fd); y++) {
-			ret = ioctl(FD(evsel, x, y), PERF_EVENT_IOC_SET_BPF, fd);
-			if (ret < 0) {
-				ret = -errno;
-				pr_err("Failed to attach perf sample-filter program\n");
-				goto err;
+	if (is_tracepoint) {
+		/*
+		 * For PERF_TYPE_TRACEPOINT, PERF_EVENT_IOC_SET_BPF attaches the
+		 * BPF program to event->tp_event->prog_array on the shared
+		 * trace_event_call, which perf_trace_run_bpf_submit() executes
+		 * for all CPUs and tasks before iterating the per-CPU perf
+		 * events. Attach once on the first FD so tp_event->prog_array
+		 * does not get duplicate copies for each per-CPU FD.
+		 */
+		fd = bpf_program__fd(skel->progs.perf_tp_sample_filter);
+		ret = ioctl(FD(evsel, 0, 0), PERF_EVENT_IOC_SET_BPF, fd);
+		if (ret < 0) {
+			ret = -errno;
+			pr_err("Failed to attach perf tracepoint sample-filter program\n");
+			goto err;
+		}
+	} else {
+		fd = bpf_program__fd(skel->progs.perf_sample_filter);
+		for (x = 0; x < xyarray__max_x(evsel->core.fd); x++) {
+			for (y = 0; y < xyarray__max_y(evsel->core.fd); y++) {
+				ret = ioctl(FD(evsel, x, y), PERF_EVENT_IOC_SET_BPF, fd);
+				if (ret < 0) {
+					ret = -errno;
+					pr_err("Failed to attach perf sample-filter program\n");
+					goto err;
+				}
 			}
 		}
 	}
@@ -649,7 +706,7 @@ static bool check_bpf_filter_capable(void)
 {
 	int fd;
 
-	if (perf_cap__capable(CAP_BPF))
+	if (can_load_bpf_filter())
 		return true;
 
 	/* Check if root already pinned the filter programs and maps */
@@ -659,7 +716,7 @@ static bool check_bpf_filter_capable(void)
 		return true;
 	}
 
-	pr_err("Error: BPF filter only works for users with the CAP_BPF capability!\n"
+	pr_err("Error: BPF filter requires CAP_BPF and CAP_PERFMON (or CAP_SYS_ADMIN)!\n"
 	       "\tPlease run 'perf record --setup-filter pin' as root first.\n");
 
 	return false;
@@ -684,6 +741,55 @@ int perf_bpf_filter__parse(struct list_head *expr_head, const char *str)
 	return ret;
 }
 
+/*
+ * perf_bpf_filter__pin() and perf_bpf_filter__unpin() only load
+ * perf_sample_filter and disable autoload on other programs in the skeleton
+ * (such as perf_tp_sample_filter). While libbpf's bpf_object__pin_maps() skips
+ * maps that were not created, bpf_object__pin_programs() and
+ * bpf_object__unpin_programs() iterate over every program in skel->obj without
+ * checking whether autoload was enabled and fail with -EINVAL when a program
+ * was not loaded. Pin and unpin the maps and the loaded perf_sample_filter
+ * program explicitly instead of calling bpf_object__pin() / bpf_object__unpin().
+ */
+static int pin_filter_object(struct sample_filter_bpf *skel, const char *path)
+{
+	char *prog_path = NULL;
+	int ret;
+
+	ret = bpf_object__pin_maps(skel->obj, path);
+	if (ret < 0)
+		return ret;
+
+	if (asprintf(&prog_path, "%s/perf_sample_filter", path) < 0) {
+		bpf_object__unpin_maps(skel->obj, path);
+		return -ENOMEM;
+	}
+
+	ret = bpf_program__pin(skel->progs.perf_sample_filter, prog_path);
+	if (ret < 0)
+		bpf_object__unpin_maps(skel->obj, path);
+
+	free(prog_path);
+	return ret;
+}
+
+static int unpin_filter_object(struct sample_filter_bpf *skel, const char *path)
+{
+	char *prog_path = NULL;
+	int ret, map_ret;
+
+	if (asprintf(&prog_path, "%s/perf_sample_filter", path) < 0) {
+		bpf_object__unpin_maps(skel->obj, path);
+		return -ENOMEM;
+	}
+
+	ret = bpf_program__unpin(skel->progs.perf_sample_filter, prog_path);
+	free(prog_path);
+
+	map_ret = bpf_object__unpin_maps(skel->obj, path);
+	return ret < 0 ? ret : map_ret;
+}
+
 int perf_bpf_filter__pin(void)
 {
 	struct sample_filter_bpf *skel;
@@ -698,6 +804,7 @@ int perf_bpf_filter__pin(void)
 	}
 
 	/* pinned program will use pid-hash */
+	bpf_program__set_autoload(skel->progs.perf_tp_sample_filter, false);
 	bpf_map__set_max_entries(skel->maps.filters, MAX_FILTERS);
 	bpf_map__set_max_entries(skel->maps.event_hash, MAX_EVT_HASH);
 	bpf_map__set_max_entries(skel->maps.idx_hash, MAX_IDX_HASH);
@@ -717,7 +824,7 @@ int perf_bpf_filter__pin(void)
 		goto err;
 	}
 
-	ret = bpf_object__pin(skel->obj, path);
+	ret = pin_filter_object(skel, path);
 	if (ret < 0) {
 		pr_err("Failed to pin BPF filter objects\n");
 		goto err;
@@ -726,8 +833,8 @@ int perf_bpf_filter__pin(void)
 	/* setup access permissions for the pinned objects */
 	dir_fd = open(path, O_PATH);
 	if (dir_fd < 0) {
-		bpf_object__unpin(skel->obj, path);
-		ret = dir_fd;
+		ret = -errno;
+		unpin_filter_object(skel, path);
 		goto err;
 	}
 
@@ -770,6 +877,8 @@ int perf_bpf_filter__pin(void)
 
 err_close:
 	close(dir_fd);
+	if (ret < 0)
+		unpin_filter_object(skel, path);
 
 err:
 	free(path);
@@ -783,13 +892,20 @@ int perf_bpf_filter__unpin(void)
 	char *path = NULL;
 	int ret = -1;
 
-	skel = sample_filter_bpf__open_and_load();
+	skel = sample_filter_bpf__open();
 	if (!skel) {
 		ret = -errno;
 		pr_err("Failed to open perf sample-filter BPF skeleton\n");
 		goto err;
 	}
 
+	bpf_program__set_autoload(skel->progs.perf_tp_sample_filter, false);
+	if (sample_filter_bpf__load(skel) < 0) {
+		ret = -errno;
+		pr_err("Failed to load perf sample-filter BPF skeleton\n");
+		goto err;
+	}
+
 	if (asprintf(&path, "%s/fs/bpf/%s", sysfs__mountpoint(),
 		     PERF_BPF_FILTER_PIN_PATH) < 0) {
 		ret = -errno;
@@ -797,7 +913,7 @@ int perf_bpf_filter__unpin(void)
 		goto err;
 	}
 
-	ret = bpf_object__unpin(skel->obj, path);
+	ret = unpin_filter_object(skel, path);
 
 err:
 	free(path);
diff --git a/tools/perf/util/bpf_skel/sample_filter.bpf.c b/tools/perf/util/bpf_skel/sample_filter.bpf.c
index 9ddac8e5cd78..ac6309728e14 100644
--- a/tools/perf/util/bpf_skel/sample_filter.bpf.c
+++ b/tools/perf/util/bpf_skel/sample_filter.bpf.c
@@ -206,6 +206,30 @@ static inline __u64 perf_get_sample(struct bpf_perf_event_data_kern *kctx,
 	return 0;
 }
 
+static __always_inline __u64 perf_get_common_sample(struct perf_bpf_filter_entry *entry)
+{
+	switch (entry->term) {
+	case PBF_TERM_TID:
+		if (entry->part)
+			return bpf_get_current_pid_tgid() >> 32;
+		return (__u32)bpf_get_current_pid_tgid();
+	case PBF_TERM_CPU:
+		return bpf_get_smp_processor_id();
+	case PBF_TERM_TIME:
+		return bpf_ktime_get_ns();
+	case PBF_TERM_CGROUP:
+		if (bpf_core_field_exists(struct task_struct, cgroups))
+			return bpf_get_current_cgroup_id();
+		return 0;
+	case PBF_TERM_UID:
+		return bpf_get_current_uid_gid() & 0xFFFFFFFF;
+	case PBF_TERM_GID:
+		return bpf_get_current_uid_gid() >> 32;
+	default:
+		return 0;
+	}
+}
+
 #define CHECK_RESULT(data, op, val)			\
 	if (!(data op val)) {				\
 		if (!in_group)				\
@@ -309,4 +333,81 @@ int perf_sample_filter(void *ctx)
 	return 0;
 }
 
+/*
+ * BPF program to be called for tracepoint perf events.
+ *
+ * For PERF_TYPE_TRACEPOINT events, the kernel's __perf_event_set_bpf_prog()
+ * rejects BPF_PROG_TYPE_PERF_EVENT and only accepts BPF_PROG_TYPE_TRACEPOINT,
+ * attaching the program to the shared trace_event_call->prog_array executed
+ * by perf_trace_run_bpf_submit() prior to perf_tp_event(). Because returning 0
+ * filters the event at trace_event_call->prog_array (affecting the
+ * trace_event_call globally while attached), tracepoint BPF filters are never
+ * pinned for unprivileged use and require CAP_BPF + CAP_PERFMON or
+ * CAP_SYS_ADMIN.
+ */
+SEC("tracepoint")
+int perf_tp_sample_filter(void *ctx)
+{
+	struct perf_bpf_filter_entry *entry;
+	__u64 sample_data;
+	int in_group = 0;
+	int group_result = 0;
+	int i, k = 0;
+	int *losts;
+
+	(void)ctx;
+	entry = bpf_map_lookup_elem(&filters, &k);
+	if (entry == NULL)
+		goto drop;
+
+	for (i = 0; i < MAX_FILTERS; i++) {
+		sample_data = perf_get_common_sample(&entry[i]);
+
+		switch (entry[i].op) {
+		case PBF_OP_EQ:
+			CHECK_RESULT(sample_data, ==, entry[i].value)
+			break;
+		case PBF_OP_NEQ:
+			CHECK_RESULT(sample_data, !=, entry[i].value)
+			break;
+		case PBF_OP_GT:
+			CHECK_RESULT(sample_data, >, entry[i].value)
+			break;
+		case PBF_OP_GE:
+			CHECK_RESULT(sample_data, >=, entry[i].value)
+			break;
+		case PBF_OP_LT:
+			CHECK_RESULT(sample_data, <, entry[i].value)
+			break;
+		case PBF_OP_LE:
+			CHECK_RESULT(sample_data, <=, entry[i].value)
+			break;
+		case PBF_OP_AND:
+			CHECK_RESULT(sample_data, &, entry[i].value)
+			break;
+		case PBF_OP_GROUP_BEGIN:
+			in_group = 1;
+			group_result = 0;
+			break;
+		case PBF_OP_GROUP_END:
+			if (group_result == 0)
+				goto drop;
+			in_group = 0;
+			break;
+		case PBF_OP_DONE:
+			return 1;
+		default:
+			break;
+		}
+	}
+	return 1;
+
+drop:
+	losts = bpf_map_lookup_elem(&dropped, &k);
+	if (losts != NULL)
+		__sync_fetch_and_add(losts, 1);
+
+	return 0;
+}
+
 char LICENSE[] SEC("license") = "Dual BSD/GPL";
-- 
2.56.1.750.gf70dc682cf-goog


^ permalink raw reply	[flat|nested] 15+ messages in thread

* [PATCH v1 13/13] perf parse-events: Route non-field tracepoint filter terms to BPF filter
  2026-11-23  7:19 [PATCH v1 00/13] perf fixes: off-cpu, stat, tool PMU, bperf, and bpf-filter fixes Ian Rogers
                   ` (11 preceding siblings ...)
  2026-11-23  7:19 ` [PATCH v1 12/13] perf bpf-filter: Support BPF sample filters on tracepoint events Ian Rogers
@ 2026-11-23  7:19 ` Ian Rogers
  12 siblings, 0 replies; 15+ messages in thread
From: Ian Rogers @ 2026-11-23  7:19 UTC (permalink / raw)
  To: Peter Zijlstra, Ingo Molnar, Arnaldo Carvalho de Melo,
	Namhyung Kim, Jiri Olsa, Ian Rogers, Adrian Hunter, James Clark
  Cc: Howard Chu, Thomas Falcon, Song Liu, linux-perf-users, linux-kernel

Commit 466db4275edd ("perf parse-events: Add parse_uid_filter helper")
only checked strstr(str, "uid") when routing tracepoint --filter strings
to evsel->bpf_filters, missing gid/tid/pid/time/cgroup BPF terms,
matching "uid" inside quoted strings or tracepoint field names, and
silently mis-evaluating tracepoint fields named "pid" when mixed with a
BPF term.

Route a tracepoint --filter to the BPF filter when it references one of
the BPF tracepoint filter terms (uid, gid, tid, pid, time, cgroup) that
is not a field of the tracepoint, looking up fields with evsel__field()
or, when built without libtraceevent, from the tracefs format file via
tp_pmu__has_field() (retaining evsel->tp_sys and evsel->tp_name
regardless of HAVE_LIBTRACEEVENT). Ignore words inside quoted string
literals, keep "cpu" as a generic ftrace field filter when used alone,
and reject filters that mix BPF terms with tracepoint fields of the same
name.

Before:
  # perf record -e kmem:mm_page_alloc --filter 'uid == 0' -- true
  libbpf: prog 'perf_sample_filter': failed to attach to perf_event FD 3: Invalid argument
  Failed to attach perf sample-filter program
  failed to set filter "BPF" on event kmem:mm_page_alloc with 22 (Invalid argument)

After:
  # perf record -e kmem:mm_page_alloc --filter 'uid == 0' -- true
  [ perf record: Woken up 1 times to write data ]
  [ perf record: Captured and wrote 0.024 MB perf.data (42 samples) ]

Fixes: 466db4275edd ("perf parse-events: Add parse_uid_filter helper")
Signed-off-by: Ian Rogers <irogers@google.com>
---
 tools/perf/Documentation/perf-record.txt |  14 +-
 tools/perf/util/evsel.c                  |   8 +-
 tools/perf/util/evsel.h                  |   2 +-
 tools/perf/util/parse-events.c           | 155 +++++++++++++++++++++--
 tools/perf/util/tp_pmu.c                 |  55 ++++++++
 tools/perf/util/tp_pmu.h                 |   1 +
 6 files changed, 216 insertions(+), 19 deletions(-)

diff --git a/tools/perf/Documentation/perf-record.txt b/tools/perf/Documentation/perf-record.txt
index 2351f7b4f5fc..e92672f45494 100644
--- a/tools/perf/Documentation/perf-record.txt
+++ b/tools/perf/Documentation/perf-record.txt
@@ -173,7 +173,19 @@ OPTIONS
 
 	A BPF filter can access the sample data and make a decision based on the
 	data.  Users need to set an appropriate sample type to use the BPF
-	filter.  BPF filters need root privilege.
+	filter.  BPF filters need CAP_BPF and CAP_PERFMON (or CAP_SYS_ADMIN, or
+	a pinned BPF filter for non-tracepoint events).  On tracepoint events,
+	BPF filters support context-independent terms ('uid', 'gid', 'tid',
+	'pid', 'cpu', 'time', 'cgroup') by attaching a
+	'BPF_PROG_TYPE_TRACEPOINT' program to the tracepoint's shared
+	'trace_event_call->prog_array', which filters the tracepoint before
+	'perf_tp_event()' runs across concurrent perf_event listeners on that
+	tracepoint.  A tracepoint filter is only treated as a BPF filter when
+	it uses one of these terms that is not a field of the tracepoint (a
+	filter only using 'cpu' remains an ftrace filter on the generic 'cpu'
+	field).  Filters mixing such BPF terms with tracepoint fields of the
+	same name (e.g. 'pid' on sched:sched_wakeup) are rejected; use separate
+	--filter options instead.
 
 	The sample data field can be specified in lower case letter.  Multiple
 	filters can be separated with comma.  For example,
diff --git a/tools/perf/util/evsel.c b/tools/perf/util/evsel.c
index f36c9b746c84..7be14596982c 100644
--- a/tools/perf/util/evsel.c
+++ b/tools/perf/util/evsel.c
@@ -589,7 +589,6 @@ struct evsel *evsel__clone(struct evsel *orig)
 			goto out_err;
 	}
 	evsel->cgrp = cgroup__get(orig->cgrp);
-#ifdef HAVE_LIBTRACEEVENT
 	if (orig->tp_sys) {
 		evsel->tp_sys = strdup(orig->tp_sys);
 		if (evsel->tp_sys == NULL)
@@ -600,6 +599,7 @@ struct evsel *evsel__clone(struct evsel *orig)
 		if (evsel->tp_name == NULL)
 			goto out_err;
 	}
+#ifdef HAVE_LIBTRACEEVENT
 	evsel->tp_format = orig->tp_format;
 #endif
 	evsel->handler = orig->handler;
@@ -670,7 +670,6 @@ struct evsel *evsel__newtp_idx(const char *sys, const char *name, int idx, bool
 	if (asprintf(&evsel->name, "%s:%s", sys, name) < 0)
 		goto out_free;
 
-#ifdef HAVE_LIBTRACEEVENT
 	evsel->tp_sys = strdup(sys);
 	if (!evsel->tp_sys)
 		goto out_free;
@@ -678,7 +677,6 @@ struct evsel *evsel__newtp_idx(const char *sys, const char *name, int idx, bool
 	evsel->tp_name = strdup(name);
 	if (!evsel->tp_name)
 		goto out_free;
-#endif
 
 	event_attr_init(&attr);
 
@@ -696,10 +694,8 @@ struct evsel *evsel__newtp_idx(const char *sys, const char *name, int idx, bool
 
 out_free:
 	zfree(&evsel->name);
-#ifdef HAVE_LIBTRACEEVENT
 	zfree(&evsel->tp_sys);
 	zfree(&evsel->tp_name);
-#endif
 	free(evsel);
 out_err:
 	return ERR_PTR(err);
@@ -2146,10 +2142,8 @@ static void evsel__exit(struct evsel *evsel)
 	perf_evsel__exit(&evsel->core);
 	zfree(&evsel->group_name);
 	zfree(&evsel->name);
-#ifdef HAVE_LIBTRACEEVENT
 	zfree(&evsel->tp_sys);
 	zfree(&evsel->tp_name);
-#endif
 	zfree(&evsel->filter);
 	zfree(&evsel->group_pmu_name);
 	zfree(&evsel->unit);
diff --git a/tools/perf/util/evsel.h b/tools/perf/util/evsel.h
index 53f3641b66e1..87b9373e7a51 100644
--- a/tools/perf/util/evsel.h
+++ b/tools/perf/util/evsel.h
@@ -64,9 +64,9 @@ struct evsel {
 		char			*name;
 		char			*group_name;
 		const char		*group_pmu_name;
-#ifdef HAVE_LIBTRACEEVENT
 		char			*tp_sys;
 		char			*tp_name;
+#ifdef HAVE_LIBTRACEEVENT
 		struct tep_event	*tp_format;
 #endif
 		char			*filter;
diff --git a/tools/perf/util/parse-events.c b/tools/perf/util/parse-events.c
index ba3e5015058c..5b284feccb08 100644
--- a/tools/perf/util/parse-events.c
+++ b/tools/perf/util/parse-events.c
@@ -4,7 +4,9 @@
 #include <linux/err.h>
 #include <linux/list_sort.h>
 #include <linux/zalloc.h>
+#include <ctype.h>
 #include <dirent.h>
+#include <string.h>
 #include <sys/ioctl.h>
 #include <sys/param.h>
 #include "cpumap.h"
@@ -2624,10 +2626,131 @@ foreach_evsel_in_last_glob(struct evlist *evlist,
 	return 0;
 }
 
-/* Will a tracepoint filter work for str or should a BPF filter be used? */
-static bool is_possible_tp_filter(const char *str)
+static bool is_filter_word_char(char c)
 {
-	return strstr(str, "uid") == NULL;
+	return isalnum((unsigned char)c) || c == '_';
+}
+
+/*
+ * Does str contain the identifier word, ignoring occurrences inside quoted
+ * string literals (e.g. prev_comm == "cpu"), cgroup path operands, and
+ * predicate argument lists?
+ */
+static bool has_filter_word(const char *str, const char *word)
+{
+	size_t len = strlen(word);
+	const char *p = str;
+
+	while (*p) {
+		const char *start, *q;
+		size_t tok_len;
+
+		if (*p == '"' || *p == '\'') {
+			char quote = *p++;
+
+			while (*p && *p != quote) {
+				if (*p == '\\' && p[1])
+					p++;
+				p++;
+			}
+			if (*p)
+				p++;
+			continue;
+		}
+		if (!is_filter_word_char(*p)) {
+			p++;
+			continue;
+		}
+		start = p;
+		while (is_filter_word_char(*p))
+			p++;
+		tok_len = (size_t)(p - start);
+		if (tok_len == len && !strncmp(start, word, len))
+			return true;
+
+		/* Skip unquoted cgroup path operands (e.g. cgroup == /test-pid). */
+		if (tok_len == 6 && !strncmp(start, "cgroup", 6)) {
+			q = p;
+			while (*q == ' ' || *q == '\t')
+				q++;
+			if (!strncmp(q, "==", 2) || !strncmp(q, "!=", 2)) {
+				q += 2;
+				while (*q == ' ' || *q == '\t')
+					q++;
+				if (*q && *q != '"' && *q != '\'') {
+					while (*q && !strchr(" \t\n,()!=>&|<", *q))
+						q++;
+					p = q;
+				}
+			}
+			continue;
+		}
+
+		/* Skip predicate argument lists (e.g. lock_held(pid)). */
+		q = p;
+		while (*q == ' ' || *q == '\t')
+			q++;
+		if (*q == '(') {
+			p = q + 1;
+			while (*p && *p != ')')
+				p++;
+			if (*p == ')')
+				p++;
+		}
+	}
+	return false;
+}
+
+static bool tp_evsel_has_field(struct evsel *evsel, const char *name)
+{
+#ifdef HAVE_LIBTRACEEVENT
+	if (evsel__field(evsel, name))
+		return true;
+#endif
+	if (evsel->tp_sys && evsel->tp_name)
+		return tp_pmu__has_field(evsel->tp_sys, evsel->tp_name, name);
+	return false;
+}
+
+/*
+ * Will a tracepoint filter work for str or should a BPF filter be used?
+ * Returns 1 for a tracepoint (ftrace) filter, 0 for a BPF filter, or a
+ * negative error when str mixes BPF-only terms with tracepoint fields that
+ * share a BPF term name (such as "pid" on sched:sched_wakeup), which a BPF
+ * filter would otherwise silently evaluate against the current task.
+ */
+static int is_possible_tp_filter(struct evsel *evsel, const char *str)
+{
+	/*
+	 * BPF terms evaluated by perf_tp_sample_filter. "cpu" is omitted as
+	 * ftrace provides a generic "cpu" field for all tracepoints (see
+	 * trace_define_generic_fields()).
+	 */
+	static const char *const bpf_tp_terms[] = {
+		"uid", "gid", "tid", "pid", "time", "cgroup",
+	};
+	const char *bpf_term = NULL, *tp_field = NULL;
+
+	for (size_t i = 0; i < ARRAY_SIZE(bpf_tp_terms); i++) {
+		if (!has_filter_word(str, bpf_tp_terms[i]))
+			continue;
+		if (tp_evsel_has_field(evsel, bpf_tp_terms[i]))
+			tp_field = bpf_tp_terms[i];
+		else if (!bpf_term)
+			bpf_term = bpf_tp_terms[i];
+	}
+	if (!bpf_term)
+		return 1;
+	if (!tp_field && has_filter_word(str, "cpu") &&
+	    tp_evsel_has_field(evsel, "cpu"))
+		tp_field = "cpu";
+	if (tp_field) {
+		pr_err("Error: filter '%s' on %s mixes BPF term '%s' with tracepoint field '%s'.\n"
+		       "Hint: use separate --filter options for tracepoint fields and BPF terms.\n",
+		       str, evsel__name(evsel), bpf_term, tp_field);
+		return -EINVAL;
+	}
+	return 0;
 }
 
 static int set_filter(struct evsel *evsel, const void *arg)
@@ -2635,6 +2758,7 @@ static int set_filter(struct evsel *evsel, const void *arg)
 	const char *str = arg;
 	int nr_addr_filters = 0;
 	struct perf_pmu *pmu;
+	int tp_filter = 0;
 
 	if (evsel == NULL) {
 		fprintf(stderr,
@@ -2642,7 +2766,12 @@ static int set_filter(struct evsel *evsel, const void *arg)
 		return -1;
 	}
 
-	if (evsel->core.attr.type == PERF_TYPE_TRACEPOINT && is_possible_tp_filter(str)) {
+	if (evsel->core.attr.type == PERF_TYPE_TRACEPOINT) {
+		tp_filter = is_possible_tp_filter(evsel, str);
+		if (tp_filter < 0)
+			return -1;
+	}
+	if (tp_filter) {
 		if (evsel__append_tp_filter(evsel, str) < 0) {
 			fprintf(stderr,
 				"not enough memory to hold filter string\n");
@@ -2680,14 +2809,20 @@ int parse_filter(const struct option *opt, const char *str,
 
 int parse_uid_filter(struct evlist *evlist, uid_t uid)
 {
-	struct option opt = {
-		.value = &evlist,
-	};
+	struct evsel *evsel;
 	char buf[128];
-	int ret;
+	int ret = 0;
 
-	snprintf(buf, sizeof(buf), "uid == %d", uid);
-	ret = parse_filter(&opt, buf, /*unset=*/0);
+	if (!evlist || evlist__nr_entries(evlist) == 0) {
+		ret = -EINVAL;
+	} else {
+		snprintf(buf, sizeof(buf), "uid == %d", uid);
+		evlist__for_each_entry(evlist, evsel) {
+			ret = perf_bpf_filter__parse(&evsel->bpf_filters, buf);
+			if (ret)
+				break;
+		}
+	}
 	if (ret) {
 		if (use_browser >= 1) {
 			/*
diff --git a/tools/perf/util/tp_pmu.c b/tools/perf/util/tp_pmu.c
index 5ac732e06841..fb3ff9435fa0 100644
--- a/tools/perf/util/tp_pmu.c
+++ b/tools/perf/util/tp_pmu.c
@@ -6,6 +6,7 @@
 #include <api/io_dir.h>
 #include <linux/kernel.h>
 #include <errno.h>
+#include <stdlib.h>
 #include <string.h>
 
 int tp_pmu__id(const char *sys, const char *name)
@@ -26,6 +27,60 @@ int tp_pmu__id(const char *sys, const char *name)
 	return id;
 }
 
+/*
+ * Does the tracefs format file of tracepoint sys:name declare a field called
+ * field? Format lines are of the form "\tfield:<type> <name>[<len>];\t...".
+ * Works without libtraceevent.
+ */
+bool tp_pmu__has_field(const char *sys, const char *name, const char *field)
+{
+	char *tp_dir = get_events_file(sys);
+	char path[PATH_MAX];
+	char *format = NULL, *line, *saveptr = NULL;
+	size_t format_size, field_len = strlen(field);
+	bool found = false;
+
+	if (!tp_dir)
+		return false;
+
+	scnprintf(path, sizeof(path), "%s/%s/format", tp_dir, name);
+	put_events_file(tp_dir);
+	if (filename__read_str(path, &format, &format_size))
+		return false;
+
+	for (line = strtok_r(format, "\n", &saveptr); line && !found;
+	     line = strtok_r(NULL, "\n", &saveptr)) {
+		char *decl = strstr(line, "field:"), *end;
+
+		if (!decl)
+			continue;
+		decl += strlen("field:");
+		end = strchr(decl, ';');
+		if (!end)
+			continue;
+		/*
+		 * Drop a trailing array suffix, e.g. "char prev_comm[16]", but
+		 * not the "[]" in the type of "__data_loc char[] name".
+		 */
+		while (end > decl && end[-1] == ' ')
+			end--;
+		if (end > decl && end[-1] == ']') {
+			while (end > decl && *end != '[')
+				end--;
+		}
+		/* The field name is the last token of the declaration. */
+		while (end > decl && end[-1] == ' ')
+			end--;
+		if ((size_t)(end - decl) >= field_len &&
+		    !strncmp(end - field_len, field, field_len) &&
+		    (end - field_len == decl || *(end - field_len - 1) == ' ' ||
+		     *(end - field_len - 1) == '*'))
+			found = true;
+	}
+	free(format);
+	return found;
+}
+
 
 int tp_pmu__for_each_tp_event(const char *sys, void *state, tp_event_callback cb)
 {
diff --git a/tools/perf/util/tp_pmu.h b/tools/perf/util/tp_pmu.h
index 30456bd6943d..a60ec0e8a176 100644
--- a/tools/perf/util/tp_pmu.h
+++ b/tools/perf/util/tp_pmu.h
@@ -8,6 +8,7 @@ typedef int (*tp_sys_callback)(void *state, const char *sys_name);
 typedef int (*tp_event_callback)(void *state, const char *sys_name, const char *evt_name);
 
 int tp_pmu__id(const char *sys, const char *name);
+bool tp_pmu__has_field(const char *sys, const char *name, const char *field);
 int tp_pmu__for_each_tp_event(const char *sys, void *state, tp_event_callback cb);
 int tp_pmu__for_each_tp_sys(void *state, tp_sys_callback cb);
 
-- 
2.56.1.750.gf70dc682cf-goog


^ permalink raw reply	[flat|nested] 15+ messages in thread

* Re: [PATCH v1 05/13] perf stat: Preserve per-evsel CPU maps across stat record and report
  2026-11-23  7:19 ` [PATCH v1 05/13] perf stat: Preserve per-evsel CPU maps across stat record and report Ian Rogers
@ 2026-11-23 17:12   ` Athira Rajeev
  0 siblings, 0 replies; 15+ messages in thread
From: Athira Rajeev @ 2026-11-23 17:12 UTC (permalink / raw)
  To: Ian Rogers
  Cc: Peter Zijlstra, Ingo Molnar, Arnaldo Carvalho de Melo,
	Namhyung Kim, Jiri Olsa, Adrian Hunter, James Clark, Howard Chu,
	Thomas Falcon, Song Liu, linux-perf-users, linux-kernel



> On 23 Nov 2026, at 12:49 PM, Ian Rogers <irogers@google.com> wrote:
> 
> Commit 6d765f5f7ec6 ("libperf evsel: Rename own_cpus to pmu_cpus") and
> commit 811082e4b668 ("perf parse-events: Support user CPUs mixed with
> threads/processes") separated an evsel's PMU cpumask (pmu_cpus) from the
> actual CPUs on which the event is opened (cpus) and taught
> __perf_evlist__propagate_maps() to collapse evsel->cpus to the "any CPU"
> (-1) map when user_requested_cpus is -1 and !evsel->requires_cpu.
> 
> However, perf_event__synthesize_event_update_cpus() continued to
> serialize evsel->core.pmu_cpus instead of evsel->core.cpus, and
> perf_event__process_event_update() only populated evsel->core.pmu_cpus
> without setting evsel->core.cpus or evsel->core.requires_cpu. This broke
> perf stat record/report (and perf script) in two ways:
> 
> 1. When recording an event opened per-CPU alongside a workload target
>   (where user_requested_cpus is -1), such as an event with a cpu= term,
>   an uncore counter, --bpf-counters, or a BPF-filtered counter,
>   PERF_RECORD_STAT events are written with concrete CPU numbers, but
>   perf stat report's perf_evlist__set_maps() collapses evsel->cpus to
>   -1 and fails with:
> 
>     $ perf stat record -e 'task-clock/cpu=0/,task-clock' -- true
>     $ perf stat report
>     Invalid CPU 0 for event task-clock/cpu=0/.

Hi Ian

Thanks for the fix, verified the fix for "perf stat report". But I have one observation when using aggregation mode.

Working case with the fix:
=======================

With the fix:

./perf stat record -e cycles/cpu=8/,cycles/cpu=9/ <workload>
./perf stat report

Perf stat report works fine
Also checked system wide.

Using -A:
=========
Before broken commits 6d765f5f7ec6 and 811082e4b668,
./perf stat record -e cycles/cpu=8/,cycles/cpu=9/ <workload>
./perf stat report -A : this was working

    ./perf stat report -A

    Performance counter stats for '/root/perf-tools-next/tools/perf/perf stat record -e cycles/cpu=8/,cycles/cpu=9/ ./stream’:  


    3,447,492,527,125      cycles/cpu=8/                                                 
    3,447,492,527,125      cycles/cpu=9/                                                          
     108.543826387 seconds time elapsed

On top of this patch, result looks like:
./perf stat report -A

 Performance counter stats for '/root/perf-tools-next/tools/perf/perf':


       2.119970008 seconds time elapsed

There are no counter line, only time elapsed. I am suspecting the change for perf_event__process_event_update needs update.
Ian,  have another query as well in the patch , adding them below.

> 
> 2. In system-wide mode (-a), per-evsel CPU restrictions such as cpu=0
>   were overwritten by the full PMU cpumask during report, causing
>   perf stat report -A to report bogus <not counted> entries on every
>   other CPU.
> 
> Fix perf_event__synthesize_event_update_cpus() to serialize
> evsel->core.cpus, and update perf_event__process_event_update() to
> populate evsel->core.cpus and set requires_cpu when the recorded CPU map
> does not use the "any CPU" (-1) placeholder. For backward compatibility
> with data files recorded by older perf binaries that wrote pmu_cpus for
> per-task (-1) counters, fall back to the "any CPU" map in
> perf_event__process_stat_event() if a -1 CPU stat event arrives for an
> evsel without -1 in its CPU map.
> 
> Update the event_update unit test and stat.sh record/report/script tests
> to cover per-evsel CPU maps on workload targets.
> 
> Fixes: 6d765f5f7ec6 ("libperf evsel: Rename own_cpus to pmu_cpus")
> Fixes: 811082e4b668 ("perf parse-events: Support user CPUs mixed with threads/processes")
> Signed-off-by: Ian Rogers <irogers@google.com>
> ---
> tools/perf/tests/event_update.c    | 43 ++++++++++++++++++++++++++----
> tools/perf/tests/shell/stat.sh     | 16 +++++++++++
> tools/perf/util/evsel.c            |  2 +-
> tools/perf/util/header.c           |  5 ++++
> tools/perf/util/stat.c             | 18 +++++++++++++
> tools/perf/util/synthetic-events.c |  7 +++--
> 6 files changed, 83 insertions(+), 8 deletions(-)
> 
> diff --git a/tools/perf/tests/event_update.c b/tools/perf/tests/event_update.c
> index 220cc0347747..bacf3c44c8e2 100644
> --- a/tools/perf/tests/event_update.c
> +++ b/tools/perf/tests/event_update.c
> @@ -1,6 +1,7 @@
> // SPDX-License-Identifier: GPL-2.0
> #include <linux/compiler.h>
> #include <perf/cpumap.h>
> +#include <perf/evlist.h>
> #include <string.h>
> #include "cpumap.h"
> #include "evlist.h"
> @@ -58,13 +59,20 @@ static int process_event_name(const struct perf_tool *tool,
> return 0;
> }
> 
> -static int process_event_cpus(const struct perf_tool *tool __maybe_unused,
> +struct event_cpus {
> + struct perf_tool tool;
> + struct evlist *evlist;
> +};
> +
> +static int process_event_cpus(const struct perf_tool *tool,
>      union perf_event *event,
>      struct perf_sample *sample __maybe_unused,
>      struct machine *machine __maybe_unused)
> {
> + struct event_cpus *tmp = container_of(tool, struct event_cpus, tool);
> struct perf_record_event_update *ev = (struct perf_record_event_update *)event;
> - struct perf_cpu_map *map;
> + struct perf_cpu_map *map, *any_cpu;
> + struct evsel *evsel;
> 
> map = cpu_map__new_data(&ev->cpus.cpus);
> 
> @@ -75,6 +83,26 @@ static int process_event_cpus(const struct perf_tool *tool __maybe_unused,
> TEST_ASSERT_VAL("wrong cpus", perf_cpu_map__cpu(map, 1).cpu == 2);
> TEST_ASSERT_VAL("wrong cpus", perf_cpu_map__cpu(map, 2).cpu == 3);
> perf_cpu_map__put(map);
> +
> + evsel = evlist__first(tmp->evlist);
> + perf_cpu_map__put(evsel->core.cpus);
> + evsel->core.cpus = NULL;
> + perf_cpu_map__put(evsel->core.pmu_cpus);
> + evsel->core.pmu_cpus = NULL;
> + evsel->core.requires_cpu = false;
> +
> + TEST_ASSERT_VAL("failed to process attr update cpus",
> + !perf_event__process_event_update(tool, event, &tmp->evlist));
> +
> + any_cpu = perf_cpu_map__new_any_cpu();
> + TEST_ASSERT_VAL("failed to allocate any_cpu map", any_cpu);
> + perf_evlist__set_maps(evlist__core(tmp->evlist), any_cpu, NULL);
> + perf_cpu_map__put(any_cpu);
> +
> + TEST_ASSERT_VAL("wrong processed cpus", perf_cpu_map__nr(evsel->core.cpus) == 3);
> + TEST_ASSERT_VAL("wrong processed cpus", perf_cpu_map__cpu(evsel->core.cpus, 0).cpu == 1);
> + TEST_ASSERT_VAL("wrong processed cpus", perf_cpu_map__cpu(evsel->core.cpus, 1).cpu == 2);
> + TEST_ASSERT_VAL("wrong processed cpus", perf_cpu_map__cpu(evsel->core.cpus, 2).cpu == 3);
> return 0;
> }
> 
> @@ -82,6 +110,7 @@ static int test__event_update(struct test_suite *test __maybe_unused, int subtes
> {
> struct evsel *evsel;
> struct event_name tmp;
> + struct event_cpus tmp_cpus;
> struct target target = {};
> struct evlist *evlist = evlist__new_default(&target, /*sample_callchains=*/false);
> 
> @@ -111,11 +140,15 @@ static int test__event_update(struct test_suite *test __maybe_unused, int subtes
> TEST_ASSERT_VAL("failed to synthesize attr update name",
> !perf_event__synthesize_event_update_name(&tmp.tool, evsel, process_event_name));
> 
> - perf_cpu_map__put(evsel->core.pmu_cpus);
> - evsel->core.pmu_cpus = perf_cpu_map__new("1,2,3");
> + perf_cpu_map__put(evsel->core.cpus);
> + evsel->core.cpus = perf_cpu_map__new("1,2,3");
> +
> + perf_tool__init(&tmp_cpus.tool, /*ordered_events=*/false);
> + tmp_cpus.evlist = evlist;
> 
> TEST_ASSERT_VAL("failed to synthesize attr update cpus",
> - !perf_event__synthesize_event_update_cpus(&tmp.tool, evsel, process_event_cpus));
> + !perf_event__synthesize_event_update_cpus(&tmp_cpus.tool, evsel,
> +  process_event_cpus));
> 
> evlist__put(evlist);
> return 0;
> diff --git a/tools/perf/tests/shell/stat.sh b/tools/perf/tests/shell/stat.sh
> index ac9e031831da..43a158ee3609 100755
> --- a/tools/perf/tests/shell/stat.sh
> +++ b/tools/perf/tests/shell/stat.sh
> @@ -77,6 +77,14 @@ test_stat_record_report() {
>     err=1
>     return
>   fi
> +  cpu=$(sed 's/[-,].*//' /sys/devices/system/cpu/online)
> +  if ! perf stat record -e "task-clock/cpu=${cpu}/,task-clock" -o - true | \
> +    perf stat report -i - 2>&1 | grep -E -q "task-clock/cpu=${cpu}/"
> +  then
> +    echo "stat record and report test [Failed per-evsel CPU]"
> +    err=1
> +    return
> +  fi
>   echo "stat record and report test [Success]"
> }
> 
> @@ -89,6 +97,14 @@ test_stat_record_script() {
>     err=1
>     return
>   fi
> +  cpu=$(sed 's/[-,].*//' /sys/devices/system/cpu/online)
> +  if ! perf stat record -e "task-clock/cpu=${cpu}/,task-clock" -o - true | \
> +    perf script -i - 2>&1 | grep -E -q "task-clock/cpu=${cpu}/"
> +  then
> +    echo "stat record and script test [Failed per-evsel CPU]"
> +    err=1
> +    return
> +  fi
>   echo "stat record and script test [Success]"
> }
> 
> diff --git a/tools/perf/util/evsel.c b/tools/perf/util/evsel.c
> index 1f96c170d277..64daef4cc345 100644
> --- a/tools/perf/util/evsel.c
> +++ b/tools/perf/util/evsel.c
> @@ -1822,7 +1822,7 @@ void evsel__config(struct evsel *evsel, const struct record_opts *opts,
> attr->exclude_user   = 1;
> }
> 
> - if (evsel->core.pmu_cpus || evsel->unit)
> + if (evsel->core.cpus || evsel->core.pmu_cpus || evsel->unit)
> evsel->core.attr.read_format |= PERF_FORMAT_ID;
> 
> /*
> diff --git a/tools/perf/util/header.c b/tools/perf/util/header.c
> index 9eec6deee190..e9af99b8c0f8 100644
> --- a/tools/perf/util/header.c
> +++ b/tools/perf/util/header.c
> @@ -5962,6 +5962,11 @@ int perf_event__process_event_update(const struct perf_tool *tool __maybe_unused
> if (map) {
> perf_cpu_map__put(evsel->core.pmu_cpus);
> evsel->core.pmu_cpus = map;
> + if (!evsel->counts) {
> + perf_cpu_map__put(evsel->core.cpus);
> + evsel->core.cpus = perf_cpu_map__get(map);

Here pmu_cpus and core.cpus will point to same data ? When evsel->counts is zero, both will carry same “perf_cpu_map” object.
So during report, the pmu_cpus will hold same contents as “cpus” , which is record opened cpu map.
But ideally pmu_cpus should be having the PMU’s cpumask ? 

Thanks
Athira

> + evsel->core.requires_cpu = !perf_cpu_map__has_any_cpu(map);
> + }
> } else
> pr_err("failed to get event_update cpus\n");
> break;
> diff --git a/tools/perf/util/stat.c b/tools/perf/util/stat.c
> index 6da3dbbde0e2..429bfc339308 100644
> --- a/tools/perf/util/stat.c
> +++ b/tools/perf/util/stat.c
> @@ -8,6 +8,7 @@
> 
> #include <linux/err.h>
> #include <linux/zalloc.h>
> +#include <perf/cpumap.h>
> 
> #include "counts.h"
> #include "cpumap.h"
> @@ -674,6 +675,23 @@ int perf_event__process_stat_event(const struct perf_tool *tool __maybe_unused,
> return -EINVAL;
> }
> cpu_map_idx = perf_cpu_map__idx(evsel__cpus(counter), (struct perf_cpu){.cpu = st->cpu});
> + if (cpu_map_idx == -1 && (s32)st->cpu == -1 && counter->counts &&
> +    evsel__nr_cpus(counter) > 0) {
> + /*
> + * Older perf tools wrote pmu_cpus instead of cpus in
> + * PERF_EVENT_UPDATE__CPUS, leaving per-task counters with a
> + * CPU list instead of the "any CPU" (-1) map used by their
> + * PERF_RECORD_STAT events.
> + */
> + struct perf_cpu_map *any_cpu = perf_cpu_map__new_any_cpu();
> +
> + if (any_cpu) {
> + perf_cpu_map__put(counter->core.cpus);
> + counter->core.cpus = any_cpu;
> + counter->core.requires_cpu = false;
> + cpu_map_idx = 0;
> + }
> + }
> if (cpu_map_idx == -1) {
> pr_err("Invalid CPU %d for event %s.\n", st->cpu, evsel__name(counter));
> return -EINVAL;
> diff --git a/tools/perf/util/synthetic-events.c b/tools/perf/util/synthetic-events.c
> index 3c8d29f27fd9..b87d15a5be6a 100644
> --- a/tools/perf/util/synthetic-events.c
> +++ b/tools/perf/util/synthetic-events.c
> @@ -2234,10 +2234,13 @@ int perf_event__synthesize_event_update_name(const struct perf_tool *tool, struc
> int perf_event__synthesize_event_update_cpus(const struct perf_tool *tool, struct evsel *evsel,
>     perf_event__handler_t process)
> {
> - struct synthesize_cpu_map_data syn_data = { .map = evsel->core.pmu_cpus };
> + struct synthesize_cpu_map_data syn_data = { .map = evsel->core.cpus };
> struct perf_record_event_update *ev;
> int err;
> 
> + if (!evsel->core.cpus)
> + return 0;
> +
> ev = cpu_map_data__alloc(&syn_data, sizeof(struct perf_event_header) + 2 * sizeof(u64));
> if (!ev)
> return -ENOMEM;
> @@ -2315,7 +2318,7 @@ int perf_event__synthesize_extra_attr(const struct perf_tool *tool, struct evlis
> }
> }
> 
> - if (evsel->core.pmu_cpus) {
> + if (evsel->core.cpus) {
> err = perf_event__synthesize_event_update_cpus(tool, evsel, process);
> if (err < 0) {
> pr_err("Couldn't synthesize evsel cpus.\n");
> -- 
> 2.56.1.750.gf70dc682cf-goog
> 
> 


^ permalink raw reply	[flat|nested] 15+ messages in thread

end of thread, other threads:[~2026-11-23 17:13 UTC | newest]

Thread overview: 15+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2026-11-23  7:19 [PATCH v1 00/13] perf fixes: off-cpu, stat, tool PMU, bperf, and bpf-filter fixes Ian Rogers
2026-11-23  7:19 ` [PATCH v1 01/13] perf off-cpu: Bound callchain length in off_cpu_write() Ian Rogers
2026-11-23  7:19 ` [PATCH v1 02/13] perf off-cpu: Fix swapped PID and TID in direct off_cpu_dump() samples Ian Rogers
2026-11-23  7:19 ` [PATCH v1 03/13] libperf evlist: Recompute CPU map when an evsel goes system wide Ian Rogers
2026-11-23  7:19 ` [PATCH v1 04/13] perf stat: Give non-perf_event_open events unique IDs for stat record Ian Rogers
2026-11-23  7:19 ` [PATCH v1 05/13] perf stat: Preserve per-evsel CPU maps across stat record and report Ian Rogers
2026-11-23 17:12   ` Athira Rajeev
2026-11-23  7:19 ` [PATCH v1 06/13] perf pmu: Don't treat tool PMU as a kernel software PMU for event grouping Ian Rogers
2026-11-23  7:19 ` [PATCH v1 07/13] perf evlist: Enable tool PMU events when starting a workload Ian Rogers
2026-11-23  7:19 ` [PATCH v1 08/13] perf stat: Respect the enabled time of exited user_time/system_time events Ian Rogers
2026-11-23  7:19 ` [PATCH v1 09/13] perf stat: Fix --bpf-counters with non-bperf, hybrid, and mixed events Ian Rogers
2026-11-23  7:19 ` [PATCH v1 10/13] perf bpf-filter: Fix bpf_link leak by using PERF_EVENT_IOC_SET_BPF Ian Rogers
2026-11-23  7:19 ` [PATCH v1 11/13] perf bpf-filter: Copy bpf_filters in evsel__clone() and close on evsel__close() Ian Rogers
2026-11-23  7:19 ` [PATCH v1 12/13] perf bpf-filter: Support BPF sample filters on tracepoint events Ian Rogers
2026-11-23  7:19 ` [PATCH v1 13/13] perf parse-events: Route non-field tracepoint filter terms to BPF filter Ian Rogers

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox

all inboxes | Powered by JetHome®