xref: /linux/samples/bpf/lwt_len_hist_user.c (revision e58e871becec2d3b04ed91c0c16fe8deac9c9dfa)
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 char bpf_log_buf[BPF_LOG_BUF_SIZE];
18 
19 static void stars(char *str, long val, long max, int width)
20 {
21 	int i;
22 
23 	for (i = 0; i < (width * val / max) - 1 && i < width - 1; i++)
24 		str[i] = '*';
25 	if (val > max)
26 		str[i - 1] = '+';
27 	str[i] = '\0';
28 }
29 
30 int main(int argc, char **argv)
31 {
32 	unsigned int nr_cpus = bpf_num_possible_cpus();
33 	const char *map_filename = "/sys/fs/bpf/tc/globals/lwt_len_hist_map";
34 	uint64_t values[nr_cpus], sum, max_value = 0, data[MAX_INDEX] = {};
35 	uint64_t key = 0, next_key, max_key = 0;
36 	char starstr[MAX_STARS];
37 	int i, map_fd;
38 
39 	map_fd = bpf_obj_get(map_filename);
40 	if (map_fd < 0) {
41 		fprintf(stderr, "bpf_obj_get(%s): %s(%d)\n",
42 			map_filename, strerror(errno), errno);
43 		return -1;
44 	}
45 
46 	while (bpf_map_get_next_key(map_fd, &key, &next_key) == 0) {
47 		if (next_key >= MAX_INDEX) {
48 			fprintf(stderr, "Key %lu out of bounds\n", next_key);
49 			continue;
50 		}
51 
52 		bpf_map_lookup_elem(map_fd, &next_key, values);
53 
54 		sum = 0;
55 		for (i = 0; i < nr_cpus; i++)
56 			sum += values[i];
57 
58 		data[next_key] = sum;
59 		if (sum && next_key > max_key)
60 			max_key = next_key;
61 
62 		if (sum > max_value)
63 			max_value = sum;
64 
65 		key = next_key;
66 	}
67 
68 	for (i = 1; i <= max_key + 1; i++) {
69 		stars(starstr, data[i - 1], max_value, MAX_STARS);
70 		printf("%8ld -> %-8ld : %-8ld |%-*s|\n",
71 		       (1l << i) >> 1, (1l << i) - 1, data[i - 1],
72 		       MAX_STARS, starstr);
73 	}
74 
75 	close(map_fd);
76 
77 	return 0;
78 }
79