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