Merge tag 'for-4.20-part2-tag' of git://git.kernel.org/pub/scm/linux/kernel/git/kdave...
[linux-2.6-block.git] / tools / perf / builtin-trace.c
1 /*
2  * builtin-trace.c
3  *
4  * Builtin 'trace' command:
5  *
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.
9  *
10  * Copyright (C) 2012, 2013, 2014, 2015 Red Hat Inc, Arnaldo Carvalho de Melo <acme@redhat.com>
11  *
12  * Initially based on the 'trace' prototype by Thomas Gleixner:
13  *
14  * http://lwn.net/Articles/415728/ ("Announcing a new utility: 'trace'")
15  *
16  * Released under the GPL v2. (and only v2, not any later version)
17  */
18
19 #include <traceevent/event-parse.h>
20 #include <api/fs/tracing_path.h>
21 #include "builtin.h"
22 #include "util/cgroup.h"
23 #include "util/color.h"
24 #include "util/debug.h"
25 #include "util/env.h"
26 #include "util/event.h"
27 #include "util/evlist.h"
28 #include <subcmd/exec-cmd.h>
29 #include "util/machine.h"
30 #include "util/path.h"
31 #include "util/session.h"
32 #include "util/thread.h"
33 #include <subcmd/parse-options.h>
34 #include "util/strlist.h"
35 #include "util/intlist.h"
36 #include "util/thread_map.h"
37 #include "util/stat.h"
38 #include "trace/beauty/beauty.h"
39 #include "trace-event.h"
40 #include "util/parse-events.h"
41 #include "util/bpf-loader.h"
42 #include "callchain.h"
43 #include "print_binary.h"
44 #include "string2.h"
45 #include "syscalltbl.h"
46 #include "rb_resort.h"
47
48 #include <errno.h>
49 #include <inttypes.h>
50 #include <poll.h>
51 #include <signal.h>
52 #include <stdlib.h>
53 #include <string.h>
54 #include <linux/err.h>
55 #include <linux/filter.h>
56 #include <linux/kernel.h>
57 #include <linux/random.h>
58 #include <linux/stringify.h>
59 #include <linux/time64.h>
60 #include <fcntl.h>
61
62 #include "sane_ctype.h"
63
64 #ifndef O_CLOEXEC
65 # define O_CLOEXEC              02000000
66 #endif
67
68 #ifndef F_LINUX_SPECIFIC_BASE
69 # define F_LINUX_SPECIFIC_BASE  1024
70 #endif
71
72 struct trace {
73         struct perf_tool        tool;
74         struct syscalltbl       *sctbl;
75         struct {
76                 int             max;
77                 struct syscall  *table;
78                 struct {
79                         struct perf_evsel *sys_enter,
80                                           *sys_exit,
81                                           *augmented;
82                 }               events;
83         } syscalls;
84         struct record_opts      opts;
85         struct perf_evlist      *evlist;
86         struct machine          *host;
87         struct thread           *current;
88         struct cgroup           *cgroup;
89         u64                     base_time;
90         FILE                    *output;
91         unsigned long           nr_events;
92         struct strlist          *ev_qualifier;
93         struct {
94                 size_t          nr;
95                 int             *entries;
96         }                       ev_qualifier_ids;
97         struct {
98                 size_t          nr;
99                 pid_t           *entries;
100         }                       filter_pids;
101         double                  duration_filter;
102         double                  runtime_ms;
103         struct {
104                 u64             vfs_getname,
105                                 proc_getname;
106         } stats;
107         unsigned int            max_stack;
108         unsigned int            min_stack;
109         bool                    not_ev_qualifier;
110         bool                    live;
111         bool                    full_time;
112         bool                    sched;
113         bool                    multiple_threads;
114         bool                    summary;
115         bool                    summary_only;
116         bool                    failure_only;
117         bool                    show_comm;
118         bool                    print_sample;
119         bool                    show_tool_stats;
120         bool                    trace_syscalls;
121         bool                    kernel_syscallchains;
122         bool                    force;
123         bool                    vfs_getname;
124         int                     trace_pgfaults;
125 };
126
127 struct tp_field {
128         int offset;
129         union {
130                 u64 (*integer)(struct tp_field *field, struct perf_sample *sample);
131                 void *(*pointer)(struct tp_field *field, struct perf_sample *sample);
132         };
133 };
134
135 #define TP_UINT_FIELD(bits) \
136 static u64 tp_field__u##bits(struct tp_field *field, struct perf_sample *sample) \
137 { \
138         u##bits value; \
139         memcpy(&value, sample->raw_data + field->offset, sizeof(value)); \
140         return value;  \
141 }
142
143 TP_UINT_FIELD(8);
144 TP_UINT_FIELD(16);
145 TP_UINT_FIELD(32);
146 TP_UINT_FIELD(64);
147
148 #define TP_UINT_FIELD__SWAPPED(bits) \
149 static u64 tp_field__swapped_u##bits(struct tp_field *field, struct perf_sample *sample) \
150 { \
151         u##bits value; \
152         memcpy(&value, sample->raw_data + field->offset, sizeof(value)); \
153         return bswap_##bits(value);\
154 }
155
156 TP_UINT_FIELD__SWAPPED(16);
157 TP_UINT_FIELD__SWAPPED(32);
158 TP_UINT_FIELD__SWAPPED(64);
159
160 static int __tp_field__init_uint(struct tp_field *field, int size, int offset, bool needs_swap)
161 {
162         field->offset = offset;
163
164         switch (size) {
165         case 1:
166                 field->integer = tp_field__u8;
167                 break;
168         case 2:
169                 field->integer = needs_swap ? tp_field__swapped_u16 : tp_field__u16;
170                 break;
171         case 4:
172                 field->integer = needs_swap ? tp_field__swapped_u32 : tp_field__u32;
173                 break;
174         case 8:
175                 field->integer = needs_swap ? tp_field__swapped_u64 : tp_field__u64;
176                 break;
177         default:
178                 return -1;
179         }
180
181         return 0;
182 }
183
184 static int tp_field__init_uint(struct tp_field *field, struct tep_format_field *format_field, bool needs_swap)
185 {
186         return __tp_field__init_uint(field, format_field->size, format_field->offset, needs_swap);
187 }
188
189 static void *tp_field__ptr(struct tp_field *field, struct perf_sample *sample)
190 {
191         return sample->raw_data + field->offset;
192 }
193
194 static int __tp_field__init_ptr(struct tp_field *field, int offset)
195 {
196         field->offset = offset;
197         field->pointer = tp_field__ptr;
198         return 0;
199 }
200
201 static int tp_field__init_ptr(struct tp_field *field, struct tep_format_field *format_field)
202 {
203         return __tp_field__init_ptr(field, format_field->offset);
204 }
205
206 struct syscall_tp {
207         struct tp_field id;
208         union {
209                 struct tp_field args, ret;
210         };
211 };
212
213 static int perf_evsel__init_tp_uint_field(struct perf_evsel *evsel,
214                                           struct tp_field *field,
215                                           const char *name)
216 {
217         struct tep_format_field *format_field = perf_evsel__field(evsel, name);
218
219         if (format_field == NULL)
220                 return -1;
221
222         return tp_field__init_uint(field, format_field, evsel->needs_swap);
223 }
224
225 #define perf_evsel__init_sc_tp_uint_field(evsel, name) \
226         ({ struct syscall_tp *sc = evsel->priv;\
227            perf_evsel__init_tp_uint_field(evsel, &sc->name, #name); })
228
229 static int perf_evsel__init_tp_ptr_field(struct perf_evsel *evsel,
230                                          struct tp_field *field,
231                                          const char *name)
232 {
233         struct tep_format_field *format_field = perf_evsel__field(evsel, name);
234
235         if (format_field == NULL)
236                 return -1;
237
238         return tp_field__init_ptr(field, format_field);
239 }
240
241 #define perf_evsel__init_sc_tp_ptr_field(evsel, name) \
242         ({ struct syscall_tp *sc = evsel->priv;\
243            perf_evsel__init_tp_ptr_field(evsel, &sc->name, #name); })
244
245 static void perf_evsel__delete_priv(struct perf_evsel *evsel)
246 {
247         zfree(&evsel->priv);
248         perf_evsel__delete(evsel);
249 }
250
251 static int perf_evsel__init_syscall_tp(struct perf_evsel *evsel)
252 {
253         struct syscall_tp *sc = evsel->priv = malloc(sizeof(struct syscall_tp));
254
255         if (evsel->priv != NULL) {
256                 if (perf_evsel__init_tp_uint_field(evsel, &sc->id, "__syscall_nr"))
257                         goto out_delete;
258                 return 0;
259         }
260
261         return -ENOMEM;
262 out_delete:
263         zfree(&evsel->priv);
264         return -ENOENT;
265 }
266
267 static int perf_evsel__init_augmented_syscall_tp(struct perf_evsel *evsel)
268 {
269         struct syscall_tp *sc = evsel->priv = malloc(sizeof(struct syscall_tp));
270
271         if (evsel->priv != NULL) {       /* field, sizeof_field, offsetof_field */
272                 if (__tp_field__init_uint(&sc->id, sizeof(long), sizeof(long long), evsel->needs_swap))
273                         goto out_delete;
274
275                 return 0;
276         }
277
278         return -ENOMEM;
279 out_delete:
280         zfree(&evsel->priv);
281         return -EINVAL;
282 }
283
284 static int perf_evsel__init_augmented_syscall_tp_args(struct perf_evsel *evsel)
285 {
286         struct syscall_tp *sc = evsel->priv;
287
288         return __tp_field__init_ptr(&sc->args, sc->id.offset + sizeof(u64));
289 }
290
291 static int perf_evsel__init_augmented_syscall_tp_ret(struct perf_evsel *evsel)
292 {
293         struct syscall_tp *sc = evsel->priv;
294
295         return __tp_field__init_uint(&sc->ret, sizeof(u64), sc->id.offset + sizeof(u64), evsel->needs_swap);
296 }
297
298 static int perf_evsel__init_raw_syscall_tp(struct perf_evsel *evsel, void *handler)
299 {
300         evsel->priv = malloc(sizeof(struct syscall_tp));
301         if (evsel->priv != NULL) {
302                 if (perf_evsel__init_sc_tp_uint_field(evsel, id))
303                         goto out_delete;
304
305                 evsel->handler = handler;
306                 return 0;
307         }
308
309         return -ENOMEM;
310
311 out_delete:
312         zfree(&evsel->priv);
313         return -ENOENT;
314 }
315
316 static struct perf_evsel *perf_evsel__raw_syscall_newtp(const char *direction, void *handler)
317 {
318         struct perf_evsel *evsel = perf_evsel__newtp("raw_syscalls", direction);
319
320         /* older kernel (e.g., RHEL6) use syscalls:{enter,exit} */
321         if (IS_ERR(evsel))
322                 evsel = perf_evsel__newtp("syscalls", direction);
323
324         if (IS_ERR(evsel))
325                 return NULL;
326
327         if (perf_evsel__init_raw_syscall_tp(evsel, handler))
328                 goto out_delete;
329
330         return evsel;
331
332 out_delete:
333         perf_evsel__delete_priv(evsel);
334         return NULL;
335 }
336
337 #define perf_evsel__sc_tp_uint(evsel, name, sample) \
338         ({ struct syscall_tp *fields = evsel->priv; \
339            fields->name.integer(&fields->name, sample); })
340
341 #define perf_evsel__sc_tp_ptr(evsel, name, sample) \
342         ({ struct syscall_tp *fields = evsel->priv; \
343            fields->name.pointer(&fields->name, sample); })
344
345 size_t strarray__scnprintf(struct strarray *sa, char *bf, size_t size, const char *intfmt, int val)
346 {
347         int idx = val - sa->offset;
348
349         if (idx < 0 || idx >= sa->nr_entries || sa->entries[idx] == NULL)
350                 return scnprintf(bf, size, intfmt, val);
351
352         return scnprintf(bf, size, "%s", sa->entries[idx]);
353 }
354
355 static size_t __syscall_arg__scnprintf_strarray(char *bf, size_t size,
356                                                 const char *intfmt,
357                                                 struct syscall_arg *arg)
358 {
359         return strarray__scnprintf(arg->parm, bf, size, intfmt, arg->val);
360 }
361
362 static size_t syscall_arg__scnprintf_strarray(char *bf, size_t size,
363                                               struct syscall_arg *arg)
364 {
365         return __syscall_arg__scnprintf_strarray(bf, size, "%d", arg);
366 }
367
368 #define SCA_STRARRAY syscall_arg__scnprintf_strarray
369
370 struct strarrays {
371         int             nr_entries;
372         struct strarray **entries;
373 };
374
375 #define DEFINE_STRARRAYS(array) struct strarrays strarrays__##array = { \
376         .nr_entries = ARRAY_SIZE(array), \
377         .entries = array, \
378 }
379
380 size_t syscall_arg__scnprintf_strarrays(char *bf, size_t size,
381                                         struct syscall_arg *arg)
382 {
383         struct strarrays *sas = arg->parm;
384         int i;
385
386         for (i = 0; i < sas->nr_entries; ++i) {
387                 struct strarray *sa = sas->entries[i];
388                 int idx = arg->val - sa->offset;
389
390                 if (idx >= 0 && idx < sa->nr_entries) {
391                         if (sa->entries[idx] == NULL)
392                                 break;
393                         return scnprintf(bf, size, "%s", sa->entries[idx]);
394                 }
395         }
396
397         return scnprintf(bf, size, "%d", arg->val);
398 }
399
400 #ifndef AT_FDCWD
401 #define AT_FDCWD        -100
402 #endif
403
404 static size_t syscall_arg__scnprintf_fd_at(char *bf, size_t size,
405                                            struct syscall_arg *arg)
406 {
407         int fd = arg->val;
408
409         if (fd == AT_FDCWD)
410                 return scnprintf(bf, size, "CWD");
411
412         return syscall_arg__scnprintf_fd(bf, size, arg);
413 }
414
415 #define SCA_FDAT syscall_arg__scnprintf_fd_at
416
417 static size_t syscall_arg__scnprintf_close_fd(char *bf, size_t size,
418                                               struct syscall_arg *arg);
419
420 #define SCA_CLOSE_FD syscall_arg__scnprintf_close_fd
421
422 size_t syscall_arg__scnprintf_hex(char *bf, size_t size, struct syscall_arg *arg)
423 {
424         return scnprintf(bf, size, "%#lx", arg->val);
425 }
426
427 size_t syscall_arg__scnprintf_int(char *bf, size_t size, struct syscall_arg *arg)
428 {
429         return scnprintf(bf, size, "%d", arg->val);
430 }
431
432 size_t syscall_arg__scnprintf_long(char *bf, size_t size, struct syscall_arg *arg)
433 {
434         return scnprintf(bf, size, "%ld", arg->val);
435 }
436
437 static const char *bpf_cmd[] = {
438         "MAP_CREATE", "MAP_LOOKUP_ELEM", "MAP_UPDATE_ELEM", "MAP_DELETE_ELEM",
439         "MAP_GET_NEXT_KEY", "PROG_LOAD",
440 };
441 static DEFINE_STRARRAY(bpf_cmd);
442
443 static const char *epoll_ctl_ops[] = { "ADD", "DEL", "MOD", };
444 static DEFINE_STRARRAY_OFFSET(epoll_ctl_ops, 1);
445
446 static const char *itimers[] = { "REAL", "VIRTUAL", "PROF", };
447 static DEFINE_STRARRAY(itimers);
448
449 static const char *keyctl_options[] = {
450         "GET_KEYRING_ID", "JOIN_SESSION_KEYRING", "UPDATE", "REVOKE", "CHOWN",
451         "SETPERM", "DESCRIBE", "CLEAR", "LINK", "UNLINK", "SEARCH", "READ",
452         "INSTANTIATE", "NEGATE", "SET_REQKEY_KEYRING", "SET_TIMEOUT",
453         "ASSUME_AUTHORITY", "GET_SECURITY", "SESSION_TO_PARENT", "REJECT",
454         "INSTANTIATE_IOV", "INVALIDATE", "GET_PERSISTENT",
455 };
456 static DEFINE_STRARRAY(keyctl_options);
457
458 static const char *whences[] = { "SET", "CUR", "END",
459 #ifdef SEEK_DATA
460 "DATA",
461 #endif
462 #ifdef SEEK_HOLE
463 "HOLE",
464 #endif
465 };
466 static DEFINE_STRARRAY(whences);
467
468 static const char *fcntl_cmds[] = {
469         "DUPFD", "GETFD", "SETFD", "GETFL", "SETFL", "GETLK", "SETLK",
470         "SETLKW", "SETOWN", "GETOWN", "SETSIG", "GETSIG", "GETLK64",
471         "SETLK64", "SETLKW64", "SETOWN_EX", "GETOWN_EX",
472         "GETOWNER_UIDS",
473 };
474 static DEFINE_STRARRAY(fcntl_cmds);
475
476 static const char *fcntl_linux_specific_cmds[] = {
477         "SETLEASE", "GETLEASE", "NOTIFY", [5] = "CANCELLK", "DUPFD_CLOEXEC",
478         "SETPIPE_SZ", "GETPIPE_SZ", "ADD_SEALS", "GET_SEALS",
479         "GET_RW_HINT", "SET_RW_HINT", "GET_FILE_RW_HINT", "SET_FILE_RW_HINT",
480 };
481
482 static DEFINE_STRARRAY_OFFSET(fcntl_linux_specific_cmds, F_LINUX_SPECIFIC_BASE);
483
484 static struct strarray *fcntl_cmds_arrays[] = {
485         &strarray__fcntl_cmds,
486         &strarray__fcntl_linux_specific_cmds,
487 };
488
489 static DEFINE_STRARRAYS(fcntl_cmds_arrays);
490
491 static const char *rlimit_resources[] = {
492         "CPU", "FSIZE", "DATA", "STACK", "CORE", "RSS", "NPROC", "NOFILE",
493         "MEMLOCK", "AS", "LOCKS", "SIGPENDING", "MSGQUEUE", "NICE", "RTPRIO",
494         "RTTIME",
495 };
496 static DEFINE_STRARRAY(rlimit_resources);
497
498 static const char *sighow[] = { "BLOCK", "UNBLOCK", "SETMASK", };
499 static DEFINE_STRARRAY(sighow);
500
501 static const char *clockid[] = {
502         "REALTIME", "MONOTONIC", "PROCESS_CPUTIME_ID", "THREAD_CPUTIME_ID",
503         "MONOTONIC_RAW", "REALTIME_COARSE", "MONOTONIC_COARSE", "BOOTTIME",
504         "REALTIME_ALARM", "BOOTTIME_ALARM", "SGI_CYCLE", "TAI"
505 };
506 static DEFINE_STRARRAY(clockid);
507
508 static size_t syscall_arg__scnprintf_access_mode(char *bf, size_t size,
509                                                  struct syscall_arg *arg)
510 {
511         size_t printed = 0;
512         int mode = arg->val;
513
514         if (mode == F_OK) /* 0 */
515                 return scnprintf(bf, size, "F");
516 #define P_MODE(n) \
517         if (mode & n##_OK) { \
518                 printed += scnprintf(bf + printed, size - printed, "%s", #n); \
519                 mode &= ~n##_OK; \
520         }
521
522         P_MODE(R);
523         P_MODE(W);
524         P_MODE(X);
525 #undef P_MODE
526
527         if (mode)
528                 printed += scnprintf(bf + printed, size - printed, "|%#x", mode);
529
530         return printed;
531 }
532
533 #define SCA_ACCMODE syscall_arg__scnprintf_access_mode
534
535 static size_t syscall_arg__scnprintf_filename(char *bf, size_t size,
536                                               struct syscall_arg *arg);
537
538 #define SCA_FILENAME syscall_arg__scnprintf_filename
539
540 static size_t syscall_arg__scnprintf_pipe_flags(char *bf, size_t size,
541                                                 struct syscall_arg *arg)
542 {
543         int printed = 0, flags = arg->val;
544
545 #define P_FLAG(n) \
546         if (flags & O_##n) { \
547                 printed += scnprintf(bf + printed, size - printed, "%s%s", printed ? "|" : "", #n); \
548                 flags &= ~O_##n; \
549         }
550
551         P_FLAG(CLOEXEC);
552         P_FLAG(NONBLOCK);
553 #undef P_FLAG
554
555         if (flags)
556                 printed += scnprintf(bf + printed, size - printed, "%s%#x", printed ? "|" : "", flags);
557
558         return printed;
559 }
560
561 #define SCA_PIPE_FLAGS syscall_arg__scnprintf_pipe_flags
562
563 #ifndef GRND_NONBLOCK
564 #define GRND_NONBLOCK   0x0001
565 #endif
566 #ifndef GRND_RANDOM
567 #define GRND_RANDOM     0x0002
568 #endif
569
570 static size_t syscall_arg__scnprintf_getrandom_flags(char *bf, size_t size,
571                                                    struct syscall_arg *arg)
572 {
573         int printed = 0, flags = arg->val;
574
575 #define P_FLAG(n) \
576         if (flags & GRND_##n) { \
577                 printed += scnprintf(bf + printed, size - printed, "%s%s", printed ? "|" : "", #n); \
578                 flags &= ~GRND_##n; \
579         }
580
581         P_FLAG(RANDOM);
582         P_FLAG(NONBLOCK);
583 #undef P_FLAG
584
585         if (flags)
586                 printed += scnprintf(bf + printed, size - printed, "%s%#x", printed ? "|" : "", flags);
587
588         return printed;
589 }
590
591 #define SCA_GETRANDOM_FLAGS syscall_arg__scnprintf_getrandom_flags
592
593 #define STRARRAY(name, array) \
594           { .scnprintf  = SCA_STRARRAY, \
595             .parm       = &strarray__##array, }
596
597 #include "trace/beauty/arch_errno_names.c"
598 #include "trace/beauty/eventfd.c"
599 #include "trace/beauty/futex_op.c"
600 #include "trace/beauty/futex_val3.c"
601 #include "trace/beauty/mmap.c"
602 #include "trace/beauty/mode_t.c"
603 #include "trace/beauty/msg_flags.c"
604 #include "trace/beauty/open_flags.c"
605 #include "trace/beauty/perf_event_open.c"
606 #include "trace/beauty/pid.c"
607 #include "trace/beauty/sched_policy.c"
608 #include "trace/beauty/seccomp.c"
609 #include "trace/beauty/signum.c"
610 #include "trace/beauty/socket_type.c"
611 #include "trace/beauty/waitid_options.c"
612
613 struct syscall_arg_fmt {
614         size_t     (*scnprintf)(char *bf, size_t size, struct syscall_arg *arg);
615         void       *parm;
616         const char *name;
617         bool       show_zero;
618 };
619
620 static struct syscall_fmt {
621         const char *name;
622         const char *alias;
623         struct syscall_arg_fmt arg[6];
624         u8         nr_args;
625         bool       errpid;
626         bool       timeout;
627         bool       hexret;
628 } syscall_fmts[] = {
629         { .name     = "access",
630           .arg = { [1] = { .scnprintf = SCA_ACCMODE,  /* mode */ }, }, },
631         { .name     = "bind",
632           .arg = { [1] = { .scnprintf = SCA_SOCKADDR, /* umyaddr */ }, }, },
633         { .name     = "bpf",
634           .arg = { [0] = STRARRAY(cmd, bpf_cmd), }, },
635         { .name     = "brk",        .hexret = true,
636           .arg = { [0] = { .scnprintf = SCA_HEX, /* brk */ }, }, },
637         { .name     = "clock_gettime",
638           .arg = { [0] = STRARRAY(clk_id, clockid), }, },
639         { .name     = "clone",      .errpid = true, .nr_args = 5,
640           .arg = { [0] = { .name = "flags",         .scnprintf = SCA_CLONE_FLAGS, },
641                    [1] = { .name = "child_stack",   .scnprintf = SCA_HEX, },
642                    [2] = { .name = "parent_tidptr", .scnprintf = SCA_HEX, },
643                    [3] = { .name = "child_tidptr",  .scnprintf = SCA_HEX, },
644                    [4] = { .name = "tls",           .scnprintf = SCA_HEX, }, }, },
645         { .name     = "close",
646           .arg = { [0] = { .scnprintf = SCA_CLOSE_FD, /* fd */ }, }, },
647         { .name     = "connect",
648           .arg = { [1] = { .scnprintf = SCA_SOCKADDR, /* servaddr */ }, }, },
649         { .name     = "epoll_ctl",
650           .arg = { [1] = STRARRAY(op, epoll_ctl_ops), }, },
651         { .name     = "eventfd2",
652           .arg = { [1] = { .scnprintf = SCA_EFD_FLAGS, /* flags */ }, }, },
653         { .name     = "fchmodat",
654           .arg = { [0] = { .scnprintf = SCA_FDAT, /* fd */ }, }, },
655         { .name     = "fchownat",
656           .arg = { [0] = { .scnprintf = SCA_FDAT, /* fd */ }, }, },
657         { .name     = "fcntl",
658           .arg = { [1] = { .scnprintf = SCA_FCNTL_CMD, /* cmd */
659                            .parm      = &strarrays__fcntl_cmds_arrays,
660                            .show_zero = true, },
661                    [2] = { .scnprintf =  SCA_FCNTL_ARG, /* arg */ }, }, },
662         { .name     = "flock",
663           .arg = { [1] = { .scnprintf = SCA_FLOCK, /* cmd */ }, }, },
664         { .name     = "fstat", .alias = "newfstat", },
665         { .name     = "fstatat", .alias = "newfstatat", },
666         { .name     = "futex",
667           .arg = { [1] = { .scnprintf = SCA_FUTEX_OP, /* op */ },
668                    [5] = { .scnprintf = SCA_FUTEX_VAL3, /* val3 */ }, }, },
669         { .name     = "futimesat",
670           .arg = { [0] = { .scnprintf = SCA_FDAT, /* fd */ }, }, },
671         { .name     = "getitimer",
672           .arg = { [0] = STRARRAY(which, itimers), }, },
673         { .name     = "getpid",     .errpid = true, },
674         { .name     = "getpgid",    .errpid = true, },
675         { .name     = "getppid",    .errpid = true, },
676         { .name     = "getrandom",
677           .arg = { [2] = { .scnprintf = SCA_GETRANDOM_FLAGS, /* flags */ }, }, },
678         { .name     = "getrlimit",
679           .arg = { [0] = STRARRAY(resource, rlimit_resources), }, },
680         { .name     = "gettid",     .errpid = true, },
681         { .name     = "ioctl",
682           .arg = {
683 #if defined(__i386__) || defined(__x86_64__)
684 /*
685  * FIXME: Make this available to all arches.
686  */
687                    [1] = { .scnprintf = SCA_IOCTL_CMD, /* cmd */ },
688                    [2] = { .scnprintf = SCA_HEX, /* arg */ }, }, },
689 #else
690                    [2] = { .scnprintf = SCA_HEX, /* arg */ }, }, },
691 #endif
692         { .name     = "kcmp",       .nr_args = 5,
693           .arg = { [0] = { .name = "pid1",      .scnprintf = SCA_PID, },
694                    [1] = { .name = "pid2",      .scnprintf = SCA_PID, },
695                    [2] = { .name = "type",      .scnprintf = SCA_KCMP_TYPE, },
696                    [3] = { .name = "idx1",      .scnprintf = SCA_KCMP_IDX, },
697                    [4] = { .name = "idx2",      .scnprintf = SCA_KCMP_IDX, }, }, },
698         { .name     = "keyctl",
699           .arg = { [0] = STRARRAY(option, keyctl_options), }, },
700         { .name     = "kill",
701           .arg = { [1] = { .scnprintf = SCA_SIGNUM, /* sig */ }, }, },
702         { .name     = "linkat",
703           .arg = { [0] = { .scnprintf = SCA_FDAT, /* fd */ }, }, },
704         { .name     = "lseek",
705           .arg = { [2] = STRARRAY(whence, whences), }, },
706         { .name     = "lstat", .alias = "newlstat", },
707         { .name     = "madvise",
708           .arg = { [0] = { .scnprintf = SCA_HEX,      /* start */ },
709                    [2] = { .scnprintf = SCA_MADV_BHV, /* behavior */ }, }, },
710         { .name     = "mkdirat",
711           .arg = { [0] = { .scnprintf = SCA_FDAT, /* fd */ }, }, },
712         { .name     = "mknodat",
713           .arg = { [0] = { .scnprintf = SCA_FDAT, /* fd */ }, }, },
714         { .name     = "mlock",
715           .arg = { [0] = { .scnprintf = SCA_HEX, /* addr */ }, }, },
716         { .name     = "mlockall",
717           .arg = { [0] = { .scnprintf = SCA_HEX, /* addr */ }, }, },
718         { .name     = "mmap",       .hexret = true,
719 /* The standard mmap maps to old_mmap on s390x */
720 #if defined(__s390x__)
721         .alias = "old_mmap",
722 #endif
723           .arg = { [0] = { .scnprintf = SCA_HEX,        /* addr */ },
724                    [2] = { .scnprintf = SCA_MMAP_PROT,  /* prot */ },
725                    [3] = { .scnprintf = SCA_MMAP_FLAGS, /* flags */ }, }, },
726         { .name     = "mprotect",
727           .arg = { [0] = { .scnprintf = SCA_HEX,        /* start */ },
728                    [2] = { .scnprintf = SCA_MMAP_PROT,  /* prot */ }, }, },
729         { .name     = "mq_unlink",
730           .arg = { [0] = { .scnprintf = SCA_FILENAME, /* u_name */ }, }, },
731         { .name     = "mremap",     .hexret = true,
732           .arg = { [0] = { .scnprintf = SCA_HEX,          /* addr */ },
733                    [3] = { .scnprintf = SCA_MREMAP_FLAGS, /* flags */ },
734                    [4] = { .scnprintf = SCA_HEX,          /* new_addr */ }, }, },
735         { .name     = "munlock",
736           .arg = { [0] = { .scnprintf = SCA_HEX, /* addr */ }, }, },
737         { .name     = "munmap",
738           .arg = { [0] = { .scnprintf = SCA_HEX, /* addr */ }, }, },
739         { .name     = "name_to_handle_at",
740           .arg = { [0] = { .scnprintf = SCA_FDAT, /* dfd */ }, }, },
741         { .name     = "newfstatat",
742           .arg = { [0] = { .scnprintf = SCA_FDAT, /* dfd */ }, }, },
743         { .name     = "open",
744           .arg = { [1] = { .scnprintf = SCA_OPEN_FLAGS, /* flags */ }, }, },
745         { .name     = "open_by_handle_at",
746           .arg = { [0] = { .scnprintf = SCA_FDAT,       /* dfd */ },
747                    [2] = { .scnprintf = SCA_OPEN_FLAGS, /* flags */ }, }, },
748         { .name     = "openat",
749           .arg = { [0] = { .scnprintf = SCA_FDAT,       /* dfd */ },
750                    [2] = { .scnprintf = SCA_OPEN_FLAGS, /* flags */ }, }, },
751         { .name     = "perf_event_open",
752           .arg = { [2] = { .scnprintf = SCA_INT,        /* cpu */ },
753                    [3] = { .scnprintf = SCA_FD,         /* group_fd */ },
754                    [4] = { .scnprintf = SCA_PERF_FLAGS, /* flags */ }, }, },
755         { .name     = "pipe2",
756           .arg = { [1] = { .scnprintf = SCA_PIPE_FLAGS, /* flags */ }, }, },
757         { .name     = "pkey_alloc",
758           .arg = { [1] = { .scnprintf = SCA_PKEY_ALLOC_ACCESS_RIGHTS,   /* access_rights */ }, }, },
759         { .name     = "pkey_free",
760           .arg = { [0] = { .scnprintf = SCA_INT,        /* key */ }, }, },
761         { .name     = "pkey_mprotect",
762           .arg = { [0] = { .scnprintf = SCA_HEX,        /* start */ },
763                    [2] = { .scnprintf = SCA_MMAP_PROT,  /* prot */ },
764                    [3] = { .scnprintf = SCA_INT,        /* pkey */ }, }, },
765         { .name     = "poll", .timeout = true, },
766         { .name     = "ppoll", .timeout = true, },
767         { .name     = "prctl", .alias = "arch_prctl",
768           .arg = { [0] = { .scnprintf = SCA_PRCTL_OPTION, /* option */ },
769                    [1] = { .scnprintf = SCA_PRCTL_ARG2, /* arg2 */ },
770                    [2] = { .scnprintf = SCA_PRCTL_ARG3, /* arg3 */ }, }, },
771         { .name     = "pread", .alias = "pread64", },
772         { .name     = "preadv", .alias = "pread", },
773         { .name     = "prlimit64",
774           .arg = { [1] = STRARRAY(resource, rlimit_resources), }, },
775         { .name     = "pwrite", .alias = "pwrite64", },
776         { .name     = "readlinkat",
777           .arg = { [0] = { .scnprintf = SCA_FDAT, /* dfd */ }, }, },
778         { .name     = "recvfrom",
779           .arg = { [3] = { .scnprintf = SCA_MSG_FLAGS, /* flags */ }, }, },
780         { .name     = "recvmmsg",
781           .arg = { [3] = { .scnprintf = SCA_MSG_FLAGS, /* flags */ }, }, },
782         { .name     = "recvmsg",
783           .arg = { [2] = { .scnprintf = SCA_MSG_FLAGS, /* flags */ }, }, },
784         { .name     = "renameat",
785           .arg = { [0] = { .scnprintf = SCA_FDAT, /* dfd */ }, }, },
786         { .name     = "rt_sigaction",
787           .arg = { [0] = { .scnprintf = SCA_SIGNUM, /* sig */ }, }, },
788         { .name     = "rt_sigprocmask",
789           .arg = { [0] = STRARRAY(how, sighow), }, },
790         { .name     = "rt_sigqueueinfo",
791           .arg = { [1] = { .scnprintf = SCA_SIGNUM, /* sig */ }, }, },
792         { .name     = "rt_tgsigqueueinfo",
793           .arg = { [2] = { .scnprintf = SCA_SIGNUM, /* sig */ }, }, },
794         { .name     = "sched_setscheduler",
795           .arg = { [1] = { .scnprintf = SCA_SCHED_POLICY, /* policy */ }, }, },
796         { .name     = "seccomp",
797           .arg = { [0] = { .scnprintf = SCA_SECCOMP_OP,    /* op */ },
798                    [1] = { .scnprintf = SCA_SECCOMP_FLAGS, /* flags */ }, }, },
799         { .name     = "select", .timeout = true, },
800         { .name     = "sendmmsg",
801           .arg = { [3] = { .scnprintf = SCA_MSG_FLAGS, /* flags */ }, }, },
802         { .name     = "sendmsg",
803           .arg = { [2] = { .scnprintf = SCA_MSG_FLAGS, /* flags */ }, }, },
804         { .name     = "sendto",
805           .arg = { [3] = { .scnprintf = SCA_MSG_FLAGS, /* flags */ },
806                    [4] = { .scnprintf = SCA_SOCKADDR, /* addr */ }, }, },
807         { .name     = "set_tid_address", .errpid = true, },
808         { .name     = "setitimer",
809           .arg = { [0] = STRARRAY(which, itimers), }, },
810         { .name     = "setrlimit",
811           .arg = { [0] = STRARRAY(resource, rlimit_resources), }, },
812         { .name     = "socket",
813           .arg = { [0] = STRARRAY(family, socket_families),
814                    [1] = { .scnprintf = SCA_SK_TYPE, /* type */ },
815                    [2] = { .scnprintf = SCA_SK_PROTO, /* protocol */ }, }, },
816         { .name     = "socketpair",
817           .arg = { [0] = STRARRAY(family, socket_families),
818                    [1] = { .scnprintf = SCA_SK_TYPE, /* type */ },
819                    [2] = { .scnprintf = SCA_SK_PROTO, /* protocol */ }, }, },
820         { .name     = "stat", .alias = "newstat", },
821         { .name     = "statx",
822           .arg = { [0] = { .scnprintf = SCA_FDAT,        /* fdat */ },
823                    [2] = { .scnprintf = SCA_STATX_FLAGS, /* flags */ } ,
824                    [3] = { .scnprintf = SCA_STATX_MASK,  /* mask */ }, }, },
825         { .name     = "swapoff",
826           .arg = { [0] = { .scnprintf = SCA_FILENAME, /* specialfile */ }, }, },
827         { .name     = "swapon",
828           .arg = { [0] = { .scnprintf = SCA_FILENAME, /* specialfile */ }, }, },
829         { .name     = "symlinkat",
830           .arg = { [0] = { .scnprintf = SCA_FDAT, /* dfd */ }, }, },
831         { .name     = "tgkill",
832           .arg = { [2] = { .scnprintf = SCA_SIGNUM, /* sig */ }, }, },
833         { .name     = "tkill",
834           .arg = { [1] = { .scnprintf = SCA_SIGNUM, /* sig */ }, }, },
835         { .name     = "umount2", .alias = "umount", },
836         { .name     = "uname", .alias = "newuname", },
837         { .name     = "unlinkat",
838           .arg = { [0] = { .scnprintf = SCA_FDAT, /* dfd */ }, }, },
839         { .name     = "utimensat",
840           .arg = { [0] = { .scnprintf = SCA_FDAT, /* dirfd */ }, }, },
841         { .name     = "wait4",      .errpid = true,
842           .arg = { [2] = { .scnprintf = SCA_WAITID_OPTIONS, /* options */ }, }, },
843         { .name     = "waitid",     .errpid = true,
844           .arg = { [3] = { .scnprintf = SCA_WAITID_OPTIONS, /* options */ }, }, },
845 };
846
847 static int syscall_fmt__cmp(const void *name, const void *fmtp)
848 {
849         const struct syscall_fmt *fmt = fmtp;
850         return strcmp(name, fmt->name);
851 }
852
853 static struct syscall_fmt *syscall_fmt__find(const char *name)
854 {
855         const int nmemb = ARRAY_SIZE(syscall_fmts);
856         return bsearch(name, syscall_fmts, nmemb, sizeof(struct syscall_fmt), syscall_fmt__cmp);
857 }
858
859 /*
860  * is_exit: is this "exit" or "exit_group"?
861  * is_open: is this "open" or "openat"? To associate the fd returned in sys_exit with the pathname in sys_enter.
862  * args_size: sum of the sizes of the syscall arguments, anything after that is augmented stuff: pathname for openat, etc.
863  */
864 struct syscall {
865         struct tep_event_format *tp_format;
866         int                 nr_args;
867         int                 args_size;
868         bool                is_exit;
869         bool                is_open;
870         struct tep_format_field *args;
871         const char          *name;
872         struct syscall_fmt  *fmt;
873         struct syscall_arg_fmt *arg_fmt;
874 };
875
876 /*
877  * We need to have this 'calculated' boolean because in some cases we really
878  * don't know what is the duration of a syscall, for instance, when we start
879  * a session and some threads are waiting for a syscall to finish, say 'poll',
880  * in which case all we can do is to print "( ? ) for duration and for the
881  * start timestamp.
882  */
883 static size_t fprintf_duration(unsigned long t, bool calculated, FILE *fp)
884 {
885         double duration = (double)t / NSEC_PER_MSEC;
886         size_t printed = fprintf(fp, "(");
887
888         if (!calculated)
889                 printed += fprintf(fp, "         ");
890         else if (duration >= 1.0)
891                 printed += color_fprintf(fp, PERF_COLOR_RED, "%6.3f ms", duration);
892         else if (duration >= 0.01)
893                 printed += color_fprintf(fp, PERF_COLOR_YELLOW, "%6.3f ms", duration);
894         else
895                 printed += color_fprintf(fp, PERF_COLOR_NORMAL, "%6.3f ms", duration);
896         return printed + fprintf(fp, "): ");
897 }
898
899 /**
900  * filename.ptr: The filename char pointer that will be vfs_getname'd
901  * filename.entry_str_pos: Where to insert the string translated from
902  *                         filename.ptr by the vfs_getname tracepoint/kprobe.
903  * ret_scnprintf: syscall args may set this to a different syscall return
904  *                formatter, for instance, fcntl may return fds, file flags, etc.
905  */
906 struct thread_trace {
907         u64               entry_time;
908         bool              entry_pending;
909         unsigned long     nr_events;
910         unsigned long     pfmaj, pfmin;
911         char              *entry_str;
912         double            runtime_ms;
913         size_t            (*ret_scnprintf)(char *bf, size_t size, struct syscall_arg *arg);
914         struct {
915                 unsigned long ptr;
916                 short int     entry_str_pos;
917                 bool          pending_open;
918                 unsigned int  namelen;
919                 char          *name;
920         } filename;
921         struct {
922                 int       max;
923                 char      **table;
924         } paths;
925
926         struct intlist *syscall_stats;
927 };
928
929 static struct thread_trace *thread_trace__new(void)
930 {
931         struct thread_trace *ttrace =  zalloc(sizeof(struct thread_trace));
932
933         if (ttrace)
934                 ttrace->paths.max = -1;
935
936         ttrace->syscall_stats = intlist__new(NULL);
937
938         return ttrace;
939 }
940
941 static struct thread_trace *thread__trace(struct thread *thread, FILE *fp)
942 {
943         struct thread_trace *ttrace;
944
945         if (thread == NULL)
946                 goto fail;
947
948         if (thread__priv(thread) == NULL)
949                 thread__set_priv(thread, thread_trace__new());
950
951         if (thread__priv(thread) == NULL)
952                 goto fail;
953
954         ttrace = thread__priv(thread);
955         ++ttrace->nr_events;
956
957         return ttrace;
958 fail:
959         color_fprintf(fp, PERF_COLOR_RED,
960                       "WARNING: not enough memory, dropping samples!\n");
961         return NULL;
962 }
963
964
965 void syscall_arg__set_ret_scnprintf(struct syscall_arg *arg,
966                                     size_t (*ret_scnprintf)(char *bf, size_t size, struct syscall_arg *arg))
967 {
968         struct thread_trace *ttrace = thread__priv(arg->thread);
969
970         ttrace->ret_scnprintf = ret_scnprintf;
971 }
972
973 #define TRACE_PFMAJ             (1 << 0)
974 #define TRACE_PFMIN             (1 << 1)
975
976 static const size_t trace__entry_str_size = 2048;
977
978 static int trace__set_fd_pathname(struct thread *thread, int fd, const char *pathname)
979 {
980         struct thread_trace *ttrace = thread__priv(thread);
981
982         if (fd > ttrace->paths.max) {
983                 char **npath = realloc(ttrace->paths.table, (fd + 1) * sizeof(char *));
984
985                 if (npath == NULL)
986                         return -1;
987
988                 if (ttrace->paths.max != -1) {
989                         memset(npath + ttrace->paths.max + 1, 0,
990                                (fd - ttrace->paths.max) * sizeof(char *));
991                 } else {
992                         memset(npath, 0, (fd + 1) * sizeof(char *));
993                 }
994
995                 ttrace->paths.table = npath;
996                 ttrace->paths.max   = fd;
997         }
998
999         ttrace->paths.table[fd] = strdup(pathname);
1000
1001         return ttrace->paths.table[fd] != NULL ? 0 : -1;
1002 }
1003
1004 static int thread__read_fd_path(struct thread *thread, int fd)
1005 {
1006         char linkname[PATH_MAX], pathname[PATH_MAX];
1007         struct stat st;
1008         int ret;
1009
1010         if (thread->pid_ == thread->tid) {
1011                 scnprintf(linkname, sizeof(linkname),
1012                           "/proc/%d/fd/%d", thread->pid_, fd);
1013         } else {
1014                 scnprintf(linkname, sizeof(linkname),
1015                           "/proc/%d/task/%d/fd/%d", thread->pid_, thread->tid, fd);
1016         }
1017
1018         if (lstat(linkname, &st) < 0 || st.st_size + 1 > (off_t)sizeof(pathname))
1019                 return -1;
1020
1021         ret = readlink(linkname, pathname, sizeof(pathname));
1022
1023         if (ret < 0 || ret > st.st_size)
1024                 return -1;
1025
1026         pathname[ret] = '\0';
1027         return trace__set_fd_pathname(thread, fd, pathname);
1028 }
1029
1030 static const char *thread__fd_path(struct thread *thread, int fd,
1031                                    struct trace *trace)
1032 {
1033         struct thread_trace *ttrace = thread__priv(thread);
1034
1035         if (ttrace == NULL)
1036                 return NULL;
1037
1038         if (fd < 0)
1039                 return NULL;
1040
1041         if ((fd > ttrace->paths.max || ttrace->paths.table[fd] == NULL)) {
1042                 if (!trace->live)
1043                         return NULL;
1044                 ++trace->stats.proc_getname;
1045                 if (thread__read_fd_path(thread, fd))
1046                         return NULL;
1047         }
1048
1049         return ttrace->paths.table[fd];
1050 }
1051
1052 size_t syscall_arg__scnprintf_fd(char *bf, size_t size, struct syscall_arg *arg)
1053 {
1054         int fd = arg->val;
1055         size_t printed = scnprintf(bf, size, "%d", fd);
1056         const char *path = thread__fd_path(arg->thread, fd, arg->trace);
1057
1058         if (path)
1059                 printed += scnprintf(bf + printed, size - printed, "<%s>", path);
1060
1061         return printed;
1062 }
1063
1064 size_t pid__scnprintf_fd(struct trace *trace, pid_t pid, int fd, char *bf, size_t size)
1065 {
1066         size_t printed = scnprintf(bf, size, "%d", fd);
1067         struct thread *thread = machine__find_thread(trace->host, pid, pid);
1068
1069         if (thread) {
1070                 const char *path = thread__fd_path(thread, fd, trace);
1071
1072                 if (path)
1073                         printed += scnprintf(bf + printed, size - printed, "<%s>", path);
1074
1075                 thread__put(thread);
1076         }
1077
1078         return printed;
1079 }
1080
1081 static size_t syscall_arg__scnprintf_close_fd(char *bf, size_t size,
1082                                               struct syscall_arg *arg)
1083 {
1084         int fd = arg->val;
1085         size_t printed = syscall_arg__scnprintf_fd(bf, size, arg);
1086         struct thread_trace *ttrace = thread__priv(arg->thread);
1087
1088         if (ttrace && fd >= 0 && fd <= ttrace->paths.max)
1089                 zfree(&ttrace->paths.table[fd]);
1090
1091         return printed;
1092 }
1093
1094 static void thread__set_filename_pos(struct thread *thread, const char *bf,
1095                                      unsigned long ptr)
1096 {
1097         struct thread_trace *ttrace = thread__priv(thread);
1098
1099         ttrace->filename.ptr = ptr;
1100         ttrace->filename.entry_str_pos = bf - ttrace->entry_str;
1101 }
1102
1103 static size_t syscall_arg__scnprintf_augmented_string(struct syscall_arg *arg, char *bf, size_t size)
1104 {
1105         struct augmented_arg *augmented_arg = arg->augmented.args;
1106
1107         return scnprintf(bf, size, "%.*s", augmented_arg->size, augmented_arg->value);
1108 }
1109
1110 static size_t syscall_arg__scnprintf_filename(char *bf, size_t size,
1111                                               struct syscall_arg *arg)
1112 {
1113         unsigned long ptr = arg->val;
1114
1115         if (arg->augmented.args)
1116                 return syscall_arg__scnprintf_augmented_string(arg, bf, size);
1117
1118         if (!arg->trace->vfs_getname)
1119                 return scnprintf(bf, size, "%#x", ptr);
1120
1121         thread__set_filename_pos(arg->thread, bf, ptr);
1122         return 0;
1123 }
1124
1125 static bool trace__filter_duration(struct trace *trace, double t)
1126 {
1127         return t < (trace->duration_filter * NSEC_PER_MSEC);
1128 }
1129
1130 static size_t __trace__fprintf_tstamp(struct trace *trace, u64 tstamp, FILE *fp)
1131 {
1132         double ts = (double)(tstamp - trace->base_time) / NSEC_PER_MSEC;
1133
1134         return fprintf(fp, "%10.3f ", ts);
1135 }
1136
1137 /*
1138  * We're handling tstamp=0 as an undefined tstamp, i.e. like when we are
1139  * using ttrace->entry_time for a thread that receives a sys_exit without
1140  * first having received a sys_enter ("poll" issued before tracing session
1141  * starts, lost sys_enter exit due to ring buffer overflow).
1142  */
1143 static size_t trace__fprintf_tstamp(struct trace *trace, u64 tstamp, FILE *fp)
1144 {
1145         if (tstamp > 0)
1146                 return __trace__fprintf_tstamp(trace, tstamp, fp);
1147
1148         return fprintf(fp, "         ? ");
1149 }
1150
1151 static bool done = false;
1152 static bool interrupted = false;
1153
1154 static void sig_handler(int sig)
1155 {
1156         done = true;
1157         interrupted = sig == SIGINT;
1158 }
1159
1160 static size_t trace__fprintf_comm_tid(struct trace *trace, struct thread *thread, FILE *fp)
1161 {
1162         size_t printed = 0;
1163
1164         if (trace->multiple_threads) {
1165                 if (trace->show_comm)
1166                         printed += fprintf(fp, "%.14s/", thread__comm_str(thread));
1167                 printed += fprintf(fp, "%d ", thread->tid);
1168         }
1169
1170         return printed;
1171 }
1172
1173 static size_t trace__fprintf_entry_head(struct trace *trace, struct thread *thread,
1174                                         u64 duration, bool duration_calculated, u64 tstamp, FILE *fp)
1175 {
1176         size_t printed = trace__fprintf_tstamp(trace, tstamp, fp);
1177         printed += fprintf_duration(duration, duration_calculated, fp);
1178         return printed + trace__fprintf_comm_tid(trace, thread, fp);
1179 }
1180
1181 static int trace__process_event(struct trace *trace, struct machine *machine,
1182                                 union perf_event *event, struct perf_sample *sample)
1183 {
1184         int ret = 0;
1185
1186         switch (event->header.type) {
1187         case PERF_RECORD_LOST:
1188                 color_fprintf(trace->output, PERF_COLOR_RED,
1189                               "LOST %" PRIu64 " events!\n", event->lost.lost);
1190                 ret = machine__process_lost_event(machine, event, sample);
1191                 break;
1192         default:
1193                 ret = machine__process_event(machine, event, sample);
1194                 break;
1195         }
1196
1197         return ret;
1198 }
1199
1200 static int trace__tool_process(struct perf_tool *tool,
1201                                union perf_event *event,
1202                                struct perf_sample *sample,
1203                                struct machine *machine)
1204 {
1205         struct trace *trace = container_of(tool, struct trace, tool);
1206         return trace__process_event(trace, machine, event, sample);
1207 }
1208
1209 static char *trace__machine__resolve_kernel_addr(void *vmachine, unsigned long long *addrp, char **modp)
1210 {
1211         struct machine *machine = vmachine;
1212
1213         if (machine->kptr_restrict_warned)
1214                 return NULL;
1215
1216         if (symbol_conf.kptr_restrict) {
1217                 pr_warning("Kernel address maps (/proc/{kallsyms,modules}) are restricted.\n\n"
1218                            "Check /proc/sys/kernel/kptr_restrict.\n\n"
1219                            "Kernel samples will not be resolved.\n");
1220                 machine->kptr_restrict_warned = true;
1221                 return NULL;
1222         }
1223
1224         return machine__resolve_kernel_addr(vmachine, addrp, modp);
1225 }
1226
1227 static int trace__symbols_init(struct trace *trace, struct perf_evlist *evlist)
1228 {
1229         int err = symbol__init(NULL);
1230
1231         if (err)
1232                 return err;
1233
1234         trace->host = machine__new_host();
1235         if (trace->host == NULL)
1236                 return -ENOMEM;
1237
1238         err = trace_event__register_resolver(trace->host, trace__machine__resolve_kernel_addr);
1239         if (err < 0)
1240                 goto out;
1241
1242         err = __machine__synthesize_threads(trace->host, &trace->tool, &trace->opts.target,
1243                                             evlist->threads, trace__tool_process, false,
1244                                             trace->opts.proc_map_timeout, 1);
1245 out:
1246         if (err)
1247                 symbol__exit();
1248
1249         return err;
1250 }
1251
1252 static void trace__symbols__exit(struct trace *trace)
1253 {
1254         machine__exit(trace->host);
1255         trace->host = NULL;
1256
1257         symbol__exit();
1258 }
1259
1260 static int syscall__alloc_arg_fmts(struct syscall *sc, int nr_args)
1261 {
1262         int idx;
1263
1264         if (nr_args == 6 && sc->fmt && sc->fmt->nr_args != 0)
1265                 nr_args = sc->fmt->nr_args;
1266
1267         sc->arg_fmt = calloc(nr_args, sizeof(*sc->arg_fmt));
1268         if (sc->arg_fmt == NULL)
1269                 return -1;
1270
1271         for (idx = 0; idx < nr_args; ++idx) {
1272                 if (sc->fmt)
1273                         sc->arg_fmt[idx] = sc->fmt->arg[idx];
1274         }
1275
1276         sc->nr_args = nr_args;
1277         return 0;
1278 }
1279
1280 static int syscall__set_arg_fmts(struct syscall *sc)
1281 {
1282         struct tep_format_field *field, *last_field = NULL;
1283         int idx = 0, len;
1284
1285         for (field = sc->args; field; field = field->next, ++idx) {
1286                 last_field = field;
1287
1288                 if (sc->fmt && sc->fmt->arg[idx].scnprintf)
1289                         continue;
1290
1291                 if (strcmp(field->type, "const char *") == 0 &&
1292                          (strcmp(field->name, "filename") == 0 ||
1293                           strcmp(field->name, "path") == 0 ||
1294                           strcmp(field->name, "pathname") == 0))
1295                         sc->arg_fmt[idx].scnprintf = SCA_FILENAME;
1296                 else if (field->flags & TEP_FIELD_IS_POINTER)
1297                         sc->arg_fmt[idx].scnprintf = syscall_arg__scnprintf_hex;
1298                 else if (strcmp(field->type, "pid_t") == 0)
1299                         sc->arg_fmt[idx].scnprintf = SCA_PID;
1300                 else if (strcmp(field->type, "umode_t") == 0)
1301                         sc->arg_fmt[idx].scnprintf = SCA_MODE_T;
1302                 else if ((strcmp(field->type, "int") == 0 ||
1303                           strcmp(field->type, "unsigned int") == 0 ||
1304                           strcmp(field->type, "long") == 0) &&
1305                          (len = strlen(field->name)) >= 2 &&
1306                          strcmp(field->name + len - 2, "fd") == 0) {
1307                         /*
1308                          * /sys/kernel/tracing/events/syscalls/sys_enter*
1309                          * egrep 'field:.*fd;' .../format|sed -r 's/.*field:([a-z ]+) [a-z_]*fd.+/\1/g'|sort|uniq -c
1310                          * 65 int
1311                          * 23 unsigned int
1312                          * 7 unsigned long
1313                          */
1314                         sc->arg_fmt[idx].scnprintf = SCA_FD;
1315                 }
1316         }
1317
1318         if (last_field)
1319                 sc->args_size = last_field->offset + last_field->size;
1320
1321         return 0;
1322 }
1323
1324 static int trace__read_syscall_info(struct trace *trace, int id)
1325 {
1326         char tp_name[128];
1327         struct syscall *sc;
1328         const char *name = syscalltbl__name(trace->sctbl, id);
1329
1330         if (name == NULL)
1331                 return -1;
1332
1333         if (id > trace->syscalls.max) {
1334                 struct syscall *nsyscalls = realloc(trace->syscalls.table, (id + 1) * sizeof(*sc));
1335
1336                 if (nsyscalls == NULL)
1337                         return -1;
1338
1339                 if (trace->syscalls.max != -1) {
1340                         memset(nsyscalls + trace->syscalls.max + 1, 0,
1341                                (id - trace->syscalls.max) * sizeof(*sc));
1342                 } else {
1343                         memset(nsyscalls, 0, (id + 1) * sizeof(*sc));
1344                 }
1345
1346                 trace->syscalls.table = nsyscalls;
1347                 trace->syscalls.max   = id;
1348         }
1349
1350         sc = trace->syscalls.table + id;
1351         sc->name = name;
1352
1353         sc->fmt  = syscall_fmt__find(sc->name);
1354
1355         snprintf(tp_name, sizeof(tp_name), "sys_enter_%s", sc->name);
1356         sc->tp_format = trace_event__tp_format("syscalls", tp_name);
1357
1358         if (IS_ERR(sc->tp_format) && sc->fmt && sc->fmt->alias) {
1359                 snprintf(tp_name, sizeof(tp_name), "sys_enter_%s", sc->fmt->alias);
1360                 sc->tp_format = trace_event__tp_format("syscalls", tp_name);
1361         }
1362
1363         if (syscall__alloc_arg_fmts(sc, IS_ERR(sc->tp_format) ? 6 : sc->tp_format->format.nr_fields))
1364                 return -1;
1365
1366         if (IS_ERR(sc->tp_format))
1367                 return -1;
1368
1369         sc->args = sc->tp_format->format.fields;
1370         /*
1371          * We need to check and discard the first variable '__syscall_nr'
1372          * or 'nr' that mean the syscall number. It is needless here.
1373          * So drop '__syscall_nr' or 'nr' field but does not exist on older kernels.
1374          */
1375         if (sc->args && (!strcmp(sc->args->name, "__syscall_nr") || !strcmp(sc->args->name, "nr"))) {
1376                 sc->args = sc->args->next;
1377                 --sc->nr_args;
1378         }
1379
1380         sc->is_exit = !strcmp(name, "exit_group") || !strcmp(name, "exit");
1381         sc->is_open = !strcmp(name, "open") || !strcmp(name, "openat");
1382
1383         return syscall__set_arg_fmts(sc);
1384 }
1385
1386 static int trace__validate_ev_qualifier(struct trace *trace)
1387 {
1388         int err = 0, i;
1389         size_t nr_allocated;
1390         struct str_node *pos;
1391
1392         trace->ev_qualifier_ids.nr = strlist__nr_entries(trace->ev_qualifier);
1393         trace->ev_qualifier_ids.entries = malloc(trace->ev_qualifier_ids.nr *
1394                                                  sizeof(trace->ev_qualifier_ids.entries[0]));
1395
1396         if (trace->ev_qualifier_ids.entries == NULL) {
1397                 fputs("Error:\tNot enough memory for allocating events qualifier ids\n",
1398                        trace->output);
1399                 err = -EINVAL;
1400                 goto out;
1401         }
1402
1403         nr_allocated = trace->ev_qualifier_ids.nr;
1404         i = 0;
1405
1406         strlist__for_each_entry(pos, trace->ev_qualifier) {
1407                 const char *sc = pos->s;
1408                 int id = syscalltbl__id(trace->sctbl, sc), match_next = -1;
1409
1410                 if (id < 0) {
1411                         id = syscalltbl__strglobmatch_first(trace->sctbl, sc, &match_next);
1412                         if (id >= 0)
1413                                 goto matches;
1414
1415                         if (err == 0) {
1416                                 fputs("Error:\tInvalid syscall ", trace->output);
1417                                 err = -EINVAL;
1418                         } else {
1419                                 fputs(", ", trace->output);
1420                         }
1421
1422                         fputs(sc, trace->output);
1423                 }
1424 matches:
1425                 trace->ev_qualifier_ids.entries[i++] = id;
1426                 if (match_next == -1)
1427                         continue;
1428
1429                 while (1) {
1430                         id = syscalltbl__strglobmatch_next(trace->sctbl, sc, &match_next);
1431                         if (id < 0)
1432                                 break;
1433                         if (nr_allocated == trace->ev_qualifier_ids.nr) {
1434                                 void *entries;
1435
1436                                 nr_allocated += 8;
1437                                 entries = realloc(trace->ev_qualifier_ids.entries,
1438                                                   nr_allocated * sizeof(trace->ev_qualifier_ids.entries[0]));
1439                                 if (entries == NULL) {
1440                                         err = -ENOMEM;
1441                                         fputs("\nError:\t Not enough memory for parsing\n", trace->output);
1442                                         goto out_free;
1443                                 }
1444                                 trace->ev_qualifier_ids.entries = entries;
1445                         }
1446                         trace->ev_qualifier_ids.nr++;
1447                         trace->ev_qualifier_ids.entries[i++] = id;
1448                 }
1449         }
1450
1451         if (err < 0) {
1452                 fputs("\nHint:\ttry 'perf list syscalls:sys_enter_*'"
1453                       "\nHint:\tand: 'man syscalls'\n", trace->output);
1454 out_free:
1455                 zfree(&trace->ev_qualifier_ids.entries);
1456                 trace->ev_qualifier_ids.nr = 0;
1457         }
1458 out:
1459         return err;
1460 }
1461
1462 /*
1463  * args is to be interpreted as a series of longs but we need to handle
1464  * 8-byte unaligned accesses. args points to raw_data within the event
1465  * and raw_data is guaranteed to be 8-byte unaligned because it is
1466  * preceded by raw_size which is a u32. So we need to copy args to a temp
1467  * variable to read it. Most notably this avoids extended load instructions
1468  * on unaligned addresses
1469  */
1470 unsigned long syscall_arg__val(struct syscall_arg *arg, u8 idx)
1471 {
1472         unsigned long val;
1473         unsigned char *p = arg->args + sizeof(unsigned long) * idx;
1474
1475         memcpy(&val, p, sizeof(val));
1476         return val;
1477 }
1478
1479 static size_t syscall__scnprintf_name(struct syscall *sc, char *bf, size_t size,
1480                                       struct syscall_arg *arg)
1481 {
1482         if (sc->arg_fmt && sc->arg_fmt[arg->idx].name)
1483                 return scnprintf(bf, size, "%s: ", sc->arg_fmt[arg->idx].name);
1484
1485         return scnprintf(bf, size, "arg%d: ", arg->idx);
1486 }
1487
1488 static size_t syscall__scnprintf_val(struct syscall *sc, char *bf, size_t size,
1489                                      struct syscall_arg *arg, unsigned long val)
1490 {
1491         if (sc->arg_fmt && sc->arg_fmt[arg->idx].scnprintf) {
1492                 arg->val = val;
1493                 if (sc->arg_fmt[arg->idx].parm)
1494                         arg->parm = sc->arg_fmt[arg->idx].parm;
1495                 return sc->arg_fmt[arg->idx].scnprintf(bf, size, arg);
1496         }
1497         return scnprintf(bf, size, "%ld", val);
1498 }
1499
1500 static size_t syscall__scnprintf_args(struct syscall *sc, char *bf, size_t size,
1501                                       unsigned char *args, void *augmented_args, int augmented_args_size,
1502                                       struct trace *trace, struct thread *thread)
1503 {
1504         size_t printed = 0;
1505         unsigned long val;
1506         u8 bit = 1;
1507         struct syscall_arg arg = {
1508                 .args   = args,
1509                 .augmented = {
1510                         .size = augmented_args_size,
1511                         .args = augmented_args,
1512                 },
1513                 .idx    = 0,
1514                 .mask   = 0,
1515                 .trace  = trace,
1516                 .thread = thread,
1517         };
1518         struct thread_trace *ttrace = thread__priv(thread);
1519
1520         /*
1521          * Things like fcntl will set this in its 'cmd' formatter to pick the
1522          * right formatter for the return value (an fd? file flags?), which is
1523          * not needed for syscalls that always return a given type, say an fd.
1524          */
1525         ttrace->ret_scnprintf = NULL;
1526
1527         if (sc->args != NULL) {
1528                 struct tep_format_field *field;
1529
1530                 for (field = sc->args; field;
1531                      field = field->next, ++arg.idx, bit <<= 1) {
1532                         if (arg.mask & bit)
1533                                 continue;
1534
1535                         val = syscall_arg__val(&arg, arg.idx);
1536
1537                         /*
1538                          * Suppress this argument if its value is zero and
1539                          * and we don't have a string associated in an
1540                          * strarray for it.
1541                          */
1542                         if (val == 0 &&
1543                             !(sc->arg_fmt &&
1544                               (sc->arg_fmt[arg.idx].show_zero ||
1545                                sc->arg_fmt[arg.idx].scnprintf == SCA_STRARRAY ||
1546                                sc->arg_fmt[arg.idx].scnprintf == SCA_STRARRAYS) &&
1547                               sc->arg_fmt[arg.idx].parm))
1548                                 continue;
1549
1550                         printed += scnprintf(bf + printed, size - printed,
1551                                              "%s%s: ", printed ? ", " : "", field->name);
1552                         printed += syscall__scnprintf_val(sc, bf + printed, size - printed, &arg, val);
1553                 }
1554         } else if (IS_ERR(sc->tp_format)) {
1555                 /*
1556                  * If we managed to read the tracepoint /format file, then we
1557                  * may end up not having any args, like with gettid(), so only
1558                  * print the raw args when we didn't manage to read it.
1559                  */
1560                 while (arg.idx < sc->nr_args) {
1561                         if (arg.mask & bit)
1562                                 goto next_arg;
1563                         val = syscall_arg__val(&arg, arg.idx);
1564                         if (printed)
1565                                 printed += scnprintf(bf + printed, size - printed, ", ");
1566                         printed += syscall__scnprintf_name(sc, bf + printed, size - printed, &arg);
1567                         printed += syscall__scnprintf_val(sc, bf + printed, size - printed, &arg, val);
1568 next_arg:
1569                         ++arg.idx;
1570                         bit <<= 1;
1571                 }
1572         }
1573
1574         return printed;
1575 }
1576
1577 typedef int (*tracepoint_handler)(struct trace *trace, struct perf_evsel *evsel,
1578                                   union perf_event *event,
1579                                   struct perf_sample *sample);
1580
1581 static struct syscall *trace__syscall_info(struct trace *trace,
1582                                            struct perf_evsel *evsel, int id)
1583 {
1584
1585         if (id < 0) {
1586
1587                 /*
1588                  * XXX: Noticed on x86_64, reproduced as far back as 3.0.36, haven't tried
1589                  * before that, leaving at a higher verbosity level till that is
1590                  * explained. Reproduced with plain ftrace with:
1591                  *
1592                  * echo 1 > /t/events/raw_syscalls/sys_exit/enable
1593                  * grep "NR -1 " /t/trace_pipe
1594                  *
1595                  * After generating some load on the machine.
1596                  */
1597                 if (verbose > 1) {
1598                         static u64 n;
1599                         fprintf(trace->output, "Invalid syscall %d id, skipping (%s, %" PRIu64 ") ...\n",
1600                                 id, perf_evsel__name(evsel), ++n);
1601                 }
1602                 return NULL;
1603         }
1604
1605         if ((id > trace->syscalls.max || trace->syscalls.table[id].name == NULL) &&
1606             trace__read_syscall_info(trace, id))
1607                 goto out_cant_read;
1608
1609         if ((id > trace->syscalls.max || trace->syscalls.table[id].name == NULL))
1610                 goto out_cant_read;
1611
1612         return &trace->syscalls.table[id];
1613
1614 out_cant_read:
1615         if (verbose > 0) {
1616                 fprintf(trace->output, "Problems reading syscall %d", id);
1617                 if (id <= trace->syscalls.max && trace->syscalls.table[id].name != NULL)
1618                         fprintf(trace->output, "(%s)", trace->syscalls.table[id].name);
1619                 fputs(" information\n", trace->output);
1620         }
1621         return NULL;
1622 }
1623
1624 static void thread__update_stats(struct thread_trace *ttrace,
1625                                  int id, struct perf_sample *sample)
1626 {
1627         struct int_node *inode;
1628         struct stats *stats;
1629         u64 duration = 0;
1630
1631         inode = intlist__findnew(ttrace->syscall_stats, id);
1632         if (inode == NULL)
1633                 return;
1634
1635         stats = inode->priv;
1636         if (stats == NULL) {
1637                 stats = malloc(sizeof(struct stats));
1638                 if (stats == NULL)
1639                         return;
1640                 init_stats(stats);
1641                 inode->priv = stats;
1642         }
1643
1644         if (ttrace->entry_time && sample->time > ttrace->entry_time)
1645                 duration = sample->time - ttrace->entry_time;
1646
1647         update_stats(stats, duration);
1648 }
1649
1650 static int trace__printf_interrupted_entry(struct trace *trace)
1651 {
1652         struct thread_trace *ttrace;
1653         size_t printed;
1654
1655         if (trace->failure_only || trace->current == NULL)
1656                 return 0;
1657
1658         ttrace = thread__priv(trace->current);
1659
1660         if (!ttrace->entry_pending)
1661                 return 0;
1662
1663         printed  = trace__fprintf_entry_head(trace, trace->current, 0, false, ttrace->entry_time, trace->output);
1664         printed += fprintf(trace->output, "%-70s) ...\n", ttrace->entry_str);
1665         ttrace->entry_pending = false;
1666
1667         return printed;
1668 }
1669
1670 static int trace__fprintf_sample(struct trace *trace, struct perf_evsel *evsel,
1671                                  struct perf_sample *sample, struct thread *thread)
1672 {
1673         int printed = 0;
1674
1675         if (trace->print_sample) {
1676                 double ts = (double)sample->time / NSEC_PER_MSEC;
1677
1678                 printed += fprintf(trace->output, "%22s %10.3f %s %d/%d [%d]\n",
1679                                    perf_evsel__name(evsel), ts,
1680                                    thread__comm_str(thread),
1681                                    sample->pid, sample->tid, sample->cpu);
1682         }
1683
1684         return printed;
1685 }
1686
1687 static void *syscall__augmented_args(struct syscall *sc, struct perf_sample *sample, int *augmented_args_size)
1688 {
1689         void *augmented_args = NULL;
1690
1691         *augmented_args_size = sample->raw_size - sc->args_size;
1692         if (*augmented_args_size > 0)
1693                 augmented_args = sample->raw_data + sc->args_size;
1694
1695         return augmented_args;
1696 }
1697
1698 static int trace__sys_enter(struct trace *trace, struct perf_evsel *evsel,
1699                             union perf_event *event __maybe_unused,
1700                             struct perf_sample *sample)
1701 {
1702         char *msg;
1703         void *args;
1704         size_t printed = 0;
1705         struct thread *thread;
1706         int id = perf_evsel__sc_tp_uint(evsel, id, sample), err = -1;
1707         int augmented_args_size = 0;
1708         void *augmented_args = NULL;
1709         struct syscall *sc = trace__syscall_info(trace, evsel, id);
1710         struct thread_trace *ttrace;
1711
1712         if (sc == NULL)
1713                 return -1;
1714
1715         thread = machine__findnew_thread(trace->host, sample->pid, sample->tid);
1716         ttrace = thread__trace(thread, trace->output);
1717         if (ttrace == NULL)
1718                 goto out_put;
1719
1720         trace__fprintf_sample(trace, evsel, sample, thread);
1721
1722         args = perf_evsel__sc_tp_ptr(evsel, args, sample);
1723
1724         if (ttrace->entry_str == NULL) {
1725                 ttrace->entry_str = malloc(trace__entry_str_size);
1726                 if (!ttrace->entry_str)
1727                         goto out_put;
1728         }
1729
1730         if (!(trace->duration_filter || trace->summary_only || trace->min_stack))
1731                 trace__printf_interrupted_entry(trace);
1732         /*
1733          * If this is raw_syscalls.sys_enter, then it always comes with the 6 possible
1734          * arguments, even if the syscall being handled, say "openat", uses only 4 arguments
1735          * this breaks syscall__augmented_args() check for augmented args, as we calculate
1736          * syscall->args_size using each syscalls:sys_enter_NAME tracefs format file,
1737          * so when handling, say the openat syscall, we end up getting 6 args for the
1738          * raw_syscalls:sys_enter event, when we expected just 4, we end up mistakenly
1739          * thinking that the extra 2 u64 args are the augmented filename, so just check
1740          * here and avoid using augmented syscalls when the evsel is the raw_syscalls one.
1741          */
1742         if (evsel != trace->syscalls.events.sys_enter)
1743                 augmented_args = syscall__augmented_args(sc, sample, &augmented_args_size);
1744         ttrace->entry_time = sample->time;
1745         msg = ttrace->entry_str;
1746         printed += scnprintf(msg + printed, trace__entry_str_size - printed, "%s(", sc->name);
1747
1748         printed += syscall__scnprintf_args(sc, msg + printed, trace__entry_str_size - printed,
1749                                            args, augmented_args, augmented_args_size, trace, thread);
1750
1751         if (sc->is_exit) {
1752                 if (!(trace->duration_filter || trace->summary_only || trace->failure_only || trace->min_stack)) {
1753                         trace__fprintf_entry_head(trace, thread, 0, false, ttrace->entry_time, trace->output);
1754                         fprintf(trace->output, "%-70s)\n", ttrace->entry_str);
1755                 }
1756         } else {
1757                 ttrace->entry_pending = true;
1758                 /* See trace__vfs_getname & trace__sys_exit */
1759                 ttrace->filename.pending_open = false;
1760         }
1761
1762         if (trace->current != thread) {
1763                 thread__put(trace->current);
1764                 trace->current = thread__get(thread);
1765         }
1766         err = 0;
1767 out_put:
1768         thread__put(thread);
1769         return err;
1770 }
1771
1772 static int trace__fprintf_sys_enter(struct trace *trace, struct perf_evsel *evsel,
1773                                     struct perf_sample *sample)
1774 {
1775         struct thread_trace *ttrace;
1776         struct thread *thread;
1777         int id = perf_evsel__sc_tp_uint(evsel, id, sample), err = -1;
1778         struct syscall *sc = trace__syscall_info(trace, evsel, id);
1779         char msg[1024];
1780         void *args, *augmented_args = NULL;
1781         int augmented_args_size;
1782
1783         if (sc == NULL)
1784                 return -1;
1785
1786         thread = machine__findnew_thread(trace->host, sample->pid, sample->tid);
1787         ttrace = thread__trace(thread, trace->output);
1788         /*
1789          * We need to get ttrace just to make sure it is there when syscall__scnprintf_args()
1790          * and the rest of the beautifiers accessing it via struct syscall_arg touches it.
1791          */
1792         if (ttrace == NULL)
1793                 goto out_put;
1794
1795         args = perf_evsel__sc_tp_ptr(evsel, args, sample);
1796         augmented_args = syscall__augmented_args(sc, sample, &augmented_args_size);
1797         syscall__scnprintf_args(sc, msg, sizeof(msg), args, augmented_args, augmented_args_size, trace, thread);
1798         fprintf(trace->output, "%s", msg);
1799         err = 0;
1800 out_put:
1801         thread__put(thread);
1802         return err;
1803 }
1804
1805 static int trace__resolve_callchain(struct trace *trace, struct perf_evsel *evsel,
1806                                     struct perf_sample *sample,
1807                                     struct callchain_cursor *cursor)
1808 {
1809         struct addr_location al;
1810         int max_stack = evsel->attr.sample_max_stack ?
1811                         evsel->attr.sample_max_stack :
1812                         trace->max_stack;
1813
1814         if (machine__resolve(trace->host, &al, sample) < 0 ||
1815             thread__resolve_callchain(al.thread, cursor, evsel, sample, NULL, NULL, max_stack))
1816                 return -1;
1817
1818         return 0;
1819 }
1820
1821 static int trace__fprintf_callchain(struct trace *trace, struct perf_sample *sample)
1822 {
1823         /* TODO: user-configurable print_opts */
1824         const unsigned int print_opts = EVSEL__PRINT_SYM |
1825                                         EVSEL__PRINT_DSO |
1826                                         EVSEL__PRINT_UNKNOWN_AS_ADDR;
1827
1828         return sample__fprintf_callchain(sample, 38, print_opts, &callchain_cursor, trace->output);
1829 }
1830
1831 static const char *errno_to_name(struct perf_evsel *evsel, int err)
1832 {
1833         struct perf_env *env = perf_evsel__env(evsel);
1834         const char *arch_name = perf_env__arch(env);
1835
1836         return arch_syscalls__strerrno(arch_name, err);
1837 }
1838
1839 static int trace__sys_exit(struct trace *trace, struct perf_evsel *evsel,
1840                            union perf_event *event __maybe_unused,
1841                            struct perf_sample *sample)
1842 {
1843         long ret;
1844         u64 duration = 0;
1845         bool duration_calculated = false;
1846         struct thread *thread;
1847         int id = perf_evsel__sc_tp_uint(evsel, id, sample), err = -1, callchain_ret = 0;
1848         struct syscall *sc = trace__syscall_info(trace, evsel, id);
1849         struct thread_trace *ttrace;
1850
1851         if (sc == NULL)
1852                 return -1;
1853
1854         thread = machine__findnew_thread(trace->host, sample->pid, sample->tid);
1855         ttrace = thread__trace(thread, trace->output);
1856         if (ttrace == NULL)
1857                 goto out_put;
1858
1859         trace__fprintf_sample(trace, evsel, sample, thread);
1860
1861         if (trace->summary)
1862                 thread__update_stats(ttrace, id, sample);
1863
1864         ret = perf_evsel__sc_tp_uint(evsel, ret, sample);
1865
1866         if (sc->is_open && ret >= 0 && ttrace->filename.pending_open) {
1867                 trace__set_fd_pathname(thread, ret, ttrace->filename.name);
1868                 ttrace->filename.pending_open = false;
1869                 ++trace->stats.vfs_getname;
1870         }
1871
1872         if (ttrace->entry_time) {
1873                 duration = sample->time - ttrace->entry_time;
1874                 if (trace__filter_duration(trace, duration))
1875                         goto out;
1876                 duration_calculated = true;
1877         } else if (trace->duration_filter)
1878                 goto out;
1879
1880         if (sample->callchain) {
1881                 callchain_ret = trace__resolve_callchain(trace, evsel, sample, &callchain_cursor);
1882                 if (callchain_ret == 0) {
1883                         if (callchain_cursor.nr < trace->min_stack)
1884                                 goto out;
1885                         callchain_ret = 1;
1886                 }
1887         }
1888
1889         if (trace->summary_only || (ret >= 0 && trace->failure_only))
1890                 goto out;
1891
1892         trace__fprintf_entry_head(trace, thread, duration, duration_calculated, ttrace->entry_time, trace->output);
1893
1894         if (ttrace->entry_pending) {
1895                 fprintf(trace->output, "%-70s", ttrace->entry_str);
1896         } else {
1897                 fprintf(trace->output, " ... [");
1898                 color_fprintf(trace->output, PERF_COLOR_YELLOW, "continued");
1899                 fprintf(trace->output, "]: %s()", sc->name);
1900         }
1901
1902         if (sc->fmt == NULL) {
1903                 if (ret < 0)
1904                         goto errno_print;
1905 signed_print:
1906                 fprintf(trace->output, ") = %ld", ret);
1907         } else if (ret < 0) {
1908 errno_print: {
1909                 char bf[STRERR_BUFSIZE];
1910                 const char *emsg = str_error_r(-ret, bf, sizeof(bf)),
1911                            *e = errno_to_name(evsel, -ret);
1912
1913                 fprintf(trace->output, ") = -1 %s %s", e, emsg);
1914         }
1915         } else if (ret == 0 && sc->fmt->timeout)
1916                 fprintf(trace->output, ") = 0 Timeout");
1917         else if (ttrace->ret_scnprintf) {
1918                 char bf[1024];
1919                 struct syscall_arg arg = {
1920                         .val    = ret,
1921                         .thread = thread,
1922                         .trace  = trace,
1923                 };
1924                 ttrace->ret_scnprintf(bf, sizeof(bf), &arg);
1925                 ttrace->ret_scnprintf = NULL;
1926                 fprintf(trace->output, ") = %s", bf);
1927         } else if (sc->fmt->hexret)
1928                 fprintf(trace->output, ") = %#lx", ret);
1929         else if (sc->fmt->errpid) {
1930                 struct thread *child = machine__find_thread(trace->host, ret, ret);
1931
1932                 if (child != NULL) {
1933                         fprintf(trace->output, ") = %ld", ret);
1934                         if (child->comm_set)
1935                                 fprintf(trace->output, " (%s)", thread__comm_str(child));
1936                         thread__put(child);
1937                 }
1938         } else
1939                 goto signed_print;
1940
1941         fputc('\n', trace->output);
1942
1943         if (callchain_ret > 0)
1944                 trace__fprintf_callchain(trace, sample);
1945         else if (callchain_ret < 0)
1946                 pr_err("Problem processing %s callchain, skipping...\n", perf_evsel__name(evsel));
1947 out:
1948         ttrace->entry_pending = false;
1949         err = 0;
1950 out_put:
1951         thread__put(thread);
1952         return err;
1953 }
1954
1955 static int trace__vfs_getname(struct trace *trace, struct perf_evsel *evsel,
1956                               union perf_event *event __maybe_unused,
1957                               struct perf_sample *sample)
1958 {
1959         struct thread *thread = machine__findnew_thread(trace->host, sample->pid, sample->tid);
1960         struct thread_trace *ttrace;
1961         size_t filename_len, entry_str_len, to_move;
1962         ssize_t remaining_space;
1963         char *pos;
1964         const char *filename = perf_evsel__rawptr(evsel, sample, "pathname");
1965
1966         if (!thread)
1967                 goto out;
1968
1969         ttrace = thread__priv(thread);
1970         if (!ttrace)
1971                 goto out_put;
1972
1973         filename_len = strlen(filename);
1974         if (filename_len == 0)
1975                 goto out_put;
1976
1977         if (ttrace->filename.namelen < filename_len) {
1978                 char *f = realloc(ttrace->filename.name, filename_len + 1);
1979
1980                 if (f == NULL)
1981                         goto out_put;
1982
1983                 ttrace->filename.namelen = filename_len;
1984                 ttrace->filename.name = f;
1985         }
1986
1987         strcpy(ttrace->filename.name, filename);
1988         ttrace->filename.pending_open = true;
1989
1990         if (!ttrace->filename.ptr)
1991                 goto out_put;
1992
1993         entry_str_len = strlen(ttrace->entry_str);
1994         remaining_space = trace__entry_str_size - entry_str_len - 1; /* \0 */
1995         if (remaining_space <= 0)
1996                 goto out_put;
1997
1998         if (filename_len > (size_t)remaining_space) {
1999                 filename += filename_len - remaining_space;
2000                 filename_len = remaining_space;
2001         }
2002
2003         to_move = entry_str_len - ttrace->filename.entry_str_pos + 1; /* \0 */
2004         pos = ttrace->entry_str + ttrace->filename.entry_str_pos;
2005         memmove(pos + filename_len, pos, to_move);
2006         memcpy(pos, filename, filename_len);
2007
2008         ttrace->filename.ptr = 0;
2009         ttrace->filename.entry_str_pos = 0;
2010 out_put:
2011         thread__put(thread);
2012 out:
2013         return 0;
2014 }
2015
2016 static int trace__sched_stat_runtime(struct trace *trace, struct perf_evsel *evsel,
2017                                      union perf_event *event __maybe_unused,
2018                                      struct perf_sample *sample)
2019 {
2020         u64 runtime = perf_evsel__intval(evsel, sample, "runtime");
2021         double runtime_ms = (double)runtime / NSEC_PER_MSEC;
2022         struct thread *thread = machine__findnew_thread(trace->host,
2023                                                         sample->pid,
2024                                                         sample->tid);
2025         struct thread_trace *ttrace = thread__trace(thread, trace->output);
2026
2027         if (ttrace == NULL)
2028                 goto out_dump;
2029
2030         ttrace->runtime_ms += runtime_ms;
2031         trace->runtime_ms += runtime_ms;
2032 out_put:
2033         thread__put(thread);
2034         return 0;
2035
2036 out_dump:
2037         fprintf(trace->output, "%s: comm=%s,pid=%u,runtime=%" PRIu64 ",vruntime=%" PRIu64 ")\n",
2038                evsel->name,
2039                perf_evsel__strval(evsel, sample, "comm"),
2040                (pid_t)perf_evsel__intval(evsel, sample, "pid"),
2041                runtime,
2042                perf_evsel__intval(evsel, sample, "vruntime"));
2043         goto out_put;
2044 }
2045
2046 static int bpf_output__printer(enum binary_printer_ops op,
2047                                unsigned int val, void *extra __maybe_unused, FILE *fp)
2048 {
2049         unsigned char ch = (unsigned char)val;
2050
2051         switch (op) {
2052         case BINARY_PRINT_CHAR_DATA:
2053                 return fprintf(fp, "%c", isprint(ch) ? ch : '.');
2054         case BINARY_PRINT_DATA_BEGIN:
2055         case BINARY_PRINT_LINE_BEGIN:
2056         case BINARY_PRINT_ADDR:
2057         case BINARY_PRINT_NUM_DATA:
2058         case BINARY_PRINT_NUM_PAD:
2059         case BINARY_PRINT_SEP:
2060         case BINARY_PRINT_CHAR_PAD:
2061         case BINARY_PRINT_LINE_END:
2062         case BINARY_PRINT_DATA_END:
2063         default:
2064                 break;
2065         }
2066
2067         return 0;
2068 }
2069
2070 static void bpf_output__fprintf(struct trace *trace,
2071                                 struct perf_sample *sample)
2072 {
2073         binary__fprintf(sample->raw_data, sample->raw_size, 8,
2074                         bpf_output__printer, NULL, trace->output);
2075 }
2076
2077 static int trace__event_handler(struct trace *trace, struct perf_evsel *evsel,
2078                                 union perf_event *event __maybe_unused,
2079                                 struct perf_sample *sample)
2080 {
2081         struct thread *thread = machine__findnew_thread(trace->host, sample->pid, sample->tid);
2082         int callchain_ret = 0;
2083
2084         if (sample->callchain) {
2085                 callchain_ret = trace__resolve_callchain(trace, evsel, sample, &callchain_cursor);
2086                 if (callchain_ret == 0) {
2087                         if (callchain_cursor.nr < trace->min_stack)
2088                                 goto out;
2089                         callchain_ret = 1;
2090                 }
2091         }
2092
2093         trace__printf_interrupted_entry(trace);
2094         trace__fprintf_tstamp(trace, sample->time, trace->output);
2095
2096         if (trace->trace_syscalls)
2097                 fprintf(trace->output, "(         ): ");
2098
2099         if (thread)
2100                 trace__fprintf_comm_tid(trace, thread, trace->output);
2101
2102         if (evsel == trace->syscalls.events.augmented) {
2103                 int id = perf_evsel__sc_tp_uint(evsel, id, sample);
2104                 struct syscall *sc = trace__syscall_info(trace, evsel, id);
2105
2106                 if (sc) {
2107                         fprintf(trace->output, "%s(", sc->name);
2108                         trace__fprintf_sys_enter(trace, evsel, sample);
2109                         fputc(')', trace->output);
2110                         goto newline;
2111                 }
2112
2113                 /*
2114                  * XXX: Not having the associated syscall info or not finding/adding
2115                  *      the thread should never happen, but if it does...
2116                  *      fall thru and print it as a bpf_output event.
2117                  */
2118         }
2119
2120         fprintf(trace->output, "%s:", evsel->name);
2121
2122         if (perf_evsel__is_bpf_output(evsel)) {
2123                 bpf_output__fprintf(trace, sample);
2124         } else if (evsel->tp_format) {
2125                 if (strncmp(evsel->tp_format->name, "sys_enter_", 10) ||
2126                     trace__fprintf_sys_enter(trace, evsel, sample)) {
2127                         event_format__fprintf(evsel->tp_format, sample->cpu,
2128                                               sample->raw_data, sample->raw_size,
2129                                               trace->output);
2130                 }
2131         }
2132
2133 newline:
2134         fprintf(trace->output, "\n");
2135
2136         if (callchain_ret > 0)
2137                 trace__fprintf_callchain(trace, sample);
2138         else if (callchain_ret < 0)
2139                 pr_err("Problem processing %s callchain, skipping...\n", perf_evsel__name(evsel));
2140         thread__put(thread);
2141 out:
2142         return 0;
2143 }
2144
2145 static void print_location(FILE *f, struct perf_sample *sample,
2146                            struct addr_location *al,
2147                            bool print_dso, bool print_sym)
2148 {
2149
2150         if ((verbose > 0 || print_dso) && al->map)
2151                 fprintf(f, "%s@", al->map->dso->long_name);
2152
2153         if ((verbose > 0 || print_sym) && al->sym)
2154                 fprintf(f, "%s+0x%" PRIx64, al->sym->name,
2155                         al->addr - al->sym->start);
2156         else if (al->map)
2157                 fprintf(f, "0x%" PRIx64, al->addr);
2158         else
2159                 fprintf(f, "0x%" PRIx64, sample->addr);
2160 }
2161
2162 static int trace__pgfault(struct trace *trace,
2163                           struct perf_evsel *evsel,
2164                           union perf_event *event __maybe_unused,
2165                           struct perf_sample *sample)
2166 {
2167         struct thread *thread;
2168         struct addr_location al;
2169         char map_type = 'd';
2170         struct thread_trace *ttrace;
2171         int err = -1;
2172         int callchain_ret = 0;
2173
2174         thread = machine__findnew_thread(trace->host, sample->pid, sample->tid);
2175
2176         if (sample->callchain) {
2177                 callchain_ret = trace__resolve_callchain(trace, evsel, sample, &callchain_cursor);
2178                 if (callchain_ret == 0) {
2179                         if (callchain_cursor.nr < trace->min_stack)
2180                                 goto out_put;
2181                         callchain_ret = 1;
2182                 }
2183         }
2184
2185         ttrace = thread__trace(thread, trace->output);
2186         if (ttrace == NULL)
2187                 goto out_put;
2188
2189         if (evsel->attr.config == PERF_COUNT_SW_PAGE_FAULTS_MAJ)
2190                 ttrace->pfmaj++;
2191         else
2192                 ttrace->pfmin++;
2193
2194         if (trace->summary_only)
2195                 goto out;
2196
2197         thread__find_symbol(thread, sample->cpumode, sample->ip, &al);
2198
2199         trace__fprintf_entry_head(trace, thread, 0, true, sample->time, trace->output);
2200
2201         fprintf(trace->output, "%sfault [",
2202                 evsel->attr.config == PERF_COUNT_SW_PAGE_FAULTS_MAJ ?
2203                 "maj" : "min");
2204
2205         print_location(trace->output, sample, &al, false, true);
2206
2207         fprintf(trace->output, "] => ");
2208
2209         thread__find_symbol(thread, sample->cpumode, sample->addr, &al);
2210
2211         if (!al.map) {
2212                 thread__find_symbol(thread, sample->cpumode, sample->addr, &al);
2213
2214                 if (al.map)
2215                         map_type = 'x';
2216                 else
2217                         map_type = '?';
2218         }
2219
2220         print_location(trace->output, sample, &al, true, false);
2221
2222         fprintf(trace->output, " (%c%c)\n", map_type, al.level);
2223
2224         if (callchain_ret > 0)
2225                 trace__fprintf_callchain(trace, sample);
2226         else if (callchain_ret < 0)
2227                 pr_err("Problem processing %s callchain, skipping...\n", perf_evsel__name(evsel));
2228 out:
2229         err = 0;
2230 out_put:
2231         thread__put(thread);
2232         return err;
2233 }
2234
2235 static void trace__set_base_time(struct trace *trace,
2236                                  struct perf_evsel *evsel,
2237                                  struct perf_sample *sample)
2238 {
2239         /*
2240          * BPF events were not setting PERF_SAMPLE_TIME, so be more robust
2241          * and don't use sample->time unconditionally, we may end up having
2242          * some other event in the future without PERF_SAMPLE_TIME for good
2243          * reason, i.e. we may not be interested in its timestamps, just in
2244          * it taking place, picking some piece of information when it
2245          * appears in our event stream (vfs_getname comes to mind).
2246          */
2247         if (trace->base_time == 0 && !trace->full_time &&
2248             (evsel->attr.sample_type & PERF_SAMPLE_TIME))
2249                 trace->base_time = sample->time;
2250 }
2251
2252 static int trace__process_sample(struct perf_tool *tool,
2253                                  union perf_event *event,
2254                                  struct perf_sample *sample,
2255                                  struct perf_evsel *evsel,
2256                                  struct machine *machine __maybe_unused)
2257 {
2258         struct trace *trace = container_of(tool, struct trace, tool);
2259         struct thread *thread;
2260         int err = 0;
2261
2262         tracepoint_handler handler = evsel->handler;
2263
2264         thread = machine__findnew_thread(trace->host, sample->pid, sample->tid);
2265         if (thread && thread__is_filtered(thread))
2266                 goto out;
2267
2268         trace__set_base_time(trace, evsel, sample);
2269
2270         if (handler) {
2271                 ++trace->nr_events;
2272                 handler(trace, evsel, event, sample);
2273         }
2274 out:
2275         thread__put(thread);
2276         return err;
2277 }
2278
2279 static int trace__record(struct trace *trace, int argc, const char **argv)
2280 {
2281         unsigned int rec_argc, i, j;
2282         const char **rec_argv;
2283         const char * const record_args[] = {
2284                 "record",
2285                 "-R",
2286                 "-m", "1024",
2287                 "-c", "1",
2288         };
2289
2290         const char * const sc_args[] = { "-e", };
2291         unsigned int sc_args_nr = ARRAY_SIZE(sc_args);
2292         const char * const majpf_args[] = { "-e", "major-faults" };
2293         unsigned int majpf_args_nr = ARRAY_SIZE(majpf_args);
2294         const char * const minpf_args[] = { "-e", "minor-faults" };
2295         unsigned int minpf_args_nr = ARRAY_SIZE(minpf_args);
2296
2297         /* +1 is for the event string below */
2298         rec_argc = ARRAY_SIZE(record_args) + sc_args_nr + 1 +
2299                 majpf_args_nr + minpf_args_nr + argc;
2300         rec_argv = calloc(rec_argc + 1, sizeof(char *));
2301
2302         if (rec_argv == NULL)
2303                 return -ENOMEM;
2304
2305         j = 0;
2306         for (i = 0; i < ARRAY_SIZE(record_args); i++)
2307                 rec_argv[j++] = record_args[i];
2308
2309         if (trace->trace_syscalls) {
2310                 for (i = 0; i < sc_args_nr; i++)
2311                         rec_argv[j++] = sc_args[i];
2312
2313                 /* event string may be different for older kernels - e.g., RHEL6 */
2314                 if (is_valid_tracepoint("raw_syscalls:sys_enter"))
2315                         rec_argv[j++] = "raw_syscalls:sys_enter,raw_syscalls:sys_exit";
2316                 else if (is_valid_tracepoint("syscalls:sys_enter"))
2317                         rec_argv[j++] = "syscalls:sys_enter,syscalls:sys_exit";
2318                 else {
2319                         pr_err("Neither raw_syscalls nor syscalls events exist.\n");
2320                         free(rec_argv);
2321                         return -1;
2322                 }
2323         }
2324
2325         if (trace->trace_pgfaults & TRACE_PFMAJ)
2326                 for (i = 0; i < majpf_args_nr; i++)
2327                         rec_argv[j++] = majpf_args[i];
2328
2329         if (trace->trace_pgfaults & TRACE_PFMIN)
2330                 for (i = 0; i < minpf_args_nr; i++)
2331                         rec_argv[j++] = minpf_args[i];
2332
2333         for (i = 0; i < (unsigned int)argc; i++)
2334                 rec_argv[j++] = argv[i];
2335
2336         return cmd_record(j, rec_argv);
2337 }
2338
2339 static size_t trace__fprintf_thread_summary(struct trace *trace, FILE *fp);
2340
2341 static bool perf_evlist__add_vfs_getname(struct perf_evlist *evlist)
2342 {
2343         struct perf_evsel *evsel = perf_evsel__newtp("probe", "vfs_getname");
2344
2345         if (IS_ERR(evsel))
2346                 return false;
2347
2348         if (perf_evsel__field(evsel, "pathname") == NULL) {
2349                 perf_evsel__delete(evsel);
2350                 return false;
2351         }
2352
2353         evsel->handler = trace__vfs_getname;
2354         perf_evlist__add(evlist, evsel);
2355         return true;
2356 }
2357
2358 static struct perf_evsel *perf_evsel__new_pgfault(u64 config)
2359 {
2360         struct perf_evsel *evsel;
2361         struct perf_event_attr attr = {
2362                 .type = PERF_TYPE_SOFTWARE,
2363                 .mmap_data = 1,
2364         };
2365
2366         attr.config = config;
2367         attr.sample_period = 1;
2368
2369         event_attr_init(&attr);
2370
2371         evsel = perf_evsel__new(&attr);
2372         if (evsel)
2373                 evsel->handler = trace__pgfault;
2374
2375         return evsel;
2376 }
2377
2378 static void trace__handle_event(struct trace *trace, union perf_event *event, struct perf_sample *sample)
2379 {
2380         const u32 type = event->header.type;
2381         struct perf_evsel *evsel;
2382
2383         if (type != PERF_RECORD_SAMPLE) {
2384                 trace__process_event(trace, trace->host, event, sample);
2385                 return;
2386         }
2387
2388         evsel = perf_evlist__id2evsel(trace->evlist, sample->id);
2389         if (evsel == NULL) {
2390                 fprintf(trace->output, "Unknown tp ID %" PRIu64 ", skipping...\n", sample->id);
2391                 return;
2392         }
2393
2394         trace__set_base_time(trace, evsel, sample);
2395
2396         if (evsel->attr.type == PERF_TYPE_TRACEPOINT &&
2397             sample->raw_data == NULL) {
2398                 fprintf(trace->output, "%s sample with no payload for tid: %d, cpu %d, raw_size=%d, skipping...\n",
2399                        perf_evsel__name(evsel), sample->tid,
2400                        sample->cpu, sample->raw_size);
2401         } else {
2402                 tracepoint_handler handler = evsel->handler;
2403                 handler(trace, evsel, event, sample);
2404         }
2405 }
2406
2407 static int trace__add_syscall_newtp(struct trace *trace)
2408 {
2409         int ret = -1;
2410         struct perf_evlist *evlist = trace->evlist;
2411         struct perf_evsel *sys_enter, *sys_exit;
2412
2413         sys_enter = perf_evsel__raw_syscall_newtp("sys_enter", trace__sys_enter);
2414         if (sys_enter == NULL)
2415                 goto out;
2416
2417         if (perf_evsel__init_sc_tp_ptr_field(sys_enter, args))
2418                 goto out_delete_sys_enter;
2419
2420         sys_exit = perf_evsel__raw_syscall_newtp("sys_exit", trace__sys_exit);
2421         if (sys_exit == NULL)
2422                 goto out_delete_sys_enter;
2423
2424         if (perf_evsel__init_sc_tp_uint_field(sys_exit, ret))
2425                 goto out_delete_sys_exit;
2426
2427         perf_evsel__config_callchain(sys_enter, &trace->opts, &callchain_param);
2428         perf_evsel__config_callchain(sys_exit, &trace->opts, &callchain_param);
2429
2430         perf_evlist__add(evlist, sys_enter);
2431         perf_evlist__add(evlist, sys_exit);
2432
2433         if (callchain_param.enabled && !trace->kernel_syscallchains) {
2434                 /*
2435                  * We're interested only in the user space callchain
2436                  * leading to the syscall, allow overriding that for
2437                  * debugging reasons using --kernel_syscall_callchains
2438                  */
2439                 sys_exit->attr.exclude_callchain_kernel = 1;
2440         }
2441
2442         trace->syscalls.events.sys_enter = sys_enter;
2443         trace->syscalls.events.sys_exit  = sys_exit;
2444
2445         ret = 0;
2446 out:
2447         return ret;
2448
2449 out_delete_sys_exit:
2450         perf_evsel__delete_priv(sys_exit);
2451 out_delete_sys_enter:
2452         perf_evsel__delete_priv(sys_enter);
2453         goto out;
2454 }
2455
2456 static int trace__set_ev_qualifier_filter(struct trace *trace)
2457 {
2458         int err = -1;
2459         struct perf_evsel *sys_exit;
2460         char *filter = asprintf_expr_inout_ints("id", !trace->not_ev_qualifier,
2461                                                 trace->ev_qualifier_ids.nr,
2462                                                 trace->ev_qualifier_ids.entries);
2463
2464         if (filter == NULL)
2465                 goto out_enomem;
2466
2467         if (!perf_evsel__append_tp_filter(trace->syscalls.events.sys_enter,
2468                                           filter)) {
2469                 sys_exit = trace->syscalls.events.sys_exit;
2470                 err = perf_evsel__append_tp_filter(sys_exit, filter);
2471         }
2472
2473         free(filter);
2474 out:
2475         return err;
2476 out_enomem:
2477         errno = ENOMEM;
2478         goto out;
2479 }
2480
2481 static int trace__set_filter_loop_pids(struct trace *trace)
2482 {
2483         unsigned int nr = 1;
2484         pid_t pids[32] = {
2485                 getpid(),
2486         };
2487         struct thread *thread = machine__find_thread(trace->host, pids[0], pids[0]);
2488
2489         while (thread && nr < ARRAY_SIZE(pids)) {
2490                 struct thread *parent = machine__find_thread(trace->host, thread->ppid, thread->ppid);
2491
2492                 if (parent == NULL)
2493                         break;
2494
2495                 if (!strcmp(thread__comm_str(parent), "sshd")) {
2496                         pids[nr++] = parent->tid;
2497                         break;
2498                 }
2499                 thread = parent;
2500         }
2501
2502         return perf_evlist__set_filter_pids(trace->evlist, nr, pids);
2503 }
2504
2505 static int trace__run(struct trace *trace, int argc, const char **argv)
2506 {
2507         struct perf_evlist *evlist = trace->evlist;
2508         struct perf_evsel *evsel, *pgfault_maj = NULL, *pgfault_min = NULL;
2509         int err = -1, i;
2510         unsigned long before;
2511         const bool forks = argc > 0;
2512         bool draining = false;
2513
2514         trace->live = true;
2515
2516         if (trace->trace_syscalls && trace__add_syscall_newtp(trace))
2517                 goto out_error_raw_syscalls;
2518
2519         if (trace->trace_syscalls)
2520                 trace->vfs_getname = perf_evlist__add_vfs_getname(evlist);
2521
2522         if ((trace->trace_pgfaults & TRACE_PFMAJ)) {
2523                 pgfault_maj = perf_evsel__new_pgfault(PERF_COUNT_SW_PAGE_FAULTS_MAJ);
2524                 if (pgfault_maj == NULL)
2525                         goto out_error_mem;
2526                 perf_evsel__config_callchain(pgfault_maj, &trace->opts, &callchain_param);
2527                 perf_evlist__add(evlist, pgfault_maj);
2528         }
2529
2530         if ((trace->trace_pgfaults & TRACE_PFMIN)) {
2531                 pgfault_min = perf_evsel__new_pgfault(PERF_COUNT_SW_PAGE_FAULTS_MIN);
2532                 if (pgfault_min == NULL)
2533                         goto out_error_mem;
2534                 perf_evsel__config_callchain(pgfault_min, &trace->opts, &callchain_param);
2535                 perf_evlist__add(evlist, pgfault_min);
2536         }
2537
2538         if (trace->sched &&
2539             perf_evlist__add_newtp(evlist, "sched", "sched_stat_runtime",
2540                                    trace__sched_stat_runtime))
2541                 goto out_error_sched_stat_runtime;
2542
2543         /*
2544          * If a global cgroup was set, apply it to all the events without an
2545          * explicit cgroup. I.e.:
2546          *
2547          *      trace -G A -e sched:*switch
2548          *
2549          * Will set all raw_syscalls:sys_{enter,exit}, pgfault, vfs_getname, etc
2550          * _and_ sched:sched_switch to the 'A' cgroup, while:
2551          *
2552          * trace -e sched:*switch -G A
2553          *
2554          * will only set the sched:sched_switch event to the 'A' cgroup, all the
2555          * other events (raw_syscalls:sys_{enter,exit}, etc are left "without"
2556          * a cgroup (on the root cgroup, sys wide, etc).
2557          *
2558          * Multiple cgroups:
2559          *
2560          * trace -G A -e sched:*switch -G B
2561          *
2562          * the syscall ones go to the 'A' cgroup, the sched:sched_switch goes
2563          * to the 'B' cgroup.
2564          *
2565          * evlist__set_default_cgroup() grabs a reference of the passed cgroup
2566          * only for the evsels still without a cgroup, i.e. evsel->cgroup == NULL.
2567          */
2568         if (trace->cgroup)
2569                 evlist__set_default_cgroup(trace->evlist, trace->cgroup);
2570
2571         err = perf_evlist__create_maps(evlist, &trace->opts.target);
2572         if (err < 0) {
2573                 fprintf(trace->output, "Problems parsing the target to trace, check your options!\n");
2574                 goto out_delete_evlist;
2575         }
2576
2577         err = trace__symbols_init(trace, evlist);
2578         if (err < 0) {
2579                 fprintf(trace->output, "Problems initializing symbol libraries!\n");
2580                 goto out_delete_evlist;
2581         }
2582
2583         perf_evlist__config(evlist, &trace->opts, &callchain_param);
2584
2585         signal(SIGCHLD, sig_handler);
2586         signal(SIGINT, sig_handler);
2587
2588         if (forks) {
2589                 err = perf_evlist__prepare_workload(evlist, &trace->opts.target,
2590                                                     argv, false, NULL);
2591                 if (err < 0) {
2592                         fprintf(trace->output, "Couldn't run the workload!\n");
2593                         goto out_delete_evlist;
2594                 }
2595         }
2596
2597         err = perf_evlist__open(evlist);
2598         if (err < 0)
2599                 goto out_error_open;
2600
2601         err = bpf__apply_obj_config();
2602         if (err) {
2603                 char errbuf[BUFSIZ];
2604
2605                 bpf__strerror_apply_obj_config(err, errbuf, sizeof(errbuf));
2606                 pr_err("ERROR: Apply config to BPF failed: %s\n",
2607                          errbuf);
2608                 goto out_error_open;
2609         }
2610
2611         /*
2612          * Better not use !target__has_task() here because we need to cover the
2613          * case where no threads were specified in the command line, but a
2614          * workload was, and in that case we will fill in the thread_map when
2615          * we fork the workload in perf_evlist__prepare_workload.
2616          */
2617         if (trace->filter_pids.nr > 0)
2618                 err = perf_evlist__set_filter_pids(evlist, trace->filter_pids.nr, trace->filter_pids.entries);
2619         else if (thread_map__pid(evlist->threads, 0) == -1)
2620                 err = trace__set_filter_loop_pids(trace);
2621
2622         if (err < 0)
2623                 goto out_error_mem;
2624
2625         if (trace->ev_qualifier_ids.nr > 0) {
2626                 err = trace__set_ev_qualifier_filter(trace);
2627                 if (err < 0)
2628                         goto out_errno;
2629
2630                 pr_debug("event qualifier tracepoint filter: %s\n",
2631                          trace->syscalls.events.sys_exit->filter);
2632         }
2633
2634         err = perf_evlist__apply_filters(evlist, &evsel);
2635         if (err < 0)
2636                 goto out_error_apply_filters;
2637
2638         err = perf_evlist__mmap(evlist, trace->opts.mmap_pages);
2639         if (err < 0)
2640                 goto out_error_mmap;
2641
2642         if (!target__none(&trace->opts.target) && !trace->opts.initial_delay)
2643                 perf_evlist__enable(evlist);
2644
2645         if (forks)
2646                 perf_evlist__start_workload(evlist);
2647
2648         if (trace->opts.initial_delay) {
2649                 usleep(trace->opts.initial_delay * 1000);
2650                 perf_evlist__enable(evlist);
2651         }
2652
2653         trace->multiple_threads = thread_map__pid(evlist->threads, 0) == -1 ||
2654                                   evlist->threads->nr > 1 ||
2655                                   perf_evlist__first(evlist)->attr.inherit;
2656
2657         /*
2658          * Now that we already used evsel->attr to ask the kernel to setup the
2659          * events, lets reuse evsel->attr.sample_max_stack as the limit in
2660          * trace__resolve_callchain(), allowing per-event max-stack settings
2661          * to override an explicitely set --max-stack global setting.
2662          */
2663         evlist__for_each_entry(evlist, evsel) {
2664                 if (evsel__has_callchain(evsel) &&
2665                     evsel->attr.sample_max_stack == 0)
2666                         evsel->attr.sample_max_stack = trace->max_stack;
2667         }
2668 again:
2669         before = trace->nr_events;
2670
2671         for (i = 0; i < evlist->nr_mmaps; i++) {
2672                 union perf_event *event;
2673                 struct perf_mmap *md;
2674
2675                 md = &evlist->mmap[i];
2676                 if (perf_mmap__read_init(md) < 0)
2677                         continue;
2678
2679                 while ((event = perf_mmap__read_event(md)) != NULL) {
2680                         struct perf_sample sample;
2681
2682                         ++trace->nr_events;
2683
2684                         err = perf_evlist__parse_sample(evlist, event, &sample);
2685                         if (err) {
2686                                 fprintf(trace->output, "Can't parse sample, err = %d, skipping...\n", err);
2687                                 goto next_event;
2688                         }
2689
2690                         trace__handle_event(trace, event, &sample);
2691 next_event:
2692                         perf_mmap__consume(md);
2693
2694                         if (interrupted)
2695                                 goto out_disable;
2696
2697                         if (done && !draining) {
2698                                 perf_evlist__disable(evlist);
2699                                 draining = true;
2700                         }
2701                 }
2702                 perf_mmap__read_done(md);
2703         }
2704
2705         if (trace->nr_events == before) {
2706                 int timeout = done ? 100 : -1;
2707
2708                 if (!draining && perf_evlist__poll(evlist, timeout) > 0) {
2709                         if (perf_evlist__filter_pollfd(evlist, POLLERR | POLLHUP) == 0)
2710                                 draining = true;
2711
2712                         goto again;
2713                 }
2714         } else {
2715                 goto again;
2716         }
2717
2718 out_disable:
2719         thread__zput(trace->current);
2720
2721         perf_evlist__disable(evlist);
2722
2723         if (!err) {
2724                 if (trace->summary)
2725                         trace__fprintf_thread_summary(trace, trace->output);
2726
2727                 if (trace->show_tool_stats) {
2728                         fprintf(trace->output, "Stats:\n "
2729                                                " vfs_getname : %" PRIu64 "\n"
2730                                                " proc_getname: %" PRIu64 "\n",
2731                                 trace->stats.vfs_getname,
2732                                 trace->stats.proc_getname);
2733                 }
2734         }
2735
2736 out_delete_evlist:
2737         trace__symbols__exit(trace);
2738
2739         perf_evlist__delete(evlist);
2740         cgroup__put(trace->cgroup);
2741         trace->evlist = NULL;
2742         trace->live = false;
2743         return err;
2744 {
2745         char errbuf[BUFSIZ];
2746
2747 out_error_sched_stat_runtime:
2748         tracing_path__strerror_open_tp(errno, errbuf, sizeof(errbuf), "sched", "sched_stat_runtime");
2749         goto out_error;
2750
2751 out_error_raw_syscalls:
2752         tracing_path__strerror_open_tp(errno, errbuf, sizeof(errbuf), "raw_syscalls", "sys_(enter|exit)");
2753         goto out_error;
2754
2755 out_error_mmap:
2756         perf_evlist__strerror_mmap(evlist, errno, errbuf, sizeof(errbuf));
2757         goto out_error;
2758
2759 out_error_open:
2760         perf_evlist__strerror_open(evlist, errno, errbuf, sizeof(errbuf));
2761
2762 out_error:
2763         fprintf(trace->output, "%s\n", errbuf);
2764         goto out_delete_evlist;
2765
2766 out_error_apply_filters:
2767         fprintf(trace->output,
2768                 "Failed to set filter \"%s\" on event %s with %d (%s)\n",
2769                 evsel->filter, perf_evsel__name(evsel), errno,
2770                 str_error_r(errno, errbuf, sizeof(errbuf)));
2771         goto out_delete_evlist;
2772 }
2773 out_error_mem:
2774         fprintf(trace->output, "Not enough memory to run!\n");
2775         goto out_delete_evlist;
2776
2777 out_errno:
2778         fprintf(trace->output, "errno=%d,%s\n", errno, strerror(errno));
2779         goto out_delete_evlist;
2780 }
2781
2782 static int trace__replay(struct trace *trace)
2783 {
2784         const struct perf_evsel_str_handler handlers[] = {
2785                 { "probe:vfs_getname",       trace__vfs_getname, },
2786         };
2787         struct perf_data data = {
2788                 .file      = {
2789                         .path = input_name,
2790                 },
2791                 .mode      = PERF_DATA_MODE_READ,
2792                 .force     = trace->force,
2793         };
2794         struct perf_session *session;
2795         struct perf_evsel *evsel;
2796         int err = -1;
2797
2798         trace->tool.sample        = trace__process_sample;
2799         trace->tool.mmap          = perf_event__process_mmap;
2800         trace->tool.mmap2         = perf_event__process_mmap2;
2801         trace->tool.comm          = perf_event__process_comm;
2802         trace->tool.exit          = perf_event__process_exit;
2803         trace->tool.fork          = perf_event__process_fork;
2804         trace->tool.attr          = perf_event__process_attr;
2805         trace->tool.tracing_data  = perf_event__process_tracing_data;
2806         trace->tool.build_id      = perf_event__process_build_id;
2807         trace->tool.namespaces    = perf_event__process_namespaces;
2808
2809         trace->tool.ordered_events = true;
2810         trace->tool.ordering_requires_timestamps = true;
2811
2812         /* add tid to output */
2813         trace->multiple_threads = true;
2814
2815         session = perf_session__new(&data, false, &trace->tool);
2816         if (session == NULL)
2817                 return -1;
2818
2819         if (trace->opts.target.pid)
2820                 symbol_conf.pid_list_str = strdup(trace->opts.target.pid);
2821
2822         if (trace->opts.target.tid)
2823                 symbol_conf.tid_list_str = strdup(trace->opts.target.tid);
2824
2825         if (symbol__init(&session->header.env) < 0)
2826                 goto out;
2827
2828         trace->host = &session->machines.host;
2829
2830         err = perf_session__set_tracepoints_handlers(session, handlers);
2831         if (err)
2832                 goto out;
2833
2834         evsel = perf_evlist__find_tracepoint_by_name(session->evlist,
2835                                                      "raw_syscalls:sys_enter");
2836         /* older kernels have syscalls tp versus raw_syscalls */
2837         if (evsel == NULL)
2838                 evsel = perf_evlist__find_tracepoint_by_name(session->evlist,
2839                                                              "syscalls:sys_enter");
2840
2841         if (evsel &&
2842             (perf_evsel__init_raw_syscall_tp(evsel, trace__sys_enter) < 0 ||
2843             perf_evsel__init_sc_tp_ptr_field(evsel, args))) {
2844                 pr_err("Error during initialize raw_syscalls:sys_enter event\n");
2845                 goto out;
2846         }
2847
2848         evsel = perf_evlist__find_tracepoint_by_name(session->evlist,
2849                                                      "raw_syscalls:sys_exit");
2850         if (evsel == NULL)
2851                 evsel = perf_evlist__find_tracepoint_by_name(session->evlist,
2852                                                              "syscalls:sys_exit");
2853         if (evsel &&
2854             (perf_evsel__init_raw_syscall_tp(evsel, trace__sys_exit) < 0 ||
2855             perf_evsel__init_sc_tp_uint_field(evsel, ret))) {
2856                 pr_err("Error during initialize raw_syscalls:sys_exit event\n");
2857                 goto out;
2858         }
2859
2860         evlist__for_each_entry(session->evlist, evsel) {
2861                 if (evsel->attr.type == PERF_TYPE_SOFTWARE &&
2862                     (evsel->attr.config == PERF_COUNT_SW_PAGE_FAULTS_MAJ ||
2863                      evsel->attr.config == PERF_COUNT_SW_PAGE_FAULTS_MIN ||
2864                      evsel->attr.config == PERF_COUNT_SW_PAGE_FAULTS))
2865                         evsel->handler = trace__pgfault;
2866         }
2867
2868         setup_pager();
2869
2870         err = perf_session__process_events(session);
2871         if (err)
2872                 pr_err("Failed to process events, error %d", err);
2873
2874         else if (trace->summary)
2875                 trace__fprintf_thread_summary(trace, trace->output);
2876
2877 out:
2878         perf_session__delete(session);
2879
2880         return err;
2881 }
2882
2883 static size_t trace__fprintf_threads_header(FILE *fp)
2884 {
2885         size_t printed;
2886
2887         printed  = fprintf(fp, "\n Summary of events:\n\n");
2888
2889         return printed;
2890 }
2891
2892 DEFINE_RESORT_RB(syscall_stats, a->msecs > b->msecs,
2893         struct stats    *stats;
2894         double          msecs;
2895         int             syscall;
2896 )
2897 {
2898         struct int_node *source = rb_entry(nd, struct int_node, rb_node);
2899         struct stats *stats = source->priv;
2900
2901         entry->syscall = source->i;
2902         entry->stats   = stats;
2903         entry->msecs   = stats ? (u64)stats->n * (avg_stats(stats) / NSEC_PER_MSEC) : 0;
2904 }
2905
2906 static size_t thread__dump_stats(struct thread_trace *ttrace,
2907                                  struct trace *trace, FILE *fp)
2908 {
2909         size_t printed = 0;
2910         struct syscall *sc;
2911         struct rb_node *nd;
2912         DECLARE_RESORT_RB_INTLIST(syscall_stats, ttrace->syscall_stats);
2913
2914         if (syscall_stats == NULL)
2915                 return 0;
2916
2917         printed += fprintf(fp, "\n");
2918
2919         printed += fprintf(fp, "   syscall            calls    total       min       avg       max      stddev\n");
2920         printed += fprintf(fp, "                               (msec)    (msec)    (msec)    (msec)        (%%)\n");
2921         printed += fprintf(fp, "   --------------- -------- --------- --------- --------- ---------     ------\n");
2922
2923         resort_rb__for_each_entry(nd, syscall_stats) {
2924                 struct stats *stats = syscall_stats_entry->stats;
2925                 if (stats) {
2926                         double min = (double)(stats->min) / NSEC_PER_MSEC;
2927                         double max = (double)(stats->max) / NSEC_PER_MSEC;
2928                         double avg = avg_stats(stats);
2929                         double pct;
2930                         u64 n = (u64) stats->n;
2931
2932                         pct = avg ? 100.0 * stddev_stats(stats)/avg : 0.0;
2933                         avg /= NSEC_PER_MSEC;
2934
2935                         sc = &trace->syscalls.table[syscall_stats_entry->syscall];
2936                         printed += fprintf(fp, "   %-15s", sc->name);
2937                         printed += fprintf(fp, " %8" PRIu64 " %9.3f %9.3f %9.3f",
2938                                            n, syscall_stats_entry->msecs, min, avg);
2939                         printed += fprintf(fp, " %9.3f %9.2f%%\n", max, pct);
2940                 }
2941         }
2942
2943         resort_rb__delete(syscall_stats);
2944         printed += fprintf(fp, "\n\n");
2945
2946         return printed;
2947 }
2948
2949 static size_t trace__fprintf_thread(FILE *fp, struct thread *thread, struct trace *trace)
2950 {
2951         size_t printed = 0;
2952         struct thread_trace *ttrace = thread__priv(thread);
2953         double ratio;
2954
2955         if (ttrace == NULL)
2956                 return 0;
2957
2958         ratio = (double)ttrace->nr_events / trace->nr_events * 100.0;
2959
2960         printed += fprintf(fp, " %s (%d), ", thread__comm_str(thread), thread->tid);
2961         printed += fprintf(fp, "%lu events, ", ttrace->nr_events);
2962         printed += fprintf(fp, "%.1f%%", ratio);
2963         if (ttrace->pfmaj)
2964                 printed += fprintf(fp, ", %lu majfaults", ttrace->pfmaj);
2965         if (ttrace->pfmin)
2966                 printed += fprintf(fp, ", %lu minfaults", ttrace->pfmin);
2967         if (trace->sched)
2968                 printed += fprintf(fp, ", %.3f msec\n", ttrace->runtime_ms);
2969         else if (fputc('\n', fp) != EOF)
2970                 ++printed;
2971
2972         printed += thread__dump_stats(ttrace, trace, fp);
2973
2974         return printed;
2975 }
2976
2977 static unsigned long thread__nr_events(struct thread_trace *ttrace)
2978 {
2979         return ttrace ? ttrace->nr_events : 0;
2980 }
2981
2982 DEFINE_RESORT_RB(threads, (thread__nr_events(a->thread->priv) < thread__nr_events(b->thread->priv)),
2983         struct thread *thread;
2984 )
2985 {
2986         entry->thread = rb_entry(nd, struct thread, rb_node);
2987 }
2988
2989 static size_t trace__fprintf_thread_summary(struct trace *trace, FILE *fp)
2990 {
2991         size_t printed = trace__fprintf_threads_header(fp);
2992         struct rb_node *nd;
2993         int i;
2994
2995         for (i = 0; i < THREADS__TABLE_SIZE; i++) {
2996                 DECLARE_RESORT_RB_MACHINE_THREADS(threads, trace->host, i);
2997
2998                 if (threads == NULL) {
2999                         fprintf(fp, "%s", "Error sorting output by nr_events!\n");
3000                         return 0;
3001                 }
3002
3003                 resort_rb__for_each_entry(nd, threads)
3004                         printed += trace__fprintf_thread(fp, threads_entry->thread, trace);
3005
3006                 resort_rb__delete(threads);
3007         }
3008         return printed;
3009 }
3010
3011 static int trace__set_duration(const struct option *opt, const char *str,
3012                                int unset __maybe_unused)
3013 {
3014         struct trace *trace = opt->value;
3015
3016         trace->duration_filter = atof(str);
3017         return 0;
3018 }
3019
3020 static int trace__set_filter_pids(const struct option *opt, const char *str,
3021                                   int unset __maybe_unused)
3022 {
3023         int ret = -1;
3024         size_t i;
3025         struct trace *trace = opt->value;
3026         /*
3027          * FIXME: introduce a intarray class, plain parse csv and create a
3028          * { int nr, int entries[] } struct...
3029          */
3030         struct intlist *list = intlist__new(str);
3031
3032         if (list == NULL)
3033                 return -1;
3034
3035         i = trace->filter_pids.nr = intlist__nr_entries(list) + 1;
3036         trace->filter_pids.entries = calloc(i, sizeof(pid_t));
3037
3038         if (trace->filter_pids.entries == NULL)
3039                 goto out;
3040
3041         trace->filter_pids.entries[0] = getpid();
3042
3043         for (i = 1; i < trace->filter_pids.nr; ++i)
3044                 trace->filter_pids.entries[i] = intlist__entry(list, i - 1)->i;
3045
3046         intlist__delete(list);
3047         ret = 0;
3048 out:
3049         return ret;
3050 }
3051
3052 static int trace__open_output(struct trace *trace, const char *filename)
3053 {
3054         struct stat st;
3055
3056         if (!stat(filename, &st) && st.st_size) {
3057                 char oldname[PATH_MAX];
3058
3059                 scnprintf(oldname, sizeof(oldname), "%s.old", filename);
3060                 unlink(oldname);
3061                 rename(filename, oldname);
3062         }
3063
3064         trace->output = fopen(filename, "w");
3065
3066         return trace->output == NULL ? -errno : 0;
3067 }
3068
3069 static int parse_pagefaults(const struct option *opt, const char *str,
3070                             int unset __maybe_unused)
3071 {
3072         int *trace_pgfaults = opt->value;
3073
3074         if (strcmp(str, "all") == 0)
3075                 *trace_pgfaults |= TRACE_PFMAJ | TRACE_PFMIN;
3076         else if (strcmp(str, "maj") == 0)
3077                 *trace_pgfaults |= TRACE_PFMAJ;
3078         else if (strcmp(str, "min") == 0)
3079                 *trace_pgfaults |= TRACE_PFMIN;
3080         else
3081                 return -1;
3082
3083         return 0;
3084 }
3085
3086 static void evlist__set_evsel_handler(struct perf_evlist *evlist, void *handler)
3087 {
3088         struct perf_evsel *evsel;
3089
3090         evlist__for_each_entry(evlist, evsel)
3091                 evsel->handler = handler;
3092 }
3093
3094 static int evlist__set_syscall_tp_fields(struct perf_evlist *evlist)
3095 {
3096         struct perf_evsel *evsel;
3097
3098         evlist__for_each_entry(evlist, evsel) {
3099                 if (evsel->priv || !evsel->tp_format)
3100                         continue;
3101
3102                 if (strcmp(evsel->tp_format->system, "syscalls"))
3103                         continue;
3104
3105                 if (perf_evsel__init_syscall_tp(evsel))
3106                         return -1;
3107
3108                 if (!strncmp(evsel->tp_format->name, "sys_enter_", 10)) {
3109                         struct syscall_tp *sc = evsel->priv;
3110
3111                         if (__tp_field__init_ptr(&sc->args, sc->id.offset + sizeof(u64)))
3112                                 return -1;
3113                 } else if (!strncmp(evsel->tp_format->name, "sys_exit_", 9)) {
3114                         struct syscall_tp *sc = evsel->priv;
3115
3116                         if (__tp_field__init_uint(&sc->ret, sizeof(u64), sc->id.offset + sizeof(u64), evsel->needs_swap))
3117                                 return -1;
3118                 }
3119         }
3120
3121         return 0;
3122 }
3123
3124 /*
3125  * XXX: Hackish, just splitting the combined -e+--event (syscalls
3126  * (raw_syscalls:{sys_{enter,exit}} + events (tracepoints, HW, SW, etc) to use
3127  * existing facilities unchanged (trace->ev_qualifier + parse_options()).
3128  *
3129  * It'd be better to introduce a parse_options() variant that would return a
3130  * list with the terms it didn't match to an event...
3131  */
3132 static int trace__parse_events_option(const struct option *opt, const char *str,
3133                                       int unset __maybe_unused)
3134 {
3135         struct trace *trace = (struct trace *)opt->value;
3136         const char *s = str;
3137         char *sep = NULL, *lists[2] = { NULL, NULL, };
3138         int len = strlen(str) + 1, err = -1, list, idx;
3139         char *strace_groups_dir = system_path(STRACE_GROUPS_DIR);
3140         char group_name[PATH_MAX];
3141
3142         if (strace_groups_dir == NULL)
3143                 return -1;
3144
3145         if (*s == '!') {
3146                 ++s;
3147                 trace->not_ev_qualifier = true;
3148         }
3149
3150         while (1) {
3151                 if ((sep = strchr(s, ',')) != NULL)
3152                         *sep = '\0';
3153
3154                 list = 0;
3155                 if (syscalltbl__id(trace->sctbl, s) >= 0 ||
3156                     syscalltbl__strglobmatch_first(trace->sctbl, s, &idx) >= 0) {
3157                         list = 1;
3158                 } else {
3159                         path__join(group_name, sizeof(group_name), strace_groups_dir, s);
3160                         if (access(group_name, R_OK) == 0)
3161                                 list = 1;
3162                 }
3163
3164                 if (lists[list]) {
3165                         sprintf(lists[list] + strlen(lists[list]), ",%s", s);
3166                 } else {
3167                         lists[list] = malloc(len);
3168                         if (lists[list] == NULL)
3169                                 goto out;
3170                         strcpy(lists[list], s);
3171                 }
3172
3173                 if (!sep)
3174                         break;
3175
3176                 *sep = ',';
3177                 s = sep + 1;
3178         }
3179
3180         if (lists[1] != NULL) {
3181                 struct strlist_config slist_config = {
3182                         .dirname = strace_groups_dir,
3183                 };
3184
3185                 trace->ev_qualifier = strlist__new(lists[1], &slist_config);
3186                 if (trace->ev_qualifier == NULL) {
3187                         fputs("Not enough memory to parse event qualifier", trace->output);
3188                         goto out;
3189                 }
3190
3191                 if (trace__validate_ev_qualifier(trace))
3192                         goto out;
3193                 trace->trace_syscalls = true;
3194         }
3195
3196         err = 0;
3197
3198         if (lists[0]) {
3199                 struct option o = OPT_CALLBACK('e', "event", &trace->evlist, "event",
3200                                                "event selector. use 'perf list' to list available events",
3201                                                parse_events_option);
3202                 err = parse_events_option(&o, lists[0], 0);
3203         }
3204 out:
3205         if (sep)
3206                 *sep = ',';
3207
3208         return err;
3209 }
3210
3211 static int trace__parse_cgroups(const struct option *opt, const char *str, int unset)
3212 {
3213         struct trace *trace = opt->value;
3214
3215         if (!list_empty(&trace->evlist->entries))
3216                 return parse_cgroups(opt, str, unset);
3217
3218         trace->cgroup = evlist__findnew_cgroup(trace->evlist, str);
3219
3220         return 0;
3221 }
3222
3223 int cmd_trace(int argc, const char **argv)
3224 {
3225         const char *trace_usage[] = {
3226                 "perf trace [<options>] [<command>]",
3227                 "perf trace [<options>] -- <command> [<options>]",
3228                 "perf trace record [<options>] [<command>]",
3229                 "perf trace record [<options>] -- <command> [<options>]",
3230                 NULL
3231         };
3232         struct trace trace = {
3233                 .syscalls = {
3234                         . max = -1,
3235                 },
3236                 .opts = {
3237                         .target = {
3238                                 .uid       = UINT_MAX,
3239                                 .uses_mmap = true,
3240                         },
3241                         .user_freq     = UINT_MAX,
3242                         .user_interval = ULLONG_MAX,
3243                         .no_buffering  = true,
3244                         .mmap_pages    = UINT_MAX,
3245                         .proc_map_timeout  = 500,
3246                 },
3247                 .output = stderr,
3248                 .show_comm = true,
3249                 .trace_syscalls = false,
3250                 .kernel_syscallchains = false,
3251                 .max_stack = UINT_MAX,
3252         };
3253         const char *output_name = NULL;
3254         const struct option trace_options[] = {
3255         OPT_CALLBACK('e', "event", &trace, "event",
3256                      "event/syscall selector. use 'perf list' to list available events",
3257                      trace__parse_events_option),
3258         OPT_BOOLEAN(0, "comm", &trace.show_comm,
3259                     "show the thread COMM next to its id"),
3260         OPT_BOOLEAN(0, "tool_stats", &trace.show_tool_stats, "show tool stats"),
3261         OPT_CALLBACK(0, "expr", &trace, "expr", "list of syscalls/events to trace",
3262                      trace__parse_events_option),
3263         OPT_STRING('o', "output", &output_name, "file", "output file name"),
3264         OPT_STRING('i', "input", &input_name, "file", "Analyze events in file"),
3265         OPT_STRING('p', "pid", &trace.opts.target.pid, "pid",
3266                     "trace events on existing process id"),
3267         OPT_STRING('t', "tid", &trace.opts.target.tid, "tid",
3268                     "trace events on existing thread id"),
3269         OPT_CALLBACK(0, "filter-pids", &trace, "CSV list of pids",
3270                      "pids to filter (by the kernel)", trace__set_filter_pids),
3271         OPT_BOOLEAN('a', "all-cpus", &trace.opts.target.system_wide,
3272                     "system-wide collection from all CPUs"),
3273         OPT_STRING('C', "cpu", &trace.opts.target.cpu_list, "cpu",
3274                     "list of cpus to monitor"),
3275         OPT_BOOLEAN(0, "no-inherit", &trace.opts.no_inherit,
3276                     "child tasks do not inherit counters"),
3277         OPT_CALLBACK('m', "mmap-pages", &trace.opts.mmap_pages, "pages",
3278                      "number of mmap data pages",
3279                      perf_evlist__parse_mmap_pages),
3280         OPT_STRING('u', "uid", &trace.opts.target.uid_str, "user",
3281                    "user to profile"),
3282         OPT_CALLBACK(0, "duration", &trace, "float",
3283                      "show only events with duration > N.M ms",
3284                      trace__set_duration),
3285         OPT_BOOLEAN(0, "sched", &trace.sched, "show blocking scheduler events"),
3286         OPT_INCR('v', "verbose", &verbose, "be more verbose"),
3287         OPT_BOOLEAN('T', "time", &trace.full_time,
3288                     "Show full timestamp, not time relative to first start"),
3289         OPT_BOOLEAN(0, "failure", &trace.failure_only,
3290                     "Show only syscalls that failed"),
3291         OPT_BOOLEAN('s', "summary", &trace.summary_only,
3292                     "Show only syscall summary with statistics"),
3293         OPT_BOOLEAN('S', "with-summary", &trace.summary,
3294                     "Show all syscalls and summary with statistics"),
3295         OPT_CALLBACK_DEFAULT('F', "pf", &trace.trace_pgfaults, "all|maj|min",
3296                      "Trace pagefaults", parse_pagefaults, "maj"),
3297         OPT_BOOLEAN(0, "syscalls", &trace.trace_syscalls, "Trace syscalls"),
3298         OPT_BOOLEAN('f', "force", &trace.force, "don't complain, do it"),
3299         OPT_CALLBACK(0, "call-graph", &trace.opts,
3300                      "record_mode[,record_size]", record_callchain_help,
3301                      &record_parse_callchain_opt),
3302         OPT_BOOLEAN(0, "kernel-syscall-graph", &trace.kernel_syscallchains,
3303                     "Show the kernel callchains on the syscall exit path"),
3304         OPT_UINTEGER(0, "min-stack", &trace.min_stack,
3305                      "Set the minimum stack depth when parsing the callchain, "
3306                      "anything below the specified depth will be ignored."),
3307         OPT_UINTEGER(0, "max-stack", &trace.max_stack,
3308                      "Set the maximum stack depth when parsing the callchain, "
3309                      "anything beyond the specified depth will be ignored. "
3310                      "Default: kernel.perf_event_max_stack or " __stringify(PERF_MAX_STACK_DEPTH)),
3311         OPT_BOOLEAN(0, "print-sample", &trace.print_sample,
3312                         "print the PERF_RECORD_SAMPLE PERF_SAMPLE_ info, for debugging"),
3313         OPT_UINTEGER(0, "proc-map-timeout", &trace.opts.proc_map_timeout,
3314                         "per thread proc mmap processing timeout in ms"),
3315         OPT_CALLBACK('G', "cgroup", &trace, "name", "monitor event in cgroup name only",
3316                      trace__parse_cgroups),
3317         OPT_UINTEGER('D', "delay", &trace.opts.initial_delay,
3318                      "ms to wait before starting measurement after program "
3319                      "start"),
3320         OPT_END()
3321         };
3322         bool __maybe_unused max_stack_user_set = true;
3323         bool mmap_pages_user_set = true;
3324         struct perf_evsel *evsel;
3325         const char * const trace_subcommands[] = { "record", NULL };
3326         int err = -1;
3327         char bf[BUFSIZ];
3328
3329         signal(SIGSEGV, sighandler_dump_stack);
3330         signal(SIGFPE, sighandler_dump_stack);
3331
3332         trace.evlist = perf_evlist__new();
3333         trace.sctbl = syscalltbl__new();
3334
3335         if (trace.evlist == NULL || trace.sctbl == NULL) {
3336                 pr_err("Not enough memory to run!\n");
3337                 err = -ENOMEM;
3338                 goto out;
3339         }
3340
3341         argc = parse_options_subcommand(argc, argv, trace_options, trace_subcommands,
3342                                  trace_usage, PARSE_OPT_STOP_AT_NON_OPTION);
3343
3344         if ((nr_cgroups || trace.cgroup) && !trace.opts.target.system_wide) {
3345                 usage_with_options_msg(trace_usage, trace_options,
3346                                        "cgroup monitoring only available in system-wide mode");
3347         }
3348
3349         evsel = bpf__setup_output_event(trace.evlist, "__augmented_syscalls__");
3350         if (IS_ERR(evsel)) {
3351                 bpf__strerror_setup_output_event(trace.evlist, PTR_ERR(evsel), bf, sizeof(bf));
3352                 pr_err("ERROR: Setup trace syscalls enter failed: %s\n", bf);
3353                 goto out;
3354         }
3355
3356         if (evsel)
3357                 trace.syscalls.events.augmented = evsel;
3358
3359         err = bpf__setup_stdout(trace.evlist);
3360         if (err) {
3361                 bpf__strerror_setup_stdout(trace.evlist, err, bf, sizeof(bf));
3362                 pr_err("ERROR: Setup BPF stdout failed: %s\n", bf);
3363                 goto out;
3364         }
3365
3366         err = -1;
3367
3368         if (trace.trace_pgfaults) {
3369                 trace.opts.sample_address = true;
3370                 trace.opts.sample_time = true;
3371         }
3372
3373         if (trace.opts.mmap_pages == UINT_MAX)
3374                 mmap_pages_user_set = false;
3375
3376         if (trace.max_stack == UINT_MAX) {
3377                 trace.max_stack = input_name ? PERF_MAX_STACK_DEPTH : sysctl__max_stack();
3378                 max_stack_user_set = false;
3379         }
3380
3381 #ifdef HAVE_DWARF_UNWIND_SUPPORT
3382         if ((trace.min_stack || max_stack_user_set) && !callchain_param.enabled) {
3383                 record_opts__parse_callchain(&trace.opts, &callchain_param, "dwarf", false);
3384         }
3385 #endif
3386
3387         if (callchain_param.enabled) {
3388                 if (!mmap_pages_user_set && geteuid() == 0)
3389                         trace.opts.mmap_pages = perf_event_mlock_kb_in_pages() * 4;
3390
3391                 symbol_conf.use_callchain = true;
3392         }
3393
3394         if (trace.evlist->nr_entries > 0) {
3395                 evlist__set_evsel_handler(trace.evlist, trace__event_handler);
3396                 if (evlist__set_syscall_tp_fields(trace.evlist)) {
3397                         perror("failed to set syscalls:* tracepoint fields");
3398                         goto out;
3399                 }
3400         }
3401
3402         /*
3403          * If we are augmenting syscalls, then combine what we put in the
3404          * __augmented_syscalls__ BPF map with what is in the
3405          * syscalls:sys_exit_FOO tracepoints, i.e. just like we do without BPF,
3406          * combining raw_syscalls:sys_enter with raw_syscalls:sys_exit.
3407          *
3408          * We'll switch to look at two BPF maps, one for sys_enter and the
3409          * other for sys_exit when we start augmenting the sys_exit paths with
3410          * buffers that are being copied from kernel to userspace, think 'read'
3411          * syscall.
3412          */
3413         if (trace.syscalls.events.augmented) {
3414                 evsel = trace.syscalls.events.augmented;
3415
3416                 if (perf_evsel__init_augmented_syscall_tp(evsel) ||
3417                     perf_evsel__init_augmented_syscall_tp_args(evsel))
3418                         goto out;
3419                 evsel->handler = trace__sys_enter;
3420
3421                 evlist__for_each_entry(trace.evlist, evsel) {
3422                         if (strstarts(perf_evsel__name(evsel), "syscalls:sys_exit_")) {
3423                                 perf_evsel__init_augmented_syscall_tp(evsel);
3424                                 perf_evsel__init_augmented_syscall_tp_ret(evsel);
3425                                 evsel->handler = trace__sys_exit;
3426                         }
3427                 }
3428         }
3429
3430         if ((argc >= 1) && (strcmp(argv[0], "record") == 0))
3431                 return trace__record(&trace, argc-1, &argv[1]);
3432
3433         /* summary_only implies summary option, but don't overwrite summary if set */
3434         if (trace.summary_only)
3435                 trace.summary = trace.summary_only;
3436
3437         if (!trace.trace_syscalls && !trace.trace_pgfaults &&
3438             trace.evlist->nr_entries == 0 /* Was --events used? */) {
3439                 trace.trace_syscalls = true;
3440         }
3441
3442         if (output_name != NULL) {
3443                 err = trace__open_output(&trace, output_name);
3444                 if (err < 0) {
3445                         perror("failed to create output file");
3446                         goto out;
3447                 }
3448         }
3449
3450         err = target__validate(&trace.opts.target);
3451         if (err) {
3452                 target__strerror(&trace.opts.target, err, bf, sizeof(bf));
3453                 fprintf(trace.output, "%s", bf);
3454                 goto out_close;
3455         }
3456
3457         err = target__parse_uid(&trace.opts.target);
3458         if (err) {
3459                 target__strerror(&trace.opts.target, err, bf, sizeof(bf));
3460                 fprintf(trace.output, "%s", bf);
3461                 goto out_close;
3462         }
3463
3464         if (!argc && target__none(&trace.opts.target))
3465                 trace.opts.target.system_wide = true;
3466
3467         if (input_name)
3468                 err = trace__replay(&trace);
3469         else
3470                 err = trace__run(&trace, argc, argv);
3471
3472 out_close:
3473         if (output_name != NULL)
3474                 fclose(trace.output);
3475 out:
3476         return err;
3477 }