perf fixes: off-cpu, stat, tool PMU, bperf, and bpf-filter fixes
Ian Rogers
reviewercover perf fixes: off-cpu, stat, tool PMU, bperf, and bpf-filter fixes
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/[email protected]/
(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(-)
Signature · 1 line
2.56.1.750.gf70dc682cf-goog
Ian Rogers
reviewerPATCH 1/13 perf off-cpu: Bound callchain length in off_cpu_write()
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.
--- tools/perf/util/bpf_off_cpu.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
tools/perf/util/bpf_off_cpu.c +2 -2
@@ -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 ;
Signature · 1 line
2.56.1.750.gf70dc682cf-goog
Ian Rogers
reviewerPATCH 2/13 perf off-cpu: Fix swapped PID and TID in direct off_cpu_dump() samples
In reply to Ian Rogers__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().
--- tools/perf/util/bpf_skel/off_cpu.bpf.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
tools/perf/util/bpf_skel/off_cpu.bpf.c +1 -1
@@ -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) */
Signature · 1 line
2.56.1.750.gf70dc682cf-goog
Ian Rogers
reviewerPATCH 3/13 libperf evlist: Recompute CPU map when an evsel goes system wide
In reply to Ian Rogersperf_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.
--- tools/lib/perf/evlist.c | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-)
tools/lib/perf/evlist.c +10 -2
@@ -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); + } } }
Signature · 1 line
2.56.1.750.gf70dc682cf-goog
Ian Rogers
reviewerPATCH 4/13 perf stat: Give non-perf_event_open events unique IDs for stat record
In reply to Ian Rogersstore_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-clockGive 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.
--- tools/perf/util/evsel.c | 42 ++++++++++++++++++++++++++++++++++++++--- 1 file changed, 39 insertions(+), 3 deletions(-)
tools/perf/util/evsel.c +39 -3
@@ -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);
Signature · 1 line
2.56.1.750.gf70dc682cf-goog
[email protected]
AI reviewRe: [PATCH v1 04/13] perf stat: Give non-perf_event_open events unique IDs for stat record
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] perf evsel: evlist__next_synthetic_id() assigns -1ULL sample.id sentinel --
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] perf evsel: evlist__next_synthetic_id() assigns -1ULL sample.id sentinel
--
commit bf429860ca696e1f7721eda193a7577f31d0f3a5
Author: Ian Rogers <[email protected]>
perf stat: Give non-perf_event_open events unique IDs for stat record
This commit assigns unique synthetic IDs counting down from ~0ULL to events that are not opened via perf_event_open(), so that perf stat record and perf stat report can distinguish them.
Quoted 16 lines
tools/perf/util/evsel.c +8
-0@@ -4724,15 +4724,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)
tools/perf/util/evsel.c struct perf_env *evsel__env(struct evsel *evsel) · line 4744
Quoted 10 lines
tools/perf/util/evsel.c +10
-0+{ +static u64 next_synthetic_id = ~0ULL ; +u64 id; + +do { + id = next_synthetic_id--; + }while (evlist__id2sid (evlist, id)); + +return id; +}
[Severity: Medium]
Does post-decrementing next_synthetic_id from ~0ULL cause the first synthetic ID to collide with the -1ULL sentinel used for unset sample.id values?
__evsel__parse_sample() initializes data->id to -1ULL (~0ULL) and leaves it at -1ULL for non-sample events when sample_id_all is not set, such as the PERF_RECORD_MMAP event synthesized during perf stat record:
tools/perf/util/evsel.c:__evsel__parse_sample() {
perf_sample__init(data, /*all=*/true);
data->evsel = evsel__get(evsel);
data->cpu = data->pid = data->tid = -1;
data->stream_id = data->id = data->time = -1ULL;
...
}When the first synthetic ID (~0ULL) is assigned to an evsel that is not first in the evlist (for example, perf stat record -e task-clock,duration_time true), evlist__id2evsel(evlist, -1ULL) resolves to that synthetic-ID evsel while sample->evsel on the PERF_RECORD_MMAP event is evlist__first(evlist). Running perf stat report then trips the assertion in machines__deliver_event():
tools/perf/util/session.c:machines__deliver_event() {
...
if (!sample->evsel) {
sample->evsel = evlist__id2evsel(evlist, sample->id);
if (sample->evsel)
sample->evsel = evsel__get(sample->evsel);
}
else
assert(sample->evsel == evlist__id2evsel(evlist, sample->id));
...
}Pre-decrementing next_synthetic_id (or initializing it to ~0ULL - 1) would avoid assigning ~0ULL as a valid event ID.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
Ian Rogers
reviewerPATCH 5/13 perf stat: Preserve per-evsel CPU maps across stat record and report
In reply to Ian RogersCommit 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.
--- 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(-)
tools/perf/tests/event_update.c +38 -5
@@ -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 subtesTEST_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 ;
tools/perf/tests/shell/stat.sh +16 -0
@@ -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]" }
tools/perf/util/evsel.c +1 -1
@@ -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 ;/*
tools/perf/util/header.c +5 -0
@@ -5962,6 +5962,11 @@ int perf_event__process_event_update(const struct perf_tool *tool __maybe_unusedif (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 ;
tools/perf/util/stat.c +18 -0
@@ -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 ;
tools/perf/util/synthetic-events.c +5 -2
@@ -2234,10 +2234,13 @@ int perf_event__synthesize_event_update_name(const struct perf_tool *tool, strucint 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" );
Signature · 1 line
2.56.1.750.gf70dc682cf-goog
[email protected]
AI reviewRe: [PATCH v1 05/13] perf stat: Preserve per-evsel CPU maps across stat record and report
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Medium] perf test: false-positive grep match on error output in stat.sh - [Low] perf stat: NULL…
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Medium] perf test: false-positive grep match on error output in stat.sh
- [Low] perf stat: NULL counter->counts dereference in perf_event__process_stat_event()
--
commit d4e30cf2ee96dddd1f10329db7c3af1b94429be0
Author: Ian Rogers <[email protected]>
perf stat: Preserve per-evsel CPU maps across stat record and report
This commit serializes and restores per-evsel CPU maps in PERF_EVENT_UPDATE__CPUS events so that per-evsel CPU restrictions are preserved across perf stat record and report, with a fallback to the "any CPU" map for older perf.data files.
Quoted 23 lines
tools/perf/tests/shell/stat.sh +8
-0@@ -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
tools/perf/tests/shell/stat.sh test_stat_record_script() { · line 109
Quoted 10 lines
tools/perf/tests/shell/stat.sh +8
-0+ 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]" }
[Severity: Medium]
Do these two pipelines pass even when perf stat report or perf script fails with the bug this commit fixes?
When perf_event__process_stat_event() rejects the CPU, it prints "Invalid CPU 0 for event task-clock/cpu=0/." to stderr. Because stat.sh does not enable pipefail and 2>&1 merges stderr into the pipe, grep matches "task-clock/cpu=${cpu}/" inside the error message itself and returns 0.
Quoted 20 lines
tools/perf/util/header.c +5
-0@@ -5962,6 +5962,11 @@ int perf_event__process_event_update(const struct perf_tool *tool __maybe_unusedif (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 ;tools/perf/util/stat.c +0
-0
[ ... ]
Quoted 14 lines
tools/perf/util/stat.c +10
-0@@ -670,6 +671,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 (); +
tools/perf/util/stat.c int perf_event__process_stat_event(const struct perf_tool *tool __maybe_unused, · line 693
Quoted 10 lines
tools/perf/util/stat.c +7
-0+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 ;
[Severity: Low]
Can perf_event__process_stat_event() dereference a NULL counter->counts pointer in perf_counts()?
Previously, evsel->core.cpus remained NULL until both the thread map and CPU map events were processed and set_maps() allocated counter->counts, so perf_cpu_map__idx() returned -1 whenever counter->counts was NULL. Now that perf_event__process_event_update() populates evsel->core.cpus before counter->counts is allocated, a PERF_RECORD_STAT event arriving before set_maps() runs can match a valid cpu_map_idx and reach perf_counts(counter->counts, cpu_map_idx, st->thread) while counter->counts is still NULL.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=5
Re: [PATCH v1 05/13] perf stat: Preserve per-evsel CPU maps across stat record and report
In reply to Ian RogersQuoted 24 lines · Ian Rogers
Commit
6d765f5f7ec6("libperf evsel: Renameown_cpustopmu_cpus") and commit811082e4b668("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 collapseevsel->cpusto the "any CPU" (-1) map whenuser_requested_cpusis -1 and !evsel->requires_cpu.However,
perf_event__synthesize_event_update_cpus()continued to serializeevsel->core.pmu_cpusinstead ofevsel->core.cpus, andperf_event__process_event_update()only populatedevsel->core.pmu_cpuswithout settingevsel->core.cpusorevsel->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_cpusis -1), such as an event with a cpu= term, an uncore counter, --bpf-counters, or a BPF-filtered counter,PERF_RECORD_STATevents are written with concrete CPU numbers, but perf stat report'sperf_evlist__set_maps()collapsesevsel->cpusto -1 and fails with:
Quoted 3 lines
$ 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 elapsedOn 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.
Quoted 171 lines
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 serializeevsel->core.cpus, and updateperf_event__process_event_update()to populateevsel->core.cpusand setrequires_cpuwhen the recorded CPU map does not use the "any CPU" (-1) placeholder. For backward compatibility with data files recorded by older perf binaries that wrotepmu_cpusfor per-task (-1) counters, fall back to the "any CPU" map inperf_event__process_stat_event()if a -1 CPU stat event arrives for an evsel without -1 in its CPU map.Update the
event_updateunit test andstat.shrecord/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 <[email protected]>---
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(-)tools/perf/tests/event_update.c +38
-5@@ -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 subtesTEST_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 ;tools/perf/tests/shell/stat.sh +16
-0@@ -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]" }tools/perf/util/evsel.c +1
-1@@ -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 ;/* tools/perf/util/header.c +0
-0
tools/perf/util/header.c int perf_event__process_event_update(const struct perf_tool *tool __maybe_unused · line 5967
Quoted 6 lines
tools/perf/util/header.c +3
-0@@ -5962,6 +5962,11 @@ int perf_event__process_event_update(const struct perf_tool *tool __maybe_unusedif (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
Quoted 73 lines
tools/perf/util/header.c +2
-0+ evsel->core.requires_cpu = !perf_cpu_map__has_any_cpu (map); + } }else pr_err ("failed to get event_update cpus\n" );break ;tools/perf/util/stat.c +18
-0@@ -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 ;tools/perf/util/synthetic-events.c +5
-2@@ -2234,10 +2234,13 @@ int perf_event__synthesize_event_update_name(const struct perf_tool *tool, strucint 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" );Signature · 1 line
2.56.1.750.gf70dc682cf-goog
Ian Rogers
reviewerRe: [PATCH v1 05/13] perf stat: Preserve per-evsel CPU maps across stat record and report
Quoted 62 lines · Athira Rajeev
Quoted 25 lines · Ian Rogers
Commit
6d765f5f7ec6("libperf evsel: Renameown_cpustopmu_cpus") and commit811082e4b668("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 collapseevsel->cpusto the "any CPU" (-1) map whenuser_requested_cpusis -1 and !evsel->requires_cpu.However,
perf_event__synthesize_event_update_cpus()continued to serializeevsel->core.pmu_cpusinstead ofevsel->core.cpus, andperf_event__process_event_update()only populatedevsel->core.pmu_cpuswithout settingevsel->core.cpusorevsel->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_cpusis -1), such as an event with a cpu= term, an uncore counter, --bpf-counters, or a BPF-filtered counter,PERF_RECORD_STATevents are written with concrete CPU numbers, but perf stat report'sperf_evlist__set_maps()collapsesevsel->cpusto -1 and fails with:Quoted 3 lines
$ 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 commits6d765f5f7ec6and811082e4b668, ./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 elapsedOn top of this patch, result looks like:
./perf stat report -A
Quoted 7 lines
Performance counter stats for '
/root/perf-tools-next/tools/perf/perf':2.119970008 seconds time elapsedThere are no counter line, only time elapsed. I am suspecting the change for
perf_event__process_event_updateneeds update. Ian, have another query as well in the patch , adding them below.
Thanks for testing and catching this!
Before commit 811082e4b668, __perf_evlist__propagate_maps() clobbered cycles/cpu=8/ and cycles/cpu=9/ to the "any CPU" (-1) map when recording a workload without -a, so both counters recorded CPU -1 (which is why both reported identical task-wide totals with no CPU8/CPU9 column).
With per-evsel CPUs preserved on workload targets, evlist->user_requested_cpus (written to PERF_RECORD_CPU_MAP) is still the "any CPU" (-1) map while evlist->all_cpus holds {8, 9}. perf_stat_init_aggr_mode_file() and perf_stat_init_aggr_mode() built stat_config.aggr_map from user_requested_cpus (-1) rather than falling back to all_cpus, so CPU 8 and CPU 9 had no entries in aggr_map and were skipped during -A output. Also process_stat_config_event() checked perf_cpu_map__is_empty(st->cpus) instead of checking whether all_cpus only contains -1 for pure task data.
I've updated patch 5 in v2 to fall back to evlist->all_cpus when user_requested_cpus is the "any CPU" (-1) map (and check all_cpus in process_stat_config_event()), so 'perf stat report -A' now displays the CPU8 and CPU9 counter lines, and added a '-A' test case in stat.sh.
Quoted 165 lines
Quoted 165 lines
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 serializeevsel->core.cpus, and updateperf_event__process_event_update()to populateevsel->core.cpusand setrequires_cpuwhen the recorded CPU map does not use the "any CPU" (-1) placeholder. For backward compatibility with data files recorded by older perf binaries that wrotepmu_cpusfor per-task (-1) counters, fall back to the "any CPU" map inperf_event__process_stat_event()if a -1 CPU stat event arrives for an evsel without -1 in its CPU map.Update the
event_updateunit test andstat.shrecord/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 <[email protected]>---
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(-)tools/perf/tests/event_update.c +38
-5@@ -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 subtesTEST_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 ;tools/perf/tests/shell/stat.sh +16
-0@@ -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]" }tools/perf/util/evsel.c +1
-1@@ -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 ;
Quoted 16 lines
tools/perf/util/header.c int perf_event__process_event_update(const struct perf_tool *tool __maybe_unused · line 5967
Quoted 12 lines
tools/perf/util/evsel.c +0
-0/* tools/perf/util/header.c +3
-0@@ -5962,6 +5962,11 @@ int perf_event__process_event_update(const struct perf_tool *tool __maybe_unusedif (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_cpusand core.cpus will point to same data ? Whenevsel->countsis zero, both will carry same “perf_cpu_map” object. So during report, thepmu_cpuswill hold same contents as “cpus” , which is record opened cpu map.
But ideallypmu_cpusshould be having the PMU’s cpumask ?
perf.data only carries a single PERF_EVENT_UPDATE__CPUS record (not a separate PMU cpumask), and during 'perf stat report' the evsels are reconstructed from PERF_RECORD_HEADER_ATTR rather than parsed against the reporting machine's local sysfs PMUs (which may be a different host with different online CPUs). When set_maps() calls __perf_evlist__propagate_maps(), non-"any CPU" evsel->cpus is intersected with evsel->pmu_cpus, so pmu_cpus needs to cover the recorded CPUs to avoid intersecting them away.
However, when map is the "any CPU" (-1) placeholder, pmu_cpus shouldn't be set to {-1}. In v2 I've guarded the pmu_cpus assignment with !perf_cpu_map__has_any_cpu(map) and added a comment explaining why pmu_cpus is populated from concrete recorded CPU maps.
Thanks,
Ian
Quoted 77 lines
Thanks
AthiraQuoted 73 lines
tools/perf/util/header.c +2
-0+ evsel->core.requires_cpu = !perf_cpu_map__has_any_cpu (map); + } }else pr_err ("failed to get event_update cpus\n" );break ;tools/perf/util/stat.c +18
-0@@ -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 ;tools/perf/util/synthetic-events.c +5
-3@@ -2234,10 +2234,13 @@ int perf_event__synthesize_event_update_name(const struct perf_tool *tool, strucint 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
Re: [PATCH v1 05/13] perf stat: Preserve per-evsel CPU maps across stat record and report
Quoted 91 lines · Ian Rogers
Quoted 62 lines · Athira Rajeev
Quoted 25 lines · Ian Rogers
Commit
6d765f5f7ec6("libperf evsel: Renameown_cpustopmu_cpus") and commit811082e4b668("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 collapseevsel->cpusto the "any CPU" (-1) map whenuser_requested_cpusis -1 and !evsel->requires_cpu.However,
perf_event__synthesize_event_update_cpus()continued to serializeevsel->core.pmu_cpusinstead ofevsel->core.cpus, andperf_event__process_event_update()only populatedevsel->core.pmu_cpuswithout settingevsel->core.cpusorevsel->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_cpusis -1), such as an event with a cpu= term, an uncore counter, --bpf-counters, or a BPF-filtered counter,PERF_RECORD_STATevents are written with concrete CPU numbers, but perf stat report'sperf_evlist__set_maps()collapsesevsel->cpusto -1 and fails with:Quoted 3 lines
$ 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 commits6d765f5f7ec6and811082e4b668, ./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 elapsedOn top of this patch, result looks like:
./perf stat report -AQuoted 7 lines
Performance counter stats for '
/root/perf-tools-next/tools/perf/perf':2.119970008 seconds time elapsedThere are no counter line, only time elapsed. I am suspecting the change for
perf_event__process_event_updateneeds update. Ian, have another query as well in the patch , adding them below.Thanks for testing and catching this!
Before commit
811082e4b668,__perf_evlist__propagate_maps()clobbered cycles/cpu=8/ and cycles/cpu=9/ to the "any CPU" (-1) map when recording a workload without -a, so both counters recorded CPU -1 (which is why both reported identical task-wide totals with no CPU8/CPU9 column).With per-evsel CPUs preserved on workload targets,
evlist->user_requested_cpus(written toPERF_RECORD_CPU_MAP) is still the "any CPU" (-1) map whileevlist->all_cpusholds {8, 9}.perf_stat_init_aggr_mode_file()andperf_stat_init_aggr_mode()built stat_config.aggr_map fromuser_requested_cpus(-1) rather than falling back toall_cpus, so CPU 8 and CPU 9 had no entries inaggr_mapand were skipped during -A output. Alsoprocess_stat_config_event()checkedperf_cpu_map__is_empty(st->cpus)instead of checking whetherall_cpusonly contains -1 for pure task data.
Quoted 4 lines
I've updated patch 5 in v2 to fall back to
evlist->all_cpuswhenuser_requested_cpusis the "any CPU" (-1) map (and checkall_cpusinprocess_stat_config_event()), so 'perf stat report -A' now displays the CPU8 and CPU9 counter lines, and added a '-A' test case instat.sh.
Hi Ian
Sure, Thanks for responding and considering the changes. Will watch out for V2 and check the new changes.
Thanks
Athira
Quoted 192 lines
Quoted 166 lines
Quoted 166 lines
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 serializeevsel->core.cpus, and updateperf_event__process_event_update()to populateevsel->core.cpusand setrequires_cpuwhen the recorded CPU map does not use the "any CPU" (-1) placeholder. For backward compatibility with data files recorded by older perf binaries that wrotepmu_cpusfor per-task (-1) counters, fall back to the "any CPU" map inperf_event__process_stat_event()if a -1 CPU stat event arrives for an evsel without -1 in its CPU map.Update the
event_updateunit test andstat.shrecord/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 <[email protected]>---
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(-)tools/perf/tests/event_update.c +38
-5@@ -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 subtesTEST_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 ;tools/perf/tests/shell/stat.sh +16
-0@@ -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]" }tools/perf/util/evsel.c +1
-1@@ -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 ;Quoted 16 lines
tools/perf/util/header.c int perf_event__process_event_update(const struct perf_tool *tool __maybe_unused · line 5967
Quoted 12 lines
tools/perf/util/evsel.c +0
-0/* tools/perf/util/header.c +3
-0@@ -5962,6 +5962,11 @@ int perf_event__process_event_update(const struct perf_tool *tool __maybe_unusedif (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_cpusand core.cpus will point to same data ? Whenevsel->countsis zero, both will carry same “perf_cpu_map” object. So during report, thepmu_cpuswill hold same contents as “cpus” , which is record opened cpu map.
But ideallypmu_cpusshould be having the PMU’s cpumask ?perf.data only carries a single
PERF_EVENT_UPDATE__CPUSrecord (not a separate PMU cpumask), and during 'perf stat report' the evsels are reconstructed fromPERF_RECORD_HEADER_ATTRrather than parsed against the reporting machine's local sysfs PMUs (which may be a different host with different online CPUs). Whenset_maps()calls__perf_evlist__propagate_maps(), non-"any CPU"evsel->cpusis intersected withevsel->pmu_cpus, sopmu_cpusneeds to cover the recorded CPUs to avoid intersecting them away.
Quoted 4 lines
However, when map is the "any CPU" (-1) placeholder,
pmu_cpusshouldn't be set to {-1}. In v2 I've guarded thepmu_cpusassignment with !perf_cpu_map__has_any_cpu(map) and added a comment explaining whypmu_cpusis populated from concrete recorded CPU maps.
Sure, having a comment will help.
Quoted 78 lines
Thanks,
IanQuoted 74 lines
Thanks
AthiraQuoted 71 lines
tools/perf/util/header.c +2
-0+ evsel->core.requires_cpu = !perf_cpu_map__has_any_cpu (map); + } }else pr_err ("failed to get event_update cpus\n" );break ;tools/perf/util/stat.c +18
-0@@ -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 ;tools/perf/util/synthetic-events.c +5
-3@@ -2234,10 +2234,13 @@ int perf_event__synthesize_event_update_name(const struct perf_tool *tool, strucint 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
Ian Rogers
reviewerPATCH 6/13 perf pmu: Don't treat tool PMU as a kernel software PMU for event grouping
In reply to Ian Rogersperf_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.
--- 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(-)
tools/perf/builtin-stat.c +5 -2
@@ -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))
tools/perf/util/evsel.c +61 -15
114 lines not on this page · raw message
tools/perf/util/parse-events.c +16 -8
@@ -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 ; }
tools/perf/util/pmu.c +1 -1
@@ -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++) {
tools/perf/util/tool_pmu.c +4 -2
@@ -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 {
Signature · 1 line
2.56.1.750.gf70dc682cf-goog
Re: [PATCH v1 06/13] perf pmu: Don't treat tool PMU as a kernel software PMU for event grouping
Hi Ian,
06/13 keeps a group that mixes a tool event with a kernel event from reaching the BUG_ON and the group read; I am not disputing that. What I want settled is whether such a group should be split or refused.
The 06/13 commit message says:
Quoted 3 lines
Return false for
PERF_PMU_TYPE_TOOLinperf_pmu__is_software(), matching hwmon and drm PMUs, and ensureevsel__compute_group_pmu_name()only substitutesperf_event_openPMU names for software and AUX events [...]
I took the other approach: perf stat refuses a group that mixes a tool event with a kernel event (one that perf_event_open() opens), unless the group is weak and its leader is user_time or system_time. With that patch, perf stat rejects -e '{user_time,cycles}' with "A tool event cannot be grouped with kernel events: user_time" and exits with status 22, instead of printing a value for the tool event and "<not supported>" for the rest. This is v4 of "perf stat: Refuse a group mixing tool and kernel events":
https://lore.kernel.org/all/[email protected]/
In v4's test, the -a case expects a refusal that the cpu-map split in evlist__check_cpu_maps() makes impossible on a machine with more than one core PMU. Only the test needs to change; the refusal code does not. I will post v5 with that fix.
The parser's split for events of another software PMU, and the split -a causes in evlist__check_cpu_maps(), are not what this is about, and I am not asking to change either. The -e '{user_time,cycles}' case is not a
regression: perf stat opens it as one group today, the kernel rejects the cycles member with EBADF, and cycles prints "<not supported>". 06/13 would count both, as two groups. I would rather be told the group is refused, with a hint at the form that does work
(-e '{cycles,instructions},user_time'), than have perf choose a grouping for me. That is a preference about what the braces mean, not a claim that 06/13 is broken, and it is yours to weigh. A warning would tell the user what happened, but the two groups would still start and stop separately, which is the part I cannot square with the braces. If a warning is what you have in mind, say so and I will take the refusal off the table.
With 06/13 as posted, the tool event keeps its own PMU name, so the group is already split by the time perf stat's check runs. Moving my check before the parser regroups the events would refuse a group over members that -a would have taken out of it, so the check has to come after both the regroup and the split in evlist__check_cpu_maps(). If 06/13 keeps both changes -- the one in perf_pmu__is_software() and the one in evsel__compute_group_pmu_name() -- the groups my test expects to be refused would be accepted instead.
The refusal does not reintroduce the fd == -1 case 06/13 guards against:
the check runs before perf_event_open(), so a group it refuses never reaches get_group_fd().
On v3 of Hang's patch, which I posted for him, Namhyung wrote (2026-11-20, <[email protected]>):
Quoted 2 lines
I think grouping with tool events would cause more headaches. Probably the simplest fix is to prohibit grouping.
Namhyung, by "prohibit grouping", did you mean that perf stat should refuse such a group, or that it should count each event on its own and print a value for it? 06/13 does the second. When I wrote v4 I read you as asking for the first, and v4 refuses exactly those groups; a group of tool events alone, such as -e '{user_time,system_time}', is still accepted.
07/13 ("perf evlist: Enable tool PMU events when starting a workload") fixes the enable_on_exec case my patch does not touch; I would like to see it land regardless of how this is settled.
So which should it be: the split in 06/13, or the refusal in v4? If the split wins, I will withdraw v4. If the refusal wins, 06/13 would have to leave the PERF_PMU_TYPE_TOOL case alone in perf_pmu__is_software() and drop the PERF_PMU_KIND checks in evsel__compute_group_pmu_name().
If you would rather leave it to Namhyung, I will go with whatever he says. I am asking you because 06/13 is your patch.
Thanks,
TAKANO Mitsuhiro
Namhyung Kim
maintainerRe: [PATCH v1 06/13] perf pmu: Don't treat tool PMU as a kernel software PMU for event grouping
Hello,
Quoted 57 lines · TAKANO Mitsuhiro
Hi Ian,
06/13 keeps a group that mixes a tool event with a kernel event from reaching the
BUG_ONand the group read; I am not disputing that. What I want settled is whether such a group should be split or refused.The 06/13 commit message says:
Quoted 3 lines
Return false for
PERF_PMU_TYPE_TOOLinperf_pmu__is_software(), matching hwmon and drm PMUs, and ensureevsel__compute_group_pmu_name()only substitutesperf_event_openPMU names for software and AUX events [...]I took the other approach: perf stat refuses a group that mixes a tool event with a kernel event (one that
perf_event_open()opens), unless the group is weak and its leader isuser_timeorsystem_time. With that patch, perf stat rejects -e '{user_time,cycles}' with "A tool event cannot be grouped with kernel events:user_time" and exits with status 22, instead of printing a value for the tool event and "<not supported>" for the rest. This is v4 of "perf stat: Refuse a group mixing tool and kernel events":https://lore.kernel.org/all/[email protected]/
In v4's test, the -a case expects a refusal that the cpu-map split in
evlist__check_cpu_maps()makes impossible on a machine with more than one core PMU. Only the test needs to change; the refusal code does not. I will post v5 with that fix.The parser's split for events of another software PMU, and the split -a causes in
evlist__check_cpu_maps(), are not what this is about, and I am not asking to change either. The -e '{user_time,cycles}' case is not a
regression: perf stat opens it as one group today, the kernel rejects the cycles member with EBADF, and cycles prints "<not supported>". 06/13 would count both, as two groups. I would rather be told the group is refused, with a hint at the form that does work
(-e '{cycles,instructions},user_time'), than have perf choose a grouping for me. That is a preference about what the braces mean, not a claim that 06/13 is broken, and it is yours to weigh. A warning would tell the user what happened, but the two groups would still start and stop separately, which is the part I cannot square with the braces. If a warning is what you have in mind, say so and I will take the refusal off the table.With 06/13 as posted, the tool event keeps its own PMU name, so the group is already split by the time perf stat's check runs. Moving my check before the parser regroups the events would refuse a group over members that -a would have taken out of it, so the check has to come after both the regroup and the split in
evlist__check_cpu_maps(). If 06/13 keeps both changes -- the one inperf_pmu__is_software()and the one inevsel__compute_group_pmu_name()-- the groups my test expects to be refused would be accepted instead.The refusal does not reintroduce the fd == -1 case 06/13 guards against:
the check runs beforeperf_event_open(), so a group it refuses never reachesget_group_fd().On v3 of Hang's patch, which I posted for him, Namhyung wrote (2026-11-20, <[email protected]>):
Quoted 8 lines
Quoted 2 lines
I think grouping with tool events would cause more headaches. Probably the simplest fix is to prohibit grouping.
Namhyung, by "prohibit grouping", did you mean that perf stat should refuse such a group, or that it should count each event on its own and print a value for it? 06/13 does the second. When I wrote v4 I read you as asking for the first, and v4 refuses exactly those groups; a group of tool events alone, such as -e '{user_time,system_time}', is still accepted.
Right, but there's no reason to group tool events IIUC.
I was afraid that events like '{user_time,instructions,system_time,cycles}' can complicate parsing and evlist handling. As they cannot be a group, it'd be easier to reject them with a message instead of adding seemingly unnecessary complexity.
Thanks,
Namhyung
Quoted 16 lines
07/13 ("perf evlist: Enable tool PMU events when starting a workload") fixes the
enable_on_execcase my patch does not touch; I would like to see it land regardless of how this is settled.So which should it be: the split in 06/13, or the refusal in v4? If the split wins, I will withdraw v4. If the refusal wins, 06/13 would have to leave the
PERF_PMU_TYPE_TOOLcase alone inperf_pmu__is_software()and drop thePERF_PMU_KINDchecks inevsel__compute_group_pmu_name().If you would rather leave it to Namhyung, I will go with whatever he says. I am asking you because 06/13 is your patch.
Thanks,
TAKANO Mitsuhiro
Ian Rogers
reviewerPATCH 7/13 perf evlist: Enable tool PMU events when starting a workload
In reply to Ian RogersWhen 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-clockEnable tool PMU events that are set to enable on exec when the workload is started.
--- tools/perf/util/evlist.c | 15 +++++++++++++++ tools/perf/util/evsel.c | 14 ++++++++++++++ 2 files changed, 29 insertions(+)
tools/perf/util/evlist.c +15 -0
@@ -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! */
tools/perf/util/evsel.c +14 -0
@@ -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)) {/*
Signature · 1 line
2.56.1.750.gf70dc682cf-goog
Ian Rogers
reviewerPATCH 8/13 perf stat: Respect the enabled time of exited user_time/system_time events
In reply to Ian RogersWhen 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-clockAdd 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.
--- 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(+)
tools/perf/builtin-stat.c +3 -0
@@ -302,6 +302,9 @@ static int read_single_counter(struct evsel *counter, int cpu_map_idx, int threaelse 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 ;
tools/perf/util/tool_pmu.c +24 -0
@@ -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 ));
tools/perf/util/tool_pmu.h +2 -0
@@ -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 );
Signature · 1 line
2.56.1.750.gf70dc682cf-goog
Ian Rogers
reviewerPATCH 9/13 perf stat: Fix --bpf-counters with non-bperf, hybrid, and mixed events
In reply to Ian RogersWhen 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.
--- 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(-)
tools/perf/builtin-stat.c +25 -2
@@ -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; }
tools/perf/util/bpf_counter.c +90 -25
201 lines not on this page · raw message
tools/perf/util/bpf_counter.h +14 -0
@@ -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 */
tools/perf/util/bpf_counter_cgroup.c +106 -39
240 lines not on this page · raw message
tools/perf/util/evlist.c +12 -5
@@ -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 exclif (!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.
tools/perf/util/evsel.c +7 -1
@@ -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++) {
Signature · 1 line
2.56.1.750.gf70dc682cf-goog
Ian Rogers
reviewerPATCH 10/13 perf bpf-filter: Fix bpf_link leak by using PERF_EVENT_IOC_SET_BPF
In reply to Ian RogersIn 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 returnedbpf_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:581SUMMARY: 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 ]
--- tools/perf/util/bpf-filter.c | 18 +++++------------- 1 file changed, 5 insertions(+), 13 deletions(-)
tools/perf/util/bpf-filter.c +5 -13
@@ -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; } }
Signature · 1 line
2.56.1.750.gf70dc682cf-goog
Ian Rogers
reviewerPATCH 11/13 perf bpf-filter: Copy bpf_filters in evsel__clone() and close on evsel__close()
In reply to Ian Rogersevsel__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.
--- 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(-)
tools/perf/util/bpf-filter.c +54 -3
@@ -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 (©->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, ©->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 ; }
tools/perf/util/bpf-filter.h +10 -0
@@ -28,7 +28,9 @@ struct perf_bpf_filter_expr *perf_bpf_filter_expr__new(enum perf_bpf_filter_termenum 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 ;
tools/perf/util/evlist.c +2 -0
@@ -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); }
tools/perf/util/evsel.c +4 -0
@@ -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); }
Signature · 1 line
2.56.1.750.gf70dc682cf-goog
[email protected]
AI reviewRe: [PATCH v1 11/13] perf bpf-filter: Copy bpf_filters in evsel__clone() and close on evsel__close()
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] perf bpf-filter: evsel->bpf_skel leak when bpf_program_profiler_ops is active --
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] perf bpf-filter: evsel->bpf_skel leak when bpf_program_profiler_ops is active
--
commit d719c3b8be630c9ad40c9c5d575ea564cff11cd7
Author: Ian Rogers <[email protected]>
perf bpf-filter: Copy bpf_filters in evsel__clone() and close on evsel__close()
This commit adds perf_bpf_filter__copy() to duplicate BPF filter expressions during evsel__clone(), and introduces perf_bpf_filter__close() to tear down BPF skeleton and pinned filter state when closing an evsel or evlist.
Quoted 17 lines
tools/perf/util/evlist.c +2
-0@@ -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); }tools/perf/util/evsel.c +0
-0
[ ... ]
tools/perf/util/evsel.c void evsel__close(struct evsel *evsel) · line 3270
Quoted 9 lines
tools/perf/util/evsel.c +2
-0@@ -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); }
[Severity: Medium]
Should these checks in evlist__close() and evsel__close() test !evsel__is_bperf(evsel) instead of !evsel__is_bpf(evsel) so that evsel->bpf_skel is not leaked when profiling a BPF program?
Only bperf shares the evsel->bpf_skel union member with leader_skel and follower_skel. When perf stat runs with both -b and --filter, bpf_counter__load() sets evsel->bpf_counter_ops to &bpf_program_profiler_ops (with a non-empty evsel->bpf_counter_list, so evsel__is_bperf(evsel) is false while evsel__is_bpf(evsel) is true) and perf_bpf_filter__prepare() populates evsel->bpf_skel (or pinned_filters).
Because evsel__is_bpf(evsel) is true, evlist__close() and evsel__close() skip perf_bpf_filter__close(evsel). This leaks the sample_filter_bpf skeleton or pinned_filter_idx entries across repeat runs (perf stat -r), and at final teardown in evsel__exit(), bpf_counter__destroy() sets evsel->bpf_skel = NULL before perf_bpf_filter__destroy() runs, leaking the sample_filter_bpf skeleton on single runs as well.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=11
Ian Rogers
reviewerPATCH 12/13 perf bpf-filter: Support BPF sample filters on tracepoint events
In reply to Ian RogersCommit 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.
--- tools/perf/util/bpf-filter.c | 158 ++++++++++++++++--- tools/perf/util/bpf_skel/sample_filter.bpf.c | 101 ++++++++++++ 2 files changed, 238 insertions(+), 21 deletions(-)
tools/perf/util/bpf-filter.c +137 -21
@@ -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_termreturn 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);
tools/perf/util/bpf_skel/sample_filter.bpf.c +101 -0
111 lines not on this page · raw message
Signature · 1 line
2.56.1.750.gf70dc682cf-goog
Ian Rogers
reviewerPATCH 13/13 perf parse-events: Route non-field tracepoint filter terms to BPF filter
In reply to Ian RogersCommit 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) ]
--- 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(-)
tools/perf/Documentation/perf-record.txt +13 -1
@@ -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,
tools/perf/util/evsel.c +1 -7
@@ -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, boolif (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);
tools/perf/util/evsel.h +1 -1
@@ -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;
tools/perf/util/parse-events.c +145 -10
189 lines not on this page · raw message
tools/perf/util/tp_pmu.c +55 -0
67 lines not on this page · raw message
tools/perf/util/tp_pmu.h +1 -0
@@ -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);
Signature · 1 line
2.56.1.750.gf70dc682cf-goog
[email protected]
AI reviewSashiko has finished reviewing this 13-patch series:
Sashiko has finished reviewing this 13-patch series:
- Patches 1-3, 6-10, 12, and 13: no issues found.
- Patch 4 ("perf stat: Give non-perf_event_open events unique ID..."): 1 potential issue (1 Medium)
- Patch 5 ("perf stat: Preserve per-evsel CPU maps across stat r..."): 2 potential issues (1 Medium, 1 Low)
- Patch 11 ("perf bpf-filter: Copy bpf_filters in evsel__clone()..."): 1 potential issue (1 Medium)
Detailed reviews have been sent as separate replies to patches 4, 5, and 11.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]