Skip to content

Commit

Permalink
libbpf-tools: fix cpufreq.bpf.c and update cpufreq for libbpf 1.0
Browse files Browse the repository at this point in the history
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 <[email protected]>
  • Loading branch information
anakryiko committed Dec 20, 2021
1 parent 4970d23 commit f2006ea
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 11 deletions.
11 changes: 11 additions & 0 deletions libbpf-tools/cpufreq.bpf.c
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand All @@ -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;
Expand Down
15 changes: 4 additions & 11 deletions libbpf-tools/cpufreq.c
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down Expand Up @@ -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)
Expand All @@ -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",
Expand Down

0 comments on commit f2006ea

Please sign in to comment.