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 #define ALIGN(x, a) __ALIGN_MASK(x, (typeof(x))(a)-1)
25 #define __ALIGN_MASK(x, mask) (((x)+(mask))&~(mask))
27 static int fd[MAX_NR_CPUS][MAX_COUNTERS];
29 static long default_interval = 0;
31 static int nr_cpus = 0;
32 static unsigned int page_size;
33 static unsigned int mmap_pages = 128;
34 static int freq = 1000;
36 static const char *output_name = "perf.data";
38 static unsigned int realtime_prio = 0;
39 static int raw_samples = 0;
40 static int system_wide = 0;
41 static int profile_cpu = -1;
42 static pid_t target_pid = -1;
43 static pid_t child_pid = -1;
44 static int inherit = 1;
46 static int append_file = 0;
47 static int call_graph = 0;
48 static int inherit_stat = 0;
49 static int no_samples = 0;
50 static int sample_address = 0;
51 static int multiplex = 0;
52 static int multiplex_fd = -1;
54 static long samples = 0;
55 static struct timeval last_read;
56 static struct timeval this_read;
58 static u64 bytes_written = 0;
60 static struct pollfd event_array[MAX_NR_CPUS * MAX_COUNTERS];
62 static int nr_poll = 0;
63 static int nr_cpu = 0;
65 static int file_new = 1;
67 struct perf_header *header = NULL;
76 static struct mmap_data mmap_array[MAX_NR_CPUS][MAX_COUNTERS];
78 static unsigned long mmap_read_head(struct mmap_data *md)
80 struct perf_event_mmap_page *pc = md->base;
89 static void mmap_write_tail(struct mmap_data *md, unsigned long tail)
91 struct perf_event_mmap_page *pc = md->base;
94 * ensure all reads are done before we write the tail out.
100 static void write_output(void *buf, size_t size)
103 int ret = write(output, buf, size);
106 die("failed to write");
111 bytes_written += ret;
115 static void mmap_read(struct mmap_data *md)
117 unsigned int head = mmap_read_head(md);
118 unsigned int old = md->prev;
119 unsigned char *data = md->base + page_size;
124 gettimeofday(&this_read, NULL);
127 * If we're further behind than half the buffer, there's a chance
128 * the writer will bite our tail and mess up the samples under us.
130 * If we somehow ended up ahead of the head, we got messed up.
132 * In either case, truncate and restart at head.
139 timersub(&this_read, &last_read, &iv);
140 msecs = iv.tv_sec*1000 + iv.tv_usec/1000;
142 fprintf(stderr, "WARNING: failed to keep up with mmap data."
143 " Last read %lu msecs ago.\n", msecs);
146 * head points to a known good entry, start there.
151 last_read = this_read;
158 if ((old & md->mask) + size != (head & md->mask)) {
159 buf = &data[old & md->mask];
160 size = md->mask + 1 - (old & md->mask);
163 write_output(buf, size);
166 buf = &data[old & md->mask];
170 write_output(buf, size);
173 mmap_write_tail(md, old);
176 static volatile int done = 0;
177 static volatile int signr = -1;
179 static void sig_handler(int sig)
185 static void sig_atexit(void)
188 kill(child_pid, SIGTERM);
193 signal(signr, SIG_DFL);
194 kill(getpid(), signr);
197 static pid_t pid_synthesize_comm_event(pid_t pid, int full)
199 struct comm_event comm_ev;
200 char filename[PATH_MAX];
205 struct dirent dirent, *next;
208 snprintf(filename, sizeof(filename), "/proc/%d/status", pid);
210 fp = fopen(filename, "r");
213 * We raced with a task exiting - just return:
216 fprintf(stderr, "couldn't open %s\n", filename);
220 memset(&comm_ev, 0, sizeof(comm_ev));
221 while (!comm_ev.comm[0] || !comm_ev.pid) {
222 if (fgets(bf, sizeof(bf), fp) == NULL)
225 if (memcmp(bf, "Name:", 5) == 0) {
227 while (*name && isspace(*name))
229 size = strlen(name) - 1;
230 memcpy(comm_ev.comm, name, size++);
231 } else if (memcmp(bf, "Tgid:", 5) == 0) {
232 char *tgids = bf + 5;
233 while (*tgids && isspace(*tgids))
235 tgid = comm_ev.pid = atoi(tgids);
239 comm_ev.header.type = PERF_RECORD_COMM;
240 size = ALIGN(size, sizeof(u64));
241 comm_ev.header.size = sizeof(comm_ev) - (sizeof(comm_ev.comm) - size);
246 write_output(&comm_ev, comm_ev.header.size);
250 snprintf(filename, sizeof(filename), "/proc/%d/task", pid);
252 tasks = opendir(filename);
253 while (!readdir_r(tasks, &dirent, &next) && next) {
255 pid = strtol(dirent.d_name, &end, 10);
261 write_output(&comm_ev, comm_ev.header.size);
270 fprintf(stderr, "couldn't get COMM and pgid, malformed %s\n",
275 static void pid_synthesize_mmap_samples(pid_t pid, pid_t tgid)
277 char filename[PATH_MAX];
280 snprintf(filename, sizeof(filename), "/proc/%d/maps", pid);
282 fp = fopen(filename, "r");
285 * We raced with a task exiting - just return:
288 fprintf(stderr, "couldn't open %s\n", filename);
292 char bf[BUFSIZ], *pbf = bf;
293 struct mmap_event mmap_ev = {
294 .header = { .type = PERF_RECORD_MMAP },
298 if (fgets(bf, sizeof(bf), fp) == NULL)
301 /* 00400000-0040c000 r-xp 00000000 fd:01 41038 /bin/cat */
302 n = hex2u64(pbf, &mmap_ev.start);
306 n = hex2u64(pbf, &mmap_ev.len);
310 if (*pbf == 'x') { /* vm_exec */
311 char *execname = strchr(bf, '/');
314 if (execname == NULL)
315 execname = strstr(bf, "[vdso]");
317 if (execname == NULL)
320 size = strlen(execname);
321 execname[size - 1] = '\0'; /* Remove \n */
322 memcpy(mmap_ev.filename, execname, size);
323 size = ALIGN(size, sizeof(u64));
324 mmap_ev.len -= mmap_ev.start;
325 mmap_ev.header.size = (sizeof(mmap_ev) -
326 (sizeof(mmap_ev.filename) - size));
330 write_output(&mmap_ev, mmap_ev.header.size);
337 static void synthesize_all(void)
340 struct dirent dirent, *next;
342 proc = opendir("/proc");
344 while (!readdir_r(proc, &dirent, &next) && next) {
348 pid = strtol(dirent.d_name, &end, 10);
349 if (*end) /* only interested in proper numerical dirents */
352 tgid = pid_synthesize_comm_event(pid, 1);
353 pid_synthesize_mmap_samples(pid, tgid);
361 static struct perf_header_attr *get_header_attr(struct perf_event_attr *a, int nr)
363 struct perf_header_attr *h_attr;
365 if (nr < header->attrs) {
366 h_attr = header->attr[nr];
368 h_attr = perf_header_attr__new(a);
369 perf_header__add_attr(header, h_attr);
375 static void create_counter(int counter, int cpu, pid_t pid)
377 struct perf_event_attr *attr = attrs + counter;
378 struct perf_header_attr *h_attr;
379 int track = !counter; /* only the first counter needs these */
387 attr->read_format = PERF_FORMAT_TOTAL_TIME_ENABLED |
388 PERF_FORMAT_TOTAL_TIME_RUNNING |
391 attr->sample_type |= PERF_SAMPLE_IP | PERF_SAMPLE_TID;
394 attr->sample_type |= PERF_SAMPLE_PERIOD;
396 attr->sample_freq = freq;
400 attr->sample_freq = 0;
403 attr->inherit_stat = 1;
406 attr->sample_type |= PERF_SAMPLE_ADDR;
409 attr->sample_type |= PERF_SAMPLE_CALLCHAIN;
412 attr->sample_type |= PERF_SAMPLE_TIME;
413 attr->sample_type |= PERF_SAMPLE_RAW;
414 attr->sample_type |= PERF_SAMPLE_CPU;
419 attr->inherit = (cpu < 0) && inherit;
423 fd[nr_cpu][counter] = sys_perf_event_open(attr, pid, cpu, group_fd, 0);
425 if (fd[nr_cpu][counter] < 0) {
429 die("Permission error - are you root?\n");
430 else if (err == ENODEV && profile_cpu != -1)
431 die("No such device - did you specify an out-of-range profile CPU?\n");
434 * If it's cycles then fall back to hrtimer
435 * based cpu-clock-tick sw counter, which
436 * is always available even if no PMU support:
438 if (attr->type == PERF_TYPE_HARDWARE
439 && attr->config == PERF_COUNT_HW_CPU_CYCLES) {
442 warning(" ... trying to fall back to cpu-clock-ticks\n");
443 attr->type = PERF_TYPE_SOFTWARE;
444 attr->config = PERF_COUNT_SW_CPU_CLOCK;
448 error("perfcounter syscall returned with %d (%s)\n",
449 fd[nr_cpu][counter], strerror(err));
450 die("No CONFIG_PERF_EVENTS=y kernel support configured?\n");
454 h_attr = get_header_attr(attr, counter);
457 if (memcmp(&h_attr->attr, attr, sizeof(*attr))) {
458 fprintf(stderr, "incompatible append\n");
463 if (read(fd[nr_cpu][counter], &read_data, sizeof(read_data)) == -1) {
464 perror("Unable to read perf file descriptor\n");
468 perf_header_attr__add_id(h_attr, read_data.id);
470 assert(fd[nr_cpu][counter] >= 0);
471 fcntl(fd[nr_cpu][counter], F_SETFL, O_NONBLOCK);
474 * First counter acts as the group leader:
476 if (group && group_fd == -1)
477 group_fd = fd[nr_cpu][counter];
478 if (multiplex && multiplex_fd == -1)
479 multiplex_fd = fd[nr_cpu][counter];
481 if (multiplex && fd[nr_cpu][counter] != multiplex_fd) {
484 ret = ioctl(fd[nr_cpu][counter], PERF_EVENT_IOC_SET_OUTPUT, multiplex_fd);
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));
502 ioctl(fd[nr_cpu][counter], PERF_EVENT_IOC_ENABLE);
505 static void open_counters(int cpu, pid_t pid)
510 for (counter = 0; counter < nr_counters; counter++)
511 create_counter(counter, cpu, pid);
516 static void atexit_header(void)
518 header->data_size += bytes_written;
520 perf_header__write(header, output);
523 static int __cmd_record(int argc, const char **argv)
530 unsigned long waking = 0;
532 page_size = sysconf(_SC_PAGE_SIZE);
533 nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
534 assert(nr_cpus <= MAX_NR_CPUS);
535 assert(nr_cpus >= 0);
538 signal(SIGCHLD, sig_handler);
539 signal(SIGINT, sig_handler);
541 if (!stat(output_name, &st) && st.st_size) {
542 if (!force && !append_file) {
543 fprintf(stderr, "Error, output file %s exists, use -A to append or -f to overwrite.\n",
551 flags = O_CREAT|O_RDWR;
557 output = open(output_name, flags, S_IRUSR|S_IWUSR);
559 perror("failed to create output file");
564 header = perf_header__read(output);
566 header = perf_header__new();
569 perf_header__set_trace_info();
571 for (i = 0; i < nr_counters; i++) {
572 if (attrs[i].sample_type & PERF_SAMPLE_RAW) {
573 perf_header__set_trace_info();
579 atexit(atexit_header);
586 open_counters(profile_cpu, pid);
588 if (profile_cpu != -1) {
589 open_counters(profile_cpu, target_pid);
591 for (i = 0; i < nr_cpus; i++)
592 open_counters(i, target_pid);
597 perf_header__write(header, output);
600 pid_t tgid = pid_synthesize_comm_event(pid, 0);
601 pid_synthesize_mmap_samples(pid, tgid);
605 if (target_pid == -1 && argc) {
608 perror("failed to fork");
611 if (execvp(argv[0], (char **)argv)) {
621 struct sched_param param;
623 param.sched_priority = realtime_prio;
624 if (sched_setscheduler(0, SCHED_FIFO, ¶m)) {
625 printf("Could not set realtime priority.\n");
633 for (i = 0; i < nr_cpu; i++) {
634 for (counter = 0; counter < nr_counters; counter++) {
635 if (mmap_array[i][counter].base)
636 mmap_read(&mmap_array[i][counter]);
640 if (hits == samples) {
643 ret = poll(event_array, nr_poll, -1);
648 for (i = 0; i < nr_cpu; i++) {
649 for (counter = 0; counter < nr_counters; counter++)
650 ioctl(fd[i][counter], PERF_EVENT_IOC_DISABLE);
655 fprintf(stderr, "[ perf record: Woken up %ld times to write data ]\n", waking);
658 * Approximate RIP event size: 24 bytes.
661 "[ perf record: Captured and wrote %.3f MB %s (~%lld samples) ]\n",
662 (double)bytes_written / 1024.0 / 1024.0,
669 static const char * const record_usage[] = {
670 "perf record [<options>] [<command>]",
671 "perf record [<options>] -- <command> [<options>]",
675 static const struct option options[] = {
676 OPT_CALLBACK('e', "event", NULL, "event",
677 "event selector. use 'perf list' to list available events",
679 OPT_INTEGER('p', "pid", &target_pid,
680 "record events on existing pid"),
681 OPT_INTEGER('r', "realtime", &realtime_prio,
682 "collect data with this RT SCHED_FIFO priority"),
683 OPT_BOOLEAN('R', "raw-samples", &raw_samples,
684 "collect raw sample records from all opened counters"),
685 OPT_BOOLEAN('a', "all-cpus", &system_wide,
686 "system-wide collection from all CPUs"),
687 OPT_BOOLEAN('A', "append", &append_file,
688 "append to the output file to do incremental profiling"),
689 OPT_INTEGER('C', "profile_cpu", &profile_cpu,
690 "CPU to profile on"),
691 OPT_BOOLEAN('f', "force", &force,
692 "overwrite existing data file"),
693 OPT_LONG('c', "count", &default_interval,
694 "event period to sample"),
695 OPT_STRING('o', "output", &output_name, "file",
697 OPT_BOOLEAN('i', "inherit", &inherit,
698 "child tasks inherit counters"),
699 OPT_INTEGER('F', "freq", &freq,
700 "profile at this frequency"),
701 OPT_INTEGER('m', "mmap-pages", &mmap_pages,
702 "number of mmap data pages"),
703 OPT_BOOLEAN('g', "call-graph", &call_graph,
704 "do call-graph (stack chain/backtrace) recording"),
705 OPT_BOOLEAN('v', "verbose", &verbose,
706 "be more verbose (show counter open errors, etc)"),
707 OPT_BOOLEAN('s', "stat", &inherit_stat,
708 "per thread counts"),
709 OPT_BOOLEAN('d', "data", &sample_address,
711 OPT_BOOLEAN('n', "no-samples", &no_samples,
713 OPT_BOOLEAN('M', "multiplex", &multiplex,
714 "multiplex counter output in a single channel"),
718 int cmd_record(int argc, const char **argv, const char *prefix __used)
722 argc = parse_options(argc, argv, options, record_usage,
723 PARSE_OPT_STOP_AT_NON_OPTION);
724 if (!argc && target_pid == -1 && !system_wide)
725 usage_with_options(record_usage, options);
729 attrs[0].type = PERF_TYPE_HARDWARE;
730 attrs[0].config = PERF_COUNT_HW_CPU_CYCLES;
734 * User specified count overrides default frequency.
736 if (default_interval)
739 default_interval = freq;
741 fprintf(stderr, "frequency and count are zero, aborting\n");
745 for (counter = 0; counter < nr_counters; counter++) {
746 if (attrs[counter].sample_period)
749 attrs[counter].sample_period = default_interval;
752 return __cmd_record(argc, argv);