GNU Linux-libre 4.19.263-gnu1
[releases.git] / tools / bpf / bpftool / common.c
1 /*
2  * Copyright (C) 2017-2018 Netronome Systems, Inc.
3  *
4  * This software is dual licensed under the GNU General License Version 2,
5  * June 1991 as shown in the file COPYING in the top-level directory of this
6  * source tree or the BSD 2-Clause License provided below.  You have the
7  * option to license this software under the complete terms of either license.
8  *
9  * The BSD 2-Clause License:
10  *
11  *     Redistribution and use in source and binary forms, with or
12  *     without modification, are permitted provided that the following
13  *     conditions are met:
14  *
15  *      1. Redistributions of source code must retain the above
16  *         copyright notice, this list of conditions and the following
17  *         disclaimer.
18  *
19  *      2. Redistributions in binary form must reproduce the above
20  *         copyright notice, this list of conditions and the following
21  *         disclaimer in the documentation and/or other materials
22  *         provided with the distribution.
23  *
24  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
27  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
28  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
29  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
30  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
31  * SOFTWARE.
32  */
33
34 #include <ctype.h>
35 #include <errno.h>
36 #include <fcntl.h>
37 #include <fts.h>
38 #include <libgen.h>
39 #include <mntent.h>
40 #include <stdbool.h>
41 #include <stdio.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <unistd.h>
45 #include <linux/limits.h>
46 #include <linux/magic.h>
47 #include <net/if.h>
48 #include <sys/mount.h>
49 #include <sys/stat.h>
50 #include <sys/types.h>
51 #include <sys/vfs.h>
52
53 #include <bpf.h>
54
55 #include "main.h"
56
57 #ifndef BPF_FS_MAGIC
58 #define BPF_FS_MAGIC            0xcafe4a11
59 #endif
60
61 void p_err(const char *fmt, ...)
62 {
63         va_list ap;
64
65         va_start(ap, fmt);
66         if (json_output) {
67                 jsonw_start_object(json_wtr);
68                 jsonw_name(json_wtr, "error");
69                 jsonw_vprintf_enquote(json_wtr, fmt, ap);
70                 jsonw_end_object(json_wtr);
71         } else {
72                 fprintf(stderr, "Error: ");
73                 vfprintf(stderr, fmt, ap);
74                 fprintf(stderr, "\n");
75         }
76         va_end(ap);
77 }
78
79 void p_info(const char *fmt, ...)
80 {
81         va_list ap;
82
83         if (json_output)
84                 return;
85
86         va_start(ap, fmt);
87         vfprintf(stderr, fmt, ap);
88         fprintf(stderr, "\n");
89         va_end(ap);
90 }
91
92 static bool is_bpffs(char *path)
93 {
94         struct statfs st_fs;
95
96         if (statfs(path, &st_fs) < 0)
97                 return false;
98
99         return (unsigned long)st_fs.f_type == BPF_FS_MAGIC;
100 }
101
102 static int mnt_bpffs(const char *target, char *buff, size_t bufflen)
103 {
104         bool bind_done = false;
105
106         while (mount("", target, "none", MS_PRIVATE | MS_REC, NULL)) {
107                 if (errno != EINVAL || bind_done) {
108                         snprintf(buff, bufflen,
109                                  "mount --make-private %s failed: %s",
110                                  target, strerror(errno));
111                         return -1;
112                 }
113
114                 if (mount(target, target, "none", MS_BIND, NULL)) {
115                         snprintf(buff, bufflen,
116                                  "mount --bind %s %s failed: %s",
117                                  target, target, strerror(errno));
118                         return -1;
119                 }
120
121                 bind_done = true;
122         }
123
124         if (mount("bpf", target, "bpf", 0, "mode=0700")) {
125                 snprintf(buff, bufflen, "mount -t bpf bpf %s failed: %s",
126                          target, strerror(errno));
127                 return -1;
128         }
129
130         return 0;
131 }
132
133 int open_obj_pinned(char *path, bool quiet)
134 {
135         int fd;
136
137         fd = bpf_obj_get(path);
138         if (fd < 0) {
139                 if (!quiet)
140                         p_err("bpf obj get (%s): %s", path,
141                               errno == EACCES && !is_bpffs(dirname(path)) ?
142                             "directory not in bpf file system (bpffs)" :
143                             strerror(errno));
144                 return -1;
145         }
146
147         return fd;
148 }
149
150 int open_obj_pinned_any(char *path, enum bpf_obj_type exp_type)
151 {
152         enum bpf_obj_type type;
153         int fd;
154
155         fd = open_obj_pinned(path, false);
156         if (fd < 0)
157                 return -1;
158
159         type = get_fd_type(fd);
160         if (type < 0) {
161                 close(fd);
162                 return type;
163         }
164         if (type != exp_type) {
165                 p_err("incorrect object type: %s", get_fd_type_name(type));
166                 close(fd);
167                 return -1;
168         }
169
170         return fd;
171 }
172
173 int do_pin_fd(int fd, const char *name)
174 {
175         char err_str[ERR_MAX_LEN];
176         char *file;
177         char *dir;
178         int err = 0;
179
180         err = bpf_obj_pin(fd, name);
181         if (!err)
182                 goto out;
183
184         file = malloc(strlen(name) + 1);
185         if (!file) {
186                 p_err("mem alloc failed");
187                 return -1;
188         }
189
190         strcpy(file, name);
191         dir = dirname(file);
192
193         if (errno != EPERM || is_bpffs(dir)) {
194                 p_err("can't pin the object (%s): %s", name, strerror(errno));
195                 goto out_free;
196         }
197
198         /* Attempt to mount bpffs, then retry pinning. */
199         err = mnt_bpffs(dir, err_str, ERR_MAX_LEN);
200         if (!err) {
201                 err = bpf_obj_pin(fd, name);
202                 if (err)
203                         p_err("can't pin the object (%s): %s", name,
204                               strerror(errno));
205         } else {
206                 err_str[ERR_MAX_LEN - 1] = '\0';
207                 p_err("can't mount BPF file system to pin the object (%s): %s",
208                       name, err_str);
209         }
210
211 out_free:
212         free(file);
213 out:
214         return err;
215 }
216
217 int do_pin_any(int argc, char **argv, int (*get_fd_by_id)(__u32))
218 {
219         unsigned int id;
220         char *endptr;
221         int err;
222         int fd;
223
224         if (argc < 3) {
225                 p_err("too few arguments, id ID and FILE path is required");
226                 return -1;
227         } else if (argc > 3) {
228                 p_err("too many arguments");
229                 return -1;
230         }
231
232         if (!is_prefix(*argv, "id")) {
233                 p_err("expected 'id' got %s", *argv);
234                 return -1;
235         }
236         NEXT_ARG();
237
238         id = strtoul(*argv, &endptr, 0);
239         if (*endptr) {
240                 p_err("can't parse %s as ID", *argv);
241                 return -1;
242         }
243         NEXT_ARG();
244
245         fd = get_fd_by_id(id);
246         if (fd < 0) {
247                 p_err("can't open object by id (%u): %s", id, strerror(errno));
248                 return -1;
249         }
250
251         err = do_pin_fd(fd, *argv);
252
253         close(fd);
254         return err;
255 }
256
257 const char *get_fd_type_name(enum bpf_obj_type type)
258 {
259         static const char * const names[] = {
260                 [BPF_OBJ_UNKNOWN]       = "unknown",
261                 [BPF_OBJ_PROG]          = "prog",
262                 [BPF_OBJ_MAP]           = "map",
263         };
264
265         if (type < 0 || type >= ARRAY_SIZE(names) || !names[type])
266                 return names[BPF_OBJ_UNKNOWN];
267
268         return names[type];
269 }
270
271 int get_fd_type(int fd)
272 {
273         char path[PATH_MAX];
274         char buf[512];
275         ssize_t n;
276
277         snprintf(path, sizeof(path), "/proc/%d/fd/%d", getpid(), fd);
278
279         n = readlink(path, buf, sizeof(buf));
280         if (n < 0) {
281                 p_err("can't read link type: %s", strerror(errno));
282                 return -1;
283         }
284         if (n == sizeof(path)) {
285                 p_err("can't read link type: path too long!");
286                 return -1;
287         }
288
289         if (strstr(buf, "bpf-map"))
290                 return BPF_OBJ_MAP;
291         else if (strstr(buf, "bpf-prog"))
292                 return BPF_OBJ_PROG;
293
294         return BPF_OBJ_UNKNOWN;
295 }
296
297 char *get_fdinfo(int fd, const char *key)
298 {
299         char path[PATH_MAX];
300         char *line = NULL;
301         size_t line_n = 0;
302         ssize_t n;
303         FILE *fdi;
304
305         snprintf(path, sizeof(path), "/proc/%d/fdinfo/%d", getpid(), fd);
306
307         fdi = fopen(path, "r");
308         if (!fdi) {
309                 p_err("can't open fdinfo: %s", strerror(errno));
310                 return NULL;
311         }
312
313         while ((n = getline(&line, &line_n, fdi)) > 0) {
314                 char *value;
315                 int len;
316
317                 if (!strstr(line, key))
318                         continue;
319
320                 fclose(fdi);
321
322                 value = strchr(line, '\t');
323                 if (!value || !value[1]) {
324                         p_err("malformed fdinfo!?");
325                         free(line);
326                         return NULL;
327                 }
328                 value++;
329
330                 len = strlen(value);
331                 memmove(line, value, len);
332                 line[len - 1] = '\0';
333
334                 return line;
335         }
336
337         p_err("key '%s' not found in fdinfo", key);
338         free(line);
339         fclose(fdi);
340         return NULL;
341 }
342
343 void print_data_json(uint8_t *data, size_t len)
344 {
345         unsigned int i;
346
347         jsonw_start_array(json_wtr);
348         for (i = 0; i < len; i++)
349                 jsonw_printf(json_wtr, "%d", data[i]);
350         jsonw_end_array(json_wtr);
351 }
352
353 void print_hex_data_json(uint8_t *data, size_t len)
354 {
355         unsigned int i;
356
357         jsonw_start_array(json_wtr);
358         for (i = 0; i < len; i++)
359                 jsonw_printf(json_wtr, "\"0x%02hhx\"", data[i]);
360         jsonw_end_array(json_wtr);
361 }
362
363 int build_pinned_obj_table(struct pinned_obj_table *tab,
364                            enum bpf_obj_type type)
365 {
366         struct bpf_prog_info pinned_info = {};
367         struct pinned_obj *obj_node = NULL;
368         __u32 len = sizeof(pinned_info);
369         struct mntent *mntent = NULL;
370         enum bpf_obj_type objtype;
371         FILE *mntfile = NULL;
372         FTSENT *ftse = NULL;
373         FTS *fts = NULL;
374         int fd, err;
375
376         mntfile = setmntent("/proc/mounts", "r");
377         if (!mntfile)
378                 return -1;
379
380         while ((mntent = getmntent(mntfile))) {
381                 char *path[] = { mntent->mnt_dir, NULL };
382
383                 if (strncmp(mntent->mnt_type, "bpf", 3) != 0)
384                         continue;
385
386                 fts = fts_open(path, 0, NULL);
387                 if (!fts)
388                         continue;
389
390                 while ((ftse = fts_read(fts))) {
391                         if (!(ftse->fts_info & FTS_F))
392                                 continue;
393                         fd = open_obj_pinned(ftse->fts_path, true);
394                         if (fd < 0)
395                                 continue;
396
397                         objtype = get_fd_type(fd);
398                         if (objtype != type) {
399                                 close(fd);
400                                 continue;
401                         }
402                         memset(&pinned_info, 0, sizeof(pinned_info));
403                         err = bpf_obj_get_info_by_fd(fd, &pinned_info, &len);
404                         if (err) {
405                                 close(fd);
406                                 continue;
407                         }
408
409                         obj_node = malloc(sizeof(*obj_node));
410                         if (!obj_node) {
411                                 close(fd);
412                                 fts_close(fts);
413                                 fclose(mntfile);
414                                 return -1;
415                         }
416
417                         memset(obj_node, 0, sizeof(*obj_node));
418                         obj_node->id = pinned_info.id;
419                         obj_node->path = strdup(ftse->fts_path);
420                         hash_add(tab->table, &obj_node->hash, obj_node->id);
421
422                         close(fd);
423                 }
424                 fts_close(fts);
425         }
426         fclose(mntfile);
427         return 0;
428 }
429
430 void delete_pinned_obj_table(struct pinned_obj_table *tab)
431 {
432         struct pinned_obj *obj;
433         struct hlist_node *tmp;
434         unsigned int bkt;
435
436         hash_for_each_safe(tab->table, bkt, tmp, obj, hash) {
437                 hash_del(&obj->hash);
438                 free(obj->path);
439                 free(obj);
440         }
441 }
442
443 unsigned int get_page_size(void)
444 {
445         static int result;
446
447         if (!result)
448                 result = getpagesize();
449         return result;
450 }
451
452 unsigned int get_possible_cpus(void)
453 {
454         static unsigned int result;
455         char buf[128];
456         long int n;
457         char *ptr;
458         int fd;
459
460         if (result)
461                 return result;
462
463         fd = open("/sys/devices/system/cpu/possible", O_RDONLY);
464         if (fd < 0) {
465                 p_err("can't open sysfs possible cpus");
466                 exit(-1);
467         }
468
469         n = read(fd, buf, sizeof(buf));
470         if (n < 2) {
471                 p_err("can't read sysfs possible cpus");
472                 exit(-1);
473         }
474         close(fd);
475
476         if (n == sizeof(buf)) {
477                 p_err("read sysfs possible cpus overflow");
478                 exit(-1);
479         }
480
481         ptr = buf;
482         n = 0;
483         while (*ptr && *ptr != '\n') {
484                 unsigned int a, b;
485
486                 if (sscanf(ptr, "%u-%u", &a, &b) == 2) {
487                         n += b - a + 1;
488
489                         ptr = strchr(ptr, '-') + 1;
490                 } else if (sscanf(ptr, "%u", &a) == 1) {
491                         n++;
492                 } else {
493                         assert(0);
494                 }
495
496                 while (isdigit(*ptr))
497                         ptr++;
498                 if (*ptr == ',')
499                         ptr++;
500         }
501
502         result = n;
503
504         return result;
505 }
506
507 static char *
508 ifindex_to_name_ns(__u32 ifindex, __u32 ns_dev, __u32 ns_ino, char *buf)
509 {
510         struct stat st;
511         int err;
512
513         err = stat("/proc/self/ns/net", &st);
514         if (err) {
515                 p_err("Can't stat /proc/self: %s", strerror(errno));
516                 return NULL;
517         }
518
519         if (st.st_dev != ns_dev || st.st_ino != ns_ino)
520                 return NULL;
521
522         return if_indextoname(ifindex, buf);
523 }
524
525 static int read_sysfs_hex_int(char *path)
526 {
527         char vendor_id_buf[8];
528         int len;
529         int fd;
530
531         fd = open(path, O_RDONLY);
532         if (fd < 0) {
533                 p_err("Can't open %s: %s", path, strerror(errno));
534                 return -1;
535         }
536
537         len = read(fd, vendor_id_buf, sizeof(vendor_id_buf));
538         close(fd);
539         if (len < 0) {
540                 p_err("Can't read %s: %s", path, strerror(errno));
541                 return -1;
542         }
543         if (len >= (int)sizeof(vendor_id_buf)) {
544                 p_err("Value in %s too long", path);
545                 return -1;
546         }
547
548         vendor_id_buf[len] = 0;
549
550         return strtol(vendor_id_buf, NULL, 0);
551 }
552
553 static int read_sysfs_netdev_hex_int(char *devname, const char *entry_name)
554 {
555         char full_path[64];
556
557         snprintf(full_path, sizeof(full_path), "/sys/class/net/%s/device/%s",
558                  devname, entry_name);
559
560         return read_sysfs_hex_int(full_path);
561 }
562
563 const char *ifindex_to_bfd_name_ns(__u32 ifindex, __u64 ns_dev, __u64 ns_ino)
564 {
565         char devname[IF_NAMESIZE];
566         int vendor_id;
567         int device_id;
568
569         if (!ifindex_to_name_ns(ifindex, ns_dev, ns_ino, devname)) {
570                 p_err("Can't get net device name for ifindex %d: %s", ifindex,
571                       strerror(errno));
572                 return NULL;
573         }
574
575         vendor_id = read_sysfs_netdev_hex_int(devname, "vendor");
576         if (vendor_id < 0) {
577                 p_err("Can't get device vendor id for %s", devname);
578                 return NULL;
579         }
580
581         switch (vendor_id) {
582         case 0x19ee:
583                 device_id = read_sysfs_netdev_hex_int(devname, "device");
584                 if (device_id != 0x4000 &&
585                     device_id != 0x6000 &&
586                     device_id != 0x6003)
587                         p_info("Unknown NFP device ID, assuming it is NFP-6xxx arch");
588                 return "NFP-6xxx";
589         default:
590                 p_err("Can't get bfd arch name for device vendor id 0x%04x",
591                       vendor_id);
592                 return NULL;
593         }
594 }
595
596 void print_dev_plain(__u32 ifindex, __u64 ns_dev, __u64 ns_inode)
597 {
598         char name[IF_NAMESIZE];
599
600         if (!ifindex)
601                 return;
602
603         printf(" dev ");
604         if (ifindex_to_name_ns(ifindex, ns_dev, ns_inode, name))
605                 printf("%s", name);
606         else
607                 printf("ifindex %u ns_dev %llu ns_ino %llu",
608                        ifindex, ns_dev, ns_inode);
609 }
610
611 void print_dev_json(__u32 ifindex, __u64 ns_dev, __u64 ns_inode)
612 {
613         char name[IF_NAMESIZE];
614
615         if (!ifindex)
616                 return;
617
618         jsonw_name(json_wtr, "dev");
619         jsonw_start_object(json_wtr);
620         jsonw_uint_field(json_wtr, "ifindex", ifindex);
621         jsonw_uint_field(json_wtr, "ns_dev", ns_dev);
622         jsonw_uint_field(json_wtr, "ns_inode", ns_inode);
623         if (ifindex_to_name_ns(ifindex, ns_dev, ns_inode, name))
624                 jsonw_string_field(json_wtr, "ifname", name);
625         jsonw_end_object(json_wtr);
626 }