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>
19 #include <linux/limits.h>
22 #include <linux/err.h>
24 #include <arpa/inet.h>
25 #include <linux/if_link.h>
27 #define MAX_CPUS 64 /* WARNING - sync with _kern.c */
29 /* How many xdp_progs are defined in _kern.c */
37 static int ifindex = -1;
38 static char ifname_buf[IF_NAMESIZE];
42 static __u32 xdp_flags = XDP_FLAGS_UPDATE_IF_NOEXIST;
43 static int cpu_map_fd;
44 static int rx_cnt_map_fd;
45 static int redirect_err_cnt_map_fd;
46 static int cpumap_enqueue_cnt_map_fd;
47 static int cpumap_kthread_cnt_map_fd;
48 static int cpus_available_map_fd;
49 static int cpus_count_map_fd;
50 static int cpus_iterator_map_fd;
51 static int exception_cnt_map_fd;
54 struct bpf_link *tp_links[NUM_TP] = { 0 };
55 static int tp_cnt = 0;
57 /* Exit return codes */
60 #define EXIT_FAIL_OPTION 2
61 #define EXIT_FAIL_XDP 3
62 #define EXIT_FAIL_BPF 4
63 #define EXIT_FAIL_MEM 5
65 static const struct option long_options[] = {
66 {"help", no_argument, NULL, 'h' },
67 {"dev", required_argument, NULL, 'd' },
68 {"skb-mode", no_argument, NULL, 'S' },
69 {"sec", required_argument, NULL, 's' },
70 {"progname", required_argument, NULL, 'p' },
71 {"qsize", required_argument, NULL, 'q' },
72 {"cpu", required_argument, NULL, 'c' },
73 {"stress-mode", no_argument, NULL, 'x' },
74 {"no-separators", no_argument, NULL, 'z' },
75 {"force", no_argument, NULL, 'F' },
79 static void int_exit(int sig)
81 __u32 curr_prog_id = 0;
84 if (bpf_get_link_xdp_id(ifindex, &curr_prog_id, xdp_flags)) {
85 printf("bpf_get_link_xdp_id failed\n");
88 if (prog_id == curr_prog_id) {
90 "Interrupted: Removing XDP program on ifindex:%d device:%s\n",
92 bpf_set_link_xdp_fd(ifindex, -1, xdp_flags);
93 } else if (!curr_prog_id) {
94 printf("couldn't find a prog id on a given iface\n");
96 printf("program on interface changed, not removing\n");
99 /* Detach tracepoints */
101 bpf_link__destroy(tp_links[--tp_cnt]);
106 static void print_avail_progs(struct bpf_object *obj)
108 struct bpf_program *pos;
110 bpf_object__for_each_program(pos, obj) {
111 if (bpf_program__is_xdp(pos))
112 printf(" %s\n", bpf_program__title(pos, false));
116 static void usage(char *argv[], struct bpf_object *obj)
120 printf("\nDOCUMENTATION:\n%s\n", __doc__);
122 printf(" Usage: %s (options-see-below)\n", argv[0]);
123 printf(" Listing options:\n");
124 for (i = 0; long_options[i].name != 0; i++) {
125 printf(" --%-12s", long_options[i].name);
126 if (long_options[i].flag != NULL)
127 printf(" flag (internal value:%d)",
128 *long_options[i].flag);
130 printf(" short-option: -%c",
131 long_options[i].val);
134 printf("\n Programs to be used for --progname:\n");
135 print_avail_progs(obj);
139 /* gettime returns the current time of day in nanoseconds.
140 * Cost: clock_gettime (ns) => 26ns (CLOCK_MONOTONIC)
141 * clock_gettime (ns) => 9ns (CLOCK_MONOTONIC_COARSE)
143 #define NANOSEC_PER_SEC 1000000000 /* 10^9 */
144 static __u64 gettime(void)
149 res = clock_gettime(CLOCK_MONOTONIC, &t);
151 fprintf(stderr, "Error with gettimeofday! (%i)\n", res);
154 return (__u64) t.tv_sec * NANOSEC_PER_SEC + t.tv_nsec;
157 /* Common stats data record shared with _kern.c */
165 struct datarec total;
168 struct stats_record {
169 struct record rx_cnt;
170 struct record redir_err;
171 struct record kthread;
172 struct record exception;
173 struct record enq[MAX_CPUS];
176 static bool map_collect_percpu(int fd, __u32 key, struct record *rec)
178 /* For percpu maps, userspace gets a value per possible CPU */
179 unsigned int nr_cpus = bpf_num_possible_cpus();
180 struct datarec values[nr_cpus];
181 __u64 sum_processed = 0;
182 __u64 sum_dropped = 0;
186 if ((bpf_map_lookup_elem(fd, &key, values)) != 0) {
188 "ERR: bpf_map_lookup_elem failed key:0x%X\n", key);
191 /* Get time as close as possible to reading map contents */
192 rec->timestamp = gettime();
194 /* Record and sum values from each CPU */
195 for (i = 0; i < nr_cpus; i++) {
196 rec->cpu[i].processed = values[i].processed;
197 sum_processed += values[i].processed;
198 rec->cpu[i].dropped = values[i].dropped;
199 sum_dropped += values[i].dropped;
200 rec->cpu[i].issue = values[i].issue;
201 sum_issue += values[i].issue;
203 rec->total.processed = sum_processed;
204 rec->total.dropped = sum_dropped;
205 rec->total.issue = sum_issue;
209 static struct datarec *alloc_record_per_cpu(void)
211 unsigned int nr_cpus = bpf_num_possible_cpus();
212 struct datarec *array;
215 size = sizeof(struct datarec) * nr_cpus;
216 array = malloc(size);
217 memset(array, 0, size);
219 fprintf(stderr, "Mem alloc error (nr_cpus:%u)\n", nr_cpus);
225 static struct stats_record *alloc_stats_record(void)
227 struct stats_record *rec;
230 rec = malloc(sizeof(*rec));
231 memset(rec, 0, sizeof(*rec));
233 fprintf(stderr, "Mem alloc error\n");
236 rec->rx_cnt.cpu = alloc_record_per_cpu();
237 rec->redir_err.cpu = alloc_record_per_cpu();
238 rec->kthread.cpu = alloc_record_per_cpu();
239 rec->exception.cpu = alloc_record_per_cpu();
240 for (i = 0; i < MAX_CPUS; i++)
241 rec->enq[i].cpu = alloc_record_per_cpu();
246 static void free_stats_record(struct stats_record *r)
250 for (i = 0; i < MAX_CPUS; i++)
252 free(r->exception.cpu);
253 free(r->kthread.cpu);
254 free(r->redir_err.cpu);
259 static double calc_period(struct record *r, struct record *p)
264 period = r->timestamp - p->timestamp;
266 period_ = ((double) period / NANOSEC_PER_SEC);
271 static __u64 calc_pps(struct datarec *r, struct datarec *p, double period_)
277 packets = r->processed - p->processed;
278 pps = packets / period_;
283 static __u64 calc_drop_pps(struct datarec *r, struct datarec *p, double period_)
289 packets = r->dropped - p->dropped;
290 pps = packets / period_;
295 static __u64 calc_errs_pps(struct datarec *r,
296 struct datarec *p, double period_)
302 packets = r->issue - p->issue;
303 pps = packets / period_;
308 static void stats_print(struct stats_record *stats_rec,
309 struct stats_record *stats_prev,
312 unsigned int nr_cpus = bpf_num_possible_cpus();
313 double pps = 0, drop = 0, err = 0;
314 struct record *rec, *prev;
320 printf("Running XDP/eBPF prog_name:%s\n", prog_name);
321 printf("%-15s %-7s %-14s %-11s %-9s\n",
322 "XDP-cpumap", "CPU:to", "pps", "drop-pps", "extra-info");
326 char *fmt_rx = "%-15s %-7d %'-14.0f %'-11.0f %'-10.0f %s\n";
327 char *fm2_rx = "%-15s %-7s %'-14.0f %'-11.0f\n";
330 rec = &stats_rec->rx_cnt;
331 prev = &stats_prev->rx_cnt;
332 t = calc_period(rec, prev);
333 for (i = 0; i < nr_cpus; i++) {
334 struct datarec *r = &rec->cpu[i];
335 struct datarec *p = &prev->cpu[i];
337 pps = calc_pps(r, p, t);
338 drop = calc_drop_pps(r, p, t);
339 err = calc_errs_pps(r, p, t);
341 errstr = "cpu-dest/err";
343 printf(fmt_rx, "XDP-RX",
344 i, pps, drop, err, errstr);
346 pps = calc_pps(&rec->total, &prev->total, t);
347 drop = calc_drop_pps(&rec->total, &prev->total, t);
348 err = calc_errs_pps(&rec->total, &prev->total, t);
349 printf(fm2_rx, "XDP-RX", "total", pps, drop);
352 /* cpumap enqueue stats */
353 for (to_cpu = 0; to_cpu < MAX_CPUS; to_cpu++) {
354 char *fmt = "%-15s %3d:%-3d %'-14.0f %'-11.0f %'-10.2f %s\n";
355 char *fm2 = "%-15s %3s:%-3d %'-14.0f %'-11.0f %'-10.2f %s\n";
358 rec = &stats_rec->enq[to_cpu];
359 prev = &stats_prev->enq[to_cpu];
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 drop = calc_drop_pps(r, p, t);
367 err = calc_errs_pps(r, p, t);
369 errstr = "bulk-average";
370 err = pps / err; /* calc average bulk size */
373 printf(fmt, "cpumap-enqueue",
374 i, to_cpu, pps, drop, err, errstr);
376 pps = calc_pps(&rec->total, &prev->total, t);
378 drop = calc_drop_pps(&rec->total, &prev->total, t);
379 err = calc_errs_pps(&rec->total, &prev->total, t);
381 errstr = "bulk-average";
382 err = pps / err; /* calc average bulk size */
384 printf(fm2, "cpumap-enqueue",
385 "sum", to_cpu, pps, drop, err, errstr);
389 /* cpumap kthread stats */
391 char *fmt_k = "%-15s %-7d %'-14.0f %'-11.0f %'-10.0f %s\n";
392 char *fm2_k = "%-15s %-7s %'-14.0f %'-11.0f %'-10.0f %s\n";
395 rec = &stats_rec->kthread;
396 prev = &stats_prev->kthread;
397 t = calc_period(rec, prev);
398 for (i = 0; i < nr_cpus; i++) {
399 struct datarec *r = &rec->cpu[i];
400 struct datarec *p = &prev->cpu[i];
402 pps = calc_pps(r, p, t);
403 drop = calc_drop_pps(r, p, t);
404 err = calc_errs_pps(r, p, t);
408 printf(fmt_k, "cpumap_kthread",
409 i, pps, drop, err, e_str);
411 pps = calc_pps(&rec->total, &prev->total, t);
412 drop = calc_drop_pps(&rec->total, &prev->total, t);
413 err = calc_errs_pps(&rec->total, &prev->total, t);
416 printf(fm2_k, "cpumap_kthread", "total", pps, drop, err, e_str);
419 /* XDP redirect err tracepoints (very unlikely) */
421 char *fmt_err = "%-15s %-7d %'-14.0f %'-11.0f\n";
422 char *fm2_err = "%-15s %-7s %'-14.0f %'-11.0f\n";
424 rec = &stats_rec->redir_err;
425 prev = &stats_prev->redir_err;
426 t = calc_period(rec, prev);
427 for (i = 0; i < nr_cpus; i++) {
428 struct datarec *r = &rec->cpu[i];
429 struct datarec *p = &prev->cpu[i];
431 pps = calc_pps(r, p, t);
432 drop = calc_drop_pps(r, p, t);
434 printf(fmt_err, "redirect_err", i, pps, drop);
436 pps = calc_pps(&rec->total, &prev->total, t);
437 drop = calc_drop_pps(&rec->total, &prev->total, t);
438 printf(fm2_err, "redirect_err", "total", pps, drop);
441 /* XDP general exception tracepoints */
443 char *fmt_err = "%-15s %-7d %'-14.0f %'-11.0f\n";
444 char *fm2_err = "%-15s %-7s %'-14.0f %'-11.0f\n";
446 rec = &stats_rec->exception;
447 prev = &stats_prev->exception;
448 t = calc_period(rec, prev);
449 for (i = 0; i < nr_cpus; i++) {
450 struct datarec *r = &rec->cpu[i];
451 struct datarec *p = &prev->cpu[i];
453 pps = calc_pps(r, p, t);
454 drop = calc_drop_pps(r, p, t);
456 printf(fmt_err, "xdp_exception", i, pps, drop);
458 pps = calc_pps(&rec->total, &prev->total, t);
459 drop = calc_drop_pps(&rec->total, &prev->total, t);
460 printf(fm2_err, "xdp_exception", "total", pps, drop);
467 static void stats_collect(struct stats_record *rec)
472 map_collect_percpu(fd, 0, &rec->rx_cnt);
474 fd = redirect_err_cnt_map_fd;
475 map_collect_percpu(fd, 1, &rec->redir_err);
477 fd = cpumap_enqueue_cnt_map_fd;
478 for (i = 0; i < MAX_CPUS; i++)
479 map_collect_percpu(fd, i, &rec->enq[i]);
481 fd = cpumap_kthread_cnt_map_fd;
482 map_collect_percpu(fd, 0, &rec->kthread);
484 fd = exception_cnt_map_fd;
485 map_collect_percpu(fd, 0, &rec->exception);
489 /* Pointer swap trick */
490 static inline void swap(struct stats_record **a, struct stats_record **b)
492 struct stats_record *tmp;
499 static int create_cpu_entry(__u32 cpu, __u32 queue_size,
500 __u32 avail_idx, bool new)
502 __u32 curr_cpus_count = 0;
506 /* Add a CPU entry to cpumap, as this allocate a cpu entry in
507 * the kernel for the cpu.
509 ret = bpf_map_update_elem(cpu_map_fd, &cpu, &queue_size, 0);
511 fprintf(stderr, "Create CPU entry failed (err:%d)\n", ret);
515 /* Inform bpf_prog's that a new CPU is available to select
516 * from via some control maps.
518 ret = bpf_map_update_elem(cpus_available_map_fd, &avail_idx, &cpu, 0);
520 fprintf(stderr, "Add to avail CPUs failed\n");
524 /* When not replacing/updating existing entry, bump the count */
525 ret = bpf_map_lookup_elem(cpus_count_map_fd, &key, &curr_cpus_count);
527 fprintf(stderr, "Failed reading curr cpus_count\n");
532 ret = bpf_map_update_elem(cpus_count_map_fd, &key,
533 &curr_cpus_count, 0);
535 fprintf(stderr, "Failed write curr cpus_count\n");
539 /* map_fd[7] = cpus_iterator */
540 printf("%s CPU:%u as idx:%u queue_size:%d (total cpus_count:%u)\n",
541 new ? "Add-new":"Replace", cpu, avail_idx,
542 queue_size, curr_cpus_count);
547 /* CPUs are zero-indexed. Thus, add a special sentinel default value
548 * in map cpus_available to mark CPU index'es not configured
550 static void mark_cpus_unavailable(void)
552 __u32 invalid_cpu = MAX_CPUS;
555 for (i = 0; i < MAX_CPUS; i++) {
556 ret = bpf_map_update_elem(cpus_available_map_fd, &i,
559 fprintf(stderr, "Failed marking CPU unavailable\n");
565 /* Stress cpumap management code by concurrently changing underlying cpumap */
566 static void stress_cpumap(void)
568 /* Changing qsize will cause kernel to free and alloc a new
569 * bpf_cpu_map_entry, with an associated/complicated tear-down
572 create_cpu_entry(1, 1024, 0, false);
573 create_cpu_entry(1, 8, 0, false);
574 create_cpu_entry(1, 16000, 0, false);
577 static void stats_poll(int interval, bool use_separators, char *prog_name,
580 struct stats_record *record, *prev;
582 record = alloc_stats_record();
583 prev = alloc_stats_record();
584 stats_collect(record);
586 /* Trick to pretty printf with thousands separators use %' */
588 setlocale(LC_NUMERIC, "en_US");
591 swap(&prev, &record);
592 stats_collect(record);
593 stats_print(record, prev, prog_name);
599 free_stats_record(record);
600 free_stats_record(prev);
603 static struct bpf_link * attach_tp(struct bpf_object *obj,
604 const char *tp_category,
607 struct bpf_program *prog;
608 struct bpf_link *link;
609 char sec_name[PATH_MAX];
612 len = snprintf(sec_name, PATH_MAX, "tracepoint/%s/%s",
613 tp_category, tp_name);
617 prog = bpf_object__find_program_by_title(obj, sec_name);
619 fprintf(stderr, "ERR: finding progsec: %s\n", sec_name);
623 link = bpf_program__attach_tracepoint(prog, tp_category, tp_name);
630 static void init_tracepoints(struct bpf_object *obj) {
631 tp_links[tp_cnt++] = attach_tp(obj, "xdp", "xdp_redirect_err");
632 tp_links[tp_cnt++] = attach_tp(obj, "xdp", "xdp_redirect_map_err");
633 tp_links[tp_cnt++] = attach_tp(obj, "xdp", "xdp_exception");
634 tp_links[tp_cnt++] = attach_tp(obj, "xdp", "xdp_cpumap_enqueue");
635 tp_links[tp_cnt++] = attach_tp(obj, "xdp", "xdp_cpumap_kthread");
638 static int init_map_fds(struct bpf_object *obj)
640 /* Maps updated by tracepoints */
641 redirect_err_cnt_map_fd =
642 bpf_object__find_map_fd_by_name(obj, "redirect_err_cnt");
643 exception_cnt_map_fd =
644 bpf_object__find_map_fd_by_name(obj, "exception_cnt");
645 cpumap_enqueue_cnt_map_fd =
646 bpf_object__find_map_fd_by_name(obj, "cpumap_enqueue_cnt");
647 cpumap_kthread_cnt_map_fd =
648 bpf_object__find_map_fd_by_name(obj, "cpumap_kthread_cnt");
650 /* Maps used by XDP */
651 rx_cnt_map_fd = bpf_object__find_map_fd_by_name(obj, "rx_cnt");
652 cpu_map_fd = bpf_object__find_map_fd_by_name(obj, "cpu_map");
653 cpus_available_map_fd =
654 bpf_object__find_map_fd_by_name(obj, "cpus_available");
655 cpus_count_map_fd = bpf_object__find_map_fd_by_name(obj, "cpus_count");
656 cpus_iterator_map_fd =
657 bpf_object__find_map_fd_by_name(obj, "cpus_iterator");
659 if (cpu_map_fd < 0 || rx_cnt_map_fd < 0 ||
660 redirect_err_cnt_map_fd < 0 || cpumap_enqueue_cnt_map_fd < 0 ||
661 cpumap_kthread_cnt_map_fd < 0 || cpus_available_map_fd < 0 ||
662 cpus_count_map_fd < 0 || cpus_iterator_map_fd < 0 ||
663 exception_cnt_map_fd < 0)
669 int main(int argc, char **argv)
671 struct rlimit r = {10 * 1024 * 1024, RLIM_INFINITY};
672 char *prog_name = "xdp_cpu_map5_lb_hash_ip_pairs";
673 struct bpf_prog_load_attr prog_load_attr = {
674 .prog_type = BPF_PROG_TYPE_UNSPEC,
676 struct bpf_prog_info info = {};
677 __u32 info_len = sizeof(info);
678 bool use_separators = true;
679 bool stress_mode = false;
680 struct bpf_program *prog;
681 struct bpf_object *obj;
691 /* Notice: choosing he queue size is very important with the
692 * ixgbe driver, because it's driver page recycling trick is
693 * dependend on pages being returned quickly. The number of
694 * out-standing packets in the system must be less-than 2x
699 snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]);
700 prog_load_attr.file = filename;
702 if (setrlimit(RLIMIT_MEMLOCK, &r)) {
703 perror("setrlimit(RLIMIT_MEMLOCK)");
707 if (bpf_prog_load_xattr(&prog_load_attr, &obj, &prog_fd))
711 fprintf(stderr, "ERR: bpf_prog_load_xattr: %s\n",
715 init_tracepoints(obj);
716 if (init_map_fds(obj) < 0) {
717 fprintf(stderr, "bpf_object__find_map_fd_by_name failed\n");
720 mark_cpus_unavailable();
722 /* Parse commands line args */
723 while ((opt = getopt_long(argc, argv, "hSd:s:p:q:c:xzF",
724 long_options, &longindex)) != -1) {
727 if (strlen(optarg) >= IF_NAMESIZE) {
728 fprintf(stderr, "ERR: --dev name too long\n");
731 ifname = (char *)&ifname_buf;
732 strncpy(ifname, optarg, IF_NAMESIZE);
733 ifindex = if_nametoindex(ifname);
736 "ERR: --dev name unknown err(%d):%s\n",
737 errno, strerror(errno));
742 interval = atoi(optarg);
745 xdp_flags |= XDP_FLAGS_SKB_MODE;
751 use_separators = false;
754 /* Selecting eBPF prog to load */
758 /* Add multiple CPUs */
759 add_cpu = strtoul(optarg, NULL, 0);
760 if (add_cpu >= MAX_CPUS) {
762 "--cpu nr too large for cpumap err(%d):%s\n",
763 errno, strerror(errno));
766 create_cpu_entry(add_cpu, qsize, added_cpus, true);
770 qsize = atoi(optarg);
773 xdp_flags &= ~XDP_FLAGS_UPDATE_IF_NOEXIST;
779 return EXIT_FAIL_OPTION;
783 if (!(xdp_flags & XDP_FLAGS_SKB_MODE))
784 xdp_flags |= XDP_FLAGS_DRV_MODE;
786 /* Required option */
788 fprintf(stderr, "ERR: required option --dev missing\n");
790 return EXIT_FAIL_OPTION;
792 /* Required option */
794 fprintf(stderr, "ERR: required option --cpu missing\n");
795 fprintf(stderr, " Specify multiple --cpu option to add more\n");
797 return EXIT_FAIL_OPTION;
800 /* Remove XDP program when program is interrupted or killed */
801 signal(SIGINT, int_exit);
802 signal(SIGTERM, int_exit);
804 prog = bpf_object__find_program_by_title(obj, prog_name);
806 fprintf(stderr, "bpf_object__find_program_by_title failed\n");
810 prog_fd = bpf_program__fd(prog);
812 fprintf(stderr, "bpf_program__fd failed\n");
816 if (bpf_set_link_xdp_fd(ifindex, prog_fd, xdp_flags) < 0) {
817 fprintf(stderr, "link set xdp fd failed\n");
818 return EXIT_FAIL_XDP;
821 err = bpf_obj_get_info_by_fd(prog_fd, &info, &info_len);
823 printf("can't get prog info - %s\n", strerror(errno));
828 stats_poll(interval, use_separators, prog_name, stress_mode);