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/symbol.h"
25 static int fd[MAX_NR_CPUS][MAX_COUNTERS];
27 static long default_interval = 0;
29 static int nr_cpus = 0;
30 static unsigned int page_size;
31 static unsigned int mmap_pages = 128;
32 static int freq = 1000;
34 static const char *output_name = "perf.data";
36 static unsigned int realtime_prio = 0;
37 static int raw_samples = 0;
38 static int system_wide = 0;
39 static int profile_cpu = -1;
40 static pid_t target_pid = -1;
41 static pid_t child_pid = -1;
42 static int inherit = 1;
44 static int append_file = 0;
45 static int call_graph = 0;
46 static int inherit_stat = 0;
47 static int no_samples = 0;
48 static int sample_address = 0;
49 static int multiplex = 0;
50 static int multiplex_fd = -1;
52 static long samples = 0;
53 static struct timeval last_read;
54 static struct timeval this_read;
56 static u64 bytes_written = 0;
58 static struct pollfd event_array[MAX_NR_CPUS * MAX_COUNTERS];
60 static int nr_poll = 0;
61 static int nr_cpu = 0;
63 static int file_new = 1;
65 struct perf_header *header = NULL;
74 static struct mmap_data mmap_array[MAX_NR_CPUS][MAX_COUNTERS];
76 static unsigned long mmap_read_head(struct mmap_data *md)
78 struct perf_event_mmap_page *pc = md->base;
87 static void mmap_write_tail(struct mmap_data *md, unsigned long tail)
89 struct perf_event_mmap_page *pc = md->base;
92 * ensure all reads are done before we write the tail out.
98 static void write_output(void *buf, size_t size)
101 int ret = write(output, buf, size);
104 die("failed to write");
109 bytes_written += ret;
113 static void write_event(event_t *buf, size_t size)
116 * Add it to the list of DSOs, so that when we finish this
117 * record session we can pick the available build-ids.
119 if (buf->header.type == PERF_RECORD_MMAP)
120 dsos__findnew(buf->mmap.filename);
122 write_output(buf, size);
125 static int process_synthesized_event(event_t *event)
127 write_event(event, event->header.size);
131 static void mmap_read(struct mmap_data *md)
133 unsigned int head = mmap_read_head(md);
134 unsigned int old = md->prev;
135 unsigned char *data = md->base + page_size;
140 gettimeofday(&this_read, NULL);
143 * If we're further behind than half the buffer, there's a chance
144 * the writer will bite our tail and mess up the samples under us.
146 * If we somehow ended up ahead of the head, we got messed up.
148 * In either case, truncate and restart at head.
155 timersub(&this_read, &last_read, &iv);
156 msecs = iv.tv_sec*1000 + iv.tv_usec/1000;
158 fprintf(stderr, "WARNING: failed to keep up with mmap data."
159 " Last read %lu msecs ago.\n", msecs);
162 * head points to a known good entry, start there.
167 last_read = this_read;
174 if ((old & md->mask) + size != (head & md->mask)) {
175 buf = &data[old & md->mask];
176 size = md->mask + 1 - (old & md->mask);
179 write_event(buf, size);
182 buf = &data[old & md->mask];
186 write_event(buf, size);
189 mmap_write_tail(md, old);
192 static volatile int done = 0;
193 static volatile int signr = -1;
195 static void sig_handler(int sig)
201 static void sig_atexit(void)
204 kill(child_pid, SIGTERM);
209 signal(signr, SIG_DFL);
210 kill(getpid(), signr);
215 static struct perf_header_attr *get_header_attr(struct perf_event_attr *a, int nr)
217 struct perf_header_attr *h_attr;
219 if (nr < header->attrs) {
220 h_attr = header->attr[nr];
222 h_attr = perf_header_attr__new(a);
224 perf_header__add_attr(header, h_attr);
230 static void create_counter(int counter, int cpu, pid_t pid)
232 char *filter = filters[counter];
233 struct perf_event_attr *attr = attrs + counter;
234 struct perf_header_attr *h_attr;
235 int track = !counter; /* only the first counter needs these */
244 attr->read_format = PERF_FORMAT_TOTAL_TIME_ENABLED |
245 PERF_FORMAT_TOTAL_TIME_RUNNING |
248 attr->sample_type |= PERF_SAMPLE_IP | PERF_SAMPLE_TID;
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 = (cpu < 0) && 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));
307 die("No CONFIG_PERF_EVENTS=y kernel support configured?\n");
311 h_attr = get_header_attr(attr, counter);
316 if (memcmp(&h_attr->attr, attr, sizeof(*attr))) {
317 fprintf(stderr, "incompatible append\n");
322 if (read(fd[nr_cpu][counter], &read_data, sizeof(read_data)) == -1) {
323 perror("Unable to read perf file descriptor\n");
327 perf_header_attr__add_id(h_attr, read_data.id);
329 assert(fd[nr_cpu][counter] >= 0);
330 fcntl(fd[nr_cpu][counter], F_SETFL, O_NONBLOCK);
333 * First counter acts as the group leader:
335 if (group && group_fd == -1)
336 group_fd = fd[nr_cpu][counter];
337 if (multiplex && multiplex_fd == -1)
338 multiplex_fd = fd[nr_cpu][counter];
340 if (multiplex && fd[nr_cpu][counter] != multiplex_fd) {
342 ret = ioctl(fd[nr_cpu][counter], PERF_EVENT_IOC_SET_OUTPUT, multiplex_fd);
345 event_array[nr_poll].fd = fd[nr_cpu][counter];
346 event_array[nr_poll].events = POLLIN;
349 mmap_array[nr_cpu][counter].counter = counter;
350 mmap_array[nr_cpu][counter].prev = 0;
351 mmap_array[nr_cpu][counter].mask = mmap_pages*page_size - 1;
352 mmap_array[nr_cpu][counter].base = mmap(NULL, (mmap_pages+1)*page_size,
353 PROT_READ|PROT_WRITE, MAP_SHARED, fd[nr_cpu][counter], 0);
354 if (mmap_array[nr_cpu][counter].base == MAP_FAILED) {
355 error("failed to mmap with %d (%s)\n", errno, strerror(errno));
360 if (filter != NULL) {
361 ret = ioctl(fd[nr_cpu][counter],
362 PERF_EVENT_IOC_SET_FILTER, filter);
364 error("failed to set filter with %d (%s)\n", errno,
370 ioctl(fd[nr_cpu][counter], PERF_EVENT_IOC_ENABLE);
373 static void open_counters(int cpu, pid_t pid)
378 for (counter = 0; counter < nr_counters; counter++)
379 create_counter(counter, cpu, pid);
384 static void atexit_header(void)
386 header->data_size += bytes_written;
388 perf_header__write(header, output, true);
391 static int __cmd_record(int argc, const char **argv)
398 unsigned long waking = 0;
400 page_size = sysconf(_SC_PAGE_SIZE);
401 nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
402 assert(nr_cpus <= MAX_NR_CPUS);
403 assert(nr_cpus >= 0);
406 signal(SIGCHLD, sig_handler);
407 signal(SIGINT, sig_handler);
409 if (!stat(output_name, &st) && st.st_size) {
410 if (!force && !append_file) {
411 fprintf(stderr, "Error, output file %s exists, use -A to append or -f to overwrite.\n",
419 flags = O_CREAT|O_RDWR;
425 output = open(output_name, flags, S_IRUSR|S_IWUSR);
427 perror("failed to create output file");
432 header = perf_header__read(output);
434 header = perf_header__new();
437 perf_header__set_feat(header, HEADER_TRACE_INFO);
439 for (i = 0; i < nr_counters; i++) {
440 if (attrs[i].sample_type & PERF_SAMPLE_RAW) {
441 perf_header__set_feat(header, HEADER_TRACE_INFO);
447 atexit(atexit_header);
454 open_counters(profile_cpu, pid);
456 if (profile_cpu != -1) {
457 open_counters(profile_cpu, target_pid);
459 for (i = 0; i < nr_cpus; i++)
460 open_counters(i, target_pid);
465 perf_header__write(header, output, false);
468 event__synthesize_thread(pid, process_synthesized_event);
470 event__synthesize_threads(process_synthesized_event);
472 if (target_pid == -1 && argc) {
475 die("failed to fork");
478 if (execvp(argv[0], (char **)argv)) {
484 * Wait a bit for the execv'ed child to appear
485 * and be updated in /proc
486 * FIXME: Do you know a less heuristical solution?
489 event__synthesize_thread(pid,
490 process_synthesized_event);
497 struct sched_param param;
499 param.sched_priority = realtime_prio;
500 if (sched_setscheduler(0, SCHED_FIFO, ¶m)) {
501 pr_err("Could not set realtime priority.\n");
509 for (i = 0; i < nr_cpu; i++) {
510 for (counter = 0; counter < nr_counters; counter++) {
511 if (mmap_array[i][counter].base)
512 mmap_read(&mmap_array[i][counter]);
516 if (hits == samples) {
519 ret = poll(event_array, nr_poll, -1);
524 for (i = 0; i < nr_cpu; i++) {
525 for (counter = 0; counter < nr_counters; counter++)
526 ioctl(fd[i][counter], PERF_EVENT_IOC_DISABLE);
531 fprintf(stderr, "[ perf record: Woken up %ld times to write data ]\n", waking);
534 * Approximate RIP event size: 24 bytes.
537 "[ perf record: Captured and wrote %.3f MB %s (~%lld samples) ]\n",
538 (double)bytes_written / 1024.0 / 1024.0,
545 static const char * const record_usage[] = {
546 "perf record [<options>] [<command>]",
547 "perf record [<options>] -- <command> [<options>]",
551 static const struct option options[] = {
552 OPT_CALLBACK('e', "event", NULL, "event",
553 "event selector. use 'perf list' to list available events",
555 OPT_CALLBACK(0, "filter", NULL, "filter",
556 "event filter", parse_filter),
557 OPT_INTEGER('p', "pid", &target_pid,
558 "record events on existing pid"),
559 OPT_INTEGER('r', "realtime", &realtime_prio,
560 "collect data with this RT SCHED_FIFO priority"),
561 OPT_BOOLEAN('R', "raw-samples", &raw_samples,
562 "collect raw sample records from all opened counters"),
563 OPT_BOOLEAN('a', "all-cpus", &system_wide,
564 "system-wide collection from all CPUs"),
565 OPT_BOOLEAN('A', "append", &append_file,
566 "append to the output file to do incremental profiling"),
567 OPT_INTEGER('C', "profile_cpu", &profile_cpu,
568 "CPU to profile on"),
569 OPT_BOOLEAN('f', "force", &force,
570 "overwrite existing data file"),
571 OPT_LONG('c', "count", &default_interval,
572 "event period to sample"),
573 OPT_STRING('o', "output", &output_name, "file",
575 OPT_BOOLEAN('i', "inherit", &inherit,
576 "child tasks inherit counters"),
577 OPT_INTEGER('F', "freq", &freq,
578 "profile at this frequency"),
579 OPT_INTEGER('m', "mmap-pages", &mmap_pages,
580 "number of mmap data pages"),
581 OPT_BOOLEAN('g', "call-graph", &call_graph,
582 "do call-graph (stack chain/backtrace) recording"),
583 OPT_BOOLEAN('v', "verbose", &verbose,
584 "be more verbose (show counter open errors, etc)"),
585 OPT_BOOLEAN('s', "stat", &inherit_stat,
586 "per thread counts"),
587 OPT_BOOLEAN('d', "data", &sample_address,
589 OPT_BOOLEAN('n', "no-samples", &no_samples,
591 OPT_BOOLEAN('M', "multiplex", &multiplex,
592 "multiplex counter output in a single channel"),
596 int cmd_record(int argc, const char **argv, const char *prefix __used)
602 argc = parse_options(argc, argv, options, record_usage,
603 PARSE_OPT_STOP_AT_NON_OPTION);
604 if (!argc && target_pid == -1 && !system_wide)
605 usage_with_options(record_usage, options);
609 attrs[0].type = PERF_TYPE_HARDWARE;
610 attrs[0].config = PERF_COUNT_HW_CPU_CYCLES;
614 * User specified count overrides default frequency.
616 if (default_interval)
619 default_interval = freq;
621 fprintf(stderr, "frequency and count are zero, aborting\n");
625 for (counter = 0; counter < nr_counters; counter++) {
626 if (attrs[counter].sample_period)
629 attrs[counter].sample_period = default_interval;
632 return __cmd_record(argc, argv);