From f2006eaa5901d6ccf51d24b18c644f2fb1d41757 Mon Sep 17 00:00:00 2001 From: Andrii Nakryiko Date: Fri, 17 Dec 2021 14:20:32 -0800 Subject: [PATCH] libbpf-tools: fix cpufreq.bpf.c and update cpufreq for libbpf 1.0 Switch to libbpf 1.0 mode and adapt libbpf API usage accordingly. Also fix cachestat.bpf.c by adding a BPF assembly trick to ensure that BPF verifier sees proper value bounds for cpu ID. Signed-off-by: Andrii Nakryiko --- libbpf-tools/cpufreq.bpf.c | 11 +++++++++++ libbpf-tools/cpufreq.c | 15 ++++----------- 2 files changed, 15 insertions(+), 11 deletions(-) diff --git a/libbpf-tools/cpufreq.bpf.c b/libbpf-tools/cpufreq.bpf.c index 697620ba..88a1bd25 100644 --- a/libbpf-tools/cpufreq.bpf.c +++ b/libbpf-tools/cpufreq.bpf.c @@ -17,11 +17,21 @@ struct { __type(value, struct hist); } hists SEC(".maps"); +#define clamp_umax(VAR, UMAX) \ + asm volatile ( \ + "if %0 <= %[max] goto +1\n" \ + "%0 = %[max]\n" \ + : "+r"(VAR) \ + : [max]"i"(UMAX) \ + ) + SEC("tp_btf/cpu_frequency") int BPF_PROG(cpu_frequency, unsigned int state, unsigned int cpu_id) { if (cpu_id >= MAX_CPU_NR) return 0; + + clamp_umax(cpu_id, MAX_CPU_NR - 1); freqs_mhz[cpu_id] = state / 1000; return 0; } @@ -36,6 +46,7 @@ int do_sample(struct bpf_perf_event_data *ctx) if (cpu >= MAX_CPU_NR) return 0; + clamp_umax(cpu, MAX_CPU_NR - 1); freq_mhz = freqs_mhz[cpu]; if (!freq_mhz) return 0; diff --git a/libbpf-tools/cpufreq.c b/libbpf-tools/cpufreq.c index b12d2b78..e42bca94 100644 --- a/libbpf-tools/cpufreq.c +++ b/libbpf-tools/cpufreq.c @@ -102,10 +102,8 @@ static int open_and_attach_perf_event(int freq, struct bpf_program *prog, return -1; } links[i] = bpf_program__attach_perf_event(prog, fd); - if (libbpf_get_error(links[i])) { - fprintf(stderr, "failed to attach perf event on cpu: " - "%d\n", i); - links[i] = NULL; + if (!links[i]) { + fprintf(stderr, "failed to attach perf event on cpu: %d\n", i); close(fd); return -1; } @@ -176,7 +174,7 @@ static void print_linear_hists(struct bpf_map *hists, printf("\n"); print_linear_hist(bss->syswide.slots, MAX_SLOTS, 0, HIST_STEP_SIZE, - "syswide"); + "syswide"); } int main(int argc, char **argv) @@ -194,14 +192,9 @@ int main(int argc, char **argv) if (err) return err; + libbpf_set_strict_mode(LIBBPF_STRICT_ALL); libbpf_set_print(libbpf_print_fn); - err = bump_memlock_rlimit(); - if (err) { - fprintf(stderr, "failed to increase rlimit: %d\n", err); - return 1; - } - nr_cpus = libbpf_num_possible_cpus(); if (nr_cpus < 0) { fprintf(stderr, "failed to get # of possible cpus: '%s'!\n", -- 2.34.1