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 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' },
53 {"readmem", no_argument, NULL, 'r' },
54 {"swapmac", no_argument, NULL, 'm' },
55 {"force", no_argument, NULL, 'F' },
59 static void int_exit(int sig)
61 __u32 curr_prog_id = 0;
64 if (bpf_xdp_query_id(ifindex, xdp_flags, &curr_prog_id)) {
65 printf("bpf_xdp_query_id failed\n");
68 if (prog_id == curr_prog_id) {
70 "Interrupted: Removing XDP program on ifindex:%d device:%s\n",
72 bpf_xdp_detach(ifindex, xdp_flags, NULL);
73 } else if (!curr_prog_id) {
74 printf("couldn't find a prog id on a given iface\n");
76 printf("program on interface changed, not removing\n");
87 enum cfg_options_flags {
92 #define XDP_ACTION_MAX (XDP_TX + 1)
93 #define XDP_ACTION_MAX_STRLEN 11
94 static const char *xdp_action_names[XDP_ACTION_MAX] = {
95 [XDP_ABORTED] = "XDP_ABORTED",
96 [XDP_DROP] = "XDP_DROP",
97 [XDP_PASS] = "XDP_PASS",
101 static const char *action2str(int action)
103 if (action < XDP_ACTION_MAX)
104 return xdp_action_names[action];
108 static int parse_xdp_action(char *action_str)
114 for (i = 0; i < XDP_ACTION_MAX; i++) {
115 maxlen = XDP_ACTION_MAX_STRLEN;
116 if (strncmp(xdp_action_names[i], action_str, maxlen) == 0) {
124 static void list_xdp_actions(void)
128 printf("Available XDP --action <options>\n");
129 for (i = 0; i < XDP_ACTION_MAX; i++)
130 printf("\t%s\n", xdp_action_names[i]);
134 static char* options2str(enum cfg_options_flags flag)
136 if (flag == NO_TOUCH)
142 fprintf(stderr, "ERR: Unknown config option flags");
146 static void usage(char *argv[])
150 printf("\nDOCUMENTATION:\n%s\n", __doc__);
151 printf(" Usage: %s (options-see-below)\n", argv[0]);
152 printf(" Listing options:\n");
153 for (i = 0; long_options[i].name != 0; i++) {
154 printf(" --%-12s", long_options[i].name);
155 if (long_options[i].flag != NULL)
156 printf(" flag (internal value:%d)",
157 *long_options[i].flag);
159 printf(" short-option: -%c",
160 long_options[i].val);
167 #define NANOSEC_PER_SEC 1000000000 /* 10^9 */
168 static __u64 gettime(void)
173 res = clock_gettime(CLOCK_MONOTONIC, &t);
175 fprintf(stderr, "Error with gettimeofday! (%i)\n", res);
178 return (__u64) t.tv_sec * NANOSEC_PER_SEC + t.tv_nsec;
181 /* Common stats data record shared with _kern.c */
188 struct datarec total;
191 struct stats_record {
196 static struct datarec *alloc_record_per_cpu(void)
198 unsigned int nr_cpus = bpf_num_possible_cpus();
199 struct datarec *array;
201 array = calloc(nr_cpus, sizeof(struct datarec));
203 fprintf(stderr, "Mem alloc error (nr_cpus:%u)\n", nr_cpus);
209 static struct record *alloc_record_per_rxq(void)
211 unsigned int nr_rxqs = bpf_map__max_entries(rx_queue_index_map);
212 struct record *array;
214 array = calloc(nr_rxqs, sizeof(struct record));
216 fprintf(stderr, "Mem alloc error (nr_rxqs:%u)\n", nr_rxqs);
222 static struct stats_record *alloc_stats_record(void)
224 unsigned int nr_rxqs = bpf_map__max_entries(rx_queue_index_map);
225 struct stats_record *rec;
228 rec = calloc(1, sizeof(struct stats_record));
230 fprintf(stderr, "Mem alloc error\n");
233 rec->rxq = alloc_record_per_rxq();
234 for (i = 0; i < nr_rxqs; i++)
235 rec->rxq[i].cpu = alloc_record_per_cpu();
237 rec->stats.cpu = alloc_record_per_cpu();
241 static void free_stats_record(struct stats_record *r)
243 unsigned int nr_rxqs = bpf_map__max_entries(rx_queue_index_map);
246 for (i = 0; i < nr_rxqs; i++)
254 static bool map_collect_percpu(int fd, __u32 key, struct record *rec)
256 /* For percpu maps, userspace gets a value per possible CPU */
257 unsigned int nr_cpus = bpf_num_possible_cpus();
258 struct datarec values[nr_cpus];
259 __u64 sum_processed = 0;
263 if ((bpf_map_lookup_elem(fd, &key, values)) != 0) {
265 "ERR: bpf_map_lookup_elem failed key:0x%X\n", key);
268 /* Get time as close as possible to reading map contents */
269 rec->timestamp = gettime();
271 /* Record and sum values from each CPU */
272 for (i = 0; i < nr_cpus; i++) {
273 rec->cpu[i].processed = values[i].processed;
274 sum_processed += values[i].processed;
275 rec->cpu[i].issue = values[i].issue;
276 sum_issue += values[i].issue;
278 rec->total.processed = sum_processed;
279 rec->total.issue = sum_issue;
283 static void stats_collect(struct stats_record *rec)
287 fd = bpf_map__fd(stats_global_map);
288 map_collect_percpu(fd, 0, &rec->stats);
290 fd = bpf_map__fd(rx_queue_index_map);
291 max_rxqs = bpf_map__max_entries(rx_queue_index_map);
292 for (i = 0; i < max_rxqs; i++)
293 map_collect_percpu(fd, i, &rec->rxq[i]);
296 static double calc_period(struct record *r, struct record *p)
301 period = r->timestamp - p->timestamp;
303 period_ = ((double) period / NANOSEC_PER_SEC);
308 static __u64 calc_pps(struct datarec *r, struct datarec *p, double period_)
314 packets = r->processed - p->processed;
315 pps = packets / period_;
320 static __u64 calc_errs_pps(struct datarec *r,
321 struct datarec *p, double period_)
327 packets = r->issue - p->issue;
328 pps = packets / period_;
333 static void stats_print(struct stats_record *stats_rec,
334 struct stats_record *stats_prev,
335 int action, __u32 cfg_opt)
337 unsigned int nr_rxqs = bpf_map__max_entries(rx_queue_index_map);
338 unsigned int nr_cpus = bpf_num_possible_cpus();
339 double pps = 0, err = 0;
340 struct record *rec, *prev;
346 printf("\nRunning XDP on dev:%s (ifindex:%d) action:%s options:%s\n",
347 ifname, ifindex, action2str(action), options2str(cfg_opt));
349 /* stats_global_map */
351 char *fmt_rx = "%-15s %-7d %'-11.0f %'-10.0f %s\n";
352 char *fm2_rx = "%-15s %-7s %'-11.0f\n";
355 printf("%-15s %-7s %-11s %-11s\n",
356 "XDP stats", "CPU", "pps", "issue-pps");
358 rec = &stats_rec->stats;
359 prev = &stats_prev->stats;
360 t = calc_period(rec, prev);
361 for (i = 0; i < nr_cpus; i++) {
362 struct datarec *r = &rec->cpu[i];
363 struct datarec *p = &prev->cpu[i];
365 pps = calc_pps (r, p, t);
366 err = calc_errs_pps(r, p, t);
368 errstr = "invalid-ifindex";
370 printf(fmt_rx, "XDP-RX CPU",
371 i, pps, err, errstr);
373 pps = calc_pps (&rec->total, &prev->total, t);
374 err = calc_errs_pps(&rec->total, &prev->total, t);
375 printf(fm2_rx, "XDP-RX CPU", "total", pps, err);
378 /* rx_queue_index_map */
379 printf("\n%-15s %-7s %-11s %-11s\n",
380 "RXQ stats", "RXQ:CPU", "pps", "issue-pps");
382 for (rxq = 0; rxq < nr_rxqs; rxq++) {
383 char *fmt_rx = "%-15s %3d:%-3d %'-11.0f %'-10.0f %s\n";
384 char *fm2_rx = "%-15s %3d:%-3s %'-11.0f\n";
388 /* Last RXQ in map catch overflows */
389 if (rxq_ == nr_rxqs - 1)
392 rec = &stats_rec->rxq[rxq];
393 prev = &stats_prev->rxq[rxq];
394 t = calc_period(rec, prev);
395 for (i = 0; i < nr_cpus; i++) {
396 struct datarec *r = &rec->cpu[i];
397 struct datarec *p = &prev->cpu[i];
399 pps = calc_pps (r, p, t);
400 err = calc_errs_pps(r, p, t);
403 errstr = "map-overflow-RXQ";
408 printf(fmt_rx, "rx_queue_index",
409 rxq_, i, pps, err, errstr);
411 pps = calc_pps (&rec->total, &prev->total, t);
412 err = calc_errs_pps(&rec->total, &prev->total, t);
414 printf(fm2_rx, "rx_queue_index", rxq_, "sum", pps, err);
419 /* Pointer swap trick */
420 static inline void swap(struct stats_record **a, struct stats_record **b)
422 struct stats_record *tmp;
429 static void stats_poll(int interval, int action, __u32 cfg_opt)
431 struct stats_record *record, *prev;
433 record = alloc_stats_record();
434 prev = alloc_stats_record();
435 stats_collect(record);
438 swap(&prev, &record);
439 stats_collect(record);
440 stats_print(record, prev, action, cfg_opt);
444 free_stats_record(record);
445 free_stats_record(prev);
449 int main(int argc, char **argv)
451 __u32 cfg_options= NO_TOUCH ; /* Default: Don't touch packet memory */
452 struct bpf_prog_info info = {};
453 __u32 info_len = sizeof(info);
454 int prog_fd, map_fd, opt, err;
455 bool use_separators = true;
456 struct config cfg = { 0 };
457 struct bpf_program *prog;
458 struct bpf_object *obj;
466 char action_str_buf[XDP_ACTION_MAX_STRLEN + 1 /* for \0 */] = { 0 };
467 int action = XDP_PASS; /* Default action */
468 char *action_str = NULL;
470 snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]);
472 obj = bpf_object__open_file(filename, NULL);
473 if (libbpf_get_error(obj))
476 prog = bpf_object__next_program(obj, NULL);
477 bpf_program__set_type(prog, BPF_PROG_TYPE_XDP);
479 err = bpf_object__load(obj);
482 prog_fd = bpf_program__fd(prog);
484 map = bpf_object__find_map_by_name(obj, "config_map");
485 stats_global_map = bpf_object__find_map_by_name(obj, "stats_global_map");
486 rx_queue_index_map = bpf_object__find_map_by_name(obj, "rx_queue_index_map");
487 if (!map || !stats_global_map || !rx_queue_index_map) {
488 printf("finding a map in obj file failed\n");
491 map_fd = bpf_map__fd(map);
494 fprintf(stderr, "ERR: bpf_prog_load_xattr: %s\n", strerror(errno));
498 /* Parse commands line args */
499 while ((opt = getopt_long(argc, argv, "FhSrmzd:s:a:",
500 long_options, &longindex)) != -1) {
503 if (strlen(optarg) >= IF_NAMESIZE) {
504 fprintf(stderr, "ERR: --dev name too long\n");
507 ifname = (char *)&ifname_buf;
508 strncpy(ifname, optarg, IF_NAMESIZE);
509 ifindex = if_nametoindex(ifname);
512 "ERR: --dev name unknown err(%d):%s\n",
513 errno, strerror(errno));
518 interval = atoi(optarg);
521 xdp_flags |= XDP_FLAGS_SKB_MODE;
524 use_separators = false;
527 action_str = (char *)&action_str_buf;
528 strncpy(action_str, optarg, XDP_ACTION_MAX_STRLEN);
531 cfg_options |= READ_MEM;
534 cfg_options |= SWAP_MAC;
537 xdp_flags &= ~XDP_FLAGS_UPDATE_IF_NOEXIST;
543 return EXIT_FAIL_OPTION;
547 if (!(xdp_flags & XDP_FLAGS_SKB_MODE))
548 xdp_flags |= XDP_FLAGS_DRV_MODE;
550 /* Required option */
552 fprintf(stderr, "ERR: required option --dev missing\n");
554 return EXIT_FAIL_OPTION;
556 cfg.ifindex = ifindex;
558 /* Parse action string */
560 action = parse_xdp_action(action_str);
562 fprintf(stderr, "ERR: Invalid XDP --action: %s\n",
565 return EXIT_FAIL_OPTION;
570 /* XDP_TX requires changing MAC-addrs, else HW may drop */
571 if (action == XDP_TX)
572 cfg_options |= SWAP_MAC;
573 cfg.options = cfg_options;
575 /* Trick to pretty printf with thousands separators use %' */
577 setlocale(LC_NUMERIC, "en_US");
579 /* User-side setup ifindex in config_map */
580 err = bpf_map_update_elem(map_fd, &key, &cfg, 0);
582 fprintf(stderr, "Store config failed (err:%d)\n", err);
586 /* Remove XDP program when program is interrupted or killed */
587 signal(SIGINT, int_exit);
588 signal(SIGTERM, int_exit);
590 if (bpf_xdp_attach(ifindex, prog_fd, xdp_flags, NULL) < 0) {
591 fprintf(stderr, "link set xdp fd failed\n");
592 return EXIT_FAIL_XDP;
595 err = bpf_obj_get_info_by_fd(prog_fd, &info, &info_len);
597 printf("can't get prog info - %s\n", strerror(errno));
602 stats_poll(interval, action, cfg_options);