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"
23 #define ALIGN(x, a) __ALIGN_MASK(x, (typeof(x))(a)-1)
24 #define __ALIGN_MASK(x, mask) (((x)+(mask))&~(mask))
26 static int fd[MAX_NR_CPUS][MAX_COUNTERS];
28 static long default_interval = 100000;
30 static int nr_cpus = 0;
31 static unsigned int page_size;
32 static unsigned int mmap_pages = 128;
35 static const char *output_name = "perf.data";
37 static unsigned int realtime_prio = 0;
38 static int system_wide = 0;
39 static pid_t target_pid = -1;
40 static int inherit = 1;
42 static int append_file = 0;
43 static int call_graph = 0;
44 static int inherit_stat = 0;
45 static int no_samples = 0;
46 static int sample_address = 0;
49 static struct timeval last_read;
50 static struct timeval this_read;
52 static u64 bytes_written;
54 static struct pollfd event_array[MAX_NR_CPUS * MAX_COUNTERS];
59 static int file_new = 1;
61 struct perf_header *header;
70 static struct mmap_data mmap_array[MAX_NR_CPUS][MAX_COUNTERS];
72 static unsigned long mmap_read_head(struct mmap_data *md)
74 struct perf_counter_mmap_page *pc = md->base;
83 static void mmap_write_tail(struct mmap_data *md, unsigned long tail)
85 struct perf_counter_mmap_page *pc = md->base;
88 * ensure all reads are done before we write the tail out.
94 static void write_output(void *buf, size_t size)
97 int ret = write(output, buf, size);
100 die("failed to write");
105 bytes_written += ret;
109 static void mmap_read(struct mmap_data *md)
111 unsigned int head = mmap_read_head(md);
112 unsigned int old = md->prev;
113 unsigned char *data = md->base + page_size;
118 gettimeofday(&this_read, NULL);
121 * If we're further behind than half the buffer, there's a chance
122 * the writer will bite our tail and mess up the samples under us.
124 * If we somehow ended up ahead of the head, we got messed up.
126 * In either case, truncate and restart at head.
133 timersub(&this_read, &last_read, &iv);
134 msecs = iv.tv_sec*1000 + iv.tv_usec/1000;
136 fprintf(stderr, "WARNING: failed to keep up with mmap data."
137 " Last read %lu msecs ago.\n", msecs);
140 * head points to a known good entry, start there.
145 last_read = this_read;
152 if ((old & md->mask) + size != (head & md->mask)) {
153 buf = &data[old & md->mask];
154 size = md->mask + 1 - (old & md->mask);
157 write_output(buf, size);
160 buf = &data[old & md->mask];
164 write_output(buf, size);
167 mmap_write_tail(md, old);
170 static volatile int done = 0;
171 static volatile int signr = -1;
173 static void sig_handler(int sig)
179 static void sig_atexit(void)
184 signal(signr, SIG_DFL);
185 kill(getpid(), signr);
188 static void pid_synthesize_comm_event(pid_t pid, int full)
190 struct comm_event comm_ev;
191 char filename[PATH_MAX];
197 struct dirent dirent, *next;
199 snprintf(filename, sizeof(filename), "/proc/%d/stat", pid);
201 fd = open(filename, O_RDONLY);
204 * We raced with a task exiting - just return:
207 fprintf(stderr, "couldn't open %s\n", filename);
210 if (read(fd, bf, sizeof(bf)) < 0) {
211 fprintf(stderr, "couldn't read %s\n", filename);
216 /* 9027 (cat) R 6747 9027 6747 34816 9027 ... */
217 memset(&comm_ev, 0, sizeof(comm_ev));
218 field = strchr(bf, '(');
221 sep = strchr(++field, ')');
225 memcpy(comm_ev.comm, field, size++);
228 comm_ev.header.type = PERF_EVENT_COMM;
229 size = ALIGN(size, sizeof(u64));
230 comm_ev.header.size = sizeof(comm_ev) - (sizeof(comm_ev.comm) - size);
235 write_output(&comm_ev, comm_ev.header.size);
239 snprintf(filename, sizeof(filename), "/proc/%d/task", pid);
241 tasks = opendir(filename);
242 while (!readdir_r(tasks, &dirent, &next) && next) {
244 pid = strtol(dirent.d_name, &end, 10);
250 write_output(&comm_ev, comm_ev.header.size);
256 fprintf(stderr, "couldn't get COMM and pgid, malformed %s\n",
261 static void pid_synthesize_mmap_samples(pid_t pid)
263 char filename[PATH_MAX];
266 snprintf(filename, sizeof(filename), "/proc/%d/maps", pid);
268 fp = fopen(filename, "r");
271 * We raced with a task exiting - just return:
274 fprintf(stderr, "couldn't open %s\n", filename);
278 char bf[BUFSIZ], *pbf = bf;
279 struct mmap_event mmap_ev = {
280 .header = { .type = PERF_EVENT_MMAP },
284 if (fgets(bf, sizeof(bf), fp) == NULL)
287 /* 00400000-0040c000 r-xp 00000000 fd:01 41038 /bin/cat */
288 n = hex2u64(pbf, &mmap_ev.start);
292 n = hex2u64(pbf, &mmap_ev.len);
296 if (*pbf == 'x') { /* vm_exec */
297 char *execname = strchr(bf, '/');
300 if (execname == NULL)
301 execname = strstr(bf, "[vdso]");
303 if (execname == NULL)
306 size = strlen(execname);
307 execname[size - 1] = '\0'; /* Remove \n */
308 memcpy(mmap_ev.filename, execname, size);
309 size = ALIGN(size, sizeof(u64));
310 mmap_ev.len -= mmap_ev.start;
311 mmap_ev.header.size = (sizeof(mmap_ev) -
312 (sizeof(mmap_ev.filename) - size));
316 write_output(&mmap_ev, mmap_ev.header.size);
323 static void synthesize_all(void)
326 struct dirent dirent, *next;
328 proc = opendir("/proc");
330 while (!readdir_r(proc, &dirent, &next) && next) {
334 pid = strtol(dirent.d_name, &end, 10);
335 if (*end) /* only interested in proper numerical dirents */
338 pid_synthesize_comm_event(pid, 1);
339 pid_synthesize_mmap_samples(pid);
347 static struct perf_header_attr *get_header_attr(struct perf_counter_attr *a, int nr)
349 struct perf_header_attr *h_attr;
351 if (nr < header->attrs) {
352 h_attr = header->attr[nr];
354 h_attr = perf_header_attr__new(a);
355 perf_header__add_attr(header, h_attr);
361 static void create_counter(int counter, int cpu, pid_t pid)
363 struct perf_counter_attr *attr = attrs + counter;
364 struct perf_header_attr *h_attr;
365 int track = !counter; /* only the first counter needs these */
373 attr->read_format = PERF_FORMAT_TOTAL_TIME_ENABLED |
374 PERF_FORMAT_TOTAL_TIME_RUNNING |
377 attr->sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_TID;
380 attr->sample_type |= PERF_SAMPLE_PERIOD;
382 attr->sample_freq = freq;
386 attr->sample_freq = 0;
389 attr->inherit_stat = 1;
392 attr->sample_type |= PERF_SAMPLE_ADDR;
395 attr->sample_type |= PERF_SAMPLE_CALLCHAIN;
400 attr->inherit = (cpu < 0) && inherit;
404 fd[nr_cpu][counter] = sys_perf_counter_open(attr, pid, cpu, group_fd, 0);
406 if (fd[nr_cpu][counter] < 0) {
410 die("Permission error - are you root?\n");
413 * If it's cycles then fall back to hrtimer
414 * based cpu-clock-tick sw counter, which
415 * is always available even if no PMU support:
417 if (attr->type == PERF_TYPE_HARDWARE
418 && attr->config == PERF_COUNT_HW_CPU_CYCLES) {
421 warning(" ... trying to fall back to cpu-clock-ticks\n");
422 attr->type = PERF_TYPE_SOFTWARE;
423 attr->config = PERF_COUNT_SW_CPU_CLOCK;
427 error("perfcounter syscall returned with %d (%s)\n",
428 fd[nr_cpu][counter], strerror(err));
429 die("No CONFIG_PERF_COUNTERS=y kernel support configured?\n");
433 h_attr = get_header_attr(attr, counter);
436 if (memcmp(&h_attr->attr, attr, sizeof(*attr))) {
437 fprintf(stderr, "incompatible append\n");
442 if (read(fd[nr_cpu][counter], &read_data, sizeof(read_data)) == -1) {
443 perror("Unable to read perf file descriptor\n");
447 perf_header_attr__add_id(h_attr, read_data.id);
449 assert(fd[nr_cpu][counter] >= 0);
450 fcntl(fd[nr_cpu][counter], F_SETFL, O_NONBLOCK);
453 * First counter acts as the group leader:
455 if (group && group_fd == -1)
456 group_fd = fd[nr_cpu][counter];
458 event_array[nr_poll].fd = fd[nr_cpu][counter];
459 event_array[nr_poll].events = POLLIN;
462 mmap_array[nr_cpu][counter].counter = counter;
463 mmap_array[nr_cpu][counter].prev = 0;
464 mmap_array[nr_cpu][counter].mask = mmap_pages*page_size - 1;
465 mmap_array[nr_cpu][counter].base = mmap(NULL, (mmap_pages+1)*page_size,
466 PROT_READ|PROT_WRITE, MAP_SHARED, fd[nr_cpu][counter], 0);
467 if (mmap_array[nr_cpu][counter].base == MAP_FAILED) {
468 error("failed to mmap with %d (%s)\n", errno, strerror(errno));
472 ioctl(fd[nr_cpu][counter], PERF_COUNTER_IOC_ENABLE);
475 static void open_counters(int cpu, pid_t pid)
480 for (counter = 0; counter < nr_counters; counter++)
481 create_counter(counter, cpu, pid);
486 static void atexit_header(void)
488 header->data_size += bytes_written;
490 perf_header__write(header, output);
493 static int __cmd_record(int argc, const char **argv)
501 page_size = sysconf(_SC_PAGE_SIZE);
502 nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
503 assert(nr_cpus <= MAX_NR_CPUS);
504 assert(nr_cpus >= 0);
507 signal(SIGCHLD, sig_handler);
508 signal(SIGINT, sig_handler);
510 if (!stat(output_name, &st) && st.st_size) {
511 if (!force && !append_file) {
512 fprintf(stderr, "Error, output file %s exists, use -A to append or -f to overwrite.\n",
520 flags = O_CREAT|O_RDWR;
526 output = open(output_name, flags, S_IRUSR|S_IWUSR);
528 perror("failed to create output file");
533 header = perf_header__read(output);
535 header = perf_header__new();
537 atexit(atexit_header);
544 open_counters(-1, pid);
545 } else for (i = 0; i < nr_cpus; i++)
546 open_counters(i, target_pid);
549 perf_header__write(header, output);
552 pid_synthesize_comm_event(pid, 0);
553 pid_synthesize_mmap_samples(pid);
557 if (target_pid == -1 && argc) {
560 perror("failed to fork");
563 if (execvp(argv[0], (char **)argv)) {
571 struct sched_param param;
573 param.sched_priority = realtime_prio;
574 if (sched_setscheduler(0, SCHED_FIFO, ¶m)) {
575 printf("Could not set realtime priority.\n");
583 for (i = 0; i < nr_cpu; i++) {
584 for (counter = 0; counter < nr_counters; counter++)
585 mmap_read(&mmap_array[i][counter]);
588 if (hits == samples) {
591 ret = poll(event_array, nr_poll, 100);
596 * Approximate RIP event size: 24 bytes.
599 "[ perf record: Captured and wrote %.3f MB %s (~%lld samples) ]\n",
600 (double)bytes_written / 1024.0 / 1024.0,
607 static const char * const record_usage[] = {
608 "perf record [<options>] [<command>]",
609 "perf record [<options>] -- <command> [<options>]",
613 static const struct option options[] = {
614 OPT_CALLBACK('e', "event", NULL, "event",
615 "event selector. use 'perf list' to list available events",
617 OPT_INTEGER('p', "pid", &target_pid,
618 "record events on existing pid"),
619 OPT_INTEGER('r', "realtime", &realtime_prio,
620 "collect data with this RT SCHED_FIFO priority"),
621 OPT_BOOLEAN('a', "all-cpus", &system_wide,
622 "system-wide collection from all CPUs"),
623 OPT_BOOLEAN('A', "append", &append_file,
624 "append to the output file to do incremental profiling"),
625 OPT_BOOLEAN('f', "force", &force,
626 "overwrite existing data file"),
627 OPT_LONG('c', "count", &default_interval,
628 "event period to sample"),
629 OPT_STRING('o', "output", &output_name, "file",
631 OPT_BOOLEAN('i', "inherit", &inherit,
632 "child tasks inherit counters"),
633 OPT_INTEGER('F', "freq", &freq,
634 "profile at this frequency"),
635 OPT_INTEGER('m', "mmap-pages", &mmap_pages,
636 "number of mmap data pages"),
637 OPT_BOOLEAN('g', "call-graph", &call_graph,
638 "do call-graph (stack chain/backtrace) recording"),
639 OPT_BOOLEAN('v', "verbose", &verbose,
640 "be more verbose (show counter open errors, etc)"),
641 OPT_BOOLEAN('s', "stat", &inherit_stat,
642 "per thread counts"),
643 OPT_BOOLEAN('d', "data", &sample_address,
645 OPT_BOOLEAN('n', "no-samples", &no_samples,
650 int cmd_record(int argc, const char **argv, const char *prefix __used)
654 argc = parse_options(argc, argv, options, record_usage,
655 PARSE_OPT_STOP_AT_NON_OPTION);
656 if (!argc && target_pid == -1 && !system_wide)
657 usage_with_options(record_usage, options);
661 attrs[0].type = PERF_TYPE_HARDWARE;
662 attrs[0].config = PERF_COUNT_HW_CPU_CYCLES;
665 for (counter = 0; counter < nr_counters; counter++) {
666 if (attrs[counter].sample_period)
669 attrs[counter].sample_period = default_interval;
672 return __cmd_record(argc, argv);