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.
8 #define _FILE_OFFSET_BITS 64
14 #include "util/build-id.h"
15 #include "util/util.h"
16 #include "util/parse-options.h"
17 #include "util/parse-events.h"
18 #include "util/string.h"
20 #include "util/header.h"
21 #include "util/event.h"
22 #include "util/debug.h"
23 #include "util/session.h"
24 #include "util/symbol.h"
29 static int fd
[MAX_NR_CPUS
][MAX_COUNTERS
];
31 static long default_interval
= 0;
33 static int nr_cpus
= 0;
34 static unsigned int page_size
;
35 static unsigned int mmap_pages
= 128;
36 static int freq
= 1000;
38 static const char *output_name
= "perf.data";
40 static unsigned int realtime_prio
= 0;
41 static int raw_samples
= 0;
42 static int system_wide
= 0;
43 static int profile_cpu
= -1;
44 static pid_t target_pid
= -1;
45 static pid_t child_pid
= -1;
46 static int inherit
= 1;
48 static int append_file
= 0;
49 static int call_graph
= 0;
50 static int inherit_stat
= 0;
51 static int no_samples
= 0;
52 static int sample_address
= 0;
53 static int multiplex
= 0;
54 static int multiplex_fd
= -1;
56 static long samples
= 0;
57 static struct timeval last_read
;
58 static struct timeval this_read
;
60 static u64 bytes_written
= 0;
62 static struct pollfd event_array
[MAX_NR_CPUS
* MAX_COUNTERS
];
64 static int nr_poll
= 0;
65 static int nr_cpu
= 0;
67 static int file_new
= 1;
68 static off_t post_processing_offset
;
70 static struct perf_session
*session
;
79 static struct mmap_data mmap_array
[MAX_NR_CPUS
][MAX_COUNTERS
];
81 static unsigned long mmap_read_head(struct mmap_data
*md
)
83 struct perf_event_mmap_page
*pc
= md
->base
;
92 static void mmap_write_tail(struct mmap_data
*md
, unsigned long tail
)
94 struct perf_event_mmap_page
*pc
= md
->base
;
97 * ensure all reads are done before we write the tail out.
100 pc
->data_tail
= tail
;
103 static void write_output(void *buf
, size_t size
)
106 int ret
= write(output
, buf
, size
);
109 die("failed to write");
114 bytes_written
+= ret
;
118 static int process_synthesized_event(event_t
*event
,
119 struct perf_session
*self __used
)
121 write_output(event
, event
->header
.size
);
125 static void mmap_read(struct mmap_data
*md
)
127 unsigned int head
= mmap_read_head(md
);
128 unsigned int old
= md
->prev
;
129 unsigned char *data
= md
->base
+ page_size
;
134 gettimeofday(&this_read
, NULL
);
137 * If we're further behind than half the buffer, there's a chance
138 * the writer will bite our tail and mess up the samples under us.
140 * If we somehow ended up ahead of the head, we got messed up.
142 * In either case, truncate and restart at head.
149 timersub(&this_read
, &last_read
, &iv
);
150 msecs
= iv
.tv_sec
*1000 + iv
.tv_usec
/1000;
152 fprintf(stderr
, "WARNING: failed to keep up with mmap data."
153 " Last read %lu msecs ago.\n", msecs
);
156 * head points to a known good entry, start there.
161 last_read
= this_read
;
168 if ((old
& md
->mask
) + size
!= (head
& md
->mask
)) {
169 buf
= &data
[old
& md
->mask
];
170 size
= md
->mask
+ 1 - (old
& md
->mask
);
173 write_output(buf
, size
);
176 buf
= &data
[old
& md
->mask
];
180 write_output(buf
, size
);
183 mmap_write_tail(md
, old
);
186 static volatile int done
= 0;
187 static volatile int signr
= -1;
189 static void sig_handler(int sig
)
195 static void sig_atexit(void)
198 kill(child_pid
, SIGTERM
);
203 signal(signr
, SIG_DFL
);
204 kill(getpid(), signr
);
209 static struct perf_header_attr
*get_header_attr(struct perf_event_attr
*a
, int nr
)
211 struct perf_header_attr
*h_attr
;
213 if (nr
< session
->header
.attrs
) {
214 h_attr
= session
->header
.attr
[nr
];
216 h_attr
= perf_header_attr__new(a
);
218 if (perf_header__add_attr(&session
->header
, h_attr
) < 0) {
219 perf_header_attr__delete(h_attr
);
227 static void create_counter(int counter
, int cpu
, pid_t pid
)
229 char *filter
= filters
[counter
];
230 struct perf_event_attr
*attr
= attrs
+ counter
;
231 struct perf_header_attr
*h_attr
;
232 int track
= !counter
; /* only the first counter needs these */
241 attr
->read_format
= PERF_FORMAT_TOTAL_TIME_ENABLED
|
242 PERF_FORMAT_TOTAL_TIME_RUNNING
|
245 attr
->sample_type
|= PERF_SAMPLE_IP
| PERF_SAMPLE_TID
;
248 attr
->sample_type
|= PERF_SAMPLE_ID
;
251 attr
->sample_type
|= PERF_SAMPLE_PERIOD
;
253 attr
->sample_freq
= freq
;
257 attr
->sample_freq
= 0;
260 attr
->inherit_stat
= 1;
263 attr
->sample_type
|= PERF_SAMPLE_ADDR
;
266 attr
->sample_type
|= PERF_SAMPLE_CALLCHAIN
;
269 attr
->sample_type
|= PERF_SAMPLE_TIME
;
270 attr
->sample_type
|= PERF_SAMPLE_RAW
;
271 attr
->sample_type
|= PERF_SAMPLE_CPU
;
276 attr
->inherit
= inherit
;
280 fd
[nr_cpu
][counter
] = sys_perf_event_open(attr
, pid
, cpu
, group_fd
, 0);
282 if (fd
[nr_cpu
][counter
] < 0) {
285 if (err
== EPERM
|| err
== EACCES
)
286 die("Permission error - are you root?\n");
287 else if (err
== ENODEV
&& profile_cpu
!= -1)
288 die("No such device - did you specify an out-of-range profile CPU?\n");
291 * If it's cycles then fall back to hrtimer
292 * based cpu-clock-tick sw counter, which
293 * is always available even if no PMU support:
295 if (attr
->type
== PERF_TYPE_HARDWARE
296 && attr
->config
== PERF_COUNT_HW_CPU_CYCLES
) {
299 warning(" ... trying to fall back to cpu-clock-ticks\n");
300 attr
->type
= PERF_TYPE_SOFTWARE
;
301 attr
->config
= PERF_COUNT_SW_CPU_CLOCK
;
305 error("perfcounter syscall returned with %d (%s)\n",
306 fd
[nr_cpu
][counter
], strerror(err
));
308 #if defined(__i386__) || defined(__x86_64__)
309 if (attr
->type
== PERF_TYPE_HARDWARE
&& err
== EOPNOTSUPP
)
310 die("No hardware sampling interrupt available. No APIC? If so then you can boot the kernel with the \"lapic\" boot parameter to force-enable it.\n");
313 die("No CONFIG_PERF_EVENTS=y kernel support configured?\n");
317 h_attr
= get_header_attr(attr
, counter
);
322 if (memcmp(&h_attr
->attr
, attr
, sizeof(*attr
))) {
323 fprintf(stderr
, "incompatible append\n");
328 if (read(fd
[nr_cpu
][counter
], &read_data
, sizeof(read_data
)) == -1) {
329 perror("Unable to read perf file descriptor\n");
333 if (perf_header_attr__add_id(h_attr
, read_data
.id
) < 0) {
334 pr_warning("Not enough memory to add id\n");
338 assert(fd
[nr_cpu
][counter
] >= 0);
339 fcntl(fd
[nr_cpu
][counter
], F_SETFL
, O_NONBLOCK
);
342 * First counter acts as the group leader:
344 if (group
&& group_fd
== -1)
345 group_fd
= fd
[nr_cpu
][counter
];
346 if (multiplex
&& multiplex_fd
== -1)
347 multiplex_fd
= fd
[nr_cpu
][counter
];
349 if (multiplex
&& fd
[nr_cpu
][counter
] != multiplex_fd
) {
351 ret
= ioctl(fd
[nr_cpu
][counter
], PERF_EVENT_IOC_SET_OUTPUT
, multiplex_fd
);
354 event_array
[nr_poll
].fd
= fd
[nr_cpu
][counter
];
355 event_array
[nr_poll
].events
= POLLIN
;
358 mmap_array
[nr_cpu
][counter
].counter
= counter
;
359 mmap_array
[nr_cpu
][counter
].prev
= 0;
360 mmap_array
[nr_cpu
][counter
].mask
= mmap_pages
*page_size
- 1;
361 mmap_array
[nr_cpu
][counter
].base
= mmap(NULL
, (mmap_pages
+1)*page_size
,
362 PROT_READ
|PROT_WRITE
, MAP_SHARED
, fd
[nr_cpu
][counter
], 0);
363 if (mmap_array
[nr_cpu
][counter
].base
== MAP_FAILED
) {
364 error("failed to mmap with %d (%s)\n", errno
, strerror(errno
));
369 if (filter
!= NULL
) {
370 ret
= ioctl(fd
[nr_cpu
][counter
],
371 PERF_EVENT_IOC_SET_FILTER
, filter
);
373 error("failed to set filter with %d (%s)\n", errno
,
379 ioctl(fd
[nr_cpu
][counter
], PERF_EVENT_IOC_ENABLE
);
382 static void open_counters(int cpu
, pid_t pid
)
387 for (counter
= 0; counter
< nr_counters
; counter
++)
388 create_counter(counter
, cpu
, pid
);
393 static int process_buildids(void)
395 u64 size
= lseek(output
, 0, SEEK_CUR
);
397 session
->fd
= output
;
398 return __perf_session__process_events(session
, post_processing_offset
,
399 size
- post_processing_offset
,
400 size
, &build_id__mark_dso_hit_ops
);
403 static void atexit_header(void)
405 session
->header
.data_size
+= bytes_written
;
408 perf_header__write(&session
->header
, output
, true);
411 static int __cmd_record(int argc
, const char **argv
)
418 unsigned long waking
= 0;
419 int child_ready_pipe
[2], go_pipe
[2];
420 const bool forks
= target_pid
== -1 && argc
> 0;
423 page_size
= sysconf(_SC_PAGE_SIZE
);
424 nr_cpus
= sysconf(_SC_NPROCESSORS_ONLN
);
425 assert(nr_cpus
<= MAX_NR_CPUS
);
426 assert(nr_cpus
>= 0);
429 signal(SIGCHLD
, sig_handler
);
430 signal(SIGINT
, sig_handler
);
432 if (forks
&& (pipe(child_ready_pipe
) < 0 || pipe(go_pipe
) < 0)) {
433 perror("failed to create pipes");
437 if (!stat(output_name
, &st
) && st
.st_size
) {
440 pr_err("Error, output file %s exists, use -A "
441 "to append or -f to overwrite.\n",
446 char oldname
[PATH_MAX
];
447 snprintf(oldname
, sizeof(oldname
), "%s.old",
450 rename(output_name
, oldname
);
456 flags
= O_CREAT
|O_RDWR
;
462 output
= open(output_name
, flags
, S_IRUSR
|S_IWUSR
);
464 perror("failed to create output file");
468 session
= perf_session__new(output_name
, O_WRONLY
, force
);
469 if (session
== NULL
) {
470 pr_err("Not enough memory for reading perf file header\n");
475 err
= perf_header__read(&session
->header
, output
);
481 perf_header__set_feat(&session
->header
, HEADER_TRACE_INFO
);
483 for (i
= 0; i
< nr_counters
; i
++) {
484 if (attrs
[i
].sample_type
& PERF_SAMPLE_RAW
) {
485 perf_header__set_feat(&session
->header
, HEADER_TRACE_INFO
);
491 atexit(atexit_header
);
496 perror("failed to fork");
501 close(child_ready_pipe
[0]);
503 fcntl(go_pipe
[0], F_SETFD
, FD_CLOEXEC
);
506 * Do a dummy execvp to get the PLT entry resolved,
507 * so we avoid the resolver overhead on the real
510 execvp("", (char **)argv
);
513 * Tell the parent we're ready to go
515 close(child_ready_pipe
[1]);
518 * Wait until the parent tells us to go.
520 if (read(go_pipe
[0], &buf
, 1) == -1)
521 perror("unable to read pipe");
523 execvp(argv
[0], (char **)argv
);
534 close(child_ready_pipe
[1]);
537 * wait for child to settle
539 if (read(child_ready_pipe
[0], &buf
, 1) == -1) {
540 perror("unable to read pipe");
543 close(child_ready_pipe
[0]);
547 if ((!system_wide
&& !inherit
) || profile_cpu
!= -1) {
548 open_counters(profile_cpu
, target_pid
);
550 for (i
= 0; i
< nr_cpus
; i
++)
551 open_counters(i
, target_pid
);
555 err
= perf_header__write(&session
->header
, output
, false);
560 post_processing_offset
= lseek(output
, 0, SEEK_CUR
);
562 err
= event__synthesize_kernel_mmap(process_synthesized_event
,
565 pr_err("Couldn't record kernel reference relocation symbol.\n");
569 err
= event__synthesize_modules(process_synthesized_event
, session
);
571 pr_err("Couldn't record kernel reference relocation symbol.\n");
575 if (!system_wide
&& profile_cpu
== -1)
576 event__synthesize_thread(target_pid
, process_synthesized_event
,
579 event__synthesize_threads(process_synthesized_event
, session
);
582 struct sched_param param
;
584 param
.sched_priority
= realtime_prio
;
585 if (sched_setscheduler(0, SCHED_FIFO
, ¶m
)) {
586 pr_err("Could not set realtime priority.\n");
600 for (i
= 0; i
< nr_cpu
; i
++) {
601 for (counter
= 0; counter
< nr_counters
; counter
++) {
602 if (mmap_array
[i
][counter
].base
)
603 mmap_read(&mmap_array
[i
][counter
]);
607 if (hits
== samples
) {
610 err
= poll(event_array
, nr_poll
, -1);
615 for (i
= 0; i
< nr_cpu
; i
++) {
616 for (counter
= 0; counter
< nr_counters
; counter
++)
617 ioctl(fd
[i
][counter
], PERF_EVENT_IOC_DISABLE
);
622 fprintf(stderr
, "[ perf record: Woken up %ld times to write data ]\n", waking
);
625 * Approximate RIP event size: 24 bytes.
628 "[ perf record: Captured and wrote %.3f MB %s (~%lld samples) ]\n",
629 (double)bytes_written
/ 1024.0 / 1024.0,
636 static const char * const record_usage
[] = {
637 "perf record [<options>] [<command>]",
638 "perf record [<options>] -- <command> [<options>]",
642 static const struct option options
[] = {
643 OPT_CALLBACK('e', "event", NULL
, "event",
644 "event selector. use 'perf list' to list available events",
646 OPT_CALLBACK(0, "filter", NULL
, "filter",
647 "event filter", parse_filter
),
648 OPT_INTEGER('p', "pid", &target_pid
,
649 "record events on existing pid"),
650 OPT_INTEGER('r', "realtime", &realtime_prio
,
651 "collect data with this RT SCHED_FIFO priority"),
652 OPT_BOOLEAN('R', "raw-samples", &raw_samples
,
653 "collect raw sample records from all opened counters"),
654 OPT_BOOLEAN('a', "all-cpus", &system_wide
,
655 "system-wide collection from all CPUs"),
656 OPT_BOOLEAN('A', "append", &append_file
,
657 "append to the output file to do incremental profiling"),
658 OPT_INTEGER('C', "profile_cpu", &profile_cpu
,
659 "CPU to profile on"),
660 OPT_BOOLEAN('f', "force", &force
,
661 "overwrite existing data file"),
662 OPT_LONG('c', "count", &default_interval
,
663 "event period to sample"),
664 OPT_STRING('o', "output", &output_name
, "file",
666 OPT_BOOLEAN('i', "inherit", &inherit
,
667 "child tasks inherit counters"),
668 OPT_INTEGER('F', "freq", &freq
,
669 "profile at this frequency"),
670 OPT_INTEGER('m', "mmap-pages", &mmap_pages
,
671 "number of mmap data pages"),
672 OPT_BOOLEAN('g', "call-graph", &call_graph
,
673 "do call-graph (stack chain/backtrace) recording"),
674 OPT_BOOLEAN('v', "verbose", &verbose
,
675 "be more verbose (show counter open errors, etc)"),
676 OPT_BOOLEAN('s', "stat", &inherit_stat
,
677 "per thread counts"),
678 OPT_BOOLEAN('d', "data", &sample_address
,
680 OPT_BOOLEAN('n', "no-samples", &no_samples
,
682 OPT_BOOLEAN('M', "multiplex", &multiplex
,
683 "multiplex counter output in a single channel"),
687 int cmd_record(int argc
, const char **argv
, const char *prefix __used
)
691 argc
= parse_options(argc
, argv
, options
, record_usage
,
692 PARSE_OPT_STOP_AT_NON_OPTION
);
693 if (!argc
&& target_pid
== -1 && !system_wide
&& profile_cpu
== -1)
694 usage_with_options(record_usage
, options
);
700 attrs
[0].type
= PERF_TYPE_HARDWARE
;
701 attrs
[0].config
= PERF_COUNT_HW_CPU_CYCLES
;
705 * User specified count overrides default frequency.
707 if (default_interval
)
710 default_interval
= freq
;
712 fprintf(stderr
, "frequency and count are zero, aborting\n");
716 for (counter
= 0; counter
< nr_counters
; counter
++) {
717 if (attrs
[counter
].sample_period
)
720 attrs
[counter
].sample_period
= default_interval
;
723 return __cmd_record(argc
, argv
);