1 // SPDX-License-Identifier: GPL-2.0 OR Linux-OpenIB
4 * ibumad BPF sample user side
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of version 2 of the GNU General Public
8 * License as published by the Free Software Foundation.
10 * Copyright(c) 2018 Ira Weiny, Intel Corporation
13 #include <linux/bpf.h>
19 #include <sys/types.h>
22 #include <sys/resource.h>
28 #include <bpf/libbpf.h>
30 static struct bpf_link *tp_links[3];
31 static struct bpf_object *obj;
35 static void dump_counts(int fd)
40 for (key = 0; key < 256; key++) {
41 if (bpf_map_lookup_elem(fd, &key, &value)) {
42 printf("failed to read key %u\n", key);
46 printf("0x%02x : %llu\n", key, value);
50 static void dump_all_counts(void)
52 printf("Read 'Class : count'\n");
53 dump_counts(map_fd[0]);
54 printf("Write 'Class : count'\n");
55 dump_counts(map_fd[1]);
58 static void dump_exit(int sig)
61 /* Detach tracepoints */
63 bpf_link__destroy(tp_links[--tp_cnt]);
65 bpf_object__close(obj);
69 static const struct option long_options[] = {
70 {"help", no_argument, NULL, 'h'},
71 {"delay", required_argument, NULL, 'd'},
74 static void usage(char *cmd)
76 printf("eBPF test program to count packets from various IP addresses\n"
77 "Usage: %s <options>\n"
78 " --help, -h this menu\n"
79 " --delay, -d <delay> wait <delay> sec between prints [1 - 1000000]\n"
84 int main(int argc, char **argv)
86 struct bpf_program *prog;
87 unsigned long delay = 5;
92 while ((opt = getopt_long(argc, argv, "hd:rSw",
93 long_options, &longindex)) != -1) {
96 delay = strtoul(optarg, NULL, 0);
97 if (delay == ULONG_MAX || delay < 0 ||
99 fprintf(stderr, "ERROR: invalid delay : %s\n",
112 /* Do one final dump when exiting */
113 signal(SIGINT, dump_exit);
114 signal(SIGTERM, dump_exit);
116 snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]);
117 obj = bpf_object__open_file(filename, NULL);
118 if (libbpf_get_error(obj)) {
119 fprintf(stderr, "ERROR: opening BPF object file failed\n");
123 /* load BPF program */
124 if (bpf_object__load(obj)) {
125 fprintf(stderr, "ERROR: loading BPF object file failed\n");
129 map_fd[0] = bpf_object__find_map_fd_by_name(obj, "read_count");
130 map_fd[1] = bpf_object__find_map_fd_by_name(obj, "write_count");
131 if (map_fd[0] < 0 || map_fd[1] < 0) {
132 fprintf(stderr, "ERROR: finding a map in obj file failed\n");
136 bpf_object__for_each_program(prog, obj) {
137 tp_links[tp_cnt] = bpf_program__attach(prog);
138 if (libbpf_get_error(tp_links[tp_cnt])) {
139 fprintf(stderr, "ERROR: bpf_program__attach failed\n");
140 tp_links[tp_cnt] = NULL;
153 /* Detach tracepoints */
155 bpf_link__destroy(tp_links[--tp_cnt]);
157 bpf_object__close(obj);