From e1089e0520482e62336a8d6efa40e064fd9796d8 Mon Sep 17 00:00:00 2001 From: Thiago Macieira Date: Wed, 19 Oct 2022 10:45:52 -0700 Subject: [PATCH] QBenchlib/Perf: don't try to benchmark the kernel The kernel has become more paranoid since 2013, when I originally wrote this code. The kernel.perf_event_paranoid sysctl controls the paranoia level[1]: === ================================================================== -1 Allow use of (almost) all events by all users. Ignore mlock limit after perf_event_mlock_kb without ``CAP_IPC_LOCK``. >=0 Disallow ftrace function tracepoint by users without ``CAP_PERFMON``. Disallow raw tracepoint access by users without ``CAP_PERFMON``. >=1 Disallow CPU event access by users without ``CAP_PERFMON``. >=2 Disallow kernel profiling by users without ``CAP_PERFMON``. === ================================================================== Since the default is 2, we QBenchlib has been failing with EACCESS: PASS : tst_MyClass::initTestCase() QBenchmarkPerfEventsMeasurer::start: perf_event_open: Permission denied [ChangeLog][QtTest] Fixed support of Linux performance counters for QBENCHMARK, which used to fail with "Permission denied" errors in default configurations. Now, QtTest will automatically fall back to profiling only userspace, like the perf(1) tool does. [1] https://github.com/torvalds/linux/blob/master/Documentation/admin-guide/sysctl/kernel.rst#perf-event-paranoid Pick-to: 5.15 6.2 6.4 Change-Id: I3c79b7e08fa346988dfefffd171f897be7794935 Reviewed-by: Giuseppe D'Angelo Reviewed-by: David Faure --- src/testlib/qbenchmarkperfevents.cpp | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/src/testlib/qbenchmarkperfevents.cpp b/src/testlib/qbenchmarkperfevents.cpp index df7f236aad..a284b86846 100644 --- a/src/testlib/qbenchmarkperfevents.cpp +++ b/src/testlib/qbenchmarkperfevents.cpp @@ -479,11 +479,17 @@ void QBenchmarkPerfEventsMeasurer::start() { initPerf(); if (fd == -1) { - // pid == 0 -> attach to the current process - // cpu == -1 -> monitor on all CPUs - // group_fd == -1 -> this is the group leader - // flags == 0 -> reserved, must be zero - fd = perf_event_open(&attr, 0, -1, -1, PERF_FLAG_FD_CLOEXEC); + pid_t pid = 0; // attach to the current process only + int cpu = -1; // on any CPU + int group_fd = -1; + int flags = PERF_FLAG_FD_CLOEXEC; + fd = perf_event_open(&attr, pid, cpu, group_fd, flags); + if (fd == -1) { + // probably a paranoid kernel (/proc/sys/kernel/perf_event_paranoid) + attr.exclude_kernel = true; + attr.exclude_hv = true; + fd = perf_event_open(&attr, pid, cpu, group_fd, flags); + } if (fd == -1) { perror("QBenchmarkPerfEventsMeasurer::start: perf_event_open"); exit(1);