1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright (c) 2017-18 David Ahern <dsahern@gmail.com>
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>
30 static int do_attach(int idx, int prog_fd, int map_fd, const char *name)
34 err = bpf_set_link_xdp_fd(idx, prog_fd, 0);
36 printf("ERROR: failed to attach program to %s\n", name);
40 /* Adding ifindex as a possible egress TX port */
41 err = bpf_map_update_elem(map_fd, &idx, &idx, 0);
43 printf("ERROR: failed using device %s as TX-port\n", name);
48 static int do_detach(int idx, const char *name)
52 err = bpf_set_link_xdp_fd(idx, -1, 0);
54 printf("ERROR: failed to detach program from %s\n", name);
56 /* TODO: Remember to cleanup map, when adding use of shared map
57 * bpf_map_delete_elem((map_fd, &idx);
62 static void usage(const char *prog)
65 "usage: %s [OPTS] interface-list\n"
67 " -d detach program\n"
68 " -D direct table lookups (skip fib rules)\n",
72 int main(int argc, char **argv)
74 struct bpf_prog_load_attr prog_load_attr = {
75 .prog_type = BPF_PROG_TYPE_XDP,
77 const char *prog_name = "xdp_fwd";
78 struct bpf_program *prog;
79 int prog_fd, map_fd = -1;
80 char filename[PATH_MAX];
81 struct bpf_object *obj;
86 while ((opt = getopt(argc, argv, ":dD")) != -1) {
92 prog_name = "xdp_fwd_direct";
95 usage(basename(argv[0]));
100 if (optind == argc) {
101 usage(basename(argv[0]));
106 snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]);
107 prog_load_attr.file = filename;
109 if (access(filename, O_RDONLY) < 0) {
110 printf("error accessing file %s: %s\n",
111 filename, strerror(errno));
115 err = bpf_prog_load_xattr(&prog_load_attr, &obj, &prog_fd);
117 printf("Does kernel support devmap lookup?\n");
118 /* If not, the error message will be:
119 * "cannot pass map_type 14 into func bpf_map_lookup_elem#1"
124 prog = bpf_object__find_program_by_title(obj, prog_name);
125 prog_fd = bpf_program__fd(prog);
127 printf("program not found: %s\n", strerror(prog_fd));
130 map_fd = bpf_map__fd(bpf_object__find_map_by_name(obj,
133 printf("map not found: %s\n", strerror(map_fd));
138 for (i = optind; i < argc; ++i) {
139 idx = if_nametoindex(argv[i]);
141 idx = strtoul(argv[i], NULL, 0);
144 fprintf(stderr, "Invalid arg\n");
148 err = do_detach(idx, argv[i]);
152 err = do_attach(idx, prog_fd, map_fd, argv[i]);