[PATCH 1/3] perf pmu: Limit PMU cpumask to online CPUs

From: Yicong Yang
Date: Mon Jun 03 2024 - 05:41:35 EST


From: Yicong Yang <yangyicong@xxxxxxxxxxxxx>

We'll initialize the PMU's cpumask from "cpumask" or "cpus" sysfs
attributes if provided by the driver without checking the CPUs
are online or not. In such case that CPUs provided by the driver
contains the offline CPUs, we'll try to open event on the offline
CPUs and then rejected by the kernel:

[root@localhost yang]# echo 0 > /sys/devices/system/cpu/cpu0/online
[root@localhost yang]# ./perf_static stat -e armv8_pmuv3_0/cycles/ --timeout 100
Error:
The sys_perf_event_open() syscall returned with 19 (No such device) for event (cpu-clock).
/bin/dmesg | grep -i perf may provide additional information.

So it's better to do a double check in the userspace and only include
the online CPUs from "cpumask" or "cpus" to avoid opening events on
offline CPUs.

Signed-off-by: Yicong Yang <yangyicong@xxxxxxxxxxxxx>
---
tools/perf/util/pmu.c | 13 +++++++++++--
1 file changed, 11 insertions(+), 2 deletions(-)

diff --git a/tools/perf/util/pmu.c b/tools/perf/util/pmu.c
index 888ce9912275..51e8d10ee28b 100644
--- a/tools/perf/util/pmu.c
+++ b/tools/perf/util/pmu.c
@@ -771,8 +771,17 @@ static struct perf_cpu_map *pmu_cpumask(int dirfd, const char *name, bool is_cor
continue;
cpus = perf_cpu_map__read(file);
fclose(file);
- if (cpus)
- return cpus;
+ if (cpus) {
+ struct perf_cpu_map *intersect __maybe_unused;
+
+ if (perf_cpu_map__is_subset(cpu_map__online(), cpus))
+ return cpus;
+
+ intersect = perf_cpu_map__intersect(cpus, cpu_map__online());
+ perf_cpu_map__put(cpus);
+ if (intersect)
+ return intersect;
+ }
}

/* Nothing found, for core PMUs assume this means all CPUs. */
--
2.24.0