Merge branch 'for-linus' into next
[linux-2.6-microblaze.git] / samples / bpf / sampleip_user.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * sampleip: sample instruction pointer and frequency count in a BPF map.
4  *
5  * Copyright 2016 Netflix, Inc.
6  */
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <unistd.h>
10 #include <errno.h>
11 #include <signal.h>
12 #include <string.h>
13 #include <linux/perf_event.h>
14 #include <linux/ptrace.h>
15 #include <linux/bpf.h>
16 #include <bpf/bpf.h>
17 #include <bpf/libbpf.h>
18 #include "perf-sys.h"
19 #include "trace_helpers.h"
20
21 #define __must_check
22 #include <linux/err.h>
23
24 #define DEFAULT_FREQ    99
25 #define DEFAULT_SECS    5
26 #define MAX_IPS         8192
27 #define PAGE_OFFSET     0xffff880000000000
28
29 static int map_fd;
30 static int nr_cpus;
31
32 static void usage(void)
33 {
34         printf("USAGE: sampleip [-F freq] [duration]\n");
35         printf("       -F freq    # sample frequency (Hertz), default 99\n");
36         printf("       duration   # sampling duration (seconds), default 5\n");
37 }
38
39 static int sampling_start(int freq, struct bpf_program *prog,
40                           struct bpf_link *links[])
41 {
42         int i, pmu_fd;
43
44         struct perf_event_attr pe_sample_attr = {
45                 .type = PERF_TYPE_SOFTWARE,
46                 .freq = 1,
47                 .sample_period = freq,
48                 .config = PERF_COUNT_SW_CPU_CLOCK,
49                 .inherit = 1,
50         };
51
52         for (i = 0; i < nr_cpus; i++) {
53                 pmu_fd = sys_perf_event_open(&pe_sample_attr, -1 /* pid */, i,
54                                             -1 /* group_fd */, 0 /* flags */);
55                 if (pmu_fd < 0) {
56                         fprintf(stderr, "ERROR: Initializing perf sampling\n");
57                         return 1;
58                 }
59                 links[i] = bpf_program__attach_perf_event(prog, pmu_fd);
60                 if (IS_ERR(links[i])) {
61                         fprintf(stderr, "ERROR: Attach perf event\n");
62                         links[i] = NULL;
63                         close(pmu_fd);
64                         return 1;
65                 }
66         }
67
68         return 0;
69 }
70
71 static void sampling_end(struct bpf_link *links[])
72 {
73         int i;
74
75         for (i = 0; i < nr_cpus; i++)
76                 bpf_link__destroy(links[i]);
77 }
78
79 struct ipcount {
80         __u64 ip;
81         __u32 count;
82 };
83
84 /* used for sorting */
85 struct ipcount counts[MAX_IPS];
86
87 static int count_cmp(const void *p1, const void *p2)
88 {
89         return ((struct ipcount *)p1)->count - ((struct ipcount *)p2)->count;
90 }
91
92 static void print_ip_map(int fd)
93 {
94         struct ksym *sym;
95         __u64 key, next_key;
96         __u32 value;
97         int i, max;
98
99         printf("%-19s %-32s %s\n", "ADDR", "KSYM", "COUNT");
100
101         /* fetch IPs and counts */
102         key = 0, i = 0;
103         while (bpf_map_get_next_key(fd, &key, &next_key) == 0) {
104                 bpf_map_lookup_elem(fd, &next_key, &value);
105                 counts[i].ip = next_key;
106                 counts[i++].count = value;
107                 key = next_key;
108         }
109         max = i;
110
111         /* sort and print */
112         qsort(counts, max, sizeof(struct ipcount), count_cmp);
113         for (i = 0; i < max; i++) {
114                 if (counts[i].ip > PAGE_OFFSET) {
115                         sym = ksym_search(counts[i].ip);
116                         if (!sym) {
117                                 printf("ksym not found. Is kallsyms loaded?\n");
118                                 continue;
119                         }
120
121                         printf("0x%-17llx %-32s %u\n", counts[i].ip, sym->name,
122                                counts[i].count);
123                 } else {
124                         printf("0x%-17llx %-32s %u\n", counts[i].ip, "(user)",
125                                counts[i].count);
126                 }
127         }
128
129         if (max == MAX_IPS) {
130                 printf("WARNING: IP hash was full (max %d entries); ", max);
131                 printf("may have dropped samples\n");
132         }
133 }
134
135 static void int_exit(int sig)
136 {
137         printf("\n");
138         print_ip_map(map_fd);
139         exit(0);
140 }
141
142 int main(int argc, char **argv)
143 {
144         int opt, freq = DEFAULT_FREQ, secs = DEFAULT_SECS, error = 1;
145         struct bpf_object *obj = NULL;
146         struct bpf_program *prog;
147         struct bpf_link **links;
148         char filename[256];
149
150         /* process arguments */
151         while ((opt = getopt(argc, argv, "F:h")) != -1) {
152                 switch (opt) {
153                 case 'F':
154                         freq = atoi(optarg);
155                         break;
156                 case 'h':
157                 default:
158                         usage();
159                         return 0;
160                 }
161         }
162         if (argc - optind == 1)
163                 secs = atoi(argv[optind]);
164         if (freq == 0 || secs == 0) {
165                 usage();
166                 return 1;
167         }
168
169         /* initialize kernel symbol translation */
170         if (load_kallsyms()) {
171                 fprintf(stderr, "ERROR: loading /proc/kallsyms\n");
172                 return 2;
173         }
174
175         /* create perf FDs for each CPU */
176         nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
177         links = calloc(nr_cpus, sizeof(struct bpf_link *));
178         if (!links) {
179                 fprintf(stderr, "ERROR: malloc of links\n");
180                 goto cleanup;
181         }
182
183         snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]);
184         obj = bpf_object__open_file(filename, NULL);
185         if (IS_ERR(obj)) {
186                 fprintf(stderr, "ERROR: opening BPF object file failed\n");
187                 obj = NULL;
188                 goto cleanup;
189         }
190
191         prog = bpf_object__find_program_by_name(obj, "do_sample");
192         if (!prog) {
193                 fprintf(stderr, "ERROR: finding a prog in obj file failed\n");
194                 goto cleanup;
195         }
196
197         /* load BPF program */
198         if (bpf_object__load(obj)) {
199                 fprintf(stderr, "ERROR: loading BPF object file failed\n");
200                 goto cleanup;
201         }
202
203         map_fd = bpf_object__find_map_fd_by_name(obj, "ip_map");
204         if (map_fd < 0) {
205                 fprintf(stderr, "ERROR: finding a map in obj file failed\n");
206                 goto cleanup;
207         }
208
209         signal(SIGINT, int_exit);
210         signal(SIGTERM, int_exit);
211
212         /* do sampling */
213         printf("Sampling at %d Hertz for %d seconds. Ctrl-C also ends.\n",
214                freq, secs);
215         if (sampling_start(freq, prog, links) != 0)
216                 goto cleanup;
217
218         sleep(secs);
219         error = 0;
220
221 cleanup:
222         sampling_end(links);
223         /* output sample counts */
224         if (!error)
225                 print_ip_map(map_fd);
226
227         free(links);
228         bpf_object__close(obj);
229         return error;
230 }