blob: d2be65d1fd86ed199909bc6c68327f7d31e6b35a [file] [log] [blame]
Brenden Blanco86af8b42016-07-19 12:16:51 -07001/* 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>
Brenden Blanco86af8b42016-07-19 12:16:51 -07008#include <assert.h>
9#include <errno.h>
10#include <signal.h>
11#include <stdio.h>
12#include <stdlib.h>
13#include <string.h>
Brenden Blanco86af8b42016-07-19 12:16:51 -070014#include <unistd.h>
Daniel Borkmanne00c7b22016-11-26 01:28:09 +010015
Brenden Blanco86af8b42016-07-19 12:16:51 -070016#include "bpf_load.h"
Daniel Borkmanne00c7b22016-11-26 01:28:09 +010017#include "bpf_util.h"
Brenden Blanco86af8b42016-07-19 12:16:51 -070018#include "libbpf.h"
19
Brenden Blanco86af8b42016-07-19 12:16:51 -070020static int ifindex;
21
22static 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 */
30static void poll_stats(int interval)
31{
Daniel Borkmanne00c7b22016-11-26 01:28:09 +010032 unsigned int nr_cpus = bpf_num_possible_cpus();
Brenden Blanco86af8b42016-07-19 12:16:51 -070033 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
Joe Stringerd40fc182016-12-14 14:43:38 -080046 assert(bpf_map_lookup_elem(map_fd[0], &key, values) == 0);
Brenden Blanco86af8b42016-07-19 12:16:51 -070047 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
57int 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}