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