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