1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright(c) 2017 Jesper Dangaard Brouer, Red Hat, Inc.
4 static const char *__doc__ =
5 " XDP redirect with a CPU-map type \"BPF_MAP_TYPE_CPUMAP\"";
15 #include <sys/resource.h>
20 #include <arpa/inet.h>
21 #include <linux/if_link.h>
23 #define MAX_CPUS 64 /* WARNING - sync with _kern.c */
25 /* How many xdp_progs are defined in _kern.c */
33 static int ifindex = -1;
34 static char ifname_buf[IF_NAMESIZE];
38 static __u32 xdp_flags = XDP_FLAGS_UPDATE_IF_NOEXIST;
39 static int cpu_map_fd;
40 static int rx_cnt_map_fd;
41 static int redirect_err_cnt_map_fd;
42 static int cpumap_enqueue_cnt_map_fd;
43 static int cpumap_kthread_cnt_map_fd;
44 static int cpus_available_map_fd;
45 static int cpus_count_map_fd;
46 static int cpus_iterator_map_fd;
47 static int exception_cnt_map_fd;
49 /* Exit return codes */
52 #define EXIT_FAIL_OPTION 2
53 #define EXIT_FAIL_XDP 3
54 #define EXIT_FAIL_BPF 4
55 #define EXIT_FAIL_MEM 5
57 static const struct option long_options[] = {
58 {"help", no_argument, NULL, 'h' },
59 {"dev", required_argument, NULL, 'd' },
60 {"skb-mode", no_argument, NULL, 'S' },
61 {"sec", required_argument, NULL, 's' },
62 {"progname", required_argument, NULL, 'p' },
63 {"qsize", required_argument, NULL, 'q' },
64 {"cpu", required_argument, NULL, 'c' },
65 {"stress-mode", no_argument, NULL, 'x' },
66 {"no-separators", no_argument, NULL, 'z' },
67 {"force", no_argument, NULL, 'F' },
71 static void int_exit(int sig)
73 __u32 curr_prog_id = 0;
76 if (bpf_get_link_xdp_id(ifindex, &curr_prog_id, xdp_flags)) {
77 printf("bpf_get_link_xdp_id failed\n");
80 if (prog_id == curr_prog_id) {
82 "Interrupted: Removing XDP program on ifindex:%d device:%s\n",
84 bpf_set_link_xdp_fd(ifindex, -1, xdp_flags);
85 } else if (!curr_prog_id) {
86 printf("couldn't find a prog id on a given iface\n");
88 printf("program on interface changed, not removing\n");
94 static void print_avail_progs(struct bpf_object *obj)
96 struct bpf_program *pos;
98 bpf_object__for_each_program(pos, obj) {
99 if (bpf_program__is_xdp(pos))
100 printf(" %s\n", bpf_program__title(pos, false));
104 static void usage(char *argv[], struct bpf_object *obj)
108 printf("\nDOCUMENTATION:\n%s\n", __doc__);
110 printf(" Usage: %s (options-see-below)\n", argv[0]);
111 printf(" Listing options:\n");
112 for (i = 0; long_options[i].name != 0; i++) {
113 printf(" --%-12s", long_options[i].name);
114 if (long_options[i].flag != NULL)
115 printf(" flag (internal value:%d)",
116 *long_options[i].flag);
118 printf(" short-option: -%c",
119 long_options[i].val);
122 printf("\n Programs to be used for --progname:\n");
123 print_avail_progs(obj);
127 /* gettime returns the current time of day in nanoseconds.
128 * Cost: clock_gettime (ns) => 26ns (CLOCK_MONOTONIC)
129 * clock_gettime (ns) => 9ns (CLOCK_MONOTONIC_COARSE)
131 #define NANOSEC_PER_SEC 1000000000 /* 10^9 */
132 static __u64 gettime(void)
137 res = clock_gettime(CLOCK_MONOTONIC, &t);
139 fprintf(stderr, "Error with gettimeofday! (%i)\n", res);
142 return (__u64) t.tv_sec * NANOSEC_PER_SEC + t.tv_nsec;
145 /* Common stats data record shared with _kern.c */
153 struct datarec total;
156 struct stats_record {
157 struct record rx_cnt;
158 struct record redir_err;
159 struct record kthread;
160 struct record exception;
161 struct record enq[MAX_CPUS];
164 static bool map_collect_percpu(int fd, __u32 key, struct record *rec)
166 /* For percpu maps, userspace gets a value per possible CPU */
167 unsigned int nr_cpus = bpf_num_possible_cpus();
168 struct datarec values[nr_cpus];
169 __u64 sum_processed = 0;
170 __u64 sum_dropped = 0;
174 if ((bpf_map_lookup_elem(fd, &key, values)) != 0) {
176 "ERR: bpf_map_lookup_elem failed key:0x%X\n", key);
179 /* Get time as close as possible to reading map contents */
180 rec->timestamp = gettime();
182 /* Record and sum values from each CPU */
183 for (i = 0; i < nr_cpus; i++) {
184 rec->cpu[i].processed = values[i].processed;
185 sum_processed += values[i].processed;
186 rec->cpu[i].dropped = values[i].dropped;
187 sum_dropped += values[i].dropped;
188 rec->cpu[i].issue = values[i].issue;
189 sum_issue += values[i].issue;
191 rec->total.processed = sum_processed;
192 rec->total.dropped = sum_dropped;
193 rec->total.issue = sum_issue;
197 static struct datarec *alloc_record_per_cpu(void)
199 unsigned int nr_cpus = bpf_num_possible_cpus();
200 struct datarec *array;
203 size = sizeof(struct datarec) * nr_cpus;
204 array = malloc(size);
205 memset(array, 0, size);
207 fprintf(stderr, "Mem alloc error (nr_cpus:%u)\n", nr_cpus);
213 static struct stats_record *alloc_stats_record(void)
215 struct stats_record *rec;
218 rec = malloc(sizeof(*rec));
219 memset(rec, 0, sizeof(*rec));
221 fprintf(stderr, "Mem alloc error\n");
224 rec->rx_cnt.cpu = alloc_record_per_cpu();
225 rec->redir_err.cpu = alloc_record_per_cpu();
226 rec->kthread.cpu = alloc_record_per_cpu();
227 rec->exception.cpu = alloc_record_per_cpu();
228 for (i = 0; i < MAX_CPUS; i++)
229 rec->enq[i].cpu = alloc_record_per_cpu();
234 static void free_stats_record(struct stats_record *r)
238 for (i = 0; i < MAX_CPUS; i++)
240 free(r->exception.cpu);
241 free(r->kthread.cpu);
242 free(r->redir_err.cpu);
247 static double calc_period(struct record *r, struct record *p)
252 period = r->timestamp - p->timestamp;
254 period_ = ((double) period / NANOSEC_PER_SEC);
259 static __u64 calc_pps(struct datarec *r, struct datarec *p, double period_)
265 packets = r->processed - p->processed;
266 pps = packets / period_;
271 static __u64 calc_drop_pps(struct datarec *r, struct datarec *p, double period_)
277 packets = r->dropped - p->dropped;
278 pps = packets / period_;
283 static __u64 calc_errs_pps(struct datarec *r,
284 struct datarec *p, double period_)
290 packets = r->issue - p->issue;
291 pps = packets / period_;
296 static void stats_print(struct stats_record *stats_rec,
297 struct stats_record *stats_prev,
300 unsigned int nr_cpus = bpf_num_possible_cpus();
301 double pps = 0, drop = 0, err = 0;
302 struct record *rec, *prev;
308 printf("Running XDP/eBPF prog_name:%s\n", prog_name);
309 printf("%-15s %-7s %-14s %-11s %-9s\n",
310 "XDP-cpumap", "CPU:to", "pps", "drop-pps", "extra-info");
314 char *fmt_rx = "%-15s %-7d %'-14.0f %'-11.0f %'-10.0f %s\n";
315 char *fm2_rx = "%-15s %-7s %'-14.0f %'-11.0f\n";
318 rec = &stats_rec->rx_cnt;
319 prev = &stats_prev->rx_cnt;
320 t = calc_period(rec, prev);
321 for (i = 0; i < nr_cpus; i++) {
322 struct datarec *r = &rec->cpu[i];
323 struct datarec *p = &prev->cpu[i];
325 pps = calc_pps(r, p, t);
326 drop = calc_drop_pps(r, p, t);
327 err = calc_errs_pps(r, p, t);
329 errstr = "cpu-dest/err";
331 printf(fmt_rx, "XDP-RX",
332 i, pps, drop, err, errstr);
334 pps = calc_pps(&rec->total, &prev->total, t);
335 drop = calc_drop_pps(&rec->total, &prev->total, t);
336 err = calc_errs_pps(&rec->total, &prev->total, t);
337 printf(fm2_rx, "XDP-RX", "total", pps, drop);
340 /* cpumap enqueue stats */
341 for (to_cpu = 0; to_cpu < MAX_CPUS; to_cpu++) {
342 char *fmt = "%-15s %3d:%-3d %'-14.0f %'-11.0f %'-10.2f %s\n";
343 char *fm2 = "%-15s %3s:%-3d %'-14.0f %'-11.0f %'-10.2f %s\n";
346 rec = &stats_rec->enq[to_cpu];
347 prev = &stats_prev->enq[to_cpu];
348 t = calc_period(rec, prev);
349 for (i = 0; i < nr_cpus; i++) {
350 struct datarec *r = &rec->cpu[i];
351 struct datarec *p = &prev->cpu[i];
353 pps = calc_pps(r, p, t);
354 drop = calc_drop_pps(r, p, t);
355 err = calc_errs_pps(r, p, t);
357 errstr = "bulk-average";
358 err = pps / err; /* calc average bulk size */
361 printf(fmt, "cpumap-enqueue",
362 i, to_cpu, pps, drop, err, errstr);
364 pps = calc_pps(&rec->total, &prev->total, t);
366 drop = calc_drop_pps(&rec->total, &prev->total, t);
367 err = calc_errs_pps(&rec->total, &prev->total, t);
369 errstr = "bulk-average";
370 err = pps / err; /* calc average bulk size */
372 printf(fm2, "cpumap-enqueue",
373 "sum", to_cpu, pps, drop, err, errstr);
377 /* cpumap kthread stats */
379 char *fmt_k = "%-15s %-7d %'-14.0f %'-11.0f %'-10.0f %s\n";
380 char *fm2_k = "%-15s %-7s %'-14.0f %'-11.0f %'-10.0f %s\n";
383 rec = &stats_rec->kthread;
384 prev = &stats_prev->kthread;
385 t = calc_period(rec, prev);
386 for (i = 0; i < nr_cpus; i++) {
387 struct datarec *r = &rec->cpu[i];
388 struct datarec *p = &prev->cpu[i];
390 pps = calc_pps(r, p, t);
391 drop = calc_drop_pps(r, p, t);
392 err = calc_errs_pps(r, p, t);
396 printf(fmt_k, "cpumap_kthread",
397 i, pps, drop, err, e_str);
399 pps = calc_pps(&rec->total, &prev->total, t);
400 drop = calc_drop_pps(&rec->total, &prev->total, t);
401 err = calc_errs_pps(&rec->total, &prev->total, t);
404 printf(fm2_k, "cpumap_kthread", "total", pps, drop, err, e_str);
407 /* XDP redirect err tracepoints (very unlikely) */
409 char *fmt_err = "%-15s %-7d %'-14.0f %'-11.0f\n";
410 char *fm2_err = "%-15s %-7s %'-14.0f %'-11.0f\n";
412 rec = &stats_rec->redir_err;
413 prev = &stats_prev->redir_err;
414 t = calc_period(rec, prev);
415 for (i = 0; i < nr_cpus; i++) {
416 struct datarec *r = &rec->cpu[i];
417 struct datarec *p = &prev->cpu[i];
419 pps = calc_pps(r, p, t);
420 drop = calc_drop_pps(r, p, t);
422 printf(fmt_err, "redirect_err", i, pps, drop);
424 pps = calc_pps(&rec->total, &prev->total, t);
425 drop = calc_drop_pps(&rec->total, &prev->total, t);
426 printf(fm2_err, "redirect_err", "total", pps, drop);
429 /* XDP general exception tracepoints */
431 char *fmt_err = "%-15s %-7d %'-14.0f %'-11.0f\n";
432 char *fm2_err = "%-15s %-7s %'-14.0f %'-11.0f\n";
434 rec = &stats_rec->exception;
435 prev = &stats_prev->exception;
436 t = calc_period(rec, prev);
437 for (i = 0; i < nr_cpus; i++) {
438 struct datarec *r = &rec->cpu[i];
439 struct datarec *p = &prev->cpu[i];
441 pps = calc_pps(r, p, t);
442 drop = calc_drop_pps(r, p, t);
444 printf(fmt_err, "xdp_exception", i, pps, drop);
446 pps = calc_pps(&rec->total, &prev->total, t);
447 drop = calc_drop_pps(&rec->total, &prev->total, t);
448 printf(fm2_err, "xdp_exception", "total", pps, drop);
455 static void stats_collect(struct stats_record *rec)
460 map_collect_percpu(fd, 0, &rec->rx_cnt);
462 fd = redirect_err_cnt_map_fd;
463 map_collect_percpu(fd, 1, &rec->redir_err);
465 fd = cpumap_enqueue_cnt_map_fd;
466 for (i = 0; i < MAX_CPUS; i++)
467 map_collect_percpu(fd, i, &rec->enq[i]);
469 fd = cpumap_kthread_cnt_map_fd;
470 map_collect_percpu(fd, 0, &rec->kthread);
472 fd = exception_cnt_map_fd;
473 map_collect_percpu(fd, 0, &rec->exception);
477 /* Pointer swap trick */
478 static inline void swap(struct stats_record **a, struct stats_record **b)
480 struct stats_record *tmp;
487 static int create_cpu_entry(__u32 cpu, __u32 queue_size,
488 __u32 avail_idx, bool new)
490 __u32 curr_cpus_count = 0;
494 /* Add a CPU entry to cpumap, as this allocate a cpu entry in
495 * the kernel for the cpu.
497 ret = bpf_map_update_elem(cpu_map_fd, &cpu, &queue_size, 0);
499 fprintf(stderr, "Create CPU entry failed (err:%d)\n", ret);
503 /* Inform bpf_prog's that a new CPU is available to select
504 * from via some control maps.
506 ret = bpf_map_update_elem(cpus_available_map_fd, &avail_idx, &cpu, 0);
508 fprintf(stderr, "Add to avail CPUs failed\n");
512 /* When not replacing/updating existing entry, bump the count */
513 ret = bpf_map_lookup_elem(cpus_count_map_fd, &key, &curr_cpus_count);
515 fprintf(stderr, "Failed reading curr cpus_count\n");
520 ret = bpf_map_update_elem(cpus_count_map_fd, &key,
521 &curr_cpus_count, 0);
523 fprintf(stderr, "Failed write curr cpus_count\n");
527 /* map_fd[7] = cpus_iterator */
528 printf("%s CPU:%u as idx:%u queue_size:%d (total cpus_count:%u)\n",
529 new ? "Add-new":"Replace", cpu, avail_idx,
530 queue_size, curr_cpus_count);
535 /* CPUs are zero-indexed. Thus, add a special sentinel default value
536 * in map cpus_available to mark CPU index'es not configured
538 static void mark_cpus_unavailable(void)
540 __u32 invalid_cpu = MAX_CPUS;
543 for (i = 0; i < MAX_CPUS; i++) {
544 ret = bpf_map_update_elem(cpus_available_map_fd, &i,
547 fprintf(stderr, "Failed marking CPU unavailable\n");
553 /* Stress cpumap management code by concurrently changing underlying cpumap */
554 static void stress_cpumap(void)
556 /* Changing qsize will cause kernel to free and alloc a new
557 * bpf_cpu_map_entry, with an associated/complicated tear-down
560 create_cpu_entry(1, 1024, 0, false);
561 create_cpu_entry(1, 8, 0, false);
562 create_cpu_entry(1, 16000, 0, false);
565 static void stats_poll(int interval, bool use_separators, char *prog_name,
568 struct stats_record *record, *prev;
570 record = alloc_stats_record();
571 prev = alloc_stats_record();
572 stats_collect(record);
574 /* Trick to pretty printf with thousands separators use %' */
576 setlocale(LC_NUMERIC, "en_US");
579 swap(&prev, &record);
580 stats_collect(record);
581 stats_print(record, prev, prog_name);
587 free_stats_record(record);
588 free_stats_record(prev);
591 static int init_map_fds(struct bpf_object *obj)
593 cpu_map_fd = bpf_object__find_map_fd_by_name(obj, "cpu_map");
594 rx_cnt_map_fd = bpf_object__find_map_fd_by_name(obj, "rx_cnt");
595 redirect_err_cnt_map_fd =
596 bpf_object__find_map_fd_by_name(obj, "redirect_err_cnt");
597 cpumap_enqueue_cnt_map_fd =
598 bpf_object__find_map_fd_by_name(obj, "cpumap_enqueue_cnt");
599 cpumap_kthread_cnt_map_fd =
600 bpf_object__find_map_fd_by_name(obj, "cpumap_kthread_cnt");
601 cpus_available_map_fd =
602 bpf_object__find_map_fd_by_name(obj, "cpus_available");
603 cpus_count_map_fd = bpf_object__find_map_fd_by_name(obj, "cpus_count");
604 cpus_iterator_map_fd =
605 bpf_object__find_map_fd_by_name(obj, "cpus_iterator");
606 exception_cnt_map_fd =
607 bpf_object__find_map_fd_by_name(obj, "exception_cnt");
609 if (cpu_map_fd < 0 || rx_cnt_map_fd < 0 ||
610 redirect_err_cnt_map_fd < 0 || cpumap_enqueue_cnt_map_fd < 0 ||
611 cpumap_kthread_cnt_map_fd < 0 || cpus_available_map_fd < 0 ||
612 cpus_count_map_fd < 0 || cpus_iterator_map_fd < 0 ||
613 exception_cnt_map_fd < 0)
619 int main(int argc, char **argv)
621 struct rlimit r = {10 * 1024 * 1024, RLIM_INFINITY};
622 char *prog_name = "xdp_cpu_map5_lb_hash_ip_pairs";
623 struct bpf_prog_load_attr prog_load_attr = {
624 .prog_type = BPF_PROG_TYPE_UNSPEC,
626 struct bpf_prog_info info = {};
627 __u32 info_len = sizeof(info);
628 bool use_separators = true;
629 bool stress_mode = false;
630 struct bpf_program *prog;
631 struct bpf_object *obj;
641 /* Notice: choosing he queue size is very important with the
642 * ixgbe driver, because it's driver page recycling trick is
643 * dependend on pages being returned quickly. The number of
644 * out-standing packets in the system must be less-than 2x
649 snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]);
650 prog_load_attr.file = filename;
652 if (setrlimit(RLIMIT_MEMLOCK, &r)) {
653 perror("setrlimit(RLIMIT_MEMLOCK)");
657 if (bpf_prog_load_xattr(&prog_load_attr, &obj, &prog_fd))
661 fprintf(stderr, "ERR: bpf_prog_load_xattr: %s\n",
665 if (init_map_fds(obj) < 0) {
666 fprintf(stderr, "bpf_object__find_map_fd_by_name failed\n");
669 mark_cpus_unavailable();
671 /* Parse commands line args */
672 while ((opt = getopt_long(argc, argv, "hSd:s:p:q:c:xzF",
673 long_options, &longindex)) != -1) {
676 if (strlen(optarg) >= IF_NAMESIZE) {
677 fprintf(stderr, "ERR: --dev name too long\n");
680 ifname = (char *)&ifname_buf;
681 strncpy(ifname, optarg, IF_NAMESIZE);
682 ifindex = if_nametoindex(ifname);
685 "ERR: --dev name unknown err(%d):%s\n",
686 errno, strerror(errno));
691 interval = atoi(optarg);
694 xdp_flags |= XDP_FLAGS_SKB_MODE;
700 use_separators = false;
703 /* Selecting eBPF prog to load */
707 /* Add multiple CPUs */
708 add_cpu = strtoul(optarg, NULL, 0);
709 if (add_cpu >= MAX_CPUS) {
711 "--cpu nr too large for cpumap err(%d):%s\n",
712 errno, strerror(errno));
715 create_cpu_entry(add_cpu, qsize, added_cpus, true);
719 qsize = atoi(optarg);
722 xdp_flags &= ~XDP_FLAGS_UPDATE_IF_NOEXIST;
728 return EXIT_FAIL_OPTION;
731 /* Required option */
733 fprintf(stderr, "ERR: required option --dev missing\n");
735 return EXIT_FAIL_OPTION;
737 /* Required option */
739 fprintf(stderr, "ERR: required option --cpu missing\n");
740 fprintf(stderr, " Specify multiple --cpu option to add more\n");
742 return EXIT_FAIL_OPTION;
745 /* Remove XDP program when program is interrupted or killed */
746 signal(SIGINT, int_exit);
747 signal(SIGTERM, int_exit);
749 prog = bpf_object__find_program_by_title(obj, prog_name);
751 fprintf(stderr, "bpf_object__find_program_by_title failed\n");
755 prog_fd = bpf_program__fd(prog);
757 fprintf(stderr, "bpf_program__fd failed\n");
761 if (bpf_set_link_xdp_fd(ifindex, prog_fd, xdp_flags) < 0) {
762 fprintf(stderr, "link set xdp fd failed\n");
763 return EXIT_FAIL_XDP;
766 err = bpf_obj_get_info_by_fd(prog_fd, &info, &info_len);
768 printf("can't get prog info - %s\n", strerror(errno));
773 stats_poll(interval, use_separators, prog_name, stress_mode);