perf trace: Enclose strings with double quotes
[linux/fpc-iii.git] / tools / perf / builtin-trace.c
blobdc8cadeb3fa5c23f05ea878c13e7d738485985c0
1 /*
2 * builtin-trace.c
4 * Builtin 'trace' command:
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.
10 * Copyright (C) 2012, 2013, 2014, 2015 Red Hat Inc, Arnaldo Carvalho de Melo <acme@redhat.com>
12 * Initially based on the 'trace' prototype by Thomas Gleixner:
14 * http://lwn.net/Articles/415728/ ("Announcing a new utility: 'trace'")
16 * Released under the GPL v2. (and only v2, not any later version)
19 #include <traceevent/event-parse.h>
20 #include <api/fs/tracing_path.h>
21 #include <bpf/bpf.h>
22 #include "builtin.h"
23 #include "util/cgroup.h"
24 #include "util/color.h"
25 #include "util/config.h"
26 #include "util/debug.h"
27 #include "util/env.h"
28 #include "util/event.h"
29 #include "util/evlist.h"
30 #include <subcmd/exec-cmd.h>
31 #include "util/machine.h"
32 #include "util/path.h"
33 #include "util/session.h"
34 #include "util/thread.h"
35 #include <subcmd/parse-options.h>
36 #include "util/strlist.h"
37 #include "util/intlist.h"
38 #include "util/thread_map.h"
39 #include "util/stat.h"
40 #include "trace/beauty/beauty.h"
41 #include "trace-event.h"
42 #include "util/parse-events.h"
43 #include "util/bpf-loader.h"
44 #include "callchain.h"
45 #include "print_binary.h"
46 #include "string2.h"
47 #include "syscalltbl.h"
48 #include "rb_resort.h"
50 #include <errno.h>
51 #include <inttypes.h>
52 #include <poll.h>
53 #include <signal.h>
54 #include <stdlib.h>
55 #include <string.h>
56 #include <linux/err.h>
57 #include <linux/filter.h>
58 #include <linux/kernel.h>
59 #include <linux/random.h>
60 #include <linux/stringify.h>
61 #include <linux/time64.h>
62 #include <fcntl.h>
64 #include "sane_ctype.h"
66 #ifndef O_CLOEXEC
67 # define O_CLOEXEC 02000000
68 #endif
70 #ifndef F_LINUX_SPECIFIC_BASE
71 # define F_LINUX_SPECIFIC_BASE 1024
72 #endif
74 struct trace {
75 struct perf_tool tool;
76 struct syscalltbl *sctbl;
77 struct {
78 int max;
79 struct syscall *table;
80 struct bpf_map *map;
81 struct {
82 struct perf_evsel *sys_enter,
83 *sys_exit,
84 *augmented;
85 } events;
86 } syscalls;
87 struct record_opts opts;
88 struct perf_evlist *evlist;
89 struct machine *host;
90 struct thread *current;
91 struct cgroup *cgroup;
92 u64 base_time;
93 FILE *output;
94 unsigned long nr_events;
95 unsigned long nr_events_printed;
96 unsigned long max_events;
97 struct strlist *ev_qualifier;
98 struct {
99 size_t nr;
100 int *entries;
101 } ev_qualifier_ids;
102 struct {
103 size_t nr;
104 pid_t *entries;
105 struct bpf_map *map;
106 } filter_pids;
107 double duration_filter;
108 double runtime_ms;
109 struct {
110 u64 vfs_getname,
111 proc_getname;
112 } stats;
113 unsigned int max_stack;
114 unsigned int min_stack;
115 bool sort_events;
116 bool raw_augmented_syscalls;
117 bool not_ev_qualifier;
118 bool live;
119 bool full_time;
120 bool sched;
121 bool multiple_threads;
122 bool summary;
123 bool summary_only;
124 bool failure_only;
125 bool show_comm;
126 bool print_sample;
127 bool show_tool_stats;
128 bool trace_syscalls;
129 bool kernel_syscallchains;
130 s16 args_alignment;
131 bool show_tstamp;
132 bool show_duration;
133 bool show_zeros;
134 bool show_arg_names;
135 bool force;
136 bool vfs_getname;
137 int trace_pgfaults;
138 struct {
139 struct ordered_events data;
140 u64 last;
141 } oe;
144 struct tp_field {
145 int offset;
146 union {
147 u64 (*integer)(struct tp_field *field, struct perf_sample *sample);
148 void *(*pointer)(struct tp_field *field, struct perf_sample *sample);
152 #define TP_UINT_FIELD(bits) \
153 static u64 tp_field__u##bits(struct tp_field *field, struct perf_sample *sample) \
155 u##bits value; \
156 memcpy(&value, sample->raw_data + field->offset, sizeof(value)); \
157 return value; \
160 TP_UINT_FIELD(8);
161 TP_UINT_FIELD(16);
162 TP_UINT_FIELD(32);
163 TP_UINT_FIELD(64);
165 #define TP_UINT_FIELD__SWAPPED(bits) \
166 static u64 tp_field__swapped_u##bits(struct tp_field *field, struct perf_sample *sample) \
168 u##bits value; \
169 memcpy(&value, sample->raw_data + field->offset, sizeof(value)); \
170 return bswap_##bits(value);\
173 TP_UINT_FIELD__SWAPPED(16);
174 TP_UINT_FIELD__SWAPPED(32);
175 TP_UINT_FIELD__SWAPPED(64);
177 static int __tp_field__init_uint(struct tp_field *field, int size, int offset, bool needs_swap)
179 field->offset = offset;
181 switch (size) {
182 case 1:
183 field->integer = tp_field__u8;
184 break;
185 case 2:
186 field->integer = needs_swap ? tp_field__swapped_u16 : tp_field__u16;
187 break;
188 case 4:
189 field->integer = needs_swap ? tp_field__swapped_u32 : tp_field__u32;
190 break;
191 case 8:
192 field->integer = needs_swap ? tp_field__swapped_u64 : tp_field__u64;
193 break;
194 default:
195 return -1;
198 return 0;
201 static int tp_field__init_uint(struct tp_field *field, struct tep_format_field *format_field, bool needs_swap)
203 return __tp_field__init_uint(field, format_field->size, format_field->offset, needs_swap);
206 static void *tp_field__ptr(struct tp_field *field, struct perf_sample *sample)
208 return sample->raw_data + field->offset;
211 static int __tp_field__init_ptr(struct tp_field *field, int offset)
213 field->offset = offset;
214 field->pointer = tp_field__ptr;
215 return 0;
218 static int tp_field__init_ptr(struct tp_field *field, struct tep_format_field *format_field)
220 return __tp_field__init_ptr(field, format_field->offset);
223 struct syscall_tp {
224 struct tp_field id;
225 union {
226 struct tp_field args, ret;
230 static int perf_evsel__init_tp_uint_field(struct perf_evsel *evsel,
231 struct tp_field *field,
232 const char *name)
234 struct tep_format_field *format_field = perf_evsel__field(evsel, name);
236 if (format_field == NULL)
237 return -1;
239 return tp_field__init_uint(field, format_field, evsel->needs_swap);
242 #define perf_evsel__init_sc_tp_uint_field(evsel, name) \
243 ({ struct syscall_tp *sc = evsel->priv;\
244 perf_evsel__init_tp_uint_field(evsel, &sc->name, #name); })
246 static int perf_evsel__init_tp_ptr_field(struct perf_evsel *evsel,
247 struct tp_field *field,
248 const char *name)
250 struct tep_format_field *format_field = perf_evsel__field(evsel, name);
252 if (format_field == NULL)
253 return -1;
255 return tp_field__init_ptr(field, format_field);
258 #define perf_evsel__init_sc_tp_ptr_field(evsel, name) \
259 ({ struct syscall_tp *sc = evsel->priv;\
260 perf_evsel__init_tp_ptr_field(evsel, &sc->name, #name); })
262 static void perf_evsel__delete_priv(struct perf_evsel *evsel)
264 zfree(&evsel->priv);
265 perf_evsel__delete(evsel);
268 static int perf_evsel__init_syscall_tp(struct perf_evsel *evsel)
270 struct syscall_tp *sc = evsel->priv = malloc(sizeof(struct syscall_tp));
272 if (evsel->priv != NULL) {
273 if (perf_evsel__init_tp_uint_field(evsel, &sc->id, "__syscall_nr") &&
274 perf_evsel__init_tp_uint_field(evsel, &sc->id, "nr"))
275 goto out_delete;
276 return 0;
279 return -ENOMEM;
280 out_delete:
281 zfree(&evsel->priv);
282 return -ENOENT;
285 static int perf_evsel__init_augmented_syscall_tp(struct perf_evsel *evsel)
287 struct syscall_tp *sc = evsel->priv = malloc(sizeof(struct syscall_tp));
289 if (evsel->priv != NULL) { /* field, sizeof_field, offsetof_field */
290 if (__tp_field__init_uint(&sc->id, sizeof(long), sizeof(long long), evsel->needs_swap))
291 goto out_delete;
293 return 0;
296 return -ENOMEM;
297 out_delete:
298 zfree(&evsel->priv);
299 return -EINVAL;
302 static int perf_evsel__init_augmented_syscall_tp_args(struct perf_evsel *evsel)
304 struct syscall_tp *sc = evsel->priv;
306 return __tp_field__init_ptr(&sc->args, sc->id.offset + sizeof(u64));
309 static int perf_evsel__init_augmented_syscall_tp_ret(struct perf_evsel *evsel)
311 struct syscall_tp *sc = evsel->priv;
313 return __tp_field__init_uint(&sc->ret, sizeof(u64), sc->id.offset + sizeof(u64), evsel->needs_swap);
316 static int perf_evsel__init_raw_syscall_tp(struct perf_evsel *evsel, void *handler)
318 evsel->priv = malloc(sizeof(struct syscall_tp));
319 if (evsel->priv != NULL) {
320 if (perf_evsel__init_sc_tp_uint_field(evsel, id))
321 goto out_delete;
323 evsel->handler = handler;
324 return 0;
327 return -ENOMEM;
329 out_delete:
330 zfree(&evsel->priv);
331 return -ENOENT;
334 static struct perf_evsel *perf_evsel__raw_syscall_newtp(const char *direction, void *handler)
336 struct perf_evsel *evsel = perf_evsel__newtp("raw_syscalls", direction);
338 /* older kernel (e.g., RHEL6) use syscalls:{enter,exit} */
339 if (IS_ERR(evsel))
340 evsel = perf_evsel__newtp("syscalls", direction);
342 if (IS_ERR(evsel))
343 return NULL;
345 if (perf_evsel__init_raw_syscall_tp(evsel, handler))
346 goto out_delete;
348 return evsel;
350 out_delete:
351 perf_evsel__delete_priv(evsel);
352 return NULL;
355 #define perf_evsel__sc_tp_uint(evsel, name, sample) \
356 ({ struct syscall_tp *fields = evsel->priv; \
357 fields->name.integer(&fields->name, sample); })
359 #define perf_evsel__sc_tp_ptr(evsel, name, sample) \
360 ({ struct syscall_tp *fields = evsel->priv; \
361 fields->name.pointer(&fields->name, sample); })
363 size_t strarray__scnprintf(struct strarray *sa, char *bf, size_t size, const char *intfmt, int val)
365 int idx = val - sa->offset;
367 if (idx < 0 || idx >= sa->nr_entries || sa->entries[idx] == NULL)
368 return scnprintf(bf, size, intfmt, val);
370 return scnprintf(bf, size, "%s", sa->entries[idx]);
373 static size_t __syscall_arg__scnprintf_strarray(char *bf, size_t size,
374 const char *intfmt,
375 struct syscall_arg *arg)
377 return strarray__scnprintf(arg->parm, bf, size, intfmt, arg->val);
380 static size_t syscall_arg__scnprintf_strarray(char *bf, size_t size,
381 struct syscall_arg *arg)
383 return __syscall_arg__scnprintf_strarray(bf, size, "%d", arg);
386 #define SCA_STRARRAY syscall_arg__scnprintf_strarray
388 struct strarrays {
389 int nr_entries;
390 struct strarray **entries;
393 #define DEFINE_STRARRAYS(array) struct strarrays strarrays__##array = { \
394 .nr_entries = ARRAY_SIZE(array), \
395 .entries = array, \
398 size_t syscall_arg__scnprintf_strarrays(char *bf, size_t size,
399 struct syscall_arg *arg)
401 struct strarrays *sas = arg->parm;
402 int i;
404 for (i = 0; i < sas->nr_entries; ++i) {
405 struct strarray *sa = sas->entries[i];
406 int idx = arg->val - sa->offset;
408 if (idx >= 0 && idx < sa->nr_entries) {
409 if (sa->entries[idx] == NULL)
410 break;
411 return scnprintf(bf, size, "%s", sa->entries[idx]);
415 return scnprintf(bf, size, "%d", arg->val);
418 #ifndef AT_FDCWD
419 #define AT_FDCWD -100
420 #endif
422 static size_t syscall_arg__scnprintf_fd_at(char *bf, size_t size,
423 struct syscall_arg *arg)
425 int fd = arg->val;
427 if (fd == AT_FDCWD)
428 return scnprintf(bf, size, "CWD");
430 return syscall_arg__scnprintf_fd(bf, size, arg);
433 #define SCA_FDAT syscall_arg__scnprintf_fd_at
435 static size_t syscall_arg__scnprintf_close_fd(char *bf, size_t size,
436 struct syscall_arg *arg);
438 #define SCA_CLOSE_FD syscall_arg__scnprintf_close_fd
440 size_t syscall_arg__scnprintf_hex(char *bf, size_t size, struct syscall_arg *arg)
442 return scnprintf(bf, size, "%#lx", arg->val);
445 size_t syscall_arg__scnprintf_int(char *bf, size_t size, struct syscall_arg *arg)
447 return scnprintf(bf, size, "%d", arg->val);
450 size_t syscall_arg__scnprintf_long(char *bf, size_t size, struct syscall_arg *arg)
452 return scnprintf(bf, size, "%ld", arg->val);
455 static const char *bpf_cmd[] = {
456 "MAP_CREATE", "MAP_LOOKUP_ELEM", "MAP_UPDATE_ELEM", "MAP_DELETE_ELEM",
457 "MAP_GET_NEXT_KEY", "PROG_LOAD",
459 static DEFINE_STRARRAY(bpf_cmd);
461 static const char *epoll_ctl_ops[] = { "ADD", "DEL", "MOD", };
462 static DEFINE_STRARRAY_OFFSET(epoll_ctl_ops, 1);
464 static const char *itimers[] = { "REAL", "VIRTUAL", "PROF", };
465 static DEFINE_STRARRAY(itimers);
467 static const char *keyctl_options[] = {
468 "GET_KEYRING_ID", "JOIN_SESSION_KEYRING", "UPDATE", "REVOKE", "CHOWN",
469 "SETPERM", "DESCRIBE", "CLEAR", "LINK", "UNLINK", "SEARCH", "READ",
470 "INSTANTIATE", "NEGATE", "SET_REQKEY_KEYRING", "SET_TIMEOUT",
471 "ASSUME_AUTHORITY", "GET_SECURITY", "SESSION_TO_PARENT", "REJECT",
472 "INSTANTIATE_IOV", "INVALIDATE", "GET_PERSISTENT",
474 static DEFINE_STRARRAY(keyctl_options);
476 static const char *whences[] = { "SET", "CUR", "END",
477 #ifdef SEEK_DATA
478 "DATA",
479 #endif
480 #ifdef SEEK_HOLE
481 "HOLE",
482 #endif
484 static DEFINE_STRARRAY(whences);
486 static const char *fcntl_cmds[] = {
487 "DUPFD", "GETFD", "SETFD", "GETFL", "SETFL", "GETLK", "SETLK",
488 "SETLKW", "SETOWN", "GETOWN", "SETSIG", "GETSIG", "GETLK64",
489 "SETLK64", "SETLKW64", "SETOWN_EX", "GETOWN_EX",
490 "GETOWNER_UIDS",
492 static DEFINE_STRARRAY(fcntl_cmds);
494 static const char *fcntl_linux_specific_cmds[] = {
495 "SETLEASE", "GETLEASE", "NOTIFY", [5] = "CANCELLK", "DUPFD_CLOEXEC",
496 "SETPIPE_SZ", "GETPIPE_SZ", "ADD_SEALS", "GET_SEALS",
497 "GET_RW_HINT", "SET_RW_HINT", "GET_FILE_RW_HINT", "SET_FILE_RW_HINT",
500 static DEFINE_STRARRAY_OFFSET(fcntl_linux_specific_cmds, F_LINUX_SPECIFIC_BASE);
502 static struct strarray *fcntl_cmds_arrays[] = {
503 &strarray__fcntl_cmds,
504 &strarray__fcntl_linux_specific_cmds,
507 static DEFINE_STRARRAYS(fcntl_cmds_arrays);
509 static const char *rlimit_resources[] = {
510 "CPU", "FSIZE", "DATA", "STACK", "CORE", "RSS", "NPROC", "NOFILE",
511 "MEMLOCK", "AS", "LOCKS", "SIGPENDING", "MSGQUEUE", "NICE", "RTPRIO",
512 "RTTIME",
514 static DEFINE_STRARRAY(rlimit_resources);
516 static const char *sighow[] = { "BLOCK", "UNBLOCK", "SETMASK", };
517 static DEFINE_STRARRAY(sighow);
519 static const char *clockid[] = {
520 "REALTIME", "MONOTONIC", "PROCESS_CPUTIME_ID", "THREAD_CPUTIME_ID",
521 "MONOTONIC_RAW", "REALTIME_COARSE", "MONOTONIC_COARSE", "BOOTTIME",
522 "REALTIME_ALARM", "BOOTTIME_ALARM", "SGI_CYCLE", "TAI"
524 static DEFINE_STRARRAY(clockid);
526 static size_t syscall_arg__scnprintf_access_mode(char *bf, size_t size,
527 struct syscall_arg *arg)
529 size_t printed = 0;
530 int mode = arg->val;
532 if (mode == F_OK) /* 0 */
533 return scnprintf(bf, size, "F");
534 #define P_MODE(n) \
535 if (mode & n##_OK) { \
536 printed += scnprintf(bf + printed, size - printed, "%s", #n); \
537 mode &= ~n##_OK; \
540 P_MODE(R);
541 P_MODE(W);
542 P_MODE(X);
543 #undef P_MODE
545 if (mode)
546 printed += scnprintf(bf + printed, size - printed, "|%#x", mode);
548 return printed;
551 #define SCA_ACCMODE syscall_arg__scnprintf_access_mode
553 static size_t syscall_arg__scnprintf_filename(char *bf, size_t size,
554 struct syscall_arg *arg);
556 #define SCA_FILENAME syscall_arg__scnprintf_filename
558 static size_t syscall_arg__scnprintf_pipe_flags(char *bf, size_t size,
559 struct syscall_arg *arg)
561 int printed = 0, flags = arg->val;
563 #define P_FLAG(n) \
564 if (flags & O_##n) { \
565 printed += scnprintf(bf + printed, size - printed, "%s%s", printed ? "|" : "", #n); \
566 flags &= ~O_##n; \
569 P_FLAG(CLOEXEC);
570 P_FLAG(NONBLOCK);
571 #undef P_FLAG
573 if (flags)
574 printed += scnprintf(bf + printed, size - printed, "%s%#x", printed ? "|" : "", flags);
576 return printed;
579 #define SCA_PIPE_FLAGS syscall_arg__scnprintf_pipe_flags
581 #ifndef GRND_NONBLOCK
582 #define GRND_NONBLOCK 0x0001
583 #endif
584 #ifndef GRND_RANDOM
585 #define GRND_RANDOM 0x0002
586 #endif
588 static size_t syscall_arg__scnprintf_getrandom_flags(char *bf, size_t size,
589 struct syscall_arg *arg)
591 int printed = 0, flags = arg->val;
593 #define P_FLAG(n) \
594 if (flags & GRND_##n) { \
595 printed += scnprintf(bf + printed, size - printed, "%s%s", printed ? "|" : "", #n); \
596 flags &= ~GRND_##n; \
599 P_FLAG(RANDOM);
600 P_FLAG(NONBLOCK);
601 #undef P_FLAG
603 if (flags)
604 printed += scnprintf(bf + printed, size - printed, "%s%#x", printed ? "|" : "", flags);
606 return printed;
609 #define SCA_GETRANDOM_FLAGS syscall_arg__scnprintf_getrandom_flags
611 #define STRARRAY(name, array) \
612 { .scnprintf = SCA_STRARRAY, \
613 .parm = &strarray__##array, }
615 #include "trace/beauty/arch_errno_names.c"
616 #include "trace/beauty/eventfd.c"
617 #include "trace/beauty/futex_op.c"
618 #include "trace/beauty/futex_val3.c"
619 #include "trace/beauty/mmap.c"
620 #include "trace/beauty/mode_t.c"
621 #include "trace/beauty/msg_flags.c"
622 #include "trace/beauty/open_flags.c"
623 #include "trace/beauty/perf_event_open.c"
624 #include "trace/beauty/pid.c"
625 #include "trace/beauty/sched_policy.c"
626 #include "trace/beauty/seccomp.c"
627 #include "trace/beauty/signum.c"
628 #include "trace/beauty/socket_type.c"
629 #include "trace/beauty/waitid_options.c"
631 struct syscall_arg_fmt {
632 size_t (*scnprintf)(char *bf, size_t size, struct syscall_arg *arg);
633 unsigned long (*mask_val)(struct syscall_arg *arg, unsigned long val);
634 void *parm;
635 const char *name;
636 bool show_zero;
639 static struct syscall_fmt {
640 const char *name;
641 const char *alias;
642 struct syscall_arg_fmt arg[6];
643 u8 nr_args;
644 bool errpid;
645 bool timeout;
646 bool hexret;
647 } syscall_fmts[] = {
648 { .name = "access",
649 .arg = { [1] = { .scnprintf = SCA_ACCMODE, /* mode */ }, }, },
650 { .name = "bind",
651 .arg = { [1] = { .scnprintf = SCA_SOCKADDR, /* umyaddr */ }, }, },
652 { .name = "bpf",
653 .arg = { [0] = STRARRAY(cmd, bpf_cmd), }, },
654 { .name = "brk", .hexret = true,
655 .arg = { [0] = { .scnprintf = SCA_HEX, /* brk */ }, }, },
656 { .name = "clock_gettime",
657 .arg = { [0] = STRARRAY(clk_id, clockid), }, },
658 { .name = "clone", .errpid = true, .nr_args = 5,
659 .arg = { [0] = { .name = "flags", .scnprintf = SCA_CLONE_FLAGS, },
660 [1] = { .name = "child_stack", .scnprintf = SCA_HEX, },
661 [2] = { .name = "parent_tidptr", .scnprintf = SCA_HEX, },
662 [3] = { .name = "child_tidptr", .scnprintf = SCA_HEX, },
663 [4] = { .name = "tls", .scnprintf = SCA_HEX, }, }, },
664 { .name = "close",
665 .arg = { [0] = { .scnprintf = SCA_CLOSE_FD, /* fd */ }, }, },
666 { .name = "connect",
667 .arg = { [1] = { .scnprintf = SCA_SOCKADDR, /* servaddr */ }, }, },
668 { .name = "epoll_ctl",
669 .arg = { [1] = STRARRAY(op, epoll_ctl_ops), }, },
670 { .name = "eventfd2",
671 .arg = { [1] = { .scnprintf = SCA_EFD_FLAGS, /* flags */ }, }, },
672 { .name = "fchmodat",
673 .arg = { [0] = { .scnprintf = SCA_FDAT, /* fd */ }, }, },
674 { .name = "fchownat",
675 .arg = { [0] = { .scnprintf = SCA_FDAT, /* fd */ }, }, },
676 { .name = "fcntl",
677 .arg = { [1] = { .scnprintf = SCA_FCNTL_CMD, /* cmd */
678 .parm = &strarrays__fcntl_cmds_arrays,
679 .show_zero = true, },
680 [2] = { .scnprintf = SCA_FCNTL_ARG, /* arg */ }, }, },
681 { .name = "flock",
682 .arg = { [1] = { .scnprintf = SCA_FLOCK, /* cmd */ }, }, },
683 { .name = "fstat", .alias = "newfstat", },
684 { .name = "fstatat", .alias = "newfstatat", },
685 { .name = "futex",
686 .arg = { [1] = { .scnprintf = SCA_FUTEX_OP, /* op */ },
687 [5] = { .scnprintf = SCA_FUTEX_VAL3, /* val3 */ }, }, },
688 { .name = "futimesat",
689 .arg = { [0] = { .scnprintf = SCA_FDAT, /* fd */ }, }, },
690 { .name = "getitimer",
691 .arg = { [0] = STRARRAY(which, itimers), }, },
692 { .name = "getpid", .errpid = true, },
693 { .name = "getpgid", .errpid = true, },
694 { .name = "getppid", .errpid = true, },
695 { .name = "getrandom",
696 .arg = { [2] = { .scnprintf = SCA_GETRANDOM_FLAGS, /* flags */ }, }, },
697 { .name = "getrlimit",
698 .arg = { [0] = STRARRAY(resource, rlimit_resources), }, },
699 { .name = "gettid", .errpid = true, },
700 { .name = "ioctl",
701 .arg = {
702 #if defined(__i386__) || defined(__x86_64__)
704 * FIXME: Make this available to all arches.
706 [1] = { .scnprintf = SCA_IOCTL_CMD, /* cmd */ },
707 [2] = { .scnprintf = SCA_HEX, /* arg */ }, }, },
708 #else
709 [2] = { .scnprintf = SCA_HEX, /* arg */ }, }, },
710 #endif
711 { .name = "kcmp", .nr_args = 5,
712 .arg = { [0] = { .name = "pid1", .scnprintf = SCA_PID, },
713 [1] = { .name = "pid2", .scnprintf = SCA_PID, },
714 [2] = { .name = "type", .scnprintf = SCA_KCMP_TYPE, },
715 [3] = { .name = "idx1", .scnprintf = SCA_KCMP_IDX, },
716 [4] = { .name = "idx2", .scnprintf = SCA_KCMP_IDX, }, }, },
717 { .name = "keyctl",
718 .arg = { [0] = STRARRAY(option, keyctl_options), }, },
719 { .name = "kill",
720 .arg = { [1] = { .scnprintf = SCA_SIGNUM, /* sig */ }, }, },
721 { .name = "linkat",
722 .arg = { [0] = { .scnprintf = SCA_FDAT, /* fd */ }, }, },
723 { .name = "lseek",
724 .arg = { [2] = STRARRAY(whence, whences), }, },
725 { .name = "lstat", .alias = "newlstat", },
726 { .name = "madvise",
727 .arg = { [0] = { .scnprintf = SCA_HEX, /* start */ },
728 [2] = { .scnprintf = SCA_MADV_BHV, /* behavior */ }, }, },
729 { .name = "mkdirat",
730 .arg = { [0] = { .scnprintf = SCA_FDAT, /* fd */ }, }, },
731 { .name = "mknodat",
732 .arg = { [0] = { .scnprintf = SCA_FDAT, /* fd */ }, }, },
733 { .name = "mlock",
734 .arg = { [0] = { .scnprintf = SCA_HEX, /* addr */ }, }, },
735 { .name = "mlockall",
736 .arg = { [0] = { .scnprintf = SCA_HEX, /* addr */ }, }, },
737 { .name = "mmap", .hexret = true,
738 /* The standard mmap maps to old_mmap on s390x */
739 #if defined(__s390x__)
740 .alias = "old_mmap",
741 #endif
742 .arg = { [0] = { .scnprintf = SCA_HEX, /* addr */ },
743 [2] = { .scnprintf = SCA_MMAP_PROT, /* prot */ },
744 [3] = { .scnprintf = SCA_MMAP_FLAGS, /* flags */ }, }, },
745 { .name = "mount",
746 .arg = { [0] = { .scnprintf = SCA_FILENAME, /* dev_name */ },
747 [3] = { .scnprintf = SCA_MOUNT_FLAGS, /* flags */
748 .mask_val = SCAMV_MOUNT_FLAGS, /* flags */ }, }, },
749 { .name = "mprotect",
750 .arg = { [0] = { .scnprintf = SCA_HEX, /* start */ },
751 [2] = { .scnprintf = SCA_MMAP_PROT, /* prot */ }, }, },
752 { .name = "mq_unlink",
753 .arg = { [0] = { .scnprintf = SCA_FILENAME, /* u_name */ }, }, },
754 { .name = "mremap", .hexret = true,
755 .arg = { [0] = { .scnprintf = SCA_HEX, /* addr */ },
756 [3] = { .scnprintf = SCA_MREMAP_FLAGS, /* flags */ },
757 [4] = { .scnprintf = SCA_HEX, /* new_addr */ }, }, },
758 { .name = "munlock",
759 .arg = { [0] = { .scnprintf = SCA_HEX, /* addr */ }, }, },
760 { .name = "munmap",
761 .arg = { [0] = { .scnprintf = SCA_HEX, /* addr */ }, }, },
762 { .name = "name_to_handle_at",
763 .arg = { [0] = { .scnprintf = SCA_FDAT, /* dfd */ }, }, },
764 { .name = "newfstatat",
765 .arg = { [0] = { .scnprintf = SCA_FDAT, /* dfd */ }, }, },
766 { .name = "open",
767 .arg = { [1] = { .scnprintf = SCA_OPEN_FLAGS, /* flags */ }, }, },
768 { .name = "open_by_handle_at",
769 .arg = { [0] = { .scnprintf = SCA_FDAT, /* dfd */ },
770 [2] = { .scnprintf = SCA_OPEN_FLAGS, /* flags */ }, }, },
771 { .name = "openat",
772 .arg = { [0] = { .scnprintf = SCA_FDAT, /* dfd */ },
773 [2] = { .scnprintf = SCA_OPEN_FLAGS, /* flags */ }, }, },
774 { .name = "perf_event_open",
775 .arg = { [2] = { .scnprintf = SCA_INT, /* cpu */ },
776 [3] = { .scnprintf = SCA_FD, /* group_fd */ },
777 [4] = { .scnprintf = SCA_PERF_FLAGS, /* flags */ }, }, },
778 { .name = "pipe2",
779 .arg = { [1] = { .scnprintf = SCA_PIPE_FLAGS, /* flags */ }, }, },
780 { .name = "pkey_alloc",
781 .arg = { [1] = { .scnprintf = SCA_PKEY_ALLOC_ACCESS_RIGHTS, /* access_rights */ }, }, },
782 { .name = "pkey_free",
783 .arg = { [0] = { .scnprintf = SCA_INT, /* key */ }, }, },
784 { .name = "pkey_mprotect",
785 .arg = { [0] = { .scnprintf = SCA_HEX, /* start */ },
786 [2] = { .scnprintf = SCA_MMAP_PROT, /* prot */ },
787 [3] = { .scnprintf = SCA_INT, /* pkey */ }, }, },
788 { .name = "poll", .timeout = true, },
789 { .name = "ppoll", .timeout = true, },
790 { .name = "prctl", .alias = "arch_prctl",
791 .arg = { [0] = { .scnprintf = SCA_PRCTL_OPTION, /* option */ },
792 [1] = { .scnprintf = SCA_PRCTL_ARG2, /* arg2 */ },
793 [2] = { .scnprintf = SCA_PRCTL_ARG3, /* arg3 */ }, }, },
794 { .name = "pread", .alias = "pread64", },
795 { .name = "preadv", .alias = "pread", },
796 { .name = "prlimit64",
797 .arg = { [1] = STRARRAY(resource, rlimit_resources), }, },
798 { .name = "pwrite", .alias = "pwrite64", },
799 { .name = "readlinkat",
800 .arg = { [0] = { .scnprintf = SCA_FDAT, /* dfd */ }, }, },
801 { .name = "recvfrom",
802 .arg = { [3] = { .scnprintf = SCA_MSG_FLAGS, /* flags */ }, }, },
803 { .name = "recvmmsg",
804 .arg = { [3] = { .scnprintf = SCA_MSG_FLAGS, /* flags */ }, }, },
805 { .name = "recvmsg",
806 .arg = { [2] = { .scnprintf = SCA_MSG_FLAGS, /* flags */ }, }, },
807 { .name = "renameat",
808 .arg = { [0] = { .scnprintf = SCA_FDAT, /* olddirfd */ },
809 [2] = { .scnprintf = SCA_FDAT, /* newdirfd */ }, }, },
810 { .name = "renameat2",
811 .arg = { [0] = { .scnprintf = SCA_FDAT, /* olddirfd */ },
812 [2] = { .scnprintf = SCA_FDAT, /* newdirfd */ },
813 [4] = { .scnprintf = SCA_RENAMEAT2_FLAGS, /* flags */ }, }, },
814 { .name = "rt_sigaction",
815 .arg = { [0] = { .scnprintf = SCA_SIGNUM, /* sig */ }, }, },
816 { .name = "rt_sigprocmask",
817 .arg = { [0] = STRARRAY(how, sighow), }, },
818 { .name = "rt_sigqueueinfo",
819 .arg = { [1] = { .scnprintf = SCA_SIGNUM, /* sig */ }, }, },
820 { .name = "rt_tgsigqueueinfo",
821 .arg = { [2] = { .scnprintf = SCA_SIGNUM, /* sig */ }, }, },
822 { .name = "sched_setscheduler",
823 .arg = { [1] = { .scnprintf = SCA_SCHED_POLICY, /* policy */ }, }, },
824 { .name = "seccomp",
825 .arg = { [0] = { .scnprintf = SCA_SECCOMP_OP, /* op */ },
826 [1] = { .scnprintf = SCA_SECCOMP_FLAGS, /* flags */ }, }, },
827 { .name = "select", .timeout = true, },
828 { .name = "sendmmsg",
829 .arg = { [3] = { .scnprintf = SCA_MSG_FLAGS, /* flags */ }, }, },
830 { .name = "sendmsg",
831 .arg = { [2] = { .scnprintf = SCA_MSG_FLAGS, /* flags */ }, }, },
832 { .name = "sendto",
833 .arg = { [3] = { .scnprintf = SCA_MSG_FLAGS, /* flags */ },
834 [4] = { .scnprintf = SCA_SOCKADDR, /* addr */ }, }, },
835 { .name = "set_tid_address", .errpid = true, },
836 { .name = "setitimer",
837 .arg = { [0] = STRARRAY(which, itimers), }, },
838 { .name = "setrlimit",
839 .arg = { [0] = STRARRAY(resource, rlimit_resources), }, },
840 { .name = "socket",
841 .arg = { [0] = STRARRAY(family, socket_families),
842 [1] = { .scnprintf = SCA_SK_TYPE, /* type */ },
843 [2] = { .scnprintf = SCA_SK_PROTO, /* protocol */ }, }, },
844 { .name = "socketpair",
845 .arg = { [0] = STRARRAY(family, socket_families),
846 [1] = { .scnprintf = SCA_SK_TYPE, /* type */ },
847 [2] = { .scnprintf = SCA_SK_PROTO, /* protocol */ }, }, },
848 { .name = "stat", .alias = "newstat", },
849 { .name = "statx",
850 .arg = { [0] = { .scnprintf = SCA_FDAT, /* fdat */ },
851 [2] = { .scnprintf = SCA_STATX_FLAGS, /* flags */ } ,
852 [3] = { .scnprintf = SCA_STATX_MASK, /* mask */ }, }, },
853 { .name = "swapoff",
854 .arg = { [0] = { .scnprintf = SCA_FILENAME, /* specialfile */ }, }, },
855 { .name = "swapon",
856 .arg = { [0] = { .scnprintf = SCA_FILENAME, /* specialfile */ }, }, },
857 { .name = "symlinkat",
858 .arg = { [0] = { .scnprintf = SCA_FDAT, /* dfd */ }, }, },
859 { .name = "tgkill",
860 .arg = { [2] = { .scnprintf = SCA_SIGNUM, /* sig */ }, }, },
861 { .name = "tkill",
862 .arg = { [1] = { .scnprintf = SCA_SIGNUM, /* sig */ }, }, },
863 { .name = "umount2", .alias = "umount",
864 .arg = { [0] = { .scnprintf = SCA_FILENAME, /* name */ }, }, },
865 { .name = "uname", .alias = "newuname", },
866 { .name = "unlinkat",
867 .arg = { [0] = { .scnprintf = SCA_FDAT, /* dfd */ }, }, },
868 { .name = "utimensat",
869 .arg = { [0] = { .scnprintf = SCA_FDAT, /* dirfd */ }, }, },
870 { .name = "wait4", .errpid = true,
871 .arg = { [2] = { .scnprintf = SCA_WAITID_OPTIONS, /* options */ }, }, },
872 { .name = "waitid", .errpid = true,
873 .arg = { [3] = { .scnprintf = SCA_WAITID_OPTIONS, /* options */ }, }, },
876 static int syscall_fmt__cmp(const void *name, const void *fmtp)
878 const struct syscall_fmt *fmt = fmtp;
879 return strcmp(name, fmt->name);
882 static struct syscall_fmt *syscall_fmt__find(const char *name)
884 const int nmemb = ARRAY_SIZE(syscall_fmts);
885 return bsearch(name, syscall_fmts, nmemb, sizeof(struct syscall_fmt), syscall_fmt__cmp);
888 static struct syscall_fmt *syscall_fmt__find_by_alias(const char *alias)
890 int i, nmemb = ARRAY_SIZE(syscall_fmts);
892 for (i = 0; i < nmemb; ++i) {
893 if (syscall_fmts[i].alias && strcmp(syscall_fmts[i].alias, alias) == 0)
894 return &syscall_fmts[i];
897 return NULL;
901 * is_exit: is this "exit" or "exit_group"?
902 * is_open: is this "open" or "openat"? To associate the fd returned in sys_exit with the pathname in sys_enter.
903 * args_size: sum of the sizes of the syscall arguments, anything after that is augmented stuff: pathname for openat, etc.
905 struct syscall {
906 struct tep_event *tp_format;
907 int nr_args;
908 int args_size;
909 bool is_exit;
910 bool is_open;
911 struct tep_format_field *args;
912 const char *name;
913 struct syscall_fmt *fmt;
914 struct syscall_arg_fmt *arg_fmt;
917 struct bpf_map_syscall_entry {
918 bool enabled;
922 * We need to have this 'calculated' boolean because in some cases we really
923 * don't know what is the duration of a syscall, for instance, when we start
924 * a session and some threads are waiting for a syscall to finish, say 'poll',
925 * in which case all we can do is to print "( ? ) for duration and for the
926 * start timestamp.
928 static size_t fprintf_duration(unsigned long t, bool calculated, FILE *fp)
930 double duration = (double)t / NSEC_PER_MSEC;
931 size_t printed = fprintf(fp, "(");
933 if (!calculated)
934 printed += fprintf(fp, " ");
935 else if (duration >= 1.0)
936 printed += color_fprintf(fp, PERF_COLOR_RED, "%6.3f ms", duration);
937 else if (duration >= 0.01)
938 printed += color_fprintf(fp, PERF_COLOR_YELLOW, "%6.3f ms", duration);
939 else
940 printed += color_fprintf(fp, PERF_COLOR_NORMAL, "%6.3f ms", duration);
941 return printed + fprintf(fp, "): ");
945 * filename.ptr: The filename char pointer that will be vfs_getname'd
946 * filename.entry_str_pos: Where to insert the string translated from
947 * filename.ptr by the vfs_getname tracepoint/kprobe.
948 * ret_scnprintf: syscall args may set this to a different syscall return
949 * formatter, for instance, fcntl may return fds, file flags, etc.
951 struct thread_trace {
952 u64 entry_time;
953 bool entry_pending;
954 unsigned long nr_events;
955 unsigned long pfmaj, pfmin;
956 char *entry_str;
957 double runtime_ms;
958 size_t (*ret_scnprintf)(char *bf, size_t size, struct syscall_arg *arg);
959 struct {
960 unsigned long ptr;
961 short int entry_str_pos;
962 bool pending_open;
963 unsigned int namelen;
964 char *name;
965 } filename;
966 struct {
967 int max;
968 char **table;
969 } paths;
971 struct intlist *syscall_stats;
974 static struct thread_trace *thread_trace__new(void)
976 struct thread_trace *ttrace = zalloc(sizeof(struct thread_trace));
978 if (ttrace)
979 ttrace->paths.max = -1;
981 ttrace->syscall_stats = intlist__new(NULL);
983 return ttrace;
986 static struct thread_trace *thread__trace(struct thread *thread, FILE *fp)
988 struct thread_trace *ttrace;
990 if (thread == NULL)
991 goto fail;
993 if (thread__priv(thread) == NULL)
994 thread__set_priv(thread, thread_trace__new());
996 if (thread__priv(thread) == NULL)
997 goto fail;
999 ttrace = thread__priv(thread);
1000 ++ttrace->nr_events;
1002 return ttrace;
1003 fail:
1004 color_fprintf(fp, PERF_COLOR_RED,
1005 "WARNING: not enough memory, dropping samples!\n");
1006 return NULL;
1010 void syscall_arg__set_ret_scnprintf(struct syscall_arg *arg,
1011 size_t (*ret_scnprintf)(char *bf, size_t size, struct syscall_arg *arg))
1013 struct thread_trace *ttrace = thread__priv(arg->thread);
1015 ttrace->ret_scnprintf = ret_scnprintf;
1018 #define TRACE_PFMAJ (1 << 0)
1019 #define TRACE_PFMIN (1 << 1)
1021 static const size_t trace__entry_str_size = 2048;
1023 static int trace__set_fd_pathname(struct thread *thread, int fd, const char *pathname)
1025 struct thread_trace *ttrace = thread__priv(thread);
1027 if (fd > ttrace->paths.max) {
1028 char **npath = realloc(ttrace->paths.table, (fd + 1) * sizeof(char *));
1030 if (npath == NULL)
1031 return -1;
1033 if (ttrace->paths.max != -1) {
1034 memset(npath + ttrace->paths.max + 1, 0,
1035 (fd - ttrace->paths.max) * sizeof(char *));
1036 } else {
1037 memset(npath, 0, (fd + 1) * sizeof(char *));
1040 ttrace->paths.table = npath;
1041 ttrace->paths.max = fd;
1044 ttrace->paths.table[fd] = strdup(pathname);
1046 return ttrace->paths.table[fd] != NULL ? 0 : -1;
1049 static int thread__read_fd_path(struct thread *thread, int fd)
1051 char linkname[PATH_MAX], pathname[PATH_MAX];
1052 struct stat st;
1053 int ret;
1055 if (thread->pid_ == thread->tid) {
1056 scnprintf(linkname, sizeof(linkname),
1057 "/proc/%d/fd/%d", thread->pid_, fd);
1058 } else {
1059 scnprintf(linkname, sizeof(linkname),
1060 "/proc/%d/task/%d/fd/%d", thread->pid_, thread->tid, fd);
1063 if (lstat(linkname, &st) < 0 || st.st_size + 1 > (off_t)sizeof(pathname))
1064 return -1;
1066 ret = readlink(linkname, pathname, sizeof(pathname));
1068 if (ret < 0 || ret > st.st_size)
1069 return -1;
1071 pathname[ret] = '\0';
1072 return trace__set_fd_pathname(thread, fd, pathname);
1075 static const char *thread__fd_path(struct thread *thread, int fd,
1076 struct trace *trace)
1078 struct thread_trace *ttrace = thread__priv(thread);
1080 if (ttrace == NULL)
1081 return NULL;
1083 if (fd < 0)
1084 return NULL;
1086 if ((fd > ttrace->paths.max || ttrace->paths.table[fd] == NULL)) {
1087 if (!trace->live)
1088 return NULL;
1089 ++trace->stats.proc_getname;
1090 if (thread__read_fd_path(thread, fd))
1091 return NULL;
1094 return ttrace->paths.table[fd];
1097 size_t syscall_arg__scnprintf_fd(char *bf, size_t size, struct syscall_arg *arg)
1099 int fd = arg->val;
1100 size_t printed = scnprintf(bf, size, "%d", fd);
1101 const char *path = thread__fd_path(arg->thread, fd, arg->trace);
1103 if (path)
1104 printed += scnprintf(bf + printed, size - printed, "<%s>", path);
1106 return printed;
1109 size_t pid__scnprintf_fd(struct trace *trace, pid_t pid, int fd, char *bf, size_t size)
1111 size_t printed = scnprintf(bf, size, "%d", fd);
1112 struct thread *thread = machine__find_thread(trace->host, pid, pid);
1114 if (thread) {
1115 const char *path = thread__fd_path(thread, fd, trace);
1117 if (path)
1118 printed += scnprintf(bf + printed, size - printed, "<%s>", path);
1120 thread__put(thread);
1123 return printed;
1126 static size_t syscall_arg__scnprintf_close_fd(char *bf, size_t size,
1127 struct syscall_arg *arg)
1129 int fd = arg->val;
1130 size_t printed = syscall_arg__scnprintf_fd(bf, size, arg);
1131 struct thread_trace *ttrace = thread__priv(arg->thread);
1133 if (ttrace && fd >= 0 && fd <= ttrace->paths.max)
1134 zfree(&ttrace->paths.table[fd]);
1136 return printed;
1139 static void thread__set_filename_pos(struct thread *thread, const char *bf,
1140 unsigned long ptr)
1142 struct thread_trace *ttrace = thread__priv(thread);
1144 ttrace->filename.ptr = ptr;
1145 ttrace->filename.entry_str_pos = bf - ttrace->entry_str;
1148 static size_t syscall_arg__scnprintf_augmented_string(struct syscall_arg *arg, char *bf, size_t size)
1150 struct augmented_arg *augmented_arg = arg->augmented.args;
1152 return scnprintf(bf, size, "\"%.*s\"", augmented_arg->size, augmented_arg->value);
1155 static size_t syscall_arg__scnprintf_filename(char *bf, size_t size,
1156 struct syscall_arg *arg)
1158 unsigned long ptr = arg->val;
1160 if (arg->augmented.args)
1161 return syscall_arg__scnprintf_augmented_string(arg, bf, size);
1163 if (!arg->trace->vfs_getname)
1164 return scnprintf(bf, size, "%#x", ptr);
1166 thread__set_filename_pos(arg->thread, bf, ptr);
1167 return 0;
1170 static bool trace__filter_duration(struct trace *trace, double t)
1172 return t < (trace->duration_filter * NSEC_PER_MSEC);
1175 static size_t __trace__fprintf_tstamp(struct trace *trace, u64 tstamp, FILE *fp)
1177 double ts = (double)(tstamp - trace->base_time) / NSEC_PER_MSEC;
1179 return fprintf(fp, "%10.3f ", ts);
1183 * We're handling tstamp=0 as an undefined tstamp, i.e. like when we are
1184 * using ttrace->entry_time for a thread that receives a sys_exit without
1185 * first having received a sys_enter ("poll" issued before tracing session
1186 * starts, lost sys_enter exit due to ring buffer overflow).
1188 static size_t trace__fprintf_tstamp(struct trace *trace, u64 tstamp, FILE *fp)
1190 if (tstamp > 0)
1191 return __trace__fprintf_tstamp(trace, tstamp, fp);
1193 return fprintf(fp, " ? ");
1196 static bool done = false;
1197 static bool interrupted = false;
1199 static void sig_handler(int sig)
1201 done = true;
1202 interrupted = sig == SIGINT;
1205 static size_t trace__fprintf_comm_tid(struct trace *trace, struct thread *thread, FILE *fp)
1207 size_t printed = 0;
1209 if (trace->multiple_threads) {
1210 if (trace->show_comm)
1211 printed += fprintf(fp, "%.14s/", thread__comm_str(thread));
1212 printed += fprintf(fp, "%d ", thread->tid);
1215 return printed;
1218 static size_t trace__fprintf_entry_head(struct trace *trace, struct thread *thread,
1219 u64 duration, bool duration_calculated, u64 tstamp, FILE *fp)
1221 size_t printed = 0;
1223 if (trace->show_tstamp)
1224 printed = trace__fprintf_tstamp(trace, tstamp, fp);
1225 if (trace->show_duration)
1226 printed += fprintf_duration(duration, duration_calculated, fp);
1227 return printed + trace__fprintf_comm_tid(trace, thread, fp);
1230 static int trace__process_event(struct trace *trace, struct machine *machine,
1231 union perf_event *event, struct perf_sample *sample)
1233 int ret = 0;
1235 switch (event->header.type) {
1236 case PERF_RECORD_LOST:
1237 color_fprintf(trace->output, PERF_COLOR_RED,
1238 "LOST %" PRIu64 " events!\n", event->lost.lost);
1239 ret = machine__process_lost_event(machine, event, sample);
1240 break;
1241 default:
1242 ret = machine__process_event(machine, event, sample);
1243 break;
1246 return ret;
1249 static int trace__tool_process(struct perf_tool *tool,
1250 union perf_event *event,
1251 struct perf_sample *sample,
1252 struct machine *machine)
1254 struct trace *trace = container_of(tool, struct trace, tool);
1255 return trace__process_event(trace, machine, event, sample);
1258 static char *trace__machine__resolve_kernel_addr(void *vmachine, unsigned long long *addrp, char **modp)
1260 struct machine *machine = vmachine;
1262 if (machine->kptr_restrict_warned)
1263 return NULL;
1265 if (symbol_conf.kptr_restrict) {
1266 pr_warning("Kernel address maps (/proc/{kallsyms,modules}) are restricted.\n\n"
1267 "Check /proc/sys/kernel/kptr_restrict.\n\n"
1268 "Kernel samples will not be resolved.\n");
1269 machine->kptr_restrict_warned = true;
1270 return NULL;
1273 return machine__resolve_kernel_addr(vmachine, addrp, modp);
1276 static int trace__symbols_init(struct trace *trace, struct perf_evlist *evlist)
1278 int err = symbol__init(NULL);
1280 if (err)
1281 return err;
1283 trace->host = machine__new_host();
1284 if (trace->host == NULL)
1285 return -ENOMEM;
1287 err = trace_event__register_resolver(trace->host, trace__machine__resolve_kernel_addr);
1288 if (err < 0)
1289 goto out;
1291 err = __machine__synthesize_threads(trace->host, &trace->tool, &trace->opts.target,
1292 evlist->threads, trace__tool_process, false,
1294 out:
1295 if (err)
1296 symbol__exit();
1298 return err;
1301 static void trace__symbols__exit(struct trace *trace)
1303 machine__exit(trace->host);
1304 trace->host = NULL;
1306 symbol__exit();
1309 static int syscall__alloc_arg_fmts(struct syscall *sc, int nr_args)
1311 int idx;
1313 if (nr_args == 6 && sc->fmt && sc->fmt->nr_args != 0)
1314 nr_args = sc->fmt->nr_args;
1316 sc->arg_fmt = calloc(nr_args, sizeof(*sc->arg_fmt));
1317 if (sc->arg_fmt == NULL)
1318 return -1;
1320 for (idx = 0; idx < nr_args; ++idx) {
1321 if (sc->fmt)
1322 sc->arg_fmt[idx] = sc->fmt->arg[idx];
1325 sc->nr_args = nr_args;
1326 return 0;
1329 static int syscall__set_arg_fmts(struct syscall *sc)
1331 struct tep_format_field *field, *last_field = NULL;
1332 int idx = 0, len;
1334 for (field = sc->args; field; field = field->next, ++idx) {
1335 last_field = field;
1337 if (sc->fmt && sc->fmt->arg[idx].scnprintf)
1338 continue;
1340 if (strcmp(field->type, "const char *") == 0 &&
1341 (strcmp(field->name, "filename") == 0 ||
1342 strcmp(field->name, "path") == 0 ||
1343 strcmp(field->name, "pathname") == 0))
1344 sc->arg_fmt[idx].scnprintf = SCA_FILENAME;
1345 else if (field->flags & TEP_FIELD_IS_POINTER)
1346 sc->arg_fmt[idx].scnprintf = syscall_arg__scnprintf_hex;
1347 else if (strcmp(field->type, "pid_t") == 0)
1348 sc->arg_fmt[idx].scnprintf = SCA_PID;
1349 else if (strcmp(field->type, "umode_t") == 0)
1350 sc->arg_fmt[idx].scnprintf = SCA_MODE_T;
1351 else if ((strcmp(field->type, "int") == 0 ||
1352 strcmp(field->type, "unsigned int") == 0 ||
1353 strcmp(field->type, "long") == 0) &&
1354 (len = strlen(field->name)) >= 2 &&
1355 strcmp(field->name + len - 2, "fd") == 0) {
1357 * /sys/kernel/tracing/events/syscalls/sys_enter*
1358 * egrep 'field:.*fd;' .../format|sed -r 's/.*field:([a-z ]+) [a-z_]*fd.+/\1/g'|sort|uniq -c
1359 * 65 int
1360 * 23 unsigned int
1361 * 7 unsigned long
1363 sc->arg_fmt[idx].scnprintf = SCA_FD;
1367 if (last_field)
1368 sc->args_size = last_field->offset + last_field->size;
1370 return 0;
1373 static int trace__read_syscall_info(struct trace *trace, int id)
1375 char tp_name[128];
1376 struct syscall *sc;
1377 const char *name = syscalltbl__name(trace->sctbl, id);
1379 if (name == NULL)
1380 return -1;
1382 if (id > trace->syscalls.max) {
1383 struct syscall *nsyscalls = realloc(trace->syscalls.table, (id + 1) * sizeof(*sc));
1385 if (nsyscalls == NULL)
1386 return -1;
1388 if (trace->syscalls.max != -1) {
1389 memset(nsyscalls + trace->syscalls.max + 1, 0,
1390 (id - trace->syscalls.max) * sizeof(*sc));
1391 } else {
1392 memset(nsyscalls, 0, (id + 1) * sizeof(*sc));
1395 trace->syscalls.table = nsyscalls;
1396 trace->syscalls.max = id;
1399 sc = trace->syscalls.table + id;
1400 sc->name = name;
1402 sc->fmt = syscall_fmt__find(sc->name);
1404 snprintf(tp_name, sizeof(tp_name), "sys_enter_%s", sc->name);
1405 sc->tp_format = trace_event__tp_format("syscalls", tp_name);
1407 if (IS_ERR(sc->tp_format) && sc->fmt && sc->fmt->alias) {
1408 snprintf(tp_name, sizeof(tp_name), "sys_enter_%s", sc->fmt->alias);
1409 sc->tp_format = trace_event__tp_format("syscalls", tp_name);
1412 if (syscall__alloc_arg_fmts(sc, IS_ERR(sc->tp_format) ? 6 : sc->tp_format->format.nr_fields))
1413 return -1;
1415 if (IS_ERR(sc->tp_format))
1416 return -1;
1418 sc->args = sc->tp_format->format.fields;
1420 * We need to check and discard the first variable '__syscall_nr'
1421 * or 'nr' that mean the syscall number. It is needless here.
1422 * So drop '__syscall_nr' or 'nr' field but does not exist on older kernels.
1424 if (sc->args && (!strcmp(sc->args->name, "__syscall_nr") || !strcmp(sc->args->name, "nr"))) {
1425 sc->args = sc->args->next;
1426 --sc->nr_args;
1429 sc->is_exit = !strcmp(name, "exit_group") || !strcmp(name, "exit");
1430 sc->is_open = !strcmp(name, "open") || !strcmp(name, "openat");
1432 return syscall__set_arg_fmts(sc);
1435 static int trace__validate_ev_qualifier(struct trace *trace)
1437 int err = 0, i;
1438 size_t nr_allocated;
1439 struct str_node *pos;
1441 trace->ev_qualifier_ids.nr = strlist__nr_entries(trace->ev_qualifier);
1442 trace->ev_qualifier_ids.entries = malloc(trace->ev_qualifier_ids.nr *
1443 sizeof(trace->ev_qualifier_ids.entries[0]));
1445 if (trace->ev_qualifier_ids.entries == NULL) {
1446 fputs("Error:\tNot enough memory for allocating events qualifier ids\n",
1447 trace->output);
1448 err = -EINVAL;
1449 goto out;
1452 nr_allocated = trace->ev_qualifier_ids.nr;
1453 i = 0;
1455 strlist__for_each_entry(pos, trace->ev_qualifier) {
1456 const char *sc = pos->s;
1457 int id = syscalltbl__id(trace->sctbl, sc), match_next = -1;
1459 if (id < 0) {
1460 id = syscalltbl__strglobmatch_first(trace->sctbl, sc, &match_next);
1461 if (id >= 0)
1462 goto matches;
1464 if (err == 0) {
1465 fputs("Error:\tInvalid syscall ", trace->output);
1466 err = -EINVAL;
1467 } else {
1468 fputs(", ", trace->output);
1471 fputs(sc, trace->output);
1473 matches:
1474 trace->ev_qualifier_ids.entries[i++] = id;
1475 if (match_next == -1)
1476 continue;
1478 while (1) {
1479 id = syscalltbl__strglobmatch_next(trace->sctbl, sc, &match_next);
1480 if (id < 0)
1481 break;
1482 if (nr_allocated == trace->ev_qualifier_ids.nr) {
1483 void *entries;
1485 nr_allocated += 8;
1486 entries = realloc(trace->ev_qualifier_ids.entries,
1487 nr_allocated * sizeof(trace->ev_qualifier_ids.entries[0]));
1488 if (entries == NULL) {
1489 err = -ENOMEM;
1490 fputs("\nError:\t Not enough memory for parsing\n", trace->output);
1491 goto out_free;
1493 trace->ev_qualifier_ids.entries = entries;
1495 trace->ev_qualifier_ids.nr++;
1496 trace->ev_qualifier_ids.entries[i++] = id;
1500 if (err < 0) {
1501 fputs("\nHint:\ttry 'perf list syscalls:sys_enter_*'"
1502 "\nHint:\tand: 'man syscalls'\n", trace->output);
1503 out_free:
1504 zfree(&trace->ev_qualifier_ids.entries);
1505 trace->ev_qualifier_ids.nr = 0;
1507 out:
1508 return err;
1512 * args is to be interpreted as a series of longs but we need to handle
1513 * 8-byte unaligned accesses. args points to raw_data within the event
1514 * and raw_data is guaranteed to be 8-byte unaligned because it is
1515 * preceded by raw_size which is a u32. So we need to copy args to a temp
1516 * variable to read it. Most notably this avoids extended load instructions
1517 * on unaligned addresses
1519 unsigned long syscall_arg__val(struct syscall_arg *arg, u8 idx)
1521 unsigned long val;
1522 unsigned char *p = arg->args + sizeof(unsigned long) * idx;
1524 memcpy(&val, p, sizeof(val));
1525 return val;
1528 static size_t syscall__scnprintf_name(struct syscall *sc, char *bf, size_t size,
1529 struct syscall_arg *arg)
1531 if (sc->arg_fmt && sc->arg_fmt[arg->idx].name)
1532 return scnprintf(bf, size, "%s: ", sc->arg_fmt[arg->idx].name);
1534 return scnprintf(bf, size, "arg%d: ", arg->idx);
1538 * Check if the value is in fact zero, i.e. mask whatever needs masking, such
1539 * as mount 'flags' argument that needs ignoring some magic flag, see comment
1540 * in tools/perf/trace/beauty/mount_flags.c
1542 static unsigned long syscall__mask_val(struct syscall *sc, struct syscall_arg *arg, unsigned long val)
1544 if (sc->arg_fmt && sc->arg_fmt[arg->idx].mask_val)
1545 return sc->arg_fmt[arg->idx].mask_val(arg, val);
1547 return val;
1550 static size_t syscall__scnprintf_val(struct syscall *sc, char *bf, size_t size,
1551 struct syscall_arg *arg, unsigned long val)
1553 if (sc->arg_fmt && sc->arg_fmt[arg->idx].scnprintf) {
1554 arg->val = val;
1555 if (sc->arg_fmt[arg->idx].parm)
1556 arg->parm = sc->arg_fmt[arg->idx].parm;
1557 return sc->arg_fmt[arg->idx].scnprintf(bf, size, arg);
1559 return scnprintf(bf, size, "%ld", val);
1562 static size_t syscall__scnprintf_args(struct syscall *sc, char *bf, size_t size,
1563 unsigned char *args, void *augmented_args, int augmented_args_size,
1564 struct trace *trace, struct thread *thread)
1566 size_t printed = 0;
1567 unsigned long val;
1568 u8 bit = 1;
1569 struct syscall_arg arg = {
1570 .args = args,
1571 .augmented = {
1572 .size = augmented_args_size,
1573 .args = augmented_args,
1575 .idx = 0,
1576 .mask = 0,
1577 .trace = trace,
1578 .thread = thread,
1580 struct thread_trace *ttrace = thread__priv(thread);
1583 * Things like fcntl will set this in its 'cmd' formatter to pick the
1584 * right formatter for the return value (an fd? file flags?), which is
1585 * not needed for syscalls that always return a given type, say an fd.
1587 ttrace->ret_scnprintf = NULL;
1589 if (sc->args != NULL) {
1590 struct tep_format_field *field;
1592 for (field = sc->args; field;
1593 field = field->next, ++arg.idx, bit <<= 1) {
1594 if (arg.mask & bit)
1595 continue;
1597 val = syscall_arg__val(&arg, arg.idx);
1599 * Some syscall args need some mask, most don't and
1600 * return val untouched.
1602 val = syscall__mask_val(sc, &arg, val);
1605 * Suppress this argument if its value is zero and
1606 * and we don't have a string associated in an
1607 * strarray for it.
1609 if (val == 0 &&
1610 !trace->show_zeros &&
1611 !(sc->arg_fmt &&
1612 (sc->arg_fmt[arg.idx].show_zero ||
1613 sc->arg_fmt[arg.idx].scnprintf == SCA_STRARRAY ||
1614 sc->arg_fmt[arg.idx].scnprintf == SCA_STRARRAYS) &&
1615 sc->arg_fmt[arg.idx].parm))
1616 continue;
1618 printed += scnprintf(bf + printed, size - printed, "%s", printed ? ", " : "");
1620 if (trace->show_arg_names)
1621 printed += scnprintf(bf + printed, size - printed, "%s: ", field->name);
1623 printed += syscall__scnprintf_val(sc, bf + printed, size - printed, &arg, val);
1625 } else if (IS_ERR(sc->tp_format)) {
1627 * If we managed to read the tracepoint /format file, then we
1628 * may end up not having any args, like with gettid(), so only
1629 * print the raw args when we didn't manage to read it.
1631 while (arg.idx < sc->nr_args) {
1632 if (arg.mask & bit)
1633 goto next_arg;
1634 val = syscall_arg__val(&arg, arg.idx);
1635 if (printed)
1636 printed += scnprintf(bf + printed, size - printed, ", ");
1637 printed += syscall__scnprintf_name(sc, bf + printed, size - printed, &arg);
1638 printed += syscall__scnprintf_val(sc, bf + printed, size - printed, &arg, val);
1639 next_arg:
1640 ++arg.idx;
1641 bit <<= 1;
1645 return printed;
1648 typedef int (*tracepoint_handler)(struct trace *trace, struct perf_evsel *evsel,
1649 union perf_event *event,
1650 struct perf_sample *sample);
1652 static struct syscall *trace__syscall_info(struct trace *trace,
1653 struct perf_evsel *evsel, int id)
1656 if (id < 0) {
1659 * XXX: Noticed on x86_64, reproduced as far back as 3.0.36, haven't tried
1660 * before that, leaving at a higher verbosity level till that is
1661 * explained. Reproduced with plain ftrace with:
1663 * echo 1 > /t/events/raw_syscalls/sys_exit/enable
1664 * grep "NR -1 " /t/trace_pipe
1666 * After generating some load on the machine.
1668 if (verbose > 1) {
1669 static u64 n;
1670 fprintf(trace->output, "Invalid syscall %d id, skipping (%s, %" PRIu64 ") ...\n",
1671 id, perf_evsel__name(evsel), ++n);
1673 return NULL;
1676 if ((id > trace->syscalls.max || trace->syscalls.table[id].name == NULL) &&
1677 trace__read_syscall_info(trace, id))
1678 goto out_cant_read;
1680 if ((id > trace->syscalls.max || trace->syscalls.table[id].name == NULL))
1681 goto out_cant_read;
1683 return &trace->syscalls.table[id];
1685 out_cant_read:
1686 if (verbose > 0) {
1687 fprintf(trace->output, "Problems reading syscall %d", id);
1688 if (id <= trace->syscalls.max && trace->syscalls.table[id].name != NULL)
1689 fprintf(trace->output, "(%s)", trace->syscalls.table[id].name);
1690 fputs(" information\n", trace->output);
1692 return NULL;
1695 static void thread__update_stats(struct thread_trace *ttrace,
1696 int id, struct perf_sample *sample)
1698 struct int_node *inode;
1699 struct stats *stats;
1700 u64 duration = 0;
1702 inode = intlist__findnew(ttrace->syscall_stats, id);
1703 if (inode == NULL)
1704 return;
1706 stats = inode->priv;
1707 if (stats == NULL) {
1708 stats = malloc(sizeof(struct stats));
1709 if (stats == NULL)
1710 return;
1711 init_stats(stats);
1712 inode->priv = stats;
1715 if (ttrace->entry_time && sample->time > ttrace->entry_time)
1716 duration = sample->time - ttrace->entry_time;
1718 update_stats(stats, duration);
1721 static int trace__printf_interrupted_entry(struct trace *trace)
1723 struct thread_trace *ttrace;
1724 size_t printed;
1726 if (trace->failure_only || trace->current == NULL)
1727 return 0;
1729 ttrace = thread__priv(trace->current);
1731 if (!ttrace->entry_pending)
1732 return 0;
1734 printed = trace__fprintf_entry_head(trace, trace->current, 0, false, ttrace->entry_time, trace->output);
1735 printed += fprintf(trace->output, "%-*s) ...\n", trace->args_alignment, ttrace->entry_str);
1736 ttrace->entry_pending = false;
1738 ++trace->nr_events_printed;
1740 return printed;
1743 static int trace__fprintf_sample(struct trace *trace, struct perf_evsel *evsel,
1744 struct perf_sample *sample, struct thread *thread)
1746 int printed = 0;
1748 if (trace->print_sample) {
1749 double ts = (double)sample->time / NSEC_PER_MSEC;
1751 printed += fprintf(trace->output, "%22s %10.3f %s %d/%d [%d]\n",
1752 perf_evsel__name(evsel), ts,
1753 thread__comm_str(thread),
1754 sample->pid, sample->tid, sample->cpu);
1757 return printed;
1760 static void *syscall__augmented_args(struct syscall *sc, struct perf_sample *sample, int *augmented_args_size, bool raw_augmented)
1762 void *augmented_args = NULL;
1764 * For now with BPF raw_augmented we hook into raw_syscalls:sys_enter
1765 * and there we get all 6 syscall args plus the tracepoint common
1766 * fields (sizeof(long)) and the syscall_nr (another long). So we check
1767 * if that is the case and if so don't look after the sc->args_size,
1768 * but always after the full raw_syscalls:sys_enter payload, which is
1769 * fixed.
1771 * We'll revisit this later to pass s->args_size to the BPF augmenter
1772 * (now tools/perf/examples/bpf/augmented_raw_syscalls.c, so that it
1773 * copies only what we need for each syscall, like what happens when we
1774 * use syscalls:sys_enter_NAME, so that we reduce the kernel/userspace
1775 * traffic to just what is needed for each syscall.
1777 int args_size = raw_augmented ? (8 * (int)sizeof(long)) : sc->args_size;
1779 *augmented_args_size = sample->raw_size - args_size;
1780 if (*augmented_args_size > 0)
1781 augmented_args = sample->raw_data + args_size;
1783 return augmented_args;
1786 static int trace__sys_enter(struct trace *trace, struct perf_evsel *evsel,
1787 union perf_event *event __maybe_unused,
1788 struct perf_sample *sample)
1790 char *msg;
1791 void *args;
1792 size_t printed = 0;
1793 struct thread *thread;
1794 int id = perf_evsel__sc_tp_uint(evsel, id, sample), err = -1;
1795 int augmented_args_size = 0;
1796 void *augmented_args = NULL;
1797 struct syscall *sc = trace__syscall_info(trace, evsel, id);
1798 struct thread_trace *ttrace;
1800 if (sc == NULL)
1801 return -1;
1803 thread = machine__findnew_thread(trace->host, sample->pid, sample->tid);
1804 ttrace = thread__trace(thread, trace->output);
1805 if (ttrace == NULL)
1806 goto out_put;
1808 trace__fprintf_sample(trace, evsel, sample, thread);
1810 args = perf_evsel__sc_tp_ptr(evsel, args, sample);
1812 if (ttrace->entry_str == NULL) {
1813 ttrace->entry_str = malloc(trace__entry_str_size);
1814 if (!ttrace->entry_str)
1815 goto out_put;
1818 if (!(trace->duration_filter || trace->summary_only || trace->min_stack))
1819 trace__printf_interrupted_entry(trace);
1821 * If this is raw_syscalls.sys_enter, then it always comes with the 6 possible
1822 * arguments, even if the syscall being handled, say "openat", uses only 4 arguments
1823 * this breaks syscall__augmented_args() check for augmented args, as we calculate
1824 * syscall->args_size using each syscalls:sys_enter_NAME tracefs format file,
1825 * so when handling, say the openat syscall, we end up getting 6 args for the
1826 * raw_syscalls:sys_enter event, when we expected just 4, we end up mistakenly
1827 * thinking that the extra 2 u64 args are the augmented filename, so just check
1828 * here and avoid using augmented syscalls when the evsel is the raw_syscalls one.
1830 if (evsel != trace->syscalls.events.sys_enter)
1831 augmented_args = syscall__augmented_args(sc, sample, &augmented_args_size, trace->raw_augmented_syscalls);
1832 ttrace->entry_time = sample->time;
1833 msg = ttrace->entry_str;
1834 printed += scnprintf(msg + printed, trace__entry_str_size - printed, "%s(", sc->name);
1836 printed += syscall__scnprintf_args(sc, msg + printed, trace__entry_str_size - printed,
1837 args, augmented_args, augmented_args_size, trace, thread);
1839 if (sc->is_exit) {
1840 if (!(trace->duration_filter || trace->summary_only || trace->failure_only || trace->min_stack)) {
1841 trace__fprintf_entry_head(trace, thread, 0, false, ttrace->entry_time, trace->output);
1842 fprintf(trace->output, "%-*s)\n", trace->args_alignment, ttrace->entry_str);
1844 } else {
1845 ttrace->entry_pending = true;
1846 /* See trace__vfs_getname & trace__sys_exit */
1847 ttrace->filename.pending_open = false;
1850 if (trace->current != thread) {
1851 thread__put(trace->current);
1852 trace->current = thread__get(thread);
1854 err = 0;
1855 out_put:
1856 thread__put(thread);
1857 return err;
1860 static int trace__fprintf_sys_enter(struct trace *trace, struct perf_evsel *evsel,
1861 struct perf_sample *sample)
1863 struct thread_trace *ttrace;
1864 struct thread *thread;
1865 int id = perf_evsel__sc_tp_uint(evsel, id, sample), err = -1;
1866 struct syscall *sc = trace__syscall_info(trace, evsel, id);
1867 char msg[1024];
1868 void *args, *augmented_args = NULL;
1869 int augmented_args_size;
1871 if (sc == NULL)
1872 return -1;
1874 thread = machine__findnew_thread(trace->host, sample->pid, sample->tid);
1875 ttrace = thread__trace(thread, trace->output);
1877 * We need to get ttrace just to make sure it is there when syscall__scnprintf_args()
1878 * and the rest of the beautifiers accessing it via struct syscall_arg touches it.
1880 if (ttrace == NULL)
1881 goto out_put;
1883 args = perf_evsel__sc_tp_ptr(evsel, args, sample);
1884 augmented_args = syscall__augmented_args(sc, sample, &augmented_args_size, trace->raw_augmented_syscalls);
1885 syscall__scnprintf_args(sc, msg, sizeof(msg), args, augmented_args, augmented_args_size, trace, thread);
1886 fprintf(trace->output, "%s", msg);
1887 err = 0;
1888 out_put:
1889 thread__put(thread);
1890 return err;
1893 static int trace__resolve_callchain(struct trace *trace, struct perf_evsel *evsel,
1894 struct perf_sample *sample,
1895 struct callchain_cursor *cursor)
1897 struct addr_location al;
1898 int max_stack = evsel->attr.sample_max_stack ?
1899 evsel->attr.sample_max_stack :
1900 trace->max_stack;
1901 int err;
1903 if (machine__resolve(trace->host, &al, sample) < 0)
1904 return -1;
1906 err = thread__resolve_callchain(al.thread, cursor, evsel, sample, NULL, NULL, max_stack);
1907 addr_location__put(&al);
1908 return err;
1911 static int trace__fprintf_callchain(struct trace *trace, struct perf_sample *sample)
1913 /* TODO: user-configurable print_opts */
1914 const unsigned int print_opts = EVSEL__PRINT_SYM |
1915 EVSEL__PRINT_DSO |
1916 EVSEL__PRINT_UNKNOWN_AS_ADDR;
1918 return sample__fprintf_callchain(sample, 38, print_opts, &callchain_cursor, trace->output);
1921 static const char *errno_to_name(struct perf_evsel *evsel, int err)
1923 struct perf_env *env = perf_evsel__env(evsel);
1924 const char *arch_name = perf_env__arch(env);
1926 return arch_syscalls__strerrno(arch_name, err);
1929 static int trace__sys_exit(struct trace *trace, struct perf_evsel *evsel,
1930 union perf_event *event __maybe_unused,
1931 struct perf_sample *sample)
1933 long ret;
1934 u64 duration = 0;
1935 bool duration_calculated = false;
1936 struct thread *thread;
1937 int id = perf_evsel__sc_tp_uint(evsel, id, sample), err = -1, callchain_ret = 0;
1938 struct syscall *sc = trace__syscall_info(trace, evsel, id);
1939 struct thread_trace *ttrace;
1941 if (sc == NULL)
1942 return -1;
1944 thread = machine__findnew_thread(trace->host, sample->pid, sample->tid);
1945 ttrace = thread__trace(thread, trace->output);
1946 if (ttrace == NULL)
1947 goto out_put;
1949 trace__fprintf_sample(trace, evsel, sample, thread);
1951 if (trace->summary)
1952 thread__update_stats(ttrace, id, sample);
1954 ret = perf_evsel__sc_tp_uint(evsel, ret, sample);
1956 if (sc->is_open && ret >= 0 && ttrace->filename.pending_open) {
1957 trace__set_fd_pathname(thread, ret, ttrace->filename.name);
1958 ttrace->filename.pending_open = false;
1959 ++trace->stats.vfs_getname;
1962 if (ttrace->entry_time) {
1963 duration = sample->time - ttrace->entry_time;
1964 if (trace__filter_duration(trace, duration))
1965 goto out;
1966 duration_calculated = true;
1967 } else if (trace->duration_filter)
1968 goto out;
1970 if (sample->callchain) {
1971 callchain_ret = trace__resolve_callchain(trace, evsel, sample, &callchain_cursor);
1972 if (callchain_ret == 0) {
1973 if (callchain_cursor.nr < trace->min_stack)
1974 goto out;
1975 callchain_ret = 1;
1979 if (trace->summary_only || (ret >= 0 && trace->failure_only))
1980 goto out;
1982 trace__fprintf_entry_head(trace, thread, duration, duration_calculated, ttrace->entry_time, trace->output);
1984 if (ttrace->entry_pending) {
1985 fprintf(trace->output, "%-*s", trace->args_alignment, ttrace->entry_str);
1986 } else {
1987 fprintf(trace->output, " ... [");
1988 color_fprintf(trace->output, PERF_COLOR_YELLOW, "continued");
1989 fprintf(trace->output, "]: %s()", sc->name);
1992 if (sc->fmt == NULL) {
1993 if (ret < 0)
1994 goto errno_print;
1995 signed_print:
1996 fprintf(trace->output, ") = %ld", ret);
1997 } else if (ret < 0) {
1998 errno_print: {
1999 char bf[STRERR_BUFSIZE];
2000 const char *emsg = str_error_r(-ret, bf, sizeof(bf)),
2001 *e = errno_to_name(evsel, -ret);
2003 fprintf(trace->output, ") = -1 %s %s", e, emsg);
2005 } else if (ret == 0 && sc->fmt->timeout)
2006 fprintf(trace->output, ") = 0 Timeout");
2007 else if (ttrace->ret_scnprintf) {
2008 char bf[1024];
2009 struct syscall_arg arg = {
2010 .val = ret,
2011 .thread = thread,
2012 .trace = trace,
2014 ttrace->ret_scnprintf(bf, sizeof(bf), &arg);
2015 ttrace->ret_scnprintf = NULL;
2016 fprintf(trace->output, ") = %s", bf);
2017 } else if (sc->fmt->hexret)
2018 fprintf(trace->output, ") = %#lx", ret);
2019 else if (sc->fmt->errpid) {
2020 struct thread *child = machine__find_thread(trace->host, ret, ret);
2022 if (child != NULL) {
2023 fprintf(trace->output, ") = %ld", ret);
2024 if (child->comm_set)
2025 fprintf(trace->output, " (%s)", thread__comm_str(child));
2026 thread__put(child);
2028 } else
2029 goto signed_print;
2031 fputc('\n', trace->output);
2034 * We only consider an 'event' for the sake of --max-events a non-filtered
2035 * sys_enter + sys_exit and other tracepoint events.
2037 if (++trace->nr_events_printed == trace->max_events && trace->max_events != ULONG_MAX)
2038 interrupted = true;
2040 if (callchain_ret > 0)
2041 trace__fprintf_callchain(trace, sample);
2042 else if (callchain_ret < 0)
2043 pr_err("Problem processing %s callchain, skipping...\n", perf_evsel__name(evsel));
2044 out:
2045 ttrace->entry_pending = false;
2046 err = 0;
2047 out_put:
2048 thread__put(thread);
2049 return err;
2052 static int trace__vfs_getname(struct trace *trace, struct perf_evsel *evsel,
2053 union perf_event *event __maybe_unused,
2054 struct perf_sample *sample)
2056 struct thread *thread = machine__findnew_thread(trace->host, sample->pid, sample->tid);
2057 struct thread_trace *ttrace;
2058 size_t filename_len, entry_str_len, to_move;
2059 ssize_t remaining_space;
2060 char *pos;
2061 const char *filename = perf_evsel__rawptr(evsel, sample, "pathname");
2063 if (!thread)
2064 goto out;
2066 ttrace = thread__priv(thread);
2067 if (!ttrace)
2068 goto out_put;
2070 filename_len = strlen(filename);
2071 if (filename_len == 0)
2072 goto out_put;
2074 if (ttrace->filename.namelen < filename_len) {
2075 char *f = realloc(ttrace->filename.name, filename_len + 1);
2077 if (f == NULL)
2078 goto out_put;
2080 ttrace->filename.namelen = filename_len;
2081 ttrace->filename.name = f;
2084 strcpy(ttrace->filename.name, filename);
2085 ttrace->filename.pending_open = true;
2087 if (!ttrace->filename.ptr)
2088 goto out_put;
2090 entry_str_len = strlen(ttrace->entry_str);
2091 remaining_space = trace__entry_str_size - entry_str_len - 1; /* \0 */
2092 if (remaining_space <= 0)
2093 goto out_put;
2095 if (filename_len > (size_t)remaining_space) {
2096 filename += filename_len - remaining_space;
2097 filename_len = remaining_space;
2100 to_move = entry_str_len - ttrace->filename.entry_str_pos + 1; /* \0 */
2101 pos = ttrace->entry_str + ttrace->filename.entry_str_pos;
2102 memmove(pos + filename_len, pos, to_move);
2103 memcpy(pos, filename, filename_len);
2105 ttrace->filename.ptr = 0;
2106 ttrace->filename.entry_str_pos = 0;
2107 out_put:
2108 thread__put(thread);
2109 out:
2110 return 0;
2113 static int trace__sched_stat_runtime(struct trace *trace, struct perf_evsel *evsel,
2114 union perf_event *event __maybe_unused,
2115 struct perf_sample *sample)
2117 u64 runtime = perf_evsel__intval(evsel, sample, "runtime");
2118 double runtime_ms = (double)runtime / NSEC_PER_MSEC;
2119 struct thread *thread = machine__findnew_thread(trace->host,
2120 sample->pid,
2121 sample->tid);
2122 struct thread_trace *ttrace = thread__trace(thread, trace->output);
2124 if (ttrace == NULL)
2125 goto out_dump;
2127 ttrace->runtime_ms += runtime_ms;
2128 trace->runtime_ms += runtime_ms;
2129 out_put:
2130 thread__put(thread);
2131 return 0;
2133 out_dump:
2134 fprintf(trace->output, "%s: comm=%s,pid=%u,runtime=%" PRIu64 ",vruntime=%" PRIu64 ")\n",
2135 evsel->name,
2136 perf_evsel__strval(evsel, sample, "comm"),
2137 (pid_t)perf_evsel__intval(evsel, sample, "pid"),
2138 runtime,
2139 perf_evsel__intval(evsel, sample, "vruntime"));
2140 goto out_put;
2143 static int bpf_output__printer(enum binary_printer_ops op,
2144 unsigned int val, void *extra __maybe_unused, FILE *fp)
2146 unsigned char ch = (unsigned char)val;
2148 switch (op) {
2149 case BINARY_PRINT_CHAR_DATA:
2150 return fprintf(fp, "%c", isprint(ch) ? ch : '.');
2151 case BINARY_PRINT_DATA_BEGIN:
2152 case BINARY_PRINT_LINE_BEGIN:
2153 case BINARY_PRINT_ADDR:
2154 case BINARY_PRINT_NUM_DATA:
2155 case BINARY_PRINT_NUM_PAD:
2156 case BINARY_PRINT_SEP:
2157 case BINARY_PRINT_CHAR_PAD:
2158 case BINARY_PRINT_LINE_END:
2159 case BINARY_PRINT_DATA_END:
2160 default:
2161 break;
2164 return 0;
2167 static void bpf_output__fprintf(struct trace *trace,
2168 struct perf_sample *sample)
2170 binary__fprintf(sample->raw_data, sample->raw_size, 8,
2171 bpf_output__printer, NULL, trace->output);
2172 ++trace->nr_events_printed;
2175 static int trace__event_handler(struct trace *trace, struct perf_evsel *evsel,
2176 union perf_event *event __maybe_unused,
2177 struct perf_sample *sample)
2179 struct thread *thread;
2180 int callchain_ret = 0;
2182 * Check if we called perf_evsel__disable(evsel) due to, for instance,
2183 * this event's max_events having been hit and this is an entry coming
2184 * from the ring buffer that we should discard, since the max events
2185 * have already been considered/printed.
2187 if (evsel->disabled)
2188 return 0;
2190 thread = machine__findnew_thread(trace->host, sample->pid, sample->tid);
2192 if (sample->callchain) {
2193 callchain_ret = trace__resolve_callchain(trace, evsel, sample, &callchain_cursor);
2194 if (callchain_ret == 0) {
2195 if (callchain_cursor.nr < trace->min_stack)
2196 goto out;
2197 callchain_ret = 1;
2201 trace__printf_interrupted_entry(trace);
2202 trace__fprintf_tstamp(trace, sample->time, trace->output);
2204 if (trace->trace_syscalls && trace->show_duration)
2205 fprintf(trace->output, "( ): ");
2207 if (thread)
2208 trace__fprintf_comm_tid(trace, thread, trace->output);
2210 if (evsel == trace->syscalls.events.augmented) {
2211 int id = perf_evsel__sc_tp_uint(evsel, id, sample);
2212 struct syscall *sc = trace__syscall_info(trace, evsel, id);
2214 if (sc) {
2215 fprintf(trace->output, "%s(", sc->name);
2216 trace__fprintf_sys_enter(trace, evsel, sample);
2217 fputc(')', trace->output);
2218 goto newline;
2222 * XXX: Not having the associated syscall info or not finding/adding
2223 * the thread should never happen, but if it does...
2224 * fall thru and print it as a bpf_output event.
2228 fprintf(trace->output, "%s:", evsel->name);
2230 if (perf_evsel__is_bpf_output(evsel)) {
2231 bpf_output__fprintf(trace, sample);
2232 } else if (evsel->tp_format) {
2233 if (strncmp(evsel->tp_format->name, "sys_enter_", 10) ||
2234 trace__fprintf_sys_enter(trace, evsel, sample)) {
2235 event_format__fprintf(evsel->tp_format, sample->cpu,
2236 sample->raw_data, sample->raw_size,
2237 trace->output);
2238 ++trace->nr_events_printed;
2240 if (evsel->max_events != ULONG_MAX && ++evsel->nr_events_printed == evsel->max_events) {
2241 perf_evsel__disable(evsel);
2242 perf_evsel__close(evsel);
2247 newline:
2248 fprintf(trace->output, "\n");
2250 if (callchain_ret > 0)
2251 trace__fprintf_callchain(trace, sample);
2252 else if (callchain_ret < 0)
2253 pr_err("Problem processing %s callchain, skipping...\n", perf_evsel__name(evsel));
2254 out:
2255 thread__put(thread);
2256 return 0;
2259 static void print_location(FILE *f, struct perf_sample *sample,
2260 struct addr_location *al,
2261 bool print_dso, bool print_sym)
2264 if ((verbose > 0 || print_dso) && al->map)
2265 fprintf(f, "%s@", al->map->dso->long_name);
2267 if ((verbose > 0 || print_sym) && al->sym)
2268 fprintf(f, "%s+0x%" PRIx64, al->sym->name,
2269 al->addr - al->sym->start);
2270 else if (al->map)
2271 fprintf(f, "0x%" PRIx64, al->addr);
2272 else
2273 fprintf(f, "0x%" PRIx64, sample->addr);
2276 static int trace__pgfault(struct trace *trace,
2277 struct perf_evsel *evsel,
2278 union perf_event *event __maybe_unused,
2279 struct perf_sample *sample)
2281 struct thread *thread;
2282 struct addr_location al;
2283 char map_type = 'd';
2284 struct thread_trace *ttrace;
2285 int err = -1;
2286 int callchain_ret = 0;
2288 thread = machine__findnew_thread(trace->host, sample->pid, sample->tid);
2290 if (sample->callchain) {
2291 callchain_ret = trace__resolve_callchain(trace, evsel, sample, &callchain_cursor);
2292 if (callchain_ret == 0) {
2293 if (callchain_cursor.nr < trace->min_stack)
2294 goto out_put;
2295 callchain_ret = 1;
2299 ttrace = thread__trace(thread, trace->output);
2300 if (ttrace == NULL)
2301 goto out_put;
2303 if (evsel->attr.config == PERF_COUNT_SW_PAGE_FAULTS_MAJ)
2304 ttrace->pfmaj++;
2305 else
2306 ttrace->pfmin++;
2308 if (trace->summary_only)
2309 goto out;
2311 thread__find_symbol(thread, sample->cpumode, sample->ip, &al);
2313 trace__fprintf_entry_head(trace, thread, 0, true, sample->time, trace->output);
2315 fprintf(trace->output, "%sfault [",
2316 evsel->attr.config == PERF_COUNT_SW_PAGE_FAULTS_MAJ ?
2317 "maj" : "min");
2319 print_location(trace->output, sample, &al, false, true);
2321 fprintf(trace->output, "] => ");
2323 thread__find_symbol(thread, sample->cpumode, sample->addr, &al);
2325 if (!al.map) {
2326 thread__find_symbol(thread, sample->cpumode, sample->addr, &al);
2328 if (al.map)
2329 map_type = 'x';
2330 else
2331 map_type = '?';
2334 print_location(trace->output, sample, &al, true, false);
2336 fprintf(trace->output, " (%c%c)\n", map_type, al.level);
2338 if (callchain_ret > 0)
2339 trace__fprintf_callchain(trace, sample);
2340 else if (callchain_ret < 0)
2341 pr_err("Problem processing %s callchain, skipping...\n", perf_evsel__name(evsel));
2343 ++trace->nr_events_printed;
2344 out:
2345 err = 0;
2346 out_put:
2347 thread__put(thread);
2348 return err;
2351 static void trace__set_base_time(struct trace *trace,
2352 struct perf_evsel *evsel,
2353 struct perf_sample *sample)
2356 * BPF events were not setting PERF_SAMPLE_TIME, so be more robust
2357 * and don't use sample->time unconditionally, we may end up having
2358 * some other event in the future without PERF_SAMPLE_TIME for good
2359 * reason, i.e. we may not be interested in its timestamps, just in
2360 * it taking place, picking some piece of information when it
2361 * appears in our event stream (vfs_getname comes to mind).
2363 if (trace->base_time == 0 && !trace->full_time &&
2364 (evsel->attr.sample_type & PERF_SAMPLE_TIME))
2365 trace->base_time = sample->time;
2368 static int trace__process_sample(struct perf_tool *tool,
2369 union perf_event *event,
2370 struct perf_sample *sample,
2371 struct perf_evsel *evsel,
2372 struct machine *machine __maybe_unused)
2374 struct trace *trace = container_of(tool, struct trace, tool);
2375 struct thread *thread;
2376 int err = 0;
2378 tracepoint_handler handler = evsel->handler;
2380 thread = machine__findnew_thread(trace->host, sample->pid, sample->tid);
2381 if (thread && thread__is_filtered(thread))
2382 goto out;
2384 trace__set_base_time(trace, evsel, sample);
2386 if (handler) {
2387 ++trace->nr_events;
2388 handler(trace, evsel, event, sample);
2390 out:
2391 thread__put(thread);
2392 return err;
2395 static int trace__record(struct trace *trace, int argc, const char **argv)
2397 unsigned int rec_argc, i, j;
2398 const char **rec_argv;
2399 const char * const record_args[] = {
2400 "record",
2401 "-R",
2402 "-m", "1024",
2403 "-c", "1",
2406 const char * const sc_args[] = { "-e", };
2407 unsigned int sc_args_nr = ARRAY_SIZE(sc_args);
2408 const char * const majpf_args[] = { "-e", "major-faults" };
2409 unsigned int majpf_args_nr = ARRAY_SIZE(majpf_args);
2410 const char * const minpf_args[] = { "-e", "minor-faults" };
2411 unsigned int minpf_args_nr = ARRAY_SIZE(minpf_args);
2413 /* +1 is for the event string below */
2414 rec_argc = ARRAY_SIZE(record_args) + sc_args_nr + 1 +
2415 majpf_args_nr + minpf_args_nr + argc;
2416 rec_argv = calloc(rec_argc + 1, sizeof(char *));
2418 if (rec_argv == NULL)
2419 return -ENOMEM;
2421 j = 0;
2422 for (i = 0; i < ARRAY_SIZE(record_args); i++)
2423 rec_argv[j++] = record_args[i];
2425 if (trace->trace_syscalls) {
2426 for (i = 0; i < sc_args_nr; i++)
2427 rec_argv[j++] = sc_args[i];
2429 /* event string may be different for older kernels - e.g., RHEL6 */
2430 if (is_valid_tracepoint("raw_syscalls:sys_enter"))
2431 rec_argv[j++] = "raw_syscalls:sys_enter,raw_syscalls:sys_exit";
2432 else if (is_valid_tracepoint("syscalls:sys_enter"))
2433 rec_argv[j++] = "syscalls:sys_enter,syscalls:sys_exit";
2434 else {
2435 pr_err("Neither raw_syscalls nor syscalls events exist.\n");
2436 free(rec_argv);
2437 return -1;
2441 if (trace->trace_pgfaults & TRACE_PFMAJ)
2442 for (i = 0; i < majpf_args_nr; i++)
2443 rec_argv[j++] = majpf_args[i];
2445 if (trace->trace_pgfaults & TRACE_PFMIN)
2446 for (i = 0; i < minpf_args_nr; i++)
2447 rec_argv[j++] = minpf_args[i];
2449 for (i = 0; i < (unsigned int)argc; i++)
2450 rec_argv[j++] = argv[i];
2452 return cmd_record(j, rec_argv);
2455 static size_t trace__fprintf_thread_summary(struct trace *trace, FILE *fp);
2457 static bool perf_evlist__add_vfs_getname(struct perf_evlist *evlist)
2459 struct perf_evsel *evsel = perf_evsel__newtp("probe", "vfs_getname");
2461 if (IS_ERR(evsel))
2462 return false;
2464 if (perf_evsel__field(evsel, "pathname") == NULL) {
2465 perf_evsel__delete(evsel);
2466 return false;
2469 evsel->handler = trace__vfs_getname;
2470 perf_evlist__add(evlist, evsel);
2471 return true;
2474 static struct perf_evsel *perf_evsel__new_pgfault(u64 config)
2476 struct perf_evsel *evsel;
2477 struct perf_event_attr attr = {
2478 .type = PERF_TYPE_SOFTWARE,
2479 .mmap_data = 1,
2482 attr.config = config;
2483 attr.sample_period = 1;
2485 event_attr_init(&attr);
2487 evsel = perf_evsel__new(&attr);
2488 if (evsel)
2489 evsel->handler = trace__pgfault;
2491 return evsel;
2494 static void trace__handle_event(struct trace *trace, union perf_event *event, struct perf_sample *sample)
2496 const u32 type = event->header.type;
2497 struct perf_evsel *evsel;
2499 if (type != PERF_RECORD_SAMPLE) {
2500 trace__process_event(trace, trace->host, event, sample);
2501 return;
2504 evsel = perf_evlist__id2evsel(trace->evlist, sample->id);
2505 if (evsel == NULL) {
2506 fprintf(trace->output, "Unknown tp ID %" PRIu64 ", skipping...\n", sample->id);
2507 return;
2510 trace__set_base_time(trace, evsel, sample);
2512 if (evsel->attr.type == PERF_TYPE_TRACEPOINT &&
2513 sample->raw_data == NULL) {
2514 fprintf(trace->output, "%s sample with no payload for tid: %d, cpu %d, raw_size=%d, skipping...\n",
2515 perf_evsel__name(evsel), sample->tid,
2516 sample->cpu, sample->raw_size);
2517 } else {
2518 tracepoint_handler handler = evsel->handler;
2519 handler(trace, evsel, event, sample);
2522 if (trace->nr_events_printed >= trace->max_events && trace->max_events != ULONG_MAX)
2523 interrupted = true;
2526 static int trace__add_syscall_newtp(struct trace *trace)
2528 int ret = -1;
2529 struct perf_evlist *evlist = trace->evlist;
2530 struct perf_evsel *sys_enter, *sys_exit;
2532 sys_enter = perf_evsel__raw_syscall_newtp("sys_enter", trace__sys_enter);
2533 if (sys_enter == NULL)
2534 goto out;
2536 if (perf_evsel__init_sc_tp_ptr_field(sys_enter, args))
2537 goto out_delete_sys_enter;
2539 sys_exit = perf_evsel__raw_syscall_newtp("sys_exit", trace__sys_exit);
2540 if (sys_exit == NULL)
2541 goto out_delete_sys_enter;
2543 if (perf_evsel__init_sc_tp_uint_field(sys_exit, ret))
2544 goto out_delete_sys_exit;
2546 perf_evsel__config_callchain(sys_enter, &trace->opts, &callchain_param);
2547 perf_evsel__config_callchain(sys_exit, &trace->opts, &callchain_param);
2549 perf_evlist__add(evlist, sys_enter);
2550 perf_evlist__add(evlist, sys_exit);
2552 if (callchain_param.enabled && !trace->kernel_syscallchains) {
2554 * We're interested only in the user space callchain
2555 * leading to the syscall, allow overriding that for
2556 * debugging reasons using --kernel_syscall_callchains
2558 sys_exit->attr.exclude_callchain_kernel = 1;
2561 trace->syscalls.events.sys_enter = sys_enter;
2562 trace->syscalls.events.sys_exit = sys_exit;
2564 ret = 0;
2565 out:
2566 return ret;
2568 out_delete_sys_exit:
2569 perf_evsel__delete_priv(sys_exit);
2570 out_delete_sys_enter:
2571 perf_evsel__delete_priv(sys_enter);
2572 goto out;
2575 static int trace__set_ev_qualifier_tp_filter(struct trace *trace)
2577 int err = -1;
2578 struct perf_evsel *sys_exit;
2579 char *filter = asprintf_expr_inout_ints("id", !trace->not_ev_qualifier,
2580 trace->ev_qualifier_ids.nr,
2581 trace->ev_qualifier_ids.entries);
2583 if (filter == NULL)
2584 goto out_enomem;
2586 if (!perf_evsel__append_tp_filter(trace->syscalls.events.sys_enter,
2587 filter)) {
2588 sys_exit = trace->syscalls.events.sys_exit;
2589 err = perf_evsel__append_tp_filter(sys_exit, filter);
2592 free(filter);
2593 out:
2594 return err;
2595 out_enomem:
2596 errno = ENOMEM;
2597 goto out;
2600 #ifdef HAVE_LIBBPF_SUPPORT
2601 static int trace__set_ev_qualifier_bpf_filter(struct trace *trace)
2603 int fd = bpf_map__fd(trace->syscalls.map);
2604 struct bpf_map_syscall_entry value = {
2605 .enabled = !trace->not_ev_qualifier,
2607 int err = 0;
2608 size_t i;
2610 for (i = 0; i < trace->ev_qualifier_ids.nr; ++i) {
2611 int key = trace->ev_qualifier_ids.entries[i];
2613 err = bpf_map_update_elem(fd, &key, &value, BPF_EXIST);
2614 if (err)
2615 break;
2618 return err;
2621 static int __trace__init_syscalls_bpf_map(struct trace *trace, bool enabled)
2623 int fd = bpf_map__fd(trace->syscalls.map);
2624 struct bpf_map_syscall_entry value = {
2625 .enabled = enabled,
2627 int err = 0, key;
2629 for (key = 0; key < trace->sctbl->syscalls.nr_entries; ++key) {
2630 err = bpf_map_update_elem(fd, &key, &value, BPF_ANY);
2631 if (err)
2632 break;
2635 return err;
2638 static int trace__init_syscalls_bpf_map(struct trace *trace)
2640 bool enabled = true;
2642 if (trace->ev_qualifier_ids.nr)
2643 enabled = trace->not_ev_qualifier;
2645 return __trace__init_syscalls_bpf_map(trace, enabled);
2647 #else
2648 static int trace__set_ev_qualifier_bpf_filter(struct trace *trace __maybe_unused)
2650 return 0;
2653 static int trace__init_syscalls_bpf_map(struct trace *trace __maybe_unused)
2655 return 0;
2657 #endif // HAVE_LIBBPF_SUPPORT
2659 static int trace__set_ev_qualifier_filter(struct trace *trace)
2661 if (trace->syscalls.map)
2662 return trace__set_ev_qualifier_bpf_filter(trace);
2663 return trace__set_ev_qualifier_tp_filter(trace);
2666 static int bpf_map__set_filter_pids(struct bpf_map *map __maybe_unused,
2667 size_t npids __maybe_unused, pid_t *pids __maybe_unused)
2669 int err = 0;
2670 #ifdef HAVE_LIBBPF_SUPPORT
2671 bool value = true;
2672 int map_fd = bpf_map__fd(map);
2673 size_t i;
2675 for (i = 0; i < npids; ++i) {
2676 err = bpf_map_update_elem(map_fd, &pids[i], &value, BPF_ANY);
2677 if (err)
2678 break;
2680 #endif
2681 return err;
2684 static int trace__set_filter_loop_pids(struct trace *trace)
2686 unsigned int nr = 1, err;
2687 pid_t pids[32] = {
2688 getpid(),
2690 struct thread *thread = machine__find_thread(trace->host, pids[0], pids[0]);
2692 while (thread && nr < ARRAY_SIZE(pids)) {
2693 struct thread *parent = machine__find_thread(trace->host, thread->ppid, thread->ppid);
2695 if (parent == NULL)
2696 break;
2698 if (!strcmp(thread__comm_str(parent), "sshd")) {
2699 pids[nr++] = parent->tid;
2700 break;
2702 thread = parent;
2705 err = perf_evlist__set_tp_filter_pids(trace->evlist, nr, pids);
2706 if (!err && trace->filter_pids.map)
2707 err = bpf_map__set_filter_pids(trace->filter_pids.map, nr, pids);
2709 return err;
2712 static int trace__set_filter_pids(struct trace *trace)
2714 int err = 0;
2716 * Better not use !target__has_task() here because we need to cover the
2717 * case where no threads were specified in the command line, but a
2718 * workload was, and in that case we will fill in the thread_map when
2719 * we fork the workload in perf_evlist__prepare_workload.
2721 if (trace->filter_pids.nr > 0) {
2722 err = perf_evlist__set_tp_filter_pids(trace->evlist, trace->filter_pids.nr,
2723 trace->filter_pids.entries);
2724 if (!err && trace->filter_pids.map) {
2725 err = bpf_map__set_filter_pids(trace->filter_pids.map, trace->filter_pids.nr,
2726 trace->filter_pids.entries);
2728 } else if (thread_map__pid(trace->evlist->threads, 0) == -1) {
2729 err = trace__set_filter_loop_pids(trace);
2732 return err;
2735 static int __trace__deliver_event(struct trace *trace, union perf_event *event)
2737 struct perf_evlist *evlist = trace->evlist;
2738 struct perf_sample sample;
2739 int err;
2741 err = perf_evlist__parse_sample(evlist, event, &sample);
2742 if (err)
2743 fprintf(trace->output, "Can't parse sample, err = %d, skipping...\n", err);
2744 else
2745 trace__handle_event(trace, event, &sample);
2747 return 0;
2750 static int __trace__flush_events(struct trace *trace)
2752 u64 first = ordered_events__first_time(&trace->oe.data);
2753 u64 flush = trace->oe.last - NSEC_PER_SEC;
2755 /* Is there some thing to flush.. */
2756 if (first && first < flush)
2757 return ordered_events__flush_time(&trace->oe.data, flush);
2759 return 0;
2762 static int trace__flush_events(struct trace *trace)
2764 return !trace->sort_events ? 0 : __trace__flush_events(trace);
2767 static int trace__deliver_event(struct trace *trace, union perf_event *event)
2769 int err;
2771 if (!trace->sort_events)
2772 return __trace__deliver_event(trace, event);
2774 err = perf_evlist__parse_sample_timestamp(trace->evlist, event, &trace->oe.last);
2775 if (err && err != -1)
2776 return err;
2778 err = ordered_events__queue(&trace->oe.data, event, trace->oe.last, 0);
2779 if (err)
2780 return err;
2782 return trace__flush_events(trace);
2785 static int ordered_events__deliver_event(struct ordered_events *oe,
2786 struct ordered_event *event)
2788 struct trace *trace = container_of(oe, struct trace, oe.data);
2790 return __trace__deliver_event(trace, event->event);
2793 static int trace__run(struct trace *trace, int argc, const char **argv)
2795 struct perf_evlist *evlist = trace->evlist;
2796 struct perf_evsel *evsel, *pgfault_maj = NULL, *pgfault_min = NULL;
2797 int err = -1, i;
2798 unsigned long before;
2799 const bool forks = argc > 0;
2800 bool draining = false;
2802 trace->live = true;
2804 if (!trace->raw_augmented_syscalls) {
2805 if (trace->trace_syscalls && trace__add_syscall_newtp(trace))
2806 goto out_error_raw_syscalls;
2808 if (trace->trace_syscalls)
2809 trace->vfs_getname = perf_evlist__add_vfs_getname(evlist);
2812 if ((trace->trace_pgfaults & TRACE_PFMAJ)) {
2813 pgfault_maj = perf_evsel__new_pgfault(PERF_COUNT_SW_PAGE_FAULTS_MAJ);
2814 if (pgfault_maj == NULL)
2815 goto out_error_mem;
2816 perf_evsel__config_callchain(pgfault_maj, &trace->opts, &callchain_param);
2817 perf_evlist__add(evlist, pgfault_maj);
2820 if ((trace->trace_pgfaults & TRACE_PFMIN)) {
2821 pgfault_min = perf_evsel__new_pgfault(PERF_COUNT_SW_PAGE_FAULTS_MIN);
2822 if (pgfault_min == NULL)
2823 goto out_error_mem;
2824 perf_evsel__config_callchain(pgfault_min, &trace->opts, &callchain_param);
2825 perf_evlist__add(evlist, pgfault_min);
2828 if (trace->sched &&
2829 perf_evlist__add_newtp(evlist, "sched", "sched_stat_runtime",
2830 trace__sched_stat_runtime))
2831 goto out_error_sched_stat_runtime;
2834 * If a global cgroup was set, apply it to all the events without an
2835 * explicit cgroup. I.e.:
2837 * trace -G A -e sched:*switch
2839 * Will set all raw_syscalls:sys_{enter,exit}, pgfault, vfs_getname, etc
2840 * _and_ sched:sched_switch to the 'A' cgroup, while:
2842 * trace -e sched:*switch -G A
2844 * will only set the sched:sched_switch event to the 'A' cgroup, all the
2845 * other events (raw_syscalls:sys_{enter,exit}, etc are left "without"
2846 * a cgroup (on the root cgroup, sys wide, etc).
2848 * Multiple cgroups:
2850 * trace -G A -e sched:*switch -G B
2852 * the syscall ones go to the 'A' cgroup, the sched:sched_switch goes
2853 * to the 'B' cgroup.
2855 * evlist__set_default_cgroup() grabs a reference of the passed cgroup
2856 * only for the evsels still without a cgroup, i.e. evsel->cgroup == NULL.
2858 if (trace->cgroup)
2859 evlist__set_default_cgroup(trace->evlist, trace->cgroup);
2861 err = perf_evlist__create_maps(evlist, &trace->opts.target);
2862 if (err < 0) {
2863 fprintf(trace->output, "Problems parsing the target to trace, check your options!\n");
2864 goto out_delete_evlist;
2867 err = trace__symbols_init(trace, evlist);
2868 if (err < 0) {
2869 fprintf(trace->output, "Problems initializing symbol libraries!\n");
2870 goto out_delete_evlist;
2873 perf_evlist__config(evlist, &trace->opts, &callchain_param);
2875 signal(SIGCHLD, sig_handler);
2876 signal(SIGINT, sig_handler);
2878 if (forks) {
2879 err = perf_evlist__prepare_workload(evlist, &trace->opts.target,
2880 argv, false, NULL);
2881 if (err < 0) {
2882 fprintf(trace->output, "Couldn't run the workload!\n");
2883 goto out_delete_evlist;
2887 err = perf_evlist__open(evlist);
2888 if (err < 0)
2889 goto out_error_open;
2891 err = bpf__apply_obj_config();
2892 if (err) {
2893 char errbuf[BUFSIZ];
2895 bpf__strerror_apply_obj_config(err, errbuf, sizeof(errbuf));
2896 pr_err("ERROR: Apply config to BPF failed: %s\n",
2897 errbuf);
2898 goto out_error_open;
2901 err = trace__set_filter_pids(trace);
2902 if (err < 0)
2903 goto out_error_mem;
2905 if (trace->syscalls.map)
2906 trace__init_syscalls_bpf_map(trace);
2908 if (trace->ev_qualifier_ids.nr > 0) {
2909 err = trace__set_ev_qualifier_filter(trace);
2910 if (err < 0)
2911 goto out_errno;
2913 if (trace->syscalls.events.sys_exit) {
2914 pr_debug("event qualifier tracepoint filter: %s\n",
2915 trace->syscalls.events.sys_exit->filter);
2919 err = perf_evlist__apply_filters(evlist, &evsel);
2920 if (err < 0)
2921 goto out_error_apply_filters;
2923 err = perf_evlist__mmap(evlist, trace->opts.mmap_pages);
2924 if (err < 0)
2925 goto out_error_mmap;
2927 if (!target__none(&trace->opts.target) && !trace->opts.initial_delay)
2928 perf_evlist__enable(evlist);
2930 if (forks)
2931 perf_evlist__start_workload(evlist);
2933 if (trace->opts.initial_delay) {
2934 usleep(trace->opts.initial_delay * 1000);
2935 perf_evlist__enable(evlist);
2938 trace->multiple_threads = thread_map__pid(evlist->threads, 0) == -1 ||
2939 evlist->threads->nr > 1 ||
2940 perf_evlist__first(evlist)->attr.inherit;
2943 * Now that we already used evsel->attr to ask the kernel to setup the
2944 * events, lets reuse evsel->attr.sample_max_stack as the limit in
2945 * trace__resolve_callchain(), allowing per-event max-stack settings
2946 * to override an explicitly set --max-stack global setting.
2948 evlist__for_each_entry(evlist, evsel) {
2949 if (evsel__has_callchain(evsel) &&
2950 evsel->attr.sample_max_stack == 0)
2951 evsel->attr.sample_max_stack = trace->max_stack;
2953 again:
2954 before = trace->nr_events;
2956 for (i = 0; i < evlist->nr_mmaps; i++) {
2957 union perf_event *event;
2958 struct perf_mmap *md;
2960 md = &evlist->mmap[i];
2961 if (perf_mmap__read_init(md) < 0)
2962 continue;
2964 while ((event = perf_mmap__read_event(md)) != NULL) {
2965 ++trace->nr_events;
2967 err = trace__deliver_event(trace, event);
2968 if (err)
2969 goto out_disable;
2971 perf_mmap__consume(md);
2973 if (interrupted)
2974 goto out_disable;
2976 if (done && !draining) {
2977 perf_evlist__disable(evlist);
2978 draining = true;
2981 perf_mmap__read_done(md);
2984 if (trace->nr_events == before) {
2985 int timeout = done ? 100 : -1;
2987 if (!draining && perf_evlist__poll(evlist, timeout) > 0) {
2988 if (perf_evlist__filter_pollfd(evlist, POLLERR | POLLHUP | POLLNVAL) == 0)
2989 draining = true;
2991 goto again;
2992 } else {
2993 if (trace__flush_events(trace))
2994 goto out_disable;
2996 } else {
2997 goto again;
3000 out_disable:
3001 thread__zput(trace->current);
3003 perf_evlist__disable(evlist);
3005 if (trace->sort_events)
3006 ordered_events__flush(&trace->oe.data, OE_FLUSH__FINAL);
3008 if (!err) {
3009 if (trace->summary)
3010 trace__fprintf_thread_summary(trace, trace->output);
3012 if (trace->show_tool_stats) {
3013 fprintf(trace->output, "Stats:\n "
3014 " vfs_getname : %" PRIu64 "\n"
3015 " proc_getname: %" PRIu64 "\n",
3016 trace->stats.vfs_getname,
3017 trace->stats.proc_getname);
3021 out_delete_evlist:
3022 trace__symbols__exit(trace);
3024 perf_evlist__delete(evlist);
3025 cgroup__put(trace->cgroup);
3026 trace->evlist = NULL;
3027 trace->live = false;
3028 return err;
3030 char errbuf[BUFSIZ];
3032 out_error_sched_stat_runtime:
3033 tracing_path__strerror_open_tp(errno, errbuf, sizeof(errbuf), "sched", "sched_stat_runtime");
3034 goto out_error;
3036 out_error_raw_syscalls:
3037 tracing_path__strerror_open_tp(errno, errbuf, sizeof(errbuf), "raw_syscalls", "sys_(enter|exit)");
3038 goto out_error;
3040 out_error_mmap:
3041 perf_evlist__strerror_mmap(evlist, errno, errbuf, sizeof(errbuf));
3042 goto out_error;
3044 out_error_open:
3045 perf_evlist__strerror_open(evlist, errno, errbuf, sizeof(errbuf));
3047 out_error:
3048 fprintf(trace->output, "%s\n", errbuf);
3049 goto out_delete_evlist;
3051 out_error_apply_filters:
3052 fprintf(trace->output,
3053 "Failed to set filter \"%s\" on event %s with %d (%s)\n",
3054 evsel->filter, perf_evsel__name(evsel), errno,
3055 str_error_r(errno, errbuf, sizeof(errbuf)));
3056 goto out_delete_evlist;
3058 out_error_mem:
3059 fprintf(trace->output, "Not enough memory to run!\n");
3060 goto out_delete_evlist;
3062 out_errno:
3063 fprintf(trace->output, "errno=%d,%s\n", errno, strerror(errno));
3064 goto out_delete_evlist;
3067 static int trace__replay(struct trace *trace)
3069 const struct perf_evsel_str_handler handlers[] = {
3070 { "probe:vfs_getname", trace__vfs_getname, },
3072 struct perf_data data = {
3073 .file = {
3074 .path = input_name,
3076 .mode = PERF_DATA_MODE_READ,
3077 .force = trace->force,
3079 struct perf_session *session;
3080 struct perf_evsel *evsel;
3081 int err = -1;
3083 trace->tool.sample = trace__process_sample;
3084 trace->tool.mmap = perf_event__process_mmap;
3085 trace->tool.mmap2 = perf_event__process_mmap2;
3086 trace->tool.comm = perf_event__process_comm;
3087 trace->tool.exit = perf_event__process_exit;
3088 trace->tool.fork = perf_event__process_fork;
3089 trace->tool.attr = perf_event__process_attr;
3090 trace->tool.tracing_data = perf_event__process_tracing_data;
3091 trace->tool.build_id = perf_event__process_build_id;
3092 trace->tool.namespaces = perf_event__process_namespaces;
3094 trace->tool.ordered_events = true;
3095 trace->tool.ordering_requires_timestamps = true;
3097 /* add tid to output */
3098 trace->multiple_threads = true;
3100 session = perf_session__new(&data, false, &trace->tool);
3101 if (session == NULL)
3102 return -1;
3104 if (trace->opts.target.pid)
3105 symbol_conf.pid_list_str = strdup(trace->opts.target.pid);
3107 if (trace->opts.target.tid)
3108 symbol_conf.tid_list_str = strdup(trace->opts.target.tid);
3110 if (symbol__init(&session->header.env) < 0)
3111 goto out;
3113 trace->host = &session->machines.host;
3115 err = perf_session__set_tracepoints_handlers(session, handlers);
3116 if (err)
3117 goto out;
3119 evsel = perf_evlist__find_tracepoint_by_name(session->evlist,
3120 "raw_syscalls:sys_enter");
3121 /* older kernels have syscalls tp versus raw_syscalls */
3122 if (evsel == NULL)
3123 evsel = perf_evlist__find_tracepoint_by_name(session->evlist,
3124 "syscalls:sys_enter");
3126 if (evsel &&
3127 (perf_evsel__init_raw_syscall_tp(evsel, trace__sys_enter) < 0 ||
3128 perf_evsel__init_sc_tp_ptr_field(evsel, args))) {
3129 pr_err("Error during initialize raw_syscalls:sys_enter event\n");
3130 goto out;
3133 evsel = perf_evlist__find_tracepoint_by_name(session->evlist,
3134 "raw_syscalls:sys_exit");
3135 if (evsel == NULL)
3136 evsel = perf_evlist__find_tracepoint_by_name(session->evlist,
3137 "syscalls:sys_exit");
3138 if (evsel &&
3139 (perf_evsel__init_raw_syscall_tp(evsel, trace__sys_exit) < 0 ||
3140 perf_evsel__init_sc_tp_uint_field(evsel, ret))) {
3141 pr_err("Error during initialize raw_syscalls:sys_exit event\n");
3142 goto out;
3145 evlist__for_each_entry(session->evlist, evsel) {
3146 if (evsel->attr.type == PERF_TYPE_SOFTWARE &&
3147 (evsel->attr.config == PERF_COUNT_SW_PAGE_FAULTS_MAJ ||
3148 evsel->attr.config == PERF_COUNT_SW_PAGE_FAULTS_MIN ||
3149 evsel->attr.config == PERF_COUNT_SW_PAGE_FAULTS))
3150 evsel->handler = trace__pgfault;
3153 setup_pager();
3155 err = perf_session__process_events(session);
3156 if (err)
3157 pr_err("Failed to process events, error %d", err);
3159 else if (trace->summary)
3160 trace__fprintf_thread_summary(trace, trace->output);
3162 out:
3163 perf_session__delete(session);
3165 return err;
3168 static size_t trace__fprintf_threads_header(FILE *fp)
3170 size_t printed;
3172 printed = fprintf(fp, "\n Summary of events:\n\n");
3174 return printed;
3177 DEFINE_RESORT_RB(syscall_stats, a->msecs > b->msecs,
3178 struct stats *stats;
3179 double msecs;
3180 int syscall;
3183 struct int_node *source = rb_entry(nd, struct int_node, rb_node);
3184 struct stats *stats = source->priv;
3186 entry->syscall = source->i;
3187 entry->stats = stats;
3188 entry->msecs = stats ? (u64)stats->n * (avg_stats(stats) / NSEC_PER_MSEC) : 0;
3191 static size_t thread__dump_stats(struct thread_trace *ttrace,
3192 struct trace *trace, FILE *fp)
3194 size_t printed = 0;
3195 struct syscall *sc;
3196 struct rb_node *nd;
3197 DECLARE_RESORT_RB_INTLIST(syscall_stats, ttrace->syscall_stats);
3199 if (syscall_stats == NULL)
3200 return 0;
3202 printed += fprintf(fp, "\n");
3204 printed += fprintf(fp, " syscall calls total min avg max stddev\n");
3205 printed += fprintf(fp, " (msec) (msec) (msec) (msec) (%%)\n");
3206 printed += fprintf(fp, " --------------- -------- --------- --------- --------- --------- ------\n");
3208 resort_rb__for_each_entry(nd, syscall_stats) {
3209 struct stats *stats = syscall_stats_entry->stats;
3210 if (stats) {
3211 double min = (double)(stats->min) / NSEC_PER_MSEC;
3212 double max = (double)(stats->max) / NSEC_PER_MSEC;
3213 double avg = avg_stats(stats);
3214 double pct;
3215 u64 n = (u64) stats->n;
3217 pct = avg ? 100.0 * stddev_stats(stats)/avg : 0.0;
3218 avg /= NSEC_PER_MSEC;
3220 sc = &trace->syscalls.table[syscall_stats_entry->syscall];
3221 printed += fprintf(fp, " %-15s", sc->name);
3222 printed += fprintf(fp, " %8" PRIu64 " %9.3f %9.3f %9.3f",
3223 n, syscall_stats_entry->msecs, min, avg);
3224 printed += fprintf(fp, " %9.3f %9.2f%%\n", max, pct);
3228 resort_rb__delete(syscall_stats);
3229 printed += fprintf(fp, "\n\n");
3231 return printed;
3234 static size_t trace__fprintf_thread(FILE *fp, struct thread *thread, struct trace *trace)
3236 size_t printed = 0;
3237 struct thread_trace *ttrace = thread__priv(thread);
3238 double ratio;
3240 if (ttrace == NULL)
3241 return 0;
3243 ratio = (double)ttrace->nr_events / trace->nr_events * 100.0;
3245 printed += fprintf(fp, " %s (%d), ", thread__comm_str(thread), thread->tid);
3246 printed += fprintf(fp, "%lu events, ", ttrace->nr_events);
3247 printed += fprintf(fp, "%.1f%%", ratio);
3248 if (ttrace->pfmaj)
3249 printed += fprintf(fp, ", %lu majfaults", ttrace->pfmaj);
3250 if (ttrace->pfmin)
3251 printed += fprintf(fp, ", %lu minfaults", ttrace->pfmin);
3252 if (trace->sched)
3253 printed += fprintf(fp, ", %.3f msec\n", ttrace->runtime_ms);
3254 else if (fputc('\n', fp) != EOF)
3255 ++printed;
3257 printed += thread__dump_stats(ttrace, trace, fp);
3259 return printed;
3262 static unsigned long thread__nr_events(struct thread_trace *ttrace)
3264 return ttrace ? ttrace->nr_events : 0;
3267 DEFINE_RESORT_RB(threads, (thread__nr_events(a->thread->priv) < thread__nr_events(b->thread->priv)),
3268 struct thread *thread;
3271 entry->thread = rb_entry(nd, struct thread, rb_node);
3274 static size_t trace__fprintf_thread_summary(struct trace *trace, FILE *fp)
3276 size_t printed = trace__fprintf_threads_header(fp);
3277 struct rb_node *nd;
3278 int i;
3280 for (i = 0; i < THREADS__TABLE_SIZE; i++) {
3281 DECLARE_RESORT_RB_MACHINE_THREADS(threads, trace->host, i);
3283 if (threads == NULL) {
3284 fprintf(fp, "%s", "Error sorting output by nr_events!\n");
3285 return 0;
3288 resort_rb__for_each_entry(nd, threads)
3289 printed += trace__fprintf_thread(fp, threads_entry->thread, trace);
3291 resort_rb__delete(threads);
3293 return printed;
3296 static int trace__set_duration(const struct option *opt, const char *str,
3297 int unset __maybe_unused)
3299 struct trace *trace = opt->value;
3301 trace->duration_filter = atof(str);
3302 return 0;
3305 static int trace__set_filter_pids_from_option(const struct option *opt, const char *str,
3306 int unset __maybe_unused)
3308 int ret = -1;
3309 size_t i;
3310 struct trace *trace = opt->value;
3312 * FIXME: introduce a intarray class, plain parse csv and create a
3313 * { int nr, int entries[] } struct...
3315 struct intlist *list = intlist__new(str);
3317 if (list == NULL)
3318 return -1;
3320 i = trace->filter_pids.nr = intlist__nr_entries(list) + 1;
3321 trace->filter_pids.entries = calloc(i, sizeof(pid_t));
3323 if (trace->filter_pids.entries == NULL)
3324 goto out;
3326 trace->filter_pids.entries[0] = getpid();
3328 for (i = 1; i < trace->filter_pids.nr; ++i)
3329 trace->filter_pids.entries[i] = intlist__entry(list, i - 1)->i;
3331 intlist__delete(list);
3332 ret = 0;
3333 out:
3334 return ret;
3337 static int trace__open_output(struct trace *trace, const char *filename)
3339 struct stat st;
3341 if (!stat(filename, &st) && st.st_size) {
3342 char oldname[PATH_MAX];
3344 scnprintf(oldname, sizeof(oldname), "%s.old", filename);
3345 unlink(oldname);
3346 rename(filename, oldname);
3349 trace->output = fopen(filename, "w");
3351 return trace->output == NULL ? -errno : 0;
3354 static int parse_pagefaults(const struct option *opt, const char *str,
3355 int unset __maybe_unused)
3357 int *trace_pgfaults = opt->value;
3359 if (strcmp(str, "all") == 0)
3360 *trace_pgfaults |= TRACE_PFMAJ | TRACE_PFMIN;
3361 else if (strcmp(str, "maj") == 0)
3362 *trace_pgfaults |= TRACE_PFMAJ;
3363 else if (strcmp(str, "min") == 0)
3364 *trace_pgfaults |= TRACE_PFMIN;
3365 else
3366 return -1;
3368 return 0;
3371 static void evlist__set_evsel_handler(struct perf_evlist *evlist, void *handler)
3373 struct perf_evsel *evsel;
3375 evlist__for_each_entry(evlist, evsel)
3376 evsel->handler = handler;
3379 static int evlist__set_syscall_tp_fields(struct perf_evlist *evlist)
3381 struct perf_evsel *evsel;
3383 evlist__for_each_entry(evlist, evsel) {
3384 if (evsel->priv || !evsel->tp_format)
3385 continue;
3387 if (strcmp(evsel->tp_format->system, "syscalls"))
3388 continue;
3390 if (perf_evsel__init_syscall_tp(evsel))
3391 return -1;
3393 if (!strncmp(evsel->tp_format->name, "sys_enter_", 10)) {
3394 struct syscall_tp *sc = evsel->priv;
3396 if (__tp_field__init_ptr(&sc->args, sc->id.offset + sizeof(u64)))
3397 return -1;
3398 } else if (!strncmp(evsel->tp_format->name, "sys_exit_", 9)) {
3399 struct syscall_tp *sc = evsel->priv;
3401 if (__tp_field__init_uint(&sc->ret, sizeof(u64), sc->id.offset + sizeof(u64), evsel->needs_swap))
3402 return -1;
3406 return 0;
3410 * XXX: Hackish, just splitting the combined -e+--event (syscalls
3411 * (raw_syscalls:{sys_{enter,exit}} + events (tracepoints, HW, SW, etc) to use
3412 * existing facilities unchanged (trace->ev_qualifier + parse_options()).
3414 * It'd be better to introduce a parse_options() variant that would return a
3415 * list with the terms it didn't match to an event...
3417 static int trace__parse_events_option(const struct option *opt, const char *str,
3418 int unset __maybe_unused)
3420 struct trace *trace = (struct trace *)opt->value;
3421 const char *s = str;
3422 char *sep = NULL, *lists[2] = { NULL, NULL, };
3423 int len = strlen(str) + 1, err = -1, list, idx;
3424 char *strace_groups_dir = system_path(STRACE_GROUPS_DIR);
3425 char group_name[PATH_MAX];
3426 struct syscall_fmt *fmt;
3428 if (strace_groups_dir == NULL)
3429 return -1;
3431 if (*s == '!') {
3432 ++s;
3433 trace->not_ev_qualifier = true;
3436 while (1) {
3437 if ((sep = strchr(s, ',')) != NULL)
3438 *sep = '\0';
3440 list = 0;
3441 if (syscalltbl__id(trace->sctbl, s) >= 0 ||
3442 syscalltbl__strglobmatch_first(trace->sctbl, s, &idx) >= 0) {
3443 list = 1;
3444 goto do_concat;
3447 fmt = syscall_fmt__find_by_alias(s);
3448 if (fmt != NULL) {
3449 list = 1;
3450 s = fmt->name;
3451 } else {
3452 path__join(group_name, sizeof(group_name), strace_groups_dir, s);
3453 if (access(group_name, R_OK) == 0)
3454 list = 1;
3456 do_concat:
3457 if (lists[list]) {
3458 sprintf(lists[list] + strlen(lists[list]), ",%s", s);
3459 } else {
3460 lists[list] = malloc(len);
3461 if (lists[list] == NULL)
3462 goto out;
3463 strcpy(lists[list], s);
3466 if (!sep)
3467 break;
3469 *sep = ',';
3470 s = sep + 1;
3473 if (lists[1] != NULL) {
3474 struct strlist_config slist_config = {
3475 .dirname = strace_groups_dir,
3478 trace->ev_qualifier = strlist__new(lists[1], &slist_config);
3479 if (trace->ev_qualifier == NULL) {
3480 fputs("Not enough memory to parse event qualifier", trace->output);
3481 goto out;
3484 if (trace__validate_ev_qualifier(trace))
3485 goto out;
3486 trace->trace_syscalls = true;
3489 err = 0;
3491 if (lists[0]) {
3492 struct option o = OPT_CALLBACK('e', "event", &trace->evlist, "event",
3493 "event selector. use 'perf list' to list available events",
3494 parse_events_option);
3495 err = parse_events_option(&o, lists[0], 0);
3497 out:
3498 if (sep)
3499 *sep = ',';
3501 return err;
3504 static int trace__parse_cgroups(const struct option *opt, const char *str, int unset)
3506 struct trace *trace = opt->value;
3508 if (!list_empty(&trace->evlist->entries))
3509 return parse_cgroups(opt, str, unset);
3511 trace->cgroup = evlist__findnew_cgroup(trace->evlist, str);
3513 return 0;
3516 static struct bpf_map *bpf__find_map_by_name(const char *name)
3518 struct bpf_object *obj, *tmp;
3520 bpf_object__for_each_safe(obj, tmp) {
3521 struct bpf_map *map = bpf_object__find_map_by_name(obj, name);
3522 if (map)
3523 return map;
3527 return NULL;
3530 static void trace__set_bpf_map_filtered_pids(struct trace *trace)
3532 trace->filter_pids.map = bpf__find_map_by_name("pids_filtered");
3535 static void trace__set_bpf_map_syscalls(struct trace *trace)
3537 trace->syscalls.map = bpf__find_map_by_name("syscalls");
3540 static int trace__config(const char *var, const char *value, void *arg)
3542 struct trace *trace = arg;
3543 int err = 0;
3545 if (!strcmp(var, "trace.add_events")) {
3546 struct option o = OPT_CALLBACK('e', "event", &trace->evlist, "event",
3547 "event selector. use 'perf list' to list available events",
3548 parse_events_option);
3549 err = parse_events_option(&o, value, 0);
3550 } else if (!strcmp(var, "trace.show_timestamp")) {
3551 trace->show_tstamp = perf_config_bool(var, value);
3552 } else if (!strcmp(var, "trace.show_duration")) {
3553 trace->show_duration = perf_config_bool(var, value);
3554 } else if (!strcmp(var, "trace.show_arg_names")) {
3555 trace->show_arg_names = perf_config_bool(var, value);
3556 if (!trace->show_arg_names)
3557 trace->show_zeros = true;
3558 } else if (!strcmp(var, "trace.show_zeros")) {
3559 bool new_show_zeros = perf_config_bool(var, value);
3560 if (!trace->show_arg_names && !new_show_zeros) {
3561 pr_warning("trace.show_zeros has to be set when trace.show_arg_names=no\n");
3562 goto out;
3564 trace->show_zeros = new_show_zeros;
3565 } else if (!strcmp(var, "trace.no_inherit")) {
3566 trace->opts.no_inherit = perf_config_bool(var, value);
3567 } else if (!strcmp(var, "trace.args_alignment")) {
3568 int args_alignment = 0;
3569 if (perf_config_int(&args_alignment, var, value) == 0)
3570 trace->args_alignment = args_alignment;
3572 out:
3573 return err;
3576 int cmd_trace(int argc, const char **argv)
3578 const char *trace_usage[] = {
3579 "perf trace [<options>] [<command>]",
3580 "perf trace [<options>] -- <command> [<options>]",
3581 "perf trace record [<options>] [<command>]",
3582 "perf trace record [<options>] -- <command> [<options>]",
3583 NULL
3585 struct trace trace = {
3586 .syscalls = {
3587 . max = -1,
3589 .opts = {
3590 .target = {
3591 .uid = UINT_MAX,
3592 .uses_mmap = true,
3594 .user_freq = UINT_MAX,
3595 .user_interval = ULLONG_MAX,
3596 .no_buffering = true,
3597 .mmap_pages = UINT_MAX,
3599 .output = stderr,
3600 .show_comm = true,
3601 .show_tstamp = true,
3602 .show_duration = true,
3603 .show_arg_names = true,
3604 .args_alignment = 70,
3605 .trace_syscalls = false,
3606 .kernel_syscallchains = false,
3607 .max_stack = UINT_MAX,
3608 .max_events = ULONG_MAX,
3610 const char *output_name = NULL;
3611 const struct option trace_options[] = {
3612 OPT_CALLBACK('e', "event", &trace, "event",
3613 "event/syscall selector. use 'perf list' to list available events",
3614 trace__parse_events_option),
3615 OPT_BOOLEAN(0, "comm", &trace.show_comm,
3616 "show the thread COMM next to its id"),
3617 OPT_BOOLEAN(0, "tool_stats", &trace.show_tool_stats, "show tool stats"),
3618 OPT_CALLBACK(0, "expr", &trace, "expr", "list of syscalls/events to trace",
3619 trace__parse_events_option),
3620 OPT_STRING('o', "output", &output_name, "file", "output file name"),
3621 OPT_STRING('i', "input", &input_name, "file", "Analyze events in file"),
3622 OPT_STRING('p', "pid", &trace.opts.target.pid, "pid",
3623 "trace events on existing process id"),
3624 OPT_STRING('t', "tid", &trace.opts.target.tid, "tid",
3625 "trace events on existing thread id"),
3626 OPT_CALLBACK(0, "filter-pids", &trace, "CSV list of pids",
3627 "pids to filter (by the kernel)", trace__set_filter_pids_from_option),
3628 OPT_BOOLEAN('a', "all-cpus", &trace.opts.target.system_wide,
3629 "system-wide collection from all CPUs"),
3630 OPT_STRING('C', "cpu", &trace.opts.target.cpu_list, "cpu",
3631 "list of cpus to monitor"),
3632 OPT_BOOLEAN(0, "no-inherit", &trace.opts.no_inherit,
3633 "child tasks do not inherit counters"),
3634 OPT_CALLBACK('m', "mmap-pages", &trace.opts.mmap_pages, "pages",
3635 "number of mmap data pages",
3636 perf_evlist__parse_mmap_pages),
3637 OPT_STRING('u', "uid", &trace.opts.target.uid_str, "user",
3638 "user to profile"),
3639 OPT_CALLBACK(0, "duration", &trace, "float",
3640 "show only events with duration > N.M ms",
3641 trace__set_duration),
3642 OPT_BOOLEAN(0, "sched", &trace.sched, "show blocking scheduler events"),
3643 OPT_INCR('v', "verbose", &verbose, "be more verbose"),
3644 OPT_BOOLEAN('T', "time", &trace.full_time,
3645 "Show full timestamp, not time relative to first start"),
3646 OPT_BOOLEAN(0, "failure", &trace.failure_only,
3647 "Show only syscalls that failed"),
3648 OPT_BOOLEAN('s', "summary", &trace.summary_only,
3649 "Show only syscall summary with statistics"),
3650 OPT_BOOLEAN('S', "with-summary", &trace.summary,
3651 "Show all syscalls and summary with statistics"),
3652 OPT_CALLBACK_DEFAULT('F', "pf", &trace.trace_pgfaults, "all|maj|min",
3653 "Trace pagefaults", parse_pagefaults, "maj"),
3654 OPT_BOOLEAN(0, "syscalls", &trace.trace_syscalls, "Trace syscalls"),
3655 OPT_BOOLEAN('f', "force", &trace.force, "don't complain, do it"),
3656 OPT_CALLBACK(0, "call-graph", &trace.opts,
3657 "record_mode[,record_size]", record_callchain_help,
3658 &record_parse_callchain_opt),
3659 OPT_BOOLEAN(0, "kernel-syscall-graph", &trace.kernel_syscallchains,
3660 "Show the kernel callchains on the syscall exit path"),
3661 OPT_ULONG(0, "max-events", &trace.max_events,
3662 "Set the maximum number of events to print, exit after that is reached. "),
3663 OPT_UINTEGER(0, "min-stack", &trace.min_stack,
3664 "Set the minimum stack depth when parsing the callchain, "
3665 "anything below the specified depth will be ignored."),
3666 OPT_UINTEGER(0, "max-stack", &trace.max_stack,
3667 "Set the maximum stack depth when parsing the callchain, "
3668 "anything beyond the specified depth will be ignored. "
3669 "Default: kernel.perf_event_max_stack or " __stringify(PERF_MAX_STACK_DEPTH)),
3670 OPT_BOOLEAN(0, "sort-events", &trace.sort_events,
3671 "Sort batch of events before processing, use if getting out of order events"),
3672 OPT_BOOLEAN(0, "print-sample", &trace.print_sample,
3673 "print the PERF_RECORD_SAMPLE PERF_SAMPLE_ info, for debugging"),
3674 OPT_UINTEGER(0, "proc-map-timeout", &proc_map_timeout,
3675 "per thread proc mmap processing timeout in ms"),
3676 OPT_CALLBACK('G', "cgroup", &trace, "name", "monitor event in cgroup name only",
3677 trace__parse_cgroups),
3678 OPT_UINTEGER('D', "delay", &trace.opts.initial_delay,
3679 "ms to wait before starting measurement after program "
3680 "start"),
3681 OPT_END()
3683 bool __maybe_unused max_stack_user_set = true;
3684 bool mmap_pages_user_set = true;
3685 struct perf_evsel *evsel;
3686 const char * const trace_subcommands[] = { "record", NULL };
3687 int err = -1;
3688 char bf[BUFSIZ];
3690 signal(SIGSEGV, sighandler_dump_stack);
3691 signal(SIGFPE, sighandler_dump_stack);
3693 trace.evlist = perf_evlist__new();
3694 trace.sctbl = syscalltbl__new();
3696 if (trace.evlist == NULL || trace.sctbl == NULL) {
3697 pr_err("Not enough memory to run!\n");
3698 err = -ENOMEM;
3699 goto out;
3702 err = perf_config(trace__config, &trace);
3703 if (err)
3704 goto out;
3706 argc = parse_options_subcommand(argc, argv, trace_options, trace_subcommands,
3707 trace_usage, PARSE_OPT_STOP_AT_NON_OPTION);
3709 if ((nr_cgroups || trace.cgroup) && !trace.opts.target.system_wide) {
3710 usage_with_options_msg(trace_usage, trace_options,
3711 "cgroup monitoring only available in system-wide mode");
3714 evsel = bpf__setup_output_event(trace.evlist, "__augmented_syscalls__");
3715 if (IS_ERR(evsel)) {
3716 bpf__strerror_setup_output_event(trace.evlist, PTR_ERR(evsel), bf, sizeof(bf));
3717 pr_err("ERROR: Setup trace syscalls enter failed: %s\n", bf);
3718 goto out;
3721 if (evsel) {
3722 trace.syscalls.events.augmented = evsel;
3723 trace__set_bpf_map_filtered_pids(&trace);
3724 trace__set_bpf_map_syscalls(&trace);
3727 err = bpf__setup_stdout(trace.evlist);
3728 if (err) {
3729 bpf__strerror_setup_stdout(trace.evlist, err, bf, sizeof(bf));
3730 pr_err("ERROR: Setup BPF stdout failed: %s\n", bf);
3731 goto out;
3734 err = -1;
3736 if (trace.trace_pgfaults) {
3737 trace.opts.sample_address = true;
3738 trace.opts.sample_time = true;
3741 if (trace.opts.mmap_pages == UINT_MAX)
3742 mmap_pages_user_set = false;
3744 if (trace.max_stack == UINT_MAX) {
3745 trace.max_stack = input_name ? PERF_MAX_STACK_DEPTH : sysctl__max_stack();
3746 max_stack_user_set = false;
3749 #ifdef HAVE_DWARF_UNWIND_SUPPORT
3750 if ((trace.min_stack || max_stack_user_set) && !callchain_param.enabled) {
3751 record_opts__parse_callchain(&trace.opts, &callchain_param, "dwarf", false);
3753 #endif
3755 if (callchain_param.enabled) {
3756 if (!mmap_pages_user_set && geteuid() == 0)
3757 trace.opts.mmap_pages = perf_event_mlock_kb_in_pages() * 4;
3759 symbol_conf.use_callchain = true;
3762 if (trace.evlist->nr_entries > 0) {
3763 evlist__set_evsel_handler(trace.evlist, trace__event_handler);
3764 if (evlist__set_syscall_tp_fields(trace.evlist)) {
3765 perror("failed to set syscalls:* tracepoint fields");
3766 goto out;
3770 if (trace.sort_events) {
3771 ordered_events__init(&trace.oe.data, ordered_events__deliver_event, &trace);
3772 ordered_events__set_copy_on_queue(&trace.oe.data, true);
3776 * If we are augmenting syscalls, then combine what we put in the
3777 * __augmented_syscalls__ BPF map with what is in the
3778 * syscalls:sys_exit_FOO tracepoints, i.e. just like we do without BPF,
3779 * combining raw_syscalls:sys_enter with raw_syscalls:sys_exit.
3781 * We'll switch to look at two BPF maps, one for sys_enter and the
3782 * other for sys_exit when we start augmenting the sys_exit paths with
3783 * buffers that are being copied from kernel to userspace, think 'read'
3784 * syscall.
3786 if (trace.syscalls.events.augmented) {
3787 evsel = trace.syscalls.events.augmented;
3789 if (perf_evsel__init_augmented_syscall_tp(evsel) ||
3790 perf_evsel__init_augmented_syscall_tp_args(evsel))
3791 goto out;
3792 evsel->handler = trace__sys_enter;
3794 evlist__for_each_entry(trace.evlist, evsel) {
3795 bool raw_syscalls_sys_exit = strcmp(perf_evsel__name(evsel), "raw_syscalls:sys_exit") == 0;
3797 if (raw_syscalls_sys_exit) {
3798 trace.raw_augmented_syscalls = true;
3799 goto init_augmented_syscall_tp;
3802 if (strstarts(perf_evsel__name(evsel), "syscalls:sys_exit_")) {
3803 init_augmented_syscall_tp:
3804 perf_evsel__init_augmented_syscall_tp(evsel);
3805 perf_evsel__init_augmented_syscall_tp_ret(evsel);
3806 evsel->handler = trace__sys_exit;
3811 if ((argc >= 1) && (strcmp(argv[0], "record") == 0))
3812 return trace__record(&trace, argc-1, &argv[1]);
3814 /* summary_only implies summary option, but don't overwrite summary if set */
3815 if (trace.summary_only)
3816 trace.summary = trace.summary_only;
3818 if (!trace.trace_syscalls && !trace.trace_pgfaults &&
3819 trace.evlist->nr_entries == 0 /* Was --events used? */) {
3820 trace.trace_syscalls = true;
3823 if (output_name != NULL) {
3824 err = trace__open_output(&trace, output_name);
3825 if (err < 0) {
3826 perror("failed to create output file");
3827 goto out;
3831 err = target__validate(&trace.opts.target);
3832 if (err) {
3833 target__strerror(&trace.opts.target, err, bf, sizeof(bf));
3834 fprintf(trace.output, "%s", bf);
3835 goto out_close;
3838 err = target__parse_uid(&trace.opts.target);
3839 if (err) {
3840 target__strerror(&trace.opts.target, err, bf, sizeof(bf));
3841 fprintf(trace.output, "%s", bf);
3842 goto out_close;
3845 if (!argc && target__none(&trace.opts.target))
3846 trace.opts.target.system_wide = true;
3848 if (input_name)
3849 err = trace__replay(&trace);
3850 else
3851 err = trace__run(&trace, argc, argv);
3853 out_close:
3854 if (output_name != NULL)
3855 fclose(trace.output);
3856 out:
3857 return err;