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