1 /* SPDX-License-Identifier: GPL-2.0
2 * Copyright (c) 2018 Facebook
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of version 2 of the GNU General Public
6 * License as published by the Free Software Foundation.
9 #include <linux/if_link.h>
16 #include <sys/resource.h>
17 #include <arpa/inet.h>
18 #include <netinet/ether.h>
22 #include "bpf/libbpf.h"
24 #define STATS_INTERVAL_S 2U
26 static int ifindex = -1;
27 static __u32 xdp_flags;
29 static void int_exit(int sig)
32 bpf_set_link_xdp_fd(ifindex, -1, xdp_flags);
36 /* simple "icmp packet too big sent" counter
38 static void poll_stats(unsigned int map_fd, unsigned int kill_after_s)
40 time_t started_at = time(NULL);
45 while (!kill_after_s || time(NULL) - started_at <= kill_after_s) {
46 sleep(STATS_INTERVAL_S);
48 assert(bpf_map_lookup_elem(map_fd, &key, &value) == 0);
50 printf("icmp \"packet too big\" sent: %10llu pkts\n", value);
54 static void usage(const char *cmd)
56 printf("Start a XDP prog which send ICMP \"packet too big\" \n"
57 "messages if ingress packet is bigger then MAX_SIZE bytes\n");
58 printf("Usage: %s [...]\n", cmd);
59 printf(" -i <ifindex> Interface Index\n");
60 printf(" -T <stop-after-X-seconds> Default: 0 (forever)\n");
61 printf(" -S use skb-mode\n");
62 printf(" -N enforce native mode\n");
63 printf(" -h Display this help\n");
66 int main(int argc, char **argv)
68 struct rlimit r = {RLIM_INFINITY, RLIM_INFINITY};
69 struct bpf_prog_load_attr prog_load_attr = {
70 .prog_type = BPF_PROG_TYPE_XDP,
72 unsigned char opt_flags[256] = {};
73 unsigned int kill_after_s = 0;
74 const char *optstr = "i:T:SNh";
75 int i, prog_fd, map_fd, opt;
76 struct bpf_object *obj;
80 for (i = 0; i < strlen(optstr); i++)
81 if (optstr[i] != 'h' && 'a' <= optstr[i] && optstr[i] <= 'z')
82 opt_flags[(unsigned char)optstr[i]] = 1;
84 while ((opt = getopt(argc, argv, optstr)) != -1) {
88 ifindex = atoi(optarg);
91 kill_after_s = atoi(optarg);
94 xdp_flags |= XDP_FLAGS_SKB_MODE;
97 xdp_flags |= XDP_FLAGS_DRV_MODE;
106 for (i = 0; i < strlen(optstr); i++) {
107 if (opt_flags[(unsigned int)optstr[i]]) {
108 fprintf(stderr, "Missing argument -%c\n", optstr[i]);
114 if (setrlimit(RLIMIT_MEMLOCK, &r)) {
115 perror("setrlimit(RLIMIT_MEMLOCK, RLIM_INFINITY)");
119 snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]);
120 prog_load_attr.file = filename;
122 if (bpf_prog_load_xattr(&prog_load_attr, &obj, &prog_fd))
125 map = bpf_map__next(NULL, obj);
127 printf("finding a map in obj file failed\n");
130 map_fd = bpf_map__fd(map);
133 printf("load_bpf_file: %s\n", strerror(errno));
137 signal(SIGINT, int_exit);
138 signal(SIGTERM, int_exit);
140 if (bpf_set_link_xdp_fd(ifindex, prog_fd, xdp_flags) < 0) {
141 printf("link set xdp fd failed\n");
145 poll_stats(map_fd, kill_after_s);
147 bpf_set_link_xdp_fd(ifindex, -1, xdp_flags);