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