1 /* SPDX-License-Identifier: GPL-2.0
2 * Copyright (c) 2017 Jesper Dangaard Brouer, Red Hat Inc.
4 static const char *__doc__ = " XDP RX-queue info extract example\n\n"
5 "Monitor how many packets per sec (pps) are received\n"
6 "per NIC RX queue index and which CPU processed the packet\n"
17 #include <sys/resource.h>
22 #include <arpa/inet.h>
23 #include <linux/if_link.h>
26 #include "bpf/libbpf.h"
29 static int ifindex = -1;
30 static char ifname_buf[IF_NAMESIZE];
33 static __u32 xdp_flags;
35 static struct bpf_map *stats_global_map;
36 static struct bpf_map *rx_queue_index_map;
38 /* Exit return codes */
41 #define EXIT_FAIL_OPTION 2
42 #define EXIT_FAIL_XDP 3
43 #define EXIT_FAIL_BPF 4
44 #define EXIT_FAIL_MEM 5
46 static const struct option long_options[] = {
47 {"help", no_argument, NULL, 'h' },
48 {"dev", required_argument, NULL, 'd' },
49 {"skb-mode", no_argument, NULL, 'S' },
50 {"sec", required_argument, NULL, 's' },
51 {"no-separators", no_argument, NULL, 'z' },
52 {"action", required_argument, NULL, 'a' },
56 static void int_exit(int sig)
59 "Interrupted: Removing XDP program on ifindex:%d device:%s\n",
62 bpf_set_link_xdp_fd(ifindex, -1, xdp_flags);
70 #define XDP_ACTION_MAX (XDP_TX + 1)
71 #define XDP_ACTION_MAX_STRLEN 11
72 static const char *xdp_action_names[XDP_ACTION_MAX] = {
73 [XDP_ABORTED] = "XDP_ABORTED",
74 [XDP_DROP] = "XDP_DROP",
75 [XDP_PASS] = "XDP_PASS",
79 static const char *action2str(int action)
81 if (action < XDP_ACTION_MAX)
82 return xdp_action_names[action];
86 static int parse_xdp_action(char *action_str)
92 for (i = 0; i < XDP_ACTION_MAX; i++) {
93 maxlen = XDP_ACTION_MAX_STRLEN;
94 if (strncmp(xdp_action_names[i], action_str, maxlen) == 0) {
102 static void list_xdp_actions(void)
106 printf("Available XDP --action <options>\n");
107 for (i = 0; i < XDP_ACTION_MAX; i++)
108 printf("\t%s\n", xdp_action_names[i]);
112 static void usage(char *argv[])
116 printf("\nDOCUMENTATION:\n%s\n", __doc__);
117 printf(" Usage: %s (options-see-below)\n", argv[0]);
118 printf(" Listing options:\n");
119 for (i = 0; long_options[i].name != 0; i++) {
120 printf(" --%-12s", long_options[i].name);
121 if (long_options[i].flag != NULL)
122 printf(" flag (internal value:%d)",
123 *long_options[i].flag);
125 printf(" short-option: -%c",
126 long_options[i].val);
133 #define NANOSEC_PER_SEC 1000000000 /* 10^9 */
134 static __u64 gettime(void)
139 res = clock_gettime(CLOCK_MONOTONIC, &t);
141 fprintf(stderr, "Error with gettimeofday! (%i)\n", res);
144 return (__u64) t.tv_sec * NANOSEC_PER_SEC + t.tv_nsec;
147 /* Common stats data record shared with _kern.c */
154 struct datarec total;
157 struct stats_record {
162 static struct datarec *alloc_record_per_cpu(void)
164 unsigned int nr_cpus = bpf_num_possible_cpus();
165 struct datarec *array;
168 size = sizeof(struct datarec) * nr_cpus;
169 array = malloc(size);
170 memset(array, 0, size);
172 fprintf(stderr, "Mem alloc error (nr_cpus:%u)\n", nr_cpus);
178 static struct record *alloc_record_per_rxq(void)
180 unsigned int nr_rxqs = bpf_map__def(rx_queue_index_map)->max_entries;
181 struct record *array;
184 size = sizeof(struct record) * nr_rxqs;
185 array = malloc(size);
186 memset(array, 0, size);
188 fprintf(stderr, "Mem alloc error (nr_rxqs:%u)\n", nr_rxqs);
194 static struct stats_record *alloc_stats_record(void)
196 unsigned int nr_rxqs = bpf_map__def(rx_queue_index_map)->max_entries;
197 struct stats_record *rec;
200 rec = malloc(sizeof(*rec));
201 memset(rec, 0, sizeof(*rec));
203 fprintf(stderr, "Mem alloc error\n");
206 rec->rxq = alloc_record_per_rxq();
207 for (i = 0; i < nr_rxqs; i++)
208 rec->rxq[i].cpu = alloc_record_per_cpu();
210 rec->stats.cpu = alloc_record_per_cpu();
214 static void free_stats_record(struct stats_record *r)
216 unsigned int nr_rxqs = bpf_map__def(rx_queue_index_map)->max_entries;
219 for (i = 0; i < nr_rxqs; i++)
227 static bool map_collect_percpu(int fd, __u32 key, struct record *rec)
229 /* For percpu maps, userspace gets a value per possible CPU */
230 unsigned int nr_cpus = bpf_num_possible_cpus();
231 struct datarec values[nr_cpus];
232 __u64 sum_processed = 0;
236 if ((bpf_map_lookup_elem(fd, &key, values)) != 0) {
238 "ERR: bpf_map_lookup_elem failed key:0x%X\n", key);
241 /* Get time as close as possible to reading map contents */
242 rec->timestamp = gettime();
244 /* Record and sum values from each CPU */
245 for (i = 0; i < nr_cpus; i++) {
246 rec->cpu[i].processed = values[i].processed;
247 sum_processed += values[i].processed;
248 rec->cpu[i].issue = values[i].issue;
249 sum_issue += values[i].issue;
251 rec->total.processed = sum_processed;
252 rec->total.issue = sum_issue;
256 static void stats_collect(struct stats_record *rec)
260 fd = bpf_map__fd(stats_global_map);
261 map_collect_percpu(fd, 0, &rec->stats);
263 fd = bpf_map__fd(rx_queue_index_map);
264 max_rxqs = bpf_map__def(rx_queue_index_map)->max_entries;
265 for (i = 0; i < max_rxqs; i++)
266 map_collect_percpu(fd, i, &rec->rxq[i]);
269 static double calc_period(struct record *r, struct record *p)
274 period = r->timestamp - p->timestamp;
276 period_ = ((double) period / NANOSEC_PER_SEC);
281 static __u64 calc_pps(struct datarec *r, struct datarec *p, double period_)
287 packets = r->processed - p->processed;
288 pps = packets / period_;
293 static __u64 calc_errs_pps(struct datarec *r,
294 struct datarec *p, double period_)
300 packets = r->issue - p->issue;
301 pps = packets / period_;
306 static void stats_print(struct stats_record *stats_rec,
307 struct stats_record *stats_prev,
310 unsigned int nr_rxqs = bpf_map__def(rx_queue_index_map)->max_entries;
311 unsigned int nr_cpus = bpf_num_possible_cpus();
312 double pps = 0, err = 0;
313 struct record *rec, *prev;
319 printf("\nRunning XDP on dev:%s (ifindex:%d) action:%s\n",
320 ifname, ifindex, action2str(action));
322 /* stats_global_map */
324 char *fmt_rx = "%-15s %-7d %'-11.0f %'-10.0f %s\n";
325 char *fm2_rx = "%-15s %-7s %'-11.0f\n";
328 printf("%-15s %-7s %-11s %-11s\n",
329 "XDP stats", "CPU", "pps", "issue-pps");
331 rec = &stats_rec->stats;
332 prev = &stats_prev->stats;
333 t = calc_period(rec, prev);
334 for (i = 0; i < nr_cpus; i++) {
335 struct datarec *r = &rec->cpu[i];
336 struct datarec *p = &prev->cpu[i];
338 pps = calc_pps (r, p, t);
339 err = calc_errs_pps(r, p, t);
341 errstr = "invalid-ifindex";
343 printf(fmt_rx, "XDP-RX CPU",
344 i, pps, err, errstr);
346 pps = calc_pps (&rec->total, &prev->total, t);
347 err = calc_errs_pps(&rec->total, &prev->total, t);
348 printf(fm2_rx, "XDP-RX CPU", "total", pps, err);
351 /* rx_queue_index_map */
352 printf("\n%-15s %-7s %-11s %-11s\n",
353 "RXQ stats", "RXQ:CPU", "pps", "issue-pps");
355 for (rxq = 0; rxq < nr_rxqs; rxq++) {
356 char *fmt_rx = "%-15s %3d:%-3d %'-11.0f %'-10.0f %s\n";
357 char *fm2_rx = "%-15s %3d:%-3s %'-11.0f\n";
361 /* Last RXQ in map catch overflows */
362 if (rxq_ == nr_rxqs - 1)
365 rec = &stats_rec->rxq[rxq];
366 prev = &stats_prev->rxq[rxq];
367 t = calc_period(rec, prev);
368 for (i = 0; i < nr_cpus; i++) {
369 struct datarec *r = &rec->cpu[i];
370 struct datarec *p = &prev->cpu[i];
372 pps = calc_pps (r, p, t);
373 err = calc_errs_pps(r, p, t);
376 errstr = "map-overflow-RXQ";
381 printf(fmt_rx, "rx_queue_index",
382 rxq_, i, pps, err, errstr);
384 pps = calc_pps (&rec->total, &prev->total, t);
385 err = calc_errs_pps(&rec->total, &prev->total, t);
387 printf(fm2_rx, "rx_queue_index", rxq_, "sum", pps, err);
392 /* Pointer swap trick */
393 static inline void swap(struct stats_record **a, struct stats_record **b)
395 struct stats_record *tmp;
402 static void stats_poll(int interval, int action)
404 struct stats_record *record, *prev;
406 record = alloc_stats_record();
407 prev = alloc_stats_record();
408 stats_collect(record);
411 swap(&prev, &record);
412 stats_collect(record);
413 stats_print(record, prev, action);
417 free_stats_record(record);
418 free_stats_record(prev);
422 int main(int argc, char **argv)
424 struct rlimit r = {10 * 1024 * 1024, RLIM_INFINITY};
425 struct bpf_prog_load_attr prog_load_attr = {
426 .prog_type = BPF_PROG_TYPE_XDP,
428 int prog_fd, map_fd, opt, err;
429 bool use_separators = true;
430 struct config cfg = { 0 };
431 struct bpf_object *obj;
438 char action_str_buf[XDP_ACTION_MAX_STRLEN + 1 /* for \0 */] = { 0 };
439 int action = XDP_PASS; /* Default action */
440 char *action_str = NULL;
442 snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]);
443 prog_load_attr.file = filename;
445 if (setrlimit(RLIMIT_MEMLOCK, &r)) {
446 perror("setrlimit(RLIMIT_MEMLOCK)");
450 if (bpf_prog_load_xattr(&prog_load_attr, &obj, &prog_fd))
453 map = bpf_map__next(NULL, obj);
454 stats_global_map = bpf_map__next(map, obj);
455 rx_queue_index_map = bpf_map__next(stats_global_map, obj);
456 if (!map || !stats_global_map || !rx_queue_index_map) {
457 printf("finding a map in obj file failed\n");
460 map_fd = bpf_map__fd(map);
463 fprintf(stderr, "ERR: load_bpf_file: %s\n", strerror(errno));
467 /* Parse commands line args */
468 while ((opt = getopt_long(argc, argv, "hSd:",
469 long_options, &longindex)) != -1) {
472 if (strlen(optarg) >= IF_NAMESIZE) {
473 fprintf(stderr, "ERR: --dev name too long\n");
476 ifname = (char *)&ifname_buf;
477 strncpy(ifname, optarg, IF_NAMESIZE);
478 ifindex = if_nametoindex(ifname);
481 "ERR: --dev name unknown err(%d):%s\n",
482 errno, strerror(errno));
487 interval = atoi(optarg);
490 xdp_flags |= XDP_FLAGS_SKB_MODE;
493 use_separators = false;
496 action_str = (char *)&action_str_buf;
497 strncpy(action_str, optarg, XDP_ACTION_MAX_STRLEN);
503 return EXIT_FAIL_OPTION;
506 /* Required option */
508 fprintf(stderr, "ERR: required option --dev missing\n");
510 return EXIT_FAIL_OPTION;
512 cfg.ifindex = ifindex;
514 /* Parse action string */
516 action = parse_xdp_action(action_str);
518 fprintf(stderr, "ERR: Invalid XDP --action: %s\n",
521 return EXIT_FAIL_OPTION;
526 /* Trick to pretty printf with thousands separators use %' */
528 setlocale(LC_NUMERIC, "en_US");
530 /* User-side setup ifindex in config_map */
531 err = bpf_map_update_elem(map_fd, &key, &cfg, 0);
533 fprintf(stderr, "Store config failed (err:%d)\n", err);
537 /* Remove XDP program when program is interrupted */
538 signal(SIGINT, int_exit);
540 if (bpf_set_link_xdp_fd(ifindex, prog_fd, xdp_flags) < 0) {
541 fprintf(stderr, "link set xdp fd failed\n");
542 return EXIT_FAIL_XDP;
545 stats_poll(interval, action);