1 // SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)
2 /* Copyright (C) 2017-2018 Netronome Systems, Inc. */
19 #include <sys/mount.h>
20 #include <sys/resource.h>
24 #include <linux/filter.h>
25 #include <linux/limits.h>
26 #include <linux/magic.h>
27 #include <linux/unistd.h>
30 #include <bpf/hashmap.h>
31 #include <bpf/libbpf.h> /* libbpf_num_possible_cpus */
37 #define BPF_FS_MAGIC 0xcafe4a11
40 void p_err(const char *fmt, ...)
46 jsonw_start_object(json_wtr);
47 jsonw_name(json_wtr, "error");
48 jsonw_vprintf_enquote(json_wtr, fmt, ap);
49 jsonw_end_object(json_wtr);
51 fprintf(stderr, "Error: ");
52 vfprintf(stderr, fmt, ap);
53 fprintf(stderr, "\n");
58 void p_info(const char *fmt, ...)
66 vfprintf(stderr, fmt, ap);
67 fprintf(stderr, "\n");
71 static bool is_bpffs(const char *path)
75 if (statfs(path, &st_fs) < 0)
78 return (unsigned long)st_fs.f_type == BPF_FS_MAGIC;
81 /* Probe whether kernel switched from memlock-based (RLIMIT_MEMLOCK) to
82 * memcg-based memory accounting for BPF maps and programs. This was done in
83 * commit 97306be45fbe ("Merge branch 'switch to memcg-based memory
84 * accounting'"), in Linux 5.11.
86 * Libbpf also offers to probe for memcg-based accounting vs rlimit, but does
87 * so by checking for the availability of a given BPF helper and this has
88 * failed on some kernels with backports in the past, see commit 6b4384ff1088
89 * ("Revert "bpftool: Use libbpf 1.0 API mode instead of RLIMIT_MEMLOCK"").
90 * Instead, we can probe by lowering the process-based rlimit to 0, trying to
91 * load a BPF object, and resetting the rlimit. If the load succeeds then
92 * memcg-based accounting is supported.
94 * This would be too dangerous to do in the library, because multithreaded
95 * applications might attempt to load items while the rlimit is at 0. Given
96 * that bpftool is single-threaded, this is fine to do here.
98 static bool known_to_need_rlimit(void)
100 struct rlimit rlim_init, rlim_cur_zero = {};
101 struct bpf_insn insns[] = {
102 BPF_MOV64_IMM(BPF_REG_0, 0),
105 size_t insn_cnt = ARRAY_SIZE(insns);
109 memset(&attr, 0, sizeof(attr));
110 attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
111 attr.insns = ptr_to_u64(insns);
112 attr.insn_cnt = insn_cnt;
113 attr.license = ptr_to_u64("GPL");
115 if (getrlimit(RLIMIT_MEMLOCK, &rlim_init))
118 /* Drop the soft limit to zero. We maintain the hard limit to its
119 * current value, because lowering it would be a permanent operation
120 * for unprivileged users.
122 rlim_cur_zero.rlim_max = rlim_init.rlim_max;
123 if (setrlimit(RLIMIT_MEMLOCK, &rlim_cur_zero))
126 /* Do not use bpf_prog_load() from libbpf here, because it calls
127 * bump_rlimit_memlock(), interfering with the current probe.
129 prog_fd = syscall(__NR_bpf, BPF_PROG_LOAD, &attr, sizeof(attr));
132 /* reset soft rlimit to its initial value */
133 setrlimit(RLIMIT_MEMLOCK, &rlim_init);
142 void set_max_rlimit(void)
144 struct rlimit rinf = { RLIM_INFINITY, RLIM_INFINITY };
146 if (known_to_need_rlimit())
147 setrlimit(RLIMIT_MEMLOCK, &rinf);
151 mnt_fs(const char *target, const char *type, char *buff, size_t bufflen)
153 bool bind_done = false;
155 while (mount("", target, "none", MS_PRIVATE | MS_REC, NULL)) {
156 if (errno != EINVAL || bind_done) {
157 snprintf(buff, bufflen,
158 "mount --make-private %s failed: %s",
159 target, strerror(errno));
163 if (mount(target, target, "none", MS_BIND, NULL)) {
164 snprintf(buff, bufflen,
165 "mount --bind %s %s failed: %s",
166 target, target, strerror(errno));
173 if (mount(type, target, type, 0, "mode=0700")) {
174 snprintf(buff, bufflen, "mount -t %s %s %s failed: %s",
175 type, type, target, strerror(errno));
182 int mount_tracefs(const char *target)
184 char err_str[ERR_MAX_LEN];
187 err = mnt_fs(target, "tracefs", err_str, ERR_MAX_LEN);
189 err_str[ERR_MAX_LEN - 1] = '\0';
190 p_err("can't mount tracefs: %s", err_str);
196 int open_obj_pinned(const char *path, bool quiet)
201 pname = strdup(path);
204 p_err("mem alloc failed");
208 fd = bpf_obj_get(pname);
211 p_err("bpf obj get (%s): %s", pname,
212 errno == EACCES && !is_bpffs(dirname(pname)) ?
213 "directory not in bpf file system (bpffs)" :
224 int open_obj_pinned_any(const char *path, enum bpf_obj_type exp_type)
226 enum bpf_obj_type type;
229 fd = open_obj_pinned(path, false);
233 type = get_fd_type(fd);
238 if (type != exp_type) {
239 p_err("incorrect object type: %s", get_fd_type_name(type));
247 int mount_bpffs_for_pin(const char *name, bool is_dir)
249 char err_str[ERR_MAX_LEN];
254 if (is_dir && is_bpffs(name))
257 file = malloc(strlen(name) + 1);
259 p_err("mem alloc failed");
267 /* nothing to do if already mounted */
271 p_err("no BPF file system found, not mounting it due to --nomount option");
276 err = mnt_fs(dir, "bpf", err_str, ERR_MAX_LEN);
278 err_str[ERR_MAX_LEN - 1] = '\0';
279 p_err("can't mount BPF file system to pin the object (%s): %s",
288 int do_pin_fd(int fd, const char *name)
292 err = mount_bpffs_for_pin(name, false);
296 err = bpf_obj_pin(fd, name);
298 p_err("can't pin the object (%s): %s", name, strerror(errno));
303 int do_pin_any(int argc, char **argv, int (*get_fd)(int *, char ***))
311 fd = get_fd(&argc, &argv);
315 err = do_pin_fd(fd, *argv);
321 const char *get_fd_type_name(enum bpf_obj_type type)
323 static const char * const names[] = {
324 [BPF_OBJ_UNKNOWN] = "unknown",
325 [BPF_OBJ_PROG] = "prog",
326 [BPF_OBJ_MAP] = "map",
327 [BPF_OBJ_LINK] = "link",
330 if (type < 0 || type >= ARRAY_SIZE(names) || !names[type])
331 return names[BPF_OBJ_UNKNOWN];
336 void get_prog_full_name(const struct bpf_prog_info *prog_info, int prog_fd,
337 char *name_buff, size_t buff_len)
339 const char *prog_name = prog_info->name;
340 const struct btf_type *func_type;
341 const struct bpf_func_info finfo = {};
342 struct bpf_prog_info info = {};
343 __u32 info_len = sizeof(info);
344 struct btf *prog_btf = NULL;
346 if (buff_len <= BPF_OBJ_NAME_LEN ||
347 strlen(prog_info->name) < BPF_OBJ_NAME_LEN - 1)
350 if (!prog_info->btf_id || prog_info->nr_func_info == 0)
353 info.nr_func_info = 1;
354 info.func_info_rec_size = prog_info->func_info_rec_size;
355 if (info.func_info_rec_size > sizeof(finfo))
356 info.func_info_rec_size = sizeof(finfo);
357 info.func_info = ptr_to_u64(&finfo);
359 if (bpf_prog_get_info_by_fd(prog_fd, &info, &info_len))
362 prog_btf = btf__load_from_kernel_by_id(info.btf_id);
366 func_type = btf__type_by_id(prog_btf, finfo.type_id);
367 if (!func_type || !btf_is_func(func_type))
370 prog_name = btf__name_by_offset(prog_btf, func_type->name_off);
373 snprintf(name_buff, buff_len, "%s", prog_name);
379 int get_fd_type(int fd)
385 snprintf(path, sizeof(path), "/proc/self/fd/%d", fd);
387 n = readlink(path, buf, sizeof(buf));
389 p_err("can't read link type: %s", strerror(errno));
392 if (n == sizeof(path)) {
393 p_err("can't read link type: path too long!");
397 if (strstr(buf, "bpf-map"))
399 else if (strstr(buf, "bpf-prog"))
401 else if (strstr(buf, "bpf-link"))
404 return BPF_OBJ_UNKNOWN;
407 char *get_fdinfo(int fd, const char *key)
415 snprintf(path, sizeof(path), "/proc/self/fdinfo/%d", fd);
417 fdi = fopen(path, "r");
421 while ((n = getline(&line, &line_n, fdi)) > 0) {
425 if (!strstr(line, key))
430 value = strchr(line, '\t');
431 if (!value || !value[1]) {
438 memmove(line, value, len);
439 line[len - 1] = '\0';
449 void print_data_json(uint8_t *data, size_t len)
453 jsonw_start_array(json_wtr);
454 for (i = 0; i < len; i++)
455 jsonw_printf(json_wtr, "%d", data[i]);
456 jsonw_end_array(json_wtr);
459 void print_hex_data_json(uint8_t *data, size_t len)
463 jsonw_start_array(json_wtr);
464 for (i = 0; i < len; i++)
465 jsonw_printf(json_wtr, "\"0x%02hhx\"", data[i]);
466 jsonw_end_array(json_wtr);
469 /* extra params for nftw cb */
470 static struct hashmap *build_fn_table;
471 static enum bpf_obj_type build_fn_type;
473 static int do_build_table_cb(const char *fpath, const struct stat *sb,
474 int typeflag, struct FTW *ftwbuf)
476 struct bpf_prog_info pinned_info;
477 __u32 len = sizeof(pinned_info);
478 enum bpf_obj_type objtype;
482 if (typeflag != FTW_F)
485 fd = open_obj_pinned(fpath, true);
489 objtype = get_fd_type(fd);
490 if (objtype != build_fn_type)
493 memset(&pinned_info, 0, sizeof(pinned_info));
494 if (bpf_prog_get_info_by_fd(fd, &pinned_info, &len))
497 path = strdup(fpath);
503 err = hashmap__append(build_fn_table, pinned_info.id, path);
505 p_err("failed to append entry to hashmap for ID %u, path '%s': %s",
506 pinned_info.id, path, strerror(errno));
517 int build_pinned_obj_table(struct hashmap *tab,
518 enum bpf_obj_type type)
520 struct mntent *mntent = NULL;
521 FILE *mntfile = NULL;
522 int flags = FTW_PHYS;
526 mntfile = setmntent("/proc/mounts", "r");
530 build_fn_table = tab;
531 build_fn_type = type;
533 while ((mntent = getmntent(mntfile))) {
534 char *path = mntent->mnt_dir;
536 if (strncmp(mntent->mnt_type, "bpf", 3) != 0)
538 err = nftw(path, do_build_table_cb, nopenfd, flags);
546 void delete_pinned_obj_table(struct hashmap *map)
548 struct hashmap_entry *entry;
554 hashmap__for_each_entry(map, entry, bkt)
560 unsigned int get_page_size(void)
565 result = getpagesize();
569 unsigned int get_possible_cpus(void)
571 int cpus = libbpf_num_possible_cpus();
574 p_err("Can't get # of possible cpus: %s", strerror(-cpus));
581 ifindex_to_name_ns(__u32 ifindex, __u32 ns_dev, __u32 ns_ino, char *buf)
586 err = stat("/proc/self/ns/net", &st);
588 p_err("Can't stat /proc/self: %s", strerror(errno));
592 if (st.st_dev != ns_dev || st.st_ino != ns_ino)
595 return if_indextoname(ifindex, buf);
598 static int read_sysfs_hex_int(char *path)
600 char vendor_id_buf[8];
604 fd = open(path, O_RDONLY);
606 p_err("Can't open %s: %s", path, strerror(errno));
610 len = read(fd, vendor_id_buf, sizeof(vendor_id_buf));
613 p_err("Can't read %s: %s", path, strerror(errno));
616 if (len >= (int)sizeof(vendor_id_buf)) {
617 p_err("Value in %s too long", path);
621 vendor_id_buf[len] = 0;
623 return strtol(vendor_id_buf, NULL, 0);
626 static int read_sysfs_netdev_hex_int(char *devname, const char *entry_name)
630 snprintf(full_path, sizeof(full_path), "/sys/class/net/%s/device/%s",
631 devname, entry_name);
633 return read_sysfs_hex_int(full_path);
637 ifindex_to_arch(__u32 ifindex, __u64 ns_dev, __u64 ns_ino, const char **opt)
639 __maybe_unused int device_id;
640 char devname[IF_NAMESIZE];
643 if (!ifindex_to_name_ns(ifindex, ns_dev, ns_ino, devname)) {
644 p_err("Can't get net device name for ifindex %d: %s", ifindex,
649 vendor_id = read_sysfs_netdev_hex_int(devname, "vendor");
651 p_err("Can't get device vendor id for %s", devname);
656 #ifdef HAVE_LIBBFD_SUPPORT
658 device_id = read_sysfs_netdev_hex_int(devname, "device");
659 if (device_id != 0x4000 &&
660 device_id != 0x6000 &&
662 p_info("Unknown NFP device ID, assuming it is NFP-6xxx arch");
665 #endif /* HAVE_LIBBFD_SUPPORT */
666 /* No NFP support in LLVM, we have no valid triple to return. */
668 p_err("Can't get arch name for device vendor id 0x%04x",
674 void print_dev_plain(__u32 ifindex, __u64 ns_dev, __u64 ns_inode)
676 char name[IF_NAMESIZE];
681 printf(" offloaded_to ");
682 if (ifindex_to_name_ns(ifindex, ns_dev, ns_inode, name))
685 printf("ifindex %u ns_dev %llu ns_ino %llu",
686 ifindex, ns_dev, ns_inode);
689 void print_dev_json(__u32 ifindex, __u64 ns_dev, __u64 ns_inode)
691 char name[IF_NAMESIZE];
696 jsonw_name(json_wtr, "dev");
697 jsonw_start_object(json_wtr);
698 jsonw_uint_field(json_wtr, "ifindex", ifindex);
699 jsonw_uint_field(json_wtr, "ns_dev", ns_dev);
700 jsonw_uint_field(json_wtr, "ns_inode", ns_inode);
701 if (ifindex_to_name_ns(ifindex, ns_dev, ns_inode, name))
702 jsonw_string_field(json_wtr, "ifname", name);
703 jsonw_end_object(json_wtr);
706 int parse_u32_arg(int *argc, char ***argv, __u32 *val, const char *what)
713 p_err("%s already specified", what);
717 *val = strtoul(**argv, &endptr, 0);
719 p_err("can't parse %s as %s", **argv, what);
728 print_all_levels(__maybe_unused enum libbpf_print_level level,
729 const char *format, va_list args)
731 return vfprintf(stderr, format, args);
734 static int prog_fd_by_nametag(void *nametag, int **fds, bool tag)
736 char prog_name[MAX_PROG_FULL_NAME];
743 struct bpf_prog_info info = {};
744 __u32 len = sizeof(info);
746 err = bpf_prog_get_next_id(id, &id);
748 if (errno != ENOENT) {
749 p_err("%s", strerror(errno));
755 fd = bpf_prog_get_fd_by_id(id);
757 p_err("can't get prog by id (%u): %s",
758 id, strerror(errno));
762 err = bpf_prog_get_info_by_fd(fd, &info, &len);
764 p_err("can't get prog info (%u): %s",
765 id, strerror(errno));
769 if (tag && memcmp(nametag, info.tag, BPF_TAG_SIZE)) {
775 get_prog_full_name(&info, fd, prog_name,
777 if (strncmp(nametag, prog_name, sizeof(prog_name))) {
784 tmp = realloc(*fds, (nb_fds + 1) * sizeof(int));
786 p_err("failed to realloc");
791 (*fds)[nb_fds++] = fd;
797 while (--nb_fds >= 0)
798 close((*fds)[nb_fds]);
802 int prog_parse_fds(int *argc, char ***argv, int **fds)
804 if (is_prefix(**argv, "id")) {
810 id = strtoul(**argv, &endptr, 0);
812 p_err("can't parse %s as ID", **argv);
817 (*fds)[0] = bpf_prog_get_fd_by_id(id);
819 p_err("get by id (%u): %s", id, strerror(errno));
823 } else if (is_prefix(**argv, "tag")) {
824 unsigned char tag[BPF_TAG_SIZE];
828 if (sscanf(**argv, BPF_TAG_FMT, tag, tag + 1, tag + 2,
829 tag + 3, tag + 4, tag + 5, tag + 6, tag + 7)
831 p_err("can't parse tag");
836 return prog_fd_by_nametag(tag, fds, true);
837 } else if (is_prefix(**argv, "name")) {
843 if (strlen(name) > MAX_PROG_FULL_NAME - 1) {
844 p_err("can't parse name");
849 return prog_fd_by_nametag(name, fds, false);
850 } else if (is_prefix(**argv, "pinned")) {
858 (*fds)[0] = open_obj_pinned_any(path, BPF_OBJ_PROG);
864 p_err("expected 'id', 'tag', 'name' or 'pinned', got: '%s'?", **argv);
868 int prog_parse_fd(int *argc, char ***argv)
873 fds = malloc(sizeof(int));
875 p_err("mem alloc failed");
878 nb_fds = prog_parse_fds(argc, argv, &fds);
881 p_err("several programs match this handle");
895 static int map_fd_by_name(char *name, int **fds)
903 struct bpf_map_info info = {};
904 __u32 len = sizeof(info);
906 err = bpf_map_get_next_id(id, &id);
908 if (errno != ENOENT) {
909 p_err("%s", strerror(errno));
915 fd = bpf_map_get_fd_by_id(id);
917 p_err("can't get map by id (%u): %s",
918 id, strerror(errno));
922 err = bpf_map_get_info_by_fd(fd, &info, &len);
924 p_err("can't get map info (%u): %s",
925 id, strerror(errno));
929 if (strncmp(name, info.name, BPF_OBJ_NAME_LEN)) {
935 tmp = realloc(*fds, (nb_fds + 1) * sizeof(int));
937 p_err("failed to realloc");
942 (*fds)[nb_fds++] = fd;
948 while (--nb_fds >= 0)
949 close((*fds)[nb_fds]);
953 int map_parse_fds(int *argc, char ***argv, int **fds)
955 if (is_prefix(**argv, "id")) {
961 id = strtoul(**argv, &endptr, 0);
963 p_err("can't parse %s as ID", **argv);
968 (*fds)[0] = bpf_map_get_fd_by_id(id);
970 p_err("get map by id (%u): %s", id, strerror(errno));
974 } else if (is_prefix(**argv, "name")) {
980 if (strlen(name) > BPF_OBJ_NAME_LEN - 1) {
981 p_err("can't parse name");
986 return map_fd_by_name(name, fds);
987 } else if (is_prefix(**argv, "pinned")) {
995 (*fds)[0] = open_obj_pinned_any(path, BPF_OBJ_MAP);
1001 p_err("expected 'id', 'name' or 'pinned', got: '%s'?", **argv);
1005 int map_parse_fd(int *argc, char ***argv)
1010 fds = malloc(sizeof(int));
1012 p_err("mem alloc failed");
1015 nb_fds = map_parse_fds(argc, argv, &fds);
1018 p_err("several maps match this handle");
1032 int map_parse_fd_and_info(int *argc, char ***argv, struct bpf_map_info *info,
1038 fd = map_parse_fd(argc, argv);
1042 err = bpf_map_get_info_by_fd(fd, info, info_len);
1044 p_err("can't get map info: %s", strerror(errno));
1052 size_t hash_fn_for_key_as_id(long key, void *ctx)
1057 bool equal_fn_for_key_as_id(long k1, long k2, void *ctx)
1062 const char *bpf_attach_type_input_str(enum bpf_attach_type t)
1065 case BPF_CGROUP_INET_INGRESS: return "ingress";
1066 case BPF_CGROUP_INET_EGRESS: return "egress";
1067 case BPF_CGROUP_INET_SOCK_CREATE: return "sock_create";
1068 case BPF_CGROUP_INET_SOCK_RELEASE: return "sock_release";
1069 case BPF_CGROUP_SOCK_OPS: return "sock_ops";
1070 case BPF_CGROUP_DEVICE: return "device";
1071 case BPF_CGROUP_INET4_BIND: return "bind4";
1072 case BPF_CGROUP_INET6_BIND: return "bind6";
1073 case BPF_CGROUP_INET4_CONNECT: return "connect4";
1074 case BPF_CGROUP_INET6_CONNECT: return "connect6";
1075 case BPF_CGROUP_INET4_POST_BIND: return "post_bind4";
1076 case BPF_CGROUP_INET6_POST_BIND: return "post_bind6";
1077 case BPF_CGROUP_INET4_GETPEERNAME: return "getpeername4";
1078 case BPF_CGROUP_INET6_GETPEERNAME: return "getpeername6";
1079 case BPF_CGROUP_INET4_GETSOCKNAME: return "getsockname4";
1080 case BPF_CGROUP_INET6_GETSOCKNAME: return "getsockname6";
1081 case BPF_CGROUP_UDP4_SENDMSG: return "sendmsg4";
1082 case BPF_CGROUP_UDP6_SENDMSG: return "sendmsg6";
1083 case BPF_CGROUP_SYSCTL: return "sysctl";
1084 case BPF_CGROUP_UDP4_RECVMSG: return "recvmsg4";
1085 case BPF_CGROUP_UDP6_RECVMSG: return "recvmsg6";
1086 case BPF_CGROUP_GETSOCKOPT: return "getsockopt";
1087 case BPF_CGROUP_SETSOCKOPT: return "setsockopt";
1088 case BPF_TRACE_RAW_TP: return "raw_tp";
1089 case BPF_TRACE_FENTRY: return "fentry";
1090 case BPF_TRACE_FEXIT: return "fexit";
1091 case BPF_MODIFY_RETURN: return "mod_ret";
1092 case BPF_SK_REUSEPORT_SELECT: return "sk_skb_reuseport_select";
1093 case BPF_SK_REUSEPORT_SELECT_OR_MIGRATE: return "sk_skb_reuseport_select_or_migrate";
1094 default: return libbpf_bpf_attach_type_str(t);
1098 int pathname_concat(char *buf, int buf_sz, const char *path,
1103 len = snprintf(buf, buf_sz, "%s/%s", path, name);
1107 return -ENAMETOOLONG;