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"
22 #define ALIGN(x, a) __ALIGN_MASK(x, (typeof(x))(a)-1)
23 #define __ALIGN_MASK(x, mask) (((x)+(mask))&~(mask))
25 static int fd[MAX_NR_CPUS][MAX_COUNTERS];
27 static long default_interval = 100000;
29 static int nr_cpus = 0;
30 static unsigned int page_size;
31 static unsigned int mmap_pages = 128;
34 static const char *output_name = "perf.data";
36 static unsigned int realtime_prio = 0;
37 static int system_wide = 0;
38 static pid_t target_pid = -1;
39 static int inherit = 1;
41 static int append_file = 0;
42 static int call_graph = 0;
43 static int inherit_stat = 0;
44 static int no_samples = 0;
45 static int sample_address = 0;
48 static struct timeval last_read;
49 static struct timeval this_read;
51 static u64 bytes_written;
53 static struct pollfd event_array[MAX_NR_CPUS * MAX_COUNTERS];
58 static int file_new = 1;
60 struct perf_header *header;
69 static struct mmap_data mmap_array[MAX_NR_CPUS][MAX_COUNTERS];
71 static unsigned long mmap_read_head(struct mmap_data *md)
73 struct perf_counter_mmap_page *pc = md->base;
82 static void mmap_write_tail(struct mmap_data *md, unsigned long tail)
84 struct perf_counter_mmap_page *pc = md->base;
87 * ensure all reads are done before we write the tail out.
93 static void write_output(void *buf, size_t size)
96 int ret = write(output, buf, size);
99 die("failed to write");
104 bytes_written += ret;
108 static void mmap_read(struct mmap_data *md)
110 unsigned int head = mmap_read_head(md);
111 unsigned int old = md->prev;
112 unsigned char *data = md->base + page_size;
117 gettimeofday(&this_read, NULL);
120 * If we're further behind than half the buffer, there's a chance
121 * the writer will bite our tail and mess up the samples under us.
123 * If we somehow ended up ahead of the head, we got messed up.
125 * In either case, truncate and restart at head.
132 timersub(&this_read, &last_read, &iv);
133 msecs = iv.tv_sec*1000 + iv.tv_usec/1000;
135 fprintf(stderr, "WARNING: failed to keep up with mmap data."
136 " Last read %lu msecs ago.\n", msecs);
139 * head points to a known good entry, start there.
144 last_read = this_read;
151 if ((old & md->mask) + size != (head & md->mask)) {
152 buf = &data[old & md->mask];
153 size = md->mask + 1 - (old & md->mask);
156 write_output(buf, size);
159 buf = &data[old & md->mask];
163 write_output(buf, size);
166 mmap_write_tail(md, old);
169 static volatile int done = 0;
170 static volatile int signr = -1;
172 static void sig_handler(int sig)
178 static void sig_atexit(void)
183 signal(signr, SIG_DFL);
184 kill(getpid(), signr);
187 static void pid_synthesize_comm_event(pid_t pid, int full)
189 struct comm_event comm_ev;
190 char filename[PATH_MAX];
196 struct dirent dirent, *next;
198 snprintf(filename, sizeof(filename), "/proc/%d/stat", pid);
200 fd = open(filename, O_RDONLY);
203 * We raced with a task exiting - just return:
206 fprintf(stderr, "couldn't open %s\n", filename);
209 if (read(fd, bf, sizeof(bf)) < 0) {
210 fprintf(stderr, "couldn't read %s\n", filename);
215 /* 9027 (cat) R 6747 9027 6747 34816 9027 ... */
216 memset(&comm_ev, 0, sizeof(comm_ev));
217 field = strchr(bf, '(');
220 sep = strchr(++field, ')');
224 memcpy(comm_ev.comm, field, size++);
227 comm_ev.header.type = PERF_EVENT_COMM;
228 size = ALIGN(size, sizeof(u64));
229 comm_ev.header.size = sizeof(comm_ev) - (sizeof(comm_ev.comm) - size);
234 write_output(&comm_ev, comm_ev.header.size);
238 snprintf(filename, sizeof(filename), "/proc/%d/task", pid);
240 tasks = opendir(filename);
241 while (!readdir_r(tasks, &dirent, &next) && next) {
243 pid = strtol(dirent.d_name, &end, 10);
249 write_output(&comm_ev, comm_ev.header.size);
255 fprintf(stderr, "couldn't get COMM and pgid, malformed %s\n",
260 static void pid_synthesize_mmap_samples(pid_t pid)
262 char filename[PATH_MAX];
265 snprintf(filename, sizeof(filename), "/proc/%d/maps", pid);
267 fp = fopen(filename, "r");
270 * We raced with a task exiting - just return:
273 fprintf(stderr, "couldn't open %s\n", filename);
277 char bf[BUFSIZ], *pbf = bf;
278 struct mmap_event mmap_ev = {
279 .header = { .type = PERF_EVENT_MMAP },
283 if (fgets(bf, sizeof(bf), fp) == NULL)
286 /* 00400000-0040c000 r-xp 00000000 fd:01 41038 /bin/cat */
287 n = hex2u64(pbf, &mmap_ev.start);
291 n = hex2u64(pbf, &mmap_ev.len);
295 if (*pbf == 'x') { /* vm_exec */
296 char *execname = strchr(bf, '/');
299 if (execname == NULL)
300 execname = strstr(bf, "[vdso]");
302 if (execname == NULL)
305 size = strlen(execname);
306 execname[size - 1] = '\0'; /* Remove \n */
307 memcpy(mmap_ev.filename, execname, size);
308 size = ALIGN(size, sizeof(u64));
309 mmap_ev.len -= mmap_ev.start;
310 mmap_ev.header.size = (sizeof(mmap_ev) -
311 (sizeof(mmap_ev.filename) - size));
315 write_output(&mmap_ev, mmap_ev.header.size);
322 static void synthesize_all(void)
325 struct dirent dirent, *next;
327 proc = opendir("/proc");
329 while (!readdir_r(proc, &dirent, &next) && next) {
333 pid = strtol(dirent.d_name, &end, 10);
334 if (*end) /* only interested in proper numerical dirents */
337 pid_synthesize_comm_event(pid, 1);
338 pid_synthesize_mmap_samples(pid);
346 static struct perf_header_attr *get_header_attr(struct perf_counter_attr *a, int nr)
348 struct perf_header_attr *h_attr;
350 if (nr < header->attrs) {
351 h_attr = header->attr[nr];
353 h_attr = perf_header_attr__new(a);
354 perf_header__add_attr(header, h_attr);
360 static void create_counter(int counter, int cpu, pid_t pid)
362 struct perf_counter_attr *attr = attrs + counter;
363 struct perf_header_attr *h_attr;
364 int track = !counter; /* only the first counter needs these */
372 attr->read_format = PERF_FORMAT_TOTAL_TIME_ENABLED |
373 PERF_FORMAT_TOTAL_TIME_RUNNING |
376 attr->sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_TID;
379 attr->sample_type |= PERF_SAMPLE_PERIOD;
381 attr->sample_freq = freq;
385 attr->sample_freq = 0;
388 attr->inherit_stat = 1;
391 attr->sample_type |= PERF_SAMPLE_ADDR;
394 attr->sample_type |= PERF_SAMPLE_CALLCHAIN;
399 attr->inherit = (cpu < 0) && inherit;
403 fd[nr_cpu][counter] = sys_perf_counter_open(attr, pid, cpu, group_fd, 0);
405 if (fd[nr_cpu][counter] < 0) {
409 die("Permission error - are you root?\n");
412 * If it's cycles then fall back to hrtimer
413 * based cpu-clock-tick sw counter, which
414 * is always available even if no PMU support:
416 if (attr->type == PERF_TYPE_HARDWARE
417 && attr->config == PERF_COUNT_HW_CPU_CYCLES) {
420 warning(" ... trying to fall back to cpu-clock-ticks\n");
421 attr->type = PERF_TYPE_SOFTWARE;
422 attr->config = PERF_COUNT_SW_CPU_CLOCK;
426 error("perfcounter syscall returned with %d (%s)\n",
427 fd[nr_cpu][counter], strerror(err));
428 die("No CONFIG_PERF_COUNTERS=y kernel support configured?\n");
432 h_attr = get_header_attr(attr, counter);
435 if (memcmp(&h_attr->attr, attr, sizeof(*attr))) {
436 fprintf(stderr, "incompatible append\n");
441 if (read(fd[nr_cpu][counter], &read_data, sizeof(read_data)) == -1) {
442 perror("Unable to read perf file descriptor\n");
446 perf_header_attr__add_id(h_attr, read_data.id);
448 assert(fd[nr_cpu][counter] >= 0);
449 fcntl(fd[nr_cpu][counter], F_SETFL, O_NONBLOCK);
452 * First counter acts as the group leader:
454 if (group && group_fd == -1)
455 group_fd = fd[nr_cpu][counter];
457 event_array[nr_poll].fd = fd[nr_cpu][counter];
458 event_array[nr_poll].events = POLLIN;
461 mmap_array[nr_cpu][counter].counter = counter;
462 mmap_array[nr_cpu][counter].prev = 0;
463 mmap_array[nr_cpu][counter].mask = mmap_pages*page_size - 1;
464 mmap_array[nr_cpu][counter].base = mmap(NULL, (mmap_pages+1)*page_size,
465 PROT_READ|PROT_WRITE, MAP_SHARED, fd[nr_cpu][counter], 0);
466 if (mmap_array[nr_cpu][counter].base == MAP_FAILED) {
467 error("failed to mmap with %d (%s)\n", errno, strerror(errno));
471 ioctl(fd[nr_cpu][counter], PERF_COUNTER_IOC_ENABLE);
474 static void open_counters(int cpu, pid_t pid)
479 for (counter = 0; counter < nr_counters; counter++)
480 create_counter(counter, cpu, pid);
485 static void atexit_header(void)
487 header->data_size += bytes_written;
489 perf_header__write(header, output);
492 static int __cmd_record(int argc, const char **argv)
500 page_size = sysconf(_SC_PAGE_SIZE);
501 nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
502 assert(nr_cpus <= MAX_NR_CPUS);
503 assert(nr_cpus >= 0);
506 signal(SIGCHLD, sig_handler);
507 signal(SIGINT, sig_handler);
509 if (!stat(output_name, &st) && st.st_size) {
510 if (!force && !append_file) {
511 fprintf(stderr, "Error, output file %s exists, use -A to append or -f to overwrite.\n",
519 flags = O_CREAT|O_RDWR;
525 output = open(output_name, flags, S_IRUSR|S_IWUSR);
527 perror("failed to create output file");
532 header = perf_header__read(output);
534 header = perf_header__new();
536 atexit(atexit_header);
543 open_counters(-1, pid);
544 } else for (i = 0; i < nr_cpus; i++)
545 open_counters(i, target_pid);
548 perf_header__write(header, output);
551 pid_synthesize_comm_event(pid, 0);
552 pid_synthesize_mmap_samples(pid);
556 if (target_pid == -1 && argc) {
559 perror("failed to fork");
562 if (execvp(argv[0], (char **)argv)) {
570 struct sched_param param;
572 param.sched_priority = realtime_prio;
573 if (sched_setscheduler(0, SCHED_FIFO, ¶m)) {
574 printf("Could not set realtime priority.\n");
582 for (i = 0; i < nr_cpu; i++) {
583 for (counter = 0; counter < nr_counters; counter++)
584 mmap_read(&mmap_array[i][counter]);
587 if (hits == samples) {
590 ret = poll(event_array, nr_poll, 100);
595 * Approximate RIP event size: 24 bytes.
598 "[ perf record: Captured and wrote %.3f MB %s (~%lld samples) ]\n",
599 (double)bytes_written / 1024.0 / 1024.0,
606 static const char * const record_usage[] = {
607 "perf record [<options>] [<command>]",
608 "perf record [<options>] -- <command> [<options>]",
612 static const struct option options[] = {
613 OPT_CALLBACK('e', "event", NULL, "event",
614 "event selector. use 'perf list' to list available events",
616 OPT_INTEGER('p', "pid", &target_pid,
617 "record events on existing pid"),
618 OPT_INTEGER('r', "realtime", &realtime_prio,
619 "collect data with this RT SCHED_FIFO priority"),
620 OPT_BOOLEAN('a', "all-cpus", &system_wide,
621 "system-wide collection from all CPUs"),
622 OPT_BOOLEAN('A', "append", &append_file,
623 "append to the output file to do incremental profiling"),
624 OPT_BOOLEAN('f', "force", &force,
625 "overwrite existing data file"),
626 OPT_LONG('c', "count", &default_interval,
627 "event period to sample"),
628 OPT_STRING('o', "output", &output_name, "file",
630 OPT_BOOLEAN('i', "inherit", &inherit,
631 "child tasks inherit counters"),
632 OPT_INTEGER('F', "freq", &freq,
633 "profile at this frequency"),
634 OPT_INTEGER('m', "mmap-pages", &mmap_pages,
635 "number of mmap data pages"),
636 OPT_BOOLEAN('g', "call-graph", &call_graph,
637 "do call-graph (stack chain/backtrace) recording"),
638 OPT_BOOLEAN('v', "verbose", &verbose,
639 "be more verbose (show counter open errors, etc)"),
640 OPT_BOOLEAN('s', "stat", &inherit_stat,
641 "per thread counts"),
642 OPT_BOOLEAN('d', "data", &sample_address,
644 OPT_BOOLEAN('n', "no-samples", &no_samples,
649 int cmd_record(int argc, const char **argv, const char *prefix __used)
653 argc = parse_options(argc, argv, options, record_usage,
654 PARSE_OPT_STOP_AT_NON_OPTION);
655 if (!argc && target_pid == -1 && !system_wide)
656 usage_with_options(record_usage, options);
660 attrs[0].type = PERF_TYPE_HARDWARE;
661 attrs[0].config = PERF_COUNT_HW_CPU_CYCLES;
664 for (counter = 0; counter < nr_counters; counter++) {
665 if (attrs[counter].sample_period)
668 attrs[counter].sample_period = default_interval;
671 return __cmd_record(argc, argv);