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 verbose
= 0;
44 static int inherit_stat
= 0;
45 static int no_samples
= 0;
46 static int sample_address
= 0;
49 static struct timeval last_read
;
50 static struct timeval this_read
;
52 static u64 bytes_written
;
54 static struct pollfd event_array
[MAX_NR_CPUS
* MAX_COUNTERS
];
59 static int file_new
= 1;
61 struct perf_header
*header
;
64 struct perf_event_header header
;
70 char filename
[PATH_MAX
];
74 struct perf_event_header header
;
88 static struct mmap_data mmap_array
[MAX_NR_CPUS
][MAX_COUNTERS
];
90 static unsigned long mmap_read_head(struct mmap_data
*md
)
92 struct perf_counter_mmap_page
*pc
= md
->base
;
101 static void mmap_write_tail(struct mmap_data
*md
, unsigned long tail
)
103 struct perf_counter_mmap_page
*pc
= md
->base
;
106 * ensure all reads are done before we write the tail out.
109 pc
->data_tail
= tail
;
112 static void write_output(void *buf
, size_t size
)
115 int ret
= write(output
, buf
, size
);
118 die("failed to write");
123 bytes_written
+= ret
;
127 static void mmap_read(struct mmap_data
*md
)
129 unsigned int head
= mmap_read_head(md
);
130 unsigned int old
= md
->prev
;
131 unsigned char *data
= md
->base
+ page_size
;
136 gettimeofday(&this_read
, NULL
);
139 * If we're further behind than half the buffer, there's a chance
140 * the writer will bite our tail and mess up the samples under us.
142 * If we somehow ended up ahead of the head, we got messed up.
144 * In either case, truncate and restart at head.
151 timersub(&this_read
, &last_read
, &iv
);
152 msecs
= iv
.tv_sec
*1000 + iv
.tv_usec
/1000;
154 fprintf(stderr
, "WARNING: failed to keep up with mmap data."
155 " Last read %lu msecs ago.\n", msecs
);
158 * head points to a known good entry, start there.
163 last_read
= this_read
;
170 if ((old
& md
->mask
) + size
!= (head
& md
->mask
)) {
171 buf
= &data
[old
& md
->mask
];
172 size
= md
->mask
+ 1 - (old
& md
->mask
);
175 write_output(buf
, size
);
178 buf
= &data
[old
& md
->mask
];
182 write_output(buf
, size
);
185 mmap_write_tail(md
, old
);
188 static volatile int done
= 0;
189 static volatile int signr
= -1;
191 static void sig_handler(int sig
)
197 static void sig_atexit(void)
202 signal(signr
, SIG_DFL
);
203 kill(getpid(), signr
);
206 static void pid_synthesize_comm_event(pid_t pid
, int full
)
208 struct comm_event comm_ev
;
209 char filename
[PATH_MAX
];
215 struct dirent dirent
, *next
;
217 snprintf(filename
, sizeof(filename
), "/proc/%d/stat", pid
);
219 fd
= open(filename
, O_RDONLY
);
222 * We raced with a task exiting - just return:
225 fprintf(stderr
, "couldn't open %s\n", filename
);
228 if (read(fd
, bf
, sizeof(bf
)) < 0) {
229 fprintf(stderr
, "couldn't read %s\n", filename
);
234 /* 9027 (cat) R 6747 9027 6747 34816 9027 ... */
235 memset(&comm_ev
, 0, sizeof(comm_ev
));
236 field
= strchr(bf
, '(');
239 sep
= strchr(++field
, ')');
243 memcpy(comm_ev
.comm
, field
, size
++);
246 comm_ev
.header
.type
= PERF_EVENT_COMM
;
247 size
= ALIGN(size
, sizeof(u64
));
248 comm_ev
.header
.size
= sizeof(comm_ev
) - (sizeof(comm_ev
.comm
) - size
);
253 write_output(&comm_ev
, comm_ev
.header
.size
);
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 write_output(&comm_ev
, comm_ev
.header
.size
);
274 fprintf(stderr
, "couldn't get COMM and pgid, malformed %s\n",
279 static void pid_synthesize_mmap_samples(pid_t pid
)
281 char filename
[PATH_MAX
];
284 snprintf(filename
, sizeof(filename
), "/proc/%d/maps", pid
);
286 fp
= fopen(filename
, "r");
289 * We raced with a task exiting - just return:
292 fprintf(stderr
, "couldn't open %s\n", filename
);
296 char bf
[BUFSIZ
], *pbf
= bf
;
297 struct mmap_event mmap_ev
= {
298 .header
= { .type
= PERF_EVENT_MMAP
},
302 if (fgets(bf
, sizeof(bf
), fp
) == NULL
)
305 /* 00400000-0040c000 r-xp 00000000 fd:01 41038 /bin/cat */
306 n
= hex2u64(pbf
, &mmap_ev
.start
);
310 n
= hex2u64(pbf
, &mmap_ev
.len
);
314 if (*pbf
== 'x') { /* vm_exec */
315 char *execname
= strchr(bf
, '/');
318 if (execname
== NULL
)
319 execname
= strstr(bf
, "[vdso]");
321 if (execname
== NULL
)
324 size
= strlen(execname
);
325 execname
[size
- 1] = '\0'; /* Remove \n */
326 memcpy(mmap_ev
.filename
, execname
, size
);
327 size
= ALIGN(size
, sizeof(u64
));
328 mmap_ev
.len
-= mmap_ev
.start
;
329 mmap_ev
.header
.size
= (sizeof(mmap_ev
) -
330 (sizeof(mmap_ev
.filename
) - size
));
334 write_output(&mmap_ev
, mmap_ev
.header
.size
);
341 static void synthesize_all(void)
344 struct dirent dirent
, *next
;
346 proc
= opendir("/proc");
348 while (!readdir_r(proc
, &dirent
, &next
) && next
) {
352 pid
= strtol(dirent
.d_name
, &end
, 10);
353 if (*end
) /* only interested in proper numerical dirents */
356 pid_synthesize_comm_event(pid
, 1);
357 pid_synthesize_mmap_samples(pid
);
365 static struct perf_header_attr
*get_header_attr(struct perf_counter_attr
*a
, int nr
)
367 struct perf_header_attr
*h_attr
;
369 if (nr
< header
->attrs
) {
370 h_attr
= header
->attr
[nr
];
372 h_attr
= perf_header_attr__new(a
);
373 perf_header__add_attr(header
, h_attr
);
379 static void create_counter(int counter
, int cpu
, pid_t pid
)
381 struct perf_counter_attr
*attr
= attrs
+ counter
;
382 struct perf_header_attr
*h_attr
;
383 int track
= !counter
; /* only the first counter needs these */
391 attr
->read_format
= PERF_FORMAT_TOTAL_TIME_ENABLED
|
392 PERF_FORMAT_TOTAL_TIME_RUNNING
|
395 attr
->sample_type
= PERF_SAMPLE_IP
| PERF_SAMPLE_TID
;
398 attr
->sample_type
|= PERF_SAMPLE_PERIOD
;
400 attr
->sample_freq
= freq
;
404 attr
->sample_freq
= 0;
407 attr
->inherit_stat
= 1;
410 attr
->sample_type
|= PERF_SAMPLE_ADDR
;
413 attr
->sample_type
|= PERF_SAMPLE_CALLCHAIN
;
418 attr
->inherit
= (cpu
< 0) && inherit
;
422 fd
[nr_cpu
][counter
] = sys_perf_counter_open(attr
, pid
, cpu
, group_fd
, 0);
424 if (fd
[nr_cpu
][counter
] < 0) {
428 die("Permission error - are you root?\n");
431 * If it's cycles then fall back to hrtimer
432 * based cpu-clock-tick sw counter, which
433 * is always available even if no PMU support:
435 if (attr
->type
== PERF_TYPE_HARDWARE
436 && attr
->config
== PERF_COUNT_HW_CPU_CYCLES
) {
439 warning(" ... trying to fall back to cpu-clock-ticks\n");
440 attr
->type
= PERF_TYPE_SOFTWARE
;
441 attr
->config
= PERF_COUNT_SW_CPU_CLOCK
;
445 error("perfcounter syscall returned with %d (%s)\n",
446 fd
[nr_cpu
][counter
], strerror(err
));
447 die("No CONFIG_PERF_COUNTERS=y kernel support configured?\n");
451 h_attr
= get_header_attr(attr
, counter
);
454 if (memcmp(&h_attr
->attr
, attr
, sizeof(*attr
))) {
455 fprintf(stderr
, "incompatible append\n");
460 if (read(fd
[nr_cpu
][counter
], &read_data
, sizeof(read_data
)) == -1) {
461 perror("Unable to read perf file descriptor\n");
465 perf_header_attr__add_id(h_attr
, read_data
.id
);
467 assert(fd
[nr_cpu
][counter
] >= 0);
468 fcntl(fd
[nr_cpu
][counter
], F_SETFL
, O_NONBLOCK
);
471 * First counter acts as the group leader:
473 if (group
&& group_fd
== -1)
474 group_fd
= fd
[nr_cpu
][counter
];
476 event_array
[nr_poll
].fd
= fd
[nr_cpu
][counter
];
477 event_array
[nr_poll
].events
= POLLIN
;
480 mmap_array
[nr_cpu
][counter
].counter
= counter
;
481 mmap_array
[nr_cpu
][counter
].prev
= 0;
482 mmap_array
[nr_cpu
][counter
].mask
= mmap_pages
*page_size
- 1;
483 mmap_array
[nr_cpu
][counter
].base
= mmap(NULL
, (mmap_pages
+1)*page_size
,
484 PROT_READ
|PROT_WRITE
, MAP_SHARED
, fd
[nr_cpu
][counter
], 0);
485 if (mmap_array
[nr_cpu
][counter
].base
== MAP_FAILED
) {
486 error("failed to mmap with %d (%s)\n", errno
, strerror(errno
));
490 ioctl(fd
[nr_cpu
][counter
], PERF_COUNTER_IOC_ENABLE
);
493 static void open_counters(int cpu
, pid_t pid
)
498 for (counter
= 0; counter
< nr_counters
; counter
++)
499 create_counter(counter
, cpu
, pid
);
504 static void atexit_header(void)
506 header
->data_size
+= bytes_written
;
508 perf_header__write(header
, output
);
511 static int __cmd_record(int argc
, const char **argv
)
519 page_size
= sysconf(_SC_PAGE_SIZE
);
520 nr_cpus
= sysconf(_SC_NPROCESSORS_ONLN
);
521 assert(nr_cpus
<= MAX_NR_CPUS
);
522 assert(nr_cpus
>= 0);
525 signal(SIGCHLD
, sig_handler
);
526 signal(SIGINT
, sig_handler
);
528 if (!stat(output_name
, &st
) && !force
&& !append_file
) {
529 fprintf(stderr
, "Error, output file %s exists, use -A to append or -f to overwrite.\n",
534 flags
= O_CREAT
|O_RDWR
;
540 output
= open(output_name
, flags
, S_IRUSR
|S_IWUSR
);
542 perror("failed to create output file");
547 header
= perf_header__read(output
);
549 header
= perf_header__new();
551 atexit(atexit_header
);
558 open_counters(-1, pid
);
559 } else for (i
= 0; i
< nr_cpus
; i
++)
560 open_counters(i
, target_pid
);
563 perf_header__write(header
, output
);
566 pid_synthesize_comm_event(pid
, 0);
567 pid_synthesize_mmap_samples(pid
);
571 if (target_pid
== -1 && argc
) {
574 perror("failed to fork");
577 if (execvp(argv
[0], (char **)argv
)) {
585 struct sched_param param
;
587 param
.sched_priority
= realtime_prio
;
588 if (sched_setscheduler(0, SCHED_FIFO
, ¶m
)) {
589 printf("Could not set realtime priority.\n");
597 for (i
= 0; i
< nr_cpu
; i
++) {
598 for (counter
= 0; counter
< nr_counters
; counter
++)
599 mmap_read(&mmap_array
[i
][counter
]);
602 if (hits
== samples
) {
605 ret
= poll(event_array
, nr_poll
, 100);
610 * Approximate RIP event size: 24 bytes.
613 "[ perf record: Captured and wrote %.3f MB %s (~%lld samples) ]\n",
614 (double)bytes_written
/ 1024.0 / 1024.0,
621 static const char * const record_usage
[] = {
622 "perf record [<options>] [<command>]",
623 "perf record [<options>] -- <command> [<options>]",
627 static const struct option options
[] = {
628 OPT_CALLBACK('e', "event", NULL
, "event",
629 "event selector. use 'perf list' to list available events",
631 OPT_INTEGER('p', "pid", &target_pid
,
632 "record events on existing pid"),
633 OPT_INTEGER('r', "realtime", &realtime_prio
,
634 "collect data with this RT SCHED_FIFO priority"),
635 OPT_BOOLEAN('a', "all-cpus", &system_wide
,
636 "system-wide collection from all CPUs"),
637 OPT_BOOLEAN('A', "append", &append_file
,
638 "append to the output file to do incremental profiling"),
639 OPT_BOOLEAN('f', "force", &force
,
640 "overwrite existing data file"),
641 OPT_LONG('c', "count", &default_interval
,
642 "event period to sample"),
643 OPT_STRING('o', "output", &output_name
, "file",
645 OPT_BOOLEAN('i', "inherit", &inherit
,
646 "child tasks inherit counters"),
647 OPT_INTEGER('F', "freq", &freq
,
648 "profile at this frequency"),
649 OPT_INTEGER('m', "mmap-pages", &mmap_pages
,
650 "number of mmap data pages"),
651 OPT_BOOLEAN('g', "call-graph", &call_graph
,
652 "do call-graph (stack chain/backtrace) recording"),
653 OPT_BOOLEAN('v', "verbose", &verbose
,
654 "be more verbose (show counter open errors, etc)"),
655 OPT_BOOLEAN('s', "stat", &inherit_stat
,
656 "per thread counts"),
657 OPT_BOOLEAN('d', "data", &sample_address
,
659 OPT_BOOLEAN('n', "no-samples", &no_samples
,
664 int cmd_record(int argc
, const char **argv
, const char *prefix __used
)
668 argc
= parse_options(argc
, argv
, options
, record_usage
,
669 PARSE_OPT_STOP_AT_NON_OPTION
);
670 if (!argc
&& target_pid
== -1 && !system_wide
)
671 usage_with_options(record_usage
, options
);
675 attrs
[0].type
= PERF_TYPE_HARDWARE
;
676 attrs
[0].config
= PERF_COUNT_HW_CPU_CYCLES
;
679 for (counter
= 0; counter
< nr_counters
; counter
++) {
680 if (attrs
[counter
].sample_period
)
683 attrs
[counter
].sample_period
= default_interval
;
686 return __cmd_record(argc
, argv
);