Merge branch 'x86/cpu' into perf/core, to pick up dependent changes
[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 struct bpf_map_syscall_entry {
975         bool    enabled;
976 };
977
978 /*
979  * We need to have this 'calculated' boolean because in some cases we really
980  * don't know what is the duration of a syscall, for instance, when we start
981  * a session and some threads are waiting for a syscall to finish, say 'poll',
982  * in which case all we can do is to print "( ? ) for duration and for the
983  * start timestamp.
984  */
985 static size_t fprintf_duration(unsigned long t, bool calculated, FILE *fp)
986 {
987         double duration = (double)t / NSEC_PER_MSEC;
988         size_t printed = fprintf(fp, "(");
989
990         if (!calculated)
991                 printed += fprintf(fp, "         ");
992         else if (duration >= 1.0)
993                 printed += color_fprintf(fp, PERF_COLOR_RED, "%6.3f ms", duration);
994         else if (duration >= 0.01)
995                 printed += color_fprintf(fp, PERF_COLOR_YELLOW, "%6.3f ms", duration);
996         else
997                 printed += color_fprintf(fp, PERF_COLOR_NORMAL, "%6.3f ms", duration);
998         return printed + fprintf(fp, "): ");
999 }
1000
1001 /**
1002  * filename.ptr: The filename char pointer that will be vfs_getname'd
1003  * filename.entry_str_pos: Where to insert the string translated from
1004  *                         filename.ptr by the vfs_getname tracepoint/kprobe.
1005  * ret_scnprintf: syscall args may set this to a different syscall return
1006  *                formatter, for instance, fcntl may return fds, file flags, etc.
1007  */
1008 struct thread_trace {
1009         u64               entry_time;
1010         bool              entry_pending;
1011         unsigned long     nr_events;
1012         unsigned long     pfmaj, pfmin;
1013         char              *entry_str;
1014         double            runtime_ms;
1015         size_t            (*ret_scnprintf)(char *bf, size_t size, struct syscall_arg *arg);
1016         struct {
1017                 unsigned long ptr;
1018                 short int     entry_str_pos;
1019                 bool          pending_open;
1020                 unsigned int  namelen;
1021                 char          *name;
1022         } filename;
1023         struct {
1024                 int           max;
1025                 struct file   *table;
1026         } files;
1027
1028         struct intlist *syscall_stats;
1029 };
1030
1031 static struct thread_trace *thread_trace__new(void)
1032 {
1033         struct thread_trace *ttrace =  zalloc(sizeof(struct thread_trace));
1034
1035         if (ttrace)
1036                 ttrace->files.max = -1;
1037
1038         ttrace->syscall_stats = intlist__new(NULL);
1039
1040         return ttrace;
1041 }
1042
1043 static struct thread_trace *thread__trace(struct thread *thread, FILE *fp)
1044 {
1045         struct thread_trace *ttrace;
1046
1047         if (thread == NULL)
1048                 goto fail;
1049
1050         if (thread__priv(thread) == NULL)
1051                 thread__set_priv(thread, thread_trace__new());
1052
1053         if (thread__priv(thread) == NULL)
1054                 goto fail;
1055
1056         ttrace = thread__priv(thread);
1057         ++ttrace->nr_events;
1058
1059         return ttrace;
1060 fail:
1061         color_fprintf(fp, PERF_COLOR_RED,
1062                       "WARNING: not enough memory, dropping samples!\n");
1063         return NULL;
1064 }
1065
1066
1067 void syscall_arg__set_ret_scnprintf(struct syscall_arg *arg,
1068                                     size_t (*ret_scnprintf)(char *bf, size_t size, struct syscall_arg *arg))
1069 {
1070         struct thread_trace *ttrace = thread__priv(arg->thread);
1071
1072         ttrace->ret_scnprintf = ret_scnprintf;
1073 }
1074
1075 #define TRACE_PFMAJ             (1 << 0)
1076 #define TRACE_PFMIN             (1 << 1)
1077
1078 static const size_t trace__entry_str_size = 2048;
1079
1080 static struct file *thread_trace__files_entry(struct thread_trace *ttrace, int fd)
1081 {
1082         if (fd < 0)
1083                 return NULL;
1084
1085         if (fd > ttrace->files.max) {
1086                 struct file *nfiles = realloc(ttrace->files.table, (fd + 1) * sizeof(struct file));
1087
1088                 if (nfiles == NULL)
1089                         return NULL;
1090
1091                 if (ttrace->files.max != -1) {
1092                         memset(nfiles + ttrace->files.max + 1, 0,
1093                                (fd - ttrace->files.max) * sizeof(struct file));
1094                 } else {
1095                         memset(nfiles, 0, (fd + 1) * sizeof(struct file));
1096                 }
1097
1098                 ttrace->files.table = nfiles;
1099                 ttrace->files.max   = fd;
1100         }
1101
1102         return ttrace->files.table + fd;
1103 }
1104
1105 struct file *thread__files_entry(struct thread *thread, int fd)
1106 {
1107         return thread_trace__files_entry(thread__priv(thread), fd);
1108 }
1109
1110 static int trace__set_fd_pathname(struct thread *thread, int fd, const char *pathname)
1111 {
1112         struct thread_trace *ttrace = thread__priv(thread);
1113         struct file *file = thread_trace__files_entry(ttrace, fd);
1114
1115         if (file != NULL) {
1116                 struct stat st;
1117                 if (stat(pathname, &st) == 0)
1118                         file->dev_maj = major(st.st_rdev);
1119                 file->pathname = strdup(pathname);
1120                 if (file->pathname)
1121                         return 0;
1122         }
1123
1124         return -1;
1125 }
1126
1127 static int thread__read_fd_path(struct thread *thread, int fd)
1128 {
1129         char linkname[PATH_MAX], pathname[PATH_MAX];
1130         struct stat st;
1131         int ret;
1132
1133         if (thread->pid_ == thread->tid) {
1134                 scnprintf(linkname, sizeof(linkname),
1135                           "/proc/%d/fd/%d", thread->pid_, fd);
1136         } else {
1137                 scnprintf(linkname, sizeof(linkname),
1138                           "/proc/%d/task/%d/fd/%d", thread->pid_, thread->tid, fd);
1139         }
1140
1141         if (lstat(linkname, &st) < 0 || st.st_size + 1 > (off_t)sizeof(pathname))
1142                 return -1;
1143
1144         ret = readlink(linkname, pathname, sizeof(pathname));
1145
1146         if (ret < 0 || ret > st.st_size)
1147                 return -1;
1148
1149         pathname[ret] = '\0';
1150         return trace__set_fd_pathname(thread, fd, pathname);
1151 }
1152
1153 static const char *thread__fd_path(struct thread *thread, int fd,
1154                                    struct trace *trace)
1155 {
1156         struct thread_trace *ttrace = thread__priv(thread);
1157
1158         if (ttrace == NULL)
1159                 return NULL;
1160
1161         if (fd < 0)
1162                 return NULL;
1163
1164         if ((fd > ttrace->files.max || ttrace->files.table[fd].pathname == NULL)) {
1165                 if (!trace->live)
1166                         return NULL;
1167                 ++trace->stats.proc_getname;
1168                 if (thread__read_fd_path(thread, fd))
1169                         return NULL;
1170         }
1171
1172         return ttrace->files.table[fd].pathname;
1173 }
1174
1175 size_t syscall_arg__scnprintf_fd(char *bf, size_t size, struct syscall_arg *arg)
1176 {
1177         int fd = arg->val;
1178         size_t printed = scnprintf(bf, size, "%d", fd);
1179         const char *path = thread__fd_path(arg->thread, fd, arg->trace);
1180
1181         if (path)
1182                 printed += scnprintf(bf + printed, size - printed, "<%s>", path);
1183
1184         return printed;
1185 }
1186
1187 size_t pid__scnprintf_fd(struct trace *trace, pid_t pid, int fd, char *bf, size_t size)
1188 {
1189         size_t printed = scnprintf(bf, size, "%d", fd);
1190         struct thread *thread = machine__find_thread(trace->host, pid, pid);
1191
1192         if (thread) {
1193                 const char *path = thread__fd_path(thread, fd, trace);
1194
1195                 if (path)
1196                         printed += scnprintf(bf + printed, size - printed, "<%s>", path);
1197
1198                 thread__put(thread);
1199         }
1200
1201         return printed;
1202 }
1203
1204 static size_t syscall_arg__scnprintf_close_fd(char *bf, size_t size,
1205                                               struct syscall_arg *arg)
1206 {
1207         int fd = arg->val;
1208         size_t printed = syscall_arg__scnprintf_fd(bf, size, arg);
1209         struct thread_trace *ttrace = thread__priv(arg->thread);
1210
1211         if (ttrace && fd >= 0 && fd <= ttrace->files.max)
1212                 zfree(&ttrace->files.table[fd].pathname);
1213
1214         return printed;
1215 }
1216
1217 static void thread__set_filename_pos(struct thread *thread, const char *bf,
1218                                      unsigned long ptr)
1219 {
1220         struct thread_trace *ttrace = thread__priv(thread);
1221
1222         ttrace->filename.ptr = ptr;
1223         ttrace->filename.entry_str_pos = bf - ttrace->entry_str;
1224 }
1225
1226 static size_t syscall_arg__scnprintf_augmented_string(struct syscall_arg *arg, char *bf, size_t size)
1227 {
1228         struct augmented_arg *augmented_arg = arg->augmented.args;
1229
1230         return scnprintf(bf, size, "\"%.*s\"", augmented_arg->size, augmented_arg->value);
1231 }
1232
1233 static size_t syscall_arg__scnprintf_filename(char *bf, size_t size,
1234                                               struct syscall_arg *arg)
1235 {
1236         unsigned long ptr = arg->val;
1237
1238         if (arg->augmented.args)
1239                 return syscall_arg__scnprintf_augmented_string(arg, bf, size);
1240
1241         if (!arg->trace->vfs_getname)
1242                 return scnprintf(bf, size, "%#x", ptr);
1243
1244         thread__set_filename_pos(arg->thread, bf, ptr);
1245         return 0;
1246 }
1247
1248 static bool trace__filter_duration(struct trace *trace, double t)
1249 {
1250         return t < (trace->duration_filter * NSEC_PER_MSEC);
1251 }
1252
1253 static size_t __trace__fprintf_tstamp(struct trace *trace, u64 tstamp, FILE *fp)
1254 {
1255         double ts = (double)(tstamp - trace->base_time) / NSEC_PER_MSEC;
1256
1257         return fprintf(fp, "%10.3f ", ts);
1258 }
1259
1260 /*
1261  * We're handling tstamp=0 as an undefined tstamp, i.e. like when we are
1262  * using ttrace->entry_time for a thread that receives a sys_exit without
1263  * first having received a sys_enter ("poll" issued before tracing session
1264  * starts, lost sys_enter exit due to ring buffer overflow).
1265  */
1266 static size_t trace__fprintf_tstamp(struct trace *trace, u64 tstamp, FILE *fp)
1267 {
1268         if (tstamp > 0)
1269                 return __trace__fprintf_tstamp(trace, tstamp, fp);
1270
1271         return fprintf(fp, "         ? ");
1272 }
1273
1274 static bool done = false;
1275 static bool interrupted = false;
1276
1277 static void sig_handler(int sig)
1278 {
1279         done = true;
1280         interrupted = sig == SIGINT;
1281 }
1282
1283 static size_t trace__fprintf_comm_tid(struct trace *trace, struct thread *thread, FILE *fp)
1284 {
1285         size_t printed = 0;
1286
1287         if (trace->multiple_threads) {
1288                 if (trace->show_comm)
1289                         printed += fprintf(fp, "%.14s/", thread__comm_str(thread));
1290                 printed += fprintf(fp, "%d ", thread->tid);
1291         }
1292
1293         return printed;
1294 }
1295
1296 static size_t trace__fprintf_entry_head(struct trace *trace, struct thread *thread,
1297                                         u64 duration, bool duration_calculated, u64 tstamp, FILE *fp)
1298 {
1299         size_t printed = 0;
1300
1301         if (trace->show_tstamp)
1302                 printed = trace__fprintf_tstamp(trace, tstamp, fp);
1303         if (trace->show_duration)
1304                 printed += fprintf_duration(duration, duration_calculated, fp);
1305         return printed + trace__fprintf_comm_tid(trace, thread, fp);
1306 }
1307
1308 static int trace__process_event(struct trace *trace, struct machine *machine,
1309                                 union perf_event *event, struct perf_sample *sample)
1310 {
1311         int ret = 0;
1312
1313         switch (event->header.type) {
1314         case PERF_RECORD_LOST:
1315                 color_fprintf(trace->output, PERF_COLOR_RED,
1316                               "LOST %" PRIu64 " events!\n", event->lost.lost);
1317                 ret = machine__process_lost_event(machine, event, sample);
1318                 break;
1319         default:
1320                 ret = machine__process_event(machine, event, sample);
1321                 break;
1322         }
1323
1324         return ret;
1325 }
1326
1327 static int trace__tool_process(struct perf_tool *tool,
1328                                union perf_event *event,
1329                                struct perf_sample *sample,
1330                                struct machine *machine)
1331 {
1332         struct trace *trace = container_of(tool, struct trace, tool);
1333         return trace__process_event(trace, machine, event, sample);
1334 }
1335
1336 static char *trace__machine__resolve_kernel_addr(void *vmachine, unsigned long long *addrp, char **modp)
1337 {
1338         struct machine *machine = vmachine;
1339
1340         if (machine->kptr_restrict_warned)
1341                 return NULL;
1342
1343         if (symbol_conf.kptr_restrict) {
1344                 pr_warning("Kernel address maps (/proc/{kallsyms,modules}) are restricted.\n\n"
1345                            "Check /proc/sys/kernel/kptr_restrict.\n\n"
1346                            "Kernel samples will not be resolved.\n");
1347                 machine->kptr_restrict_warned = true;
1348                 return NULL;
1349         }
1350
1351         return machine__resolve_kernel_addr(vmachine, addrp, modp);
1352 }
1353
1354 static int trace__symbols_init(struct trace *trace, struct perf_evlist *evlist)
1355 {
1356         int err = symbol__init(NULL);
1357
1358         if (err)
1359                 return err;
1360
1361         trace->host = machine__new_host();
1362         if (trace->host == NULL)
1363                 return -ENOMEM;
1364
1365         err = trace_event__register_resolver(trace->host, trace__machine__resolve_kernel_addr);
1366         if (err < 0)
1367                 goto out;
1368
1369         err = __machine__synthesize_threads(trace->host, &trace->tool, &trace->opts.target,
1370                                             evlist->threads, trace__tool_process, false,
1371                                             1);
1372 out:
1373         if (err)
1374                 symbol__exit();
1375
1376         return err;
1377 }
1378
1379 static void trace__symbols__exit(struct trace *trace)
1380 {
1381         machine__exit(trace->host);
1382         trace->host = NULL;
1383
1384         symbol__exit();
1385 }
1386
1387 static int syscall__alloc_arg_fmts(struct syscall *sc, int nr_args)
1388 {
1389         int idx;
1390
1391         if (nr_args == 6 && sc->fmt && sc->fmt->nr_args != 0)
1392                 nr_args = sc->fmt->nr_args;
1393
1394         sc->arg_fmt = calloc(nr_args, sizeof(*sc->arg_fmt));
1395         if (sc->arg_fmt == NULL)
1396                 return -1;
1397
1398         for (idx = 0; idx < nr_args; ++idx) {
1399                 if (sc->fmt)
1400                         sc->arg_fmt[idx] = sc->fmt->arg[idx];
1401         }
1402
1403         sc->nr_args = nr_args;
1404         return 0;
1405 }
1406
1407 static int syscall__set_arg_fmts(struct syscall *sc)
1408 {
1409         struct tep_format_field *field, *last_field = NULL;
1410         int idx = 0, len;
1411
1412         for (field = sc->args; field; field = field->next, ++idx) {
1413                 last_field = field;
1414
1415                 if (sc->fmt && sc->fmt->arg[idx].scnprintf)
1416                         continue;
1417
1418                 if (strcmp(field->type, "const char *") == 0 &&
1419                          (strcmp(field->name, "filename") == 0 ||
1420                           strcmp(field->name, "path") == 0 ||
1421                           strcmp(field->name, "pathname") == 0))
1422                         sc->arg_fmt[idx].scnprintf = SCA_FILENAME;
1423                 else if ((field->flags & TEP_FIELD_IS_POINTER) || strstr(field->name, "addr"))
1424                         sc->arg_fmt[idx].scnprintf = SCA_PTR;
1425                 else if (strcmp(field->type, "pid_t") == 0)
1426                         sc->arg_fmt[idx].scnprintf = SCA_PID;
1427                 else if (strcmp(field->type, "umode_t") == 0)
1428                         sc->arg_fmt[idx].scnprintf = SCA_MODE_T;
1429                 else if ((strcmp(field->type, "int") == 0 ||
1430                           strcmp(field->type, "unsigned int") == 0 ||
1431                           strcmp(field->type, "long") == 0) &&
1432                          (len = strlen(field->name)) >= 2 &&
1433                          strcmp(field->name + len - 2, "fd") == 0) {
1434                         /*
1435                          * /sys/kernel/tracing/events/syscalls/sys_enter*
1436                          * egrep 'field:.*fd;' .../format|sed -r 's/.*field:([a-z ]+) [a-z_]*fd.+/\1/g'|sort|uniq -c
1437                          * 65 int
1438                          * 23 unsigned int
1439                          * 7 unsigned long
1440                          */
1441                         sc->arg_fmt[idx].scnprintf = SCA_FD;
1442                 }
1443         }
1444
1445         if (last_field)
1446                 sc->args_size = last_field->offset + last_field->size;
1447
1448         return 0;
1449 }
1450
1451 static int trace__read_syscall_info(struct trace *trace, int id)
1452 {
1453         char tp_name[128];
1454         struct syscall *sc;
1455         const char *name = syscalltbl__name(trace->sctbl, id);
1456
1457         if (name == NULL)
1458                 return -1;
1459
1460         if (id > trace->syscalls.max) {
1461                 struct syscall *nsyscalls = realloc(trace->syscalls.table, (id + 1) * sizeof(*sc));
1462
1463                 if (nsyscalls == NULL)
1464                         return -1;
1465
1466                 if (trace->syscalls.max != -1) {
1467                         memset(nsyscalls + trace->syscalls.max + 1, 0,
1468                                (id - trace->syscalls.max) * sizeof(*sc));
1469                 } else {
1470                         memset(nsyscalls, 0, (id + 1) * sizeof(*sc));
1471                 }
1472
1473                 trace->syscalls.table = nsyscalls;
1474                 trace->syscalls.max   = id;
1475         }
1476
1477         sc = trace->syscalls.table + id;
1478         sc->name = name;
1479
1480         sc->fmt  = syscall_fmt__find(sc->name);
1481
1482         snprintf(tp_name, sizeof(tp_name), "sys_enter_%s", sc->name);
1483         sc->tp_format = trace_event__tp_format("syscalls", tp_name);
1484
1485         if (IS_ERR(sc->tp_format) && sc->fmt && sc->fmt->alias) {
1486                 snprintf(tp_name, sizeof(tp_name), "sys_enter_%s", sc->fmt->alias);
1487                 sc->tp_format = trace_event__tp_format("syscalls", tp_name);
1488         }
1489
1490         if (syscall__alloc_arg_fmts(sc, IS_ERR(sc->tp_format) ? 6 : sc->tp_format->format.nr_fields))
1491                 return -1;
1492
1493         if (IS_ERR(sc->tp_format))
1494                 return -1;
1495
1496         sc->args = sc->tp_format->format.fields;
1497         /*
1498          * We need to check and discard the first variable '__syscall_nr'
1499          * or 'nr' that mean the syscall number. It is needless here.
1500          * So drop '__syscall_nr' or 'nr' field but does not exist on older kernels.
1501          */
1502         if (sc->args && (!strcmp(sc->args->name, "__syscall_nr") || !strcmp(sc->args->name, "nr"))) {
1503                 sc->args = sc->args->next;
1504                 --sc->nr_args;
1505         }
1506
1507         sc->is_exit = !strcmp(name, "exit_group") || !strcmp(name, "exit");
1508         sc->is_open = !strcmp(name, "open") || !strcmp(name, "openat");
1509
1510         return syscall__set_arg_fmts(sc);
1511 }
1512
1513 static int trace__validate_ev_qualifier(struct trace *trace)
1514 {
1515         int err = 0, i;
1516         size_t nr_allocated;
1517         struct str_node *pos;
1518
1519         trace->ev_qualifier_ids.nr = strlist__nr_entries(trace->ev_qualifier);
1520         trace->ev_qualifier_ids.entries = malloc(trace->ev_qualifier_ids.nr *
1521                                                  sizeof(trace->ev_qualifier_ids.entries[0]));
1522
1523         if (trace->ev_qualifier_ids.entries == NULL) {
1524                 fputs("Error:\tNot enough memory for allocating events qualifier ids\n",
1525                        trace->output);
1526                 err = -EINVAL;
1527                 goto out;
1528         }
1529
1530         nr_allocated = trace->ev_qualifier_ids.nr;
1531         i = 0;
1532
1533         strlist__for_each_entry(pos, trace->ev_qualifier) {
1534                 const char *sc = pos->s;
1535                 int id = syscalltbl__id(trace->sctbl, sc), match_next = -1;
1536
1537                 if (id < 0) {
1538                         id = syscalltbl__strglobmatch_first(trace->sctbl, sc, &match_next);
1539                         if (id >= 0)
1540                                 goto matches;
1541
1542                         if (err == 0) {
1543                                 fputs("Error:\tInvalid syscall ", trace->output);
1544                                 err = -EINVAL;
1545                         } else {
1546                                 fputs(", ", trace->output);
1547                         }
1548
1549                         fputs(sc, trace->output);
1550                 }
1551 matches:
1552                 trace->ev_qualifier_ids.entries[i++] = id;
1553                 if (match_next == -1)
1554                         continue;
1555
1556                 while (1) {
1557                         id = syscalltbl__strglobmatch_next(trace->sctbl, sc, &match_next);
1558                         if (id < 0)
1559                                 break;
1560                         if (nr_allocated == trace->ev_qualifier_ids.nr) {
1561                                 void *entries;
1562
1563                                 nr_allocated += 8;
1564                                 entries = realloc(trace->ev_qualifier_ids.entries,
1565                                                   nr_allocated * sizeof(trace->ev_qualifier_ids.entries[0]));
1566                                 if (entries == NULL) {
1567                                         err = -ENOMEM;
1568                                         fputs("\nError:\t Not enough memory for parsing\n", trace->output);
1569                                         goto out_free;
1570                                 }
1571                                 trace->ev_qualifier_ids.entries = entries;
1572                         }
1573                         trace->ev_qualifier_ids.nr++;
1574                         trace->ev_qualifier_ids.entries[i++] = id;
1575                 }
1576         }
1577
1578         if (err < 0) {
1579                 fputs("\nHint:\ttry 'perf list syscalls:sys_enter_*'"
1580                       "\nHint:\tand: 'man syscalls'\n", trace->output);
1581 out_free:
1582                 zfree(&trace->ev_qualifier_ids.entries);
1583                 trace->ev_qualifier_ids.nr = 0;
1584         }
1585 out:
1586         return err;
1587 }
1588
1589 /*
1590  * args is to be interpreted as a series of longs but we need to handle
1591  * 8-byte unaligned accesses. args points to raw_data within the event
1592  * and raw_data is guaranteed to be 8-byte unaligned because it is
1593  * preceded by raw_size which is a u32. So we need to copy args to a temp
1594  * variable to read it. Most notably this avoids extended load instructions
1595  * on unaligned addresses
1596  */
1597 unsigned long syscall_arg__val(struct syscall_arg *arg, u8 idx)
1598 {
1599         unsigned long val;
1600         unsigned char *p = arg->args + sizeof(unsigned long) * idx;
1601
1602         memcpy(&val, p, sizeof(val));
1603         return val;
1604 }
1605
1606 static size_t syscall__scnprintf_name(struct syscall *sc, char *bf, size_t size,
1607                                       struct syscall_arg *arg)
1608 {
1609         if (sc->arg_fmt && sc->arg_fmt[arg->idx].name)
1610                 return scnprintf(bf, size, "%s: ", sc->arg_fmt[arg->idx].name);
1611
1612         return scnprintf(bf, size, "arg%d: ", arg->idx);
1613 }
1614
1615 /*
1616  * Check if the value is in fact zero, i.e. mask whatever needs masking, such
1617  * as mount 'flags' argument that needs ignoring some magic flag, see comment
1618  * in tools/perf/trace/beauty/mount_flags.c
1619  */
1620 static unsigned long syscall__mask_val(struct syscall *sc, struct syscall_arg *arg, unsigned long val)
1621 {
1622         if (sc->arg_fmt && sc->arg_fmt[arg->idx].mask_val)
1623                 return sc->arg_fmt[arg->idx].mask_val(arg, val);
1624
1625         return val;
1626 }
1627
1628 static size_t syscall__scnprintf_val(struct syscall *sc, char *bf, size_t size,
1629                                      struct syscall_arg *arg, unsigned long val)
1630 {
1631         if (sc->arg_fmt && sc->arg_fmt[arg->idx].scnprintf) {
1632                 arg->val = val;
1633                 if (sc->arg_fmt[arg->idx].parm)
1634                         arg->parm = sc->arg_fmt[arg->idx].parm;
1635                 return sc->arg_fmt[arg->idx].scnprintf(bf, size, arg);
1636         }
1637         return scnprintf(bf, size, "%ld", val);
1638 }
1639
1640 static size_t syscall__scnprintf_args(struct syscall *sc, char *bf, size_t size,
1641                                       unsigned char *args, void *augmented_args, int augmented_args_size,
1642                                       struct trace *trace, struct thread *thread)
1643 {
1644         size_t printed = 0;
1645         unsigned long val;
1646         u8 bit = 1;
1647         struct syscall_arg arg = {
1648                 .args   = args,
1649                 .augmented = {
1650                         .size = augmented_args_size,
1651                         .args = augmented_args,
1652                 },
1653                 .idx    = 0,
1654                 .mask   = 0,
1655                 .trace  = trace,
1656                 .thread = thread,
1657                 .show_string_prefix = trace->show_string_prefix,
1658         };
1659         struct thread_trace *ttrace = thread__priv(thread);
1660
1661         /*
1662          * Things like fcntl will set this in its 'cmd' formatter to pick the
1663          * right formatter for the return value (an fd? file flags?), which is
1664          * not needed for syscalls that always return a given type, say an fd.
1665          */
1666         ttrace->ret_scnprintf = NULL;
1667
1668         if (sc->args != NULL) {
1669                 struct tep_format_field *field;
1670
1671                 for (field = sc->args; field;
1672                      field = field->next, ++arg.idx, bit <<= 1) {
1673                         if (arg.mask & bit)
1674                                 continue;
1675
1676                         val = syscall_arg__val(&arg, arg.idx);
1677                         /*
1678                          * Some syscall args need some mask, most don't and
1679                          * return val untouched.
1680                          */
1681                         val = syscall__mask_val(sc, &arg, val);
1682
1683                         /*
1684                          * Suppress this argument if its value is zero and
1685                          * and we don't have a string associated in an
1686                          * strarray for it.
1687                          */
1688                         if (val == 0 &&
1689                             !trace->show_zeros &&
1690                             !(sc->arg_fmt &&
1691                               (sc->arg_fmt[arg.idx].show_zero ||
1692                                sc->arg_fmt[arg.idx].scnprintf == SCA_STRARRAY ||
1693                                sc->arg_fmt[arg.idx].scnprintf == SCA_STRARRAYS) &&
1694                               sc->arg_fmt[arg.idx].parm))
1695                                 continue;
1696
1697                         printed += scnprintf(bf + printed, size - printed, "%s", printed ? ", " : "");
1698
1699                         if (trace->show_arg_names)
1700                                 printed += scnprintf(bf + printed, size - printed, "%s: ", field->name);
1701
1702                         printed += syscall__scnprintf_val(sc, bf + printed, size - printed, &arg, val);
1703                 }
1704         } else if (IS_ERR(sc->tp_format)) {
1705                 /*
1706                  * If we managed to read the tracepoint /format file, then we
1707                  * may end up not having any args, like with gettid(), so only
1708                  * print the raw args when we didn't manage to read it.
1709                  */
1710                 while (arg.idx < sc->nr_args) {
1711                         if (arg.mask & bit)
1712                                 goto next_arg;
1713                         val = syscall_arg__val(&arg, arg.idx);
1714                         if (printed)
1715                                 printed += scnprintf(bf + printed, size - printed, ", ");
1716                         printed += syscall__scnprintf_name(sc, bf + printed, size - printed, &arg);
1717                         printed += syscall__scnprintf_val(sc, bf + printed, size - printed, &arg, val);
1718 next_arg:
1719                         ++arg.idx;
1720                         bit <<= 1;
1721                 }
1722         }
1723
1724         return printed;
1725 }
1726
1727 typedef int (*tracepoint_handler)(struct trace *trace, struct perf_evsel *evsel,
1728                                   union perf_event *event,
1729                                   struct perf_sample *sample);
1730
1731 static struct syscall *trace__syscall_info(struct trace *trace,
1732                                            struct perf_evsel *evsel, int id)
1733 {
1734
1735         if (id < 0) {
1736
1737                 /*
1738                  * XXX: Noticed on x86_64, reproduced as far back as 3.0.36, haven't tried
1739                  * before that, leaving at a higher verbosity level till that is
1740                  * explained. Reproduced with plain ftrace with:
1741                  *
1742                  * echo 1 > /t/events/raw_syscalls/sys_exit/enable
1743                  * grep "NR -1 " /t/trace_pipe
1744                  *
1745                  * After generating some load on the machine.
1746                  */
1747                 if (verbose > 1) {
1748                         static u64 n;
1749                         fprintf(trace->output, "Invalid syscall %d id, skipping (%s, %" PRIu64 ") ...\n",
1750                                 id, perf_evsel__name(evsel), ++n);
1751                 }
1752                 return NULL;
1753         }
1754
1755         if ((id > trace->syscalls.max || trace->syscalls.table[id].name == NULL) &&
1756             trace__read_syscall_info(trace, id))
1757                 goto out_cant_read;
1758
1759         if ((id > trace->syscalls.max || trace->syscalls.table[id].name == NULL))
1760                 goto out_cant_read;
1761
1762         return &trace->syscalls.table[id];
1763
1764 out_cant_read:
1765         if (verbose > 0) {
1766                 fprintf(trace->output, "Problems reading syscall %d", id);
1767                 if (id <= trace->syscalls.max && trace->syscalls.table[id].name != NULL)
1768                         fprintf(trace->output, "(%s)", trace->syscalls.table[id].name);
1769                 fputs(" information\n", trace->output);
1770         }
1771         return NULL;
1772 }
1773
1774 static void thread__update_stats(struct thread_trace *ttrace,
1775                                  int id, struct perf_sample *sample)
1776 {
1777         struct int_node *inode;
1778         struct stats *stats;
1779         u64 duration = 0;
1780
1781         inode = intlist__findnew(ttrace->syscall_stats, id);
1782         if (inode == NULL)
1783                 return;
1784
1785         stats = inode->priv;
1786         if (stats == NULL) {
1787                 stats = malloc(sizeof(struct stats));
1788                 if (stats == NULL)
1789                         return;
1790                 init_stats(stats);
1791                 inode->priv = stats;
1792         }
1793
1794         if (ttrace->entry_time && sample->time > ttrace->entry_time)
1795                 duration = sample->time - ttrace->entry_time;
1796
1797         update_stats(stats, duration);
1798 }
1799
1800 static int trace__printf_interrupted_entry(struct trace *trace)
1801 {
1802         struct thread_trace *ttrace;
1803         size_t printed;
1804         int len;
1805
1806         if (trace->failure_only || trace->current == NULL)
1807                 return 0;
1808
1809         ttrace = thread__priv(trace->current);
1810
1811         if (!ttrace->entry_pending)
1812                 return 0;
1813
1814         printed  = trace__fprintf_entry_head(trace, trace->current, 0, false, ttrace->entry_time, trace->output);
1815         printed += len = fprintf(trace->output, "%s)", ttrace->entry_str);
1816
1817         if (len < trace->args_alignment - 4)
1818                 printed += fprintf(trace->output, "%-*s", trace->args_alignment - 4 - len, " ");
1819
1820         printed += fprintf(trace->output, " ...\n");
1821
1822         ttrace->entry_pending = false;
1823         ++trace->nr_events_printed;
1824
1825         return printed;
1826 }
1827
1828 static int trace__fprintf_sample(struct trace *trace, struct perf_evsel *evsel,
1829                                  struct perf_sample *sample, struct thread *thread)
1830 {
1831         int printed = 0;
1832
1833         if (trace->print_sample) {
1834                 double ts = (double)sample->time / NSEC_PER_MSEC;
1835
1836                 printed += fprintf(trace->output, "%22s %10.3f %s %d/%d [%d]\n",
1837                                    perf_evsel__name(evsel), ts,
1838                                    thread__comm_str(thread),
1839                                    sample->pid, sample->tid, sample->cpu);
1840         }
1841
1842         return printed;
1843 }
1844
1845 static void *syscall__augmented_args(struct syscall *sc, struct perf_sample *sample, int *augmented_args_size, int raw_augmented_args_size)
1846 {
1847         void *augmented_args = NULL;
1848         /*
1849          * For now with BPF raw_augmented we hook into raw_syscalls:sys_enter
1850          * and there we get all 6 syscall args plus the tracepoint common fields
1851          * that gets calculated at the start and the syscall_nr (another long).
1852          * So we check if that is the case and if so don't look after the
1853          * sc->args_size but always after the full raw_syscalls:sys_enter payload,
1854          * which is fixed.
1855          *
1856          * We'll revisit this later to pass s->args_size to the BPF augmenter
1857          * (now tools/perf/examples/bpf/augmented_raw_syscalls.c, so that it
1858          * copies only what we need for each syscall, like what happens when we
1859          * use syscalls:sys_enter_NAME, so that we reduce the kernel/userspace
1860          * traffic to just what is needed for each syscall.
1861          */
1862         int args_size = raw_augmented_args_size ?: sc->args_size;
1863
1864         *augmented_args_size = sample->raw_size - args_size;
1865         if (*augmented_args_size > 0)
1866                 augmented_args = sample->raw_data + args_size;
1867
1868         return augmented_args;
1869 }
1870
1871 static int trace__sys_enter(struct trace *trace, struct perf_evsel *evsel,
1872                             union perf_event *event __maybe_unused,
1873                             struct perf_sample *sample)
1874 {
1875         char *msg;
1876         void *args;
1877         int printed = 0;
1878         struct thread *thread;
1879         int id = perf_evsel__sc_tp_uint(evsel, id, sample), err = -1;
1880         int augmented_args_size = 0;
1881         void *augmented_args = NULL;
1882         struct syscall *sc = trace__syscall_info(trace, evsel, id);
1883         struct thread_trace *ttrace;
1884
1885         if (sc == NULL)
1886                 return -1;
1887
1888         thread = machine__findnew_thread(trace->host, sample->pid, sample->tid);
1889         ttrace = thread__trace(thread, trace->output);
1890         if (ttrace == NULL)
1891                 goto out_put;
1892
1893         trace__fprintf_sample(trace, evsel, sample, thread);
1894
1895         args = perf_evsel__sc_tp_ptr(evsel, args, sample);
1896
1897         if (ttrace->entry_str == NULL) {
1898                 ttrace->entry_str = malloc(trace__entry_str_size);
1899                 if (!ttrace->entry_str)
1900                         goto out_put;
1901         }
1902
1903         if (!(trace->duration_filter || trace->summary_only || trace->min_stack))
1904                 trace__printf_interrupted_entry(trace);
1905         /*
1906          * If this is raw_syscalls.sys_enter, then it always comes with the 6 possible
1907          * arguments, even if the syscall being handled, say "openat", uses only 4 arguments
1908          * this breaks syscall__augmented_args() check for augmented args, as we calculate
1909          * syscall->args_size using each syscalls:sys_enter_NAME tracefs format file,
1910          * so when handling, say the openat syscall, we end up getting 6 args for the
1911          * raw_syscalls:sys_enter event, when we expected just 4, we end up mistakenly
1912          * thinking that the extra 2 u64 args are the augmented filename, so just check
1913          * here and avoid using augmented syscalls when the evsel is the raw_syscalls one.
1914          */
1915         if (evsel != trace->syscalls.events.sys_enter)
1916                 augmented_args = syscall__augmented_args(sc, sample, &augmented_args_size, trace->raw_augmented_syscalls_args_size);
1917         ttrace->entry_time = sample->time;
1918         msg = ttrace->entry_str;
1919         printed += scnprintf(msg + printed, trace__entry_str_size - printed, "%s(", sc->name);
1920
1921         printed += syscall__scnprintf_args(sc, msg + printed, trace__entry_str_size - printed,
1922                                            args, augmented_args, augmented_args_size, trace, thread);
1923
1924         if (sc->is_exit) {
1925                 if (!(trace->duration_filter || trace->summary_only || trace->failure_only || trace->min_stack)) {
1926                         int alignment = 0;
1927
1928                         trace__fprintf_entry_head(trace, thread, 0, false, ttrace->entry_time, trace->output);
1929                         printed = fprintf(trace->output, "%s)", ttrace->entry_str);
1930                         if (trace->args_alignment > printed)
1931                                 alignment = trace->args_alignment - printed;
1932                         fprintf(trace->output, "%*s= ?\n", alignment, " ");
1933                 }
1934         } else {
1935                 ttrace->entry_pending = true;
1936                 /* See trace__vfs_getname & trace__sys_exit */
1937                 ttrace->filename.pending_open = false;
1938         }
1939
1940         if (trace->current != thread) {
1941                 thread__put(trace->current);
1942                 trace->current = thread__get(thread);
1943         }
1944         err = 0;
1945 out_put:
1946         thread__put(thread);
1947         return err;
1948 }
1949
1950 static int trace__fprintf_sys_enter(struct trace *trace, struct perf_evsel *evsel,
1951                                     struct perf_sample *sample)
1952 {
1953         struct thread_trace *ttrace;
1954         struct thread *thread;
1955         int id = perf_evsel__sc_tp_uint(evsel, id, sample), err = -1;
1956         struct syscall *sc = trace__syscall_info(trace, evsel, id);
1957         char msg[1024];
1958         void *args, *augmented_args = NULL;
1959         int augmented_args_size;
1960
1961         if (sc == NULL)
1962                 return -1;
1963
1964         thread = machine__findnew_thread(trace->host, sample->pid, sample->tid);
1965         ttrace = thread__trace(thread, trace->output);
1966         /*
1967          * We need to get ttrace just to make sure it is there when syscall__scnprintf_args()
1968          * and the rest of the beautifiers accessing it via struct syscall_arg touches it.
1969          */
1970         if (ttrace == NULL)
1971                 goto out_put;
1972
1973         args = perf_evsel__sc_tp_ptr(evsel, args, sample);
1974         augmented_args = syscall__augmented_args(sc, sample, &augmented_args_size, trace->raw_augmented_syscalls_args_size);
1975         syscall__scnprintf_args(sc, msg, sizeof(msg), args, augmented_args, augmented_args_size, trace, thread);
1976         fprintf(trace->output, "%s", msg);
1977         err = 0;
1978 out_put:
1979         thread__put(thread);
1980         return err;
1981 }
1982
1983 static int trace__resolve_callchain(struct trace *trace, struct perf_evsel *evsel,
1984                                     struct perf_sample *sample,
1985                                     struct callchain_cursor *cursor)
1986 {
1987         struct addr_location al;
1988         int max_stack = evsel->attr.sample_max_stack ?
1989                         evsel->attr.sample_max_stack :
1990                         trace->max_stack;
1991         int err;
1992
1993         if (machine__resolve(trace->host, &al, sample) < 0)
1994                 return -1;
1995
1996         err = thread__resolve_callchain(al.thread, cursor, evsel, sample, NULL, NULL, max_stack);
1997         addr_location__put(&al);
1998         return err;
1999 }
2000
2001 static int trace__fprintf_callchain(struct trace *trace, struct perf_sample *sample)
2002 {
2003         /* TODO: user-configurable print_opts */
2004         const unsigned int print_opts = EVSEL__PRINT_SYM |
2005                                         EVSEL__PRINT_DSO |
2006                                         EVSEL__PRINT_UNKNOWN_AS_ADDR;
2007
2008         return sample__fprintf_callchain(sample, 38, print_opts, &callchain_cursor, trace->output);
2009 }
2010
2011 static const char *errno_to_name(struct perf_evsel *evsel, int err)
2012 {
2013         struct perf_env *env = perf_evsel__env(evsel);
2014         const char *arch_name = perf_env__arch(env);
2015
2016         return arch_syscalls__strerrno(arch_name, err);
2017 }
2018
2019 static int trace__sys_exit(struct trace *trace, struct perf_evsel *evsel,
2020                            union perf_event *event __maybe_unused,
2021                            struct perf_sample *sample)
2022 {
2023         long ret;
2024         u64 duration = 0;
2025         bool duration_calculated = false;
2026         struct thread *thread;
2027         int id = perf_evsel__sc_tp_uint(evsel, id, sample), err = -1, callchain_ret = 0, printed = 0;
2028         int alignment = trace->args_alignment;
2029         struct syscall *sc = trace__syscall_info(trace, evsel, id);
2030         struct thread_trace *ttrace;
2031
2032         if (sc == NULL)
2033                 return -1;
2034
2035         thread = machine__findnew_thread(trace->host, sample->pid, sample->tid);
2036         ttrace = thread__trace(thread, trace->output);
2037         if (ttrace == NULL)
2038                 goto out_put;
2039
2040         trace__fprintf_sample(trace, evsel, sample, thread);
2041
2042         if (trace->summary)
2043                 thread__update_stats(ttrace, id, sample);
2044
2045         ret = perf_evsel__sc_tp_uint(evsel, ret, sample);
2046
2047         if (sc->is_open && ret >= 0 && ttrace->filename.pending_open) {
2048                 trace__set_fd_pathname(thread, ret, ttrace->filename.name);
2049                 ttrace->filename.pending_open = false;
2050                 ++trace->stats.vfs_getname;
2051         }
2052
2053         if (ttrace->entry_time) {
2054                 duration = sample->time - ttrace->entry_time;
2055                 if (trace__filter_duration(trace, duration))
2056                         goto out;
2057                 duration_calculated = true;
2058         } else if (trace->duration_filter)
2059                 goto out;
2060
2061         if (sample->callchain) {
2062                 callchain_ret = trace__resolve_callchain(trace, evsel, sample, &callchain_cursor);
2063                 if (callchain_ret == 0) {
2064                         if (callchain_cursor.nr < trace->min_stack)
2065                                 goto out;
2066                         callchain_ret = 1;
2067                 }
2068         }
2069
2070         if (trace->summary_only || (ret >= 0 && trace->failure_only))
2071                 goto out;
2072
2073         trace__fprintf_entry_head(trace, thread, duration, duration_calculated, ttrace->entry_time, trace->output);
2074
2075         if (ttrace->entry_pending) {
2076                 printed = fprintf(trace->output, "%s", ttrace->entry_str);
2077         } else {
2078                 printed += fprintf(trace->output, " ... [");
2079                 color_fprintf(trace->output, PERF_COLOR_YELLOW, "continued");
2080                 printed += 9;
2081                 printed += fprintf(trace->output, "]: %s()", sc->name);
2082         }
2083
2084         printed++; /* the closing ')' */
2085
2086         if (alignment > printed)
2087                 alignment -= printed;
2088         else
2089                 alignment = 0;
2090
2091         fprintf(trace->output, ")%*s= ", alignment, " ");
2092
2093         if (sc->fmt == NULL) {
2094                 if (ret < 0)
2095                         goto errno_print;
2096 signed_print:
2097                 fprintf(trace->output, "%ld", ret);
2098         } else if (ret < 0) {
2099 errno_print: {
2100                 char bf[STRERR_BUFSIZE];
2101                 const char *emsg = str_error_r(-ret, bf, sizeof(bf)),
2102                            *e = errno_to_name(evsel, -ret);
2103
2104                 fprintf(trace->output, "-1 %s (%s)", e, emsg);
2105         }
2106         } else if (ret == 0 && sc->fmt->timeout)
2107                 fprintf(trace->output, "0 (Timeout)");
2108         else if (ttrace->ret_scnprintf) {
2109                 char bf[1024];
2110                 struct syscall_arg arg = {
2111                         .val    = ret,
2112                         .thread = thread,
2113                         .trace  = trace,
2114                 };
2115                 ttrace->ret_scnprintf(bf, sizeof(bf), &arg);
2116                 ttrace->ret_scnprintf = NULL;
2117                 fprintf(trace->output, "%s", bf);
2118         } else if (sc->fmt->hexret)
2119                 fprintf(trace->output, "%#lx", ret);
2120         else if (sc->fmt->errpid) {
2121                 struct thread *child = machine__find_thread(trace->host, ret, ret);
2122
2123                 if (child != NULL) {
2124                         fprintf(trace->output, "%ld", ret);
2125                         if (child->comm_set)
2126                                 fprintf(trace->output, " (%s)", thread__comm_str(child));
2127                         thread__put(child);
2128                 }
2129         } else
2130                 goto signed_print;
2131
2132         fputc('\n', trace->output);
2133
2134         /*
2135          * We only consider an 'event' for the sake of --max-events a non-filtered
2136          * sys_enter + sys_exit and other tracepoint events.
2137          */
2138         if (++trace->nr_events_printed == trace->max_events && trace->max_events != ULONG_MAX)
2139                 interrupted = true;
2140
2141         if (callchain_ret > 0)
2142                 trace__fprintf_callchain(trace, sample);
2143         else if (callchain_ret < 0)
2144                 pr_err("Problem processing %s callchain, skipping...\n", perf_evsel__name(evsel));
2145 out:
2146         ttrace->entry_pending = false;
2147         err = 0;
2148 out_put:
2149         thread__put(thread);
2150         return err;
2151 }
2152
2153 static int trace__vfs_getname(struct trace *trace, struct perf_evsel *evsel,
2154                               union perf_event *event __maybe_unused,
2155                               struct perf_sample *sample)
2156 {
2157         struct thread *thread = machine__findnew_thread(trace->host, sample->pid, sample->tid);
2158         struct thread_trace *ttrace;
2159         size_t filename_len, entry_str_len, to_move;
2160         ssize_t remaining_space;
2161         char *pos;
2162         const char *filename = perf_evsel__rawptr(evsel, sample, "pathname");
2163
2164         if (!thread)
2165                 goto out;
2166
2167         ttrace = thread__priv(thread);
2168         if (!ttrace)
2169                 goto out_put;
2170
2171         filename_len = strlen(filename);
2172         if (filename_len == 0)
2173                 goto out_put;
2174
2175         if (ttrace->filename.namelen < filename_len) {
2176                 char *f = realloc(ttrace->filename.name, filename_len + 1);
2177
2178                 if (f == NULL)
2179                         goto out_put;
2180
2181                 ttrace->filename.namelen = filename_len;
2182                 ttrace->filename.name = f;
2183         }
2184
2185         strcpy(ttrace->filename.name, filename);
2186         ttrace->filename.pending_open = true;
2187
2188         if (!ttrace->filename.ptr)
2189                 goto out_put;
2190
2191         entry_str_len = strlen(ttrace->entry_str);
2192         remaining_space = trace__entry_str_size - entry_str_len - 1; /* \0 */
2193         if (remaining_space <= 0)
2194                 goto out_put;
2195
2196         if (filename_len > (size_t)remaining_space) {
2197                 filename += filename_len - remaining_space;
2198                 filename_len = remaining_space;
2199         }
2200
2201         to_move = entry_str_len - ttrace->filename.entry_str_pos + 1; /* \0 */
2202         pos = ttrace->entry_str + ttrace->filename.entry_str_pos;
2203         memmove(pos + filename_len, pos, to_move);
2204         memcpy(pos, filename, filename_len);
2205
2206         ttrace->filename.ptr = 0;
2207         ttrace->filename.entry_str_pos = 0;
2208 out_put:
2209         thread__put(thread);
2210 out:
2211         return 0;
2212 }
2213
2214 static int trace__sched_stat_runtime(struct trace *trace, struct perf_evsel *evsel,
2215                                      union perf_event *event __maybe_unused,
2216                                      struct perf_sample *sample)
2217 {
2218         u64 runtime = perf_evsel__intval(evsel, sample, "runtime");
2219         double runtime_ms = (double)runtime / NSEC_PER_MSEC;
2220         struct thread *thread = machine__findnew_thread(trace->host,
2221                                                         sample->pid,
2222                                                         sample->tid);
2223         struct thread_trace *ttrace = thread__trace(thread, trace->output);
2224
2225         if (ttrace == NULL)
2226                 goto out_dump;
2227
2228         ttrace->runtime_ms += runtime_ms;
2229         trace->runtime_ms += runtime_ms;
2230 out_put:
2231         thread__put(thread);
2232         return 0;
2233
2234 out_dump:
2235         fprintf(trace->output, "%s: comm=%s,pid=%u,runtime=%" PRIu64 ",vruntime=%" PRIu64 ")\n",
2236                evsel->name,
2237                perf_evsel__strval(evsel, sample, "comm"),
2238                (pid_t)perf_evsel__intval(evsel, sample, "pid"),
2239                runtime,
2240                perf_evsel__intval(evsel, sample, "vruntime"));
2241         goto out_put;
2242 }
2243
2244 static int bpf_output__printer(enum binary_printer_ops op,
2245                                unsigned int val, void *extra __maybe_unused, FILE *fp)
2246 {
2247         unsigned char ch = (unsigned char)val;
2248
2249         switch (op) {
2250         case BINARY_PRINT_CHAR_DATA:
2251                 return fprintf(fp, "%c", isprint(ch) ? ch : '.');
2252         case BINARY_PRINT_DATA_BEGIN:
2253         case BINARY_PRINT_LINE_BEGIN:
2254         case BINARY_PRINT_ADDR:
2255         case BINARY_PRINT_NUM_DATA:
2256         case BINARY_PRINT_NUM_PAD:
2257         case BINARY_PRINT_SEP:
2258         case BINARY_PRINT_CHAR_PAD:
2259         case BINARY_PRINT_LINE_END:
2260         case BINARY_PRINT_DATA_END:
2261         default:
2262                 break;
2263         }
2264
2265         return 0;
2266 }
2267
2268 static void bpf_output__fprintf(struct trace *trace,
2269                                 struct perf_sample *sample)
2270 {
2271         binary__fprintf(sample->raw_data, sample->raw_size, 8,
2272                         bpf_output__printer, NULL, trace->output);
2273         ++trace->nr_events_printed;
2274 }
2275
2276 static int trace__event_handler(struct trace *trace, struct perf_evsel *evsel,
2277                                 union perf_event *event __maybe_unused,
2278                                 struct perf_sample *sample)
2279 {
2280         struct thread *thread;
2281         int callchain_ret = 0;
2282         /*
2283          * Check if we called perf_evsel__disable(evsel) due to, for instance,
2284          * this event's max_events having been hit and this is an entry coming
2285          * from the ring buffer that we should discard, since the max events
2286          * have already been considered/printed.
2287          */
2288         if (evsel->disabled)
2289                 return 0;
2290
2291         thread = machine__findnew_thread(trace->host, sample->pid, sample->tid);
2292
2293         if (sample->callchain) {
2294                 callchain_ret = trace__resolve_callchain(trace, evsel, sample, &callchain_cursor);
2295                 if (callchain_ret == 0) {
2296                         if (callchain_cursor.nr < trace->min_stack)
2297                                 goto out;
2298                         callchain_ret = 1;
2299                 }
2300         }
2301
2302         trace__printf_interrupted_entry(trace);
2303         trace__fprintf_tstamp(trace, sample->time, trace->output);
2304
2305         if (trace->trace_syscalls && trace->show_duration)
2306                 fprintf(trace->output, "(         ): ");
2307
2308         if (thread)
2309                 trace__fprintf_comm_tid(trace, thread, trace->output);
2310
2311         if (evsel == trace->syscalls.events.augmented) {
2312                 int id = perf_evsel__sc_tp_uint(evsel, id, sample);
2313                 struct syscall *sc = trace__syscall_info(trace, evsel, id);
2314
2315                 if (sc) {
2316                         fprintf(trace->output, "%s(", sc->name);
2317                         trace__fprintf_sys_enter(trace, evsel, sample);
2318                         fputc(')', trace->output);
2319                         goto newline;
2320                 }
2321
2322                 /*
2323                  * XXX: Not having the associated syscall info or not finding/adding
2324                  *      the thread should never happen, but if it does...
2325                  *      fall thru and print it as a bpf_output event.
2326                  */
2327         }
2328
2329         fprintf(trace->output, "%s:", evsel->name);
2330
2331         if (perf_evsel__is_bpf_output(evsel)) {
2332                 bpf_output__fprintf(trace, sample);
2333         } else if (evsel->tp_format) {
2334                 if (strncmp(evsel->tp_format->name, "sys_enter_", 10) ||
2335                     trace__fprintf_sys_enter(trace, evsel, sample)) {
2336                         event_format__fprintf(evsel->tp_format, sample->cpu,
2337                                               sample->raw_data, sample->raw_size,
2338                                               trace->output);
2339                         ++trace->nr_events_printed;
2340
2341                         if (evsel->max_events != ULONG_MAX && ++evsel->nr_events_printed == evsel->max_events) {
2342                                 perf_evsel__disable(evsel);
2343                                 perf_evsel__close(evsel);
2344                         }
2345                 }
2346         }
2347
2348 newline:
2349         fprintf(trace->output, "\n");
2350
2351         if (callchain_ret > 0)
2352                 trace__fprintf_callchain(trace, sample);
2353         else if (callchain_ret < 0)
2354                 pr_err("Problem processing %s callchain, skipping...\n", perf_evsel__name(evsel));
2355 out:
2356         thread__put(thread);
2357         return 0;
2358 }
2359
2360 static void print_location(FILE *f, struct perf_sample *sample,
2361                            struct addr_location *al,
2362                            bool print_dso, bool print_sym)
2363 {
2364
2365         if ((verbose > 0 || print_dso) && al->map)
2366                 fprintf(f, "%s@", al->map->dso->long_name);
2367
2368         if ((verbose > 0 || print_sym) && al->sym)
2369                 fprintf(f, "%s+0x%" PRIx64, al->sym->name,
2370                         al->addr - al->sym->start);
2371         else if (al->map)
2372                 fprintf(f, "0x%" PRIx64, al->addr);
2373         else
2374                 fprintf(f, "0x%" PRIx64, sample->addr);
2375 }
2376
2377 static int trace__pgfault(struct trace *trace,
2378                           struct perf_evsel *evsel,
2379                           union perf_event *event __maybe_unused,
2380                           struct perf_sample *sample)
2381 {
2382         struct thread *thread;
2383         struct addr_location al;
2384         char map_type = 'd';
2385         struct thread_trace *ttrace;
2386         int err = -1;
2387         int callchain_ret = 0;
2388
2389         thread = machine__findnew_thread(trace->host, sample->pid, sample->tid);
2390
2391         if (sample->callchain) {
2392                 callchain_ret = trace__resolve_callchain(trace, evsel, sample, &callchain_cursor);
2393                 if (callchain_ret == 0) {
2394                         if (callchain_cursor.nr < trace->min_stack)
2395                                 goto out_put;
2396                         callchain_ret = 1;
2397                 }
2398         }
2399
2400         ttrace = thread__trace(thread, trace->output);
2401         if (ttrace == NULL)
2402                 goto out_put;
2403
2404         if (evsel->attr.config == PERF_COUNT_SW_PAGE_FAULTS_MAJ)
2405                 ttrace->pfmaj++;
2406         else
2407                 ttrace->pfmin++;
2408
2409         if (trace->summary_only)
2410                 goto out;
2411
2412         thread__find_symbol(thread, sample->cpumode, sample->ip, &al);
2413
2414         trace__fprintf_entry_head(trace, thread, 0, true, sample->time, trace->output);
2415
2416         fprintf(trace->output, "%sfault [",
2417                 evsel->attr.config == PERF_COUNT_SW_PAGE_FAULTS_MAJ ?
2418                 "maj" : "min");
2419
2420         print_location(trace->output, sample, &al, false, true);
2421
2422         fprintf(trace->output, "] => ");
2423
2424         thread__find_symbol(thread, sample->cpumode, sample->addr, &al);
2425
2426         if (!al.map) {
2427                 thread__find_symbol(thread, sample->cpumode, sample->addr, &al);
2428
2429                 if (al.map)
2430                         map_type = 'x';
2431                 else
2432                         map_type = '?';
2433         }
2434
2435         print_location(trace->output, sample, &al, true, false);
2436
2437         fprintf(trace->output, " (%c%c)\n", map_type, al.level);
2438
2439         if (callchain_ret > 0)
2440                 trace__fprintf_callchain(trace, sample);
2441         else if (callchain_ret < 0)
2442                 pr_err("Problem processing %s callchain, skipping...\n", perf_evsel__name(evsel));
2443
2444         ++trace->nr_events_printed;
2445 out:
2446         err = 0;
2447 out_put:
2448         thread__put(thread);
2449         return err;
2450 }
2451
2452 static void trace__set_base_time(struct trace *trace,
2453                                  struct perf_evsel *evsel,
2454                                  struct perf_sample *sample)
2455 {
2456         /*
2457          * BPF events were not setting PERF_SAMPLE_TIME, so be more robust
2458          * and don't use sample->time unconditionally, we may end up having
2459          * some other event in the future without PERF_SAMPLE_TIME for good
2460          * reason, i.e. we may not be interested in its timestamps, just in
2461          * it taking place, picking some piece of information when it
2462          * appears in our event stream (vfs_getname comes to mind).
2463          */
2464         if (trace->base_time == 0 && !trace->full_time &&
2465             (evsel->attr.sample_type & PERF_SAMPLE_TIME))
2466                 trace->base_time = sample->time;
2467 }
2468
2469 static int trace__process_sample(struct perf_tool *tool,
2470                                  union perf_event *event,
2471                                  struct perf_sample *sample,
2472                                  struct perf_evsel *evsel,
2473                                  struct machine *machine __maybe_unused)
2474 {
2475         struct trace *trace = container_of(tool, struct trace, tool);
2476         struct thread *thread;
2477         int err = 0;
2478
2479         tracepoint_handler handler = evsel->handler;
2480
2481         thread = machine__findnew_thread(trace->host, sample->pid, sample->tid);
2482         if (thread && thread__is_filtered(thread))
2483                 goto out;
2484
2485         trace__set_base_time(trace, evsel, sample);
2486
2487         if (handler) {
2488                 ++trace->nr_events;
2489                 handler(trace, evsel, event, sample);
2490         }
2491 out:
2492         thread__put(thread);
2493         return err;
2494 }
2495
2496 static int trace__record(struct trace *trace, int argc, const char **argv)
2497 {
2498         unsigned int rec_argc, i, j;
2499         const char **rec_argv;
2500         const char * const record_args[] = {
2501                 "record",
2502                 "-R",
2503                 "-m", "1024",
2504                 "-c", "1",
2505         };
2506
2507         const char * const sc_args[] = { "-e", };
2508         unsigned int sc_args_nr = ARRAY_SIZE(sc_args);
2509         const char * const majpf_args[] = { "-e", "major-faults" };
2510         unsigned int majpf_args_nr = ARRAY_SIZE(majpf_args);
2511         const char * const minpf_args[] = { "-e", "minor-faults" };
2512         unsigned int minpf_args_nr = ARRAY_SIZE(minpf_args);
2513
2514         /* +1 is for the event string below */
2515         rec_argc = ARRAY_SIZE(record_args) + sc_args_nr + 1 +
2516                 majpf_args_nr + minpf_args_nr + argc;
2517         rec_argv = calloc(rec_argc + 1, sizeof(char *));
2518
2519         if (rec_argv == NULL)
2520                 return -ENOMEM;
2521
2522         j = 0;
2523         for (i = 0; i < ARRAY_SIZE(record_args); i++)
2524                 rec_argv[j++] = record_args[i];
2525
2526         if (trace->trace_syscalls) {
2527                 for (i = 0; i < sc_args_nr; i++)
2528                         rec_argv[j++] = sc_args[i];
2529
2530                 /* event string may be different for older kernels - e.g., RHEL6 */
2531                 if (is_valid_tracepoint("raw_syscalls:sys_enter"))
2532                         rec_argv[j++] = "raw_syscalls:sys_enter,raw_syscalls:sys_exit";
2533                 else if (is_valid_tracepoint("syscalls:sys_enter"))
2534                         rec_argv[j++] = "syscalls:sys_enter,syscalls:sys_exit";
2535                 else {
2536                         pr_err("Neither raw_syscalls nor syscalls events exist.\n");
2537                         free(rec_argv);
2538                         return -1;
2539                 }
2540         }
2541
2542         if (trace->trace_pgfaults & TRACE_PFMAJ)
2543                 for (i = 0; i < majpf_args_nr; i++)
2544                         rec_argv[j++] = majpf_args[i];
2545
2546         if (trace->trace_pgfaults & TRACE_PFMIN)
2547                 for (i = 0; i < minpf_args_nr; i++)
2548                         rec_argv[j++] = minpf_args[i];
2549
2550         for (i = 0; i < (unsigned int)argc; i++)
2551                 rec_argv[j++] = argv[i];
2552
2553         return cmd_record(j, rec_argv);
2554 }
2555
2556 static size_t trace__fprintf_thread_summary(struct trace *trace, FILE *fp);
2557
2558 static bool perf_evlist__add_vfs_getname(struct perf_evlist *evlist)
2559 {
2560         bool found = false;
2561         struct perf_evsel *evsel, *tmp;
2562         struct parse_events_error err = { .idx = 0, };
2563         int ret = parse_events(evlist, "probe:vfs_getname*", &err);
2564
2565         if (ret)
2566                 return false;
2567
2568         evlist__for_each_entry_safe(evlist, evsel, tmp) {
2569                 if (!strstarts(perf_evsel__name(evsel), "probe:vfs_getname"))
2570                         continue;
2571
2572                 if (perf_evsel__field(evsel, "pathname")) {
2573                         evsel->handler = trace__vfs_getname;
2574                         found = true;
2575                         continue;
2576                 }
2577
2578                 list_del_init(&evsel->node);
2579                 evsel->evlist = NULL;
2580                 perf_evsel__delete(evsel);
2581         }
2582
2583         return found;
2584 }
2585
2586 static struct perf_evsel *perf_evsel__new_pgfault(u64 config)
2587 {
2588         struct perf_evsel *evsel;
2589         struct perf_event_attr attr = {
2590                 .type = PERF_TYPE_SOFTWARE,
2591                 .mmap_data = 1,
2592         };
2593
2594         attr.config = config;
2595         attr.sample_period = 1;
2596
2597         event_attr_init(&attr);
2598
2599         evsel = perf_evsel__new(&attr);
2600         if (evsel)
2601                 evsel->handler = trace__pgfault;
2602
2603         return evsel;
2604 }
2605
2606 static void trace__handle_event(struct trace *trace, union perf_event *event, struct perf_sample *sample)
2607 {
2608         const u32 type = event->header.type;
2609         struct perf_evsel *evsel;
2610
2611         if (type != PERF_RECORD_SAMPLE) {
2612                 trace__process_event(trace, trace->host, event, sample);
2613                 return;
2614         }
2615
2616         evsel = perf_evlist__id2evsel(trace->evlist, sample->id);
2617         if (evsel == NULL) {
2618                 fprintf(trace->output, "Unknown tp ID %" PRIu64 ", skipping...\n", sample->id);
2619                 return;
2620         }
2621
2622         trace__set_base_time(trace, evsel, sample);
2623
2624         if (evsel->attr.type == PERF_TYPE_TRACEPOINT &&
2625             sample->raw_data == NULL) {
2626                 fprintf(trace->output, "%s sample with no payload for tid: %d, cpu %d, raw_size=%d, skipping...\n",
2627                        perf_evsel__name(evsel), sample->tid,
2628                        sample->cpu, sample->raw_size);
2629         } else {
2630                 tracepoint_handler handler = evsel->handler;
2631                 handler(trace, evsel, event, sample);
2632         }
2633
2634         if (trace->nr_events_printed >= trace->max_events && trace->max_events != ULONG_MAX)
2635                 interrupted = true;
2636 }
2637
2638 static int trace__add_syscall_newtp(struct trace *trace)
2639 {
2640         int ret = -1;
2641         struct perf_evlist *evlist = trace->evlist;
2642         struct perf_evsel *sys_enter, *sys_exit;
2643
2644         sys_enter = perf_evsel__raw_syscall_newtp("sys_enter", trace__sys_enter);
2645         if (sys_enter == NULL)
2646                 goto out;
2647
2648         if (perf_evsel__init_sc_tp_ptr_field(sys_enter, args))
2649                 goto out_delete_sys_enter;
2650
2651         sys_exit = perf_evsel__raw_syscall_newtp("sys_exit", trace__sys_exit);
2652         if (sys_exit == NULL)
2653                 goto out_delete_sys_enter;
2654
2655         if (perf_evsel__init_sc_tp_uint_field(sys_exit, ret))
2656                 goto out_delete_sys_exit;
2657
2658         perf_evsel__config_callchain(sys_enter, &trace->opts, &callchain_param);
2659         perf_evsel__config_callchain(sys_exit, &trace->opts, &callchain_param);
2660
2661         perf_evlist__add(evlist, sys_enter);
2662         perf_evlist__add(evlist, sys_exit);
2663
2664         if (callchain_param.enabled && !trace->kernel_syscallchains) {
2665                 /*
2666                  * We're interested only in the user space callchain
2667                  * leading to the syscall, allow overriding that for
2668                  * debugging reasons using --kernel_syscall_callchains
2669                  */
2670                 sys_exit->attr.exclude_callchain_kernel = 1;
2671         }
2672
2673         trace->syscalls.events.sys_enter = sys_enter;
2674         trace->syscalls.events.sys_exit  = sys_exit;
2675
2676         ret = 0;
2677 out:
2678         return ret;
2679
2680 out_delete_sys_exit:
2681         perf_evsel__delete_priv(sys_exit);
2682 out_delete_sys_enter:
2683         perf_evsel__delete_priv(sys_enter);
2684         goto out;
2685 }
2686
2687 static int trace__set_ev_qualifier_tp_filter(struct trace *trace)
2688 {
2689         int err = -1;
2690         struct perf_evsel *sys_exit;
2691         char *filter = asprintf_expr_inout_ints("id", !trace->not_ev_qualifier,
2692                                                 trace->ev_qualifier_ids.nr,
2693                                                 trace->ev_qualifier_ids.entries);
2694
2695         if (filter == NULL)
2696                 goto out_enomem;
2697
2698         if (!perf_evsel__append_tp_filter(trace->syscalls.events.sys_enter,
2699                                           filter)) {
2700                 sys_exit = trace->syscalls.events.sys_exit;
2701                 err = perf_evsel__append_tp_filter(sys_exit, filter);
2702         }
2703
2704         free(filter);
2705 out:
2706         return err;
2707 out_enomem:
2708         errno = ENOMEM;
2709         goto out;
2710 }
2711
2712 #ifdef HAVE_LIBBPF_SUPPORT
2713 static int trace__set_ev_qualifier_bpf_filter(struct trace *trace)
2714 {
2715         int fd = bpf_map__fd(trace->syscalls.map);
2716         struct bpf_map_syscall_entry value = {
2717                 .enabled = !trace->not_ev_qualifier,
2718         };
2719         int err = 0;
2720         size_t i;
2721
2722         for (i = 0; i < trace->ev_qualifier_ids.nr; ++i) {
2723                 int key = trace->ev_qualifier_ids.entries[i];
2724
2725                 err = bpf_map_update_elem(fd, &key, &value, BPF_EXIST);
2726                 if (err)
2727                         break;
2728         }
2729
2730         return err;
2731 }
2732
2733 static int __trace__init_syscalls_bpf_map(struct trace *trace, bool enabled)
2734 {
2735         int fd = bpf_map__fd(trace->syscalls.map);
2736         struct bpf_map_syscall_entry value = {
2737                 .enabled = enabled,
2738         };
2739         int err = 0, key;
2740
2741         for (key = 0; key < trace->sctbl->syscalls.nr_entries; ++key) {
2742                 err = bpf_map_update_elem(fd, &key, &value, BPF_ANY);
2743                 if (err)
2744                         break;
2745         }
2746
2747         return err;
2748 }
2749
2750 static int trace__init_syscalls_bpf_map(struct trace *trace)
2751 {
2752         bool enabled = true;
2753
2754         if (trace->ev_qualifier_ids.nr)
2755                 enabled = trace->not_ev_qualifier;
2756
2757         return __trace__init_syscalls_bpf_map(trace, enabled);
2758 }
2759 #else
2760 static int trace__set_ev_qualifier_bpf_filter(struct trace *trace __maybe_unused)
2761 {
2762         return 0;
2763 }
2764
2765 static int trace__init_syscalls_bpf_map(struct trace *trace __maybe_unused)
2766 {
2767         return 0;
2768 }
2769 #endif // HAVE_LIBBPF_SUPPORT
2770
2771 static int trace__set_ev_qualifier_filter(struct trace *trace)
2772 {
2773         if (trace->syscalls.map)
2774                 return trace__set_ev_qualifier_bpf_filter(trace);
2775         if (trace->syscalls.events.sys_enter)
2776                 return trace__set_ev_qualifier_tp_filter(trace);
2777         return 0;
2778 }
2779
2780 static int bpf_map__set_filter_pids(struct bpf_map *map __maybe_unused,
2781                                     size_t npids __maybe_unused, pid_t *pids __maybe_unused)
2782 {
2783         int err = 0;
2784 #ifdef HAVE_LIBBPF_SUPPORT
2785         bool value = true;
2786         int map_fd = bpf_map__fd(map);
2787         size_t i;
2788
2789         for (i = 0; i < npids; ++i) {
2790                 err = bpf_map_update_elem(map_fd, &pids[i], &value, BPF_ANY);
2791                 if (err)
2792                         break;
2793         }
2794 #endif
2795         return err;
2796 }
2797
2798 static int trace__set_filter_loop_pids(struct trace *trace)
2799 {
2800         unsigned int nr = 1, err;
2801         pid_t pids[32] = {
2802                 getpid(),
2803         };
2804         struct thread *thread = machine__find_thread(trace->host, pids[0], pids[0]);
2805
2806         while (thread && nr < ARRAY_SIZE(pids)) {
2807                 struct thread *parent = machine__find_thread(trace->host, thread->ppid, thread->ppid);
2808
2809                 if (parent == NULL)
2810                         break;
2811
2812                 if (!strcmp(thread__comm_str(parent), "sshd") ||
2813                     strstarts(thread__comm_str(parent), "gnome-terminal")) {
2814                         pids[nr++] = parent->tid;
2815                         break;
2816                 }
2817                 thread = parent;
2818         }
2819
2820         err = perf_evlist__set_tp_filter_pids(trace->evlist, nr, pids);
2821         if (!err && trace->filter_pids.map)
2822                 err = bpf_map__set_filter_pids(trace->filter_pids.map, nr, pids);
2823
2824         return err;
2825 }
2826
2827 static int trace__set_filter_pids(struct trace *trace)
2828 {
2829         int err = 0;
2830         /*
2831          * Better not use !target__has_task() here because we need to cover the
2832          * case where no threads were specified in the command line, but a
2833          * workload was, and in that case we will fill in the thread_map when
2834          * we fork the workload in perf_evlist__prepare_workload.
2835          */
2836         if (trace->filter_pids.nr > 0) {
2837                 err = perf_evlist__set_tp_filter_pids(trace->evlist, trace->filter_pids.nr,
2838                                                       trace->filter_pids.entries);
2839                 if (!err && trace->filter_pids.map) {
2840                         err = bpf_map__set_filter_pids(trace->filter_pids.map, trace->filter_pids.nr,
2841                                                        trace->filter_pids.entries);
2842                 }
2843         } else if (thread_map__pid(trace->evlist->threads, 0) == -1) {
2844                 err = trace__set_filter_loop_pids(trace);
2845         }
2846
2847         return err;
2848 }
2849
2850 static int __trace__deliver_event(struct trace *trace, union perf_event *event)
2851 {
2852         struct perf_evlist *evlist = trace->evlist;
2853         struct perf_sample sample;
2854         int err;
2855
2856         err = perf_evlist__parse_sample(evlist, event, &sample);
2857         if (err)
2858                 fprintf(trace->output, "Can't parse sample, err = %d, skipping...\n", err);
2859         else
2860                 trace__handle_event(trace, event, &sample);
2861
2862         return 0;
2863 }
2864
2865 static int __trace__flush_events(struct trace *trace)
2866 {
2867         u64 first = ordered_events__first_time(&trace->oe.data);
2868         u64 flush = trace->oe.last - NSEC_PER_SEC;
2869
2870         /* Is there some thing to flush.. */
2871         if (first && first < flush)
2872                 return ordered_events__flush_time(&trace->oe.data, flush);
2873
2874         return 0;
2875 }
2876
2877 static int trace__flush_events(struct trace *trace)
2878 {
2879         return !trace->sort_events ? 0 : __trace__flush_events(trace);
2880 }
2881
2882 static int trace__deliver_event(struct trace *trace, union perf_event *event)
2883 {
2884         int err;
2885
2886         if (!trace->sort_events)
2887                 return __trace__deliver_event(trace, event);
2888
2889         err = perf_evlist__parse_sample_timestamp(trace->evlist, event, &trace->oe.last);
2890         if (err && err != -1)
2891                 return err;
2892
2893         err = ordered_events__queue(&trace->oe.data, event, trace->oe.last, 0);
2894         if (err)
2895                 return err;
2896
2897         return trace__flush_events(trace);
2898 }
2899
2900 static int ordered_events__deliver_event(struct ordered_events *oe,
2901                                          struct ordered_event *event)
2902 {
2903         struct trace *trace = container_of(oe, struct trace, oe.data);
2904
2905         return __trace__deliver_event(trace, event->event);
2906 }
2907
2908 static int trace__run(struct trace *trace, int argc, const char **argv)
2909 {
2910         struct perf_evlist *evlist = trace->evlist;
2911         struct perf_evsel *evsel, *pgfault_maj = NULL, *pgfault_min = NULL;
2912         int err = -1, i;
2913         unsigned long before;
2914         const bool forks = argc > 0;
2915         bool draining = false;
2916
2917         trace->live = true;
2918
2919         if (!trace->raw_augmented_syscalls) {
2920                 if (trace->trace_syscalls && trace__add_syscall_newtp(trace))
2921                         goto out_error_raw_syscalls;
2922
2923                 if (trace->trace_syscalls)
2924                         trace->vfs_getname = perf_evlist__add_vfs_getname(evlist);
2925         }
2926
2927         if ((trace->trace_pgfaults & TRACE_PFMAJ)) {
2928                 pgfault_maj = perf_evsel__new_pgfault(PERF_COUNT_SW_PAGE_FAULTS_MAJ);
2929                 if (pgfault_maj == NULL)
2930                         goto out_error_mem;
2931                 perf_evsel__config_callchain(pgfault_maj, &trace->opts, &callchain_param);
2932                 perf_evlist__add(evlist, pgfault_maj);
2933         }
2934
2935         if ((trace->trace_pgfaults & TRACE_PFMIN)) {
2936                 pgfault_min = perf_evsel__new_pgfault(PERF_COUNT_SW_PAGE_FAULTS_MIN);
2937                 if (pgfault_min == NULL)
2938                         goto out_error_mem;
2939                 perf_evsel__config_callchain(pgfault_min, &trace->opts, &callchain_param);
2940                 perf_evlist__add(evlist, pgfault_min);
2941         }
2942
2943         if (trace->sched &&
2944             perf_evlist__add_newtp(evlist, "sched", "sched_stat_runtime",
2945                                    trace__sched_stat_runtime))
2946                 goto out_error_sched_stat_runtime;
2947
2948         /*
2949          * If a global cgroup was set, apply it to all the events without an
2950          * explicit cgroup. I.e.:
2951          *
2952          *      trace -G A -e sched:*switch
2953          *
2954          * Will set all raw_syscalls:sys_{enter,exit}, pgfault, vfs_getname, etc
2955          * _and_ sched:sched_switch to the 'A' cgroup, while:
2956          *
2957          * trace -e sched:*switch -G A
2958          *
2959          * will only set the sched:sched_switch event to the 'A' cgroup, all the
2960          * other events (raw_syscalls:sys_{enter,exit}, etc are left "without"
2961          * a cgroup (on the root cgroup, sys wide, etc).
2962          *
2963          * Multiple cgroups:
2964          *
2965          * trace -G A -e sched:*switch -G B
2966          *
2967          * the syscall ones go to the 'A' cgroup, the sched:sched_switch goes
2968          * to the 'B' cgroup.
2969          *
2970          * evlist__set_default_cgroup() grabs a reference of the passed cgroup
2971          * only for the evsels still without a cgroup, i.e. evsel->cgroup == NULL.
2972          */
2973         if (trace->cgroup)
2974                 evlist__set_default_cgroup(trace->evlist, trace->cgroup);
2975
2976         err = perf_evlist__create_maps(evlist, &trace->opts.target);
2977         if (err < 0) {
2978                 fprintf(trace->output, "Problems parsing the target to trace, check your options!\n");
2979                 goto out_delete_evlist;
2980         }
2981
2982         err = trace__symbols_init(trace, evlist);
2983         if (err < 0) {
2984                 fprintf(trace->output, "Problems initializing symbol libraries!\n");
2985                 goto out_delete_evlist;
2986         }
2987
2988         perf_evlist__config(evlist, &trace->opts, &callchain_param);
2989
2990         signal(SIGCHLD, sig_handler);
2991         signal(SIGINT, sig_handler);
2992
2993         if (forks) {
2994                 err = perf_evlist__prepare_workload(evlist, &trace->opts.target,
2995                                                     argv, false, NULL);
2996                 if (err < 0) {
2997                         fprintf(trace->output, "Couldn't run the workload!\n");
2998                         goto out_delete_evlist;
2999                 }
3000         }
3001
3002         err = perf_evlist__open(evlist);
3003         if (err < 0)
3004                 goto out_error_open;
3005
3006         err = bpf__apply_obj_config();
3007         if (err) {
3008                 char errbuf[BUFSIZ];
3009
3010                 bpf__strerror_apply_obj_config(err, errbuf, sizeof(errbuf));
3011                 pr_err("ERROR: Apply config to BPF failed: %s\n",
3012                          errbuf);
3013                 goto out_error_open;
3014         }
3015
3016         err = trace__set_filter_pids(trace);
3017         if (err < 0)
3018                 goto out_error_mem;
3019
3020         if (trace->syscalls.map)
3021                 trace__init_syscalls_bpf_map(trace);
3022
3023         if (trace->ev_qualifier_ids.nr > 0) {
3024                 err = trace__set_ev_qualifier_filter(trace);
3025                 if (err < 0)
3026                         goto out_errno;
3027
3028                 if (trace->syscalls.events.sys_exit) {
3029                         pr_debug("event qualifier tracepoint filter: %s\n",
3030                                  trace->syscalls.events.sys_exit->filter);
3031                 }
3032         }
3033
3034         err = perf_evlist__apply_filters(evlist, &evsel);
3035         if (err < 0)
3036                 goto out_error_apply_filters;
3037
3038         if (trace->dump.map)
3039                 bpf_map__fprintf(trace->dump.map, trace->output);
3040
3041         err = perf_evlist__mmap(evlist, trace->opts.mmap_pages);
3042         if (err < 0)
3043                 goto out_error_mmap;
3044
3045         if (!target__none(&trace->opts.target) && !trace->opts.initial_delay)
3046                 perf_evlist__enable(evlist);
3047
3048         if (forks)
3049                 perf_evlist__start_workload(evlist);
3050
3051         if (trace->opts.initial_delay) {
3052                 usleep(trace->opts.initial_delay * 1000);
3053                 perf_evlist__enable(evlist);
3054         }
3055
3056         trace->multiple_threads = thread_map__pid(evlist->threads, 0) == -1 ||
3057                                   evlist->threads->nr > 1 ||
3058                                   perf_evlist__first(evlist)->attr.inherit;
3059
3060         /*
3061          * Now that we already used evsel->attr to ask the kernel to setup the
3062          * events, lets reuse evsel->attr.sample_max_stack as the limit in
3063          * trace__resolve_callchain(), allowing per-event max-stack settings
3064          * to override an explicitly set --max-stack global setting.
3065          */
3066         evlist__for_each_entry(evlist, evsel) {
3067                 if (evsel__has_callchain(evsel) &&
3068                     evsel->attr.sample_max_stack == 0)
3069                         evsel->attr.sample_max_stack = trace->max_stack;
3070         }
3071 again:
3072         before = trace->nr_events;
3073
3074         for (i = 0; i < evlist->nr_mmaps; i++) {
3075                 union perf_event *event;
3076                 struct perf_mmap *md;
3077
3078                 md = &evlist->mmap[i];
3079                 if (perf_mmap__read_init(md) < 0)
3080                         continue;
3081
3082                 while ((event = perf_mmap__read_event(md)) != NULL) {
3083                         ++trace->nr_events;
3084
3085                         err = trace__deliver_event(trace, event);
3086                         if (err)
3087                                 goto out_disable;
3088
3089                         perf_mmap__consume(md);
3090
3091                         if (interrupted)
3092                                 goto out_disable;
3093
3094                         if (done && !draining) {
3095                                 perf_evlist__disable(evlist);
3096                                 draining = true;
3097                         }
3098                 }
3099                 perf_mmap__read_done(md);
3100         }
3101
3102         if (trace->nr_events == before) {
3103                 int timeout = done ? 100 : -1;
3104
3105                 if (!draining && perf_evlist__poll(evlist, timeout) > 0) {
3106                         if (perf_evlist__filter_pollfd(evlist, POLLERR | POLLHUP | POLLNVAL) == 0)
3107                                 draining = true;
3108
3109                         goto again;
3110                 } else {
3111                         if (trace__flush_events(trace))
3112                                 goto out_disable;
3113                 }
3114         } else {
3115                 goto again;
3116         }
3117
3118 out_disable:
3119         thread__zput(trace->current);
3120
3121         perf_evlist__disable(evlist);
3122
3123         if (trace->sort_events)
3124                 ordered_events__flush(&trace->oe.data, OE_FLUSH__FINAL);
3125
3126         if (!err) {
3127                 if (trace->summary)
3128                         trace__fprintf_thread_summary(trace, trace->output);
3129
3130                 if (trace->show_tool_stats) {
3131                         fprintf(trace->output, "Stats:\n "
3132                                                " vfs_getname : %" PRIu64 "\n"
3133                                                " proc_getname: %" PRIu64 "\n",
3134                                 trace->stats.vfs_getname,
3135                                 trace->stats.proc_getname);
3136                 }
3137         }
3138
3139 out_delete_evlist:
3140         trace__symbols__exit(trace);
3141
3142         perf_evlist__delete(evlist);
3143         cgroup__put(trace->cgroup);
3144         trace->evlist = NULL;
3145         trace->live = false;
3146         return err;
3147 {
3148         char errbuf[BUFSIZ];
3149
3150 out_error_sched_stat_runtime:
3151         tracing_path__strerror_open_tp(errno, errbuf, sizeof(errbuf), "sched", "sched_stat_runtime");
3152         goto out_error;
3153
3154 out_error_raw_syscalls:
3155         tracing_path__strerror_open_tp(errno, errbuf, sizeof(errbuf), "raw_syscalls", "sys_(enter|exit)");
3156         goto out_error;
3157
3158 out_error_mmap:
3159         perf_evlist__strerror_mmap(evlist, errno, errbuf, sizeof(errbuf));
3160         goto out_error;
3161
3162 out_error_open:
3163         perf_evlist__strerror_open(evlist, errno, errbuf, sizeof(errbuf));
3164
3165 out_error:
3166         fprintf(trace->output, "%s\n", errbuf);
3167         goto out_delete_evlist;
3168
3169 out_error_apply_filters:
3170         fprintf(trace->output,
3171                 "Failed to set filter \"%s\" on event %s with %d (%s)\n",
3172                 evsel->filter, perf_evsel__name(evsel), errno,
3173                 str_error_r(errno, errbuf, sizeof(errbuf)));
3174         goto out_delete_evlist;
3175 }
3176 out_error_mem:
3177         fprintf(trace->output, "Not enough memory to run!\n");
3178         goto out_delete_evlist;
3179
3180 out_errno:
3181         fprintf(trace->output, "errno=%d,%s\n", errno, strerror(errno));
3182         goto out_delete_evlist;
3183 }
3184
3185 static int trace__replay(struct trace *trace)
3186 {
3187         const struct perf_evsel_str_handler handlers[] = {
3188                 { "probe:vfs_getname",       trace__vfs_getname, },
3189         };
3190         struct perf_data data = {
3191                 .path  = input_name,
3192                 .mode  = PERF_DATA_MODE_READ,
3193                 .force = trace->force,
3194         };
3195         struct perf_session *session;
3196         struct perf_evsel *evsel;
3197         int err = -1;
3198
3199         trace->tool.sample        = trace__process_sample;
3200         trace->tool.mmap          = perf_event__process_mmap;
3201         trace->tool.mmap2         = perf_event__process_mmap2;
3202         trace->tool.comm          = perf_event__process_comm;
3203         trace->tool.exit          = perf_event__process_exit;
3204         trace->tool.fork          = perf_event__process_fork;
3205         trace->tool.attr          = perf_event__process_attr;
3206         trace->tool.tracing_data  = perf_event__process_tracing_data;
3207         trace->tool.build_id      = perf_event__process_build_id;
3208         trace->tool.namespaces    = perf_event__process_namespaces;
3209
3210         trace->tool.ordered_events = true;
3211         trace->tool.ordering_requires_timestamps = true;
3212
3213         /* add tid to output */
3214         trace->multiple_threads = true;
3215
3216         session = perf_session__new(&data, false, &trace->tool);
3217         if (session == NULL)
3218                 return -1;
3219
3220         if (trace->opts.target.pid)
3221                 symbol_conf.pid_list_str = strdup(trace->opts.target.pid);
3222
3223         if (trace->opts.target.tid)
3224                 symbol_conf.tid_list_str = strdup(trace->opts.target.tid);
3225
3226         if (symbol__init(&session->header.env) < 0)
3227                 goto out;
3228
3229         trace->host = &session->machines.host;
3230
3231         err = perf_session__set_tracepoints_handlers(session, handlers);
3232         if (err)
3233                 goto out;
3234
3235         evsel = perf_evlist__find_tracepoint_by_name(session->evlist,
3236                                                      "raw_syscalls:sys_enter");
3237         /* older kernels have syscalls tp versus raw_syscalls */
3238         if (evsel == NULL)
3239                 evsel = perf_evlist__find_tracepoint_by_name(session->evlist,
3240                                                              "syscalls:sys_enter");
3241
3242         if (evsel &&
3243             (perf_evsel__init_raw_syscall_tp(evsel, trace__sys_enter) < 0 ||
3244             perf_evsel__init_sc_tp_ptr_field(evsel, args))) {
3245                 pr_err("Error during initialize raw_syscalls:sys_enter event\n");
3246                 goto out;
3247         }
3248
3249         evsel = perf_evlist__find_tracepoint_by_name(session->evlist,
3250                                                      "raw_syscalls:sys_exit");
3251         if (evsel == NULL)
3252                 evsel = perf_evlist__find_tracepoint_by_name(session->evlist,
3253                                                              "syscalls:sys_exit");
3254         if (evsel &&
3255             (perf_evsel__init_raw_syscall_tp(evsel, trace__sys_exit) < 0 ||
3256             perf_evsel__init_sc_tp_uint_field(evsel, ret))) {
3257                 pr_err("Error during initialize raw_syscalls:sys_exit event\n");
3258                 goto out;
3259         }
3260
3261         evlist__for_each_entry(session->evlist, evsel) {
3262                 if (evsel->attr.type == PERF_TYPE_SOFTWARE &&
3263                     (evsel->attr.config == PERF_COUNT_SW_PAGE_FAULTS_MAJ ||
3264                      evsel->attr.config == PERF_COUNT_SW_PAGE_FAULTS_MIN ||
3265                      evsel->attr.config == PERF_COUNT_SW_PAGE_FAULTS))
3266                         evsel->handler = trace__pgfault;
3267         }
3268
3269         setup_pager();
3270
3271         err = perf_session__process_events(session);
3272         if (err)
3273                 pr_err("Failed to process events, error %d", err);
3274
3275         else if (trace->summary)
3276                 trace__fprintf_thread_summary(trace, trace->output);
3277
3278 out:
3279         perf_session__delete(session);
3280
3281         return err;
3282 }
3283
3284 static size_t trace__fprintf_threads_header(FILE *fp)
3285 {
3286         size_t printed;
3287
3288         printed  = fprintf(fp, "\n Summary of events:\n\n");
3289
3290         return printed;
3291 }
3292
3293 DEFINE_RESORT_RB(syscall_stats, a->msecs > b->msecs,
3294         struct stats    *stats;
3295         double          msecs;
3296         int             syscall;
3297 )
3298 {
3299         struct int_node *source = rb_entry(nd, struct int_node, rb_node);
3300         struct stats *stats = source->priv;
3301
3302         entry->syscall = source->i;
3303         entry->stats   = stats;
3304         entry->msecs   = stats ? (u64)stats->n * (avg_stats(stats) / NSEC_PER_MSEC) : 0;
3305 }
3306
3307 static size_t thread__dump_stats(struct thread_trace *ttrace,
3308                                  struct trace *trace, FILE *fp)
3309 {
3310         size_t printed = 0;
3311         struct syscall *sc;
3312         struct rb_node *nd;
3313         DECLARE_RESORT_RB_INTLIST(syscall_stats, ttrace->syscall_stats);
3314
3315         if (syscall_stats == NULL)
3316                 return 0;
3317
3318         printed += fprintf(fp, "\n");
3319
3320         printed += fprintf(fp, "   syscall            calls    total       min       avg       max      stddev\n");
3321         printed += fprintf(fp, "                               (msec)    (msec)    (msec)    (msec)        (%%)\n");
3322         printed += fprintf(fp, "   --------------- -------- --------- --------- --------- ---------     ------\n");
3323
3324         resort_rb__for_each_entry(nd, syscall_stats) {
3325                 struct stats *stats = syscall_stats_entry->stats;
3326                 if (stats) {
3327                         double min = (double)(stats->min) / NSEC_PER_MSEC;
3328                         double max = (double)(stats->max) / NSEC_PER_MSEC;
3329                         double avg = avg_stats(stats);
3330                         double pct;
3331                         u64 n = (u64) stats->n;
3332
3333                         pct = avg ? 100.0 * stddev_stats(stats)/avg : 0.0;
3334                         avg /= NSEC_PER_MSEC;
3335
3336                         sc = &trace->syscalls.table[syscall_stats_entry->syscall];
3337                         printed += fprintf(fp, "   %-15s", sc->name);
3338                         printed += fprintf(fp, " %8" PRIu64 " %9.3f %9.3f %9.3f",
3339                                            n, syscall_stats_entry->msecs, min, avg);
3340                         printed += fprintf(fp, " %9.3f %9.2f%%\n", max, pct);
3341                 }
3342         }
3343
3344         resort_rb__delete(syscall_stats);
3345         printed += fprintf(fp, "\n\n");
3346
3347         return printed;
3348 }
3349
3350 static size_t trace__fprintf_thread(FILE *fp, struct thread *thread, struct trace *trace)
3351 {
3352         size_t printed = 0;
3353         struct thread_trace *ttrace = thread__priv(thread);
3354         double ratio;
3355
3356         if (ttrace == NULL)
3357                 return 0;
3358
3359         ratio = (double)ttrace->nr_events / trace->nr_events * 100.0;
3360
3361         printed += fprintf(fp, " %s (%d), ", thread__comm_str(thread), thread->tid);
3362         printed += fprintf(fp, "%lu events, ", ttrace->nr_events);
3363         printed += fprintf(fp, "%.1f%%", ratio);
3364         if (ttrace->pfmaj)
3365                 printed += fprintf(fp, ", %lu majfaults", ttrace->pfmaj);
3366         if (ttrace->pfmin)
3367                 printed += fprintf(fp, ", %lu minfaults", ttrace->pfmin);
3368         if (trace->sched)
3369                 printed += fprintf(fp, ", %.3f msec\n", ttrace->runtime_ms);
3370         else if (fputc('\n', fp) != EOF)
3371                 ++printed;
3372
3373         printed += thread__dump_stats(ttrace, trace, fp);
3374
3375         return printed;
3376 }
3377
3378 static unsigned long thread__nr_events(struct thread_trace *ttrace)
3379 {
3380         return ttrace ? ttrace->nr_events : 0;
3381 }
3382
3383 DEFINE_RESORT_RB(threads, (thread__nr_events(a->thread->priv) < thread__nr_events(b->thread->priv)),
3384         struct thread *thread;
3385 )
3386 {
3387         entry->thread = rb_entry(nd, struct thread, rb_node);
3388 }
3389
3390 static size_t trace__fprintf_thread_summary(struct trace *trace, FILE *fp)
3391 {
3392         size_t printed = trace__fprintf_threads_header(fp);
3393         struct rb_node *nd;
3394         int i;
3395
3396         for (i = 0; i < THREADS__TABLE_SIZE; i++) {
3397                 DECLARE_RESORT_RB_MACHINE_THREADS(threads, trace->host, i);
3398
3399                 if (threads == NULL) {
3400                         fprintf(fp, "%s", "Error sorting output by nr_events!\n");
3401                         return 0;
3402                 }
3403
3404                 resort_rb__for_each_entry(nd, threads)
3405                         printed += trace__fprintf_thread(fp, threads_entry->thread, trace);
3406
3407                 resort_rb__delete(threads);
3408         }
3409         return printed;
3410 }
3411
3412 static int trace__set_duration(const struct option *opt, const char *str,
3413                                int unset __maybe_unused)
3414 {
3415         struct trace *trace = opt->value;
3416
3417         trace->duration_filter = atof(str);
3418         return 0;
3419 }
3420
3421 static int trace__set_filter_pids_from_option(const struct option *opt, const char *str,
3422                                               int unset __maybe_unused)
3423 {
3424         int ret = -1;
3425         size_t i;
3426         struct trace *trace = opt->value;
3427         /*
3428          * FIXME: introduce a intarray class, plain parse csv and create a
3429          * { int nr, int entries[] } struct...
3430          */
3431         struct intlist *list = intlist__new(str);
3432
3433         if (list == NULL)
3434                 return -1;
3435
3436         i = trace->filter_pids.nr = intlist__nr_entries(list) + 1;
3437         trace->filter_pids.entries = calloc(i, sizeof(pid_t));
3438
3439         if (trace->filter_pids.entries == NULL)
3440                 goto out;
3441
3442         trace->filter_pids.entries[0] = getpid();
3443
3444         for (i = 1; i < trace->filter_pids.nr; ++i)
3445                 trace->filter_pids.entries[i] = intlist__entry(list, i - 1)->i;
3446
3447         intlist__delete(list);
3448         ret = 0;
3449 out:
3450         return ret;
3451 }
3452
3453 static int trace__open_output(struct trace *trace, const char *filename)
3454 {
3455         struct stat st;
3456
3457         if (!stat(filename, &st) && st.st_size) {
3458                 char oldname[PATH_MAX];
3459
3460                 scnprintf(oldname, sizeof(oldname), "%s.old", filename);
3461                 unlink(oldname);
3462                 rename(filename, oldname);
3463         }
3464
3465         trace->output = fopen(filename, "w");
3466
3467         return trace->output == NULL ? -errno : 0;
3468 }
3469
3470 static int parse_pagefaults(const struct option *opt, const char *str,
3471                             int unset __maybe_unused)
3472 {
3473         int *trace_pgfaults = opt->value;
3474
3475         if (strcmp(str, "all") == 0)
3476                 *trace_pgfaults |= TRACE_PFMAJ | TRACE_PFMIN;
3477         else if (strcmp(str, "maj") == 0)
3478                 *trace_pgfaults |= TRACE_PFMAJ;
3479         else if (strcmp(str, "min") == 0)
3480                 *trace_pgfaults |= TRACE_PFMIN;
3481         else
3482                 return -1;
3483
3484         return 0;
3485 }
3486
3487 static void evlist__set_evsel_handler(struct perf_evlist *evlist, void *handler)
3488 {
3489         struct perf_evsel *evsel;
3490
3491         evlist__for_each_entry(evlist, evsel)
3492                 evsel->handler = handler;
3493 }
3494
3495 static int evlist__set_syscall_tp_fields(struct perf_evlist *evlist)
3496 {
3497         struct perf_evsel *evsel;
3498
3499         evlist__for_each_entry(evlist, evsel) {
3500                 if (evsel->priv || !evsel->tp_format)
3501                         continue;
3502
3503                 if (strcmp(evsel->tp_format->system, "syscalls"))
3504                         continue;
3505
3506                 if (perf_evsel__init_syscall_tp(evsel))
3507                         return -1;
3508
3509                 if (!strncmp(evsel->tp_format->name, "sys_enter_", 10)) {
3510                         struct syscall_tp *sc = evsel->priv;
3511
3512                         if (__tp_field__init_ptr(&sc->args, sc->id.offset + sizeof(u64)))
3513                                 return -1;
3514                 } else if (!strncmp(evsel->tp_format->name, "sys_exit_", 9)) {
3515                         struct syscall_tp *sc = evsel->priv;
3516
3517                         if (__tp_field__init_uint(&sc->ret, sizeof(u64), sc->id.offset + sizeof(u64), evsel->needs_swap))
3518                                 return -1;
3519                 }
3520         }
3521
3522         return 0;
3523 }
3524
3525 /*
3526  * XXX: Hackish, just splitting the combined -e+--event (syscalls
3527  * (raw_syscalls:{sys_{enter,exit}} + events (tracepoints, HW, SW, etc) to use
3528  * existing facilities unchanged (trace->ev_qualifier + parse_options()).
3529  *
3530  * It'd be better to introduce a parse_options() variant that would return a
3531  * list with the terms it didn't match to an event...
3532  */
3533 static int trace__parse_events_option(const struct option *opt, const char *str,
3534                                       int unset __maybe_unused)
3535 {
3536         struct trace *trace = (struct trace *)opt->value;
3537         const char *s = str;
3538         char *sep = NULL, *lists[2] = { NULL, NULL, };
3539         int len = strlen(str) + 1, err = -1, list, idx;
3540         char *strace_groups_dir = system_path(STRACE_GROUPS_DIR);
3541         char group_name[PATH_MAX];
3542         struct syscall_fmt *fmt;
3543
3544         if (strace_groups_dir == NULL)
3545                 return -1;
3546
3547         if (*s == '!') {
3548                 ++s;
3549                 trace->not_ev_qualifier = true;
3550         }
3551
3552         while (1) {
3553                 if ((sep = strchr(s, ',')) != NULL)
3554                         *sep = '\0';
3555
3556                 list = 0;
3557                 if (syscalltbl__id(trace->sctbl, s) >= 0 ||
3558                     syscalltbl__strglobmatch_first(trace->sctbl, s, &idx) >= 0) {
3559                         list = 1;
3560                         goto do_concat;
3561                 }
3562
3563                 fmt = syscall_fmt__find_by_alias(s);
3564                 if (fmt != NULL) {
3565                         list = 1;
3566                         s = fmt->name;
3567                 } else {
3568                         path__join(group_name, sizeof(group_name), strace_groups_dir, s);
3569                         if (access(group_name, R_OK) == 0)
3570                                 list = 1;
3571                 }
3572 do_concat:
3573                 if (lists[list]) {
3574                         sprintf(lists[list] + strlen(lists[list]), ",%s", s);
3575                 } else {
3576                         lists[list] = malloc(len);
3577                         if (lists[list] == NULL)
3578                                 goto out;
3579                         strcpy(lists[list], s);
3580                 }
3581
3582                 if (!sep)
3583                         break;
3584
3585                 *sep = ',';
3586                 s = sep + 1;
3587         }
3588
3589         if (lists[1] != NULL) {
3590                 struct strlist_config slist_config = {
3591                         .dirname = strace_groups_dir,
3592                 };
3593
3594                 trace->ev_qualifier = strlist__new(lists[1], &slist_config);
3595                 if (trace->ev_qualifier == NULL) {
3596                         fputs("Not enough memory to parse event qualifier", trace->output);
3597                         goto out;
3598                 }
3599
3600                 if (trace__validate_ev_qualifier(trace))
3601                         goto out;
3602                 trace->trace_syscalls = true;
3603         }
3604
3605         err = 0;
3606
3607         if (lists[0]) {
3608                 struct option o = OPT_CALLBACK('e', "event", &trace->evlist, "event",
3609                                                "event selector. use 'perf list' to list available events",
3610                                                parse_events_option);
3611                 err = parse_events_option(&o, lists[0], 0);
3612         }
3613 out:
3614         if (sep)
3615                 *sep = ',';
3616
3617         return err;
3618 }
3619
3620 static int trace__parse_cgroups(const struct option *opt, const char *str, int unset)
3621 {
3622         struct trace *trace = opt->value;
3623
3624         if (!list_empty(&trace->evlist->entries))
3625                 return parse_cgroups(opt, str, unset);
3626
3627         trace->cgroup = evlist__findnew_cgroup(trace->evlist, str);
3628
3629         return 0;
3630 }
3631
3632 static struct bpf_map *bpf__find_map_by_name(const char *name)
3633 {
3634         struct bpf_object *obj, *tmp;
3635
3636         bpf_object__for_each_safe(obj, tmp) {
3637                 struct bpf_map *map = bpf_object__find_map_by_name(obj, name);
3638                 if (map)
3639                         return map;
3640
3641         }
3642
3643         return NULL;
3644 }
3645
3646 static void trace__set_bpf_map_filtered_pids(struct trace *trace)
3647 {
3648         trace->filter_pids.map = bpf__find_map_by_name("pids_filtered");
3649 }
3650
3651 static void trace__set_bpf_map_syscalls(struct trace *trace)
3652 {
3653         trace->syscalls.map = bpf__find_map_by_name("syscalls");
3654 }
3655
3656 static int trace__config(const char *var, const char *value, void *arg)
3657 {
3658         struct trace *trace = arg;
3659         int err = 0;
3660
3661         if (!strcmp(var, "trace.add_events")) {
3662                 struct option o = OPT_CALLBACK('e', "event", &trace->evlist, "event",
3663                                                "event selector. use 'perf list' to list available events",
3664                                                parse_events_option);
3665                 err = parse_events_option(&o, value, 0);
3666         } else if (!strcmp(var, "trace.show_timestamp")) {
3667                 trace->show_tstamp = perf_config_bool(var, value);
3668         } else if (!strcmp(var, "trace.show_duration")) {
3669                 trace->show_duration = perf_config_bool(var, value);
3670         } else if (!strcmp(var, "trace.show_arg_names")) {
3671                 trace->show_arg_names = perf_config_bool(var, value);
3672                 if (!trace->show_arg_names)
3673                         trace->show_zeros = true;
3674         } else if (!strcmp(var, "trace.show_zeros")) {
3675                 bool new_show_zeros = perf_config_bool(var, value);
3676                 if (!trace->show_arg_names && !new_show_zeros) {
3677                         pr_warning("trace.show_zeros has to be set when trace.show_arg_names=no\n");
3678                         goto out;
3679                 }
3680                 trace->show_zeros = new_show_zeros;
3681         } else if (!strcmp(var, "trace.show_prefix")) {
3682                 trace->show_string_prefix = perf_config_bool(var, value);
3683         } else if (!strcmp(var, "trace.no_inherit")) {
3684                 trace->opts.no_inherit = perf_config_bool(var, value);
3685         } else if (!strcmp(var, "trace.args_alignment")) {
3686                 int args_alignment = 0;
3687                 if (perf_config_int(&args_alignment, var, value) == 0)
3688                         trace->args_alignment = args_alignment;
3689         }
3690 out:
3691         return err;
3692 }
3693
3694 int cmd_trace(int argc, const char **argv)
3695 {
3696         const char *trace_usage[] = {
3697                 "perf trace [<options>] [<command>]",
3698                 "perf trace [<options>] -- <command> [<options>]",
3699                 "perf trace record [<options>] [<command>]",
3700                 "perf trace record [<options>] -- <command> [<options>]",
3701                 NULL
3702         };
3703         struct trace trace = {
3704                 .syscalls = {
3705                         . max = -1,
3706                 },
3707                 .opts = {
3708                         .target = {
3709                                 .uid       = UINT_MAX,
3710                                 .uses_mmap = true,
3711                         },
3712                         .user_freq     = UINT_MAX,
3713                         .user_interval = ULLONG_MAX,
3714                         .no_buffering  = true,
3715                         .mmap_pages    = UINT_MAX,
3716                 },
3717                 .output = stderr,
3718                 .show_comm = true,
3719                 .show_tstamp = true,
3720                 .show_duration = true,
3721                 .show_arg_names = true,
3722                 .args_alignment = 70,
3723                 .trace_syscalls = false,
3724                 .kernel_syscallchains = false,
3725                 .max_stack = UINT_MAX,
3726                 .max_events = ULONG_MAX,
3727         };
3728         const char *map_dump_str = NULL;
3729         const char *output_name = NULL;
3730         const struct option trace_options[] = {
3731         OPT_CALLBACK('e', "event", &trace, "event",
3732                      "event/syscall selector. use 'perf list' to list available events",
3733                      trace__parse_events_option),
3734         OPT_BOOLEAN(0, "comm", &trace.show_comm,
3735                     "show the thread COMM next to its id"),
3736         OPT_BOOLEAN(0, "tool_stats", &trace.show_tool_stats, "show tool stats"),
3737         OPT_CALLBACK(0, "expr", &trace, "expr", "list of syscalls/events to trace",
3738                      trace__parse_events_option),
3739         OPT_STRING('o', "output", &output_name, "file", "output file name"),
3740         OPT_STRING('i', "input", &input_name, "file", "Analyze events in file"),
3741         OPT_STRING('p', "pid", &trace.opts.target.pid, "pid",
3742                     "trace events on existing process id"),
3743         OPT_STRING('t', "tid", &trace.opts.target.tid, "tid",
3744                     "trace events on existing thread id"),
3745         OPT_CALLBACK(0, "filter-pids", &trace, "CSV list of pids",
3746                      "pids to filter (by the kernel)", trace__set_filter_pids_from_option),
3747         OPT_BOOLEAN('a', "all-cpus", &trace.opts.target.system_wide,
3748                     "system-wide collection from all CPUs"),
3749         OPT_STRING('C', "cpu", &trace.opts.target.cpu_list, "cpu",
3750                     "list of cpus to monitor"),
3751         OPT_BOOLEAN(0, "no-inherit", &trace.opts.no_inherit,
3752                     "child tasks do not inherit counters"),
3753         OPT_CALLBACK('m', "mmap-pages", &trace.opts.mmap_pages, "pages",
3754                      "number of mmap data pages",
3755                      perf_evlist__parse_mmap_pages),
3756         OPT_STRING('u', "uid", &trace.opts.target.uid_str, "user",
3757                    "user to profile"),
3758         OPT_CALLBACK(0, "duration", &trace, "float",
3759                      "show only events with duration > N.M ms",
3760                      trace__set_duration),
3761 #ifdef HAVE_LIBBPF_SUPPORT
3762         OPT_STRING(0, "map-dump", &map_dump_str, "BPF map", "BPF map to periodically dump"),
3763 #endif
3764         OPT_BOOLEAN(0, "sched", &trace.sched, "show blocking scheduler events"),
3765         OPT_INCR('v', "verbose", &verbose, "be more verbose"),
3766         OPT_BOOLEAN('T', "time", &trace.full_time,
3767                     "Show full timestamp, not time relative to first start"),
3768         OPT_BOOLEAN(0, "failure", &trace.failure_only,
3769                     "Show only syscalls that failed"),
3770         OPT_BOOLEAN('s', "summary", &trace.summary_only,
3771                     "Show only syscall summary with statistics"),
3772         OPT_BOOLEAN('S', "with-summary", &trace.summary,
3773                     "Show all syscalls and summary with statistics"),
3774         OPT_CALLBACK_DEFAULT('F', "pf", &trace.trace_pgfaults, "all|maj|min",
3775                      "Trace pagefaults", parse_pagefaults, "maj"),
3776         OPT_BOOLEAN(0, "syscalls", &trace.trace_syscalls, "Trace syscalls"),
3777         OPT_BOOLEAN('f', "force", &trace.force, "don't complain, do it"),
3778         OPT_CALLBACK(0, "call-graph", &trace.opts,
3779                      "record_mode[,record_size]", record_callchain_help,
3780                      &record_parse_callchain_opt),
3781         OPT_BOOLEAN(0, "kernel-syscall-graph", &trace.kernel_syscallchains,
3782                     "Show the kernel callchains on the syscall exit path"),
3783         OPT_ULONG(0, "max-events", &trace.max_events,
3784                 "Set the maximum number of events to print, exit after that is reached. "),
3785         OPT_UINTEGER(0, "min-stack", &trace.min_stack,
3786                      "Set the minimum stack depth when parsing the callchain, "
3787                      "anything below the specified depth will be ignored."),
3788         OPT_UINTEGER(0, "max-stack", &trace.max_stack,
3789                      "Set the maximum stack depth when parsing the callchain, "
3790                      "anything beyond the specified depth will be ignored. "
3791                      "Default: kernel.perf_event_max_stack or " __stringify(PERF_MAX_STACK_DEPTH)),
3792         OPT_BOOLEAN(0, "sort-events", &trace.sort_events,
3793                         "Sort batch of events before processing, use if getting out of order events"),
3794         OPT_BOOLEAN(0, "print-sample", &trace.print_sample,
3795                         "print the PERF_RECORD_SAMPLE PERF_SAMPLE_ info, for debugging"),
3796         OPT_UINTEGER(0, "proc-map-timeout", &proc_map_timeout,
3797                         "per thread proc mmap processing timeout in ms"),
3798         OPT_CALLBACK('G', "cgroup", &trace, "name", "monitor event in cgroup name only",
3799                      trace__parse_cgroups),
3800         OPT_UINTEGER('D', "delay", &trace.opts.initial_delay,
3801                      "ms to wait before starting measurement after program "
3802                      "start"),
3803         OPT_END()
3804         };
3805         bool __maybe_unused max_stack_user_set = true;
3806         bool mmap_pages_user_set = true;
3807         struct perf_evsel *evsel;
3808         const char * const trace_subcommands[] = { "record", NULL };
3809         int err = -1;
3810         char bf[BUFSIZ];
3811
3812         signal(SIGSEGV, sighandler_dump_stack);
3813         signal(SIGFPE, sighandler_dump_stack);
3814
3815         trace.evlist = perf_evlist__new();
3816         trace.sctbl = syscalltbl__new();
3817
3818         if (trace.evlist == NULL || trace.sctbl == NULL) {
3819                 pr_err("Not enough memory to run!\n");
3820                 err = -ENOMEM;
3821                 goto out;
3822         }
3823
3824         err = perf_config(trace__config, &trace);
3825         if (err)
3826                 goto out;
3827
3828         argc = parse_options_subcommand(argc, argv, trace_options, trace_subcommands,
3829                                  trace_usage, PARSE_OPT_STOP_AT_NON_OPTION);
3830
3831         if ((nr_cgroups || trace.cgroup) && !trace.opts.target.system_wide) {
3832                 usage_with_options_msg(trace_usage, trace_options,
3833                                        "cgroup monitoring only available in system-wide mode");
3834         }
3835
3836         evsel = bpf__setup_output_event(trace.evlist, "__augmented_syscalls__");
3837         if (IS_ERR(evsel)) {
3838                 bpf__strerror_setup_output_event(trace.evlist, PTR_ERR(evsel), bf, sizeof(bf));
3839                 pr_err("ERROR: Setup trace syscalls enter failed: %s\n", bf);
3840                 goto out;
3841         }
3842
3843         if (evsel) {
3844                 trace.syscalls.events.augmented = evsel;
3845                 trace__set_bpf_map_filtered_pids(&trace);
3846                 trace__set_bpf_map_syscalls(&trace);
3847         }
3848
3849         err = bpf__setup_stdout(trace.evlist);
3850         if (err) {
3851                 bpf__strerror_setup_stdout(trace.evlist, err, bf, sizeof(bf));
3852                 pr_err("ERROR: Setup BPF stdout failed: %s\n", bf);
3853                 goto out;
3854         }
3855
3856         err = -1;
3857
3858         if (map_dump_str) {
3859                 trace.dump.map = bpf__find_map_by_name(map_dump_str);
3860                 if (trace.dump.map == NULL) {
3861                         pr_err("ERROR: BPF map \"%s\" not found\n", map_dump_str);
3862                         goto out;
3863                 }
3864         }
3865
3866         if (trace.trace_pgfaults) {
3867                 trace.opts.sample_address = true;
3868                 trace.opts.sample_time = true;
3869         }
3870
3871         if (trace.opts.mmap_pages == UINT_MAX)
3872                 mmap_pages_user_set = false;
3873
3874         if (trace.max_stack == UINT_MAX) {
3875                 trace.max_stack = input_name ? PERF_MAX_STACK_DEPTH : sysctl__max_stack();
3876                 max_stack_user_set = false;
3877         }
3878
3879 #ifdef HAVE_DWARF_UNWIND_SUPPORT
3880         if ((trace.min_stack || max_stack_user_set) && !callchain_param.enabled) {
3881                 record_opts__parse_callchain(&trace.opts, &callchain_param, "dwarf", false);
3882         }
3883 #endif
3884
3885         if (callchain_param.enabled) {
3886                 if (!mmap_pages_user_set && geteuid() == 0)
3887                         trace.opts.mmap_pages = perf_event_mlock_kb_in_pages() * 4;
3888
3889                 symbol_conf.use_callchain = true;
3890         }
3891
3892         if (trace.evlist->nr_entries > 0) {
3893                 evlist__set_evsel_handler(trace.evlist, trace__event_handler);
3894                 if (evlist__set_syscall_tp_fields(trace.evlist)) {
3895                         perror("failed to set syscalls:* tracepoint fields");
3896                         goto out;
3897                 }
3898         }
3899
3900         if (trace.sort_events) {
3901                 ordered_events__init(&trace.oe.data, ordered_events__deliver_event, &trace);
3902                 ordered_events__set_copy_on_queue(&trace.oe.data, true);
3903         }
3904
3905         /*
3906          * If we are augmenting syscalls, then combine what we put in the
3907          * __augmented_syscalls__ BPF map with what is in the
3908          * syscalls:sys_exit_FOO tracepoints, i.e. just like we do without BPF,
3909          * combining raw_syscalls:sys_enter with raw_syscalls:sys_exit.
3910          *
3911          * We'll switch to look at two BPF maps, one for sys_enter and the
3912          * other for sys_exit when we start augmenting the sys_exit paths with
3913          * buffers that are being copied from kernel to userspace, think 'read'
3914          * syscall.
3915          */
3916         if (trace.syscalls.events.augmented) {
3917                 evlist__for_each_entry(trace.evlist, evsel) {
3918                         bool raw_syscalls_sys_exit = strcmp(perf_evsel__name(evsel), "raw_syscalls:sys_exit") == 0;
3919
3920                         if (raw_syscalls_sys_exit) {
3921                                 trace.raw_augmented_syscalls = true;
3922                                 goto init_augmented_syscall_tp;
3923                         }
3924
3925                         if (trace.syscalls.events.augmented->priv == NULL &&
3926                             strstr(perf_evsel__name(evsel), "syscalls:sys_enter")) {
3927                                 struct perf_evsel *augmented = trace.syscalls.events.augmented;
3928                                 if (perf_evsel__init_augmented_syscall_tp(augmented, evsel) ||
3929                                     perf_evsel__init_augmented_syscall_tp_args(augmented))
3930                                         goto out;
3931                                 augmented->handler = trace__sys_enter;
3932                         }
3933
3934                         if (strstarts(perf_evsel__name(evsel), "syscalls:sys_exit_")) {
3935                                 struct syscall_tp *sc;
3936 init_augmented_syscall_tp:
3937                                 if (perf_evsel__init_augmented_syscall_tp(evsel, evsel))
3938                                         goto out;
3939                                 sc = evsel->priv;
3940                                 /*
3941                                  * For now with BPF raw_augmented we hook into
3942                                  * raw_syscalls:sys_enter and there we get all
3943                                  * 6 syscall args plus the tracepoint common
3944                                  * fields and the syscall_nr (another long).
3945                                  * So we check if that is the case and if so
3946                                  * don't look after the sc->args_size but
3947                                  * always after the full raw_syscalls:sys_enter
3948                                  * payload, which is fixed.
3949                                  *
3950                                  * We'll revisit this later to pass
3951                                  * s->args_size to the BPF augmenter (now
3952                                  * tools/perf/examples/bpf/augmented_raw_syscalls.c,
3953                                  * so that it copies only what we need for each
3954                                  * syscall, like what happens when we use
3955                                  * syscalls:sys_enter_NAME, so that we reduce
3956                                  * the kernel/userspace traffic to just what is
3957                                  * needed for each syscall.
3958                                  */
3959                                 if (trace.raw_augmented_syscalls)
3960                                         trace.raw_augmented_syscalls_args_size = (6 + 1) * sizeof(long) + sc->id.offset;
3961                                 perf_evsel__init_augmented_syscall_tp_ret(evsel);
3962                                 evsel->handler = trace__sys_exit;
3963                         }
3964                 }
3965         }
3966
3967         if ((argc >= 1) && (strcmp(argv[0], "record") == 0))
3968                 return trace__record(&trace, argc-1, &argv[1]);
3969
3970         /* summary_only implies summary option, but don't overwrite summary if set */
3971         if (trace.summary_only)
3972                 trace.summary = trace.summary_only;
3973
3974         if (!trace.trace_syscalls && !trace.trace_pgfaults &&
3975             trace.evlist->nr_entries == 0 /* Was --events used? */) {
3976                 trace.trace_syscalls = true;
3977         }
3978
3979         if (output_name != NULL) {
3980                 err = trace__open_output(&trace, output_name);
3981                 if (err < 0) {
3982                         perror("failed to create output file");
3983                         goto out;
3984                 }
3985         }
3986
3987         err = target__validate(&trace.opts.target);
3988         if (err) {
3989                 target__strerror(&trace.opts.target, err, bf, sizeof(bf));
3990                 fprintf(trace.output, "%s", bf);
3991                 goto out_close;
3992         }
3993
3994         err = target__parse_uid(&trace.opts.target);
3995         if (err) {
3996                 target__strerror(&trace.opts.target, err, bf, sizeof(bf));
3997                 fprintf(trace.output, "%s", bf);
3998                 goto out_close;
3999         }
4000
4001         if (!argc && target__none(&trace.opts.target))
4002                 trace.opts.target.system_wide = true;
4003
4004         if (input_name)
4005                 err = trace__replay(&trace);
4006         else
4007                 err = trace__run(&trace, argc, argv);
4008
4009 out_close:
4010         if (output_name != NULL)
4011                 fclose(trace.output);
4012 out:
4013         return err;
4014 }