From mboxrd@z Thu Jan 1 00:00:00 1970 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=74.125.82.174 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1796189599; b=T1Tl5xJFSQ15v0XSm6GrFJoRZfbrYxu9LsMiHyrrglMQT58ZfO+3SHnJHSEtnX+9AtBG rzhVPvh1i/nOIA8PDSjuaS7IV8UznLj77gkH2c2nPEWM7dBlrAyBJxMqHKd6Kf42PAn/O 7++11pp0FirzQIQD5BYudrwUDOqNRoPe2cIRGAtDi7va9LvIf+gihgtlhZ4CILzQYKZtD XtSwgDggALVGsDlotbbWoB7X5jIRnR4tMvmwR7aPMQ9XOA7IIgnNfAWG59g5FxepUrdE9 aFjCEVM1yx2omyFh7KoGV4F9WMbeNGL5SrTG2urJ27O2w2CObtNuVMu9RPTmsUunSNQ== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1796189599; h=DMARC-Filter:Received:DKIM-Signature:X-Google-DKIM-Signature: X-Forwarded-Encrypted:X-Gm-Message-State:X-Gm-Gg:X-Received:Received: From:To:Cc:Subject:Date:Message-ID:X-Mailer:In-Reply-To:References: MIME-Version:Content-Transfer-Encoding; bh=zLCsV3/+6tKI7bQ28592sNKtihoNnmk5ilTIIGFhFd8=; b=itzOTUnU0ss6+ay/Iooe6Ts0nU54T0Domxt/r4VR/lG4P/eyZT9fDNCHRgwuqDBRLoaQ PjzDbWpqtrJ4WAFno3hqGSsFn+xwBDJhhZy75naYlA6PAUlPzxahFA9dQMrbM5kGxqusf QD0avkxo3J0Z1yk7AXjFNSEtTRZmdceM8d0JIlRMBvDaghJv3SVVjstt/iLzuA85K35FV GtHXGILL+B370WtwoBXJsHI+30JQbuN4qzNy1jKtllHE43b/L5+OviQM7TK5+rtD/tGXg r0G99OnFz0mZYOYOIYxhpSfWajSeJBXqq7LHGajal34ccY5ur/+DoGgoVbjeTGLXLYw== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=gmail.com; spf=pass smtp.mailfrom=gmail.com; dkim=pass header.d=gmail.com header.i=@gmail.com header.a=rsa-sha256 header.s=20260707 header.b=NKuaD4e4; arc=none smtp.remote-ip=74.125.82.174 Received: from mail-dy1-f174.google.com (mail-dy1-f174.google.com [74.125.82.174]) (using TLSv1.3 with cipher TLS_AES_128_GCM_SHA256 (128/128 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id E8211606A322 for ; Wed, 2 Dec 2026 05:33:18 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org E8211606A322 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=gmail.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.a=rsa-sha256 header.s=20260707 header.b=NKuaD4e4 Received: by mail-dy1-f174.google.com with SMTP id 5a478bee46e88-38692f62b22so2022632eec.0 for ; Tue, 01 Dec 2026 21:33:18 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20260707; t=1796189598; x=1796794398; darn=vger.kernel.org; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:from:to:cc:subject:date :message-id:reply-to:content-type; bh=zLCsV3/+6tKI7bQ28592sNKtihoNnmk5ilTIIGFhFd8=; b=NKuaD4e4dgkGStItEjsn35+UFbo8gHerJt7jcjjv5/xbGIHxjNQ2bNCkxT6igGZ+Nc sbjy1MlgRUplsKCFw2sRb+V5n/JBzdpPOFmF5YQ33vOaXWpTNguc/KJfdWjgfw5caTSf eDprlkrTZZcBzqoIFmUGJTyW4bqBPVjGYKZuEmCUj1gLQcWubqFqxVtJmXBIoY5nb64B uWNHPIL0YlskMVCYO7NXV/CoubAfBAGSp6/81PLndJYfOGM1mplQu33hwKUJatJ6hE+f f0+4qbnQwJWc5ogSaXT1Sp9l351EtXi/aycTEWWdwcqJ7xvVsRuwmDwsxQ748oJzl719 jsmQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20260707; t=1796189598; x=1796794398; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-gg:x-gm-message-state:from :to:cc:subject:date:message-id:reply-to:content-type; bh=zLCsV3/+6tKI7bQ28592sNKtihoNnmk5ilTIIGFhFd8=; b=A9YZP77/um6mMUlJZphZYYrbpxqNfOnAbKmdE9NtZW8bwZg1X33e8oBpRvVH1IbCsZ ppSlH/KY+DjFXKcoyiXP7oYTCh6+0yJkF2s0StbqVyLqR2uUYvWKlCwBhpI+RdvEJle9 TY8H1ziRjGLTbTqvW4o1Jqk672ehoc7F6nrtcV+cR+5WnjCXmc/wfwqeGu86Bovy1s/7 YVfNvRLKxHPF+lG1/Fo9qzqbIrNqoP6OtJsu+3CqBJEc2GbWQSDjIO6Dg6OCi9KaM0yv j4a6MJIdj7tvp7PwpaxxIwR20+UOSgaBpvp/Kq/7rsaNT14J4TFqHwdGE2pXeHN60Rye TXYw== X-Forwarded-Encrypted: i=1; AL+hErFvNMxGAHWbPL+qOPnHm6zyfGU7Ep5THoVFmdRVCflTE0VjyD9oerP2B1YRamZloRzRT9dK7ymvLvI0cYY=@vger.kernel.org X-Gm-Message-State: APuU4Z8Mxe88TSUsSPCRAVeWB3bBKbSXZJFG+X2+EZN0mcOyBbKTSpt5 xHpytZQ62v4AoDf+pNva9MmQ58xkJRGsvbf81ZdJt81LZfLzngVVepBK X-Gm-Gg: AZFdTZdX5KvHhgOW8YimGlEZ6wqrdd2F4Id0DOpW+N29Fqq5mKYN/iI+FTCc09jHd1Y 9uE4wY8BO2cMhbPFr13OYhWJdsqPMPECIMvwc4d+AjO55AWeF4XG1/wVLKEr01CoqIAwiDiWLRu UuSJHsc2kMB2o055//eA8McyIBKqLAIgC8RSRGkvYUuRGlQvp/WNNVi+VjHfAhW+0GUQSEkZfaZ 0eaCw1KgbmatunjsnHSy9GCc3jHr39LsCQQhQ36rtwucy/hoFXSVQRW1SQ4YrVZx+4bLKVqur2X XL/1iJ+2o5dQEYrhKqmCBeLJwf3tJCuHqZCWYGvd4iZMgjkC20I2c0ERGgFQ3xHQrTNODzjYKhQ TZ9yAmEyE3qRzsGC7umpzdIQ+RcG7NxXThytuFpS6LO6pbPiKrK1tzDJRrc9tWxI70/fY0MPwei lPcYKbAmYO/aM7R6bfR7gyBCzAobFsfuEfYWeCIS49DlTkiMyhb/VXfQTPadJqZUE9L+spIeHqU ALzmtumGAe/LP9JTxZkRoSArFZmR2lzAlaI6d77J8pMJHr8X3CuKYAfrMeSWE9E74xOzubTpqJg JTp6SN95PFmN2wpiGt5m X-Received: by 2002:a05:693c:4146:10b0:387:1be3:2c1b with SMTP id 5a478bee46e88-3871be47e6emr5922061eec.15.1796189596945; Tue, 01 Dec 2026 21:33:16 -0800 (PST) Received: from a1-free ([2603:c021:8021:f000:0:1865:8c38:18fc]) by smtp.gmail.com with ESMTPSA id 5a478bee46e88-38567daaf70sm114280982eec.28.2026.12.01.21.33.14 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Tue, 01 Dec 2026 21:33:16 -0800 (PST) From: TAKANO Mitsuhiro To: linux-perf-users@vger.kernel.org, Arnaldo Carvalho de Melo , Namhyung Kim Cc: Ian Rogers , Peter Zijlstra , Ingo Molnar , Mark Rutland , Hang Zhengyang , Alexander Shishkin , Jiri Olsa , Adrian Hunter , James Clark , linux-kernel@vger.kernel.org, TAKANO Mitsuhiro , Sashiko Subject: [PATCH v12] perf stat: Refuse a group mixing tool and kernel events Date: Wed, 2 Dec 2026 05:33:12 +0000 Message-ID: <20261202053312.2695722-1-takano32@gmail.com> X-Mailer: git-send-email 2.53.0 In-Reply-To: <20261201235504.2534857-1-takano32@gmail.com> References: <20261201235504.2534857-1-takano32@gmail.com> X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 Content-Transfer-Encoding: 8bit A tool event has no kernel counterpart: user_time and system_time read /proc/stat, or /proc//stat for a workload, and duration_time keeps its value in perf itself. perf-list(1) says events from different PMUs cannot be grouped except for some software events, and the tool PMU counts as software, so a tool event stays in the group the user wrote. A group of a tool event and an event from a different software PMU, such as cpu-clock, is split by the parser, and evlist__check_cpu_maps() removes members whose CPUs do not match the leader under -a or -C. hwmon and drm are not software PMUs in that sense, so such a group is refused rather than split. What is left is a group that cannot be counted. Before this change, with user_time or system_time as the leader, get_group_fd() handed the procfs descriptor to the members and the kernel rejected each with EBADF. With duration_time as the leader there was no descriptor, so the members got -2 and failed with EINVAL, "broken group leader" appearing only in the debug log. A DEBUG=1 build asserted in the BUG_ON(fd == -1 && leader->supported) below first, and the early returns above now make that BUG_ON unreachable on these paths. Either way perf stat printed the tool event and "" for the rest of the group: $ perf stat -e '{user_time,cycles}' -- sleep 0.05 0 user_time cycles Before this change too, with a kernel event as the leader, the members did open, but the group read failed with ENOSPC. perf sized the buffer for leader->core.nr_members entries, which included the tool event, while the kernel filled in one entry fewer; readn() then asked for the remainder with a count below the kernel's read_size, so the rest of the group came out as "". That was the shape of -e '{cycles,instructions,duration_time}', which had not been counted since commit 6828d6929b76 ("perf evsel: Refactor tool events"). Counting such a group means moving the leader to a kernel event and letting the group read skip the tool members; that is left to a separate series. Splitting the tool event out and warning, as evlist__check_cpu_maps() does, would let the kernel events count, but the tool event would lose the group's window and the warning is easy to miss in a script. The braces are the user's explicit request, so perf stat should not quietly reinterpret them. Ian's "perf pmu: Don't treat tool PMU as a kernel software PMU for event grouping" splits it in the parser and this check then has nothing to refuse; Hang's patch opens the members with group_fd = -1 instead, which this check preempts. Only one of the three should be applied. Refuse the group before the workload is started: A tool event cannot be grouped with kernel events: user_time That is followed by "Put it outside the braces", as in -e '{cycles,instructions},duration_time'. perf stat used to leave the rest of the group uncounted and exit 0; it now exits 22. Namhyung Kim preferred the refusal to counting the events one by one. A leader that has no perf_event_open() descriptor, such as a tool event, a hwmon or drm event, or a retire-latency event, returns -2 before its fd array is read, and BUG_ON(!leader->core.fd) is gone: only a retire-latency leader has no array at all, so that is no longer a bug. The same change sets errno for the -2 it returns, EINVAL, so a weak group whose leader was skipped is split as well rather than keep members that then have no fd to enable; a strong group keeps the leader's errno, so an unprivileged open still reports the perf_event_paranoid diagnostic. Where the core PMU covers only part of the CPUs (hybrid x86, big.LITTLE arm64), evlist__check_cpu_maps() takes the tool event out first under -a, so no mixed group is left to refuse. Sashiko's review of v4 had already raised this, together with the NULL dereference that the get_group_fd() change above prevents. The test no longer requires cycles to be printed when no hardware cycles event can be counted: the evsel falls back to task-clock or is renamed, and the group output is still checked. A weak group led by a tool event under -a is now run as well, so the crash above stays fixed. The test refuses the group under -p and -C as well, requires a tool event to be counted rather than printed as "", and takes for the hybrid case only a name that appears both counted and uncounted. Sashiko's review of v6 found that a weak group led by a tool event is not split when the member that keeps no descriptor is a retire-latency event: evsel__open_cpu() returns from evsel__tpebs_open() without a descriptor and without asking for the group fd, so the member keeps core.fd == NULL and stays in the group. Enabling the leader walked into it, and so did disabling it, which -a and -p always do around the workload: evsel__enable_cpu() and evsel__disable_cpu() now skip a member whose fd array is NULL, and the guard is on evsel__enable() and evsel__disable() too so that the next caller of those does not have to rediscover it. get_group_fd() returns -2 for a retire-latency leader as it does for a tool leader, instead of reading the NULL fd array. The test's "" check was too strict on a hybrid machine: an unqualified cycles expands into one evsel per core PMU, a per-task run uses one core type only, and the other PMU prints "". The test now skips a group that counted at least one event and fails one that counted nothing, which is the regression it is for. The retire-latency case runs under -a, without which the workload starts with enable_on_exec and the group is never enabled or disabled here. I built perf, ran tools/perf/tests/shell/stat+tool_group.sh and checkpatch.pl --strict. The -a segmentation fault above was reproduced here before the guard; with the guard the command exits 0 and prints for cycles:k. The EBADF and the group-read failure were not re-observed: kernel events cannot be opened here (perf_event_paranoid=4). The hybrid skip was not exercised: this machine is not hybrid. The retire-latency group runs here without crashing, but this machine has no PMU that reports retire latency, so the member is read as zero rather than measured. The hwmon and drm paths were read, not run: this machine has neither PMU, and the test covers tool events only. Fixes: 6828d6929b76 ("perf evsel: Refactor tool events") Reported-by: Sashiko Link: https://lore.kernel.org/all/sashiko-outbox-227849@kernel.org/ Link: https://lore.kernel.org/all/sashiko-outbox-231330@kernel.org/ Link: https://lore.kernel.org/all/sashiko-outbox-232396@kernel.org/ Cc: Hang Zhengyang Link: https://lore.kernel.org/all/20261111-tool-pmu-leader-v2-1-3faa0fb98c51@gmail.com/ Suggested-by: Namhyung Kim Link: https://lore.kernel.org/all/awC_aZXD5FBGu4mO@google.com/ Link: https://lore.kernel.org/all/awTXdgY38s2bijW5@google.com/ Cc: Ian Rogers Link: https://lore.kernel.org/all/20261123071913.653315-7-irogers@google.com/ Signed-off-by: TAKANO Mitsuhiro --- v12: Four reviews of v11, three of them on the man page. The man page said a group that mixes a hwmon or drm event is not split. Only the group with a software event and such an event is not split: -e '{hwmon_x,cycles}' is split like any other group across PMUs. It also attributed the split to -a and -C rather than to evlist__check_cpu_maps(), which runs on every command, and said a tool event is taken out when the core PMU covers part of the CPUs. Measured: -a removes duration_time, read on one CPU, and keeps user_time and system_time, read on every CPU, so -e '{cycles,user_time}' is still refused under -a. The refusal condition is 'next to an event perf opens with perf_event_open()', not 'an event another PMU', so a group of a tool event and a hwmon event, which is not refused, is not described as refused either. The commit message said every -2 from get_group_fd() sets an errno; it sets EINVAL for the leader perf does not open, and for fd == -1 only for a weak group, so a strong group keeps the leader's errno. The test read the hybrid case from any numbered line, so a group that counted nothing could be taken for a hybrid machine; it now needs the same event counted and uncounted, with the PMU prefix and the metric comment stripped. A tool event printed as '' was a skip in three more places; it is a failure everywhere now. The refusal message is anchored to 'A tool event', the -p and -C cases are refused as well, the -C case is skipped when CPU 0 is not online, and the retire-latency case is skipped where -a cannot be used. Rebuilt perf, ran stat+tool_group.sh: 6 skipped, no failures, and checkpatch.pl --strict: 0 errors, 1 warning for the new test file. tools/perf/Documentation/perf-stat.txt | 25 ++ tools/perf/builtin-stat.c | 76 +++++ tools/perf/tests/shell/stat+tool_group.sh | 386 ++++++++++++++++++++++ tools/perf/util/evsel.c | 111 ++++++- 4 files changed, 584 insertions(+), 14 deletions(-) create mode 100755 tools/perf/tests/shell/stat+tool_group.sh diff --git a/tools/perf/Documentation/perf-stat.txt b/tools/perf/Documentation/perf-stat.txt index 8ea17da89976..f14fea70f8fb 100644 --- a/tools/perf/Documentation/perf-stat.txt +++ b/tools/perf/Documentation/perf-stat.txt @@ -65,6 +65,31 @@ 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 + stat itself and have no event in the kernel; a hwmon event reads + a sysfs file and a drm event reads /proc//fdinfo. None of + them is opened with perf_event_open. The parser splits a group + whose members are from different PMUs, and warns that events were + regrouped, except when a member is from a software PMU and takes + the PMU name of a member that is not, or when the leader is an aux + event such as intel_pt and names the whole group. A tool event + and cpu-clock, both from software PMUs, are split. A member whose + CPUs do not match the CPUs of the leader is removed from the group + before it is checked, which is what -a and -C usually cause: -a + removes duration_time, read on one CPU, and keeps user_time and + system_time, read on every CPU. A group that is not split and + holds an event perf stat does not open next to an event that perf + opens with perf_event_open() is refused, as in + -e '{user_time,cycles}', instead of printing the event and leaving + the rest of the group uncounted. Put it 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 such an event is left to the weak group handling, which + splits it when a member fails to open with EINVAL or EBADF; a + member perf stat does not open itself, such as a retire-latency + event, keeps no descriptor and is skipped when the group is + enabled or disabled. Any other weak group that mixes them is + refused like a strong group. -i:: --no-inherit:: diff --git a/tools/perf/builtin-stat.c b/tools/perf/builtin-stat.c index 37752d6bfef4..4fa3958c4cf3 100644 --- a/tools/perf/builtin-stat.c +++ b/tools/perf/builtin-stat.c @@ -2469,6 +2469,77 @@ static int parse_tpebs_mode(const struct option *opt, const char *str, } #endif // HAVE_ARCH_X86_64_SUPPORT +/* + * An event perf does not open with perf_event_open has no event in the + * kernel: a tool event like user_time is read from a file such as + * /proc/stat or computed in perf itself, hwmon reads a sysfs file, and + * drm reads /proc//fdinfo. A group that mixes one with an event + * the kernel opens cannot be counted. get_group_fd() has no group fd to + * hand to the members when the leader is such an event, so the members + * cannot be in a kernel group with it; 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 such an event is left to the weak group handling in the + * open loop, which splits it when a member fails to open; any other weak + * group is refused like a strong one. + */ +static int check_unopened_in_group(struct evlist *evlist) +{ + struct evsel *leader, *evsel; + + evlist__for_each_entry(evlist, leader) { + struct evsel *unopened = 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. + */ + evlist__for_each_entry(evlist, evsel) { + if (!evsel__has_leader(evsel, leader)) + continue; + if (evsel__is_non_perf_event_open_pmu(evsel)) { + if (!unopened) + unopened = evsel; + } else { + has_kernel = true; + } + weak |= evsel->weak_group; + } + + if (!unopened || !has_kernel) + continue; + + /* + * A weak group led by an event perf does not open is left to + * the weak group handling in the open loop: get_group_fd() + * returns -2 for such a leader, the open fails with EINVAL, + * and that is what splits the group. Any other weak group + * does not get that far, so it is refused like a strong one. + */ + if (weak && evsel__is_non_perf_event_open_pmu(leader)) + continue; + + if (evsel__is_tool(unopened)) { + pr_err("A tool event cannot be grouped with kernel events: %s\n", + evsel__name(unopened)); + } else { + pr_err("An event perf does not open cannot be grouped with kernel events: %s\n", + evsel__name(unopened)); + } + pr_err("Put it outside the braces, as in -e '{cycles,instructions},duration_time'.\n"); + return -EINVAL; + } + return 0; +} + int cmd_stat(int argc, const char **argv) { struct opt_aggr_mode opt_mode = {}; @@ -2947,6 +3018,11 @@ int cmd_stat(int argc, const char **argv) evlist__check_cpu_maps(evsel_list); + if (check_unopened_in_group(evsel_list)) { + status = -EINVAL; + goto out; + } + /* * Initialize thread_map with comm names, * so we could print it out on output. diff --git a/tools/perf/tests/shell/stat+tool_group.sh b/tools/perf/tests/shell/stat+tool_group.sh new file mode 100755 index 000000000000..4a2aae62321c --- /dev/null +++ b/tools/perf/tests/shell/stat+tool_group.sh @@ -0,0 +1,386 @@ +#!/bin/bash +# SPDX-License-Identifier: GPL-2.0 +# perf stat tool events in an event group (no_mlock) + +set -e +export LC_ALL=C + +out= +stderr= +err=0 +skipped=0 + +cleanup() { + rm -f "${out}" "${stderr}" + + trap - EXIT TERM INT +} + +trap_cleanup() { + echo "Unexpected signal in ${FUNCNAME[1]}" + cleanup + exit 1 +} +trap trap_cleanup EXIT TERM INT + +out=$(mktemp /tmp/__perf_test.stat_tool_group.XXXXXX) +stderr=$(mktemp /tmp/__perf_test.stat_tool_group.XXXXXX) + +# A tool event has no event in the kernel: perf reads it from a file such +# as /proc/stat, or computes it in perf itself, so it cannot be counted in +# a group that is opened with perf_event_open(). Such a group used to +# print the tool event and leave the rest of the group uncounted, so perf +# stat has to say what is wrong instead. + +# Whether this kernel lets the user open a hardware event decides whether +# the accepted cases can show a measured value at all. An event that is +# not supported prints a "" line even when perf stat exits 0. +kernel_events=1 +if ! perf stat -e cycles -o "${out}" -- true 2> /dev/null || + grep -q "" "${out}" || + ! grep -q "cycles" "${out}"; then + kernel_events=0 +fi + +# CPU-wide events need root or perf_event_paranoid <= 0, so -a can fail even +# when a per-thread event works. +syswide=1 +if ! perf stat -a -e cycles -o /dev/null -- true 2> /dev/null; then + syswide=0 +fi + +refused() { + local group="$1" tool="$2" rc=0 + shift 2 + + echo "Testing that perf stat refuses ${group} $*" + perf stat "$@" -e "${group}" -o "${out}" -- true 2> "${stderr}" || rc=$? + + if [ "${rc}" = 0 ]; then + echo "perf stat accepted ${group} [Failed]" + err=1 + return + fi + if [ "${rc}" != 22 ]; then + echo "perf stat failed with ${rc}, expected 22 [Failed]" + cat "${stderr}" + err=1 + fi + if ! grep -qE "^A tool event cannot be grouped with kernel events: (${tool})([/:][^ ]*)?$" \ + "${stderr}"; then + echo "perf stat failed without naming ${tool} as a tool event [Failed]" + cat "${stderr}" + err=1 + fi + if ! grep -q "Put it outside the braces" "${stderr}"; then + echo "perf stat failed without saying how to write it [Failed]" + cat "${stderr}" + err=1 + fi +} + +# A group may hold two events perf stat does not open, and the message names +# whichever comes first in the evlist, so accept either name and either +# wording. The refusal itself still has to be there. +refused_either() { + local group="$1" rc=0 + local pattern="^(A tool event|An event perf does not open) cannot be grouped" + + pattern="${pattern} with kernel events: (user_time|cycles:R)\$" + + echo "Testing that perf stat refuses ${group}" + perf stat -e "${group}" -o "${out}" -- true 2> "${stderr}" || rc=$? + + if [ "${rc}" != 22 ]; then + echo "perf stat did not refuse ${group} with 22 (${rc}) [Failed]" + cat "${stderr}" + err=1 + return + fi + if ! grep -qE "${pattern}" "${stderr}"; then + echo "perf stat refused ${group} without naming an event perf does not open [Failed]" + cat "${stderr}" + err=1 + fi +} + +# A counted event has a number in the first column; an event perf stat could +# not open prints "" instead. +counted() { + local name="$1" + + grep -qE "^[[:space:]]*[0-9][0-9,.]*[[:space:]]+(${name})([/:][^ ]*)?[[:space:]]*$" \ + "${out}" +} + +# A hybrid machine expands an unqualified cycles into one evsel per core PMU +# and counts only the core type the task ran on, so that name shows up both +# counted and as , possibly with a PMU prefix and a metric +# comment after it. A group that is simply not counted shows the name in the +# column only, which is the regression to catch. +hybrid_core_types() { + awk 'function bare(name) { + gsub(/\/$/, "", name) + sub(/^[^\/]*\//, "", name) + return name + } + FNR == NR { + sub(/#.*/, "") + if ($1 ~ /^[0-9][0-9,.]*$/) + counted[bare($(NF))] = 1 + next + } + // { + sub(/#.*/, "") + if (bare($(NF)) in counted) + found = 1 + } + END { exit !found }' "${out}" "${out}" +} + +# The events named after the group have to show up in the output. +accepted() { + local group="$1" name rc=0 + + shift + echo "Testing that perf stat accepts ${group}" + perf stat -e "${group}" -o "${out}" -- true 2> "${stderr}" || rc=$? + + if [ "${rc}" != 0 ]; then + cat "${stderr}" + echo "perf stat failed for ${group} (${rc}) [Failed]" + err=1 + return + fi + if grep -q "cannot be grouped with kernel events" "${stderr}"; then + cat "${stderr}" + echo "perf stat refused ${group} [Failed]" + err=1 + return + fi + for name in "$@"; do + case "${name}" in + cycles|cycles:*|instructions|instructions:*) + # When no hardware cycles event can be counted, cycles falls back to + # task-clock and the evsel is renamed, so it need not appear. + [ "${kernel_events}" = 0 ] && continue ;; + *) + # perf reads a tool event itself, so the kernel's permissions do not + # decide whether it is counted: "" here is a bug. + if ! counted "${name}"; then + echo "perf stat did not count ${name} [Failed]" + cat "${out}" + err=1 + fi + continue ;; + esac + if ! grep -q -- "${name}" "${out}"; then + echo "perf stat did not print ${name} [Failed]" + cat "${out}" + err=1 + fi + done + if grep -q "" "${out}"; then + if [ "${kernel_events}" = 1 ]; then + echo "perf stat could not open an event in ${group} [Failed]" + cat "${out}" + err=1 + else + paranoid=$(cat /proc/sys/kernel/perf_event_paranoid 2>/dev/null || echo unknown) + echo "perf stat could not open an event in ${group} (paranoid=${paranoid}) [Skipped]" + skipped=$((skipped + 1)) + fi + elif grep -q "" "${out}"; then + if [ "${kernel_events}" = 1 ] && hybrid_core_types; then + echo "perf stat counted only one core type of ${group} [Skipped]" + skipped=$((skipped + 1)) + else + echo "perf stat did not count an event in ${group} [Failed]" + cat "${out}" + err=1 + fi + fi +} + +# The tool event as the leader and as a member, a common group that puts +# the tool event last, and a weak group led by a kernel event, which is +# refused the same way. +refused '{user_time,cycles}' user_time +refused '{cycles,user_time}' user_time +refused '{duration_time,instructions}' duration_time +refused '{cycles,instructions,duration_time}' duration_time +refused '{cycles,user_time}:W' user_time + +# The tool event in the middle of a group, and the first of two tool +# events, which is the one the message names. +refused '{cycles,user_time,instructions}' user_time +refused '{user_time,system_time,cycles}' user_time + +# The leader is the event perf stat does not open: a retire-latency leader +# keeps no fd array at all, and a strong group is refused before the open. +# Either event of the group can be the one the message names, since a +# retire-latency event is not opened with perf_event_open() either, and the +# parser is free to sort it before the tool event. +refused_either '{cycles:R,user_time}' +refused_either '{user_time,cycles:R}' + +# -p keeps the any-CPU map of the plain case, but without enable_on_exec perf +# stat enables and disables the group itself, so the refusal has to come +# before the open. +refused '{user_time,cycles}' user_time -p $$ + +# -C keeps the CPU map the user asked for. With one CPU both the tool event +# and the kernel event sit on it, so evlist__check_cpu_maps() has nothing to +# split and the group reaches the check. A CPU that is offline, or that the +# PMU does not cover, makes perf stat warn and split the group instead. +if grep -qE '(^|,)0(,|$)' /sys/devices/system/cpu/online 2>/dev/null; then + refused '{cycles,duration_time}' duration_time -C 0 +else + echo "CPU 0 is not online, cannot test -C [Skipped]" + skipped=$((skipped + 1)) +fi + +# evlist__check_cpu_maps() takes duration_time out of this group (it is +# read on one CPU only), which leaves cycles and user_time apart in the +# evlist; the tool event has to be found anyway. On a machine with one +# CPU there is nothing to split, so either tool event can be the first. +# Whether the group is refused or split depends on the machine, and the +# test accepts both, but it must not reach the tool event through a +# member with no descriptor either way. +rc=0 +perf stat -a -e '{cycles,duration_time,user_time}' -o "${out}" -- true \ + 2> "${stderr}" || rc=$? +if [ "${rc}" -ge 128 ]; then + echo "perf stat crashed on -a [Failed]" + err=1 +elif [ "${rc}" -eq 0 ]; then + if [ "${syswide}" = 1 ] && [ "${kernel_events}" = 1 ]; then + # -a opens every evsel on the CPUs of its own PMU, so a hybrid machine + # does not leave a copy uncounted here the way a per-task run does. + if grep -q "" "${out}"; then + echo "perf stat could not open an event on -a [Failed]" + cat "${out}" + err=1 + elif grep -q "" "${out}"; then + echo "perf stat left an event uncounted on -a [Failed]" + cat "${out}" + err=1 + elif ! counted user_time; then + echo "perf stat dropped user_time from -a [Failed]" + cat "${out}" + err=1 + fi + else + echo "perf stat counted -a without full access [Skipped]" + skipped=$((skipped + 1)) + fi +elif [ "${rc}" -eq 22 ]; then + if ! grep -qE "A tool event cannot be grouped with kernel events: (user_time|duration_time)" \ + "${stderr}" || + ! grep -q "Put it outside the braces" "${stderr}"; then + echo "perf stat refused -a without the full message [Failed]" + cat "${stderr}" + err=1 + fi +elif [ "${rc}" -ne 0 ]; then + echo "perf stat left -a with ${rc} [Failed]" + cat "${stderr}" + err=1 +fi + +# A group of tool events only is read by perf itself, a single event in +# braces is not a group, a tool event outside the braces is not a member, +# and a weak group led by a tool event is split by the weak group +# handling. The member of such a group must never be enabled through a +# descriptor that was freed; that used to crash under -a when the open of +# the member failed outside the split conditions. +rc=0 +perf stat -a -e '{user_time,cycles:k}:W' -o "${out}" -- true \ + 2> "${stderr}" || rc=$? +if [ "${rc}" -ge 128 ]; then + echo "perf stat crashed on a weak tool group under -a [Failed]" + err=1 +elif [ "${rc}" -ne 0 ]; then + echo "perf stat left a weak tool group under -a with ${rc} [Failed]" + cat "${stderr}" + err=1 +elif ! counted user_time; then + echo "perf stat dropped user_time from a weak tool group under -a [Failed]" + cat "${out}" + err=1 +fi + +# A retire-latency event is read by the TPEBS reader rather than opened with +# perf_event_open(), so it keeps no descriptor even while it is a member of +# the group. A weak group led by a tool event is not split when such a +# member fails to open, so the member stays in the group, and enabling or +# disabling the group used to walk to it and dereference the NULL +# descriptor. -a and -p walk the group around the workload; a workload +# that starts with enable_on_exec does not, so this case needs -a, and is +# skipped where -a cannot be used. A crash is the failure: the event needs +# a PMU that reports retire latency, and the run is free to count nothing. +if [ "${syswide}" = 0 ]; then + echo "perf stat cannot use -a here, retire-latency case [Skipped]" + skipped=$((skipped + 1)) +else + rc=0 + perf stat -a -e '{user_time,cycles:R}:W' -o "${out}" -- true \ + 2> "${stderr}" || rc=$? + if [ "${rc}" -ge 128 ]; then + echo "perf stat crashed on a retire-latency member in a tool group [Failed]" + cat "${stderr}" + err=1 + elif [ "${rc}" -eq 0 ]; then + if ! counted user_time; then + echo "perf stat dropped user_time from a retire-latency tool group [Failed]" + cat "${out}" + err=1 + elif ! awk '$1 ~ /^[0-9][0-9,.]*$/ && $1 + 0 > 0 && $2 ~ /^cycles:R$/ { found = 1 } + END { exit !found }' "${out}"; then + echo "perf stat read no retire latency here [Skipped]" + skipped=$((skipped + 1)) + fi + else + # A weak group led by a tool event is split by the weak group handling, + # so perf stat is not expected to refuse this one: an exit here is a bug. + echo "perf stat left a retire-latency tool group with ${rc} [Failed]" + cat "${stderr}" + err=1 + fi +fi + +accepted '{user_time,system_time}' user_time system_time +accepted '{duration_time,user_time}' duration_time user_time +accepted '{user_time}' user_time +accepted '{cycles,instructions},duration_time' duration_time cycles instructions +accepted '{user_time,cycles}:W' user_time cycles +accepted '{system_time,cycles}:W' system_time cycles +accepted '{duration_time,cycles}:W' duration_time cycles + +echo "Testing that a tool event on its own is accepted" +if ! perf stat -e user_time -o "${out}" -- true; then + echo "perf stat rejected a tool event on its own [Failed]" + err=1 +elif ! counted user_time; then + echo "perf stat did not print user_time [Failed]" + cat "${out}" + err=1 +fi + +echo "Testing that the default events still work" +if ! perf stat -o "${out}" -- true; then + echo "perf stat without -e failed [Failed]" + err=1 +fi + +cleanup + +if [ "${err}" = 0 ] && [ "${skipped}" -gt 0 ]; then + echo "perf stat tool event group test [Success] (${skipped} skipped)" +elif [ "${err}" = 0 ]; then + echo "perf stat tool event group test [Success]" +else + echo "perf stat tool event group test [Failed]" +fi + +exit "${err}" diff --git a/tools/perf/util/evsel.c b/tools/perf/util/evsel.c index d060fca8090f..ff8e8e322858 100644 --- a/tools/perf/util/evsel.c +++ b/tools/perf/util/evsel.c @@ -1922,7 +1922,22 @@ int evsel__enable_cpu(struct evsel *evsel, int cpu_map_idx) * group leader. We must manually enable them in * userspace. */ - int mem_err = evsel__enable_cpu(member, cpu_map_idx); + int mem_err; + + /* + * A member the kernel never opened keeps no + * descriptor, and one whose open failed has + * had it freed. A weak group led by a tool + * event is not split when such a member + * fails, so it is still in the group here: + * there is nothing to enable for it, and + * passing its NULL descriptor to the ioctl + * would dereference it. + */ + if (!member->core.fd) + continue; + + mem_err = evsel__enable_cpu(member, cpu_map_idx); if (mem_err) return mem_err; @@ -1957,10 +1972,20 @@ int evsel__enable(struct evsel *evsel) * group leader. We must manually enable them in * userspace. */ - int mem_err = evsel__enable(member); + int mem_err; - if (mem_err) - return mem_err; + /* + * A member with no descriptor was never + * opened, or its open failed and freed + * one. It has nothing to enable, and its + * flag is updated with the rest below. + */ + if (member->core.fd) { + mem_err = evsel__enable(member); + + if (mem_err) + return mem_err; + } } member->disabled = false; } @@ -1991,7 +2016,19 @@ int evsel__disable_cpu(struct evsel *evsel, int cpu_map_idx) * kernel when disabling the group leader. We must * manually disable them in userspace. */ - int mem_err = evsel__disable_cpu(member, cpu_map_idx); + int mem_err; + + /* + * A member with no descriptor was never + * opened, or its open failed and freed + * one. A weak group led by a tool event + * keeps such a member, so there is + * nothing to disable for it here. + */ + if (!member->core.fd) + continue; + + mem_err = evsel__disable_cpu(member, cpu_map_idx); if (mem_err) return mem_err; @@ -2031,10 +2068,20 @@ int evsel__disable(struct evsel *evsel) * kernel when disabling the group leader. We must * manually disable them in userspace. */ - int mem_err = evsel__disable(member); + int mem_err; - if (mem_err) - return mem_err; + /* + * A member with no descriptor was never + * opened, or its open failed and freed + * one. It has nothing to disable, and its + * flag is updated with the rest below. + */ + if (member->core.fd) { + mem_err = evsel__disable(member); + + if (mem_err) + return mem_err; + } } member->disabled = true; } @@ -2371,23 +2418,59 @@ static int get_group_fd(struct evsel *evsel, int cpu_map_idx, int thread) return -1; /* - * Leader must be already processed/open, - * if not it's a bug. + * Leader must already be processed/open, unless it is one of the + * events perf reads itself: a tool event keeps a procfs descriptor + * or none, and a retire-latency event keeps none. Both are refused + * below rather than treated as a bug. */ - BUG_ON(!leader->core.fd); - cpu_map_idx = evsel__hybrid_group_cpu_map_idx(evsel, cpu_map_idx); if (cpu_map_idx == -1) return -1; + if (evsel__is_non_perf_event_open_pmu(leader)) { + /* + * A tool event has no perf_event_open() descriptor, or has + * only a procfs one (user_time, system_time); hwmon keeps a + * sysfs one and drm keeps none. None of them can be a group + * fd for the members. builtin-stat.c decides on the weak + * group split from errno. + */ + errno = EINVAL; + return -2; + } + if (!leader->core.fd) { + /* + * A leader that was never opened, or whose open freed its + * descriptor, has no group fd to hand out. A retire-latency + * leader is read by the TPEBS reader rather than opened, and + * a weak group keeps it, so report it the way the open loop + * expects instead of reading the NULL array. + */ + errno = EINVAL; + return -2; + } + fd = FD(leader, cpu_map_idx, thread); BUG_ON(fd == -1 && leader->supported); /* * When the leader has been skipped, return -2 to distinguish from no - * group leader case. + * group leader case. Set errno the same way the two refusals above + * do, so that the open loop splits the weak group for either. */ - return fd == -1 ? -2 : fd; + if (fd == -1) { + /* + * A weak group is split on EINVAL, but a strong group must + * keep the leader's errno: an unprivileged open that failed + * with EACCES has to keep reporting the perf_event_paranoid + * diagnostic rather than turn into "Invalid argument". + */ + if (evsel->weak_group) + errno = EINVAL; + return -2; + } + + return fd; } static void evsel__remove_fd(struct evsel *pos, int nr_cpus, int nr_threads, int thread_idx) base-commit: b6a9fa34ce4187cb69d3c588a4bbffc31ce5db8f -- 2.53.0