Path: blob/master/tools/testing/selftests/bpf/flow_dissector_load.c
26285 views
// SPDX-License-Identifier: GPL-2.01#include <error.h>2#include <errno.h>3#include <getopt.h>4#include <stdio.h>5#include <stdlib.h>6#include <string.h>7#include <sys/stat.h>8#include <fcntl.h>9#include <unistd.h>10#include <bpf/bpf.h>11#include <bpf/libbpf.h>1213#include "flow_dissector_load.h"1415const char *cfg_pin_path = "/sys/fs/bpf/flow_dissector";16const char *cfg_map_name = "jmp_table";17bool cfg_attach = true;18char *cfg_prog_name;19char *cfg_path_name;2021static void load_and_attach_program(void)22{23int prog_fd, ret;24struct bpf_object *obj;2526/* Use libbpf 1.0 API mode */27libbpf_set_strict_mode(LIBBPF_STRICT_ALL);2829ret = bpf_flow_load(&obj, cfg_path_name, cfg_prog_name,30cfg_map_name, NULL, &prog_fd, NULL);31if (ret)32error(1, 0, "bpf_flow_load %s", cfg_path_name);3334ret = bpf_prog_attach(prog_fd, 0 /* Ignore */, BPF_FLOW_DISSECTOR, 0);35if (ret)36error(1, 0, "bpf_prog_attach %s", cfg_path_name);3738ret = bpf_object__pin(obj, cfg_pin_path);39if (ret)40error(1, 0, "bpf_object__pin %s", cfg_pin_path);41}4243static void detach_program(void)44{45char command[64];46int ret;4748ret = bpf_prog_detach(0, BPF_FLOW_DISSECTOR);49if (ret)50error(1, 0, "bpf_prog_detach");5152/* To unpin, it is necessary and sufficient to just remove this dir */53sprintf(command, "rm -r %s", cfg_pin_path);54ret = system(command);55if (ret)56error(1, errno, "%s", command);57}5859static void parse_opts(int argc, char **argv)60{61bool attach = false;62bool detach = false;63int c;6465while ((c = getopt(argc, argv, "adp:s:")) != -1) {66switch (c) {67case 'a':68if (detach)69error(1, 0, "attach/detach are exclusive");70attach = true;71break;72case 'd':73if (attach)74error(1, 0, "attach/detach are exclusive");75detach = true;76break;77case 'p':78if (cfg_path_name)79error(1, 0, "only one path can be given");8081cfg_path_name = optarg;82break;83case 's':84if (cfg_prog_name)85error(1, 0, "only one prog can be given");8687cfg_prog_name = optarg;88break;89}90}9192if (detach)93cfg_attach = false;9495if (cfg_attach && !cfg_path_name)96error(1, 0, "must provide a path to the BPF program");9798if (cfg_attach && !cfg_prog_name)99error(1, 0, "must provide a section name");100}101102int main(int argc, char **argv)103{104parse_opts(argc, argv);105if (cfg_attach)106load_and_attach_program();107else108detach_program();109return 0;110}111112113