4 * Builtin record command: Record the profile of a workload
5 * (or a CPU, or a PID) into the perf.data output file - for
6 * later analysis via perf report.
12 #include "util/util.h"
13 #include "util/parse-options.h"
14 #include "util/parse-events.h"
15 #include "util/string.h"
17 #include "util/header.h"
18 #include "util/event.h"
19 #include "util/debug.h"
20 #include "util/trace-event.h"
25 #define ALIGN(x, a) __ALIGN_MASK(x, (typeof(x))(a)-1)
26 #define __ALIGN_MASK(x, mask) (((x)+(mask))&~(mask))
28 static int fd
[MAX_NR_CPUS
][MAX_COUNTERS
];
30 static long default_interval
= 100000;
32 static int nr_cpus
= 0;
33 static unsigned int page_size
;
34 static unsigned int mmap_pages
= 128;
37 static const char *output_name
= "perf.data";
39 static unsigned int realtime_prio
= 0;
40 static int raw_samples
= 0;
41 static int system_wide
= 0;
42 static int profile_cpu
= -1;
43 static pid_t target_pid
= -1;
44 static pid_t child_pid
= -1;
45 static int inherit
= 1;
47 static int append_file
= 0;
48 static int call_graph
= 0;
49 static int inherit_stat
= 0;
50 static int no_samples
= 0;
51 static int sample_address
= 0;
52 static int multiplex
= 0;
53 static int multiplex_fd
= -1;
56 static struct timeval last_read
;
57 static struct timeval this_read
;
59 static u64 bytes_written
;
61 static struct pollfd event_array
[MAX_NR_CPUS
* MAX_COUNTERS
];
66 static int file_new
= 1;
68 struct perf_header
*header
;
77 static struct mmap_data mmap_array
[MAX_NR_CPUS
][MAX_COUNTERS
];
79 static unsigned long mmap_read_head(struct mmap_data
*md
)
81 struct perf_event_mmap_page
*pc
= md
->base
;
90 static void mmap_write_tail(struct mmap_data
*md
, unsigned long tail
)
92 struct perf_event_mmap_page
*pc
= md
->base
;
95 * ensure all reads are done before we write the tail out.
101 static void write_output(void *buf
, size_t size
)
104 int ret
= write(output
, buf
, size
);
107 die("failed to write");
112 bytes_written
+= ret
;
116 static void mmap_read(struct mmap_data
*md
)
118 unsigned int head
= mmap_read_head(md
);
119 unsigned int old
= md
->prev
;
120 unsigned char *data
= md
->base
+ page_size
;
125 gettimeofday(&this_read
, NULL
);
128 * If we're further behind than half the buffer, there's a chance
129 * the writer will bite our tail and mess up the samples under us.
131 * If we somehow ended up ahead of the head, we got messed up.
133 * In either case, truncate and restart at head.
140 timersub(&this_read
, &last_read
, &iv
);
141 msecs
= iv
.tv_sec
*1000 + iv
.tv_usec
/1000;
143 fprintf(stderr
, "WARNING: failed to keep up with mmap data."
144 " Last read %lu msecs ago.\n", msecs
);
147 * head points to a known good entry, start there.
152 last_read
= this_read
;
159 if ((old
& md
->mask
) + size
!= (head
& md
->mask
)) {
160 buf
= &data
[old
& md
->mask
];
161 size
= md
->mask
+ 1 - (old
& md
->mask
);
164 write_output(buf
, size
);
167 buf
= &data
[old
& md
->mask
];
171 write_output(buf
, size
);
174 mmap_write_tail(md
, old
);
177 static volatile int done
= 0;
178 static volatile int signr
= -1;
180 static void sig_handler(int sig
)
186 static void sig_atexit(void)
189 kill(child_pid
, SIGTERM
);
194 signal(signr
, SIG_DFL
);
195 kill(getpid(), signr
);
198 static pid_t
pid_synthesize_comm_event(pid_t pid
, int full
)
200 struct comm_event comm_ev
;
201 char filename
[PATH_MAX
];
206 struct dirent dirent
, *next
;
209 snprintf(filename
, sizeof(filename
), "/proc/%d/status", pid
);
211 fp
= fopen(filename
, "r");
214 * We raced with a task exiting - just return:
217 fprintf(stderr
, "couldn't open %s\n", filename
);
221 memset(&comm_ev
, 0, sizeof(comm_ev
));
222 while (!comm_ev
.comm
[0] || !comm_ev
.pid
) {
223 if (fgets(bf
, sizeof(bf
), fp
) == NULL
)
226 if (memcmp(bf
, "Name:", 5) == 0) {
228 while (*name
&& isspace(*name
))
230 size
= strlen(name
) - 1;
231 memcpy(comm_ev
.comm
, name
, size
++);
232 } else if (memcmp(bf
, "Tgid:", 5) == 0) {
233 char *tgids
= bf
+ 5;
234 while (*tgids
&& isspace(*tgids
))
236 tgid
= comm_ev
.pid
= atoi(tgids
);
240 comm_ev
.header
.type
= PERF_RECORD_COMM
;
241 size
= ALIGN(size
, sizeof(u64
));
242 comm_ev
.header
.size
= sizeof(comm_ev
) - (sizeof(comm_ev
.comm
) - size
);
247 write_output(&comm_ev
, comm_ev
.header
.size
);
251 snprintf(filename
, sizeof(filename
), "/proc/%d/task", pid
);
253 tasks
= opendir(filename
);
254 while (!readdir_r(tasks
, &dirent
, &next
) && next
) {
256 pid
= strtol(dirent
.d_name
, &end
, 10);
262 write_output(&comm_ev
, comm_ev
.header
.size
);
271 fprintf(stderr
, "couldn't get COMM and pgid, malformed %s\n",
276 static void pid_synthesize_mmap_samples(pid_t pid
, pid_t tgid
)
278 char filename
[PATH_MAX
];
281 snprintf(filename
, sizeof(filename
), "/proc/%d/maps", pid
);
283 fp
= fopen(filename
, "r");
286 * We raced with a task exiting - just return:
289 fprintf(stderr
, "couldn't open %s\n", filename
);
293 char bf
[BUFSIZ
], *pbf
= bf
;
294 struct mmap_event mmap_ev
= {
295 .header
= { .type
= PERF_RECORD_MMAP
},
299 if (fgets(bf
, sizeof(bf
), fp
) == NULL
)
302 /* 00400000-0040c000 r-xp 00000000 fd:01 41038 /bin/cat */
303 n
= hex2u64(pbf
, &mmap_ev
.start
);
307 n
= hex2u64(pbf
, &mmap_ev
.len
);
311 if (*pbf
== 'x') { /* vm_exec */
312 char *execname
= strchr(bf
, '/');
315 if (execname
== NULL
)
316 execname
= strstr(bf
, "[vdso]");
318 if (execname
== NULL
)
321 size
= strlen(execname
);
322 execname
[size
- 1] = '\0'; /* Remove \n */
323 memcpy(mmap_ev
.filename
, execname
, size
);
324 size
= ALIGN(size
, sizeof(u64
));
325 mmap_ev
.len
-= mmap_ev
.start
;
326 mmap_ev
.header
.size
= (sizeof(mmap_ev
) -
327 (sizeof(mmap_ev
.filename
) - size
));
331 write_output(&mmap_ev
, mmap_ev
.header
.size
);
338 static void synthesize_all(void)
341 struct dirent dirent
, *next
;
343 proc
= opendir("/proc");
345 while (!readdir_r(proc
, &dirent
, &next
) && next
) {
349 pid
= strtol(dirent
.d_name
, &end
, 10);
350 if (*end
) /* only interested in proper numerical dirents */
353 tgid
= pid_synthesize_comm_event(pid
, 1);
354 pid_synthesize_mmap_samples(pid
, tgid
);
362 static struct perf_header_attr
*get_header_attr(struct perf_event_attr
*a
, int nr
)
364 struct perf_header_attr
*h_attr
;
366 if (nr
< header
->attrs
) {
367 h_attr
= header
->attr
[nr
];
369 h_attr
= perf_header_attr__new(a
);
370 perf_header__add_attr(header
, h_attr
);
376 static void create_counter(int counter
, int cpu
, pid_t pid
)
378 struct perf_event_attr
*attr
= attrs
+ counter
;
379 struct perf_header_attr
*h_attr
;
380 int track
= !counter
; /* only the first counter needs these */
388 attr
->read_format
= PERF_FORMAT_TOTAL_TIME_ENABLED
|
389 PERF_FORMAT_TOTAL_TIME_RUNNING
|
392 attr
->sample_type
|= PERF_SAMPLE_IP
| PERF_SAMPLE_TID
;
395 attr
->sample_type
|= PERF_SAMPLE_PERIOD
;
397 attr
->sample_freq
= freq
;
401 attr
->sample_freq
= 0;
404 attr
->inherit_stat
= 1;
407 attr
->sample_type
|= PERF_SAMPLE_ADDR
;
410 attr
->sample_type
|= PERF_SAMPLE_CALLCHAIN
;
413 attr
->sample_type
|= PERF_SAMPLE_TIME
;
414 attr
->sample_type
|= PERF_SAMPLE_RAW
;
415 attr
->sample_type
|= PERF_SAMPLE_CPU
;
420 attr
->inherit
= (cpu
< 0) && inherit
;
424 fd
[nr_cpu
][counter
] = sys_perf_event_open(attr
, pid
, cpu
, group_fd
, 0);
426 if (fd
[nr_cpu
][counter
] < 0) {
429 if (err
== EPERM
|| err
== EACCES
)
430 die("Permission error - are you root?\n");
431 else if (err
== ENODEV
&& profile_cpu
!= -1)
432 die("No such device - did you specify an out-of-range profile CPU?\n");
435 * If it's cycles then fall back to hrtimer
436 * based cpu-clock-tick sw counter, which
437 * is always available even if no PMU support:
439 if (attr
->type
== PERF_TYPE_HARDWARE
440 && attr
->config
== PERF_COUNT_HW_CPU_CYCLES
) {
443 warning(" ... trying to fall back to cpu-clock-ticks\n");
444 attr
->type
= PERF_TYPE_SOFTWARE
;
445 attr
->config
= PERF_COUNT_SW_CPU_CLOCK
;
449 error("perfcounter syscall returned with %d (%s)\n",
450 fd
[nr_cpu
][counter
], strerror(err
));
451 die("No CONFIG_PERF_EVENTS=y kernel support configured?\n");
455 h_attr
= get_header_attr(attr
, counter
);
458 if (memcmp(&h_attr
->attr
, attr
, sizeof(*attr
))) {
459 fprintf(stderr
, "incompatible append\n");
464 if (read(fd
[nr_cpu
][counter
], &read_data
, sizeof(read_data
)) == -1) {
465 perror("Unable to read perf file descriptor\n");
469 perf_header_attr__add_id(h_attr
, read_data
.id
);
471 assert(fd
[nr_cpu
][counter
] >= 0);
472 fcntl(fd
[nr_cpu
][counter
], F_SETFL
, O_NONBLOCK
);
475 * First counter acts as the group leader:
477 if (group
&& group_fd
== -1)
478 group_fd
= fd
[nr_cpu
][counter
];
479 if (multiplex
&& multiplex_fd
== -1)
480 multiplex_fd
= fd
[nr_cpu
][counter
];
482 if (multiplex
&& fd
[nr_cpu
][counter
] != multiplex_fd
) {
485 ret
= ioctl(fd
[nr_cpu
][counter
], PERF_EVENT_IOC_SET_OUTPUT
, multiplex_fd
);
488 event_array
[nr_poll
].fd
= fd
[nr_cpu
][counter
];
489 event_array
[nr_poll
].events
= POLLIN
;
492 mmap_array
[nr_cpu
][counter
].counter
= counter
;
493 mmap_array
[nr_cpu
][counter
].prev
= 0;
494 mmap_array
[nr_cpu
][counter
].mask
= mmap_pages
*page_size
- 1;
495 mmap_array
[nr_cpu
][counter
].base
= mmap(NULL
, (mmap_pages
+1)*page_size
,
496 PROT_READ
|PROT_WRITE
, MAP_SHARED
, fd
[nr_cpu
][counter
], 0);
497 if (mmap_array
[nr_cpu
][counter
].base
== MAP_FAILED
) {
498 error("failed to mmap with %d (%s)\n", errno
, strerror(errno
));
503 ioctl(fd
[nr_cpu
][counter
], PERF_EVENT_IOC_ENABLE
);
506 static void open_counters(int cpu
, pid_t pid
)
511 for (counter
= 0; counter
< nr_counters
; counter
++)
512 create_counter(counter
, cpu
, pid
);
517 static void atexit_header(void)
519 header
->data_size
+= bytes_written
;
521 perf_header__write(header
, output
);
524 static int __cmd_record(int argc
, const char **argv
)
531 unsigned long waking
= 0;
533 page_size
= sysconf(_SC_PAGE_SIZE
);
534 nr_cpus
= sysconf(_SC_NPROCESSORS_ONLN
);
535 assert(nr_cpus
<= MAX_NR_CPUS
);
536 assert(nr_cpus
>= 0);
539 signal(SIGCHLD
, sig_handler
);
540 signal(SIGINT
, sig_handler
);
542 if (!stat(output_name
, &st
) && st
.st_size
) {
543 if (!force
&& !append_file
) {
544 fprintf(stderr
, "Error, output file %s exists, use -A to append or -f to overwrite.\n",
552 flags
= O_CREAT
|O_RDWR
;
558 output
= open(output_name
, flags
, S_IRUSR
|S_IWUSR
);
560 perror("failed to create output file");
565 header
= perf_header__read(output
);
567 header
= perf_header__new();
571 read_tracing_data(attrs
, nr_counters
);
573 for (i
= 0; i
< nr_counters
; i
++) {
574 if (attrs
[i
].sample_type
& PERF_SAMPLE_RAW
) {
575 read_tracing_data(attrs
, nr_counters
);
580 atexit(atexit_header
);
587 open_counters(profile_cpu
, pid
);
589 if (profile_cpu
!= -1) {
590 open_counters(profile_cpu
, target_pid
);
592 for (i
= 0; i
< nr_cpus
; i
++)
593 open_counters(i
, target_pid
);
598 perf_header__write(header
, output
);
601 pid_t tgid
= pid_synthesize_comm_event(pid
, 0);
602 pid_synthesize_mmap_samples(pid
, tgid
);
606 if (target_pid
== -1 && argc
) {
609 perror("failed to fork");
612 if (execvp(argv
[0], (char **)argv
)) {
622 struct sched_param param
;
624 param
.sched_priority
= realtime_prio
;
625 if (sched_setscheduler(0, SCHED_FIFO
, ¶m
)) {
626 printf("Could not set realtime priority.\n");
634 for (i
= 0; i
< nr_cpu
; i
++) {
635 for (counter
= 0; counter
< nr_counters
; counter
++) {
636 if (mmap_array
[i
][counter
].base
)
637 mmap_read(&mmap_array
[i
][counter
]);
641 if (hits
== samples
) {
644 ret
= poll(event_array
, nr_poll
, -1);
649 for (i
= 0; i
< nr_cpu
; i
++) {
650 for (counter
= 0; counter
< nr_counters
; counter
++)
651 ioctl(fd
[i
][counter
], PERF_EVENT_IOC_DISABLE
);
656 fprintf(stderr
, "[ perf record: Woken up %ld times to write data ]\n", waking
);
659 * Approximate RIP event size: 24 bytes.
662 "[ perf record: Captured and wrote %.3f MB %s (~%lld samples) ]\n",
663 (double)bytes_written
/ 1024.0 / 1024.0,
670 static const char * const record_usage
[] = {
671 "perf record [<options>] [<command>]",
672 "perf record [<options>] -- <command> [<options>]",
676 static const struct option options
[] = {
677 OPT_CALLBACK('e', "event", NULL
, "event",
678 "event selector. use 'perf list' to list available events",
680 OPT_INTEGER('p', "pid", &target_pid
,
681 "record events on existing pid"),
682 OPT_INTEGER('r', "realtime", &realtime_prio
,
683 "collect data with this RT SCHED_FIFO priority"),
684 OPT_BOOLEAN('R', "raw-samples", &raw_samples
,
685 "collect raw sample records from all opened counters"),
686 OPT_BOOLEAN('a', "all-cpus", &system_wide
,
687 "system-wide collection from all CPUs"),
688 OPT_BOOLEAN('A', "append", &append_file
,
689 "append to the output file to do incremental profiling"),
690 OPT_INTEGER('C', "profile_cpu", &profile_cpu
,
691 "CPU to profile on"),
692 OPT_BOOLEAN('f', "force", &force
,
693 "overwrite existing data file"),
694 OPT_LONG('c', "count", &default_interval
,
695 "event period to sample"),
696 OPT_STRING('o', "output", &output_name
, "file",
698 OPT_BOOLEAN('i', "inherit", &inherit
,
699 "child tasks inherit counters"),
700 OPT_INTEGER('F', "freq", &freq
,
701 "profile at this frequency"),
702 OPT_INTEGER('m', "mmap-pages", &mmap_pages
,
703 "number of mmap data pages"),
704 OPT_BOOLEAN('g', "call-graph", &call_graph
,
705 "do call-graph (stack chain/backtrace) recording"),
706 OPT_BOOLEAN('v', "verbose", &verbose
,
707 "be more verbose (show counter open errors, etc)"),
708 OPT_BOOLEAN('s', "stat", &inherit_stat
,
709 "per thread counts"),
710 OPT_BOOLEAN('d', "data", &sample_address
,
712 OPT_BOOLEAN('n', "no-samples", &no_samples
,
714 OPT_BOOLEAN('M', "multiplex", &multiplex
,
715 "multiplex counter output in a single channel"),
719 int cmd_record(int argc
, const char **argv
, const char *prefix __used
)
723 argc
= parse_options(argc
, argv
, options
, record_usage
,
724 PARSE_OPT_STOP_AT_NON_OPTION
);
725 if (!argc
&& target_pid
== -1 && !system_wide
)
726 usage_with_options(record_usage
, options
);
730 attrs
[0].type
= PERF_TYPE_HARDWARE
;
731 attrs
[0].config
= PERF_COUNT_HW_CPU_CYCLES
;
734 for (counter
= 0; counter
< nr_counters
; counter
++) {
735 if (attrs
[counter
].sample_period
)
738 attrs
[counter
].sample_period
= default_interval
;
741 return __cmd_record(argc
, argv
);