1 // SPDX-License-Identifier: GPL-2.0
3 /* Copyright (c) 2019 Facebook */
10 #include <linux/err.h>
11 #include <linux/zalloc.h>
12 #include <api/fs/fs.h>
13 #include <perf/bpf_perf.h>
15 #include "bpf_counter.h"
16 #include "bpf-utils.h"
24 #include "thread_map.h"
26 #include "bpf_skel/bpf_prog_profiler.skel.h"
27 #include "bpf_skel/bperf_u.h"
28 #include "bpf_skel/bperf_leader.skel.h"
29 #include "bpf_skel/bperf_follower.skel.h"
31 #define ATTR_MAP_SIZE 16
33 static inline void *u64_to_ptr(__u64 ptr)
35 return (void *)(unsigned long)ptr;
38 static struct bpf_counter *bpf_counter_alloc(void)
40 struct bpf_counter *counter;
42 counter = zalloc(sizeof(*counter));
44 INIT_LIST_HEAD(&counter->list);
48 static int bpf_program_profiler__destroy(struct evsel *evsel)
50 struct bpf_counter *counter, *tmp;
52 list_for_each_entry_safe(counter, tmp,
53 &evsel->bpf_counter_list, list) {
54 list_del_init(&counter->list);
55 bpf_prog_profiler_bpf__destroy(counter->skel);
58 assert(list_empty(&evsel->bpf_counter_list));
63 static char *bpf_target_prog_name(int tgt_fd)
65 struct bpf_func_info *func_info;
66 struct perf_bpil *info_linear;
67 const struct btf_type *t;
68 struct btf *btf = NULL;
71 info_linear = get_bpf_prog_info_linear(tgt_fd, 1UL << PERF_BPIL_FUNC_INFO);
72 if (IS_ERR_OR_NULL(info_linear)) {
73 pr_debug("failed to get info_linear for prog FD %d\n", tgt_fd);
77 if (info_linear->info.btf_id == 0) {
78 pr_debug("prog FD %d doesn't have valid btf\n", tgt_fd);
82 btf = btf__load_from_kernel_by_id(info_linear->info.btf_id);
83 if (libbpf_get_error(btf)) {
84 pr_debug("failed to load btf for prog FD %d\n", tgt_fd);
88 func_info = u64_to_ptr(info_linear->info.func_info);
89 t = btf__type_by_id(btf, func_info[0].type_id);
91 pr_debug("btf %d doesn't have type %d\n",
92 info_linear->info.btf_id, func_info[0].type_id);
95 name = strdup(btf__name_by_offset(btf, t->name_off));
102 static int bpf_program_profiler_load_one(struct evsel *evsel, u32 prog_id)
104 struct bpf_prog_profiler_bpf *skel;
105 struct bpf_counter *counter;
106 struct bpf_program *prog;
111 prog_fd = bpf_prog_get_fd_by_id(prog_id);
113 pr_err("Failed to open fd for bpf prog %u\n", prog_id);
116 counter = bpf_counter_alloc();
122 skel = bpf_prog_profiler_bpf__open();
124 pr_err("Failed to open bpf skeleton\n");
128 skel->rodata->num_cpu = evsel__nr_cpus(evsel);
130 bpf_map__set_max_entries(skel->maps.events, evsel__nr_cpus(evsel));
131 bpf_map__set_max_entries(skel->maps.fentry_readings, 1);
132 bpf_map__set_max_entries(skel->maps.accum_readings, 1);
134 prog_name = bpf_target_prog_name(prog_fd);
136 pr_err("Failed to get program name for bpf prog %u. Does it have BTF?\n", prog_id);
140 bpf_object__for_each_program(prog, skel->obj) {
141 err = bpf_program__set_attach_target(prog, prog_fd, prog_name);
143 pr_err("bpf_program__set_attach_target failed.\n"
144 "Does bpf prog %u have BTF?\n", prog_id);
149 err = bpf_prog_profiler_bpf__load(skel);
151 pr_err("bpf_prog_profiler_bpf__load failed\n");
155 assert(skel != NULL);
156 counter->skel = skel;
157 list_add(&counter->list, &evsel->bpf_counter_list);
161 bpf_prog_profiler_bpf__destroy(skel);
167 static int bpf_program_profiler__load(struct evsel *evsel, struct target *target)
169 char *bpf_str, *bpf_str_, *tok, *saveptr = NULL, *p;
173 bpf_str_ = bpf_str = strdup(target->bpf_str);
177 while ((tok = strtok_r(bpf_str, ",", &saveptr)) != NULL) {
178 prog_id = strtoul(tok, &p, 10);
179 if (prog_id == 0 || prog_id == UINT_MAX ||
180 (*p != '\0' && *p != ',')) {
181 pr_err("Failed to parse bpf prog ids %s\n",
186 ret = bpf_program_profiler_load_one(evsel, prog_id);
188 bpf_program_profiler__destroy(evsel);
198 static int bpf_program_profiler__enable(struct evsel *evsel)
200 struct bpf_counter *counter;
203 list_for_each_entry(counter, &evsel->bpf_counter_list, list) {
204 assert(counter->skel != NULL);
205 ret = bpf_prog_profiler_bpf__attach(counter->skel);
207 bpf_program_profiler__destroy(evsel);
214 static int bpf_program_profiler__disable(struct evsel *evsel)
216 struct bpf_counter *counter;
218 list_for_each_entry(counter, &evsel->bpf_counter_list, list) {
219 assert(counter->skel != NULL);
220 bpf_prog_profiler_bpf__detach(counter->skel);
225 static int bpf_program_profiler__read(struct evsel *evsel)
227 // BPF_MAP_TYPE_PERCPU_ARRAY uses /sys/devices/system/cpu/possible
228 // Sometimes possible > online, like on a Ryzen 3900X that has 24
229 // threads but its possible showed 0-31 -acme
230 int num_cpu_bpf = libbpf_num_possible_cpus();
231 struct bpf_perf_event_value values[num_cpu_bpf];
232 struct bpf_counter *counter;
233 struct perf_counts_values *counts;
236 int err, idx, bpf_cpu;
238 if (list_empty(&evsel->bpf_counter_list))
241 perf_cpu_map__for_each_idx(idx, evsel__cpus(evsel)) {
242 counts = perf_counts(evsel->counts, idx, 0);
247 list_for_each_entry(counter, &evsel->bpf_counter_list, list) {
248 struct bpf_prog_profiler_bpf *skel = counter->skel;
250 assert(skel != NULL);
251 reading_map_fd = bpf_map__fd(skel->maps.accum_readings);
253 err = bpf_map_lookup_elem(reading_map_fd, &key, values);
255 pr_err("failed to read value\n");
259 for (bpf_cpu = 0; bpf_cpu < num_cpu_bpf; bpf_cpu++) {
260 idx = perf_cpu_map__idx(evsel__cpus(evsel),
261 (struct perf_cpu){.cpu = bpf_cpu});
264 counts = perf_counts(evsel->counts, idx, 0);
265 counts->val += values[bpf_cpu].counter;
266 counts->ena += values[bpf_cpu].enabled;
267 counts->run += values[bpf_cpu].running;
273 static int bpf_program_profiler__install_pe(struct evsel *evsel, int cpu_map_idx,
276 struct bpf_prog_profiler_bpf *skel;
277 struct bpf_counter *counter;
280 list_for_each_entry(counter, &evsel->bpf_counter_list, list) {
281 skel = counter->skel;
282 assert(skel != NULL);
284 ret = bpf_map_update_elem(bpf_map__fd(skel->maps.events),
285 &cpu_map_idx, &fd, BPF_ANY);
292 struct bpf_counter_ops bpf_program_profiler_ops = {
293 .load = bpf_program_profiler__load,
294 .enable = bpf_program_profiler__enable,
295 .disable = bpf_program_profiler__disable,
296 .read = bpf_program_profiler__read,
297 .destroy = bpf_program_profiler__destroy,
298 .install_pe = bpf_program_profiler__install_pe,
301 static bool bperf_attr_map_compatible(int attr_map_fd)
303 struct bpf_map_info map_info = {0};
304 __u32 map_info_len = sizeof(map_info);
307 err = bpf_obj_get_info_by_fd(attr_map_fd, &map_info, &map_info_len);
311 return (map_info.key_size == sizeof(struct perf_event_attr)) &&
312 (map_info.value_size == sizeof(struct perf_event_attr_map_entry));
315 static int bperf_lock_attr_map(struct target *target)
320 if (target->attr_map) {
321 scnprintf(path, PATH_MAX, "%s", target->attr_map);
323 scnprintf(path, PATH_MAX, "%s/fs/bpf/%s", sysfs__mountpoint(),
324 BPF_PERF_DEFAULT_ATTR_MAP_PATH);
327 if (access(path, F_OK)) {
328 map_fd = bpf_map_create(BPF_MAP_TYPE_HASH, NULL,
329 sizeof(struct perf_event_attr),
330 sizeof(struct perf_event_attr_map_entry),
331 ATTR_MAP_SIZE, NULL);
335 err = bpf_obj_pin(map_fd, path);
337 /* someone pinned the map in parallel? */
339 map_fd = bpf_obj_get(path);
344 map_fd = bpf_obj_get(path);
349 if (!bperf_attr_map_compatible(map_fd)) {
354 err = flock(map_fd, LOCK_EX);
362 static int bperf_check_target(struct evsel *evsel,
363 struct target *target,
364 enum bperf_filter_type *filter_type,
365 __u32 *filter_entry_cnt)
367 if (evsel->core.leader->nr_members > 1) {
368 pr_err("bpf managed perf events do not yet support groups.\n");
372 /* determine filter type based on target */
373 if (target->system_wide) {
374 *filter_type = BPERF_FILTER_GLOBAL;
375 *filter_entry_cnt = 1;
376 } else if (target->cpu_list) {
377 *filter_type = BPERF_FILTER_CPU;
378 *filter_entry_cnt = perf_cpu_map__nr(evsel__cpus(evsel));
379 } else if (target->tid) {
380 *filter_type = BPERF_FILTER_PID;
381 *filter_entry_cnt = perf_thread_map__nr(evsel->core.threads);
382 } else if (target->pid || evsel->evlist->workload.pid != -1) {
383 *filter_type = BPERF_FILTER_TGID;
384 *filter_entry_cnt = perf_thread_map__nr(evsel->core.threads);
386 pr_err("bpf managed perf events do not yet support these targets.\n");
393 static struct perf_cpu_map *all_cpu_map;
395 static int bperf_reload_leader_program(struct evsel *evsel, int attr_map_fd,
396 struct perf_event_attr_map_entry *entry)
398 struct bperf_leader_bpf *skel = bperf_leader_bpf__open();
399 int link_fd, diff_map_fd, err;
400 struct bpf_link *link = NULL;
403 pr_err("Failed to open leader skeleton\n");
407 bpf_map__set_max_entries(skel->maps.events, libbpf_num_possible_cpus());
408 err = bperf_leader_bpf__load(skel);
410 pr_err("Failed to load leader skeleton\n");
414 link = bpf_program__attach(skel->progs.on_switch);
416 pr_err("Failed to attach leader program\n");
421 link_fd = bpf_link__fd(link);
422 diff_map_fd = bpf_map__fd(skel->maps.diff_readings);
423 entry->link_id = bpf_link_get_id(link_fd);
424 entry->diff_map_id = bpf_map_get_id(diff_map_fd);
425 err = bpf_map_update_elem(attr_map_fd, &evsel->core.attr, entry, BPF_ANY);
428 evsel->bperf_leader_link_fd = bpf_link_get_fd_by_id(entry->link_id);
429 assert(evsel->bperf_leader_link_fd >= 0);
432 * save leader_skel for install_pe, which is called within
433 * following evsel__open_per_cpu call
435 evsel->leader_skel = skel;
436 evsel__open_per_cpu(evsel, all_cpu_map, -1);
439 bperf_leader_bpf__destroy(skel);
440 bpf_link__destroy(link);
444 static int bperf__load(struct evsel *evsel, struct target *target)
446 struct perf_event_attr_map_entry entry = {0xffffffff, 0xffffffff};
447 int attr_map_fd, diff_map_fd = -1, err;
448 enum bperf_filter_type filter_type;
449 __u32 filter_entry_cnt, i;
451 if (bperf_check_target(evsel, target, &filter_type, &filter_entry_cnt))
455 all_cpu_map = perf_cpu_map__new(NULL);
460 evsel->bperf_leader_prog_fd = -1;
461 evsel->bperf_leader_link_fd = -1;
464 * Step 1: hold a fd on the leader program and the bpf_link, if
465 * the program is not already gone, reload the program.
466 * Use flock() to ensure exclusive access to the perf_event_attr
469 attr_map_fd = bperf_lock_attr_map(target);
470 if (attr_map_fd < 0) {
471 pr_err("Failed to lock perf_event_attr map\n");
475 err = bpf_map_lookup_elem(attr_map_fd, &evsel->core.attr, &entry);
477 err = bpf_map_update_elem(attr_map_fd, &evsel->core.attr, &entry, BPF_ANY);
482 evsel->bperf_leader_link_fd = bpf_link_get_fd_by_id(entry.link_id);
483 if (evsel->bperf_leader_link_fd < 0 &&
484 bperf_reload_leader_program(evsel, attr_map_fd, &entry)) {
489 * The bpf_link holds reference to the leader program, and the
490 * leader program holds reference to the maps. Therefore, if
491 * link_id is valid, diff_map_id should also be valid.
493 evsel->bperf_leader_prog_fd = bpf_prog_get_fd_by_id(
494 bpf_link_get_prog_id(evsel->bperf_leader_link_fd));
495 assert(evsel->bperf_leader_prog_fd >= 0);
497 diff_map_fd = bpf_map_get_fd_by_id(entry.diff_map_id);
498 assert(diff_map_fd >= 0);
501 * bperf uses BPF_PROG_TEST_RUN to get accurate reading. Check
502 * whether the kernel support it
504 err = bperf_trigger_reading(evsel->bperf_leader_prog_fd, 0);
506 pr_err("The kernel does not support test_run for raw_tp BPF programs.\n"
507 "Therefore, --use-bpf might show inaccurate readings\n");
511 /* Step 2: load the follower skeleton */
512 evsel->follower_skel = bperf_follower_bpf__open();
513 if (!evsel->follower_skel) {
515 pr_err("Failed to open follower skeleton\n");
519 /* attach fexit program to the leader program */
520 bpf_program__set_attach_target(evsel->follower_skel->progs.fexit_XXX,
521 evsel->bperf_leader_prog_fd, "on_switch");
523 /* connect to leader diff_reading map */
524 bpf_map__reuse_fd(evsel->follower_skel->maps.diff_readings, diff_map_fd);
526 /* set up reading map */
527 bpf_map__set_max_entries(evsel->follower_skel->maps.accum_readings,
529 /* set up follower filter based on target */
530 bpf_map__set_max_entries(evsel->follower_skel->maps.filter,
532 err = bperf_follower_bpf__load(evsel->follower_skel);
534 pr_err("Failed to load follower skeleton\n");
535 bperf_follower_bpf__destroy(evsel->follower_skel);
536 evsel->follower_skel = NULL;
540 for (i = 0; i < filter_entry_cnt; i++) {
544 if (filter_type == BPERF_FILTER_PID ||
545 filter_type == BPERF_FILTER_TGID)
546 key = perf_thread_map__pid(evsel->core.threads, i);
547 else if (filter_type == BPERF_FILTER_CPU)
548 key = perf_cpu_map__cpu(evsel->core.cpus, i).cpu;
552 filter_map_fd = bpf_map__fd(evsel->follower_skel->maps.filter);
553 bpf_map_update_elem(filter_map_fd, &key, &i, BPF_ANY);
556 evsel->follower_skel->bss->type = filter_type;
558 err = bperf_follower_bpf__attach(evsel->follower_skel);
561 if (err && evsel->bperf_leader_link_fd >= 0)
562 close(evsel->bperf_leader_link_fd);
563 if (err && evsel->bperf_leader_prog_fd >= 0)
564 close(evsel->bperf_leader_prog_fd);
565 if (diff_map_fd >= 0)
568 flock(attr_map_fd, LOCK_UN);
574 static int bperf__install_pe(struct evsel *evsel, int cpu_map_idx, int fd)
576 struct bperf_leader_bpf *skel = evsel->leader_skel;
578 return bpf_map_update_elem(bpf_map__fd(skel->maps.events),
579 &cpu_map_idx, &fd, BPF_ANY);
583 * trigger the leader prog on each cpu, so the accum_reading map could get
584 * the latest readings.
586 static int bperf_sync_counters(struct evsel *evsel)
590 num_cpu = perf_cpu_map__nr(all_cpu_map);
591 for (i = 0; i < num_cpu; i++) {
592 cpu = perf_cpu_map__cpu(all_cpu_map, i).cpu;
593 bperf_trigger_reading(evsel->bperf_leader_prog_fd, cpu);
598 static int bperf__enable(struct evsel *evsel)
600 evsel->follower_skel->bss->enabled = 1;
604 static int bperf__disable(struct evsel *evsel)
606 evsel->follower_skel->bss->enabled = 0;
610 static int bperf__read(struct evsel *evsel)
612 struct bperf_follower_bpf *skel = evsel->follower_skel;
613 __u32 num_cpu_bpf = cpu__max_cpu().cpu;
614 struct bpf_perf_event_value values[num_cpu_bpf];
615 struct perf_counts_values *counts;
616 int reading_map_fd, err = 0;
620 bperf_sync_counters(evsel);
621 reading_map_fd = bpf_map__fd(skel->maps.accum_readings);
623 for (i = 0; i < bpf_map__max_entries(skel->maps.accum_readings); i++) {
624 struct perf_cpu entry;
627 err = bpf_map_lookup_elem(reading_map_fd, &i, values);
630 switch (evsel->follower_skel->bss->type) {
631 case BPERF_FILTER_GLOBAL:
634 perf_cpu_map__for_each_cpu(entry, j, evsel__cpus(evsel)) {
635 counts = perf_counts(evsel->counts, j, 0);
636 counts->val = values[entry.cpu].counter;
637 counts->ena = values[entry.cpu].enabled;
638 counts->run = values[entry.cpu].running;
641 case BPERF_FILTER_CPU:
642 cpu = perf_cpu_map__cpu(evsel__cpus(evsel), i).cpu;
644 counts = perf_counts(evsel->counts, i, 0);
645 counts->val = values[cpu].counter;
646 counts->ena = values[cpu].enabled;
647 counts->run = values[cpu].running;
649 case BPERF_FILTER_PID:
650 case BPERF_FILTER_TGID:
651 counts = perf_counts(evsel->counts, 0, i);
656 for (cpu = 0; cpu < num_cpu_bpf; cpu++) {
657 counts->val += values[cpu].counter;
658 counts->ena += values[cpu].enabled;
659 counts->run += values[cpu].running;
670 static int bperf__destroy(struct evsel *evsel)
672 bperf_follower_bpf__destroy(evsel->follower_skel);
673 close(evsel->bperf_leader_prog_fd);
674 close(evsel->bperf_leader_link_fd);
679 * bperf: share hardware PMCs with BPF
681 * perf uses performance monitoring counters (PMC) to monitor system
682 * performance. The PMCs are limited hardware resources. For example,
683 * Intel CPUs have 3x fixed PMCs and 4x programmable PMCs per cpu.
685 * Modern data center systems use these PMCs in many different ways:
686 * system level monitoring, (maybe nested) container level monitoring, per
687 * process monitoring, profiling (in sample mode), etc. In some cases,
688 * there are more active perf_events than available hardware PMCs. To allow
689 * all perf_events to have a chance to run, it is necessary to do expensive
690 * time multiplexing of events.
692 * On the other hand, many monitoring tools count the common metrics
693 * (cycles, instructions). It is a waste to have multiple tools create
694 * multiple perf_events of "cycles" and occupy multiple PMCs.
696 * bperf tries to reduce such wastes by allowing multiple perf_events of
697 * "cycles" or "instructions" (at different scopes) to share PMUs. Instead
698 * of having each perf-stat session to read its own perf_events, bperf uses
699 * BPF programs to read the perf_events and aggregate readings to BPF maps.
700 * Then, the perf-stat session(s) reads the values from these BPF maps.
703 * shared progs and maps <- || -> per session progs and maps
707 * --------------- fexit || -----------------
708 * | --------||----> | follower prog |
709 * --------------- / || --- -----------------
710 * cs -> | leader prog |/ ||/ | |
711 * --> --------------- /|| -------------- ------------------
712 * / | | / || | filter map | | accum_readings |
713 * / ------------ ------------ || -------------- ------------------
714 * | | prev map | | diff map | || |
715 * | ------------ ------------ || |
717 * = \ ==================================================== | ============
721 * BPF_PROG_TEST_RUN BPF_MAP_LOOKUP_ELEM
724 * \------ perf-stat ----------------------/
726 * The figure above shows the architecture of bperf. Note that the figure
727 * is divided into 3 regions: shared progs and maps (top left), per session
728 * progs and maps (top right), and user space (bottom).
730 * The leader prog is triggered on each context switch (cs). The leader
731 * prog reads perf_events and stores the difference (current_reading -
732 * previous_reading) to the diff map. For the same metric, e.g. "cycles",
733 * multiple perf-stat sessions share the same leader prog.
735 * Each perf-stat session creates a follower prog as fexit program to the
736 * leader prog. It is possible to attach up to BPF_MAX_TRAMP_PROGS (38)
737 * follower progs to the same leader prog. The follower prog checks current
738 * task and processor ID to decide whether to add the value from the diff
739 * map to its accumulated reading map (accum_readings).
741 * Finally, perf-stat user space reads the value from accum_reading map.
743 * Besides context switch, it is also necessary to trigger the leader prog
744 * before perf-stat reads the value. Otherwise, the accum_reading map may
745 * not have the latest reading from the perf_events. This is achieved by
746 * triggering the event via sys_bpf(BPF_PROG_TEST_RUN) to each CPU.
748 * Comment before the definition of struct perf_event_attr_map_entry
749 * describes how different sessions of perf-stat share information about
753 struct bpf_counter_ops bperf_ops = {
755 .enable = bperf__enable,
756 .disable = bperf__disable,
758 .install_pe = bperf__install_pe,
759 .destroy = bperf__destroy,
762 extern struct bpf_counter_ops bperf_cgrp_ops;
764 static inline bool bpf_counter_skip(struct evsel *evsel)
766 return evsel->bpf_counter_ops == NULL;
769 int bpf_counter__install_pe(struct evsel *evsel, int cpu_map_idx, int fd)
771 if (bpf_counter_skip(evsel))
773 return evsel->bpf_counter_ops->install_pe(evsel, cpu_map_idx, fd);
776 int bpf_counter__load(struct evsel *evsel, struct target *target)
779 evsel->bpf_counter_ops = &bpf_program_profiler_ops;
780 else if (cgrp_event_expanded && target->use_bpf)
781 evsel->bpf_counter_ops = &bperf_cgrp_ops;
782 else if (target->use_bpf || evsel->bpf_counter ||
783 evsel__match_bpf_counter_events(evsel->name))
784 evsel->bpf_counter_ops = &bperf_ops;
786 if (evsel->bpf_counter_ops)
787 return evsel->bpf_counter_ops->load(evsel, target);
791 int bpf_counter__enable(struct evsel *evsel)
793 if (bpf_counter_skip(evsel))
795 return evsel->bpf_counter_ops->enable(evsel);
798 int bpf_counter__disable(struct evsel *evsel)
800 if (bpf_counter_skip(evsel))
802 return evsel->bpf_counter_ops->disable(evsel);
805 int bpf_counter__read(struct evsel *evsel)
807 if (bpf_counter_skip(evsel))
809 return evsel->bpf_counter_ops->read(evsel);
812 void bpf_counter__destroy(struct evsel *evsel)
814 if (bpf_counter_skip(evsel))
816 evsel->bpf_counter_ops->destroy(evsel);
817 evsel->bpf_counter_ops = NULL;
818 evsel->bpf_skel = NULL;