Linux 5.1.15
[linux/fpc-iii.git] / tools / perf / builtin-trace.c
blobf5b3a1e9c1ddfc446cb37dc7fb30d4959dfae648
1 /*
2 * builtin-trace.c
4 * Builtin 'trace' command:
6 * Display a continuously updated trace of any workload, CPU, specific PID,
7 * system wide, etc. Default format is loosely strace like, but any other
8 * event may be specified using --event.
10 * Copyright (C) 2012, 2013, 2014, 2015 Red Hat Inc, Arnaldo Carvalho de Melo <acme@redhat.com>
12 * Initially based on the 'trace' prototype by Thomas Gleixner:
14 * http://lwn.net/Articles/415728/ ("Announcing a new utility: 'trace'")
16 * Released under the GPL v2. (and only v2, not any later version)
19 #include <traceevent/event-parse.h>
20 #include <api/fs/tracing_path.h>
21 #include <bpf/bpf.h>
22 #include "util/bpf_map.h"
23 #include "builtin.h"
24 #include "util/cgroup.h"
25 #include "util/color.h"
26 #include "util/config.h"
27 #include "util/debug.h"
28 #include "util/env.h"
29 #include "util/event.h"
30 #include "util/evlist.h"
31 #include <subcmd/exec-cmd.h>
32 #include "util/machine.h"
33 #include "util/map.h"
34 #include "util/symbol.h"
35 #include "util/path.h"
36 #include "util/session.h"
37 #include "util/thread.h"
38 #include <subcmd/parse-options.h>
39 #include "util/strlist.h"
40 #include "util/intlist.h"
41 #include "util/thread_map.h"
42 #include "util/stat.h"
43 #include "trace/beauty/beauty.h"
44 #include "trace-event.h"
45 #include "util/parse-events.h"
46 #include "util/bpf-loader.h"
47 #include "callchain.h"
48 #include "print_binary.h"
49 #include "string2.h"
50 #include "syscalltbl.h"
51 #include "rb_resort.h"
53 #include <errno.h>
54 #include <inttypes.h>
55 #include <poll.h>
56 #include <signal.h>
57 #include <stdlib.h>
58 #include <string.h>
59 #include <linux/err.h>
60 #include <linux/filter.h>
61 #include <linux/kernel.h>
62 #include <linux/random.h>
63 #include <linux/stringify.h>
64 #include <linux/time64.h>
65 #include <fcntl.h>
66 #include <sys/sysmacros.h>
68 #include "sane_ctype.h"
70 #ifndef O_CLOEXEC
71 # define O_CLOEXEC 02000000
72 #endif
74 #ifndef F_LINUX_SPECIFIC_BASE
75 # define F_LINUX_SPECIFIC_BASE 1024
76 #endif
78 struct trace {
79 struct perf_tool tool;
80 struct syscalltbl *sctbl;
81 struct {
82 int max;
83 struct syscall *table;
84 struct bpf_map *map;
85 struct {
86 struct perf_evsel *sys_enter,
87 *sys_exit,
88 *augmented;
89 } events;
90 } syscalls;
91 struct {
92 struct bpf_map *map;
93 } dump;
94 struct record_opts opts;
95 struct perf_evlist *evlist;
96 struct machine *host;
97 struct thread *current;
98 struct cgroup *cgroup;
99 u64 base_time;
100 FILE *output;
101 unsigned long nr_events;
102 unsigned long nr_events_printed;
103 unsigned long max_events;
104 struct strlist *ev_qualifier;
105 struct {
106 size_t nr;
107 int *entries;
108 } ev_qualifier_ids;
109 struct {
110 size_t nr;
111 pid_t *entries;
112 struct bpf_map *map;
113 } filter_pids;
114 double duration_filter;
115 double runtime_ms;
116 struct {
117 u64 vfs_getname,
118 proc_getname;
119 } stats;
120 unsigned int max_stack;
121 unsigned int min_stack;
122 int raw_augmented_syscalls_args_size;
123 bool raw_augmented_syscalls;
124 bool sort_events;
125 bool not_ev_qualifier;
126 bool live;
127 bool full_time;
128 bool sched;
129 bool multiple_threads;
130 bool summary;
131 bool summary_only;
132 bool failure_only;
133 bool show_comm;
134 bool print_sample;
135 bool show_tool_stats;
136 bool trace_syscalls;
137 bool kernel_syscallchains;
138 s16 args_alignment;
139 bool show_tstamp;
140 bool show_duration;
141 bool show_zeros;
142 bool show_arg_names;
143 bool show_string_prefix;
144 bool force;
145 bool vfs_getname;
146 int trace_pgfaults;
147 struct {
148 struct ordered_events data;
149 u64 last;
150 } oe;
153 struct tp_field {
154 int offset;
155 union {
156 u64 (*integer)(struct tp_field *field, struct perf_sample *sample);
157 void *(*pointer)(struct tp_field *field, struct perf_sample *sample);
161 #define TP_UINT_FIELD(bits) \
162 static u64 tp_field__u##bits(struct tp_field *field, struct perf_sample *sample) \
164 u##bits value; \
165 memcpy(&value, sample->raw_data + field->offset, sizeof(value)); \
166 return value; \
169 TP_UINT_FIELD(8);
170 TP_UINT_FIELD(16);
171 TP_UINT_FIELD(32);
172 TP_UINT_FIELD(64);
174 #define TP_UINT_FIELD__SWAPPED(bits) \
175 static u64 tp_field__swapped_u##bits(struct tp_field *field, struct perf_sample *sample) \
177 u##bits value; \
178 memcpy(&value, sample->raw_data + field->offset, sizeof(value)); \
179 return bswap_##bits(value);\
182 TP_UINT_FIELD__SWAPPED(16);
183 TP_UINT_FIELD__SWAPPED(32);
184 TP_UINT_FIELD__SWAPPED(64);
186 static int __tp_field__init_uint(struct tp_field *field, int size, int offset, bool needs_swap)
188 field->offset = offset;
190 switch (size) {
191 case 1:
192 field->integer = tp_field__u8;
193 break;
194 case 2:
195 field->integer = needs_swap ? tp_field__swapped_u16 : tp_field__u16;
196 break;
197 case 4:
198 field->integer = needs_swap ? tp_field__swapped_u32 : tp_field__u32;
199 break;
200 case 8:
201 field->integer = needs_swap ? tp_field__swapped_u64 : tp_field__u64;
202 break;
203 default:
204 return -1;
207 return 0;
210 static int tp_field__init_uint(struct tp_field *field, struct tep_format_field *format_field, bool needs_swap)
212 return __tp_field__init_uint(field, format_field->size, format_field->offset, needs_swap);
215 static void *tp_field__ptr(struct tp_field *field, struct perf_sample *sample)
217 return sample->raw_data + field->offset;
220 static int __tp_field__init_ptr(struct tp_field *field, int offset)
222 field->offset = offset;
223 field->pointer = tp_field__ptr;
224 return 0;
227 static int tp_field__init_ptr(struct tp_field *field, struct tep_format_field *format_field)
229 return __tp_field__init_ptr(field, format_field->offset);
232 struct syscall_tp {
233 struct tp_field id;
234 union {
235 struct tp_field args, ret;
239 static int perf_evsel__init_tp_uint_field(struct perf_evsel *evsel,
240 struct tp_field *field,
241 const char *name)
243 struct tep_format_field *format_field = perf_evsel__field(evsel, name);
245 if (format_field == NULL)
246 return -1;
248 return tp_field__init_uint(field, format_field, evsel->needs_swap);
251 #define perf_evsel__init_sc_tp_uint_field(evsel, name) \
252 ({ struct syscall_tp *sc = evsel->priv;\
253 perf_evsel__init_tp_uint_field(evsel, &sc->name, #name); })
255 static int perf_evsel__init_tp_ptr_field(struct perf_evsel *evsel,
256 struct tp_field *field,
257 const char *name)
259 struct tep_format_field *format_field = perf_evsel__field(evsel, name);
261 if (format_field == NULL)
262 return -1;
264 return tp_field__init_ptr(field, format_field);
267 #define perf_evsel__init_sc_tp_ptr_field(evsel, name) \
268 ({ struct syscall_tp *sc = evsel->priv;\
269 perf_evsel__init_tp_ptr_field(evsel, &sc->name, #name); })
271 static void perf_evsel__delete_priv(struct perf_evsel *evsel)
273 zfree(&evsel->priv);
274 perf_evsel__delete(evsel);
277 static int perf_evsel__init_syscall_tp(struct perf_evsel *evsel)
279 struct syscall_tp *sc = evsel->priv = malloc(sizeof(struct syscall_tp));
281 if (evsel->priv != NULL) {
282 if (perf_evsel__init_tp_uint_field(evsel, &sc->id, "__syscall_nr") &&
283 perf_evsel__init_tp_uint_field(evsel, &sc->id, "nr"))
284 goto out_delete;
285 return 0;
288 return -ENOMEM;
289 out_delete:
290 zfree(&evsel->priv);
291 return -ENOENT;
294 static int perf_evsel__init_augmented_syscall_tp(struct perf_evsel *evsel, struct perf_evsel *tp)
296 struct syscall_tp *sc = evsel->priv = malloc(sizeof(struct syscall_tp));
298 if (evsel->priv != NULL) {
299 struct tep_format_field *syscall_id = perf_evsel__field(tp, "id");
300 if (syscall_id == NULL)
301 syscall_id = perf_evsel__field(tp, "__syscall_nr");
302 if (syscall_id == NULL)
303 goto out_delete;
304 if (__tp_field__init_uint(&sc->id, syscall_id->size, syscall_id->offset, evsel->needs_swap))
305 goto out_delete;
307 return 0;
310 return -ENOMEM;
311 out_delete:
312 zfree(&evsel->priv);
313 return -EINVAL;
316 static int perf_evsel__init_augmented_syscall_tp_args(struct perf_evsel *evsel)
318 struct syscall_tp *sc = evsel->priv;
320 return __tp_field__init_ptr(&sc->args, sc->id.offset + sizeof(u64));
323 static int perf_evsel__init_augmented_syscall_tp_ret(struct perf_evsel *evsel)
325 struct syscall_tp *sc = evsel->priv;
327 return __tp_field__init_uint(&sc->ret, sizeof(u64), sc->id.offset + sizeof(u64), evsel->needs_swap);
330 static int perf_evsel__init_raw_syscall_tp(struct perf_evsel *evsel, void *handler)
332 evsel->priv = malloc(sizeof(struct syscall_tp));
333 if (evsel->priv != NULL) {
334 if (perf_evsel__init_sc_tp_uint_field(evsel, id))
335 goto out_delete;
337 evsel->handler = handler;
338 return 0;
341 return -ENOMEM;
343 out_delete:
344 zfree(&evsel->priv);
345 return -ENOENT;
348 static struct perf_evsel *perf_evsel__raw_syscall_newtp(const char *direction, void *handler)
350 struct perf_evsel *evsel = perf_evsel__newtp("raw_syscalls", direction);
352 /* older kernel (e.g., RHEL6) use syscalls:{enter,exit} */
353 if (IS_ERR(evsel))
354 evsel = perf_evsel__newtp("syscalls", direction);
356 if (IS_ERR(evsel))
357 return NULL;
359 if (perf_evsel__init_raw_syscall_tp(evsel, handler))
360 goto out_delete;
362 return evsel;
364 out_delete:
365 perf_evsel__delete_priv(evsel);
366 return NULL;
369 #define perf_evsel__sc_tp_uint(evsel, name, sample) \
370 ({ struct syscall_tp *fields = evsel->priv; \
371 fields->name.integer(&fields->name, sample); })
373 #define perf_evsel__sc_tp_ptr(evsel, name, sample) \
374 ({ struct syscall_tp *fields = evsel->priv; \
375 fields->name.pointer(&fields->name, sample); })
377 size_t strarray__scnprintf(struct strarray *sa, char *bf, size_t size, const char *intfmt, bool show_prefix, int val)
379 int idx = val - sa->offset;
381 if (idx < 0 || idx >= sa->nr_entries || sa->entries[idx] == NULL) {
382 size_t printed = scnprintf(bf, size, intfmt, val);
383 if (show_prefix)
384 printed += scnprintf(bf + printed, size - printed, " /* %s??? */", sa->prefix);
385 return printed;
388 return scnprintf(bf, size, "%s%s", show_prefix ? sa->prefix : "", sa->entries[idx]);
391 static size_t __syscall_arg__scnprintf_strarray(char *bf, size_t size,
392 const char *intfmt,
393 struct syscall_arg *arg)
395 return strarray__scnprintf(arg->parm, bf, size, intfmt, arg->show_string_prefix, arg->val);
398 static size_t syscall_arg__scnprintf_strarray(char *bf, size_t size,
399 struct syscall_arg *arg)
401 return __syscall_arg__scnprintf_strarray(bf, size, "%d", arg);
404 #define SCA_STRARRAY syscall_arg__scnprintf_strarray
406 size_t strarrays__scnprintf(struct strarrays *sas, char *bf, size_t size, const char *intfmt, bool show_prefix, int val)
408 size_t printed;
409 int i;
411 for (i = 0; i < sas->nr_entries; ++i) {
412 struct strarray *sa = sas->entries[i];
413 int idx = val - sa->offset;
415 if (idx >= 0 && idx < sa->nr_entries) {
416 if (sa->entries[idx] == NULL)
417 break;
418 return scnprintf(bf, size, "%s%s", show_prefix ? sa->prefix : "", sa->entries[idx]);
422 printed = scnprintf(bf, size, intfmt, val);
423 if (show_prefix)
424 printed += scnprintf(bf + printed, size - printed, " /* %s??? */", sas->entries[0]->prefix);
425 return printed;
428 size_t syscall_arg__scnprintf_strarrays(char *bf, size_t size,
429 struct syscall_arg *arg)
431 return strarrays__scnprintf(arg->parm, bf, size, "%d", arg->show_string_prefix, arg->val);
434 #ifndef AT_FDCWD
435 #define AT_FDCWD -100
436 #endif
438 static size_t syscall_arg__scnprintf_fd_at(char *bf, size_t size,
439 struct syscall_arg *arg)
441 int fd = arg->val;
442 const char *prefix = "AT_FD";
444 if (fd == AT_FDCWD)
445 return scnprintf(bf, size, "%s%s", arg->show_string_prefix ? prefix : "", "CWD");
447 return syscall_arg__scnprintf_fd(bf, size, arg);
450 #define SCA_FDAT syscall_arg__scnprintf_fd_at
452 static size_t syscall_arg__scnprintf_close_fd(char *bf, size_t size,
453 struct syscall_arg *arg);
455 #define SCA_CLOSE_FD syscall_arg__scnprintf_close_fd
457 size_t syscall_arg__scnprintf_hex(char *bf, size_t size, struct syscall_arg *arg)
459 return scnprintf(bf, size, "%#lx", arg->val);
462 size_t syscall_arg__scnprintf_ptr(char *bf, size_t size, struct syscall_arg *arg)
464 if (arg->val == 0)
465 return scnprintf(bf, size, "NULL");
466 return syscall_arg__scnprintf_hex(bf, size, arg);
469 size_t syscall_arg__scnprintf_int(char *bf, size_t size, struct syscall_arg *arg)
471 return scnprintf(bf, size, "%d", arg->val);
474 size_t syscall_arg__scnprintf_long(char *bf, size_t size, struct syscall_arg *arg)
476 return scnprintf(bf, size, "%ld", arg->val);
479 static const char *bpf_cmd[] = {
480 "MAP_CREATE", "MAP_LOOKUP_ELEM", "MAP_UPDATE_ELEM", "MAP_DELETE_ELEM",
481 "MAP_GET_NEXT_KEY", "PROG_LOAD",
483 static DEFINE_STRARRAY(bpf_cmd, "BPF_");
485 static const char *epoll_ctl_ops[] = { "ADD", "DEL", "MOD", };
486 static DEFINE_STRARRAY_OFFSET(epoll_ctl_ops, "EPOLL_CTL_", 1);
488 static const char *itimers[] = { "REAL", "VIRTUAL", "PROF", };
489 static DEFINE_STRARRAY(itimers, "ITIMER_");
491 static const char *keyctl_options[] = {
492 "GET_KEYRING_ID", "JOIN_SESSION_KEYRING", "UPDATE", "REVOKE", "CHOWN",
493 "SETPERM", "DESCRIBE", "CLEAR", "LINK", "UNLINK", "SEARCH", "READ",
494 "INSTANTIATE", "NEGATE", "SET_REQKEY_KEYRING", "SET_TIMEOUT",
495 "ASSUME_AUTHORITY", "GET_SECURITY", "SESSION_TO_PARENT", "REJECT",
496 "INSTANTIATE_IOV", "INVALIDATE", "GET_PERSISTENT",
498 static DEFINE_STRARRAY(keyctl_options, "KEYCTL_");
500 static const char *whences[] = { "SET", "CUR", "END",
501 #ifdef SEEK_DATA
502 "DATA",
503 #endif
504 #ifdef SEEK_HOLE
505 "HOLE",
506 #endif
508 static DEFINE_STRARRAY(whences, "SEEK_");
510 static const char *fcntl_cmds[] = {
511 "DUPFD", "GETFD", "SETFD", "GETFL", "SETFL", "GETLK", "SETLK",
512 "SETLKW", "SETOWN", "GETOWN", "SETSIG", "GETSIG", "GETLK64",
513 "SETLK64", "SETLKW64", "SETOWN_EX", "GETOWN_EX",
514 "GETOWNER_UIDS",
516 static DEFINE_STRARRAY(fcntl_cmds, "F_");
518 static const char *fcntl_linux_specific_cmds[] = {
519 "SETLEASE", "GETLEASE", "NOTIFY", [5] = "CANCELLK", "DUPFD_CLOEXEC",
520 "SETPIPE_SZ", "GETPIPE_SZ", "ADD_SEALS", "GET_SEALS",
521 "GET_RW_HINT", "SET_RW_HINT", "GET_FILE_RW_HINT", "SET_FILE_RW_HINT",
524 static DEFINE_STRARRAY_OFFSET(fcntl_linux_specific_cmds, "F_", F_LINUX_SPECIFIC_BASE);
526 static struct strarray *fcntl_cmds_arrays[] = {
527 &strarray__fcntl_cmds,
528 &strarray__fcntl_linux_specific_cmds,
531 static DEFINE_STRARRAYS(fcntl_cmds_arrays);
533 static const char *rlimit_resources[] = {
534 "CPU", "FSIZE", "DATA", "STACK", "CORE", "RSS", "NPROC", "NOFILE",
535 "MEMLOCK", "AS", "LOCKS", "SIGPENDING", "MSGQUEUE", "NICE", "RTPRIO",
536 "RTTIME",
538 static DEFINE_STRARRAY(rlimit_resources, "RLIMIT_");
540 static const char *sighow[] = { "BLOCK", "UNBLOCK", "SETMASK", };
541 static DEFINE_STRARRAY(sighow, "SIG_");
543 static const char *clockid[] = {
544 "REALTIME", "MONOTONIC", "PROCESS_CPUTIME_ID", "THREAD_CPUTIME_ID",
545 "MONOTONIC_RAW", "REALTIME_COARSE", "MONOTONIC_COARSE", "BOOTTIME",
546 "REALTIME_ALARM", "BOOTTIME_ALARM", "SGI_CYCLE", "TAI"
548 static DEFINE_STRARRAY(clockid, "CLOCK_");
550 static size_t syscall_arg__scnprintf_access_mode(char *bf, size_t size,
551 struct syscall_arg *arg)
553 bool show_prefix = arg->show_string_prefix;
554 const char *suffix = "_OK";
555 size_t printed = 0;
556 int mode = arg->val;
558 if (mode == F_OK) /* 0 */
559 return scnprintf(bf, size, "F%s", show_prefix ? suffix : "");
560 #define P_MODE(n) \
561 if (mode & n##_OK) { \
562 printed += scnprintf(bf + printed, size - printed, "%s%s", #n, show_prefix ? suffix : ""); \
563 mode &= ~n##_OK; \
566 P_MODE(R);
567 P_MODE(W);
568 P_MODE(X);
569 #undef P_MODE
571 if (mode)
572 printed += scnprintf(bf + printed, size - printed, "|%#x", mode);
574 return printed;
577 #define SCA_ACCMODE syscall_arg__scnprintf_access_mode
579 static size_t syscall_arg__scnprintf_filename(char *bf, size_t size,
580 struct syscall_arg *arg);
582 #define SCA_FILENAME syscall_arg__scnprintf_filename
584 static size_t syscall_arg__scnprintf_pipe_flags(char *bf, size_t size,
585 struct syscall_arg *arg)
587 bool show_prefix = arg->show_string_prefix;
588 const char *prefix = "O_";
589 int printed = 0, flags = arg->val;
591 #define P_FLAG(n) \
592 if (flags & O_##n) { \
593 printed += scnprintf(bf + printed, size - printed, "%s%s%s", printed ? "|" : "", show_prefix ? prefix : "", #n); \
594 flags &= ~O_##n; \
597 P_FLAG(CLOEXEC);
598 P_FLAG(NONBLOCK);
599 #undef P_FLAG
601 if (flags)
602 printed += scnprintf(bf + printed, size - printed, "%s%#x", printed ? "|" : "", flags);
604 return printed;
607 #define SCA_PIPE_FLAGS syscall_arg__scnprintf_pipe_flags
609 #ifndef GRND_NONBLOCK
610 #define GRND_NONBLOCK 0x0001
611 #endif
612 #ifndef GRND_RANDOM
613 #define GRND_RANDOM 0x0002
614 #endif
616 static size_t syscall_arg__scnprintf_getrandom_flags(char *bf, size_t size,
617 struct syscall_arg *arg)
619 bool show_prefix = arg->show_string_prefix;
620 const char *prefix = "GRND_";
621 int printed = 0, flags = arg->val;
623 #define P_FLAG(n) \
624 if (flags & GRND_##n) { \
625 printed += scnprintf(bf + printed, size - printed, "%s%s%s", printed ? "|" : "", show_prefix ? prefix : "", #n); \
626 flags &= ~GRND_##n; \
629 P_FLAG(RANDOM);
630 P_FLAG(NONBLOCK);
631 #undef P_FLAG
633 if (flags)
634 printed += scnprintf(bf + printed, size - printed, "%s%#x", printed ? "|" : "", flags);
636 return printed;
639 #define SCA_GETRANDOM_FLAGS syscall_arg__scnprintf_getrandom_flags
641 #define STRARRAY(name, array) \
642 { .scnprintf = SCA_STRARRAY, \
643 .parm = &strarray__##array, }
645 #include "trace/beauty/arch_errno_names.c"
646 #include "trace/beauty/eventfd.c"
647 #include "trace/beauty/futex_op.c"
648 #include "trace/beauty/futex_val3.c"
649 #include "trace/beauty/mmap.c"
650 #include "trace/beauty/mode_t.c"
651 #include "trace/beauty/msg_flags.c"
652 #include "trace/beauty/open_flags.c"
653 #include "trace/beauty/perf_event_open.c"
654 #include "trace/beauty/pid.c"
655 #include "trace/beauty/sched_policy.c"
656 #include "trace/beauty/seccomp.c"
657 #include "trace/beauty/signum.c"
658 #include "trace/beauty/socket_type.c"
659 #include "trace/beauty/waitid_options.c"
661 struct syscall_arg_fmt {
662 size_t (*scnprintf)(char *bf, size_t size, struct syscall_arg *arg);
663 unsigned long (*mask_val)(struct syscall_arg *arg, unsigned long val);
664 void *parm;
665 const char *name;
666 bool show_zero;
669 static struct syscall_fmt {
670 const char *name;
671 const char *alias;
672 struct syscall_arg_fmt arg[6];
673 u8 nr_args;
674 bool errpid;
675 bool timeout;
676 bool hexret;
677 } syscall_fmts[] = {
678 { .name = "access",
679 .arg = { [1] = { .scnprintf = SCA_ACCMODE, /* mode */ }, }, },
680 { .name = "arch_prctl",
681 .arg = { [0] = { .scnprintf = SCA_X86_ARCH_PRCTL_CODE, /* code */ },
682 [1] = { .scnprintf = SCA_PTR, /* arg2 */ }, }, },
683 { .name = "bind",
684 .arg = { [1] = { .scnprintf = SCA_SOCKADDR, /* umyaddr */ }, }, },
685 { .name = "bpf",
686 .arg = { [0] = STRARRAY(cmd, bpf_cmd), }, },
687 { .name = "brk", .hexret = true,
688 .arg = { [0] = { .scnprintf = SCA_PTR, /* brk */ }, }, },
689 { .name = "clock_gettime",
690 .arg = { [0] = STRARRAY(clk_id, clockid), }, },
691 { .name = "clone", .errpid = true, .nr_args = 5,
692 .arg = { [0] = { .name = "flags", .scnprintf = SCA_CLONE_FLAGS, },
693 [1] = { .name = "child_stack", .scnprintf = SCA_HEX, },
694 [2] = { .name = "parent_tidptr", .scnprintf = SCA_HEX, },
695 [3] = { .name = "child_tidptr", .scnprintf = SCA_HEX, },
696 [4] = { .name = "tls", .scnprintf = SCA_HEX, }, }, },
697 { .name = "close",
698 .arg = { [0] = { .scnprintf = SCA_CLOSE_FD, /* fd */ }, }, },
699 { .name = "connect",
700 .arg = { [1] = { .scnprintf = SCA_SOCKADDR, /* servaddr */ }, }, },
701 { .name = "epoll_ctl",
702 .arg = { [1] = STRARRAY(op, epoll_ctl_ops), }, },
703 { .name = "eventfd2",
704 .arg = { [1] = { .scnprintf = SCA_EFD_FLAGS, /* flags */ }, }, },
705 { .name = "fchmodat",
706 .arg = { [0] = { .scnprintf = SCA_FDAT, /* fd */ }, }, },
707 { .name = "fchownat",
708 .arg = { [0] = { .scnprintf = SCA_FDAT, /* fd */ }, }, },
709 { .name = "fcntl",
710 .arg = { [1] = { .scnprintf = SCA_FCNTL_CMD, /* cmd */
711 .parm = &strarrays__fcntl_cmds_arrays,
712 .show_zero = true, },
713 [2] = { .scnprintf = SCA_FCNTL_ARG, /* arg */ }, }, },
714 { .name = "flock",
715 .arg = { [1] = { .scnprintf = SCA_FLOCK, /* cmd */ }, }, },
716 { .name = "fstat", .alias = "newfstat", },
717 { .name = "fstatat", .alias = "newfstatat", },
718 { .name = "futex",
719 .arg = { [1] = { .scnprintf = SCA_FUTEX_OP, /* op */ },
720 [5] = { .scnprintf = SCA_FUTEX_VAL3, /* val3 */ }, }, },
721 { .name = "futimesat",
722 .arg = { [0] = { .scnprintf = SCA_FDAT, /* fd */ }, }, },
723 { .name = "getitimer",
724 .arg = { [0] = STRARRAY(which, itimers), }, },
725 { .name = "getpid", .errpid = true, },
726 { .name = "getpgid", .errpid = true, },
727 { .name = "getppid", .errpid = true, },
728 { .name = "getrandom",
729 .arg = { [2] = { .scnprintf = SCA_GETRANDOM_FLAGS, /* flags */ }, }, },
730 { .name = "getrlimit",
731 .arg = { [0] = STRARRAY(resource, rlimit_resources), }, },
732 { .name = "gettid", .errpid = true, },
733 { .name = "ioctl",
734 .arg = {
735 #if defined(__i386__) || defined(__x86_64__)
737 * FIXME: Make this available to all arches.
739 [1] = { .scnprintf = SCA_IOCTL_CMD, /* cmd */ },
740 [2] = { .scnprintf = SCA_HEX, /* arg */ }, }, },
741 #else
742 [2] = { .scnprintf = SCA_HEX, /* arg */ }, }, },
743 #endif
744 { .name = "kcmp", .nr_args = 5,
745 .arg = { [0] = { .name = "pid1", .scnprintf = SCA_PID, },
746 [1] = { .name = "pid2", .scnprintf = SCA_PID, },
747 [2] = { .name = "type", .scnprintf = SCA_KCMP_TYPE, },
748 [3] = { .name = "idx1", .scnprintf = SCA_KCMP_IDX, },
749 [4] = { .name = "idx2", .scnprintf = SCA_KCMP_IDX, }, }, },
750 { .name = "keyctl",
751 .arg = { [0] = STRARRAY(option, keyctl_options), }, },
752 { .name = "kill",
753 .arg = { [1] = { .scnprintf = SCA_SIGNUM, /* sig */ }, }, },
754 { .name = "linkat",
755 .arg = { [0] = { .scnprintf = SCA_FDAT, /* fd */ }, }, },
756 { .name = "lseek",
757 .arg = { [2] = STRARRAY(whence, whences), }, },
758 { .name = "lstat", .alias = "newlstat", },
759 { .name = "madvise",
760 .arg = { [0] = { .scnprintf = SCA_HEX, /* start */ },
761 [2] = { .scnprintf = SCA_MADV_BHV, /* behavior */ }, }, },
762 { .name = "mkdirat",
763 .arg = { [0] = { .scnprintf = SCA_FDAT, /* fd */ }, }, },
764 { .name = "mknodat",
765 .arg = { [0] = { .scnprintf = SCA_FDAT, /* fd */ }, }, },
766 { .name = "mmap", .hexret = true,
767 /* The standard mmap maps to old_mmap on s390x */
768 #if defined(__s390x__)
769 .alias = "old_mmap",
770 #endif
771 .arg = { [2] = { .scnprintf = SCA_MMAP_PROT, /* prot */ },
772 [3] = { .scnprintf = SCA_MMAP_FLAGS, /* flags */ },
773 [5] = { .scnprintf = SCA_HEX, /* offset */ }, }, },
774 { .name = "mount",
775 .arg = { [0] = { .scnprintf = SCA_FILENAME, /* dev_name */ },
776 [3] = { .scnprintf = SCA_MOUNT_FLAGS, /* flags */
777 .mask_val = SCAMV_MOUNT_FLAGS, /* flags */ }, }, },
778 { .name = "mprotect",
779 .arg = { [0] = { .scnprintf = SCA_HEX, /* start */ },
780 [2] = { .scnprintf = SCA_MMAP_PROT, /* prot */ }, }, },
781 { .name = "mq_unlink",
782 .arg = { [0] = { .scnprintf = SCA_FILENAME, /* u_name */ }, }, },
783 { .name = "mremap", .hexret = true,
784 .arg = { [3] = { .scnprintf = SCA_MREMAP_FLAGS, /* flags */ }, }, },
785 { .name = "name_to_handle_at",
786 .arg = { [0] = { .scnprintf = SCA_FDAT, /* dfd */ }, }, },
787 { .name = "newfstatat",
788 .arg = { [0] = { .scnprintf = SCA_FDAT, /* dfd */ }, }, },
789 { .name = "open",
790 .arg = { [1] = { .scnprintf = SCA_OPEN_FLAGS, /* flags */ }, }, },
791 { .name = "open_by_handle_at",
792 .arg = { [0] = { .scnprintf = SCA_FDAT, /* dfd */ },
793 [2] = { .scnprintf = SCA_OPEN_FLAGS, /* flags */ }, }, },
794 { .name = "openat",
795 .arg = { [0] = { .scnprintf = SCA_FDAT, /* dfd */ },
796 [2] = { .scnprintf = SCA_OPEN_FLAGS, /* flags */ }, }, },
797 { .name = "perf_event_open",
798 .arg = { [2] = { .scnprintf = SCA_INT, /* cpu */ },
799 [3] = { .scnprintf = SCA_FD, /* group_fd */ },
800 [4] = { .scnprintf = SCA_PERF_FLAGS, /* flags */ }, }, },
801 { .name = "pipe2",
802 .arg = { [1] = { .scnprintf = SCA_PIPE_FLAGS, /* flags */ }, }, },
803 { .name = "pkey_alloc",
804 .arg = { [1] = { .scnprintf = SCA_PKEY_ALLOC_ACCESS_RIGHTS, /* access_rights */ }, }, },
805 { .name = "pkey_free",
806 .arg = { [0] = { .scnprintf = SCA_INT, /* key */ }, }, },
807 { .name = "pkey_mprotect",
808 .arg = { [0] = { .scnprintf = SCA_HEX, /* start */ },
809 [2] = { .scnprintf = SCA_MMAP_PROT, /* prot */ },
810 [3] = { .scnprintf = SCA_INT, /* pkey */ }, }, },
811 { .name = "poll", .timeout = true, },
812 { .name = "ppoll", .timeout = true, },
813 { .name = "prctl",
814 .arg = { [0] = { .scnprintf = SCA_PRCTL_OPTION, /* option */ },
815 [1] = { .scnprintf = SCA_PRCTL_ARG2, /* arg2 */ },
816 [2] = { .scnprintf = SCA_PRCTL_ARG3, /* arg3 */ }, }, },
817 { .name = "pread", .alias = "pread64", },
818 { .name = "preadv", .alias = "pread", },
819 { .name = "prlimit64",
820 .arg = { [1] = STRARRAY(resource, rlimit_resources), }, },
821 { .name = "pwrite", .alias = "pwrite64", },
822 { .name = "readlinkat",
823 .arg = { [0] = { .scnprintf = SCA_FDAT, /* dfd */ }, }, },
824 { .name = "recvfrom",
825 .arg = { [3] = { .scnprintf = SCA_MSG_FLAGS, /* flags */ }, }, },
826 { .name = "recvmmsg",
827 .arg = { [3] = { .scnprintf = SCA_MSG_FLAGS, /* flags */ }, }, },
828 { .name = "recvmsg",
829 .arg = { [2] = { .scnprintf = SCA_MSG_FLAGS, /* flags */ }, }, },
830 { .name = "renameat",
831 .arg = { [0] = { .scnprintf = SCA_FDAT, /* olddirfd */ },
832 [2] = { .scnprintf = SCA_FDAT, /* newdirfd */ }, }, },
833 { .name = "renameat2",
834 .arg = { [0] = { .scnprintf = SCA_FDAT, /* olddirfd */ },
835 [2] = { .scnprintf = SCA_FDAT, /* newdirfd */ },
836 [4] = { .scnprintf = SCA_RENAMEAT2_FLAGS, /* flags */ }, }, },
837 { .name = "rt_sigaction",
838 .arg = { [0] = { .scnprintf = SCA_SIGNUM, /* sig */ }, }, },
839 { .name = "rt_sigprocmask",
840 .arg = { [0] = STRARRAY(how, sighow), }, },
841 { .name = "rt_sigqueueinfo",
842 .arg = { [1] = { .scnprintf = SCA_SIGNUM, /* sig */ }, }, },
843 { .name = "rt_tgsigqueueinfo",
844 .arg = { [2] = { .scnprintf = SCA_SIGNUM, /* sig */ }, }, },
845 { .name = "sched_setscheduler",
846 .arg = { [1] = { .scnprintf = SCA_SCHED_POLICY, /* policy */ }, }, },
847 { .name = "seccomp",
848 .arg = { [0] = { .scnprintf = SCA_SECCOMP_OP, /* op */ },
849 [1] = { .scnprintf = SCA_SECCOMP_FLAGS, /* flags */ }, }, },
850 { .name = "select", .timeout = true, },
851 { .name = "sendmmsg",
852 .arg = { [3] = { .scnprintf = SCA_MSG_FLAGS, /* flags */ }, }, },
853 { .name = "sendmsg",
854 .arg = { [2] = { .scnprintf = SCA_MSG_FLAGS, /* flags */ }, }, },
855 { .name = "sendto",
856 .arg = { [3] = { .scnprintf = SCA_MSG_FLAGS, /* flags */ },
857 [4] = { .scnprintf = SCA_SOCKADDR, /* addr */ }, }, },
858 { .name = "set_tid_address", .errpid = true, },
859 { .name = "setitimer",
860 .arg = { [0] = STRARRAY(which, itimers), }, },
861 { .name = "setrlimit",
862 .arg = { [0] = STRARRAY(resource, rlimit_resources), }, },
863 { .name = "socket",
864 .arg = { [0] = STRARRAY(family, socket_families),
865 [1] = { .scnprintf = SCA_SK_TYPE, /* type */ },
866 [2] = { .scnprintf = SCA_SK_PROTO, /* protocol */ }, }, },
867 { .name = "socketpair",
868 .arg = { [0] = STRARRAY(family, socket_families),
869 [1] = { .scnprintf = SCA_SK_TYPE, /* type */ },
870 [2] = { .scnprintf = SCA_SK_PROTO, /* protocol */ }, }, },
871 { .name = "stat", .alias = "newstat", },
872 { .name = "statx",
873 .arg = { [0] = { .scnprintf = SCA_FDAT, /* fdat */ },
874 [2] = { .scnprintf = SCA_STATX_FLAGS, /* flags */ } ,
875 [3] = { .scnprintf = SCA_STATX_MASK, /* mask */ }, }, },
876 { .name = "swapoff",
877 .arg = { [0] = { .scnprintf = SCA_FILENAME, /* specialfile */ }, }, },
878 { .name = "swapon",
879 .arg = { [0] = { .scnprintf = SCA_FILENAME, /* specialfile */ }, }, },
880 { .name = "symlinkat",
881 .arg = { [0] = { .scnprintf = SCA_FDAT, /* dfd */ }, }, },
882 { .name = "tgkill",
883 .arg = { [2] = { .scnprintf = SCA_SIGNUM, /* sig */ }, }, },
884 { .name = "tkill",
885 .arg = { [1] = { .scnprintf = SCA_SIGNUM, /* sig */ }, }, },
886 { .name = "umount2", .alias = "umount",
887 .arg = { [0] = { .scnprintf = SCA_FILENAME, /* name */ }, }, },
888 { .name = "uname", .alias = "newuname", },
889 { .name = "unlinkat",
890 .arg = { [0] = { .scnprintf = SCA_FDAT, /* dfd */ }, }, },
891 { .name = "utimensat",
892 .arg = { [0] = { .scnprintf = SCA_FDAT, /* dirfd */ }, }, },
893 { .name = "wait4", .errpid = true,
894 .arg = { [2] = { .scnprintf = SCA_WAITID_OPTIONS, /* options */ }, }, },
895 { .name = "waitid", .errpid = true,
896 .arg = { [3] = { .scnprintf = SCA_WAITID_OPTIONS, /* options */ }, }, },
899 static int syscall_fmt__cmp(const void *name, const void *fmtp)
901 const struct syscall_fmt *fmt = fmtp;
902 return strcmp(name, fmt->name);
905 static struct syscall_fmt *syscall_fmt__find(const char *name)
907 const int nmemb = ARRAY_SIZE(syscall_fmts);
908 return bsearch(name, syscall_fmts, nmemb, sizeof(struct syscall_fmt), syscall_fmt__cmp);
911 static struct syscall_fmt *syscall_fmt__find_by_alias(const char *alias)
913 int i, nmemb = ARRAY_SIZE(syscall_fmts);
915 for (i = 0; i < nmemb; ++i) {
916 if (syscall_fmts[i].alias && strcmp(syscall_fmts[i].alias, alias) == 0)
917 return &syscall_fmts[i];
920 return NULL;
924 * is_exit: is this "exit" or "exit_group"?
925 * is_open: is this "open" or "openat"? To associate the fd returned in sys_exit with the pathname in sys_enter.
926 * args_size: sum of the sizes of the syscall arguments, anything after that is augmented stuff: pathname for openat, etc.
928 struct syscall {
929 struct tep_event *tp_format;
930 int nr_args;
931 int args_size;
932 bool is_exit;
933 bool is_open;
934 struct tep_format_field *args;
935 const char *name;
936 struct syscall_fmt *fmt;
937 struct syscall_arg_fmt *arg_fmt;
940 struct bpf_map_syscall_entry {
941 bool enabled;
945 * We need to have this 'calculated' boolean because in some cases we really
946 * don't know what is the duration of a syscall, for instance, when we start
947 * a session and some threads are waiting for a syscall to finish, say 'poll',
948 * in which case all we can do is to print "( ? ) for duration and for the
949 * start timestamp.
951 static size_t fprintf_duration(unsigned long t, bool calculated, FILE *fp)
953 double duration = (double)t / NSEC_PER_MSEC;
954 size_t printed = fprintf(fp, "(");
956 if (!calculated)
957 printed += fprintf(fp, " ");
958 else if (duration >= 1.0)
959 printed += color_fprintf(fp, PERF_COLOR_RED, "%6.3f ms", duration);
960 else if (duration >= 0.01)
961 printed += color_fprintf(fp, PERF_COLOR_YELLOW, "%6.3f ms", duration);
962 else
963 printed += color_fprintf(fp, PERF_COLOR_NORMAL, "%6.3f ms", duration);
964 return printed + fprintf(fp, "): ");
968 * filename.ptr: The filename char pointer that will be vfs_getname'd
969 * filename.entry_str_pos: Where to insert the string translated from
970 * filename.ptr by the vfs_getname tracepoint/kprobe.
971 * ret_scnprintf: syscall args may set this to a different syscall return
972 * formatter, for instance, fcntl may return fds, file flags, etc.
974 struct thread_trace {
975 u64 entry_time;
976 bool entry_pending;
977 unsigned long nr_events;
978 unsigned long pfmaj, pfmin;
979 char *entry_str;
980 double runtime_ms;
981 size_t (*ret_scnprintf)(char *bf, size_t size, struct syscall_arg *arg);
982 struct {
983 unsigned long ptr;
984 short int entry_str_pos;
985 bool pending_open;
986 unsigned int namelen;
987 char *name;
988 } filename;
989 struct {
990 int max;
991 struct file *table;
992 } files;
994 struct intlist *syscall_stats;
997 static struct thread_trace *thread_trace__new(void)
999 struct thread_trace *ttrace = zalloc(sizeof(struct thread_trace));
1001 if (ttrace)
1002 ttrace->files.max = -1;
1004 ttrace->syscall_stats = intlist__new(NULL);
1006 return ttrace;
1009 static struct thread_trace *thread__trace(struct thread *thread, FILE *fp)
1011 struct thread_trace *ttrace;
1013 if (thread == NULL)
1014 goto fail;
1016 if (thread__priv(thread) == NULL)
1017 thread__set_priv(thread, thread_trace__new());
1019 if (thread__priv(thread) == NULL)
1020 goto fail;
1022 ttrace = thread__priv(thread);
1023 ++ttrace->nr_events;
1025 return ttrace;
1026 fail:
1027 color_fprintf(fp, PERF_COLOR_RED,
1028 "WARNING: not enough memory, dropping samples!\n");
1029 return NULL;
1033 void syscall_arg__set_ret_scnprintf(struct syscall_arg *arg,
1034 size_t (*ret_scnprintf)(char *bf, size_t size, struct syscall_arg *arg))
1036 struct thread_trace *ttrace = thread__priv(arg->thread);
1038 ttrace->ret_scnprintf = ret_scnprintf;
1041 #define TRACE_PFMAJ (1 << 0)
1042 #define TRACE_PFMIN (1 << 1)
1044 static const size_t trace__entry_str_size = 2048;
1046 static struct file *thread_trace__files_entry(struct thread_trace *ttrace, int fd)
1048 if (fd < 0)
1049 return NULL;
1051 if (fd > ttrace->files.max) {
1052 struct file *nfiles = realloc(ttrace->files.table, (fd + 1) * sizeof(struct file));
1054 if (nfiles == NULL)
1055 return NULL;
1057 if (ttrace->files.max != -1) {
1058 memset(nfiles + ttrace->files.max + 1, 0,
1059 (fd - ttrace->files.max) * sizeof(struct file));
1060 } else {
1061 memset(nfiles, 0, (fd + 1) * sizeof(struct file));
1064 ttrace->files.table = nfiles;
1065 ttrace->files.max = fd;
1068 return ttrace->files.table + fd;
1071 struct file *thread__files_entry(struct thread *thread, int fd)
1073 return thread_trace__files_entry(thread__priv(thread), fd);
1076 static int trace__set_fd_pathname(struct thread *thread, int fd, const char *pathname)
1078 struct thread_trace *ttrace = thread__priv(thread);
1079 struct file *file = thread_trace__files_entry(ttrace, fd);
1081 if (file != NULL) {
1082 struct stat st;
1083 if (stat(pathname, &st) == 0)
1084 file->dev_maj = major(st.st_rdev);
1085 file->pathname = strdup(pathname);
1086 if (file->pathname)
1087 return 0;
1090 return -1;
1093 static int thread__read_fd_path(struct thread *thread, int fd)
1095 char linkname[PATH_MAX], pathname[PATH_MAX];
1096 struct stat st;
1097 int ret;
1099 if (thread->pid_ == thread->tid) {
1100 scnprintf(linkname, sizeof(linkname),
1101 "/proc/%d/fd/%d", thread->pid_, fd);
1102 } else {
1103 scnprintf(linkname, sizeof(linkname),
1104 "/proc/%d/task/%d/fd/%d", thread->pid_, thread->tid, fd);
1107 if (lstat(linkname, &st) < 0 || st.st_size + 1 > (off_t)sizeof(pathname))
1108 return -1;
1110 ret = readlink(linkname, pathname, sizeof(pathname));
1112 if (ret < 0 || ret > st.st_size)
1113 return -1;
1115 pathname[ret] = '\0';
1116 return trace__set_fd_pathname(thread, fd, pathname);
1119 static const char *thread__fd_path(struct thread *thread, int fd,
1120 struct trace *trace)
1122 struct thread_trace *ttrace = thread__priv(thread);
1124 if (ttrace == NULL)
1125 return NULL;
1127 if (fd < 0)
1128 return NULL;
1130 if ((fd > ttrace->files.max || ttrace->files.table[fd].pathname == NULL)) {
1131 if (!trace->live)
1132 return NULL;
1133 ++trace->stats.proc_getname;
1134 if (thread__read_fd_path(thread, fd))
1135 return NULL;
1138 return ttrace->files.table[fd].pathname;
1141 size_t syscall_arg__scnprintf_fd(char *bf, size_t size, struct syscall_arg *arg)
1143 int fd = arg->val;
1144 size_t printed = scnprintf(bf, size, "%d", fd);
1145 const char *path = thread__fd_path(arg->thread, fd, arg->trace);
1147 if (path)
1148 printed += scnprintf(bf + printed, size - printed, "<%s>", path);
1150 return printed;
1153 size_t pid__scnprintf_fd(struct trace *trace, pid_t pid, int fd, char *bf, size_t size)
1155 size_t printed = scnprintf(bf, size, "%d", fd);
1156 struct thread *thread = machine__find_thread(trace->host, pid, pid);
1158 if (thread) {
1159 const char *path = thread__fd_path(thread, fd, trace);
1161 if (path)
1162 printed += scnprintf(bf + printed, size - printed, "<%s>", path);
1164 thread__put(thread);
1167 return printed;
1170 static size_t syscall_arg__scnprintf_close_fd(char *bf, size_t size,
1171 struct syscall_arg *arg)
1173 int fd = arg->val;
1174 size_t printed = syscall_arg__scnprintf_fd(bf, size, arg);
1175 struct thread_trace *ttrace = thread__priv(arg->thread);
1177 if (ttrace && fd >= 0 && fd <= ttrace->files.max)
1178 zfree(&ttrace->files.table[fd].pathname);
1180 return printed;
1183 static void thread__set_filename_pos(struct thread *thread, const char *bf,
1184 unsigned long ptr)
1186 struct thread_trace *ttrace = thread__priv(thread);
1188 ttrace->filename.ptr = ptr;
1189 ttrace->filename.entry_str_pos = bf - ttrace->entry_str;
1192 static size_t syscall_arg__scnprintf_augmented_string(struct syscall_arg *arg, char *bf, size_t size)
1194 struct augmented_arg *augmented_arg = arg->augmented.args;
1196 return scnprintf(bf, size, "\"%.*s\"", augmented_arg->size, augmented_arg->value);
1199 static size_t syscall_arg__scnprintf_filename(char *bf, size_t size,
1200 struct syscall_arg *arg)
1202 unsigned long ptr = arg->val;
1204 if (arg->augmented.args)
1205 return syscall_arg__scnprintf_augmented_string(arg, bf, size);
1207 if (!arg->trace->vfs_getname)
1208 return scnprintf(bf, size, "%#x", ptr);
1210 thread__set_filename_pos(arg->thread, bf, ptr);
1211 return 0;
1214 static bool trace__filter_duration(struct trace *trace, double t)
1216 return t < (trace->duration_filter * NSEC_PER_MSEC);
1219 static size_t __trace__fprintf_tstamp(struct trace *trace, u64 tstamp, FILE *fp)
1221 double ts = (double)(tstamp - trace->base_time) / NSEC_PER_MSEC;
1223 return fprintf(fp, "%10.3f ", ts);
1227 * We're handling tstamp=0 as an undefined tstamp, i.e. like when we are
1228 * using ttrace->entry_time for a thread that receives a sys_exit without
1229 * first having received a sys_enter ("poll" issued before tracing session
1230 * starts, lost sys_enter exit due to ring buffer overflow).
1232 static size_t trace__fprintf_tstamp(struct trace *trace, u64 tstamp, FILE *fp)
1234 if (tstamp > 0)
1235 return __trace__fprintf_tstamp(trace, tstamp, fp);
1237 return fprintf(fp, " ? ");
1240 static bool done = false;
1241 static bool interrupted = false;
1243 static void sig_handler(int sig)
1245 done = true;
1246 interrupted = sig == SIGINT;
1249 static size_t trace__fprintf_comm_tid(struct trace *trace, struct thread *thread, FILE *fp)
1251 size_t printed = 0;
1253 if (trace->multiple_threads) {
1254 if (trace->show_comm)
1255 printed += fprintf(fp, "%.14s/", thread__comm_str(thread));
1256 printed += fprintf(fp, "%d ", thread->tid);
1259 return printed;
1262 static size_t trace__fprintf_entry_head(struct trace *trace, struct thread *thread,
1263 u64 duration, bool duration_calculated, u64 tstamp, FILE *fp)
1265 size_t printed = 0;
1267 if (trace->show_tstamp)
1268 printed = trace__fprintf_tstamp(trace, tstamp, fp);
1269 if (trace->show_duration)
1270 printed += fprintf_duration(duration, duration_calculated, fp);
1271 return printed + trace__fprintf_comm_tid(trace, thread, fp);
1274 static int trace__process_event(struct trace *trace, struct machine *machine,
1275 union perf_event *event, struct perf_sample *sample)
1277 int ret = 0;
1279 switch (event->header.type) {
1280 case PERF_RECORD_LOST:
1281 color_fprintf(trace->output, PERF_COLOR_RED,
1282 "LOST %" PRIu64 " events!\n", event->lost.lost);
1283 ret = machine__process_lost_event(machine, event, sample);
1284 break;
1285 default:
1286 ret = machine__process_event(machine, event, sample);
1287 break;
1290 return ret;
1293 static int trace__tool_process(struct perf_tool *tool,
1294 union perf_event *event,
1295 struct perf_sample *sample,
1296 struct machine *machine)
1298 struct trace *trace = container_of(tool, struct trace, tool);
1299 return trace__process_event(trace, machine, event, sample);
1302 static char *trace__machine__resolve_kernel_addr(void *vmachine, unsigned long long *addrp, char **modp)
1304 struct machine *machine = vmachine;
1306 if (machine->kptr_restrict_warned)
1307 return NULL;
1309 if (symbol_conf.kptr_restrict) {
1310 pr_warning("Kernel address maps (/proc/{kallsyms,modules}) are restricted.\n\n"
1311 "Check /proc/sys/kernel/kptr_restrict.\n\n"
1312 "Kernel samples will not be resolved.\n");
1313 machine->kptr_restrict_warned = true;
1314 return NULL;
1317 return machine__resolve_kernel_addr(vmachine, addrp, modp);
1320 static int trace__symbols_init(struct trace *trace, struct perf_evlist *evlist)
1322 int err = symbol__init(NULL);
1324 if (err)
1325 return err;
1327 trace->host = machine__new_host();
1328 if (trace->host == NULL)
1329 return -ENOMEM;
1331 err = trace_event__register_resolver(trace->host, trace__machine__resolve_kernel_addr);
1332 if (err < 0)
1333 goto out;
1335 err = __machine__synthesize_threads(trace->host, &trace->tool, &trace->opts.target,
1336 evlist->threads, trace__tool_process, false,
1338 out:
1339 if (err)
1340 symbol__exit();
1342 return err;
1345 static void trace__symbols__exit(struct trace *trace)
1347 machine__exit(trace->host);
1348 trace->host = NULL;
1350 symbol__exit();
1353 static int syscall__alloc_arg_fmts(struct syscall *sc, int nr_args)
1355 int idx;
1357 if (nr_args == 6 && sc->fmt && sc->fmt->nr_args != 0)
1358 nr_args = sc->fmt->nr_args;
1360 sc->arg_fmt = calloc(nr_args, sizeof(*sc->arg_fmt));
1361 if (sc->arg_fmt == NULL)
1362 return -1;
1364 for (idx = 0; idx < nr_args; ++idx) {
1365 if (sc->fmt)
1366 sc->arg_fmt[idx] = sc->fmt->arg[idx];
1369 sc->nr_args = nr_args;
1370 return 0;
1373 static int syscall__set_arg_fmts(struct syscall *sc)
1375 struct tep_format_field *field, *last_field = NULL;
1376 int idx = 0, len;
1378 for (field = sc->args; field; field = field->next, ++idx) {
1379 last_field = field;
1381 if (sc->fmt && sc->fmt->arg[idx].scnprintf)
1382 continue;
1384 if (strcmp(field->type, "const char *") == 0 &&
1385 (strcmp(field->name, "filename") == 0 ||
1386 strcmp(field->name, "path") == 0 ||
1387 strcmp(field->name, "pathname") == 0))
1388 sc->arg_fmt[idx].scnprintf = SCA_FILENAME;
1389 else if ((field->flags & TEP_FIELD_IS_POINTER) || strstr(field->name, "addr"))
1390 sc->arg_fmt[idx].scnprintf = SCA_PTR;
1391 else if (strcmp(field->type, "pid_t") == 0)
1392 sc->arg_fmt[idx].scnprintf = SCA_PID;
1393 else if (strcmp(field->type, "umode_t") == 0)
1394 sc->arg_fmt[idx].scnprintf = SCA_MODE_T;
1395 else if ((strcmp(field->type, "int") == 0 ||
1396 strcmp(field->type, "unsigned int") == 0 ||
1397 strcmp(field->type, "long") == 0) &&
1398 (len = strlen(field->name)) >= 2 &&
1399 strcmp(field->name + len - 2, "fd") == 0) {
1401 * /sys/kernel/tracing/events/syscalls/sys_enter*
1402 * egrep 'field:.*fd;' .../format|sed -r 's/.*field:([a-z ]+) [a-z_]*fd.+/\1/g'|sort|uniq -c
1403 * 65 int
1404 * 23 unsigned int
1405 * 7 unsigned long
1407 sc->arg_fmt[idx].scnprintf = SCA_FD;
1411 if (last_field)
1412 sc->args_size = last_field->offset + last_field->size;
1414 return 0;
1417 static int trace__read_syscall_info(struct trace *trace, int id)
1419 char tp_name[128];
1420 struct syscall *sc;
1421 const char *name = syscalltbl__name(trace->sctbl, id);
1423 if (name == NULL)
1424 return -1;
1426 if (id > trace->syscalls.max) {
1427 struct syscall *nsyscalls = realloc(trace->syscalls.table, (id + 1) * sizeof(*sc));
1429 if (nsyscalls == NULL)
1430 return -1;
1432 if (trace->syscalls.max != -1) {
1433 memset(nsyscalls + trace->syscalls.max + 1, 0,
1434 (id - trace->syscalls.max) * sizeof(*sc));
1435 } else {
1436 memset(nsyscalls, 0, (id + 1) * sizeof(*sc));
1439 trace->syscalls.table = nsyscalls;
1440 trace->syscalls.max = id;
1443 sc = trace->syscalls.table + id;
1444 sc->name = name;
1446 sc->fmt = syscall_fmt__find(sc->name);
1448 snprintf(tp_name, sizeof(tp_name), "sys_enter_%s", sc->name);
1449 sc->tp_format = trace_event__tp_format("syscalls", tp_name);
1451 if (IS_ERR(sc->tp_format) && sc->fmt && sc->fmt->alias) {
1452 snprintf(tp_name, sizeof(tp_name), "sys_enter_%s", sc->fmt->alias);
1453 sc->tp_format = trace_event__tp_format("syscalls", tp_name);
1456 if (syscall__alloc_arg_fmts(sc, IS_ERR(sc->tp_format) ? 6 : sc->tp_format->format.nr_fields))
1457 return -1;
1459 if (IS_ERR(sc->tp_format))
1460 return -1;
1462 sc->args = sc->tp_format->format.fields;
1464 * We need to check and discard the first variable '__syscall_nr'
1465 * or 'nr' that mean the syscall number. It is needless here.
1466 * So drop '__syscall_nr' or 'nr' field but does not exist on older kernels.
1468 if (sc->args && (!strcmp(sc->args->name, "__syscall_nr") || !strcmp(sc->args->name, "nr"))) {
1469 sc->args = sc->args->next;
1470 --sc->nr_args;
1473 sc->is_exit = !strcmp(name, "exit_group") || !strcmp(name, "exit");
1474 sc->is_open = !strcmp(name, "open") || !strcmp(name, "openat");
1476 return syscall__set_arg_fmts(sc);
1479 static int trace__validate_ev_qualifier(struct trace *trace)
1481 int err = 0, i;
1482 size_t nr_allocated;
1483 struct str_node *pos;
1485 trace->ev_qualifier_ids.nr = strlist__nr_entries(trace->ev_qualifier);
1486 trace->ev_qualifier_ids.entries = malloc(trace->ev_qualifier_ids.nr *
1487 sizeof(trace->ev_qualifier_ids.entries[0]));
1489 if (trace->ev_qualifier_ids.entries == NULL) {
1490 fputs("Error:\tNot enough memory for allocating events qualifier ids\n",
1491 trace->output);
1492 err = -EINVAL;
1493 goto out;
1496 nr_allocated = trace->ev_qualifier_ids.nr;
1497 i = 0;
1499 strlist__for_each_entry(pos, trace->ev_qualifier) {
1500 const char *sc = pos->s;
1501 int id = syscalltbl__id(trace->sctbl, sc), match_next = -1;
1503 if (id < 0) {
1504 id = syscalltbl__strglobmatch_first(trace->sctbl, sc, &match_next);
1505 if (id >= 0)
1506 goto matches;
1508 if (err == 0) {
1509 fputs("Error:\tInvalid syscall ", trace->output);
1510 err = -EINVAL;
1511 } else {
1512 fputs(", ", trace->output);
1515 fputs(sc, trace->output);
1517 matches:
1518 trace->ev_qualifier_ids.entries[i++] = id;
1519 if (match_next == -1)
1520 continue;
1522 while (1) {
1523 id = syscalltbl__strglobmatch_next(trace->sctbl, sc, &match_next);
1524 if (id < 0)
1525 break;
1526 if (nr_allocated == trace->ev_qualifier_ids.nr) {
1527 void *entries;
1529 nr_allocated += 8;
1530 entries = realloc(trace->ev_qualifier_ids.entries,
1531 nr_allocated * sizeof(trace->ev_qualifier_ids.entries[0]));
1532 if (entries == NULL) {
1533 err = -ENOMEM;
1534 fputs("\nError:\t Not enough memory for parsing\n", trace->output);
1535 goto out_free;
1537 trace->ev_qualifier_ids.entries = entries;
1539 trace->ev_qualifier_ids.nr++;
1540 trace->ev_qualifier_ids.entries[i++] = id;
1544 if (err < 0) {
1545 fputs("\nHint:\ttry 'perf list syscalls:sys_enter_*'"
1546 "\nHint:\tand: 'man syscalls'\n", trace->output);
1547 out_free:
1548 zfree(&trace->ev_qualifier_ids.entries);
1549 trace->ev_qualifier_ids.nr = 0;
1551 out:
1552 return err;
1556 * args is to be interpreted as a series of longs but we need to handle
1557 * 8-byte unaligned accesses. args points to raw_data within the event
1558 * and raw_data is guaranteed to be 8-byte unaligned because it is
1559 * preceded by raw_size which is a u32. So we need to copy args to a temp
1560 * variable to read it. Most notably this avoids extended load instructions
1561 * on unaligned addresses
1563 unsigned long syscall_arg__val(struct syscall_arg *arg, u8 idx)
1565 unsigned long val;
1566 unsigned char *p = arg->args + sizeof(unsigned long) * idx;
1568 memcpy(&val, p, sizeof(val));
1569 return val;
1572 static size_t syscall__scnprintf_name(struct syscall *sc, char *bf, size_t size,
1573 struct syscall_arg *arg)
1575 if (sc->arg_fmt && sc->arg_fmt[arg->idx].name)
1576 return scnprintf(bf, size, "%s: ", sc->arg_fmt[arg->idx].name);
1578 return scnprintf(bf, size, "arg%d: ", arg->idx);
1582 * Check if the value is in fact zero, i.e. mask whatever needs masking, such
1583 * as mount 'flags' argument that needs ignoring some magic flag, see comment
1584 * in tools/perf/trace/beauty/mount_flags.c
1586 static unsigned long syscall__mask_val(struct syscall *sc, struct syscall_arg *arg, unsigned long val)
1588 if (sc->arg_fmt && sc->arg_fmt[arg->idx].mask_val)
1589 return sc->arg_fmt[arg->idx].mask_val(arg, val);
1591 return val;
1594 static size_t syscall__scnprintf_val(struct syscall *sc, char *bf, size_t size,
1595 struct syscall_arg *arg, unsigned long val)
1597 if (sc->arg_fmt && sc->arg_fmt[arg->idx].scnprintf) {
1598 arg->val = val;
1599 if (sc->arg_fmt[arg->idx].parm)
1600 arg->parm = sc->arg_fmt[arg->idx].parm;
1601 return sc->arg_fmt[arg->idx].scnprintf(bf, size, arg);
1603 return scnprintf(bf, size, "%ld", val);
1606 static size_t syscall__scnprintf_args(struct syscall *sc, char *bf, size_t size,
1607 unsigned char *args, void *augmented_args, int augmented_args_size,
1608 struct trace *trace, struct thread *thread)
1610 size_t printed = 0;
1611 unsigned long val;
1612 u8 bit = 1;
1613 struct syscall_arg arg = {
1614 .args = args,
1615 .augmented = {
1616 .size = augmented_args_size,
1617 .args = augmented_args,
1619 .idx = 0,
1620 .mask = 0,
1621 .trace = trace,
1622 .thread = thread,
1623 .show_string_prefix = trace->show_string_prefix,
1625 struct thread_trace *ttrace = thread__priv(thread);
1628 * Things like fcntl will set this in its 'cmd' formatter to pick the
1629 * right formatter for the return value (an fd? file flags?), which is
1630 * not needed for syscalls that always return a given type, say an fd.
1632 ttrace->ret_scnprintf = NULL;
1634 if (sc->args != NULL) {
1635 struct tep_format_field *field;
1637 for (field = sc->args; field;
1638 field = field->next, ++arg.idx, bit <<= 1) {
1639 if (arg.mask & bit)
1640 continue;
1642 val = syscall_arg__val(&arg, arg.idx);
1644 * Some syscall args need some mask, most don't and
1645 * return val untouched.
1647 val = syscall__mask_val(sc, &arg, val);
1650 * Suppress this argument if its value is zero and
1651 * and we don't have a string associated in an
1652 * strarray for it.
1654 if (val == 0 &&
1655 !trace->show_zeros &&
1656 !(sc->arg_fmt &&
1657 (sc->arg_fmt[arg.idx].show_zero ||
1658 sc->arg_fmt[arg.idx].scnprintf == SCA_STRARRAY ||
1659 sc->arg_fmt[arg.idx].scnprintf == SCA_STRARRAYS) &&
1660 sc->arg_fmt[arg.idx].parm))
1661 continue;
1663 printed += scnprintf(bf + printed, size - printed, "%s", printed ? ", " : "");
1665 if (trace->show_arg_names)
1666 printed += scnprintf(bf + printed, size - printed, "%s: ", field->name);
1668 printed += syscall__scnprintf_val(sc, bf + printed, size - printed, &arg, val);
1670 } else if (IS_ERR(sc->tp_format)) {
1672 * If we managed to read the tracepoint /format file, then we
1673 * may end up not having any args, like with gettid(), so only
1674 * print the raw args when we didn't manage to read it.
1676 while (arg.idx < sc->nr_args) {
1677 if (arg.mask & bit)
1678 goto next_arg;
1679 val = syscall_arg__val(&arg, arg.idx);
1680 if (printed)
1681 printed += scnprintf(bf + printed, size - printed, ", ");
1682 printed += syscall__scnprintf_name(sc, bf + printed, size - printed, &arg);
1683 printed += syscall__scnprintf_val(sc, bf + printed, size - printed, &arg, val);
1684 next_arg:
1685 ++arg.idx;
1686 bit <<= 1;
1690 return printed;
1693 typedef int (*tracepoint_handler)(struct trace *trace, struct perf_evsel *evsel,
1694 union perf_event *event,
1695 struct perf_sample *sample);
1697 static struct syscall *trace__syscall_info(struct trace *trace,
1698 struct perf_evsel *evsel, int id)
1701 if (id < 0) {
1704 * XXX: Noticed on x86_64, reproduced as far back as 3.0.36, haven't tried
1705 * before that, leaving at a higher verbosity level till that is
1706 * explained. Reproduced with plain ftrace with:
1708 * echo 1 > /t/events/raw_syscalls/sys_exit/enable
1709 * grep "NR -1 " /t/trace_pipe
1711 * After generating some load on the machine.
1713 if (verbose > 1) {
1714 static u64 n;
1715 fprintf(trace->output, "Invalid syscall %d id, skipping (%s, %" PRIu64 ") ...\n",
1716 id, perf_evsel__name(evsel), ++n);
1718 return NULL;
1721 if ((id > trace->syscalls.max || trace->syscalls.table[id].name == NULL) &&
1722 trace__read_syscall_info(trace, id))
1723 goto out_cant_read;
1725 if ((id > trace->syscalls.max || trace->syscalls.table[id].name == NULL))
1726 goto out_cant_read;
1728 return &trace->syscalls.table[id];
1730 out_cant_read:
1731 if (verbose > 0) {
1732 fprintf(trace->output, "Problems reading syscall %d", id);
1733 if (id <= trace->syscalls.max && trace->syscalls.table[id].name != NULL)
1734 fprintf(trace->output, "(%s)", trace->syscalls.table[id].name);
1735 fputs(" information\n", trace->output);
1737 return NULL;
1740 static void thread__update_stats(struct thread_trace *ttrace,
1741 int id, struct perf_sample *sample)
1743 struct int_node *inode;
1744 struct stats *stats;
1745 u64 duration = 0;
1747 inode = intlist__findnew(ttrace->syscall_stats, id);
1748 if (inode == NULL)
1749 return;
1751 stats = inode->priv;
1752 if (stats == NULL) {
1753 stats = malloc(sizeof(struct stats));
1754 if (stats == NULL)
1755 return;
1756 init_stats(stats);
1757 inode->priv = stats;
1760 if (ttrace->entry_time && sample->time > ttrace->entry_time)
1761 duration = sample->time - ttrace->entry_time;
1763 update_stats(stats, duration);
1766 static int trace__printf_interrupted_entry(struct trace *trace)
1768 struct thread_trace *ttrace;
1769 size_t printed;
1770 int len;
1772 if (trace->failure_only || trace->current == NULL)
1773 return 0;
1775 ttrace = thread__priv(trace->current);
1777 if (!ttrace->entry_pending)
1778 return 0;
1780 printed = trace__fprintf_entry_head(trace, trace->current, 0, false, ttrace->entry_time, trace->output);
1781 printed += len = fprintf(trace->output, "%s)", ttrace->entry_str);
1783 if (len < trace->args_alignment - 4)
1784 printed += fprintf(trace->output, "%-*s", trace->args_alignment - 4 - len, " ");
1786 printed += fprintf(trace->output, " ...\n");
1788 ttrace->entry_pending = false;
1789 ++trace->nr_events_printed;
1791 return printed;
1794 static int trace__fprintf_sample(struct trace *trace, struct perf_evsel *evsel,
1795 struct perf_sample *sample, struct thread *thread)
1797 int printed = 0;
1799 if (trace->print_sample) {
1800 double ts = (double)sample->time / NSEC_PER_MSEC;
1802 printed += fprintf(trace->output, "%22s %10.3f %s %d/%d [%d]\n",
1803 perf_evsel__name(evsel), ts,
1804 thread__comm_str(thread),
1805 sample->pid, sample->tid, sample->cpu);
1808 return printed;
1811 static void *syscall__augmented_args(struct syscall *sc, struct perf_sample *sample, int *augmented_args_size, int raw_augmented_args_size)
1813 void *augmented_args = NULL;
1815 * For now with BPF raw_augmented we hook into raw_syscalls:sys_enter
1816 * and there we get all 6 syscall args plus the tracepoint common fields
1817 * that gets calculated at the start and the syscall_nr (another long).
1818 * So we check if that is the case and if so don't look after the
1819 * sc->args_size but always after the full raw_syscalls:sys_enter payload,
1820 * which is fixed.
1822 * We'll revisit this later to pass s->args_size to the BPF augmenter
1823 * (now tools/perf/examples/bpf/augmented_raw_syscalls.c, so that it
1824 * copies only what we need for each syscall, like what happens when we
1825 * use syscalls:sys_enter_NAME, so that we reduce the kernel/userspace
1826 * traffic to just what is needed for each syscall.
1828 int args_size = raw_augmented_args_size ?: sc->args_size;
1830 *augmented_args_size = sample->raw_size - args_size;
1831 if (*augmented_args_size > 0)
1832 augmented_args = sample->raw_data + args_size;
1834 return augmented_args;
1837 static int trace__sys_enter(struct trace *trace, struct perf_evsel *evsel,
1838 union perf_event *event __maybe_unused,
1839 struct perf_sample *sample)
1841 char *msg;
1842 void *args;
1843 int printed = 0;
1844 struct thread *thread;
1845 int id = perf_evsel__sc_tp_uint(evsel, id, sample), err = -1;
1846 int augmented_args_size = 0;
1847 void *augmented_args = NULL;
1848 struct syscall *sc = trace__syscall_info(trace, evsel, id);
1849 struct thread_trace *ttrace;
1851 if (sc == NULL)
1852 return -1;
1854 thread = machine__findnew_thread(trace->host, sample->pid, sample->tid);
1855 ttrace = thread__trace(thread, trace->output);
1856 if (ttrace == NULL)
1857 goto out_put;
1859 trace__fprintf_sample(trace, evsel, sample, thread);
1861 args = perf_evsel__sc_tp_ptr(evsel, args, sample);
1863 if (ttrace->entry_str == NULL) {
1864 ttrace->entry_str = malloc(trace__entry_str_size);
1865 if (!ttrace->entry_str)
1866 goto out_put;
1869 if (!(trace->duration_filter || trace->summary_only || trace->min_stack))
1870 trace__printf_interrupted_entry(trace);
1872 * If this is raw_syscalls.sys_enter, then it always comes with the 6 possible
1873 * arguments, even if the syscall being handled, say "openat", uses only 4 arguments
1874 * this breaks syscall__augmented_args() check for augmented args, as we calculate
1875 * syscall->args_size using each syscalls:sys_enter_NAME tracefs format file,
1876 * so when handling, say the openat syscall, we end up getting 6 args for the
1877 * raw_syscalls:sys_enter event, when we expected just 4, we end up mistakenly
1878 * thinking that the extra 2 u64 args are the augmented filename, so just check
1879 * here and avoid using augmented syscalls when the evsel is the raw_syscalls one.
1881 if (evsel != trace->syscalls.events.sys_enter)
1882 augmented_args = syscall__augmented_args(sc, sample, &augmented_args_size, trace->raw_augmented_syscalls_args_size);
1883 ttrace->entry_time = sample->time;
1884 msg = ttrace->entry_str;
1885 printed += scnprintf(msg + printed, trace__entry_str_size - printed, "%s(", sc->name);
1887 printed += syscall__scnprintf_args(sc, msg + printed, trace__entry_str_size - printed,
1888 args, augmented_args, augmented_args_size, trace, thread);
1890 if (sc->is_exit) {
1891 if (!(trace->duration_filter || trace->summary_only || trace->failure_only || trace->min_stack)) {
1892 int alignment = 0;
1894 trace__fprintf_entry_head(trace, thread, 0, false, ttrace->entry_time, trace->output);
1895 printed = fprintf(trace->output, "%s)", ttrace->entry_str);
1896 if (trace->args_alignment > printed)
1897 alignment = trace->args_alignment - printed;
1898 fprintf(trace->output, "%*s= ?\n", alignment, " ");
1900 } else {
1901 ttrace->entry_pending = true;
1902 /* See trace__vfs_getname & trace__sys_exit */
1903 ttrace->filename.pending_open = false;
1906 if (trace->current != thread) {
1907 thread__put(trace->current);
1908 trace->current = thread__get(thread);
1910 err = 0;
1911 out_put:
1912 thread__put(thread);
1913 return err;
1916 static int trace__fprintf_sys_enter(struct trace *trace, struct perf_evsel *evsel,
1917 struct perf_sample *sample)
1919 struct thread_trace *ttrace;
1920 struct thread *thread;
1921 int id = perf_evsel__sc_tp_uint(evsel, id, sample), err = -1;
1922 struct syscall *sc = trace__syscall_info(trace, evsel, id);
1923 char msg[1024];
1924 void *args, *augmented_args = NULL;
1925 int augmented_args_size;
1927 if (sc == NULL)
1928 return -1;
1930 thread = machine__findnew_thread(trace->host, sample->pid, sample->tid);
1931 ttrace = thread__trace(thread, trace->output);
1933 * We need to get ttrace just to make sure it is there when syscall__scnprintf_args()
1934 * and the rest of the beautifiers accessing it via struct syscall_arg touches it.
1936 if (ttrace == NULL)
1937 goto out_put;
1939 args = perf_evsel__sc_tp_ptr(evsel, args, sample);
1940 augmented_args = syscall__augmented_args(sc, sample, &augmented_args_size, trace->raw_augmented_syscalls_args_size);
1941 syscall__scnprintf_args(sc, msg, sizeof(msg), args, augmented_args, augmented_args_size, trace, thread);
1942 fprintf(trace->output, "%s", msg);
1943 err = 0;
1944 out_put:
1945 thread__put(thread);
1946 return err;
1949 static int trace__resolve_callchain(struct trace *trace, struct perf_evsel *evsel,
1950 struct perf_sample *sample,
1951 struct callchain_cursor *cursor)
1953 struct addr_location al;
1954 int max_stack = evsel->attr.sample_max_stack ?
1955 evsel->attr.sample_max_stack :
1956 trace->max_stack;
1957 int err;
1959 if (machine__resolve(trace->host, &al, sample) < 0)
1960 return -1;
1962 err = thread__resolve_callchain(al.thread, cursor, evsel, sample, NULL, NULL, max_stack);
1963 addr_location__put(&al);
1964 return err;
1967 static int trace__fprintf_callchain(struct trace *trace, struct perf_sample *sample)
1969 /* TODO: user-configurable print_opts */
1970 const unsigned int print_opts = EVSEL__PRINT_SYM |
1971 EVSEL__PRINT_DSO |
1972 EVSEL__PRINT_UNKNOWN_AS_ADDR;
1974 return sample__fprintf_callchain(sample, 38, print_opts, &callchain_cursor, trace->output);
1977 static const char *errno_to_name(struct perf_evsel *evsel, int err)
1979 struct perf_env *env = perf_evsel__env(evsel);
1980 const char *arch_name = perf_env__arch(env);
1982 return arch_syscalls__strerrno(arch_name, err);
1985 static int trace__sys_exit(struct trace *trace, struct perf_evsel *evsel,
1986 union perf_event *event __maybe_unused,
1987 struct perf_sample *sample)
1989 long ret;
1990 u64 duration = 0;
1991 bool duration_calculated = false;
1992 struct thread *thread;
1993 int id = perf_evsel__sc_tp_uint(evsel, id, sample), err = -1, callchain_ret = 0, printed = 0;
1994 int alignment = trace->args_alignment;
1995 struct syscall *sc = trace__syscall_info(trace, evsel, id);
1996 struct thread_trace *ttrace;
1998 if (sc == NULL)
1999 return -1;
2001 thread = machine__findnew_thread(trace->host, sample->pid, sample->tid);
2002 ttrace = thread__trace(thread, trace->output);
2003 if (ttrace == NULL)
2004 goto out_put;
2006 trace__fprintf_sample(trace, evsel, sample, thread);
2008 if (trace->summary)
2009 thread__update_stats(ttrace, id, sample);
2011 ret = perf_evsel__sc_tp_uint(evsel, ret, sample);
2013 if (sc->is_open && ret >= 0 && ttrace->filename.pending_open) {
2014 trace__set_fd_pathname(thread, ret, ttrace->filename.name);
2015 ttrace->filename.pending_open = false;
2016 ++trace->stats.vfs_getname;
2019 if (ttrace->entry_time) {
2020 duration = sample->time - ttrace->entry_time;
2021 if (trace__filter_duration(trace, duration))
2022 goto out;
2023 duration_calculated = true;
2024 } else if (trace->duration_filter)
2025 goto out;
2027 if (sample->callchain) {
2028 callchain_ret = trace__resolve_callchain(trace, evsel, sample, &callchain_cursor);
2029 if (callchain_ret == 0) {
2030 if (callchain_cursor.nr < trace->min_stack)
2031 goto out;
2032 callchain_ret = 1;
2036 if (trace->summary_only || (ret >= 0 && trace->failure_only))
2037 goto out;
2039 trace__fprintf_entry_head(trace, thread, duration, duration_calculated, ttrace->entry_time, trace->output);
2041 if (ttrace->entry_pending) {
2042 printed = fprintf(trace->output, "%s", ttrace->entry_str);
2043 } else {
2044 printed += fprintf(trace->output, " ... [");
2045 color_fprintf(trace->output, PERF_COLOR_YELLOW, "continued");
2046 printed += 9;
2047 printed += fprintf(trace->output, "]: %s()", sc->name);
2050 printed++; /* the closing ')' */
2052 if (alignment > printed)
2053 alignment -= printed;
2054 else
2055 alignment = 0;
2057 fprintf(trace->output, ")%*s= ", alignment, " ");
2059 if (sc->fmt == NULL) {
2060 if (ret < 0)
2061 goto errno_print;
2062 signed_print:
2063 fprintf(trace->output, "%ld", ret);
2064 } else if (ret < 0) {
2065 errno_print: {
2066 char bf[STRERR_BUFSIZE];
2067 const char *emsg = str_error_r(-ret, bf, sizeof(bf)),
2068 *e = errno_to_name(evsel, -ret);
2070 fprintf(trace->output, "-1 %s (%s)", e, emsg);
2072 } else if (ret == 0 && sc->fmt->timeout)
2073 fprintf(trace->output, "0 (Timeout)");
2074 else if (ttrace->ret_scnprintf) {
2075 char bf[1024];
2076 struct syscall_arg arg = {
2077 .val = ret,
2078 .thread = thread,
2079 .trace = trace,
2081 ttrace->ret_scnprintf(bf, sizeof(bf), &arg);
2082 ttrace->ret_scnprintf = NULL;
2083 fprintf(trace->output, "%s", bf);
2084 } else if (sc->fmt->hexret)
2085 fprintf(trace->output, "%#lx", ret);
2086 else if (sc->fmt->errpid) {
2087 struct thread *child = machine__find_thread(trace->host, ret, ret);
2089 if (child != NULL) {
2090 fprintf(trace->output, "%ld", ret);
2091 if (child->comm_set)
2092 fprintf(trace->output, " (%s)", thread__comm_str(child));
2093 thread__put(child);
2095 } else
2096 goto signed_print;
2098 fputc('\n', trace->output);
2101 * We only consider an 'event' for the sake of --max-events a non-filtered
2102 * sys_enter + sys_exit and other tracepoint events.
2104 if (++trace->nr_events_printed == trace->max_events && trace->max_events != ULONG_MAX)
2105 interrupted = true;
2107 if (callchain_ret > 0)
2108 trace__fprintf_callchain(trace, sample);
2109 else if (callchain_ret < 0)
2110 pr_err("Problem processing %s callchain, skipping...\n", perf_evsel__name(evsel));
2111 out:
2112 ttrace->entry_pending = false;
2113 err = 0;
2114 out_put:
2115 thread__put(thread);
2116 return err;
2119 static int trace__vfs_getname(struct trace *trace, struct perf_evsel *evsel,
2120 union perf_event *event __maybe_unused,
2121 struct perf_sample *sample)
2123 struct thread *thread = machine__findnew_thread(trace->host, sample->pid, sample->tid);
2124 struct thread_trace *ttrace;
2125 size_t filename_len, entry_str_len, to_move;
2126 ssize_t remaining_space;
2127 char *pos;
2128 const char *filename = perf_evsel__rawptr(evsel, sample, "pathname");
2130 if (!thread)
2131 goto out;
2133 ttrace = thread__priv(thread);
2134 if (!ttrace)
2135 goto out_put;
2137 filename_len = strlen(filename);
2138 if (filename_len == 0)
2139 goto out_put;
2141 if (ttrace->filename.namelen < filename_len) {
2142 char *f = realloc(ttrace->filename.name, filename_len + 1);
2144 if (f == NULL)
2145 goto out_put;
2147 ttrace->filename.namelen = filename_len;
2148 ttrace->filename.name = f;
2151 strcpy(ttrace->filename.name, filename);
2152 ttrace->filename.pending_open = true;
2154 if (!ttrace->filename.ptr)
2155 goto out_put;
2157 entry_str_len = strlen(ttrace->entry_str);
2158 remaining_space = trace__entry_str_size - entry_str_len - 1; /* \0 */
2159 if (remaining_space <= 0)
2160 goto out_put;
2162 if (filename_len > (size_t)remaining_space) {
2163 filename += filename_len - remaining_space;
2164 filename_len = remaining_space;
2167 to_move = entry_str_len - ttrace->filename.entry_str_pos + 1; /* \0 */
2168 pos = ttrace->entry_str + ttrace->filename.entry_str_pos;
2169 memmove(pos + filename_len, pos, to_move);
2170 memcpy(pos, filename, filename_len);
2172 ttrace->filename.ptr = 0;
2173 ttrace->filename.entry_str_pos = 0;
2174 out_put:
2175 thread__put(thread);
2176 out:
2177 return 0;
2180 static int trace__sched_stat_runtime(struct trace *trace, struct perf_evsel *evsel,
2181 union perf_event *event __maybe_unused,
2182 struct perf_sample *sample)
2184 u64 runtime = perf_evsel__intval(evsel, sample, "runtime");
2185 double runtime_ms = (double)runtime / NSEC_PER_MSEC;
2186 struct thread *thread = machine__findnew_thread(trace->host,
2187 sample->pid,
2188 sample->tid);
2189 struct thread_trace *ttrace = thread__trace(thread, trace->output);
2191 if (ttrace == NULL)
2192 goto out_dump;
2194 ttrace->runtime_ms += runtime_ms;
2195 trace->runtime_ms += runtime_ms;
2196 out_put:
2197 thread__put(thread);
2198 return 0;
2200 out_dump:
2201 fprintf(trace->output, "%s: comm=%s,pid=%u,runtime=%" PRIu64 ",vruntime=%" PRIu64 ")\n",
2202 evsel->name,
2203 perf_evsel__strval(evsel, sample, "comm"),
2204 (pid_t)perf_evsel__intval(evsel, sample, "pid"),
2205 runtime,
2206 perf_evsel__intval(evsel, sample, "vruntime"));
2207 goto out_put;
2210 static int bpf_output__printer(enum binary_printer_ops op,
2211 unsigned int val, void *extra __maybe_unused, FILE *fp)
2213 unsigned char ch = (unsigned char)val;
2215 switch (op) {
2216 case BINARY_PRINT_CHAR_DATA:
2217 return fprintf(fp, "%c", isprint(ch) ? ch : '.');
2218 case BINARY_PRINT_DATA_BEGIN:
2219 case BINARY_PRINT_LINE_BEGIN:
2220 case BINARY_PRINT_ADDR:
2221 case BINARY_PRINT_NUM_DATA:
2222 case BINARY_PRINT_NUM_PAD:
2223 case BINARY_PRINT_SEP:
2224 case BINARY_PRINT_CHAR_PAD:
2225 case BINARY_PRINT_LINE_END:
2226 case BINARY_PRINT_DATA_END:
2227 default:
2228 break;
2231 return 0;
2234 static void bpf_output__fprintf(struct trace *trace,
2235 struct perf_sample *sample)
2237 binary__fprintf(sample->raw_data, sample->raw_size, 8,
2238 bpf_output__printer, NULL, trace->output);
2239 ++trace->nr_events_printed;
2242 static int trace__event_handler(struct trace *trace, struct perf_evsel *evsel,
2243 union perf_event *event __maybe_unused,
2244 struct perf_sample *sample)
2246 struct thread *thread;
2247 int callchain_ret = 0;
2249 * Check if we called perf_evsel__disable(evsel) due to, for instance,
2250 * this event's max_events having been hit and this is an entry coming
2251 * from the ring buffer that we should discard, since the max events
2252 * have already been considered/printed.
2254 if (evsel->disabled)
2255 return 0;
2257 thread = machine__findnew_thread(trace->host, sample->pid, sample->tid);
2259 if (sample->callchain) {
2260 callchain_ret = trace__resolve_callchain(trace, evsel, sample, &callchain_cursor);
2261 if (callchain_ret == 0) {
2262 if (callchain_cursor.nr < trace->min_stack)
2263 goto out;
2264 callchain_ret = 1;
2268 trace__printf_interrupted_entry(trace);
2269 trace__fprintf_tstamp(trace, sample->time, trace->output);
2271 if (trace->trace_syscalls && trace->show_duration)
2272 fprintf(trace->output, "( ): ");
2274 if (thread)
2275 trace__fprintf_comm_tid(trace, thread, trace->output);
2277 if (evsel == trace->syscalls.events.augmented) {
2278 int id = perf_evsel__sc_tp_uint(evsel, id, sample);
2279 struct syscall *sc = trace__syscall_info(trace, evsel, id);
2281 if (sc) {
2282 fprintf(trace->output, "%s(", sc->name);
2283 trace__fprintf_sys_enter(trace, evsel, sample);
2284 fputc(')', trace->output);
2285 goto newline;
2289 * XXX: Not having the associated syscall info or not finding/adding
2290 * the thread should never happen, but if it does...
2291 * fall thru and print it as a bpf_output event.
2295 fprintf(trace->output, "%s:", evsel->name);
2297 if (perf_evsel__is_bpf_output(evsel)) {
2298 bpf_output__fprintf(trace, sample);
2299 } else if (evsel->tp_format) {
2300 if (strncmp(evsel->tp_format->name, "sys_enter_", 10) ||
2301 trace__fprintf_sys_enter(trace, evsel, sample)) {
2302 event_format__fprintf(evsel->tp_format, sample->cpu,
2303 sample->raw_data, sample->raw_size,
2304 trace->output);
2305 ++trace->nr_events_printed;
2307 if (evsel->max_events != ULONG_MAX && ++evsel->nr_events_printed == evsel->max_events) {
2308 perf_evsel__disable(evsel);
2309 perf_evsel__close(evsel);
2314 newline:
2315 fprintf(trace->output, "\n");
2317 if (callchain_ret > 0)
2318 trace__fprintf_callchain(trace, sample);
2319 else if (callchain_ret < 0)
2320 pr_err("Problem processing %s callchain, skipping...\n", perf_evsel__name(evsel));
2321 out:
2322 thread__put(thread);
2323 return 0;
2326 static void print_location(FILE *f, struct perf_sample *sample,
2327 struct addr_location *al,
2328 bool print_dso, bool print_sym)
2331 if ((verbose > 0 || print_dso) && al->map)
2332 fprintf(f, "%s@", al->map->dso->long_name);
2334 if ((verbose > 0 || print_sym) && al->sym)
2335 fprintf(f, "%s+0x%" PRIx64, al->sym->name,
2336 al->addr - al->sym->start);
2337 else if (al->map)
2338 fprintf(f, "0x%" PRIx64, al->addr);
2339 else
2340 fprintf(f, "0x%" PRIx64, sample->addr);
2343 static int trace__pgfault(struct trace *trace,
2344 struct perf_evsel *evsel,
2345 union perf_event *event __maybe_unused,
2346 struct perf_sample *sample)
2348 struct thread *thread;
2349 struct addr_location al;
2350 char map_type = 'd';
2351 struct thread_trace *ttrace;
2352 int err = -1;
2353 int callchain_ret = 0;
2355 thread = machine__findnew_thread(trace->host, sample->pid, sample->tid);
2357 if (sample->callchain) {
2358 callchain_ret = trace__resolve_callchain(trace, evsel, sample, &callchain_cursor);
2359 if (callchain_ret == 0) {
2360 if (callchain_cursor.nr < trace->min_stack)
2361 goto out_put;
2362 callchain_ret = 1;
2366 ttrace = thread__trace(thread, trace->output);
2367 if (ttrace == NULL)
2368 goto out_put;
2370 if (evsel->attr.config == PERF_COUNT_SW_PAGE_FAULTS_MAJ)
2371 ttrace->pfmaj++;
2372 else
2373 ttrace->pfmin++;
2375 if (trace->summary_only)
2376 goto out;
2378 thread__find_symbol(thread, sample->cpumode, sample->ip, &al);
2380 trace__fprintf_entry_head(trace, thread, 0, true, sample->time, trace->output);
2382 fprintf(trace->output, "%sfault [",
2383 evsel->attr.config == PERF_COUNT_SW_PAGE_FAULTS_MAJ ?
2384 "maj" : "min");
2386 print_location(trace->output, sample, &al, false, true);
2388 fprintf(trace->output, "] => ");
2390 thread__find_symbol(thread, sample->cpumode, sample->addr, &al);
2392 if (!al.map) {
2393 thread__find_symbol(thread, sample->cpumode, sample->addr, &al);
2395 if (al.map)
2396 map_type = 'x';
2397 else
2398 map_type = '?';
2401 print_location(trace->output, sample, &al, true, false);
2403 fprintf(trace->output, " (%c%c)\n", map_type, al.level);
2405 if (callchain_ret > 0)
2406 trace__fprintf_callchain(trace, sample);
2407 else if (callchain_ret < 0)
2408 pr_err("Problem processing %s callchain, skipping...\n", perf_evsel__name(evsel));
2410 ++trace->nr_events_printed;
2411 out:
2412 err = 0;
2413 out_put:
2414 thread__put(thread);
2415 return err;
2418 static void trace__set_base_time(struct trace *trace,
2419 struct perf_evsel *evsel,
2420 struct perf_sample *sample)
2423 * BPF events were not setting PERF_SAMPLE_TIME, so be more robust
2424 * and don't use sample->time unconditionally, we may end up having
2425 * some other event in the future without PERF_SAMPLE_TIME for good
2426 * reason, i.e. we may not be interested in its timestamps, just in
2427 * it taking place, picking some piece of information when it
2428 * appears in our event stream (vfs_getname comes to mind).
2430 if (trace->base_time == 0 && !trace->full_time &&
2431 (evsel->attr.sample_type & PERF_SAMPLE_TIME))
2432 trace->base_time = sample->time;
2435 static int trace__process_sample(struct perf_tool *tool,
2436 union perf_event *event,
2437 struct perf_sample *sample,
2438 struct perf_evsel *evsel,
2439 struct machine *machine __maybe_unused)
2441 struct trace *trace = container_of(tool, struct trace, tool);
2442 struct thread *thread;
2443 int err = 0;
2445 tracepoint_handler handler = evsel->handler;
2447 thread = machine__findnew_thread(trace->host, sample->pid, sample->tid);
2448 if (thread && thread__is_filtered(thread))
2449 goto out;
2451 trace__set_base_time(trace, evsel, sample);
2453 if (handler) {
2454 ++trace->nr_events;
2455 handler(trace, evsel, event, sample);
2457 out:
2458 thread__put(thread);
2459 return err;
2462 static int trace__record(struct trace *trace, int argc, const char **argv)
2464 unsigned int rec_argc, i, j;
2465 const char **rec_argv;
2466 const char * const record_args[] = {
2467 "record",
2468 "-R",
2469 "-m", "1024",
2470 "-c", "1",
2473 const char * const sc_args[] = { "-e", };
2474 unsigned int sc_args_nr = ARRAY_SIZE(sc_args);
2475 const char * const majpf_args[] = { "-e", "major-faults" };
2476 unsigned int majpf_args_nr = ARRAY_SIZE(majpf_args);
2477 const char * const minpf_args[] = { "-e", "minor-faults" };
2478 unsigned int minpf_args_nr = ARRAY_SIZE(minpf_args);
2480 /* +1 is for the event string below */
2481 rec_argc = ARRAY_SIZE(record_args) + sc_args_nr + 1 +
2482 majpf_args_nr + minpf_args_nr + argc;
2483 rec_argv = calloc(rec_argc + 1, sizeof(char *));
2485 if (rec_argv == NULL)
2486 return -ENOMEM;
2488 j = 0;
2489 for (i = 0; i < ARRAY_SIZE(record_args); i++)
2490 rec_argv[j++] = record_args[i];
2492 if (trace->trace_syscalls) {
2493 for (i = 0; i < sc_args_nr; i++)
2494 rec_argv[j++] = sc_args[i];
2496 /* event string may be different for older kernels - e.g., RHEL6 */
2497 if (is_valid_tracepoint("raw_syscalls:sys_enter"))
2498 rec_argv[j++] = "raw_syscalls:sys_enter,raw_syscalls:sys_exit";
2499 else if (is_valid_tracepoint("syscalls:sys_enter"))
2500 rec_argv[j++] = "syscalls:sys_enter,syscalls:sys_exit";
2501 else {
2502 pr_err("Neither raw_syscalls nor syscalls events exist.\n");
2503 free(rec_argv);
2504 return -1;
2508 if (trace->trace_pgfaults & TRACE_PFMAJ)
2509 for (i = 0; i < majpf_args_nr; i++)
2510 rec_argv[j++] = majpf_args[i];
2512 if (trace->trace_pgfaults & TRACE_PFMIN)
2513 for (i = 0; i < minpf_args_nr; i++)
2514 rec_argv[j++] = minpf_args[i];
2516 for (i = 0; i < (unsigned int)argc; i++)
2517 rec_argv[j++] = argv[i];
2519 return cmd_record(j, rec_argv);
2522 static size_t trace__fprintf_thread_summary(struct trace *trace, FILE *fp);
2524 static bool perf_evlist__add_vfs_getname(struct perf_evlist *evlist)
2526 bool found = false;
2527 struct perf_evsel *evsel, *tmp;
2528 struct parse_events_error err = { .idx = 0, };
2529 int ret = parse_events(evlist, "probe:vfs_getname*", &err);
2531 if (ret)
2532 return false;
2534 evlist__for_each_entry_safe(evlist, evsel, tmp) {
2535 if (!strstarts(perf_evsel__name(evsel), "probe:vfs_getname"))
2536 continue;
2538 if (perf_evsel__field(evsel, "pathname")) {
2539 evsel->handler = trace__vfs_getname;
2540 found = true;
2541 continue;
2544 list_del_init(&evsel->node);
2545 evsel->evlist = NULL;
2546 perf_evsel__delete(evsel);
2549 return found;
2552 static struct perf_evsel *perf_evsel__new_pgfault(u64 config)
2554 struct perf_evsel *evsel;
2555 struct perf_event_attr attr = {
2556 .type = PERF_TYPE_SOFTWARE,
2557 .mmap_data = 1,
2560 attr.config = config;
2561 attr.sample_period = 1;
2563 event_attr_init(&attr);
2565 evsel = perf_evsel__new(&attr);
2566 if (evsel)
2567 evsel->handler = trace__pgfault;
2569 return evsel;
2572 static void trace__handle_event(struct trace *trace, union perf_event *event, struct perf_sample *sample)
2574 const u32 type = event->header.type;
2575 struct perf_evsel *evsel;
2577 if (type != PERF_RECORD_SAMPLE) {
2578 trace__process_event(trace, trace->host, event, sample);
2579 return;
2582 evsel = perf_evlist__id2evsel(trace->evlist, sample->id);
2583 if (evsel == NULL) {
2584 fprintf(trace->output, "Unknown tp ID %" PRIu64 ", skipping...\n", sample->id);
2585 return;
2588 trace__set_base_time(trace, evsel, sample);
2590 if (evsel->attr.type == PERF_TYPE_TRACEPOINT &&
2591 sample->raw_data == NULL) {
2592 fprintf(trace->output, "%s sample with no payload for tid: %d, cpu %d, raw_size=%d, skipping...\n",
2593 perf_evsel__name(evsel), sample->tid,
2594 sample->cpu, sample->raw_size);
2595 } else {
2596 tracepoint_handler handler = evsel->handler;
2597 handler(trace, evsel, event, sample);
2600 if (trace->nr_events_printed >= trace->max_events && trace->max_events != ULONG_MAX)
2601 interrupted = true;
2604 static int trace__add_syscall_newtp(struct trace *trace)
2606 int ret = -1;
2607 struct perf_evlist *evlist = trace->evlist;
2608 struct perf_evsel *sys_enter, *sys_exit;
2610 sys_enter = perf_evsel__raw_syscall_newtp("sys_enter", trace__sys_enter);
2611 if (sys_enter == NULL)
2612 goto out;
2614 if (perf_evsel__init_sc_tp_ptr_field(sys_enter, args))
2615 goto out_delete_sys_enter;
2617 sys_exit = perf_evsel__raw_syscall_newtp("sys_exit", trace__sys_exit);
2618 if (sys_exit == NULL)
2619 goto out_delete_sys_enter;
2621 if (perf_evsel__init_sc_tp_uint_field(sys_exit, ret))
2622 goto out_delete_sys_exit;
2624 perf_evsel__config_callchain(sys_enter, &trace->opts, &callchain_param);
2625 perf_evsel__config_callchain(sys_exit, &trace->opts, &callchain_param);
2627 perf_evlist__add(evlist, sys_enter);
2628 perf_evlist__add(evlist, sys_exit);
2630 if (callchain_param.enabled && !trace->kernel_syscallchains) {
2632 * We're interested only in the user space callchain
2633 * leading to the syscall, allow overriding that for
2634 * debugging reasons using --kernel_syscall_callchains
2636 sys_exit->attr.exclude_callchain_kernel = 1;
2639 trace->syscalls.events.sys_enter = sys_enter;
2640 trace->syscalls.events.sys_exit = sys_exit;
2642 ret = 0;
2643 out:
2644 return ret;
2646 out_delete_sys_exit:
2647 perf_evsel__delete_priv(sys_exit);
2648 out_delete_sys_enter:
2649 perf_evsel__delete_priv(sys_enter);
2650 goto out;
2653 static int trace__set_ev_qualifier_tp_filter(struct trace *trace)
2655 int err = -1;
2656 struct perf_evsel *sys_exit;
2657 char *filter = asprintf_expr_inout_ints("id", !trace->not_ev_qualifier,
2658 trace->ev_qualifier_ids.nr,
2659 trace->ev_qualifier_ids.entries);
2661 if (filter == NULL)
2662 goto out_enomem;
2664 if (!perf_evsel__append_tp_filter(trace->syscalls.events.sys_enter,
2665 filter)) {
2666 sys_exit = trace->syscalls.events.sys_exit;
2667 err = perf_evsel__append_tp_filter(sys_exit, filter);
2670 free(filter);
2671 out:
2672 return err;
2673 out_enomem:
2674 errno = ENOMEM;
2675 goto out;
2678 #ifdef HAVE_LIBBPF_SUPPORT
2679 static int trace__set_ev_qualifier_bpf_filter(struct trace *trace)
2681 int fd = bpf_map__fd(trace->syscalls.map);
2682 struct bpf_map_syscall_entry value = {
2683 .enabled = !trace->not_ev_qualifier,
2685 int err = 0;
2686 size_t i;
2688 for (i = 0; i < trace->ev_qualifier_ids.nr; ++i) {
2689 int key = trace->ev_qualifier_ids.entries[i];
2691 err = bpf_map_update_elem(fd, &key, &value, BPF_EXIST);
2692 if (err)
2693 break;
2696 return err;
2699 static int __trace__init_syscalls_bpf_map(struct trace *trace, bool enabled)
2701 int fd = bpf_map__fd(trace->syscalls.map);
2702 struct bpf_map_syscall_entry value = {
2703 .enabled = enabled,
2705 int err = 0, key;
2707 for (key = 0; key < trace->sctbl->syscalls.nr_entries; ++key) {
2708 err = bpf_map_update_elem(fd, &key, &value, BPF_ANY);
2709 if (err)
2710 break;
2713 return err;
2716 static int trace__init_syscalls_bpf_map(struct trace *trace)
2718 bool enabled = true;
2720 if (trace->ev_qualifier_ids.nr)
2721 enabled = trace->not_ev_qualifier;
2723 return __trace__init_syscalls_bpf_map(trace, enabled);
2725 #else
2726 static int trace__set_ev_qualifier_bpf_filter(struct trace *trace __maybe_unused)
2728 return 0;
2731 static int trace__init_syscalls_bpf_map(struct trace *trace __maybe_unused)
2733 return 0;
2735 #endif // HAVE_LIBBPF_SUPPORT
2737 static int trace__set_ev_qualifier_filter(struct trace *trace)
2739 if (trace->syscalls.map)
2740 return trace__set_ev_qualifier_bpf_filter(trace);
2741 if (trace->syscalls.events.sys_enter)
2742 return trace__set_ev_qualifier_tp_filter(trace);
2743 return 0;
2746 static int bpf_map__set_filter_pids(struct bpf_map *map __maybe_unused,
2747 size_t npids __maybe_unused, pid_t *pids __maybe_unused)
2749 int err = 0;
2750 #ifdef HAVE_LIBBPF_SUPPORT
2751 bool value = true;
2752 int map_fd = bpf_map__fd(map);
2753 size_t i;
2755 for (i = 0; i < npids; ++i) {
2756 err = bpf_map_update_elem(map_fd, &pids[i], &value, BPF_ANY);
2757 if (err)
2758 break;
2760 #endif
2761 return err;
2764 static int trace__set_filter_loop_pids(struct trace *trace)
2766 unsigned int nr = 1, err;
2767 pid_t pids[32] = {
2768 getpid(),
2770 struct thread *thread = machine__find_thread(trace->host, pids[0], pids[0]);
2772 while (thread && nr < ARRAY_SIZE(pids)) {
2773 struct thread *parent = machine__find_thread(trace->host, thread->ppid, thread->ppid);
2775 if (parent == NULL)
2776 break;
2778 if (!strcmp(thread__comm_str(parent), "sshd") ||
2779 strstarts(thread__comm_str(parent), "gnome-terminal")) {
2780 pids[nr++] = parent->tid;
2781 break;
2783 thread = parent;
2786 err = perf_evlist__set_tp_filter_pids(trace->evlist, nr, pids);
2787 if (!err && trace->filter_pids.map)
2788 err = bpf_map__set_filter_pids(trace->filter_pids.map, nr, pids);
2790 return err;
2793 static int trace__set_filter_pids(struct trace *trace)
2795 int err = 0;
2797 * Better not use !target__has_task() here because we need to cover the
2798 * case where no threads were specified in the command line, but a
2799 * workload was, and in that case we will fill in the thread_map when
2800 * we fork the workload in perf_evlist__prepare_workload.
2802 if (trace->filter_pids.nr > 0) {
2803 err = perf_evlist__set_tp_filter_pids(trace->evlist, trace->filter_pids.nr,
2804 trace->filter_pids.entries);
2805 if (!err && trace->filter_pids.map) {
2806 err = bpf_map__set_filter_pids(trace->filter_pids.map, trace->filter_pids.nr,
2807 trace->filter_pids.entries);
2809 } else if (thread_map__pid(trace->evlist->threads, 0) == -1) {
2810 err = trace__set_filter_loop_pids(trace);
2813 return err;
2816 static int __trace__deliver_event(struct trace *trace, union perf_event *event)
2818 struct perf_evlist *evlist = trace->evlist;
2819 struct perf_sample sample;
2820 int err;
2822 err = perf_evlist__parse_sample(evlist, event, &sample);
2823 if (err)
2824 fprintf(trace->output, "Can't parse sample, err = %d, skipping...\n", err);
2825 else
2826 trace__handle_event(trace, event, &sample);
2828 return 0;
2831 static int __trace__flush_events(struct trace *trace)
2833 u64 first = ordered_events__first_time(&trace->oe.data);
2834 u64 flush = trace->oe.last - NSEC_PER_SEC;
2836 /* Is there some thing to flush.. */
2837 if (first && first < flush)
2838 return ordered_events__flush_time(&trace->oe.data, flush);
2840 return 0;
2843 static int trace__flush_events(struct trace *trace)
2845 return !trace->sort_events ? 0 : __trace__flush_events(trace);
2848 static int trace__deliver_event(struct trace *trace, union perf_event *event)
2850 int err;
2852 if (!trace->sort_events)
2853 return __trace__deliver_event(trace, event);
2855 err = perf_evlist__parse_sample_timestamp(trace->evlist, event, &trace->oe.last);
2856 if (err && err != -1)
2857 return err;
2859 err = ordered_events__queue(&trace->oe.data, event, trace->oe.last, 0);
2860 if (err)
2861 return err;
2863 return trace__flush_events(trace);
2866 static int ordered_events__deliver_event(struct ordered_events *oe,
2867 struct ordered_event *event)
2869 struct trace *trace = container_of(oe, struct trace, oe.data);
2871 return __trace__deliver_event(trace, event->event);
2874 static int trace__run(struct trace *trace, int argc, const char **argv)
2876 struct perf_evlist *evlist = trace->evlist;
2877 struct perf_evsel *evsel, *pgfault_maj = NULL, *pgfault_min = NULL;
2878 int err = -1, i;
2879 unsigned long before;
2880 const bool forks = argc > 0;
2881 bool draining = false;
2883 trace->live = true;
2885 if (!trace->raw_augmented_syscalls) {
2886 if (trace->trace_syscalls && trace__add_syscall_newtp(trace))
2887 goto out_error_raw_syscalls;
2889 if (trace->trace_syscalls)
2890 trace->vfs_getname = perf_evlist__add_vfs_getname(evlist);
2893 if ((trace->trace_pgfaults & TRACE_PFMAJ)) {
2894 pgfault_maj = perf_evsel__new_pgfault(PERF_COUNT_SW_PAGE_FAULTS_MAJ);
2895 if (pgfault_maj == NULL)
2896 goto out_error_mem;
2897 perf_evsel__config_callchain(pgfault_maj, &trace->opts, &callchain_param);
2898 perf_evlist__add(evlist, pgfault_maj);
2901 if ((trace->trace_pgfaults & TRACE_PFMIN)) {
2902 pgfault_min = perf_evsel__new_pgfault(PERF_COUNT_SW_PAGE_FAULTS_MIN);
2903 if (pgfault_min == NULL)
2904 goto out_error_mem;
2905 perf_evsel__config_callchain(pgfault_min, &trace->opts, &callchain_param);
2906 perf_evlist__add(evlist, pgfault_min);
2909 if (trace->sched &&
2910 perf_evlist__add_newtp(evlist, "sched", "sched_stat_runtime",
2911 trace__sched_stat_runtime))
2912 goto out_error_sched_stat_runtime;
2915 * If a global cgroup was set, apply it to all the events without an
2916 * explicit cgroup. I.e.:
2918 * trace -G A -e sched:*switch
2920 * Will set all raw_syscalls:sys_{enter,exit}, pgfault, vfs_getname, etc
2921 * _and_ sched:sched_switch to the 'A' cgroup, while:
2923 * trace -e sched:*switch -G A
2925 * will only set the sched:sched_switch event to the 'A' cgroup, all the
2926 * other events (raw_syscalls:sys_{enter,exit}, etc are left "without"
2927 * a cgroup (on the root cgroup, sys wide, etc).
2929 * Multiple cgroups:
2931 * trace -G A -e sched:*switch -G B
2933 * the syscall ones go to the 'A' cgroup, the sched:sched_switch goes
2934 * to the 'B' cgroup.
2936 * evlist__set_default_cgroup() grabs a reference of the passed cgroup
2937 * only for the evsels still without a cgroup, i.e. evsel->cgroup == NULL.
2939 if (trace->cgroup)
2940 evlist__set_default_cgroup(trace->evlist, trace->cgroup);
2942 err = perf_evlist__create_maps(evlist, &trace->opts.target);
2943 if (err < 0) {
2944 fprintf(trace->output, "Problems parsing the target to trace, check your options!\n");
2945 goto out_delete_evlist;
2948 err = trace__symbols_init(trace, evlist);
2949 if (err < 0) {
2950 fprintf(trace->output, "Problems initializing symbol libraries!\n");
2951 goto out_delete_evlist;
2954 perf_evlist__config(evlist, &trace->opts, &callchain_param);
2956 signal(SIGCHLD, sig_handler);
2957 signal(SIGINT, sig_handler);
2959 if (forks) {
2960 err = perf_evlist__prepare_workload(evlist, &trace->opts.target,
2961 argv, false, NULL);
2962 if (err < 0) {
2963 fprintf(trace->output, "Couldn't run the workload!\n");
2964 goto out_delete_evlist;
2968 err = perf_evlist__open(evlist);
2969 if (err < 0)
2970 goto out_error_open;
2972 err = bpf__apply_obj_config();
2973 if (err) {
2974 char errbuf[BUFSIZ];
2976 bpf__strerror_apply_obj_config(err, errbuf, sizeof(errbuf));
2977 pr_err("ERROR: Apply config to BPF failed: %s\n",
2978 errbuf);
2979 goto out_error_open;
2982 err = trace__set_filter_pids(trace);
2983 if (err < 0)
2984 goto out_error_mem;
2986 if (trace->syscalls.map)
2987 trace__init_syscalls_bpf_map(trace);
2989 if (trace->ev_qualifier_ids.nr > 0) {
2990 err = trace__set_ev_qualifier_filter(trace);
2991 if (err < 0)
2992 goto out_errno;
2994 if (trace->syscalls.events.sys_exit) {
2995 pr_debug("event qualifier tracepoint filter: %s\n",
2996 trace->syscalls.events.sys_exit->filter);
3000 err = perf_evlist__apply_filters(evlist, &evsel);
3001 if (err < 0)
3002 goto out_error_apply_filters;
3004 if (trace->dump.map)
3005 bpf_map__fprintf(trace->dump.map, trace->output);
3007 err = perf_evlist__mmap(evlist, trace->opts.mmap_pages);
3008 if (err < 0)
3009 goto out_error_mmap;
3011 if (!target__none(&trace->opts.target) && !trace->opts.initial_delay)
3012 perf_evlist__enable(evlist);
3014 if (forks)
3015 perf_evlist__start_workload(evlist);
3017 if (trace->opts.initial_delay) {
3018 usleep(trace->opts.initial_delay * 1000);
3019 perf_evlist__enable(evlist);
3022 trace->multiple_threads = thread_map__pid(evlist->threads, 0) == -1 ||
3023 evlist->threads->nr > 1 ||
3024 perf_evlist__first(evlist)->attr.inherit;
3027 * Now that we already used evsel->attr to ask the kernel to setup the
3028 * events, lets reuse evsel->attr.sample_max_stack as the limit in
3029 * trace__resolve_callchain(), allowing per-event max-stack settings
3030 * to override an explicitly set --max-stack global setting.
3032 evlist__for_each_entry(evlist, evsel) {
3033 if (evsel__has_callchain(evsel) &&
3034 evsel->attr.sample_max_stack == 0)
3035 evsel->attr.sample_max_stack = trace->max_stack;
3037 again:
3038 before = trace->nr_events;
3040 for (i = 0; i < evlist->nr_mmaps; i++) {
3041 union perf_event *event;
3042 struct perf_mmap *md;
3044 md = &evlist->mmap[i];
3045 if (perf_mmap__read_init(md) < 0)
3046 continue;
3048 while ((event = perf_mmap__read_event(md)) != NULL) {
3049 ++trace->nr_events;
3051 err = trace__deliver_event(trace, event);
3052 if (err)
3053 goto out_disable;
3055 perf_mmap__consume(md);
3057 if (interrupted)
3058 goto out_disable;
3060 if (done && !draining) {
3061 perf_evlist__disable(evlist);
3062 draining = true;
3065 perf_mmap__read_done(md);
3068 if (trace->nr_events == before) {
3069 int timeout = done ? 100 : -1;
3071 if (!draining && perf_evlist__poll(evlist, timeout) > 0) {
3072 if (perf_evlist__filter_pollfd(evlist, POLLERR | POLLHUP | POLLNVAL) == 0)
3073 draining = true;
3075 goto again;
3076 } else {
3077 if (trace__flush_events(trace))
3078 goto out_disable;
3080 } else {
3081 goto again;
3084 out_disable:
3085 thread__zput(trace->current);
3087 perf_evlist__disable(evlist);
3089 if (trace->sort_events)
3090 ordered_events__flush(&trace->oe.data, OE_FLUSH__FINAL);
3092 if (!err) {
3093 if (trace->summary)
3094 trace__fprintf_thread_summary(trace, trace->output);
3096 if (trace->show_tool_stats) {
3097 fprintf(trace->output, "Stats:\n "
3098 " vfs_getname : %" PRIu64 "\n"
3099 " proc_getname: %" PRIu64 "\n",
3100 trace->stats.vfs_getname,
3101 trace->stats.proc_getname);
3105 out_delete_evlist:
3106 trace__symbols__exit(trace);
3108 perf_evlist__delete(evlist);
3109 cgroup__put(trace->cgroup);
3110 trace->evlist = NULL;
3111 trace->live = false;
3112 return err;
3114 char errbuf[BUFSIZ];
3116 out_error_sched_stat_runtime:
3117 tracing_path__strerror_open_tp(errno, errbuf, sizeof(errbuf), "sched", "sched_stat_runtime");
3118 goto out_error;
3120 out_error_raw_syscalls:
3121 tracing_path__strerror_open_tp(errno, errbuf, sizeof(errbuf), "raw_syscalls", "sys_(enter|exit)");
3122 goto out_error;
3124 out_error_mmap:
3125 perf_evlist__strerror_mmap(evlist, errno, errbuf, sizeof(errbuf));
3126 goto out_error;
3128 out_error_open:
3129 perf_evlist__strerror_open(evlist, errno, errbuf, sizeof(errbuf));
3131 out_error:
3132 fprintf(trace->output, "%s\n", errbuf);
3133 goto out_delete_evlist;
3135 out_error_apply_filters:
3136 fprintf(trace->output,
3137 "Failed to set filter \"%s\" on event %s with %d (%s)\n",
3138 evsel->filter, perf_evsel__name(evsel), errno,
3139 str_error_r(errno, errbuf, sizeof(errbuf)));
3140 goto out_delete_evlist;
3142 out_error_mem:
3143 fprintf(trace->output, "Not enough memory to run!\n");
3144 goto out_delete_evlist;
3146 out_errno:
3147 fprintf(trace->output, "errno=%d,%s\n", errno, strerror(errno));
3148 goto out_delete_evlist;
3151 static int trace__replay(struct trace *trace)
3153 const struct perf_evsel_str_handler handlers[] = {
3154 { "probe:vfs_getname", trace__vfs_getname, },
3156 struct perf_data data = {
3157 .path = input_name,
3158 .mode = PERF_DATA_MODE_READ,
3159 .force = trace->force,
3161 struct perf_session *session;
3162 struct perf_evsel *evsel;
3163 int err = -1;
3165 trace->tool.sample = trace__process_sample;
3166 trace->tool.mmap = perf_event__process_mmap;
3167 trace->tool.mmap2 = perf_event__process_mmap2;
3168 trace->tool.comm = perf_event__process_comm;
3169 trace->tool.exit = perf_event__process_exit;
3170 trace->tool.fork = perf_event__process_fork;
3171 trace->tool.attr = perf_event__process_attr;
3172 trace->tool.tracing_data = perf_event__process_tracing_data;
3173 trace->tool.build_id = perf_event__process_build_id;
3174 trace->tool.namespaces = perf_event__process_namespaces;
3176 trace->tool.ordered_events = true;
3177 trace->tool.ordering_requires_timestamps = true;
3179 /* add tid to output */
3180 trace->multiple_threads = true;
3182 session = perf_session__new(&data, false, &trace->tool);
3183 if (session == NULL)
3184 return -1;
3186 if (trace->opts.target.pid)
3187 symbol_conf.pid_list_str = strdup(trace->opts.target.pid);
3189 if (trace->opts.target.tid)
3190 symbol_conf.tid_list_str = strdup(trace->opts.target.tid);
3192 if (symbol__init(&session->header.env) < 0)
3193 goto out;
3195 trace->host = &session->machines.host;
3197 err = perf_session__set_tracepoints_handlers(session, handlers);
3198 if (err)
3199 goto out;
3201 evsel = perf_evlist__find_tracepoint_by_name(session->evlist,
3202 "raw_syscalls:sys_enter");
3203 /* older kernels have syscalls tp versus raw_syscalls */
3204 if (evsel == NULL)
3205 evsel = perf_evlist__find_tracepoint_by_name(session->evlist,
3206 "syscalls:sys_enter");
3208 if (evsel &&
3209 (perf_evsel__init_raw_syscall_tp(evsel, trace__sys_enter) < 0 ||
3210 perf_evsel__init_sc_tp_ptr_field(evsel, args))) {
3211 pr_err("Error during initialize raw_syscalls:sys_enter event\n");
3212 goto out;
3215 evsel = perf_evlist__find_tracepoint_by_name(session->evlist,
3216 "raw_syscalls:sys_exit");
3217 if (evsel == NULL)
3218 evsel = perf_evlist__find_tracepoint_by_name(session->evlist,
3219 "syscalls:sys_exit");
3220 if (evsel &&
3221 (perf_evsel__init_raw_syscall_tp(evsel, trace__sys_exit) < 0 ||
3222 perf_evsel__init_sc_tp_uint_field(evsel, ret))) {
3223 pr_err("Error during initialize raw_syscalls:sys_exit event\n");
3224 goto out;
3227 evlist__for_each_entry(session->evlist, evsel) {
3228 if (evsel->attr.type == PERF_TYPE_SOFTWARE &&
3229 (evsel->attr.config == PERF_COUNT_SW_PAGE_FAULTS_MAJ ||
3230 evsel->attr.config == PERF_COUNT_SW_PAGE_FAULTS_MIN ||
3231 evsel->attr.config == PERF_COUNT_SW_PAGE_FAULTS))
3232 evsel->handler = trace__pgfault;
3235 setup_pager();
3237 err = perf_session__process_events(session);
3238 if (err)
3239 pr_err("Failed to process events, error %d", err);
3241 else if (trace->summary)
3242 trace__fprintf_thread_summary(trace, trace->output);
3244 out:
3245 perf_session__delete(session);
3247 return err;
3250 static size_t trace__fprintf_threads_header(FILE *fp)
3252 size_t printed;
3254 printed = fprintf(fp, "\n Summary of events:\n\n");
3256 return printed;
3259 DEFINE_RESORT_RB(syscall_stats, a->msecs > b->msecs,
3260 struct stats *stats;
3261 double msecs;
3262 int syscall;
3265 struct int_node *source = rb_entry(nd, struct int_node, rb_node);
3266 struct stats *stats = source->priv;
3268 entry->syscall = source->i;
3269 entry->stats = stats;
3270 entry->msecs = stats ? (u64)stats->n * (avg_stats(stats) / NSEC_PER_MSEC) : 0;
3273 static size_t thread__dump_stats(struct thread_trace *ttrace,
3274 struct trace *trace, FILE *fp)
3276 size_t printed = 0;
3277 struct syscall *sc;
3278 struct rb_node *nd;
3279 DECLARE_RESORT_RB_INTLIST(syscall_stats, ttrace->syscall_stats);
3281 if (syscall_stats == NULL)
3282 return 0;
3284 printed += fprintf(fp, "\n");
3286 printed += fprintf(fp, " syscall calls total min avg max stddev\n");
3287 printed += fprintf(fp, " (msec) (msec) (msec) (msec) (%%)\n");
3288 printed += fprintf(fp, " --------------- -------- --------- --------- --------- --------- ------\n");
3290 resort_rb__for_each_entry(nd, syscall_stats) {
3291 struct stats *stats = syscall_stats_entry->stats;
3292 if (stats) {
3293 double min = (double)(stats->min) / NSEC_PER_MSEC;
3294 double max = (double)(stats->max) / NSEC_PER_MSEC;
3295 double avg = avg_stats(stats);
3296 double pct;
3297 u64 n = (u64) stats->n;
3299 pct = avg ? 100.0 * stddev_stats(stats)/avg : 0.0;
3300 avg /= NSEC_PER_MSEC;
3302 sc = &trace->syscalls.table[syscall_stats_entry->syscall];
3303 printed += fprintf(fp, " %-15s", sc->name);
3304 printed += fprintf(fp, " %8" PRIu64 " %9.3f %9.3f %9.3f",
3305 n, syscall_stats_entry->msecs, min, avg);
3306 printed += fprintf(fp, " %9.3f %9.2f%%\n", max, pct);
3310 resort_rb__delete(syscall_stats);
3311 printed += fprintf(fp, "\n\n");
3313 return printed;
3316 static size_t trace__fprintf_thread(FILE *fp, struct thread *thread, struct trace *trace)
3318 size_t printed = 0;
3319 struct thread_trace *ttrace = thread__priv(thread);
3320 double ratio;
3322 if (ttrace == NULL)
3323 return 0;
3325 ratio = (double)ttrace->nr_events / trace->nr_events * 100.0;
3327 printed += fprintf(fp, " %s (%d), ", thread__comm_str(thread), thread->tid);
3328 printed += fprintf(fp, "%lu events, ", ttrace->nr_events);
3329 printed += fprintf(fp, "%.1f%%", ratio);
3330 if (ttrace->pfmaj)
3331 printed += fprintf(fp, ", %lu majfaults", ttrace->pfmaj);
3332 if (ttrace->pfmin)
3333 printed += fprintf(fp, ", %lu minfaults", ttrace->pfmin);
3334 if (trace->sched)
3335 printed += fprintf(fp, ", %.3f msec\n", ttrace->runtime_ms);
3336 else if (fputc('\n', fp) != EOF)
3337 ++printed;
3339 printed += thread__dump_stats(ttrace, trace, fp);
3341 return printed;
3344 static unsigned long thread__nr_events(struct thread_trace *ttrace)
3346 return ttrace ? ttrace->nr_events : 0;
3349 DEFINE_RESORT_RB(threads, (thread__nr_events(a->thread->priv) < thread__nr_events(b->thread->priv)),
3350 struct thread *thread;
3353 entry->thread = rb_entry(nd, struct thread, rb_node);
3356 static size_t trace__fprintf_thread_summary(struct trace *trace, FILE *fp)
3358 size_t printed = trace__fprintf_threads_header(fp);
3359 struct rb_node *nd;
3360 int i;
3362 for (i = 0; i < THREADS__TABLE_SIZE; i++) {
3363 DECLARE_RESORT_RB_MACHINE_THREADS(threads, trace->host, i);
3365 if (threads == NULL) {
3366 fprintf(fp, "%s", "Error sorting output by nr_events!\n");
3367 return 0;
3370 resort_rb__for_each_entry(nd, threads)
3371 printed += trace__fprintf_thread(fp, threads_entry->thread, trace);
3373 resort_rb__delete(threads);
3375 return printed;
3378 static int trace__set_duration(const struct option *opt, const char *str,
3379 int unset __maybe_unused)
3381 struct trace *trace = opt->value;
3383 trace->duration_filter = atof(str);
3384 return 0;
3387 static int trace__set_filter_pids_from_option(const struct option *opt, const char *str,
3388 int unset __maybe_unused)
3390 int ret = -1;
3391 size_t i;
3392 struct trace *trace = opt->value;
3394 * FIXME: introduce a intarray class, plain parse csv and create a
3395 * { int nr, int entries[] } struct...
3397 struct intlist *list = intlist__new(str);
3399 if (list == NULL)
3400 return -1;
3402 i = trace->filter_pids.nr = intlist__nr_entries(list) + 1;
3403 trace->filter_pids.entries = calloc(i, sizeof(pid_t));
3405 if (trace->filter_pids.entries == NULL)
3406 goto out;
3408 trace->filter_pids.entries[0] = getpid();
3410 for (i = 1; i < trace->filter_pids.nr; ++i)
3411 trace->filter_pids.entries[i] = intlist__entry(list, i - 1)->i;
3413 intlist__delete(list);
3414 ret = 0;
3415 out:
3416 return ret;
3419 static int trace__open_output(struct trace *trace, const char *filename)
3421 struct stat st;
3423 if (!stat(filename, &st) && st.st_size) {
3424 char oldname[PATH_MAX];
3426 scnprintf(oldname, sizeof(oldname), "%s.old", filename);
3427 unlink(oldname);
3428 rename(filename, oldname);
3431 trace->output = fopen(filename, "w");
3433 return trace->output == NULL ? -errno : 0;
3436 static int parse_pagefaults(const struct option *opt, const char *str,
3437 int unset __maybe_unused)
3439 int *trace_pgfaults = opt->value;
3441 if (strcmp(str, "all") == 0)
3442 *trace_pgfaults |= TRACE_PFMAJ | TRACE_PFMIN;
3443 else if (strcmp(str, "maj") == 0)
3444 *trace_pgfaults |= TRACE_PFMAJ;
3445 else if (strcmp(str, "min") == 0)
3446 *trace_pgfaults |= TRACE_PFMIN;
3447 else
3448 return -1;
3450 return 0;
3453 static void evlist__set_evsel_handler(struct perf_evlist *evlist, void *handler)
3455 struct perf_evsel *evsel;
3457 evlist__for_each_entry(evlist, evsel)
3458 evsel->handler = handler;
3461 static int evlist__set_syscall_tp_fields(struct perf_evlist *evlist)
3463 struct perf_evsel *evsel;
3465 evlist__for_each_entry(evlist, evsel) {
3466 if (evsel->priv || !evsel->tp_format)
3467 continue;
3469 if (strcmp(evsel->tp_format->system, "syscalls"))
3470 continue;
3472 if (perf_evsel__init_syscall_tp(evsel))
3473 return -1;
3475 if (!strncmp(evsel->tp_format->name, "sys_enter_", 10)) {
3476 struct syscall_tp *sc = evsel->priv;
3478 if (__tp_field__init_ptr(&sc->args, sc->id.offset + sizeof(u64)))
3479 return -1;
3480 } else if (!strncmp(evsel->tp_format->name, "sys_exit_", 9)) {
3481 struct syscall_tp *sc = evsel->priv;
3483 if (__tp_field__init_uint(&sc->ret, sizeof(u64), sc->id.offset + sizeof(u64), evsel->needs_swap))
3484 return -1;
3488 return 0;
3492 * XXX: Hackish, just splitting the combined -e+--event (syscalls
3493 * (raw_syscalls:{sys_{enter,exit}} + events (tracepoints, HW, SW, etc) to use
3494 * existing facilities unchanged (trace->ev_qualifier + parse_options()).
3496 * It'd be better to introduce a parse_options() variant that would return a
3497 * list with the terms it didn't match to an event...
3499 static int trace__parse_events_option(const struct option *opt, const char *str,
3500 int unset __maybe_unused)
3502 struct trace *trace = (struct trace *)opt->value;
3503 const char *s = str;
3504 char *sep = NULL, *lists[2] = { NULL, NULL, };
3505 int len = strlen(str) + 1, err = -1, list, idx;
3506 char *strace_groups_dir = system_path(STRACE_GROUPS_DIR);
3507 char group_name[PATH_MAX];
3508 struct syscall_fmt *fmt;
3510 if (strace_groups_dir == NULL)
3511 return -1;
3513 if (*s == '!') {
3514 ++s;
3515 trace->not_ev_qualifier = true;
3518 while (1) {
3519 if ((sep = strchr(s, ',')) != NULL)
3520 *sep = '\0';
3522 list = 0;
3523 if (syscalltbl__id(trace->sctbl, s) >= 0 ||
3524 syscalltbl__strglobmatch_first(trace->sctbl, s, &idx) >= 0) {
3525 list = 1;
3526 goto do_concat;
3529 fmt = syscall_fmt__find_by_alias(s);
3530 if (fmt != NULL) {
3531 list = 1;
3532 s = fmt->name;
3533 } else {
3534 path__join(group_name, sizeof(group_name), strace_groups_dir, s);
3535 if (access(group_name, R_OK) == 0)
3536 list = 1;
3538 do_concat:
3539 if (lists[list]) {
3540 sprintf(lists[list] + strlen(lists[list]), ",%s", s);
3541 } else {
3542 lists[list] = malloc(len);
3543 if (lists[list] == NULL)
3544 goto out;
3545 strcpy(lists[list], s);
3548 if (!sep)
3549 break;
3551 *sep = ',';
3552 s = sep + 1;
3555 if (lists[1] != NULL) {
3556 struct strlist_config slist_config = {
3557 .dirname = strace_groups_dir,
3560 trace->ev_qualifier = strlist__new(lists[1], &slist_config);
3561 if (trace->ev_qualifier == NULL) {
3562 fputs("Not enough memory to parse event qualifier", trace->output);
3563 goto out;
3566 if (trace__validate_ev_qualifier(trace))
3567 goto out;
3568 trace->trace_syscalls = true;
3571 err = 0;
3573 if (lists[0]) {
3574 struct option o = OPT_CALLBACK('e', "event", &trace->evlist, "event",
3575 "event selector. use 'perf list' to list available events",
3576 parse_events_option);
3577 err = parse_events_option(&o, lists[0], 0);
3579 out:
3580 if (sep)
3581 *sep = ',';
3583 return err;
3586 static int trace__parse_cgroups(const struct option *opt, const char *str, int unset)
3588 struct trace *trace = opt->value;
3590 if (!list_empty(&trace->evlist->entries))
3591 return parse_cgroups(opt, str, unset);
3593 trace->cgroup = evlist__findnew_cgroup(trace->evlist, str);
3595 return 0;
3598 static struct bpf_map *bpf__find_map_by_name(const char *name)
3600 struct bpf_object *obj, *tmp;
3602 bpf_object__for_each_safe(obj, tmp) {
3603 struct bpf_map *map = bpf_object__find_map_by_name(obj, name);
3604 if (map)
3605 return map;
3609 return NULL;
3612 static void trace__set_bpf_map_filtered_pids(struct trace *trace)
3614 trace->filter_pids.map = bpf__find_map_by_name("pids_filtered");
3617 static void trace__set_bpf_map_syscalls(struct trace *trace)
3619 trace->syscalls.map = bpf__find_map_by_name("syscalls");
3622 static int trace__config(const char *var, const char *value, void *arg)
3624 struct trace *trace = arg;
3625 int err = 0;
3627 if (!strcmp(var, "trace.add_events")) {
3628 struct option o = OPT_CALLBACK('e', "event", &trace->evlist, "event",
3629 "event selector. use 'perf list' to list available events",
3630 parse_events_option);
3631 err = parse_events_option(&o, value, 0);
3632 } else if (!strcmp(var, "trace.show_timestamp")) {
3633 trace->show_tstamp = perf_config_bool(var, value);
3634 } else if (!strcmp(var, "trace.show_duration")) {
3635 trace->show_duration = perf_config_bool(var, value);
3636 } else if (!strcmp(var, "trace.show_arg_names")) {
3637 trace->show_arg_names = perf_config_bool(var, value);
3638 if (!trace->show_arg_names)
3639 trace->show_zeros = true;
3640 } else if (!strcmp(var, "trace.show_zeros")) {
3641 bool new_show_zeros = perf_config_bool(var, value);
3642 if (!trace->show_arg_names && !new_show_zeros) {
3643 pr_warning("trace.show_zeros has to be set when trace.show_arg_names=no\n");
3644 goto out;
3646 trace->show_zeros = new_show_zeros;
3647 } else if (!strcmp(var, "trace.show_prefix")) {
3648 trace->show_string_prefix = perf_config_bool(var, value);
3649 } else if (!strcmp(var, "trace.no_inherit")) {
3650 trace->opts.no_inherit = perf_config_bool(var, value);
3651 } else if (!strcmp(var, "trace.args_alignment")) {
3652 int args_alignment = 0;
3653 if (perf_config_int(&args_alignment, var, value) == 0)
3654 trace->args_alignment = args_alignment;
3656 out:
3657 return err;
3660 int cmd_trace(int argc, const char **argv)
3662 const char *trace_usage[] = {
3663 "perf trace [<options>] [<command>]",
3664 "perf trace [<options>] -- <command> [<options>]",
3665 "perf trace record [<options>] [<command>]",
3666 "perf trace record [<options>] -- <command> [<options>]",
3667 NULL
3669 struct trace trace = {
3670 .syscalls = {
3671 . max = -1,
3673 .opts = {
3674 .target = {
3675 .uid = UINT_MAX,
3676 .uses_mmap = true,
3678 .user_freq = UINT_MAX,
3679 .user_interval = ULLONG_MAX,
3680 .no_buffering = true,
3681 .mmap_pages = UINT_MAX,
3683 .output = stderr,
3684 .show_comm = true,
3685 .show_tstamp = true,
3686 .show_duration = true,
3687 .show_arg_names = true,
3688 .args_alignment = 70,
3689 .trace_syscalls = false,
3690 .kernel_syscallchains = false,
3691 .max_stack = UINT_MAX,
3692 .max_events = ULONG_MAX,
3694 const char *map_dump_str = NULL;
3695 const char *output_name = NULL;
3696 const struct option trace_options[] = {
3697 OPT_CALLBACK('e', "event", &trace, "event",
3698 "event/syscall selector. use 'perf list' to list available events",
3699 trace__parse_events_option),
3700 OPT_BOOLEAN(0, "comm", &trace.show_comm,
3701 "show the thread COMM next to its id"),
3702 OPT_BOOLEAN(0, "tool_stats", &trace.show_tool_stats, "show tool stats"),
3703 OPT_CALLBACK(0, "expr", &trace, "expr", "list of syscalls/events to trace",
3704 trace__parse_events_option),
3705 OPT_STRING('o', "output", &output_name, "file", "output file name"),
3706 OPT_STRING('i', "input", &input_name, "file", "Analyze events in file"),
3707 OPT_STRING('p', "pid", &trace.opts.target.pid, "pid",
3708 "trace events on existing process id"),
3709 OPT_STRING('t', "tid", &trace.opts.target.tid, "tid",
3710 "trace events on existing thread id"),
3711 OPT_CALLBACK(0, "filter-pids", &trace, "CSV list of pids",
3712 "pids to filter (by the kernel)", trace__set_filter_pids_from_option),
3713 OPT_BOOLEAN('a', "all-cpus", &trace.opts.target.system_wide,
3714 "system-wide collection from all CPUs"),
3715 OPT_STRING('C', "cpu", &trace.opts.target.cpu_list, "cpu",
3716 "list of cpus to monitor"),
3717 OPT_BOOLEAN(0, "no-inherit", &trace.opts.no_inherit,
3718 "child tasks do not inherit counters"),
3719 OPT_CALLBACK('m', "mmap-pages", &trace.opts.mmap_pages, "pages",
3720 "number of mmap data pages",
3721 perf_evlist__parse_mmap_pages),
3722 OPT_STRING('u', "uid", &trace.opts.target.uid_str, "user",
3723 "user to profile"),
3724 OPT_CALLBACK(0, "duration", &trace, "float",
3725 "show only events with duration > N.M ms",
3726 trace__set_duration),
3727 #ifdef HAVE_LIBBPF_SUPPORT
3728 OPT_STRING(0, "map-dump", &map_dump_str, "BPF map", "BPF map to periodically dump"),
3729 #endif
3730 OPT_BOOLEAN(0, "sched", &trace.sched, "show blocking scheduler events"),
3731 OPT_INCR('v', "verbose", &verbose, "be more verbose"),
3732 OPT_BOOLEAN('T', "time", &trace.full_time,
3733 "Show full timestamp, not time relative to first start"),
3734 OPT_BOOLEAN(0, "failure", &trace.failure_only,
3735 "Show only syscalls that failed"),
3736 OPT_BOOLEAN('s', "summary", &trace.summary_only,
3737 "Show only syscall summary with statistics"),
3738 OPT_BOOLEAN('S', "with-summary", &trace.summary,
3739 "Show all syscalls and summary with statistics"),
3740 OPT_CALLBACK_DEFAULT('F', "pf", &trace.trace_pgfaults, "all|maj|min",
3741 "Trace pagefaults", parse_pagefaults, "maj"),
3742 OPT_BOOLEAN(0, "syscalls", &trace.trace_syscalls, "Trace syscalls"),
3743 OPT_BOOLEAN('f', "force", &trace.force, "don't complain, do it"),
3744 OPT_CALLBACK(0, "call-graph", &trace.opts,
3745 "record_mode[,record_size]", record_callchain_help,
3746 &record_parse_callchain_opt),
3747 OPT_BOOLEAN(0, "kernel-syscall-graph", &trace.kernel_syscallchains,
3748 "Show the kernel callchains on the syscall exit path"),
3749 OPT_ULONG(0, "max-events", &trace.max_events,
3750 "Set the maximum number of events to print, exit after that is reached. "),
3751 OPT_UINTEGER(0, "min-stack", &trace.min_stack,
3752 "Set the minimum stack depth when parsing the callchain, "
3753 "anything below the specified depth will be ignored."),
3754 OPT_UINTEGER(0, "max-stack", &trace.max_stack,
3755 "Set the maximum stack depth when parsing the callchain, "
3756 "anything beyond the specified depth will be ignored. "
3757 "Default: kernel.perf_event_max_stack or " __stringify(PERF_MAX_STACK_DEPTH)),
3758 OPT_BOOLEAN(0, "sort-events", &trace.sort_events,
3759 "Sort batch of events before processing, use if getting out of order events"),
3760 OPT_BOOLEAN(0, "print-sample", &trace.print_sample,
3761 "print the PERF_RECORD_SAMPLE PERF_SAMPLE_ info, for debugging"),
3762 OPT_UINTEGER(0, "proc-map-timeout", &proc_map_timeout,
3763 "per thread proc mmap processing timeout in ms"),
3764 OPT_CALLBACK('G', "cgroup", &trace, "name", "monitor event in cgroup name only",
3765 trace__parse_cgroups),
3766 OPT_UINTEGER('D', "delay", &trace.opts.initial_delay,
3767 "ms to wait before starting measurement after program "
3768 "start"),
3769 OPT_END()
3771 bool __maybe_unused max_stack_user_set = true;
3772 bool mmap_pages_user_set = true;
3773 struct perf_evsel *evsel;
3774 const char * const trace_subcommands[] = { "record", NULL };
3775 int err = -1;
3776 char bf[BUFSIZ];
3778 signal(SIGSEGV, sighandler_dump_stack);
3779 signal(SIGFPE, sighandler_dump_stack);
3781 trace.evlist = perf_evlist__new();
3782 trace.sctbl = syscalltbl__new();
3784 if (trace.evlist == NULL || trace.sctbl == NULL) {
3785 pr_err("Not enough memory to run!\n");
3786 err = -ENOMEM;
3787 goto out;
3790 err = perf_config(trace__config, &trace);
3791 if (err)
3792 goto out;
3794 argc = parse_options_subcommand(argc, argv, trace_options, trace_subcommands,
3795 trace_usage, PARSE_OPT_STOP_AT_NON_OPTION);
3797 if ((nr_cgroups || trace.cgroup) && !trace.opts.target.system_wide) {
3798 usage_with_options_msg(trace_usage, trace_options,
3799 "cgroup monitoring only available in system-wide mode");
3802 evsel = bpf__setup_output_event(trace.evlist, "__augmented_syscalls__");
3803 if (IS_ERR(evsel)) {
3804 bpf__strerror_setup_output_event(trace.evlist, PTR_ERR(evsel), bf, sizeof(bf));
3805 pr_err("ERROR: Setup trace syscalls enter failed: %s\n", bf);
3806 goto out;
3809 if (evsel) {
3810 trace.syscalls.events.augmented = evsel;
3811 trace__set_bpf_map_filtered_pids(&trace);
3812 trace__set_bpf_map_syscalls(&trace);
3815 err = bpf__setup_stdout(trace.evlist);
3816 if (err) {
3817 bpf__strerror_setup_stdout(trace.evlist, err, bf, sizeof(bf));
3818 pr_err("ERROR: Setup BPF stdout failed: %s\n", bf);
3819 goto out;
3822 err = -1;
3824 if (map_dump_str) {
3825 trace.dump.map = bpf__find_map_by_name(map_dump_str);
3826 if (trace.dump.map == NULL) {
3827 pr_err("ERROR: BPF map \"%s\" not found\n", map_dump_str);
3828 goto out;
3832 if (trace.trace_pgfaults) {
3833 trace.opts.sample_address = true;
3834 trace.opts.sample_time = true;
3837 if (trace.opts.mmap_pages == UINT_MAX)
3838 mmap_pages_user_set = false;
3840 if (trace.max_stack == UINT_MAX) {
3841 trace.max_stack = input_name ? PERF_MAX_STACK_DEPTH : sysctl__max_stack();
3842 max_stack_user_set = false;
3845 #ifdef HAVE_DWARF_UNWIND_SUPPORT
3846 if ((trace.min_stack || max_stack_user_set) && !callchain_param.enabled) {
3847 record_opts__parse_callchain(&trace.opts, &callchain_param, "dwarf", false);
3849 #endif
3851 if (callchain_param.enabled) {
3852 if (!mmap_pages_user_set && geteuid() == 0)
3853 trace.opts.mmap_pages = perf_event_mlock_kb_in_pages() * 4;
3855 symbol_conf.use_callchain = true;
3858 if (trace.evlist->nr_entries > 0) {
3859 evlist__set_evsel_handler(trace.evlist, trace__event_handler);
3860 if (evlist__set_syscall_tp_fields(trace.evlist)) {
3861 perror("failed to set syscalls:* tracepoint fields");
3862 goto out;
3866 if (trace.sort_events) {
3867 ordered_events__init(&trace.oe.data, ordered_events__deliver_event, &trace);
3868 ordered_events__set_copy_on_queue(&trace.oe.data, true);
3872 * If we are augmenting syscalls, then combine what we put in the
3873 * __augmented_syscalls__ BPF map with what is in the
3874 * syscalls:sys_exit_FOO tracepoints, i.e. just like we do without BPF,
3875 * combining raw_syscalls:sys_enter with raw_syscalls:sys_exit.
3877 * We'll switch to look at two BPF maps, one for sys_enter and the
3878 * other for sys_exit when we start augmenting the sys_exit paths with
3879 * buffers that are being copied from kernel to userspace, think 'read'
3880 * syscall.
3882 if (trace.syscalls.events.augmented) {
3883 evlist__for_each_entry(trace.evlist, evsel) {
3884 bool raw_syscalls_sys_exit = strcmp(perf_evsel__name(evsel), "raw_syscalls:sys_exit") == 0;
3886 if (raw_syscalls_sys_exit) {
3887 trace.raw_augmented_syscalls = true;
3888 goto init_augmented_syscall_tp;
3891 if (trace.syscalls.events.augmented->priv == NULL &&
3892 strstr(perf_evsel__name(evsel), "syscalls:sys_enter")) {
3893 struct perf_evsel *augmented = trace.syscalls.events.augmented;
3894 if (perf_evsel__init_augmented_syscall_tp(augmented, evsel) ||
3895 perf_evsel__init_augmented_syscall_tp_args(augmented))
3896 goto out;
3897 augmented->handler = trace__sys_enter;
3900 if (strstarts(perf_evsel__name(evsel), "syscalls:sys_exit_")) {
3901 struct syscall_tp *sc;
3902 init_augmented_syscall_tp:
3903 if (perf_evsel__init_augmented_syscall_tp(evsel, evsel))
3904 goto out;
3905 sc = evsel->priv;
3907 * For now with BPF raw_augmented we hook into
3908 * raw_syscalls:sys_enter and there we get all
3909 * 6 syscall args plus the tracepoint common
3910 * fields and the syscall_nr (another long).
3911 * So we check if that is the case and if so
3912 * don't look after the sc->args_size but
3913 * always after the full raw_syscalls:sys_enter
3914 * payload, which is fixed.
3916 * We'll revisit this later to pass
3917 * s->args_size to the BPF augmenter (now
3918 * tools/perf/examples/bpf/augmented_raw_syscalls.c,
3919 * so that it copies only what we need for each
3920 * syscall, like what happens when we use
3921 * syscalls:sys_enter_NAME, so that we reduce
3922 * the kernel/userspace traffic to just what is
3923 * needed for each syscall.
3925 if (trace.raw_augmented_syscalls)
3926 trace.raw_augmented_syscalls_args_size = (6 + 1) * sizeof(long) + sc->id.offset;
3927 perf_evsel__init_augmented_syscall_tp_ret(evsel);
3928 evsel->handler = trace__sys_exit;
3933 if ((argc >= 1) && (strcmp(argv[0], "record") == 0))
3934 return trace__record(&trace, argc-1, &argv[1]);
3936 /* summary_only implies summary option, but don't overwrite summary if set */
3937 if (trace.summary_only)
3938 trace.summary = trace.summary_only;
3940 if (!trace.trace_syscalls && !trace.trace_pgfaults &&
3941 trace.evlist->nr_entries == 0 /* Was --events used? */) {
3942 trace.trace_syscalls = true;
3945 if (output_name != NULL) {
3946 err = trace__open_output(&trace, output_name);
3947 if (err < 0) {
3948 perror("failed to create output file");
3949 goto out;
3953 err = target__validate(&trace.opts.target);
3954 if (err) {
3955 target__strerror(&trace.opts.target, err, bf, sizeof(bf));
3956 fprintf(trace.output, "%s", bf);
3957 goto out_close;
3960 err = target__parse_uid(&trace.opts.target);
3961 if (err) {
3962 target__strerror(&trace.opts.target, err, bf, sizeof(bf));
3963 fprintf(trace.output, "%s", bf);
3964 goto out_close;
3967 if (!argc && target__none(&trace.opts.target))
3968 trace.opts.target.system_wide = true;
3970 if (input_name)
3971 err = trace__replay(&trace);
3972 else
3973 err = trace__run(&trace, argc, argv);
3975 out_close:
3976 if (output_name != NULL)
3977 fclose(trace.output);
3978 out:
3979 return err;