1 // SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)
2 /* Copyright (C) 2017-2018 Netronome Systems, Inc. */
15 #include <sys/ioctl.h>
16 #include <sys/types.h>
18 #include <sys/syscall.h>
21 #include <linux/err.h>
22 #include <linux/perf_event.h>
23 #include <linux/sizes.h>
27 #include <bpf/libbpf.h>
28 #include <bpf/bpf_gen_internal.h>
29 #include <bpf/skel_internal.h>
33 #include "xlated_dumper.h"
35 #define BPF_METADATA_PREFIX "bpf_metadata_"
36 #define BPF_METADATA_PREFIX_LEN (sizeof(BPF_METADATA_PREFIX) - 1)
38 const char * const prog_type_name[] = {
39 [BPF_PROG_TYPE_UNSPEC] = "unspec",
40 [BPF_PROG_TYPE_SOCKET_FILTER] = "socket_filter",
41 [BPF_PROG_TYPE_KPROBE] = "kprobe",
42 [BPF_PROG_TYPE_SCHED_CLS] = "sched_cls",
43 [BPF_PROG_TYPE_SCHED_ACT] = "sched_act",
44 [BPF_PROG_TYPE_TRACEPOINT] = "tracepoint",
45 [BPF_PROG_TYPE_XDP] = "xdp",
46 [BPF_PROG_TYPE_PERF_EVENT] = "perf_event",
47 [BPF_PROG_TYPE_CGROUP_SKB] = "cgroup_skb",
48 [BPF_PROG_TYPE_CGROUP_SOCK] = "cgroup_sock",
49 [BPF_PROG_TYPE_LWT_IN] = "lwt_in",
50 [BPF_PROG_TYPE_LWT_OUT] = "lwt_out",
51 [BPF_PROG_TYPE_LWT_XMIT] = "lwt_xmit",
52 [BPF_PROG_TYPE_SOCK_OPS] = "sock_ops",
53 [BPF_PROG_TYPE_SK_SKB] = "sk_skb",
54 [BPF_PROG_TYPE_CGROUP_DEVICE] = "cgroup_device",
55 [BPF_PROG_TYPE_SK_MSG] = "sk_msg",
56 [BPF_PROG_TYPE_RAW_TRACEPOINT] = "raw_tracepoint",
57 [BPF_PROG_TYPE_CGROUP_SOCK_ADDR] = "cgroup_sock_addr",
58 [BPF_PROG_TYPE_LWT_SEG6LOCAL] = "lwt_seg6local",
59 [BPF_PROG_TYPE_LIRC_MODE2] = "lirc_mode2",
60 [BPF_PROG_TYPE_SK_REUSEPORT] = "sk_reuseport",
61 [BPF_PROG_TYPE_FLOW_DISSECTOR] = "flow_dissector",
62 [BPF_PROG_TYPE_CGROUP_SYSCTL] = "cgroup_sysctl",
63 [BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE] = "raw_tracepoint_writable",
64 [BPF_PROG_TYPE_CGROUP_SOCKOPT] = "cgroup_sockopt",
65 [BPF_PROG_TYPE_TRACING] = "tracing",
66 [BPF_PROG_TYPE_STRUCT_OPS] = "struct_ops",
67 [BPF_PROG_TYPE_EXT] = "ext",
68 [BPF_PROG_TYPE_LSM] = "lsm",
69 [BPF_PROG_TYPE_SK_LOOKUP] = "sk_lookup",
72 const size_t prog_type_name_size = ARRAY_SIZE(prog_type_name);
79 static const char * const attach_type_strings[] = {
80 [BPF_SK_SKB_STREAM_PARSER] = "stream_parser",
81 [BPF_SK_SKB_STREAM_VERDICT] = "stream_verdict",
82 [BPF_SK_SKB_VERDICT] = "skb_verdict",
83 [BPF_SK_MSG_VERDICT] = "msg_verdict",
84 [BPF_FLOW_DISSECTOR] = "flow_dissector",
85 [__MAX_BPF_ATTACH_TYPE] = NULL,
88 static enum bpf_attach_type parse_attach_type(const char *str)
90 enum bpf_attach_type type;
92 for (type = 0; type < __MAX_BPF_ATTACH_TYPE; type++) {
93 if (attach_type_strings[type] &&
94 is_prefix(str, attach_type_strings[type]))
98 return __MAX_BPF_ATTACH_TYPE;
101 static void print_boot_time(__u64 nsecs, char *buf, unsigned int size)
103 struct timespec real_time_ts, boot_time_ts;
104 time_t wallclock_secs;
109 if (clock_gettime(CLOCK_REALTIME, &real_time_ts) ||
110 clock_gettime(CLOCK_BOOTTIME, &boot_time_ts)) {
111 perror("Can't read clocks");
112 snprintf(buf, size, "%llu", nsecs / 1000000000);
116 wallclock_secs = (real_time_ts.tv_sec - boot_time_ts.tv_sec) +
117 (real_time_ts.tv_nsec - boot_time_ts.tv_nsec + nsecs) /
121 if (!localtime_r(&wallclock_secs, &load_tm)) {
122 snprintf(buf, size, "%llu", nsecs / 1000000000);
127 strftime(buf, size, "%s", &load_tm);
129 strftime(buf, size, "%FT%T%z", &load_tm);
132 static void show_prog_maps(int fd, __u32 num_maps)
134 struct bpf_prog_info info = {};
135 __u32 len = sizeof(info);
136 __u32 map_ids[num_maps];
140 info.nr_map_ids = num_maps;
141 info.map_ids = ptr_to_u64(map_ids);
143 err = bpf_obj_get_info_by_fd(fd, &info, &len);
144 if (err || !info.nr_map_ids)
148 jsonw_name(json_wtr, "map_ids");
149 jsonw_start_array(json_wtr);
150 for (i = 0; i < info.nr_map_ids; i++)
151 jsonw_uint(json_wtr, map_ids[i]);
152 jsonw_end_array(json_wtr);
155 for (i = 0; i < info.nr_map_ids; i++)
156 printf("%u%s", map_ids[i],
157 i == info.nr_map_ids - 1 ? "" : ",");
161 static void *find_metadata(int prog_fd, struct bpf_map_info *map_info)
163 struct bpf_prog_info prog_info;
174 memset(&prog_info, 0, sizeof(prog_info));
175 prog_info_len = sizeof(prog_info);
176 ret = bpf_obj_get_info_by_fd(prog_fd, &prog_info, &prog_info_len);
180 if (!prog_info.nr_map_ids)
183 map_ids = calloc(prog_info.nr_map_ids, sizeof(__u32));
187 nr_maps = prog_info.nr_map_ids;
188 memset(&prog_info, 0, sizeof(prog_info));
189 prog_info.nr_map_ids = nr_maps;
190 prog_info.map_ids = ptr_to_u64(map_ids);
191 prog_info_len = sizeof(prog_info);
193 ret = bpf_obj_get_info_by_fd(prog_fd, &prog_info, &prog_info_len);
197 for (i = 0; i < prog_info.nr_map_ids; i++) {
198 map_fd = bpf_map_get_fd_by_id(map_ids[i]);
202 memset(map_info, 0, sizeof(*map_info));
203 map_info_len = sizeof(*map_info);
204 ret = bpf_obj_get_info_by_fd(map_fd, map_info, &map_info_len);
210 if (map_info->type != BPF_MAP_TYPE_ARRAY ||
211 map_info->key_size != sizeof(int) ||
212 map_info->max_entries != 1 ||
213 !map_info->btf_value_type_id ||
214 !strstr(map_info->name, ".rodata")) {
219 value = malloc(map_info->value_size);
225 if (bpf_map_lookup_elem(map_fd, &key, value)) {
241 static bool has_metadata_prefix(const char *s)
243 return strncmp(s, BPF_METADATA_PREFIX, BPF_METADATA_PREFIX_LEN) == 0;
246 static void show_prog_metadata(int fd, __u32 num_maps)
248 const struct btf_type *t_datasec, *t_var;
249 struct bpf_map_info map_info;
250 struct btf_var_secinfo *vsi;
251 bool printed_header = false;
252 unsigned int i, vlen;
261 memset(&map_info, 0, sizeof(map_info));
262 value = find_metadata(fd, &map_info);
266 btf = btf__load_from_kernel_by_id(map_info.btf_id);
267 if (libbpf_get_error(btf))
270 t_datasec = btf__type_by_id(btf, map_info.btf_value_type_id);
271 if (!btf_is_datasec(t_datasec))
274 vlen = btf_vlen(t_datasec);
275 vsi = btf_var_secinfos(t_datasec);
277 /* We don't proceed to check the kinds of the elements of the DATASEC.
278 * The verifier enforces them to be BTF_KIND_VAR.
282 struct btf_dumper d = {
285 .is_plain_text = false,
288 for (i = 0; i < vlen; i++, vsi++) {
289 t_var = btf__type_by_id(btf, vsi->type);
290 name = btf__name_by_offset(btf, t_var->name_off);
292 if (!has_metadata_prefix(name))
295 if (!printed_header) {
296 jsonw_name(json_wtr, "metadata");
297 jsonw_start_object(json_wtr);
298 printed_header = true;
301 jsonw_name(json_wtr, name + BPF_METADATA_PREFIX_LEN);
302 err = btf_dumper_type(&d, t_var->type, value + vsi->offset);
304 p_err("btf dump failed: %d", err);
309 jsonw_end_object(json_wtr);
311 json_writer_t *btf_wtr;
312 struct btf_dumper d = {
314 .is_plain_text = true,
317 for (i = 0; i < vlen; i++, vsi++) {
318 t_var = btf__type_by_id(btf, vsi->type);
319 name = btf__name_by_offset(btf, t_var->name_off);
321 if (!has_metadata_prefix(name))
324 if (!printed_header) {
325 printf("\tmetadata:");
327 btf_wtr = jsonw_new(stdout);
329 p_err("jsonw alloc failed");
334 printed_header = true;
337 printf("\n\t\t%s = ", name + BPF_METADATA_PREFIX_LEN);
339 jsonw_reset(btf_wtr);
340 err = btf_dumper_type(&d, t_var->type, value + vsi->offset);
342 p_err("btf dump failed: %d", err);
347 jsonw_destroy(&btf_wtr);
355 static void print_prog_header_json(struct bpf_prog_info *info)
357 jsonw_uint_field(json_wtr, "id", info->id);
358 if (info->type < ARRAY_SIZE(prog_type_name))
359 jsonw_string_field(json_wtr, "type",
360 prog_type_name[info->type]);
362 jsonw_uint_field(json_wtr, "type", info->type);
365 jsonw_string_field(json_wtr, "name", info->name);
367 jsonw_name(json_wtr, "tag");
368 jsonw_printf(json_wtr, "\"" BPF_TAG_FMT "\"",
369 info->tag[0], info->tag[1], info->tag[2], info->tag[3],
370 info->tag[4], info->tag[5], info->tag[6], info->tag[7]);
372 jsonw_bool_field(json_wtr, "gpl_compatible", info->gpl_compatible);
373 if (info->run_time_ns) {
374 jsonw_uint_field(json_wtr, "run_time_ns", info->run_time_ns);
375 jsonw_uint_field(json_wtr, "run_cnt", info->run_cnt);
377 if (info->recursion_misses)
378 jsonw_uint_field(json_wtr, "recursion_misses", info->recursion_misses);
381 static void print_prog_json(struct bpf_prog_info *info, int fd)
385 jsonw_start_object(json_wtr);
386 print_prog_header_json(info);
387 print_dev_json(info->ifindex, info->netns_dev, info->netns_ino);
389 if (info->load_time) {
392 print_boot_time(info->load_time, buf, sizeof(buf));
394 /* Piggy back on load_time, since 0 uid is a valid one */
395 jsonw_name(json_wtr, "loaded_at");
396 jsonw_printf(json_wtr, "%s", buf);
397 jsonw_uint_field(json_wtr, "uid", info->created_by_uid);
400 jsonw_uint_field(json_wtr, "bytes_xlated", info->xlated_prog_len);
402 if (info->jited_prog_len) {
403 jsonw_bool_field(json_wtr, "jited", true);
404 jsonw_uint_field(json_wtr, "bytes_jited", info->jited_prog_len);
406 jsonw_bool_field(json_wtr, "jited", false);
409 memlock = get_fdinfo(fd, "memlock");
411 jsonw_int_field(json_wtr, "bytes_memlock", atoi(memlock));
414 if (info->nr_map_ids)
415 show_prog_maps(fd, info->nr_map_ids);
418 jsonw_int_field(json_wtr, "btf_id", info->btf_id);
420 if (!hash_empty(prog_table.table)) {
421 struct pinned_obj *obj;
423 jsonw_name(json_wtr, "pinned");
424 jsonw_start_array(json_wtr);
425 hash_for_each_possible(prog_table.table, obj, hash, info->id) {
426 if (obj->id == info->id)
427 jsonw_string(json_wtr, obj->path);
429 jsonw_end_array(json_wtr);
432 emit_obj_refs_json(&refs_table, info->id, json_wtr);
434 show_prog_metadata(fd, info->nr_map_ids);
436 jsonw_end_object(json_wtr);
439 static void print_prog_header_plain(struct bpf_prog_info *info)
441 printf("%u: ", info->id);
442 if (info->type < ARRAY_SIZE(prog_type_name))
443 printf("%s ", prog_type_name[info->type]);
445 printf("type %u ", info->type);
448 printf("name %s ", info->name);
451 fprint_hex(stdout, info->tag, BPF_TAG_SIZE, "");
452 print_dev_plain(info->ifindex, info->netns_dev, info->netns_ino);
453 printf("%s", info->gpl_compatible ? " gpl" : "");
454 if (info->run_time_ns)
455 printf(" run_time_ns %lld run_cnt %lld",
456 info->run_time_ns, info->run_cnt);
457 if (info->recursion_misses)
458 printf(" recursion_misses %lld", info->recursion_misses);
462 static void print_prog_plain(struct bpf_prog_info *info, int fd)
466 print_prog_header_plain(info);
468 if (info->load_time) {
471 print_boot_time(info->load_time, buf, sizeof(buf));
473 /* Piggy back on load_time, since 0 uid is a valid one */
474 printf("\tloaded_at %s uid %u\n", buf, info->created_by_uid);
477 printf("\txlated %uB", info->xlated_prog_len);
479 if (info->jited_prog_len)
480 printf(" jited %uB", info->jited_prog_len);
482 printf(" not jited");
484 memlock = get_fdinfo(fd, "memlock");
486 printf(" memlock %sB", memlock);
489 if (info->nr_map_ids)
490 show_prog_maps(fd, info->nr_map_ids);
492 if (!hash_empty(prog_table.table)) {
493 struct pinned_obj *obj;
495 hash_for_each_possible(prog_table.table, obj, hash, info->id) {
496 if (obj->id == info->id)
497 printf("\n\tpinned %s", obj->path);
502 printf("\n\tbtf_id %d", info->btf_id);
504 emit_obj_refs_plain(&refs_table, info->id, "\n\tpids ");
508 show_prog_metadata(fd, info->nr_map_ids);
511 static int show_prog(int fd)
513 struct bpf_prog_info info = {};
514 __u32 len = sizeof(info);
517 err = bpf_obj_get_info_by_fd(fd, &info, &len);
519 p_err("can't get prog info: %s", strerror(errno));
524 print_prog_json(&info, fd);
526 print_prog_plain(&info, fd);
531 static int do_show_subset(int argc, char **argv)
537 fds = malloc(sizeof(int));
539 p_err("mem alloc failed");
542 nb_fds = prog_parse_fds(&argc, &argv, &fds);
546 if (json_output && nb_fds > 1)
547 jsonw_start_array(json_wtr); /* root array */
548 for (i = 0; i < nb_fds; i++) {
549 err = show_prog(fds[i]);
551 for (; i < nb_fds; i++)
557 if (json_output && nb_fds > 1)
558 jsonw_end_array(json_wtr); /* root array */
565 static int do_show(int argc, char **argv)
572 build_pinned_obj_table(&prog_table, BPF_OBJ_PROG);
573 build_obj_refs_table(&refs_table, BPF_OBJ_PROG);
576 return do_show_subset(argc, argv);
582 jsonw_start_array(json_wtr);
584 err = bpf_prog_get_next_id(id, &id);
586 if (errno == ENOENT) {
590 p_err("can't get next program: %s%s", strerror(errno),
591 errno == EINVAL ? " -- kernel too old?" : "");
596 fd = bpf_prog_get_fd_by_id(id);
600 p_err("can't get prog by id (%u): %s",
601 id, strerror(errno));
613 jsonw_end_array(json_wtr);
615 delete_obj_refs_table(&refs_table);
621 prog_dump(struct bpf_prog_info *info, enum dump_mode mode,
622 char *filepath, bool opcodes, bool visual, bool linum)
624 struct bpf_prog_linfo *prog_linfo = NULL;
625 const char *disasm_opt = NULL;
626 struct dump_data dd = {};
627 void *func_info = NULL;
628 struct btf *btf = NULL;
635 if (mode == DUMP_JITED) {
636 if (info->jited_prog_len == 0 || !info->jited_prog_insns) {
637 p_info("no instructions returned");
640 buf = u64_to_ptr(info->jited_prog_insns);
641 member_len = info->jited_prog_len;
642 } else { /* DUMP_XLATED */
643 if (info->xlated_prog_len == 0 || !info->xlated_prog_insns) {
644 p_err("error retrieving insn dump: kernel.kptr_restrict set?");
647 buf = u64_to_ptr(info->xlated_prog_insns);
648 member_len = info->xlated_prog_len;
652 btf = btf__load_from_kernel_by_id(info->btf_id);
653 if (libbpf_get_error(btf)) {
654 p_err("failed to get btf");
659 func_info = u64_to_ptr(info->func_info);
661 if (info->nr_line_info) {
662 prog_linfo = bpf_prog_linfo__new(info);
664 p_info("error in processing bpf_line_info. continue without it.");
668 fd = open(filepath, O_WRONLY | O_CREAT | O_TRUNC, 0600);
670 p_err("can't open file %s: %s", filepath,
675 n = write(fd, buf, member_len);
677 if (n != (ssize_t)member_len) {
678 p_err("error writing output file: %s",
679 n < 0 ? strerror(errno) : "short write");
684 jsonw_null(json_wtr);
685 } else if (mode == DUMP_JITED) {
686 const char *name = NULL;
689 name = ifindex_to_bfd_params(info->ifindex,
697 if (info->nr_jited_func_lens && info->jited_func_lens) {
698 struct kernel_sym *sym = NULL;
699 struct bpf_func_info *record;
700 char sym_name[SYM_MAX_NAME];
701 unsigned char *img = buf;
705 if (info->nr_jited_ksyms) {
706 kernel_syms_load(&dd);
707 ksyms = u64_to_ptr(info->jited_ksyms);
711 jsonw_start_array(json_wtr);
713 lens = u64_to_ptr(info->jited_func_lens);
714 for (i = 0; i < info->nr_jited_func_lens; i++) {
716 sym = kernel_syms_search(&dd, ksyms[i]);
718 sprintf(sym_name, "%s", sym->name);
720 sprintf(sym_name, "0x%016llx", ksyms[i]);
722 strcpy(sym_name, "unknown");
726 record = func_info + i * info->func_info_rec_size;
727 btf_dumper_type_only(btf, record->type_id,
733 jsonw_start_object(json_wtr);
734 if (func_info && func_sig[0] != '\0') {
735 jsonw_name(json_wtr, "proto");
736 jsonw_string(json_wtr, func_sig);
738 jsonw_name(json_wtr, "name");
739 jsonw_string(json_wtr, sym_name);
740 jsonw_name(json_wtr, "insns");
742 if (func_info && func_sig[0] != '\0')
743 printf("%s:\n", func_sig);
744 printf("%s:\n", sym_name);
747 disasm_print_insn(img, lens[i], opcodes,
748 name, disasm_opt, btf,
749 prog_linfo, ksyms[i], i,
755 jsonw_end_object(json_wtr);
761 jsonw_end_array(json_wtr);
763 disasm_print_insn(buf, member_len, opcodes, name,
764 disasm_opt, btf, NULL, 0, 0, false);
768 jsonw_null(json_wtr);
770 dump_xlated_cfg(buf, member_len);
772 kernel_syms_load(&dd);
773 dd.nr_jited_ksyms = info->nr_jited_ksyms;
774 dd.jited_ksyms = u64_to_ptr(info->jited_ksyms);
776 dd.func_info = func_info;
777 dd.finfo_rec_size = info->func_info_rec_size;
778 dd.prog_linfo = prog_linfo;
781 dump_xlated_json(&dd, buf, member_len, opcodes,
784 dump_xlated_plain(&dd, buf, member_len, opcodes,
786 kernel_syms_destroy(&dd);
793 bpf_prog_linfo__free(prog_linfo);
797 static int do_dump(int argc, char **argv)
799 struct bpf_prog_info_linear *info_linear;
800 char *filepath = NULL;
801 bool opcodes = false;
810 if (is_prefix(*argv, "jited")) {
814 } else if (is_prefix(*argv, "xlated")) {
817 p_err("expected 'xlated' or 'jited', got: %s", *argv);
825 fds = malloc(sizeof(int));
827 p_err("mem alloc failed");
830 nb_fds = prog_parse_fds(&argc, &argv, &fds);
834 if (is_prefix(*argv, "file")) {
837 p_err("expected file path");
841 p_err("several programs matched");
847 } else if (is_prefix(*argv, "opcodes")) {
850 } else if (is_prefix(*argv, "visual")) {
852 p_err("several programs matched");
858 } else if (is_prefix(*argv, "linum")) {
868 if (mode == DUMP_JITED)
869 arrays = 1UL << BPF_PROG_INFO_JITED_INSNS;
871 arrays = 1UL << BPF_PROG_INFO_XLATED_INSNS;
873 arrays |= 1UL << BPF_PROG_INFO_JITED_KSYMS;
874 arrays |= 1UL << BPF_PROG_INFO_JITED_FUNC_LENS;
875 arrays |= 1UL << BPF_PROG_INFO_FUNC_INFO;
876 arrays |= 1UL << BPF_PROG_INFO_LINE_INFO;
877 arrays |= 1UL << BPF_PROG_INFO_JITED_LINE_INFO;
879 if (json_output && nb_fds > 1)
880 jsonw_start_array(json_wtr); /* root array */
881 for (i = 0; i < nb_fds; i++) {
882 info_linear = bpf_program__get_prog_info_linear(fds[i], arrays);
883 if (IS_ERR_OR_NULL(info_linear)) {
884 p_err("can't get prog info: %s", strerror(errno));
888 if (json_output && nb_fds > 1) {
889 jsonw_start_object(json_wtr); /* prog object */
890 print_prog_header_json(&info_linear->info);
891 jsonw_name(json_wtr, "insns");
892 } else if (nb_fds > 1) {
893 print_prog_header_plain(&info_linear->info);
896 err = prog_dump(&info_linear->info, mode, filepath, opcodes,
899 if (json_output && nb_fds > 1)
900 jsonw_end_object(json_wtr); /* prog object */
901 else if (i != nb_fds - 1 && nb_fds > 1)
909 if (json_output && nb_fds > 1)
910 jsonw_end_array(json_wtr); /* root array */
913 for (; i < nb_fds; i++)
920 static int do_pin(int argc, char **argv)
924 err = do_pin_any(argc, argv, prog_parse_fd);
925 if (!err && json_output)
926 jsonw_null(json_wtr);
936 static int map_replace_compar(const void *p1, const void *p2)
938 const struct map_replace *a = p1, *b = p2;
940 return a->idx - b->idx;
943 static int parse_attach_detach_args(int argc, char **argv, int *progfd,
944 enum bpf_attach_type *attach_type,
950 *progfd = prog_parse_fd(&argc, &argv);
954 *attach_type = parse_attach_type(*argv);
955 if (*attach_type == __MAX_BPF_ATTACH_TYPE) {
956 p_err("invalid attach/detach type");
960 if (*attach_type == BPF_FLOW_DISSECTOR) {
969 *mapfd = map_parse_fd(&argc, &argv);
976 static int do_attach(int argc, char **argv)
978 enum bpf_attach_type attach_type;
982 err = parse_attach_detach_args(argc, argv,
983 &progfd, &attach_type, &mapfd);
987 err = bpf_prog_attach(progfd, mapfd, attach_type, 0);
989 p_err("failed prog attach to map");
994 jsonw_null(json_wtr);
998 static int do_detach(int argc, char **argv)
1000 enum bpf_attach_type attach_type;
1004 err = parse_attach_detach_args(argc, argv,
1005 &progfd, &attach_type, &mapfd);
1009 err = bpf_prog_detach2(progfd, mapfd, attach_type);
1011 p_err("failed prog detach from map");
1016 jsonw_null(json_wtr);
1020 static int check_single_stdin(char *file_data_in, char *file_ctx_in)
1022 if (file_data_in && file_ctx_in &&
1023 !strcmp(file_data_in, "-") && !strcmp(file_ctx_in, "-")) {
1024 p_err("cannot use standard input for both data_in and ctx_in");
1031 static int get_run_data(const char *fname, void **data_ptr, unsigned int *size)
1033 size_t block_size = 256;
1034 size_t buf_size = block_size;
1045 if (!strcmp(fname, "-"))
1048 f = fopen(fname, "r");
1050 p_err("failed to open %s: %s", fname, strerror(errno));
1054 *data_ptr = malloc(block_size);
1056 p_err("failed to allocate memory for data_in/ctx_in: %s",
1061 while ((nb_read += fread(*data_ptr + nb_read, 1, block_size, f))) {
1065 p_err("failed to read data_in/ctx_in from %s: %s",
1066 fname, strerror(errno));
1069 if (nb_read > buf_size - block_size) {
1070 if (buf_size == UINT32_MAX) {
1071 p_err("data_in/ctx_in is too long (max: %d)",
1075 /* No space for fread()-ing next chunk; realloc() */
1077 tmp = realloc(*data_ptr, buf_size);
1079 p_err("failed to reallocate data_in/ctx_in: %s",
1101 static void hex_print(void *data, unsigned int size, FILE *f)
1106 for (i = 0; i < size; i += 16) {
1108 fprintf(f, "%07zx\t", i);
1110 /* Hexadecimal values */
1111 for (j = i; j < i + 16 && j < size; j++)
1112 fprintf(f, "%02x%s", *(uint8_t *)(data + j),
1114 for (; j < i + 16; j++)
1115 fprintf(f, " %s", j % 2 ? " " : "");
1117 /* ASCII values (if relevant), '.' otherwise */
1119 for (j = i; j < i + 16 && j < size; j++) {
1120 c = *(char *)(data + j);
1121 if (c < ' ' || c > '~')
1123 fprintf(f, "%c%s", c, j == i + 7 ? " " : "");
1131 print_run_output(void *data, unsigned int size, const char *fname,
1132 const char *json_key)
1140 if (!strcmp(fname, "-")) {
1143 jsonw_name(json_wtr, json_key);
1144 print_data_json(data, size);
1146 hex_print(data, size, f);
1151 f = fopen(fname, "w");
1153 p_err("failed to open %s: %s", fname, strerror(errno));
1157 nb_written = fwrite(data, 1, size, f);
1159 if (nb_written != size) {
1160 p_err("failed to write output data/ctx: %s", strerror(errno));
1167 static int alloc_run_data(void **data_ptr, unsigned int size_out)
1169 *data_ptr = calloc(size_out, 1);
1171 p_err("failed to allocate memory for output data/ctx: %s",
1179 static int do_run(int argc, char **argv)
1181 char *data_fname_in = NULL, *data_fname_out = NULL;
1182 char *ctx_fname_in = NULL, *ctx_fname_out = NULL;
1183 struct bpf_prog_test_run_attr test_attr = {0};
1184 const unsigned int default_size = SZ_32K;
1185 void *data_in = NULL, *data_out = NULL;
1186 void *ctx_in = NULL, *ctx_out = NULL;
1187 unsigned int repeat = 1;
1193 fd = prog_parse_fd(&argc, &argv);
1198 if (detect_common_prefix(*argv, "data_in", "data_out",
1199 "data_size_out", NULL))
1201 if (detect_common_prefix(*argv, "ctx_in", "ctx_out",
1202 "ctx_size_out", NULL))
1205 if (is_prefix(*argv, "data_in")) {
1210 data_fname_in = GET_ARG();
1211 if (check_single_stdin(data_fname_in, ctx_fname_in))
1213 } else if (is_prefix(*argv, "data_out")) {
1218 data_fname_out = GET_ARG();
1219 } else if (is_prefix(*argv, "data_size_out")) {
1226 test_attr.data_size_out = strtoul(*argv, &endptr, 0);
1228 p_err("can't parse %s as output data size",
1233 } else if (is_prefix(*argv, "ctx_in")) {
1238 ctx_fname_in = GET_ARG();
1239 if (check_single_stdin(data_fname_in, ctx_fname_in))
1241 } else if (is_prefix(*argv, "ctx_out")) {
1246 ctx_fname_out = GET_ARG();
1247 } else if (is_prefix(*argv, "ctx_size_out")) {
1254 test_attr.ctx_size_out = strtoul(*argv, &endptr, 0);
1256 p_err("can't parse %s as output context size",
1261 } else if (is_prefix(*argv, "repeat")) {
1268 repeat = strtoul(*argv, &endptr, 0);
1270 p_err("can't parse %s as repeat number",
1276 p_err("expected no more arguments, 'data_in', 'data_out', 'data_size_out', 'ctx_in', 'ctx_out', 'ctx_size_out' or 'repeat', got: '%s'?",
1282 err = get_run_data(data_fname_in, &data_in, &test_attr.data_size_in);
1287 if (!test_attr.data_size_out)
1288 test_attr.data_size_out = default_size;
1289 err = alloc_run_data(&data_out, test_attr.data_size_out);
1294 err = get_run_data(ctx_fname_in, &ctx_in, &test_attr.ctx_size_in);
1299 if (!test_attr.ctx_size_out)
1300 test_attr.ctx_size_out = default_size;
1301 err = alloc_run_data(&ctx_out, test_attr.ctx_size_out);
1306 test_attr.prog_fd = fd;
1307 test_attr.repeat = repeat;
1308 test_attr.data_in = data_in;
1309 test_attr.data_out = data_out;
1310 test_attr.ctx_in = ctx_in;
1311 test_attr.ctx_out = ctx_out;
1313 err = bpf_prog_test_run_xattr(&test_attr);
1315 p_err("failed to run program: %s", strerror(errno));
1322 jsonw_start_object(json_wtr); /* root */
1324 /* Do not exit on errors occurring when printing output data/context,
1325 * we still want to print return value and duration for program run.
1327 if (test_attr.data_size_out)
1328 err += print_run_output(test_attr.data_out,
1329 test_attr.data_size_out,
1330 data_fname_out, "data_out");
1331 if (test_attr.ctx_size_out)
1332 err += print_run_output(test_attr.ctx_out,
1333 test_attr.ctx_size_out,
1334 ctx_fname_out, "ctx_out");
1337 jsonw_uint_field(json_wtr, "retval", test_attr.retval);
1338 jsonw_uint_field(json_wtr, "duration", test_attr.duration);
1339 jsonw_end_object(json_wtr); /* root */
1341 fprintf(stdout, "Return value: %u, duration%s: %uns\n",
1343 repeat > 1 ? " (average)" : "", test_attr.duration);
1359 get_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
1360 enum bpf_attach_type *expected_attach_type)
1362 libbpf_print_fn_t print_backup;
1365 ret = libbpf_prog_type_by_name(name, prog_type, expected_attach_type);
1369 /* libbpf_prog_type_by_name() failed, let's re-run with debug level */
1370 print_backup = libbpf_set_print(print_all_levels);
1371 ret = libbpf_prog_type_by_name(name, prog_type, expected_attach_type);
1372 libbpf_set_print(print_backup);
1377 static int load_with_options(int argc, char **argv, bool first_prog_only)
1379 enum bpf_prog_type common_prog_type = BPF_PROG_TYPE_UNSPEC;
1380 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, open_opts,
1381 .relaxed_maps = relaxed_maps,
1383 struct bpf_object_load_attr load_attr = { 0 };
1384 enum bpf_attach_type expected_attach_type;
1385 struct map_replace *map_replace = NULL;
1386 struct bpf_program *prog = NULL, *pos;
1387 unsigned int old_map_fds = 0;
1388 const char *pinmaps = NULL;
1389 struct bpf_object *obj;
1390 struct bpf_map *map;
1391 const char *pinfile;
1401 pinfile = GET_ARG();
1404 if (is_prefix(*argv, "type")) {
1409 if (common_prog_type != BPF_PROG_TYPE_UNSPEC) {
1410 p_err("program type already specified");
1411 goto err_free_reuse_maps;
1414 goto err_free_reuse_maps;
1416 /* Put a '/' at the end of type to appease libbpf */
1417 type = malloc(strlen(*argv) + 2);
1419 p_err("mem alloc failed");
1420 goto err_free_reuse_maps;
1423 strcat(type, *argv);
1426 err = get_prog_type_by_name(type, &common_prog_type,
1427 &expected_attach_type);
1430 goto err_free_reuse_maps;
1433 } else if (is_prefix(*argv, "map")) {
1434 void *new_map_replace;
1435 char *endptr, *name;
1441 goto err_free_reuse_maps;
1443 if (is_prefix(*argv, "idx")) {
1446 idx = strtoul(*argv, &endptr, 0);
1448 p_err("can't parse %s as IDX", *argv);
1449 goto err_free_reuse_maps;
1452 } else if (is_prefix(*argv, "name")) {
1458 p_err("expected 'idx' or 'name', got: '%s'?",
1460 goto err_free_reuse_maps;
1464 fd = map_parse_fd(&argc, &argv);
1466 goto err_free_reuse_maps;
1468 new_map_replace = reallocarray(map_replace,
1470 sizeof(*map_replace));
1471 if (!new_map_replace) {
1472 p_err("mem alloc failed");
1473 goto err_free_reuse_maps;
1475 map_replace = new_map_replace;
1477 map_replace[old_map_fds].idx = idx;
1478 map_replace[old_map_fds].name = name;
1479 map_replace[old_map_fds].fd = fd;
1481 } else if (is_prefix(*argv, "dev")) {
1485 p_err("offload device already specified");
1486 goto err_free_reuse_maps;
1489 goto err_free_reuse_maps;
1491 ifindex = if_nametoindex(*argv);
1493 p_err("unrecognized netdevice '%s': %s",
1494 *argv, strerror(errno));
1495 goto err_free_reuse_maps;
1498 } else if (is_prefix(*argv, "pinmaps")) {
1502 goto err_free_reuse_maps;
1504 pinmaps = GET_ARG();
1506 p_err("expected no more arguments, 'type', 'map' or 'dev', got: '%s'?",
1508 goto err_free_reuse_maps;
1514 obj = bpf_object__open_file(file, &open_opts);
1515 if (libbpf_get_error(obj)) {
1516 p_err("failed to open object file");
1517 goto err_free_reuse_maps;
1520 bpf_object__for_each_program(pos, obj) {
1521 enum bpf_prog_type prog_type = common_prog_type;
1523 if (prog_type == BPF_PROG_TYPE_UNSPEC) {
1524 const char *sec_name = bpf_program__section_name(pos);
1526 err = get_prog_type_by_name(sec_name, &prog_type,
1527 &expected_attach_type);
1532 bpf_program__set_ifindex(pos, ifindex);
1533 bpf_program__set_type(pos, prog_type);
1534 bpf_program__set_expected_attach_type(pos, expected_attach_type);
1537 qsort(map_replace, old_map_fds, sizeof(*map_replace),
1538 map_replace_compar);
1540 /* After the sort maps by name will be first on the list, because they
1541 * have idx == -1. Resolve them.
1544 while (j < old_map_fds && map_replace[j].name) {
1546 bpf_object__for_each_map(map, obj) {
1547 if (!strcmp(bpf_map__name(map), map_replace[j].name)) {
1548 map_replace[j].idx = i;
1553 if (map_replace[j].idx == -1) {
1554 p_err("unable to find map '%s'", map_replace[j].name);
1559 /* Resort if any names were resolved */
1561 qsort(map_replace, old_map_fds, sizeof(*map_replace),
1562 map_replace_compar);
1564 /* Set ifindex and name reuse */
1567 bpf_object__for_each_map(map, obj) {
1568 if (!bpf_map__is_offload_neutral(map))
1569 bpf_map__set_ifindex(map, ifindex);
1571 if (j < old_map_fds && idx == map_replace[j].idx) {
1572 err = bpf_map__reuse_fd(map, map_replace[j++].fd);
1574 p_err("unable to set up map reuse: %d", err);
1578 /* Next reuse wants to apply to the same map */
1579 if (j < old_map_fds && map_replace[j].idx == idx) {
1580 p_err("replacement for map idx %d specified more than once",
1588 if (j < old_map_fds) {
1589 p_err("map idx '%d' not used", map_replace[j].idx);
1593 load_attr.obj = obj;
1595 /* log_level1 + log_level2 + stats, but not stable UAPI */
1596 load_attr.log_level = 1 + 2 + 4;
1598 err = bpf_object__load_xattr(&load_attr);
1600 p_err("failed to load object file");
1604 err = mount_bpffs_for_pin(pinfile);
1608 if (first_prog_only) {
1609 prog = bpf_program__next(NULL, obj);
1611 p_err("object file doesn't contain any bpf program");
1615 err = bpf_obj_pin(bpf_program__fd(prog), pinfile);
1617 p_err("failed to pin program %s",
1618 bpf_program__section_name(prog));
1622 err = bpf_object__pin_programs(obj, pinfile);
1624 p_err("failed to pin all programs");
1630 err = bpf_object__pin_maps(obj, pinmaps);
1632 p_err("failed to pin all maps");
1638 jsonw_null(json_wtr);
1640 bpf_object__close(obj);
1641 for (i = 0; i < old_map_fds; i++)
1642 close(map_replace[i].fd);
1648 if (first_prog_only)
1651 bpf_object__unpin_programs(obj, pinfile);
1653 bpf_object__close(obj);
1654 err_free_reuse_maps:
1655 for (i = 0; i < old_map_fds; i++)
1656 close(map_replace[i].fd);
1661 static int count_open_fds(void)
1663 DIR *dp = opendir("/proc/self/fd");
1670 while ((de = readdir(dp)))
1677 static int try_loader(struct gen_loader_opts *gen)
1679 struct bpf_load_and_run_opts opts = {};
1680 struct bpf_loader_ctx *ctx;
1681 int ctx_sz = sizeof(*ctx) + 64 * max(sizeof(struct bpf_map_desc),
1682 sizeof(struct bpf_prog_desc));
1683 int log_buf_sz = (1u << 24) - 1;
1684 int err, fds_before, fd_delta;
1687 ctx = alloca(ctx_sz);
1688 memset(ctx, 0, ctx_sz);
1691 ctx->log_size = log_buf_sz;
1692 log_buf = malloc(log_buf_sz);
1695 ctx->log_buf = (long) log_buf;
1697 opts.data = gen->data;
1698 opts.data_sz = gen->data_sz;
1699 opts.insns = gen->insns;
1700 opts.insns_sz = gen->insns_sz;
1701 fds_before = count_open_fds();
1702 err = bpf_load_and_run(&opts);
1703 fd_delta = count_open_fds() - fds_before;
1705 fprintf(stderr, "err %d\n%s\n%s", err, opts.errstr, log_buf);
1707 fprintf(stderr, "loader prog leaked %d FDs\n",
1714 static int do_loader(int argc, char **argv)
1716 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, open_opts);
1717 DECLARE_LIBBPF_OPTS(gen_loader_opts, gen);
1718 struct bpf_object_load_attr load_attr = {};
1719 struct bpf_object *obj;
1727 obj = bpf_object__open_file(file, &open_opts);
1728 if (libbpf_get_error(obj)) {
1729 p_err("failed to open object file");
1733 err = bpf_object__gen_loader(obj, &gen);
1737 load_attr.obj = obj;
1739 /* log_level1 + log_level2 + stats, but not stable UAPI */
1740 load_attr.log_level = 1 + 2 + 4;
1742 err = bpf_object__load_xattr(&load_attr);
1744 p_err("failed to load object file");
1748 if (verifier_logs) {
1749 struct dump_data dd = {};
1751 kernel_syms_load(&dd);
1752 dump_xlated_plain(&dd, (void *)gen.insns, gen.insns_sz, false, false);
1753 kernel_syms_destroy(&dd);
1755 err = try_loader(&gen);
1757 bpf_object__close(obj);
1761 static int do_load(int argc, char **argv)
1764 return do_loader(argc, argv);
1765 return load_with_options(argc, argv, true);
1768 static int do_loadall(int argc, char **argv)
1770 return load_with_options(argc, argv, false);
1773 #ifdef BPFTOOL_WITHOUT_SKELETONS
1775 static int do_profile(int argc, char **argv)
1777 p_err("bpftool prog profile command is not supported. Please build bpftool with clang >= 10.0.0");
1781 #else /* BPFTOOL_WITHOUT_SKELETONS */
1783 #include "profiler.skel.h"
1785 struct profile_metric {
1787 struct bpf_perf_event_value val;
1788 struct perf_event_attr attr;
1791 /* calculate ratios like instructions per cycle */
1792 const int ratio_metric; /* 0 for N/A, 1 for index 0 (cycles) */
1793 const char *ratio_desc;
1794 const float ratio_mul;
1799 .type = PERF_TYPE_HARDWARE,
1800 .config = PERF_COUNT_HW_CPU_CYCLES,
1805 .name = "instructions",
1807 .type = PERF_TYPE_HARDWARE,
1808 .config = PERF_COUNT_HW_INSTRUCTIONS,
1812 .ratio_desc = "insns per cycle",
1816 .name = "l1d_loads",
1818 .type = PERF_TYPE_HW_CACHE,
1820 PERF_COUNT_HW_CACHE_L1D |
1821 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1822 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16),
1827 .name = "llc_misses",
1829 .type = PERF_TYPE_HW_CACHE,
1831 PERF_COUNT_HW_CACHE_LL |
1832 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1833 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16),
1837 .ratio_desc = "LLC misses per million insns",
1841 .name = "itlb_misses",
1843 .type = PERF_TYPE_HW_CACHE,
1845 PERF_COUNT_HW_CACHE_ITLB |
1846 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1847 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16),
1851 .ratio_desc = "itlb misses per million insns",
1855 .name = "dtlb_misses",
1857 .type = PERF_TYPE_HW_CACHE,
1859 PERF_COUNT_HW_CACHE_DTLB |
1860 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1861 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16),
1865 .ratio_desc = "dtlb misses per million insns",
1870 static __u64 profile_total_count;
1872 #define MAX_NUM_PROFILE_METRICS 4
1874 static int profile_parse_metrics(int argc, char **argv)
1876 unsigned int metric_cnt;
1877 int selected_cnt = 0;
1880 metric_cnt = sizeof(metrics) / sizeof(struct profile_metric);
1883 for (i = 0; i < metric_cnt; i++) {
1884 if (is_prefix(argv[0], metrics[i].name)) {
1885 if (!metrics[i].selected)
1887 metrics[i].selected = true;
1891 if (i == metric_cnt) {
1892 p_err("unknown metric %s", argv[0]);
1897 if (selected_cnt > MAX_NUM_PROFILE_METRICS) {
1898 p_err("too many (%d) metrics, please specify no more than %d metrics at at time",
1899 selected_cnt, MAX_NUM_PROFILE_METRICS);
1902 return selected_cnt;
1905 static void profile_read_values(struct profiler_bpf *obj)
1907 __u32 m, cpu, num_cpu = obj->rodata->num_cpu;
1908 int reading_map_fd, count_map_fd;
1909 __u64 counts[num_cpu];
1913 reading_map_fd = bpf_map__fd(obj->maps.accum_readings);
1914 count_map_fd = bpf_map__fd(obj->maps.counts);
1915 if (reading_map_fd < 0 || count_map_fd < 0) {
1916 p_err("failed to get fd for map");
1920 err = bpf_map_lookup_elem(count_map_fd, &key, counts);
1922 p_err("failed to read count_map: %s", strerror(errno));
1926 profile_total_count = 0;
1927 for (cpu = 0; cpu < num_cpu; cpu++)
1928 profile_total_count += counts[cpu];
1930 for (m = 0; m < ARRAY_SIZE(metrics); m++) {
1931 struct bpf_perf_event_value values[num_cpu];
1933 if (!metrics[m].selected)
1936 err = bpf_map_lookup_elem(reading_map_fd, &key, values);
1938 p_err("failed to read reading_map: %s",
1942 for (cpu = 0; cpu < num_cpu; cpu++) {
1943 metrics[m].val.counter += values[cpu].counter;
1944 metrics[m].val.enabled += values[cpu].enabled;
1945 metrics[m].val.running += values[cpu].running;
1951 static void profile_print_readings_json(void)
1955 jsonw_start_array(json_wtr);
1956 for (m = 0; m < ARRAY_SIZE(metrics); m++) {
1957 if (!metrics[m].selected)
1959 jsonw_start_object(json_wtr);
1960 jsonw_string_field(json_wtr, "metric", metrics[m].name);
1961 jsonw_lluint_field(json_wtr, "run_cnt", profile_total_count);
1962 jsonw_lluint_field(json_wtr, "value", metrics[m].val.counter);
1963 jsonw_lluint_field(json_wtr, "enabled", metrics[m].val.enabled);
1964 jsonw_lluint_field(json_wtr, "running", metrics[m].val.running);
1966 jsonw_end_object(json_wtr);
1968 jsonw_end_array(json_wtr);
1971 static void profile_print_readings_plain(void)
1975 printf("\n%18llu %-20s\n", profile_total_count, "run_cnt");
1976 for (m = 0; m < ARRAY_SIZE(metrics); m++) {
1977 struct bpf_perf_event_value *val = &metrics[m].val;
1980 if (!metrics[m].selected)
1982 printf("%18llu %-20s", val->counter, metrics[m].name);
1984 r = metrics[m].ratio_metric - 1;
1985 if (r >= 0 && metrics[r].selected &&
1986 metrics[r].val.counter > 0) {
1987 printf("# %8.2f %-30s",
1988 val->counter * metrics[m].ratio_mul /
1989 metrics[r].val.counter,
1990 metrics[m].ratio_desc);
1992 printf("%-41s", "");
1995 if (val->enabled > val->running)
1997 val->running * 100.0 / val->enabled);
2002 static void profile_print_readings(void)
2005 profile_print_readings_json();
2007 profile_print_readings_plain();
2010 static char *profile_target_name(int tgt_fd)
2012 struct bpf_prog_info_linear *info_linear;
2013 struct bpf_func_info *func_info;
2014 const struct btf_type *t;
2015 struct btf *btf = NULL;
2018 info_linear = bpf_program__get_prog_info_linear(
2019 tgt_fd, 1UL << BPF_PROG_INFO_FUNC_INFO);
2020 if (IS_ERR_OR_NULL(info_linear)) {
2021 p_err("failed to get info_linear for prog FD %d", tgt_fd);
2025 if (info_linear->info.btf_id == 0) {
2026 p_err("prog FD %d doesn't have valid btf", tgt_fd);
2030 btf = btf__load_from_kernel_by_id(info_linear->info.btf_id);
2031 if (libbpf_get_error(btf)) {
2032 p_err("failed to load btf for prog FD %d", tgt_fd);
2036 func_info = u64_to_ptr(info_linear->info.func_info);
2037 t = btf__type_by_id(btf, func_info[0].type_id);
2039 p_err("btf %d doesn't have type %d",
2040 info_linear->info.btf_id, func_info[0].type_id);
2043 name = strdup(btf__name_by_offset(btf, t->name_off));
2050 static struct profiler_bpf *profile_obj;
2051 static int profile_tgt_fd = -1;
2052 static char *profile_tgt_name;
2053 static int *profile_perf_events;
2054 static int profile_perf_event_cnt;
2056 static void profile_close_perf_events(struct profiler_bpf *obj)
2060 for (i = profile_perf_event_cnt - 1; i >= 0; i--)
2061 close(profile_perf_events[i]);
2063 free(profile_perf_events);
2064 profile_perf_event_cnt = 0;
2067 static int profile_open_perf_events(struct profiler_bpf *obj)
2069 unsigned int cpu, m;
2072 profile_perf_events = calloc(
2073 sizeof(int), obj->rodata->num_cpu * obj->rodata->num_metric);
2074 if (!profile_perf_events) {
2075 p_err("failed to allocate memory for perf_event array: %s",
2079 map_fd = bpf_map__fd(obj->maps.events);
2081 p_err("failed to get fd for events map");
2085 for (m = 0; m < ARRAY_SIZE(metrics); m++) {
2086 if (!metrics[m].selected)
2088 for (cpu = 0; cpu < obj->rodata->num_cpu; cpu++) {
2089 pmu_fd = syscall(__NR_perf_event_open, &metrics[m].attr,
2090 -1/*pid*/, cpu, -1/*group_fd*/, 0);
2092 bpf_map_update_elem(map_fd, &profile_perf_event_cnt,
2093 &pmu_fd, BPF_ANY) ||
2094 ioctl(pmu_fd, PERF_EVENT_IOC_ENABLE, 0)) {
2095 p_err("failed to create event %s on cpu %d",
2096 metrics[m].name, cpu);
2099 profile_perf_events[profile_perf_event_cnt++] = pmu_fd;
2105 static void profile_print_and_cleanup(void)
2107 profile_close_perf_events(profile_obj);
2108 profile_read_values(profile_obj);
2109 profile_print_readings();
2110 profiler_bpf__destroy(profile_obj);
2112 close(profile_tgt_fd);
2113 free(profile_tgt_name);
2116 static void int_exit(int signo)
2118 profile_print_and_cleanup();
2122 static int do_profile(int argc, char **argv)
2124 int num_metric, num_cpu, err = -1;
2125 struct bpf_program *prog;
2126 unsigned long duration;
2129 /* we at least need two args for the prog and one metric */
2133 /* parse target fd */
2134 profile_tgt_fd = prog_parse_fd(&argc, &argv);
2135 if (profile_tgt_fd < 0) {
2136 p_err("failed to parse fd");
2140 /* parse profiling optional duration */
2141 if (argc > 2 && is_prefix(argv[0], "duration")) {
2143 duration = strtoul(*argv, &endptr, 0);
2148 duration = UINT_MAX;
2151 num_metric = profile_parse_metrics(argc, argv);
2152 if (num_metric <= 0)
2155 num_cpu = libbpf_num_possible_cpus();
2157 p_err("failed to identify number of CPUs");
2161 profile_obj = profiler_bpf__open();
2163 p_err("failed to open and/or load BPF object");
2167 profile_obj->rodata->num_cpu = num_cpu;
2168 profile_obj->rodata->num_metric = num_metric;
2170 /* adjust map sizes */
2171 bpf_map__resize(profile_obj->maps.events, num_metric * num_cpu);
2172 bpf_map__resize(profile_obj->maps.fentry_readings, num_metric);
2173 bpf_map__resize(profile_obj->maps.accum_readings, num_metric);
2174 bpf_map__resize(profile_obj->maps.counts, 1);
2176 /* change target name */
2177 profile_tgt_name = profile_target_name(profile_tgt_fd);
2178 if (!profile_tgt_name)
2181 bpf_object__for_each_program(prog, profile_obj->obj) {
2182 err = bpf_program__set_attach_target(prog, profile_tgt_fd,
2185 p_err("failed to set attach target\n");
2191 err = profiler_bpf__load(profile_obj);
2193 p_err("failed to load profile_obj");
2197 err = profile_open_perf_events(profile_obj);
2201 err = profiler_bpf__attach(profile_obj);
2203 p_err("failed to attach profile_obj");
2206 signal(SIGINT, int_exit);
2209 profile_print_and_cleanup();
2213 profile_close_perf_events(profile_obj);
2215 profiler_bpf__destroy(profile_obj);
2216 close(profile_tgt_fd);
2217 free(profile_tgt_name);
2221 #endif /* BPFTOOL_WITHOUT_SKELETONS */
2223 static int do_help(int argc, char **argv)
2226 jsonw_null(json_wtr);
2231 "Usage: %1$s %2$s { show | list } [PROG]\n"
2232 " %1$s %2$s dump xlated PROG [{ file FILE | opcodes | visual | linum }]\n"
2233 " %1$s %2$s dump jited PROG [{ file FILE | opcodes | linum }]\n"
2234 " %1$s %2$s pin PROG FILE\n"
2235 " %1$s %2$s { load | loadall } OBJ PATH \\\n"
2236 " [type TYPE] [dev NAME] \\\n"
2237 " [map { idx IDX | name NAME } MAP]\\\n"
2238 " [pinmaps MAP_DIR]\n"
2239 " %1$s %2$s attach PROG ATTACH_TYPE [MAP]\n"
2240 " %1$s %2$s detach PROG ATTACH_TYPE [MAP]\n"
2241 " %1$s %2$s run PROG \\\n"
2242 " data_in FILE \\\n"
2243 " [data_out FILE [data_size_out L]] \\\n"
2244 " [ctx_in FILE [ctx_out FILE [ctx_size_out M]]] \\\n"
2246 " %1$s %2$s profile PROG [duration DURATION] METRICs\n"
2247 " %1$s %2$s tracelog\n"
2250 " " HELP_SPEC_MAP "\n"
2251 " " HELP_SPEC_PROGRAM "\n"
2252 " TYPE := { socket | kprobe | kretprobe | classifier | action |\n"
2253 " tracepoint | raw_tracepoint | xdp | perf_event | cgroup/skb |\n"
2254 " cgroup/sock | cgroup/dev | lwt_in | lwt_out | lwt_xmit |\n"
2255 " lwt_seg6local | sockops | sk_skb | sk_msg | lirc_mode2 |\n"
2256 " sk_reuseport | flow_dissector | cgroup/sysctl |\n"
2257 " cgroup/bind4 | cgroup/bind6 | cgroup/post_bind4 |\n"
2258 " cgroup/post_bind6 | cgroup/connect4 | cgroup/connect6 |\n"
2259 " cgroup/getpeername4 | cgroup/getpeername6 |\n"
2260 " cgroup/getsockname4 | cgroup/getsockname6 | cgroup/sendmsg4 |\n"
2261 " cgroup/sendmsg6 | cgroup/recvmsg4 | cgroup/recvmsg6 |\n"
2262 " cgroup/getsockopt | cgroup/setsockopt | cgroup/sock_release |\n"
2263 " struct_ops | fentry | fexit | freplace | sk_lookup }\n"
2264 " ATTACH_TYPE := { msg_verdict | skb_verdict | stream_verdict |\n"
2265 " stream_parser | flow_dissector }\n"
2266 " METRIC := { cycles | instructions | l1d_loads | llc_misses | itlb_misses | dtlb_misses }\n"
2267 " " HELP_SPEC_OPTIONS " |\n"
2268 " {-f|--bpffs} | {-m|--mapcompat} | {-n|--nomount} |\n"
2269 " {-L|--use-loader} }\n"
2271 bin_name, argv[-2]);
2276 static const struct cmd cmds[] = {
2277 { "show", do_show },
2278 { "list", do_show },
2279 { "help", do_help },
2280 { "dump", do_dump },
2282 { "load", do_load },
2283 { "loadall", do_loadall },
2284 { "attach", do_attach },
2285 { "detach", do_detach },
2286 { "tracelog", do_tracelog },
2288 { "profile", do_profile },
2292 int do_prog(int argc, char **argv)
2294 return cmd_select(cmds, argc, argv, do_help);