]> git.karo-electronics.de Git - karo-tx-linux.git/blob - samples/bpf/xdp1_user.c
Merge branch 'next' of git://git.kernel.org/pub/scm/linux/kernel/git/jmorris/linux...
[karo-tx-linux.git] / samples / bpf / xdp1_user.c
1 /* Copyright (c) 2016 PLUMgrid
2  *
3  * This program is free software; you can redistribute it and/or
4  * modify it under the terms of version 2 of the GNU General Public
5  * License as published by the Free Software Foundation.
6  */
7 #include <linux/bpf.h>
8 #include <assert.h>
9 #include <errno.h>
10 #include <signal.h>
11 #include <stdio.h>
12 #include <stdlib.h>
13 #include <string.h>
14 #include <unistd.h>
15
16 #include "bpf_load.h"
17 #include "bpf_util.h"
18 #include "libbpf.h"
19
20 static int ifindex;
21
22 static void int_exit(int sig)
23 {
24         set_link_xdp_fd(ifindex, -1);
25         exit(0);
26 }
27
28 /* simple per-protocol drop counter
29  */
30 static void poll_stats(int interval)
31 {
32         unsigned int nr_cpus = bpf_num_possible_cpus();
33         const unsigned int nr_keys = 256;
34         __u64 values[nr_cpus], prev[nr_keys][nr_cpus];
35         __u32 key;
36         int i;
37
38         memset(prev, 0, sizeof(prev));
39
40         while (1) {
41                 sleep(interval);
42
43                 for (key = 0; key < nr_keys; key++) {
44                         __u64 sum = 0;
45
46                         assert(bpf_lookup_elem(map_fd[0], &key, values) == 0);
47                         for (i = 0; i < nr_cpus; i++)
48                                 sum += (values[i] - prev[key][i]);
49                         if (sum)
50                                 printf("proto %u: %10llu pkt/s\n",
51                                        key, sum / interval);
52                         memcpy(prev[key], values, sizeof(values));
53                 }
54         }
55 }
56
57 int main(int ac, char **argv)
58 {
59         char filename[256];
60
61         snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]);
62
63         if (ac != 2) {
64                 printf("usage: %s IFINDEX\n", argv[0]);
65                 return 1;
66         }
67
68         ifindex = strtoul(argv[1], NULL, 0);
69
70         if (load_bpf_file(filename)) {
71                 printf("%s", bpf_log_buf);
72                 return 1;
73         }
74
75         if (!prog_fd[0]) {
76                 printf("load_bpf_file: %s\n", strerror(errno));
77                 return 1;
78         }
79
80         signal(SIGINT, int_exit);
81
82         if (set_link_xdp_fd(ifindex, prog_fd[0]) < 0) {
83                 printf("link set xdp fd failed\n");
84                 return 1;
85         }
86
87         poll_stats(2);
88
89         return 0;
90 }