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
];
34 static __u32 xdp_flags
= XDP_FLAGS_UPDATE_IF_NOEXIST
;
36 static struct bpf_map
*stats_global_map
;
37 static struct bpf_map
*rx_queue_index_map
;
39 /* Exit return codes */
42 #define EXIT_FAIL_OPTION 2
43 #define EXIT_FAIL_XDP 3
44 #define EXIT_FAIL_BPF 4
45 #define EXIT_FAIL_MEM 5
47 static const struct option long_options
[] = {
48 {"help", no_argument
, NULL
, 'h' },
49 {"dev", required_argument
, NULL
, 'd' },
50 {"skb-mode", no_argument
, NULL
, 'S' },
51 {"sec", required_argument
, NULL
, 's' },
52 {"no-separators", no_argument
, NULL
, 'z' },
53 {"action", required_argument
, NULL
, 'a' },
54 {"readmem", no_argument
, NULL
, 'r' },
55 {"swapmac", no_argument
, NULL
, 'm' },
56 {"force", no_argument
, NULL
, 'F' },
60 static void int_exit(int sig
)
62 __u32 curr_prog_id
= 0;
65 if (bpf_get_link_xdp_id(ifindex
, &curr_prog_id
, xdp_flags
)) {
66 printf("bpf_get_link_xdp_id failed\n");
69 if (prog_id
== curr_prog_id
) {
71 "Interrupted: Removing XDP program on ifindex:%d device:%s\n",
73 bpf_set_link_xdp_fd(ifindex
, -1, xdp_flags
);
74 } else if (!curr_prog_id
) {
75 printf("couldn't find a prog id on a given iface\n");
77 printf("program on interface changed, not removing\n");
88 enum cfg_options_flags
{
93 #define XDP_ACTION_MAX (XDP_TX + 1)
94 #define XDP_ACTION_MAX_STRLEN 11
95 static const char *xdp_action_names
[XDP_ACTION_MAX
] = {
96 [XDP_ABORTED
] = "XDP_ABORTED",
97 [XDP_DROP
] = "XDP_DROP",
98 [XDP_PASS
] = "XDP_PASS",
102 static const char *action2str(int action
)
104 if (action
< XDP_ACTION_MAX
)
105 return xdp_action_names
[action
];
109 static int parse_xdp_action(char *action_str
)
115 for (i
= 0; i
< XDP_ACTION_MAX
; i
++) {
116 maxlen
= XDP_ACTION_MAX_STRLEN
;
117 if (strncmp(xdp_action_names
[i
], action_str
, maxlen
) == 0) {
125 static void list_xdp_actions(void)
129 printf("Available XDP --action <options>\n");
130 for (i
= 0; i
< XDP_ACTION_MAX
; i
++)
131 printf("\t%s\n", xdp_action_names
[i
]);
135 static char* options2str(enum cfg_options_flags flag
)
137 if (flag
== NO_TOUCH
)
143 fprintf(stderr
, "ERR: Unknown config option flags");
147 static void usage(char *argv
[])
151 printf("\nDOCUMENTATION:\n%s\n", __doc__
);
152 printf(" Usage: %s (options-see-below)\n", argv
[0]);
153 printf(" Listing options:\n");
154 for (i
= 0; long_options
[i
].name
!= 0; i
++) {
155 printf(" --%-12s", long_options
[i
].name
);
156 if (long_options
[i
].flag
!= NULL
)
157 printf(" flag (internal value:%d)",
158 *long_options
[i
].flag
);
160 printf(" short-option: -%c",
161 long_options
[i
].val
);
168 #define NANOSEC_PER_SEC 1000000000 /* 10^9 */
169 static __u64
gettime(void)
174 res
= clock_gettime(CLOCK_MONOTONIC
, &t
);
176 fprintf(stderr
, "Error with gettimeofday! (%i)\n", res
);
179 return (__u64
) t
.tv_sec
* NANOSEC_PER_SEC
+ t
.tv_nsec
;
182 /* Common stats data record shared with _kern.c */
189 struct datarec total
;
192 struct stats_record
{
197 static struct datarec
*alloc_record_per_cpu(void)
199 unsigned int nr_cpus
= bpf_num_possible_cpus();
200 struct datarec
*array
;
202 array
= calloc(nr_cpus
, sizeof(struct datarec
));
204 fprintf(stderr
, "Mem alloc error (nr_cpus:%u)\n", nr_cpus
);
210 static struct record
*alloc_record_per_rxq(void)
212 unsigned int nr_rxqs
= bpf_map__def(rx_queue_index_map
)->max_entries
;
213 struct record
*array
;
215 array
= calloc(nr_rxqs
, sizeof(struct record
));
217 fprintf(stderr
, "Mem alloc error (nr_rxqs:%u)\n", nr_rxqs
);
223 static struct stats_record
*alloc_stats_record(void)
225 unsigned int nr_rxqs
= bpf_map__def(rx_queue_index_map
)->max_entries
;
226 struct stats_record
*rec
;
229 rec
= calloc(1, sizeof(struct stats_record
));
231 fprintf(stderr
, "Mem alloc error\n");
234 rec
->rxq
= alloc_record_per_rxq();
235 for (i
= 0; i
< nr_rxqs
; i
++)
236 rec
->rxq
[i
].cpu
= alloc_record_per_cpu();
238 rec
->stats
.cpu
= alloc_record_per_cpu();
242 static void free_stats_record(struct stats_record
*r
)
244 unsigned int nr_rxqs
= bpf_map__def(rx_queue_index_map
)->max_entries
;
247 for (i
= 0; i
< nr_rxqs
; i
++)
255 static bool map_collect_percpu(int fd
, __u32 key
, struct record
*rec
)
257 /* For percpu maps, userspace gets a value per possible CPU */
258 unsigned int nr_cpus
= bpf_num_possible_cpus();
259 struct datarec values
[nr_cpus
];
260 __u64 sum_processed
= 0;
264 if ((bpf_map_lookup_elem(fd
, &key
, values
)) != 0) {
266 "ERR: bpf_map_lookup_elem failed key:0x%X\n", key
);
269 /* Get time as close as possible to reading map contents */
270 rec
->timestamp
= gettime();
272 /* Record and sum values from each CPU */
273 for (i
= 0; i
< nr_cpus
; i
++) {
274 rec
->cpu
[i
].processed
= values
[i
].processed
;
275 sum_processed
+= values
[i
].processed
;
276 rec
->cpu
[i
].issue
= values
[i
].issue
;
277 sum_issue
+= values
[i
].issue
;
279 rec
->total
.processed
= sum_processed
;
280 rec
->total
.issue
= sum_issue
;
284 static void stats_collect(struct stats_record
*rec
)
288 fd
= bpf_map__fd(stats_global_map
);
289 map_collect_percpu(fd
, 0, &rec
->stats
);
291 fd
= bpf_map__fd(rx_queue_index_map
);
292 max_rxqs
= bpf_map__def(rx_queue_index_map
)->max_entries
;
293 for (i
= 0; i
< max_rxqs
; i
++)
294 map_collect_percpu(fd
, i
, &rec
->rxq
[i
]);
297 static double calc_period(struct record
*r
, struct record
*p
)
302 period
= r
->timestamp
- p
->timestamp
;
304 period_
= ((double) period
/ NANOSEC_PER_SEC
);
309 static __u64
calc_pps(struct datarec
*r
, struct datarec
*p
, double period_
)
315 packets
= r
->processed
- p
->processed
;
316 pps
= packets
/ period_
;
321 static __u64
calc_errs_pps(struct datarec
*r
,
322 struct datarec
*p
, double period_
)
328 packets
= r
->issue
- p
->issue
;
329 pps
= packets
/ period_
;
334 static void stats_print(struct stats_record
*stats_rec
,
335 struct stats_record
*stats_prev
,
336 int action
, __u32 cfg_opt
)
338 unsigned int nr_rxqs
= bpf_map__def(rx_queue_index_map
)->max_entries
;
339 unsigned int nr_cpus
= bpf_num_possible_cpus();
340 double pps
= 0, err
= 0;
341 struct record
*rec
, *prev
;
347 printf("\nRunning XDP on dev:%s (ifindex:%d) action:%s options:%s\n",
348 ifname
, ifindex
, action2str(action
), options2str(cfg_opt
));
350 /* stats_global_map */
352 char *fmt_rx
= "%-15s %-7d %'-11.0f %'-10.0f %s\n";
353 char *fm2_rx
= "%-15s %-7s %'-11.0f\n";
356 printf("%-15s %-7s %-11s %-11s\n",
357 "XDP stats", "CPU", "pps", "issue-pps");
359 rec
= &stats_rec
->stats
;
360 prev
= &stats_prev
->stats
;
361 t
= calc_period(rec
, prev
);
362 for (i
= 0; i
< nr_cpus
; i
++) {
363 struct datarec
*r
= &rec
->cpu
[i
];
364 struct datarec
*p
= &prev
->cpu
[i
];
366 pps
= calc_pps (r
, p
, t
);
367 err
= calc_errs_pps(r
, p
, t
);
369 errstr
= "invalid-ifindex";
371 printf(fmt_rx
, "XDP-RX CPU",
372 i
, pps
, err
, errstr
);
374 pps
= calc_pps (&rec
->total
, &prev
->total
, t
);
375 err
= calc_errs_pps(&rec
->total
, &prev
->total
, t
);
376 printf(fm2_rx
, "XDP-RX CPU", "total", pps
, err
);
379 /* rx_queue_index_map */
380 printf("\n%-15s %-7s %-11s %-11s\n",
381 "RXQ stats", "RXQ:CPU", "pps", "issue-pps");
383 for (rxq
= 0; rxq
< nr_rxqs
; rxq
++) {
384 char *fmt_rx
= "%-15s %3d:%-3d %'-11.0f %'-10.0f %s\n";
385 char *fm2_rx
= "%-15s %3d:%-3s %'-11.0f\n";
389 /* Last RXQ in map catch overflows */
390 if (rxq_
== nr_rxqs
- 1)
393 rec
= &stats_rec
->rxq
[rxq
];
394 prev
= &stats_prev
->rxq
[rxq
];
395 t
= calc_period(rec
, prev
);
396 for (i
= 0; i
< nr_cpus
; i
++) {
397 struct datarec
*r
= &rec
->cpu
[i
];
398 struct datarec
*p
= &prev
->cpu
[i
];
400 pps
= calc_pps (r
, p
, t
);
401 err
= calc_errs_pps(r
, p
, t
);
404 errstr
= "map-overflow-RXQ";
409 printf(fmt_rx
, "rx_queue_index",
410 rxq_
, i
, pps
, err
, errstr
);
412 pps
= calc_pps (&rec
->total
, &prev
->total
, t
);
413 err
= calc_errs_pps(&rec
->total
, &prev
->total
, t
);
415 printf(fm2_rx
, "rx_queue_index", rxq_
, "sum", pps
, err
);
420 /* Pointer swap trick */
421 static inline void swap(struct stats_record
**a
, struct stats_record
**b
)
423 struct stats_record
*tmp
;
430 static void stats_poll(int interval
, int action
, __u32 cfg_opt
)
432 struct stats_record
*record
, *prev
;
434 record
= alloc_stats_record();
435 prev
= alloc_stats_record();
436 stats_collect(record
);
439 swap(&prev
, &record
);
440 stats_collect(record
);
441 stats_print(record
, prev
, action
, cfg_opt
);
445 free_stats_record(record
);
446 free_stats_record(prev
);
450 int main(int argc
, char **argv
)
452 __u32 cfg_options
= NO_TOUCH
; /* Default: Don't touch packet memory */
453 struct bpf_prog_load_attr prog_load_attr
= {
454 .prog_type
= BPF_PROG_TYPE_XDP
,
456 struct bpf_prog_info info
= {};
457 __u32 info_len
= sizeof(info
);
458 int prog_fd
, map_fd
, opt
, err
;
459 bool use_separators
= true;
460 struct config cfg
= { 0 };
461 struct bpf_object
*obj
;
469 char action_str_buf
[XDP_ACTION_MAX_STRLEN
+ 1 /* for \0 */] = { 0 };
470 int action
= XDP_PASS
; /* Default action */
471 char *action_str
= NULL
;
473 snprintf(filename
, sizeof(filename
), "%s_kern.o", argv
[0]);
474 prog_load_attr
.file
= filename
;
476 if (bpf_prog_load_xattr(&prog_load_attr
, &obj
, &prog_fd
))
479 map
= bpf_object__find_map_by_name(obj
, "config_map");
480 stats_global_map
= bpf_object__find_map_by_name(obj
, "stats_global_map");
481 rx_queue_index_map
= bpf_object__find_map_by_name(obj
, "rx_queue_index_map");
482 if (!map
|| !stats_global_map
|| !rx_queue_index_map
) {
483 printf("finding a map in obj file failed\n");
486 map_fd
= bpf_map__fd(map
);
489 fprintf(stderr
, "ERR: bpf_prog_load_xattr: %s\n", strerror(errno
));
493 /* Parse commands line args */
494 while ((opt
= getopt_long(argc
, argv
, "FhSrmzd:s:a:",
495 long_options
, &longindex
)) != -1) {
498 if (strlen(optarg
) >= IF_NAMESIZE
) {
499 fprintf(stderr
, "ERR: --dev name too long\n");
502 ifname
= (char *)&ifname_buf
;
503 strncpy(ifname
, optarg
, IF_NAMESIZE
);
504 ifindex
= if_nametoindex(ifname
);
507 "ERR: --dev name unknown err(%d):%s\n",
508 errno
, strerror(errno
));
513 interval
= atoi(optarg
);
516 xdp_flags
|= XDP_FLAGS_SKB_MODE
;
519 use_separators
= false;
522 action_str
= (char *)&action_str_buf
;
523 strncpy(action_str
, optarg
, XDP_ACTION_MAX_STRLEN
);
526 cfg_options
|= READ_MEM
;
529 cfg_options
|= SWAP_MAC
;
532 xdp_flags
&= ~XDP_FLAGS_UPDATE_IF_NOEXIST
;
538 return EXIT_FAIL_OPTION
;
542 if (!(xdp_flags
& XDP_FLAGS_SKB_MODE
))
543 xdp_flags
|= XDP_FLAGS_DRV_MODE
;
545 /* Required option */
547 fprintf(stderr
, "ERR: required option --dev missing\n");
549 return EXIT_FAIL_OPTION
;
551 cfg
.ifindex
= ifindex
;
553 /* Parse action string */
555 action
= parse_xdp_action(action_str
);
557 fprintf(stderr
, "ERR: Invalid XDP --action: %s\n",
560 return EXIT_FAIL_OPTION
;
565 /* XDP_TX requires changing MAC-addrs, else HW may drop */
566 if (action
== XDP_TX
)
567 cfg_options
|= SWAP_MAC
;
568 cfg
.options
= cfg_options
;
570 /* Trick to pretty printf with thousands separators use %' */
572 setlocale(LC_NUMERIC
, "en_US");
574 /* User-side setup ifindex in config_map */
575 err
= bpf_map_update_elem(map_fd
, &key
, &cfg
, 0);
577 fprintf(stderr
, "Store config failed (err:%d)\n", err
);
581 /* Remove XDP program when program is interrupted or killed */
582 signal(SIGINT
, int_exit
);
583 signal(SIGTERM
, int_exit
);
585 if (bpf_set_link_xdp_fd(ifindex
, prog_fd
, xdp_flags
) < 0) {
586 fprintf(stderr
, "link set xdp fd failed\n");
587 return EXIT_FAIL_XDP
;
590 err
= bpf_obj_get_info_by_fd(prog_fd
, &info
, &info_len
);
592 printf("can't get prog info - %s\n", strerror(errno
));
597 stats_poll(interval
, action
, cfg_options
);