perf tools: Use fallback for sample_addr_correlates_sym() cases
[linux/fpc-iii.git] / tools / perf / builtin-trace.c
blob8e3c3f74a3a40d9954dde999d4b96f87434cf444
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 "builtin.h"
23 #include "util/cgroup.h"
24 #include "util/color.h"
25 #include "util/debug.h"
26 #include "util/env.h"
27 #include "util/event.h"
28 #include "util/evlist.h"
29 #include <subcmd/exec-cmd.h>
30 #include "util/machine.h"
31 #include "util/path.h"
32 #include "util/session.h"
33 #include "util/thread.h"
34 #include <subcmd/parse-options.h>
35 #include "util/strlist.h"
36 #include "util/intlist.h"
37 #include "util/thread_map.h"
38 #include "util/stat.h"
39 #include "trace/beauty/beauty.h"
40 #include "trace-event.h"
41 #include "util/parse-events.h"
42 #include "util/bpf-loader.h"
43 #include "callchain.h"
44 #include "print_binary.h"
45 #include "string2.h"
46 #include "syscalltbl.h"
47 #include "rb_resort.h"
49 #include <errno.h>
50 #include <inttypes.h>
51 #include <poll.h>
52 #include <signal.h>
53 #include <stdlib.h>
54 #include <string.h>
55 #include <linux/err.h>
56 #include <linux/filter.h>
57 #include <linux/kernel.h>
58 #include <linux/random.h>
59 #include <linux/stringify.h>
60 #include <linux/time64.h>
61 #include <fcntl.h>
63 #include "sane_ctype.h"
65 #ifndef O_CLOEXEC
66 # define O_CLOEXEC 02000000
67 #endif
69 #ifndef F_LINUX_SPECIFIC_BASE
70 # define F_LINUX_SPECIFIC_BASE 1024
71 #endif
73 struct trace {
74 struct perf_tool tool;
75 struct syscalltbl *sctbl;
76 struct {
77 int max;
78 struct syscall *table;
79 struct {
80 struct perf_evsel *sys_enter,
81 *sys_exit,
82 *augmented;
83 } events;
84 } syscalls;
85 struct record_opts opts;
86 struct perf_evlist *evlist;
87 struct machine *host;
88 struct thread *current;
89 struct cgroup *cgroup;
90 u64 base_time;
91 FILE *output;
92 unsigned long nr_events;
93 unsigned long nr_events_printed;
94 unsigned long max_events;
95 struct strlist *ev_qualifier;
96 struct {
97 size_t nr;
98 int *entries;
99 } ev_qualifier_ids;
100 struct {
101 size_t nr;
102 pid_t *entries;
103 struct bpf_map *map;
104 } filter_pids;
105 double duration_filter;
106 double runtime_ms;
107 struct {
108 u64 vfs_getname,
109 proc_getname;
110 } stats;
111 unsigned int max_stack;
112 unsigned int min_stack;
113 bool raw_augmented_syscalls;
114 bool not_ev_qualifier;
115 bool live;
116 bool full_time;
117 bool sched;
118 bool multiple_threads;
119 bool summary;
120 bool summary_only;
121 bool failure_only;
122 bool show_comm;
123 bool print_sample;
124 bool show_tool_stats;
125 bool trace_syscalls;
126 bool kernel_syscallchains;
127 bool force;
128 bool vfs_getname;
129 int trace_pgfaults;
132 struct tp_field {
133 int offset;
134 union {
135 u64 (*integer)(struct tp_field *field, struct perf_sample *sample);
136 void *(*pointer)(struct tp_field *field, struct perf_sample *sample);
140 #define TP_UINT_FIELD(bits) \
141 static u64 tp_field__u##bits(struct tp_field *field, struct perf_sample *sample) \
143 u##bits value; \
144 memcpy(&value, sample->raw_data + field->offset, sizeof(value)); \
145 return value; \
148 TP_UINT_FIELD(8);
149 TP_UINT_FIELD(16);
150 TP_UINT_FIELD(32);
151 TP_UINT_FIELD(64);
153 #define TP_UINT_FIELD__SWAPPED(bits) \
154 static u64 tp_field__swapped_u##bits(struct tp_field *field, struct perf_sample *sample) \
156 u##bits value; \
157 memcpy(&value, sample->raw_data + field->offset, sizeof(value)); \
158 return bswap_##bits(value);\
161 TP_UINT_FIELD__SWAPPED(16);
162 TP_UINT_FIELD__SWAPPED(32);
163 TP_UINT_FIELD__SWAPPED(64);
165 static int __tp_field__init_uint(struct tp_field *field, int size, int offset, bool needs_swap)
167 field->offset = offset;
169 switch (size) {
170 case 1:
171 field->integer = tp_field__u8;
172 break;
173 case 2:
174 field->integer = needs_swap ? tp_field__swapped_u16 : tp_field__u16;
175 break;
176 case 4:
177 field->integer = needs_swap ? tp_field__swapped_u32 : tp_field__u32;
178 break;
179 case 8:
180 field->integer = needs_swap ? tp_field__swapped_u64 : tp_field__u64;
181 break;
182 default:
183 return -1;
186 return 0;
189 static int tp_field__init_uint(struct tp_field *field, struct tep_format_field *format_field, bool needs_swap)
191 return __tp_field__init_uint(field, format_field->size, format_field->offset, needs_swap);
194 static void *tp_field__ptr(struct tp_field *field, struct perf_sample *sample)
196 return sample->raw_data + field->offset;
199 static int __tp_field__init_ptr(struct tp_field *field, int offset)
201 field->offset = offset;
202 field->pointer = tp_field__ptr;
203 return 0;
206 static int tp_field__init_ptr(struct tp_field *field, struct tep_format_field *format_field)
208 return __tp_field__init_ptr(field, format_field->offset);
211 struct syscall_tp {
212 struct tp_field id;
213 union {
214 struct tp_field args, ret;
218 static int perf_evsel__init_tp_uint_field(struct perf_evsel *evsel,
219 struct tp_field *field,
220 const char *name)
222 struct tep_format_field *format_field = perf_evsel__field(evsel, name);
224 if (format_field == NULL)
225 return -1;
227 return tp_field__init_uint(field, format_field, evsel->needs_swap);
230 #define perf_evsel__init_sc_tp_uint_field(evsel, name) \
231 ({ struct syscall_tp *sc = evsel->priv;\
232 perf_evsel__init_tp_uint_field(evsel, &sc->name, #name); })
234 static int perf_evsel__init_tp_ptr_field(struct perf_evsel *evsel,
235 struct tp_field *field,
236 const char *name)
238 struct tep_format_field *format_field = perf_evsel__field(evsel, name);
240 if (format_field == NULL)
241 return -1;
243 return tp_field__init_ptr(field, format_field);
246 #define perf_evsel__init_sc_tp_ptr_field(evsel, name) \
247 ({ struct syscall_tp *sc = evsel->priv;\
248 perf_evsel__init_tp_ptr_field(evsel, &sc->name, #name); })
250 static void perf_evsel__delete_priv(struct perf_evsel *evsel)
252 zfree(&evsel->priv);
253 perf_evsel__delete(evsel);
256 static int perf_evsel__init_syscall_tp(struct perf_evsel *evsel)
258 struct syscall_tp *sc = evsel->priv = malloc(sizeof(struct syscall_tp));
260 if (evsel->priv != NULL) {
261 if (perf_evsel__init_tp_uint_field(evsel, &sc->id, "__syscall_nr"))
262 goto out_delete;
263 return 0;
266 return -ENOMEM;
267 out_delete:
268 zfree(&evsel->priv);
269 return -ENOENT;
272 static int perf_evsel__init_augmented_syscall_tp(struct perf_evsel *evsel)
274 struct syscall_tp *sc = evsel->priv = malloc(sizeof(struct syscall_tp));
276 if (evsel->priv != NULL) { /* field, sizeof_field, offsetof_field */
277 if (__tp_field__init_uint(&sc->id, sizeof(long), sizeof(long long), evsel->needs_swap))
278 goto out_delete;
280 return 0;
283 return -ENOMEM;
284 out_delete:
285 zfree(&evsel->priv);
286 return -EINVAL;
289 static int perf_evsel__init_augmented_syscall_tp_args(struct perf_evsel *evsel)
291 struct syscall_tp *sc = evsel->priv;
293 return __tp_field__init_ptr(&sc->args, sc->id.offset + sizeof(u64));
296 static int perf_evsel__init_augmented_syscall_tp_ret(struct perf_evsel *evsel)
298 struct syscall_tp *sc = evsel->priv;
300 return __tp_field__init_uint(&sc->ret, sizeof(u64), sc->id.offset + sizeof(u64), evsel->needs_swap);
303 static int perf_evsel__init_raw_syscall_tp(struct perf_evsel *evsel, void *handler)
305 evsel->priv = malloc(sizeof(struct syscall_tp));
306 if (evsel->priv != NULL) {
307 if (perf_evsel__init_sc_tp_uint_field(evsel, id))
308 goto out_delete;
310 evsel->handler = handler;
311 return 0;
314 return -ENOMEM;
316 out_delete:
317 zfree(&evsel->priv);
318 return -ENOENT;
321 static struct perf_evsel *perf_evsel__raw_syscall_newtp(const char *direction, void *handler)
323 struct perf_evsel *evsel = perf_evsel__newtp("raw_syscalls", direction);
325 /* older kernel (e.g., RHEL6) use syscalls:{enter,exit} */
326 if (IS_ERR(evsel))
327 evsel = perf_evsel__newtp("syscalls", direction);
329 if (IS_ERR(evsel))
330 return NULL;
332 if (perf_evsel__init_raw_syscall_tp(evsel, handler))
333 goto out_delete;
335 return evsel;
337 out_delete:
338 perf_evsel__delete_priv(evsel);
339 return NULL;
342 #define perf_evsel__sc_tp_uint(evsel, name, sample) \
343 ({ struct syscall_tp *fields = evsel->priv; \
344 fields->name.integer(&fields->name, sample); })
346 #define perf_evsel__sc_tp_ptr(evsel, name, sample) \
347 ({ struct syscall_tp *fields = evsel->priv; \
348 fields->name.pointer(&fields->name, sample); })
350 size_t strarray__scnprintf(struct strarray *sa, char *bf, size_t size, const char *intfmt, int val)
352 int idx = val - sa->offset;
354 if (idx < 0 || idx >= sa->nr_entries || sa->entries[idx] == NULL)
355 return scnprintf(bf, size, intfmt, val);
357 return scnprintf(bf, size, "%s", sa->entries[idx]);
360 static size_t __syscall_arg__scnprintf_strarray(char *bf, size_t size,
361 const char *intfmt,
362 struct syscall_arg *arg)
364 return strarray__scnprintf(arg->parm, bf, size, intfmt, arg->val);
367 static size_t syscall_arg__scnprintf_strarray(char *bf, size_t size,
368 struct syscall_arg *arg)
370 return __syscall_arg__scnprintf_strarray(bf, size, "%d", arg);
373 #define SCA_STRARRAY syscall_arg__scnprintf_strarray
375 struct strarrays {
376 int nr_entries;
377 struct strarray **entries;
380 #define DEFINE_STRARRAYS(array) struct strarrays strarrays__##array = { \
381 .nr_entries = ARRAY_SIZE(array), \
382 .entries = array, \
385 size_t syscall_arg__scnprintf_strarrays(char *bf, size_t size,
386 struct syscall_arg *arg)
388 struct strarrays *sas = arg->parm;
389 int i;
391 for (i = 0; i < sas->nr_entries; ++i) {
392 struct strarray *sa = sas->entries[i];
393 int idx = arg->val - sa->offset;
395 if (idx >= 0 && idx < sa->nr_entries) {
396 if (sa->entries[idx] == NULL)
397 break;
398 return scnprintf(bf, size, "%s", sa->entries[idx]);
402 return scnprintf(bf, size, "%d", arg->val);
405 #ifndef AT_FDCWD
406 #define AT_FDCWD -100
407 #endif
409 static size_t syscall_arg__scnprintf_fd_at(char *bf, size_t size,
410 struct syscall_arg *arg)
412 int fd = arg->val;
414 if (fd == AT_FDCWD)
415 return scnprintf(bf, size, "CWD");
417 return syscall_arg__scnprintf_fd(bf, size, arg);
420 #define SCA_FDAT syscall_arg__scnprintf_fd_at
422 static size_t syscall_arg__scnprintf_close_fd(char *bf, size_t size,
423 struct syscall_arg *arg);
425 #define SCA_CLOSE_FD syscall_arg__scnprintf_close_fd
427 size_t syscall_arg__scnprintf_hex(char *bf, size_t size, struct syscall_arg *arg)
429 return scnprintf(bf, size, "%#lx", arg->val);
432 size_t syscall_arg__scnprintf_int(char *bf, size_t size, struct syscall_arg *arg)
434 return scnprintf(bf, size, "%d", arg->val);
437 size_t syscall_arg__scnprintf_long(char *bf, size_t size, struct syscall_arg *arg)
439 return scnprintf(bf, size, "%ld", arg->val);
442 static const char *bpf_cmd[] = {
443 "MAP_CREATE", "MAP_LOOKUP_ELEM", "MAP_UPDATE_ELEM", "MAP_DELETE_ELEM",
444 "MAP_GET_NEXT_KEY", "PROG_LOAD",
446 static DEFINE_STRARRAY(bpf_cmd);
448 static const char *epoll_ctl_ops[] = { "ADD", "DEL", "MOD", };
449 static DEFINE_STRARRAY_OFFSET(epoll_ctl_ops, 1);
451 static const char *itimers[] = { "REAL", "VIRTUAL", "PROF", };
452 static DEFINE_STRARRAY(itimers);
454 static const char *keyctl_options[] = {
455 "GET_KEYRING_ID", "JOIN_SESSION_KEYRING", "UPDATE", "REVOKE", "CHOWN",
456 "SETPERM", "DESCRIBE", "CLEAR", "LINK", "UNLINK", "SEARCH", "READ",
457 "INSTANTIATE", "NEGATE", "SET_REQKEY_KEYRING", "SET_TIMEOUT",
458 "ASSUME_AUTHORITY", "GET_SECURITY", "SESSION_TO_PARENT", "REJECT",
459 "INSTANTIATE_IOV", "INVALIDATE", "GET_PERSISTENT",
461 static DEFINE_STRARRAY(keyctl_options);
463 static const char *whences[] = { "SET", "CUR", "END",
464 #ifdef SEEK_DATA
465 "DATA",
466 #endif
467 #ifdef SEEK_HOLE
468 "HOLE",
469 #endif
471 static DEFINE_STRARRAY(whences);
473 static const char *fcntl_cmds[] = {
474 "DUPFD", "GETFD", "SETFD", "GETFL", "SETFL", "GETLK", "SETLK",
475 "SETLKW", "SETOWN", "GETOWN", "SETSIG", "GETSIG", "GETLK64",
476 "SETLK64", "SETLKW64", "SETOWN_EX", "GETOWN_EX",
477 "GETOWNER_UIDS",
479 static DEFINE_STRARRAY(fcntl_cmds);
481 static const char *fcntl_linux_specific_cmds[] = {
482 "SETLEASE", "GETLEASE", "NOTIFY", [5] = "CANCELLK", "DUPFD_CLOEXEC",
483 "SETPIPE_SZ", "GETPIPE_SZ", "ADD_SEALS", "GET_SEALS",
484 "GET_RW_HINT", "SET_RW_HINT", "GET_FILE_RW_HINT", "SET_FILE_RW_HINT",
487 static DEFINE_STRARRAY_OFFSET(fcntl_linux_specific_cmds, F_LINUX_SPECIFIC_BASE);
489 static struct strarray *fcntl_cmds_arrays[] = {
490 &strarray__fcntl_cmds,
491 &strarray__fcntl_linux_specific_cmds,
494 static DEFINE_STRARRAYS(fcntl_cmds_arrays);
496 static const char *rlimit_resources[] = {
497 "CPU", "FSIZE", "DATA", "STACK", "CORE", "RSS", "NPROC", "NOFILE",
498 "MEMLOCK", "AS", "LOCKS", "SIGPENDING", "MSGQUEUE", "NICE", "RTPRIO",
499 "RTTIME",
501 static DEFINE_STRARRAY(rlimit_resources);
503 static const char *sighow[] = { "BLOCK", "UNBLOCK", "SETMASK", };
504 static DEFINE_STRARRAY(sighow);
506 static const char *clockid[] = {
507 "REALTIME", "MONOTONIC", "PROCESS_CPUTIME_ID", "THREAD_CPUTIME_ID",
508 "MONOTONIC_RAW", "REALTIME_COARSE", "MONOTONIC_COARSE", "BOOTTIME",
509 "REALTIME_ALARM", "BOOTTIME_ALARM", "SGI_CYCLE", "TAI"
511 static DEFINE_STRARRAY(clockid);
513 static size_t syscall_arg__scnprintf_access_mode(char *bf, size_t size,
514 struct syscall_arg *arg)
516 size_t printed = 0;
517 int mode = arg->val;
519 if (mode == F_OK) /* 0 */
520 return scnprintf(bf, size, "F");
521 #define P_MODE(n) \
522 if (mode & n##_OK) { \
523 printed += scnprintf(bf + printed, size - printed, "%s", #n); \
524 mode &= ~n##_OK; \
527 P_MODE(R);
528 P_MODE(W);
529 P_MODE(X);
530 #undef P_MODE
532 if (mode)
533 printed += scnprintf(bf + printed, size - printed, "|%#x", mode);
535 return printed;
538 #define SCA_ACCMODE syscall_arg__scnprintf_access_mode
540 static size_t syscall_arg__scnprintf_filename(char *bf, size_t size,
541 struct syscall_arg *arg);
543 #define SCA_FILENAME syscall_arg__scnprintf_filename
545 static size_t syscall_arg__scnprintf_pipe_flags(char *bf, size_t size,
546 struct syscall_arg *arg)
548 int printed = 0, flags = arg->val;
550 #define P_FLAG(n) \
551 if (flags & O_##n) { \
552 printed += scnprintf(bf + printed, size - printed, "%s%s", printed ? "|" : "", #n); \
553 flags &= ~O_##n; \
556 P_FLAG(CLOEXEC);
557 P_FLAG(NONBLOCK);
558 #undef P_FLAG
560 if (flags)
561 printed += scnprintf(bf + printed, size - printed, "%s%#x", printed ? "|" : "", flags);
563 return printed;
566 #define SCA_PIPE_FLAGS syscall_arg__scnprintf_pipe_flags
568 #ifndef GRND_NONBLOCK
569 #define GRND_NONBLOCK 0x0001
570 #endif
571 #ifndef GRND_RANDOM
572 #define GRND_RANDOM 0x0002
573 #endif
575 static size_t syscall_arg__scnprintf_getrandom_flags(char *bf, size_t size,
576 struct syscall_arg *arg)
578 int printed = 0, flags = arg->val;
580 #define P_FLAG(n) \
581 if (flags & GRND_##n) { \
582 printed += scnprintf(bf + printed, size - printed, "%s%s", printed ? "|" : "", #n); \
583 flags &= ~GRND_##n; \
586 P_FLAG(RANDOM);
587 P_FLAG(NONBLOCK);
588 #undef P_FLAG
590 if (flags)
591 printed += scnprintf(bf + printed, size - printed, "%s%#x", printed ? "|" : "", flags);
593 return printed;
596 #define SCA_GETRANDOM_FLAGS syscall_arg__scnprintf_getrandom_flags
598 #define STRARRAY(name, array) \
599 { .scnprintf = SCA_STRARRAY, \
600 .parm = &strarray__##array, }
602 #include "trace/beauty/arch_errno_names.c"
603 #include "trace/beauty/eventfd.c"
604 #include "trace/beauty/futex_op.c"
605 #include "trace/beauty/futex_val3.c"
606 #include "trace/beauty/mmap.c"
607 #include "trace/beauty/mode_t.c"
608 #include "trace/beauty/msg_flags.c"
609 #include "trace/beauty/open_flags.c"
610 #include "trace/beauty/perf_event_open.c"
611 #include "trace/beauty/pid.c"
612 #include "trace/beauty/sched_policy.c"
613 #include "trace/beauty/seccomp.c"
614 #include "trace/beauty/signum.c"
615 #include "trace/beauty/socket_type.c"
616 #include "trace/beauty/waitid_options.c"
618 struct syscall_arg_fmt {
619 size_t (*scnprintf)(char *bf, size_t size, struct syscall_arg *arg);
620 unsigned long (*mask_val)(struct syscall_arg *arg, unsigned long val);
621 void *parm;
622 const char *name;
623 bool show_zero;
626 static struct syscall_fmt {
627 const char *name;
628 const char *alias;
629 struct syscall_arg_fmt arg[6];
630 u8 nr_args;
631 bool errpid;
632 bool timeout;
633 bool hexret;
634 } syscall_fmts[] = {
635 { .name = "access",
636 .arg = { [1] = { .scnprintf = SCA_ACCMODE, /* mode */ }, }, },
637 { .name = "bind",
638 .arg = { [1] = { .scnprintf = SCA_SOCKADDR, /* umyaddr */ }, }, },
639 { .name = "bpf",
640 .arg = { [0] = STRARRAY(cmd, bpf_cmd), }, },
641 { .name = "brk", .hexret = true,
642 .arg = { [0] = { .scnprintf = SCA_HEX, /* brk */ }, }, },
643 { .name = "clock_gettime",
644 .arg = { [0] = STRARRAY(clk_id, clockid), }, },
645 { .name = "clone", .errpid = true, .nr_args = 5,
646 .arg = { [0] = { .name = "flags", .scnprintf = SCA_CLONE_FLAGS, },
647 [1] = { .name = "child_stack", .scnprintf = SCA_HEX, },
648 [2] = { .name = "parent_tidptr", .scnprintf = SCA_HEX, },
649 [3] = { .name = "child_tidptr", .scnprintf = SCA_HEX, },
650 [4] = { .name = "tls", .scnprintf = SCA_HEX, }, }, },
651 { .name = "close",
652 .arg = { [0] = { .scnprintf = SCA_CLOSE_FD, /* fd */ }, }, },
653 { .name = "connect",
654 .arg = { [1] = { .scnprintf = SCA_SOCKADDR, /* servaddr */ }, }, },
655 { .name = "epoll_ctl",
656 .arg = { [1] = STRARRAY(op, epoll_ctl_ops), }, },
657 { .name = "eventfd2",
658 .arg = { [1] = { .scnprintf = SCA_EFD_FLAGS, /* flags */ }, }, },
659 { .name = "fchmodat",
660 .arg = { [0] = { .scnprintf = SCA_FDAT, /* fd */ }, }, },
661 { .name = "fchownat",
662 .arg = { [0] = { .scnprintf = SCA_FDAT, /* fd */ }, }, },
663 { .name = "fcntl",
664 .arg = { [1] = { .scnprintf = SCA_FCNTL_CMD, /* cmd */
665 .parm = &strarrays__fcntl_cmds_arrays,
666 .show_zero = true, },
667 [2] = { .scnprintf = SCA_FCNTL_ARG, /* arg */ }, }, },
668 { .name = "flock",
669 .arg = { [1] = { .scnprintf = SCA_FLOCK, /* cmd */ }, }, },
670 { .name = "fstat", .alias = "newfstat", },
671 { .name = "fstatat", .alias = "newfstatat", },
672 { .name = "futex",
673 .arg = { [1] = { .scnprintf = SCA_FUTEX_OP, /* op */ },
674 [5] = { .scnprintf = SCA_FUTEX_VAL3, /* val3 */ }, }, },
675 { .name = "futimesat",
676 .arg = { [0] = { .scnprintf = SCA_FDAT, /* fd */ }, }, },
677 { .name = "getitimer",
678 .arg = { [0] = STRARRAY(which, itimers), }, },
679 { .name = "getpid", .errpid = true, },
680 { .name = "getpgid", .errpid = true, },
681 { .name = "getppid", .errpid = true, },
682 { .name = "getrandom",
683 .arg = { [2] = { .scnprintf = SCA_GETRANDOM_FLAGS, /* flags */ }, }, },
684 { .name = "getrlimit",
685 .arg = { [0] = STRARRAY(resource, rlimit_resources), }, },
686 { .name = "gettid", .errpid = true, },
687 { .name = "ioctl",
688 .arg = {
689 #if defined(__i386__) || defined(__x86_64__)
691 * FIXME: Make this available to all arches.
693 [1] = { .scnprintf = SCA_IOCTL_CMD, /* cmd */ },
694 [2] = { .scnprintf = SCA_HEX, /* arg */ }, }, },
695 #else
696 [2] = { .scnprintf = SCA_HEX, /* arg */ }, }, },
697 #endif
698 { .name = "kcmp", .nr_args = 5,
699 .arg = { [0] = { .name = "pid1", .scnprintf = SCA_PID, },
700 [1] = { .name = "pid2", .scnprintf = SCA_PID, },
701 [2] = { .name = "type", .scnprintf = SCA_KCMP_TYPE, },
702 [3] = { .name = "idx1", .scnprintf = SCA_KCMP_IDX, },
703 [4] = { .name = "idx2", .scnprintf = SCA_KCMP_IDX, }, }, },
704 { .name = "keyctl",
705 .arg = { [0] = STRARRAY(option, keyctl_options), }, },
706 { .name = "kill",
707 .arg = { [1] = { .scnprintf = SCA_SIGNUM, /* sig */ }, }, },
708 { .name = "linkat",
709 .arg = { [0] = { .scnprintf = SCA_FDAT, /* fd */ }, }, },
710 { .name = "lseek",
711 .arg = { [2] = STRARRAY(whence, whences), }, },
712 { .name = "lstat", .alias = "newlstat", },
713 { .name = "madvise",
714 .arg = { [0] = { .scnprintf = SCA_HEX, /* start */ },
715 [2] = { .scnprintf = SCA_MADV_BHV, /* behavior */ }, }, },
716 { .name = "mkdirat",
717 .arg = { [0] = { .scnprintf = SCA_FDAT, /* fd */ }, }, },
718 { .name = "mknodat",
719 .arg = { [0] = { .scnprintf = SCA_FDAT, /* fd */ }, }, },
720 { .name = "mlock",
721 .arg = { [0] = { .scnprintf = SCA_HEX, /* addr */ }, }, },
722 { .name = "mlockall",
723 .arg = { [0] = { .scnprintf = SCA_HEX, /* addr */ }, }, },
724 { .name = "mmap", .hexret = true,
725 /* The standard mmap maps to old_mmap on s390x */
726 #if defined(__s390x__)
727 .alias = "old_mmap",
728 #endif
729 .arg = { [0] = { .scnprintf = SCA_HEX, /* addr */ },
730 [2] = { .scnprintf = SCA_MMAP_PROT, /* prot */ },
731 [3] = { .scnprintf = SCA_MMAP_FLAGS, /* flags */ }, }, },
732 { .name = "mount",
733 .arg = { [0] = { .scnprintf = SCA_FILENAME, /* dev_name */ },
734 [3] = { .scnprintf = SCA_MOUNT_FLAGS, /* flags */
735 .mask_val = SCAMV_MOUNT_FLAGS, /* flags */ }, }, },
736 { .name = "mprotect",
737 .arg = { [0] = { .scnprintf = SCA_HEX, /* start */ },
738 [2] = { .scnprintf = SCA_MMAP_PROT, /* prot */ }, }, },
739 { .name = "mq_unlink",
740 .arg = { [0] = { .scnprintf = SCA_FILENAME, /* u_name */ }, }, },
741 { .name = "mremap", .hexret = true,
742 .arg = { [0] = { .scnprintf = SCA_HEX, /* addr */ },
743 [3] = { .scnprintf = SCA_MREMAP_FLAGS, /* flags */ },
744 [4] = { .scnprintf = SCA_HEX, /* new_addr */ }, }, },
745 { .name = "munlock",
746 .arg = { [0] = { .scnprintf = SCA_HEX, /* addr */ }, }, },
747 { .name = "munmap",
748 .arg = { [0] = { .scnprintf = SCA_HEX, /* addr */ }, }, },
749 { .name = "name_to_handle_at",
750 .arg = { [0] = { .scnprintf = SCA_FDAT, /* dfd */ }, }, },
751 { .name = "newfstatat",
752 .arg = { [0] = { .scnprintf = SCA_FDAT, /* dfd */ }, }, },
753 { .name = "open",
754 .arg = { [1] = { .scnprintf = SCA_OPEN_FLAGS, /* flags */ }, }, },
755 { .name = "open_by_handle_at",
756 .arg = { [0] = { .scnprintf = SCA_FDAT, /* dfd */ },
757 [2] = { .scnprintf = SCA_OPEN_FLAGS, /* flags */ }, }, },
758 { .name = "openat",
759 .arg = { [0] = { .scnprintf = SCA_FDAT, /* dfd */ },
760 [2] = { .scnprintf = SCA_OPEN_FLAGS, /* flags */ }, }, },
761 { .name = "perf_event_open",
762 .arg = { [2] = { .scnprintf = SCA_INT, /* cpu */ },
763 [3] = { .scnprintf = SCA_FD, /* group_fd */ },
764 [4] = { .scnprintf = SCA_PERF_FLAGS, /* flags */ }, }, },
765 { .name = "pipe2",
766 .arg = { [1] = { .scnprintf = SCA_PIPE_FLAGS, /* flags */ }, }, },
767 { .name = "pkey_alloc",
768 .arg = { [1] = { .scnprintf = SCA_PKEY_ALLOC_ACCESS_RIGHTS, /* access_rights */ }, }, },
769 { .name = "pkey_free",
770 .arg = { [0] = { .scnprintf = SCA_INT, /* key */ }, }, },
771 { .name = "pkey_mprotect",
772 .arg = { [0] = { .scnprintf = SCA_HEX, /* start */ },
773 [2] = { .scnprintf = SCA_MMAP_PROT, /* prot */ },
774 [3] = { .scnprintf = SCA_INT, /* pkey */ }, }, },
775 { .name = "poll", .timeout = true, },
776 { .name = "ppoll", .timeout = true, },
777 { .name = "prctl", .alias = "arch_prctl",
778 .arg = { [0] = { .scnprintf = SCA_PRCTL_OPTION, /* option */ },
779 [1] = { .scnprintf = SCA_PRCTL_ARG2, /* arg2 */ },
780 [2] = { .scnprintf = SCA_PRCTL_ARG3, /* arg3 */ }, }, },
781 { .name = "pread", .alias = "pread64", },
782 { .name = "preadv", .alias = "pread", },
783 { .name = "prlimit64",
784 .arg = { [1] = STRARRAY(resource, rlimit_resources), }, },
785 { .name = "pwrite", .alias = "pwrite64", },
786 { .name = "readlinkat",
787 .arg = { [0] = { .scnprintf = SCA_FDAT, /* dfd */ }, }, },
788 { .name = "recvfrom",
789 .arg = { [3] = { .scnprintf = SCA_MSG_FLAGS, /* flags */ }, }, },
790 { .name = "recvmmsg",
791 .arg = { [3] = { .scnprintf = SCA_MSG_FLAGS, /* flags */ }, }, },
792 { .name = "recvmsg",
793 .arg = { [2] = { .scnprintf = SCA_MSG_FLAGS, /* flags */ }, }, },
794 { .name = "renameat",
795 .arg = { [0] = { .scnprintf = SCA_FDAT, /* dfd */ }, }, },
796 { .name = "rt_sigaction",
797 .arg = { [0] = { .scnprintf = SCA_SIGNUM, /* sig */ }, }, },
798 { .name = "rt_sigprocmask",
799 .arg = { [0] = STRARRAY(how, sighow), }, },
800 { .name = "rt_sigqueueinfo",
801 .arg = { [1] = { .scnprintf = SCA_SIGNUM, /* sig */ }, }, },
802 { .name = "rt_tgsigqueueinfo",
803 .arg = { [2] = { .scnprintf = SCA_SIGNUM, /* sig */ }, }, },
804 { .name = "sched_setscheduler",
805 .arg = { [1] = { .scnprintf = SCA_SCHED_POLICY, /* policy */ }, }, },
806 { .name = "seccomp",
807 .arg = { [0] = { .scnprintf = SCA_SECCOMP_OP, /* op */ },
808 [1] = { .scnprintf = SCA_SECCOMP_FLAGS, /* flags */ }, }, },
809 { .name = "select", .timeout = true, },
810 { .name = "sendmmsg",
811 .arg = { [3] = { .scnprintf = SCA_MSG_FLAGS, /* flags */ }, }, },
812 { .name = "sendmsg",
813 .arg = { [2] = { .scnprintf = SCA_MSG_FLAGS, /* flags */ }, }, },
814 { .name = "sendto",
815 .arg = { [3] = { .scnprintf = SCA_MSG_FLAGS, /* flags */ },
816 [4] = { .scnprintf = SCA_SOCKADDR, /* addr */ }, }, },
817 { .name = "set_tid_address", .errpid = true, },
818 { .name = "setitimer",
819 .arg = { [0] = STRARRAY(which, itimers), }, },
820 { .name = "setrlimit",
821 .arg = { [0] = STRARRAY(resource, rlimit_resources), }, },
822 { .name = "socket",
823 .arg = { [0] = STRARRAY(family, socket_families),
824 [1] = { .scnprintf = SCA_SK_TYPE, /* type */ },
825 [2] = { .scnprintf = SCA_SK_PROTO, /* protocol */ }, }, },
826 { .name = "socketpair",
827 .arg = { [0] = STRARRAY(family, socket_families),
828 [1] = { .scnprintf = SCA_SK_TYPE, /* type */ },
829 [2] = { .scnprintf = SCA_SK_PROTO, /* protocol */ }, }, },
830 { .name = "stat", .alias = "newstat", },
831 { .name = "statx",
832 .arg = { [0] = { .scnprintf = SCA_FDAT, /* fdat */ },
833 [2] = { .scnprintf = SCA_STATX_FLAGS, /* flags */ } ,
834 [3] = { .scnprintf = SCA_STATX_MASK, /* mask */ }, }, },
835 { .name = "swapoff",
836 .arg = { [0] = { .scnprintf = SCA_FILENAME, /* specialfile */ }, }, },
837 { .name = "swapon",
838 .arg = { [0] = { .scnprintf = SCA_FILENAME, /* specialfile */ }, }, },
839 { .name = "symlinkat",
840 .arg = { [0] = { .scnprintf = SCA_FDAT, /* dfd */ }, }, },
841 { .name = "tgkill",
842 .arg = { [2] = { .scnprintf = SCA_SIGNUM, /* sig */ }, }, },
843 { .name = "tkill",
844 .arg = { [1] = { .scnprintf = SCA_SIGNUM, /* sig */ }, }, },
845 { .name = "umount2", .alias = "umount",
846 .arg = { [0] = { .scnprintf = SCA_FILENAME, /* name */ }, }, },
847 { .name = "uname", .alias = "newuname", },
848 { .name = "unlinkat",
849 .arg = { [0] = { .scnprintf = SCA_FDAT, /* dfd */ }, }, },
850 { .name = "utimensat",
851 .arg = { [0] = { .scnprintf = SCA_FDAT, /* dirfd */ }, }, },
852 { .name = "wait4", .errpid = true,
853 .arg = { [2] = { .scnprintf = SCA_WAITID_OPTIONS, /* options */ }, }, },
854 { .name = "waitid", .errpid = true,
855 .arg = { [3] = { .scnprintf = SCA_WAITID_OPTIONS, /* options */ }, }, },
858 static int syscall_fmt__cmp(const void *name, const void *fmtp)
860 const struct syscall_fmt *fmt = fmtp;
861 return strcmp(name, fmt->name);
864 static struct syscall_fmt *syscall_fmt__find(const char *name)
866 const int nmemb = ARRAY_SIZE(syscall_fmts);
867 return bsearch(name, syscall_fmts, nmemb, sizeof(struct syscall_fmt), syscall_fmt__cmp);
870 static struct syscall_fmt *syscall_fmt__find_by_alias(const char *alias)
872 int i, nmemb = ARRAY_SIZE(syscall_fmts);
874 for (i = 0; i < nmemb; ++i) {
875 if (syscall_fmts[i].alias && strcmp(syscall_fmts[i].alias, alias) == 0)
876 return &syscall_fmts[i];
879 return NULL;
883 * is_exit: is this "exit" or "exit_group"?
884 * is_open: is this "open" or "openat"? To associate the fd returned in sys_exit with the pathname in sys_enter.
885 * args_size: sum of the sizes of the syscall arguments, anything after that is augmented stuff: pathname for openat, etc.
887 struct syscall {
888 struct tep_event_format *tp_format;
889 int nr_args;
890 int args_size;
891 bool is_exit;
892 bool is_open;
893 struct tep_format_field *args;
894 const char *name;
895 struct syscall_fmt *fmt;
896 struct syscall_arg_fmt *arg_fmt;
900 * We need to have this 'calculated' boolean because in some cases we really
901 * don't know what is the duration of a syscall, for instance, when we start
902 * a session and some threads are waiting for a syscall to finish, say 'poll',
903 * in which case all we can do is to print "( ? ) for duration and for the
904 * start timestamp.
906 static size_t fprintf_duration(unsigned long t, bool calculated, FILE *fp)
908 double duration = (double)t / NSEC_PER_MSEC;
909 size_t printed = fprintf(fp, "(");
911 if (!calculated)
912 printed += fprintf(fp, " ");
913 else if (duration >= 1.0)
914 printed += color_fprintf(fp, PERF_COLOR_RED, "%6.3f ms", duration);
915 else if (duration >= 0.01)
916 printed += color_fprintf(fp, PERF_COLOR_YELLOW, "%6.3f ms", duration);
917 else
918 printed += color_fprintf(fp, PERF_COLOR_NORMAL, "%6.3f ms", duration);
919 return printed + fprintf(fp, "): ");
923 * filename.ptr: The filename char pointer that will be vfs_getname'd
924 * filename.entry_str_pos: Where to insert the string translated from
925 * filename.ptr by the vfs_getname tracepoint/kprobe.
926 * ret_scnprintf: syscall args may set this to a different syscall return
927 * formatter, for instance, fcntl may return fds, file flags, etc.
929 struct thread_trace {
930 u64 entry_time;
931 bool entry_pending;
932 unsigned long nr_events;
933 unsigned long pfmaj, pfmin;
934 char *entry_str;
935 double runtime_ms;
936 size_t (*ret_scnprintf)(char *bf, size_t size, struct syscall_arg *arg);
937 struct {
938 unsigned long ptr;
939 short int entry_str_pos;
940 bool pending_open;
941 unsigned int namelen;
942 char *name;
943 } filename;
944 struct {
945 int max;
946 char **table;
947 } paths;
949 struct intlist *syscall_stats;
952 static struct thread_trace *thread_trace__new(void)
954 struct thread_trace *ttrace = zalloc(sizeof(struct thread_trace));
956 if (ttrace)
957 ttrace->paths.max = -1;
959 ttrace->syscall_stats = intlist__new(NULL);
961 return ttrace;
964 static struct thread_trace *thread__trace(struct thread *thread, FILE *fp)
966 struct thread_trace *ttrace;
968 if (thread == NULL)
969 goto fail;
971 if (thread__priv(thread) == NULL)
972 thread__set_priv(thread, thread_trace__new());
974 if (thread__priv(thread) == NULL)
975 goto fail;
977 ttrace = thread__priv(thread);
978 ++ttrace->nr_events;
980 return ttrace;
981 fail:
982 color_fprintf(fp, PERF_COLOR_RED,
983 "WARNING: not enough memory, dropping samples!\n");
984 return NULL;
988 void syscall_arg__set_ret_scnprintf(struct syscall_arg *arg,
989 size_t (*ret_scnprintf)(char *bf, size_t size, struct syscall_arg *arg))
991 struct thread_trace *ttrace = thread__priv(arg->thread);
993 ttrace->ret_scnprintf = ret_scnprintf;
996 #define TRACE_PFMAJ (1 << 0)
997 #define TRACE_PFMIN (1 << 1)
999 static const size_t trace__entry_str_size = 2048;
1001 static int trace__set_fd_pathname(struct thread *thread, int fd, const char *pathname)
1003 struct thread_trace *ttrace = thread__priv(thread);
1005 if (fd > ttrace->paths.max) {
1006 char **npath = realloc(ttrace->paths.table, (fd + 1) * sizeof(char *));
1008 if (npath == NULL)
1009 return -1;
1011 if (ttrace->paths.max != -1) {
1012 memset(npath + ttrace->paths.max + 1, 0,
1013 (fd - ttrace->paths.max) * sizeof(char *));
1014 } else {
1015 memset(npath, 0, (fd + 1) * sizeof(char *));
1018 ttrace->paths.table = npath;
1019 ttrace->paths.max = fd;
1022 ttrace->paths.table[fd] = strdup(pathname);
1024 return ttrace->paths.table[fd] != NULL ? 0 : -1;
1027 static int thread__read_fd_path(struct thread *thread, int fd)
1029 char linkname[PATH_MAX], pathname[PATH_MAX];
1030 struct stat st;
1031 int ret;
1033 if (thread->pid_ == thread->tid) {
1034 scnprintf(linkname, sizeof(linkname),
1035 "/proc/%d/fd/%d", thread->pid_, fd);
1036 } else {
1037 scnprintf(linkname, sizeof(linkname),
1038 "/proc/%d/task/%d/fd/%d", thread->pid_, thread->tid, fd);
1041 if (lstat(linkname, &st) < 0 || st.st_size + 1 > (off_t)sizeof(pathname))
1042 return -1;
1044 ret = readlink(linkname, pathname, sizeof(pathname));
1046 if (ret < 0 || ret > st.st_size)
1047 return -1;
1049 pathname[ret] = '\0';
1050 return trace__set_fd_pathname(thread, fd, pathname);
1053 static const char *thread__fd_path(struct thread *thread, int fd,
1054 struct trace *trace)
1056 struct thread_trace *ttrace = thread__priv(thread);
1058 if (ttrace == NULL)
1059 return NULL;
1061 if (fd < 0)
1062 return NULL;
1064 if ((fd > ttrace->paths.max || ttrace->paths.table[fd] == NULL)) {
1065 if (!trace->live)
1066 return NULL;
1067 ++trace->stats.proc_getname;
1068 if (thread__read_fd_path(thread, fd))
1069 return NULL;
1072 return ttrace->paths.table[fd];
1075 size_t syscall_arg__scnprintf_fd(char *bf, size_t size, struct syscall_arg *arg)
1077 int fd = arg->val;
1078 size_t printed = scnprintf(bf, size, "%d", fd);
1079 const char *path = thread__fd_path(arg->thread, fd, arg->trace);
1081 if (path)
1082 printed += scnprintf(bf + printed, size - printed, "<%s>", path);
1084 return printed;
1087 size_t pid__scnprintf_fd(struct trace *trace, pid_t pid, int fd, char *bf, size_t size)
1089 size_t printed = scnprintf(bf, size, "%d", fd);
1090 struct thread *thread = machine__find_thread(trace->host, pid, pid);
1092 if (thread) {
1093 const char *path = thread__fd_path(thread, fd, trace);
1095 if (path)
1096 printed += scnprintf(bf + printed, size - printed, "<%s>", path);
1098 thread__put(thread);
1101 return printed;
1104 static size_t syscall_arg__scnprintf_close_fd(char *bf, size_t size,
1105 struct syscall_arg *arg)
1107 int fd = arg->val;
1108 size_t printed = syscall_arg__scnprintf_fd(bf, size, arg);
1109 struct thread_trace *ttrace = thread__priv(arg->thread);
1111 if (ttrace && fd >= 0 && fd <= ttrace->paths.max)
1112 zfree(&ttrace->paths.table[fd]);
1114 return printed;
1117 static void thread__set_filename_pos(struct thread *thread, const char *bf,
1118 unsigned long ptr)
1120 struct thread_trace *ttrace = thread__priv(thread);
1122 ttrace->filename.ptr = ptr;
1123 ttrace->filename.entry_str_pos = bf - ttrace->entry_str;
1126 static size_t syscall_arg__scnprintf_augmented_string(struct syscall_arg *arg, char *bf, size_t size)
1128 struct augmented_arg *augmented_arg = arg->augmented.args;
1130 return scnprintf(bf, size, "%.*s", augmented_arg->size, augmented_arg->value);
1133 static size_t syscall_arg__scnprintf_filename(char *bf, size_t size,
1134 struct syscall_arg *arg)
1136 unsigned long ptr = arg->val;
1138 if (arg->augmented.args)
1139 return syscall_arg__scnprintf_augmented_string(arg, bf, size);
1141 if (!arg->trace->vfs_getname)
1142 return scnprintf(bf, size, "%#x", ptr);
1144 thread__set_filename_pos(arg->thread, bf, ptr);
1145 return 0;
1148 static bool trace__filter_duration(struct trace *trace, double t)
1150 return t < (trace->duration_filter * NSEC_PER_MSEC);
1153 static size_t __trace__fprintf_tstamp(struct trace *trace, u64 tstamp, FILE *fp)
1155 double ts = (double)(tstamp - trace->base_time) / NSEC_PER_MSEC;
1157 return fprintf(fp, "%10.3f ", ts);
1161 * We're handling tstamp=0 as an undefined tstamp, i.e. like when we are
1162 * using ttrace->entry_time for a thread that receives a sys_exit without
1163 * first having received a sys_enter ("poll" issued before tracing session
1164 * starts, lost sys_enter exit due to ring buffer overflow).
1166 static size_t trace__fprintf_tstamp(struct trace *trace, u64 tstamp, FILE *fp)
1168 if (tstamp > 0)
1169 return __trace__fprintf_tstamp(trace, tstamp, fp);
1171 return fprintf(fp, " ? ");
1174 static bool done = false;
1175 static bool interrupted = false;
1177 static void sig_handler(int sig)
1179 done = true;
1180 interrupted = sig == SIGINT;
1183 static size_t trace__fprintf_comm_tid(struct trace *trace, struct thread *thread, FILE *fp)
1185 size_t printed = 0;
1187 if (trace->multiple_threads) {
1188 if (trace->show_comm)
1189 printed += fprintf(fp, "%.14s/", thread__comm_str(thread));
1190 printed += fprintf(fp, "%d ", thread->tid);
1193 return printed;
1196 static size_t trace__fprintf_entry_head(struct trace *trace, struct thread *thread,
1197 u64 duration, bool duration_calculated, u64 tstamp, FILE *fp)
1199 size_t printed = trace__fprintf_tstamp(trace, tstamp, fp);
1200 printed += fprintf_duration(duration, duration_calculated, fp);
1201 return printed + trace__fprintf_comm_tid(trace, thread, fp);
1204 static int trace__process_event(struct trace *trace, struct machine *machine,
1205 union perf_event *event, struct perf_sample *sample)
1207 int ret = 0;
1209 switch (event->header.type) {
1210 case PERF_RECORD_LOST:
1211 color_fprintf(trace->output, PERF_COLOR_RED,
1212 "LOST %" PRIu64 " events!\n", event->lost.lost);
1213 ret = machine__process_lost_event(machine, event, sample);
1214 break;
1215 default:
1216 ret = machine__process_event(machine, event, sample);
1217 break;
1220 return ret;
1223 static int trace__tool_process(struct perf_tool *tool,
1224 union perf_event *event,
1225 struct perf_sample *sample,
1226 struct machine *machine)
1228 struct trace *trace = container_of(tool, struct trace, tool);
1229 return trace__process_event(trace, machine, event, sample);
1232 static char *trace__machine__resolve_kernel_addr(void *vmachine, unsigned long long *addrp, char **modp)
1234 struct machine *machine = vmachine;
1236 if (machine->kptr_restrict_warned)
1237 return NULL;
1239 if (symbol_conf.kptr_restrict) {
1240 pr_warning("Kernel address maps (/proc/{kallsyms,modules}) are restricted.\n\n"
1241 "Check /proc/sys/kernel/kptr_restrict.\n\n"
1242 "Kernel samples will not be resolved.\n");
1243 machine->kptr_restrict_warned = true;
1244 return NULL;
1247 return machine__resolve_kernel_addr(vmachine, addrp, modp);
1250 static int trace__symbols_init(struct trace *trace, struct perf_evlist *evlist)
1252 int err = symbol__init(NULL);
1254 if (err)
1255 return err;
1257 trace->host = machine__new_host();
1258 if (trace->host == NULL)
1259 return -ENOMEM;
1261 err = trace_event__register_resolver(trace->host, trace__machine__resolve_kernel_addr);
1262 if (err < 0)
1263 goto out;
1265 err = __machine__synthesize_threads(trace->host, &trace->tool, &trace->opts.target,
1266 evlist->threads, trace__tool_process, false,
1267 trace->opts.proc_map_timeout, 1);
1268 out:
1269 if (err)
1270 symbol__exit();
1272 return err;
1275 static void trace__symbols__exit(struct trace *trace)
1277 machine__exit(trace->host);
1278 trace->host = NULL;
1280 symbol__exit();
1283 static int syscall__alloc_arg_fmts(struct syscall *sc, int nr_args)
1285 int idx;
1287 if (nr_args == 6 && sc->fmt && sc->fmt->nr_args != 0)
1288 nr_args = sc->fmt->nr_args;
1290 sc->arg_fmt = calloc(nr_args, sizeof(*sc->arg_fmt));
1291 if (sc->arg_fmt == NULL)
1292 return -1;
1294 for (idx = 0; idx < nr_args; ++idx) {
1295 if (sc->fmt)
1296 sc->arg_fmt[idx] = sc->fmt->arg[idx];
1299 sc->nr_args = nr_args;
1300 return 0;
1303 static int syscall__set_arg_fmts(struct syscall *sc)
1305 struct tep_format_field *field, *last_field = NULL;
1306 int idx = 0, len;
1308 for (field = sc->args; field; field = field->next, ++idx) {
1309 last_field = field;
1311 if (sc->fmt && sc->fmt->arg[idx].scnprintf)
1312 continue;
1314 if (strcmp(field->type, "const char *") == 0 &&
1315 (strcmp(field->name, "filename") == 0 ||
1316 strcmp(field->name, "path") == 0 ||
1317 strcmp(field->name, "pathname") == 0))
1318 sc->arg_fmt[idx].scnprintf = SCA_FILENAME;
1319 else if (field->flags & TEP_FIELD_IS_POINTER)
1320 sc->arg_fmt[idx].scnprintf = syscall_arg__scnprintf_hex;
1321 else if (strcmp(field->type, "pid_t") == 0)
1322 sc->arg_fmt[idx].scnprintf = SCA_PID;
1323 else if (strcmp(field->type, "umode_t") == 0)
1324 sc->arg_fmt[idx].scnprintf = SCA_MODE_T;
1325 else if ((strcmp(field->type, "int") == 0 ||
1326 strcmp(field->type, "unsigned int") == 0 ||
1327 strcmp(field->type, "long") == 0) &&
1328 (len = strlen(field->name)) >= 2 &&
1329 strcmp(field->name + len - 2, "fd") == 0) {
1331 * /sys/kernel/tracing/events/syscalls/sys_enter*
1332 * egrep 'field:.*fd;' .../format|sed -r 's/.*field:([a-z ]+) [a-z_]*fd.+/\1/g'|sort|uniq -c
1333 * 65 int
1334 * 23 unsigned int
1335 * 7 unsigned long
1337 sc->arg_fmt[idx].scnprintf = SCA_FD;
1341 if (last_field)
1342 sc->args_size = last_field->offset + last_field->size;
1344 return 0;
1347 static int trace__read_syscall_info(struct trace *trace, int id)
1349 char tp_name[128];
1350 struct syscall *sc;
1351 const char *name = syscalltbl__name(trace->sctbl, id);
1353 if (name == NULL)
1354 return -1;
1356 if (id > trace->syscalls.max) {
1357 struct syscall *nsyscalls = realloc(trace->syscalls.table, (id + 1) * sizeof(*sc));
1359 if (nsyscalls == NULL)
1360 return -1;
1362 if (trace->syscalls.max != -1) {
1363 memset(nsyscalls + trace->syscalls.max + 1, 0,
1364 (id - trace->syscalls.max) * sizeof(*sc));
1365 } else {
1366 memset(nsyscalls, 0, (id + 1) * sizeof(*sc));
1369 trace->syscalls.table = nsyscalls;
1370 trace->syscalls.max = id;
1373 sc = trace->syscalls.table + id;
1374 sc->name = name;
1376 sc->fmt = syscall_fmt__find(sc->name);
1378 snprintf(tp_name, sizeof(tp_name), "sys_enter_%s", sc->name);
1379 sc->tp_format = trace_event__tp_format("syscalls", tp_name);
1381 if (IS_ERR(sc->tp_format) && sc->fmt && sc->fmt->alias) {
1382 snprintf(tp_name, sizeof(tp_name), "sys_enter_%s", sc->fmt->alias);
1383 sc->tp_format = trace_event__tp_format("syscalls", tp_name);
1386 if (syscall__alloc_arg_fmts(sc, IS_ERR(sc->tp_format) ? 6 : sc->tp_format->format.nr_fields))
1387 return -1;
1389 if (IS_ERR(sc->tp_format))
1390 return -1;
1392 sc->args = sc->tp_format->format.fields;
1394 * We need to check and discard the first variable '__syscall_nr'
1395 * or 'nr' that mean the syscall number. It is needless here.
1396 * So drop '__syscall_nr' or 'nr' field but does not exist on older kernels.
1398 if (sc->args && (!strcmp(sc->args->name, "__syscall_nr") || !strcmp(sc->args->name, "nr"))) {
1399 sc->args = sc->args->next;
1400 --sc->nr_args;
1403 sc->is_exit = !strcmp(name, "exit_group") || !strcmp(name, "exit");
1404 sc->is_open = !strcmp(name, "open") || !strcmp(name, "openat");
1406 return syscall__set_arg_fmts(sc);
1409 static int trace__validate_ev_qualifier(struct trace *trace)
1411 int err = 0, i;
1412 size_t nr_allocated;
1413 struct str_node *pos;
1415 trace->ev_qualifier_ids.nr = strlist__nr_entries(trace->ev_qualifier);
1416 trace->ev_qualifier_ids.entries = malloc(trace->ev_qualifier_ids.nr *
1417 sizeof(trace->ev_qualifier_ids.entries[0]));
1419 if (trace->ev_qualifier_ids.entries == NULL) {
1420 fputs("Error:\tNot enough memory for allocating events qualifier ids\n",
1421 trace->output);
1422 err = -EINVAL;
1423 goto out;
1426 nr_allocated = trace->ev_qualifier_ids.nr;
1427 i = 0;
1429 strlist__for_each_entry(pos, trace->ev_qualifier) {
1430 const char *sc = pos->s;
1431 int id = syscalltbl__id(trace->sctbl, sc), match_next = -1;
1433 if (id < 0) {
1434 id = syscalltbl__strglobmatch_first(trace->sctbl, sc, &match_next);
1435 if (id >= 0)
1436 goto matches;
1438 if (err == 0) {
1439 fputs("Error:\tInvalid syscall ", trace->output);
1440 err = -EINVAL;
1441 } else {
1442 fputs(", ", trace->output);
1445 fputs(sc, trace->output);
1447 matches:
1448 trace->ev_qualifier_ids.entries[i++] = id;
1449 if (match_next == -1)
1450 continue;
1452 while (1) {
1453 id = syscalltbl__strglobmatch_next(trace->sctbl, sc, &match_next);
1454 if (id < 0)
1455 break;
1456 if (nr_allocated == trace->ev_qualifier_ids.nr) {
1457 void *entries;
1459 nr_allocated += 8;
1460 entries = realloc(trace->ev_qualifier_ids.entries,
1461 nr_allocated * sizeof(trace->ev_qualifier_ids.entries[0]));
1462 if (entries == NULL) {
1463 err = -ENOMEM;
1464 fputs("\nError:\t Not enough memory for parsing\n", trace->output);
1465 goto out_free;
1467 trace->ev_qualifier_ids.entries = entries;
1469 trace->ev_qualifier_ids.nr++;
1470 trace->ev_qualifier_ids.entries[i++] = id;
1474 if (err < 0) {
1475 fputs("\nHint:\ttry 'perf list syscalls:sys_enter_*'"
1476 "\nHint:\tand: 'man syscalls'\n", trace->output);
1477 out_free:
1478 zfree(&trace->ev_qualifier_ids.entries);
1479 trace->ev_qualifier_ids.nr = 0;
1481 out:
1482 return err;
1486 * args is to be interpreted as a series of longs but we need to handle
1487 * 8-byte unaligned accesses. args points to raw_data within the event
1488 * and raw_data is guaranteed to be 8-byte unaligned because it is
1489 * preceded by raw_size which is a u32. So we need to copy args to a temp
1490 * variable to read it. Most notably this avoids extended load instructions
1491 * on unaligned addresses
1493 unsigned long syscall_arg__val(struct syscall_arg *arg, u8 idx)
1495 unsigned long val;
1496 unsigned char *p = arg->args + sizeof(unsigned long) * idx;
1498 memcpy(&val, p, sizeof(val));
1499 return val;
1502 static size_t syscall__scnprintf_name(struct syscall *sc, char *bf, size_t size,
1503 struct syscall_arg *arg)
1505 if (sc->arg_fmt && sc->arg_fmt[arg->idx].name)
1506 return scnprintf(bf, size, "%s: ", sc->arg_fmt[arg->idx].name);
1508 return scnprintf(bf, size, "arg%d: ", arg->idx);
1512 * Check if the value is in fact zero, i.e. mask whatever needs masking, such
1513 * as mount 'flags' argument that needs ignoring some magic flag, see comment
1514 * in tools/perf/trace/beauty/mount_flags.c
1516 static unsigned long syscall__mask_val(struct syscall *sc, struct syscall_arg *arg, unsigned long val)
1518 if (sc->arg_fmt && sc->arg_fmt[arg->idx].mask_val)
1519 return sc->arg_fmt[arg->idx].mask_val(arg, val);
1521 return val;
1524 static size_t syscall__scnprintf_val(struct syscall *sc, char *bf, size_t size,
1525 struct syscall_arg *arg, unsigned long val)
1527 if (sc->arg_fmt && sc->arg_fmt[arg->idx].scnprintf) {
1528 arg->val = val;
1529 if (sc->arg_fmt[arg->idx].parm)
1530 arg->parm = sc->arg_fmt[arg->idx].parm;
1531 return sc->arg_fmt[arg->idx].scnprintf(bf, size, arg);
1533 return scnprintf(bf, size, "%ld", val);
1536 static size_t syscall__scnprintf_args(struct syscall *sc, char *bf, size_t size,
1537 unsigned char *args, void *augmented_args, int augmented_args_size,
1538 struct trace *trace, struct thread *thread)
1540 size_t printed = 0;
1541 unsigned long val;
1542 u8 bit = 1;
1543 struct syscall_arg arg = {
1544 .args = args,
1545 .augmented = {
1546 .size = augmented_args_size,
1547 .args = augmented_args,
1549 .idx = 0,
1550 .mask = 0,
1551 .trace = trace,
1552 .thread = thread,
1554 struct thread_trace *ttrace = thread__priv(thread);
1557 * Things like fcntl will set this in its 'cmd' formatter to pick the
1558 * right formatter for the return value (an fd? file flags?), which is
1559 * not needed for syscalls that always return a given type, say an fd.
1561 ttrace->ret_scnprintf = NULL;
1563 if (sc->args != NULL) {
1564 struct tep_format_field *field;
1566 for (field = sc->args; field;
1567 field = field->next, ++arg.idx, bit <<= 1) {
1568 if (arg.mask & bit)
1569 continue;
1571 val = syscall_arg__val(&arg, arg.idx);
1573 * Some syscall args need some mask, most don't and
1574 * return val untouched.
1576 val = syscall__mask_val(sc, &arg, val);
1579 * Suppress this argument if its value is zero and
1580 * and we don't have a string associated in an
1581 * strarray for it.
1583 if (val == 0 &&
1584 !(sc->arg_fmt &&
1585 (sc->arg_fmt[arg.idx].show_zero ||
1586 sc->arg_fmt[arg.idx].scnprintf == SCA_STRARRAY ||
1587 sc->arg_fmt[arg.idx].scnprintf == SCA_STRARRAYS) &&
1588 sc->arg_fmt[arg.idx].parm))
1589 continue;
1591 printed += scnprintf(bf + printed, size - printed,
1592 "%s%s: ", printed ? ", " : "", field->name);
1593 printed += syscall__scnprintf_val(sc, bf + printed, size - printed, &arg, val);
1595 } else if (IS_ERR(sc->tp_format)) {
1597 * If we managed to read the tracepoint /format file, then we
1598 * may end up not having any args, like with gettid(), so only
1599 * print the raw args when we didn't manage to read it.
1601 while (arg.idx < sc->nr_args) {
1602 if (arg.mask & bit)
1603 goto next_arg;
1604 val = syscall_arg__val(&arg, arg.idx);
1605 if (printed)
1606 printed += scnprintf(bf + printed, size - printed, ", ");
1607 printed += syscall__scnprintf_name(sc, bf + printed, size - printed, &arg);
1608 printed += syscall__scnprintf_val(sc, bf + printed, size - printed, &arg, val);
1609 next_arg:
1610 ++arg.idx;
1611 bit <<= 1;
1615 return printed;
1618 typedef int (*tracepoint_handler)(struct trace *trace, struct perf_evsel *evsel,
1619 union perf_event *event,
1620 struct perf_sample *sample);
1622 static struct syscall *trace__syscall_info(struct trace *trace,
1623 struct perf_evsel *evsel, int id)
1626 if (id < 0) {
1629 * XXX: Noticed on x86_64, reproduced as far back as 3.0.36, haven't tried
1630 * before that, leaving at a higher verbosity level till that is
1631 * explained. Reproduced with plain ftrace with:
1633 * echo 1 > /t/events/raw_syscalls/sys_exit/enable
1634 * grep "NR -1 " /t/trace_pipe
1636 * After generating some load on the machine.
1638 if (verbose > 1) {
1639 static u64 n;
1640 fprintf(trace->output, "Invalid syscall %d id, skipping (%s, %" PRIu64 ") ...\n",
1641 id, perf_evsel__name(evsel), ++n);
1643 return NULL;
1646 if ((id > trace->syscalls.max || trace->syscalls.table[id].name == NULL) &&
1647 trace__read_syscall_info(trace, id))
1648 goto out_cant_read;
1650 if ((id > trace->syscalls.max || trace->syscalls.table[id].name == NULL))
1651 goto out_cant_read;
1653 return &trace->syscalls.table[id];
1655 out_cant_read:
1656 if (verbose > 0) {
1657 fprintf(trace->output, "Problems reading syscall %d", id);
1658 if (id <= trace->syscalls.max && trace->syscalls.table[id].name != NULL)
1659 fprintf(trace->output, "(%s)", trace->syscalls.table[id].name);
1660 fputs(" information\n", trace->output);
1662 return NULL;
1665 static void thread__update_stats(struct thread_trace *ttrace,
1666 int id, struct perf_sample *sample)
1668 struct int_node *inode;
1669 struct stats *stats;
1670 u64 duration = 0;
1672 inode = intlist__findnew(ttrace->syscall_stats, id);
1673 if (inode == NULL)
1674 return;
1676 stats = inode->priv;
1677 if (stats == NULL) {
1678 stats = malloc(sizeof(struct stats));
1679 if (stats == NULL)
1680 return;
1681 init_stats(stats);
1682 inode->priv = stats;
1685 if (ttrace->entry_time && sample->time > ttrace->entry_time)
1686 duration = sample->time - ttrace->entry_time;
1688 update_stats(stats, duration);
1691 static int trace__printf_interrupted_entry(struct trace *trace)
1693 struct thread_trace *ttrace;
1694 size_t printed;
1696 if (trace->failure_only || trace->current == NULL)
1697 return 0;
1699 ttrace = thread__priv(trace->current);
1701 if (!ttrace->entry_pending)
1702 return 0;
1704 printed = trace__fprintf_entry_head(trace, trace->current, 0, false, ttrace->entry_time, trace->output);
1705 printed += fprintf(trace->output, "%-70s) ...\n", ttrace->entry_str);
1706 ttrace->entry_pending = false;
1708 ++trace->nr_events_printed;
1710 return printed;
1713 static int trace__fprintf_sample(struct trace *trace, struct perf_evsel *evsel,
1714 struct perf_sample *sample, struct thread *thread)
1716 int printed = 0;
1718 if (trace->print_sample) {
1719 double ts = (double)sample->time / NSEC_PER_MSEC;
1721 printed += fprintf(trace->output, "%22s %10.3f %s %d/%d [%d]\n",
1722 perf_evsel__name(evsel), ts,
1723 thread__comm_str(thread),
1724 sample->pid, sample->tid, sample->cpu);
1727 return printed;
1730 static void *syscall__augmented_args(struct syscall *sc, struct perf_sample *sample, int *augmented_args_size, bool raw_augmented)
1732 void *augmented_args = NULL;
1734 * For now with BPF raw_augmented we hook into raw_syscalls:sys_enter
1735 * and there we get all 6 syscall args plus the tracepoint common
1736 * fields (sizeof(long)) and the syscall_nr (another long). So we check
1737 * if that is the case and if so don't look after the sc->args_size,
1738 * but always after the full raw_syscalls:sys_enter payload, which is
1739 * fixed.
1741 * We'll revisit this later to pass s->args_size to the BPF augmenter
1742 * (now tools/perf/examples/bpf/augmented_raw_syscalls.c, so that it
1743 * copies only what we need for each syscall, like what happens when we
1744 * use syscalls:sys_enter_NAME, so that we reduce the kernel/userspace
1745 * traffic to just what is needed for each syscall.
1747 int args_size = raw_augmented ? (8 * (int)sizeof(long)) : sc->args_size;
1749 *augmented_args_size = sample->raw_size - args_size;
1750 if (*augmented_args_size > 0)
1751 augmented_args = sample->raw_data + args_size;
1753 return augmented_args;
1756 static int trace__sys_enter(struct trace *trace, struct perf_evsel *evsel,
1757 union perf_event *event __maybe_unused,
1758 struct perf_sample *sample)
1760 char *msg;
1761 void *args;
1762 size_t printed = 0;
1763 struct thread *thread;
1764 int id = perf_evsel__sc_tp_uint(evsel, id, sample), err = -1;
1765 int augmented_args_size = 0;
1766 void *augmented_args = NULL;
1767 struct syscall *sc = trace__syscall_info(trace, evsel, id);
1768 struct thread_trace *ttrace;
1770 if (sc == NULL)
1771 return -1;
1773 thread = machine__findnew_thread(trace->host, sample->pid, sample->tid);
1774 ttrace = thread__trace(thread, trace->output);
1775 if (ttrace == NULL)
1776 goto out_put;
1778 trace__fprintf_sample(trace, evsel, sample, thread);
1780 args = perf_evsel__sc_tp_ptr(evsel, args, sample);
1782 if (ttrace->entry_str == NULL) {
1783 ttrace->entry_str = malloc(trace__entry_str_size);
1784 if (!ttrace->entry_str)
1785 goto out_put;
1788 if (!(trace->duration_filter || trace->summary_only || trace->min_stack))
1789 trace__printf_interrupted_entry(trace);
1791 * If this is raw_syscalls.sys_enter, then it always comes with the 6 possible
1792 * arguments, even if the syscall being handled, say "openat", uses only 4 arguments
1793 * this breaks syscall__augmented_args() check for augmented args, as we calculate
1794 * syscall->args_size using each syscalls:sys_enter_NAME tracefs format file,
1795 * so when handling, say the openat syscall, we end up getting 6 args for the
1796 * raw_syscalls:sys_enter event, when we expected just 4, we end up mistakenly
1797 * thinking that the extra 2 u64 args are the augmented filename, so just check
1798 * here and avoid using augmented syscalls when the evsel is the raw_syscalls one.
1800 if (evsel != trace->syscalls.events.sys_enter)
1801 augmented_args = syscall__augmented_args(sc, sample, &augmented_args_size, trace->raw_augmented_syscalls);
1802 ttrace->entry_time = sample->time;
1803 msg = ttrace->entry_str;
1804 printed += scnprintf(msg + printed, trace__entry_str_size - printed, "%s(", sc->name);
1806 printed += syscall__scnprintf_args(sc, msg + printed, trace__entry_str_size - printed,
1807 args, augmented_args, augmented_args_size, trace, thread);
1809 if (sc->is_exit) {
1810 if (!(trace->duration_filter || trace->summary_only || trace->failure_only || trace->min_stack)) {
1811 trace__fprintf_entry_head(trace, thread, 0, false, ttrace->entry_time, trace->output);
1812 fprintf(trace->output, "%-70s)\n", ttrace->entry_str);
1814 } else {
1815 ttrace->entry_pending = true;
1816 /* See trace__vfs_getname & trace__sys_exit */
1817 ttrace->filename.pending_open = false;
1820 if (trace->current != thread) {
1821 thread__put(trace->current);
1822 trace->current = thread__get(thread);
1824 err = 0;
1825 out_put:
1826 thread__put(thread);
1827 return err;
1830 static int trace__fprintf_sys_enter(struct trace *trace, struct perf_evsel *evsel,
1831 struct perf_sample *sample)
1833 struct thread_trace *ttrace;
1834 struct thread *thread;
1835 int id = perf_evsel__sc_tp_uint(evsel, id, sample), err = -1;
1836 struct syscall *sc = trace__syscall_info(trace, evsel, id);
1837 char msg[1024];
1838 void *args, *augmented_args = NULL;
1839 int augmented_args_size;
1841 if (sc == NULL)
1842 return -1;
1844 thread = machine__findnew_thread(trace->host, sample->pid, sample->tid);
1845 ttrace = thread__trace(thread, trace->output);
1847 * We need to get ttrace just to make sure it is there when syscall__scnprintf_args()
1848 * and the rest of the beautifiers accessing it via struct syscall_arg touches it.
1850 if (ttrace == NULL)
1851 goto out_put;
1853 args = perf_evsel__sc_tp_ptr(evsel, args, sample);
1854 augmented_args = syscall__augmented_args(sc, sample, &augmented_args_size, trace->raw_augmented_syscalls);
1855 syscall__scnprintf_args(sc, msg, sizeof(msg), args, augmented_args, augmented_args_size, trace, thread);
1856 fprintf(trace->output, "%s", msg);
1857 err = 0;
1858 out_put:
1859 thread__put(thread);
1860 return err;
1863 static int trace__resolve_callchain(struct trace *trace, struct perf_evsel *evsel,
1864 struct perf_sample *sample,
1865 struct callchain_cursor *cursor)
1867 struct addr_location al;
1868 int max_stack = evsel->attr.sample_max_stack ?
1869 evsel->attr.sample_max_stack :
1870 trace->max_stack;
1871 int err;
1873 if (machine__resolve(trace->host, &al, sample) < 0)
1874 return -1;
1876 err = thread__resolve_callchain(al.thread, cursor, evsel, sample, NULL, NULL, max_stack);
1877 addr_location__put(&al);
1878 return err;
1881 static int trace__fprintf_callchain(struct trace *trace, struct perf_sample *sample)
1883 /* TODO: user-configurable print_opts */
1884 const unsigned int print_opts = EVSEL__PRINT_SYM |
1885 EVSEL__PRINT_DSO |
1886 EVSEL__PRINT_UNKNOWN_AS_ADDR;
1888 return sample__fprintf_callchain(sample, 38, print_opts, &callchain_cursor, trace->output);
1891 static const char *errno_to_name(struct perf_evsel *evsel, int err)
1893 struct perf_env *env = perf_evsel__env(evsel);
1894 const char *arch_name = perf_env__arch(env);
1896 return arch_syscalls__strerrno(arch_name, err);
1899 static int trace__sys_exit(struct trace *trace, struct perf_evsel *evsel,
1900 union perf_event *event __maybe_unused,
1901 struct perf_sample *sample)
1903 long ret;
1904 u64 duration = 0;
1905 bool duration_calculated = false;
1906 struct thread *thread;
1907 int id = perf_evsel__sc_tp_uint(evsel, id, sample), err = -1, callchain_ret = 0;
1908 struct syscall *sc = trace__syscall_info(trace, evsel, id);
1909 struct thread_trace *ttrace;
1911 if (sc == NULL)
1912 return -1;
1914 thread = machine__findnew_thread(trace->host, sample->pid, sample->tid);
1915 ttrace = thread__trace(thread, trace->output);
1916 if (ttrace == NULL)
1917 goto out_put;
1919 trace__fprintf_sample(trace, evsel, sample, thread);
1921 if (trace->summary)
1922 thread__update_stats(ttrace, id, sample);
1924 ret = perf_evsel__sc_tp_uint(evsel, ret, sample);
1926 if (sc->is_open && ret >= 0 && ttrace->filename.pending_open) {
1927 trace__set_fd_pathname(thread, ret, ttrace->filename.name);
1928 ttrace->filename.pending_open = false;
1929 ++trace->stats.vfs_getname;
1932 if (ttrace->entry_time) {
1933 duration = sample->time - ttrace->entry_time;
1934 if (trace__filter_duration(trace, duration))
1935 goto out;
1936 duration_calculated = true;
1937 } else if (trace->duration_filter)
1938 goto out;
1940 if (sample->callchain) {
1941 callchain_ret = trace__resolve_callchain(trace, evsel, sample, &callchain_cursor);
1942 if (callchain_ret == 0) {
1943 if (callchain_cursor.nr < trace->min_stack)
1944 goto out;
1945 callchain_ret = 1;
1949 if (trace->summary_only || (ret >= 0 && trace->failure_only))
1950 goto out;
1952 trace__fprintf_entry_head(trace, thread, duration, duration_calculated, ttrace->entry_time, trace->output);
1954 if (ttrace->entry_pending) {
1955 fprintf(trace->output, "%-70s", ttrace->entry_str);
1956 } else {
1957 fprintf(trace->output, " ... [");
1958 color_fprintf(trace->output, PERF_COLOR_YELLOW, "continued");
1959 fprintf(trace->output, "]: %s()", sc->name);
1962 if (sc->fmt == NULL) {
1963 if (ret < 0)
1964 goto errno_print;
1965 signed_print:
1966 fprintf(trace->output, ") = %ld", ret);
1967 } else if (ret < 0) {
1968 errno_print: {
1969 char bf[STRERR_BUFSIZE];
1970 const char *emsg = str_error_r(-ret, bf, sizeof(bf)),
1971 *e = errno_to_name(evsel, -ret);
1973 fprintf(trace->output, ") = -1 %s %s", e, emsg);
1975 } else if (ret == 0 && sc->fmt->timeout)
1976 fprintf(trace->output, ") = 0 Timeout");
1977 else if (ttrace->ret_scnprintf) {
1978 char bf[1024];
1979 struct syscall_arg arg = {
1980 .val = ret,
1981 .thread = thread,
1982 .trace = trace,
1984 ttrace->ret_scnprintf(bf, sizeof(bf), &arg);
1985 ttrace->ret_scnprintf = NULL;
1986 fprintf(trace->output, ") = %s", bf);
1987 } else if (sc->fmt->hexret)
1988 fprintf(trace->output, ") = %#lx", ret);
1989 else if (sc->fmt->errpid) {
1990 struct thread *child = machine__find_thread(trace->host, ret, ret);
1992 if (child != NULL) {
1993 fprintf(trace->output, ") = %ld", ret);
1994 if (child->comm_set)
1995 fprintf(trace->output, " (%s)", thread__comm_str(child));
1996 thread__put(child);
1998 } else
1999 goto signed_print;
2001 fputc('\n', trace->output);
2004 * We only consider an 'event' for the sake of --max-events a non-filtered
2005 * sys_enter + sys_exit and other tracepoint events.
2007 if (++trace->nr_events_printed == trace->max_events && trace->max_events != ULONG_MAX)
2008 interrupted = true;
2010 if (callchain_ret > 0)
2011 trace__fprintf_callchain(trace, sample);
2012 else if (callchain_ret < 0)
2013 pr_err("Problem processing %s callchain, skipping...\n", perf_evsel__name(evsel));
2014 out:
2015 ttrace->entry_pending = false;
2016 err = 0;
2017 out_put:
2018 thread__put(thread);
2019 return err;
2022 static int trace__vfs_getname(struct trace *trace, struct perf_evsel *evsel,
2023 union perf_event *event __maybe_unused,
2024 struct perf_sample *sample)
2026 struct thread *thread = machine__findnew_thread(trace->host, sample->pid, sample->tid);
2027 struct thread_trace *ttrace;
2028 size_t filename_len, entry_str_len, to_move;
2029 ssize_t remaining_space;
2030 char *pos;
2031 const char *filename = perf_evsel__rawptr(evsel, sample, "pathname");
2033 if (!thread)
2034 goto out;
2036 ttrace = thread__priv(thread);
2037 if (!ttrace)
2038 goto out_put;
2040 filename_len = strlen(filename);
2041 if (filename_len == 0)
2042 goto out_put;
2044 if (ttrace->filename.namelen < filename_len) {
2045 char *f = realloc(ttrace->filename.name, filename_len + 1);
2047 if (f == NULL)
2048 goto out_put;
2050 ttrace->filename.namelen = filename_len;
2051 ttrace->filename.name = f;
2054 strcpy(ttrace->filename.name, filename);
2055 ttrace->filename.pending_open = true;
2057 if (!ttrace->filename.ptr)
2058 goto out_put;
2060 entry_str_len = strlen(ttrace->entry_str);
2061 remaining_space = trace__entry_str_size - entry_str_len - 1; /* \0 */
2062 if (remaining_space <= 0)
2063 goto out_put;
2065 if (filename_len > (size_t)remaining_space) {
2066 filename += filename_len - remaining_space;
2067 filename_len = remaining_space;
2070 to_move = entry_str_len - ttrace->filename.entry_str_pos + 1; /* \0 */
2071 pos = ttrace->entry_str + ttrace->filename.entry_str_pos;
2072 memmove(pos + filename_len, pos, to_move);
2073 memcpy(pos, filename, filename_len);
2075 ttrace->filename.ptr = 0;
2076 ttrace->filename.entry_str_pos = 0;
2077 out_put:
2078 thread__put(thread);
2079 out:
2080 return 0;
2083 static int trace__sched_stat_runtime(struct trace *trace, struct perf_evsel *evsel,
2084 union perf_event *event __maybe_unused,
2085 struct perf_sample *sample)
2087 u64 runtime = perf_evsel__intval(evsel, sample, "runtime");
2088 double runtime_ms = (double)runtime / NSEC_PER_MSEC;
2089 struct thread *thread = machine__findnew_thread(trace->host,
2090 sample->pid,
2091 sample->tid);
2092 struct thread_trace *ttrace = thread__trace(thread, trace->output);
2094 if (ttrace == NULL)
2095 goto out_dump;
2097 ttrace->runtime_ms += runtime_ms;
2098 trace->runtime_ms += runtime_ms;
2099 out_put:
2100 thread__put(thread);
2101 return 0;
2103 out_dump:
2104 fprintf(trace->output, "%s: comm=%s,pid=%u,runtime=%" PRIu64 ",vruntime=%" PRIu64 ")\n",
2105 evsel->name,
2106 perf_evsel__strval(evsel, sample, "comm"),
2107 (pid_t)perf_evsel__intval(evsel, sample, "pid"),
2108 runtime,
2109 perf_evsel__intval(evsel, sample, "vruntime"));
2110 goto out_put;
2113 static int bpf_output__printer(enum binary_printer_ops op,
2114 unsigned int val, void *extra __maybe_unused, FILE *fp)
2116 unsigned char ch = (unsigned char)val;
2118 switch (op) {
2119 case BINARY_PRINT_CHAR_DATA:
2120 return fprintf(fp, "%c", isprint(ch) ? ch : '.');
2121 case BINARY_PRINT_DATA_BEGIN:
2122 case BINARY_PRINT_LINE_BEGIN:
2123 case BINARY_PRINT_ADDR:
2124 case BINARY_PRINT_NUM_DATA:
2125 case BINARY_PRINT_NUM_PAD:
2126 case BINARY_PRINT_SEP:
2127 case BINARY_PRINT_CHAR_PAD:
2128 case BINARY_PRINT_LINE_END:
2129 case BINARY_PRINT_DATA_END:
2130 default:
2131 break;
2134 return 0;
2137 static void bpf_output__fprintf(struct trace *trace,
2138 struct perf_sample *sample)
2140 binary__fprintf(sample->raw_data, sample->raw_size, 8,
2141 bpf_output__printer, NULL, trace->output);
2142 ++trace->nr_events_printed;
2145 static int trace__event_handler(struct trace *trace, struct perf_evsel *evsel,
2146 union perf_event *event __maybe_unused,
2147 struct perf_sample *sample)
2149 struct thread *thread;
2150 int callchain_ret = 0;
2152 * Check if we called perf_evsel__disable(evsel) due to, for instance,
2153 * this event's max_events having been hit and this is an entry coming
2154 * from the ring buffer that we should discard, since the max events
2155 * have already been considered/printed.
2157 if (evsel->disabled)
2158 return 0;
2160 thread = machine__findnew_thread(trace->host, sample->pid, sample->tid);
2162 if (sample->callchain) {
2163 callchain_ret = trace__resolve_callchain(trace, evsel, sample, &callchain_cursor);
2164 if (callchain_ret == 0) {
2165 if (callchain_cursor.nr < trace->min_stack)
2166 goto out;
2167 callchain_ret = 1;
2171 trace__printf_interrupted_entry(trace);
2172 trace__fprintf_tstamp(trace, sample->time, trace->output);
2174 if (trace->trace_syscalls)
2175 fprintf(trace->output, "( ): ");
2177 if (thread)
2178 trace__fprintf_comm_tid(trace, thread, trace->output);
2180 if (evsel == trace->syscalls.events.augmented) {
2181 int id = perf_evsel__sc_tp_uint(evsel, id, sample);
2182 struct syscall *sc = trace__syscall_info(trace, evsel, id);
2184 if (sc) {
2185 fprintf(trace->output, "%s(", sc->name);
2186 trace__fprintf_sys_enter(trace, evsel, sample);
2187 fputc(')', trace->output);
2188 goto newline;
2192 * XXX: Not having the associated syscall info or not finding/adding
2193 * the thread should never happen, but if it does...
2194 * fall thru and print it as a bpf_output event.
2198 fprintf(trace->output, "%s:", evsel->name);
2200 if (perf_evsel__is_bpf_output(evsel)) {
2201 bpf_output__fprintf(trace, sample);
2202 } else if (evsel->tp_format) {
2203 if (strncmp(evsel->tp_format->name, "sys_enter_", 10) ||
2204 trace__fprintf_sys_enter(trace, evsel, sample)) {
2205 event_format__fprintf(evsel->tp_format, sample->cpu,
2206 sample->raw_data, sample->raw_size,
2207 trace->output);
2208 ++trace->nr_events_printed;
2210 if (evsel->max_events != ULONG_MAX && ++evsel->nr_events_printed == evsel->max_events) {
2211 perf_evsel__disable(evsel);
2212 perf_evsel__close(evsel);
2217 newline:
2218 fprintf(trace->output, "\n");
2220 if (callchain_ret > 0)
2221 trace__fprintf_callchain(trace, sample);
2222 else if (callchain_ret < 0)
2223 pr_err("Problem processing %s callchain, skipping...\n", perf_evsel__name(evsel));
2224 out:
2225 thread__put(thread);
2226 return 0;
2229 static void print_location(FILE *f, struct perf_sample *sample,
2230 struct addr_location *al,
2231 bool print_dso, bool print_sym)
2234 if ((verbose > 0 || print_dso) && al->map)
2235 fprintf(f, "%s@", al->map->dso->long_name);
2237 if ((verbose > 0 || print_sym) && al->sym)
2238 fprintf(f, "%s+0x%" PRIx64, al->sym->name,
2239 al->addr - al->sym->start);
2240 else if (al->map)
2241 fprintf(f, "0x%" PRIx64, al->addr);
2242 else
2243 fprintf(f, "0x%" PRIx64, sample->addr);
2246 static int trace__pgfault(struct trace *trace,
2247 struct perf_evsel *evsel,
2248 union perf_event *event __maybe_unused,
2249 struct perf_sample *sample)
2251 struct thread *thread;
2252 struct addr_location al;
2253 char map_type = 'd';
2254 struct thread_trace *ttrace;
2255 int err = -1;
2256 int callchain_ret = 0;
2258 thread = machine__findnew_thread(trace->host, sample->pid, sample->tid);
2260 if (sample->callchain) {
2261 callchain_ret = trace__resolve_callchain(trace, evsel, sample, &callchain_cursor);
2262 if (callchain_ret == 0) {
2263 if (callchain_cursor.nr < trace->min_stack)
2264 goto out_put;
2265 callchain_ret = 1;
2269 ttrace = thread__trace(thread, trace->output);
2270 if (ttrace == NULL)
2271 goto out_put;
2273 if (evsel->attr.config == PERF_COUNT_SW_PAGE_FAULTS_MAJ)
2274 ttrace->pfmaj++;
2275 else
2276 ttrace->pfmin++;
2278 if (trace->summary_only)
2279 goto out;
2281 thread__find_symbol(thread, sample->cpumode, sample->ip, &al);
2283 trace__fprintf_entry_head(trace, thread, 0, true, sample->time, trace->output);
2285 fprintf(trace->output, "%sfault [",
2286 evsel->attr.config == PERF_COUNT_SW_PAGE_FAULTS_MAJ ?
2287 "maj" : "min");
2289 print_location(trace->output, sample, &al, false, true);
2291 fprintf(trace->output, "] => ");
2293 thread__find_symbol(thread, sample->cpumode, sample->addr, &al);
2295 if (!al.map) {
2296 thread__find_symbol(thread, sample->cpumode, sample->addr, &al);
2298 if (al.map)
2299 map_type = 'x';
2300 else
2301 map_type = '?';
2304 print_location(trace->output, sample, &al, true, false);
2306 fprintf(trace->output, " (%c%c)\n", map_type, al.level);
2308 if (callchain_ret > 0)
2309 trace__fprintf_callchain(trace, sample);
2310 else if (callchain_ret < 0)
2311 pr_err("Problem processing %s callchain, skipping...\n", perf_evsel__name(evsel));
2313 ++trace->nr_events_printed;
2314 out:
2315 err = 0;
2316 out_put:
2317 thread__put(thread);
2318 return err;
2321 static void trace__set_base_time(struct trace *trace,
2322 struct perf_evsel *evsel,
2323 struct perf_sample *sample)
2326 * BPF events were not setting PERF_SAMPLE_TIME, so be more robust
2327 * and don't use sample->time unconditionally, we may end up having
2328 * some other event in the future without PERF_SAMPLE_TIME for good
2329 * reason, i.e. we may not be interested in its timestamps, just in
2330 * it taking place, picking some piece of information when it
2331 * appears in our event stream (vfs_getname comes to mind).
2333 if (trace->base_time == 0 && !trace->full_time &&
2334 (evsel->attr.sample_type & PERF_SAMPLE_TIME))
2335 trace->base_time = sample->time;
2338 static int trace__process_sample(struct perf_tool *tool,
2339 union perf_event *event,
2340 struct perf_sample *sample,
2341 struct perf_evsel *evsel,
2342 struct machine *machine __maybe_unused)
2344 struct trace *trace = container_of(tool, struct trace, tool);
2345 struct thread *thread;
2346 int err = 0;
2348 tracepoint_handler handler = evsel->handler;
2350 thread = machine__findnew_thread(trace->host, sample->pid, sample->tid);
2351 if (thread && thread__is_filtered(thread))
2352 goto out;
2354 trace__set_base_time(trace, evsel, sample);
2356 if (handler) {
2357 ++trace->nr_events;
2358 handler(trace, evsel, event, sample);
2360 out:
2361 thread__put(thread);
2362 return err;
2365 static int trace__record(struct trace *trace, int argc, const char **argv)
2367 unsigned int rec_argc, i, j;
2368 const char **rec_argv;
2369 const char * const record_args[] = {
2370 "record",
2371 "-R",
2372 "-m", "1024",
2373 "-c", "1",
2376 const char * const sc_args[] = { "-e", };
2377 unsigned int sc_args_nr = ARRAY_SIZE(sc_args);
2378 const char * const majpf_args[] = { "-e", "major-faults" };
2379 unsigned int majpf_args_nr = ARRAY_SIZE(majpf_args);
2380 const char * const minpf_args[] = { "-e", "minor-faults" };
2381 unsigned int minpf_args_nr = ARRAY_SIZE(minpf_args);
2383 /* +1 is for the event string below */
2384 rec_argc = ARRAY_SIZE(record_args) + sc_args_nr + 1 +
2385 majpf_args_nr + minpf_args_nr + argc;
2386 rec_argv = calloc(rec_argc + 1, sizeof(char *));
2388 if (rec_argv == NULL)
2389 return -ENOMEM;
2391 j = 0;
2392 for (i = 0; i < ARRAY_SIZE(record_args); i++)
2393 rec_argv[j++] = record_args[i];
2395 if (trace->trace_syscalls) {
2396 for (i = 0; i < sc_args_nr; i++)
2397 rec_argv[j++] = sc_args[i];
2399 /* event string may be different for older kernels - e.g., RHEL6 */
2400 if (is_valid_tracepoint("raw_syscalls:sys_enter"))
2401 rec_argv[j++] = "raw_syscalls:sys_enter,raw_syscalls:sys_exit";
2402 else if (is_valid_tracepoint("syscalls:sys_enter"))
2403 rec_argv[j++] = "syscalls:sys_enter,syscalls:sys_exit";
2404 else {
2405 pr_err("Neither raw_syscalls nor syscalls events exist.\n");
2406 free(rec_argv);
2407 return -1;
2411 if (trace->trace_pgfaults & TRACE_PFMAJ)
2412 for (i = 0; i < majpf_args_nr; i++)
2413 rec_argv[j++] = majpf_args[i];
2415 if (trace->trace_pgfaults & TRACE_PFMIN)
2416 for (i = 0; i < minpf_args_nr; i++)
2417 rec_argv[j++] = minpf_args[i];
2419 for (i = 0; i < (unsigned int)argc; i++)
2420 rec_argv[j++] = argv[i];
2422 return cmd_record(j, rec_argv);
2425 static size_t trace__fprintf_thread_summary(struct trace *trace, FILE *fp);
2427 static bool perf_evlist__add_vfs_getname(struct perf_evlist *evlist)
2429 struct perf_evsel *evsel = perf_evsel__newtp("probe", "vfs_getname");
2431 if (IS_ERR(evsel))
2432 return false;
2434 if (perf_evsel__field(evsel, "pathname") == NULL) {
2435 perf_evsel__delete(evsel);
2436 return false;
2439 evsel->handler = trace__vfs_getname;
2440 perf_evlist__add(evlist, evsel);
2441 return true;
2444 static struct perf_evsel *perf_evsel__new_pgfault(u64 config)
2446 struct perf_evsel *evsel;
2447 struct perf_event_attr attr = {
2448 .type = PERF_TYPE_SOFTWARE,
2449 .mmap_data = 1,
2452 attr.config = config;
2453 attr.sample_period = 1;
2455 event_attr_init(&attr);
2457 evsel = perf_evsel__new(&attr);
2458 if (evsel)
2459 evsel->handler = trace__pgfault;
2461 return evsel;
2464 static void trace__handle_event(struct trace *trace, union perf_event *event, struct perf_sample *sample)
2466 const u32 type = event->header.type;
2467 struct perf_evsel *evsel;
2469 if (type != PERF_RECORD_SAMPLE) {
2470 trace__process_event(trace, trace->host, event, sample);
2471 return;
2474 evsel = perf_evlist__id2evsel(trace->evlist, sample->id);
2475 if (evsel == NULL) {
2476 fprintf(trace->output, "Unknown tp ID %" PRIu64 ", skipping...\n", sample->id);
2477 return;
2480 trace__set_base_time(trace, evsel, sample);
2482 if (evsel->attr.type == PERF_TYPE_TRACEPOINT &&
2483 sample->raw_data == NULL) {
2484 fprintf(trace->output, "%s sample with no payload for tid: %d, cpu %d, raw_size=%d, skipping...\n",
2485 perf_evsel__name(evsel), sample->tid,
2486 sample->cpu, sample->raw_size);
2487 } else {
2488 tracepoint_handler handler = evsel->handler;
2489 handler(trace, evsel, event, sample);
2492 if (trace->nr_events_printed >= trace->max_events && trace->max_events != ULONG_MAX)
2493 interrupted = true;
2496 static int trace__add_syscall_newtp(struct trace *trace)
2498 int ret = -1;
2499 struct perf_evlist *evlist = trace->evlist;
2500 struct perf_evsel *sys_enter, *sys_exit;
2502 sys_enter = perf_evsel__raw_syscall_newtp("sys_enter", trace__sys_enter);
2503 if (sys_enter == NULL)
2504 goto out;
2506 if (perf_evsel__init_sc_tp_ptr_field(sys_enter, args))
2507 goto out_delete_sys_enter;
2509 sys_exit = perf_evsel__raw_syscall_newtp("sys_exit", trace__sys_exit);
2510 if (sys_exit == NULL)
2511 goto out_delete_sys_enter;
2513 if (perf_evsel__init_sc_tp_uint_field(sys_exit, ret))
2514 goto out_delete_sys_exit;
2516 perf_evsel__config_callchain(sys_enter, &trace->opts, &callchain_param);
2517 perf_evsel__config_callchain(sys_exit, &trace->opts, &callchain_param);
2519 perf_evlist__add(evlist, sys_enter);
2520 perf_evlist__add(evlist, sys_exit);
2522 if (callchain_param.enabled && !trace->kernel_syscallchains) {
2524 * We're interested only in the user space callchain
2525 * leading to the syscall, allow overriding that for
2526 * debugging reasons using --kernel_syscall_callchains
2528 sys_exit->attr.exclude_callchain_kernel = 1;
2531 trace->syscalls.events.sys_enter = sys_enter;
2532 trace->syscalls.events.sys_exit = sys_exit;
2534 ret = 0;
2535 out:
2536 return ret;
2538 out_delete_sys_exit:
2539 perf_evsel__delete_priv(sys_exit);
2540 out_delete_sys_enter:
2541 perf_evsel__delete_priv(sys_enter);
2542 goto out;
2545 static int trace__set_ev_qualifier_filter(struct trace *trace)
2547 int err = -1;
2548 struct perf_evsel *sys_exit;
2549 char *filter = asprintf_expr_inout_ints("id", !trace->not_ev_qualifier,
2550 trace->ev_qualifier_ids.nr,
2551 trace->ev_qualifier_ids.entries);
2553 if (filter == NULL)
2554 goto out_enomem;
2556 if (!perf_evsel__append_tp_filter(trace->syscalls.events.sys_enter,
2557 filter)) {
2558 sys_exit = trace->syscalls.events.sys_exit;
2559 err = perf_evsel__append_tp_filter(sys_exit, filter);
2562 free(filter);
2563 out:
2564 return err;
2565 out_enomem:
2566 errno = ENOMEM;
2567 goto out;
2570 static int bpf_map__set_filter_pids(struct bpf_map *map __maybe_unused,
2571 size_t npids __maybe_unused, pid_t *pids __maybe_unused)
2573 int err = 0;
2574 #ifdef HAVE_LIBBPF_SUPPORT
2575 bool value = true;
2576 int map_fd = bpf_map__fd(map);
2577 size_t i;
2579 for (i = 0; i < npids; ++i) {
2580 err = bpf_map_update_elem(map_fd, &pids[i], &value, BPF_ANY);
2581 if (err)
2582 break;
2584 #endif
2585 return err;
2588 static int trace__set_filter_loop_pids(struct trace *trace)
2590 unsigned int nr = 1, err;
2591 pid_t pids[32] = {
2592 getpid(),
2594 struct thread *thread = machine__find_thread(trace->host, pids[0], pids[0]);
2596 while (thread && nr < ARRAY_SIZE(pids)) {
2597 struct thread *parent = machine__find_thread(trace->host, thread->ppid, thread->ppid);
2599 if (parent == NULL)
2600 break;
2602 if (!strcmp(thread__comm_str(parent), "sshd")) {
2603 pids[nr++] = parent->tid;
2604 break;
2606 thread = parent;
2609 err = perf_evlist__set_tp_filter_pids(trace->evlist, nr, pids);
2610 if (!err && trace->filter_pids.map)
2611 err = bpf_map__set_filter_pids(trace->filter_pids.map, nr, pids);
2613 return err;
2616 static int trace__set_filter_pids(struct trace *trace)
2618 int err = 0;
2620 * Better not use !target__has_task() here because we need to cover the
2621 * case where no threads were specified in the command line, but a
2622 * workload was, and in that case we will fill in the thread_map when
2623 * we fork the workload in perf_evlist__prepare_workload.
2625 if (trace->filter_pids.nr > 0) {
2626 err = perf_evlist__set_tp_filter_pids(trace->evlist, trace->filter_pids.nr,
2627 trace->filter_pids.entries);
2628 if (!err && trace->filter_pids.map) {
2629 err = bpf_map__set_filter_pids(trace->filter_pids.map, trace->filter_pids.nr,
2630 trace->filter_pids.entries);
2632 } else if (thread_map__pid(trace->evlist->threads, 0) == -1) {
2633 err = trace__set_filter_loop_pids(trace);
2636 return err;
2639 static int trace__run(struct trace *trace, int argc, const char **argv)
2641 struct perf_evlist *evlist = trace->evlist;
2642 struct perf_evsel *evsel, *pgfault_maj = NULL, *pgfault_min = NULL;
2643 int err = -1, i;
2644 unsigned long before;
2645 const bool forks = argc > 0;
2646 bool draining = false;
2648 trace->live = true;
2650 if (trace->trace_syscalls && trace__add_syscall_newtp(trace))
2651 goto out_error_raw_syscalls;
2653 if (trace->trace_syscalls)
2654 trace->vfs_getname = perf_evlist__add_vfs_getname(evlist);
2656 if ((trace->trace_pgfaults & TRACE_PFMAJ)) {
2657 pgfault_maj = perf_evsel__new_pgfault(PERF_COUNT_SW_PAGE_FAULTS_MAJ);
2658 if (pgfault_maj == NULL)
2659 goto out_error_mem;
2660 perf_evsel__config_callchain(pgfault_maj, &trace->opts, &callchain_param);
2661 perf_evlist__add(evlist, pgfault_maj);
2664 if ((trace->trace_pgfaults & TRACE_PFMIN)) {
2665 pgfault_min = perf_evsel__new_pgfault(PERF_COUNT_SW_PAGE_FAULTS_MIN);
2666 if (pgfault_min == NULL)
2667 goto out_error_mem;
2668 perf_evsel__config_callchain(pgfault_min, &trace->opts, &callchain_param);
2669 perf_evlist__add(evlist, pgfault_min);
2672 if (trace->sched &&
2673 perf_evlist__add_newtp(evlist, "sched", "sched_stat_runtime",
2674 trace__sched_stat_runtime))
2675 goto out_error_sched_stat_runtime;
2678 * If a global cgroup was set, apply it to all the events without an
2679 * explicit cgroup. I.e.:
2681 * trace -G A -e sched:*switch
2683 * Will set all raw_syscalls:sys_{enter,exit}, pgfault, vfs_getname, etc
2684 * _and_ sched:sched_switch to the 'A' cgroup, while:
2686 * trace -e sched:*switch -G A
2688 * will only set the sched:sched_switch event to the 'A' cgroup, all the
2689 * other events (raw_syscalls:sys_{enter,exit}, etc are left "without"
2690 * a cgroup (on the root cgroup, sys wide, etc).
2692 * Multiple cgroups:
2694 * trace -G A -e sched:*switch -G B
2696 * the syscall ones go to the 'A' cgroup, the sched:sched_switch goes
2697 * to the 'B' cgroup.
2699 * evlist__set_default_cgroup() grabs a reference of the passed cgroup
2700 * only for the evsels still without a cgroup, i.e. evsel->cgroup == NULL.
2702 if (trace->cgroup)
2703 evlist__set_default_cgroup(trace->evlist, trace->cgroup);
2705 err = perf_evlist__create_maps(evlist, &trace->opts.target);
2706 if (err < 0) {
2707 fprintf(trace->output, "Problems parsing the target to trace, check your options!\n");
2708 goto out_delete_evlist;
2711 err = trace__symbols_init(trace, evlist);
2712 if (err < 0) {
2713 fprintf(trace->output, "Problems initializing symbol libraries!\n");
2714 goto out_delete_evlist;
2717 perf_evlist__config(evlist, &trace->opts, &callchain_param);
2719 signal(SIGCHLD, sig_handler);
2720 signal(SIGINT, sig_handler);
2722 if (forks) {
2723 err = perf_evlist__prepare_workload(evlist, &trace->opts.target,
2724 argv, false, NULL);
2725 if (err < 0) {
2726 fprintf(trace->output, "Couldn't run the workload!\n");
2727 goto out_delete_evlist;
2731 err = perf_evlist__open(evlist);
2732 if (err < 0)
2733 goto out_error_open;
2735 err = bpf__apply_obj_config();
2736 if (err) {
2737 char errbuf[BUFSIZ];
2739 bpf__strerror_apply_obj_config(err, errbuf, sizeof(errbuf));
2740 pr_err("ERROR: Apply config to BPF failed: %s\n",
2741 errbuf);
2742 goto out_error_open;
2745 err = trace__set_filter_pids(trace);
2746 if (err < 0)
2747 goto out_error_mem;
2749 if (trace->ev_qualifier_ids.nr > 0) {
2750 err = trace__set_ev_qualifier_filter(trace);
2751 if (err < 0)
2752 goto out_errno;
2754 pr_debug("event qualifier tracepoint filter: %s\n",
2755 trace->syscalls.events.sys_exit->filter);
2758 err = perf_evlist__apply_filters(evlist, &evsel);
2759 if (err < 0)
2760 goto out_error_apply_filters;
2762 err = perf_evlist__mmap(evlist, trace->opts.mmap_pages);
2763 if (err < 0)
2764 goto out_error_mmap;
2766 if (!target__none(&trace->opts.target) && !trace->opts.initial_delay)
2767 perf_evlist__enable(evlist);
2769 if (forks)
2770 perf_evlist__start_workload(evlist);
2772 if (trace->opts.initial_delay) {
2773 usleep(trace->opts.initial_delay * 1000);
2774 perf_evlist__enable(evlist);
2777 trace->multiple_threads = thread_map__pid(evlist->threads, 0) == -1 ||
2778 evlist->threads->nr > 1 ||
2779 perf_evlist__first(evlist)->attr.inherit;
2782 * Now that we already used evsel->attr to ask the kernel to setup the
2783 * events, lets reuse evsel->attr.sample_max_stack as the limit in
2784 * trace__resolve_callchain(), allowing per-event max-stack settings
2785 * to override an explicitely set --max-stack global setting.
2787 evlist__for_each_entry(evlist, evsel) {
2788 if (evsel__has_callchain(evsel) &&
2789 evsel->attr.sample_max_stack == 0)
2790 evsel->attr.sample_max_stack = trace->max_stack;
2792 again:
2793 before = trace->nr_events;
2795 for (i = 0; i < evlist->nr_mmaps; i++) {
2796 union perf_event *event;
2797 struct perf_mmap *md;
2799 md = &evlist->mmap[i];
2800 if (perf_mmap__read_init(md) < 0)
2801 continue;
2803 while ((event = perf_mmap__read_event(md)) != NULL) {
2804 struct perf_sample sample;
2806 ++trace->nr_events;
2808 err = perf_evlist__parse_sample(evlist, event, &sample);
2809 if (err) {
2810 fprintf(trace->output, "Can't parse sample, err = %d, skipping...\n", err);
2811 goto next_event;
2814 trace__handle_event(trace, event, &sample);
2815 next_event:
2816 perf_mmap__consume(md);
2818 if (interrupted)
2819 goto out_disable;
2821 if (done && !draining) {
2822 perf_evlist__disable(evlist);
2823 draining = true;
2826 perf_mmap__read_done(md);
2829 if (trace->nr_events == before) {
2830 int timeout = done ? 100 : -1;
2832 if (!draining && perf_evlist__poll(evlist, timeout) > 0) {
2833 if (perf_evlist__filter_pollfd(evlist, POLLERR | POLLHUP | POLLNVAL) == 0)
2834 draining = true;
2836 goto again;
2838 } else {
2839 goto again;
2842 out_disable:
2843 thread__zput(trace->current);
2845 perf_evlist__disable(evlist);
2847 if (!err) {
2848 if (trace->summary)
2849 trace__fprintf_thread_summary(trace, trace->output);
2851 if (trace->show_tool_stats) {
2852 fprintf(trace->output, "Stats:\n "
2853 " vfs_getname : %" PRIu64 "\n"
2854 " proc_getname: %" PRIu64 "\n",
2855 trace->stats.vfs_getname,
2856 trace->stats.proc_getname);
2860 out_delete_evlist:
2861 trace__symbols__exit(trace);
2863 perf_evlist__delete(evlist);
2864 cgroup__put(trace->cgroup);
2865 trace->evlist = NULL;
2866 trace->live = false;
2867 return err;
2869 char errbuf[BUFSIZ];
2871 out_error_sched_stat_runtime:
2872 tracing_path__strerror_open_tp(errno, errbuf, sizeof(errbuf), "sched", "sched_stat_runtime");
2873 goto out_error;
2875 out_error_raw_syscalls:
2876 tracing_path__strerror_open_tp(errno, errbuf, sizeof(errbuf), "raw_syscalls", "sys_(enter|exit)");
2877 goto out_error;
2879 out_error_mmap:
2880 perf_evlist__strerror_mmap(evlist, errno, errbuf, sizeof(errbuf));
2881 goto out_error;
2883 out_error_open:
2884 perf_evlist__strerror_open(evlist, errno, errbuf, sizeof(errbuf));
2886 out_error:
2887 fprintf(trace->output, "%s\n", errbuf);
2888 goto out_delete_evlist;
2890 out_error_apply_filters:
2891 fprintf(trace->output,
2892 "Failed to set filter \"%s\" on event %s with %d (%s)\n",
2893 evsel->filter, perf_evsel__name(evsel), errno,
2894 str_error_r(errno, errbuf, sizeof(errbuf)));
2895 goto out_delete_evlist;
2897 out_error_mem:
2898 fprintf(trace->output, "Not enough memory to run!\n");
2899 goto out_delete_evlist;
2901 out_errno:
2902 fprintf(trace->output, "errno=%d,%s\n", errno, strerror(errno));
2903 goto out_delete_evlist;
2906 static int trace__replay(struct trace *trace)
2908 const struct perf_evsel_str_handler handlers[] = {
2909 { "probe:vfs_getname", trace__vfs_getname, },
2911 struct perf_data data = {
2912 .file = {
2913 .path = input_name,
2915 .mode = PERF_DATA_MODE_READ,
2916 .force = trace->force,
2918 struct perf_session *session;
2919 struct perf_evsel *evsel;
2920 int err = -1;
2922 trace->tool.sample = trace__process_sample;
2923 trace->tool.mmap = perf_event__process_mmap;
2924 trace->tool.mmap2 = perf_event__process_mmap2;
2925 trace->tool.comm = perf_event__process_comm;
2926 trace->tool.exit = perf_event__process_exit;
2927 trace->tool.fork = perf_event__process_fork;
2928 trace->tool.attr = perf_event__process_attr;
2929 trace->tool.tracing_data = perf_event__process_tracing_data;
2930 trace->tool.build_id = perf_event__process_build_id;
2931 trace->tool.namespaces = perf_event__process_namespaces;
2933 trace->tool.ordered_events = true;
2934 trace->tool.ordering_requires_timestamps = true;
2936 /* add tid to output */
2937 trace->multiple_threads = true;
2939 session = perf_session__new(&data, false, &trace->tool);
2940 if (session == NULL)
2941 return -1;
2943 if (trace->opts.target.pid)
2944 symbol_conf.pid_list_str = strdup(trace->opts.target.pid);
2946 if (trace->opts.target.tid)
2947 symbol_conf.tid_list_str = strdup(trace->opts.target.tid);
2949 if (symbol__init(&session->header.env) < 0)
2950 goto out;
2952 trace->host = &session->machines.host;
2954 err = perf_session__set_tracepoints_handlers(session, handlers);
2955 if (err)
2956 goto out;
2958 evsel = perf_evlist__find_tracepoint_by_name(session->evlist,
2959 "raw_syscalls:sys_enter");
2960 /* older kernels have syscalls tp versus raw_syscalls */
2961 if (evsel == NULL)
2962 evsel = perf_evlist__find_tracepoint_by_name(session->evlist,
2963 "syscalls:sys_enter");
2965 if (evsel &&
2966 (perf_evsel__init_raw_syscall_tp(evsel, trace__sys_enter) < 0 ||
2967 perf_evsel__init_sc_tp_ptr_field(evsel, args))) {
2968 pr_err("Error during initialize raw_syscalls:sys_enter event\n");
2969 goto out;
2972 evsel = perf_evlist__find_tracepoint_by_name(session->evlist,
2973 "raw_syscalls:sys_exit");
2974 if (evsel == NULL)
2975 evsel = perf_evlist__find_tracepoint_by_name(session->evlist,
2976 "syscalls:sys_exit");
2977 if (evsel &&
2978 (perf_evsel__init_raw_syscall_tp(evsel, trace__sys_exit) < 0 ||
2979 perf_evsel__init_sc_tp_uint_field(evsel, ret))) {
2980 pr_err("Error during initialize raw_syscalls:sys_exit event\n");
2981 goto out;
2984 evlist__for_each_entry(session->evlist, evsel) {
2985 if (evsel->attr.type == PERF_TYPE_SOFTWARE &&
2986 (evsel->attr.config == PERF_COUNT_SW_PAGE_FAULTS_MAJ ||
2987 evsel->attr.config == PERF_COUNT_SW_PAGE_FAULTS_MIN ||
2988 evsel->attr.config == PERF_COUNT_SW_PAGE_FAULTS))
2989 evsel->handler = trace__pgfault;
2992 setup_pager();
2994 err = perf_session__process_events(session);
2995 if (err)
2996 pr_err("Failed to process events, error %d", err);
2998 else if (trace->summary)
2999 trace__fprintf_thread_summary(trace, trace->output);
3001 out:
3002 perf_session__delete(session);
3004 return err;
3007 static size_t trace__fprintf_threads_header(FILE *fp)
3009 size_t printed;
3011 printed = fprintf(fp, "\n Summary of events:\n\n");
3013 return printed;
3016 DEFINE_RESORT_RB(syscall_stats, a->msecs > b->msecs,
3017 struct stats *stats;
3018 double msecs;
3019 int syscall;
3022 struct int_node *source = rb_entry(nd, struct int_node, rb_node);
3023 struct stats *stats = source->priv;
3025 entry->syscall = source->i;
3026 entry->stats = stats;
3027 entry->msecs = stats ? (u64)stats->n * (avg_stats(stats) / NSEC_PER_MSEC) : 0;
3030 static size_t thread__dump_stats(struct thread_trace *ttrace,
3031 struct trace *trace, FILE *fp)
3033 size_t printed = 0;
3034 struct syscall *sc;
3035 struct rb_node *nd;
3036 DECLARE_RESORT_RB_INTLIST(syscall_stats, ttrace->syscall_stats);
3038 if (syscall_stats == NULL)
3039 return 0;
3041 printed += fprintf(fp, "\n");
3043 printed += fprintf(fp, " syscall calls total min avg max stddev\n");
3044 printed += fprintf(fp, " (msec) (msec) (msec) (msec) (%%)\n");
3045 printed += fprintf(fp, " --------------- -------- --------- --------- --------- --------- ------\n");
3047 resort_rb__for_each_entry(nd, syscall_stats) {
3048 struct stats *stats = syscall_stats_entry->stats;
3049 if (stats) {
3050 double min = (double)(stats->min) / NSEC_PER_MSEC;
3051 double max = (double)(stats->max) / NSEC_PER_MSEC;
3052 double avg = avg_stats(stats);
3053 double pct;
3054 u64 n = (u64) stats->n;
3056 pct = avg ? 100.0 * stddev_stats(stats)/avg : 0.0;
3057 avg /= NSEC_PER_MSEC;
3059 sc = &trace->syscalls.table[syscall_stats_entry->syscall];
3060 printed += fprintf(fp, " %-15s", sc->name);
3061 printed += fprintf(fp, " %8" PRIu64 " %9.3f %9.3f %9.3f",
3062 n, syscall_stats_entry->msecs, min, avg);
3063 printed += fprintf(fp, " %9.3f %9.2f%%\n", max, pct);
3067 resort_rb__delete(syscall_stats);
3068 printed += fprintf(fp, "\n\n");
3070 return printed;
3073 static size_t trace__fprintf_thread(FILE *fp, struct thread *thread, struct trace *trace)
3075 size_t printed = 0;
3076 struct thread_trace *ttrace = thread__priv(thread);
3077 double ratio;
3079 if (ttrace == NULL)
3080 return 0;
3082 ratio = (double)ttrace->nr_events / trace->nr_events * 100.0;
3084 printed += fprintf(fp, " %s (%d), ", thread__comm_str(thread), thread->tid);
3085 printed += fprintf(fp, "%lu events, ", ttrace->nr_events);
3086 printed += fprintf(fp, "%.1f%%", ratio);
3087 if (ttrace->pfmaj)
3088 printed += fprintf(fp, ", %lu majfaults", ttrace->pfmaj);
3089 if (ttrace->pfmin)
3090 printed += fprintf(fp, ", %lu minfaults", ttrace->pfmin);
3091 if (trace->sched)
3092 printed += fprintf(fp, ", %.3f msec\n", ttrace->runtime_ms);
3093 else if (fputc('\n', fp) != EOF)
3094 ++printed;
3096 printed += thread__dump_stats(ttrace, trace, fp);
3098 return printed;
3101 static unsigned long thread__nr_events(struct thread_trace *ttrace)
3103 return ttrace ? ttrace->nr_events : 0;
3106 DEFINE_RESORT_RB(threads, (thread__nr_events(a->thread->priv) < thread__nr_events(b->thread->priv)),
3107 struct thread *thread;
3110 entry->thread = rb_entry(nd, struct thread, rb_node);
3113 static size_t trace__fprintf_thread_summary(struct trace *trace, FILE *fp)
3115 size_t printed = trace__fprintf_threads_header(fp);
3116 struct rb_node *nd;
3117 int i;
3119 for (i = 0; i < THREADS__TABLE_SIZE; i++) {
3120 DECLARE_RESORT_RB_MACHINE_THREADS(threads, trace->host, i);
3122 if (threads == NULL) {
3123 fprintf(fp, "%s", "Error sorting output by nr_events!\n");
3124 return 0;
3127 resort_rb__for_each_entry(nd, threads)
3128 printed += trace__fprintf_thread(fp, threads_entry->thread, trace);
3130 resort_rb__delete(threads);
3132 return printed;
3135 static int trace__set_duration(const struct option *opt, const char *str,
3136 int unset __maybe_unused)
3138 struct trace *trace = opt->value;
3140 trace->duration_filter = atof(str);
3141 return 0;
3144 static int trace__set_filter_pids_from_option(const struct option *opt, const char *str,
3145 int unset __maybe_unused)
3147 int ret = -1;
3148 size_t i;
3149 struct trace *trace = opt->value;
3151 * FIXME: introduce a intarray class, plain parse csv and create a
3152 * { int nr, int entries[] } struct...
3154 struct intlist *list = intlist__new(str);
3156 if (list == NULL)
3157 return -1;
3159 i = trace->filter_pids.nr = intlist__nr_entries(list) + 1;
3160 trace->filter_pids.entries = calloc(i, sizeof(pid_t));
3162 if (trace->filter_pids.entries == NULL)
3163 goto out;
3165 trace->filter_pids.entries[0] = getpid();
3167 for (i = 1; i < trace->filter_pids.nr; ++i)
3168 trace->filter_pids.entries[i] = intlist__entry(list, i - 1)->i;
3170 intlist__delete(list);
3171 ret = 0;
3172 out:
3173 return ret;
3176 static int trace__open_output(struct trace *trace, const char *filename)
3178 struct stat st;
3180 if (!stat(filename, &st) && st.st_size) {
3181 char oldname[PATH_MAX];
3183 scnprintf(oldname, sizeof(oldname), "%s.old", filename);
3184 unlink(oldname);
3185 rename(filename, oldname);
3188 trace->output = fopen(filename, "w");
3190 return trace->output == NULL ? -errno : 0;
3193 static int parse_pagefaults(const struct option *opt, const char *str,
3194 int unset __maybe_unused)
3196 int *trace_pgfaults = opt->value;
3198 if (strcmp(str, "all") == 0)
3199 *trace_pgfaults |= TRACE_PFMAJ | TRACE_PFMIN;
3200 else if (strcmp(str, "maj") == 0)
3201 *trace_pgfaults |= TRACE_PFMAJ;
3202 else if (strcmp(str, "min") == 0)
3203 *trace_pgfaults |= TRACE_PFMIN;
3204 else
3205 return -1;
3207 return 0;
3210 static void evlist__set_evsel_handler(struct perf_evlist *evlist, void *handler)
3212 struct perf_evsel *evsel;
3214 evlist__for_each_entry(evlist, evsel)
3215 evsel->handler = handler;
3218 static int evlist__set_syscall_tp_fields(struct perf_evlist *evlist)
3220 struct perf_evsel *evsel;
3222 evlist__for_each_entry(evlist, evsel) {
3223 if (evsel->priv || !evsel->tp_format)
3224 continue;
3226 if (strcmp(evsel->tp_format->system, "syscalls"))
3227 continue;
3229 if (perf_evsel__init_syscall_tp(evsel))
3230 return -1;
3232 if (!strncmp(evsel->tp_format->name, "sys_enter_", 10)) {
3233 struct syscall_tp *sc = evsel->priv;
3235 if (__tp_field__init_ptr(&sc->args, sc->id.offset + sizeof(u64)))
3236 return -1;
3237 } else if (!strncmp(evsel->tp_format->name, "sys_exit_", 9)) {
3238 struct syscall_tp *sc = evsel->priv;
3240 if (__tp_field__init_uint(&sc->ret, sizeof(u64), sc->id.offset + sizeof(u64), evsel->needs_swap))
3241 return -1;
3245 return 0;
3249 * XXX: Hackish, just splitting the combined -e+--event (syscalls
3250 * (raw_syscalls:{sys_{enter,exit}} + events (tracepoints, HW, SW, etc) to use
3251 * existing facilities unchanged (trace->ev_qualifier + parse_options()).
3253 * It'd be better to introduce a parse_options() variant that would return a
3254 * list with the terms it didn't match to an event...
3256 static int trace__parse_events_option(const struct option *opt, const char *str,
3257 int unset __maybe_unused)
3259 struct trace *trace = (struct trace *)opt->value;
3260 const char *s = str;
3261 char *sep = NULL, *lists[2] = { NULL, NULL, };
3262 int len = strlen(str) + 1, err = -1, list, idx;
3263 char *strace_groups_dir = system_path(STRACE_GROUPS_DIR);
3264 char group_name[PATH_MAX];
3265 struct syscall_fmt *fmt;
3267 if (strace_groups_dir == NULL)
3268 return -1;
3270 if (*s == '!') {
3271 ++s;
3272 trace->not_ev_qualifier = true;
3275 while (1) {
3276 if ((sep = strchr(s, ',')) != NULL)
3277 *sep = '\0';
3279 list = 0;
3280 if (syscalltbl__id(trace->sctbl, s) >= 0 ||
3281 syscalltbl__strglobmatch_first(trace->sctbl, s, &idx) >= 0) {
3282 list = 1;
3283 goto do_concat;
3286 fmt = syscall_fmt__find_by_alias(s);
3287 if (fmt != NULL) {
3288 list = 1;
3289 s = fmt->name;
3290 } else {
3291 path__join(group_name, sizeof(group_name), strace_groups_dir, s);
3292 if (access(group_name, R_OK) == 0)
3293 list = 1;
3295 do_concat:
3296 if (lists[list]) {
3297 sprintf(lists[list] + strlen(lists[list]), ",%s", s);
3298 } else {
3299 lists[list] = malloc(len);
3300 if (lists[list] == NULL)
3301 goto out;
3302 strcpy(lists[list], s);
3305 if (!sep)
3306 break;
3308 *sep = ',';
3309 s = sep + 1;
3312 if (lists[1] != NULL) {
3313 struct strlist_config slist_config = {
3314 .dirname = strace_groups_dir,
3317 trace->ev_qualifier = strlist__new(lists[1], &slist_config);
3318 if (trace->ev_qualifier == NULL) {
3319 fputs("Not enough memory to parse event qualifier", trace->output);
3320 goto out;
3323 if (trace__validate_ev_qualifier(trace))
3324 goto out;
3325 trace->trace_syscalls = true;
3328 err = 0;
3330 if (lists[0]) {
3331 struct option o = OPT_CALLBACK('e', "event", &trace->evlist, "event",
3332 "event selector. use 'perf list' to list available events",
3333 parse_events_option);
3334 err = parse_events_option(&o, lists[0], 0);
3336 out:
3337 if (sep)
3338 *sep = ',';
3340 return err;
3343 static int trace__parse_cgroups(const struct option *opt, const char *str, int unset)
3345 struct trace *trace = opt->value;
3347 if (!list_empty(&trace->evlist->entries))
3348 return parse_cgroups(opt, str, unset);
3350 trace->cgroup = evlist__findnew_cgroup(trace->evlist, str);
3352 return 0;
3355 static struct bpf_map *bpf__find_map_by_name(const char *name)
3357 struct bpf_object *obj, *tmp;
3359 bpf_object__for_each_safe(obj, tmp) {
3360 struct bpf_map *map = bpf_object__find_map_by_name(obj, name);
3361 if (map)
3362 return map;
3366 return NULL;
3369 static void trace__set_bpf_map_filtered_pids(struct trace *trace)
3371 trace->filter_pids.map = bpf__find_map_by_name("pids_filtered");
3374 int cmd_trace(int argc, const char **argv)
3376 const char *trace_usage[] = {
3377 "perf trace [<options>] [<command>]",
3378 "perf trace [<options>] -- <command> [<options>]",
3379 "perf trace record [<options>] [<command>]",
3380 "perf trace record [<options>] -- <command> [<options>]",
3381 NULL
3383 struct trace trace = {
3384 .syscalls = {
3385 . max = -1,
3387 .opts = {
3388 .target = {
3389 .uid = UINT_MAX,
3390 .uses_mmap = true,
3392 .user_freq = UINT_MAX,
3393 .user_interval = ULLONG_MAX,
3394 .no_buffering = true,
3395 .mmap_pages = UINT_MAX,
3396 .proc_map_timeout = 500,
3398 .output = stderr,
3399 .show_comm = true,
3400 .trace_syscalls = false,
3401 .kernel_syscallchains = false,
3402 .max_stack = UINT_MAX,
3403 .max_events = ULONG_MAX,
3405 const char *output_name = NULL;
3406 const struct option trace_options[] = {
3407 OPT_CALLBACK('e', "event", &trace, "event",
3408 "event/syscall selector. use 'perf list' to list available events",
3409 trace__parse_events_option),
3410 OPT_BOOLEAN(0, "comm", &trace.show_comm,
3411 "show the thread COMM next to its id"),
3412 OPT_BOOLEAN(0, "tool_stats", &trace.show_tool_stats, "show tool stats"),
3413 OPT_CALLBACK(0, "expr", &trace, "expr", "list of syscalls/events to trace",
3414 trace__parse_events_option),
3415 OPT_STRING('o', "output", &output_name, "file", "output file name"),
3416 OPT_STRING('i', "input", &input_name, "file", "Analyze events in file"),
3417 OPT_STRING('p', "pid", &trace.opts.target.pid, "pid",
3418 "trace events on existing process id"),
3419 OPT_STRING('t', "tid", &trace.opts.target.tid, "tid",
3420 "trace events on existing thread id"),
3421 OPT_CALLBACK(0, "filter-pids", &trace, "CSV list of pids",
3422 "pids to filter (by the kernel)", trace__set_filter_pids_from_option),
3423 OPT_BOOLEAN('a', "all-cpus", &trace.opts.target.system_wide,
3424 "system-wide collection from all CPUs"),
3425 OPT_STRING('C', "cpu", &trace.opts.target.cpu_list, "cpu",
3426 "list of cpus to monitor"),
3427 OPT_BOOLEAN(0, "no-inherit", &trace.opts.no_inherit,
3428 "child tasks do not inherit counters"),
3429 OPT_CALLBACK('m', "mmap-pages", &trace.opts.mmap_pages, "pages",
3430 "number of mmap data pages",
3431 perf_evlist__parse_mmap_pages),
3432 OPT_STRING('u', "uid", &trace.opts.target.uid_str, "user",
3433 "user to profile"),
3434 OPT_CALLBACK(0, "duration", &trace, "float",
3435 "show only events with duration > N.M ms",
3436 trace__set_duration),
3437 OPT_BOOLEAN(0, "sched", &trace.sched, "show blocking scheduler events"),
3438 OPT_INCR('v', "verbose", &verbose, "be more verbose"),
3439 OPT_BOOLEAN('T', "time", &trace.full_time,
3440 "Show full timestamp, not time relative to first start"),
3441 OPT_BOOLEAN(0, "failure", &trace.failure_only,
3442 "Show only syscalls that failed"),
3443 OPT_BOOLEAN('s', "summary", &trace.summary_only,
3444 "Show only syscall summary with statistics"),
3445 OPT_BOOLEAN('S', "with-summary", &trace.summary,
3446 "Show all syscalls and summary with statistics"),
3447 OPT_CALLBACK_DEFAULT('F', "pf", &trace.trace_pgfaults, "all|maj|min",
3448 "Trace pagefaults", parse_pagefaults, "maj"),
3449 OPT_BOOLEAN(0, "syscalls", &trace.trace_syscalls, "Trace syscalls"),
3450 OPT_BOOLEAN('f', "force", &trace.force, "don't complain, do it"),
3451 OPT_CALLBACK(0, "call-graph", &trace.opts,
3452 "record_mode[,record_size]", record_callchain_help,
3453 &record_parse_callchain_opt),
3454 OPT_BOOLEAN(0, "kernel-syscall-graph", &trace.kernel_syscallchains,
3455 "Show the kernel callchains on the syscall exit path"),
3456 OPT_ULONG(0, "max-events", &trace.max_events,
3457 "Set the maximum number of events to print, exit after that is reached. "),
3458 OPT_UINTEGER(0, "min-stack", &trace.min_stack,
3459 "Set the minimum stack depth when parsing the callchain, "
3460 "anything below the specified depth will be ignored."),
3461 OPT_UINTEGER(0, "max-stack", &trace.max_stack,
3462 "Set the maximum stack depth when parsing the callchain, "
3463 "anything beyond the specified depth will be ignored. "
3464 "Default: kernel.perf_event_max_stack or " __stringify(PERF_MAX_STACK_DEPTH)),
3465 OPT_BOOLEAN(0, "print-sample", &trace.print_sample,
3466 "print the PERF_RECORD_SAMPLE PERF_SAMPLE_ info, for debugging"),
3467 OPT_UINTEGER(0, "proc-map-timeout", &trace.opts.proc_map_timeout,
3468 "per thread proc mmap processing timeout in ms"),
3469 OPT_CALLBACK('G', "cgroup", &trace, "name", "monitor event in cgroup name only",
3470 trace__parse_cgroups),
3471 OPT_UINTEGER('D', "delay", &trace.opts.initial_delay,
3472 "ms to wait before starting measurement after program "
3473 "start"),
3474 OPT_END()
3476 bool __maybe_unused max_stack_user_set = true;
3477 bool mmap_pages_user_set = true;
3478 struct perf_evsel *evsel;
3479 const char * const trace_subcommands[] = { "record", NULL };
3480 int err = -1;
3481 char bf[BUFSIZ];
3483 signal(SIGSEGV, sighandler_dump_stack);
3484 signal(SIGFPE, sighandler_dump_stack);
3486 trace.evlist = perf_evlist__new();
3487 trace.sctbl = syscalltbl__new();
3489 if (trace.evlist == NULL || trace.sctbl == NULL) {
3490 pr_err("Not enough memory to run!\n");
3491 err = -ENOMEM;
3492 goto out;
3495 argc = parse_options_subcommand(argc, argv, trace_options, trace_subcommands,
3496 trace_usage, PARSE_OPT_STOP_AT_NON_OPTION);
3498 if ((nr_cgroups || trace.cgroup) && !trace.opts.target.system_wide) {
3499 usage_with_options_msg(trace_usage, trace_options,
3500 "cgroup monitoring only available in system-wide mode");
3503 evsel = bpf__setup_output_event(trace.evlist, "__augmented_syscalls__");
3504 if (IS_ERR(evsel)) {
3505 bpf__strerror_setup_output_event(trace.evlist, PTR_ERR(evsel), bf, sizeof(bf));
3506 pr_err("ERROR: Setup trace syscalls enter failed: %s\n", bf);
3507 goto out;
3510 if (evsel) {
3511 trace.syscalls.events.augmented = evsel;
3512 trace__set_bpf_map_filtered_pids(&trace);
3515 err = bpf__setup_stdout(trace.evlist);
3516 if (err) {
3517 bpf__strerror_setup_stdout(trace.evlist, err, bf, sizeof(bf));
3518 pr_err("ERROR: Setup BPF stdout failed: %s\n", bf);
3519 goto out;
3522 err = -1;
3524 if (trace.trace_pgfaults) {
3525 trace.opts.sample_address = true;
3526 trace.opts.sample_time = true;
3529 if (trace.opts.mmap_pages == UINT_MAX)
3530 mmap_pages_user_set = false;
3532 if (trace.max_stack == UINT_MAX) {
3533 trace.max_stack = input_name ? PERF_MAX_STACK_DEPTH : sysctl__max_stack();
3534 max_stack_user_set = false;
3537 #ifdef HAVE_DWARF_UNWIND_SUPPORT
3538 if ((trace.min_stack || max_stack_user_set) && !callchain_param.enabled) {
3539 record_opts__parse_callchain(&trace.opts, &callchain_param, "dwarf", false);
3541 #endif
3543 if (callchain_param.enabled) {
3544 if (!mmap_pages_user_set && geteuid() == 0)
3545 trace.opts.mmap_pages = perf_event_mlock_kb_in_pages() * 4;
3547 symbol_conf.use_callchain = true;
3550 if (trace.evlist->nr_entries > 0) {
3551 evlist__set_evsel_handler(trace.evlist, trace__event_handler);
3552 if (evlist__set_syscall_tp_fields(trace.evlist)) {
3553 perror("failed to set syscalls:* tracepoint fields");
3554 goto out;
3559 * If we are augmenting syscalls, then combine what we put in the
3560 * __augmented_syscalls__ BPF map with what is in the
3561 * syscalls:sys_exit_FOO tracepoints, i.e. just like we do without BPF,
3562 * combining raw_syscalls:sys_enter with raw_syscalls:sys_exit.
3564 * We'll switch to look at two BPF maps, one for sys_enter and the
3565 * other for sys_exit when we start augmenting the sys_exit paths with
3566 * buffers that are being copied from kernel to userspace, think 'read'
3567 * syscall.
3569 if (trace.syscalls.events.augmented) {
3570 evsel = trace.syscalls.events.augmented;
3572 if (perf_evsel__init_augmented_syscall_tp(evsel) ||
3573 perf_evsel__init_augmented_syscall_tp_args(evsel))
3574 goto out;
3575 evsel->handler = trace__sys_enter;
3577 evlist__for_each_entry(trace.evlist, evsel) {
3578 bool raw_syscalls_sys_exit = strcmp(perf_evsel__name(evsel), "raw_syscalls:sys_exit") == 0;
3580 if (raw_syscalls_sys_exit) {
3581 trace.raw_augmented_syscalls = true;
3582 goto init_augmented_syscall_tp;
3585 if (strstarts(perf_evsel__name(evsel), "syscalls:sys_exit_")) {
3586 init_augmented_syscall_tp:
3587 perf_evsel__init_augmented_syscall_tp(evsel);
3588 perf_evsel__init_augmented_syscall_tp_ret(evsel);
3589 evsel->handler = trace__sys_exit;
3594 if ((argc >= 1) && (strcmp(argv[0], "record") == 0))
3595 return trace__record(&trace, argc-1, &argv[1]);
3597 /* summary_only implies summary option, but don't overwrite summary if set */
3598 if (trace.summary_only)
3599 trace.summary = trace.summary_only;
3601 if (!trace.trace_syscalls && !trace.trace_pgfaults &&
3602 trace.evlist->nr_entries == 0 /* Was --events used? */) {
3603 trace.trace_syscalls = true;
3606 if (output_name != NULL) {
3607 err = trace__open_output(&trace, output_name);
3608 if (err < 0) {
3609 perror("failed to create output file");
3610 goto out;
3614 err = target__validate(&trace.opts.target);
3615 if (err) {
3616 target__strerror(&trace.opts.target, err, bf, sizeof(bf));
3617 fprintf(trace.output, "%s", bf);
3618 goto out_close;
3621 err = target__parse_uid(&trace.opts.target);
3622 if (err) {
3623 target__strerror(&trace.opts.target, err, bf, sizeof(bf));
3624 fprintf(trace.output, "%s", bf);
3625 goto out_close;
3628 if (!argc && target__none(&trace.opts.target))
3629 trace.opts.target.system_wide = true;
3631 if (input_name)
3632 err = trace__replay(&trace);
3633 else
3634 err = trace__run(&trace, argc, argv);
3636 out_close:
3637 if (output_name != NULL)
3638 fclose(trace.output);
3639 out:
3640 return err;