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);
794 static int do_dump(int argc, char **argv)
796 struct bpf_prog_info_linear *info_linear;
797 char *filepath = NULL;
798 bool opcodes = false;
807 if (is_prefix(*argv, "jited")) {
811 } else if (is_prefix(*argv, "xlated")) {
814 p_err("expected 'xlated' or 'jited', got: %s", *argv);
822 fds = malloc(sizeof(int));
824 p_err("mem alloc failed");
827 nb_fds = prog_parse_fds(&argc, &argv, &fds);
831 if (is_prefix(*argv, "file")) {
834 p_err("expected file path");
838 p_err("several programs matched");
844 } else if (is_prefix(*argv, "opcodes")) {
847 } else if (is_prefix(*argv, "visual")) {
849 p_err("several programs matched");
855 } else if (is_prefix(*argv, "linum")) {
865 if (mode == DUMP_JITED)
866 arrays = 1UL << BPF_PROG_INFO_JITED_INSNS;
868 arrays = 1UL << BPF_PROG_INFO_XLATED_INSNS;
870 arrays |= 1UL << BPF_PROG_INFO_JITED_KSYMS;
871 arrays |= 1UL << BPF_PROG_INFO_JITED_FUNC_LENS;
872 arrays |= 1UL << BPF_PROG_INFO_FUNC_INFO;
873 arrays |= 1UL << BPF_PROG_INFO_LINE_INFO;
874 arrays |= 1UL << BPF_PROG_INFO_JITED_LINE_INFO;
876 if (json_output && nb_fds > 1)
877 jsonw_start_array(json_wtr); /* root array */
878 for (i = 0; i < nb_fds; i++) {
879 info_linear = bpf_program__get_prog_info_linear(fds[i], arrays);
880 if (IS_ERR_OR_NULL(info_linear)) {
881 p_err("can't get prog info: %s", strerror(errno));
885 if (json_output && nb_fds > 1) {
886 jsonw_start_object(json_wtr); /* prog object */
887 print_prog_header_json(&info_linear->info);
888 jsonw_name(json_wtr, "insns");
889 } else if (nb_fds > 1) {
890 print_prog_header_plain(&info_linear->info);
893 err = prog_dump(&info_linear->info, mode, filepath, opcodes,
896 if (json_output && nb_fds > 1)
897 jsonw_end_object(json_wtr); /* prog object */
898 else if (i != nb_fds - 1 && nb_fds > 1)
906 if (json_output && nb_fds > 1)
907 jsonw_end_array(json_wtr); /* root array */
910 for (; i < nb_fds; i++)
917 static int do_pin(int argc, char **argv)
921 err = do_pin_any(argc, argv, prog_parse_fd);
922 if (!err && json_output)
923 jsonw_null(json_wtr);
933 static int map_replace_compar(const void *p1, const void *p2)
935 const struct map_replace *a = p1, *b = p2;
937 return a->idx - b->idx;
940 static int parse_attach_detach_args(int argc, char **argv, int *progfd,
941 enum bpf_attach_type *attach_type,
947 *progfd = prog_parse_fd(&argc, &argv);
951 *attach_type = parse_attach_type(*argv);
952 if (*attach_type == __MAX_BPF_ATTACH_TYPE) {
953 p_err("invalid attach/detach type");
957 if (*attach_type == BPF_FLOW_DISSECTOR) {
966 *mapfd = map_parse_fd(&argc, &argv);
973 static int do_attach(int argc, char **argv)
975 enum bpf_attach_type attach_type;
979 err = parse_attach_detach_args(argc, argv,
980 &progfd, &attach_type, &mapfd);
984 err = bpf_prog_attach(progfd, mapfd, attach_type, 0);
986 p_err("failed prog attach to map");
991 jsonw_null(json_wtr);
995 static int do_detach(int argc, char **argv)
997 enum bpf_attach_type attach_type;
1001 err = parse_attach_detach_args(argc, argv,
1002 &progfd, &attach_type, &mapfd);
1006 err = bpf_prog_detach2(progfd, mapfd, attach_type);
1008 p_err("failed prog detach from map");
1013 jsonw_null(json_wtr);
1017 static int check_single_stdin(char *file_data_in, char *file_ctx_in)
1019 if (file_data_in && file_ctx_in &&
1020 !strcmp(file_data_in, "-") && !strcmp(file_ctx_in, "-")) {
1021 p_err("cannot use standard input for both data_in and ctx_in");
1028 static int get_run_data(const char *fname, void **data_ptr, unsigned int *size)
1030 size_t block_size = 256;
1031 size_t buf_size = block_size;
1042 if (!strcmp(fname, "-"))
1045 f = fopen(fname, "r");
1047 p_err("failed to open %s: %s", fname, strerror(errno));
1051 *data_ptr = malloc(block_size);
1053 p_err("failed to allocate memory for data_in/ctx_in: %s",
1058 while ((nb_read += fread(*data_ptr + nb_read, 1, block_size, f))) {
1062 p_err("failed to read data_in/ctx_in from %s: %s",
1063 fname, strerror(errno));
1066 if (nb_read > buf_size - block_size) {
1067 if (buf_size == UINT32_MAX) {
1068 p_err("data_in/ctx_in is too long (max: %d)",
1072 /* No space for fread()-ing next chunk; realloc() */
1074 tmp = realloc(*data_ptr, buf_size);
1076 p_err("failed to reallocate data_in/ctx_in: %s",
1098 static void hex_print(void *data, unsigned int size, FILE *f)
1103 for (i = 0; i < size; i += 16) {
1105 fprintf(f, "%07zx\t", i);
1107 /* Hexadecimal values */
1108 for (j = i; j < i + 16 && j < size; j++)
1109 fprintf(f, "%02x%s", *(uint8_t *)(data + j),
1111 for (; j < i + 16; j++)
1112 fprintf(f, " %s", j % 2 ? " " : "");
1114 /* ASCII values (if relevant), '.' otherwise */
1116 for (j = i; j < i + 16 && j < size; j++) {
1117 c = *(char *)(data + j);
1118 if (c < ' ' || c > '~')
1120 fprintf(f, "%c%s", c, j == i + 7 ? " " : "");
1128 print_run_output(void *data, unsigned int size, const char *fname,
1129 const char *json_key)
1137 if (!strcmp(fname, "-")) {
1140 jsonw_name(json_wtr, json_key);
1141 print_data_json(data, size);
1143 hex_print(data, size, f);
1148 f = fopen(fname, "w");
1150 p_err("failed to open %s: %s", fname, strerror(errno));
1154 nb_written = fwrite(data, 1, size, f);
1156 if (nb_written != size) {
1157 p_err("failed to write output data/ctx: %s", strerror(errno));
1164 static int alloc_run_data(void **data_ptr, unsigned int size_out)
1166 *data_ptr = calloc(size_out, 1);
1168 p_err("failed to allocate memory for output data/ctx: %s",
1176 static int do_run(int argc, char **argv)
1178 char *data_fname_in = NULL, *data_fname_out = NULL;
1179 char *ctx_fname_in = NULL, *ctx_fname_out = NULL;
1180 struct bpf_prog_test_run_attr test_attr = {0};
1181 const unsigned int default_size = SZ_32K;
1182 void *data_in = NULL, *data_out = NULL;
1183 void *ctx_in = NULL, *ctx_out = NULL;
1184 unsigned int repeat = 1;
1190 fd = prog_parse_fd(&argc, &argv);
1195 if (detect_common_prefix(*argv, "data_in", "data_out",
1196 "data_size_out", NULL))
1198 if (detect_common_prefix(*argv, "ctx_in", "ctx_out",
1199 "ctx_size_out", NULL))
1202 if (is_prefix(*argv, "data_in")) {
1207 data_fname_in = GET_ARG();
1208 if (check_single_stdin(data_fname_in, ctx_fname_in))
1210 } else if (is_prefix(*argv, "data_out")) {
1215 data_fname_out = GET_ARG();
1216 } else if (is_prefix(*argv, "data_size_out")) {
1223 test_attr.data_size_out = strtoul(*argv, &endptr, 0);
1225 p_err("can't parse %s as output data size",
1230 } else if (is_prefix(*argv, "ctx_in")) {
1235 ctx_fname_in = GET_ARG();
1236 if (check_single_stdin(data_fname_in, ctx_fname_in))
1238 } else if (is_prefix(*argv, "ctx_out")) {
1243 ctx_fname_out = GET_ARG();
1244 } else if (is_prefix(*argv, "ctx_size_out")) {
1251 test_attr.ctx_size_out = strtoul(*argv, &endptr, 0);
1253 p_err("can't parse %s as output context size",
1258 } else if (is_prefix(*argv, "repeat")) {
1265 repeat = strtoul(*argv, &endptr, 0);
1267 p_err("can't parse %s as repeat number",
1273 p_err("expected no more arguments, 'data_in', 'data_out', 'data_size_out', 'ctx_in', 'ctx_out', 'ctx_size_out' or 'repeat', got: '%s'?",
1279 err = get_run_data(data_fname_in, &data_in, &test_attr.data_size_in);
1284 if (!test_attr.data_size_out)
1285 test_attr.data_size_out = default_size;
1286 err = alloc_run_data(&data_out, test_attr.data_size_out);
1291 err = get_run_data(ctx_fname_in, &ctx_in, &test_attr.ctx_size_in);
1296 if (!test_attr.ctx_size_out)
1297 test_attr.ctx_size_out = default_size;
1298 err = alloc_run_data(&ctx_out, test_attr.ctx_size_out);
1303 test_attr.prog_fd = fd;
1304 test_attr.repeat = repeat;
1305 test_attr.data_in = data_in;
1306 test_attr.data_out = data_out;
1307 test_attr.ctx_in = ctx_in;
1308 test_attr.ctx_out = ctx_out;
1310 err = bpf_prog_test_run_xattr(&test_attr);
1312 p_err("failed to run program: %s", strerror(errno));
1319 jsonw_start_object(json_wtr); /* root */
1321 /* Do not exit on errors occurring when printing output data/context,
1322 * we still want to print return value and duration for program run.
1324 if (test_attr.data_size_out)
1325 err += print_run_output(test_attr.data_out,
1326 test_attr.data_size_out,
1327 data_fname_out, "data_out");
1328 if (test_attr.ctx_size_out)
1329 err += print_run_output(test_attr.ctx_out,
1330 test_attr.ctx_size_out,
1331 ctx_fname_out, "ctx_out");
1334 jsonw_uint_field(json_wtr, "retval", test_attr.retval);
1335 jsonw_uint_field(json_wtr, "duration", test_attr.duration);
1336 jsonw_end_object(json_wtr); /* root */
1338 fprintf(stdout, "Return value: %u, duration%s: %uns\n",
1340 repeat > 1 ? " (average)" : "", test_attr.duration);
1356 get_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
1357 enum bpf_attach_type *expected_attach_type)
1359 libbpf_print_fn_t print_backup;
1362 ret = libbpf_prog_type_by_name(name, prog_type, expected_attach_type);
1366 /* libbpf_prog_type_by_name() failed, let's re-run with debug level */
1367 print_backup = libbpf_set_print(print_all_levels);
1368 ret = libbpf_prog_type_by_name(name, prog_type, expected_attach_type);
1369 libbpf_set_print(print_backup);
1374 static int load_with_options(int argc, char **argv, bool first_prog_only)
1376 enum bpf_prog_type common_prog_type = BPF_PROG_TYPE_UNSPEC;
1377 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, open_opts,
1378 .relaxed_maps = relaxed_maps,
1380 struct bpf_object_load_attr load_attr = { 0 };
1381 enum bpf_attach_type expected_attach_type;
1382 struct map_replace *map_replace = NULL;
1383 struct bpf_program *prog = NULL, *pos;
1384 unsigned int old_map_fds = 0;
1385 const char *pinmaps = NULL;
1386 struct bpf_object *obj;
1387 struct bpf_map *map;
1388 const char *pinfile;
1398 pinfile = GET_ARG();
1401 if (is_prefix(*argv, "type")) {
1406 if (common_prog_type != BPF_PROG_TYPE_UNSPEC) {
1407 p_err("program type already specified");
1408 goto err_free_reuse_maps;
1411 goto err_free_reuse_maps;
1413 /* Put a '/' at the end of type to appease libbpf */
1414 type = malloc(strlen(*argv) + 2);
1416 p_err("mem alloc failed");
1417 goto err_free_reuse_maps;
1420 strcat(type, *argv);
1423 err = get_prog_type_by_name(type, &common_prog_type,
1424 &expected_attach_type);
1427 goto err_free_reuse_maps;
1430 } else if (is_prefix(*argv, "map")) {
1431 void *new_map_replace;
1432 char *endptr, *name;
1438 goto err_free_reuse_maps;
1440 if (is_prefix(*argv, "idx")) {
1443 idx = strtoul(*argv, &endptr, 0);
1445 p_err("can't parse %s as IDX", *argv);
1446 goto err_free_reuse_maps;
1449 } else if (is_prefix(*argv, "name")) {
1455 p_err("expected 'idx' or 'name', got: '%s'?",
1457 goto err_free_reuse_maps;
1461 fd = map_parse_fd(&argc, &argv);
1463 goto err_free_reuse_maps;
1465 new_map_replace = reallocarray(map_replace,
1467 sizeof(*map_replace));
1468 if (!new_map_replace) {
1469 p_err("mem alloc failed");
1470 goto err_free_reuse_maps;
1472 map_replace = new_map_replace;
1474 map_replace[old_map_fds].idx = idx;
1475 map_replace[old_map_fds].name = name;
1476 map_replace[old_map_fds].fd = fd;
1478 } else if (is_prefix(*argv, "dev")) {
1482 p_err("offload device already specified");
1483 goto err_free_reuse_maps;
1486 goto err_free_reuse_maps;
1488 ifindex = if_nametoindex(*argv);
1490 p_err("unrecognized netdevice '%s': %s",
1491 *argv, strerror(errno));
1492 goto err_free_reuse_maps;
1495 } else if (is_prefix(*argv, "pinmaps")) {
1499 goto err_free_reuse_maps;
1501 pinmaps = GET_ARG();
1503 p_err("expected no more arguments, 'type', 'map' or 'dev', got: '%s'?",
1505 goto err_free_reuse_maps;
1511 obj = bpf_object__open_file(file, &open_opts);
1512 if (libbpf_get_error(obj)) {
1513 p_err("failed to open object file");
1514 goto err_free_reuse_maps;
1517 bpf_object__for_each_program(pos, obj) {
1518 enum bpf_prog_type prog_type = common_prog_type;
1520 if (prog_type == BPF_PROG_TYPE_UNSPEC) {
1521 const char *sec_name = bpf_program__section_name(pos);
1523 err = get_prog_type_by_name(sec_name, &prog_type,
1524 &expected_attach_type);
1529 bpf_program__set_ifindex(pos, ifindex);
1530 bpf_program__set_type(pos, prog_type);
1531 bpf_program__set_expected_attach_type(pos, expected_attach_type);
1534 qsort(map_replace, old_map_fds, sizeof(*map_replace),
1535 map_replace_compar);
1537 /* After the sort maps by name will be first on the list, because they
1538 * have idx == -1. Resolve them.
1541 while (j < old_map_fds && map_replace[j].name) {
1543 bpf_object__for_each_map(map, obj) {
1544 if (!strcmp(bpf_map__name(map), map_replace[j].name)) {
1545 map_replace[j].idx = i;
1550 if (map_replace[j].idx == -1) {
1551 p_err("unable to find map '%s'", map_replace[j].name);
1556 /* Resort if any names were resolved */
1558 qsort(map_replace, old_map_fds, sizeof(*map_replace),
1559 map_replace_compar);
1561 /* Set ifindex and name reuse */
1564 bpf_object__for_each_map(map, obj) {
1565 if (!bpf_map__is_offload_neutral(map))
1566 bpf_map__set_ifindex(map, ifindex);
1568 if (j < old_map_fds && idx == map_replace[j].idx) {
1569 err = bpf_map__reuse_fd(map, map_replace[j++].fd);
1571 p_err("unable to set up map reuse: %d", err);
1575 /* Next reuse wants to apply to the same map */
1576 if (j < old_map_fds && map_replace[j].idx == idx) {
1577 p_err("replacement for map idx %d specified more than once",
1585 if (j < old_map_fds) {
1586 p_err("map idx '%d' not used", map_replace[j].idx);
1590 load_attr.obj = obj;
1592 /* log_level1 + log_level2 + stats, but not stable UAPI */
1593 load_attr.log_level = 1 + 2 + 4;
1595 err = bpf_object__load_xattr(&load_attr);
1597 p_err("failed to load object file");
1601 err = mount_bpffs_for_pin(pinfile);
1605 if (first_prog_only) {
1606 prog = bpf_program__next(NULL, obj);
1608 p_err("object file doesn't contain any bpf program");
1612 err = bpf_obj_pin(bpf_program__fd(prog), pinfile);
1614 p_err("failed to pin program %s",
1615 bpf_program__section_name(prog));
1619 err = bpf_object__pin_programs(obj, pinfile);
1621 p_err("failed to pin all programs");
1627 err = bpf_object__pin_maps(obj, pinmaps);
1629 p_err("failed to pin all maps");
1635 jsonw_null(json_wtr);
1637 bpf_object__close(obj);
1638 for (i = 0; i < old_map_fds; i++)
1639 close(map_replace[i].fd);
1645 if (first_prog_only)
1648 bpf_object__unpin_programs(obj, pinfile);
1650 bpf_object__close(obj);
1651 err_free_reuse_maps:
1652 for (i = 0; i < old_map_fds; i++)
1653 close(map_replace[i].fd);
1658 static int count_open_fds(void)
1660 DIR *dp = opendir("/proc/self/fd");
1667 while ((de = readdir(dp)))
1674 static int try_loader(struct gen_loader_opts *gen)
1676 struct bpf_load_and_run_opts opts = {};
1677 struct bpf_loader_ctx *ctx;
1678 int ctx_sz = sizeof(*ctx) + 64 * max(sizeof(struct bpf_map_desc),
1679 sizeof(struct bpf_prog_desc));
1680 int log_buf_sz = (1u << 24) - 1;
1681 int err, fds_before, fd_delta;
1684 ctx = alloca(ctx_sz);
1685 memset(ctx, 0, ctx_sz);
1688 ctx->log_size = log_buf_sz;
1689 log_buf = malloc(log_buf_sz);
1692 ctx->log_buf = (long) log_buf;
1694 opts.data = gen->data;
1695 opts.data_sz = gen->data_sz;
1696 opts.insns = gen->insns;
1697 opts.insns_sz = gen->insns_sz;
1698 fds_before = count_open_fds();
1699 err = bpf_load_and_run(&opts);
1700 fd_delta = count_open_fds() - fds_before;
1702 fprintf(stderr, "err %d\n%s\n%s", err, opts.errstr, log_buf);
1704 fprintf(stderr, "loader prog leaked %d FDs\n",
1711 static int do_loader(int argc, char **argv)
1713 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, open_opts);
1714 DECLARE_LIBBPF_OPTS(gen_loader_opts, gen);
1715 struct bpf_object_load_attr load_attr = {};
1716 struct bpf_object *obj;
1724 obj = bpf_object__open_file(file, &open_opts);
1725 if (libbpf_get_error(obj)) {
1726 p_err("failed to open object file");
1730 err = bpf_object__gen_loader(obj, &gen);
1734 load_attr.obj = obj;
1736 /* log_level1 + log_level2 + stats, but not stable UAPI */
1737 load_attr.log_level = 1 + 2 + 4;
1739 err = bpf_object__load_xattr(&load_attr);
1741 p_err("failed to load object file");
1745 if (verifier_logs) {
1746 struct dump_data dd = {};
1748 kernel_syms_load(&dd);
1749 dump_xlated_plain(&dd, (void *)gen.insns, gen.insns_sz, false, false);
1750 kernel_syms_destroy(&dd);
1752 err = try_loader(&gen);
1754 bpf_object__close(obj);
1758 static int do_load(int argc, char **argv)
1761 return do_loader(argc, argv);
1762 return load_with_options(argc, argv, true);
1765 static int do_loadall(int argc, char **argv)
1767 return load_with_options(argc, argv, false);
1770 #ifdef BPFTOOL_WITHOUT_SKELETONS
1772 static int do_profile(int argc, char **argv)
1774 p_err("bpftool prog profile command is not supported. Please build bpftool with clang >= 10.0.0");
1778 #else /* BPFTOOL_WITHOUT_SKELETONS */
1780 #include "profiler.skel.h"
1782 struct profile_metric {
1784 struct bpf_perf_event_value val;
1785 struct perf_event_attr attr;
1788 /* calculate ratios like instructions per cycle */
1789 const int ratio_metric; /* 0 for N/A, 1 for index 0 (cycles) */
1790 const char *ratio_desc;
1791 const float ratio_mul;
1796 .type = PERF_TYPE_HARDWARE,
1797 .config = PERF_COUNT_HW_CPU_CYCLES,
1802 .name = "instructions",
1804 .type = PERF_TYPE_HARDWARE,
1805 .config = PERF_COUNT_HW_INSTRUCTIONS,
1809 .ratio_desc = "insns per cycle",
1813 .name = "l1d_loads",
1815 .type = PERF_TYPE_HW_CACHE,
1817 PERF_COUNT_HW_CACHE_L1D |
1818 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1819 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16),
1824 .name = "llc_misses",
1826 .type = PERF_TYPE_HW_CACHE,
1828 PERF_COUNT_HW_CACHE_LL |
1829 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1830 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16),
1834 .ratio_desc = "LLC misses per million insns",
1838 .name = "itlb_misses",
1840 .type = PERF_TYPE_HW_CACHE,
1842 PERF_COUNT_HW_CACHE_ITLB |
1843 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1844 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16),
1848 .ratio_desc = "itlb misses per million insns",
1852 .name = "dtlb_misses",
1854 .type = PERF_TYPE_HW_CACHE,
1856 PERF_COUNT_HW_CACHE_DTLB |
1857 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1858 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16),
1862 .ratio_desc = "dtlb misses per million insns",
1867 static __u64 profile_total_count;
1869 #define MAX_NUM_PROFILE_METRICS 4
1871 static int profile_parse_metrics(int argc, char **argv)
1873 unsigned int metric_cnt;
1874 int selected_cnt = 0;
1877 metric_cnt = sizeof(metrics) / sizeof(struct profile_metric);
1880 for (i = 0; i < metric_cnt; i++) {
1881 if (is_prefix(argv[0], metrics[i].name)) {
1882 if (!metrics[i].selected)
1884 metrics[i].selected = true;
1888 if (i == metric_cnt) {
1889 p_err("unknown metric %s", argv[0]);
1894 if (selected_cnt > MAX_NUM_PROFILE_METRICS) {
1895 p_err("too many (%d) metrics, please specify no more than %d metrics at at time",
1896 selected_cnt, MAX_NUM_PROFILE_METRICS);
1899 return selected_cnt;
1902 static void profile_read_values(struct profiler_bpf *obj)
1904 __u32 m, cpu, num_cpu = obj->rodata->num_cpu;
1905 int reading_map_fd, count_map_fd;
1906 __u64 counts[num_cpu];
1910 reading_map_fd = bpf_map__fd(obj->maps.accum_readings);
1911 count_map_fd = bpf_map__fd(obj->maps.counts);
1912 if (reading_map_fd < 0 || count_map_fd < 0) {
1913 p_err("failed to get fd for map");
1917 err = bpf_map_lookup_elem(count_map_fd, &key, counts);
1919 p_err("failed to read count_map: %s", strerror(errno));
1923 profile_total_count = 0;
1924 for (cpu = 0; cpu < num_cpu; cpu++)
1925 profile_total_count += counts[cpu];
1927 for (m = 0; m < ARRAY_SIZE(metrics); m++) {
1928 struct bpf_perf_event_value values[num_cpu];
1930 if (!metrics[m].selected)
1933 err = bpf_map_lookup_elem(reading_map_fd, &key, values);
1935 p_err("failed to read reading_map: %s",
1939 for (cpu = 0; cpu < num_cpu; cpu++) {
1940 metrics[m].val.counter += values[cpu].counter;
1941 metrics[m].val.enabled += values[cpu].enabled;
1942 metrics[m].val.running += values[cpu].running;
1948 static void profile_print_readings_json(void)
1952 jsonw_start_array(json_wtr);
1953 for (m = 0; m < ARRAY_SIZE(metrics); m++) {
1954 if (!metrics[m].selected)
1956 jsonw_start_object(json_wtr);
1957 jsonw_string_field(json_wtr, "metric", metrics[m].name);
1958 jsonw_lluint_field(json_wtr, "run_cnt", profile_total_count);
1959 jsonw_lluint_field(json_wtr, "value", metrics[m].val.counter);
1960 jsonw_lluint_field(json_wtr, "enabled", metrics[m].val.enabled);
1961 jsonw_lluint_field(json_wtr, "running", metrics[m].val.running);
1963 jsonw_end_object(json_wtr);
1965 jsonw_end_array(json_wtr);
1968 static void profile_print_readings_plain(void)
1972 printf("\n%18llu %-20s\n", profile_total_count, "run_cnt");
1973 for (m = 0; m < ARRAY_SIZE(metrics); m++) {
1974 struct bpf_perf_event_value *val = &metrics[m].val;
1977 if (!metrics[m].selected)
1979 printf("%18llu %-20s", val->counter, metrics[m].name);
1981 r = metrics[m].ratio_metric - 1;
1982 if (r >= 0 && metrics[r].selected &&
1983 metrics[r].val.counter > 0) {
1984 printf("# %8.2f %-30s",
1985 val->counter * metrics[m].ratio_mul /
1986 metrics[r].val.counter,
1987 metrics[m].ratio_desc);
1989 printf("%-41s", "");
1992 if (val->enabled > val->running)
1994 val->running * 100.0 / val->enabled);
1999 static void profile_print_readings(void)
2002 profile_print_readings_json();
2004 profile_print_readings_plain();
2007 static char *profile_target_name(int tgt_fd)
2009 struct bpf_prog_info_linear *info_linear;
2010 struct bpf_func_info *func_info;
2011 const struct btf_type *t;
2012 struct btf *btf = NULL;
2015 info_linear = bpf_program__get_prog_info_linear(
2016 tgt_fd, 1UL << BPF_PROG_INFO_FUNC_INFO);
2017 if (IS_ERR_OR_NULL(info_linear)) {
2018 p_err("failed to get info_linear for prog FD %d", tgt_fd);
2022 if (info_linear->info.btf_id == 0) {
2023 p_err("prog FD %d doesn't have valid btf", tgt_fd);
2027 btf = btf__load_from_kernel_by_id(info_linear->info.btf_id);
2028 if (libbpf_get_error(btf)) {
2029 p_err("failed to load btf for prog FD %d", tgt_fd);
2033 func_info = u64_to_ptr(info_linear->info.func_info);
2034 t = btf__type_by_id(btf, func_info[0].type_id);
2036 p_err("btf %d doesn't have type %d",
2037 info_linear->info.btf_id, func_info[0].type_id);
2040 name = strdup(btf__name_by_offset(btf, t->name_off));
2047 static struct profiler_bpf *profile_obj;
2048 static int profile_tgt_fd = -1;
2049 static char *profile_tgt_name;
2050 static int *profile_perf_events;
2051 static int profile_perf_event_cnt;
2053 static void profile_close_perf_events(struct profiler_bpf *obj)
2057 for (i = profile_perf_event_cnt - 1; i >= 0; i--)
2058 close(profile_perf_events[i]);
2060 free(profile_perf_events);
2061 profile_perf_event_cnt = 0;
2064 static int profile_open_perf_events(struct profiler_bpf *obj)
2066 unsigned int cpu, m;
2069 profile_perf_events = calloc(
2070 sizeof(int), obj->rodata->num_cpu * obj->rodata->num_metric);
2071 if (!profile_perf_events) {
2072 p_err("failed to allocate memory for perf_event array: %s",
2076 map_fd = bpf_map__fd(obj->maps.events);
2078 p_err("failed to get fd for events map");
2082 for (m = 0; m < ARRAY_SIZE(metrics); m++) {
2083 if (!metrics[m].selected)
2085 for (cpu = 0; cpu < obj->rodata->num_cpu; cpu++) {
2086 pmu_fd = syscall(__NR_perf_event_open, &metrics[m].attr,
2087 -1/*pid*/, cpu, -1/*group_fd*/, 0);
2089 bpf_map_update_elem(map_fd, &profile_perf_event_cnt,
2090 &pmu_fd, BPF_ANY) ||
2091 ioctl(pmu_fd, PERF_EVENT_IOC_ENABLE, 0)) {
2092 p_err("failed to create event %s on cpu %d",
2093 metrics[m].name, cpu);
2096 profile_perf_events[profile_perf_event_cnt++] = pmu_fd;
2102 static void profile_print_and_cleanup(void)
2104 profile_close_perf_events(profile_obj);
2105 profile_read_values(profile_obj);
2106 profile_print_readings();
2107 profiler_bpf__destroy(profile_obj);
2109 close(profile_tgt_fd);
2110 free(profile_tgt_name);
2113 static void int_exit(int signo)
2115 profile_print_and_cleanup();
2119 static int do_profile(int argc, char **argv)
2121 int num_metric, num_cpu, err = -1;
2122 struct bpf_program *prog;
2123 unsigned long duration;
2126 /* we at least need two args for the prog and one metric */
2130 /* parse target fd */
2131 profile_tgt_fd = prog_parse_fd(&argc, &argv);
2132 if (profile_tgt_fd < 0) {
2133 p_err("failed to parse fd");
2137 /* parse profiling optional duration */
2138 if (argc > 2 && is_prefix(argv[0], "duration")) {
2140 duration = strtoul(*argv, &endptr, 0);
2145 duration = UINT_MAX;
2148 num_metric = profile_parse_metrics(argc, argv);
2149 if (num_metric <= 0)
2152 num_cpu = libbpf_num_possible_cpus();
2154 p_err("failed to identify number of CPUs");
2158 profile_obj = profiler_bpf__open();
2160 p_err("failed to open and/or load BPF object");
2164 profile_obj->rodata->num_cpu = num_cpu;
2165 profile_obj->rodata->num_metric = num_metric;
2167 /* adjust map sizes */
2168 bpf_map__resize(profile_obj->maps.events, num_metric * num_cpu);
2169 bpf_map__resize(profile_obj->maps.fentry_readings, num_metric);
2170 bpf_map__resize(profile_obj->maps.accum_readings, num_metric);
2171 bpf_map__resize(profile_obj->maps.counts, 1);
2173 /* change target name */
2174 profile_tgt_name = profile_target_name(profile_tgt_fd);
2175 if (!profile_tgt_name)
2178 bpf_object__for_each_program(prog, profile_obj->obj) {
2179 err = bpf_program__set_attach_target(prog, profile_tgt_fd,
2182 p_err("failed to set attach target\n");
2188 err = profiler_bpf__load(profile_obj);
2190 p_err("failed to load profile_obj");
2194 err = profile_open_perf_events(profile_obj);
2198 err = profiler_bpf__attach(profile_obj);
2200 p_err("failed to attach profile_obj");
2203 signal(SIGINT, int_exit);
2206 profile_print_and_cleanup();
2210 profile_close_perf_events(profile_obj);
2212 profiler_bpf__destroy(profile_obj);
2213 close(profile_tgt_fd);
2214 free(profile_tgt_name);
2218 #endif /* BPFTOOL_WITHOUT_SKELETONS */
2220 static int do_help(int argc, char **argv)
2223 jsonw_null(json_wtr);
2228 "Usage: %1$s %2$s { show | list } [PROG]\n"
2229 " %1$s %2$s dump xlated PROG [{ file FILE | opcodes | visual | linum }]\n"
2230 " %1$s %2$s dump jited PROG [{ file FILE | opcodes | linum }]\n"
2231 " %1$s %2$s pin PROG FILE\n"
2232 " %1$s %2$s { load | loadall } OBJ PATH \\\n"
2233 " [type TYPE] [dev NAME] \\\n"
2234 " [map { idx IDX | name NAME } MAP]\\\n"
2235 " [pinmaps MAP_DIR]\n"
2236 " %1$s %2$s attach PROG ATTACH_TYPE [MAP]\n"
2237 " %1$s %2$s detach PROG ATTACH_TYPE [MAP]\n"
2238 " %1$s %2$s run PROG \\\n"
2239 " data_in FILE \\\n"
2240 " [data_out FILE [data_size_out L]] \\\n"
2241 " [ctx_in FILE [ctx_out FILE [ctx_size_out M]]] \\\n"
2243 " %1$s %2$s profile PROG [duration DURATION] METRICs\n"
2244 " %1$s %2$s tracelog\n"
2247 " " HELP_SPEC_MAP "\n"
2248 " " HELP_SPEC_PROGRAM "\n"
2249 " TYPE := { socket | kprobe | kretprobe | classifier | action |\n"
2250 " tracepoint | raw_tracepoint | xdp | perf_event | cgroup/skb |\n"
2251 " cgroup/sock | cgroup/dev | lwt_in | lwt_out | lwt_xmit |\n"
2252 " lwt_seg6local | sockops | sk_skb | sk_msg | lirc_mode2 |\n"
2253 " sk_reuseport | flow_dissector | cgroup/sysctl |\n"
2254 " cgroup/bind4 | cgroup/bind6 | cgroup/post_bind4 |\n"
2255 " cgroup/post_bind6 | cgroup/connect4 | cgroup/connect6 |\n"
2256 " cgroup/getpeername4 | cgroup/getpeername6 |\n"
2257 " cgroup/getsockname4 | cgroup/getsockname6 | cgroup/sendmsg4 |\n"
2258 " cgroup/sendmsg6 | cgroup/recvmsg4 | cgroup/recvmsg6 |\n"
2259 " cgroup/getsockopt | cgroup/setsockopt | cgroup/sock_release |\n"
2260 " struct_ops | fentry | fexit | freplace | sk_lookup }\n"
2261 " ATTACH_TYPE := { msg_verdict | skb_verdict | stream_verdict |\n"
2262 " stream_parser | flow_dissector }\n"
2263 " METRIC := { cycles | instructions | l1d_loads | llc_misses | itlb_misses | dtlb_misses }\n"
2264 " " HELP_SPEC_OPTIONS " |\n"
2265 " {-f|--bpffs} | {-m|--mapcompat} | {-n|--nomount} |\n"
2266 " {-L|--use-loader} }\n"
2268 bin_name, argv[-2]);
2273 static const struct cmd cmds[] = {
2274 { "show", do_show },
2275 { "list", do_show },
2276 { "help", do_help },
2277 { "dump", do_dump },
2279 { "load", do_load },
2280 { "loadall", do_loadall },
2281 { "attach", do_attach },
2282 { "detach", do_detach },
2283 { "tracelog", do_tracelog },
2285 { "profile", do_profile },
2289 int do_prog(int argc, char **argv)
2291 return cmd_select(cmds, argc, argv, do_help);