1 // SPDX-License-Identifier: GPL-2.0-only
5 * Builtin 'trace' command:
7 * Display a continuously updated trace of any workload, CPU, specific PID,
8 * system wide, etc. Default format is loosely strace like, but any other
9 * event may be specified using --event.
11 * Copyright (C) 2012, 2013, 2014, 2015 Red Hat Inc, Arnaldo Carvalho de Melo <acme@redhat.com>
13 * Initially based on the 'trace' prototype by Thomas Gleixner:
15 * http://lwn.net/Articles/415728/ ("Announcing a new utility: 'trace'")
18 #include <traceevent/event-parse.h>
19 #include <api/fs/tracing_path.h>
21 #include "util/bpf_map.h"
23 #include "util/cgroup.h"
24 #include "util/color.h"
25 #include "util/config.h"
26 #include "util/debug.h"
28 #include "util/event.h"
29 #include "util/evlist.h"
30 #include <subcmd/exec-cmd.h>
31 #include "util/machine.h"
33 #include "util/symbol.h"
34 #include "util/path.h"
35 #include "util/session.h"
36 #include "util/thread.h"
37 #include <subcmd/parse-options.h>
38 #include "util/strlist.h"
39 #include "util/intlist.h"
40 #include "util/thread_map.h"
41 #include "util/stat.h"
42 #include "trace/beauty/beauty.h"
43 #include "trace-event.h"
44 #include "util/parse-events.h"
45 #include "util/bpf-loader.h"
46 #include "callchain.h"
47 #include "print_binary.h"
49 #include "syscalltbl.h"
50 #include "rb_resort.h"
58 #include <linux/err.h>
59 #include <linux/filter.h>
60 #include <linux/kernel.h>
61 #include <linux/random.h>
62 #include <linux/stringify.h>
63 #include <linux/time64.h>
65 #include <sys/sysmacros.h>
67 #include "sane_ctype.h"
70 # define O_CLOEXEC 02000000
73 #ifndef F_LINUX_SPECIFIC_BASE
74 # define F_LINUX_SPECIFIC_BASE 1024
78 struct perf_tool tool;
79 struct syscalltbl *sctbl;
82 struct syscall *table;
85 struct perf_evsel *sys_enter,
93 struct record_opts opts;
94 struct perf_evlist *evlist;
96 struct thread *current;
97 struct cgroup *cgroup;
100 unsigned long nr_events;
101 unsigned long nr_events_printed;
102 unsigned long max_events;
103 struct strlist *ev_qualifier;
113 double duration_filter;
119 unsigned int max_stack;
120 unsigned int min_stack;
121 int raw_augmented_syscalls_args_size;
122 bool raw_augmented_syscalls;
124 bool not_ev_qualifier;
128 bool multiple_threads;
134 bool show_tool_stats;
136 bool kernel_syscallchains;
142 bool show_string_prefix;
147 struct ordered_events data;
155 u64 (*integer)(struct tp_field *field, struct perf_sample *sample);
156 void *(*pointer)(struct tp_field *field, struct perf_sample *sample);
160 #define TP_UINT_FIELD(bits) \
161 static u64 tp_field__u##bits(struct tp_field *field, struct perf_sample *sample) \
164 memcpy(&value, sample->raw_data + field->offset, sizeof(value)); \
173 #define TP_UINT_FIELD__SWAPPED(bits) \
174 static u64 tp_field__swapped_u##bits(struct tp_field *field, struct perf_sample *sample) \
177 memcpy(&value, sample->raw_data + field->offset, sizeof(value)); \
178 return bswap_##bits(value);\
181 TP_UINT_FIELD__SWAPPED(16);
182 TP_UINT_FIELD__SWAPPED(32);
183 TP_UINT_FIELD__SWAPPED(64);
185 static int __tp_field__init_uint(struct tp_field *field, int size, int offset, bool needs_swap)
187 field->offset = offset;
191 field->integer = tp_field__u8;
194 field->integer = needs_swap ? tp_field__swapped_u16 : tp_field__u16;
197 field->integer = needs_swap ? tp_field__swapped_u32 : tp_field__u32;
200 field->integer = needs_swap ? tp_field__swapped_u64 : tp_field__u64;
209 static int tp_field__init_uint(struct tp_field *field, struct tep_format_field *format_field, bool needs_swap)
211 return __tp_field__init_uint(field, format_field->size, format_field->offset, needs_swap);
214 static void *tp_field__ptr(struct tp_field *field, struct perf_sample *sample)
216 return sample->raw_data + field->offset;
219 static int __tp_field__init_ptr(struct tp_field *field, int offset)
221 field->offset = offset;
222 field->pointer = tp_field__ptr;
226 static int tp_field__init_ptr(struct tp_field *field, struct tep_format_field *format_field)
228 return __tp_field__init_ptr(field, format_field->offset);
234 struct tp_field args, ret;
238 static int perf_evsel__init_tp_uint_field(struct perf_evsel *evsel,
239 struct tp_field *field,
242 struct tep_format_field *format_field = perf_evsel__field(evsel, name);
244 if (format_field == NULL)
247 return tp_field__init_uint(field, format_field, evsel->needs_swap);
250 #define perf_evsel__init_sc_tp_uint_field(evsel, name) \
251 ({ struct syscall_tp *sc = evsel->priv;\
252 perf_evsel__init_tp_uint_field(evsel, &sc->name, #name); })
254 static int perf_evsel__init_tp_ptr_field(struct perf_evsel *evsel,
255 struct tp_field *field,
258 struct tep_format_field *format_field = perf_evsel__field(evsel, name);
260 if (format_field == NULL)
263 return tp_field__init_ptr(field, format_field);
266 #define perf_evsel__init_sc_tp_ptr_field(evsel, name) \
267 ({ struct syscall_tp *sc = evsel->priv;\
268 perf_evsel__init_tp_ptr_field(evsel, &sc->name, #name); })
270 static void perf_evsel__delete_priv(struct perf_evsel *evsel)
273 perf_evsel__delete(evsel);
276 static int perf_evsel__init_syscall_tp(struct perf_evsel *evsel)
278 struct syscall_tp *sc = evsel->priv = malloc(sizeof(struct syscall_tp));
280 if (evsel->priv != NULL) {
281 if (perf_evsel__init_tp_uint_field(evsel, &sc->id, "__syscall_nr") &&
282 perf_evsel__init_tp_uint_field(evsel, &sc->id, "nr"))
293 static int perf_evsel__init_augmented_syscall_tp(struct perf_evsel *evsel, struct perf_evsel *tp)
295 struct syscall_tp *sc = evsel->priv = malloc(sizeof(struct syscall_tp));
297 if (evsel->priv != NULL) {
298 struct tep_format_field *syscall_id = perf_evsel__field(tp, "id");
299 if (syscall_id == NULL)
300 syscall_id = perf_evsel__field(tp, "__syscall_nr");
301 if (syscall_id == NULL)
303 if (__tp_field__init_uint(&sc->id, syscall_id->size, syscall_id->offset, evsel->needs_swap))
315 static int perf_evsel__init_augmented_syscall_tp_args(struct perf_evsel *evsel)
317 struct syscall_tp *sc = evsel->priv;
319 return __tp_field__init_ptr(&sc->args, sc->id.offset + sizeof(u64));
322 static int perf_evsel__init_augmented_syscall_tp_ret(struct perf_evsel *evsel)
324 struct syscall_tp *sc = evsel->priv;
326 return __tp_field__init_uint(&sc->ret, sizeof(u64), sc->id.offset + sizeof(u64), evsel->needs_swap);
329 static int perf_evsel__init_raw_syscall_tp(struct perf_evsel *evsel, void *handler)
331 evsel->priv = malloc(sizeof(struct syscall_tp));
332 if (evsel->priv != NULL) {
333 if (perf_evsel__init_sc_tp_uint_field(evsel, id))
336 evsel->handler = handler;
347 static struct perf_evsel *perf_evsel__raw_syscall_newtp(const char *direction, void *handler)
349 struct perf_evsel *evsel = perf_evsel__newtp("raw_syscalls", direction);
351 /* older kernel (e.g., RHEL6) use syscalls:{enter,exit} */
353 evsel = perf_evsel__newtp("syscalls", direction);
358 if (perf_evsel__init_raw_syscall_tp(evsel, handler))
364 perf_evsel__delete_priv(evsel);
368 #define perf_evsel__sc_tp_uint(evsel, name, sample) \
369 ({ struct syscall_tp *fields = evsel->priv; \
370 fields->name.integer(&fields->name, sample); })
372 #define perf_evsel__sc_tp_ptr(evsel, name, sample) \
373 ({ struct syscall_tp *fields = evsel->priv; \
374 fields->name.pointer(&fields->name, sample); })
376 size_t strarray__scnprintf(struct strarray *sa, char *bf, size_t size, const char *intfmt, bool show_prefix, int val)
378 int idx = val - sa->offset;
380 if (idx < 0 || idx >= sa->nr_entries || sa->entries[idx] == NULL) {
381 size_t printed = scnprintf(bf, size, intfmt, val);
383 printed += scnprintf(bf + printed, size - printed, " /* %s??? */", sa->prefix);
387 return scnprintf(bf, size, "%s%s", show_prefix ? sa->prefix : "", sa->entries[idx]);
390 static size_t __syscall_arg__scnprintf_strarray(char *bf, size_t size,
392 struct syscall_arg *arg)
394 return strarray__scnprintf(arg->parm, bf, size, intfmt, arg->show_string_prefix, arg->val);
397 static size_t syscall_arg__scnprintf_strarray(char *bf, size_t size,
398 struct syscall_arg *arg)
400 return __syscall_arg__scnprintf_strarray(bf, size, "%d", arg);
403 #define SCA_STRARRAY syscall_arg__scnprintf_strarray
405 size_t syscall_arg__scnprintf_strarray_flags(char *bf, size_t size, struct syscall_arg *arg)
407 return strarray__scnprintf_flags(arg->parm, bf, size, arg->show_string_prefix, arg->val);
410 size_t strarrays__scnprintf(struct strarrays *sas, char *bf, size_t size, const char *intfmt, bool show_prefix, int val)
415 for (i = 0; i < sas->nr_entries; ++i) {
416 struct strarray *sa = sas->entries[i];
417 int idx = val - sa->offset;
419 if (idx >= 0 && idx < sa->nr_entries) {
420 if (sa->entries[idx] == NULL)
422 return scnprintf(bf, size, "%s%s", show_prefix ? sa->prefix : "", sa->entries[idx]);
426 printed = scnprintf(bf, size, intfmt, val);
428 printed += scnprintf(bf + printed, size - printed, " /* %s??? */", sas->entries[0]->prefix);
432 size_t syscall_arg__scnprintf_strarrays(char *bf, size_t size,
433 struct syscall_arg *arg)
435 return strarrays__scnprintf(arg->parm, bf, size, "%d", arg->show_string_prefix, arg->val);
439 #define AT_FDCWD -100
442 static size_t syscall_arg__scnprintf_fd_at(char *bf, size_t size,
443 struct syscall_arg *arg)
446 const char *prefix = "AT_FD";
449 return scnprintf(bf, size, "%s%s", arg->show_string_prefix ? prefix : "", "CWD");
451 return syscall_arg__scnprintf_fd(bf, size, arg);
454 #define SCA_FDAT syscall_arg__scnprintf_fd_at
456 static size_t syscall_arg__scnprintf_close_fd(char *bf, size_t size,
457 struct syscall_arg *arg);
459 #define SCA_CLOSE_FD syscall_arg__scnprintf_close_fd
461 size_t syscall_arg__scnprintf_hex(char *bf, size_t size, struct syscall_arg *arg)
463 return scnprintf(bf, size, "%#lx", arg->val);
466 size_t syscall_arg__scnprintf_ptr(char *bf, size_t size, struct syscall_arg *arg)
469 return scnprintf(bf, size, "NULL");
470 return syscall_arg__scnprintf_hex(bf, size, arg);
473 size_t syscall_arg__scnprintf_int(char *bf, size_t size, struct syscall_arg *arg)
475 return scnprintf(bf, size, "%d", arg->val);
478 size_t syscall_arg__scnprintf_long(char *bf, size_t size, struct syscall_arg *arg)
480 return scnprintf(bf, size, "%ld", arg->val);
483 static const char *bpf_cmd[] = {
484 "MAP_CREATE", "MAP_LOOKUP_ELEM", "MAP_UPDATE_ELEM", "MAP_DELETE_ELEM",
485 "MAP_GET_NEXT_KEY", "PROG_LOAD",
487 static DEFINE_STRARRAY(bpf_cmd, "BPF_");
489 static const char *fsmount_flags[] = {
492 static DEFINE_STRARRAY(fsmount_flags, "FSMOUNT_");
494 #include "trace/beauty/generated/fsconfig_arrays.c"
496 static DEFINE_STRARRAY(fsconfig_cmds, "FSCONFIG_");
498 static const char *epoll_ctl_ops[] = { "ADD", "DEL", "MOD", };
499 static DEFINE_STRARRAY_OFFSET(epoll_ctl_ops, "EPOLL_CTL_", 1);
501 static const char *itimers[] = { "REAL", "VIRTUAL", "PROF", };
502 static DEFINE_STRARRAY(itimers, "ITIMER_");
504 static const char *keyctl_options[] = {
505 "GET_KEYRING_ID", "JOIN_SESSION_KEYRING", "UPDATE", "REVOKE", "CHOWN",
506 "SETPERM", "DESCRIBE", "CLEAR", "LINK", "UNLINK", "SEARCH", "READ",
507 "INSTANTIATE", "NEGATE", "SET_REQKEY_KEYRING", "SET_TIMEOUT",
508 "ASSUME_AUTHORITY", "GET_SECURITY", "SESSION_TO_PARENT", "REJECT",
509 "INSTANTIATE_IOV", "INVALIDATE", "GET_PERSISTENT",
511 static DEFINE_STRARRAY(keyctl_options, "KEYCTL_");
513 static const char *whences[] = { "SET", "CUR", "END",
521 static DEFINE_STRARRAY(whences, "SEEK_");
523 static const char *fcntl_cmds[] = {
524 "DUPFD", "GETFD", "SETFD", "GETFL", "SETFL", "GETLK", "SETLK",
525 "SETLKW", "SETOWN", "GETOWN", "SETSIG", "GETSIG", "GETLK64",
526 "SETLK64", "SETLKW64", "SETOWN_EX", "GETOWN_EX",
529 static DEFINE_STRARRAY(fcntl_cmds, "F_");
531 static const char *fcntl_linux_specific_cmds[] = {
532 "SETLEASE", "GETLEASE", "NOTIFY", [5] = "CANCELLK", "DUPFD_CLOEXEC",
533 "SETPIPE_SZ", "GETPIPE_SZ", "ADD_SEALS", "GET_SEALS",
534 "GET_RW_HINT", "SET_RW_HINT", "GET_FILE_RW_HINT", "SET_FILE_RW_HINT",
537 static DEFINE_STRARRAY_OFFSET(fcntl_linux_specific_cmds, "F_", F_LINUX_SPECIFIC_BASE);
539 static struct strarray *fcntl_cmds_arrays[] = {
540 &strarray__fcntl_cmds,
541 &strarray__fcntl_linux_specific_cmds,
544 static DEFINE_STRARRAYS(fcntl_cmds_arrays);
546 static const char *rlimit_resources[] = {
547 "CPU", "FSIZE", "DATA", "STACK", "CORE", "RSS", "NPROC", "NOFILE",
548 "MEMLOCK", "AS", "LOCKS", "SIGPENDING", "MSGQUEUE", "NICE", "RTPRIO",
551 static DEFINE_STRARRAY(rlimit_resources, "RLIMIT_");
553 static const char *sighow[] = { "BLOCK", "UNBLOCK", "SETMASK", };
554 static DEFINE_STRARRAY(sighow, "SIG_");
556 static const char *clockid[] = {
557 "REALTIME", "MONOTONIC", "PROCESS_CPUTIME_ID", "THREAD_CPUTIME_ID",
558 "MONOTONIC_RAW", "REALTIME_COARSE", "MONOTONIC_COARSE", "BOOTTIME",
559 "REALTIME_ALARM", "BOOTTIME_ALARM", "SGI_CYCLE", "TAI"
561 static DEFINE_STRARRAY(clockid, "CLOCK_");
563 static size_t syscall_arg__scnprintf_access_mode(char *bf, size_t size,
564 struct syscall_arg *arg)
566 bool show_prefix = arg->show_string_prefix;
567 const char *suffix = "_OK";
571 if (mode == F_OK) /* 0 */
572 return scnprintf(bf, size, "F%s", show_prefix ? suffix : "");
574 if (mode & n##_OK) { \
575 printed += scnprintf(bf + printed, size - printed, "%s%s", #n, show_prefix ? suffix : ""); \
585 printed += scnprintf(bf + printed, size - printed, "|%#x", mode);
590 #define SCA_ACCMODE syscall_arg__scnprintf_access_mode
592 static size_t syscall_arg__scnprintf_filename(char *bf, size_t size,
593 struct syscall_arg *arg);
595 #define SCA_FILENAME syscall_arg__scnprintf_filename
597 static size_t syscall_arg__scnprintf_pipe_flags(char *bf, size_t size,
598 struct syscall_arg *arg)
600 bool show_prefix = arg->show_string_prefix;
601 const char *prefix = "O_";
602 int printed = 0, flags = arg->val;
605 if (flags & O_##n) { \
606 printed += scnprintf(bf + printed, size - printed, "%s%s%s", printed ? "|" : "", show_prefix ? prefix : "", #n); \
615 printed += scnprintf(bf + printed, size - printed, "%s%#x", printed ? "|" : "", flags);
620 #define SCA_PIPE_FLAGS syscall_arg__scnprintf_pipe_flags
622 #ifndef GRND_NONBLOCK
623 #define GRND_NONBLOCK 0x0001
626 #define GRND_RANDOM 0x0002
629 static size_t syscall_arg__scnprintf_getrandom_flags(char *bf, size_t size,
630 struct syscall_arg *arg)
632 bool show_prefix = arg->show_string_prefix;
633 const char *prefix = "GRND_";
634 int printed = 0, flags = arg->val;
637 if (flags & GRND_##n) { \
638 printed += scnprintf(bf + printed, size - printed, "%s%s%s", printed ? "|" : "", show_prefix ? prefix : "", #n); \
639 flags &= ~GRND_##n; \
647 printed += scnprintf(bf + printed, size - printed, "%s%#x", printed ? "|" : "", flags);
652 #define SCA_GETRANDOM_FLAGS syscall_arg__scnprintf_getrandom_flags
654 #define STRARRAY(name, array) \
655 { .scnprintf = SCA_STRARRAY, \
656 .parm = &strarray__##array, }
658 #define STRARRAY_FLAGS(name, array) \
659 { .scnprintf = SCA_STRARRAY_FLAGS, \
660 .parm = &strarray__##array, }
662 #include "trace/beauty/arch_errno_names.c"
663 #include "trace/beauty/eventfd.c"
664 #include "trace/beauty/futex_op.c"
665 #include "trace/beauty/futex_val3.c"
666 #include "trace/beauty/mmap.c"
667 #include "trace/beauty/mode_t.c"
668 #include "trace/beauty/msg_flags.c"
669 #include "trace/beauty/open_flags.c"
670 #include "trace/beauty/perf_event_open.c"
671 #include "trace/beauty/pid.c"
672 #include "trace/beauty/sched_policy.c"
673 #include "trace/beauty/seccomp.c"
674 #include "trace/beauty/signum.c"
675 #include "trace/beauty/socket_type.c"
676 #include "trace/beauty/waitid_options.c"
678 struct syscall_arg_fmt {
679 size_t (*scnprintf)(char *bf, size_t size, struct syscall_arg *arg);
680 unsigned long (*mask_val)(struct syscall_arg *arg, unsigned long val);
686 static struct syscall_fmt {
689 struct syscall_arg_fmt arg[6];
696 .arg = { [1] = { .scnprintf = SCA_ACCMODE, /* mode */ }, }, },
697 { .name = "arch_prctl",
698 .arg = { [0] = { .scnprintf = SCA_X86_ARCH_PRCTL_CODE, /* code */ },
699 [1] = { .scnprintf = SCA_PTR, /* arg2 */ }, }, },
701 .arg = { [1] = { .scnprintf = SCA_SOCKADDR, /* umyaddr */ }, }, },
703 .arg = { [0] = STRARRAY(cmd, bpf_cmd), }, },
704 { .name = "brk", .hexret = true,
705 .arg = { [0] = { .scnprintf = SCA_PTR, /* brk */ }, }, },
706 { .name = "clock_gettime",
707 .arg = { [0] = STRARRAY(clk_id, clockid), }, },
708 { .name = "clone", .errpid = true, .nr_args = 5,
709 .arg = { [0] = { .name = "flags", .scnprintf = SCA_CLONE_FLAGS, },
710 [1] = { .name = "child_stack", .scnprintf = SCA_HEX, },
711 [2] = { .name = "parent_tidptr", .scnprintf = SCA_HEX, },
712 [3] = { .name = "child_tidptr", .scnprintf = SCA_HEX, },
713 [4] = { .name = "tls", .scnprintf = SCA_HEX, }, }, },
715 .arg = { [0] = { .scnprintf = SCA_CLOSE_FD, /* fd */ }, }, },
717 .arg = { [1] = { .scnprintf = SCA_SOCKADDR, /* servaddr */ }, }, },
718 { .name = "epoll_ctl",
719 .arg = { [1] = STRARRAY(op, epoll_ctl_ops), }, },
720 { .name = "eventfd2",
721 .arg = { [1] = { .scnprintf = SCA_EFD_FLAGS, /* flags */ }, }, },
722 { .name = "fchmodat",
723 .arg = { [0] = { .scnprintf = SCA_FDAT, /* fd */ }, }, },
724 { .name = "fchownat",
725 .arg = { [0] = { .scnprintf = SCA_FDAT, /* fd */ }, }, },
727 .arg = { [1] = { .scnprintf = SCA_FCNTL_CMD, /* cmd */
728 .parm = &strarrays__fcntl_cmds_arrays,
729 .show_zero = true, },
730 [2] = { .scnprintf = SCA_FCNTL_ARG, /* arg */ }, }, },
732 .arg = { [1] = { .scnprintf = SCA_FLOCK, /* cmd */ }, }, },
733 { .name = "fsconfig",
734 .arg = { [1] = STRARRAY(cmd, fsconfig_cmds), }, },
736 .arg = { [1] = STRARRAY_FLAGS(flags, fsmount_flags),
737 [2] = { .scnprintf = SCA_FSMOUNT_ATTR_FLAGS, /* attr_flags */ }, }, },
739 .arg = { [0] = { .scnprintf = SCA_FDAT, /* dfd */ },
740 [1] = { .scnprintf = SCA_FILENAME, /* path */ },
741 [2] = { .scnprintf = SCA_FSPICK_FLAGS, /* flags */ }, }, },
742 { .name = "fstat", .alias = "newfstat", },
743 { .name = "fstatat", .alias = "newfstatat", },
745 .arg = { [1] = { .scnprintf = SCA_FUTEX_OP, /* op */ },
746 [5] = { .scnprintf = SCA_FUTEX_VAL3, /* val3 */ }, }, },
747 { .name = "futimesat",
748 .arg = { [0] = { .scnprintf = SCA_FDAT, /* fd */ }, }, },
749 { .name = "getitimer",
750 .arg = { [0] = STRARRAY(which, itimers), }, },
751 { .name = "getpid", .errpid = true, },
752 { .name = "getpgid", .errpid = true, },
753 { .name = "getppid", .errpid = true, },
754 { .name = "getrandom",
755 .arg = { [2] = { .scnprintf = SCA_GETRANDOM_FLAGS, /* flags */ }, }, },
756 { .name = "getrlimit",
757 .arg = { [0] = STRARRAY(resource, rlimit_resources), }, },
758 { .name = "gettid", .errpid = true, },
761 #if defined(__i386__) || defined(__x86_64__)
763 * FIXME: Make this available to all arches.
765 [1] = { .scnprintf = SCA_IOCTL_CMD, /* cmd */ },
766 [2] = { .scnprintf = SCA_HEX, /* arg */ }, }, },
768 [2] = { .scnprintf = SCA_HEX, /* arg */ }, }, },
770 { .name = "kcmp", .nr_args = 5,
771 .arg = { [0] = { .name = "pid1", .scnprintf = SCA_PID, },
772 [1] = { .name = "pid2", .scnprintf = SCA_PID, },
773 [2] = { .name = "type", .scnprintf = SCA_KCMP_TYPE, },
774 [3] = { .name = "idx1", .scnprintf = SCA_KCMP_IDX, },
775 [4] = { .name = "idx2", .scnprintf = SCA_KCMP_IDX, }, }, },
777 .arg = { [0] = STRARRAY(option, keyctl_options), }, },
779 .arg = { [1] = { .scnprintf = SCA_SIGNUM, /* sig */ }, }, },
781 .arg = { [0] = { .scnprintf = SCA_FDAT, /* fd */ }, }, },
783 .arg = { [2] = STRARRAY(whence, whences), }, },
784 { .name = "lstat", .alias = "newlstat", },
786 .arg = { [0] = { .scnprintf = SCA_HEX, /* start */ },
787 [2] = { .scnprintf = SCA_MADV_BHV, /* behavior */ }, }, },
789 .arg = { [0] = { .scnprintf = SCA_FDAT, /* fd */ }, }, },
791 .arg = { [0] = { .scnprintf = SCA_FDAT, /* fd */ }, }, },
792 { .name = "mmap", .hexret = true,
793 /* The standard mmap maps to old_mmap on s390x */
794 #if defined(__s390x__)
797 .arg = { [2] = { .scnprintf = SCA_MMAP_PROT, /* prot */ },
798 [3] = { .scnprintf = SCA_MMAP_FLAGS, /* flags */ },
799 [5] = { .scnprintf = SCA_HEX, /* offset */ }, }, },
801 .arg = { [0] = { .scnprintf = SCA_FILENAME, /* dev_name */ },
802 [3] = { .scnprintf = SCA_MOUNT_FLAGS, /* flags */
803 .mask_val = SCAMV_MOUNT_FLAGS, /* flags */ }, }, },
804 { .name = "move_mount",
805 .arg = { [0] = { .scnprintf = SCA_FDAT, /* from_dfd */ },
806 [1] = { .scnprintf = SCA_FILENAME, /* from_pathname */ },
807 [2] = { .scnprintf = SCA_FDAT, /* to_dfd */ },
808 [3] = { .scnprintf = SCA_FILENAME, /* to_pathname */ },
809 [4] = { .scnprintf = SCA_MOVE_MOUNT_FLAGS, /* flags */ }, }, },
810 { .name = "mprotect",
811 .arg = { [0] = { .scnprintf = SCA_HEX, /* start */ },
812 [2] = { .scnprintf = SCA_MMAP_PROT, /* prot */ }, }, },
813 { .name = "mq_unlink",
814 .arg = { [0] = { .scnprintf = SCA_FILENAME, /* u_name */ }, }, },
815 { .name = "mremap", .hexret = true,
816 .arg = { [3] = { .scnprintf = SCA_MREMAP_FLAGS, /* flags */ }, }, },
817 { .name = "name_to_handle_at",
818 .arg = { [0] = { .scnprintf = SCA_FDAT, /* dfd */ }, }, },
819 { .name = "newfstatat",
820 .arg = { [0] = { .scnprintf = SCA_FDAT, /* dfd */ }, }, },
822 .arg = { [1] = { .scnprintf = SCA_OPEN_FLAGS, /* flags */ }, }, },
823 { .name = "open_by_handle_at",
824 .arg = { [0] = { .scnprintf = SCA_FDAT, /* dfd */ },
825 [2] = { .scnprintf = SCA_OPEN_FLAGS, /* flags */ }, }, },
827 .arg = { [0] = { .scnprintf = SCA_FDAT, /* dfd */ },
828 [2] = { .scnprintf = SCA_OPEN_FLAGS, /* flags */ }, }, },
829 { .name = "perf_event_open",
830 .arg = { [2] = { .scnprintf = SCA_INT, /* cpu */ },
831 [3] = { .scnprintf = SCA_FD, /* group_fd */ },
832 [4] = { .scnprintf = SCA_PERF_FLAGS, /* flags */ }, }, },
834 .arg = { [1] = { .scnprintf = SCA_PIPE_FLAGS, /* flags */ }, }, },
835 { .name = "pkey_alloc",
836 .arg = { [1] = { .scnprintf = SCA_PKEY_ALLOC_ACCESS_RIGHTS, /* access_rights */ }, }, },
837 { .name = "pkey_free",
838 .arg = { [0] = { .scnprintf = SCA_INT, /* key */ }, }, },
839 { .name = "pkey_mprotect",
840 .arg = { [0] = { .scnprintf = SCA_HEX, /* start */ },
841 [2] = { .scnprintf = SCA_MMAP_PROT, /* prot */ },
842 [3] = { .scnprintf = SCA_INT, /* pkey */ }, }, },
843 { .name = "poll", .timeout = true, },
844 { .name = "ppoll", .timeout = true, },
846 .arg = { [0] = { .scnprintf = SCA_PRCTL_OPTION, /* option */ },
847 [1] = { .scnprintf = SCA_PRCTL_ARG2, /* arg2 */ },
848 [2] = { .scnprintf = SCA_PRCTL_ARG3, /* arg3 */ }, }, },
849 { .name = "pread", .alias = "pread64", },
850 { .name = "preadv", .alias = "pread", },
851 { .name = "prlimit64",
852 .arg = { [1] = STRARRAY(resource, rlimit_resources), }, },
853 { .name = "pwrite", .alias = "pwrite64", },
854 { .name = "readlinkat",
855 .arg = { [0] = { .scnprintf = SCA_FDAT, /* dfd */ }, }, },
856 { .name = "recvfrom",
857 .arg = { [3] = { .scnprintf = SCA_MSG_FLAGS, /* flags */ }, }, },
858 { .name = "recvmmsg",
859 .arg = { [3] = { .scnprintf = SCA_MSG_FLAGS, /* flags */ }, }, },
861 .arg = { [2] = { .scnprintf = SCA_MSG_FLAGS, /* flags */ }, }, },
862 { .name = "renameat",
863 .arg = { [0] = { .scnprintf = SCA_FDAT, /* olddirfd */ },
864 [2] = { .scnprintf = SCA_FDAT, /* newdirfd */ }, }, },
865 { .name = "renameat2",
866 .arg = { [0] = { .scnprintf = SCA_FDAT, /* olddirfd */ },
867 [2] = { .scnprintf = SCA_FDAT, /* newdirfd */ },
868 [4] = { .scnprintf = SCA_RENAMEAT2_FLAGS, /* flags */ }, }, },
869 { .name = "rt_sigaction",
870 .arg = { [0] = { .scnprintf = SCA_SIGNUM, /* sig */ }, }, },
871 { .name = "rt_sigprocmask",
872 .arg = { [0] = STRARRAY(how, sighow), }, },
873 { .name = "rt_sigqueueinfo",
874 .arg = { [1] = { .scnprintf = SCA_SIGNUM, /* sig */ }, }, },
875 { .name = "rt_tgsigqueueinfo",
876 .arg = { [2] = { .scnprintf = SCA_SIGNUM, /* sig */ }, }, },
877 { .name = "sched_setscheduler",
878 .arg = { [1] = { .scnprintf = SCA_SCHED_POLICY, /* policy */ }, }, },
880 .arg = { [0] = { .scnprintf = SCA_SECCOMP_OP, /* op */ },
881 [1] = { .scnprintf = SCA_SECCOMP_FLAGS, /* flags */ }, }, },
882 { .name = "select", .timeout = true, },
883 { .name = "sendmmsg",
884 .arg = { [3] = { .scnprintf = SCA_MSG_FLAGS, /* flags */ }, }, },
886 .arg = { [2] = { .scnprintf = SCA_MSG_FLAGS, /* flags */ }, }, },
888 .arg = { [3] = { .scnprintf = SCA_MSG_FLAGS, /* flags */ },
889 [4] = { .scnprintf = SCA_SOCKADDR, /* addr */ }, }, },
890 { .name = "set_tid_address", .errpid = true, },
891 { .name = "setitimer",
892 .arg = { [0] = STRARRAY(which, itimers), }, },
893 { .name = "setrlimit",
894 .arg = { [0] = STRARRAY(resource, rlimit_resources), }, },
896 .arg = { [0] = STRARRAY(family, socket_families),
897 [1] = { .scnprintf = SCA_SK_TYPE, /* type */ },
898 [2] = { .scnprintf = SCA_SK_PROTO, /* protocol */ }, }, },
899 { .name = "socketpair",
900 .arg = { [0] = STRARRAY(family, socket_families),
901 [1] = { .scnprintf = SCA_SK_TYPE, /* type */ },
902 [2] = { .scnprintf = SCA_SK_PROTO, /* protocol */ }, }, },
903 { .name = "stat", .alias = "newstat", },
905 .arg = { [0] = { .scnprintf = SCA_FDAT, /* fdat */ },
906 [2] = { .scnprintf = SCA_STATX_FLAGS, /* flags */ } ,
907 [3] = { .scnprintf = SCA_STATX_MASK, /* mask */ }, }, },
909 .arg = { [0] = { .scnprintf = SCA_FILENAME, /* specialfile */ }, }, },
911 .arg = { [0] = { .scnprintf = SCA_FILENAME, /* specialfile */ }, }, },
912 { .name = "symlinkat",
913 .arg = { [0] = { .scnprintf = SCA_FDAT, /* dfd */ }, }, },
914 { .name = "sync_file_range",
915 .arg = { [3] = { .scnprintf = SCA_SYNC_FILE_RANGE_FLAGS, /* flags */ }, }, },
917 .arg = { [2] = { .scnprintf = SCA_SIGNUM, /* sig */ }, }, },
919 .arg = { [1] = { .scnprintf = SCA_SIGNUM, /* sig */ }, }, },
920 { .name = "umount2", .alias = "umount",
921 .arg = { [0] = { .scnprintf = SCA_FILENAME, /* name */ }, }, },
922 { .name = "uname", .alias = "newuname", },
923 { .name = "unlinkat",
924 .arg = { [0] = { .scnprintf = SCA_FDAT, /* dfd */ }, }, },
925 { .name = "utimensat",
926 .arg = { [0] = { .scnprintf = SCA_FDAT, /* dirfd */ }, }, },
927 { .name = "wait4", .errpid = true,
928 .arg = { [2] = { .scnprintf = SCA_WAITID_OPTIONS, /* options */ }, }, },
929 { .name = "waitid", .errpid = true,
930 .arg = { [3] = { .scnprintf = SCA_WAITID_OPTIONS, /* options */ }, }, },
933 static int syscall_fmt__cmp(const void *name, const void *fmtp)
935 const struct syscall_fmt *fmt = fmtp;
936 return strcmp(name, fmt->name);
939 static struct syscall_fmt *syscall_fmt__find(const char *name)
941 const int nmemb = ARRAY_SIZE(syscall_fmts);
942 return bsearch(name, syscall_fmts, nmemb, sizeof(struct syscall_fmt), syscall_fmt__cmp);
945 static struct syscall_fmt *syscall_fmt__find_by_alias(const char *alias)
947 int i, nmemb = ARRAY_SIZE(syscall_fmts);
949 for (i = 0; i < nmemb; ++i) {
950 if (syscall_fmts[i].alias && strcmp(syscall_fmts[i].alias, alias) == 0)
951 return &syscall_fmts[i];
958 * is_exit: is this "exit" or "exit_group"?
959 * is_open: is this "open" or "openat"? To associate the fd returned in sys_exit with the pathname in sys_enter.
960 * args_size: sum of the sizes of the syscall arguments, anything after that is augmented stuff: pathname for openat, etc.
963 struct tep_event *tp_format;
968 struct tep_format_field *args;
970 struct syscall_fmt *fmt;
971 struct syscall_arg_fmt *arg_fmt;
975 * Must match what is in the BPF program:
977 * tools/perf/examples/bpf/augmented_raw_syscalls.c
979 struct bpf_map_syscall_entry {
981 u16 string_args_len[6];
985 * We need to have this 'calculated' boolean because in some cases we really
986 * don't know what is the duration of a syscall, for instance, when we start
987 * a session and some threads are waiting for a syscall to finish, say 'poll',
988 * in which case all we can do is to print "( ? ) for duration and for the
991 static size_t fprintf_duration(unsigned long t, bool calculated, FILE *fp)
993 double duration = (double)t / NSEC_PER_MSEC;
994 size_t printed = fprintf(fp, "(");
997 printed += fprintf(fp, " ");
998 else if (duration >= 1.0)
999 printed += color_fprintf(fp, PERF_COLOR_RED, "%6.3f ms", duration);
1000 else if (duration >= 0.01)
1001 printed += color_fprintf(fp, PERF_COLOR_YELLOW, "%6.3f ms", duration);
1003 printed += color_fprintf(fp, PERF_COLOR_NORMAL, "%6.3f ms", duration);
1004 return printed + fprintf(fp, "): ");
1008 * filename.ptr: The filename char pointer that will be vfs_getname'd
1009 * filename.entry_str_pos: Where to insert the string translated from
1010 * filename.ptr by the vfs_getname tracepoint/kprobe.
1011 * ret_scnprintf: syscall args may set this to a different syscall return
1012 * formatter, for instance, fcntl may return fds, file flags, etc.
1014 struct thread_trace {
1017 unsigned long nr_events;
1018 unsigned long pfmaj, pfmin;
1021 size_t (*ret_scnprintf)(char *bf, size_t size, struct syscall_arg *arg);
1024 short int entry_str_pos;
1026 unsigned int namelen;
1034 struct intlist *syscall_stats;
1037 static struct thread_trace *thread_trace__new(void)
1039 struct thread_trace *ttrace = zalloc(sizeof(struct thread_trace));
1042 ttrace->files.max = -1;
1044 ttrace->syscall_stats = intlist__new(NULL);
1049 static struct thread_trace *thread__trace(struct thread *thread, FILE *fp)
1051 struct thread_trace *ttrace;
1056 if (thread__priv(thread) == NULL)
1057 thread__set_priv(thread, thread_trace__new());
1059 if (thread__priv(thread) == NULL)
1062 ttrace = thread__priv(thread);
1063 ++ttrace->nr_events;
1067 color_fprintf(fp, PERF_COLOR_RED,
1068 "WARNING: not enough memory, dropping samples!\n");
1073 void syscall_arg__set_ret_scnprintf(struct syscall_arg *arg,
1074 size_t (*ret_scnprintf)(char *bf, size_t size, struct syscall_arg *arg))
1076 struct thread_trace *ttrace = thread__priv(arg->thread);
1078 ttrace->ret_scnprintf = ret_scnprintf;
1081 #define TRACE_PFMAJ (1 << 0)
1082 #define TRACE_PFMIN (1 << 1)
1084 static const size_t trace__entry_str_size = 2048;
1086 static struct file *thread_trace__files_entry(struct thread_trace *ttrace, int fd)
1091 if (fd > ttrace->files.max) {
1092 struct file *nfiles = realloc(ttrace->files.table, (fd + 1) * sizeof(struct file));
1097 if (ttrace->files.max != -1) {
1098 memset(nfiles + ttrace->files.max + 1, 0,
1099 (fd - ttrace->files.max) * sizeof(struct file));
1101 memset(nfiles, 0, (fd + 1) * sizeof(struct file));
1104 ttrace->files.table = nfiles;
1105 ttrace->files.max = fd;
1108 return ttrace->files.table + fd;
1111 struct file *thread__files_entry(struct thread *thread, int fd)
1113 return thread_trace__files_entry(thread__priv(thread), fd);
1116 static int trace__set_fd_pathname(struct thread *thread, int fd, const char *pathname)
1118 struct thread_trace *ttrace = thread__priv(thread);
1119 struct file *file = thread_trace__files_entry(ttrace, fd);
1123 if (stat(pathname, &st) == 0)
1124 file->dev_maj = major(st.st_rdev);
1125 file->pathname = strdup(pathname);
1133 static int thread__read_fd_path(struct thread *thread, int fd)
1135 char linkname[PATH_MAX], pathname[PATH_MAX];
1139 if (thread->pid_ == thread->tid) {
1140 scnprintf(linkname, sizeof(linkname),
1141 "/proc/%d/fd/%d", thread->pid_, fd);
1143 scnprintf(linkname, sizeof(linkname),
1144 "/proc/%d/task/%d/fd/%d", thread->pid_, thread->tid, fd);
1147 if (lstat(linkname, &st) < 0 || st.st_size + 1 > (off_t)sizeof(pathname))
1150 ret = readlink(linkname, pathname, sizeof(pathname));
1152 if (ret < 0 || ret > st.st_size)
1155 pathname[ret] = '\0';
1156 return trace__set_fd_pathname(thread, fd, pathname);
1159 static const char *thread__fd_path(struct thread *thread, int fd,
1160 struct trace *trace)
1162 struct thread_trace *ttrace = thread__priv(thread);
1170 if ((fd > ttrace->files.max || ttrace->files.table[fd].pathname == NULL)) {
1173 ++trace->stats.proc_getname;
1174 if (thread__read_fd_path(thread, fd))
1178 return ttrace->files.table[fd].pathname;
1181 size_t syscall_arg__scnprintf_fd(char *bf, size_t size, struct syscall_arg *arg)
1184 size_t printed = scnprintf(bf, size, "%d", fd);
1185 const char *path = thread__fd_path(arg->thread, fd, arg->trace);
1188 printed += scnprintf(bf + printed, size - printed, "<%s>", path);
1193 size_t pid__scnprintf_fd(struct trace *trace, pid_t pid, int fd, char *bf, size_t size)
1195 size_t printed = scnprintf(bf, size, "%d", fd);
1196 struct thread *thread = machine__find_thread(trace->host, pid, pid);
1199 const char *path = thread__fd_path(thread, fd, trace);
1202 printed += scnprintf(bf + printed, size - printed, "<%s>", path);
1204 thread__put(thread);
1210 static size_t syscall_arg__scnprintf_close_fd(char *bf, size_t size,
1211 struct syscall_arg *arg)
1214 size_t printed = syscall_arg__scnprintf_fd(bf, size, arg);
1215 struct thread_trace *ttrace = thread__priv(arg->thread);
1217 if (ttrace && fd >= 0 && fd <= ttrace->files.max)
1218 zfree(&ttrace->files.table[fd].pathname);
1223 static void thread__set_filename_pos(struct thread *thread, const char *bf,
1226 struct thread_trace *ttrace = thread__priv(thread);
1228 ttrace->filename.ptr = ptr;
1229 ttrace->filename.entry_str_pos = bf - ttrace->entry_str;
1232 static size_t syscall_arg__scnprintf_augmented_string(struct syscall_arg *arg, char *bf, size_t size)
1234 struct augmented_arg *augmented_arg = arg->augmented.args;
1235 size_t printed = scnprintf(bf, size, "\"%.*s\"", augmented_arg->size, augmented_arg->value);
1237 * So that the next arg with a payload can consume its augmented arg, i.e. for rename* syscalls
1238 * we would have two strings, each prefixed by its size.
1240 int consumed = sizeof(*augmented_arg) + augmented_arg->size;
1242 arg->augmented.args += consumed;
1243 arg->augmented.size -= consumed;
1248 static size_t syscall_arg__scnprintf_filename(char *bf, size_t size,
1249 struct syscall_arg *arg)
1251 unsigned long ptr = arg->val;
1253 if (arg->augmented.args)
1254 return syscall_arg__scnprintf_augmented_string(arg, bf, size);
1256 if (!arg->trace->vfs_getname)
1257 return scnprintf(bf, size, "%#x", ptr);
1259 thread__set_filename_pos(arg->thread, bf, ptr);
1263 static bool trace__filter_duration(struct trace *trace, double t)
1265 return t < (trace->duration_filter * NSEC_PER_MSEC);
1268 static size_t __trace__fprintf_tstamp(struct trace *trace, u64 tstamp, FILE *fp)
1270 double ts = (double)(tstamp - trace->base_time) / NSEC_PER_MSEC;
1272 return fprintf(fp, "%10.3f ", ts);
1276 * We're handling tstamp=0 as an undefined tstamp, i.e. like when we are
1277 * using ttrace->entry_time for a thread that receives a sys_exit without
1278 * first having received a sys_enter ("poll" issued before tracing session
1279 * starts, lost sys_enter exit due to ring buffer overflow).
1281 static size_t trace__fprintf_tstamp(struct trace *trace, u64 tstamp, FILE *fp)
1284 return __trace__fprintf_tstamp(trace, tstamp, fp);
1286 return fprintf(fp, " ? ");
1289 static bool done = false;
1290 static bool interrupted = false;
1292 static void sig_handler(int sig)
1295 interrupted = sig == SIGINT;
1298 static size_t trace__fprintf_comm_tid(struct trace *trace, struct thread *thread, FILE *fp)
1302 if (trace->multiple_threads) {
1303 if (trace->show_comm)
1304 printed += fprintf(fp, "%.14s/", thread__comm_str(thread));
1305 printed += fprintf(fp, "%d ", thread->tid);
1311 static size_t trace__fprintf_entry_head(struct trace *trace, struct thread *thread,
1312 u64 duration, bool duration_calculated, u64 tstamp, FILE *fp)
1316 if (trace->show_tstamp)
1317 printed = trace__fprintf_tstamp(trace, tstamp, fp);
1318 if (trace->show_duration)
1319 printed += fprintf_duration(duration, duration_calculated, fp);
1320 return printed + trace__fprintf_comm_tid(trace, thread, fp);
1323 static int trace__process_event(struct trace *trace, struct machine *machine,
1324 union perf_event *event, struct perf_sample *sample)
1328 switch (event->header.type) {
1329 case PERF_RECORD_LOST:
1330 color_fprintf(trace->output, PERF_COLOR_RED,
1331 "LOST %" PRIu64 " events!\n", event->lost.lost);
1332 ret = machine__process_lost_event(machine, event, sample);
1335 ret = machine__process_event(machine, event, sample);
1342 static int trace__tool_process(struct perf_tool *tool,
1343 union perf_event *event,
1344 struct perf_sample *sample,
1345 struct machine *machine)
1347 struct trace *trace = container_of(tool, struct trace, tool);
1348 return trace__process_event(trace, machine, event, sample);
1351 static char *trace__machine__resolve_kernel_addr(void *vmachine, unsigned long long *addrp, char **modp)
1353 struct machine *machine = vmachine;
1355 if (machine->kptr_restrict_warned)
1358 if (symbol_conf.kptr_restrict) {
1359 pr_warning("Kernel address maps (/proc/{kallsyms,modules}) are restricted.\n\n"
1360 "Check /proc/sys/kernel/kptr_restrict.\n\n"
1361 "Kernel samples will not be resolved.\n");
1362 machine->kptr_restrict_warned = true;
1366 return machine__resolve_kernel_addr(vmachine, addrp, modp);
1369 static int trace__symbols_init(struct trace *trace, struct perf_evlist *evlist)
1371 int err = symbol__init(NULL);
1376 trace->host = machine__new_host();
1377 if (trace->host == NULL)
1380 err = trace_event__register_resolver(trace->host, trace__machine__resolve_kernel_addr);
1384 err = __machine__synthesize_threads(trace->host, &trace->tool, &trace->opts.target,
1385 evlist->threads, trace__tool_process, false,
1394 static void trace__symbols__exit(struct trace *trace)
1396 machine__exit(trace->host);
1402 static int syscall__alloc_arg_fmts(struct syscall *sc, int nr_args)
1406 if (nr_args == 6 && sc->fmt && sc->fmt->nr_args != 0)
1407 nr_args = sc->fmt->nr_args;
1409 sc->arg_fmt = calloc(nr_args, sizeof(*sc->arg_fmt));
1410 if (sc->arg_fmt == NULL)
1413 for (idx = 0; idx < nr_args; ++idx) {
1415 sc->arg_fmt[idx] = sc->fmt->arg[idx];
1418 sc->nr_args = nr_args;
1422 static int syscall__set_arg_fmts(struct syscall *sc)
1424 struct tep_format_field *field, *last_field = NULL;
1427 for (field = sc->args; field; field = field->next, ++idx) {
1430 if (sc->fmt && sc->fmt->arg[idx].scnprintf)
1433 len = strlen(field->name);
1435 if (strcmp(field->type, "const char *") == 0 &&
1436 ((len >= 4 && strcmp(field->name + len - 4, "name") == 0) ||
1437 strstr(field->name, "path") != NULL))
1438 sc->arg_fmt[idx].scnprintf = SCA_FILENAME;
1439 else if ((field->flags & TEP_FIELD_IS_POINTER) || strstr(field->name, "addr"))
1440 sc->arg_fmt[idx].scnprintf = SCA_PTR;
1441 else if (strcmp(field->type, "pid_t") == 0)
1442 sc->arg_fmt[idx].scnprintf = SCA_PID;
1443 else if (strcmp(field->type, "umode_t") == 0)
1444 sc->arg_fmt[idx].scnprintf = SCA_MODE_T;
1445 else if ((strcmp(field->type, "int") == 0 ||
1446 strcmp(field->type, "unsigned int") == 0 ||
1447 strcmp(field->type, "long") == 0) &&
1448 len >= 2 && strcmp(field->name + len - 2, "fd") == 0) {
1450 * /sys/kernel/tracing/events/syscalls/sys_enter*
1451 * egrep 'field:.*fd;' .../format|sed -r 's/.*field:([a-z ]+) [a-z_]*fd.+/\1/g'|sort|uniq -c
1456 sc->arg_fmt[idx].scnprintf = SCA_FD;
1461 sc->args_size = last_field->offset + last_field->size;
1466 static int trace__read_syscall_info(struct trace *trace, int id)
1470 const char *name = syscalltbl__name(trace->sctbl, id);
1475 if (id > trace->syscalls.max) {
1476 struct syscall *nsyscalls = realloc(trace->syscalls.table, (id + 1) * sizeof(*sc));
1478 if (nsyscalls == NULL)
1481 if (trace->syscalls.max != -1) {
1482 memset(nsyscalls + trace->syscalls.max + 1, 0,
1483 (id - trace->syscalls.max) * sizeof(*sc));
1485 memset(nsyscalls, 0, (id + 1) * sizeof(*sc));
1488 trace->syscalls.table = nsyscalls;
1489 trace->syscalls.max = id;
1492 sc = trace->syscalls.table + id;
1495 sc->fmt = syscall_fmt__find(sc->name);
1497 snprintf(tp_name, sizeof(tp_name), "sys_enter_%s", sc->name);
1498 sc->tp_format = trace_event__tp_format("syscalls", tp_name);
1500 if (IS_ERR(sc->tp_format) && sc->fmt && sc->fmt->alias) {
1501 snprintf(tp_name, sizeof(tp_name), "sys_enter_%s", sc->fmt->alias);
1502 sc->tp_format = trace_event__tp_format("syscalls", tp_name);
1505 if (syscall__alloc_arg_fmts(sc, IS_ERR(sc->tp_format) ? 6 : sc->tp_format->format.nr_fields))
1508 if (IS_ERR(sc->tp_format))
1511 sc->args = sc->tp_format->format.fields;
1513 * We need to check and discard the first variable '__syscall_nr'
1514 * or 'nr' that mean the syscall number. It is needless here.
1515 * So drop '__syscall_nr' or 'nr' field but does not exist on older kernels.
1517 if (sc->args && (!strcmp(sc->args->name, "__syscall_nr") || !strcmp(sc->args->name, "nr"))) {
1518 sc->args = sc->args->next;
1522 sc->is_exit = !strcmp(name, "exit_group") || !strcmp(name, "exit");
1523 sc->is_open = !strcmp(name, "open") || !strcmp(name, "openat");
1525 return syscall__set_arg_fmts(sc);
1528 static int trace__validate_ev_qualifier(struct trace *trace)
1531 bool printed_invalid_prefix = false;
1532 size_t nr_allocated;
1533 struct str_node *pos;
1535 trace->ev_qualifier_ids.nr = strlist__nr_entries(trace->ev_qualifier);
1536 trace->ev_qualifier_ids.entries = malloc(trace->ev_qualifier_ids.nr *
1537 sizeof(trace->ev_qualifier_ids.entries[0]));
1539 if (trace->ev_qualifier_ids.entries == NULL) {
1540 fputs("Error:\tNot enough memory for allocating events qualifier ids\n",
1546 nr_allocated = trace->ev_qualifier_ids.nr;
1549 strlist__for_each_entry(pos, trace->ev_qualifier) {
1550 const char *sc = pos->s;
1551 int id = syscalltbl__id(trace->sctbl, sc), match_next = -1;
1554 id = syscalltbl__strglobmatch_first(trace->sctbl, sc, &match_next);
1558 if (!printed_invalid_prefix) {
1559 pr_debug("Skipping unknown syscalls: ");
1560 printed_invalid_prefix = true;
1569 trace->ev_qualifier_ids.entries[i++] = id;
1570 if (match_next == -1)
1574 id = syscalltbl__strglobmatch_next(trace->sctbl, sc, &match_next);
1577 if (nr_allocated == trace->ev_qualifier_ids.nr) {
1581 entries = realloc(trace->ev_qualifier_ids.entries,
1582 nr_allocated * sizeof(trace->ev_qualifier_ids.entries[0]));
1583 if (entries == NULL) {
1585 fputs("\nError:\t Not enough memory for parsing\n", trace->output);
1588 trace->ev_qualifier_ids.entries = entries;
1590 trace->ev_qualifier_ids.nr++;
1591 trace->ev_qualifier_ids.entries[i++] = id;
1596 if (printed_invalid_prefix)
1600 zfree(&trace->ev_qualifier_ids.entries);
1601 trace->ev_qualifier_ids.nr = 0;
1606 * args is to be interpreted as a series of longs but we need to handle
1607 * 8-byte unaligned accesses. args points to raw_data within the event
1608 * and raw_data is guaranteed to be 8-byte unaligned because it is
1609 * preceded by raw_size which is a u32. So we need to copy args to a temp
1610 * variable to read it. Most notably this avoids extended load instructions
1611 * on unaligned addresses
1613 unsigned long syscall_arg__val(struct syscall_arg *arg, u8 idx)
1616 unsigned char *p = arg->args + sizeof(unsigned long) * idx;
1618 memcpy(&val, p, sizeof(val));
1622 static size_t syscall__scnprintf_name(struct syscall *sc, char *bf, size_t size,
1623 struct syscall_arg *arg)
1625 if (sc->arg_fmt && sc->arg_fmt[arg->idx].name)
1626 return scnprintf(bf, size, "%s: ", sc->arg_fmt[arg->idx].name);
1628 return scnprintf(bf, size, "arg%d: ", arg->idx);
1632 * Check if the value is in fact zero, i.e. mask whatever needs masking, such
1633 * as mount 'flags' argument that needs ignoring some magic flag, see comment
1634 * in tools/perf/trace/beauty/mount_flags.c
1636 static unsigned long syscall__mask_val(struct syscall *sc, struct syscall_arg *arg, unsigned long val)
1638 if (sc->arg_fmt && sc->arg_fmt[arg->idx].mask_val)
1639 return sc->arg_fmt[arg->idx].mask_val(arg, val);
1644 static size_t syscall__scnprintf_val(struct syscall *sc, char *bf, size_t size,
1645 struct syscall_arg *arg, unsigned long val)
1647 if (sc->arg_fmt && sc->arg_fmt[arg->idx].scnprintf) {
1649 if (sc->arg_fmt[arg->idx].parm)
1650 arg->parm = sc->arg_fmt[arg->idx].parm;
1651 return sc->arg_fmt[arg->idx].scnprintf(bf, size, arg);
1653 return scnprintf(bf, size, "%ld", val);
1656 static size_t syscall__scnprintf_args(struct syscall *sc, char *bf, size_t size,
1657 unsigned char *args, void *augmented_args, int augmented_args_size,
1658 struct trace *trace, struct thread *thread)
1663 struct syscall_arg arg = {
1666 .size = augmented_args_size,
1667 .args = augmented_args,
1673 .show_string_prefix = trace->show_string_prefix,
1675 struct thread_trace *ttrace = thread__priv(thread);
1678 * Things like fcntl will set this in its 'cmd' formatter to pick the
1679 * right formatter for the return value (an fd? file flags?), which is
1680 * not needed for syscalls that always return a given type, say an fd.
1682 ttrace->ret_scnprintf = NULL;
1684 if (sc->args != NULL) {
1685 struct tep_format_field *field;
1687 for (field = sc->args; field;
1688 field = field->next, ++arg.idx, bit <<= 1) {
1692 val = syscall_arg__val(&arg, arg.idx);
1694 * Some syscall args need some mask, most don't and
1695 * return val untouched.
1697 val = syscall__mask_val(sc, &arg, val);
1700 * Suppress this argument if its value is zero and
1701 * and we don't have a string associated in an
1705 !trace->show_zeros &&
1707 (sc->arg_fmt[arg.idx].show_zero ||
1708 sc->arg_fmt[arg.idx].scnprintf == SCA_STRARRAY ||
1709 sc->arg_fmt[arg.idx].scnprintf == SCA_STRARRAYS) &&
1710 sc->arg_fmt[arg.idx].parm))
1713 printed += scnprintf(bf + printed, size - printed, "%s", printed ? ", " : "");
1715 if (trace->show_arg_names)
1716 printed += scnprintf(bf + printed, size - printed, "%s: ", field->name);
1718 printed += syscall__scnprintf_val(sc, bf + printed, size - printed, &arg, val);
1720 } else if (IS_ERR(sc->tp_format)) {
1722 * If we managed to read the tracepoint /format file, then we
1723 * may end up not having any args, like with gettid(), so only
1724 * print the raw args when we didn't manage to read it.
1726 while (arg.idx < sc->nr_args) {
1729 val = syscall_arg__val(&arg, arg.idx);
1731 printed += scnprintf(bf + printed, size - printed, ", ");
1732 printed += syscall__scnprintf_name(sc, bf + printed, size - printed, &arg);
1733 printed += syscall__scnprintf_val(sc, bf + printed, size - printed, &arg, val);
1743 typedef int (*tracepoint_handler)(struct trace *trace, struct perf_evsel *evsel,
1744 union perf_event *event,
1745 struct perf_sample *sample);
1747 static struct syscall *trace__syscall_info(struct trace *trace,
1748 struct perf_evsel *evsel, int id)
1754 * XXX: Noticed on x86_64, reproduced as far back as 3.0.36, haven't tried
1755 * before that, leaving at a higher verbosity level till that is
1756 * explained. Reproduced with plain ftrace with:
1758 * echo 1 > /t/events/raw_syscalls/sys_exit/enable
1759 * grep "NR -1 " /t/trace_pipe
1761 * After generating some load on the machine.
1765 fprintf(trace->output, "Invalid syscall %d id, skipping (%s, %" PRIu64 ") ...\n",
1766 id, perf_evsel__name(evsel), ++n);
1771 if ((id > trace->syscalls.max || trace->syscalls.table[id].name == NULL) &&
1772 trace__read_syscall_info(trace, id))
1775 if ((id > trace->syscalls.max || trace->syscalls.table[id].name == NULL))
1778 return &trace->syscalls.table[id];
1782 fprintf(trace->output, "Problems reading syscall %d", id);
1783 if (id <= trace->syscalls.max && trace->syscalls.table[id].name != NULL)
1784 fprintf(trace->output, "(%s)", trace->syscalls.table[id].name);
1785 fputs(" information\n", trace->output);
1790 static void thread__update_stats(struct thread_trace *ttrace,
1791 int id, struct perf_sample *sample)
1793 struct int_node *inode;
1794 struct stats *stats;
1797 inode = intlist__findnew(ttrace->syscall_stats, id);
1801 stats = inode->priv;
1802 if (stats == NULL) {
1803 stats = malloc(sizeof(struct stats));
1807 inode->priv = stats;
1810 if (ttrace->entry_time && sample->time > ttrace->entry_time)
1811 duration = sample->time - ttrace->entry_time;
1813 update_stats(stats, duration);
1816 static int trace__printf_interrupted_entry(struct trace *trace)
1818 struct thread_trace *ttrace;
1822 if (trace->failure_only || trace->current == NULL)
1825 ttrace = thread__priv(trace->current);
1827 if (!ttrace->entry_pending)
1830 printed = trace__fprintf_entry_head(trace, trace->current, 0, false, ttrace->entry_time, trace->output);
1831 printed += len = fprintf(trace->output, "%s)", ttrace->entry_str);
1833 if (len < trace->args_alignment - 4)
1834 printed += fprintf(trace->output, "%-*s", trace->args_alignment - 4 - len, " ");
1836 printed += fprintf(trace->output, " ...\n");
1838 ttrace->entry_pending = false;
1839 ++trace->nr_events_printed;
1844 static int trace__fprintf_sample(struct trace *trace, struct perf_evsel *evsel,
1845 struct perf_sample *sample, struct thread *thread)
1849 if (trace->print_sample) {
1850 double ts = (double)sample->time / NSEC_PER_MSEC;
1852 printed += fprintf(trace->output, "%22s %10.3f %s %d/%d [%d]\n",
1853 perf_evsel__name(evsel), ts,
1854 thread__comm_str(thread),
1855 sample->pid, sample->tid, sample->cpu);
1861 static void *syscall__augmented_args(struct syscall *sc, struct perf_sample *sample, int *augmented_args_size, int raw_augmented_args_size)
1863 void *augmented_args = NULL;
1865 * For now with BPF raw_augmented we hook into raw_syscalls:sys_enter
1866 * and there we get all 6 syscall args plus the tracepoint common fields
1867 * that gets calculated at the start and the syscall_nr (another long).
1868 * So we check if that is the case and if so don't look after the
1869 * sc->args_size but always after the full raw_syscalls:sys_enter payload,
1872 * We'll revisit this later to pass s->args_size to the BPF augmenter
1873 * (now tools/perf/examples/bpf/augmented_raw_syscalls.c, so that it
1874 * copies only what we need for each syscall, like what happens when we
1875 * use syscalls:sys_enter_NAME, so that we reduce the kernel/userspace
1876 * traffic to just what is needed for each syscall.
1878 int args_size = raw_augmented_args_size ?: sc->args_size;
1880 *augmented_args_size = sample->raw_size - args_size;
1881 if (*augmented_args_size > 0)
1882 augmented_args = sample->raw_data + args_size;
1884 return augmented_args;
1887 static int trace__sys_enter(struct trace *trace, struct perf_evsel *evsel,
1888 union perf_event *event __maybe_unused,
1889 struct perf_sample *sample)
1894 struct thread *thread;
1895 int id = perf_evsel__sc_tp_uint(evsel, id, sample), err = -1;
1896 int augmented_args_size = 0;
1897 void *augmented_args = NULL;
1898 struct syscall *sc = trace__syscall_info(trace, evsel, id);
1899 struct thread_trace *ttrace;
1904 thread = machine__findnew_thread(trace->host, sample->pid, sample->tid);
1905 ttrace = thread__trace(thread, trace->output);
1909 trace__fprintf_sample(trace, evsel, sample, thread);
1911 args = perf_evsel__sc_tp_ptr(evsel, args, sample);
1913 if (ttrace->entry_str == NULL) {
1914 ttrace->entry_str = malloc(trace__entry_str_size);
1915 if (!ttrace->entry_str)
1919 if (!(trace->duration_filter || trace->summary_only || trace->min_stack))
1920 trace__printf_interrupted_entry(trace);
1922 * If this is raw_syscalls.sys_enter, then it always comes with the 6 possible
1923 * arguments, even if the syscall being handled, say "openat", uses only 4 arguments
1924 * this breaks syscall__augmented_args() check for augmented args, as we calculate
1925 * syscall->args_size using each syscalls:sys_enter_NAME tracefs format file,
1926 * so when handling, say the openat syscall, we end up getting 6 args for the
1927 * raw_syscalls:sys_enter event, when we expected just 4, we end up mistakenly
1928 * thinking that the extra 2 u64 args are the augmented filename, so just check
1929 * here and avoid using augmented syscalls when the evsel is the raw_syscalls one.
1931 if (evsel != trace->syscalls.events.sys_enter)
1932 augmented_args = syscall__augmented_args(sc, sample, &augmented_args_size, trace->raw_augmented_syscalls_args_size);
1933 ttrace->entry_time = sample->time;
1934 msg = ttrace->entry_str;
1935 printed += scnprintf(msg + printed, trace__entry_str_size - printed, "%s(", sc->name);
1937 printed += syscall__scnprintf_args(sc, msg + printed, trace__entry_str_size - printed,
1938 args, augmented_args, augmented_args_size, trace, thread);
1941 if (!(trace->duration_filter || trace->summary_only || trace->failure_only || trace->min_stack)) {
1944 trace__fprintf_entry_head(trace, thread, 0, false, ttrace->entry_time, trace->output);
1945 printed = fprintf(trace->output, "%s)", ttrace->entry_str);
1946 if (trace->args_alignment > printed)
1947 alignment = trace->args_alignment - printed;
1948 fprintf(trace->output, "%*s= ?\n", alignment, " ");
1951 ttrace->entry_pending = true;
1952 /* See trace__vfs_getname & trace__sys_exit */
1953 ttrace->filename.pending_open = false;
1956 if (trace->current != thread) {
1957 thread__put(trace->current);
1958 trace->current = thread__get(thread);
1962 thread__put(thread);
1966 static int trace__fprintf_sys_enter(struct trace *trace, struct perf_evsel *evsel,
1967 struct perf_sample *sample)
1969 struct thread_trace *ttrace;
1970 struct thread *thread;
1971 int id = perf_evsel__sc_tp_uint(evsel, id, sample), err = -1;
1972 struct syscall *sc = trace__syscall_info(trace, evsel, id);
1974 void *args, *augmented_args = NULL;
1975 int augmented_args_size;
1980 thread = machine__findnew_thread(trace->host, sample->pid, sample->tid);
1981 ttrace = thread__trace(thread, trace->output);
1983 * We need to get ttrace just to make sure it is there when syscall__scnprintf_args()
1984 * and the rest of the beautifiers accessing it via struct syscall_arg touches it.
1989 args = perf_evsel__sc_tp_ptr(evsel, args, sample);
1990 augmented_args = syscall__augmented_args(sc, sample, &augmented_args_size, trace->raw_augmented_syscalls_args_size);
1991 syscall__scnprintf_args(sc, msg, sizeof(msg), args, augmented_args, augmented_args_size, trace, thread);
1992 fprintf(trace->output, "%s", msg);
1995 thread__put(thread);
1999 static int trace__resolve_callchain(struct trace *trace, struct perf_evsel *evsel,
2000 struct perf_sample *sample,
2001 struct callchain_cursor *cursor)
2003 struct addr_location al;
2004 int max_stack = evsel->attr.sample_max_stack ?
2005 evsel->attr.sample_max_stack :
2009 if (machine__resolve(trace->host, &al, sample) < 0)
2012 err = thread__resolve_callchain(al.thread, cursor, evsel, sample, NULL, NULL, max_stack);
2013 addr_location__put(&al);
2017 static int trace__fprintf_callchain(struct trace *trace, struct perf_sample *sample)
2019 /* TODO: user-configurable print_opts */
2020 const unsigned int print_opts = EVSEL__PRINT_SYM |
2022 EVSEL__PRINT_UNKNOWN_AS_ADDR;
2024 return sample__fprintf_callchain(sample, 38, print_opts, &callchain_cursor, trace->output);
2027 static const char *errno_to_name(struct perf_evsel *evsel, int err)
2029 struct perf_env *env = perf_evsel__env(evsel);
2030 const char *arch_name = perf_env__arch(env);
2032 return arch_syscalls__strerrno(arch_name, err);
2035 static int trace__sys_exit(struct trace *trace, struct perf_evsel *evsel,
2036 union perf_event *event __maybe_unused,
2037 struct perf_sample *sample)
2041 bool duration_calculated = false;
2042 struct thread *thread;
2043 int id = perf_evsel__sc_tp_uint(evsel, id, sample), err = -1, callchain_ret = 0, printed = 0;
2044 int alignment = trace->args_alignment;
2045 struct syscall *sc = trace__syscall_info(trace, evsel, id);
2046 struct thread_trace *ttrace;
2051 thread = machine__findnew_thread(trace->host, sample->pid, sample->tid);
2052 ttrace = thread__trace(thread, trace->output);
2056 trace__fprintf_sample(trace, evsel, sample, thread);
2059 thread__update_stats(ttrace, id, sample);
2061 ret = perf_evsel__sc_tp_uint(evsel, ret, sample);
2063 if (sc->is_open && ret >= 0 && ttrace->filename.pending_open) {
2064 trace__set_fd_pathname(thread, ret, ttrace->filename.name);
2065 ttrace->filename.pending_open = false;
2066 ++trace->stats.vfs_getname;
2069 if (ttrace->entry_time) {
2070 duration = sample->time - ttrace->entry_time;
2071 if (trace__filter_duration(trace, duration))
2073 duration_calculated = true;
2074 } else if (trace->duration_filter)
2077 if (sample->callchain) {
2078 callchain_ret = trace__resolve_callchain(trace, evsel, sample, &callchain_cursor);
2079 if (callchain_ret == 0) {
2080 if (callchain_cursor.nr < trace->min_stack)
2086 if (trace->summary_only || (ret >= 0 && trace->failure_only))
2089 trace__fprintf_entry_head(trace, thread, duration, duration_calculated, ttrace->entry_time, trace->output);
2091 if (ttrace->entry_pending) {
2092 printed = fprintf(trace->output, "%s", ttrace->entry_str);
2094 printed += fprintf(trace->output, " ... [");
2095 color_fprintf(trace->output, PERF_COLOR_YELLOW, "continued");
2097 printed += fprintf(trace->output, "]: %s()", sc->name);
2100 printed++; /* the closing ')' */
2102 if (alignment > printed)
2103 alignment -= printed;
2107 fprintf(trace->output, ")%*s= ", alignment, " ");
2109 if (sc->fmt == NULL) {
2113 fprintf(trace->output, "%ld", ret);
2114 } else if (ret < 0) {
2116 char bf[STRERR_BUFSIZE];
2117 const char *emsg = str_error_r(-ret, bf, sizeof(bf)),
2118 *e = errno_to_name(evsel, -ret);
2120 fprintf(trace->output, "-1 %s (%s)", e, emsg);
2122 } else if (ret == 0 && sc->fmt->timeout)
2123 fprintf(trace->output, "0 (Timeout)");
2124 else if (ttrace->ret_scnprintf) {
2126 struct syscall_arg arg = {
2131 ttrace->ret_scnprintf(bf, sizeof(bf), &arg);
2132 ttrace->ret_scnprintf = NULL;
2133 fprintf(trace->output, "%s", bf);
2134 } else if (sc->fmt->hexret)
2135 fprintf(trace->output, "%#lx", ret);
2136 else if (sc->fmt->errpid) {
2137 struct thread *child = machine__find_thread(trace->host, ret, ret);
2139 if (child != NULL) {
2140 fprintf(trace->output, "%ld", ret);
2141 if (child->comm_set)
2142 fprintf(trace->output, " (%s)", thread__comm_str(child));
2148 fputc('\n', trace->output);
2151 * We only consider an 'event' for the sake of --max-events a non-filtered
2152 * sys_enter + sys_exit and other tracepoint events.
2154 if (++trace->nr_events_printed == trace->max_events && trace->max_events != ULONG_MAX)
2157 if (callchain_ret > 0)
2158 trace__fprintf_callchain(trace, sample);
2159 else if (callchain_ret < 0)
2160 pr_err("Problem processing %s callchain, skipping...\n", perf_evsel__name(evsel));
2162 ttrace->entry_pending = false;
2165 thread__put(thread);
2169 static int trace__vfs_getname(struct trace *trace, struct perf_evsel *evsel,
2170 union perf_event *event __maybe_unused,
2171 struct perf_sample *sample)
2173 struct thread *thread = machine__findnew_thread(trace->host, sample->pid, sample->tid);
2174 struct thread_trace *ttrace;
2175 size_t filename_len, entry_str_len, to_move;
2176 ssize_t remaining_space;
2178 const char *filename = perf_evsel__rawptr(evsel, sample, "pathname");
2183 ttrace = thread__priv(thread);
2187 filename_len = strlen(filename);
2188 if (filename_len == 0)
2191 if (ttrace->filename.namelen < filename_len) {
2192 char *f = realloc(ttrace->filename.name, filename_len + 1);
2197 ttrace->filename.namelen = filename_len;
2198 ttrace->filename.name = f;
2201 strcpy(ttrace->filename.name, filename);
2202 ttrace->filename.pending_open = true;
2204 if (!ttrace->filename.ptr)
2207 entry_str_len = strlen(ttrace->entry_str);
2208 remaining_space = trace__entry_str_size - entry_str_len - 1; /* \0 */
2209 if (remaining_space <= 0)
2212 if (filename_len > (size_t)remaining_space) {
2213 filename += filename_len - remaining_space;
2214 filename_len = remaining_space;
2217 to_move = entry_str_len - ttrace->filename.entry_str_pos + 1; /* \0 */
2218 pos = ttrace->entry_str + ttrace->filename.entry_str_pos;
2219 memmove(pos + filename_len, pos, to_move);
2220 memcpy(pos, filename, filename_len);
2222 ttrace->filename.ptr = 0;
2223 ttrace->filename.entry_str_pos = 0;
2225 thread__put(thread);
2230 static int trace__sched_stat_runtime(struct trace *trace, struct perf_evsel *evsel,
2231 union perf_event *event __maybe_unused,
2232 struct perf_sample *sample)
2234 u64 runtime = perf_evsel__intval(evsel, sample, "runtime");
2235 double runtime_ms = (double)runtime / NSEC_PER_MSEC;
2236 struct thread *thread = machine__findnew_thread(trace->host,
2239 struct thread_trace *ttrace = thread__trace(thread, trace->output);
2244 ttrace->runtime_ms += runtime_ms;
2245 trace->runtime_ms += runtime_ms;
2247 thread__put(thread);
2251 fprintf(trace->output, "%s: comm=%s,pid=%u,runtime=%" PRIu64 ",vruntime=%" PRIu64 ")\n",
2253 perf_evsel__strval(evsel, sample, "comm"),
2254 (pid_t)perf_evsel__intval(evsel, sample, "pid"),
2256 perf_evsel__intval(evsel, sample, "vruntime"));
2260 static int bpf_output__printer(enum binary_printer_ops op,
2261 unsigned int val, void *extra __maybe_unused, FILE *fp)
2263 unsigned char ch = (unsigned char)val;
2266 case BINARY_PRINT_CHAR_DATA:
2267 return fprintf(fp, "%c", isprint(ch) ? ch : '.');
2268 case BINARY_PRINT_DATA_BEGIN:
2269 case BINARY_PRINT_LINE_BEGIN:
2270 case BINARY_PRINT_ADDR:
2271 case BINARY_PRINT_NUM_DATA:
2272 case BINARY_PRINT_NUM_PAD:
2273 case BINARY_PRINT_SEP:
2274 case BINARY_PRINT_CHAR_PAD:
2275 case BINARY_PRINT_LINE_END:
2276 case BINARY_PRINT_DATA_END:
2284 static void bpf_output__fprintf(struct trace *trace,
2285 struct perf_sample *sample)
2287 binary__fprintf(sample->raw_data, sample->raw_size, 8,
2288 bpf_output__printer, NULL, trace->output);
2289 ++trace->nr_events_printed;
2292 static int trace__event_handler(struct trace *trace, struct perf_evsel *evsel,
2293 union perf_event *event __maybe_unused,
2294 struct perf_sample *sample)
2296 struct thread *thread;
2297 int callchain_ret = 0;
2299 * Check if we called perf_evsel__disable(evsel) due to, for instance,
2300 * this event's max_events having been hit and this is an entry coming
2301 * from the ring buffer that we should discard, since the max events
2302 * have already been considered/printed.
2304 if (evsel->disabled)
2307 thread = machine__findnew_thread(trace->host, sample->pid, sample->tid);
2309 if (sample->callchain) {
2310 callchain_ret = trace__resolve_callchain(trace, evsel, sample, &callchain_cursor);
2311 if (callchain_ret == 0) {
2312 if (callchain_cursor.nr < trace->min_stack)
2318 trace__printf_interrupted_entry(trace);
2319 trace__fprintf_tstamp(trace, sample->time, trace->output);
2321 if (trace->trace_syscalls && trace->show_duration)
2322 fprintf(trace->output, "( ): ");
2325 trace__fprintf_comm_tid(trace, thread, trace->output);
2327 if (evsel == trace->syscalls.events.augmented) {
2328 int id = perf_evsel__sc_tp_uint(evsel, id, sample);
2329 struct syscall *sc = trace__syscall_info(trace, evsel, id);
2332 fprintf(trace->output, "%s(", sc->name);
2333 trace__fprintf_sys_enter(trace, evsel, sample);
2334 fputc(')', trace->output);
2339 * XXX: Not having the associated syscall info or not finding/adding
2340 * the thread should never happen, but if it does...
2341 * fall thru and print it as a bpf_output event.
2345 fprintf(trace->output, "%s:", evsel->name);
2347 if (perf_evsel__is_bpf_output(evsel)) {
2348 bpf_output__fprintf(trace, sample);
2349 } else if (evsel->tp_format) {
2350 if (strncmp(evsel->tp_format->name, "sys_enter_", 10) ||
2351 trace__fprintf_sys_enter(trace, evsel, sample)) {
2352 event_format__fprintf(evsel->tp_format, sample->cpu,
2353 sample->raw_data, sample->raw_size,
2355 ++trace->nr_events_printed;
2357 if (evsel->max_events != ULONG_MAX && ++evsel->nr_events_printed == evsel->max_events) {
2358 perf_evsel__disable(evsel);
2359 perf_evsel__close(evsel);
2365 fprintf(trace->output, "\n");
2367 if (callchain_ret > 0)
2368 trace__fprintf_callchain(trace, sample);
2369 else if (callchain_ret < 0)
2370 pr_err("Problem processing %s callchain, skipping...\n", perf_evsel__name(evsel));
2372 thread__put(thread);
2376 static void print_location(FILE *f, struct perf_sample *sample,
2377 struct addr_location *al,
2378 bool print_dso, bool print_sym)
2381 if ((verbose > 0 || print_dso) && al->map)
2382 fprintf(f, "%s@", al->map->dso->long_name);
2384 if ((verbose > 0 || print_sym) && al->sym)
2385 fprintf(f, "%s+0x%" PRIx64, al->sym->name,
2386 al->addr - al->sym->start);
2388 fprintf(f, "0x%" PRIx64, al->addr);
2390 fprintf(f, "0x%" PRIx64, sample->addr);
2393 static int trace__pgfault(struct trace *trace,
2394 struct perf_evsel *evsel,
2395 union perf_event *event __maybe_unused,
2396 struct perf_sample *sample)
2398 struct thread *thread;
2399 struct addr_location al;
2400 char map_type = 'd';
2401 struct thread_trace *ttrace;
2403 int callchain_ret = 0;
2405 thread = machine__findnew_thread(trace->host, sample->pid, sample->tid);
2407 if (sample->callchain) {
2408 callchain_ret = trace__resolve_callchain(trace, evsel, sample, &callchain_cursor);
2409 if (callchain_ret == 0) {
2410 if (callchain_cursor.nr < trace->min_stack)
2416 ttrace = thread__trace(thread, trace->output);
2420 if (evsel->attr.config == PERF_COUNT_SW_PAGE_FAULTS_MAJ)
2425 if (trace->summary_only)
2428 thread__find_symbol(thread, sample->cpumode, sample->ip, &al);
2430 trace__fprintf_entry_head(trace, thread, 0, true, sample->time, trace->output);
2432 fprintf(trace->output, "%sfault [",
2433 evsel->attr.config == PERF_COUNT_SW_PAGE_FAULTS_MAJ ?
2436 print_location(trace->output, sample, &al, false, true);
2438 fprintf(trace->output, "] => ");
2440 thread__find_symbol(thread, sample->cpumode, sample->addr, &al);
2443 thread__find_symbol(thread, sample->cpumode, sample->addr, &al);
2451 print_location(trace->output, sample, &al, true, false);
2453 fprintf(trace->output, " (%c%c)\n", map_type, al.level);
2455 if (callchain_ret > 0)
2456 trace__fprintf_callchain(trace, sample);
2457 else if (callchain_ret < 0)
2458 pr_err("Problem processing %s callchain, skipping...\n", perf_evsel__name(evsel));
2460 ++trace->nr_events_printed;
2464 thread__put(thread);
2468 static void trace__set_base_time(struct trace *trace,
2469 struct perf_evsel *evsel,
2470 struct perf_sample *sample)
2473 * BPF events were not setting PERF_SAMPLE_TIME, so be more robust
2474 * and don't use sample->time unconditionally, we may end up having
2475 * some other event in the future without PERF_SAMPLE_TIME for good
2476 * reason, i.e. we may not be interested in its timestamps, just in
2477 * it taking place, picking some piece of information when it
2478 * appears in our event stream (vfs_getname comes to mind).
2480 if (trace->base_time == 0 && !trace->full_time &&
2481 (evsel->attr.sample_type & PERF_SAMPLE_TIME))
2482 trace->base_time = sample->time;
2485 static int trace__process_sample(struct perf_tool *tool,
2486 union perf_event *event,
2487 struct perf_sample *sample,
2488 struct perf_evsel *evsel,
2489 struct machine *machine __maybe_unused)
2491 struct trace *trace = container_of(tool, struct trace, tool);
2492 struct thread *thread;
2495 tracepoint_handler handler = evsel->handler;
2497 thread = machine__findnew_thread(trace->host, sample->pid, sample->tid);
2498 if (thread && thread__is_filtered(thread))
2501 trace__set_base_time(trace, evsel, sample);
2505 handler(trace, evsel, event, sample);
2508 thread__put(thread);
2512 static int trace__record(struct trace *trace, int argc, const char **argv)
2514 unsigned int rec_argc, i, j;
2515 const char **rec_argv;
2516 const char * const record_args[] = {
2523 const char * const sc_args[] = { "-e", };
2524 unsigned int sc_args_nr = ARRAY_SIZE(sc_args);
2525 const char * const majpf_args[] = { "-e", "major-faults" };
2526 unsigned int majpf_args_nr = ARRAY_SIZE(majpf_args);
2527 const char * const minpf_args[] = { "-e", "minor-faults" };
2528 unsigned int minpf_args_nr = ARRAY_SIZE(minpf_args);
2530 /* +1 is for the event string below */
2531 rec_argc = ARRAY_SIZE(record_args) + sc_args_nr + 1 +
2532 majpf_args_nr + minpf_args_nr + argc;
2533 rec_argv = calloc(rec_argc + 1, sizeof(char *));
2535 if (rec_argv == NULL)
2539 for (i = 0; i < ARRAY_SIZE(record_args); i++)
2540 rec_argv[j++] = record_args[i];
2542 if (trace->trace_syscalls) {
2543 for (i = 0; i < sc_args_nr; i++)
2544 rec_argv[j++] = sc_args[i];
2546 /* event string may be different for older kernels - e.g., RHEL6 */
2547 if (is_valid_tracepoint("raw_syscalls:sys_enter"))
2548 rec_argv[j++] = "raw_syscalls:sys_enter,raw_syscalls:sys_exit";
2549 else if (is_valid_tracepoint("syscalls:sys_enter"))
2550 rec_argv[j++] = "syscalls:sys_enter,syscalls:sys_exit";
2552 pr_err("Neither raw_syscalls nor syscalls events exist.\n");
2558 if (trace->trace_pgfaults & TRACE_PFMAJ)
2559 for (i = 0; i < majpf_args_nr; i++)
2560 rec_argv[j++] = majpf_args[i];
2562 if (trace->trace_pgfaults & TRACE_PFMIN)
2563 for (i = 0; i < minpf_args_nr; i++)
2564 rec_argv[j++] = minpf_args[i];
2566 for (i = 0; i < (unsigned int)argc; i++)
2567 rec_argv[j++] = argv[i];
2569 return cmd_record(j, rec_argv);
2572 static size_t trace__fprintf_thread_summary(struct trace *trace, FILE *fp);
2574 static bool perf_evlist__add_vfs_getname(struct perf_evlist *evlist)
2577 struct perf_evsel *evsel, *tmp;
2578 struct parse_events_error err = { .idx = 0, };
2579 int ret = parse_events(evlist, "probe:vfs_getname*", &err);
2584 evlist__for_each_entry_safe(evlist, evsel, tmp) {
2585 if (!strstarts(perf_evsel__name(evsel), "probe:vfs_getname"))
2588 if (perf_evsel__field(evsel, "pathname")) {
2589 evsel->handler = trace__vfs_getname;
2594 list_del_init(&evsel->node);
2595 evsel->evlist = NULL;
2596 perf_evsel__delete(evsel);
2602 static struct perf_evsel *perf_evsel__new_pgfault(u64 config)
2604 struct perf_evsel *evsel;
2605 struct perf_event_attr attr = {
2606 .type = PERF_TYPE_SOFTWARE,
2610 attr.config = config;
2611 attr.sample_period = 1;
2613 event_attr_init(&attr);
2615 evsel = perf_evsel__new(&attr);
2617 evsel->handler = trace__pgfault;
2622 static void trace__handle_event(struct trace *trace, union perf_event *event, struct perf_sample *sample)
2624 const u32 type = event->header.type;
2625 struct perf_evsel *evsel;
2627 if (type != PERF_RECORD_SAMPLE) {
2628 trace__process_event(trace, trace->host, event, sample);
2632 evsel = perf_evlist__id2evsel(trace->evlist, sample->id);
2633 if (evsel == NULL) {
2634 fprintf(trace->output, "Unknown tp ID %" PRIu64 ", skipping...\n", sample->id);
2638 trace__set_base_time(trace, evsel, sample);
2640 if (evsel->attr.type == PERF_TYPE_TRACEPOINT &&
2641 sample->raw_data == NULL) {
2642 fprintf(trace->output, "%s sample with no payload for tid: %d, cpu %d, raw_size=%d, skipping...\n",
2643 perf_evsel__name(evsel), sample->tid,
2644 sample->cpu, sample->raw_size);
2646 tracepoint_handler handler = evsel->handler;
2647 handler(trace, evsel, event, sample);
2650 if (trace->nr_events_printed >= trace->max_events && trace->max_events != ULONG_MAX)
2654 static int trace__add_syscall_newtp(struct trace *trace)
2657 struct perf_evlist *evlist = trace->evlist;
2658 struct perf_evsel *sys_enter, *sys_exit;
2660 sys_enter = perf_evsel__raw_syscall_newtp("sys_enter", trace__sys_enter);
2661 if (sys_enter == NULL)
2664 if (perf_evsel__init_sc_tp_ptr_field(sys_enter, args))
2665 goto out_delete_sys_enter;
2667 sys_exit = perf_evsel__raw_syscall_newtp("sys_exit", trace__sys_exit);
2668 if (sys_exit == NULL)
2669 goto out_delete_sys_enter;
2671 if (perf_evsel__init_sc_tp_uint_field(sys_exit, ret))
2672 goto out_delete_sys_exit;
2674 perf_evsel__config_callchain(sys_enter, &trace->opts, &callchain_param);
2675 perf_evsel__config_callchain(sys_exit, &trace->opts, &callchain_param);
2677 perf_evlist__add(evlist, sys_enter);
2678 perf_evlist__add(evlist, sys_exit);
2680 if (callchain_param.enabled && !trace->kernel_syscallchains) {
2682 * We're interested only in the user space callchain
2683 * leading to the syscall, allow overriding that for
2684 * debugging reasons using --kernel_syscall_callchains
2686 sys_exit->attr.exclude_callchain_kernel = 1;
2689 trace->syscalls.events.sys_enter = sys_enter;
2690 trace->syscalls.events.sys_exit = sys_exit;
2696 out_delete_sys_exit:
2697 perf_evsel__delete_priv(sys_exit);
2698 out_delete_sys_enter:
2699 perf_evsel__delete_priv(sys_enter);
2703 static int trace__set_ev_qualifier_tp_filter(struct trace *trace)
2706 struct perf_evsel *sys_exit;
2707 char *filter = asprintf_expr_inout_ints("id", !trace->not_ev_qualifier,
2708 trace->ev_qualifier_ids.nr,
2709 trace->ev_qualifier_ids.entries);
2714 if (!perf_evsel__append_tp_filter(trace->syscalls.events.sys_enter,
2716 sys_exit = trace->syscalls.events.sys_exit;
2717 err = perf_evsel__append_tp_filter(sys_exit, filter);
2728 #ifdef HAVE_LIBBPF_SUPPORT
2729 static void trace__init_bpf_map_syscall_args(struct trace *trace, int id, struct bpf_map_syscall_entry *entry)
2731 struct syscall *sc = trace__syscall_info(trace, NULL, id);
2737 for (; arg < sc->nr_args; ++arg) {
2738 entry->string_args_len[arg] = 0;
2739 if (sc->arg_fmt[arg].scnprintf == SCA_FILENAME) {
2740 /* Should be set like strace -s strsize */
2741 entry->string_args_len[arg] = PATH_MAX;
2745 for (; arg < 6; ++arg)
2746 entry->string_args_len[arg] = 0;
2748 static int trace__set_ev_qualifier_bpf_filter(struct trace *trace)
2750 int fd = bpf_map__fd(trace->syscalls.map);
2751 struct bpf_map_syscall_entry value = {
2752 .enabled = !trace->not_ev_qualifier,
2757 for (i = 0; i < trace->ev_qualifier_ids.nr; ++i) {
2758 int key = trace->ev_qualifier_ids.entries[i];
2761 trace__init_bpf_map_syscall_args(trace, key, &value);
2763 err = bpf_map_update_elem(fd, &key, &value, BPF_EXIST);
2771 static int __trace__init_syscalls_bpf_map(struct trace *trace, bool enabled)
2773 int fd = bpf_map__fd(trace->syscalls.map);
2774 struct bpf_map_syscall_entry value = {
2779 for (key = 0; key < trace->sctbl->syscalls.nr_entries; ++key) {
2781 trace__init_bpf_map_syscall_args(trace, key, &value);
2783 err = bpf_map_update_elem(fd, &key, &value, BPF_ANY);
2791 static int trace__init_syscalls_bpf_map(struct trace *trace)
2793 bool enabled = true;
2795 if (trace->ev_qualifier_ids.nr)
2796 enabled = trace->not_ev_qualifier;
2798 return __trace__init_syscalls_bpf_map(trace, enabled);
2801 static int trace__set_ev_qualifier_bpf_filter(struct trace *trace __maybe_unused)
2806 static int trace__init_syscalls_bpf_map(struct trace *trace __maybe_unused)
2810 #endif // HAVE_LIBBPF_SUPPORT
2812 static int trace__set_ev_qualifier_filter(struct trace *trace)
2814 if (trace->syscalls.map)
2815 return trace__set_ev_qualifier_bpf_filter(trace);
2816 if (trace->syscalls.events.sys_enter)
2817 return trace__set_ev_qualifier_tp_filter(trace);
2821 static int bpf_map__set_filter_pids(struct bpf_map *map __maybe_unused,
2822 size_t npids __maybe_unused, pid_t *pids __maybe_unused)
2825 #ifdef HAVE_LIBBPF_SUPPORT
2827 int map_fd = bpf_map__fd(map);
2830 for (i = 0; i < npids; ++i) {
2831 err = bpf_map_update_elem(map_fd, &pids[i], &value, BPF_ANY);
2839 static int trace__set_filter_loop_pids(struct trace *trace)
2841 unsigned int nr = 1, err;
2845 struct thread *thread = machine__find_thread(trace->host, pids[0], pids[0]);
2847 while (thread && nr < ARRAY_SIZE(pids)) {
2848 struct thread *parent = machine__find_thread(trace->host, thread->ppid, thread->ppid);
2853 if (!strcmp(thread__comm_str(parent), "sshd") ||
2854 strstarts(thread__comm_str(parent), "gnome-terminal")) {
2855 pids[nr++] = parent->tid;
2861 err = perf_evlist__set_tp_filter_pids(trace->evlist, nr, pids);
2862 if (!err && trace->filter_pids.map)
2863 err = bpf_map__set_filter_pids(trace->filter_pids.map, nr, pids);
2868 static int trace__set_filter_pids(struct trace *trace)
2872 * Better not use !target__has_task() here because we need to cover the
2873 * case where no threads were specified in the command line, but a
2874 * workload was, and in that case we will fill in the thread_map when
2875 * we fork the workload in perf_evlist__prepare_workload.
2877 if (trace->filter_pids.nr > 0) {
2878 err = perf_evlist__set_tp_filter_pids(trace->evlist, trace->filter_pids.nr,
2879 trace->filter_pids.entries);
2880 if (!err && trace->filter_pids.map) {
2881 err = bpf_map__set_filter_pids(trace->filter_pids.map, trace->filter_pids.nr,
2882 trace->filter_pids.entries);
2884 } else if (thread_map__pid(trace->evlist->threads, 0) == -1) {
2885 err = trace__set_filter_loop_pids(trace);
2891 static int __trace__deliver_event(struct trace *trace, union perf_event *event)
2893 struct perf_evlist *evlist = trace->evlist;
2894 struct perf_sample sample;
2897 err = perf_evlist__parse_sample(evlist, event, &sample);
2899 fprintf(trace->output, "Can't parse sample, err = %d, skipping...\n", err);
2901 trace__handle_event(trace, event, &sample);
2906 static int __trace__flush_events(struct trace *trace)
2908 u64 first = ordered_events__first_time(&trace->oe.data);
2909 u64 flush = trace->oe.last - NSEC_PER_SEC;
2911 /* Is there some thing to flush.. */
2912 if (first && first < flush)
2913 return ordered_events__flush_time(&trace->oe.data, flush);
2918 static int trace__flush_events(struct trace *trace)
2920 return !trace->sort_events ? 0 : __trace__flush_events(trace);
2923 static int trace__deliver_event(struct trace *trace, union perf_event *event)
2927 if (!trace->sort_events)
2928 return __trace__deliver_event(trace, event);
2930 err = perf_evlist__parse_sample_timestamp(trace->evlist, event, &trace->oe.last);
2931 if (err && err != -1)
2934 err = ordered_events__queue(&trace->oe.data, event, trace->oe.last, 0);
2938 return trace__flush_events(trace);
2941 static int ordered_events__deliver_event(struct ordered_events *oe,
2942 struct ordered_event *event)
2944 struct trace *trace = container_of(oe, struct trace, oe.data);
2946 return __trace__deliver_event(trace, event->event);
2949 static int trace__run(struct trace *trace, int argc, const char **argv)
2951 struct perf_evlist *evlist = trace->evlist;
2952 struct perf_evsel *evsel, *pgfault_maj = NULL, *pgfault_min = NULL;
2954 unsigned long before;
2955 const bool forks = argc > 0;
2956 bool draining = false;
2960 if (!trace->raw_augmented_syscalls) {
2961 if (trace->trace_syscalls && trace__add_syscall_newtp(trace))
2962 goto out_error_raw_syscalls;
2964 if (trace->trace_syscalls)
2965 trace->vfs_getname = perf_evlist__add_vfs_getname(evlist);
2968 if ((trace->trace_pgfaults & TRACE_PFMAJ)) {
2969 pgfault_maj = perf_evsel__new_pgfault(PERF_COUNT_SW_PAGE_FAULTS_MAJ);
2970 if (pgfault_maj == NULL)
2972 perf_evsel__config_callchain(pgfault_maj, &trace->opts, &callchain_param);
2973 perf_evlist__add(evlist, pgfault_maj);
2976 if ((trace->trace_pgfaults & TRACE_PFMIN)) {
2977 pgfault_min = perf_evsel__new_pgfault(PERF_COUNT_SW_PAGE_FAULTS_MIN);
2978 if (pgfault_min == NULL)
2980 perf_evsel__config_callchain(pgfault_min, &trace->opts, &callchain_param);
2981 perf_evlist__add(evlist, pgfault_min);
2985 perf_evlist__add_newtp(evlist, "sched", "sched_stat_runtime",
2986 trace__sched_stat_runtime))
2987 goto out_error_sched_stat_runtime;
2990 * If a global cgroup was set, apply it to all the events without an
2991 * explicit cgroup. I.e.:
2993 * trace -G A -e sched:*switch
2995 * Will set all raw_syscalls:sys_{enter,exit}, pgfault, vfs_getname, etc
2996 * _and_ sched:sched_switch to the 'A' cgroup, while:
2998 * trace -e sched:*switch -G A
3000 * will only set the sched:sched_switch event to the 'A' cgroup, all the
3001 * other events (raw_syscalls:sys_{enter,exit}, etc are left "without"
3002 * a cgroup (on the root cgroup, sys wide, etc).
3006 * trace -G A -e sched:*switch -G B
3008 * the syscall ones go to the 'A' cgroup, the sched:sched_switch goes
3009 * to the 'B' cgroup.
3011 * evlist__set_default_cgroup() grabs a reference of the passed cgroup
3012 * only for the evsels still without a cgroup, i.e. evsel->cgroup == NULL.
3015 evlist__set_default_cgroup(trace->evlist, trace->cgroup);
3017 err = perf_evlist__create_maps(evlist, &trace->opts.target);
3019 fprintf(trace->output, "Problems parsing the target to trace, check your options!\n");
3020 goto out_delete_evlist;
3023 err = trace__symbols_init(trace, evlist);
3025 fprintf(trace->output, "Problems initializing symbol libraries!\n");
3026 goto out_delete_evlist;
3029 perf_evlist__config(evlist, &trace->opts, &callchain_param);
3031 signal(SIGCHLD, sig_handler);
3032 signal(SIGINT, sig_handler);
3035 err = perf_evlist__prepare_workload(evlist, &trace->opts.target,
3038 fprintf(trace->output, "Couldn't run the workload!\n");
3039 goto out_delete_evlist;
3043 err = perf_evlist__open(evlist);
3045 goto out_error_open;
3047 err = bpf__apply_obj_config();
3049 char errbuf[BUFSIZ];
3051 bpf__strerror_apply_obj_config(err, errbuf, sizeof(errbuf));
3052 pr_err("ERROR: Apply config to BPF failed: %s\n",
3054 goto out_error_open;
3057 err = trace__set_filter_pids(trace);
3061 if (trace->syscalls.map)
3062 trace__init_syscalls_bpf_map(trace);
3064 if (trace->ev_qualifier_ids.nr > 0) {
3065 err = trace__set_ev_qualifier_filter(trace);
3069 if (trace->syscalls.events.sys_exit) {
3070 pr_debug("event qualifier tracepoint filter: %s\n",
3071 trace->syscalls.events.sys_exit->filter);
3075 err = perf_evlist__apply_filters(evlist, &evsel);
3077 goto out_error_apply_filters;
3079 if (trace->dump.map)
3080 bpf_map__fprintf(trace->dump.map, trace->output);
3082 err = perf_evlist__mmap(evlist, trace->opts.mmap_pages);
3084 goto out_error_mmap;
3086 if (!target__none(&trace->opts.target) && !trace->opts.initial_delay)
3087 perf_evlist__enable(evlist);
3090 perf_evlist__start_workload(evlist);
3092 if (trace->opts.initial_delay) {
3093 usleep(trace->opts.initial_delay * 1000);
3094 perf_evlist__enable(evlist);
3097 trace->multiple_threads = thread_map__pid(evlist->threads, 0) == -1 ||
3098 evlist->threads->nr > 1 ||
3099 perf_evlist__first(evlist)->attr.inherit;
3102 * Now that we already used evsel->attr to ask the kernel to setup the
3103 * events, lets reuse evsel->attr.sample_max_stack as the limit in
3104 * trace__resolve_callchain(), allowing per-event max-stack settings
3105 * to override an explicitly set --max-stack global setting.
3107 evlist__for_each_entry(evlist, evsel) {
3108 if (evsel__has_callchain(evsel) &&
3109 evsel->attr.sample_max_stack == 0)
3110 evsel->attr.sample_max_stack = trace->max_stack;
3113 before = trace->nr_events;
3115 for (i = 0; i < evlist->nr_mmaps; i++) {
3116 union perf_event *event;
3117 struct perf_mmap *md;
3119 md = &evlist->mmap[i];
3120 if (perf_mmap__read_init(md) < 0)
3123 while ((event = perf_mmap__read_event(md)) != NULL) {
3126 err = trace__deliver_event(trace, event);
3130 perf_mmap__consume(md);
3135 if (done && !draining) {
3136 perf_evlist__disable(evlist);
3140 perf_mmap__read_done(md);
3143 if (trace->nr_events == before) {
3144 int timeout = done ? 100 : -1;
3146 if (!draining && perf_evlist__poll(evlist, timeout) > 0) {
3147 if (perf_evlist__filter_pollfd(evlist, POLLERR | POLLHUP | POLLNVAL) == 0)
3152 if (trace__flush_events(trace))
3160 thread__zput(trace->current);
3162 perf_evlist__disable(evlist);
3164 if (trace->sort_events)
3165 ordered_events__flush(&trace->oe.data, OE_FLUSH__FINAL);
3169 trace__fprintf_thread_summary(trace, trace->output);
3171 if (trace->show_tool_stats) {
3172 fprintf(trace->output, "Stats:\n "
3173 " vfs_getname : %" PRIu64 "\n"
3174 " proc_getname: %" PRIu64 "\n",
3175 trace->stats.vfs_getname,
3176 trace->stats.proc_getname);
3181 trace__symbols__exit(trace);
3183 perf_evlist__delete(evlist);
3184 cgroup__put(trace->cgroup);
3185 trace->evlist = NULL;
3186 trace->live = false;
3189 char errbuf[BUFSIZ];
3191 out_error_sched_stat_runtime:
3192 tracing_path__strerror_open_tp(errno, errbuf, sizeof(errbuf), "sched", "sched_stat_runtime");
3195 out_error_raw_syscalls:
3196 tracing_path__strerror_open_tp(errno, errbuf, sizeof(errbuf), "raw_syscalls", "sys_(enter|exit)");
3200 perf_evlist__strerror_mmap(evlist, errno, errbuf, sizeof(errbuf));
3204 perf_evlist__strerror_open(evlist, errno, errbuf, sizeof(errbuf));
3207 fprintf(trace->output, "%s\n", errbuf);
3208 goto out_delete_evlist;
3210 out_error_apply_filters:
3211 fprintf(trace->output,
3212 "Failed to set filter \"%s\" on event %s with %d (%s)\n",
3213 evsel->filter, perf_evsel__name(evsel), errno,
3214 str_error_r(errno, errbuf, sizeof(errbuf)));
3215 goto out_delete_evlist;
3218 fprintf(trace->output, "Not enough memory to run!\n");
3219 goto out_delete_evlist;
3222 fprintf(trace->output, "errno=%d,%s\n", errno, strerror(errno));
3223 goto out_delete_evlist;
3226 static int trace__replay(struct trace *trace)
3228 const struct perf_evsel_str_handler handlers[] = {
3229 { "probe:vfs_getname", trace__vfs_getname, },
3231 struct perf_data data = {
3233 .mode = PERF_DATA_MODE_READ,
3234 .force = trace->force,
3236 struct perf_session *session;
3237 struct perf_evsel *evsel;
3240 trace->tool.sample = trace__process_sample;
3241 trace->tool.mmap = perf_event__process_mmap;
3242 trace->tool.mmap2 = perf_event__process_mmap2;
3243 trace->tool.comm = perf_event__process_comm;
3244 trace->tool.exit = perf_event__process_exit;
3245 trace->tool.fork = perf_event__process_fork;
3246 trace->tool.attr = perf_event__process_attr;
3247 trace->tool.tracing_data = perf_event__process_tracing_data;
3248 trace->tool.build_id = perf_event__process_build_id;
3249 trace->tool.namespaces = perf_event__process_namespaces;
3251 trace->tool.ordered_events = true;
3252 trace->tool.ordering_requires_timestamps = true;
3254 /* add tid to output */
3255 trace->multiple_threads = true;
3257 session = perf_session__new(&data, false, &trace->tool);
3258 if (session == NULL)
3261 if (trace->opts.target.pid)
3262 symbol_conf.pid_list_str = strdup(trace->opts.target.pid);
3264 if (trace->opts.target.tid)
3265 symbol_conf.tid_list_str = strdup(trace->opts.target.tid);
3267 if (symbol__init(&session->header.env) < 0)
3270 trace->host = &session->machines.host;
3272 err = perf_session__set_tracepoints_handlers(session, handlers);
3276 evsel = perf_evlist__find_tracepoint_by_name(session->evlist,
3277 "raw_syscalls:sys_enter");
3278 /* older kernels have syscalls tp versus raw_syscalls */
3280 evsel = perf_evlist__find_tracepoint_by_name(session->evlist,
3281 "syscalls:sys_enter");
3284 (perf_evsel__init_raw_syscall_tp(evsel, trace__sys_enter) < 0 ||
3285 perf_evsel__init_sc_tp_ptr_field(evsel, args))) {
3286 pr_err("Error during initialize raw_syscalls:sys_enter event\n");
3290 evsel = perf_evlist__find_tracepoint_by_name(session->evlist,
3291 "raw_syscalls:sys_exit");
3293 evsel = perf_evlist__find_tracepoint_by_name(session->evlist,
3294 "syscalls:sys_exit");
3296 (perf_evsel__init_raw_syscall_tp(evsel, trace__sys_exit) < 0 ||
3297 perf_evsel__init_sc_tp_uint_field(evsel, ret))) {
3298 pr_err("Error during initialize raw_syscalls:sys_exit event\n");
3302 evlist__for_each_entry(session->evlist, evsel) {
3303 if (evsel->attr.type == PERF_TYPE_SOFTWARE &&
3304 (evsel->attr.config == PERF_COUNT_SW_PAGE_FAULTS_MAJ ||
3305 evsel->attr.config == PERF_COUNT_SW_PAGE_FAULTS_MIN ||
3306 evsel->attr.config == PERF_COUNT_SW_PAGE_FAULTS))
3307 evsel->handler = trace__pgfault;
3312 err = perf_session__process_events(session);
3314 pr_err("Failed to process events, error %d", err);
3316 else if (trace->summary)
3317 trace__fprintf_thread_summary(trace, trace->output);
3320 perf_session__delete(session);
3325 static size_t trace__fprintf_threads_header(FILE *fp)
3329 printed = fprintf(fp, "\n Summary of events:\n\n");
3334 DEFINE_RESORT_RB(syscall_stats, a->msecs > b->msecs,
3335 struct stats *stats;
3340 struct int_node *source = rb_entry(nd, struct int_node, rb_node);
3341 struct stats *stats = source->priv;
3343 entry->syscall = source->i;
3344 entry->stats = stats;
3345 entry->msecs = stats ? (u64)stats->n * (avg_stats(stats) / NSEC_PER_MSEC) : 0;
3348 static size_t thread__dump_stats(struct thread_trace *ttrace,
3349 struct trace *trace, FILE *fp)
3354 DECLARE_RESORT_RB_INTLIST(syscall_stats, ttrace->syscall_stats);
3356 if (syscall_stats == NULL)
3359 printed += fprintf(fp, "\n");
3361 printed += fprintf(fp, " syscall calls total min avg max stddev\n");
3362 printed += fprintf(fp, " (msec) (msec) (msec) (msec) (%%)\n");
3363 printed += fprintf(fp, " --------------- -------- --------- --------- --------- --------- ------\n");
3365 resort_rb__for_each_entry(nd, syscall_stats) {
3366 struct stats *stats = syscall_stats_entry->stats;
3368 double min = (double)(stats->min) / NSEC_PER_MSEC;
3369 double max = (double)(stats->max) / NSEC_PER_MSEC;
3370 double avg = avg_stats(stats);
3372 u64 n = (u64) stats->n;
3374 pct = avg ? 100.0 * stddev_stats(stats)/avg : 0.0;
3375 avg /= NSEC_PER_MSEC;
3377 sc = &trace->syscalls.table[syscall_stats_entry->syscall];
3378 printed += fprintf(fp, " %-15s", sc->name);
3379 printed += fprintf(fp, " %8" PRIu64 " %9.3f %9.3f %9.3f",
3380 n, syscall_stats_entry->msecs, min, avg);
3381 printed += fprintf(fp, " %9.3f %9.2f%%\n", max, pct);
3385 resort_rb__delete(syscall_stats);
3386 printed += fprintf(fp, "\n\n");
3391 static size_t trace__fprintf_thread(FILE *fp, struct thread *thread, struct trace *trace)
3394 struct thread_trace *ttrace = thread__priv(thread);
3400 ratio = (double)ttrace->nr_events / trace->nr_events * 100.0;
3402 printed += fprintf(fp, " %s (%d), ", thread__comm_str(thread), thread->tid);
3403 printed += fprintf(fp, "%lu events, ", ttrace->nr_events);
3404 printed += fprintf(fp, "%.1f%%", ratio);
3406 printed += fprintf(fp, ", %lu majfaults", ttrace->pfmaj);
3408 printed += fprintf(fp, ", %lu minfaults", ttrace->pfmin);
3410 printed += fprintf(fp, ", %.3f msec\n", ttrace->runtime_ms);
3411 else if (fputc('\n', fp) != EOF)
3414 printed += thread__dump_stats(ttrace, trace, fp);
3419 static unsigned long thread__nr_events(struct thread_trace *ttrace)
3421 return ttrace ? ttrace->nr_events : 0;
3424 DEFINE_RESORT_RB(threads, (thread__nr_events(a->thread->priv) < thread__nr_events(b->thread->priv)),
3425 struct thread *thread;
3428 entry->thread = rb_entry(nd, struct thread, rb_node);
3431 static size_t trace__fprintf_thread_summary(struct trace *trace, FILE *fp)
3433 size_t printed = trace__fprintf_threads_header(fp);
3437 for (i = 0; i < THREADS__TABLE_SIZE; i++) {
3438 DECLARE_RESORT_RB_MACHINE_THREADS(threads, trace->host, i);
3440 if (threads == NULL) {
3441 fprintf(fp, "%s", "Error sorting output by nr_events!\n");
3445 resort_rb__for_each_entry(nd, threads)
3446 printed += trace__fprintf_thread(fp, threads_entry->thread, trace);
3448 resort_rb__delete(threads);
3453 static int trace__set_duration(const struct option *opt, const char *str,
3454 int unset __maybe_unused)
3456 struct trace *trace = opt->value;
3458 trace->duration_filter = atof(str);
3462 static int trace__set_filter_pids_from_option(const struct option *opt, const char *str,
3463 int unset __maybe_unused)
3467 struct trace *trace = opt->value;
3469 * FIXME: introduce a intarray class, plain parse csv and create a
3470 * { int nr, int entries[] } struct...
3472 struct intlist *list = intlist__new(str);
3477 i = trace->filter_pids.nr = intlist__nr_entries(list) + 1;
3478 trace->filter_pids.entries = calloc(i, sizeof(pid_t));
3480 if (trace->filter_pids.entries == NULL)
3483 trace->filter_pids.entries[0] = getpid();
3485 for (i = 1; i < trace->filter_pids.nr; ++i)
3486 trace->filter_pids.entries[i] = intlist__entry(list, i - 1)->i;
3488 intlist__delete(list);
3494 static int trace__open_output(struct trace *trace, const char *filename)
3498 if (!stat(filename, &st) && st.st_size) {
3499 char oldname[PATH_MAX];
3501 scnprintf(oldname, sizeof(oldname), "%s.old", filename);
3503 rename(filename, oldname);
3506 trace->output = fopen(filename, "w");
3508 return trace->output == NULL ? -errno : 0;
3511 static int parse_pagefaults(const struct option *opt, const char *str,
3512 int unset __maybe_unused)
3514 int *trace_pgfaults = opt->value;
3516 if (strcmp(str, "all") == 0)
3517 *trace_pgfaults |= TRACE_PFMAJ | TRACE_PFMIN;
3518 else if (strcmp(str, "maj") == 0)
3519 *trace_pgfaults |= TRACE_PFMAJ;
3520 else if (strcmp(str, "min") == 0)
3521 *trace_pgfaults |= TRACE_PFMIN;
3528 static void evlist__set_evsel_handler(struct perf_evlist *evlist, void *handler)
3530 struct perf_evsel *evsel;
3532 evlist__for_each_entry(evlist, evsel)
3533 evsel->handler = handler;
3536 static int evlist__set_syscall_tp_fields(struct perf_evlist *evlist)
3538 struct perf_evsel *evsel;
3540 evlist__for_each_entry(evlist, evsel) {
3541 if (evsel->priv || !evsel->tp_format)
3544 if (strcmp(evsel->tp_format->system, "syscalls"))
3547 if (perf_evsel__init_syscall_tp(evsel))
3550 if (!strncmp(evsel->tp_format->name, "sys_enter_", 10)) {
3551 struct syscall_tp *sc = evsel->priv;
3553 if (__tp_field__init_ptr(&sc->args, sc->id.offset + sizeof(u64)))
3555 } else if (!strncmp(evsel->tp_format->name, "sys_exit_", 9)) {
3556 struct syscall_tp *sc = evsel->priv;
3558 if (__tp_field__init_uint(&sc->ret, sizeof(u64), sc->id.offset + sizeof(u64), evsel->needs_swap))
3567 * XXX: Hackish, just splitting the combined -e+--event (syscalls
3568 * (raw_syscalls:{sys_{enter,exit}} + events (tracepoints, HW, SW, etc) to use
3569 * existing facilities unchanged (trace->ev_qualifier + parse_options()).
3571 * It'd be better to introduce a parse_options() variant that would return a
3572 * list with the terms it didn't match to an event...
3574 static int trace__parse_events_option(const struct option *opt, const char *str,
3575 int unset __maybe_unused)
3577 struct trace *trace = (struct trace *)opt->value;
3578 const char *s = str;
3579 char *sep = NULL, *lists[2] = { NULL, NULL, };
3580 int len = strlen(str) + 1, err = -1, list, idx;
3581 char *strace_groups_dir = system_path(STRACE_GROUPS_DIR);
3582 char group_name[PATH_MAX];
3583 struct syscall_fmt *fmt;
3585 if (strace_groups_dir == NULL)
3590 trace->not_ev_qualifier = true;
3594 if ((sep = strchr(s, ',')) != NULL)
3598 if (syscalltbl__id(trace->sctbl, s) >= 0 ||
3599 syscalltbl__strglobmatch_first(trace->sctbl, s, &idx) >= 0) {
3604 fmt = syscall_fmt__find_by_alias(s);
3609 path__join(group_name, sizeof(group_name), strace_groups_dir, s);
3610 if (access(group_name, R_OK) == 0)
3615 sprintf(lists[list] + strlen(lists[list]), ",%s", s);
3617 lists[list] = malloc(len);
3618 if (lists[list] == NULL)
3620 strcpy(lists[list], s);
3630 if (lists[1] != NULL) {
3631 struct strlist_config slist_config = {
3632 .dirname = strace_groups_dir,
3635 trace->ev_qualifier = strlist__new(lists[1], &slist_config);
3636 if (trace->ev_qualifier == NULL) {
3637 fputs("Not enough memory to parse event qualifier", trace->output);
3641 if (trace__validate_ev_qualifier(trace))
3643 trace->trace_syscalls = true;
3649 struct option o = OPT_CALLBACK('e', "event", &trace->evlist, "event",
3650 "event selector. use 'perf list' to list available events",
3651 parse_events_option);
3652 err = parse_events_option(&o, lists[0], 0);
3661 static int trace__parse_cgroups(const struct option *opt, const char *str, int unset)
3663 struct trace *trace = opt->value;
3665 if (!list_empty(&trace->evlist->entries))
3666 return parse_cgroups(opt, str, unset);
3668 trace->cgroup = evlist__findnew_cgroup(trace->evlist, str);
3673 static struct bpf_map *bpf__find_map_by_name(const char *name)
3675 struct bpf_object *obj, *tmp;
3677 bpf_object__for_each_safe(obj, tmp) {
3678 struct bpf_map *map = bpf_object__find_map_by_name(obj, name);
3687 static void trace__set_bpf_map_filtered_pids(struct trace *trace)
3689 trace->filter_pids.map = bpf__find_map_by_name("pids_filtered");
3692 static void trace__set_bpf_map_syscalls(struct trace *trace)
3694 trace->syscalls.map = bpf__find_map_by_name("syscalls");
3697 static int trace__config(const char *var, const char *value, void *arg)
3699 struct trace *trace = arg;
3702 if (!strcmp(var, "trace.add_events")) {
3703 struct option o = OPT_CALLBACK('e', "event", &trace->evlist, "event",
3704 "event selector. use 'perf list' to list available events",
3705 parse_events_option);
3707 * We can't propagate parse_event_option() return, as it is 1
3708 * for failure while perf_config() expects -1.
3710 if (parse_events_option(&o, value, 0))
3712 } else if (!strcmp(var, "trace.show_timestamp")) {
3713 trace->show_tstamp = perf_config_bool(var, value);
3714 } else if (!strcmp(var, "trace.show_duration")) {
3715 trace->show_duration = perf_config_bool(var, value);
3716 } else if (!strcmp(var, "trace.show_arg_names")) {
3717 trace->show_arg_names = perf_config_bool(var, value);
3718 if (!trace->show_arg_names)
3719 trace->show_zeros = true;
3720 } else if (!strcmp(var, "trace.show_zeros")) {
3721 bool new_show_zeros = perf_config_bool(var, value);
3722 if (!trace->show_arg_names && !new_show_zeros) {
3723 pr_warning("trace.show_zeros has to be set when trace.show_arg_names=no\n");
3726 trace->show_zeros = new_show_zeros;
3727 } else if (!strcmp(var, "trace.show_prefix")) {
3728 trace->show_string_prefix = perf_config_bool(var, value);
3729 } else if (!strcmp(var, "trace.no_inherit")) {
3730 trace->opts.no_inherit = perf_config_bool(var, value);
3731 } else if (!strcmp(var, "trace.args_alignment")) {
3732 int args_alignment = 0;
3733 if (perf_config_int(&args_alignment, var, value) == 0)
3734 trace->args_alignment = args_alignment;
3740 int cmd_trace(int argc, const char **argv)
3742 const char *trace_usage[] = {
3743 "perf trace [<options>] [<command>]",
3744 "perf trace [<options>] -- <command> [<options>]",
3745 "perf trace record [<options>] [<command>]",
3746 "perf trace record [<options>] -- <command> [<options>]",
3749 struct trace trace = {
3758 .user_freq = UINT_MAX,
3759 .user_interval = ULLONG_MAX,
3760 .no_buffering = true,
3761 .mmap_pages = UINT_MAX,
3765 .show_tstamp = true,
3766 .show_duration = true,
3767 .show_arg_names = true,
3768 .args_alignment = 70,
3769 .trace_syscalls = false,
3770 .kernel_syscallchains = false,
3771 .max_stack = UINT_MAX,
3772 .max_events = ULONG_MAX,
3774 const char *map_dump_str = NULL;
3775 const char *output_name = NULL;
3776 const struct option trace_options[] = {
3777 OPT_CALLBACK('e', "event", &trace, "event",
3778 "event/syscall selector. use 'perf list' to list available events",
3779 trace__parse_events_option),
3780 OPT_BOOLEAN(0, "comm", &trace.show_comm,
3781 "show the thread COMM next to its id"),
3782 OPT_BOOLEAN(0, "tool_stats", &trace.show_tool_stats, "show tool stats"),
3783 OPT_CALLBACK(0, "expr", &trace, "expr", "list of syscalls/events to trace",
3784 trace__parse_events_option),
3785 OPT_STRING('o', "output", &output_name, "file", "output file name"),
3786 OPT_STRING('i', "input", &input_name, "file", "Analyze events in file"),
3787 OPT_STRING('p', "pid", &trace.opts.target.pid, "pid",
3788 "trace events on existing process id"),
3789 OPT_STRING('t', "tid", &trace.opts.target.tid, "tid",
3790 "trace events on existing thread id"),
3791 OPT_CALLBACK(0, "filter-pids", &trace, "CSV list of pids",
3792 "pids to filter (by the kernel)", trace__set_filter_pids_from_option),
3793 OPT_BOOLEAN('a', "all-cpus", &trace.opts.target.system_wide,
3794 "system-wide collection from all CPUs"),
3795 OPT_STRING('C', "cpu", &trace.opts.target.cpu_list, "cpu",
3796 "list of cpus to monitor"),
3797 OPT_BOOLEAN(0, "no-inherit", &trace.opts.no_inherit,
3798 "child tasks do not inherit counters"),
3799 OPT_CALLBACK('m', "mmap-pages", &trace.opts.mmap_pages, "pages",
3800 "number of mmap data pages",
3801 perf_evlist__parse_mmap_pages),
3802 OPT_STRING('u', "uid", &trace.opts.target.uid_str, "user",
3804 OPT_CALLBACK(0, "duration", &trace, "float",
3805 "show only events with duration > N.M ms",
3806 trace__set_duration),
3807 #ifdef HAVE_LIBBPF_SUPPORT
3808 OPT_STRING(0, "map-dump", &map_dump_str, "BPF map", "BPF map to periodically dump"),
3810 OPT_BOOLEAN(0, "sched", &trace.sched, "show blocking scheduler events"),
3811 OPT_INCR('v', "verbose", &verbose, "be more verbose"),
3812 OPT_BOOLEAN('T', "time", &trace.full_time,
3813 "Show full timestamp, not time relative to first start"),
3814 OPT_BOOLEAN(0, "failure", &trace.failure_only,
3815 "Show only syscalls that failed"),
3816 OPT_BOOLEAN('s', "summary", &trace.summary_only,
3817 "Show only syscall summary with statistics"),
3818 OPT_BOOLEAN('S', "with-summary", &trace.summary,
3819 "Show all syscalls and summary with statistics"),
3820 OPT_CALLBACK_DEFAULT('F', "pf", &trace.trace_pgfaults, "all|maj|min",
3821 "Trace pagefaults", parse_pagefaults, "maj"),
3822 OPT_BOOLEAN(0, "syscalls", &trace.trace_syscalls, "Trace syscalls"),
3823 OPT_BOOLEAN('f', "force", &trace.force, "don't complain, do it"),
3824 OPT_CALLBACK(0, "call-graph", &trace.opts,
3825 "record_mode[,record_size]", record_callchain_help,
3826 &record_parse_callchain_opt),
3827 OPT_BOOLEAN(0, "kernel-syscall-graph", &trace.kernel_syscallchains,
3828 "Show the kernel callchains on the syscall exit path"),
3829 OPT_ULONG(0, "max-events", &trace.max_events,
3830 "Set the maximum number of events to print, exit after that is reached. "),
3831 OPT_UINTEGER(0, "min-stack", &trace.min_stack,
3832 "Set the minimum stack depth when parsing the callchain, "
3833 "anything below the specified depth will be ignored."),
3834 OPT_UINTEGER(0, "max-stack", &trace.max_stack,
3835 "Set the maximum stack depth when parsing the callchain, "
3836 "anything beyond the specified depth will be ignored. "
3837 "Default: kernel.perf_event_max_stack or " __stringify(PERF_MAX_STACK_DEPTH)),
3838 OPT_BOOLEAN(0, "sort-events", &trace.sort_events,
3839 "Sort batch of events before processing, use if getting out of order events"),
3840 OPT_BOOLEAN(0, "print-sample", &trace.print_sample,
3841 "print the PERF_RECORD_SAMPLE PERF_SAMPLE_ info, for debugging"),
3842 OPT_UINTEGER(0, "proc-map-timeout", &proc_map_timeout,
3843 "per thread proc mmap processing timeout in ms"),
3844 OPT_CALLBACK('G', "cgroup", &trace, "name", "monitor event in cgroup name only",
3845 trace__parse_cgroups),
3846 OPT_UINTEGER('D', "delay", &trace.opts.initial_delay,
3847 "ms to wait before starting measurement after program "
3851 bool __maybe_unused max_stack_user_set = true;
3852 bool mmap_pages_user_set = true;
3853 struct perf_evsel *evsel;
3854 const char * const trace_subcommands[] = { "record", NULL };
3858 signal(SIGSEGV, sighandler_dump_stack);
3859 signal(SIGFPE, sighandler_dump_stack);
3861 trace.evlist = perf_evlist__new();
3862 trace.sctbl = syscalltbl__new();
3864 if (trace.evlist == NULL || trace.sctbl == NULL) {
3865 pr_err("Not enough memory to run!\n");
3870 err = perf_config(trace__config, &trace);
3874 argc = parse_options_subcommand(argc, argv, trace_options, trace_subcommands,
3875 trace_usage, PARSE_OPT_STOP_AT_NON_OPTION);
3877 if ((nr_cgroups || trace.cgroup) && !trace.opts.target.system_wide) {
3878 usage_with_options_msg(trace_usage, trace_options,
3879 "cgroup monitoring only available in system-wide mode");
3882 evsel = bpf__setup_output_event(trace.evlist, "__augmented_syscalls__");
3883 if (IS_ERR(evsel)) {
3884 bpf__strerror_setup_output_event(trace.evlist, PTR_ERR(evsel), bf, sizeof(bf));
3885 pr_err("ERROR: Setup trace syscalls enter failed: %s\n", bf);
3890 trace.syscalls.events.augmented = evsel;
3891 trace__set_bpf_map_filtered_pids(&trace);
3892 trace__set_bpf_map_syscalls(&trace);
3895 err = bpf__setup_stdout(trace.evlist);
3897 bpf__strerror_setup_stdout(trace.evlist, err, bf, sizeof(bf));
3898 pr_err("ERROR: Setup BPF stdout failed: %s\n", bf);
3905 trace.dump.map = bpf__find_map_by_name(map_dump_str);
3906 if (trace.dump.map == NULL) {
3907 pr_err("ERROR: BPF map \"%s\" not found\n", map_dump_str);
3912 if (trace.trace_pgfaults) {
3913 trace.opts.sample_address = true;
3914 trace.opts.sample_time = true;
3917 if (trace.opts.mmap_pages == UINT_MAX)
3918 mmap_pages_user_set = false;
3920 if (trace.max_stack == UINT_MAX) {
3921 trace.max_stack = input_name ? PERF_MAX_STACK_DEPTH : sysctl__max_stack();
3922 max_stack_user_set = false;
3925 #ifdef HAVE_DWARF_UNWIND_SUPPORT
3926 if ((trace.min_stack || max_stack_user_set) && !callchain_param.enabled) {
3927 record_opts__parse_callchain(&trace.opts, &callchain_param, "dwarf", false);
3931 if (callchain_param.enabled) {
3932 if (!mmap_pages_user_set && geteuid() == 0)
3933 trace.opts.mmap_pages = perf_event_mlock_kb_in_pages() * 4;
3935 symbol_conf.use_callchain = true;
3938 if (trace.evlist->nr_entries > 0) {
3939 evlist__set_evsel_handler(trace.evlist, trace__event_handler);
3940 if (evlist__set_syscall_tp_fields(trace.evlist)) {
3941 perror("failed to set syscalls:* tracepoint fields");
3946 if (trace.sort_events) {
3947 ordered_events__init(&trace.oe.data, ordered_events__deliver_event, &trace);
3948 ordered_events__set_copy_on_queue(&trace.oe.data, true);
3952 * If we are augmenting syscalls, then combine what we put in the
3953 * __augmented_syscalls__ BPF map with what is in the
3954 * syscalls:sys_exit_FOO tracepoints, i.e. just like we do without BPF,
3955 * combining raw_syscalls:sys_enter with raw_syscalls:sys_exit.
3957 * We'll switch to look at two BPF maps, one for sys_enter and the
3958 * other for sys_exit when we start augmenting the sys_exit paths with
3959 * buffers that are being copied from kernel to userspace, think 'read'
3962 if (trace.syscalls.events.augmented) {
3963 evlist__for_each_entry(trace.evlist, evsel) {
3964 bool raw_syscalls_sys_exit = strcmp(perf_evsel__name(evsel), "raw_syscalls:sys_exit") == 0;
3966 if (raw_syscalls_sys_exit) {
3967 trace.raw_augmented_syscalls = true;
3968 goto init_augmented_syscall_tp;
3971 if (trace.syscalls.events.augmented->priv == NULL &&
3972 strstr(perf_evsel__name(evsel), "syscalls:sys_enter")) {
3973 struct perf_evsel *augmented = trace.syscalls.events.augmented;
3974 if (perf_evsel__init_augmented_syscall_tp(augmented, evsel) ||
3975 perf_evsel__init_augmented_syscall_tp_args(augmented))
3977 augmented->handler = trace__sys_enter;
3980 if (strstarts(perf_evsel__name(evsel), "syscalls:sys_exit_")) {
3981 struct syscall_tp *sc;
3982 init_augmented_syscall_tp:
3983 if (perf_evsel__init_augmented_syscall_tp(evsel, evsel))
3987 * For now with BPF raw_augmented we hook into
3988 * raw_syscalls:sys_enter and there we get all
3989 * 6 syscall args plus the tracepoint common
3990 * fields and the syscall_nr (another long).
3991 * So we check if that is the case and if so
3992 * don't look after the sc->args_size but
3993 * always after the full raw_syscalls:sys_enter
3994 * payload, which is fixed.
3996 * We'll revisit this later to pass
3997 * s->args_size to the BPF augmenter (now
3998 * tools/perf/examples/bpf/augmented_raw_syscalls.c,
3999 * so that it copies only what we need for each
4000 * syscall, like what happens when we use
4001 * syscalls:sys_enter_NAME, so that we reduce
4002 * the kernel/userspace traffic to just what is
4003 * needed for each syscall.
4005 if (trace.raw_augmented_syscalls)
4006 trace.raw_augmented_syscalls_args_size = (6 + 1) * sizeof(long) + sc->id.offset;
4007 perf_evsel__init_augmented_syscall_tp_ret(evsel);
4008 evsel->handler = trace__sys_exit;
4013 if ((argc >= 1) && (strcmp(argv[0], "record") == 0))
4014 return trace__record(&trace, argc-1, &argv[1]);
4016 /* summary_only implies summary option, but don't overwrite summary if set */
4017 if (trace.summary_only)
4018 trace.summary = trace.summary_only;
4020 if (!trace.trace_syscalls && !trace.trace_pgfaults &&
4021 trace.evlist->nr_entries == 0 /* Was --events used? */) {
4022 trace.trace_syscalls = true;
4025 if (output_name != NULL) {
4026 err = trace__open_output(&trace, output_name);
4028 perror("failed to create output file");
4033 err = target__validate(&trace.opts.target);
4035 target__strerror(&trace.opts.target, err, bf, sizeof(bf));
4036 fprintf(trace.output, "%s", bf);
4040 err = target__parse_uid(&trace.opts.target);
4042 target__strerror(&trace.opts.target, err, bf, sizeof(bf));
4043 fprintf(trace.output, "%s", bf);
4047 if (!argc && target__none(&trace.opts.target))
4048 trace.opts.target.system_wide = true;
4051 err = trace__replay(&trace);
4053 err = trace__run(&trace, argc, argv);
4056 if (output_name != NULL)
4057 fclose(trace.output);