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