Skip to contentSkip to conversation

perf stat: Count kernel events in a group led by a tool event

PATCH New Hang Zhengyang 4 participants 10 messages Nov 11 – Nov 22 perf events

lore
Share & tools
lore
#0 lore raw

PATCH v2 1/1 perf stat: Count kernel events in a group led by a tool event

A tool event like user_time has no perf event in the kernel, but get_group_fd() still passes its fd, the /proc/stat fd, as the group_fd of the members. The kernel rejects each member with EBADF and nothing is counted:

  $ perf stat -a -e '{user_time,cycles,instructions}' -- sleep 0.05
                   0      user_time
     <not supported>      cycles
     <not supported>      instructions

Open the members with group_fd = -1, as the enable/disable code already assumes. They are then on their own, so read them without PERF_FORMAT_GROUP and open them disabled like a leader, so that -D, --control and enable_on_exec still apply. Keep reporting a broken group when the leader failed to open.

  $ perf stat -a -e '{user_time,cycles,instructions}' -- sleep 0.05
                   0      user_time
            38257394      cycles
            21228043      instructions

The kernel events in such a group are no longer scheduled together.

Fixes 6828d6929b76 ("perf evsel: Refactor tool events")
Assisted-by Claude:claude-opus-5-5

---
This goes on top of TAKANO's segfault fix, as asked in that thread. A tool event as a member, as in '{cycles,user_time}', is still not counted; I'll send that separately.

Ian, the other way is to take tool events out of such groups in perf
stat with a warning, the way mismatched cpus are handled, which also
covers the member case. I went with the group_fd = -1 that
0b18bced5444 describes; happy to switch if you'd rather split them.
---
Changes in v2:
- Open the members disabled like a leader, so -D, --control and enable_on_exec apply to them (sashiko)
- Report a broken group when the leader failed to open, as before, so
perf record is unchanged (sashiko)
- Limit to tool event leaders: a hwmon leader can't enable its members
- Link to v1: https://lore.kernel.org/r/[email protected]

---
 tools/perf/builtin-stat.c | 10 ++++++----
 tools/perf/util/evsel.c   |  8 ++++++++
 2 files changed, 14 insertions(+), 4 deletions(-)
tools/perf/builtin-stat.c +6 -4
index 37752d6bfef4..07d01028bdea 100644
@@ -719,9 +719,10 @@ static int create_perf_stat_counter(struct evsel *evsel,
 	/*
 	 * The event is part of non trivial group, let's enable
 	 * the group read (for leader) and ID retrieval for all
-	 * members.
+	 * members.  Members of a tool event leader are opened and
+	 * read on their own.
 	 */
-	if (leader->core.nr_members > 1)
+	if (leader->core.nr_members > 1 && !evsel__is_tool(leader))
 		attr->read_format |= PERF_FORMAT_ID|PERF_FORMAT_GROUP;
 
 	attr->inherit = !config->no_inherit && list_empty(&evsel->bpf_counter_list);
@@ -748,9 +749,10 @@ static int create_perf_stat_counter(struct evsel *evsel,
 	/*
 	 * Disabling all counters initially, they will be enabled
 	 * either manually by us or by kernel via enable_on_exec
-	 * set later.
+	 * set later.  Members of a tool event leader are opened on
+	 * their own and enabled with it, so they need it too.
 	 */
-	if (evsel__is_group_leader(evsel)) {
+	if (evsel__is_group_leader(evsel) || evsel__is_tool(leader)) {
 		attr->disabled = 1;
 
 		if (target__enable_on_exec(&target))
tools/perf/util/evsel.c +8 -0
index 560741d9599d..e3ed645cc289 100644
@@ -2378,6 +2378,14 @@ static int get_group_fd(struct evsel *evsel, int cpu_map_idx, int thread)
 	if (!evsel->supported || evsel__is_group_leader(evsel))
 		return -1;
 
+	/*
+	 * A tool event leader has no perf event to group with, so open
+	 * the member on its own, or report the group as broken (-2) if
+	 * the leader failed to open.
+	 */
+	if (evsel__is_tool(leader))
+		return leader->supported ? -1 : -2;
+
 	/*
 	 * Leader must be already processed/open,
 	 * if not it's a bug.

---
base-commit: cc905a18a647a8e3ad42cd1596baa0e08fba26eb
change-id: 20261111-tool-pmu-leader-d25fe8153599
prerequisite-message-id: <[email protected]>
prerequisite-patch-id: b92ce8b0c6248a4af182670458912b760b98a410

Best regards,

Signature · 1 line
Hang Zhengyang <[email protected]>
#1 lore raw
Sashiko has reviewed this patch and found no issues.
Quoted 23 lines

From: Hang Zhengyang <[email protected]>

A tool event like user_time has no perf event in the kernel, but get_group_fd() still passes its fd, the /proc/stat fd, as the group_fd of the members. The kernel rejects each member with EBADF and nothing is counted:

  $ perf stat -a -e '{user_time,cycles,instructions}' -- sleep 0.05
                   0      user_time
     <not supported>      cycles
     <not supported>      instructions

Open the members with group_fd = -1, as the enable/disable code already assumes. They are then on their own, so read them without PERF_FORMAT_GROUP and open them disabled like a leader, so that -D, --control and enable_on_exec still apply. Keep reporting a broken group when the leader failed to open.

  $ perf stat -a -e '{user_time,cycles,instructions}' -- sleep 0.05
                   0      user_time
            38257394      cycles
            21228043      instructions
Quoted 5 lines

The kernel events in such a group are no longer scheduled together.

Fixes 6828d6929b76 ("perf evsel: Refactor tool events")
Assisted-by Claude:claude-opus-5-5

Sashiko has reviewed this patch and found no issues.

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

PATCH v3 1/1 perf stat: Count kernel events in a group led by a tool event

In reply to Hang Zhengyang

From: Hang Zhengyang <[email protected]>

A tool event like user_time has no perf event in the kernel, but get_group_fd() still passes its fd, the /proc/stat fd, as the group_fd of the members. The kernel rejects each member with EBADF and nothing is counted:

  $ perf stat -a -e '{user_time,cycles,instructions}' -- sleep 0.05
                   0      user_time
     <not supported>      cycles
     <not supported>      instructions

Open the members with group_fd = -1, as the enable/disable code already assumes, and read them on their own: the leader is not asked for counts of events that are not in its kernel group. A kernel event member is opened disabled, as a leader is, so that it starts with the workload and still honours -D and --control. A tool event member is left as it
is: it counts from open and an explicit disable is what stops it, so disabling it here would leave nobody to start it when perf relies on enable_on_exec.

  $ perf stat -a -e '{user_time,cycles,instructions}' -- sleep 0.05
                   0      user_time
            38257394      cycles
            21228043      instructions

The kernel events in such a group are no longer scheduled together, which is the price of counting them at all. A tool event used as a member, as in '{cycles,user_time}', is still not counted; that also needs the leader's group read to be handled and is left for a follow-up.

Fixes 6828d6929b76 ("perf evsel: Refactor tool events")

Written with LLM assistants: the group_fd change and its testing by Hang Zhengyang with Claude, the v3 condition and its measurement by TAKANO Mitsuhiro with Hermes Agent. perf was built here and 'perf test -v 10' passes with and without the change.

---
v3: open only the kernel event members disabled. A tool event member
counts from open and an explicit disable is what stops it, so opening it disabled left nobody to start it when perf relies on
enable_on_exec: 'perf stat -e "{user_time,system_time}" -- sleep 0.2' went from ~2.7 ms of system_time to 0 on an arm64 KVM guest. The non-standard Assisted-by tag is replaced by a prose disclosure, and the patch is regenerated on 7.4-rc2.

The libperf fix that stops the NULL dereference is a separate patch (<[email protected]>); this one does not depend on it.

 tools/perf/builtin-stat.c | 16 ++++++++++++----
 tools/perf/util/evsel.c   |  8 ++++++++
 2 files changed, 20 insertions(+), 4 deletions(-)
tools/perf/builtin-stat.c +12 -4
index 37752d6bfef4..57956f55ea09 100644
@@ -719,9 +719,10 @@ static int create_perf_stat_counter(struct evsel *evsel,
 	/*
 	 * The event is part of non trivial group, let's enable
 	 * the group read (for leader) and ID retrieval for all
-	 * members.
+	 * members.  Members of a tool event leader are opened and
+	 * read on their own.
 	 */
-	if (leader->core.nr_members > 1)
+	if (leader->core.nr_members > 1 && !evsel__is_tool(leader))
 		attr->read_format |= PERF_FORMAT_ID|PERF_FORMAT_GROUP;
 
 	attr->inherit = !config->no_inherit && list_empty(&evsel->bpf_counter_list);
@@ -748,9 +749,16 @@ static int create_perf_stat_counter(struct evsel *evsel,
 	/*
 	 * Disabling all counters initially, they will be enabled
 	 * either manually by us or by kernel via enable_on_exec
-	 * set later.
+	 * set later.  A kernel event that a tool event leader has as
+	 * a member is not in the kernel's group either, so it has to
+	 * be opened disabled to start together with the workload.
+	 * A tool event member counts from open and is only stopped by
+	 * an explicit disable, so leaving it enabled here keeps its
+	 * count; disabling it would leave nobody to start it when
+	 * perf relies on enable_on_exec.
 	 */
-	if (evsel__is_group_leader(evsel)) {
+	if (evsel__is_group_leader(evsel) ||
+	    (evsel__is_tool(leader) && !evsel__is_tool(evsel))) {
 		attr->disabled = 1;
 
 		if (target__enable_on_exec(&target))
tools/perf/util/evsel.c +8 -0
index d060fca8090f..7f514cde6840 100644
@@ -2370,6 +2370,14 @@ static int get_group_fd(struct evsel *evsel, int cpu_map_idx, int thread)
 	if (!evsel->supported || evsel__is_group_leader(evsel))
 		return -1;
 
+	/*
+	 * A tool event leader has no perf event to group with, so open
+	 * the member on its own, or report the group as broken (-2) if
+	 * the leader failed to open.
+	 */
+	if (evsel__is_tool(leader))
+		return leader->supported ? -1 : -2;
+
 	/*
 	 * Leader must be already processed/open,
 	 * if not it's a bug.

base-commit: 7475ea8b58616b33c04afb976cf0fbaad9dd63fb

Signature · 1 line
2.53.0
#3 lore raw
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] perf stat: broken tool event enable/disable for -D, --control, and exec in…

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] perf stat: broken tool event enable/disable for -D, --control, and exec in create_perf_stat_counter()
--

commit 0e981d5b2ece1f32ac47445309993697c6cdb096
Author: Hang Zhengyang <[email protected]>

perf stat: Count kernel events in a group led by a tool event

This commit opens members of a group led by a tool event on their own with group_fd = -1 and without PERF_FORMAT_GROUP, while opening kernel event members initially disabled.

Quoted 4 lines
tools/perf/builtin-stat.c +0 -0
index 37752d6bfef45..57956f55ea09b 100644

[ ... ]

Quoted 9 lines
tools/perf/builtin-stat.c +4 -1
@@ -748,9 +749,16 @@ static int create_perf_stat_counter(struct evsel *evsel,
 	/*
 	 * Disabling all counters initially, they will be enabled
 	 * either manually by us or by kernel via enable_on_exec
-	 * set later.
+	 * set later.  A kernel event that a tool event leader has as
+	 * a member is not in the kernel's group either, so it has to
+	 * be opened disabled to start together with the workload.
+	 * A tool event member counts from open and is only stopped by

tools/perf/builtin-stat.c static int create_perf_stat_counter(struct evsel *evsel, · line 764

Quoted 10 lines
tools/perf/builtin-stat.c +5 -1
+	 * an explicit disable, so leaving it enabled here keeps its
+	 * count; disabling it would leave nobody to start it when
+	 * perf relies on enable_on_exec.
 	 */
-	if (evsel__is_group_leader(evsel)) {
+	if (evsel__is_group_leader(evsel) ||
+	    (evsel__is_tool(leader) && !evsel__is_tool(evsel))) {
 		attr->disabled = 1;
 
 		if (target__enable_on_exec(&target))

[Severity: Medium]
Does conditioning attr->disabled on leader vs. member rather than target__enable_on_exec(&target) leave tool event members enabled during -D / --control and leave tool event leaders disabled during exec workloads?

In evsel__tool_pmu_open(), attr->disabled sets evsel->disabled = true and start_time = INVALID_START_TIME; otherwise evsel->disabled is false and start_time is sampled immediately at open.

When !target__enable_on_exec(&target) (such as with -D or --control), enable_counters() calls evlist__enable(), and evsel__enable_cpu() enables each member of a tool-led group via evsel__tool_pmu_enable_cpu():

tools/perf/util/tool_pmu.c:evsel__tool_pmu_enable_cpu() {
	if (!evsel->disabled)
		return 0;
    ...
}

Because a tool event member in a group like '{user_time,system_time}' is skipped by !evsel__is_tool(evsel) and opened with attr->disabled == 0, evsel__tool_pmu_enable_cpu() returns early without resetting start_time, so the member counts continuously through the disabled delay window.

Conversely, when target__enable_on_exec(&target) is true (such as 'perf stat -e "{user_time,cycles}" -- sleep 0.2'), enable_counters() skips evlist__enable() because kernel events are enabled on exec. A tool event leader still matches evsel__is_group_leader(evsel) and opens with evsel->disabled = true; nothing enables it on exec, so evsel__tool_pmu_read() returns 0.

Should tool events instead set attr->disabled = 1 only when !target__enable_on_exec(&target), regardless of whether they are the group leader or a member?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
#4 lore raw
Quoted 2 lines · On Wed, 11 Nov 2026 11:33:19 +0000, [email protected] wrote:

[...] leave tool event members enabled during -D / --control and leave tool event leaders disabled during exec workloads?

Both happen without this patch too, with tool events outside any group (perf-tools-next cc905a18a647):

  $ perf stat -e user_time,system_time -- dd if=/dev/zero of=/dev/null bs=1 count=300000
  -> user_time 0, system_time 0
  $ perf stat -D 400 -e user_time,system_time -- sh -c 'dd ... ; sleep 0.6'
  -> user_time 173 ms, system_time 137 ms, though dd ends within 400 ms

The first is what TAKANO's "perf stat: Start tool events when enable_on_exec is used" fixes.

Thanks,
Hang

maintainer
#5 lore raw
In reply to TAKANO Mitsuhiro

Hello,

Quoted 11 lines · TAKANO Mitsuhiro

From: Hang Zhengyang <[email protected]>

A tool event like user_time has no perf event in the kernel, but get_group_fd() still passes its fd, the /proc/stat fd, as the group_fd of the members. The kernel rejects each member with EBADF and nothing is counted:

  $ perf stat -a -e '{user_time,cycles,instructions}' -- sleep 0.05
                   0      user_time
     <not supported>      cycles
     <not supported>      instructions

Thanks for reporting this. Looks like a tricky case for tool events. I think it's better to make the first non-tool event as a leader, but I'm afraid it'd make evlist management complex.

Ian, any thoughts?

Thanks,
Namhyung

Quoted 105 lines

Open the members with group_fd = -1, as the enable/disable code already assumes, and read them on their own: the leader is not asked for counts of events that are not in its kernel group. A kernel event member is opened disabled, as a leader is, so that it starts with the workload and still honours -D and --control. A tool event member is left as it
is: it counts from open and an explicit disable is what stops it, so disabling it here would leave nobody to start it when perf relies on enable_on_exec.

  $ perf stat -a -e '{user_time,cycles,instructions}' -- sleep 0.05
                   0      user_time
            38257394      cycles
            21228043      instructions

The kernel events in such a group are no longer scheduled together, which is the price of counting them at all. A tool event used as a member, as in '{cycles,user_time}', is still not counted; that also needs the leader's group read to be handled and is left for a follow-up.

Fixes 6828d6929b76 ("perf evsel: Refactor tool events")

Written with LLM assistants: the group_fd change and its testing by Hang Zhengyang with Claude, the v3 condition and its measurement by TAKANO Mitsuhiro with Hermes Agent. perf was built here and 'perf test -v 10' passes with and without the change.

---
v3: open only the kernel event members disabled. A tool event member
counts from open and an explicit disable is what stops it, so opening it disabled left nobody to start it when perf relies on
enable_on_exec: 'perf stat -e "{user_time,system_time}" -- sleep 0.2' went from ~2.7 ms of system_time to 0 on an arm64 KVM guest. The non-standard Assisted-by tag is replaced by a prose disclosure, and the patch is regenerated on 7.4-rc2.

The libperf fix that stops the NULL dereference is a separate patch (<[email protected]>); this one does not depend on it.

 tools/perf/builtin-stat.c | 16 ++++++++++++----
 tools/perf/util/evsel.c   |  8 ++++++++
 2 files changed, 20 insertions(+), 4 deletions(-)
tools/perf/builtin-stat.c +12 -4
index 37752d6bfef4..57956f55ea09 100644
@@ -719,9 +719,10 @@ static int create_perf_stat_counter(struct evsel *evsel,
 	/*
 	 * The event is part of non trivial group, let's enable
 	 * the group read (for leader) and ID retrieval for all
-	 * members.
+	 * members.  Members of a tool event leader are opened and
+	 * read on their own.
 	 */
-	if (leader->core.nr_members > 1)
+	if (leader->core.nr_members > 1 && !evsel__is_tool(leader))
 		attr->read_format |= PERF_FORMAT_ID|PERF_FORMAT_GROUP;
 
 	attr->inherit = !config->no_inherit && list_empty(&evsel->bpf_counter_list);
@@ -748,9 +749,16 @@ static int create_perf_stat_counter(struct evsel *evsel,
 	/*
 	 * Disabling all counters initially, they will be enabled
 	 * either manually by us or by kernel via enable_on_exec
-	 * set later.
+	 * set later.  A kernel event that a tool event leader has as
+	 * a member is not in the kernel's group either, so it has to
+	 * be opened disabled to start together with the workload.
+	 * A tool event member counts from open and is only stopped by
+	 * an explicit disable, so leaving it enabled here keeps its
+	 * count; disabling it would leave nobody to start it when
+	 * perf relies on enable_on_exec.
 	 */
-	if (evsel__is_group_leader(evsel)) {
+	if (evsel__is_group_leader(evsel) ||
+	    (evsel__is_tool(leader) && !evsel__is_tool(evsel))) {
 		attr->disabled = 1;
 
 		if (target__enable_on_exec(&target))
tools/perf/util/evsel.c +8 -0
index d060fca8090f..7f514cde6840 100644
@@ -2370,6 +2370,14 @@ static int get_group_fd(struct evsel *evsel, int cpu_map_idx, int thread)
 	if (!evsel->supported || evsel__is_group_leader(evsel))
 		return -1;
 
+	/*
+	 * A tool event leader has no perf event to group with, so open
+	 * the member on its own, or report the group as broken (-2) if
+	 * the leader failed to open.
+	 */
+	if (evsel__is_tool(leader))
+		return leader->supported ? -1 : -2;
+
 	/*
 	 * Leader must be already processed/open,
 	 * if not it's a bug.

base-commit: 7475ea8b58616b33c04afb976cf0fbaad9dd63fb

Signature · 1 line
2.53.0
#6 lore raw

Hi Namhyung,

Quoted 1 line

I think it's better to make the first non-tool event as a leader

I agree, and I think that is where this ends up. What stops me from doing it in this patch is the group read: with a kernel event as the leader, evsel__group_read_nr_members() still counts a tool event member, while the kernel knows nothing about it (a tool event is not opened through perf_event_open, it reads /proc/stat) and returns one entry fewer. evsel__process_group_data() then rejects the read with -EINVAL and the kernel events of that group come out as <not counted> as well. The smallest version of that is a few lines, but it changes what every group with a tool event member prints, so it wants its own test and its own commit rather than riding along with the EBADF fix.

Quoted 1 line

but I'm afraid it'd make evlist management complex

v3 leaves the group structure alone: no new evlist entry, nr_members unchanged, and evsel->leader stays whoever it already was. What changes is how the members are opened:

- get_group_fd(): with group_fd = -1 instead of the tool event's /proc/stat fd, or -2 when the leader failed to open, the same -2 the skipped-leader case already returns for a broken group;
- create_perf_stat_counter(): a kernel event member is opened disabled, as a leader is, so that it starts with the workload, and PERF_FORMAT_GROUP is not requested for the members - read_format is per fd, and GROUP is what would send each member's read down the group path that only a leader can take. PERF_FORMAT_ID goes with it:
without a group read nothing demuxes ids.

The cost is real and the changelog states it: in -e '{user_time,a,b}', a and b no longer share an on/off window.

Two things this does not change, both of which happen without the patch:
a tool event member still counts through a -D / --control window, and a tool event leader under enable_on_exec is still not started by anything - that is what "perf stat: Start tool events when enable_on_exec is used" is for.

Either way the leader move is a separate series; I can post it once the direction is settled.

Thanks,
TAKANO

maintainer
#7 lore raw
Quoted 34 lines · TAKANO Mitsuhiro

Hi Namhyung,

Quoted 1 line

I think it's better to make the first non-tool event as a leader

I agree, and I think that is where this ends up. What stops me from doing it in this patch is the group read: with a kernel event as the leader, evsel__group_read_nr_members() still counts a tool event member, while the kernel knows nothing about it (a tool event is not opened through perf_event_open, it reads /proc/stat) and returns one entry fewer. evsel__process_group_data() then rejects the read with -EINVAL and the kernel events of that group come out as <not counted> as well. The smallest version of that is a few lines, but it changes what every group with a tool event member prints, so it wants its own test and its own commit rather than riding along with the EBADF fix.

Quoted 1 line

but I'm afraid it'd make evlist management complex

v3 leaves the group structure alone: no new evlist entry, nr_members unchanged, and evsel->leader stays whoever it already was. What changes is how the members are opened:

- get_group_fd(): with group_fd = -1 instead of the tool event's /proc/stat fd, or -2 when the leader failed to open, the same -2 the skipped-leader case already returns for a broken group;
- create_perf_stat_counter(): a kernel event member is opened disabled, as a leader is, so that it starts with the workload, and PERF_FORMAT_GROUP is not requested for the members - read_format is per fd, and GROUP is what would send each member's read down the group path that only a leader can take. PERF_FORMAT_ID goes with it:
without a group read nothing demuxes ids.

The cost is real and the changelog states it: in -e '{user_time,a,b}', a and b no longer share an on/off window.

Quoted 8 lines

Two things this does not change, both of which happen without the patch:
a tool event member still counts through a -D / --control window, and a tool event leader under enable_on_exec is still not started by anything - that is what "perf stat: Start tool events when enable_on_exec is used" is for.

Either way the leader move is a separate series; I can post it once the direction is settled.

I think grouping with tool events would cause more headaches. Probably the simplest fix is to prohibit grouping.

Thanks,
Namhyung

#8 lore raw

PATCH v4 1/1 perf stat: Refuse a group mixing tool and kernel events

In reply to TAKANO Mitsuhiro

A tool event has no event in the kernel. user_time and system_time read /proc/stat, or /proc/<pid>/stat for a workload, and duration_time keeps its value in perf itself. perf-list(1) says that events from different PMUs cannot be grouped, with some exceptions for software events; the tool PMU counts as software there, so a tool event stays in a group a user writes and, when it leads, the members are opened with its descriptor as the group fd.

Two things split such a group before it is opened: the parser splits a tool event from an event of another software PMU, such as cpu-clock, and evlist__check_cpu_maps() drops members whose CPUs do not match the leader under -a or -C. The group this patch is about is the one left after that, and it cannot be counted.

With user_time or system_time as the leader, get_group_fd() hands the procfs descriptor to the members, and the kernel rejects each of them with EBADF. With duration_time as the leader there is no descriptor at
all: its members get -2 and fail with "broken group leader" in the debug log. Either way perf stat prints the tool event and "<not supported>" for the rest of the group:

  $ perf stat -e '{user_time,cycles}' -- sleep 0.05
                   0      user_time
     <not supported>      cycles

With a kernel event as the leader the kernel events do open, but the group read is rejected: evsel__group_read_nr_members() counts the tool event, while the kernel returns one entry fewer, so evsel__process_group_data() fails and the events come out as "<not counted>". The form -e '{cycles,instructions,duration_time}', with the tool event inside the braces, is in that shape and has not been counted since 6828d6929b76.

Counting such a group means moving the leader to a kernel event, which changes the order of a group the user wrote with a tool event first, and it also needs the group read to skip the tool members; that is left to a separate series. Opening the members outside the group, as my v3 did and as Hang's v2 does, drops the group semantics, and a group that has a tool event as a member still cannot be counted. Taking the tool event out of the group and warning, as Hang offered in the notes of his v2 patch and as evlist__check_cpu_maps() does for members whose CPUs do not match the leader, would let the kernel events count, but the group would no longer be scheduled as one, so the tool event and the kernel events would have different enabled and running times, and the warning is easy to lose in a script. For -e the braces are the user's explicit request, so perf stat should not quietly reinterpret them; metricgroup moves tool events out of the groups it builds itself, which is a different case. Refuse the group instead:

  $ perf stat -e '{user_time,cycles}' -- sleep 0.05
  A tool event cannot be grouped with kernel events: user_time

followed by a hint to put the tool event outside the braces, as in -e '{cycles,instructions},duration_time'.

perf stat now exits 22 before the workload is started, where it used to leave the rest of the group uncounted and exit 0.

A group of tool events only is still accepted, as before. A weak group led by user_time or system_time is left to the weak group handling, which splits it when a member fails the open with EBADF; any other weak group that mixes them does not fail that way and is refused like a strong one.

The code, the test, the man page and this message were written with Hermes Agent (deepseek-v4.1-flash); the work started from Hang's report and the review thread linked below, and I reviewed the result, built perf, and ran tools/perf/tests/shell/stat+tool_group.sh and checkpatch --strict. Kernel events cannot be opened on this machine (perf_event_paranoid=4), so the EBADF and the group read were not re-observed here; the group is refused before any event is opened.

---
v4: refuse the group instead of counting it, as suggested by Namhyung Kim
in https://lore.kernel.org/all/[email protected]/
This replaces v3, which is withdrawn: its group_fd, read_format and disabled changes are dropped and no code from it remains.

I read "prohibit grouping" as the group that mixes a tool event with an event the kernel opens: -e '{user_time,system_time}' is read by perf itself and is not refused today. If you meant every group that holds a tool event, dropping the has_kernel test, and the weak check with it, is a couple of lines.

The parser still splits a tool event from another software PMU, and -a or -C still split a group whose members do not share the leader's CPUs; this refuses the group that is left after that.

A weak group led by user_time or system_time is left to the weak group handling, which splits it when a member fails with EBADF; any other weak group is refused.

Ian: Hang offered, in his v2, to take tool events out of such groups with a warning instead. I did not do that because the group would no longer be scheduled as one and the warning is easy to lose in a script. If you would rather have that, I can redo it.

Namhyung asked for the leader to move, then for grouping to be prohibited. Hang's v2 (Link) takes a third route, group_fd = -1, and is still open; only one of v2 and this patch should be applied:
v2 counts the members outside the group, this refuses the group.

On this base, -a or -C with a weak group led by a tool event crashes in the enable loop with a released fd array. That is older than this patch, and the libperf fix "libperf: Handle an evsel without an fd array in enable/disable"
(https://lore.kernel.org/all/[email protected]/),
which is in perf-tools-next, removes it.

 tools/perf/Documentation/perf-stat.txt    |  14 +++
 tools/perf/builtin-stat.c                 |  76 ++++++++++++
 tools/perf/tests/shell/stat+tool_group.sh | 144 ++++++++++++++++++++++
 3 files changed, 234 insertions(+)
 create mode 100755 tools/perf/tests/shell/stat+tool_group.sh
tools/perf/Documentation/perf-stat.txt +14 -0
index 8ea17da89976..34323f446e92 100644
@@ -65,6 +65,20 @@ report::
 	Multiple PMU instances are typical for uncore PMUs, so the prefix
 	'uncore_' is also ignored when performing this match.
 
+	Tool events such as duration_time and user_time are read by perf
+	itself and have no event in the kernel.  A group of a tool event and
+	an event from a different software PMU, such as cpu-clock, is split by
+	the parser, which warns that events were regrouped; -a and -C split
+	a group whose members do not share the CPUs of the leader in the
+	same way.  A group that is not split and mixes a tool event with an
+	event the kernel opens is refused, as in -e '{user_time,cycles}',
+	instead of printing the tool event and leaving the rest of the group
+	uncounted.  Put the tool event outside the braces instead, as in
+	-e '{cycles,instructions},duration_time'.  A group of tool events
+	only is accepted.  A weak group (:W) led by user_time or system_time
+	is left to the weak group handling, which splits it when the kernel
+	refuses the members with EBADF; any other weak group that mixes them is
+	refused like a strong group.
 
 -i::
 --no-inherit::
tools/perf/builtin-stat.c +76 -0

88 lines not on this page · raw message

tools/perf/tests/shell/stat+tool_group.sh new file +144 -0

144 lines not on this page · raw message

base-commit: c44104f3642da720164042623e4832836aefdd8e

Signature · 1 line
2.53.0
#9 lore raw

Re: [PATCH v4] perf stat: Refuse a group mixing tool and kernel events

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Medium] perf stat: weak group exemption in check_tool_groups() causes NULL deref - [Medium] perf stat…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Medium] perf stat: weak group exemption in check_tool_groups() causes NULL deref
- [Medium] perf stat: evlist__check_cpu_maps() splits hybrid tool groups before check
--

commit fce47ddb742e055cde4f936f3597701fcf5103c2
Author: TAKANO Mitsuhiro <[email protected]>

perf stat: Refuse a group mixing tool and kernel events

This commit adds check_tool_groups() to refuse event groups that mix tool events with kernel events, together with documentation and a shell test.

Quoted 60 lines
tools/perf/builtin-stat.c +52 -0
index 37752d6bfef45..7396cd92346af 100644
@@ -2469,6 +2469,77 @@ static int parse_tpebs_mode(const struct option *opt, const char *str,
 }
 #endif // HAVE_ARCH_X86_64_SUPPORT
 
+/*
+ * A tool event like user_time has no event in the kernel: it reads
+ * /proc/stat, or keeps its value in perf itself.  A group that mixes one
+ * with an event the kernel opens cannot be counted.
+ * get_group_fd() passes the leader's descriptor as the group fd, and the
+ * tool event has a procfs descriptor or none at all, so the kernel rejects
+ * the members with EBADF or perf gives up with "broken group leader"; with
+ * a kernel event as the leader the members do open, but the group read is
+ * rejected as the kernel knows only the members it opened.  perf stat used
+ * to leave the rest of the group uncounted in both cases, when the CPU maps
+ * had not split the group first; refuse the group instead.  A group with no
+ * event the kernel opens is left alone, as perf reads each event in it.  A
+ * weak group led by user_time or system_time is left to the weak group
+ * handling in the open loop, which splits it when a member fails with
+ * EBADF; any other weak group is refused like a strong one.
+ */
+static int check_tool_groups(struct evlist *evlist)
+{
+	struct evsel *leader, *evsel;
+
+	evlist__for_each_entry(evlist, leader) {
+		struct evsel *tool = NULL;
+		bool has_kernel = false, weak = false;
+
+		if (!evsel__is_group_leader(leader) || leader->core.nr_members < 2)
+			continue;
+
+		/*
+		 * The members of a group are not necessarily adjacent in the
+		 * evlist: evlist__check_cpu_maps() makes a removed member a
+		 * leader of its own without moving it, and so does a weak
+		 * group split in the open loop.
+		 */
+		evlist__for_each_entry(evlist, evsel) {
+			if (!evsel__has_leader(evsel, leader))
+				continue;
+			if (evsel__is_tool(evsel)) {
+				if (!tool)
+					tool = evsel;
+			} else if (!evsel__is_non_perf_event_open_pmu(evsel)) {
+				has_kernel = true;
+			}
+			weak |= evsel->weak_group;
+		}
+
+		if (!tool || !has_kernel)
+			continue;
+
+		/*
+		 * A weak group led by user_time or system_time is split by the
+		 * weak group handling in the open loop, as the kernel refuses
+		 * the members with EBADF, and that is what :W asks for.  Any

tools/perf/builtin-stat.c static int parse_tpebs_mode(const struct option *opt, const char *str, · line 2533

Quoted 10 lines
tools/perf/builtin-stat.c +10 -0
+		 * other weak group does not get that far, so it is refused
+		 * like a strong group.
+		 */
+		if (weak && evsel__is_tool(leader)) {
+			enum tool_pmu_event ev = evsel__tool_event(leader);
+
+			if (ev == TOOL_PMU__EVENT_USER_TIME ||
+			    ev == TOOL_PMU__EVENT_SYSTEM_TIME)
+				continue;
+		}

[Severity: Medium]
Can a weak group led by user_time or system_time still bypass the EBADF split in __run_perf_stat() and trigger a NULL pointer dereference of evsel->fd?

In the kernel, sys_perf_event_open() checks security_perf_event_open() and perf_allow_kernel() before looking up group_fd with is_perf_file(group). If a kernel member fails there with EACCES (for example, running perf stat -a -e '{user_time,cycles:k}:W' -- true unprivileged under the default kernel.perf_event_paranoid=2, where evsel__fallback() cannot fall back because exclude_user is set), __run_perf_stat() does not call evlist__reset_weak_group() because it only splits on EINVAL or EBADF.

__run_perf_stat() then calls perf_evsel__free_fd(&counter->core) on the unsupported member while leaving it attached to the user_time leader, and evlist__enable() -> evsel__enable_cpu() -> perf_evsel__run_ioctl() dereferences NULL evsel->fd in xyarray__max_y(evsel->fd).

[ ... ]

tools/perf/builtin-stat.c int cmd_stat(int argc, const char **argv) · line 3024

Quoted 8 lines
tools/perf/builtin-stat.c +4 -0
@@ -2947,6 +3018,11 @@ int cmd_stat(int argc, const char **argv)
 
 	evlist__check_cpu_maps(evsel_list);
 
+	if (check_tool_groups(evsel_list)) {
+		status = -EINVAL;
+		goto out;
+	}

[Severity: Medium]
On hybrid CPU systems, doesn't running evlist__check_cpu_maps() before check_tool_groups() split all tool events out of a core PMU group under -a before check_tool_groups() can refuse it?

On a hybrid machine (such as Intel cpu_core and cpu_atom), core PMU events like cycles have core.cpus restricted to that PMU's CPU subset, while duration_time has 1 CPU and user_time has all online CPUs. Under -a, perf_cpu_map__equal(leader->core.cpus, evsel->core.cpus) is false for both tool events, so evlist__check_cpu_maps() removes both from the group and reduces leader->core.nr_members to 1. check_tool_groups() then sees no group left to refuse, and the new test case in stat+tool_group.sh:

refused '{cycles,duration_time,user_time}' 'user_time|duration_time' -a

exits 0 and fails on hybrid machines.

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