1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2016 Facebook
8 #include <linux/perf_event.h>
11 #include <bpf/libbpf.h>
13 #include "trace_helpers.h"
15 #define PRINT_RAW_ADDR 0
17 /* counts, stackmap */
20 static void print_ksym(__u64 addr)
26 sym = ksym_search(addr);
28 printf("ksym not found. Is kallsyms loaded?\n");
33 printf("%s/%llx;", sym->name, addr);
35 printf("%s;", sym->name);
38 #define TASK_COMM_LEN 16
41 char waker[TASK_COMM_LEN];
42 char target[TASK_COMM_LEN];
47 static void print_stack(struct key_t *key, __u64 count)
49 __u64 ip[PERF_MAX_STACK_DEPTH] = {};
53 printf("%s;", key->target);
54 if (bpf_map_lookup_elem(map_fd[1], &key->tret, ip) != 0) {
57 for (i = PERF_MAX_STACK_DEPTH - 1; i >= 0; i--)
61 if (bpf_map_lookup_elem(map_fd[1], &key->wret, ip) != 0) {
64 for (i = 0; i < PERF_MAX_STACK_DEPTH; i++)
67 printf(";%s %lld\n", key->waker, count);
69 if ((key->tret == -EEXIST || key->wret == -EEXIST) && !warned) {
70 printf("stackmap collisions seen. Consider increasing size\n");
72 } else if (((int)(key->tret) < 0 || (int)(key->wret) < 0)) {
73 printf("err stackid %d %d\n", key->tret, key->wret);
77 static void print_stacks(int fd)
79 struct key_t key = {}, next_key;
82 while (bpf_map_get_next_key(fd, &key, &next_key) == 0) {
83 bpf_map_lookup_elem(fd, &next_key, &value);
84 print_stack(&next_key, value);
89 static void int_exit(int sig)
91 print_stacks(map_fd[0]);
95 int main(int argc, char **argv)
97 struct bpf_object *obj = NULL;
98 struct bpf_link *links[2];
99 struct bpf_program *prog;
100 int delay = 1, i = 0;
103 if (load_kallsyms()) {
104 printf("failed to process /proc/kallsyms\n");
108 snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]);
109 obj = bpf_object__open_file(filename, NULL);
110 if (libbpf_get_error(obj)) {
111 fprintf(stderr, "ERROR: opening BPF object file failed\n");
116 /* load BPF program */
117 if (bpf_object__load(obj)) {
118 fprintf(stderr, "ERROR: loading BPF object file failed\n");
122 map_fd[0] = bpf_object__find_map_fd_by_name(obj, "counts");
123 map_fd[1] = bpf_object__find_map_fd_by_name(obj, "stackmap");
124 if (map_fd[0] < 0 || map_fd[1] < 0) {
125 fprintf(stderr, "ERROR: finding a map in obj file failed\n");
129 signal(SIGINT, int_exit);
130 signal(SIGTERM, int_exit);
132 bpf_object__for_each_program(prog, obj) {
133 links[i] = bpf_program__attach(prog);
134 if (libbpf_get_error(links[i])) {
135 fprintf(stderr, "ERROR: bpf_program__attach failed\n");
143 delay = atoi(argv[1]);
145 print_stacks(map_fd[0]);
148 for (i--; i >= 0; i--)
149 bpf_link__destroy(links[i]);
151 bpf_object__close(obj);