xref: /openbmc/linux/samples/bpf/lwt_len_hist_user.c (revision c51d39010a1bccc9c1294e2d7c00005aefeb2b5c)
1 #include <linux/unistd.h>
2 #include <linux/bpf.h>
3 
4 #include <stdlib.h>
5 #include <stdio.h>
6 #include <unistd.h>
7 #include <string.h>
8 #include <errno.h>
9 #include <arpa/inet.h>
10 
11 #include "libbpf.h"
12 #include "bpf_util.h"
13 
14 #define MAX_INDEX 64
15 #define MAX_STARS 38
16 
17 static void stars(char *str, long val, long max, int width)
18 {
19 	int i;
20 
21 	for (i = 0; i < (width * val / max) - 1 && i < width - 1; i++)
22 		str[i] = '*';
23 	if (val > max)
24 		str[i - 1] = '+';
25 	str[i] = '\0';
26 }
27 
28 int main(int argc, char **argv)
29 {
30 	unsigned int nr_cpus = bpf_num_possible_cpus();
31 	const char *map_filename = "/sys/fs/bpf/tc/globals/lwt_len_hist_map";
32 	uint64_t values[nr_cpus], sum, max_value = 0, data[MAX_INDEX] = {};
33 	uint64_t key = 0, next_key, max_key = 0;
34 	char starstr[MAX_STARS];
35 	int i, map_fd;
36 
37 	map_fd = bpf_obj_get(map_filename);
38 	if (map_fd < 0) {
39 		fprintf(stderr, "bpf_obj_get(%s): %s(%d)\n",
40 			map_filename, strerror(errno), errno);
41 		return -1;
42 	}
43 
44 	while (bpf_get_next_key(map_fd, &key, &next_key) == 0) {
45 		if (next_key >= MAX_INDEX) {
46 			fprintf(stderr, "Key %lu out of bounds\n", next_key);
47 			continue;
48 		}
49 
50 		bpf_lookup_elem(map_fd, &next_key, values);
51 
52 		sum = 0;
53 		for (i = 0; i < nr_cpus; i++)
54 			sum += values[i];
55 
56 		data[next_key] = sum;
57 		if (sum && next_key > max_key)
58 			max_key = next_key;
59 
60 		if (sum > max_value)
61 			max_value = sum;
62 
63 		key = next_key;
64 	}
65 
66 	for (i = 1; i <= max_key + 1; i++) {
67 		stars(starstr, data[i - 1], max_value, MAX_STARS);
68 		printf("%8ld -> %-8ld : %-8ld |%-*s|\n",
69 		       (1l << i) >> 1, (1l << i) - 1, data[i - 1],
70 		       MAX_STARS, starstr);
71 	}
72 
73 	close(map_fd);
74 
75 	return 0;
76 }
77