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 raw_samples = 0;
38 static int system_wide = 0;
39 static int profile_cpu = -1;
40 static pid_t target_pid = -1;
41 static int inherit = 1;
43 static int append_file = 0;
44 static int call_graph = 0;
45 static int verbose = 0;
46 static int inherit_stat = 0;
47 static int no_samples = 0;
48 static int sample_address = 0;
51 static struct timeval last_read;
52 static struct timeval this_read;
54 static u64 bytes_written;
56 static struct pollfd event_array[MAX_NR_CPUS * MAX_COUNTERS];
61 static int file_new = 1;
63 struct perf_header *header;
66 struct perf_event_header header;
72 char filename[PATH_MAX];
76 struct perf_event_header header;
90 static struct mmap_data mmap_array[MAX_NR_CPUS][MAX_COUNTERS];
92 static unsigned long mmap_read_head(struct mmap_data *md)
94 struct perf_counter_mmap_page *pc = md->base;
103 static void mmap_write_tail(struct mmap_data *md, unsigned long tail)
105 struct perf_counter_mmap_page *pc = md->base;
108 * ensure all reads are done before we write the tail out.
111 pc->data_tail = tail;
114 static void write_output(void *buf, size_t size)
117 int ret = write(output, buf, size);
120 die("failed to write");
125 bytes_written += ret;
129 static void mmap_read(struct mmap_data *md)
131 unsigned int head = mmap_read_head(md);
132 unsigned int old = md->prev;
133 unsigned char *data = md->base + page_size;
138 gettimeofday(&this_read, NULL);
141 * If we're further behind than half the buffer, there's a chance
142 * the writer will bite our tail and mess up the samples under us.
144 * If we somehow ended up ahead of the head, we got messed up.
146 * In either case, truncate and restart at head.
153 timersub(&this_read, &last_read, &iv);
154 msecs = iv.tv_sec*1000 + iv.tv_usec/1000;
156 fprintf(stderr, "WARNING: failed to keep up with mmap data."
157 " Last read %lu msecs ago.\n", msecs);
160 * head points to a known good entry, start there.
165 last_read = this_read;
172 if ((old & md->mask) + size != (head & md->mask)) {
173 buf = &data[old & md->mask];
174 size = md->mask + 1 - (old & md->mask);
177 write_output(buf, size);
180 buf = &data[old & md->mask];
184 write_output(buf, size);
187 mmap_write_tail(md, old);
190 static volatile int done = 0;
191 static volatile int signr = -1;
193 static void sig_handler(int sig)
199 static void sig_atexit(void)
204 signal(signr, SIG_DFL);
205 kill(getpid(), signr);
208 static pid_t pid_synthesize_comm_event(pid_t pid, int full)
210 struct comm_event comm_ev;
211 char filename[PATH_MAX];
216 struct dirent dirent, *next;
219 snprintf(filename, sizeof(filename), "/proc/%d/status", pid);
221 fp = fopen(filename, "r");
224 * We raced with a task exiting - just return:
227 fprintf(stderr, "couldn't open %s\n", filename);
231 memset(&comm_ev, 0, sizeof(comm_ev));
232 while (!comm_ev.comm[0] || !comm_ev.pid) {
233 if (fgets(bf, sizeof(bf), fp) == NULL)
236 if (memcmp(bf, "Name:", 5) == 0) {
238 while (*name && isspace(*name))
240 size = strlen(name) - 1;
241 memcpy(comm_ev.comm, name, size++);
242 } else if (memcmp(bf, "Tgid:", 5) == 0) {
243 char *tgids = bf + 5;
244 while (*tgids && isspace(*tgids))
246 tgid = comm_ev.pid = atoi(tgids);
250 comm_ev.header.type = PERF_EVENT_COMM;
251 size = ALIGN(size, sizeof(u64));
252 comm_ev.header.size = sizeof(comm_ev) - (sizeof(comm_ev.comm) - size);
257 write_output(&comm_ev, comm_ev.header.size);
261 snprintf(filename, sizeof(filename), "/proc/%d/task", pid);
263 tasks = opendir(filename);
264 while (!readdir_r(tasks, &dirent, &next) && next) {
266 pid = strtol(dirent.d_name, &end, 10);
272 write_output(&comm_ev, comm_ev.header.size);
281 fprintf(stderr, "couldn't get COMM and pgid, malformed %s\n",
286 static void pid_synthesize_mmap_samples(pid_t pid, pid_t tgid)
288 char filename[PATH_MAX];
291 snprintf(filename, sizeof(filename), "/proc/%d/maps", pid);
293 fp = fopen(filename, "r");
296 * We raced with a task exiting - just return:
299 fprintf(stderr, "couldn't open %s\n", filename);
303 char bf[BUFSIZ], *pbf = bf;
304 struct mmap_event mmap_ev = {
305 .header = { .type = PERF_EVENT_MMAP },
309 if (fgets(bf, sizeof(bf), fp) == NULL)
312 /* 00400000-0040c000 r-xp 00000000 fd:01 41038 /bin/cat */
313 n = hex2u64(pbf, &mmap_ev.start);
317 n = hex2u64(pbf, &mmap_ev.len);
321 if (*pbf == 'x') { /* vm_exec */
322 char *execname = strchr(bf, '/');
325 if (execname == NULL)
326 execname = strstr(bf, "[vdso]");
328 if (execname == NULL)
331 size = strlen(execname);
332 execname[size - 1] = '\0'; /* Remove \n */
333 memcpy(mmap_ev.filename, execname, size);
334 size = ALIGN(size, sizeof(u64));
335 mmap_ev.len -= mmap_ev.start;
336 mmap_ev.header.size = (sizeof(mmap_ev) -
337 (sizeof(mmap_ev.filename) - size));
341 write_output(&mmap_ev, mmap_ev.header.size);
348 static void synthesize_all(void)
351 struct dirent dirent, *next;
353 proc = opendir("/proc");
355 while (!readdir_r(proc, &dirent, &next) && next) {
359 pid = strtol(dirent.d_name, &end, 10);
360 if (*end) /* only interested in proper numerical dirents */
363 tgid = pid_synthesize_comm_event(pid, 1);
364 pid_synthesize_mmap_samples(pid, tgid);
372 static struct perf_header_attr *get_header_attr(struct perf_counter_attr *a, int nr)
374 struct perf_header_attr *h_attr;
376 if (nr < header->attrs) {
377 h_attr = header->attr[nr];
379 h_attr = perf_header_attr__new(a);
380 perf_header__add_attr(header, h_attr);
386 static void create_counter(int counter, int cpu, pid_t pid)
388 struct perf_counter_attr *attr = attrs + counter;
389 struct perf_header_attr *h_attr;
390 int track = !counter; /* only the first counter needs these */
398 attr->read_format = PERF_FORMAT_TOTAL_TIME_ENABLED |
399 PERF_FORMAT_TOTAL_TIME_RUNNING |
402 attr->sample_type |= PERF_SAMPLE_IP | PERF_SAMPLE_TID;
405 attr->sample_type |= PERF_SAMPLE_PERIOD;
407 attr->sample_freq = freq;
411 attr->sample_freq = 0;
414 attr->inherit_stat = 1;
417 attr->sample_type |= PERF_SAMPLE_ADDR;
420 attr->sample_type |= PERF_SAMPLE_CALLCHAIN;
423 attr->sample_type |= PERF_SAMPLE_RAW;
427 attr->inherit = (cpu < 0) && inherit;
431 fd[nr_cpu][counter] = sys_perf_counter_open(attr, pid, cpu, group_fd, 0);
433 if (fd[nr_cpu][counter] < 0) {
437 die("Permission error - are you root?\n");
438 else if (err == ENODEV && profile_cpu != -1)
439 die("No such device - did you specify an out-of-range profile CPU?\n");
442 * If it's cycles then fall back to hrtimer
443 * based cpu-clock-tick sw counter, which
444 * is always available even if no PMU support:
446 if (attr->type == PERF_TYPE_HARDWARE
447 && attr->config == PERF_COUNT_HW_CPU_CYCLES) {
450 warning(" ... trying to fall back to cpu-clock-ticks\n");
451 attr->type = PERF_TYPE_SOFTWARE;
452 attr->config = PERF_COUNT_SW_CPU_CLOCK;
456 error("perfcounter syscall returned with %d (%s)\n",
457 fd[nr_cpu][counter], strerror(err));
458 die("No CONFIG_PERF_COUNTERS=y kernel support configured?\n");
462 h_attr = get_header_attr(attr, counter);
465 if (memcmp(&h_attr->attr, attr, sizeof(*attr))) {
466 fprintf(stderr, "incompatible append\n");
471 if (read(fd[nr_cpu][counter], &read_data, sizeof(read_data)) == -1) {
472 perror("Unable to read perf file descriptor\n");
476 perf_header_attr__add_id(h_attr, read_data.id);
478 assert(fd[nr_cpu][counter] >= 0);
479 fcntl(fd[nr_cpu][counter], F_SETFL, O_NONBLOCK);
482 * First counter acts as the group leader:
484 if (group && group_fd == -1)
485 group_fd = fd[nr_cpu][counter];
487 event_array[nr_poll].fd = fd[nr_cpu][counter];
488 event_array[nr_poll].events = POLLIN;
491 mmap_array[nr_cpu][counter].counter = counter;
492 mmap_array[nr_cpu][counter].prev = 0;
493 mmap_array[nr_cpu][counter].mask = mmap_pages*page_size - 1;
494 mmap_array[nr_cpu][counter].base = mmap(NULL, (mmap_pages+1)*page_size,
495 PROT_READ|PROT_WRITE, MAP_SHARED, fd[nr_cpu][counter], 0);
496 if (mmap_array[nr_cpu][counter].base == MAP_FAILED) {
497 error("failed to mmap with %d (%s)\n", errno, strerror(errno));
501 ioctl(fd[nr_cpu][counter], PERF_COUNTER_IOC_ENABLE);
504 static void open_counters(int cpu, pid_t pid)
509 for (counter = 0; counter < nr_counters; counter++)
510 create_counter(counter, cpu, pid);
515 static void atexit_header(void)
517 header->data_size += bytes_written;
519 perf_header__write(header, output);
522 static int __cmd_record(int argc, const char **argv)
530 page_size = sysconf(_SC_PAGE_SIZE);
531 nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
532 assert(nr_cpus <= MAX_NR_CPUS);
533 assert(nr_cpus >= 0);
536 signal(SIGCHLD, sig_handler);
537 signal(SIGINT, sig_handler);
539 if (!stat(output_name, &st) && st.st_size) {
540 if (!force && !append_file) {
541 fprintf(stderr, "Error, output file %s exists, use -A to append or -f to overwrite.\n",
549 flags = O_CREAT|O_RDWR;
555 output = open(output_name, flags, S_IRUSR|S_IWUSR);
557 perror("failed to create output file");
562 header = perf_header__read(output);
564 header = perf_header__new();
566 atexit(atexit_header);
573 open_counters(profile_cpu, pid);
575 if (profile_cpu != -1) {
576 open_counters(profile_cpu, target_pid);
578 for (i = 0; i < nr_cpus; i++)
579 open_counters(i, target_pid);
584 perf_header__write(header, output);
587 pid_t tgid = pid_synthesize_comm_event(pid, 0);
588 pid_synthesize_mmap_samples(pid, tgid);
592 if (target_pid == -1 && argc) {
595 perror("failed to fork");
598 if (execvp(argv[0], (char **)argv)) {
606 struct sched_param param;
608 param.sched_priority = realtime_prio;
609 if (sched_setscheduler(0, SCHED_FIFO, ¶m)) {
610 printf("Could not set realtime priority.\n");
618 for (i = 0; i < nr_cpu; i++) {
619 for (counter = 0; counter < nr_counters; counter++)
620 mmap_read(&mmap_array[i][counter]);
623 if (hits == samples) {
626 ret = poll(event_array, nr_poll, 100);
631 * Approximate RIP event size: 24 bytes.
634 "[ perf record: Captured and wrote %.3f MB %s (~%lld samples) ]\n",
635 (double)bytes_written / 1024.0 / 1024.0,
642 static const char * const record_usage[] = {
643 "perf record [<options>] [<command>]",
644 "perf record [<options>] -- <command> [<options>]",
648 static const struct option options[] = {
649 OPT_CALLBACK('e', "event", NULL, "event",
650 "event selector. use 'perf list' to list available events",
652 OPT_INTEGER('p', "pid", &target_pid,
653 "record events on existing pid"),
654 OPT_INTEGER('r', "realtime", &realtime_prio,
655 "collect data with this RT SCHED_FIFO priority"),
656 OPT_BOOLEAN('R', "raw-samples", &raw_samples,
657 "collect raw sample records from all opened counters"),
658 OPT_BOOLEAN('a', "all-cpus", &system_wide,
659 "system-wide collection from all CPUs"),
660 OPT_BOOLEAN('A', "append", &append_file,
661 "append to the output file to do incremental profiling"),
662 OPT_INTEGER('C', "profile_cpu", &profile_cpu,
663 "CPU to profile on"),
664 OPT_BOOLEAN('f', "force", &force,
665 "overwrite existing data file"),
666 OPT_LONG('c', "count", &default_interval,
667 "event period to sample"),
668 OPT_STRING('o', "output", &output_name, "file",
670 OPT_BOOLEAN('i', "inherit", &inherit,
671 "child tasks inherit counters"),
672 OPT_INTEGER('F', "freq", &freq,
673 "profile at this frequency"),
674 OPT_INTEGER('m', "mmap-pages", &mmap_pages,
675 "number of mmap data pages"),
676 OPT_BOOLEAN('g', "call-graph", &call_graph,
677 "do call-graph (stack chain/backtrace) recording"),
678 OPT_BOOLEAN('v', "verbose", &verbose,
679 "be more verbose (show counter open errors, etc)"),
680 OPT_BOOLEAN('s', "stat", &inherit_stat,
681 "per thread counts"),
682 OPT_BOOLEAN('d', "data", &sample_address,
684 OPT_BOOLEAN('n', "no-samples", &no_samples,
689 int cmd_record(int argc, const char **argv, const char *prefix __used)
693 argc = parse_options(argc, argv, options, record_usage,
694 PARSE_OPT_STOP_AT_NON_OPTION);
695 if (!argc && target_pid == -1 && !system_wide)
696 usage_with_options(record_usage, options);
700 attrs[0].type = PERF_TYPE_HARDWARE;
701 attrs[0].config = PERF_COUNT_HW_CPU_CYCLES;
704 for (counter = 0; counter < nr_counters; counter++) {
705 if (attrs[counter].sample_period)
708 attrs[counter].sample_period = default_interval;
711 return __cmd_record(argc, argv);