4 * Builtin 'trace' command:
6 * Display a continuously updated trace of any workload, CPU, specific PID,
7 * system wide, etc. Default format is loosely strace like, but any other
8 * event may be specified using --event.
10 * Copyright (C) 2012, 2013, 2014, 2015 Red Hat Inc, Arnaldo Carvalho de Melo <acme@redhat.com>
12 * Initially based on the 'trace' prototype by Thomas Gleixner:
14 * http://lwn.net/Articles/415728/ ("Announcing a new utility: 'trace'")
17 #include "util/record.h"
18 #include <traceevent/event-parse.h>
19 #include <api/fs/tracing_path.h>
21 #include "util/bpf_map.h"
22 #include "util/rlimit.h"
24 #include "util/cgroup.h"
25 #include "util/color.h"
26 #include "util/config.h"
27 #include "util/debug.h"
30 #include "util/event.h"
31 #include "util/evsel.h"
32 #include "util/evsel_fprintf.h"
33 #include "util/synthetic-events.h"
34 #include "util/evlist.h"
35 #include "util/evswitch.h"
36 #include "util/mmap.h"
37 #include <subcmd/pager.h>
38 #include <subcmd/exec-cmd.h>
39 #include "util/machine.h"
41 #include "util/symbol.h"
42 #include "util/path.h"
43 #include "util/session.h"
44 #include "util/thread.h"
45 #include <subcmd/parse-options.h>
46 #include "util/strlist.h"
47 #include "util/intlist.h"
48 #include "util/thread_map.h"
49 #include "util/stat.h"
50 #include "util/tool.h"
51 #include "util/util.h"
52 #include "trace/beauty/beauty.h"
53 #include "trace-event.h"
54 #include "util/parse-events.h"
55 #include "util/bpf-loader.h"
56 #include "callchain.h"
57 #include "print_binary.h"
59 #include "syscalltbl.h"
60 #include "rb_resort.h"
69 #include <linux/err.h>
70 #include <linux/filter.h>
71 #include <linux/kernel.h>
72 #include <linux/random.h>
73 #include <linux/stringify.h>
74 #include <linux/time64.h>
75 #include <linux/zalloc.h>
77 #include <sys/sysmacros.h>
79 #include <linux/ctype.h>
80 #include <perf/mmap.h>
83 # define O_CLOEXEC 02000000
86 #ifndef F_LINUX_SPECIFIC_BASE
87 # define F_LINUX_SPECIFIC_BASE 1024
91 * strtoul: Go from a string to a value, i.e. for msr: MSR_FS_BASE to 0xc0000100
93 struct syscall_arg_fmt {
94 size_t (*scnprintf)(char *bf, size_t size, struct syscall_arg *arg);
95 bool (*strtoul)(char *bf, size_t size, struct syscall_arg *arg, u64 *val);
96 unsigned long (*mask_val)(struct syscall_arg *arg, unsigned long val);
99 u16 nr_entries; // for arrays
107 const char *sys_enter,
110 struct syscall_arg_fmt arg[6];
118 struct perf_tool tool;
119 struct syscalltbl *sctbl;
121 struct syscall *table;
123 struct { // per syscall BPF_MAP_TYPE_PROG_ARRAY
124 struct bpf_map *sys_enter,
128 struct evsel *sys_enter,
132 struct bpf_program *unaugmented_prog;
137 struct record_opts opts;
138 struct evlist *evlist;
139 struct machine *host;
140 struct thread *current;
141 struct bpf_object *bpf_obj;
142 struct cgroup *cgroup;
145 unsigned long nr_events;
146 unsigned long nr_events_printed;
147 unsigned long max_events;
148 struct evswitch evswitch;
149 struct strlist *ev_qualifier;
159 double duration_filter;
165 unsigned int max_stack;
166 unsigned int min_stack;
167 int raw_augmented_syscalls_args_size;
168 bool raw_augmented_syscalls;
169 bool fd_path_disabled;
171 bool not_ev_qualifier;
175 bool multiple_threads;
182 bool show_tool_stats;
184 bool libtraceevent_print;
185 bool kernel_syscallchains;
191 bool show_string_prefix;
195 char *perfconfig_events;
197 struct ordered_events data;
205 u64 (*integer)(struct tp_field *field, struct perf_sample *sample);
206 void *(*pointer)(struct tp_field *field, struct perf_sample *sample);
210 #define TP_UINT_FIELD(bits) \
211 static u64 tp_field__u##bits(struct tp_field *field, struct perf_sample *sample) \
214 memcpy(&value, sample->raw_data + field->offset, sizeof(value)); \
223 #define TP_UINT_FIELD__SWAPPED(bits) \
224 static u64 tp_field__swapped_u##bits(struct tp_field *field, struct perf_sample *sample) \
227 memcpy(&value, sample->raw_data + field->offset, sizeof(value)); \
228 return bswap_##bits(value);\
231 TP_UINT_FIELD__SWAPPED(16);
232 TP_UINT_FIELD__SWAPPED(32);
233 TP_UINT_FIELD__SWAPPED(64);
235 static int __tp_field__init_uint(struct tp_field *field, int size, int offset, bool needs_swap)
237 field->offset = offset;
241 field->integer = tp_field__u8;
244 field->integer = needs_swap ? tp_field__swapped_u16 : tp_field__u16;
247 field->integer = needs_swap ? tp_field__swapped_u32 : tp_field__u32;
250 field->integer = needs_swap ? tp_field__swapped_u64 : tp_field__u64;
259 static int tp_field__init_uint(struct tp_field *field, struct tep_format_field *format_field, bool needs_swap)
261 return __tp_field__init_uint(field, format_field->size, format_field->offset, needs_swap);
264 static void *tp_field__ptr(struct tp_field *field, struct perf_sample *sample)
266 return sample->raw_data + field->offset;
269 static int __tp_field__init_ptr(struct tp_field *field, int offset)
271 field->offset = offset;
272 field->pointer = tp_field__ptr;
276 static int tp_field__init_ptr(struct tp_field *field, struct tep_format_field *format_field)
278 return __tp_field__init_ptr(field, format_field->offset);
284 struct tp_field args, ret;
289 * The evsel->priv as used by 'perf trace'
290 * sc: for raw_syscalls:sys_{enter,exit} and syscalls:sys_{enter,exit}_SYSCALLNAME
291 * fmt: for all the other tracepoints
294 struct syscall_tp sc;
295 struct syscall_arg_fmt *fmt;
298 static struct evsel_trace *evsel_trace__new(void)
300 return zalloc(sizeof(struct evsel_trace));
303 static void evsel_trace__delete(struct evsel_trace *et)
313 * Used with raw_syscalls:sys_{enter,exit} and with the
314 * syscalls:sys_{enter,exit}_SYSCALL tracepoints
316 static inline struct syscall_tp *__evsel__syscall_tp(struct evsel *evsel)
318 struct evsel_trace *et = evsel->priv;
323 static struct syscall_tp *evsel__syscall_tp(struct evsel *evsel)
325 if (evsel->priv == NULL) {
326 evsel->priv = evsel_trace__new();
327 if (evsel->priv == NULL)
331 return __evsel__syscall_tp(evsel);
335 * Used with all the other tracepoints.
337 static inline struct syscall_arg_fmt *__evsel__syscall_arg_fmt(struct evsel *evsel)
339 struct evsel_trace *et = evsel->priv;
344 static struct syscall_arg_fmt *evsel__syscall_arg_fmt(struct evsel *evsel)
346 struct evsel_trace *et = evsel->priv;
348 if (evsel->priv == NULL) {
349 et = evsel->priv = evsel_trace__new();
355 if (et->fmt == NULL) {
356 et->fmt = calloc(evsel->tp_format->format.nr_fields, sizeof(struct syscall_arg_fmt));
361 return __evsel__syscall_arg_fmt(evsel);
364 evsel_trace__delete(evsel->priv);
369 static int perf_evsel__init_tp_uint_field(struct evsel *evsel,
370 struct tp_field *field,
373 struct tep_format_field *format_field = perf_evsel__field(evsel, name);
375 if (format_field == NULL)
378 return tp_field__init_uint(field, format_field, evsel->needs_swap);
381 #define perf_evsel__init_sc_tp_uint_field(evsel, name) \
382 ({ struct syscall_tp *sc = __evsel__syscall_tp(evsel);\
383 perf_evsel__init_tp_uint_field(evsel, &sc->name, #name); })
385 static int perf_evsel__init_tp_ptr_field(struct evsel *evsel,
386 struct tp_field *field,
389 struct tep_format_field *format_field = perf_evsel__field(evsel, name);
391 if (format_field == NULL)
394 return tp_field__init_ptr(field, format_field);
397 #define perf_evsel__init_sc_tp_ptr_field(evsel, name) \
398 ({ struct syscall_tp *sc = __evsel__syscall_tp(evsel);\
399 perf_evsel__init_tp_ptr_field(evsel, &sc->name, #name); })
401 static void evsel__delete_priv(struct evsel *evsel)
404 evsel__delete(evsel);
407 static int perf_evsel__init_syscall_tp(struct evsel *evsel)
409 struct syscall_tp *sc = evsel__syscall_tp(evsel);
412 if (perf_evsel__init_tp_uint_field(evsel, &sc->id, "__syscall_nr") &&
413 perf_evsel__init_tp_uint_field(evsel, &sc->id, "nr"))
421 static int perf_evsel__init_augmented_syscall_tp(struct evsel *evsel, struct evsel *tp)
423 struct syscall_tp *sc = evsel__syscall_tp(evsel);
426 struct tep_format_field *syscall_id = perf_evsel__field(tp, "id");
427 if (syscall_id == NULL)
428 syscall_id = perf_evsel__field(tp, "__syscall_nr");
429 if (syscall_id == NULL ||
430 __tp_field__init_uint(&sc->id, syscall_id->size, syscall_id->offset, evsel->needs_swap))
439 static int perf_evsel__init_augmented_syscall_tp_args(struct evsel *evsel)
441 struct syscall_tp *sc = __evsel__syscall_tp(evsel);
443 return __tp_field__init_ptr(&sc->args, sc->id.offset + sizeof(u64));
446 static int perf_evsel__init_augmented_syscall_tp_ret(struct evsel *evsel)
448 struct syscall_tp *sc = __evsel__syscall_tp(evsel);
450 return __tp_field__init_uint(&sc->ret, sizeof(u64), sc->id.offset + sizeof(u64), evsel->needs_swap);
453 static int perf_evsel__init_raw_syscall_tp(struct evsel *evsel, void *handler)
455 if (evsel__syscall_tp(evsel) != NULL) {
456 if (perf_evsel__init_sc_tp_uint_field(evsel, id))
459 evsel->handler = handler;
466 static struct evsel *perf_evsel__raw_syscall_newtp(const char *direction, void *handler)
468 struct evsel *evsel = perf_evsel__newtp("raw_syscalls", direction);
470 /* older kernel (e.g., RHEL6) use syscalls:{enter,exit} */
472 evsel = perf_evsel__newtp("syscalls", direction);
477 if (perf_evsel__init_raw_syscall_tp(evsel, handler))
483 evsel__delete_priv(evsel);
487 #define perf_evsel__sc_tp_uint(evsel, name, sample) \
488 ({ struct syscall_tp *fields = __evsel__syscall_tp(evsel); \
489 fields->name.integer(&fields->name, sample); })
491 #define perf_evsel__sc_tp_ptr(evsel, name, sample) \
492 ({ struct syscall_tp *fields = __evsel__syscall_tp(evsel); \
493 fields->name.pointer(&fields->name, sample); })
495 size_t strarray__scnprintf_suffix(struct strarray *sa, char *bf, size_t size, const char *intfmt, bool show_suffix, int val)
497 int idx = val - sa->offset;
499 if (idx < 0 || idx >= sa->nr_entries || sa->entries[idx] == NULL) {
500 size_t printed = scnprintf(bf, size, intfmt, val);
502 printed += scnprintf(bf + printed, size - printed, " /* %s??? */", sa->prefix);
506 return scnprintf(bf, size, "%s%s", sa->entries[idx], show_suffix ? sa->prefix : "");
509 size_t strarray__scnprintf(struct strarray *sa, char *bf, size_t size, const char *intfmt, bool show_prefix, int val)
511 int idx = val - sa->offset;
513 if (idx < 0 || idx >= sa->nr_entries || sa->entries[idx] == NULL) {
514 size_t printed = scnprintf(bf, size, intfmt, val);
516 printed += scnprintf(bf + printed, size - printed, " /* %s??? */", sa->prefix);
520 return scnprintf(bf, size, "%s%s", show_prefix ? sa->prefix : "", sa->entries[idx]);
523 static size_t __syscall_arg__scnprintf_strarray(char *bf, size_t size,
525 struct syscall_arg *arg)
527 return strarray__scnprintf(arg->parm, bf, size, intfmt, arg->show_string_prefix, arg->val);
530 static size_t syscall_arg__scnprintf_strarray(char *bf, size_t size,
531 struct syscall_arg *arg)
533 return __syscall_arg__scnprintf_strarray(bf, size, "%d", arg);
536 #define SCA_STRARRAY syscall_arg__scnprintf_strarray
538 bool syscall_arg__strtoul_strarray(char *bf, size_t size, struct syscall_arg *arg, u64 *ret)
540 return strarray__strtoul(arg->parm, bf, size, ret);
543 bool syscall_arg__strtoul_strarrays(char *bf, size_t size, struct syscall_arg *arg, u64 *ret)
545 return strarrays__strtoul(arg->parm, bf, size, ret);
548 size_t syscall_arg__scnprintf_strarray_flags(char *bf, size_t size, struct syscall_arg *arg)
550 return strarray__scnprintf_flags(arg->parm, bf, size, arg->show_string_prefix, arg->val);
553 size_t strarrays__scnprintf(struct strarrays *sas, char *bf, size_t size, const char *intfmt, bool show_prefix, int val)
558 for (i = 0; i < sas->nr_entries; ++i) {
559 struct strarray *sa = sas->entries[i];
560 int idx = val - sa->offset;
562 if (idx >= 0 && idx < sa->nr_entries) {
563 if (sa->entries[idx] == NULL)
565 return scnprintf(bf, size, "%s%s", show_prefix ? sa->prefix : "", sa->entries[idx]);
569 printed = scnprintf(bf, size, intfmt, val);
571 printed += scnprintf(bf + printed, size - printed, " /* %s??? */", sas->entries[0]->prefix);
575 bool strarray__strtoul(struct strarray *sa, char *bf, size_t size, u64 *ret)
579 for (i = 0; i < sa->nr_entries; ++i) {
580 if (sa->entries[i] && strncmp(sa->entries[i], bf, size) == 0 && sa->entries[i][size] == '\0') {
581 *ret = sa->offset + i;
589 bool strarrays__strtoul(struct strarrays *sas, char *bf, size_t size, u64 *ret)
593 for (i = 0; i < sas->nr_entries; ++i) {
594 struct strarray *sa = sas->entries[i];
596 if (strarray__strtoul(sa, bf, size, ret))
603 size_t syscall_arg__scnprintf_strarrays(char *bf, size_t size,
604 struct syscall_arg *arg)
606 return strarrays__scnprintf(arg->parm, bf, size, "%d", arg->show_string_prefix, arg->val);
610 #define AT_FDCWD -100
613 static size_t syscall_arg__scnprintf_fd_at(char *bf, size_t size,
614 struct syscall_arg *arg)
617 const char *prefix = "AT_FD";
620 return scnprintf(bf, size, "%s%s", arg->show_string_prefix ? prefix : "", "CWD");
622 return syscall_arg__scnprintf_fd(bf, size, arg);
625 #define SCA_FDAT syscall_arg__scnprintf_fd_at
627 static size_t syscall_arg__scnprintf_close_fd(char *bf, size_t size,
628 struct syscall_arg *arg);
630 #define SCA_CLOSE_FD syscall_arg__scnprintf_close_fd
632 size_t syscall_arg__scnprintf_hex(char *bf, size_t size, struct syscall_arg *arg)
634 return scnprintf(bf, size, "%#lx", arg->val);
637 size_t syscall_arg__scnprintf_ptr(char *bf, size_t size, struct syscall_arg *arg)
640 return scnprintf(bf, size, "NULL");
641 return syscall_arg__scnprintf_hex(bf, size, arg);
644 size_t syscall_arg__scnprintf_int(char *bf, size_t size, struct syscall_arg *arg)
646 return scnprintf(bf, size, "%d", arg->val);
649 size_t syscall_arg__scnprintf_long(char *bf, size_t size, struct syscall_arg *arg)
651 return scnprintf(bf, size, "%ld", arg->val);
654 static size_t syscall_arg__scnprintf_char_array(char *bf, size_t size, struct syscall_arg *arg)
656 // XXX Hey, maybe for sched:sched_switch prev/next comm fields we can
657 // fill missing comms using thread__set_comm()...
658 // here or in a special syscall_arg__scnprintf_pid_sched_tp...
659 return scnprintf(bf, size, "\"%-.*s\"", arg->fmt->nr_entries ?: arg->len, arg->val);
662 #define SCA_CHAR_ARRAY syscall_arg__scnprintf_char_array
664 static const char *bpf_cmd[] = {
665 "MAP_CREATE", "MAP_LOOKUP_ELEM", "MAP_UPDATE_ELEM", "MAP_DELETE_ELEM",
666 "MAP_GET_NEXT_KEY", "PROG_LOAD",
668 static DEFINE_STRARRAY(bpf_cmd, "BPF_");
670 static const char *fsmount_flags[] = {
673 static DEFINE_STRARRAY(fsmount_flags, "FSMOUNT_");
675 #include "trace/beauty/generated/fsconfig_arrays.c"
677 static DEFINE_STRARRAY(fsconfig_cmds, "FSCONFIG_");
679 static const char *epoll_ctl_ops[] = { "ADD", "DEL", "MOD", };
680 static DEFINE_STRARRAY_OFFSET(epoll_ctl_ops, "EPOLL_CTL_", 1);
682 static const char *itimers[] = { "REAL", "VIRTUAL", "PROF", };
683 static DEFINE_STRARRAY(itimers, "ITIMER_");
685 static const char *keyctl_options[] = {
686 "GET_KEYRING_ID", "JOIN_SESSION_KEYRING", "UPDATE", "REVOKE", "CHOWN",
687 "SETPERM", "DESCRIBE", "CLEAR", "LINK", "UNLINK", "SEARCH", "READ",
688 "INSTANTIATE", "NEGATE", "SET_REQKEY_KEYRING", "SET_TIMEOUT",
689 "ASSUME_AUTHORITY", "GET_SECURITY", "SESSION_TO_PARENT", "REJECT",
690 "INSTANTIATE_IOV", "INVALIDATE", "GET_PERSISTENT",
692 static DEFINE_STRARRAY(keyctl_options, "KEYCTL_");
694 static const char *whences[] = { "SET", "CUR", "END",
702 static DEFINE_STRARRAY(whences, "SEEK_");
704 static const char *fcntl_cmds[] = {
705 "DUPFD", "GETFD", "SETFD", "GETFL", "SETFL", "GETLK", "SETLK",
706 "SETLKW", "SETOWN", "GETOWN", "SETSIG", "GETSIG", "GETLK64",
707 "SETLK64", "SETLKW64", "SETOWN_EX", "GETOWN_EX",
710 static DEFINE_STRARRAY(fcntl_cmds, "F_");
712 static const char *fcntl_linux_specific_cmds[] = {
713 "SETLEASE", "GETLEASE", "NOTIFY", [5] = "CANCELLK", "DUPFD_CLOEXEC",
714 "SETPIPE_SZ", "GETPIPE_SZ", "ADD_SEALS", "GET_SEALS",
715 "GET_RW_HINT", "SET_RW_HINT", "GET_FILE_RW_HINT", "SET_FILE_RW_HINT",
718 static DEFINE_STRARRAY_OFFSET(fcntl_linux_specific_cmds, "F_", F_LINUX_SPECIFIC_BASE);
720 static struct strarray *fcntl_cmds_arrays[] = {
721 &strarray__fcntl_cmds,
722 &strarray__fcntl_linux_specific_cmds,
725 static DEFINE_STRARRAYS(fcntl_cmds_arrays);
727 static const char *rlimit_resources[] = {
728 "CPU", "FSIZE", "DATA", "STACK", "CORE", "RSS", "NPROC", "NOFILE",
729 "MEMLOCK", "AS", "LOCKS", "SIGPENDING", "MSGQUEUE", "NICE", "RTPRIO",
732 static DEFINE_STRARRAY(rlimit_resources, "RLIMIT_");
734 static const char *sighow[] = { "BLOCK", "UNBLOCK", "SETMASK", };
735 static DEFINE_STRARRAY(sighow, "SIG_");
737 static const char *clockid[] = {
738 "REALTIME", "MONOTONIC", "PROCESS_CPUTIME_ID", "THREAD_CPUTIME_ID",
739 "MONOTONIC_RAW", "REALTIME_COARSE", "MONOTONIC_COARSE", "BOOTTIME",
740 "REALTIME_ALARM", "BOOTTIME_ALARM", "SGI_CYCLE", "TAI"
742 static DEFINE_STRARRAY(clockid, "CLOCK_");
744 static size_t syscall_arg__scnprintf_access_mode(char *bf, size_t size,
745 struct syscall_arg *arg)
747 bool show_prefix = arg->show_string_prefix;
748 const char *suffix = "_OK";
752 if (mode == F_OK) /* 0 */
753 return scnprintf(bf, size, "F%s", show_prefix ? suffix : "");
755 if (mode & n##_OK) { \
756 printed += scnprintf(bf + printed, size - printed, "%s%s", #n, show_prefix ? suffix : ""); \
766 printed += scnprintf(bf + printed, size - printed, "|%#x", mode);
771 #define SCA_ACCMODE syscall_arg__scnprintf_access_mode
773 static size_t syscall_arg__scnprintf_filename(char *bf, size_t size,
774 struct syscall_arg *arg);
776 #define SCA_FILENAME syscall_arg__scnprintf_filename
778 static size_t syscall_arg__scnprintf_pipe_flags(char *bf, size_t size,
779 struct syscall_arg *arg)
781 bool show_prefix = arg->show_string_prefix;
782 const char *prefix = "O_";
783 int printed = 0, flags = arg->val;
786 if (flags & O_##n) { \
787 printed += scnprintf(bf + printed, size - printed, "%s%s%s", printed ? "|" : "", show_prefix ? prefix : "", #n); \
796 printed += scnprintf(bf + printed, size - printed, "%s%#x", printed ? "|" : "", flags);
801 #define SCA_PIPE_FLAGS syscall_arg__scnprintf_pipe_flags
803 #ifndef GRND_NONBLOCK
804 #define GRND_NONBLOCK 0x0001
807 #define GRND_RANDOM 0x0002
810 static size_t syscall_arg__scnprintf_getrandom_flags(char *bf, size_t size,
811 struct syscall_arg *arg)
813 bool show_prefix = arg->show_string_prefix;
814 const char *prefix = "GRND_";
815 int printed = 0, flags = arg->val;
818 if (flags & GRND_##n) { \
819 printed += scnprintf(bf + printed, size - printed, "%s%s%s", printed ? "|" : "", show_prefix ? prefix : "", #n); \
820 flags &= ~GRND_##n; \
828 printed += scnprintf(bf + printed, size - printed, "%s%#x", printed ? "|" : "", flags);
833 #define SCA_GETRANDOM_FLAGS syscall_arg__scnprintf_getrandom_flags
835 #define STRARRAY(name, array) \
836 { .scnprintf = SCA_STRARRAY, \
837 .strtoul = STUL_STRARRAY, \
838 .parm = &strarray__##array, }
840 #define STRARRAY_FLAGS(name, array) \
841 { .scnprintf = SCA_STRARRAY_FLAGS, \
842 .parm = &strarray__##array, }
844 #include "trace/beauty/arch_errno_names.c"
845 #include "trace/beauty/eventfd.c"
846 #include "trace/beauty/futex_op.c"
847 #include "trace/beauty/futex_val3.c"
848 #include "trace/beauty/mmap.c"
849 #include "trace/beauty/mode_t.c"
850 #include "trace/beauty/msg_flags.c"
851 #include "trace/beauty/open_flags.c"
852 #include "trace/beauty/perf_event_open.c"
853 #include "trace/beauty/pid.c"
854 #include "trace/beauty/sched_policy.c"
855 #include "trace/beauty/seccomp.c"
856 #include "trace/beauty/signum.c"
857 #include "trace/beauty/socket_type.c"
858 #include "trace/beauty/waitid_options.c"
860 static struct syscall_fmt syscall_fmts[] = {
862 .arg = { [1] = { .scnprintf = SCA_ACCMODE, /* mode */ }, }, },
863 { .name = "arch_prctl",
864 .arg = { [0] = { .scnprintf = SCA_X86_ARCH_PRCTL_CODE, /* code */ },
865 [1] = { .scnprintf = SCA_PTR, /* arg2 */ }, }, },
867 .arg = { [0] = { .scnprintf = SCA_INT, /* fd */ },
868 [1] = { .scnprintf = SCA_SOCKADDR, /* umyaddr */ },
869 [2] = { .scnprintf = SCA_INT, /* addrlen */ }, }, },
871 .arg = { [0] = STRARRAY(cmd, bpf_cmd), }, },
872 { .name = "brk", .hexret = true,
873 .arg = { [0] = { .scnprintf = SCA_PTR, /* brk */ }, }, },
874 { .name = "clock_gettime",
875 .arg = { [0] = STRARRAY(clk_id, clockid), }, },
876 { .name = "clone", .errpid = true, .nr_args = 5,
877 .arg = { [0] = { .name = "flags", .scnprintf = SCA_CLONE_FLAGS, },
878 [1] = { .name = "child_stack", .scnprintf = SCA_HEX, },
879 [2] = { .name = "parent_tidptr", .scnprintf = SCA_HEX, },
880 [3] = { .name = "child_tidptr", .scnprintf = SCA_HEX, },
881 [4] = { .name = "tls", .scnprintf = SCA_HEX, }, }, },
883 .arg = { [0] = { .scnprintf = SCA_CLOSE_FD, /* fd */ }, }, },
885 .arg = { [0] = { .scnprintf = SCA_INT, /* fd */ },
886 [1] = { .scnprintf = SCA_SOCKADDR, /* servaddr */ },
887 [2] = { .scnprintf = SCA_INT, /* addrlen */ }, }, },
888 { .name = "epoll_ctl",
889 .arg = { [1] = STRARRAY(op, epoll_ctl_ops), }, },
890 { .name = "eventfd2",
891 .arg = { [1] = { .scnprintf = SCA_EFD_FLAGS, /* flags */ }, }, },
892 { .name = "fchmodat",
893 .arg = { [0] = { .scnprintf = SCA_FDAT, /* fd */ }, }, },
894 { .name = "fchownat",
895 .arg = { [0] = { .scnprintf = SCA_FDAT, /* fd */ }, }, },
897 .arg = { [1] = { .scnprintf = SCA_FCNTL_CMD, /* cmd */
898 .strtoul = STUL_STRARRAYS,
899 .parm = &strarrays__fcntl_cmds_arrays,
900 .show_zero = true, },
901 [2] = { .scnprintf = SCA_FCNTL_ARG, /* arg */ }, }, },
903 .arg = { [1] = { .scnprintf = SCA_FLOCK, /* cmd */ }, }, },
904 { .name = "fsconfig",
905 .arg = { [1] = STRARRAY(cmd, fsconfig_cmds), }, },
907 .arg = { [1] = STRARRAY_FLAGS(flags, fsmount_flags),
908 [2] = { .scnprintf = SCA_FSMOUNT_ATTR_FLAGS, /* attr_flags */ }, }, },
910 .arg = { [0] = { .scnprintf = SCA_FDAT, /* dfd */ },
911 [1] = { .scnprintf = SCA_FILENAME, /* path */ },
912 [2] = { .scnprintf = SCA_FSPICK_FLAGS, /* flags */ }, }, },
913 { .name = "fstat", .alias = "newfstat", },
914 { .name = "fstatat", .alias = "newfstatat", },
916 .arg = { [1] = { .scnprintf = SCA_FUTEX_OP, /* op */ },
917 [5] = { .scnprintf = SCA_FUTEX_VAL3, /* val3 */ }, }, },
918 { .name = "futimesat",
919 .arg = { [0] = { .scnprintf = SCA_FDAT, /* fd */ }, }, },
920 { .name = "getitimer",
921 .arg = { [0] = STRARRAY(which, itimers), }, },
922 { .name = "getpid", .errpid = true, },
923 { .name = "getpgid", .errpid = true, },
924 { .name = "getppid", .errpid = true, },
925 { .name = "getrandom",
926 .arg = { [2] = { .scnprintf = SCA_GETRANDOM_FLAGS, /* flags */ }, }, },
927 { .name = "getrlimit",
928 .arg = { [0] = STRARRAY(resource, rlimit_resources), }, },
929 { .name = "gettid", .errpid = true, },
932 #if defined(__i386__) || defined(__x86_64__)
934 * FIXME: Make this available to all arches.
936 [1] = { .scnprintf = SCA_IOCTL_CMD, /* cmd */ },
937 [2] = { .scnprintf = SCA_HEX, /* arg */ }, }, },
939 [2] = { .scnprintf = SCA_HEX, /* arg */ }, }, },
941 { .name = "kcmp", .nr_args = 5,
942 .arg = { [0] = { .name = "pid1", .scnprintf = SCA_PID, },
943 [1] = { .name = "pid2", .scnprintf = SCA_PID, },
944 [2] = { .name = "type", .scnprintf = SCA_KCMP_TYPE, },
945 [3] = { .name = "idx1", .scnprintf = SCA_KCMP_IDX, },
946 [4] = { .name = "idx2", .scnprintf = SCA_KCMP_IDX, }, }, },
948 .arg = { [0] = STRARRAY(option, keyctl_options), }, },
950 .arg = { [1] = { .scnprintf = SCA_SIGNUM, /* sig */ }, }, },
952 .arg = { [0] = { .scnprintf = SCA_FDAT, /* fd */ }, }, },
954 .arg = { [2] = STRARRAY(whence, whences), }, },
955 { .name = "lstat", .alias = "newlstat", },
957 .arg = { [0] = { .scnprintf = SCA_HEX, /* start */ },
958 [2] = { .scnprintf = SCA_MADV_BHV, /* behavior */ }, }, },
960 .arg = { [0] = { .scnprintf = SCA_FDAT, /* fd */ }, }, },
962 .arg = { [0] = { .scnprintf = SCA_FDAT, /* fd */ }, }, },
963 { .name = "mmap", .hexret = true,
964 /* The standard mmap maps to old_mmap on s390x */
965 #if defined(__s390x__)
968 .arg = { [2] = { .scnprintf = SCA_MMAP_PROT, /* prot */ },
969 [3] = { .scnprintf = SCA_MMAP_FLAGS, /* flags */ },
970 [5] = { .scnprintf = SCA_HEX, /* offset */ }, }, },
972 .arg = { [0] = { .scnprintf = SCA_FILENAME, /* dev_name */ },
973 [3] = { .scnprintf = SCA_MOUNT_FLAGS, /* flags */
974 .mask_val = SCAMV_MOUNT_FLAGS, /* flags */ }, }, },
975 { .name = "move_mount",
976 .arg = { [0] = { .scnprintf = SCA_FDAT, /* from_dfd */ },
977 [1] = { .scnprintf = SCA_FILENAME, /* from_pathname */ },
978 [2] = { .scnprintf = SCA_FDAT, /* to_dfd */ },
979 [3] = { .scnprintf = SCA_FILENAME, /* to_pathname */ },
980 [4] = { .scnprintf = SCA_MOVE_MOUNT_FLAGS, /* flags */ }, }, },
981 { .name = "mprotect",
982 .arg = { [0] = { .scnprintf = SCA_HEX, /* start */ },
983 [2] = { .scnprintf = SCA_MMAP_PROT, /* prot */ }, }, },
984 { .name = "mq_unlink",
985 .arg = { [0] = { .scnprintf = SCA_FILENAME, /* u_name */ }, }, },
986 { .name = "mremap", .hexret = true,
987 .arg = { [3] = { .scnprintf = SCA_MREMAP_FLAGS, /* flags */ }, }, },
988 { .name = "name_to_handle_at",
989 .arg = { [0] = { .scnprintf = SCA_FDAT, /* dfd */ }, }, },
990 { .name = "newfstatat",
991 .arg = { [0] = { .scnprintf = SCA_FDAT, /* dfd */ }, }, },
993 .arg = { [1] = { .scnprintf = SCA_OPEN_FLAGS, /* flags */ }, }, },
994 { .name = "open_by_handle_at",
995 .arg = { [0] = { .scnprintf = SCA_FDAT, /* dfd */ },
996 [2] = { .scnprintf = SCA_OPEN_FLAGS, /* flags */ }, }, },
998 .arg = { [0] = { .scnprintf = SCA_FDAT, /* dfd */ },
999 [2] = { .scnprintf = SCA_OPEN_FLAGS, /* flags */ }, }, },
1000 { .name = "perf_event_open",
1001 .arg = { [2] = { .scnprintf = SCA_INT, /* cpu */ },
1002 [3] = { .scnprintf = SCA_FD, /* group_fd */ },
1003 [4] = { .scnprintf = SCA_PERF_FLAGS, /* flags */ }, }, },
1005 .arg = { [1] = { .scnprintf = SCA_PIPE_FLAGS, /* flags */ }, }, },
1006 { .name = "pkey_alloc",
1007 .arg = { [1] = { .scnprintf = SCA_PKEY_ALLOC_ACCESS_RIGHTS, /* access_rights */ }, }, },
1008 { .name = "pkey_free",
1009 .arg = { [0] = { .scnprintf = SCA_INT, /* key */ }, }, },
1010 { .name = "pkey_mprotect",
1011 .arg = { [0] = { .scnprintf = SCA_HEX, /* start */ },
1012 [2] = { .scnprintf = SCA_MMAP_PROT, /* prot */ },
1013 [3] = { .scnprintf = SCA_INT, /* pkey */ }, }, },
1014 { .name = "poll", .timeout = true, },
1015 { .name = "ppoll", .timeout = true, },
1017 .arg = { [0] = { .scnprintf = SCA_PRCTL_OPTION, /* option */ },
1018 [1] = { .scnprintf = SCA_PRCTL_ARG2, /* arg2 */ },
1019 [2] = { .scnprintf = SCA_PRCTL_ARG3, /* arg3 */ }, }, },
1020 { .name = "pread", .alias = "pread64", },
1021 { .name = "preadv", .alias = "pread", },
1022 { .name = "prlimit64",
1023 .arg = { [1] = STRARRAY(resource, rlimit_resources), }, },
1024 { .name = "pwrite", .alias = "pwrite64", },
1025 { .name = "readlinkat",
1026 .arg = { [0] = { .scnprintf = SCA_FDAT, /* dfd */ }, }, },
1027 { .name = "recvfrom",
1028 .arg = { [3] = { .scnprintf = SCA_MSG_FLAGS, /* flags */ }, }, },
1029 { .name = "recvmmsg",
1030 .arg = { [3] = { .scnprintf = SCA_MSG_FLAGS, /* flags */ }, }, },
1031 { .name = "recvmsg",
1032 .arg = { [2] = { .scnprintf = SCA_MSG_FLAGS, /* flags */ }, }, },
1033 { .name = "renameat",
1034 .arg = { [0] = { .scnprintf = SCA_FDAT, /* olddirfd */ },
1035 [2] = { .scnprintf = SCA_FDAT, /* newdirfd */ }, }, },
1036 { .name = "renameat2",
1037 .arg = { [0] = { .scnprintf = SCA_FDAT, /* olddirfd */ },
1038 [2] = { .scnprintf = SCA_FDAT, /* newdirfd */ },
1039 [4] = { .scnprintf = SCA_RENAMEAT2_FLAGS, /* flags */ }, }, },
1040 { .name = "rt_sigaction",
1041 .arg = { [0] = { .scnprintf = SCA_SIGNUM, /* sig */ }, }, },
1042 { .name = "rt_sigprocmask",
1043 .arg = { [0] = STRARRAY(how, sighow), }, },
1044 { .name = "rt_sigqueueinfo",
1045 .arg = { [1] = { .scnprintf = SCA_SIGNUM, /* sig */ }, }, },
1046 { .name = "rt_tgsigqueueinfo",
1047 .arg = { [2] = { .scnprintf = SCA_SIGNUM, /* sig */ }, }, },
1048 { .name = "sched_setscheduler",
1049 .arg = { [1] = { .scnprintf = SCA_SCHED_POLICY, /* policy */ }, }, },
1050 { .name = "seccomp",
1051 .arg = { [0] = { .scnprintf = SCA_SECCOMP_OP, /* op */ },
1052 [1] = { .scnprintf = SCA_SECCOMP_FLAGS, /* flags */ }, }, },
1053 { .name = "select", .timeout = true, },
1054 { .name = "sendfile", .alias = "sendfile64", },
1055 { .name = "sendmmsg",
1056 .arg = { [3] = { .scnprintf = SCA_MSG_FLAGS, /* flags */ }, }, },
1057 { .name = "sendmsg",
1058 .arg = { [2] = { .scnprintf = SCA_MSG_FLAGS, /* flags */ }, }, },
1060 .arg = { [3] = { .scnprintf = SCA_MSG_FLAGS, /* flags */ },
1061 [4] = { .scnprintf = SCA_SOCKADDR, /* addr */ }, }, },
1062 { .name = "set_tid_address", .errpid = true, },
1063 { .name = "setitimer",
1064 .arg = { [0] = STRARRAY(which, itimers), }, },
1065 { .name = "setrlimit",
1066 .arg = { [0] = STRARRAY(resource, rlimit_resources), }, },
1068 .arg = { [0] = STRARRAY(family, socket_families),
1069 [1] = { .scnprintf = SCA_SK_TYPE, /* type */ },
1070 [2] = { .scnprintf = SCA_SK_PROTO, /* protocol */ }, }, },
1071 { .name = "socketpair",
1072 .arg = { [0] = STRARRAY(family, socket_families),
1073 [1] = { .scnprintf = SCA_SK_TYPE, /* type */ },
1074 [2] = { .scnprintf = SCA_SK_PROTO, /* protocol */ }, }, },
1075 { .name = "stat", .alias = "newstat", },
1077 .arg = { [0] = { .scnprintf = SCA_FDAT, /* fdat */ },
1078 [2] = { .scnprintf = SCA_STATX_FLAGS, /* flags */ } ,
1079 [3] = { .scnprintf = SCA_STATX_MASK, /* mask */ }, }, },
1080 { .name = "swapoff",
1081 .arg = { [0] = { .scnprintf = SCA_FILENAME, /* specialfile */ }, }, },
1083 .arg = { [0] = { .scnprintf = SCA_FILENAME, /* specialfile */ }, }, },
1084 { .name = "symlinkat",
1085 .arg = { [0] = { .scnprintf = SCA_FDAT, /* dfd */ }, }, },
1086 { .name = "sync_file_range",
1087 .arg = { [3] = { .scnprintf = SCA_SYNC_FILE_RANGE_FLAGS, /* flags */ }, }, },
1089 .arg = { [2] = { .scnprintf = SCA_SIGNUM, /* sig */ }, }, },
1091 .arg = { [1] = { .scnprintf = SCA_SIGNUM, /* sig */ }, }, },
1092 { .name = "umount2", .alias = "umount",
1093 .arg = { [0] = { .scnprintf = SCA_FILENAME, /* name */ }, }, },
1094 { .name = "uname", .alias = "newuname", },
1095 { .name = "unlinkat",
1096 .arg = { [0] = { .scnprintf = SCA_FDAT, /* dfd */ }, }, },
1097 { .name = "utimensat",
1098 .arg = { [0] = { .scnprintf = SCA_FDAT, /* dirfd */ }, }, },
1099 { .name = "wait4", .errpid = true,
1100 .arg = { [2] = { .scnprintf = SCA_WAITID_OPTIONS, /* options */ }, }, },
1101 { .name = "waitid", .errpid = true,
1102 .arg = { [3] = { .scnprintf = SCA_WAITID_OPTIONS, /* options */ }, }, },
1105 static int syscall_fmt__cmp(const void *name, const void *fmtp)
1107 const struct syscall_fmt *fmt = fmtp;
1108 return strcmp(name, fmt->name);
1111 static struct syscall_fmt *__syscall_fmt__find(struct syscall_fmt *fmts, const int nmemb, const char *name)
1113 return bsearch(name, fmts, nmemb, sizeof(struct syscall_fmt), syscall_fmt__cmp);
1116 static struct syscall_fmt *syscall_fmt__find(const char *name)
1118 const int nmemb = ARRAY_SIZE(syscall_fmts);
1119 return __syscall_fmt__find(syscall_fmts, nmemb, name);
1122 static struct syscall_fmt *__syscall_fmt__find_by_alias(struct syscall_fmt *fmts, const int nmemb, const char *alias)
1126 for (i = 0; i < nmemb; ++i) {
1127 if (fmts[i].alias && strcmp(fmts[i].alias, alias) == 0)
1134 static struct syscall_fmt *syscall_fmt__find_by_alias(const char *alias)
1136 const int nmemb = ARRAY_SIZE(syscall_fmts);
1137 return __syscall_fmt__find_by_alias(syscall_fmts, nmemb, alias);
1141 * is_exit: is this "exit" or "exit_group"?
1142 * is_open: is this "open" or "openat"? To associate the fd returned in sys_exit with the pathname in sys_enter.
1143 * args_size: sum of the sizes of the syscall arguments, anything after that is augmented stuff: pathname for openat, etc.
1144 * nonexistent: Just a hole in the syscall table, syscall id not allocated
1147 struct tep_event *tp_format;
1151 struct bpf_program *sys_enter,
1157 struct tep_format_field *args;
1159 struct syscall_fmt *fmt;
1160 struct syscall_arg_fmt *arg_fmt;
1164 * Must match what is in the BPF program:
1166 * tools/perf/examples/bpf/augmented_raw_syscalls.c
1168 struct bpf_map_syscall_entry {
1170 u16 string_args_len[6];
1174 * We need to have this 'calculated' boolean because in some cases we really
1175 * don't know what is the duration of a syscall, for instance, when we start
1176 * a session and some threads are waiting for a syscall to finish, say 'poll',
1177 * in which case all we can do is to print "( ? ) for duration and for the
1180 static size_t fprintf_duration(unsigned long t, bool calculated, FILE *fp)
1182 double duration = (double)t / NSEC_PER_MSEC;
1183 size_t printed = fprintf(fp, "(");
1186 printed += fprintf(fp, " ");
1187 else if (duration >= 1.0)
1188 printed += color_fprintf(fp, PERF_COLOR_RED, "%6.3f ms", duration);
1189 else if (duration >= 0.01)
1190 printed += color_fprintf(fp, PERF_COLOR_YELLOW, "%6.3f ms", duration);
1192 printed += color_fprintf(fp, PERF_COLOR_NORMAL, "%6.3f ms", duration);
1193 return printed + fprintf(fp, "): ");
1197 * filename.ptr: The filename char pointer that will be vfs_getname'd
1198 * filename.entry_str_pos: Where to insert the string translated from
1199 * filename.ptr by the vfs_getname tracepoint/kprobe.
1200 * ret_scnprintf: syscall args may set this to a different syscall return
1201 * formatter, for instance, fcntl may return fds, file flags, etc.
1203 struct thread_trace {
1206 unsigned long nr_events;
1207 unsigned long pfmaj, pfmin;
1210 size_t (*ret_scnprintf)(char *bf, size_t size, struct syscall_arg *arg);
1213 short int entry_str_pos;
1215 unsigned int namelen;
1223 struct intlist *syscall_stats;
1226 static struct thread_trace *thread_trace__new(void)
1228 struct thread_trace *ttrace = zalloc(sizeof(struct thread_trace));
1231 ttrace->files.max = -1;
1232 ttrace->syscall_stats = intlist__new(NULL);
1238 static struct thread_trace *thread__trace(struct thread *thread, FILE *fp)
1240 struct thread_trace *ttrace;
1245 if (thread__priv(thread) == NULL)
1246 thread__set_priv(thread, thread_trace__new());
1248 if (thread__priv(thread) == NULL)
1251 ttrace = thread__priv(thread);
1252 ++ttrace->nr_events;
1256 color_fprintf(fp, PERF_COLOR_RED,
1257 "WARNING: not enough memory, dropping samples!\n");
1262 void syscall_arg__set_ret_scnprintf(struct syscall_arg *arg,
1263 size_t (*ret_scnprintf)(char *bf, size_t size, struct syscall_arg *arg))
1265 struct thread_trace *ttrace = thread__priv(arg->thread);
1267 ttrace->ret_scnprintf = ret_scnprintf;
1270 #define TRACE_PFMAJ (1 << 0)
1271 #define TRACE_PFMIN (1 << 1)
1273 static const size_t trace__entry_str_size = 2048;
1275 static struct file *thread_trace__files_entry(struct thread_trace *ttrace, int fd)
1280 if (fd > ttrace->files.max) {
1281 struct file *nfiles = realloc(ttrace->files.table, (fd + 1) * sizeof(struct file));
1286 if (ttrace->files.max != -1) {
1287 memset(nfiles + ttrace->files.max + 1, 0,
1288 (fd - ttrace->files.max) * sizeof(struct file));
1290 memset(nfiles, 0, (fd + 1) * sizeof(struct file));
1293 ttrace->files.table = nfiles;
1294 ttrace->files.max = fd;
1297 return ttrace->files.table + fd;
1300 struct file *thread__files_entry(struct thread *thread, int fd)
1302 return thread_trace__files_entry(thread__priv(thread), fd);
1305 static int trace__set_fd_pathname(struct thread *thread, int fd, const char *pathname)
1307 struct thread_trace *ttrace = thread__priv(thread);
1308 struct file *file = thread_trace__files_entry(ttrace, fd);
1312 if (stat(pathname, &st) == 0)
1313 file->dev_maj = major(st.st_rdev);
1314 file->pathname = strdup(pathname);
1322 static int thread__read_fd_path(struct thread *thread, int fd)
1324 char linkname[PATH_MAX], pathname[PATH_MAX];
1328 if (thread->pid_ == thread->tid) {
1329 scnprintf(linkname, sizeof(linkname),
1330 "/proc/%d/fd/%d", thread->pid_, fd);
1332 scnprintf(linkname, sizeof(linkname),
1333 "/proc/%d/task/%d/fd/%d", thread->pid_, thread->tid, fd);
1336 if (lstat(linkname, &st) < 0 || st.st_size + 1 > (off_t)sizeof(pathname))
1339 ret = readlink(linkname, pathname, sizeof(pathname));
1341 if (ret < 0 || ret > st.st_size)
1344 pathname[ret] = '\0';
1345 return trace__set_fd_pathname(thread, fd, pathname);
1348 static const char *thread__fd_path(struct thread *thread, int fd,
1349 struct trace *trace)
1351 struct thread_trace *ttrace = thread__priv(thread);
1353 if (ttrace == NULL || trace->fd_path_disabled)
1359 if ((fd > ttrace->files.max || ttrace->files.table[fd].pathname == NULL)) {
1362 ++trace->stats.proc_getname;
1363 if (thread__read_fd_path(thread, fd))
1367 return ttrace->files.table[fd].pathname;
1370 size_t syscall_arg__scnprintf_fd(char *bf, size_t size, struct syscall_arg *arg)
1373 size_t printed = scnprintf(bf, size, "%d", fd);
1374 const char *path = thread__fd_path(arg->thread, fd, arg->trace);
1377 printed += scnprintf(bf + printed, size - printed, "<%s>", path);
1382 size_t pid__scnprintf_fd(struct trace *trace, pid_t pid, int fd, char *bf, size_t size)
1384 size_t printed = scnprintf(bf, size, "%d", fd);
1385 struct thread *thread = machine__find_thread(trace->host, pid, pid);
1388 const char *path = thread__fd_path(thread, fd, trace);
1391 printed += scnprintf(bf + printed, size - printed, "<%s>", path);
1393 thread__put(thread);
1399 static size_t syscall_arg__scnprintf_close_fd(char *bf, size_t size,
1400 struct syscall_arg *arg)
1403 size_t printed = syscall_arg__scnprintf_fd(bf, size, arg);
1404 struct thread_trace *ttrace = thread__priv(arg->thread);
1406 if (ttrace && fd >= 0 && fd <= ttrace->files.max)
1407 zfree(&ttrace->files.table[fd].pathname);
1412 static void thread__set_filename_pos(struct thread *thread, const char *bf,
1415 struct thread_trace *ttrace = thread__priv(thread);
1417 ttrace->filename.ptr = ptr;
1418 ttrace->filename.entry_str_pos = bf - ttrace->entry_str;
1421 static size_t syscall_arg__scnprintf_augmented_string(struct syscall_arg *arg, char *bf, size_t size)
1423 struct augmented_arg *augmented_arg = arg->augmented.args;
1424 size_t printed = scnprintf(bf, size, "\"%.*s\"", augmented_arg->size, augmented_arg->value);
1426 * So that the next arg with a payload can consume its augmented arg, i.e. for rename* syscalls
1427 * we would have two strings, each prefixed by its size.
1429 int consumed = sizeof(*augmented_arg) + augmented_arg->size;
1431 arg->augmented.args = ((void *)arg->augmented.args) + consumed;
1432 arg->augmented.size -= consumed;
1437 static size_t syscall_arg__scnprintf_filename(char *bf, size_t size,
1438 struct syscall_arg *arg)
1440 unsigned long ptr = arg->val;
1442 if (arg->augmented.args)
1443 return syscall_arg__scnprintf_augmented_string(arg, bf, size);
1445 if (!arg->trace->vfs_getname)
1446 return scnprintf(bf, size, "%#x", ptr);
1448 thread__set_filename_pos(arg->thread, bf, ptr);
1452 static bool trace__filter_duration(struct trace *trace, double t)
1454 return t < (trace->duration_filter * NSEC_PER_MSEC);
1457 static size_t __trace__fprintf_tstamp(struct trace *trace, u64 tstamp, FILE *fp)
1459 double ts = (double)(tstamp - trace->base_time) / NSEC_PER_MSEC;
1461 return fprintf(fp, "%10.3f ", ts);
1465 * We're handling tstamp=0 as an undefined tstamp, i.e. like when we are
1466 * using ttrace->entry_time for a thread that receives a sys_exit without
1467 * first having received a sys_enter ("poll" issued before tracing session
1468 * starts, lost sys_enter exit due to ring buffer overflow).
1470 static size_t trace__fprintf_tstamp(struct trace *trace, u64 tstamp, FILE *fp)
1473 return __trace__fprintf_tstamp(trace, tstamp, fp);
1475 return fprintf(fp, " ? ");
1478 static bool done = false;
1479 static bool interrupted = false;
1481 static void sig_handler(int sig)
1484 interrupted = sig == SIGINT;
1487 static size_t trace__fprintf_comm_tid(struct trace *trace, struct thread *thread, FILE *fp)
1491 if (trace->multiple_threads) {
1492 if (trace->show_comm)
1493 printed += fprintf(fp, "%.14s/", thread__comm_str(thread));
1494 printed += fprintf(fp, "%d ", thread->tid);
1500 static size_t trace__fprintf_entry_head(struct trace *trace, struct thread *thread,
1501 u64 duration, bool duration_calculated, u64 tstamp, FILE *fp)
1505 if (trace->show_tstamp)
1506 printed = trace__fprintf_tstamp(trace, tstamp, fp);
1507 if (trace->show_duration)
1508 printed += fprintf_duration(duration, duration_calculated, fp);
1509 return printed + trace__fprintf_comm_tid(trace, thread, fp);
1512 static int trace__process_event(struct trace *trace, struct machine *machine,
1513 union perf_event *event, struct perf_sample *sample)
1517 switch (event->header.type) {
1518 case PERF_RECORD_LOST:
1519 color_fprintf(trace->output, PERF_COLOR_RED,
1520 "LOST %" PRIu64 " events!\n", event->lost.lost);
1521 ret = machine__process_lost_event(machine, event, sample);
1524 ret = machine__process_event(machine, event, sample);
1531 static int trace__tool_process(struct perf_tool *tool,
1532 union perf_event *event,
1533 struct perf_sample *sample,
1534 struct machine *machine)
1536 struct trace *trace = container_of(tool, struct trace, tool);
1537 return trace__process_event(trace, machine, event, sample);
1540 static char *trace__machine__resolve_kernel_addr(void *vmachine, unsigned long long *addrp, char **modp)
1542 struct machine *machine = vmachine;
1544 if (machine->kptr_restrict_warned)
1547 if (symbol_conf.kptr_restrict) {
1548 pr_warning("Kernel address maps (/proc/{kallsyms,modules}) are restricted.\n\n"
1549 "Check /proc/sys/kernel/kptr_restrict and /proc/sys/kernel/perf_event_paranoid.\n\n"
1550 "Kernel samples will not be resolved.\n");
1551 machine->kptr_restrict_warned = true;
1555 return machine__resolve_kernel_addr(vmachine, addrp, modp);
1558 static int trace__symbols_init(struct trace *trace, struct evlist *evlist)
1560 int err = symbol__init(NULL);
1565 trace->host = machine__new_host();
1566 if (trace->host == NULL)
1569 err = trace_event__register_resolver(trace->host, trace__machine__resolve_kernel_addr);
1573 err = __machine__synthesize_threads(trace->host, &trace->tool, &trace->opts.target,
1574 evlist->core.threads, trace__tool_process, false,
1583 static void trace__symbols__exit(struct trace *trace)
1585 machine__exit(trace->host);
1591 static int syscall__alloc_arg_fmts(struct syscall *sc, int nr_args)
1595 if (nr_args == 6 && sc->fmt && sc->fmt->nr_args != 0)
1596 nr_args = sc->fmt->nr_args;
1598 sc->arg_fmt = calloc(nr_args, sizeof(*sc->arg_fmt));
1599 if (sc->arg_fmt == NULL)
1602 for (idx = 0; idx < nr_args; ++idx) {
1604 sc->arg_fmt[idx] = sc->fmt->arg[idx];
1607 sc->nr_args = nr_args;
1611 static struct syscall_arg_fmt syscall_arg_fmts__by_name[] = {
1612 { .name = "msr", .scnprintf = SCA_X86_MSR, .strtoul = STUL_X86_MSR, },
1613 { .name = "vector", .scnprintf = SCA_X86_IRQ_VECTORS, .strtoul = STUL_X86_IRQ_VECTORS, },
1616 static int syscall_arg_fmt__cmp(const void *name, const void *fmtp)
1618 const struct syscall_arg_fmt *fmt = fmtp;
1619 return strcmp(name, fmt->name);
1622 static struct syscall_arg_fmt *
1623 __syscall_arg_fmt__find_by_name(struct syscall_arg_fmt *fmts, const int nmemb, const char *name)
1625 return bsearch(name, fmts, nmemb, sizeof(struct syscall_arg_fmt), syscall_arg_fmt__cmp);
1628 static struct syscall_arg_fmt *syscall_arg_fmt__find_by_name(const char *name)
1630 const int nmemb = ARRAY_SIZE(syscall_arg_fmts__by_name);
1631 return __syscall_arg_fmt__find_by_name(syscall_arg_fmts__by_name, nmemb, name);
1634 static struct tep_format_field *
1635 syscall_arg_fmt__init_array(struct syscall_arg_fmt *arg, struct tep_format_field *field)
1637 struct tep_format_field *last_field = NULL;
1640 for (; field; field = field->next, ++arg) {
1646 len = strlen(field->name);
1648 if (strcmp(field->type, "const char *") == 0 &&
1649 ((len >= 4 && strcmp(field->name + len - 4, "name") == 0) ||
1650 strstr(field->name, "path") != NULL))
1651 arg->scnprintf = SCA_FILENAME;
1652 else if ((field->flags & TEP_FIELD_IS_POINTER) || strstr(field->name, "addr"))
1653 arg->scnprintf = SCA_PTR;
1654 else if (strcmp(field->type, "pid_t") == 0)
1655 arg->scnprintf = SCA_PID;
1656 else if (strcmp(field->type, "umode_t") == 0)
1657 arg->scnprintf = SCA_MODE_T;
1658 else if ((field->flags & TEP_FIELD_IS_ARRAY) && strstr(field->type, "char")) {
1659 arg->scnprintf = SCA_CHAR_ARRAY;
1660 arg->nr_entries = field->arraylen;
1661 } else if ((strcmp(field->type, "int") == 0 ||
1662 strcmp(field->type, "unsigned int") == 0 ||
1663 strcmp(field->type, "long") == 0) &&
1664 len >= 2 && strcmp(field->name + len - 2, "fd") == 0) {
1666 * /sys/kernel/tracing/events/syscalls/sys_enter*
1667 * egrep 'field:.*fd;' .../format|sed -r 's/.*field:([a-z ]+) [a-z_]*fd.+/\1/g'|sort|uniq -c
1672 arg->scnprintf = SCA_FD;
1674 struct syscall_arg_fmt *fmt = syscall_arg_fmt__find_by_name(field->name);
1677 arg->scnprintf = fmt->scnprintf;
1678 arg->strtoul = fmt->strtoul;
1686 static int syscall__set_arg_fmts(struct syscall *sc)
1688 struct tep_format_field *last_field = syscall_arg_fmt__init_array(sc->arg_fmt, sc->args);
1691 sc->args_size = last_field->offset + last_field->size;
1696 static int trace__read_syscall_info(struct trace *trace, int id)
1700 const char *name = syscalltbl__name(trace->sctbl, id);
1702 if (trace->syscalls.table == NULL) {
1703 trace->syscalls.table = calloc(trace->sctbl->syscalls.max_id + 1, sizeof(*sc));
1704 if (trace->syscalls.table == NULL)
1708 sc = trace->syscalls.table + id;
1709 if (sc->nonexistent)
1713 sc->nonexistent = true;
1718 sc->fmt = syscall_fmt__find(sc->name);
1720 snprintf(tp_name, sizeof(tp_name), "sys_enter_%s", sc->name);
1721 sc->tp_format = trace_event__tp_format("syscalls", tp_name);
1723 if (IS_ERR(sc->tp_format) && sc->fmt && sc->fmt->alias) {
1724 snprintf(tp_name, sizeof(tp_name), "sys_enter_%s", sc->fmt->alias);
1725 sc->tp_format = trace_event__tp_format("syscalls", tp_name);
1728 if (syscall__alloc_arg_fmts(sc, IS_ERR(sc->tp_format) ? 6 : sc->tp_format->format.nr_fields))
1731 if (IS_ERR(sc->tp_format))
1732 return PTR_ERR(sc->tp_format);
1734 sc->args = sc->tp_format->format.fields;
1736 * We need to check and discard the first variable '__syscall_nr'
1737 * or 'nr' that mean the syscall number. It is needless here.
1738 * So drop '__syscall_nr' or 'nr' field but does not exist on older kernels.
1740 if (sc->args && (!strcmp(sc->args->name, "__syscall_nr") || !strcmp(sc->args->name, "nr"))) {
1741 sc->args = sc->args->next;
1745 sc->is_exit = !strcmp(name, "exit_group") || !strcmp(name, "exit");
1746 sc->is_open = !strcmp(name, "open") || !strcmp(name, "openat");
1748 return syscall__set_arg_fmts(sc);
1751 static int perf_evsel__init_tp_arg_scnprintf(struct evsel *evsel)
1753 struct syscall_arg_fmt *fmt = evsel__syscall_arg_fmt(evsel);
1756 syscall_arg_fmt__init_array(fmt, evsel->tp_format->format.fields);
1763 static int intcmp(const void *a, const void *b)
1765 const int *one = a, *another = b;
1767 return *one - *another;
1770 static int trace__validate_ev_qualifier(struct trace *trace)
1773 bool printed_invalid_prefix = false;
1774 struct str_node *pos;
1775 size_t nr_used = 0, nr_allocated = strlist__nr_entries(trace->ev_qualifier);
1777 trace->ev_qualifier_ids.entries = malloc(nr_allocated *
1778 sizeof(trace->ev_qualifier_ids.entries[0]));
1780 if (trace->ev_qualifier_ids.entries == NULL) {
1781 fputs("Error:\tNot enough memory for allocating events qualifier ids\n",
1787 strlist__for_each_entry(pos, trace->ev_qualifier) {
1788 const char *sc = pos->s;
1789 int id = syscalltbl__id(trace->sctbl, sc), match_next = -1;
1792 id = syscalltbl__strglobmatch_first(trace->sctbl, sc, &match_next);
1796 if (!printed_invalid_prefix) {
1797 pr_debug("Skipping unknown syscalls: ");
1798 printed_invalid_prefix = true;
1807 trace->ev_qualifier_ids.entries[nr_used++] = id;
1808 if (match_next == -1)
1812 id = syscalltbl__strglobmatch_next(trace->sctbl, sc, &match_next);
1815 if (nr_allocated == nr_used) {
1819 entries = realloc(trace->ev_qualifier_ids.entries,
1820 nr_allocated * sizeof(trace->ev_qualifier_ids.entries[0]));
1821 if (entries == NULL) {
1823 fputs("\nError:\t Not enough memory for parsing\n", trace->output);
1826 trace->ev_qualifier_ids.entries = entries;
1828 trace->ev_qualifier_ids.entries[nr_used++] = id;
1832 trace->ev_qualifier_ids.nr = nr_used;
1833 qsort(trace->ev_qualifier_ids.entries, nr_used, sizeof(int), intcmp);
1835 if (printed_invalid_prefix)
1839 zfree(&trace->ev_qualifier_ids.entries);
1840 trace->ev_qualifier_ids.nr = 0;
1844 static __maybe_unused bool trace__syscall_enabled(struct trace *trace, int id)
1846 bool in_ev_qualifier;
1848 if (trace->ev_qualifier_ids.nr == 0)
1851 in_ev_qualifier = bsearch(&id, trace->ev_qualifier_ids.entries,
1852 trace->ev_qualifier_ids.nr, sizeof(int), intcmp) != NULL;
1854 if (in_ev_qualifier)
1855 return !trace->not_ev_qualifier;
1857 return trace->not_ev_qualifier;
1861 * args is to be interpreted as a series of longs but we need to handle
1862 * 8-byte unaligned accesses. args points to raw_data within the event
1863 * and raw_data is guaranteed to be 8-byte unaligned because it is
1864 * preceded by raw_size which is a u32. So we need to copy args to a temp
1865 * variable to read it. Most notably this avoids extended load instructions
1866 * on unaligned addresses
1868 unsigned long syscall_arg__val(struct syscall_arg *arg, u8 idx)
1871 unsigned char *p = arg->args + sizeof(unsigned long) * idx;
1873 memcpy(&val, p, sizeof(val));
1877 static size_t syscall__scnprintf_name(struct syscall *sc, char *bf, size_t size,
1878 struct syscall_arg *arg)
1880 if (sc->arg_fmt && sc->arg_fmt[arg->idx].name)
1881 return scnprintf(bf, size, "%s: ", sc->arg_fmt[arg->idx].name);
1883 return scnprintf(bf, size, "arg%d: ", arg->idx);
1887 * Check if the value is in fact zero, i.e. mask whatever needs masking, such
1888 * as mount 'flags' argument that needs ignoring some magic flag, see comment
1889 * in tools/perf/trace/beauty/mount_flags.c
1891 static unsigned long syscall_arg_fmt__mask_val(struct syscall_arg_fmt *fmt, struct syscall_arg *arg, unsigned long val)
1893 if (fmt && fmt->mask_val)
1894 return fmt->mask_val(arg, val);
1899 static size_t syscall_arg_fmt__scnprintf_val(struct syscall_arg_fmt *fmt, char *bf, size_t size,
1900 struct syscall_arg *arg, unsigned long val)
1902 if (fmt && fmt->scnprintf) {
1905 arg->parm = fmt->parm;
1906 return fmt->scnprintf(bf, size, arg);
1908 return scnprintf(bf, size, "%ld", val);
1911 static size_t syscall__scnprintf_args(struct syscall *sc, char *bf, size_t size,
1912 unsigned char *args, void *augmented_args, int augmented_args_size,
1913 struct trace *trace, struct thread *thread)
1918 struct syscall_arg arg = {
1921 .size = augmented_args_size,
1922 .args = augmented_args,
1928 .show_string_prefix = trace->show_string_prefix,
1930 struct thread_trace *ttrace = thread__priv(thread);
1933 * Things like fcntl will set this in its 'cmd' formatter to pick the
1934 * right formatter for the return value (an fd? file flags?), which is
1935 * not needed for syscalls that always return a given type, say an fd.
1937 ttrace->ret_scnprintf = NULL;
1939 if (sc->args != NULL) {
1940 struct tep_format_field *field;
1942 for (field = sc->args; field;
1943 field = field->next, ++arg.idx, bit <<= 1) {
1947 arg.fmt = &sc->arg_fmt[arg.idx];
1948 val = syscall_arg__val(&arg, arg.idx);
1950 * Some syscall args need some mask, most don't and
1951 * return val untouched.
1953 val = syscall_arg_fmt__mask_val(&sc->arg_fmt[arg.idx], &arg, val);
1956 * Suppress this argument if its value is zero and
1957 * and we don't have a string associated in an
1961 !trace->show_zeros &&
1963 (sc->arg_fmt[arg.idx].show_zero ||
1964 sc->arg_fmt[arg.idx].scnprintf == SCA_STRARRAY ||
1965 sc->arg_fmt[arg.idx].scnprintf == SCA_STRARRAYS) &&
1966 sc->arg_fmt[arg.idx].parm))
1969 printed += scnprintf(bf + printed, size - printed, "%s", printed ? ", " : "");
1971 if (trace->show_arg_names)
1972 printed += scnprintf(bf + printed, size - printed, "%s: ", field->name);
1974 printed += syscall_arg_fmt__scnprintf_val(&sc->arg_fmt[arg.idx],
1975 bf + printed, size - printed, &arg, val);
1977 } else if (IS_ERR(sc->tp_format)) {
1979 * If we managed to read the tracepoint /format file, then we
1980 * may end up not having any args, like with gettid(), so only
1981 * print the raw args when we didn't manage to read it.
1983 while (arg.idx < sc->nr_args) {
1986 val = syscall_arg__val(&arg, arg.idx);
1988 printed += scnprintf(bf + printed, size - printed, ", ");
1989 printed += syscall__scnprintf_name(sc, bf + printed, size - printed, &arg);
1990 printed += syscall_arg_fmt__scnprintf_val(&sc->arg_fmt[arg.idx], bf + printed, size - printed, &arg, val);
2000 typedef int (*tracepoint_handler)(struct trace *trace, struct evsel *evsel,
2001 union perf_event *event,
2002 struct perf_sample *sample);
2004 static struct syscall *trace__syscall_info(struct trace *trace,
2005 struct evsel *evsel, int id)
2012 * XXX: Noticed on x86_64, reproduced as far back as 3.0.36, haven't tried
2013 * before that, leaving at a higher verbosity level till that is
2014 * explained. Reproduced with plain ftrace with:
2016 * echo 1 > /t/events/raw_syscalls/sys_exit/enable
2017 * grep "NR -1 " /t/trace_pipe
2019 * After generating some load on the machine.
2023 fprintf(trace->output, "Invalid syscall %d id, skipping (%s, %" PRIu64 ") ...\n",
2024 id, perf_evsel__name(evsel), ++n);
2031 if (id > trace->sctbl->syscalls.max_id)
2034 if ((trace->syscalls.table == NULL || trace->syscalls.table[id].name == NULL) &&
2035 (err = trace__read_syscall_info(trace, id)) != 0)
2038 if (trace->syscalls.table[id].name == NULL) {
2039 if (trace->syscalls.table[id].nonexistent)
2044 return &trace->syscalls.table[id];
2048 char sbuf[STRERR_BUFSIZE];
2049 fprintf(trace->output, "Problems reading syscall %d: %d (%s)", id, -err, str_error_r(-err, sbuf, sizeof(sbuf)));
2050 if (id <= trace->sctbl->syscalls.max_id && trace->syscalls.table[id].name != NULL)
2051 fprintf(trace->output, "(%s)", trace->syscalls.table[id].name);
2052 fputs(" information\n", trace->output);
2057 struct syscall_stats {
2064 static void thread__update_stats(struct thread *thread, struct thread_trace *ttrace,
2065 int id, struct perf_sample *sample, long err, bool errno_summary)
2067 struct int_node *inode;
2068 struct syscall_stats *stats;
2071 inode = intlist__findnew(ttrace->syscall_stats, id);
2075 stats = inode->priv;
2076 if (stats == NULL) {
2077 stats = malloc(sizeof(*stats));
2081 stats->nr_failures = 0;
2082 stats->max_errno = 0;
2083 stats->errnos = NULL;
2084 init_stats(&stats->stats);
2085 inode->priv = stats;
2088 if (ttrace->entry_time && sample->time > ttrace->entry_time)
2089 duration = sample->time - ttrace->entry_time;
2091 update_stats(&stats->stats, duration);
2094 ++stats->nr_failures;
2100 if (err > stats->max_errno) {
2101 u32 *new_errnos = realloc(stats->errnos, err * sizeof(u32));
2104 memset(new_errnos + stats->max_errno, 0, (err - stats->max_errno) * sizeof(u32));
2106 pr_debug("Not enough memory for errno stats for thread \"%s\"(%d/%d), results will be incomplete\n",
2107 thread__comm_str(thread), thread->pid_, thread->tid);
2111 stats->errnos = new_errnos;
2112 stats->max_errno = err;
2115 ++stats->errnos[err - 1];
2119 static int trace__printf_interrupted_entry(struct trace *trace)
2121 struct thread_trace *ttrace;
2125 if (trace->failure_only || trace->current == NULL)
2128 ttrace = thread__priv(trace->current);
2130 if (!ttrace->entry_pending)
2133 printed = trace__fprintf_entry_head(trace, trace->current, 0, false, ttrace->entry_time, trace->output);
2134 printed += len = fprintf(trace->output, "%s)", ttrace->entry_str);
2136 if (len < trace->args_alignment - 4)
2137 printed += fprintf(trace->output, "%-*s", trace->args_alignment - 4 - len, " ");
2139 printed += fprintf(trace->output, " ...\n");
2141 ttrace->entry_pending = false;
2142 ++trace->nr_events_printed;
2147 static int trace__fprintf_sample(struct trace *trace, struct evsel *evsel,
2148 struct perf_sample *sample, struct thread *thread)
2152 if (trace->print_sample) {
2153 double ts = (double)sample->time / NSEC_PER_MSEC;
2155 printed += fprintf(trace->output, "%22s %10.3f %s %d/%d [%d]\n",
2156 perf_evsel__name(evsel), ts,
2157 thread__comm_str(thread),
2158 sample->pid, sample->tid, sample->cpu);
2164 static void *syscall__augmented_args(struct syscall *sc, struct perf_sample *sample, int *augmented_args_size, int raw_augmented_args_size)
2166 void *augmented_args = NULL;
2168 * For now with BPF raw_augmented we hook into raw_syscalls:sys_enter
2169 * and there we get all 6 syscall args plus the tracepoint common fields
2170 * that gets calculated at the start and the syscall_nr (another long).
2171 * So we check if that is the case and if so don't look after the
2172 * sc->args_size but always after the full raw_syscalls:sys_enter payload,
2175 * We'll revisit this later to pass s->args_size to the BPF augmenter
2176 * (now tools/perf/examples/bpf/augmented_raw_syscalls.c, so that it
2177 * copies only what we need for each syscall, like what happens when we
2178 * use syscalls:sys_enter_NAME, so that we reduce the kernel/userspace
2179 * traffic to just what is needed for each syscall.
2181 int args_size = raw_augmented_args_size ?: sc->args_size;
2183 *augmented_args_size = sample->raw_size - args_size;
2184 if (*augmented_args_size > 0)
2185 augmented_args = sample->raw_data + args_size;
2187 return augmented_args;
2190 static int trace__sys_enter(struct trace *trace, struct evsel *evsel,
2191 union perf_event *event __maybe_unused,
2192 struct perf_sample *sample)
2197 struct thread *thread;
2198 int id = perf_evsel__sc_tp_uint(evsel, id, sample), err = -1;
2199 int augmented_args_size = 0;
2200 void *augmented_args = NULL;
2201 struct syscall *sc = trace__syscall_info(trace, evsel, id);
2202 struct thread_trace *ttrace;
2207 thread = machine__findnew_thread(trace->host, sample->pid, sample->tid);
2208 ttrace = thread__trace(thread, trace->output);
2212 trace__fprintf_sample(trace, evsel, sample, thread);
2214 args = perf_evsel__sc_tp_ptr(evsel, args, sample);
2216 if (ttrace->entry_str == NULL) {
2217 ttrace->entry_str = malloc(trace__entry_str_size);
2218 if (!ttrace->entry_str)
2222 if (!(trace->duration_filter || trace->summary_only || trace->min_stack))
2223 trace__printf_interrupted_entry(trace);
2225 * If this is raw_syscalls.sys_enter, then it always comes with the 6 possible
2226 * arguments, even if the syscall being handled, say "openat", uses only 4 arguments
2227 * this breaks syscall__augmented_args() check for augmented args, as we calculate
2228 * syscall->args_size using each syscalls:sys_enter_NAME tracefs format file,
2229 * so when handling, say the openat syscall, we end up getting 6 args for the
2230 * raw_syscalls:sys_enter event, when we expected just 4, we end up mistakenly
2231 * thinking that the extra 2 u64 args are the augmented filename, so just check
2232 * here and avoid using augmented syscalls when the evsel is the raw_syscalls one.
2234 if (evsel != trace->syscalls.events.sys_enter)
2235 augmented_args = syscall__augmented_args(sc, sample, &augmented_args_size, trace->raw_augmented_syscalls_args_size);
2236 ttrace->entry_time = sample->time;
2237 msg = ttrace->entry_str;
2238 printed += scnprintf(msg + printed, trace__entry_str_size - printed, "%s(", sc->name);
2240 printed += syscall__scnprintf_args(sc, msg + printed, trace__entry_str_size - printed,
2241 args, augmented_args, augmented_args_size, trace, thread);
2244 if (!(trace->duration_filter || trace->summary_only || trace->failure_only || trace->min_stack)) {
2247 trace__fprintf_entry_head(trace, thread, 0, false, ttrace->entry_time, trace->output);
2248 printed = fprintf(trace->output, "%s)", ttrace->entry_str);
2249 if (trace->args_alignment > printed)
2250 alignment = trace->args_alignment - printed;
2251 fprintf(trace->output, "%*s= ?\n", alignment, " ");
2254 ttrace->entry_pending = true;
2255 /* See trace__vfs_getname & trace__sys_exit */
2256 ttrace->filename.pending_open = false;
2259 if (trace->current != thread) {
2260 thread__put(trace->current);
2261 trace->current = thread__get(thread);
2265 thread__put(thread);
2269 static int trace__fprintf_sys_enter(struct trace *trace, struct evsel *evsel,
2270 struct perf_sample *sample)
2272 struct thread_trace *ttrace;
2273 struct thread *thread;
2274 int id = perf_evsel__sc_tp_uint(evsel, id, sample), err = -1;
2275 struct syscall *sc = trace__syscall_info(trace, evsel, id);
2277 void *args, *augmented_args = NULL;
2278 int augmented_args_size;
2283 thread = machine__findnew_thread(trace->host, sample->pid, sample->tid);
2284 ttrace = thread__trace(thread, trace->output);
2286 * We need to get ttrace just to make sure it is there when syscall__scnprintf_args()
2287 * and the rest of the beautifiers accessing it via struct syscall_arg touches it.
2292 args = perf_evsel__sc_tp_ptr(evsel, args, sample);
2293 augmented_args = syscall__augmented_args(sc, sample, &augmented_args_size, trace->raw_augmented_syscalls_args_size);
2294 syscall__scnprintf_args(sc, msg, sizeof(msg), args, augmented_args, augmented_args_size, trace, thread);
2295 fprintf(trace->output, "%s", msg);
2298 thread__put(thread);
2302 static int trace__resolve_callchain(struct trace *trace, struct evsel *evsel,
2303 struct perf_sample *sample,
2304 struct callchain_cursor *cursor)
2306 struct addr_location al;
2307 int max_stack = evsel->core.attr.sample_max_stack ?
2308 evsel->core.attr.sample_max_stack :
2312 if (machine__resolve(trace->host, &al, sample) < 0)
2315 err = thread__resolve_callchain(al.thread, cursor, evsel, sample, NULL, NULL, max_stack);
2316 addr_location__put(&al);
2320 static int trace__fprintf_callchain(struct trace *trace, struct perf_sample *sample)
2322 /* TODO: user-configurable print_opts */
2323 const unsigned int print_opts = EVSEL__PRINT_SYM |
2325 EVSEL__PRINT_UNKNOWN_AS_ADDR;
2327 return sample__fprintf_callchain(sample, 38, print_opts, &callchain_cursor, symbol_conf.bt_stop_list, trace->output);
2330 static const char *errno_to_name(struct evsel *evsel, int err)
2332 struct perf_env *env = perf_evsel__env(evsel);
2333 const char *arch_name = perf_env__arch(env);
2335 return arch_syscalls__strerrno(arch_name, err);
2338 static int trace__sys_exit(struct trace *trace, struct evsel *evsel,
2339 union perf_event *event __maybe_unused,
2340 struct perf_sample *sample)
2344 bool duration_calculated = false;
2345 struct thread *thread;
2346 int id = perf_evsel__sc_tp_uint(evsel, id, sample), err = -1, callchain_ret = 0, printed = 0;
2347 int alignment = trace->args_alignment;
2348 struct syscall *sc = trace__syscall_info(trace, evsel, id);
2349 struct thread_trace *ttrace;
2354 thread = machine__findnew_thread(trace->host, sample->pid, sample->tid);
2355 ttrace = thread__trace(thread, trace->output);
2359 trace__fprintf_sample(trace, evsel, sample, thread);
2361 ret = perf_evsel__sc_tp_uint(evsel, ret, sample);
2364 thread__update_stats(thread, ttrace, id, sample, ret, trace->errno_summary);
2366 if (!trace->fd_path_disabled && sc->is_open && ret >= 0 && ttrace->filename.pending_open) {
2367 trace__set_fd_pathname(thread, ret, ttrace->filename.name);
2368 ttrace->filename.pending_open = false;
2369 ++trace->stats.vfs_getname;
2372 if (ttrace->entry_time) {
2373 duration = sample->time - ttrace->entry_time;
2374 if (trace__filter_duration(trace, duration))
2376 duration_calculated = true;
2377 } else if (trace->duration_filter)
2380 if (sample->callchain) {
2381 callchain_ret = trace__resolve_callchain(trace, evsel, sample, &callchain_cursor);
2382 if (callchain_ret == 0) {
2383 if (callchain_cursor.nr < trace->min_stack)
2389 if (trace->summary_only || (ret >= 0 && trace->failure_only))
2392 trace__fprintf_entry_head(trace, thread, duration, duration_calculated, ttrace->entry_time, trace->output);
2394 if (ttrace->entry_pending) {
2395 printed = fprintf(trace->output, "%s", ttrace->entry_str);
2397 printed += fprintf(trace->output, " ... [");
2398 color_fprintf(trace->output, PERF_COLOR_YELLOW, "continued");
2400 printed += fprintf(trace->output, "]: %s()", sc->name);
2403 printed++; /* the closing ')' */
2405 if (alignment > printed)
2406 alignment -= printed;
2410 fprintf(trace->output, ")%*s= ", alignment, " ");
2412 if (sc->fmt == NULL) {
2416 fprintf(trace->output, "%ld", ret);
2417 } else if (ret < 0) {
2419 char bf[STRERR_BUFSIZE];
2420 const char *emsg = str_error_r(-ret, bf, sizeof(bf)),
2421 *e = errno_to_name(evsel, -ret);
2423 fprintf(trace->output, "-1 %s (%s)", e, emsg);
2425 } else if (ret == 0 && sc->fmt->timeout)
2426 fprintf(trace->output, "0 (Timeout)");
2427 else if (ttrace->ret_scnprintf) {
2429 struct syscall_arg arg = {
2434 ttrace->ret_scnprintf(bf, sizeof(bf), &arg);
2435 ttrace->ret_scnprintf = NULL;
2436 fprintf(trace->output, "%s", bf);
2437 } else if (sc->fmt->hexret)
2438 fprintf(trace->output, "%#lx", ret);
2439 else if (sc->fmt->errpid) {
2440 struct thread *child = machine__find_thread(trace->host, ret, ret);
2442 if (child != NULL) {
2443 fprintf(trace->output, "%ld", ret);
2444 if (child->comm_set)
2445 fprintf(trace->output, " (%s)", thread__comm_str(child));
2451 fputc('\n', trace->output);
2454 * We only consider an 'event' for the sake of --max-events a non-filtered
2455 * sys_enter + sys_exit and other tracepoint events.
2457 if (++trace->nr_events_printed == trace->max_events && trace->max_events != ULONG_MAX)
2460 if (callchain_ret > 0)
2461 trace__fprintf_callchain(trace, sample);
2462 else if (callchain_ret < 0)
2463 pr_err("Problem processing %s callchain, skipping...\n", perf_evsel__name(evsel));
2465 ttrace->entry_pending = false;
2468 thread__put(thread);
2472 static int trace__vfs_getname(struct trace *trace, struct evsel *evsel,
2473 union perf_event *event __maybe_unused,
2474 struct perf_sample *sample)
2476 struct thread *thread = machine__findnew_thread(trace->host, sample->pid, sample->tid);
2477 struct thread_trace *ttrace;
2478 size_t filename_len, entry_str_len, to_move;
2479 ssize_t remaining_space;
2481 const char *filename = perf_evsel__rawptr(evsel, sample, "pathname");
2486 ttrace = thread__priv(thread);
2490 filename_len = strlen(filename);
2491 if (filename_len == 0)
2494 if (ttrace->filename.namelen < filename_len) {
2495 char *f = realloc(ttrace->filename.name, filename_len + 1);
2500 ttrace->filename.namelen = filename_len;
2501 ttrace->filename.name = f;
2504 strcpy(ttrace->filename.name, filename);
2505 ttrace->filename.pending_open = true;
2507 if (!ttrace->filename.ptr)
2510 entry_str_len = strlen(ttrace->entry_str);
2511 remaining_space = trace__entry_str_size - entry_str_len - 1; /* \0 */
2512 if (remaining_space <= 0)
2515 if (filename_len > (size_t)remaining_space) {
2516 filename += filename_len - remaining_space;
2517 filename_len = remaining_space;
2520 to_move = entry_str_len - ttrace->filename.entry_str_pos + 1; /* \0 */
2521 pos = ttrace->entry_str + ttrace->filename.entry_str_pos;
2522 memmove(pos + filename_len, pos, to_move);
2523 memcpy(pos, filename, filename_len);
2525 ttrace->filename.ptr = 0;
2526 ttrace->filename.entry_str_pos = 0;
2528 thread__put(thread);
2533 static int trace__sched_stat_runtime(struct trace *trace, struct evsel *evsel,
2534 union perf_event *event __maybe_unused,
2535 struct perf_sample *sample)
2537 u64 runtime = perf_evsel__intval(evsel, sample, "runtime");
2538 double runtime_ms = (double)runtime / NSEC_PER_MSEC;
2539 struct thread *thread = machine__findnew_thread(trace->host,
2542 struct thread_trace *ttrace = thread__trace(thread, trace->output);
2547 ttrace->runtime_ms += runtime_ms;
2548 trace->runtime_ms += runtime_ms;
2550 thread__put(thread);
2554 fprintf(trace->output, "%s: comm=%s,pid=%u,runtime=%" PRIu64 ",vruntime=%" PRIu64 ")\n",
2556 perf_evsel__strval(evsel, sample, "comm"),
2557 (pid_t)perf_evsel__intval(evsel, sample, "pid"),
2559 perf_evsel__intval(evsel, sample, "vruntime"));
2563 static int bpf_output__printer(enum binary_printer_ops op,
2564 unsigned int val, void *extra __maybe_unused, FILE *fp)
2566 unsigned char ch = (unsigned char)val;
2569 case BINARY_PRINT_CHAR_DATA:
2570 return fprintf(fp, "%c", isprint(ch) ? ch : '.');
2571 case BINARY_PRINT_DATA_BEGIN:
2572 case BINARY_PRINT_LINE_BEGIN:
2573 case BINARY_PRINT_ADDR:
2574 case BINARY_PRINT_NUM_DATA:
2575 case BINARY_PRINT_NUM_PAD:
2576 case BINARY_PRINT_SEP:
2577 case BINARY_PRINT_CHAR_PAD:
2578 case BINARY_PRINT_LINE_END:
2579 case BINARY_PRINT_DATA_END:
2587 static void bpf_output__fprintf(struct trace *trace,
2588 struct perf_sample *sample)
2590 binary__fprintf(sample->raw_data, sample->raw_size, 8,
2591 bpf_output__printer, NULL, trace->output);
2592 ++trace->nr_events_printed;
2595 static size_t trace__fprintf_tp_fields(struct trace *trace, struct evsel *evsel, struct perf_sample *sample,
2596 struct thread *thread, void *augmented_args, int augmented_args_size)
2599 size_t size = sizeof(bf);
2600 struct tep_format_field *field = evsel->tp_format->format.fields;
2601 struct syscall_arg_fmt *arg = __evsel__syscall_arg_fmt(evsel);
2605 struct syscall_arg syscall_arg = {
2607 .size = augmented_args_size,
2608 .args = augmented_args,
2614 .show_string_prefix = trace->show_string_prefix,
2617 for (; field && arg; field = field->next, ++syscall_arg.idx, bit <<= 1, ++arg) {
2618 if (syscall_arg.mask & bit)
2621 syscall_arg.len = 0;
2622 syscall_arg.fmt = arg;
2623 if (field->flags & TEP_FIELD_IS_ARRAY) {
2624 int offset = field->offset;
2626 if (field->flags & TEP_FIELD_IS_DYNAMIC) {
2627 offset = format_field__intval(field, sample, evsel->needs_swap);
2628 syscall_arg.len = offset >> 16;
2632 val = (uintptr_t)(sample->raw_data + offset);
2634 val = format_field__intval(field, sample, evsel->needs_swap);
2636 * Some syscall args need some mask, most don't and
2637 * return val untouched.
2639 val = syscall_arg_fmt__mask_val(arg, &syscall_arg, val);
2642 * Suppress this argument if its value is zero and
2643 * and we don't have a string associated in an
2647 !trace->show_zeros &&
2648 !((arg->show_zero ||
2649 arg->scnprintf == SCA_STRARRAY ||
2650 arg->scnprintf == SCA_STRARRAYS) &&
2654 printed += scnprintf(bf + printed, size - printed, "%s", printed ? ", " : "");
2657 * XXX Perhaps we should have a show_tp_arg_names,
2658 * leaving show_arg_names just for syscalls?
2660 if (1 || trace->show_arg_names)
2661 printed += scnprintf(bf + printed, size - printed, "%s: ", field->name);
2663 printed += syscall_arg_fmt__scnprintf_val(arg, bf + printed, size - printed, &syscall_arg, val);
2666 return printed + fprintf(trace->output, "%s", bf);
2669 static int trace__event_handler(struct trace *trace, struct evsel *evsel,
2670 union perf_event *event __maybe_unused,
2671 struct perf_sample *sample)
2673 struct thread *thread;
2674 int callchain_ret = 0;
2676 * Check if we called perf_evsel__disable(evsel) due to, for instance,
2677 * this event's max_events having been hit and this is an entry coming
2678 * from the ring buffer that we should discard, since the max events
2679 * have already been considered/printed.
2681 if (evsel->disabled)
2684 thread = machine__findnew_thread(trace->host, sample->pid, sample->tid);
2686 if (sample->callchain) {
2687 callchain_ret = trace__resolve_callchain(trace, evsel, sample, &callchain_cursor);
2688 if (callchain_ret == 0) {
2689 if (callchain_cursor.nr < trace->min_stack)
2695 trace__printf_interrupted_entry(trace);
2696 trace__fprintf_tstamp(trace, sample->time, trace->output);
2698 if (trace->trace_syscalls && trace->show_duration)
2699 fprintf(trace->output, "( ): ");
2702 trace__fprintf_comm_tid(trace, thread, trace->output);
2704 if (evsel == trace->syscalls.events.augmented) {
2705 int id = perf_evsel__sc_tp_uint(evsel, id, sample);
2706 struct syscall *sc = trace__syscall_info(trace, evsel, id);
2709 fprintf(trace->output, "%s(", sc->name);
2710 trace__fprintf_sys_enter(trace, evsel, sample);
2711 fputc(')', trace->output);
2716 * XXX: Not having the associated syscall info or not finding/adding
2717 * the thread should never happen, but if it does...
2718 * fall thru and print it as a bpf_output event.
2722 fprintf(trace->output, "%s(", evsel->name);
2724 if (perf_evsel__is_bpf_output(evsel)) {
2725 bpf_output__fprintf(trace, sample);
2726 } else if (evsel->tp_format) {
2727 if (strncmp(evsel->tp_format->name, "sys_enter_", 10) ||
2728 trace__fprintf_sys_enter(trace, evsel, sample)) {
2729 if (trace->libtraceevent_print) {
2730 event_format__fprintf(evsel->tp_format, sample->cpu,
2731 sample->raw_data, sample->raw_size,
2734 trace__fprintf_tp_fields(trace, evsel, sample, thread, NULL, 0);
2740 fprintf(trace->output, ")\n");
2742 if (callchain_ret > 0)
2743 trace__fprintf_callchain(trace, sample);
2744 else if (callchain_ret < 0)
2745 pr_err("Problem processing %s callchain, skipping...\n", perf_evsel__name(evsel));
2747 ++trace->nr_events_printed;
2749 if (evsel->max_events != ULONG_MAX && ++evsel->nr_events_printed == evsel->max_events) {
2750 evsel__disable(evsel);
2751 evsel__close(evsel);
2754 thread__put(thread);
2758 static void print_location(FILE *f, struct perf_sample *sample,
2759 struct addr_location *al,
2760 bool print_dso, bool print_sym)
2763 if ((verbose > 0 || print_dso) && al->map)
2764 fprintf(f, "%s@", al->map->dso->long_name);
2766 if ((verbose > 0 || print_sym) && al->sym)
2767 fprintf(f, "%s+0x%" PRIx64, al->sym->name,
2768 al->addr - al->sym->start);
2770 fprintf(f, "0x%" PRIx64, al->addr);
2772 fprintf(f, "0x%" PRIx64, sample->addr);
2775 static int trace__pgfault(struct trace *trace,
2776 struct evsel *evsel,
2777 union perf_event *event __maybe_unused,
2778 struct perf_sample *sample)
2780 struct thread *thread;
2781 struct addr_location al;
2782 char map_type = 'd';
2783 struct thread_trace *ttrace;
2785 int callchain_ret = 0;
2787 thread = machine__findnew_thread(trace->host, sample->pid, sample->tid);
2789 if (sample->callchain) {
2790 callchain_ret = trace__resolve_callchain(trace, evsel, sample, &callchain_cursor);
2791 if (callchain_ret == 0) {
2792 if (callchain_cursor.nr < trace->min_stack)
2798 ttrace = thread__trace(thread, trace->output);
2802 if (evsel->core.attr.config == PERF_COUNT_SW_PAGE_FAULTS_MAJ)
2807 if (trace->summary_only)
2810 thread__find_symbol(thread, sample->cpumode, sample->ip, &al);
2812 trace__fprintf_entry_head(trace, thread, 0, true, sample->time, trace->output);
2814 fprintf(trace->output, "%sfault [",
2815 evsel->core.attr.config == PERF_COUNT_SW_PAGE_FAULTS_MAJ ?
2818 print_location(trace->output, sample, &al, false, true);
2820 fprintf(trace->output, "] => ");
2822 thread__find_symbol(thread, sample->cpumode, sample->addr, &al);
2825 thread__find_symbol(thread, sample->cpumode, sample->addr, &al);
2833 print_location(trace->output, sample, &al, true, false);
2835 fprintf(trace->output, " (%c%c)\n", map_type, al.level);
2837 if (callchain_ret > 0)
2838 trace__fprintf_callchain(trace, sample);
2839 else if (callchain_ret < 0)
2840 pr_err("Problem processing %s callchain, skipping...\n", perf_evsel__name(evsel));
2842 ++trace->nr_events_printed;
2846 thread__put(thread);
2850 static void trace__set_base_time(struct trace *trace,
2851 struct evsel *evsel,
2852 struct perf_sample *sample)
2855 * BPF events were not setting PERF_SAMPLE_TIME, so be more robust
2856 * and don't use sample->time unconditionally, we may end up having
2857 * some other event in the future without PERF_SAMPLE_TIME for good
2858 * reason, i.e. we may not be interested in its timestamps, just in
2859 * it taking place, picking some piece of information when it
2860 * appears in our event stream (vfs_getname comes to mind).
2862 if (trace->base_time == 0 && !trace->full_time &&
2863 (evsel->core.attr.sample_type & PERF_SAMPLE_TIME))
2864 trace->base_time = sample->time;
2867 static int trace__process_sample(struct perf_tool *tool,
2868 union perf_event *event,
2869 struct perf_sample *sample,
2870 struct evsel *evsel,
2871 struct machine *machine __maybe_unused)
2873 struct trace *trace = container_of(tool, struct trace, tool);
2874 struct thread *thread;
2877 tracepoint_handler handler = evsel->handler;
2879 thread = machine__findnew_thread(trace->host, sample->pid, sample->tid);
2880 if (thread && thread__is_filtered(thread))
2883 trace__set_base_time(trace, evsel, sample);
2887 handler(trace, evsel, event, sample);
2890 thread__put(thread);
2894 static int trace__record(struct trace *trace, int argc, const char **argv)
2896 unsigned int rec_argc, i, j;
2897 const char **rec_argv;
2898 const char * const record_args[] = {
2904 pid_t pid = getpid();
2905 char *filter = asprintf__tp_filter_pids(1, &pid);
2906 const char * const sc_args[] = { "-e", };
2907 unsigned int sc_args_nr = ARRAY_SIZE(sc_args);
2908 const char * const majpf_args[] = { "-e", "major-faults" };
2909 unsigned int majpf_args_nr = ARRAY_SIZE(majpf_args);
2910 const char * const minpf_args[] = { "-e", "minor-faults" };
2911 unsigned int minpf_args_nr = ARRAY_SIZE(minpf_args);
2914 /* +3 is for the event string below and the pid filter */
2915 rec_argc = ARRAY_SIZE(record_args) + sc_args_nr + 3 +
2916 majpf_args_nr + minpf_args_nr + argc;
2917 rec_argv = calloc(rec_argc + 1, sizeof(char *));
2919 if (rec_argv == NULL || filter == NULL)
2923 for (i = 0; i < ARRAY_SIZE(record_args); i++)
2924 rec_argv[j++] = record_args[i];
2926 if (trace->trace_syscalls) {
2927 for (i = 0; i < sc_args_nr; i++)
2928 rec_argv[j++] = sc_args[i];
2930 /* event string may be different for older kernels - e.g., RHEL6 */
2931 if (is_valid_tracepoint("raw_syscalls:sys_enter"))
2932 rec_argv[j++] = "raw_syscalls:sys_enter,raw_syscalls:sys_exit";
2933 else if (is_valid_tracepoint("syscalls:sys_enter"))
2934 rec_argv[j++] = "syscalls:sys_enter,syscalls:sys_exit";
2936 pr_err("Neither raw_syscalls nor syscalls events exist.\n");
2941 rec_argv[j++] = "--filter";
2942 rec_argv[j++] = filter;
2944 if (trace->trace_pgfaults & TRACE_PFMAJ)
2945 for (i = 0; i < majpf_args_nr; i++)
2946 rec_argv[j++] = majpf_args[i];
2948 if (trace->trace_pgfaults & TRACE_PFMIN)
2949 for (i = 0; i < minpf_args_nr; i++)
2950 rec_argv[j++] = minpf_args[i];
2952 for (i = 0; i < (unsigned int)argc; i++)
2953 rec_argv[j++] = argv[i];
2955 err = cmd_record(j, rec_argv);
2962 static size_t trace__fprintf_thread_summary(struct trace *trace, FILE *fp);
2964 static bool evlist__add_vfs_getname(struct evlist *evlist)
2967 struct evsel *evsel, *tmp;
2968 struct parse_events_error err = { .idx = 0, };
2969 int ret = parse_events(evlist, "probe:vfs_getname*", &err);
2974 evlist__for_each_entry_safe(evlist, evsel, tmp) {
2975 if (!strstarts(perf_evsel__name(evsel), "probe:vfs_getname"))
2978 if (perf_evsel__field(evsel, "pathname")) {
2979 evsel->handler = trace__vfs_getname;
2984 list_del_init(&evsel->core.node);
2985 evsel->evlist = NULL;
2986 evsel__delete(evsel);
2992 static struct evsel *perf_evsel__new_pgfault(u64 config)
2994 struct evsel *evsel;
2995 struct perf_event_attr attr = {
2996 .type = PERF_TYPE_SOFTWARE,
3000 attr.config = config;
3001 attr.sample_period = 1;
3003 event_attr_init(&attr);
3005 evsel = evsel__new(&attr);
3007 evsel->handler = trace__pgfault;
3012 static void trace__handle_event(struct trace *trace, union perf_event *event, struct perf_sample *sample)
3014 const u32 type = event->header.type;
3015 struct evsel *evsel;
3017 if (type != PERF_RECORD_SAMPLE) {
3018 trace__process_event(trace, trace->host, event, sample);
3022 evsel = perf_evlist__id2evsel(trace->evlist, sample->id);
3023 if (evsel == NULL) {
3024 fprintf(trace->output, "Unknown tp ID %" PRIu64 ", skipping...\n", sample->id);
3028 if (evswitch__discard(&trace->evswitch, evsel))
3031 trace__set_base_time(trace, evsel, sample);
3033 if (evsel->core.attr.type == PERF_TYPE_TRACEPOINT &&
3034 sample->raw_data == NULL) {
3035 fprintf(trace->output, "%s sample with no payload for tid: %d, cpu %d, raw_size=%d, skipping...\n",
3036 perf_evsel__name(evsel), sample->tid,
3037 sample->cpu, sample->raw_size);
3039 tracepoint_handler handler = evsel->handler;
3040 handler(trace, evsel, event, sample);
3043 if (trace->nr_events_printed >= trace->max_events && trace->max_events != ULONG_MAX)
3047 static int trace__add_syscall_newtp(struct trace *trace)
3050 struct evlist *evlist = trace->evlist;
3051 struct evsel *sys_enter, *sys_exit;
3053 sys_enter = perf_evsel__raw_syscall_newtp("sys_enter", trace__sys_enter);
3054 if (sys_enter == NULL)
3057 if (perf_evsel__init_sc_tp_ptr_field(sys_enter, args))
3058 goto out_delete_sys_enter;
3060 sys_exit = perf_evsel__raw_syscall_newtp("sys_exit", trace__sys_exit);
3061 if (sys_exit == NULL)
3062 goto out_delete_sys_enter;
3064 if (perf_evsel__init_sc_tp_uint_field(sys_exit, ret))
3065 goto out_delete_sys_exit;
3067 perf_evsel__config_callchain(sys_enter, &trace->opts, &callchain_param);
3068 perf_evsel__config_callchain(sys_exit, &trace->opts, &callchain_param);
3070 evlist__add(evlist, sys_enter);
3071 evlist__add(evlist, sys_exit);
3073 if (callchain_param.enabled && !trace->kernel_syscallchains) {
3075 * We're interested only in the user space callchain
3076 * leading to the syscall, allow overriding that for
3077 * debugging reasons using --kernel_syscall_callchains
3079 sys_exit->core.attr.exclude_callchain_kernel = 1;
3082 trace->syscalls.events.sys_enter = sys_enter;
3083 trace->syscalls.events.sys_exit = sys_exit;
3089 out_delete_sys_exit:
3090 evsel__delete_priv(sys_exit);
3091 out_delete_sys_enter:
3092 evsel__delete_priv(sys_enter);
3096 static int trace__set_ev_qualifier_tp_filter(struct trace *trace)
3099 struct evsel *sys_exit;
3100 char *filter = asprintf_expr_inout_ints("id", !trace->not_ev_qualifier,
3101 trace->ev_qualifier_ids.nr,
3102 trace->ev_qualifier_ids.entries);
3107 if (!perf_evsel__append_tp_filter(trace->syscalls.events.sys_enter,
3109 sys_exit = trace->syscalls.events.sys_exit;
3110 err = perf_evsel__append_tp_filter(sys_exit, filter);
3121 #ifdef HAVE_LIBBPF_SUPPORT
3122 static struct bpf_program *trace__find_bpf_program_by_title(struct trace *trace, const char *name)
3124 if (trace->bpf_obj == NULL)
3127 return bpf_object__find_program_by_title(trace->bpf_obj, name);
3130 static struct bpf_program *trace__find_syscall_bpf_prog(struct trace *trace, struct syscall *sc,
3131 const char *prog_name, const char *type)
3133 struct bpf_program *prog;
3135 if (prog_name == NULL) {
3136 char default_prog_name[256];
3137 scnprintf(default_prog_name, sizeof(default_prog_name), "!syscalls:sys_%s_%s", type, sc->name);
3138 prog = trace__find_bpf_program_by_title(trace, default_prog_name);
3141 if (sc->fmt && sc->fmt->alias) {
3142 scnprintf(default_prog_name, sizeof(default_prog_name), "!syscalls:sys_%s_%s", type, sc->fmt->alias);
3143 prog = trace__find_bpf_program_by_title(trace, default_prog_name);
3147 goto out_unaugmented;
3150 prog = trace__find_bpf_program_by_title(trace, prog_name);
3157 pr_debug("Couldn't find BPF prog \"%s\" to associate with syscalls:sys_%s_%s, not augmenting it\n",
3158 prog_name, type, sc->name);
3160 return trace->syscalls.unaugmented_prog;
3163 static void trace__init_syscall_bpf_progs(struct trace *trace, int id)
3165 struct syscall *sc = trace__syscall_info(trace, NULL, id);
3170 sc->bpf_prog.sys_enter = trace__find_syscall_bpf_prog(trace, sc, sc->fmt ? sc->fmt->bpf_prog_name.sys_enter : NULL, "enter");
3171 sc->bpf_prog.sys_exit = trace__find_syscall_bpf_prog(trace, sc, sc->fmt ? sc->fmt->bpf_prog_name.sys_exit : NULL, "exit");
3174 static int trace__bpf_prog_sys_enter_fd(struct trace *trace, int id)
3176 struct syscall *sc = trace__syscall_info(trace, NULL, id);
3177 return sc ? bpf_program__fd(sc->bpf_prog.sys_enter) : bpf_program__fd(trace->syscalls.unaugmented_prog);
3180 static int trace__bpf_prog_sys_exit_fd(struct trace *trace, int id)
3182 struct syscall *sc = trace__syscall_info(trace, NULL, id);
3183 return sc ? bpf_program__fd(sc->bpf_prog.sys_exit) : bpf_program__fd(trace->syscalls.unaugmented_prog);
3186 static void trace__init_bpf_map_syscall_args(struct trace *trace, int id, struct bpf_map_syscall_entry *entry)
3188 struct syscall *sc = trace__syscall_info(trace, NULL, id);
3194 for (; arg < sc->nr_args; ++arg) {
3195 entry->string_args_len[arg] = 0;
3196 if (sc->arg_fmt[arg].scnprintf == SCA_FILENAME) {
3197 /* Should be set like strace -s strsize */
3198 entry->string_args_len[arg] = PATH_MAX;
3202 for (; arg < 6; ++arg)
3203 entry->string_args_len[arg] = 0;
3205 static int trace__set_ev_qualifier_bpf_filter(struct trace *trace)
3207 int fd = bpf_map__fd(trace->syscalls.map);
3208 struct bpf_map_syscall_entry value = {
3209 .enabled = !trace->not_ev_qualifier,
3214 for (i = 0; i < trace->ev_qualifier_ids.nr; ++i) {
3215 int key = trace->ev_qualifier_ids.entries[i];
3217 if (value.enabled) {
3218 trace__init_bpf_map_syscall_args(trace, key, &value);
3219 trace__init_syscall_bpf_progs(trace, key);
3222 err = bpf_map_update_elem(fd, &key, &value, BPF_EXIST);
3230 static int __trace__init_syscalls_bpf_map(struct trace *trace, bool enabled)
3232 int fd = bpf_map__fd(trace->syscalls.map);
3233 struct bpf_map_syscall_entry value = {
3238 for (key = 0; key < trace->sctbl->syscalls.nr_entries; ++key) {
3240 trace__init_bpf_map_syscall_args(trace, key, &value);
3242 err = bpf_map_update_elem(fd, &key, &value, BPF_ANY);
3250 static int trace__init_syscalls_bpf_map(struct trace *trace)
3252 bool enabled = true;
3254 if (trace->ev_qualifier_ids.nr)
3255 enabled = trace->not_ev_qualifier;
3257 return __trace__init_syscalls_bpf_map(trace, enabled);
3260 static struct bpf_program *trace__find_usable_bpf_prog_entry(struct trace *trace, struct syscall *sc)
3262 struct tep_format_field *field, *candidate_field;
3266 * We're only interested in syscalls that have a pointer:
3268 for (field = sc->args; field; field = field->next) {
3269 if (field->flags & TEP_FIELD_IS_POINTER)
3270 goto try_to_find_pair;
3276 for (id = 0; id < trace->sctbl->syscalls.nr_entries; ++id) {
3277 struct syscall *pair = trace__syscall_info(trace, NULL, id);
3278 struct bpf_program *pair_prog;
3279 bool is_candidate = false;
3281 if (pair == NULL || pair == sc ||
3282 pair->bpf_prog.sys_enter == trace->syscalls.unaugmented_prog)
3285 for (field = sc->args, candidate_field = pair->args;
3286 field && candidate_field; field = field->next, candidate_field = candidate_field->next) {
3287 bool is_pointer = field->flags & TEP_FIELD_IS_POINTER,
3288 candidate_is_pointer = candidate_field->flags & TEP_FIELD_IS_POINTER;
3291 if (!candidate_is_pointer) {
3292 // The candidate just doesn't copies our pointer arg, might copy other pointers we want.
3296 if (candidate_is_pointer) {
3297 // The candidate might copy a pointer we don't have, skip it.
3298 goto next_candidate;
3303 if (strcmp(field->type, candidate_field->type))
3304 goto next_candidate;
3306 is_candidate = true;
3310 goto next_candidate;
3313 * Check if the tentative pair syscall augmenter has more pointers, if it has,
3314 * then it may be collecting that and we then can't use it, as it would collect
3315 * more than what is common to the two syscalls.
3317 if (candidate_field) {
3318 for (candidate_field = candidate_field->next; candidate_field; candidate_field = candidate_field->next)
3319 if (candidate_field->flags & TEP_FIELD_IS_POINTER)
3320 goto next_candidate;
3323 pair_prog = pair->bpf_prog.sys_enter;
3325 * If the pair isn't enabled, then its bpf_prog.sys_enter will not
3326 * have been searched for, so search it here and if it returns the
3327 * unaugmented one, then ignore it, otherwise we'll reuse that BPF
3328 * program for a filtered syscall on a non-filtered one.
3330 * For instance, we have "!syscalls:sys_enter_renameat" and that is
3331 * useful for "renameat2".
3333 if (pair_prog == NULL) {
3334 pair_prog = trace__find_syscall_bpf_prog(trace, pair, pair->fmt ? pair->fmt->bpf_prog_name.sys_enter : NULL, "enter");
3335 if (pair_prog == trace->syscalls.unaugmented_prog)
3336 goto next_candidate;
3339 pr_debug("Reusing \"%s\" BPF sys_enter augmenter for \"%s\"\n", pair->name, sc->name);
3348 static int trace__init_syscalls_bpf_prog_array_maps(struct trace *trace)
3350 int map_enter_fd = bpf_map__fd(trace->syscalls.prog_array.sys_enter),
3351 map_exit_fd = bpf_map__fd(trace->syscalls.prog_array.sys_exit);
3354 for (key = 0; key < trace->sctbl->syscalls.nr_entries; ++key) {
3357 if (!trace__syscall_enabled(trace, key))
3360 trace__init_syscall_bpf_progs(trace, key);
3362 // It'll get at least the "!raw_syscalls:unaugmented"
3363 prog_fd = trace__bpf_prog_sys_enter_fd(trace, key);
3364 err = bpf_map_update_elem(map_enter_fd, &key, &prog_fd, BPF_ANY);
3367 prog_fd = trace__bpf_prog_sys_exit_fd(trace, key);
3368 err = bpf_map_update_elem(map_exit_fd, &key, &prog_fd, BPF_ANY);
3374 * Now lets do a second pass looking for enabled syscalls without
3375 * an augmenter that have a signature that is a superset of another
3376 * syscall with an augmenter so that we can auto-reuse it.
3378 * I.e. if we have an augmenter for the "open" syscall that has
3381 * int open(const char *pathname, int flags, mode_t mode);
3383 * I.e. that will collect just the first string argument, then we
3384 * can reuse it for the 'creat' syscall, that has this signature:
3386 * int creat(const char *pathname, mode_t mode);
3390 * int stat(const char *pathname, struct stat *statbuf);
3391 * int lstat(const char *pathname, struct stat *statbuf);
3393 * Because the 'open' augmenter will collect the first arg as a string,
3394 * and leave alone all the other args, which already helps with
3395 * beautifying 'stat' and 'lstat''s pathname arg.
3397 * Then, in time, when 'stat' gets an augmenter that collects both
3398 * first and second arg (this one on the raw_syscalls:sys_exit prog
3399 * array tail call, then that one will be used.
3401 for (key = 0; key < trace->sctbl->syscalls.nr_entries; ++key) {
3402 struct syscall *sc = trace__syscall_info(trace, NULL, key);
3403 struct bpf_program *pair_prog;
3406 if (sc == NULL || sc->bpf_prog.sys_enter == NULL)
3410 * For now we're just reusing the sys_enter prog, and if it
3411 * already has an augmenter, we don't need to find one.
3413 if (sc->bpf_prog.sys_enter != trace->syscalls.unaugmented_prog)
3417 * Look at all the other syscalls for one that has a signature
3418 * that is close enough that we can share:
3420 pair_prog = trace__find_usable_bpf_prog_entry(trace, sc);
3421 if (pair_prog == NULL)
3424 sc->bpf_prog.sys_enter = pair_prog;
3427 * Update the BPF_MAP_TYPE_PROG_SHARED for raw_syscalls:sys_enter
3428 * with the fd for the program we're reusing:
3430 prog_fd = bpf_program__fd(sc->bpf_prog.sys_enter);
3431 err = bpf_map_update_elem(map_enter_fd, &key, &prog_fd, BPF_ANY);
3440 static void trace__delete_augmented_syscalls(struct trace *trace)
3442 struct evsel *evsel, *tmp;
3444 evlist__remove(trace->evlist, trace->syscalls.events.augmented);
3445 evsel__delete(trace->syscalls.events.augmented);
3446 trace->syscalls.events.augmented = NULL;
3448 evlist__for_each_entry_safe(trace->evlist, tmp, evsel) {
3449 if (evsel->bpf_obj == trace->bpf_obj) {
3450 evlist__remove(trace->evlist, evsel);
3451 evsel__delete(evsel);
3456 bpf_object__close(trace->bpf_obj);
3457 trace->bpf_obj = NULL;
3459 #else // HAVE_LIBBPF_SUPPORT
3460 static int trace__set_ev_qualifier_bpf_filter(struct trace *trace __maybe_unused)
3465 static int trace__init_syscalls_bpf_map(struct trace *trace __maybe_unused)
3470 static struct bpf_program *trace__find_bpf_program_by_title(struct trace *trace __maybe_unused,
3471 const char *name __maybe_unused)
3476 static int trace__init_syscalls_bpf_prog_array_maps(struct trace *trace __maybe_unused)
3481 static void trace__delete_augmented_syscalls(struct trace *trace __maybe_unused)
3484 #endif // HAVE_LIBBPF_SUPPORT
3486 static bool trace__only_augmented_syscalls_evsels(struct trace *trace)
3488 struct evsel *evsel;
3490 evlist__for_each_entry(trace->evlist, evsel) {
3491 if (evsel == trace->syscalls.events.augmented ||
3492 evsel->bpf_obj == trace->bpf_obj)
3501 static int trace__set_ev_qualifier_filter(struct trace *trace)
3503 if (trace->syscalls.map)
3504 return trace__set_ev_qualifier_bpf_filter(trace);
3505 if (trace->syscalls.events.sys_enter)
3506 return trace__set_ev_qualifier_tp_filter(trace);
3510 static int bpf_map__set_filter_pids(struct bpf_map *map __maybe_unused,
3511 size_t npids __maybe_unused, pid_t *pids __maybe_unused)
3514 #ifdef HAVE_LIBBPF_SUPPORT
3516 int map_fd = bpf_map__fd(map);
3519 for (i = 0; i < npids; ++i) {
3520 err = bpf_map_update_elem(map_fd, &pids[i], &value, BPF_ANY);
3528 static int trace__set_filter_loop_pids(struct trace *trace)
3530 unsigned int nr = 1, err;
3534 struct thread *thread = machine__find_thread(trace->host, pids[0], pids[0]);
3536 while (thread && nr < ARRAY_SIZE(pids)) {
3537 struct thread *parent = machine__find_thread(trace->host, thread->ppid, thread->ppid);
3542 if (!strcmp(thread__comm_str(parent), "sshd") ||
3543 strstarts(thread__comm_str(parent), "gnome-terminal")) {
3544 pids[nr++] = parent->tid;
3550 err = perf_evlist__append_tp_filter_pids(trace->evlist, nr, pids);
3551 if (!err && trace->filter_pids.map)
3552 err = bpf_map__set_filter_pids(trace->filter_pids.map, nr, pids);
3557 static int trace__set_filter_pids(struct trace *trace)
3561 * Better not use !target__has_task() here because we need to cover the
3562 * case where no threads were specified in the command line, but a
3563 * workload was, and in that case we will fill in the thread_map when
3564 * we fork the workload in perf_evlist__prepare_workload.
3566 if (trace->filter_pids.nr > 0) {
3567 err = perf_evlist__append_tp_filter_pids(trace->evlist, trace->filter_pids.nr,
3568 trace->filter_pids.entries);
3569 if (!err && trace->filter_pids.map) {
3570 err = bpf_map__set_filter_pids(trace->filter_pids.map, trace->filter_pids.nr,
3571 trace->filter_pids.entries);
3573 } else if (perf_thread_map__pid(trace->evlist->core.threads, 0) == -1) {
3574 err = trace__set_filter_loop_pids(trace);
3580 static int __trace__deliver_event(struct trace *trace, union perf_event *event)
3582 struct evlist *evlist = trace->evlist;
3583 struct perf_sample sample;
3586 err = perf_evlist__parse_sample(evlist, event, &sample);
3588 fprintf(trace->output, "Can't parse sample, err = %d, skipping...\n", err);
3590 trace__handle_event(trace, event, &sample);
3595 static int __trace__flush_events(struct trace *trace)
3597 u64 first = ordered_events__first_time(&trace->oe.data);
3598 u64 flush = trace->oe.last - NSEC_PER_SEC;
3600 /* Is there some thing to flush.. */
3601 if (first && first < flush)
3602 return ordered_events__flush_time(&trace->oe.data, flush);
3607 static int trace__flush_events(struct trace *trace)
3609 return !trace->sort_events ? 0 : __trace__flush_events(trace);
3612 static int trace__deliver_event(struct trace *trace, union perf_event *event)
3616 if (!trace->sort_events)
3617 return __trace__deliver_event(trace, event);
3619 err = perf_evlist__parse_sample_timestamp(trace->evlist, event, &trace->oe.last);
3620 if (err && err != -1)
3623 err = ordered_events__queue(&trace->oe.data, event, trace->oe.last, 0);
3627 return trace__flush_events(trace);
3630 static int ordered_events__deliver_event(struct ordered_events *oe,
3631 struct ordered_event *event)
3633 struct trace *trace = container_of(oe, struct trace, oe.data);
3635 return __trace__deliver_event(trace, event->event);
3638 static struct syscall_arg_fmt *perf_evsel__syscall_arg_fmt(struct evsel *evsel, char *arg)
3640 struct tep_format_field *field;
3641 struct syscall_arg_fmt *fmt = __evsel__syscall_arg_fmt(evsel);
3643 if (evsel->tp_format == NULL || fmt == NULL)
3646 for (field = evsel->tp_format->format.fields; field; field = field->next, ++fmt)
3647 if (strcmp(field->name, arg) == 0)
3653 static int trace__expand_filter(struct trace *trace __maybe_unused, struct evsel *evsel)
3655 char *tok, *left = evsel->filter, *new_filter = evsel->filter;
3657 while ((tok = strpbrk(left, "=<>!")) != NULL) {
3658 char *right = tok + 1, *right_end;
3663 while (isspace(*right))
3669 while (!isalpha(*left))
3670 if (++left == tok) {
3672 * Bail out, can't find the name of the argument that is being
3673 * used in the filter, let it try to set this filter, will fail later.
3678 right_end = right + 1;
3679 while (isalnum(*right_end) || *right_end == '_')
3682 if (isalpha(*right)) {
3683 struct syscall_arg_fmt *fmt;
3684 int left_size = tok - left,
3685 right_size = right_end - right;
3688 while (isspace(left[left_size - 1]))
3691 scnprintf(arg, sizeof(arg), "%.*s", left_size, left);
3693 fmt = perf_evsel__syscall_arg_fmt(evsel, arg);
3695 pr_err("\"%s\" not found in \"%s\", can't set filter \"%s\"\n",
3696 arg, evsel->name, evsel->filter);
3700 pr_debug2("trying to expand \"%s\" \"%.*s\" \"%.*s\" -> ",
3701 arg, (int)(right - tok), tok, right_size, right);
3705 struct syscall_arg syscall_arg = {
3709 if (fmt->strtoul(right, right_size, &syscall_arg, &val)) {
3710 char *n, expansion[19];
3711 int expansion_lenght = scnprintf(expansion, sizeof(expansion), "%#" PRIx64, val);
3712 int expansion_offset = right - new_filter;
3714 pr_debug("%s", expansion);
3716 if (asprintf(&n, "%.*s%s%s", expansion_offset, new_filter, expansion, right_end) < 0) {
3717 pr_debug(" out of memory!\n");
3721 if (new_filter != evsel->filter)
3723 left = n + expansion_offset + expansion_lenght;
3726 pr_err("\"%.*s\" not found for \"%s\" in \"%s\", can't set filter \"%s\"\n",
3727 right_size, right, arg, evsel->name, evsel->filter);
3731 pr_err("No resolver (strtoul) for \"%s\" in \"%s\", can't set filter \"%s\"\n",
3732 arg, evsel->name, evsel->filter);
3742 if (new_filter != evsel->filter) {
3743 pr_debug("New filter for %s: %s\n", evsel->name, new_filter);
3744 perf_evsel__set_filter(evsel, new_filter);
3751 static int trace__expand_filters(struct trace *trace, struct evsel **err_evsel)
3753 struct evlist *evlist = trace->evlist;
3754 struct evsel *evsel;
3756 evlist__for_each_entry(evlist, evsel) {
3757 if (evsel->filter == NULL)
3760 if (trace__expand_filter(trace, evsel)) {
3769 static int trace__run(struct trace *trace, int argc, const char **argv)
3771 struct evlist *evlist = trace->evlist;
3772 struct evsel *evsel, *pgfault_maj = NULL, *pgfault_min = NULL;
3774 unsigned long before;
3775 const bool forks = argc > 0;
3776 bool draining = false;
3780 if (!trace->raw_augmented_syscalls) {
3781 if (trace->trace_syscalls && trace__add_syscall_newtp(trace))
3782 goto out_error_raw_syscalls;
3784 if (trace->trace_syscalls)
3785 trace->vfs_getname = evlist__add_vfs_getname(evlist);
3788 if ((trace->trace_pgfaults & TRACE_PFMAJ)) {
3789 pgfault_maj = perf_evsel__new_pgfault(PERF_COUNT_SW_PAGE_FAULTS_MAJ);
3790 if (pgfault_maj == NULL)
3792 perf_evsel__config_callchain(pgfault_maj, &trace->opts, &callchain_param);
3793 evlist__add(evlist, pgfault_maj);
3796 if ((trace->trace_pgfaults & TRACE_PFMIN)) {
3797 pgfault_min = perf_evsel__new_pgfault(PERF_COUNT_SW_PAGE_FAULTS_MIN);
3798 if (pgfault_min == NULL)
3800 perf_evsel__config_callchain(pgfault_min, &trace->opts, &callchain_param);
3801 evlist__add(evlist, pgfault_min);
3805 perf_evlist__add_newtp(evlist, "sched", "sched_stat_runtime",
3806 trace__sched_stat_runtime))
3807 goto out_error_sched_stat_runtime;
3809 * If a global cgroup was set, apply it to all the events without an
3810 * explicit cgroup. I.e.:
3812 * trace -G A -e sched:*switch
3814 * Will set all raw_syscalls:sys_{enter,exit}, pgfault, vfs_getname, etc
3815 * _and_ sched:sched_switch to the 'A' cgroup, while:
3817 * trace -e sched:*switch -G A
3819 * will only set the sched:sched_switch event to the 'A' cgroup, all the
3820 * other events (raw_syscalls:sys_{enter,exit}, etc are left "without"
3821 * a cgroup (on the root cgroup, sys wide, etc).
3825 * trace -G A -e sched:*switch -G B
3827 * the syscall ones go to the 'A' cgroup, the sched:sched_switch goes
3828 * to the 'B' cgroup.
3830 * evlist__set_default_cgroup() grabs a reference of the passed cgroup
3831 * only for the evsels still without a cgroup, i.e. evsel->cgroup == NULL.
3834 evlist__set_default_cgroup(trace->evlist, trace->cgroup);
3836 err = perf_evlist__create_maps(evlist, &trace->opts.target);
3838 fprintf(trace->output, "Problems parsing the target to trace, check your options!\n");
3839 goto out_delete_evlist;
3842 err = trace__symbols_init(trace, evlist);
3844 fprintf(trace->output, "Problems initializing symbol libraries!\n");
3845 goto out_delete_evlist;
3848 perf_evlist__config(evlist, &trace->opts, &callchain_param);
3850 signal(SIGCHLD, sig_handler);
3851 signal(SIGINT, sig_handler);
3854 err = perf_evlist__prepare_workload(evlist, &trace->opts.target,
3857 fprintf(trace->output, "Couldn't run the workload!\n");
3858 goto out_delete_evlist;
3862 err = evlist__open(evlist);
3864 goto out_error_open;
3866 err = bpf__apply_obj_config();
3868 char errbuf[BUFSIZ];
3870 bpf__strerror_apply_obj_config(err, errbuf, sizeof(errbuf));
3871 pr_err("ERROR: Apply config to BPF failed: %s\n",
3873 goto out_error_open;
3876 err = trace__set_filter_pids(trace);
3880 if (trace->syscalls.map)
3881 trace__init_syscalls_bpf_map(trace);
3883 if (trace->syscalls.prog_array.sys_enter)
3884 trace__init_syscalls_bpf_prog_array_maps(trace);
3886 if (trace->ev_qualifier_ids.nr > 0) {
3887 err = trace__set_ev_qualifier_filter(trace);
3891 if (trace->syscalls.events.sys_exit) {
3892 pr_debug("event qualifier tracepoint filter: %s\n",
3893 trace->syscalls.events.sys_exit->filter);
3898 * If the "close" syscall is not traced, then we will not have the
3899 * opportunity to, in syscall_arg__scnprintf_close_fd() invalidate the
3900 * fd->pathname table and were ending up showing the last value set by
3901 * syscalls opening a pathname and associating it with a descriptor or
3902 * reading it from /proc/pid/fd/ in cases where that doesn't make
3905 * So just disable this beautifier (SCA_FD, SCA_FDAT) when 'close' is
3908 trace->fd_path_disabled = !trace__syscall_enabled(trace, syscalltbl__id(trace->sctbl, "close"));
3910 err = trace__expand_filters(trace, &evsel);
3912 goto out_delete_evlist;
3913 err = perf_evlist__apply_filters(evlist, &evsel);
3915 goto out_error_apply_filters;
3917 if (trace->dump.map)
3918 bpf_map__fprintf(trace->dump.map, trace->output);
3920 err = evlist__mmap(evlist, trace->opts.mmap_pages);
3922 goto out_error_mmap;
3924 if (!target__none(&trace->opts.target) && !trace->opts.initial_delay)
3925 evlist__enable(evlist);
3928 perf_evlist__start_workload(evlist);
3930 if (trace->opts.initial_delay) {
3931 usleep(trace->opts.initial_delay * 1000);
3932 evlist__enable(evlist);
3935 trace->multiple_threads = perf_thread_map__pid(evlist->core.threads, 0) == -1 ||
3936 evlist->core.threads->nr > 1 ||
3937 evlist__first(evlist)->core.attr.inherit;
3940 * Now that we already used evsel->core.attr to ask the kernel to setup the
3941 * events, lets reuse evsel->core.attr.sample_max_stack as the limit in
3942 * trace__resolve_callchain(), allowing per-event max-stack settings
3943 * to override an explicitly set --max-stack global setting.
3945 evlist__for_each_entry(evlist, evsel) {
3946 if (evsel__has_callchain(evsel) &&
3947 evsel->core.attr.sample_max_stack == 0)
3948 evsel->core.attr.sample_max_stack = trace->max_stack;
3951 before = trace->nr_events;
3953 for (i = 0; i < evlist->core.nr_mmaps; i++) {
3954 union perf_event *event;
3957 md = &evlist->mmap[i];
3958 if (perf_mmap__read_init(&md->core) < 0)
3961 while ((event = perf_mmap__read_event(&md->core)) != NULL) {
3964 err = trace__deliver_event(trace, event);
3968 perf_mmap__consume(&md->core);
3973 if (done && !draining) {
3974 evlist__disable(evlist);
3978 perf_mmap__read_done(&md->core);
3981 if (trace->nr_events == before) {
3982 int timeout = done ? 100 : -1;
3984 if (!draining && evlist__poll(evlist, timeout) > 0) {
3985 if (evlist__filter_pollfd(evlist, POLLERR | POLLHUP | POLLNVAL) == 0)
3990 if (trace__flush_events(trace))
3998 thread__zput(trace->current);
4000 evlist__disable(evlist);
4002 if (trace->sort_events)
4003 ordered_events__flush(&trace->oe.data, OE_FLUSH__FINAL);
4007 trace__fprintf_thread_summary(trace, trace->output);
4009 if (trace->show_tool_stats) {
4010 fprintf(trace->output, "Stats:\n "
4011 " vfs_getname : %" PRIu64 "\n"
4012 " proc_getname: %" PRIu64 "\n",
4013 trace->stats.vfs_getname,
4014 trace->stats.proc_getname);
4019 trace__symbols__exit(trace);
4021 evlist__delete(evlist);
4022 cgroup__put(trace->cgroup);
4023 trace->evlist = NULL;
4024 trace->live = false;
4027 char errbuf[BUFSIZ];
4029 out_error_sched_stat_runtime:
4030 tracing_path__strerror_open_tp(errno, errbuf, sizeof(errbuf), "sched", "sched_stat_runtime");
4033 out_error_raw_syscalls:
4034 tracing_path__strerror_open_tp(errno, errbuf, sizeof(errbuf), "raw_syscalls", "sys_(enter|exit)");
4038 perf_evlist__strerror_mmap(evlist, errno, errbuf, sizeof(errbuf));
4042 perf_evlist__strerror_open(evlist, errno, errbuf, sizeof(errbuf));
4045 fprintf(trace->output, "%s\n", errbuf);
4046 goto out_delete_evlist;
4048 out_error_apply_filters:
4049 fprintf(trace->output,
4050 "Failed to set filter \"%s\" on event %s with %d (%s)\n",
4051 evsel->filter, perf_evsel__name(evsel), errno,
4052 str_error_r(errno, errbuf, sizeof(errbuf)));
4053 goto out_delete_evlist;
4056 fprintf(trace->output, "Not enough memory to run!\n");
4057 goto out_delete_evlist;
4060 fprintf(trace->output, "errno=%d,%s\n", errno, strerror(errno));
4061 goto out_delete_evlist;
4064 static int trace__replay(struct trace *trace)
4066 const struct evsel_str_handler handlers[] = {
4067 { "probe:vfs_getname", trace__vfs_getname, },
4069 struct perf_data data = {
4071 .mode = PERF_DATA_MODE_READ,
4072 .force = trace->force,
4074 struct perf_session *session;
4075 struct evsel *evsel;
4078 trace->tool.sample = trace__process_sample;
4079 trace->tool.mmap = perf_event__process_mmap;
4080 trace->tool.mmap2 = perf_event__process_mmap2;
4081 trace->tool.comm = perf_event__process_comm;
4082 trace->tool.exit = perf_event__process_exit;
4083 trace->tool.fork = perf_event__process_fork;
4084 trace->tool.attr = perf_event__process_attr;
4085 trace->tool.tracing_data = perf_event__process_tracing_data;
4086 trace->tool.build_id = perf_event__process_build_id;
4087 trace->tool.namespaces = perf_event__process_namespaces;
4089 trace->tool.ordered_events = true;
4090 trace->tool.ordering_requires_timestamps = true;
4092 /* add tid to output */
4093 trace->multiple_threads = true;
4095 session = perf_session__new(&data, false, &trace->tool);
4096 if (IS_ERR(session))
4097 return PTR_ERR(session);
4099 if (trace->opts.target.pid)
4100 symbol_conf.pid_list_str = strdup(trace->opts.target.pid);
4102 if (trace->opts.target.tid)
4103 symbol_conf.tid_list_str = strdup(trace->opts.target.tid);
4105 if (symbol__init(&session->header.env) < 0)
4108 trace->host = &session->machines.host;
4110 err = perf_session__set_tracepoints_handlers(session, handlers);
4114 evsel = perf_evlist__find_tracepoint_by_name(session->evlist,
4115 "raw_syscalls:sys_enter");
4116 /* older kernels have syscalls tp versus raw_syscalls */
4118 evsel = perf_evlist__find_tracepoint_by_name(session->evlist,
4119 "syscalls:sys_enter");
4122 (perf_evsel__init_raw_syscall_tp(evsel, trace__sys_enter) < 0 ||
4123 perf_evsel__init_sc_tp_ptr_field(evsel, args))) {
4124 pr_err("Error during initialize raw_syscalls:sys_enter event\n");
4128 evsel = perf_evlist__find_tracepoint_by_name(session->evlist,
4129 "raw_syscalls:sys_exit");
4131 evsel = perf_evlist__find_tracepoint_by_name(session->evlist,
4132 "syscalls:sys_exit");
4134 (perf_evsel__init_raw_syscall_tp(evsel, trace__sys_exit) < 0 ||
4135 perf_evsel__init_sc_tp_uint_field(evsel, ret))) {
4136 pr_err("Error during initialize raw_syscalls:sys_exit event\n");
4140 evlist__for_each_entry(session->evlist, evsel) {
4141 if (evsel->core.attr.type == PERF_TYPE_SOFTWARE &&
4142 (evsel->core.attr.config == PERF_COUNT_SW_PAGE_FAULTS_MAJ ||
4143 evsel->core.attr.config == PERF_COUNT_SW_PAGE_FAULTS_MIN ||
4144 evsel->core.attr.config == PERF_COUNT_SW_PAGE_FAULTS))
4145 evsel->handler = trace__pgfault;
4150 err = perf_session__process_events(session);
4152 pr_err("Failed to process events, error %d", err);
4154 else if (trace->summary)
4155 trace__fprintf_thread_summary(trace, trace->output);
4158 perf_session__delete(session);
4163 static size_t trace__fprintf_threads_header(FILE *fp)
4167 printed = fprintf(fp, "\n Summary of events:\n\n");
4172 DEFINE_RESORT_RB(syscall_stats, a->msecs > b->msecs,
4173 struct syscall_stats *stats;
4178 struct int_node *source = rb_entry(nd, struct int_node, rb_node);
4179 struct syscall_stats *stats = source->priv;
4181 entry->syscall = source->i;
4182 entry->stats = stats;
4183 entry->msecs = stats ? (u64)stats->stats.n * (avg_stats(&stats->stats) / NSEC_PER_MSEC) : 0;
4186 static size_t thread__dump_stats(struct thread_trace *ttrace,
4187 struct trace *trace, FILE *fp)
4192 DECLARE_RESORT_RB_INTLIST(syscall_stats, ttrace->syscall_stats);
4194 if (syscall_stats == NULL)
4197 printed += fprintf(fp, "\n");
4199 printed += fprintf(fp, " syscall calls errors total min avg max stddev\n");
4200 printed += fprintf(fp, " (msec) (msec) (msec) (msec) (%%)\n");
4201 printed += fprintf(fp, " --------------- -------- ------ -------- --------- --------- --------- ------\n");
4203 resort_rb__for_each_entry(nd, syscall_stats) {
4204 struct syscall_stats *stats = syscall_stats_entry->stats;
4206 double min = (double)(stats->stats.min) / NSEC_PER_MSEC;
4207 double max = (double)(stats->stats.max) / NSEC_PER_MSEC;
4208 double avg = avg_stats(&stats->stats);
4210 u64 n = (u64)stats->stats.n;
4212 pct = avg ? 100.0 * stddev_stats(&stats->stats) / avg : 0.0;
4213 avg /= NSEC_PER_MSEC;
4215 sc = &trace->syscalls.table[syscall_stats_entry->syscall];
4216 printed += fprintf(fp, " %-15s", sc->name);
4217 printed += fprintf(fp, " %8" PRIu64 " %6" PRIu64 " %9.3f %9.3f %9.3f",
4218 n, stats->nr_failures, syscall_stats_entry->msecs, min, avg);
4219 printed += fprintf(fp, " %9.3f %9.2f%%\n", max, pct);
4221 if (trace->errno_summary && stats->nr_failures) {
4222 const char *arch_name = perf_env__arch(trace->host->env);
4225 for (e = 0; e < stats->max_errno; ++e) {
4226 if (stats->errnos[e] != 0)
4227 fprintf(fp, "\t\t\t\t%s: %d\n", arch_syscalls__strerrno(arch_name, e + 1), stats->errnos[e]);
4233 resort_rb__delete(syscall_stats);
4234 printed += fprintf(fp, "\n\n");
4239 static size_t trace__fprintf_thread(FILE *fp, struct thread *thread, struct trace *trace)
4242 struct thread_trace *ttrace = thread__priv(thread);
4248 ratio = (double)ttrace->nr_events / trace->nr_events * 100.0;
4250 printed += fprintf(fp, " %s (%d), ", thread__comm_str(thread), thread->tid);
4251 printed += fprintf(fp, "%lu events, ", ttrace->nr_events);
4252 printed += fprintf(fp, "%.1f%%", ratio);
4254 printed += fprintf(fp, ", %lu majfaults", ttrace->pfmaj);
4256 printed += fprintf(fp, ", %lu minfaults", ttrace->pfmin);
4258 printed += fprintf(fp, ", %.3f msec\n", ttrace->runtime_ms);
4259 else if (fputc('\n', fp) != EOF)
4262 printed += thread__dump_stats(ttrace, trace, fp);
4267 static unsigned long thread__nr_events(struct thread_trace *ttrace)
4269 return ttrace ? ttrace->nr_events : 0;
4272 DEFINE_RESORT_RB(threads, (thread__nr_events(a->thread->priv) < thread__nr_events(b->thread->priv)),
4273 struct thread *thread;
4276 entry->thread = rb_entry(nd, struct thread, rb_node);
4279 static size_t trace__fprintf_thread_summary(struct trace *trace, FILE *fp)
4281 size_t printed = trace__fprintf_threads_header(fp);
4285 for (i = 0; i < THREADS__TABLE_SIZE; i++) {
4286 DECLARE_RESORT_RB_MACHINE_THREADS(threads, trace->host, i);
4288 if (threads == NULL) {
4289 fprintf(fp, "%s", "Error sorting output by nr_events!\n");
4293 resort_rb__for_each_entry(nd, threads)
4294 printed += trace__fprintf_thread(fp, threads_entry->thread, trace);
4296 resort_rb__delete(threads);
4301 static int trace__set_duration(const struct option *opt, const char *str,
4302 int unset __maybe_unused)
4304 struct trace *trace = opt->value;
4306 trace->duration_filter = atof(str);
4310 static int trace__set_filter_pids_from_option(const struct option *opt, const char *str,
4311 int unset __maybe_unused)
4315 struct trace *trace = opt->value;
4317 * FIXME: introduce a intarray class, plain parse csv and create a
4318 * { int nr, int entries[] } struct...
4320 struct intlist *list = intlist__new(str);
4325 i = trace->filter_pids.nr = intlist__nr_entries(list) + 1;
4326 trace->filter_pids.entries = calloc(i, sizeof(pid_t));
4328 if (trace->filter_pids.entries == NULL)
4331 trace->filter_pids.entries[0] = getpid();
4333 for (i = 1; i < trace->filter_pids.nr; ++i)
4334 trace->filter_pids.entries[i] = intlist__entry(list, i - 1)->i;
4336 intlist__delete(list);
4342 static int trace__open_output(struct trace *trace, const char *filename)
4346 if (!stat(filename, &st) && st.st_size) {
4347 char oldname[PATH_MAX];
4349 scnprintf(oldname, sizeof(oldname), "%s.old", filename);
4351 rename(filename, oldname);
4354 trace->output = fopen(filename, "w");
4356 return trace->output == NULL ? -errno : 0;
4359 static int parse_pagefaults(const struct option *opt, const char *str,
4360 int unset __maybe_unused)
4362 int *trace_pgfaults = opt->value;
4364 if (strcmp(str, "all") == 0)
4365 *trace_pgfaults |= TRACE_PFMAJ | TRACE_PFMIN;
4366 else if (strcmp(str, "maj") == 0)
4367 *trace_pgfaults |= TRACE_PFMAJ;
4368 else if (strcmp(str, "min") == 0)
4369 *trace_pgfaults |= TRACE_PFMIN;
4376 static void evlist__set_default_evsel_handler(struct evlist *evlist, void *handler)
4378 struct evsel *evsel;
4380 evlist__for_each_entry(evlist, evsel) {
4381 if (evsel->handler == NULL)
4382 evsel->handler = handler;
4386 static void evsel__set_syscall_arg_fmt(struct evsel *evsel, const char *name)
4388 struct syscall_arg_fmt *fmt = evsel__syscall_arg_fmt(evsel);
4391 struct syscall_fmt *scfmt = syscall_fmt__find(name);
4396 if (strcmp(evsel->tp_format->format.fields->name, "__syscall_nr") == 0 ||
4397 strcmp(evsel->tp_format->format.fields->name, "nr") == 0)
4400 memcpy(fmt + skip, scfmt->arg, (evsel->tp_format->format.nr_fields - skip) * sizeof(*fmt));
4405 static int evlist__set_syscall_tp_fields(struct evlist *evlist)
4407 struct evsel *evsel;
4409 evlist__for_each_entry(evlist, evsel) {
4410 if (evsel->priv || !evsel->tp_format)
4413 if (strcmp(evsel->tp_format->system, "syscalls")) {
4414 perf_evsel__init_tp_arg_scnprintf(evsel);
4418 if (perf_evsel__init_syscall_tp(evsel))
4421 if (!strncmp(evsel->tp_format->name, "sys_enter_", 10)) {
4422 struct syscall_tp *sc = __evsel__syscall_tp(evsel);
4424 if (__tp_field__init_ptr(&sc->args, sc->id.offset + sizeof(u64)))
4427 evsel__set_syscall_arg_fmt(evsel, evsel->tp_format->name + sizeof("sys_enter_") - 1);
4428 } else if (!strncmp(evsel->tp_format->name, "sys_exit_", 9)) {
4429 struct syscall_tp *sc = __evsel__syscall_tp(evsel);
4431 if (__tp_field__init_uint(&sc->ret, sizeof(u64), sc->id.offset + sizeof(u64), evsel->needs_swap))
4434 evsel__set_syscall_arg_fmt(evsel, evsel->tp_format->name + sizeof("sys_exit_") - 1);
4442 * XXX: Hackish, just splitting the combined -e+--event (syscalls
4443 * (raw_syscalls:{sys_{enter,exit}} + events (tracepoints, HW, SW, etc) to use
4444 * existing facilities unchanged (trace->ev_qualifier + parse_options()).
4446 * It'd be better to introduce a parse_options() variant that would return a
4447 * list with the terms it didn't match to an event...
4449 static int trace__parse_events_option(const struct option *opt, const char *str,
4450 int unset __maybe_unused)
4452 struct trace *trace = (struct trace *)opt->value;
4453 const char *s = str;
4454 char *sep = NULL, *lists[2] = { NULL, NULL, };
4455 int len = strlen(str) + 1, err = -1, list, idx;
4456 char *strace_groups_dir = system_path(STRACE_GROUPS_DIR);
4457 char group_name[PATH_MAX];
4458 struct syscall_fmt *fmt;
4460 if (strace_groups_dir == NULL)
4465 trace->not_ev_qualifier = true;
4469 if ((sep = strchr(s, ',')) != NULL)
4473 if (syscalltbl__id(trace->sctbl, s) >= 0 ||
4474 syscalltbl__strglobmatch_first(trace->sctbl, s, &idx) >= 0) {
4479 fmt = syscall_fmt__find_by_alias(s);
4484 path__join(group_name, sizeof(group_name), strace_groups_dir, s);
4485 if (access(group_name, R_OK) == 0)
4490 sprintf(lists[list] + strlen(lists[list]), ",%s", s);
4492 lists[list] = malloc(len);
4493 if (lists[list] == NULL)
4495 strcpy(lists[list], s);
4505 if (lists[1] != NULL) {
4506 struct strlist_config slist_config = {
4507 .dirname = strace_groups_dir,
4510 trace->ev_qualifier = strlist__new(lists[1], &slist_config);
4511 if (trace->ev_qualifier == NULL) {
4512 fputs("Not enough memory to parse event qualifier", trace->output);
4516 if (trace__validate_ev_qualifier(trace))
4518 trace->trace_syscalls = true;
4524 struct option o = OPT_CALLBACK('e', "event", &trace->evlist, "event",
4525 "event selector. use 'perf list' to list available events",
4526 parse_events_option);
4527 err = parse_events_option(&o, lists[0], 0);
4536 static int trace__parse_cgroups(const struct option *opt, const char *str, int unset)
4538 struct trace *trace = opt->value;
4540 if (!list_empty(&trace->evlist->core.entries))
4541 return parse_cgroups(opt, str, unset);
4543 trace->cgroup = evlist__findnew_cgroup(trace->evlist, str);
4548 static struct bpf_map *trace__find_bpf_map_by_name(struct trace *trace, const char *name)
4550 if (trace->bpf_obj == NULL)
4553 return bpf_object__find_map_by_name(trace->bpf_obj, name);
4556 static void trace__set_bpf_map_filtered_pids(struct trace *trace)
4558 trace->filter_pids.map = trace__find_bpf_map_by_name(trace, "pids_filtered");
4561 static void trace__set_bpf_map_syscalls(struct trace *trace)
4563 trace->syscalls.map = trace__find_bpf_map_by_name(trace, "syscalls");
4564 trace->syscalls.prog_array.sys_enter = trace__find_bpf_map_by_name(trace, "syscalls_sys_enter");
4565 trace->syscalls.prog_array.sys_exit = trace__find_bpf_map_by_name(trace, "syscalls_sys_exit");
4568 static int trace__config(const char *var, const char *value, void *arg)
4570 struct trace *trace = arg;
4573 if (!strcmp(var, "trace.add_events")) {
4574 trace->perfconfig_events = strdup(value);
4575 if (trace->perfconfig_events == NULL) {
4576 pr_err("Not enough memory for %s\n", "trace.add_events");
4579 } else if (!strcmp(var, "trace.show_timestamp")) {
4580 trace->show_tstamp = perf_config_bool(var, value);
4581 } else if (!strcmp(var, "trace.show_duration")) {
4582 trace->show_duration = perf_config_bool(var, value);
4583 } else if (!strcmp(var, "trace.show_arg_names")) {
4584 trace->show_arg_names = perf_config_bool(var, value);
4585 if (!trace->show_arg_names)
4586 trace->show_zeros = true;
4587 } else if (!strcmp(var, "trace.show_zeros")) {
4588 bool new_show_zeros = perf_config_bool(var, value);
4589 if (!trace->show_arg_names && !new_show_zeros) {
4590 pr_warning("trace.show_zeros has to be set when trace.show_arg_names=no\n");
4593 trace->show_zeros = new_show_zeros;
4594 } else if (!strcmp(var, "trace.show_prefix")) {
4595 trace->show_string_prefix = perf_config_bool(var, value);
4596 } else if (!strcmp(var, "trace.no_inherit")) {
4597 trace->opts.no_inherit = perf_config_bool(var, value);
4598 } else if (!strcmp(var, "trace.args_alignment")) {
4599 int args_alignment = 0;
4600 if (perf_config_int(&args_alignment, var, value) == 0)
4601 trace->args_alignment = args_alignment;
4602 } else if (!strcmp(var, "trace.tracepoint_beautifiers")) {
4603 if (strcasecmp(value, "libtraceevent") == 0)
4604 trace->libtraceevent_print = true;
4605 else if (strcasecmp(value, "libbeauty") == 0)
4606 trace->libtraceevent_print = false;
4612 int cmd_trace(int argc, const char **argv)
4614 const char *trace_usage[] = {
4615 "perf trace [<options>] [<command>]",
4616 "perf trace [<options>] -- <command> [<options>]",
4617 "perf trace record [<options>] [<command>]",
4618 "perf trace record [<options>] -- <command> [<options>]",
4621 struct trace trace = {
4627 .user_freq = UINT_MAX,
4628 .user_interval = ULLONG_MAX,
4629 .no_buffering = true,
4630 .mmap_pages = UINT_MAX,
4634 .show_tstamp = true,
4635 .show_duration = true,
4636 .show_arg_names = true,
4637 .args_alignment = 70,
4638 .trace_syscalls = false,
4639 .kernel_syscallchains = false,
4640 .max_stack = UINT_MAX,
4641 .max_events = ULONG_MAX,
4643 const char *map_dump_str = NULL;
4644 const char *output_name = NULL;
4645 const struct option trace_options[] = {
4646 OPT_CALLBACK('e', "event", &trace, "event",
4647 "event/syscall selector. use 'perf list' to list available events",
4648 trace__parse_events_option),
4649 OPT_CALLBACK(0, "filter", &trace.evlist, "filter",
4650 "event filter", parse_filter),
4651 OPT_BOOLEAN(0, "comm", &trace.show_comm,
4652 "show the thread COMM next to its id"),
4653 OPT_BOOLEAN(0, "tool_stats", &trace.show_tool_stats, "show tool stats"),
4654 OPT_CALLBACK(0, "expr", &trace, "expr", "list of syscalls/events to trace",
4655 trace__parse_events_option),
4656 OPT_STRING('o', "output", &output_name, "file", "output file name"),
4657 OPT_STRING('i', "input", &input_name, "file", "Analyze events in file"),
4658 OPT_STRING('p', "pid", &trace.opts.target.pid, "pid",
4659 "trace events on existing process id"),
4660 OPT_STRING('t', "tid", &trace.opts.target.tid, "tid",
4661 "trace events on existing thread id"),
4662 OPT_CALLBACK(0, "filter-pids", &trace, "CSV list of pids",
4663 "pids to filter (by the kernel)", trace__set_filter_pids_from_option),
4664 OPT_BOOLEAN('a', "all-cpus", &trace.opts.target.system_wide,
4665 "system-wide collection from all CPUs"),
4666 OPT_STRING('C', "cpu", &trace.opts.target.cpu_list, "cpu",
4667 "list of cpus to monitor"),
4668 OPT_BOOLEAN(0, "no-inherit", &trace.opts.no_inherit,
4669 "child tasks do not inherit counters"),
4670 OPT_CALLBACK('m', "mmap-pages", &trace.opts.mmap_pages, "pages",
4671 "number of mmap data pages",
4672 perf_evlist__parse_mmap_pages),
4673 OPT_STRING('u', "uid", &trace.opts.target.uid_str, "user",
4675 OPT_CALLBACK(0, "duration", &trace, "float",
4676 "show only events with duration > N.M ms",
4677 trace__set_duration),
4678 #ifdef HAVE_LIBBPF_SUPPORT
4679 OPT_STRING(0, "map-dump", &map_dump_str, "BPF map", "BPF map to periodically dump"),
4681 OPT_BOOLEAN(0, "sched", &trace.sched, "show blocking scheduler events"),
4682 OPT_INCR('v', "verbose", &verbose, "be more verbose"),
4683 OPT_BOOLEAN('T', "time", &trace.full_time,
4684 "Show full timestamp, not time relative to first start"),
4685 OPT_BOOLEAN(0, "failure", &trace.failure_only,
4686 "Show only syscalls that failed"),
4687 OPT_BOOLEAN('s', "summary", &trace.summary_only,
4688 "Show only syscall summary with statistics"),
4689 OPT_BOOLEAN('S', "with-summary", &trace.summary,
4690 "Show all syscalls and summary with statistics"),
4691 OPT_BOOLEAN(0, "errno-summary", &trace.errno_summary,
4692 "Show errno stats per syscall, use with -s or -S"),
4693 OPT_CALLBACK_DEFAULT('F', "pf", &trace.trace_pgfaults, "all|maj|min",
4694 "Trace pagefaults", parse_pagefaults, "maj"),
4695 OPT_BOOLEAN(0, "syscalls", &trace.trace_syscalls, "Trace syscalls"),
4696 OPT_BOOLEAN('f', "force", &trace.force, "don't complain, do it"),
4697 OPT_CALLBACK(0, "call-graph", &trace.opts,
4698 "record_mode[,record_size]", record_callchain_help,
4699 &record_parse_callchain_opt),
4700 OPT_BOOLEAN(0, "libtraceevent_print", &trace.libtraceevent_print,
4701 "Use libtraceevent to print the tracepoint arguments."),
4702 OPT_BOOLEAN(0, "kernel-syscall-graph", &trace.kernel_syscallchains,
4703 "Show the kernel callchains on the syscall exit path"),
4704 OPT_ULONG(0, "max-events", &trace.max_events,
4705 "Set the maximum number of events to print, exit after that is reached. "),
4706 OPT_UINTEGER(0, "min-stack", &trace.min_stack,
4707 "Set the minimum stack depth when parsing the callchain, "
4708 "anything below the specified depth will be ignored."),
4709 OPT_UINTEGER(0, "max-stack", &trace.max_stack,
4710 "Set the maximum stack depth when parsing the callchain, "
4711 "anything beyond the specified depth will be ignored. "
4712 "Default: kernel.perf_event_max_stack or " __stringify(PERF_MAX_STACK_DEPTH)),
4713 OPT_BOOLEAN(0, "sort-events", &trace.sort_events,
4714 "Sort batch of events before processing, use if getting out of order events"),
4715 OPT_BOOLEAN(0, "print-sample", &trace.print_sample,
4716 "print the PERF_RECORD_SAMPLE PERF_SAMPLE_ info, for debugging"),
4717 OPT_UINTEGER(0, "proc-map-timeout", &proc_map_timeout,
4718 "per thread proc mmap processing timeout in ms"),
4719 OPT_CALLBACK('G', "cgroup", &trace, "name", "monitor event in cgroup name only",
4720 trace__parse_cgroups),
4721 OPT_UINTEGER('D', "delay", &trace.opts.initial_delay,
4722 "ms to wait before starting measurement after program "
4724 OPTS_EVSWITCH(&trace.evswitch),
4727 bool __maybe_unused max_stack_user_set = true;
4728 bool mmap_pages_user_set = true;
4729 struct evsel *evsel;
4730 const char * const trace_subcommands[] = { "record", NULL };
4734 signal(SIGSEGV, sighandler_dump_stack);
4735 signal(SIGFPE, sighandler_dump_stack);
4737 trace.evlist = evlist__new();
4738 trace.sctbl = syscalltbl__new();
4740 if (trace.evlist == NULL || trace.sctbl == NULL) {
4741 pr_err("Not enough memory to run!\n");
4747 * Parsing .perfconfig may entail creating a BPF event, that may need
4748 * to create BPF maps, so bump RLIM_MEMLOCK as the default 64K setting
4749 * is too small. This affects just this process, not touching the
4750 * global setting. If it fails we'll get something in 'perf trace -v'
4751 * to help diagnose the problem.
4753 rlimit__bump_memlock();
4755 err = perf_config(trace__config, &trace);
4759 argc = parse_options_subcommand(argc, argv, trace_options, trace_subcommands,
4760 trace_usage, PARSE_OPT_STOP_AT_NON_OPTION);
4763 * Here we already passed thru trace__parse_events_option() and it has
4764 * already figured out if -e syscall_name, if not but if --event
4765 * foo:bar was used, the user is interested _just_ in those, say,
4766 * tracepoint events, not in the strace-like syscall-name-based mode.
4768 * This is important because we need to check if strace-like mode is
4769 * needed to decided if we should filter out the eBPF
4770 * __augmented_syscalls__ code, if it is in the mix, say, via
4771 * .perfconfig trace.add_events, and filter those out.
4773 if (!trace.trace_syscalls && !trace.trace_pgfaults &&
4774 trace.evlist->core.nr_entries == 0 /* Was --events used? */) {
4775 trace.trace_syscalls = true;
4778 * Now that we have --verbose figured out, lets see if we need to parse
4779 * events from .perfconfig, so that if those events fail parsing, say some
4780 * BPF program fails, then we'll be able to use --verbose to see what went
4781 * wrong in more detail.
4783 if (trace.perfconfig_events != NULL) {
4784 struct parse_events_error parse_err = { .idx = 0, };
4786 err = parse_events(trace.evlist, trace.perfconfig_events, &parse_err);
4788 parse_events_print_error(&parse_err, trace.perfconfig_events);
4793 if ((nr_cgroups || trace.cgroup) && !trace.opts.target.system_wide) {
4794 usage_with_options_msg(trace_usage, trace_options,
4795 "cgroup monitoring only available in system-wide mode");
4798 evsel = bpf__setup_output_event(trace.evlist, "__augmented_syscalls__");
4799 if (IS_ERR(evsel)) {
4800 bpf__strerror_setup_output_event(trace.evlist, PTR_ERR(evsel), bf, sizeof(bf));
4801 pr_err("ERROR: Setup trace syscalls enter failed: %s\n", bf);
4806 trace.syscalls.events.augmented = evsel;
4808 evsel = perf_evlist__find_tracepoint_by_name(trace.evlist, "raw_syscalls:sys_enter");
4809 if (evsel == NULL) {
4810 pr_err("ERROR: raw_syscalls:sys_enter not found in the augmented BPF object\n");
4814 if (evsel->bpf_obj == NULL) {
4815 pr_err("ERROR: raw_syscalls:sys_enter not associated to a BPF object\n");
4819 trace.bpf_obj = evsel->bpf_obj;
4822 * If we have _just_ the augmenter event but don't have a
4823 * explicit --syscalls, then assume we want all strace-like
4826 if (!trace.trace_syscalls && trace__only_augmented_syscalls_evsels(&trace))
4827 trace.trace_syscalls = true;
4829 * So, if we have a syscall augmenter, but trace_syscalls, aka
4830 * strace-like syscall tracing is not set, then we need to trow
4831 * away the augmenter, i.e. all the events that were created
4832 * from that BPF object file.
4834 * This is more to fix the current .perfconfig trace.add_events
4835 * style of setting up the strace-like eBPF based syscall point
4836 * payload augmenter.
4838 * All this complexity will be avoided by adding an alternative
4839 * to trace.add_events in the form of
4840 * trace.bpf_augmented_syscalls, that will be only parsed if we
4843 * .perfconfig trace.add_events is still useful if we want, for
4844 * instance, have msr_write.msr in some .perfconfig profile based
4845 * 'perf trace --config determinism.profile' mode, where for some
4846 * particular goal/workload type we want a set of events and
4847 * output mode (with timings, etc) instead of having to add
4848 * all via the command line.
4850 * Also --config to specify an alternate .perfconfig file needs
4851 * to be implemented.
4853 if (!trace.trace_syscalls) {
4854 trace__delete_augmented_syscalls(&trace);
4856 trace__set_bpf_map_filtered_pids(&trace);
4857 trace__set_bpf_map_syscalls(&trace);
4858 trace.syscalls.unaugmented_prog = trace__find_bpf_program_by_title(&trace, "!raw_syscalls:unaugmented");
4862 err = bpf__setup_stdout(trace.evlist);
4864 bpf__strerror_setup_stdout(trace.evlist, err, bf, sizeof(bf));
4865 pr_err("ERROR: Setup BPF stdout failed: %s\n", bf);
4872 trace.dump.map = trace__find_bpf_map_by_name(&trace, map_dump_str);
4873 if (trace.dump.map == NULL) {
4874 pr_err("ERROR: BPF map \"%s\" not found\n", map_dump_str);
4879 if (trace.trace_pgfaults) {
4880 trace.opts.sample_address = true;
4881 trace.opts.sample_time = true;
4884 if (trace.opts.mmap_pages == UINT_MAX)
4885 mmap_pages_user_set = false;
4887 if (trace.max_stack == UINT_MAX) {
4888 trace.max_stack = input_name ? PERF_MAX_STACK_DEPTH : sysctl__max_stack();
4889 max_stack_user_set = false;
4892 #ifdef HAVE_DWARF_UNWIND_SUPPORT
4893 if ((trace.min_stack || max_stack_user_set) && !callchain_param.enabled) {
4894 record_opts__parse_callchain(&trace.opts, &callchain_param, "dwarf", false);
4898 if (callchain_param.enabled) {
4899 if (!mmap_pages_user_set && geteuid() == 0)
4900 trace.opts.mmap_pages = perf_event_mlock_kb_in_pages() * 4;
4902 symbol_conf.use_callchain = true;
4905 if (trace.evlist->core.nr_entries > 0) {
4906 evlist__set_default_evsel_handler(trace.evlist, trace__event_handler);
4907 if (evlist__set_syscall_tp_fields(trace.evlist)) {
4908 perror("failed to set syscalls:* tracepoint fields");
4913 if (trace.sort_events) {
4914 ordered_events__init(&trace.oe.data, ordered_events__deliver_event, &trace);
4915 ordered_events__set_copy_on_queue(&trace.oe.data, true);
4919 * If we are augmenting syscalls, then combine what we put in the
4920 * __augmented_syscalls__ BPF map with what is in the
4921 * syscalls:sys_exit_FOO tracepoints, i.e. just like we do without BPF,
4922 * combining raw_syscalls:sys_enter with raw_syscalls:sys_exit.
4924 * We'll switch to look at two BPF maps, one for sys_enter and the
4925 * other for sys_exit when we start augmenting the sys_exit paths with
4926 * buffers that are being copied from kernel to userspace, think 'read'
4929 if (trace.syscalls.events.augmented) {
4930 evlist__for_each_entry(trace.evlist, evsel) {
4931 bool raw_syscalls_sys_exit = strcmp(perf_evsel__name(evsel), "raw_syscalls:sys_exit") == 0;
4933 if (raw_syscalls_sys_exit) {
4934 trace.raw_augmented_syscalls = true;
4935 goto init_augmented_syscall_tp;
4938 if (trace.syscalls.events.augmented->priv == NULL &&
4939 strstr(perf_evsel__name(evsel), "syscalls:sys_enter")) {
4940 struct evsel *augmented = trace.syscalls.events.augmented;
4941 if (perf_evsel__init_augmented_syscall_tp(augmented, evsel) ||
4942 perf_evsel__init_augmented_syscall_tp_args(augmented))
4945 * Augmented is __augmented_syscalls__ BPF_OUTPUT event
4946 * Above we made sure we can get from the payload the tp fields
4947 * that we get from syscalls:sys_enter tracefs format file.
4949 augmented->handler = trace__sys_enter;
4951 * Now we do the same for the *syscalls:sys_enter event so that
4952 * if we handle it directly, i.e. if the BPF prog returns 0 so
4953 * as not to filter it, then we'll handle it just like we would
4954 * for the BPF_OUTPUT one:
4956 if (perf_evsel__init_augmented_syscall_tp(evsel, evsel) ||
4957 perf_evsel__init_augmented_syscall_tp_args(evsel))
4959 evsel->handler = trace__sys_enter;
4962 if (strstarts(perf_evsel__name(evsel), "syscalls:sys_exit_")) {
4963 struct syscall_tp *sc;
4964 init_augmented_syscall_tp:
4965 if (perf_evsel__init_augmented_syscall_tp(evsel, evsel))
4967 sc = __evsel__syscall_tp(evsel);
4969 * For now with BPF raw_augmented we hook into
4970 * raw_syscalls:sys_enter and there we get all
4971 * 6 syscall args plus the tracepoint common
4972 * fields and the syscall_nr (another long).
4973 * So we check if that is the case and if so
4974 * don't look after the sc->args_size but
4975 * always after the full raw_syscalls:sys_enter
4976 * payload, which is fixed.
4978 * We'll revisit this later to pass
4979 * s->args_size to the BPF augmenter (now
4980 * tools/perf/examples/bpf/augmented_raw_syscalls.c,
4981 * so that it copies only what we need for each
4982 * syscall, like what happens when we use
4983 * syscalls:sys_enter_NAME, so that we reduce
4984 * the kernel/userspace traffic to just what is
4985 * needed for each syscall.
4987 if (trace.raw_augmented_syscalls)
4988 trace.raw_augmented_syscalls_args_size = (6 + 1) * sizeof(long) + sc->id.offset;
4989 perf_evsel__init_augmented_syscall_tp_ret(evsel);
4990 evsel->handler = trace__sys_exit;
4995 if ((argc >= 1) && (strcmp(argv[0], "record") == 0))
4996 return trace__record(&trace, argc-1, &argv[1]);
4998 /* Using just --errno-summary will trigger --summary */
4999 if (trace.errno_summary && !trace.summary && !trace.summary_only)
5000 trace.summary_only = true;
5002 /* summary_only implies summary option, but don't overwrite summary if set */
5003 if (trace.summary_only)
5004 trace.summary = trace.summary_only;
5006 if (output_name != NULL) {
5007 err = trace__open_output(&trace, output_name);
5009 perror("failed to create output file");
5014 err = evswitch__init(&trace.evswitch, trace.evlist, stderr);
5018 err = target__validate(&trace.opts.target);
5020 target__strerror(&trace.opts.target, err, bf, sizeof(bf));
5021 fprintf(trace.output, "%s", bf);
5025 err = target__parse_uid(&trace.opts.target);
5027 target__strerror(&trace.opts.target, err, bf, sizeof(bf));
5028 fprintf(trace.output, "%s", bf);
5032 if (!argc && target__none(&trace.opts.target))
5033 trace.opts.target.system_wide = true;
5036 err = trace__replay(&trace);
5038 err = trace__run(&trace, argc, argv);
5041 if (output_name != NULL)
5042 fclose(trace.output);
5044 zfree(&trace.perfconfig_events);