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/session.h"
21 #include "util/symbol.h"
26 static int fd[MAX_NR_CPUS][MAX_COUNTERS];
28 static long default_interval = 0;
30 static int nr_cpus = 0;
31 static unsigned int page_size;
32 static unsigned int mmap_pages = 128;
33 static int freq = 1000;
35 static const char *output_name = "perf.data";
37 static unsigned int realtime_prio = 0;
38 static int raw_samples = 0;
39 static int system_wide = 0;
40 static int profile_cpu = -1;
41 static pid_t target_pid = -1;
42 static pid_t child_pid = -1;
43 static int inherit = 1;
45 static int append_file = 0;
46 static int call_graph = 0;
47 static int inherit_stat = 0;
48 static int no_samples = 0;
49 static int sample_address = 0;
50 static int multiplex = 0;
51 static int multiplex_fd = -1;
53 static long samples = 0;
54 static struct timeval last_read;
55 static struct timeval this_read;
57 static u64 bytes_written = 0;
59 static struct pollfd event_array[MAX_NR_CPUS * MAX_COUNTERS];
61 static int nr_poll = 0;
62 static int nr_cpu = 0;
64 static int file_new = 1;
66 static struct perf_session *session;
75 static struct mmap_data mmap_array[MAX_NR_CPUS][MAX_COUNTERS];
77 static unsigned long mmap_read_head(struct mmap_data *md)
79 struct perf_event_mmap_page *pc = md->base;
88 static void mmap_write_tail(struct mmap_data *md, unsigned long tail)
90 struct perf_event_mmap_page *pc = md->base;
93 * ensure all reads are done before we write the tail out.
99 static void write_output(void *buf, size_t size)
102 int ret = write(output, buf, size);
105 die("failed to write");
110 bytes_written += ret;
114 static void write_event(event_t *buf, size_t size)
116 size_t processed_size = buf->header.size;
121 * Add it to the list of DSOs, so that when we finish this
122 * record session we can pick the available build-ids.
124 if (ev->header.type == PERF_RECORD_MMAP) {
125 struct list_head *head = &dsos__user;
126 if (ev->header.misc == 1)
127 head = &dsos__kernel;
128 __dsos__findnew(head, ev->mmap.filename);
131 ev = ((void *)ev) + ev->header.size;
132 processed_size += ev->header.size;
133 } while (processed_size < size);
135 write_output(buf, size);
138 static int process_synthesized_event(event_t *event,
139 struct perf_session *self __used)
141 write_event(event, event->header.size);
145 static void mmap_read(struct mmap_data *md)
147 unsigned int head = mmap_read_head(md);
148 unsigned int old = md->prev;
149 unsigned char *data = md->base + page_size;
154 gettimeofday(&this_read, NULL);
157 * If we're further behind than half the buffer, there's a chance
158 * the writer will bite our tail and mess up the samples under us.
160 * If we somehow ended up ahead of the head, we got messed up.
162 * In either case, truncate and restart at head.
169 timersub(&this_read, &last_read, &iv);
170 msecs = iv.tv_sec*1000 + iv.tv_usec/1000;
172 fprintf(stderr, "WARNING: failed to keep up with mmap data."
173 " Last read %lu msecs ago.\n", msecs);
176 * head points to a known good entry, start there.
181 last_read = this_read;
188 if ((old & md->mask) + size != (head & md->mask)) {
189 buf = &data[old & md->mask];
190 size = md->mask + 1 - (old & md->mask);
193 write_event(buf, size);
196 buf = &data[old & md->mask];
200 write_event(buf, size);
203 mmap_write_tail(md, old);
206 static volatile int done = 0;
207 static volatile int signr = -1;
209 static void sig_handler(int sig)
215 static void sig_atexit(void)
218 kill(child_pid, SIGTERM);
223 signal(signr, SIG_DFL);
224 kill(getpid(), signr);
229 static struct perf_header_attr *get_header_attr(struct perf_event_attr *a, int nr)
231 struct perf_header_attr *h_attr;
233 if (nr < session->header.attrs) {
234 h_attr = session->header.attr[nr];
236 h_attr = perf_header_attr__new(a);
238 if (perf_header__add_attr(&session->header, h_attr) < 0) {
239 perf_header_attr__delete(h_attr);
247 static void create_counter(int counter, int cpu, pid_t pid)
249 char *filter = filters[counter];
250 struct perf_event_attr *attr = attrs + counter;
251 struct perf_header_attr *h_attr;
252 int track = !counter; /* only the first counter needs these */
261 attr->read_format = PERF_FORMAT_TOTAL_TIME_ENABLED |
262 PERF_FORMAT_TOTAL_TIME_RUNNING |
265 attr->sample_type |= PERF_SAMPLE_IP | PERF_SAMPLE_TID;
268 attr->sample_type |= PERF_SAMPLE_PERIOD;
270 attr->sample_freq = freq;
274 attr->sample_freq = 0;
277 attr->inherit_stat = 1;
280 attr->sample_type |= PERF_SAMPLE_ADDR;
283 attr->sample_type |= PERF_SAMPLE_CALLCHAIN;
286 attr->sample_type |= PERF_SAMPLE_TIME;
287 attr->sample_type |= PERF_SAMPLE_RAW;
288 attr->sample_type |= PERF_SAMPLE_CPU;
293 attr->inherit = inherit;
297 fd[nr_cpu][counter] = sys_perf_event_open(attr, pid, cpu, group_fd, 0);
299 if (fd[nr_cpu][counter] < 0) {
302 if (err == EPERM || err == EACCES)
303 die("Permission error - are you root?\n");
304 else if (err == ENODEV && profile_cpu != -1)
305 die("No such device - did you specify an out-of-range profile CPU?\n");
308 * If it's cycles then fall back to hrtimer
309 * based cpu-clock-tick sw counter, which
310 * is always available even if no PMU support:
312 if (attr->type == PERF_TYPE_HARDWARE
313 && attr->config == PERF_COUNT_HW_CPU_CYCLES) {
316 warning(" ... trying to fall back to cpu-clock-ticks\n");
317 attr->type = PERF_TYPE_SOFTWARE;
318 attr->config = PERF_COUNT_SW_CPU_CLOCK;
322 error("perfcounter syscall returned with %d (%s)\n",
323 fd[nr_cpu][counter], strerror(err));
325 #if defined(__i386__) || defined(__x86_64__)
326 if (attr->type == PERF_TYPE_HARDWARE && err == EOPNOTSUPP)
327 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");
330 die("No CONFIG_PERF_EVENTS=y kernel support configured?\n");
334 h_attr = get_header_attr(attr, counter);
339 if (memcmp(&h_attr->attr, attr, sizeof(*attr))) {
340 fprintf(stderr, "incompatible append\n");
345 if (read(fd[nr_cpu][counter], &read_data, sizeof(read_data)) == -1) {
346 perror("Unable to read perf file descriptor\n");
350 if (perf_header_attr__add_id(h_attr, read_data.id) < 0) {
351 pr_warning("Not enough memory to add id\n");
355 assert(fd[nr_cpu][counter] >= 0);
356 fcntl(fd[nr_cpu][counter], F_SETFL, O_NONBLOCK);
359 * First counter acts as the group leader:
361 if (group && group_fd == -1)
362 group_fd = fd[nr_cpu][counter];
363 if (multiplex && multiplex_fd == -1)
364 multiplex_fd = fd[nr_cpu][counter];
366 if (multiplex && fd[nr_cpu][counter] != multiplex_fd) {
368 ret = ioctl(fd[nr_cpu][counter], PERF_EVENT_IOC_SET_OUTPUT, multiplex_fd);
371 event_array[nr_poll].fd = fd[nr_cpu][counter];
372 event_array[nr_poll].events = POLLIN;
375 mmap_array[nr_cpu][counter].counter = counter;
376 mmap_array[nr_cpu][counter].prev = 0;
377 mmap_array[nr_cpu][counter].mask = mmap_pages*page_size - 1;
378 mmap_array[nr_cpu][counter].base = mmap(NULL, (mmap_pages+1)*page_size,
379 PROT_READ|PROT_WRITE, MAP_SHARED, fd[nr_cpu][counter], 0);
380 if (mmap_array[nr_cpu][counter].base == MAP_FAILED) {
381 error("failed to mmap with %d (%s)\n", errno, strerror(errno));
386 if (filter != NULL) {
387 ret = ioctl(fd[nr_cpu][counter],
388 PERF_EVENT_IOC_SET_FILTER, filter);
390 error("failed to set filter with %d (%s)\n", errno,
396 ioctl(fd[nr_cpu][counter], PERF_EVENT_IOC_ENABLE);
399 static void open_counters(int cpu, pid_t pid)
404 for (counter = 0; counter < nr_counters; counter++)
405 create_counter(counter, cpu, pid);
410 static void atexit_header(void)
412 session->header.data_size += bytes_written;
414 perf_header__write(&session->header, output, true);
417 static int __cmd_record(int argc, const char **argv)
424 unsigned long waking = 0;
425 int child_ready_pipe[2], go_pipe[2];
426 const bool forks = target_pid == -1 && argc > 0;
429 page_size = sysconf(_SC_PAGE_SIZE);
430 nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
431 assert(nr_cpus <= MAX_NR_CPUS);
432 assert(nr_cpus >= 0);
435 signal(SIGCHLD, sig_handler);
436 signal(SIGINT, sig_handler);
438 if (forks && (pipe(child_ready_pipe) < 0 || pipe(go_pipe) < 0)) {
439 perror("failed to create pipes");
443 if (!stat(output_name, &st) && st.st_size) {
446 pr_err("Error, output file %s exists, use -A "
447 "to append or -f to overwrite.\n",
452 char oldname[PATH_MAX];
453 snprintf(oldname, sizeof(oldname), "%s.old",
456 rename(output_name, oldname);
462 flags = O_CREAT|O_RDWR;
468 output = open(output_name, flags, S_IRUSR|S_IWUSR);
470 perror("failed to create output file");
474 session = perf_session__new(output_name, O_WRONLY, force);
475 if (session == NULL) {
476 pr_err("Not enough memory for reading perf file header\n");
480 if (perf_session__create_kernel_maps(session) < 0) {
481 pr_err("Problems creating kernel maps\n");
486 err = perf_header__read(&session->header, output);
492 perf_header__set_feat(&session->header, HEADER_TRACE_INFO);
494 for (i = 0; i < nr_counters; i++) {
495 if (attrs[i].sample_type & PERF_SAMPLE_RAW) {
496 perf_header__set_feat(&session->header, HEADER_TRACE_INFO);
502 atexit(atexit_header);
507 perror("failed to fork");
512 close(child_ready_pipe[0]);
514 fcntl(go_pipe[0], F_SETFD, FD_CLOEXEC);
517 * Do a dummy execvp to get the PLT entry resolved,
518 * so we avoid the resolver overhead on the real
521 execvp("", (char **)argv);
524 * Tell the parent we're ready to go
526 close(child_ready_pipe[1]);
529 * Wait until the parent tells us to go.
531 if (read(go_pipe[0], &buf, 1) == -1)
532 perror("unable to read pipe");
534 execvp(argv[0], (char **)argv);
545 close(child_ready_pipe[1]);
548 * wait for child to settle
550 if (read(child_ready_pipe[0], &buf, 1) == -1) {
551 perror("unable to read pipe");
554 close(child_ready_pipe[0]);
558 if ((!system_wide && !inherit) || profile_cpu != -1) {
559 open_counters(profile_cpu, target_pid);
561 for (i = 0; i < nr_cpus; i++)
562 open_counters(i, target_pid);
566 err = perf_header__write(&session->header, output, false);
571 err = event__synthesize_kernel_mmap(process_synthesized_event,
574 pr_err("Couldn't record kernel reference relocation symbol.\n");
578 err = event__synthesize_modules(process_synthesized_event, session);
580 pr_err("Couldn't record kernel reference relocation symbol.\n");
584 if (!system_wide && profile_cpu == -1)
585 event__synthesize_thread(pid, process_synthesized_event,
588 event__synthesize_threads(process_synthesized_event, session);
591 struct sched_param param;
593 param.sched_priority = realtime_prio;
594 if (sched_setscheduler(0, SCHED_FIFO, ¶m)) {
595 pr_err("Could not set realtime priority.\n");
609 for (i = 0; i < nr_cpu; i++) {
610 for (counter = 0; counter < nr_counters; counter++) {
611 if (mmap_array[i][counter].base)
612 mmap_read(&mmap_array[i][counter]);
616 if (hits == samples) {
619 err = poll(event_array, nr_poll, -1);
624 for (i = 0; i < nr_cpu; i++) {
625 for (counter = 0; counter < nr_counters; counter++)
626 ioctl(fd[i][counter], PERF_EVENT_IOC_DISABLE);
631 fprintf(stderr, "[ perf record: Woken up %ld times to write data ]\n", waking);
634 * Approximate RIP event size: 24 bytes.
637 "[ perf record: Captured and wrote %.3f MB %s (~%lld samples) ]\n",
638 (double)bytes_written / 1024.0 / 1024.0,
645 static const char * const record_usage[] = {
646 "perf record [<options>] [<command>]",
647 "perf record [<options>] -- <command> [<options>]",
651 static const struct option options[] = {
652 OPT_CALLBACK('e', "event", NULL, "event",
653 "event selector. use 'perf list' to list available events",
655 OPT_CALLBACK(0, "filter", NULL, "filter",
656 "event filter", parse_filter),
657 OPT_INTEGER('p', "pid", &target_pid,
658 "record events on existing pid"),
659 OPT_INTEGER('r', "realtime", &realtime_prio,
660 "collect data with this RT SCHED_FIFO priority"),
661 OPT_BOOLEAN('R', "raw-samples", &raw_samples,
662 "collect raw sample records from all opened counters"),
663 OPT_BOOLEAN('a', "all-cpus", &system_wide,
664 "system-wide collection from all CPUs"),
665 OPT_BOOLEAN('A', "append", &append_file,
666 "append to the output file to do incremental profiling"),
667 OPT_INTEGER('C', "profile_cpu", &profile_cpu,
668 "CPU to profile on"),
669 OPT_BOOLEAN('f', "force", &force,
670 "overwrite existing data file"),
671 OPT_LONG('c', "count", &default_interval,
672 "event period to sample"),
673 OPT_STRING('o', "output", &output_name, "file",
675 OPT_BOOLEAN('i', "inherit", &inherit,
676 "child tasks inherit counters"),
677 OPT_INTEGER('F', "freq", &freq,
678 "profile at this frequency"),
679 OPT_INTEGER('m', "mmap-pages", &mmap_pages,
680 "number of mmap data pages"),
681 OPT_BOOLEAN('g', "call-graph", &call_graph,
682 "do call-graph (stack chain/backtrace) recording"),
683 OPT_BOOLEAN('v', "verbose", &verbose,
684 "be more verbose (show counter open errors, etc)"),
685 OPT_BOOLEAN('s', "stat", &inherit_stat,
686 "per thread counts"),
687 OPT_BOOLEAN('d', "data", &sample_address,
689 OPT_BOOLEAN('n', "no-samples", &no_samples,
691 OPT_BOOLEAN('M', "multiplex", &multiplex,
692 "multiplex counter output in a single channel"),
696 int cmd_record(int argc, const char **argv, const char *prefix __used)
700 argc = parse_options(argc, argv, options, record_usage,
701 PARSE_OPT_STOP_AT_NON_OPTION);
702 if (!argc && target_pid == -1 && !system_wide && profile_cpu == -1)
703 usage_with_options(record_usage, options);
709 attrs[0].type = PERF_TYPE_HARDWARE;
710 attrs[0].config = PERF_COUNT_HW_CPU_CYCLES;
714 * User specified count overrides default frequency.
716 if (default_interval)
719 default_interval = freq;
721 fprintf(stderr, "frequency and count are zero, aborting\n");
725 for (counter = 0; counter < nr_counters; counter++) {
726 if (attrs[counter].sample_period)
729 attrs[counter].sample_period = default_interval;
732 return __cmd_record(argc, argv);