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"
19 #include "util/header.h"
20 #include "util/event.h"
21 #include "util/debug.h"
22 #include "util/session.h"
23 #include "util/symbol.h"
24 #include "util/cpumap.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 int pipe_output
= 0;
39 static const char *output_name
= "perf.data";
41 static unsigned int realtime_prio
= 0;
42 static bool raw_samples
= false;
43 static bool system_wide
= false;
44 static int profile_cpu
= -1;
45 static pid_t target_pid
= -1;
46 static pid_t target_tid
= -1;
47 static pid_t
*all_tids
= NULL
;
48 static int thread_num
= 0;
49 static pid_t child_pid
= -1;
50 static bool inherit
= true;
51 static bool force
= false;
52 static bool append_file
= false;
53 static bool call_graph
= false;
54 static bool inherit_stat
= false;
55 static bool no_samples
= false;
56 static bool sample_address
= false;
57 static bool multiplex
= false;
58 static int multiplex_fd
= -1;
60 static long samples
= 0;
61 static struct timeval last_read
;
62 static struct timeval this_read
;
64 static u64 bytes_written
= 0;
66 static struct pollfd
*event_array
;
68 static int nr_poll
= 0;
69 static int nr_cpu
= 0;
71 static int file_new
= 1;
72 static off_t post_processing_offset
;
74 static struct perf_session
*session
;
83 static struct mmap_data
*mmap_array
[MAX_NR_CPUS
][MAX_COUNTERS
];
85 static unsigned long mmap_read_head(struct mmap_data
*md
)
87 struct perf_event_mmap_page
*pc
= md
->base
;
96 static void mmap_write_tail(struct mmap_data
*md
, unsigned long tail
)
98 struct perf_event_mmap_page
*pc
= md
->base
;
101 * ensure all reads are done before we write the tail out.
104 pc
->data_tail
= tail
;
107 static void advance_output(size_t size
)
109 bytes_written
+= size
;
112 static void write_output(void *buf
, size_t size
)
115 int ret
= write(output
, buf
, size
);
118 die("failed to write");
123 bytes_written
+= ret
;
127 static int process_synthesized_event(event_t
*event
,
128 struct perf_session
*self __used
)
130 write_output(event
, event
->header
.size
);
134 static void mmap_read(struct mmap_data
*md
)
136 unsigned int head
= mmap_read_head(md
);
137 unsigned int old
= md
->prev
;
138 unsigned char *data
= md
->base
+ page_size
;
143 gettimeofday(&this_read
, NULL
);
146 * If we're further behind than half the buffer, there's a chance
147 * the writer will bite our tail and mess up the samples under us.
149 * If we somehow ended up ahead of the head, we got messed up.
151 * In either case, truncate and restart at head.
158 timersub(&this_read
, &last_read
, &iv
);
159 msecs
= iv
.tv_sec
*1000 + iv
.tv_usec
/1000;
161 fprintf(stderr
, "WARNING: failed to keep up with mmap data."
162 " Last read %lu msecs ago.\n", msecs
);
165 * head points to a known good entry, start there.
170 last_read
= this_read
;
177 if ((old
& md
->mask
) + size
!= (head
& md
->mask
)) {
178 buf
= &data
[old
& md
->mask
];
179 size
= md
->mask
+ 1 - (old
& md
->mask
);
182 write_output(buf
, size
);
185 buf
= &data
[old
& md
->mask
];
189 write_output(buf
, size
);
192 mmap_write_tail(md
, old
);
195 static volatile int done
= 0;
196 static volatile int signr
= -1;
198 static void sig_handler(int sig
)
204 static void sig_atexit(void)
207 kill(child_pid
, SIGTERM
);
212 signal(signr
, SIG_DFL
);
213 kill(getpid(), signr
);
218 static struct perf_header_attr
*get_header_attr(struct perf_event_attr
*a
, int nr
)
220 struct perf_header_attr
*h_attr
;
222 if (nr
< session
->header
.attrs
) {
223 h_attr
= session
->header
.attr
[nr
];
225 h_attr
= perf_header_attr__new(a
);
227 if (perf_header__add_attr(&session
->header
, h_attr
) < 0) {
228 perf_header_attr__delete(h_attr
);
236 static void create_counter(int counter
, int cpu
)
238 char *filter
= filters
[counter
];
239 struct perf_event_attr
*attr
= attrs
+ counter
;
240 struct perf_header_attr
*h_attr
;
241 int track
= !counter
; /* only the first counter needs these */
251 attr
->read_format
= PERF_FORMAT_TOTAL_TIME_ENABLED
|
252 PERF_FORMAT_TOTAL_TIME_RUNNING
|
255 attr
->sample_type
|= PERF_SAMPLE_IP
| PERF_SAMPLE_TID
;
258 attr
->sample_type
|= PERF_SAMPLE_ID
;
261 attr
->sample_type
|= PERF_SAMPLE_PERIOD
;
263 attr
->sample_freq
= freq
;
267 attr
->sample_freq
= 0;
270 attr
->inherit_stat
= 1;
273 attr
->sample_type
|= PERF_SAMPLE_ADDR
;
276 attr
->sample_type
|= PERF_SAMPLE_CALLCHAIN
;
279 attr
->sample_type
|= PERF_SAMPLE_TIME
;
280 attr
->sample_type
|= PERF_SAMPLE_RAW
;
281 attr
->sample_type
|= PERF_SAMPLE_CPU
;
286 attr
->inherit
= inherit
;
287 if (target_pid
== -1 && !system_wide
) {
289 attr
->enable_on_exec
= 1;
292 for (thread_index
= 0; thread_index
< thread_num
; thread_index
++) {
294 fd
[nr_cpu
][counter
][thread_index
] = sys_perf_event_open(attr
,
295 all_tids
[thread_index
], cpu
, group_fd
, 0);
297 if (fd
[nr_cpu
][counter
][thread_index
] < 0) {
300 if (err
== EPERM
|| err
== EACCES
)
301 die("Permission error - are you root?\n"
302 "\t Consider tweaking"
303 " /proc/sys/kernel/perf_event_paranoid.\n");
304 else if (err
== ENODEV
&& profile_cpu
!= -1) {
305 die("No such device - did you specify"
306 " an out-of-range profile CPU?\n");
310 * If it's cycles then fall back to hrtimer
311 * based cpu-clock-tick sw counter, which
312 * is always available even if no PMU support:
314 if (attr
->type
== PERF_TYPE_HARDWARE
315 && attr
->config
== PERF_COUNT_HW_CPU_CYCLES
) {
318 warning(" ... trying to fall back to cpu-clock-ticks\n");
319 attr
->type
= PERF_TYPE_SOFTWARE
;
320 attr
->config
= PERF_COUNT_SW_CPU_CLOCK
;
324 error("perfcounter syscall returned with %d (%s)\n",
325 fd
[nr_cpu
][counter
][thread_index
], strerror(err
));
327 #if defined(__i386__) || defined(__x86_64__)
328 if (attr
->type
== PERF_TYPE_HARDWARE
&& err
== EOPNOTSUPP
)
329 die("No hardware sampling interrupt available."
330 " No APIC? If so then you can boot the kernel"
331 " with the \"lapic\" boot parameter to"
332 " force-enable it.\n");
335 die("No CONFIG_PERF_EVENTS=y kernel support configured?\n");
339 h_attr
= get_header_attr(attr
, counter
);
344 if (memcmp(&h_attr
->attr
, attr
, sizeof(*attr
))) {
345 fprintf(stderr
, "incompatible append\n");
350 if (read(fd
[nr_cpu
][counter
][thread_index
], &read_data
, sizeof(read_data
)) == -1) {
351 perror("Unable to read perf file descriptor\n");
355 if (perf_header_attr__add_id(h_attr
, read_data
.id
) < 0) {
356 pr_warning("Not enough memory to add id\n");
360 assert(fd
[nr_cpu
][counter
][thread_index
] >= 0);
361 fcntl(fd
[nr_cpu
][counter
][thread_index
], F_SETFL
, O_NONBLOCK
);
364 * First counter acts as the group leader:
366 if (group
&& group_fd
== -1)
367 group_fd
= fd
[nr_cpu
][counter
][thread_index
];
368 if (multiplex
&& multiplex_fd
== -1)
369 multiplex_fd
= fd
[nr_cpu
][counter
][thread_index
];
371 if (multiplex
&& fd
[nr_cpu
][counter
][thread_index
] != multiplex_fd
) {
373 ret
= ioctl(fd
[nr_cpu
][counter
][thread_index
], PERF_EVENT_IOC_SET_OUTPUT
, multiplex_fd
);
376 event_array
[nr_poll
].fd
= fd
[nr_cpu
][counter
][thread_index
];
377 event_array
[nr_poll
].events
= POLLIN
;
380 mmap_array
[nr_cpu
][counter
][thread_index
].counter
= counter
;
381 mmap_array
[nr_cpu
][counter
][thread_index
].prev
= 0;
382 mmap_array
[nr_cpu
][counter
][thread_index
].mask
= mmap_pages
*page_size
- 1;
383 mmap_array
[nr_cpu
][counter
][thread_index
].base
= mmap(NULL
, (mmap_pages
+1)*page_size
,
384 PROT_READ
|PROT_WRITE
, MAP_SHARED
, fd
[nr_cpu
][counter
][thread_index
], 0);
385 if (mmap_array
[nr_cpu
][counter
][thread_index
].base
== MAP_FAILED
) {
386 error("failed to mmap with %d (%s)\n", errno
, strerror(errno
));
391 if (filter
!= NULL
) {
392 ret
= ioctl(fd
[nr_cpu
][counter
][thread_index
],
393 PERF_EVENT_IOC_SET_FILTER
, filter
);
395 error("failed to set filter with %d (%s)\n", errno
,
403 static void open_counters(int cpu
)
408 for (counter
= 0; counter
< nr_counters
; counter
++)
409 create_counter(counter
, cpu
);
414 static int process_buildids(void)
416 u64 size
= lseek(output
, 0, SEEK_CUR
);
421 session
->fd
= output
;
422 return __perf_session__process_events(session
, post_processing_offset
,
423 size
- post_processing_offset
,
424 size
, &build_id__mark_dso_hit_ops
);
427 static void atexit_header(void)
430 session
->header
.data_size
+= bytes_written
;
433 perf_header__write(&session
->header
, output
, true);
437 err
= event__synthesize_build_ids(process_synthesized_event
,
440 pr_err("Couldn't synthesize build ids.\n");
444 static int __cmd_record(int argc
, const char **argv
)
451 unsigned long waking
= 0;
452 int child_ready_pipe
[2], go_pipe
[2];
453 const bool forks
= argc
> 0;
456 page_size
= sysconf(_SC_PAGE_SIZE
);
459 signal(SIGCHLD
, sig_handler
);
460 signal(SIGINT
, sig_handler
);
462 if (forks
&& (pipe(child_ready_pipe
) < 0 || pipe(go_pipe
) < 0)) {
463 perror("failed to create pipes");
467 if (!strcmp(output_name
, "-"))
469 else if (!stat(output_name
, &st
) && st
.st_size
) {
472 pr_err("Error, output file %s exists, use -A "
473 "to append or -f to overwrite.\n",
478 char oldname
[PATH_MAX
];
479 snprintf(oldname
, sizeof(oldname
), "%s.old",
482 rename(output_name
, oldname
);
488 flags
= O_CREAT
|O_RDWR
;
495 output
= STDOUT_FILENO
;
497 output
= open(output_name
, flags
, S_IRUSR
| S_IWUSR
);
499 perror("failed to create output file");
503 session
= perf_session__new(output_name
, O_WRONLY
, force
);
504 if (session
== NULL
) {
505 pr_err("Not enough memory for reading perf file header\n");
510 err
= perf_header__read(session
, output
);
516 perf_header__set_feat(&session
->header
, HEADER_TRACE_INFO
);
518 for (i
= 0; i
< nr_counters
; i
++) {
519 if (attrs
[i
].sample_type
& PERF_SAMPLE_RAW
) {
520 perf_header__set_feat(&session
->header
, HEADER_TRACE_INFO
);
526 atexit(atexit_header
);
531 perror("failed to fork");
538 close(child_ready_pipe
[0]);
540 fcntl(go_pipe
[0], F_SETFD
, FD_CLOEXEC
);
543 * Do a dummy execvp to get the PLT entry resolved,
544 * so we avoid the resolver overhead on the real
547 execvp("", (char **)argv
);
550 * Tell the parent we're ready to go
552 close(child_ready_pipe
[1]);
555 * Wait until the parent tells us to go.
557 if (read(go_pipe
[0], &buf
, 1) == -1)
558 perror("unable to read pipe");
560 execvp(argv
[0], (char **)argv
);
566 if (!system_wide
&& target_tid
== -1 && target_pid
== -1)
567 all_tids
[0] = child_pid
;
569 close(child_ready_pipe
[1]);
572 * wait for child to settle
574 if (read(child_ready_pipe
[0], &buf
, 1) == -1) {
575 perror("unable to read pipe");
578 close(child_ready_pipe
[0]);
581 if ((!system_wide
&& !inherit
) || profile_cpu
!= -1) {
582 open_counters(profile_cpu
);
584 nr_cpus
= read_cpu_map();
585 for (i
= 0; i
< nr_cpus
; i
++)
586 open_counters(cpumap
[i
]);
590 err
= perf_header__write_pipe(output
);
593 } else if (file_new
) {
594 err
= perf_header__write(&session
->header
, output
, false);
599 post_processing_offset
= lseek(output
, 0, SEEK_CUR
);
602 err
= event__synthesize_attrs(&session
->header
,
603 process_synthesized_event
,
606 pr_err("Couldn't synthesize attrs.\n");
610 err
= event__synthesize_event_types(process_synthesized_event
,
613 pr_err("Couldn't synthesize event_types.\n");
617 err
= event__synthesize_tracing_data(output
, attrs
,
619 process_synthesized_event
,
622 pr_err("Couldn't record tracing data.\n");
629 err
= event__synthesize_kernel_mmap(process_synthesized_event
,
632 err
= event__synthesize_kernel_mmap(process_synthesized_event
,
635 pr_err("Couldn't record kernel reference relocation symbol.\n");
639 err
= event__synthesize_modules(process_synthesized_event
, session
);
641 pr_err("Couldn't record kernel reference relocation symbol.\n");
645 if (!system_wide
&& profile_cpu
== -1)
646 event__synthesize_thread(target_tid
, process_synthesized_event
,
649 event__synthesize_threads(process_synthesized_event
, session
);
652 struct sched_param param
;
654 param
.sched_priority
= realtime_prio
;
655 if (sched_setscheduler(0, SCHED_FIFO
, ¶m
)) {
656 pr_err("Could not set realtime priority.\n");
671 for (i
= 0; i
< nr_cpu
; i
++) {
672 for (counter
= 0; counter
< nr_counters
; counter
++) {
674 thread
< thread_num
; thread
++) {
675 if (mmap_array
[i
][counter
][thread
].base
)
676 mmap_read(&mmap_array
[i
][counter
][thread
]);
682 if (hits
== samples
) {
685 err
= poll(event_array
, nr_poll
, -1);
690 for (i
= 0; i
< nr_cpu
; i
++) {
692 counter
< nr_counters
;
697 ioctl(fd
[i
][counter
][thread
],
698 PERF_EVENT_IOC_DISABLE
);
704 fprintf(stderr
, "[ perf record: Woken up %ld times to write data ]\n", waking
);
707 * Approximate RIP event size: 24 bytes.
710 "[ perf record: Captured and wrote %.3f MB %s (~%lld samples) ]\n",
711 (double)bytes_written
/ 1024.0 / 1024.0,
718 static const char * const record_usage
[] = {
719 "perf record [<options>] [<command>]",
720 "perf record [<options>] -- <command> [<options>]",
724 static const struct option options
[] = {
725 OPT_CALLBACK('e', "event", NULL
, "event",
726 "event selector. use 'perf list' to list available events",
728 OPT_CALLBACK(0, "filter", NULL
, "filter",
729 "event filter", parse_filter
),
730 OPT_INTEGER('p', "pid", &target_pid
,
731 "record events on existing process id"),
732 OPT_INTEGER('t', "tid", &target_tid
,
733 "record events on existing thread id"),
734 OPT_INTEGER('r', "realtime", &realtime_prio
,
735 "collect data with this RT SCHED_FIFO priority"),
736 OPT_BOOLEAN('R', "raw-samples", &raw_samples
,
737 "collect raw sample records from all opened counters"),
738 OPT_BOOLEAN('a', "all-cpus", &system_wide
,
739 "system-wide collection from all CPUs"),
740 OPT_BOOLEAN('A', "append", &append_file
,
741 "append to the output file to do incremental profiling"),
742 OPT_INTEGER('C', "profile_cpu", &profile_cpu
,
743 "CPU to profile on"),
744 OPT_BOOLEAN('f', "force", &force
,
745 "overwrite existing data file"),
746 OPT_LONG('c', "count", &default_interval
,
747 "event period to sample"),
748 OPT_STRING('o', "output", &output_name
, "file",
750 OPT_BOOLEAN('i', "inherit", &inherit
,
751 "child tasks inherit counters"),
752 OPT_INTEGER('F', "freq", &freq
,
753 "profile at this frequency"),
754 OPT_INTEGER('m', "mmap-pages", &mmap_pages
,
755 "number of mmap data pages"),
756 OPT_BOOLEAN('g', "call-graph", &call_graph
,
757 "do call-graph (stack chain/backtrace) recording"),
758 OPT_INCR('v', "verbose", &verbose
,
759 "be more verbose (show counter open errors, etc)"),
760 OPT_BOOLEAN('s', "stat", &inherit_stat
,
761 "per thread counts"),
762 OPT_BOOLEAN('d', "data", &sample_address
,
764 OPT_BOOLEAN('n', "no-samples", &no_samples
,
766 OPT_BOOLEAN('M', "multiplex", &multiplex
,
767 "multiplex counter output in a single channel"),
771 int cmd_record(int argc
, const char **argv
, const char *prefix __used
)
776 argc
= parse_options(argc
, argv
, options
, record_usage
,
777 PARSE_OPT_STOP_AT_NON_OPTION
);
778 if (!argc
&& target_pid
== -1 && target_tid
== -1 &&
779 !system_wide
&& profile_cpu
== -1)
780 usage_with_options(record_usage
, options
);
786 attrs
[0].type
= PERF_TYPE_HARDWARE
;
787 attrs
[0].config
= PERF_COUNT_HW_CPU_CYCLES
;
790 if (target_pid
!= -1) {
791 target_tid
= target_pid
;
792 thread_num
= find_all_tid(target_pid
, &all_tids
);
793 if (thread_num
<= 0) {
794 fprintf(stderr
, "Can't find all threads of pid %d\n",
796 usage_with_options(record_usage
, options
);
799 all_tids
=malloc(sizeof(pid_t
));
803 all_tids
[0] = target_tid
;
807 for (i
= 0; i
< MAX_NR_CPUS
; i
++) {
808 for (j
= 0; j
< MAX_COUNTERS
; j
++) {
809 fd
[i
][j
] = malloc(sizeof(int)*thread_num
);
810 mmap_array
[i
][j
] = zalloc(
811 sizeof(struct mmap_data
)*thread_num
);
812 if (!fd
[i
][j
] || !mmap_array
[i
][j
])
816 event_array
= malloc(
817 sizeof(struct pollfd
)*MAX_NR_CPUS
*MAX_COUNTERS
*thread_num
);
822 * User specified count overrides default frequency.
824 if (default_interval
)
827 default_interval
= freq
;
829 fprintf(stderr
, "frequency and count are zero, aborting\n");
833 for (counter
= 0; counter
< nr_counters
; counter
++) {
834 if (attrs
[counter
].sample_period
)
837 attrs
[counter
].sample_period
= default_interval
;
840 return __cmd_record(argc
, argv
);