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>
27 #include <bpf/libbpf.h>
29 static struct bpf_link
*tp_links
[3];
30 static struct bpf_object
*obj
;
34 static void dump_counts(int fd
)
39 for (key
= 0; key
< 256; key
++) {
40 if (bpf_map_lookup_elem(fd
, &key
, &value
)) {
41 printf("failed to read key %u\n", key
);
45 printf("0x%02x : %llu\n", key
, value
);
49 static void dump_all_counts(void)
51 printf("Read 'Class : count'\n");
52 dump_counts(map_fd
[0]);
53 printf("Write 'Class : count'\n");
54 dump_counts(map_fd
[1]);
57 static void dump_exit(int sig
)
60 /* Detach tracepoints */
62 bpf_link__destroy(tp_links
[--tp_cnt
]);
64 bpf_object__close(obj
);
68 static const struct option long_options
[] = {
69 {"help", no_argument
, NULL
, 'h'},
70 {"delay", required_argument
, NULL
, 'd'},
73 static void usage(char *cmd
)
75 printf("eBPF test program to count packets from various IP addresses\n"
76 "Usage: %s <options>\n"
77 " --help, -h this menu\n"
78 " --delay, -d <delay> wait <delay> sec between prints [1 - 1000000]\n"
83 int main(int argc
, char **argv
)
85 struct bpf_program
*prog
;
86 unsigned long delay
= 5;
91 while ((opt
= getopt_long(argc
, argv
, "hd:rSw",
92 long_options
, &longindex
)) != -1) {
95 delay
= strtoul(optarg
, NULL
, 0);
96 if (delay
== ULONG_MAX
|| delay
< 0 ||
98 fprintf(stderr
, "ERROR: invalid delay : %s\n",
111 /* Do one final dump when exiting */
112 signal(SIGINT
, dump_exit
);
113 signal(SIGTERM
, dump_exit
);
115 snprintf(filename
, sizeof(filename
), "%s_kern.o", argv
[0]);
116 obj
= bpf_object__open_file(filename
, NULL
);
117 if (libbpf_get_error(obj
)) {
118 fprintf(stderr
, "ERROR: opening BPF object file failed\n");
122 /* load BPF program */
123 if (bpf_object__load(obj
)) {
124 fprintf(stderr
, "ERROR: loading BPF object file failed\n");
128 map_fd
[0] = bpf_object__find_map_fd_by_name(obj
, "read_count");
129 map_fd
[1] = bpf_object__find_map_fd_by_name(obj
, "write_count");
130 if (map_fd
[0] < 0 || map_fd
[1] < 0) {
131 fprintf(stderr
, "ERROR: finding a map in obj file failed\n");
135 bpf_object__for_each_program(prog
, obj
) {
136 tp_links
[tp_cnt
] = bpf_program__attach(prog
);
137 if (libbpf_get_error(tp_links
[tp_cnt
])) {
138 fprintf(stderr
, "ERROR: bpf_program__attach failed\n");
139 tp_links
[tp_cnt
] = NULL
;
152 /* Detach tracepoints */
154 bpf_link__destroy(tp_links
[--tp_cnt
]);
156 bpf_object__close(obj
);