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