1 // SPDX-License-Identifier: GPL-2.0
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.
8 * This program is distributed in the hope that it will be useful, but
9 * WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
14 #include <linux/bpf.h>
15 #include <linux/if_link.h>
16 #include <linux/limits.h>
27 #include "bpf/libbpf.h"
31 static int do_attach(int idx, int fd, const char *name)
35 err = bpf_set_link_xdp_fd(idx, fd, 0);
37 printf("ERROR: failed to attach program to %s\n", name);
42 static int do_detach(int idx, const char *name)
46 err = bpf_set_link_xdp_fd(idx, -1, 0);
48 printf("ERROR: failed to detach program from %s\n", name);
53 static void usage(const char *prog)
56 "usage: %s [OPTS] interface-list\n"
58 " -d detach program\n"
59 " -D direct table lookups (skip fib rules)\n",
63 int main(int argc, char **argv)
65 struct bpf_prog_load_attr prog_load_attr = {
66 .prog_type = BPF_PROG_TYPE_XDP,
68 const char *prog_name = "xdp_fwd";
69 struct bpf_program *prog;
70 char filename[PATH_MAX];
71 struct bpf_object *obj;
77 while ((opt = getopt(argc, argv, ":dD")) != -1) {
83 prog_name = "xdp_fwd_direct";
86 usage(basename(argv[0]));
92 usage(basename(argv[0]));
97 snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]);
98 prog_load_attr.file = filename;
100 if (access(filename, O_RDONLY) < 0) {
101 printf("error accessing file %s: %s\n",
102 filename, strerror(errno));
106 if (bpf_prog_load_xattr(&prog_load_attr, &obj, &prog_fd))
109 prog = bpf_object__find_program_by_title(obj, prog_name);
110 prog_fd = bpf_program__fd(prog);
112 printf("program not found: %s\n", strerror(prog_fd));
115 map_fd = bpf_map__fd(bpf_object__find_map_by_name(obj,
118 printf("map not found: %s\n", strerror(map_fd));
123 for (i = 1; i < 64; ++i)
124 bpf_map_update_elem(map_fd, &i, &i, 0);
127 for (i = optind; i < argc; ++i) {
128 idx = if_nametoindex(argv[i]);
130 idx = strtoul(argv[i], NULL, 0);
133 fprintf(stderr, "Invalid arg\n");
137 err = do_detach(idx, argv[i]);
141 err = do_attach(idx, prog_fd, argv[i]);