1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2016 Facebook
8 #include <linux/perf_event.h>
11 #include <sys/resource.h>
12 #include <bpf/libbpf.h>
14 #include "trace_helpers.h"
16 #define PRINT_RAW_ADDR 0
18 /* counts, stackmap */
21 static void print_ksym(__u64 addr)
27 sym = ksym_search(addr);
29 printf("ksym not found. Is kallsyms loaded?\n");
34 printf("%s/%llx;", sym->name, addr);
36 printf("%s;", sym->name);
39 #define TASK_COMM_LEN 16
42 char waker[TASK_COMM_LEN];
43 char target[TASK_COMM_LEN];
48 static void print_stack(struct key_t *key, __u64 count)
50 __u64 ip[PERF_MAX_STACK_DEPTH] = {};
54 printf("%s;", key->target);
55 if (bpf_map_lookup_elem(map_fd[1], &key->tret, ip) != 0) {
58 for (i = PERF_MAX_STACK_DEPTH - 1; i >= 0; i--)
62 if (bpf_map_lookup_elem(map_fd[1], &key->wret, ip) != 0) {
65 for (i = 0; i < PERF_MAX_STACK_DEPTH; i++)
68 printf(";%s %lld\n", key->waker, count);
70 if ((key->tret == -EEXIST || key->wret == -EEXIST) && !warned) {
71 printf("stackmap collisions seen. Consider increasing size\n");
73 } else if (((int)(key->tret) < 0 || (int)(key->wret) < 0)) {
74 printf("err stackid %d %d\n", key->tret, key->wret);
78 static void print_stacks(int fd)
80 struct key_t key = {}, next_key;
83 while (bpf_map_get_next_key(fd, &key, &next_key) == 0) {
84 bpf_map_lookup_elem(fd, &next_key, &value);
85 print_stack(&next_key, value);
90 static void int_exit(int sig)
92 print_stacks(map_fd[0]);
96 int main(int argc, char **argv)
98 struct bpf_object *obj = NULL;
99 struct bpf_link *links[2];
100 struct bpf_program *prog;
101 int delay = 1, i = 0;
104 if (load_kallsyms()) {
105 printf("failed to process /proc/kallsyms\n");
109 snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]);
110 obj = bpf_object__open_file(filename, NULL);
111 if (libbpf_get_error(obj)) {
112 fprintf(stderr, "ERROR: opening BPF object file failed\n");
117 /* load BPF program */
118 if (bpf_object__load(obj)) {
119 fprintf(stderr, "ERROR: loading BPF object file failed\n");
123 map_fd[0] = bpf_object__find_map_fd_by_name(obj, "counts");
124 map_fd[1] = bpf_object__find_map_fd_by_name(obj, "stackmap");
125 if (map_fd[0] < 0 || map_fd[1] < 0) {
126 fprintf(stderr, "ERROR: finding a map in obj file failed\n");
130 signal(SIGINT, int_exit);
131 signal(SIGTERM, int_exit);
133 bpf_object__for_each_program(prog, obj) {
134 links[i] = bpf_program__attach(prog);
135 if (libbpf_get_error(links[i])) {
136 fprintf(stderr, "ERROR: bpf_program__attach failed\n");
144 delay = atoi(argv[1]);
146 print_stacks(map_fd[0]);
149 for (i--; i >= 0; i--)
150 bpf_link__destroy(links[i]);
152 bpf_object__close(obj);