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"
25 #include "util/cpumap.h"
30 static int fd[MAX_NR_CPUS][MAX_COUNTERS];
32 static long default_interval = 0;
34 static int nr_cpus = 0;
35 static unsigned int page_size;
36 static unsigned int mmap_pages = 128;
37 static int freq = 1000;
39 static const char *output_name = "perf.data";
41 static unsigned int realtime_prio = 0;
42 static int raw_samples = 0;
43 static int system_wide = 0;
44 static int profile_cpu = -1;
45 static pid_t target_pid = -1;
46 static pid_t child_pid = -1;
47 static int inherit = 1;
49 static int append_file = 0;
50 static int call_graph = 0;
51 static int inherit_stat = 0;
52 static int no_samples = 0;
53 static int sample_address = 0;
54 static int multiplex = 0;
55 static int multiplex_fd = -1;
57 static long samples = 0;
58 static struct timeval last_read;
59 static struct timeval this_read;
61 static u64 bytes_written = 0;
63 static struct pollfd event_array[MAX_NR_CPUS * MAX_COUNTERS];
65 static int nr_poll = 0;
66 static int nr_cpu = 0;
68 static int file_new = 1;
69 static off_t post_processing_offset;
71 static struct perf_session *session;
80 static struct mmap_data mmap_array[MAX_NR_CPUS][MAX_COUNTERS];
82 static unsigned long mmap_read_head(struct mmap_data *md)
84 struct perf_event_mmap_page *pc = md->base;
93 static void mmap_write_tail(struct mmap_data *md, unsigned long tail)
95 struct perf_event_mmap_page *pc = md->base;
98 * ensure all reads are done before we write the tail out.
101 pc->data_tail = tail;
104 static void write_output(void *buf, size_t size)
107 int ret = write(output, buf, size);
110 die("failed to write");
115 bytes_written += ret;
119 static int process_synthesized_event(event_t *event,
120 struct perf_session *self __used)
122 write_output(event, event->header.size);
126 static void mmap_read(struct mmap_data *md)
128 unsigned int head = mmap_read_head(md);
129 unsigned int old = md->prev;
130 unsigned char *data = md->base + page_size;
135 gettimeofday(&this_read, NULL);
138 * If we're further behind than half the buffer, there's a chance
139 * the writer will bite our tail and mess up the samples under us.
141 * If we somehow ended up ahead of the head, we got messed up.
143 * In either case, truncate and restart at head.
150 timersub(&this_read, &last_read, &iv);
151 msecs = iv.tv_sec*1000 + iv.tv_usec/1000;
153 fprintf(stderr, "WARNING: failed to keep up with mmap data."
154 " Last read %lu msecs ago.\n", msecs);
157 * head points to a known good entry, start there.
162 last_read = this_read;
169 if ((old & md->mask) + size != (head & md->mask)) {
170 buf = &data[old & md->mask];
171 size = md->mask + 1 - (old & md->mask);
174 write_output(buf, size);
177 buf = &data[old & md->mask];
181 write_output(buf, size);
184 mmap_write_tail(md, old);
187 static volatile int done = 0;
188 static volatile int signr = -1;
190 static void sig_handler(int sig)
196 static void sig_atexit(void)
199 kill(child_pid, SIGTERM);
204 signal(signr, SIG_DFL);
205 kill(getpid(), signr);
210 static struct perf_header_attr *get_header_attr(struct perf_event_attr *a, int nr)
212 struct perf_header_attr *h_attr;
214 if (nr < session->header.attrs) {
215 h_attr = session->header.attr[nr];
217 h_attr = perf_header_attr__new(a);
219 if (perf_header__add_attr(&session->header, h_attr) < 0) {
220 perf_header_attr__delete(h_attr);
228 static void create_counter(int counter, int cpu, pid_t pid)
230 char *filter = filters[counter];
231 struct perf_event_attr *attr = attrs + counter;
232 struct perf_header_attr *h_attr;
233 int track = !counter; /* only the first counter needs these */
242 attr->read_format = PERF_FORMAT_TOTAL_TIME_ENABLED |
243 PERF_FORMAT_TOTAL_TIME_RUNNING |
246 attr->sample_type |= PERF_SAMPLE_IP | PERF_SAMPLE_TID;
249 attr->sample_type |= PERF_SAMPLE_ID;
252 attr->sample_type |= PERF_SAMPLE_PERIOD;
254 attr->sample_freq = freq;
258 attr->sample_freq = 0;
261 attr->inherit_stat = 1;
264 attr->sample_type |= PERF_SAMPLE_ADDR;
267 attr->sample_type |= PERF_SAMPLE_CALLCHAIN;
270 attr->sample_type |= PERF_SAMPLE_TIME;
271 attr->sample_type |= PERF_SAMPLE_RAW;
272 attr->sample_type |= PERF_SAMPLE_CPU;
277 attr->inherit = inherit;
281 fd[nr_cpu][counter] = sys_perf_event_open(attr, pid, cpu, group_fd, 0);
283 if (fd[nr_cpu][counter] < 0) {
286 if (err == EPERM || err == EACCES)
287 die("Permission error - are you root?\n"
288 "\t Consider tweaking /proc/sys/kernel/perf_event_paranoid.\n");
289 else if (err == ENODEV && profile_cpu != -1)
290 die("No such device - did you specify an out-of-range profile CPU?\n");
293 * If it's cycles then fall back to hrtimer
294 * based cpu-clock-tick sw counter, which
295 * is always available even if no PMU support:
297 if (attr->type == PERF_TYPE_HARDWARE
298 && attr->config == PERF_COUNT_HW_CPU_CYCLES) {
301 warning(" ... trying to fall back to cpu-clock-ticks\n");
302 attr->type = PERF_TYPE_SOFTWARE;
303 attr->config = PERF_COUNT_SW_CPU_CLOCK;
307 error("perfcounter syscall returned with %d (%s)\n",
308 fd[nr_cpu][counter], strerror(err));
310 #if defined(__i386__) || defined(__x86_64__)
311 if (attr->type == PERF_TYPE_HARDWARE && err == EOPNOTSUPP)
312 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");
315 die("No CONFIG_PERF_EVENTS=y kernel support configured?\n");
319 h_attr = get_header_attr(attr, counter);
324 if (memcmp(&h_attr->attr, attr, sizeof(*attr))) {
325 fprintf(stderr, "incompatible append\n");
330 if (read(fd[nr_cpu][counter], &read_data, sizeof(read_data)) == -1) {
331 perror("Unable to read perf file descriptor\n");
335 if (perf_header_attr__add_id(h_attr, read_data.id) < 0) {
336 pr_warning("Not enough memory to add id\n");
340 assert(fd[nr_cpu][counter] >= 0);
341 fcntl(fd[nr_cpu][counter], F_SETFL, O_NONBLOCK);
344 * First counter acts as the group leader:
346 if (group && group_fd == -1)
347 group_fd = fd[nr_cpu][counter];
348 if (multiplex && multiplex_fd == -1)
349 multiplex_fd = fd[nr_cpu][counter];
351 if (multiplex && fd[nr_cpu][counter] != multiplex_fd) {
353 ret = ioctl(fd[nr_cpu][counter], PERF_EVENT_IOC_SET_OUTPUT, multiplex_fd);
356 event_array[nr_poll].fd = fd[nr_cpu][counter];
357 event_array[nr_poll].events = POLLIN;
360 mmap_array[nr_cpu][counter].counter = counter;
361 mmap_array[nr_cpu][counter].prev = 0;
362 mmap_array[nr_cpu][counter].mask = mmap_pages*page_size - 1;
363 mmap_array[nr_cpu][counter].base = mmap(NULL, (mmap_pages+1)*page_size,
364 PROT_READ|PROT_WRITE, MAP_SHARED, fd[nr_cpu][counter], 0);
365 if (mmap_array[nr_cpu][counter].base == MAP_FAILED) {
366 error("failed to mmap with %d (%s)\n", errno, strerror(errno));
371 if (filter != NULL) {
372 ret = ioctl(fd[nr_cpu][counter],
373 PERF_EVENT_IOC_SET_FILTER, filter);
375 error("failed to set filter with %d (%s)\n", errno,
381 ioctl(fd[nr_cpu][counter], PERF_EVENT_IOC_ENABLE);
384 static void open_counters(int cpu, pid_t pid)
389 for (counter = 0; counter < nr_counters; counter++)
390 create_counter(counter, cpu, pid);
395 static int process_buildids(void)
397 u64 size = lseek(output, 0, SEEK_CUR);
402 session->fd = output;
403 return __perf_session__process_events(session, post_processing_offset,
404 size - post_processing_offset,
405 size, &build_id__mark_dso_hit_ops);
408 static void atexit_header(void)
410 session->header.data_size += bytes_written;
413 perf_header__write(&session->header, output, true);
416 static int __cmd_record(int argc, const char **argv)
423 unsigned long waking = 0;
424 int child_ready_pipe[2], go_pipe[2];
425 const bool forks = target_pid == -1 && argc > 0;
428 page_size = sysconf(_SC_PAGE_SIZE);
431 signal(SIGCHLD, sig_handler);
432 signal(SIGINT, sig_handler);
434 if (forks && (pipe(child_ready_pipe) < 0 || pipe(go_pipe) < 0)) {
435 perror("failed to create pipes");
439 if (!stat(output_name, &st) && st.st_size) {
442 pr_err("Error, output file %s exists, use -A "
443 "to append or -f to overwrite.\n",
448 char oldname[PATH_MAX];
449 snprintf(oldname, sizeof(oldname), "%s.old",
452 rename(output_name, oldname);
458 flags = O_CREAT|O_RDWR;
464 output = open(output_name, flags, S_IRUSR|S_IWUSR);
466 perror("failed to create output file");
470 session = perf_session__new(output_name, O_WRONLY, force);
471 if (session == NULL) {
472 pr_err("Not enough memory for reading perf file header\n");
477 err = perf_header__read(&session->header, output);
483 perf_header__set_feat(&session->header, HEADER_TRACE_INFO);
485 for (i = 0; i < nr_counters; i++) {
486 if (attrs[i].sample_type & PERF_SAMPLE_RAW) {
487 perf_header__set_feat(&session->header, HEADER_TRACE_INFO);
493 atexit(atexit_header);
498 perror("failed to fork");
503 close(child_ready_pipe[0]);
505 fcntl(go_pipe[0], F_SETFD, FD_CLOEXEC);
508 * Do a dummy execvp to get the PLT entry resolved,
509 * so we avoid the resolver overhead on the real
512 execvp("", (char **)argv);
515 * Tell the parent we're ready to go
517 close(child_ready_pipe[1]);
520 * Wait until the parent tells us to go.
522 if (read(go_pipe[0], &buf, 1) == -1)
523 perror("unable to read pipe");
525 execvp(argv[0], (char **)argv);
536 close(child_ready_pipe[1]);
539 * wait for child to settle
541 if (read(child_ready_pipe[0], &buf, 1) == -1) {
542 perror("unable to read pipe");
545 close(child_ready_pipe[0]);
549 if ((!system_wide && !inherit) || profile_cpu != -1) {
550 open_counters(profile_cpu, target_pid);
552 nr_cpus = read_cpu_map();
553 for (i = 0; i < nr_cpus; i++)
554 open_counters(cpumap[i], target_pid);
558 err = perf_header__write(&session->header, output, false);
563 post_processing_offset = lseek(output, 0, SEEK_CUR);
565 err = event__synthesize_kernel_mmap(process_synthesized_event,
568 pr_err("Couldn't record kernel reference relocation symbol.\n");
572 err = event__synthesize_modules(process_synthesized_event, session);
574 pr_err("Couldn't record kernel reference relocation symbol.\n");
578 if (!system_wide && profile_cpu == -1)
579 event__synthesize_thread(target_pid, process_synthesized_event,
582 event__synthesize_threads(process_synthesized_event, session);
585 struct sched_param param;
587 param.sched_priority = realtime_prio;
588 if (sched_setscheduler(0, SCHED_FIFO, ¶m)) {
589 pr_err("Could not set realtime priority.\n");
603 for (i = 0; i < nr_cpu; i++) {
604 for (counter = 0; counter < nr_counters; counter++) {
605 if (mmap_array[i][counter].base)
606 mmap_read(&mmap_array[i][counter]);
610 if (hits == samples) {
613 err = poll(event_array, nr_poll, -1);
618 for (i = 0; i < nr_cpu; i++) {
619 for (counter = 0; counter < nr_counters; counter++)
620 ioctl(fd[i][counter], PERF_EVENT_IOC_DISABLE);
625 fprintf(stderr, "[ perf record: Woken up %ld times to write data ]\n", waking);
628 * Approximate RIP event size: 24 bytes.
631 "[ perf record: Captured and wrote %.3f MB %s (~%lld samples) ]\n",
632 (double)bytes_written / 1024.0 / 1024.0,
639 static const char * const record_usage[] = {
640 "perf record [<options>] [<command>]",
641 "perf record [<options>] -- <command> [<options>]",
645 static const struct option options[] = {
646 OPT_CALLBACK('e', "event", NULL, "event",
647 "event selector. use 'perf list' to list available events",
649 OPT_CALLBACK(0, "filter", NULL, "filter",
650 "event filter", parse_filter),
651 OPT_INTEGER('p', "pid", &target_pid,
652 "record events on existing pid"),
653 OPT_INTEGER('r', "realtime", &realtime_prio,
654 "collect data with this RT SCHED_FIFO priority"),
655 OPT_BOOLEAN('R', "raw-samples", &raw_samples,
656 "collect raw sample records from all opened counters"),
657 OPT_BOOLEAN('a', "all-cpus", &system_wide,
658 "system-wide collection from all CPUs"),
659 OPT_BOOLEAN('A', "append", &append_file,
660 "append to the output file to do incremental profiling"),
661 OPT_INTEGER('C', "profile_cpu", &profile_cpu,
662 "CPU to profile on"),
663 OPT_BOOLEAN('f', "force", &force,
664 "overwrite existing data file"),
665 OPT_LONG('c', "count", &default_interval,
666 "event period to sample"),
667 OPT_STRING('o', "output", &output_name, "file",
669 OPT_BOOLEAN('i', "inherit", &inherit,
670 "child tasks inherit counters"),
671 OPT_INTEGER('F', "freq", &freq,
672 "profile at this frequency"),
673 OPT_INTEGER('m', "mmap-pages", &mmap_pages,
674 "number of mmap data pages"),
675 OPT_BOOLEAN('g', "call-graph", &call_graph,
676 "do call-graph (stack chain/backtrace) recording"),
677 OPT_BOOLEAN('v', "verbose", &verbose,
678 "be more verbose (show counter open errors, etc)"),
679 OPT_BOOLEAN('s', "stat", &inherit_stat,
680 "per thread counts"),
681 OPT_BOOLEAN('d', "data", &sample_address,
683 OPT_BOOLEAN('n', "no-samples", &no_samples,
685 OPT_BOOLEAN('M', "multiplex", &multiplex,
686 "multiplex counter output in a single channel"),
690 int cmd_record(int argc, const char **argv, const char *prefix __used)
694 argc = parse_options(argc, argv, options, record_usage,
695 PARSE_OPT_STOP_AT_NON_OPTION);
696 if (!argc && target_pid == -1 && !system_wide && profile_cpu == -1)
697 usage_with_options(record_usage, options);
703 attrs[0].type = PERF_TYPE_HARDWARE;
704 attrs[0].config = PERF_COUNT_HW_CPU_CYCLES;
708 * User specified count overrides default frequency.
710 if (default_interval)
713 default_interval = freq;
715 fprintf(stderr, "frequency and count are zero, aborting\n");
719 for (counter = 0; counter < nr_counters; counter++) {
720 if (attrs[counter].sample_period)
723 attrs[counter].sample_period = default_interval;
726 return __cmd_record(argc, argv);