samples/bpf: Use libbpf 1.0 API mode instead of RLIMIT_MEMLOCK
[linux-2.6-block.git] / samples / bpf / xdp_rxq_info_user.c
1 /* SPDX-License-Identifier: GPL-2.0
2  * Copyright (c) 2017 Jesper Dangaard Brouer, Red Hat Inc.
3  */
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"
7         ;
8
9 #include <errno.h>
10 #include <signal.h>
11 #include <stdio.h>
12 #include <stdlib.h>
13 #include <stdbool.h>
14 #include <string.h>
15 #include <unistd.h>
16 #include <locale.h>
17 #include <getopt.h>
18 #include <net/if.h>
19 #include <time.h>
20
21 #include <arpa/inet.h>
22 #include <linux/if_link.h>
23
24 #include <bpf/bpf.h>
25 #include <bpf/libbpf.h>
26 #include "bpf_util.h"
27
28 static int ifindex = -1;
29 static char ifname_buf[IF_NAMESIZE];
30 static char *ifname;
31 static __u32 prog_id;
32
33 static __u32 xdp_flags = XDP_FLAGS_UPDATE_IF_NOEXIST;
34
35 static struct bpf_map *stats_global_map;
36 static struct bpf_map *rx_queue_index_map;
37
38 /* Exit return codes */
39 #define EXIT_OK         0
40 #define EXIT_FAIL               1
41 #define EXIT_FAIL_OPTION        2
42 #define EXIT_FAIL_XDP           3
43 #define EXIT_FAIL_BPF           4
44 #define EXIT_FAIL_MEM           5
45
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' },
56         {0, 0, NULL,  0 }
57 };
58
59 static void int_exit(int sig)
60 {
61         __u32 curr_prog_id = 0;
62
63         if (ifindex > -1) {
64                 if (bpf_xdp_query_id(ifindex, xdp_flags, &curr_prog_id)) {
65                         printf("bpf_xdp_query_id failed\n");
66                         exit(EXIT_FAIL);
67                 }
68                 if (prog_id == curr_prog_id) {
69                         fprintf(stderr,
70                                 "Interrupted: Removing XDP program on ifindex:%d device:%s\n",
71                                 ifindex, ifname);
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");
75                 } else {
76                         printf("program on interface changed, not removing\n");
77                 }
78         }
79         exit(EXIT_OK);
80 }
81
82 struct config {
83         __u32 action;
84         int ifindex;
85         __u32 options;
86 };
87 enum cfg_options_flags {
88         NO_TOUCH = 0x0U,
89         READ_MEM = 0x1U,
90         SWAP_MAC = 0x2U,
91 };
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",
98         [XDP_TX]        = "XDP_TX",
99 };
100
101 static const char *action2str(int action)
102 {
103         if (action < XDP_ACTION_MAX)
104                 return xdp_action_names[action];
105         return NULL;
106 }
107
108 static int parse_xdp_action(char *action_str)
109 {
110         size_t maxlen;
111         __u64 action = -1;
112         int i;
113
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) {
117                         action = i;
118                         break;
119                 }
120         }
121         return action;
122 }
123
124 static void list_xdp_actions(void)
125 {
126         int i;
127
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]);
131         printf("\n");
132 }
133
134 static char* options2str(enum cfg_options_flags flag)
135 {
136         if (flag == NO_TOUCH)
137                 return "no_touch";
138         if (flag & SWAP_MAC)
139                 return "swapmac";
140         if (flag & READ_MEM)
141                 return "read";
142         fprintf(stderr, "ERR: Unknown config option flags");
143         exit(EXIT_FAIL);
144 }
145
146 static void usage(char *argv[])
147 {
148         int i;
149
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);
158                 else
159                         printf(" short-option: -%c",
160                                 long_options[i].val);
161                 printf("\n");
162         }
163         printf("\n");
164         list_xdp_actions();
165 }
166
167 #define NANOSEC_PER_SEC 1000000000 /* 10^9 */
168 static __u64 gettime(void)
169 {
170         struct timespec t;
171         int res;
172
173         res = clock_gettime(CLOCK_MONOTONIC, &t);
174         if (res < 0) {
175                 fprintf(stderr, "Error with gettimeofday! (%i)\n", res);
176                 exit(EXIT_FAIL);
177         }
178         return (__u64) t.tv_sec * NANOSEC_PER_SEC + t.tv_nsec;
179 }
180
181 /* Common stats data record shared with _kern.c */
182 struct datarec {
183         __u64 processed;
184         __u64 issue;
185 };
186 struct record {
187         __u64 timestamp;
188         struct datarec total;
189         struct datarec *cpu;
190 };
191 struct stats_record {
192         struct record stats;
193         struct record *rxq;
194 };
195
196 static struct datarec *alloc_record_per_cpu(void)
197 {
198         unsigned int nr_cpus = bpf_num_possible_cpus();
199         struct datarec *array;
200
201         array = calloc(nr_cpus, sizeof(struct datarec));
202         if (!array) {
203                 fprintf(stderr, "Mem alloc error (nr_cpus:%u)\n", nr_cpus);
204                 exit(EXIT_FAIL_MEM);
205         }
206         return array;
207 }
208
209 static struct record *alloc_record_per_rxq(void)
210 {
211         unsigned int nr_rxqs = bpf_map__max_entries(rx_queue_index_map);
212         struct record *array;
213
214         array = calloc(nr_rxqs, sizeof(struct record));
215         if (!array) {
216                 fprintf(stderr, "Mem alloc error (nr_rxqs:%u)\n", nr_rxqs);
217                 exit(EXIT_FAIL_MEM);
218         }
219         return array;
220 }
221
222 static struct stats_record *alloc_stats_record(void)
223 {
224         unsigned int nr_rxqs = bpf_map__max_entries(rx_queue_index_map);
225         struct stats_record *rec;
226         int i;
227
228         rec = calloc(1, sizeof(struct stats_record));
229         if (!rec) {
230                 fprintf(stderr, "Mem alloc error\n");
231                 exit(EXIT_FAIL_MEM);
232         }
233         rec->rxq = alloc_record_per_rxq();
234         for (i = 0; i < nr_rxqs; i++)
235                 rec->rxq[i].cpu = alloc_record_per_cpu();
236
237         rec->stats.cpu = alloc_record_per_cpu();
238         return rec;
239 }
240
241 static void free_stats_record(struct stats_record *r)
242 {
243         unsigned int nr_rxqs = bpf_map__max_entries(rx_queue_index_map);
244         int i;
245
246         for (i = 0; i < nr_rxqs; i++)
247                 free(r->rxq[i].cpu);
248
249         free(r->rxq);
250         free(r->stats.cpu);
251         free(r);
252 }
253
254 static bool map_collect_percpu(int fd, __u32 key, struct record *rec)
255 {
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;
260         __u64 sum_issue = 0;
261         int i;
262
263         if ((bpf_map_lookup_elem(fd, &key, values)) != 0) {
264                 fprintf(stderr,
265                         "ERR: bpf_map_lookup_elem failed key:0x%X\n", key);
266                 return false;
267         }
268         /* Get time as close as possible to reading map contents */
269         rec->timestamp = gettime();
270
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;
277         }
278         rec->total.processed = sum_processed;
279         rec->total.issue     = sum_issue;
280         return true;
281 }
282
283 static void stats_collect(struct stats_record *rec)
284 {
285         int fd, i, max_rxqs;
286
287         fd = bpf_map__fd(stats_global_map);
288         map_collect_percpu(fd, 0, &rec->stats);
289
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]);
294 }
295
296 static double calc_period(struct record *r, struct record *p)
297 {
298         double period_ = 0;
299         __u64 period = 0;
300
301         period = r->timestamp - p->timestamp;
302         if (period > 0)
303                 period_ = ((double) period / NANOSEC_PER_SEC);
304
305         return period_;
306 }
307
308 static __u64 calc_pps(struct datarec *r, struct datarec *p, double period_)
309 {
310         __u64 packets = 0;
311         __u64 pps = 0;
312
313         if (period_ > 0) {
314                 packets = r->processed - p->processed;
315                 pps = packets / period_;
316         }
317         return pps;
318 }
319
320 static __u64 calc_errs_pps(struct datarec *r,
321                             struct datarec *p, double period_)
322 {
323         __u64 packets = 0;
324         __u64 pps = 0;
325
326         if (period_ > 0) {
327                 packets = r->issue - p->issue;
328                 pps = packets / period_;
329         }
330         return pps;
331 }
332
333 static void stats_print(struct stats_record *stats_rec,
334                         struct stats_record *stats_prev,
335                         int action, __u32 cfg_opt)
336 {
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;
341         double t;
342         int rxq;
343         int i;
344
345         /* Header */
346         printf("\nRunning XDP on dev:%s (ifindex:%d) action:%s options:%s\n",
347                ifname, ifindex, action2str(action), options2str(cfg_opt));
348
349         /* stats_global_map */
350         {
351                 char *fmt_rx = "%-15s %-7d %'-11.0f %'-10.0f %s\n";
352                 char *fm2_rx = "%-15s %-7s %'-11.0f\n";
353                 char *errstr = "";
354
355                 printf("%-15s %-7s %-11s %-11s\n",
356                        "XDP stats", "CPU", "pps", "issue-pps");
357
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];
364
365                         pps = calc_pps     (r, p, t);
366                         err = calc_errs_pps(r, p, t);
367                         if (err > 0)
368                                 errstr = "invalid-ifindex";
369                         if (pps > 0)
370                                 printf(fmt_rx, "XDP-RX CPU",
371                                         i, pps, err, errstr);
372                 }
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);
376         }
377
378         /* rx_queue_index_map */
379         printf("\n%-15s %-7s %-11s %-11s\n",
380                "RXQ stats", "RXQ:CPU", "pps", "issue-pps");
381
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";
385                 char *errstr = "";
386                 int rxq_ = rxq;
387
388                 /* Last RXQ in map catch overflows */
389                 if (rxq_ == nr_rxqs - 1)
390                         rxq_ = -1;
391
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];
398
399                         pps = calc_pps     (r, p, t);
400                         err = calc_errs_pps(r, p, t);
401                         if (err > 0) {
402                                 if (rxq_ == -1)
403                                         errstr = "map-overflow-RXQ";
404                                 else
405                                         errstr = "err";
406                         }
407                         if (pps > 0)
408                                 printf(fmt_rx, "rx_queue_index",
409                                        rxq_, i, pps, err, errstr);
410                 }
411                 pps  = calc_pps     (&rec->total, &prev->total, t);
412                 err  = calc_errs_pps(&rec->total, &prev->total, t);
413                 if (pps || err)
414                         printf(fm2_rx, "rx_queue_index", rxq_, "sum", pps, err);
415         }
416 }
417
418
419 /* Pointer swap trick */
420 static inline void swap(struct stats_record **a, struct stats_record **b)
421 {
422         struct stats_record *tmp;
423
424         tmp = *a;
425         *a = *b;
426         *b = tmp;
427 }
428
429 static void stats_poll(int interval, int action, __u32 cfg_opt)
430 {
431         struct stats_record *record, *prev;
432
433         record = alloc_stats_record();
434         prev   = alloc_stats_record();
435         stats_collect(record);
436
437         while (1) {
438                 swap(&prev, &record);
439                 stats_collect(record);
440                 stats_print(record, prev, action, cfg_opt);
441                 sleep(interval);
442         }
443
444         free_stats_record(record);
445         free_stats_record(prev);
446 }
447
448
449 int main(int argc, char **argv)
450 {
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;
459         struct bpf_map *map;
460         char filename[256];
461         int longindex = 0;
462         int interval = 2;
463         __u32 key = 0;
464
465
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;
469
470         snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]);
471
472         obj = bpf_object__open_file(filename, NULL);
473         if (libbpf_get_error(obj))
474                 return EXIT_FAIL;
475
476         prog = bpf_object__next_program(obj, NULL);
477         bpf_program__set_type(prog, BPF_PROG_TYPE_XDP);
478
479         err = bpf_object__load(obj);
480         if (err)
481                 return EXIT_FAIL;
482         prog_fd = bpf_program__fd(prog);
483
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");
489                 return EXIT_FAIL;
490         }
491         map_fd = bpf_map__fd(map);
492
493         if (!prog_fd) {
494                 fprintf(stderr, "ERR: bpf_prog_load_xattr: %s\n", strerror(errno));
495                 return EXIT_FAIL;
496         }
497
498         /* Parse commands line args */
499         while ((opt = getopt_long(argc, argv, "FhSrmzd:s:a:",
500                                   long_options, &longindex)) != -1) {
501                 switch (opt) {
502                 case 'd':
503                         if (strlen(optarg) >= IF_NAMESIZE) {
504                                 fprintf(stderr, "ERR: --dev name too long\n");
505                                 goto error;
506                         }
507                         ifname = (char *)&ifname_buf;
508                         strncpy(ifname, optarg, IF_NAMESIZE);
509                         ifindex = if_nametoindex(ifname);
510                         if (ifindex == 0) {
511                                 fprintf(stderr,
512                                         "ERR: --dev name unknown err(%d):%s\n",
513                                         errno, strerror(errno));
514                                 goto error;
515                         }
516                         break;
517                 case 's':
518                         interval = atoi(optarg);
519                         break;
520                 case 'S':
521                         xdp_flags |= XDP_FLAGS_SKB_MODE;
522                         break;
523                 case 'z':
524                         use_separators = false;
525                         break;
526                 case 'a':
527                         action_str = (char *)&action_str_buf;
528                         strncpy(action_str, optarg, XDP_ACTION_MAX_STRLEN);
529                         break;
530                 case 'r':
531                         cfg_options |= READ_MEM;
532                         break;
533                 case 'm':
534                         cfg_options |= SWAP_MAC;
535                         break;
536                 case 'F':
537                         xdp_flags &= ~XDP_FLAGS_UPDATE_IF_NOEXIST;
538                         break;
539                 case 'h':
540                 error:
541                 default:
542                         usage(argv);
543                         return EXIT_FAIL_OPTION;
544                 }
545         }
546
547         if (!(xdp_flags & XDP_FLAGS_SKB_MODE))
548                 xdp_flags |= XDP_FLAGS_DRV_MODE;
549
550         /* Required option */
551         if (ifindex == -1) {
552                 fprintf(stderr, "ERR: required option --dev missing\n");
553                 usage(argv);
554                 return EXIT_FAIL_OPTION;
555         }
556         cfg.ifindex = ifindex;
557
558         /* Parse action string */
559         if (action_str) {
560                 action = parse_xdp_action(action_str);
561                 if (action < 0) {
562                         fprintf(stderr, "ERR: Invalid XDP --action: %s\n",
563                                 action_str);
564                         list_xdp_actions();
565                         return EXIT_FAIL_OPTION;
566                 }
567         }
568         cfg.action = action;
569
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;
574
575         /* Trick to pretty printf with thousands separators use %' */
576         if (use_separators)
577                 setlocale(LC_NUMERIC, "en_US");
578
579         /* User-side setup ifindex in config_map */
580         err = bpf_map_update_elem(map_fd, &key, &cfg, 0);
581         if (err) {
582                 fprintf(stderr, "Store config failed (err:%d)\n", err);
583                 exit(EXIT_FAIL_BPF);
584         }
585
586         /* Remove XDP program when program is interrupted or killed */
587         signal(SIGINT, int_exit);
588         signal(SIGTERM, int_exit);
589
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;
593         }
594
595         err = bpf_obj_get_info_by_fd(prog_fd, &info, &info_len);
596         if (err) {
597                 printf("can't get prog info - %s\n", strerror(errno));
598                 return err;
599         }
600         prog_id = info.id;
601
602         stats_poll(interval, action, cfg_options);
603         return EXIT_OK;
604 }