You are not logged in.
I refer to this post on Unix / Linux SE but will tailor it here just for Arch:
When reading the Performance Counters (PMC) on CPUS, the kernel.perf_event_paranoid must be <=1 (see Kernel doc)
The program below reads the PMC and should exit early with 1, if it cannot open the counter i.e. kernel.perf_event_paranoid is >1 (check after `syscall`)
Now, by default, the parameter is 2. I run the program and it should not be able to open the perf counter. I can however, still do it.
My question is why?
This script could help to reproduce:
#!/bin/bash
cat >pmc.c <<'EOF'
#include <linux/perf_event.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <unistd.h>
static struct perf_event_attr attr;
static int fdperf = -1;
static struct perf_event_mmap_page *buf = 0;
long long cpucycles_amd64rdpmc(void) {
long long result;
unsigned int seq;
long long index;
long long offset;
if (fdperf == -1) {
attr.type = PERF_TYPE_HARDWARE;
attr.config = PERF_COUNT_HW_CPU_CYCLES;
attr.exclude_kernel = 1;
fdperf = syscall(__NR_perf_event_open, &attr, 0, -1, -1, 0);
if (fdperf == -1){
fprintf(stderr, "\033[31m--> could not open perf counter. Check paranoid setting\033[0m\n");
exit(1);
}
buf = mmap(NULL, sysconf(_SC_PAGESIZE), PROT_READ, MAP_SHARED, fdperf, 0);
}
do {
seq = buf->lock;
asm volatile("" ::: "memory");
index = buf->index;
offset = buf->offset;
asm volatile("rdpmc;shlq $32,%%rdx;orq %%rdx,%%rax"
: "=a"(result)
: "c"(index - 1)
: "%rdx");
asm volatile("" ::: "memory");
} while (buf->lock != seq);
result += offset;
result &= 0xffffffffffff;
return result;
}
int main() {
long long c = cpucycles_amd64rdpmc();
printf("counter: %llx\n", c);
return 0;
}
EOF
param_name=kernel.perf_event_paranoid
read_pmc() {
echo -n "--> reading, "
sysctl "${param_name}"
}
set_pmc() {
n=$1
echo -e "--> setting to ${n}"
sudo sysctl -w "${param_name}=${n}"
read_pmc
echo "should be ${n}"
}
run() {
echo "--> running"
./pmc
}
#compile
gcc pmc.c -o pmc
read_pmc
run
echo -e "\n--> if ${param_name} as >1, that should have printed the error message\n\n"
# at point we could actually stop the test, as the number is 2
# but for completeness, I kept the rest.
set_pmc 1
run
echo -e "\n--> that should have worked and printed the counter.\n"
#re-set to 2
set_pmc 2
run
echo -e "\033[31m--> that should NOT have worked but it printed the counter\033[0m.\n"
rm pmc.c pmc(rdpmc code is based on cpucycles/amd64rdpmc.c from SUPERCOP )
My system: Linux arch4 5.18.6-arch1-1 #1 SMP PREEMPT_DYNAMIC Wed, 22 Jun 2022 18:10:56 +0000 x86_64 GNU/Linux
Last edited by joel10 (2022-07-28 08:29:02)
Offline