samples/bpf: Xdp_redirect_cpu fix missing tracepoint attach
[sfrench/cifs-2.6.git] / samples / bpf / xdp_redirect_cpu_user.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright(c) 2017 Jesper Dangaard Brouer, Red Hat, Inc.
3  */
4 static const char *__doc__ =
5         " XDP redirect with a CPU-map type \"BPF_MAP_TYPE_CPUMAP\"";
6
7 #include <errno.h>
8 #include <signal.h>
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <stdbool.h>
12 #include <string.h>
13 #include <unistd.h>
14 #include <locale.h>
15 #include <sys/resource.h>
16 #include <getopt.h>
17 #include <net/if.h>
18 #include <time.h>
19 #include <linux/limits.h>
20
21 #define __must_check
22 #include <linux/err.h>
23
24 #include <arpa/inet.h>
25 #include <linux/if_link.h>
26
27 #define MAX_CPUS 64 /* WARNING - sync with _kern.c */
28
29 /* How many xdp_progs are defined in _kern.c */
30 #define MAX_PROG 6
31
32 #include <bpf/bpf.h>
33 #include "libbpf.h"
34
35 #include "bpf_util.h"
36
37 static int ifindex = -1;
38 static char ifname_buf[IF_NAMESIZE];
39 static char *ifname;
40 static __u32 prog_id;
41
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;
52
53 #define NUM_TP 5
54 struct bpf_link *tp_links[NUM_TP] = { 0 };
55 static int tp_cnt = 0;
56
57 /* Exit return codes */
58 #define EXIT_OK         0
59 #define EXIT_FAIL               1
60 #define EXIT_FAIL_OPTION        2
61 #define EXIT_FAIL_XDP           3
62 #define EXIT_FAIL_BPF           4
63 #define EXIT_FAIL_MEM           5
64
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' },
76         {0, 0, NULL,  0 }
77 };
78
79 static void int_exit(int sig)
80 {
81         __u32 curr_prog_id = 0;
82
83         if (ifindex > -1) {
84                 if (bpf_get_link_xdp_id(ifindex, &curr_prog_id, xdp_flags)) {
85                         printf("bpf_get_link_xdp_id failed\n");
86                         exit(EXIT_FAIL);
87                 }
88                 if (prog_id == curr_prog_id) {
89                         fprintf(stderr,
90                                 "Interrupted: Removing XDP program on ifindex:%d device:%s\n",
91                                 ifindex, ifname);
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");
95                 } else {
96                         printf("program on interface changed, not removing\n");
97                 }
98         }
99         /* Detach tracepoints */
100         while (tp_cnt)
101                 bpf_link__destroy(tp_links[--tp_cnt]);
102
103         exit(EXIT_OK);
104 }
105
106 static void print_avail_progs(struct bpf_object *obj)
107 {
108         struct bpf_program *pos;
109
110         bpf_object__for_each_program(pos, obj) {
111                 if (bpf_program__is_xdp(pos))
112                         printf(" %s\n", bpf_program__title(pos, false));
113         }
114 }
115
116 static void usage(char *argv[], struct bpf_object *obj)
117 {
118         int i;
119
120         printf("\nDOCUMENTATION:\n%s\n", __doc__);
121         printf("\n");
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);
129                 else
130                         printf(" short-option: -%c",
131                                 long_options[i].val);
132                 printf("\n");
133         }
134         printf("\n Programs to be used for --progname:\n");
135         print_avail_progs(obj);
136         printf("\n");
137 }
138
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)
142  */
143 #define NANOSEC_PER_SEC 1000000000 /* 10^9 */
144 static __u64 gettime(void)
145 {
146         struct timespec t;
147         int res;
148
149         res = clock_gettime(CLOCK_MONOTONIC, &t);
150         if (res < 0) {
151                 fprintf(stderr, "Error with gettimeofday! (%i)\n", res);
152                 exit(EXIT_FAIL);
153         }
154         return (__u64) t.tv_sec * NANOSEC_PER_SEC + t.tv_nsec;
155 }
156
157 /* Common stats data record shared with _kern.c */
158 struct datarec {
159         __u64 processed;
160         __u64 dropped;
161         __u64 issue;
162 };
163 struct record {
164         __u64 timestamp;
165         struct datarec total;
166         struct datarec *cpu;
167 };
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];
174 };
175
176 static bool map_collect_percpu(int fd, __u32 key, struct record *rec)
177 {
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;
183         __u64 sum_issue = 0;
184         int i;
185
186         if ((bpf_map_lookup_elem(fd, &key, values)) != 0) {
187                 fprintf(stderr,
188                         "ERR: bpf_map_lookup_elem failed key:0x%X\n", key);
189                 return false;
190         }
191         /* Get time as close as possible to reading map contents */
192         rec->timestamp = gettime();
193
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;
202         }
203         rec->total.processed = sum_processed;
204         rec->total.dropped   = sum_dropped;
205         rec->total.issue     = sum_issue;
206         return true;
207 }
208
209 static struct datarec *alloc_record_per_cpu(void)
210 {
211         unsigned int nr_cpus = bpf_num_possible_cpus();
212         struct datarec *array;
213         size_t size;
214
215         size = sizeof(struct datarec) * nr_cpus;
216         array = malloc(size);
217         memset(array, 0, size);
218         if (!array) {
219                 fprintf(stderr, "Mem alloc error (nr_cpus:%u)\n", nr_cpus);
220                 exit(EXIT_FAIL_MEM);
221         }
222         return array;
223 }
224
225 static struct stats_record *alloc_stats_record(void)
226 {
227         struct stats_record *rec;
228         int i;
229
230         rec = malloc(sizeof(*rec));
231         memset(rec, 0, sizeof(*rec));
232         if (!rec) {
233                 fprintf(stderr, "Mem alloc error\n");
234                 exit(EXIT_FAIL_MEM);
235         }
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();
242
243         return rec;
244 }
245
246 static void free_stats_record(struct stats_record *r)
247 {
248         int i;
249
250         for (i = 0; i < MAX_CPUS; i++)
251                 free(r->enq[i].cpu);
252         free(r->exception.cpu);
253         free(r->kthread.cpu);
254         free(r->redir_err.cpu);
255         free(r->rx_cnt.cpu);
256         free(r);
257 }
258
259 static double calc_period(struct record *r, struct record *p)
260 {
261         double period_ = 0;
262         __u64 period = 0;
263
264         period = r->timestamp - p->timestamp;
265         if (period > 0)
266                 period_ = ((double) period / NANOSEC_PER_SEC);
267
268         return period_;
269 }
270
271 static __u64 calc_pps(struct datarec *r, struct datarec *p, double period_)
272 {
273         __u64 packets = 0;
274         __u64 pps = 0;
275
276         if (period_ > 0) {
277                 packets = r->processed - p->processed;
278                 pps = packets / period_;
279         }
280         return pps;
281 }
282
283 static __u64 calc_drop_pps(struct datarec *r, struct datarec *p, double period_)
284 {
285         __u64 packets = 0;
286         __u64 pps = 0;
287
288         if (period_ > 0) {
289                 packets = r->dropped - p->dropped;
290                 pps = packets / period_;
291         }
292         return pps;
293 }
294
295 static __u64 calc_errs_pps(struct datarec *r,
296                             struct datarec *p, double period_)
297 {
298         __u64 packets = 0;
299         __u64 pps = 0;
300
301         if (period_ > 0) {
302                 packets = r->issue - p->issue;
303                 pps = packets / period_;
304         }
305         return pps;
306 }
307
308 static void stats_print(struct stats_record *stats_rec,
309                         struct stats_record *stats_prev,
310                         char *prog_name)
311 {
312         unsigned int nr_cpus = bpf_num_possible_cpus();
313         double pps = 0, drop = 0, err = 0;
314         struct record *rec, *prev;
315         int to_cpu;
316         double t;
317         int i;
318
319         /* Header */
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");
323
324         /* XDP rx_cnt */
325         {
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";
328                 char *errstr = "";
329
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];
336
337                         pps = calc_pps(r, p, t);
338                         drop = calc_drop_pps(r, p, t);
339                         err  = calc_errs_pps(r, p, t);
340                         if (err > 0)
341                                 errstr = "cpu-dest/err";
342                         if (pps > 0)
343                                 printf(fmt_rx, "XDP-RX",
344                                         i, pps, drop, err, errstr);
345                 }
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);
350         }
351
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";
356                 char *errstr = "";
357
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];
364
365                         pps  = calc_pps(r, p, t);
366                         drop = calc_drop_pps(r, p, t);
367                         err  = calc_errs_pps(r, p, t);
368                         if (err > 0) {
369                                 errstr = "bulk-average";
370                                 err = pps / err; /* calc average bulk size */
371                         }
372                         if (pps > 0)
373                                 printf(fmt, "cpumap-enqueue",
374                                        i, to_cpu, pps, drop, err, errstr);
375                 }
376                 pps = calc_pps(&rec->total, &prev->total, t);
377                 if (pps > 0) {
378                         drop = calc_drop_pps(&rec->total, &prev->total, t);
379                         err  = calc_errs_pps(&rec->total, &prev->total, t);
380                         if (err > 0) {
381                                 errstr = "bulk-average";
382                                 err = pps / err; /* calc average bulk size */
383                         }
384                         printf(fm2, "cpumap-enqueue",
385                                "sum", to_cpu, pps, drop, err, errstr);
386                 }
387         }
388
389         /* cpumap kthread stats */
390         {
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";
393                 char *e_str = "";
394
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];
401
402                         pps  = calc_pps(r, p, t);
403                         drop = calc_drop_pps(r, p, t);
404                         err  = calc_errs_pps(r, p, t);
405                         if (err > 0)
406                                 e_str = "sched";
407                         if (pps > 0)
408                                 printf(fmt_k, "cpumap_kthread",
409                                        i, pps, drop, err, e_str);
410                 }
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);
414                 if (err > 0)
415                         e_str = "sched-sum";
416                 printf(fm2_k, "cpumap_kthread", "total", pps, drop, err, e_str);
417         }
418
419         /* XDP redirect err tracepoints (very unlikely) */
420         {
421                 char *fmt_err = "%-15s %-7d %'-14.0f %'-11.0f\n";
422                 char *fm2_err = "%-15s %-7s %'-14.0f %'-11.0f\n";
423
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];
430
431                         pps  = calc_pps(r, p, t);
432                         drop = calc_drop_pps(r, p, t);
433                         if (pps > 0)
434                                 printf(fmt_err, "redirect_err", i, pps, drop);
435                 }
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);
439         }
440
441         /* XDP general exception tracepoints */
442         {
443                 char *fmt_err = "%-15s %-7d %'-14.0f %'-11.0f\n";
444                 char *fm2_err = "%-15s %-7s %'-14.0f %'-11.0f\n";
445
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];
452
453                         pps  = calc_pps(r, p, t);
454                         drop = calc_drop_pps(r, p, t);
455                         if (pps > 0)
456                                 printf(fmt_err, "xdp_exception", i, pps, drop);
457                 }
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);
461         }
462
463         printf("\n");
464         fflush(stdout);
465 }
466
467 static void stats_collect(struct stats_record *rec)
468 {
469         int fd, i;
470
471         fd = rx_cnt_map_fd;
472         map_collect_percpu(fd, 0, &rec->rx_cnt);
473
474         fd = redirect_err_cnt_map_fd;
475         map_collect_percpu(fd, 1, &rec->redir_err);
476
477         fd = cpumap_enqueue_cnt_map_fd;
478         for (i = 0; i < MAX_CPUS; i++)
479                 map_collect_percpu(fd, i, &rec->enq[i]);
480
481         fd = cpumap_kthread_cnt_map_fd;
482         map_collect_percpu(fd, 0, &rec->kthread);
483
484         fd = exception_cnt_map_fd;
485         map_collect_percpu(fd, 0, &rec->exception);
486 }
487
488
489 /* Pointer swap trick */
490 static inline void swap(struct stats_record **a, struct stats_record **b)
491 {
492         struct stats_record *tmp;
493
494         tmp = *a;
495         *a = *b;
496         *b = tmp;
497 }
498
499 static int create_cpu_entry(__u32 cpu, __u32 queue_size,
500                             __u32 avail_idx, bool new)
501 {
502         __u32 curr_cpus_count = 0;
503         __u32 key = 0;
504         int ret;
505
506         /* Add a CPU entry to cpumap, as this allocate a cpu entry in
507          * the kernel for the cpu.
508          */
509         ret = bpf_map_update_elem(cpu_map_fd, &cpu, &queue_size, 0);
510         if (ret) {
511                 fprintf(stderr, "Create CPU entry failed (err:%d)\n", ret);
512                 exit(EXIT_FAIL_BPF);
513         }
514
515         /* Inform bpf_prog's that a new CPU is available to select
516          * from via some control maps.
517          */
518         ret = bpf_map_update_elem(cpus_available_map_fd, &avail_idx, &cpu, 0);
519         if (ret) {
520                 fprintf(stderr, "Add to avail CPUs failed\n");
521                 exit(EXIT_FAIL_BPF);
522         }
523
524         /* When not replacing/updating existing entry, bump the count */
525         ret = bpf_map_lookup_elem(cpus_count_map_fd, &key, &curr_cpus_count);
526         if (ret) {
527                 fprintf(stderr, "Failed reading curr cpus_count\n");
528                 exit(EXIT_FAIL_BPF);
529         }
530         if (new) {
531                 curr_cpus_count++;
532                 ret = bpf_map_update_elem(cpus_count_map_fd, &key,
533                                           &curr_cpus_count, 0);
534                 if (ret) {
535                         fprintf(stderr, "Failed write curr cpus_count\n");
536                         exit(EXIT_FAIL_BPF);
537                 }
538         }
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);
543
544         return 0;
545 }
546
547 /* CPUs are zero-indexed. Thus, add a special sentinel default value
548  * in map cpus_available to mark CPU index'es not configured
549  */
550 static void mark_cpus_unavailable(void)
551 {
552         __u32 invalid_cpu = MAX_CPUS;
553         int ret, i;
554
555         for (i = 0; i < MAX_CPUS; i++) {
556                 ret = bpf_map_update_elem(cpus_available_map_fd, &i,
557                                           &invalid_cpu, 0);
558                 if (ret) {
559                         fprintf(stderr, "Failed marking CPU unavailable\n");
560                         exit(EXIT_FAIL_BPF);
561                 }
562         }
563 }
564
565 /* Stress cpumap management code by concurrently changing underlying cpumap */
566 static void stress_cpumap(void)
567 {
568         /* Changing qsize will cause kernel to free and alloc a new
569          * bpf_cpu_map_entry, with an associated/complicated tear-down
570          * procedure.
571          */
572         create_cpu_entry(1,  1024, 0, false);
573         create_cpu_entry(1,     8, 0, false);
574         create_cpu_entry(1, 16000, 0, false);
575 }
576
577 static void stats_poll(int interval, bool use_separators, char *prog_name,
578                        bool stress_mode)
579 {
580         struct stats_record *record, *prev;
581
582         record = alloc_stats_record();
583         prev   = alloc_stats_record();
584         stats_collect(record);
585
586         /* Trick to pretty printf with thousands separators use %' */
587         if (use_separators)
588                 setlocale(LC_NUMERIC, "en_US");
589
590         while (1) {
591                 swap(&prev, &record);
592                 stats_collect(record);
593                 stats_print(record, prev, prog_name);
594                 sleep(interval);
595                 if (stress_mode)
596                         stress_cpumap();
597         }
598
599         free_stats_record(record);
600         free_stats_record(prev);
601 }
602
603 static struct bpf_link * attach_tp(struct bpf_object *obj,
604                                    const char *tp_category,
605                                    const char* tp_name)
606 {
607         struct bpf_program *prog;
608         struct bpf_link *link;
609         char sec_name[PATH_MAX];
610         int len;
611
612         len = snprintf(sec_name, PATH_MAX, "tracepoint/%s/%s",
613                        tp_category, tp_name);
614         if (len < 0)
615                 exit(EXIT_FAIL);
616
617         prog = bpf_object__find_program_by_title(obj, sec_name);
618         if (!prog) {
619                 fprintf(stderr, "ERR: finding progsec: %s\n", sec_name);
620                 exit(EXIT_FAIL_BPF);
621         }
622
623         link = bpf_program__attach_tracepoint(prog, tp_category, tp_name);
624         if (IS_ERR(link))
625                 exit(EXIT_FAIL_BPF);
626
627         return link;
628 }
629
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");
636 }
637
638 static int init_map_fds(struct bpf_object *obj)
639 {
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");
649
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");
658
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)
664                 return -ENOENT;
665
666         return 0;
667 }
668
669 int main(int argc, char **argv)
670 {
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,
675         };
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;
682         char filename[256];
683         int added_cpus = 0;
684         int longindex = 0;
685         int interval = 2;
686         int add_cpu = -1;
687         int opt, err;
688         int prog_fd;
689         __u32 qsize;
690
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
695          * RX-ring size.
696          */
697         qsize = 128+64;
698
699         snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]);
700         prog_load_attr.file = filename;
701
702         if (setrlimit(RLIMIT_MEMLOCK, &r)) {
703                 perror("setrlimit(RLIMIT_MEMLOCK)");
704                 return 1;
705         }
706
707         if (bpf_prog_load_xattr(&prog_load_attr, &obj, &prog_fd))
708                 return EXIT_FAIL;
709
710         if (prog_fd < 0) {
711                 fprintf(stderr, "ERR: bpf_prog_load_xattr: %s\n",
712                         strerror(errno));
713                 return EXIT_FAIL;
714         }
715         init_tracepoints(obj);
716         if (init_map_fds(obj) < 0) {
717                 fprintf(stderr, "bpf_object__find_map_fd_by_name failed\n");
718                 return EXIT_FAIL;
719         }
720         mark_cpus_unavailable();
721
722         /* Parse commands line args */
723         while ((opt = getopt_long(argc, argv, "hSd:s:p:q:c:xzF",
724                                   long_options, &longindex)) != -1) {
725                 switch (opt) {
726                 case 'd':
727                         if (strlen(optarg) >= IF_NAMESIZE) {
728                                 fprintf(stderr, "ERR: --dev name too long\n");
729                                 goto error;
730                         }
731                         ifname = (char *)&ifname_buf;
732                         strncpy(ifname, optarg, IF_NAMESIZE);
733                         ifindex = if_nametoindex(ifname);
734                         if (ifindex == 0) {
735                                 fprintf(stderr,
736                                         "ERR: --dev name unknown err(%d):%s\n",
737                                         errno, strerror(errno));
738                                 goto error;
739                         }
740                         break;
741                 case 's':
742                         interval = atoi(optarg);
743                         break;
744                 case 'S':
745                         xdp_flags |= XDP_FLAGS_SKB_MODE;
746                         break;
747                 case 'x':
748                         stress_mode = true;
749                         break;
750                 case 'z':
751                         use_separators = false;
752                         break;
753                 case 'p':
754                         /* Selecting eBPF prog to load */
755                         prog_name = optarg;
756                         break;
757                 case 'c':
758                         /* Add multiple CPUs */
759                         add_cpu = strtoul(optarg, NULL, 0);
760                         if (add_cpu >= MAX_CPUS) {
761                                 fprintf(stderr,
762                                 "--cpu nr too large for cpumap err(%d):%s\n",
763                                         errno, strerror(errno));
764                                 goto error;
765                         }
766                         create_cpu_entry(add_cpu, qsize, added_cpus, true);
767                         added_cpus++;
768                         break;
769                 case 'q':
770                         qsize = atoi(optarg);
771                         break;
772                 case 'F':
773                         xdp_flags &= ~XDP_FLAGS_UPDATE_IF_NOEXIST;
774                         break;
775                 case 'h':
776                 error:
777                 default:
778                         usage(argv, obj);
779                         return EXIT_FAIL_OPTION;
780                 }
781         }
782
783         if (!(xdp_flags & XDP_FLAGS_SKB_MODE))
784                 xdp_flags |= XDP_FLAGS_DRV_MODE;
785
786         /* Required option */
787         if (ifindex == -1) {
788                 fprintf(stderr, "ERR: required option --dev missing\n");
789                 usage(argv, obj);
790                 return EXIT_FAIL_OPTION;
791         }
792         /* Required option */
793         if (add_cpu == -1) {
794                 fprintf(stderr, "ERR: required option --cpu missing\n");
795                 fprintf(stderr, " Specify multiple --cpu option to add more\n");
796                 usage(argv, obj);
797                 return EXIT_FAIL_OPTION;
798         }
799
800         /* Remove XDP program when program is interrupted or killed */
801         signal(SIGINT, int_exit);
802         signal(SIGTERM, int_exit);
803
804         prog = bpf_object__find_program_by_title(obj, prog_name);
805         if (!prog) {
806                 fprintf(stderr, "bpf_object__find_program_by_title failed\n");
807                 return EXIT_FAIL;
808         }
809
810         prog_fd = bpf_program__fd(prog);
811         if (prog_fd < 0) {
812                 fprintf(stderr, "bpf_program__fd failed\n");
813                 return EXIT_FAIL;
814         }
815
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;
819         }
820
821         err = bpf_obj_get_info_by_fd(prog_fd, &info, &info_len);
822         if (err) {
823                 printf("can't get prog info - %s\n", strerror(errno));
824                 return err;
825         }
826         prog_id = info.id;
827
828         stats_poll(interval, use_separators, prog_name, stress_mode);
829         return EXIT_OK;
830 }