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