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"
23 #include "thread_map.h"
25 #include "bpf_skel/bpf_prog_profiler.skel.h"
26 #include "bpf_skel/bperf_u.h"
27 #include "bpf_skel/bperf_leader.skel.h"
28 #include "bpf_skel/bperf_follower.skel.h"
30 #define ATTR_MAP_SIZE 16
32 static inline void *u64_to_ptr(__u64 ptr)
34 return (void *)(unsigned long)ptr;
37 static struct bpf_counter *bpf_counter_alloc(void)
39 struct bpf_counter *counter;
41 counter = zalloc(sizeof(*counter));
43 INIT_LIST_HEAD(&counter->list);
47 static int bpf_program_profiler__destroy(struct evsel *evsel)
49 struct bpf_counter *counter, *tmp;
51 list_for_each_entry_safe(counter, tmp,
52 &evsel->bpf_counter_list, list) {
53 list_del_init(&counter->list);
54 bpf_prog_profiler_bpf__destroy(counter->skel);
57 assert(list_empty(&evsel->bpf_counter_list));
62 static char *bpf_target_prog_name(int tgt_fd)
64 struct bpf_prog_info_linear *info_linear;
65 struct bpf_func_info *func_info;
66 const struct btf_type *t;
67 struct btf *btf = NULL;
70 info_linear = bpf_program__get_prog_info_linear(
71 tgt_fd, 1UL << BPF_PROG_INFO_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__resize(skel->maps.events, evsel__nr_cpus(evsel));
131 bpf_map__resize(skel->maps.fentry_readings, 1);
132 bpf_map__resize(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 // perf_cpu_map uses /sys/devices/system/cpu/online
228 int num_cpu = evsel__nr_cpus(evsel);
229 // BPF_MAP_TYPE_PERCPU_ARRAY uses /sys/devices/system/cpu/possible
230 // Sometimes possible > online, like on a Ryzen 3900X that has 24
231 // threads but its possible showed 0-31 -acme
232 int num_cpu_bpf = libbpf_num_possible_cpus();
233 struct bpf_perf_event_value values[num_cpu_bpf];
234 struct bpf_counter *counter;
239 if (list_empty(&evsel->bpf_counter_list))
242 for (cpu = 0; cpu < num_cpu; cpu++) {
243 perf_counts(evsel->counts, cpu, 0)->val = 0;
244 perf_counts(evsel->counts, cpu, 0)->ena = 0;
245 perf_counts(evsel->counts, cpu, 0)->run = 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 (cpu = 0; cpu < num_cpu; cpu++) {
260 perf_counts(evsel->counts, cpu, 0)->val += values[cpu].counter;
261 perf_counts(evsel->counts, cpu, 0)->ena += values[cpu].enabled;
262 perf_counts(evsel->counts, cpu, 0)->run += values[cpu].running;
268 static int bpf_program_profiler__install_pe(struct evsel *evsel, int cpu,
271 struct bpf_prog_profiler_bpf *skel;
272 struct bpf_counter *counter;
275 list_for_each_entry(counter, &evsel->bpf_counter_list, list) {
276 skel = counter->skel;
277 assert(skel != NULL);
279 ret = bpf_map_update_elem(bpf_map__fd(skel->maps.events),
287 struct bpf_counter_ops bpf_program_profiler_ops = {
288 .load = bpf_program_profiler__load,
289 .enable = bpf_program_profiler__enable,
290 .disable = bpf_program_profiler__disable,
291 .read = bpf_program_profiler__read,
292 .destroy = bpf_program_profiler__destroy,
293 .install_pe = bpf_program_profiler__install_pe,
296 static bool bperf_attr_map_compatible(int attr_map_fd)
298 struct bpf_map_info map_info = {0};
299 __u32 map_info_len = sizeof(map_info);
302 err = bpf_obj_get_info_by_fd(attr_map_fd, &map_info, &map_info_len);
306 return (map_info.key_size == sizeof(struct perf_event_attr)) &&
307 (map_info.value_size == sizeof(struct perf_event_attr_map_entry));
310 static int bperf_lock_attr_map(struct target *target)
315 if (target->attr_map) {
316 scnprintf(path, PATH_MAX, "%s", target->attr_map);
318 scnprintf(path, PATH_MAX, "%s/fs/bpf/%s", sysfs__mountpoint(),
319 BPF_PERF_DEFAULT_ATTR_MAP_PATH);
322 if (access(path, F_OK)) {
323 map_fd = bpf_create_map(BPF_MAP_TYPE_HASH,
324 sizeof(struct perf_event_attr),
325 sizeof(struct perf_event_attr_map_entry),
330 err = bpf_obj_pin(map_fd, path);
332 /* someone pinned the map in parallel? */
334 map_fd = bpf_obj_get(path);
339 map_fd = bpf_obj_get(path);
344 if (!bperf_attr_map_compatible(map_fd)) {
349 err = flock(map_fd, LOCK_EX);
357 static int bperf_check_target(struct evsel *evsel,
358 struct target *target,
359 enum bperf_filter_type *filter_type,
360 __u32 *filter_entry_cnt)
362 if (evsel->core.leader->nr_members > 1) {
363 pr_err("bpf managed perf events do not yet support groups.\n");
367 /* determine filter type based on target */
368 if (target->system_wide) {
369 *filter_type = BPERF_FILTER_GLOBAL;
370 *filter_entry_cnt = 1;
371 } else if (target->cpu_list) {
372 *filter_type = BPERF_FILTER_CPU;
373 *filter_entry_cnt = perf_cpu_map__nr(evsel__cpus(evsel));
374 } else if (target->tid) {
375 *filter_type = BPERF_FILTER_PID;
376 *filter_entry_cnt = perf_thread_map__nr(evsel->core.threads);
377 } else if (target->pid || evsel->evlist->workload.pid != -1) {
378 *filter_type = BPERF_FILTER_TGID;
379 *filter_entry_cnt = perf_thread_map__nr(evsel->core.threads);
381 pr_err("bpf managed perf events do not yet support these targets.\n");
388 static struct perf_cpu_map *all_cpu_map;
390 static int bperf_reload_leader_program(struct evsel *evsel, int attr_map_fd,
391 struct perf_event_attr_map_entry *entry)
393 struct bperf_leader_bpf *skel = bperf_leader_bpf__open();
394 int link_fd, diff_map_fd, err;
395 struct bpf_link *link = NULL;
398 pr_err("Failed to open leader skeleton\n");
402 bpf_map__resize(skel->maps.events, libbpf_num_possible_cpus());
403 err = bperf_leader_bpf__load(skel);
405 pr_err("Failed to load leader skeleton\n");
409 link = bpf_program__attach(skel->progs.on_switch);
411 pr_err("Failed to attach leader program\n");
416 link_fd = bpf_link__fd(link);
417 diff_map_fd = bpf_map__fd(skel->maps.diff_readings);
418 entry->link_id = bpf_link_get_id(link_fd);
419 entry->diff_map_id = bpf_map_get_id(diff_map_fd);
420 err = bpf_map_update_elem(attr_map_fd, &evsel->core.attr, entry, BPF_ANY);
423 evsel->bperf_leader_link_fd = bpf_link_get_fd_by_id(entry->link_id);
424 assert(evsel->bperf_leader_link_fd >= 0);
427 * save leader_skel for install_pe, which is called within
428 * following evsel__open_per_cpu call
430 evsel->leader_skel = skel;
431 evsel__open_per_cpu(evsel, all_cpu_map, -1);
434 bperf_leader_bpf__destroy(skel);
435 bpf_link__destroy(link);
439 static int bperf__load(struct evsel *evsel, struct target *target)
441 struct perf_event_attr_map_entry entry = {0xffffffff, 0xffffffff};
442 int attr_map_fd, diff_map_fd = -1, err;
443 enum bperf_filter_type filter_type;
444 __u32 filter_entry_cnt, i;
446 if (bperf_check_target(evsel, target, &filter_type, &filter_entry_cnt))
450 all_cpu_map = perf_cpu_map__new(NULL);
455 evsel->bperf_leader_prog_fd = -1;
456 evsel->bperf_leader_link_fd = -1;
459 * Step 1: hold a fd on the leader program and the bpf_link, if
460 * the program is not already gone, reload the program.
461 * Use flock() to ensure exclusive access to the perf_event_attr
464 attr_map_fd = bperf_lock_attr_map(target);
465 if (attr_map_fd < 0) {
466 pr_err("Failed to lock perf_event_attr map\n");
470 err = bpf_map_lookup_elem(attr_map_fd, &evsel->core.attr, &entry);
472 err = bpf_map_update_elem(attr_map_fd, &evsel->core.attr, &entry, BPF_ANY);
477 evsel->bperf_leader_link_fd = bpf_link_get_fd_by_id(entry.link_id);
478 if (evsel->bperf_leader_link_fd < 0 &&
479 bperf_reload_leader_program(evsel, attr_map_fd, &entry)) {
484 * The bpf_link holds reference to the leader program, and the
485 * leader program holds reference to the maps. Therefore, if
486 * link_id is valid, diff_map_id should also be valid.
488 evsel->bperf_leader_prog_fd = bpf_prog_get_fd_by_id(
489 bpf_link_get_prog_id(evsel->bperf_leader_link_fd));
490 assert(evsel->bperf_leader_prog_fd >= 0);
492 diff_map_fd = bpf_map_get_fd_by_id(entry.diff_map_id);
493 assert(diff_map_fd >= 0);
496 * bperf uses BPF_PROG_TEST_RUN to get accurate reading. Check
497 * whether the kernel support it
499 err = bperf_trigger_reading(evsel->bperf_leader_prog_fd, 0);
501 pr_err("The kernel does not support test_run for raw_tp BPF programs.\n"
502 "Therefore, --use-bpf might show inaccurate readings\n");
506 /* Step 2: load the follower skeleton */
507 evsel->follower_skel = bperf_follower_bpf__open();
508 if (!evsel->follower_skel) {
510 pr_err("Failed to open follower skeleton\n");
514 /* attach fexit program to the leader program */
515 bpf_program__set_attach_target(evsel->follower_skel->progs.fexit_XXX,
516 evsel->bperf_leader_prog_fd, "on_switch");
518 /* connect to leader diff_reading map */
519 bpf_map__reuse_fd(evsel->follower_skel->maps.diff_readings, diff_map_fd);
521 /* set up reading map */
522 bpf_map__set_max_entries(evsel->follower_skel->maps.accum_readings,
524 /* set up follower filter based on target */
525 bpf_map__set_max_entries(evsel->follower_skel->maps.filter,
527 err = bperf_follower_bpf__load(evsel->follower_skel);
529 pr_err("Failed to load follower skeleton\n");
530 bperf_follower_bpf__destroy(evsel->follower_skel);
531 evsel->follower_skel = NULL;
535 for (i = 0; i < filter_entry_cnt; i++) {
539 if (filter_type == BPERF_FILTER_PID ||
540 filter_type == BPERF_FILTER_TGID)
541 key = evsel->core.threads->map[i].pid;
542 else if (filter_type == BPERF_FILTER_CPU)
543 key = evsel->core.cpus->map[i];
547 filter_map_fd = bpf_map__fd(evsel->follower_skel->maps.filter);
548 bpf_map_update_elem(filter_map_fd, &key, &i, BPF_ANY);
551 evsel->follower_skel->bss->type = filter_type;
553 err = bperf_follower_bpf__attach(evsel->follower_skel);
556 if (err && evsel->bperf_leader_link_fd >= 0)
557 close(evsel->bperf_leader_link_fd);
558 if (err && evsel->bperf_leader_prog_fd >= 0)
559 close(evsel->bperf_leader_prog_fd);
560 if (diff_map_fd >= 0)
563 flock(attr_map_fd, LOCK_UN);
569 static int bperf__install_pe(struct evsel *evsel, int cpu, int fd)
571 struct bperf_leader_bpf *skel = evsel->leader_skel;
573 return bpf_map_update_elem(bpf_map__fd(skel->maps.events),
578 * trigger the leader prog on each cpu, so the accum_reading map could get
579 * the latest readings.
581 static int bperf_sync_counters(struct evsel *evsel)
585 num_cpu = all_cpu_map->nr;
586 for (i = 0; i < num_cpu; i++) {
587 cpu = all_cpu_map->map[i];
588 bperf_trigger_reading(evsel->bperf_leader_prog_fd, cpu);
593 static int bperf__enable(struct evsel *evsel)
595 evsel->follower_skel->bss->enabled = 1;
599 static int bperf__disable(struct evsel *evsel)
601 evsel->follower_skel->bss->enabled = 0;
605 static int bperf__read(struct evsel *evsel)
607 struct bperf_follower_bpf *skel = evsel->follower_skel;
608 __u32 num_cpu_bpf = cpu__max_cpu();
609 struct bpf_perf_event_value values[num_cpu_bpf];
610 int reading_map_fd, err = 0;
613 bperf_sync_counters(evsel);
614 reading_map_fd = bpf_map__fd(skel->maps.accum_readings);
616 for (i = 0; i < bpf_map__max_entries(skel->maps.accum_readings); i++) {
619 err = bpf_map_lookup_elem(reading_map_fd, &i, values);
622 switch (evsel->follower_skel->bss->type) {
623 case BPERF_FILTER_GLOBAL:
626 num_cpu = all_cpu_map->nr;
627 for (j = 0; j < num_cpu; j++) {
628 cpu = all_cpu_map->map[j];
629 perf_counts(evsel->counts, cpu, 0)->val = values[cpu].counter;
630 perf_counts(evsel->counts, cpu, 0)->ena = values[cpu].enabled;
631 perf_counts(evsel->counts, cpu, 0)->run = values[cpu].running;
634 case BPERF_FILTER_CPU:
635 cpu = evsel->core.cpus->map[i];
636 perf_counts(evsel->counts, i, 0)->val = values[cpu].counter;
637 perf_counts(evsel->counts, i, 0)->ena = values[cpu].enabled;
638 perf_counts(evsel->counts, i, 0)->run = values[cpu].running;
640 case BPERF_FILTER_PID:
641 case BPERF_FILTER_TGID:
642 perf_counts(evsel->counts, 0, i)->val = 0;
643 perf_counts(evsel->counts, 0, i)->ena = 0;
644 perf_counts(evsel->counts, 0, i)->run = 0;
646 for (cpu = 0; cpu < num_cpu_bpf; cpu++) {
647 perf_counts(evsel->counts, 0, i)->val += values[cpu].counter;
648 perf_counts(evsel->counts, 0, i)->ena += values[cpu].enabled;
649 perf_counts(evsel->counts, 0, i)->run += values[cpu].running;
660 static int bperf__destroy(struct evsel *evsel)
662 bperf_follower_bpf__destroy(evsel->follower_skel);
663 close(evsel->bperf_leader_prog_fd);
664 close(evsel->bperf_leader_link_fd);
669 * bperf: share hardware PMCs with BPF
671 * perf uses performance monitoring counters (PMC) to monitor system
672 * performance. The PMCs are limited hardware resources. For example,
673 * Intel CPUs have 3x fixed PMCs and 4x programmable PMCs per cpu.
675 * Modern data center systems use these PMCs in many different ways:
676 * system level monitoring, (maybe nested) container level monitoring, per
677 * process monitoring, profiling (in sample mode), etc. In some cases,
678 * there are more active perf_events than available hardware PMCs. To allow
679 * all perf_events to have a chance to run, it is necessary to do expensive
680 * time multiplexing of events.
682 * On the other hand, many monitoring tools count the common metrics
683 * (cycles, instructions). It is a waste to have multiple tools create
684 * multiple perf_events of "cycles" and occupy multiple PMCs.
686 * bperf tries to reduce such wastes by allowing multiple perf_events of
687 * "cycles" or "instructions" (at different scopes) to share PMUs. Instead
688 * of having each perf-stat session to read its own perf_events, bperf uses
689 * BPF programs to read the perf_events and aggregate readings to BPF maps.
690 * Then, the perf-stat session(s) reads the values from these BPF maps.
693 * shared progs and maps <- || -> per session progs and maps
697 * --------------- fexit || -----------------
698 * | --------||----> | follower prog |
699 * --------------- / || --- -----------------
700 * cs -> | leader prog |/ ||/ | |
701 * --> --------------- /|| -------------- ------------------
702 * / | | / || | filter map | | accum_readings |
703 * / ------------ ------------ || -------------- ------------------
704 * | | prev map | | diff map | || |
705 * | ------------ ------------ || |
707 * = \ ==================================================== | ============
711 * BPF_PROG_TEST_RUN BPF_MAP_LOOKUP_ELEM
714 * \------ perf-stat ----------------------/
716 * The figure above shows the architecture of bperf. Note that the figure
717 * is divided into 3 regions: shared progs and maps (top left), per session
718 * progs and maps (top right), and user space (bottom).
720 * The leader prog is triggered on each context switch (cs). The leader
721 * prog reads perf_events and stores the difference (current_reading -
722 * previous_reading) to the diff map. For the same metric, e.g. "cycles",
723 * multiple perf-stat sessions share the same leader prog.
725 * Each perf-stat session creates a follower prog as fexit program to the
726 * leader prog. It is possible to attach up to BPF_MAX_TRAMP_PROGS (38)
727 * follower progs to the same leader prog. The follower prog checks current
728 * task and processor ID to decide whether to add the value from the diff
729 * map to its accumulated reading map (accum_readings).
731 * Finally, perf-stat user space reads the value from accum_reading map.
733 * Besides context switch, it is also necessary to trigger the leader prog
734 * before perf-stat reads the value. Otherwise, the accum_reading map may
735 * not have the latest reading from the perf_events. This is achieved by
736 * triggering the event via sys_bpf(BPF_PROG_TEST_RUN) to each CPU.
738 * Comment before the definition of struct perf_event_attr_map_entry
739 * describes how different sessions of perf-stat share information about
743 struct bpf_counter_ops bperf_ops = {
745 .enable = bperf__enable,
746 .disable = bperf__disable,
748 .install_pe = bperf__install_pe,
749 .destroy = bperf__destroy,
752 extern struct bpf_counter_ops bperf_cgrp_ops;
754 static inline bool bpf_counter_skip(struct evsel *evsel)
756 return list_empty(&evsel->bpf_counter_list) &&
757 evsel->follower_skel == NULL;
760 int bpf_counter__install_pe(struct evsel *evsel, int cpu, int fd)
762 if (bpf_counter_skip(evsel))
764 return evsel->bpf_counter_ops->install_pe(evsel, cpu, fd);
767 int bpf_counter__load(struct evsel *evsel, struct target *target)
770 evsel->bpf_counter_ops = &bpf_program_profiler_ops;
771 else if (cgrp_event_expanded && target->use_bpf)
772 evsel->bpf_counter_ops = &bperf_cgrp_ops;
773 else if (target->use_bpf || evsel->bpf_counter ||
774 evsel__match_bpf_counter_events(evsel->name))
775 evsel->bpf_counter_ops = &bperf_ops;
777 if (evsel->bpf_counter_ops)
778 return evsel->bpf_counter_ops->load(evsel, target);
782 int bpf_counter__enable(struct evsel *evsel)
784 if (bpf_counter_skip(evsel))
786 return evsel->bpf_counter_ops->enable(evsel);
789 int bpf_counter__disable(struct evsel *evsel)
791 if (bpf_counter_skip(evsel))
793 return evsel->bpf_counter_ops->disable(evsel);
796 int bpf_counter__read(struct evsel *evsel)
798 if (bpf_counter_skip(evsel))
800 return evsel->bpf_counter_ops->read(evsel);
803 void bpf_counter__destroy(struct evsel *evsel)
805 if (bpf_counter_skip(evsel))
807 evsel->bpf_counter_ops->destroy(evsel);
808 evsel->bpf_counter_ops = NULL;