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"
21 #include <arpa/inet.h>
22 #include <linux/if_link.h>
25 #include <bpf/libbpf.h>
28 static int ifindex = -1;
29 static char ifname_buf[IF_NAMESIZE];
33 static __u32 xdp_flags = XDP_FLAGS_UPDATE_IF_NOEXIST;
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 #define FAIL_MEM_SIG INT_MAX
47 #define FAIL_STAT_SIG (INT_MAX - 1)
49 static const struct option long_options[] = {
50 {"help", no_argument, NULL, 'h' },
51 {"dev", required_argument, NULL, 'd' },
52 {"skb-mode", no_argument, NULL, 'S' },
53 {"sec", required_argument, NULL, 's' },
54 {"no-separators", no_argument, NULL, 'z' },
55 {"action", required_argument, NULL, 'a' },
56 {"readmem", no_argument, NULL, 'r' },
57 {"swapmac", no_argument, NULL, 'm' },
58 {"force", no_argument, NULL, 'F' },
62 static void int_exit(int sig)
64 __u32 curr_prog_id = 0;
67 if (bpf_xdp_query_id(ifindex, xdp_flags, &curr_prog_id)) {
68 printf("bpf_xdp_query_id failed\n");
71 if (prog_id == curr_prog_id) {
73 "Interrupted: Removing XDP program on ifindex:%d device:%s\n",
75 bpf_xdp_detach(ifindex, xdp_flags, NULL);
76 } else if (!curr_prog_id) {
77 printf("couldn't find a prog id on a given iface\n");
79 printf("program on interface changed, not removing\n");
83 if (sig == FAIL_MEM_SIG)
85 else if (sig == FAIL_STAT_SIG)
96 enum cfg_options_flags {
101 #define XDP_ACTION_MAX (XDP_TX + 1)
102 #define XDP_ACTION_MAX_STRLEN 11
103 static const char *xdp_action_names[XDP_ACTION_MAX] = {
104 [XDP_ABORTED] = "XDP_ABORTED",
105 [XDP_DROP] = "XDP_DROP",
106 [XDP_PASS] = "XDP_PASS",
110 static const char *action2str(int action)
112 if (action < XDP_ACTION_MAX)
113 return xdp_action_names[action];
117 static int parse_xdp_action(char *action_str)
123 for (i = 0; i < XDP_ACTION_MAX; i++) {
124 maxlen = XDP_ACTION_MAX_STRLEN;
125 if (strncmp(xdp_action_names[i], action_str, maxlen) == 0) {
133 static void list_xdp_actions(void)
137 printf("Available XDP --action <options>\n");
138 for (i = 0; i < XDP_ACTION_MAX; i++)
139 printf("\t%s\n", xdp_action_names[i]);
143 static char* options2str(enum cfg_options_flags flag)
145 if (flag == NO_TOUCH)
151 fprintf(stderr, "ERR: Unknown config option flags");
152 int_exit(FAIL_STAT_SIG);
156 static void usage(char *argv[])
160 printf("\nDOCUMENTATION:\n%s\n", __doc__);
161 printf(" Usage: %s (options-see-below)\n", argv[0]);
162 printf(" Listing options:\n");
163 for (i = 0; long_options[i].name != 0; i++) {
164 printf(" --%-12s", long_options[i].name);
165 if (long_options[i].flag != NULL)
166 printf(" flag (internal value:%d)",
167 *long_options[i].flag);
169 printf(" short-option: -%c",
170 long_options[i].val);
177 #define NANOSEC_PER_SEC 1000000000 /* 10^9 */
178 static __u64 gettime(void)
183 res = clock_gettime(CLOCK_MONOTONIC, &t);
185 fprintf(stderr, "Error with gettimeofday! (%i)\n", res);
186 int_exit(FAIL_STAT_SIG);
188 return (__u64) t.tv_sec * NANOSEC_PER_SEC + t.tv_nsec;
191 /* Common stats data record shared with _kern.c */
198 struct datarec total;
201 struct stats_record {
206 static struct datarec *alloc_record_per_cpu(void)
208 unsigned int nr_cpus = bpf_num_possible_cpus();
209 struct datarec *array;
211 array = calloc(nr_cpus, sizeof(struct datarec));
213 fprintf(stderr, "Mem alloc error (nr_cpus:%u)\n", nr_cpus);
214 int_exit(FAIL_MEM_SIG);
219 static struct record *alloc_record_per_rxq(void)
221 unsigned int nr_rxqs = bpf_map__max_entries(rx_queue_index_map);
222 struct record *array;
224 array = calloc(nr_rxqs, sizeof(struct record));
226 fprintf(stderr, "Mem alloc error (nr_rxqs:%u)\n", nr_rxqs);
227 int_exit(FAIL_MEM_SIG);
232 static struct stats_record *alloc_stats_record(void)
234 unsigned int nr_rxqs = bpf_map__max_entries(rx_queue_index_map);
235 struct stats_record *rec;
238 rec = calloc(1, sizeof(struct stats_record));
240 fprintf(stderr, "Mem alloc error\n");
241 int_exit(FAIL_MEM_SIG);
243 rec->rxq = alloc_record_per_rxq();
244 for (i = 0; i < nr_rxqs; i++)
245 rec->rxq[i].cpu = alloc_record_per_cpu();
247 rec->stats.cpu = alloc_record_per_cpu();
251 static void free_stats_record(struct stats_record *r)
253 unsigned int nr_rxqs = bpf_map__max_entries(rx_queue_index_map);
256 for (i = 0; i < nr_rxqs; i++)
264 static bool map_collect_percpu(int fd, __u32 key, struct record *rec)
266 /* For percpu maps, userspace gets a value per possible CPU */
267 unsigned int nr_cpus = bpf_num_possible_cpus();
268 struct datarec values[nr_cpus];
269 __u64 sum_processed = 0;
273 if ((bpf_map_lookup_elem(fd, &key, values)) != 0) {
275 "ERR: bpf_map_lookup_elem failed key:0x%X\n", key);
278 /* Get time as close as possible to reading map contents */
279 rec->timestamp = gettime();
281 /* Record and sum values from each CPU */
282 for (i = 0; i < nr_cpus; i++) {
283 rec->cpu[i].processed = values[i].processed;
284 sum_processed += values[i].processed;
285 rec->cpu[i].issue = values[i].issue;
286 sum_issue += values[i].issue;
288 rec->total.processed = sum_processed;
289 rec->total.issue = sum_issue;
293 static void stats_collect(struct stats_record *rec)
297 fd = bpf_map__fd(stats_global_map);
298 map_collect_percpu(fd, 0, &rec->stats);
300 fd = bpf_map__fd(rx_queue_index_map);
301 max_rxqs = bpf_map__max_entries(rx_queue_index_map);
302 for (i = 0; i < max_rxqs; i++)
303 map_collect_percpu(fd, i, &rec->rxq[i]);
306 static double calc_period(struct record *r, struct record *p)
311 period = r->timestamp - p->timestamp;
313 period_ = ((double) period / NANOSEC_PER_SEC);
318 static __u64 calc_pps(struct datarec *r, struct datarec *p, double period_)
324 packets = r->processed - p->processed;
325 pps = packets / period_;
330 static __u64 calc_errs_pps(struct datarec *r,
331 struct datarec *p, double period_)
337 packets = r->issue - p->issue;
338 pps = packets / period_;
343 static void stats_print(struct stats_record *stats_rec,
344 struct stats_record *stats_prev,
345 int action, __u32 cfg_opt)
347 unsigned int nr_rxqs = bpf_map__max_entries(rx_queue_index_map);
348 unsigned int nr_cpus = bpf_num_possible_cpus();
349 double pps = 0, err = 0;
350 struct record *rec, *prev;
356 printf("\nRunning XDP on dev:%s (ifindex:%d) action:%s options:%s\n",
357 ifname, ifindex, action2str(action), options2str(cfg_opt));
359 /* stats_global_map */
361 char *fmt_rx = "%-15s %-7d %'-11.0f %'-10.0f %s\n";
362 char *fm2_rx = "%-15s %-7s %'-11.0f\n";
365 printf("%-15s %-7s %-11s %-11s\n",
366 "XDP stats", "CPU", "pps", "issue-pps");
368 rec = &stats_rec->stats;
369 prev = &stats_prev->stats;
370 t = calc_period(rec, prev);
371 for (i = 0; i < nr_cpus; i++) {
372 struct datarec *r = &rec->cpu[i];
373 struct datarec *p = &prev->cpu[i];
375 pps = calc_pps (r, p, t);
376 err = calc_errs_pps(r, p, t);
378 errstr = "invalid-ifindex";
380 printf(fmt_rx, "XDP-RX CPU",
381 i, pps, err, errstr);
383 pps = calc_pps (&rec->total, &prev->total, t);
384 err = calc_errs_pps(&rec->total, &prev->total, t);
385 printf(fm2_rx, "XDP-RX CPU", "total", pps, err);
388 /* rx_queue_index_map */
389 printf("\n%-15s %-7s %-11s %-11s\n",
390 "RXQ stats", "RXQ:CPU", "pps", "issue-pps");
392 for (rxq = 0; rxq < nr_rxqs; rxq++) {
393 char *fmt_rx = "%-15s %3d:%-3d %'-11.0f %'-10.0f %s\n";
394 char *fm2_rx = "%-15s %3d:%-3s %'-11.0f\n";
398 /* Last RXQ in map catch overflows */
399 if (rxq_ == nr_rxqs - 1)
402 rec = &stats_rec->rxq[rxq];
403 prev = &stats_prev->rxq[rxq];
404 t = calc_period(rec, prev);
405 for (i = 0; i < nr_cpus; i++) {
406 struct datarec *r = &rec->cpu[i];
407 struct datarec *p = &prev->cpu[i];
409 pps = calc_pps (r, p, t);
410 err = calc_errs_pps(r, p, t);
413 errstr = "map-overflow-RXQ";
418 printf(fmt_rx, "rx_queue_index",
419 rxq_, i, pps, err, errstr);
421 pps = calc_pps (&rec->total, &prev->total, t);
422 err = calc_errs_pps(&rec->total, &prev->total, t);
424 printf(fm2_rx, "rx_queue_index", rxq_, "sum", pps, err);
429 /* Pointer swap trick */
430 static inline void swap(struct stats_record **a, struct stats_record **b)
432 struct stats_record *tmp;
439 static void stats_poll(int interval, int action, __u32 cfg_opt)
441 struct stats_record *record, *prev;
443 record = alloc_stats_record();
444 prev = alloc_stats_record();
445 stats_collect(record);
448 swap(&prev, &record);
449 stats_collect(record);
450 stats_print(record, prev, action, cfg_opt);
454 free_stats_record(record);
455 free_stats_record(prev);
459 int main(int argc, char **argv)
461 __u32 cfg_options= NO_TOUCH ; /* Default: Don't touch packet memory */
462 struct bpf_prog_info info = {};
463 __u32 info_len = sizeof(info);
464 int prog_fd, map_fd, opt, err;
465 bool use_separators = true;
466 struct config cfg = { 0 };
467 struct bpf_program *prog;
468 struct bpf_object *obj;
476 char action_str_buf[XDP_ACTION_MAX_STRLEN + 1 /* for \0 */] = { 0 };
477 int action = XDP_PASS; /* Default action */
478 char *action_str = NULL;
480 snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]);
482 obj = bpf_object__open_file(filename, NULL);
483 if (libbpf_get_error(obj))
486 prog = bpf_object__next_program(obj, NULL);
487 bpf_program__set_type(prog, BPF_PROG_TYPE_XDP);
489 err = bpf_object__load(obj);
492 prog_fd = bpf_program__fd(prog);
494 map = bpf_object__find_map_by_name(obj, "config_map");
495 stats_global_map = bpf_object__find_map_by_name(obj, "stats_global_map");
496 rx_queue_index_map = bpf_object__find_map_by_name(obj, "rx_queue_index_map");
497 if (!map || !stats_global_map || !rx_queue_index_map) {
498 printf("finding a map in obj file failed\n");
501 map_fd = bpf_map__fd(map);
504 fprintf(stderr, "ERR: bpf_prog_load_xattr: %s\n", strerror(errno));
508 /* Parse commands line args */
509 while ((opt = getopt_long(argc, argv, "FhSrmzd:s:a:",
510 long_options, &longindex)) != -1) {
513 if (strlen(optarg) >= IF_NAMESIZE) {
514 fprintf(stderr, "ERR: --dev name too long\n");
517 ifname = (char *)&ifname_buf;
518 strncpy(ifname, optarg, IF_NAMESIZE);
519 ifindex = if_nametoindex(ifname);
522 "ERR: --dev name unknown err(%d):%s\n",
523 errno, strerror(errno));
528 interval = atoi(optarg);
531 xdp_flags |= XDP_FLAGS_SKB_MODE;
534 use_separators = false;
537 action_str = (char *)&action_str_buf;
538 strncpy(action_str, optarg, XDP_ACTION_MAX_STRLEN);
541 cfg_options |= READ_MEM;
544 cfg_options |= SWAP_MAC;
547 xdp_flags &= ~XDP_FLAGS_UPDATE_IF_NOEXIST;
553 return EXIT_FAIL_OPTION;
557 if (!(xdp_flags & XDP_FLAGS_SKB_MODE))
558 xdp_flags |= XDP_FLAGS_DRV_MODE;
560 /* Required option */
562 fprintf(stderr, "ERR: required option --dev missing\n");
564 return EXIT_FAIL_OPTION;
566 cfg.ifindex = ifindex;
568 /* Parse action string */
570 action = parse_xdp_action(action_str);
572 fprintf(stderr, "ERR: Invalid XDP --action: %s\n",
575 return EXIT_FAIL_OPTION;
580 /* XDP_TX requires changing MAC-addrs, else HW may drop */
581 if (action == XDP_TX)
582 cfg_options |= SWAP_MAC;
583 cfg.options = cfg_options;
585 /* Trick to pretty printf with thousands separators use %' */
587 setlocale(LC_NUMERIC, "en_US");
589 /* User-side setup ifindex in config_map */
590 err = bpf_map_update_elem(map_fd, &key, &cfg, 0);
592 fprintf(stderr, "Store config failed (err:%d)\n", err);
596 /* Remove XDP program when program is interrupted or killed */
597 signal(SIGINT, int_exit);
598 signal(SIGTERM, int_exit);
600 if (bpf_xdp_attach(ifindex, prog_fd, xdp_flags, NULL) < 0) {
601 fprintf(stderr, "link set xdp fd failed\n");
602 return EXIT_FAIL_XDP;
605 err = bpf_obj_get_info_by_fd(prog_fd, &info, &info_len);
607 printf("can't get prog info - %s\n", strerror(errno));
612 stats_poll(interval, action, cfg_options);