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"
20 #define ALIGN(x, a) __ALIGN_MASK(x, (typeof(x))(a)-1)
21 #define __ALIGN_MASK(x, mask) (((x)+(mask))&~(mask))
23 static int fd[MAX_NR_CPUS][MAX_COUNTERS];
25 static long default_interval = 100000;
27 static int nr_cpus = 0;
28 static unsigned int page_size;
29 static unsigned int mmap_pages = 128;
32 static const char *output_name = "perf.data";
34 static unsigned int realtime_prio = 0;
35 static int system_wide = 0;
36 static pid_t target_pid = -1;
37 static int inherit = 1;
39 static int append_file = 0;
40 static int call_graph = 0;
41 static int verbose = 0;
44 static struct timeval last_read;
45 static struct timeval this_read;
47 static __u64 bytes_written;
49 static struct pollfd event_array[MAX_NR_CPUS * MAX_COUNTERS];
55 struct perf_event_header header;
61 char filename[PATH_MAX];
65 struct perf_event_header header;
79 static struct mmap_data mmap_array[MAX_NR_CPUS][MAX_COUNTERS];
81 static unsigned long mmap_read_head(struct mmap_data *md)
83 struct perf_counter_mmap_page *pc = md->base;
92 static void mmap_write_tail(struct mmap_data *md, unsigned long tail)
94 struct perf_counter_mmap_page *pc = md->base;
97 * ensure all reads are done before we write the tail out.
100 pc->data_tail = tail;
103 static void mmap_read(struct mmap_data *md)
105 unsigned int head = mmap_read_head(md);
106 unsigned int old = md->prev;
107 unsigned char *data = md->base + page_size;
112 gettimeofday(&this_read, NULL);
115 * If we're further behind than half the buffer, there's a chance
116 * the writer will bite our tail and mess up the samples under us.
118 * If we somehow ended up ahead of the head, we got messed up.
120 * In either case, truncate and restart at head.
127 timersub(&this_read, &last_read, &iv);
128 msecs = iv.tv_sec*1000 + iv.tv_usec/1000;
130 fprintf(stderr, "WARNING: failed to keep up with mmap data."
131 " Last read %lu msecs ago.\n", msecs);
134 * head points to a known good entry, start there.
139 last_read = this_read;
146 if ((old & md->mask) + size != (head & md->mask)) {
147 buf = &data[old & md->mask];
148 size = md->mask + 1 - (old & md->mask);
152 int ret = write(output, buf, size);
155 die("failed to write");
160 bytes_written += ret;
164 buf = &data[old & md->mask];
169 int ret = write(output, buf, size);
172 die("failed to write");
177 bytes_written += ret;
181 mmap_write_tail(md, old);
184 static volatile int done = 0;
185 static volatile int signr = -1;
187 static void sig_handler(int sig)
193 static void sig_atexit(void)
198 signal(signr, SIG_DFL);
199 kill(getpid(), signr);
202 static void pid_synthesize_comm_event(pid_t pid, int full)
204 struct comm_event comm_ev;
205 char filename[PATH_MAX];
211 struct dirent dirent, *next;
213 snprintf(filename, sizeof(filename), "/proc/%d/stat", pid);
215 fd = open(filename, O_RDONLY);
218 * We raced with a task exiting - just return:
221 fprintf(stderr, "couldn't open %s\n", filename);
224 if (read(fd, bf, sizeof(bf)) < 0) {
225 fprintf(stderr, "couldn't read %s\n", filename);
230 /* 9027 (cat) R 6747 9027 6747 34816 9027 ... */
231 memset(&comm_ev, 0, sizeof(comm_ev));
232 field = strchr(bf, '(');
235 sep = strchr(++field, ')');
239 memcpy(comm_ev.comm, field, size++);
242 comm_ev.header.type = PERF_EVENT_COMM;
243 size = ALIGN(size, sizeof(__u64));
244 comm_ev.header.size = sizeof(comm_ev) - (sizeof(comm_ev.comm) - size);
249 ret = write(output, &comm_ev, comm_ev.header.size);
251 perror("failed to write");
257 snprintf(filename, sizeof(filename), "/proc/%d/task", pid);
259 tasks = opendir(filename);
260 while (!readdir_r(tasks, &dirent, &next) && next) {
262 pid = strtol(dirent.d_name, &end, 10);
268 ret = write(output, &comm_ev, comm_ev.header.size);
270 perror("failed to write");
278 fprintf(stderr, "couldn't get COMM and pgid, malformed %s\n",
283 static void pid_synthesize_mmap_samples(pid_t pid)
285 char filename[PATH_MAX];
288 snprintf(filename, sizeof(filename), "/proc/%d/maps", pid);
290 fp = fopen(filename, "r");
293 * We raced with a task exiting - just return:
296 fprintf(stderr, "couldn't open %s\n", filename);
300 char bf[BUFSIZ], *pbf = bf;
301 struct mmap_event mmap_ev = {
302 .header.type = PERF_EVENT_MMAP,
306 if (fgets(bf, sizeof(bf), fp) == NULL)
309 /* 00400000-0040c000 r-xp 00000000 fd:01 41038 /bin/cat */
310 n = hex2u64(pbf, &mmap_ev.start);
314 n = hex2u64(pbf, &mmap_ev.len);
318 if (*pbf == 'x') { /* vm_exec */
319 char *execname = strrchr(bf, ' ');
321 if (execname == NULL || execname[1] != '/')
325 size = strlen(execname);
326 execname[size - 1] = '\0'; /* Remove \n */
327 memcpy(mmap_ev.filename, execname, size);
328 size = ALIGN(size, sizeof(__u64));
329 mmap_ev.len -= mmap_ev.start;
330 mmap_ev.header.size = (sizeof(mmap_ev) -
331 (sizeof(mmap_ev.filename) - size));
335 if (write(output, &mmap_ev, mmap_ev.header.size) < 0) {
336 perror("failed to write");
345 static void synthesize_samples(void)
348 struct dirent dirent, *next;
350 proc = opendir("/proc");
352 while (!readdir_r(proc, &dirent, &next) && next) {
356 pid = strtol(dirent.d_name, &end, 10);
357 if (*end) /* only interested in proper numerical dirents */
360 pid_synthesize_comm_event(pid, 1);
361 pid_synthesize_mmap_samples(pid);
369 static void create_counter(int counter, int cpu, pid_t pid)
371 struct perf_counter_attr *attr = attrs + counter;
374 attr->sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_TID;
377 attr->sample_type |= PERF_SAMPLE_PERIOD;
379 attr->sample_freq = freq;
383 attr->sample_type |= PERF_SAMPLE_CALLCHAIN;
387 attr->inherit = (cpu < 0) && inherit;
390 track = 0; /* only the first counter needs these */
393 fd[nr_cpu][counter] = sys_perf_counter_open(attr, pid, cpu, group_fd, 0);
395 if (fd[nr_cpu][counter] < 0) {
399 die("Permission error - are you root?\n");
402 * If it's cycles then fall back to hrtimer
403 * based cpu-clock-tick sw counter, which
404 * is always available even if no PMU support:
406 if (attr->type == PERF_TYPE_HARDWARE
407 && attr->config == PERF_COUNT_HW_CPU_CYCLES) {
410 warning(" ... trying to fall back to cpu-clock-ticks\n");
411 attr->type = PERF_TYPE_SOFTWARE;
412 attr->config = PERF_COUNT_SW_CPU_CLOCK;
416 error("perfcounter syscall returned with %d (%s)\n",
417 fd[nr_cpu][counter], strerror(err));
418 die("No CONFIG_PERF_COUNTERS=y kernel support configured?\n");
422 assert(fd[nr_cpu][counter] >= 0);
423 fcntl(fd[nr_cpu][counter], F_SETFL, O_NONBLOCK);
426 * First counter acts as the group leader:
428 if (group && group_fd == -1)
429 group_fd = fd[nr_cpu][counter];
431 event_array[nr_poll].fd = fd[nr_cpu][counter];
432 event_array[nr_poll].events = POLLIN;
435 mmap_array[nr_cpu][counter].counter = counter;
436 mmap_array[nr_cpu][counter].prev = 0;
437 mmap_array[nr_cpu][counter].mask = mmap_pages*page_size - 1;
438 mmap_array[nr_cpu][counter].base = mmap(NULL, (mmap_pages+1)*page_size,
439 PROT_READ|PROT_WRITE, MAP_SHARED, fd[nr_cpu][counter], 0);
440 if (mmap_array[nr_cpu][counter].base == MAP_FAILED) {
441 error("failed to mmap with %d (%s)\n", errno, strerror(errno));
445 ioctl(fd[nr_cpu][counter], PERF_COUNTER_IOC_ENABLE);
448 static void open_counters(int cpu, pid_t pid)
453 pid_synthesize_comm_event(pid, 0);
454 pid_synthesize_mmap_samples(pid);
458 for (counter = 0; counter < nr_counters; counter++)
459 create_counter(counter, cpu, pid);
464 static int __cmd_record(int argc, const char **argv)
472 page_size = sysconf(_SC_PAGE_SIZE);
473 nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
474 assert(nr_cpus <= MAX_NR_CPUS);
475 assert(nr_cpus >= 0);
477 if (!stat(output_name, &st) && !force && !append_file) {
478 fprintf(stderr, "Error, output file %s exists, use -A to append or -f to overwrite.\n",
483 flags = O_CREAT|O_RDWR;
489 output = open(output_name, flags, S_IRUSR|S_IWUSR);
491 perror("failed to create output file");
496 open_counters(-1, target_pid != -1 ? target_pid : getpid());
497 } else for (i = 0; i < nr_cpus; i++)
498 open_counters(i, target_pid);
501 signal(SIGCHLD, sig_handler);
502 signal(SIGINT, sig_handler);
504 if (target_pid == -1 && argc) {
507 perror("failed to fork");
510 if (execvp(argv[0], (char **)argv)) {
518 struct sched_param param;
520 param.sched_priority = realtime_prio;
521 if (sched_setscheduler(0, SCHED_FIFO, ¶m)) {
522 printf("Could not set realtime priority.\n");
528 synthesize_samples();
533 for (i = 0; i < nr_cpu; i++) {
534 for (counter = 0; counter < nr_counters; counter++)
535 mmap_read(&mmap_array[i][counter]);
539 ret = poll(event_array, nr_poll, 100);
543 * Approximate RIP event size: 24 bytes.
546 "[ perf record: Captured and wrote %.3f MB %s (~%lld samples) ]\n",
547 (double)bytes_written / 1024.0 / 1024.0,
554 static const char * const record_usage[] = {
555 "perf record [<options>] [<command>]",
556 "perf record [<options>] -- <command> [<options>]",
560 static const struct option options[] = {
561 OPT_CALLBACK('e', "event", NULL, "event",
562 "event selector. use 'perf list' to list available events",
564 OPT_INTEGER('p', "pid", &target_pid,
565 "record events on existing pid"),
566 OPT_INTEGER('r', "realtime", &realtime_prio,
567 "collect data with this RT SCHED_FIFO priority"),
568 OPT_BOOLEAN('a', "all-cpus", &system_wide,
569 "system-wide collection from all CPUs"),
570 OPT_BOOLEAN('A', "append", &append_file,
571 "append to the output file to do incremental profiling"),
572 OPT_BOOLEAN('f', "force", &force,
573 "overwrite existing data file"),
574 OPT_LONG('c', "count", &default_interval,
575 "event period to sample"),
576 OPT_STRING('o', "output", &output_name, "file",
578 OPT_BOOLEAN('i', "inherit", &inherit,
579 "child tasks inherit counters"),
580 OPT_INTEGER('F', "freq", &freq,
581 "profile at this frequency"),
582 OPT_INTEGER('m', "mmap-pages", &mmap_pages,
583 "number of mmap data pages"),
584 OPT_BOOLEAN('g', "call-graph", &call_graph,
585 "do call-graph (stack chain/backtrace) recording"),
586 OPT_BOOLEAN('v', "verbose", &verbose,
587 "be more verbose (show counter open errors, etc)"),
591 int cmd_record(int argc, const char **argv, const char *prefix)
595 argc = parse_options(argc, argv, options, record_usage, 0);
596 if (!argc && target_pid == -1 && !system_wide)
597 usage_with_options(record_usage, options);
601 attrs[0].type = PERF_TYPE_HARDWARE;
602 attrs[0].config = PERF_COUNT_HW_CPU_CYCLES;
605 for (counter = 0; counter < nr_counters; counter++) {
606 if (attrs[counter].sample_period)
609 attrs[counter].sample_period = default_interval;
612 return __cmd_record(argc, argv);