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)
117 * Add it to the list of DSOs, so that when we finish this
118 * record session we can pick the available build-ids.
120 if (buf->header.type == PERF_RECORD_MMAP)
121 dsos__findnew(buf->mmap.filename);
123 write_output(buf, size);
126 static int process_synthesized_event(event_t *event,
127 struct perf_session *self __used)
129 write_event(event, event->header.size);
133 static void mmap_read(struct mmap_data *md)
135 unsigned int head = mmap_read_head(md);
136 unsigned int old = md->prev;
137 unsigned char *data = md->base + page_size;
142 gettimeofday(&this_read, NULL);
145 * If we're further behind than half the buffer, there's a chance
146 * the writer will bite our tail and mess up the samples under us.
148 * If we somehow ended up ahead of the head, we got messed up.
150 * In either case, truncate and restart at head.
157 timersub(&this_read, &last_read, &iv);
158 msecs = iv.tv_sec*1000 + iv.tv_usec/1000;
160 fprintf(stderr, "WARNING: failed to keep up with mmap data."
161 " Last read %lu msecs ago.\n", msecs);
164 * head points to a known good entry, start there.
169 last_read = this_read;
176 if ((old & md->mask) + size != (head & md->mask)) {
177 buf = &data[old & md->mask];
178 size = md->mask + 1 - (old & md->mask);
181 write_event(buf, size);
184 buf = &data[old & md->mask];
188 write_event(buf, size);
191 mmap_write_tail(md, old);
194 static volatile int done = 0;
195 static volatile int signr = -1;
197 static void sig_handler(int sig)
203 static void sig_atexit(void)
206 kill(child_pid, SIGTERM);
211 signal(signr, SIG_DFL);
212 kill(getpid(), signr);
217 static struct perf_header_attr *get_header_attr(struct perf_event_attr *a, int nr)
219 struct perf_header_attr *h_attr;
221 if (nr < session->header.attrs) {
222 h_attr = session->header.attr[nr];
224 h_attr = perf_header_attr__new(a);
226 if (perf_header__add_attr(&session->header, h_attr) < 0) {
227 perf_header_attr__delete(h_attr);
235 static void create_counter(int counter, int cpu, pid_t pid)
237 char *filter = filters[counter];
238 struct perf_event_attr *attr = attrs + counter;
239 struct perf_header_attr *h_attr;
240 int track = !counter; /* only the first counter needs these */
249 attr->read_format = PERF_FORMAT_TOTAL_TIME_ENABLED |
250 PERF_FORMAT_TOTAL_TIME_RUNNING |
253 attr->sample_type |= PERF_SAMPLE_IP | PERF_SAMPLE_TID;
256 attr->sample_type |= PERF_SAMPLE_PERIOD;
258 attr->sample_freq = freq;
262 attr->sample_freq = 0;
265 attr->inherit_stat = 1;
268 attr->sample_type |= PERF_SAMPLE_ADDR;
271 attr->sample_type |= PERF_SAMPLE_CALLCHAIN;
274 attr->sample_type |= PERF_SAMPLE_TIME;
275 attr->sample_type |= PERF_SAMPLE_RAW;
276 attr->sample_type |= PERF_SAMPLE_CPU;
281 attr->inherit = (cpu < 0) && inherit;
285 fd[nr_cpu][counter] = sys_perf_event_open(attr, pid, cpu, group_fd, 0);
287 if (fd[nr_cpu][counter] < 0) {
290 if (err == EPERM || err == EACCES)
291 die("Permission error - are you root?\n");
292 else if (err == ENODEV && profile_cpu != -1)
293 die("No such device - did you specify an out-of-range profile CPU?\n");
296 * If it's cycles then fall back to hrtimer
297 * based cpu-clock-tick sw counter, which
298 * is always available even if no PMU support:
300 if (attr->type == PERF_TYPE_HARDWARE
301 && attr->config == PERF_COUNT_HW_CPU_CYCLES) {
304 warning(" ... trying to fall back to cpu-clock-ticks\n");
305 attr->type = PERF_TYPE_SOFTWARE;
306 attr->config = PERF_COUNT_SW_CPU_CLOCK;
310 error("perfcounter syscall returned with %d (%s)\n",
311 fd[nr_cpu][counter], strerror(err));
313 #if defined(__i386__) || defined(__x86_64__)
314 if (attr->type == PERF_TYPE_HARDWARE && err == EOPNOTSUPP)
315 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");
318 die("No CONFIG_PERF_EVENTS=y kernel support configured?\n");
322 h_attr = get_header_attr(attr, counter);
327 if (memcmp(&h_attr->attr, attr, sizeof(*attr))) {
328 fprintf(stderr, "incompatible append\n");
333 if (read(fd[nr_cpu][counter], &read_data, sizeof(read_data)) == -1) {
334 perror("Unable to read perf file descriptor\n");
338 if (perf_header_attr__add_id(h_attr, read_data.id) < 0) {
339 pr_warning("Not enough memory to add id\n");
343 assert(fd[nr_cpu][counter] >= 0);
344 fcntl(fd[nr_cpu][counter], F_SETFL, O_NONBLOCK);
347 * First counter acts as the group leader:
349 if (group && group_fd == -1)
350 group_fd = fd[nr_cpu][counter];
351 if (multiplex && multiplex_fd == -1)
352 multiplex_fd = fd[nr_cpu][counter];
354 if (multiplex && fd[nr_cpu][counter] != multiplex_fd) {
356 ret = ioctl(fd[nr_cpu][counter], PERF_EVENT_IOC_SET_OUTPUT, multiplex_fd);
359 event_array[nr_poll].fd = fd[nr_cpu][counter];
360 event_array[nr_poll].events = POLLIN;
363 mmap_array[nr_cpu][counter].counter = counter;
364 mmap_array[nr_cpu][counter].prev = 0;
365 mmap_array[nr_cpu][counter].mask = mmap_pages*page_size - 1;
366 mmap_array[nr_cpu][counter].base = mmap(NULL, (mmap_pages+1)*page_size,
367 PROT_READ|PROT_WRITE, MAP_SHARED, fd[nr_cpu][counter], 0);
368 if (mmap_array[nr_cpu][counter].base == MAP_FAILED) {
369 error("failed to mmap with %d (%s)\n", errno, strerror(errno));
374 if (filter != NULL) {
375 ret = ioctl(fd[nr_cpu][counter],
376 PERF_EVENT_IOC_SET_FILTER, filter);
378 error("failed to set filter with %d (%s)\n", errno,
384 ioctl(fd[nr_cpu][counter], PERF_EVENT_IOC_ENABLE);
387 static void open_counters(int cpu, pid_t pid)
392 for (counter = 0; counter < nr_counters; counter++)
393 create_counter(counter, cpu, pid);
398 static void atexit_header(void)
400 session->header.data_size += bytes_written;
402 perf_header__write(&session->header, output, true);
405 static int __cmd_record(int argc, const char **argv)
412 unsigned long waking = 0;
414 page_size = sysconf(_SC_PAGE_SIZE);
415 nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
416 assert(nr_cpus <= MAX_NR_CPUS);
417 assert(nr_cpus >= 0);
420 signal(SIGCHLD, sig_handler);
421 signal(SIGINT, sig_handler);
423 if (!stat(output_name, &st) && st.st_size) {
426 pr_err("Error, output file %s exists, use -A "
427 "to append or -f to overwrite.\n",
432 char oldname[PATH_MAX];
433 snprintf(oldname, sizeof(oldname), "%s.old",
436 rename(output_name, oldname);
442 flags = O_CREAT|O_RDWR;
448 output = open(output_name, flags, S_IRUSR|S_IWUSR);
450 perror("failed to create output file");
454 session = perf_session__new(output_name, O_WRONLY, force);
455 if (session == NULL) {
456 pr_err("Not enough memory for reading perf file header\n");
461 err = perf_header__read(&session->header, output);
467 perf_header__set_feat(&session->header, HEADER_TRACE_INFO);
469 for (i = 0; i < nr_counters; i++) {
470 if (attrs[i].sample_type & PERF_SAMPLE_RAW) {
471 perf_header__set_feat(&session->header, HEADER_TRACE_INFO);
477 atexit(atexit_header);
484 open_counters(profile_cpu, pid);
486 if (profile_cpu != -1) {
487 open_counters(profile_cpu, target_pid);
489 for (i = 0; i < nr_cpus; i++)
490 open_counters(i, target_pid);
495 err = perf_header__write(&session->header, output, false);
501 event__synthesize_thread(pid, process_synthesized_event,
504 event__synthesize_threads(process_synthesized_event, session);
506 if (target_pid == -1 && argc) {
509 die("failed to fork");
512 if (execvp(argv[0], (char **)argv)) {
518 * Wait a bit for the execv'ed child to appear
519 * and be updated in /proc
520 * FIXME: Do you know a less heuristical solution?
523 event__synthesize_thread(pid,
524 process_synthesized_event,
532 struct sched_param param;
534 param.sched_priority = realtime_prio;
535 if (sched_setscheduler(0, SCHED_FIFO, ¶m)) {
536 pr_err("Could not set realtime priority.\n");
544 for (i = 0; i < nr_cpu; i++) {
545 for (counter = 0; counter < nr_counters; counter++) {
546 if (mmap_array[i][counter].base)
547 mmap_read(&mmap_array[i][counter]);
551 if (hits == samples) {
554 err = poll(event_array, nr_poll, -1);
559 for (i = 0; i < nr_cpu; i++) {
560 for (counter = 0; counter < nr_counters; counter++)
561 ioctl(fd[i][counter], PERF_EVENT_IOC_DISABLE);
566 fprintf(stderr, "[ perf record: Woken up %ld times to write data ]\n", waking);
569 * Approximate RIP event size: 24 bytes.
572 "[ perf record: Captured and wrote %.3f MB %s (~%lld samples) ]\n",
573 (double)bytes_written / 1024.0 / 1024.0,
580 static const char * const record_usage[] = {
581 "perf record [<options>] [<command>]",
582 "perf record [<options>] -- <command> [<options>]",
586 static const struct option options[] = {
587 OPT_CALLBACK('e', "event", NULL, "event",
588 "event selector. use 'perf list' to list available events",
590 OPT_CALLBACK(0, "filter", NULL, "filter",
591 "event filter", parse_filter),
592 OPT_INTEGER('p', "pid", &target_pid,
593 "record events on existing pid"),
594 OPT_INTEGER('r', "realtime", &realtime_prio,
595 "collect data with this RT SCHED_FIFO priority"),
596 OPT_BOOLEAN('R', "raw-samples", &raw_samples,
597 "collect raw sample records from all opened counters"),
598 OPT_BOOLEAN('a', "all-cpus", &system_wide,
599 "system-wide collection from all CPUs"),
600 OPT_BOOLEAN('A', "append", &append_file,
601 "append to the output file to do incremental profiling"),
602 OPT_INTEGER('C', "profile_cpu", &profile_cpu,
603 "CPU to profile on"),
604 OPT_BOOLEAN('f', "force", &force,
605 "overwrite existing data file"),
606 OPT_LONG('c', "count", &default_interval,
607 "event period to sample"),
608 OPT_STRING('o', "output", &output_name, "file",
610 OPT_BOOLEAN('i', "inherit", &inherit,
611 "child tasks inherit counters"),
612 OPT_INTEGER('F', "freq", &freq,
613 "profile at this frequency"),
614 OPT_INTEGER('m', "mmap-pages", &mmap_pages,
615 "number of mmap data pages"),
616 OPT_BOOLEAN('g', "call-graph", &call_graph,
617 "do call-graph (stack chain/backtrace) recording"),
618 OPT_BOOLEAN('v', "verbose", &verbose,
619 "be more verbose (show counter open errors, etc)"),
620 OPT_BOOLEAN('s', "stat", &inherit_stat,
621 "per thread counts"),
622 OPT_BOOLEAN('d', "data", &sample_address,
624 OPT_BOOLEAN('n', "no-samples", &no_samples,
626 OPT_BOOLEAN('M', "multiplex", &multiplex,
627 "multiplex counter output in a single channel"),
631 int cmd_record(int argc, const char **argv, const char *prefix __used)
635 argc = parse_options(argc, argv, options, record_usage,
636 PARSE_OPT_STOP_AT_NON_OPTION);
637 if (!argc && target_pid == -1 && !system_wide)
638 usage_with_options(record_usage, options);
644 attrs[0].type = PERF_TYPE_HARDWARE;
645 attrs[0].config = PERF_COUNT_HW_CPU_CYCLES;
649 * User specified count overrides default frequency.
651 if (default_interval)
654 default_interval = freq;
656 fprintf(stderr, "frequency and count are zero, aborting\n");
660 for (counter = 0; counter < nr_counters; counter++) {
661 if (attrs[counter].sample_period)
664 attrs[counter].sample_period = default_interval;
667 return __cmd_record(argc, argv);