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"
24 static int fd[MAX_NR_CPUS][MAX_COUNTERS];
26 static long default_interval = 0;
28 static int nr_cpus = 0;
29 static unsigned int page_size;
30 static unsigned int mmap_pages = 128;
31 static int freq = 1000;
33 static const char *output_name = "perf.data";
35 static unsigned int realtime_prio = 0;
36 static int raw_samples = 0;
37 static int system_wide = 0;
38 static int profile_cpu = -1;
39 static pid_t target_pid = -1;
40 static pid_t child_pid = -1;
41 static int inherit = 1;
43 static int append_file = 0;
44 static int call_graph = 0;
45 static int inherit_stat = 0;
46 static int no_samples = 0;
47 static int sample_address = 0;
48 static int multiplex = 0;
49 static int multiplex_fd = -1;
51 static long samples = 0;
52 static struct timeval last_read;
53 static struct timeval this_read;
55 static u64 bytes_written = 0;
57 static struct pollfd event_array[MAX_NR_CPUS * MAX_COUNTERS];
59 static int nr_poll = 0;
60 static int nr_cpu = 0;
62 static int file_new = 1;
64 struct perf_header *header = NULL;
73 static struct mmap_data mmap_array[MAX_NR_CPUS][MAX_COUNTERS];
75 static unsigned long mmap_read_head(struct mmap_data *md)
77 struct perf_event_mmap_page *pc = md->base;
86 static void mmap_write_tail(struct mmap_data *md, unsigned long tail)
88 struct perf_event_mmap_page *pc = md->base;
91 * ensure all reads are done before we write the tail out.
97 static void write_output(void *buf, size_t size)
100 int ret = write(output, buf, size);
103 die("failed to write");
108 bytes_written += ret;
112 static void mmap_read(struct mmap_data *md)
114 unsigned int head = mmap_read_head(md);
115 unsigned int old = md->prev;
116 unsigned char *data = md->base + page_size;
121 gettimeofday(&this_read, NULL);
124 * If we're further behind than half the buffer, there's a chance
125 * the writer will bite our tail and mess up the samples under us.
127 * If we somehow ended up ahead of the head, we got messed up.
129 * In either case, truncate and restart at head.
136 timersub(&this_read, &last_read, &iv);
137 msecs = iv.tv_sec*1000 + iv.tv_usec/1000;
139 fprintf(stderr, "WARNING: failed to keep up with mmap data."
140 " Last read %lu msecs ago.\n", msecs);
143 * head points to a known good entry, start there.
148 last_read = this_read;
155 if ((old & md->mask) + size != (head & md->mask)) {
156 buf = &data[old & md->mask];
157 size = md->mask + 1 - (old & md->mask);
160 write_output(buf, size);
163 buf = &data[old & md->mask];
167 write_output(buf, size);
170 mmap_write_tail(md, old);
173 static volatile int done = 0;
174 static volatile int signr = -1;
176 static void sig_handler(int sig)
182 static void sig_atexit(void)
185 kill(child_pid, SIGTERM);
190 signal(signr, SIG_DFL);
191 kill(getpid(), signr);
194 static pid_t pid_synthesize_comm_event(pid_t pid, int full)
196 struct comm_event comm_ev;
197 char filename[PATH_MAX];
202 struct dirent dirent, *next;
205 snprintf(filename, sizeof(filename), "/proc/%d/status", pid);
207 fp = fopen(filename, "r");
211 * We raced with a task exiting - just return:
214 fprintf(stderr, "couldn't open %s\n", filename);
218 memset(&comm_ev, 0, sizeof(comm_ev));
219 while (!comm_ev.comm[0] || !comm_ev.pid) {
220 if (fgets(bf, sizeof(bf), fp) == NULL)
223 if (memcmp(bf, "Name:", 5) == 0) {
225 while (*name && isspace(*name))
227 size = strlen(name) - 1;
228 memcpy(comm_ev.comm, name, size++);
229 } else if (memcmp(bf, "Tgid:", 5) == 0) {
230 char *tgids = bf + 5;
231 while (*tgids && isspace(*tgids))
233 tgid = comm_ev.pid = atoi(tgids);
237 comm_ev.header.type = PERF_RECORD_COMM;
238 size = ALIGN(size, sizeof(u64));
239 comm_ev.header.size = sizeof(comm_ev) - (sizeof(comm_ev.comm) - size);
244 write_output(&comm_ev, comm_ev.header.size);
248 snprintf(filename, sizeof(filename), "/proc/%d/task", pid);
250 tasks = opendir(filename);
254 while (!readdir_r(tasks, &dirent, &next) && next) {
256 pid = strtol(dirent.d_name, &end, 10);
262 write_output(&comm_ev, comm_ev.header.size);
271 fprintf(stderr, "couldn't get COMM and pgid, malformed %s\n",
276 static void pid_synthesize_mmap_samples(pid_t pid, pid_t tgid)
278 char filename[PATH_MAX];
281 snprintf(filename, sizeof(filename), "/proc/%d/maps", pid);
283 fp = fopen(filename, "r");
286 * We raced with a task exiting - just return:
289 fprintf(stderr, "couldn't open %s\n", filename);
293 char bf[BUFSIZ], *pbf = bf;
294 struct mmap_event mmap_ev = {
295 .header = { .type = PERF_RECORD_MMAP },
299 if (fgets(bf, sizeof(bf), fp) == NULL)
302 /* 00400000-0040c000 r-xp 00000000 fd:01 41038 /bin/cat */
303 n = hex2u64(pbf, &mmap_ev.start);
307 n = hex2u64(pbf, &mmap_ev.len);
311 if (*pbf == 'x') { /* vm_exec */
312 char *execname = strchr(bf, '/');
315 if (execname == NULL)
316 execname = strstr(bf, "[vdso]");
318 if (execname == NULL)
321 size = strlen(execname);
322 execname[size - 1] = '\0'; /* Remove \n */
323 memcpy(mmap_ev.filename, execname, size);
324 size = ALIGN(size, sizeof(u64));
325 mmap_ev.len -= mmap_ev.start;
326 mmap_ev.header.size = (sizeof(mmap_ev) -
327 (sizeof(mmap_ev.filename) - size));
331 write_output(&mmap_ev, mmap_ev.header.size);
338 static void synthesize_all(void)
341 struct dirent dirent, *next;
343 proc = opendir("/proc");
345 while (!readdir_r(proc, &dirent, &next) && next) {
349 pid = strtol(dirent.d_name, &end, 10);
350 if (*end) /* only interested in proper numerical dirents */
353 tgid = pid_synthesize_comm_event(pid, 1);
354 pid_synthesize_mmap_samples(pid, tgid);
362 static struct perf_header_attr *get_header_attr(struct perf_event_attr *a, int nr)
364 struct perf_header_attr *h_attr;
366 if (nr < header->attrs) {
367 h_attr = header->attr[nr];
369 h_attr = perf_header_attr__new(a);
370 perf_header__add_attr(header, h_attr);
376 static void create_counter(int counter, int cpu, pid_t pid)
378 char *filter = filters[counter];
379 struct perf_event_attr *attr = attrs + counter;
380 struct perf_header_attr *h_attr;
381 int track = !counter; /* only the first counter needs these */
390 attr->read_format = PERF_FORMAT_TOTAL_TIME_ENABLED |
391 PERF_FORMAT_TOTAL_TIME_RUNNING |
394 attr->sample_type |= PERF_SAMPLE_IP | PERF_SAMPLE_TID;
397 attr->sample_type |= PERF_SAMPLE_PERIOD;
399 attr->sample_freq = freq;
403 attr->sample_freq = 0;
406 attr->inherit_stat = 1;
409 attr->sample_type |= PERF_SAMPLE_ADDR;
412 attr->sample_type |= PERF_SAMPLE_CALLCHAIN;
415 attr->sample_type |= PERF_SAMPLE_TIME;
416 attr->sample_type |= PERF_SAMPLE_RAW;
417 attr->sample_type |= PERF_SAMPLE_CPU;
422 attr->inherit = (cpu < 0) && inherit;
426 fd[nr_cpu][counter] = sys_perf_event_open(attr, pid, cpu, group_fd, 0);
428 if (fd[nr_cpu][counter] < 0) {
432 die("Permission error - are you root?\n");
433 else if (err == ENODEV && profile_cpu != -1)
434 die("No such device - did you specify an out-of-range profile CPU?\n");
437 * If it's cycles then fall back to hrtimer
438 * based cpu-clock-tick sw counter, which
439 * is always available even if no PMU support:
441 if (attr->type == PERF_TYPE_HARDWARE
442 && attr->config == PERF_COUNT_HW_CPU_CYCLES) {
445 warning(" ... trying to fall back to cpu-clock-ticks\n");
446 attr->type = PERF_TYPE_SOFTWARE;
447 attr->config = PERF_COUNT_SW_CPU_CLOCK;
451 error("perfcounter syscall returned with %d (%s)\n",
452 fd[nr_cpu][counter], strerror(err));
453 die("No CONFIG_PERF_EVENTS=y kernel support configured?\n");
457 h_attr = get_header_attr(attr, counter);
460 if (memcmp(&h_attr->attr, attr, sizeof(*attr))) {
461 fprintf(stderr, "incompatible append\n");
466 if (read(fd[nr_cpu][counter], &read_data, sizeof(read_data)) == -1) {
467 perror("Unable to read perf file descriptor\n");
471 perf_header_attr__add_id(h_attr, read_data.id);
473 assert(fd[nr_cpu][counter] >= 0);
474 fcntl(fd[nr_cpu][counter], F_SETFL, O_NONBLOCK);
477 * First counter acts as the group leader:
479 if (group && group_fd == -1)
480 group_fd = fd[nr_cpu][counter];
481 if (multiplex && multiplex_fd == -1)
482 multiplex_fd = fd[nr_cpu][counter];
484 if (multiplex && fd[nr_cpu][counter] != multiplex_fd) {
486 ret = ioctl(fd[nr_cpu][counter], PERF_EVENT_IOC_SET_OUTPUT, multiplex_fd);
489 event_array[nr_poll].fd = fd[nr_cpu][counter];
490 event_array[nr_poll].events = POLLIN;
493 mmap_array[nr_cpu][counter].counter = counter;
494 mmap_array[nr_cpu][counter].prev = 0;
495 mmap_array[nr_cpu][counter].mask = mmap_pages*page_size - 1;
496 mmap_array[nr_cpu][counter].base = mmap(NULL, (mmap_pages+1)*page_size,
497 PROT_READ|PROT_WRITE, MAP_SHARED, fd[nr_cpu][counter], 0);
498 if (mmap_array[nr_cpu][counter].base == MAP_FAILED) {
499 error("failed to mmap with %d (%s)\n", errno, strerror(errno));
504 if (filter != NULL) {
505 ret = ioctl(fd[nr_cpu][counter],
506 PERF_EVENT_IOC_SET_FILTER, filter);
508 error("failed to set filter with %d (%s)\n", errno,
514 ioctl(fd[nr_cpu][counter], PERF_EVENT_IOC_ENABLE);
517 static void open_counters(int cpu, pid_t pid)
522 for (counter = 0; counter < nr_counters; counter++)
523 create_counter(counter, cpu, pid);
528 static void atexit_header(void)
530 header->data_size += bytes_written;
532 perf_header__write(header, output);
535 static int __cmd_record(int argc, const char **argv)
542 unsigned long waking = 0;
544 page_size = sysconf(_SC_PAGE_SIZE);
545 nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
546 assert(nr_cpus <= MAX_NR_CPUS);
547 assert(nr_cpus >= 0);
550 signal(SIGCHLD, sig_handler);
551 signal(SIGINT, sig_handler);
553 if (!stat(output_name, &st) && st.st_size) {
554 if (!force && !append_file) {
555 fprintf(stderr, "Error, output file %s exists, use -A to append or -f to overwrite.\n",
563 flags = O_CREAT|O_RDWR;
569 output = open(output_name, flags, S_IRUSR|S_IWUSR);
571 perror("failed to create output file");
576 header = perf_header__read(output);
578 header = perf_header__new();
581 perf_header__feat_trace_info(header);
583 for (i = 0; i < nr_counters; i++) {
584 if (attrs[i].sample_type & PERF_SAMPLE_RAW) {
585 perf_header__feat_trace_info(header);
591 atexit(atexit_header);
598 open_counters(profile_cpu, pid);
600 if (profile_cpu != -1) {
601 open_counters(profile_cpu, target_pid);
603 for (i = 0; i < nr_cpus; i++)
604 open_counters(i, target_pid);
609 perf_header__write(header, output);
612 pid_t tgid = pid_synthesize_comm_event(pid, 0);
613 pid_synthesize_mmap_samples(pid, tgid);
617 if (target_pid == -1 && argc) {
620 perror("failed to fork");
623 if (execvp(argv[0], (char **)argv)) {
633 struct sched_param param;
635 param.sched_priority = realtime_prio;
636 if (sched_setscheduler(0, SCHED_FIFO, ¶m)) {
637 pr_err("Could not set realtime priority.\n");
645 for (i = 0; i < nr_cpu; i++) {
646 for (counter = 0; counter < nr_counters; counter++) {
647 if (mmap_array[i][counter].base)
648 mmap_read(&mmap_array[i][counter]);
652 if (hits == samples) {
655 ret = poll(event_array, nr_poll, -1);
660 for (i = 0; i < nr_cpu; i++) {
661 for (counter = 0; counter < nr_counters; counter++)
662 ioctl(fd[i][counter], PERF_EVENT_IOC_DISABLE);
667 fprintf(stderr, "[ perf record: Woken up %ld times to write data ]\n", waking);
670 * Approximate RIP event size: 24 bytes.
673 "[ perf record: Captured and wrote %.3f MB %s (~%lld samples) ]\n",
674 (double)bytes_written / 1024.0 / 1024.0,
681 static const char * const record_usage[] = {
682 "perf record [<options>] [<command>]",
683 "perf record [<options>] -- <command> [<options>]",
687 static const struct option options[] = {
688 OPT_CALLBACK('e', "event", NULL, "event",
689 "event selector. use 'perf list' to list available events",
691 OPT_CALLBACK(0, "filter", NULL, "filter",
692 "event filter", parse_filter),
693 OPT_INTEGER('p', "pid", &target_pid,
694 "record events on existing pid"),
695 OPT_INTEGER('r', "realtime", &realtime_prio,
696 "collect data with this RT SCHED_FIFO priority"),
697 OPT_BOOLEAN('R', "raw-samples", &raw_samples,
698 "collect raw sample records from all opened counters"),
699 OPT_BOOLEAN('a', "all-cpus", &system_wide,
700 "system-wide collection from all CPUs"),
701 OPT_BOOLEAN('A', "append", &append_file,
702 "append to the output file to do incremental profiling"),
703 OPT_INTEGER('C', "profile_cpu", &profile_cpu,
704 "CPU to profile on"),
705 OPT_BOOLEAN('f', "force", &force,
706 "overwrite existing data file"),
707 OPT_LONG('c', "count", &default_interval,
708 "event period to sample"),
709 OPT_STRING('o', "output", &output_name, "file",
711 OPT_BOOLEAN('i', "inherit", &inherit,
712 "child tasks inherit counters"),
713 OPT_INTEGER('F', "freq", &freq,
714 "profile at this frequency"),
715 OPT_INTEGER('m', "mmap-pages", &mmap_pages,
716 "number of mmap data pages"),
717 OPT_BOOLEAN('g', "call-graph", &call_graph,
718 "do call-graph (stack chain/backtrace) recording"),
719 OPT_BOOLEAN('v', "verbose", &verbose,
720 "be more verbose (show counter open errors, etc)"),
721 OPT_BOOLEAN('s', "stat", &inherit_stat,
722 "per thread counts"),
723 OPT_BOOLEAN('d', "data", &sample_address,
725 OPT_BOOLEAN('n', "no-samples", &no_samples,
727 OPT_BOOLEAN('M', "multiplex", &multiplex,
728 "multiplex counter output in a single channel"),
732 int cmd_record(int argc, const char **argv, const char *prefix __used)
736 argc = parse_options(argc, argv, options, record_usage,
737 PARSE_OPT_STOP_AT_NON_OPTION);
738 if (!argc && target_pid == -1 && !system_wide)
739 usage_with_options(record_usage, options);
743 attrs[0].type = PERF_TYPE_HARDWARE;
744 attrs[0].config = PERF_COUNT_HW_CPU_CYCLES;
748 * User specified count overrides default frequency.
750 if (default_interval)
753 default_interval = freq;
755 fprintf(stderr, "frequency and count are zero, aborting\n");
759 for (counter = 0; counter < nr_counters; counter++) {
760 if (attrs[counter].sample_period)
763 attrs[counter].sample_period = default_interval;
766 return __cmd_record(argc, argv);