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;
48 static struct timeval last_read
;
49 static struct timeval this_read
;
51 static u64 bytes_written
;
53 static struct pollfd event_array
[MAX_NR_CPUS
* MAX_COUNTERS
];
58 static int file_new
= 1;
60 struct perf_header
*header
;
63 struct perf_event_header header
;
69 char filename
[PATH_MAX
];
73 struct perf_event_header header
;
87 static struct mmap_data mmap_array
[MAX_NR_CPUS
][MAX_COUNTERS
];
89 static unsigned long mmap_read_head(struct mmap_data
*md
)
91 struct perf_counter_mmap_page
*pc
= md
->base
;
100 static void mmap_write_tail(struct mmap_data
*md
, unsigned long tail
)
102 struct perf_counter_mmap_page
*pc
= md
->base
;
105 * ensure all reads are done before we write the tail out.
108 pc
->data_tail
= tail
;
111 static void write_output(void *buf
, size_t size
)
114 int ret
= write(output
, buf
, size
);
117 die("failed to write");
122 bytes_written
+= ret
;
126 static void mmap_read(struct mmap_data
*md
)
128 unsigned int head
= mmap_read_head(md
);
129 unsigned int old
= md
->prev
;
130 unsigned char *data
= md
->base
+ page_size
;
135 gettimeofday(&this_read
, NULL
);
138 * If we're further behind than half the buffer, there's a chance
139 * the writer will bite our tail and mess up the samples under us.
141 * If we somehow ended up ahead of the head, we got messed up.
143 * In either case, truncate and restart at head.
150 timersub(&this_read
, &last_read
, &iv
);
151 msecs
= iv
.tv_sec
*1000 + iv
.tv_usec
/1000;
153 fprintf(stderr
, "WARNING: failed to keep up with mmap data."
154 " Last read %lu msecs ago.\n", msecs
);
157 * head points to a known good entry, start there.
162 last_read
= this_read
;
169 if ((old
& md
->mask
) + size
!= (head
& md
->mask
)) {
170 buf
= &data
[old
& md
->mask
];
171 size
= md
->mask
+ 1 - (old
& md
->mask
);
174 write_output(buf
, size
);
177 buf
= &data
[old
& md
->mask
];
181 write_output(buf
, size
);
184 mmap_write_tail(md
, old
);
187 static volatile int done
= 0;
188 static volatile int signr
= -1;
190 static void sig_handler(int sig
)
196 static void sig_atexit(void)
201 signal(signr
, SIG_DFL
);
202 kill(getpid(), signr
);
205 static void pid_synthesize_comm_event(pid_t pid
, int full
)
207 struct comm_event comm_ev
;
208 char filename
[PATH_MAX
];
214 struct dirent dirent
, *next
;
216 snprintf(filename
, sizeof(filename
), "/proc/%d/stat", pid
);
218 fd
= open(filename
, O_RDONLY
);
221 * We raced with a task exiting - just return:
224 fprintf(stderr
, "couldn't open %s\n", filename
);
227 if (read(fd
, bf
, sizeof(bf
)) < 0) {
228 fprintf(stderr
, "couldn't read %s\n", filename
);
233 /* 9027 (cat) R 6747 9027 6747 34816 9027 ... */
234 memset(&comm_ev
, 0, sizeof(comm_ev
));
235 field
= strchr(bf
, '(');
238 sep
= strchr(++field
, ')');
242 memcpy(comm_ev
.comm
, field
, size
++);
245 comm_ev
.header
.type
= PERF_EVENT_COMM
;
246 size
= ALIGN(size
, sizeof(u64
));
247 comm_ev
.header
.size
= sizeof(comm_ev
) - (sizeof(comm_ev
.comm
) - size
);
252 write_output(&comm_ev
, comm_ev
.header
.size
);
256 snprintf(filename
, sizeof(filename
), "/proc/%d/task", pid
);
258 tasks
= opendir(filename
);
259 while (!readdir_r(tasks
, &dirent
, &next
) && next
) {
261 pid
= strtol(dirent
.d_name
, &end
, 10);
267 write_output(&comm_ev
, comm_ev
.header
.size
);
273 fprintf(stderr
, "couldn't get COMM and pgid, malformed %s\n",
278 static void pid_synthesize_mmap_samples(pid_t pid
)
280 char filename
[PATH_MAX
];
283 snprintf(filename
, sizeof(filename
), "/proc/%d/maps", pid
);
285 fp
= fopen(filename
, "r");
288 * We raced with a task exiting - just return:
291 fprintf(stderr
, "couldn't open %s\n", filename
);
295 char bf
[BUFSIZ
], *pbf
= bf
;
296 struct mmap_event mmap_ev
= {
297 .header
.type
= PERF_EVENT_MMAP
,
301 if (fgets(bf
, sizeof(bf
), fp
) == NULL
)
304 /* 00400000-0040c000 r-xp 00000000 fd:01 41038 /bin/cat */
305 n
= hex2u64(pbf
, &mmap_ev
.start
);
309 n
= hex2u64(pbf
, &mmap_ev
.len
);
313 if (*pbf
== 'x') { /* vm_exec */
314 char *execname
= strchr(bf
, '/');
316 if (execname
== NULL
)
319 size
= strlen(execname
);
320 execname
[size
- 1] = '\0'; /* Remove \n */
321 memcpy(mmap_ev
.filename
, execname
, size
);
322 size
= ALIGN(size
, sizeof(u64
));
323 mmap_ev
.len
-= mmap_ev
.start
;
324 mmap_ev
.header
.size
= (sizeof(mmap_ev
) -
325 (sizeof(mmap_ev
.filename
) - size
));
329 write_output(&mmap_ev
, mmap_ev
.header
.size
);
336 static void synthesize_all(void)
339 struct dirent dirent
, *next
;
341 proc
= opendir("/proc");
343 while (!readdir_r(proc
, &dirent
, &next
) && next
) {
347 pid
= strtol(dirent
.d_name
, &end
, 10);
348 if (*end
) /* only interested in proper numerical dirents */
351 pid_synthesize_comm_event(pid
, 1);
352 pid_synthesize_mmap_samples(pid
);
360 static struct perf_header_attr
*get_header_attr(struct perf_counter_attr
*a
, int nr
)
362 struct perf_header_attr
*h_attr
;
364 if (nr
< header
->attrs
) {
365 h_attr
= header
->attr
[nr
];
367 h_attr
= perf_header_attr__new(a
);
368 perf_header__add_attr(header
, h_attr
);
374 static void create_counter(int counter
, int cpu
, pid_t pid
)
376 struct perf_counter_attr
*attr
= attrs
+ counter
;
377 struct perf_header_attr
*h_attr
;
378 int track
= !counter
; /* only the first counter needs these */
386 attr
->read_format
= PERF_FORMAT_TOTAL_TIME_ENABLED
|
387 PERF_FORMAT_TOTAL_TIME_RUNNING
|
390 attr
->sample_type
= PERF_SAMPLE_IP
| PERF_SAMPLE_TID
;
393 attr
->sample_type
|= PERF_SAMPLE_PERIOD
;
395 attr
->sample_freq
= freq
;
399 attr
->sample_freq
= 0;
402 attr
->inherit_stat
= 1;
405 attr
->sample_type
|= PERF_SAMPLE_CALLCHAIN
;
409 attr
->inherit
= (cpu
< 0) && inherit
;
413 fd
[nr_cpu
][counter
] = sys_perf_counter_open(attr
, pid
, cpu
, group_fd
, 0);
415 if (fd
[nr_cpu
][counter
] < 0) {
419 die("Permission error - are you root?\n");
422 * If it's cycles then fall back to hrtimer
423 * based cpu-clock-tick sw counter, which
424 * is always available even if no PMU support:
426 if (attr
->type
== PERF_TYPE_HARDWARE
427 && attr
->config
== PERF_COUNT_HW_CPU_CYCLES
) {
430 warning(" ... trying to fall back to cpu-clock-ticks\n");
431 attr
->type
= PERF_TYPE_SOFTWARE
;
432 attr
->config
= PERF_COUNT_SW_CPU_CLOCK
;
436 error("perfcounter syscall returned with %d (%s)\n",
437 fd
[nr_cpu
][counter
], strerror(err
));
438 die("No CONFIG_PERF_COUNTERS=y kernel support configured?\n");
442 h_attr
= get_header_attr(attr
, counter
);
445 if (memcmp(&h_attr
->attr
, attr
, sizeof(*attr
))) {
446 fprintf(stderr
, "incompatible append\n");
451 if (read(fd
[nr_cpu
][counter
], &read_data
, sizeof(read_data
)) == -1) {
452 perror("Unable to read perf file descriptor\n");
456 perf_header_attr__add_id(h_attr
, read_data
.id
);
458 assert(fd
[nr_cpu
][counter
] >= 0);
459 fcntl(fd
[nr_cpu
][counter
], F_SETFL
, O_NONBLOCK
);
462 * First counter acts as the group leader:
464 if (group
&& group_fd
== -1)
465 group_fd
= fd
[nr_cpu
][counter
];
467 event_array
[nr_poll
].fd
= fd
[nr_cpu
][counter
];
468 event_array
[nr_poll
].events
= POLLIN
;
471 mmap_array
[nr_cpu
][counter
].counter
= counter
;
472 mmap_array
[nr_cpu
][counter
].prev
= 0;
473 mmap_array
[nr_cpu
][counter
].mask
= mmap_pages
*page_size
- 1;
474 mmap_array
[nr_cpu
][counter
].base
= mmap(NULL
, (mmap_pages
+1)*page_size
,
475 PROT_READ
|PROT_WRITE
, MAP_SHARED
, fd
[nr_cpu
][counter
], 0);
476 if (mmap_array
[nr_cpu
][counter
].base
== MAP_FAILED
) {
477 error("failed to mmap with %d (%s)\n", errno
, strerror(errno
));
481 ioctl(fd
[nr_cpu
][counter
], PERF_COUNTER_IOC_ENABLE
);
484 static void open_counters(int cpu
, pid_t pid
)
489 for (counter
= 0; counter
< nr_counters
; counter
++)
490 create_counter(counter
, cpu
, pid
);
495 static void atexit_header(void)
497 header
->data_size
+= bytes_written
;
499 perf_header__write(header
, output
);
502 static int __cmd_record(int argc
, const char **argv
)
510 page_size
= sysconf(_SC_PAGE_SIZE
);
511 nr_cpus
= sysconf(_SC_NPROCESSORS_ONLN
);
512 assert(nr_cpus
<= MAX_NR_CPUS
);
513 assert(nr_cpus
>= 0);
516 signal(SIGCHLD
, sig_handler
);
517 signal(SIGINT
, sig_handler
);
519 if (!stat(output_name
, &st
) && !force
&& !append_file
) {
520 fprintf(stderr
, "Error, output file %s exists, use -A to append or -f to overwrite.\n",
525 flags
= O_CREAT
|O_RDWR
;
531 output
= open(output_name
, flags
, S_IRUSR
|S_IWUSR
);
533 perror("failed to create output file");
538 header
= perf_header__read(output
);
540 header
= perf_header__new();
542 atexit(atexit_header
);
549 open_counters(-1, pid
);
550 } else for (i
= 0; i
< nr_cpus
; i
++)
551 open_counters(i
, target_pid
);
554 perf_header__write(header
, output
);
557 pid_synthesize_comm_event(pid
, 0);
558 pid_synthesize_mmap_samples(pid
);
562 if (target_pid
== -1 && argc
) {
565 perror("failed to fork");
568 if (execvp(argv
[0], (char **)argv
)) {
576 struct sched_param param
;
578 param
.sched_priority
= realtime_prio
;
579 if (sched_setscheduler(0, SCHED_FIFO
, ¶m
)) {
580 printf("Could not set realtime priority.\n");
588 for (i
= 0; i
< nr_cpu
; i
++) {
589 for (counter
= 0; counter
< nr_counters
; counter
++)
590 mmap_read(&mmap_array
[i
][counter
]);
593 if (hits
== samples
) {
596 ret
= poll(event_array
, nr_poll
, 100);
601 * Approximate RIP event size: 24 bytes.
604 "[ perf record: Captured and wrote %.3f MB %s (~%lld samples) ]\n",
605 (double)bytes_written
/ 1024.0 / 1024.0,
612 static const char * const record_usage
[] = {
613 "perf record [<options>] [<command>]",
614 "perf record [<options>] -- <command> [<options>]",
618 static const struct option options
[] = {
619 OPT_CALLBACK('e', "event", NULL
, "event",
620 "event selector. use 'perf list' to list available events",
622 OPT_INTEGER('p', "pid", &target_pid
,
623 "record events on existing pid"),
624 OPT_INTEGER('r', "realtime", &realtime_prio
,
625 "collect data with this RT SCHED_FIFO priority"),
626 OPT_BOOLEAN('a', "all-cpus", &system_wide
,
627 "system-wide collection from all CPUs"),
628 OPT_BOOLEAN('A', "append", &append_file
,
629 "append to the output file to do incremental profiling"),
630 OPT_BOOLEAN('f', "force", &force
,
631 "overwrite existing data file"),
632 OPT_LONG('c', "count", &default_interval
,
633 "event period to sample"),
634 OPT_STRING('o', "output", &output_name
, "file",
636 OPT_BOOLEAN('i', "inherit", &inherit
,
637 "child tasks inherit counters"),
638 OPT_INTEGER('F', "freq", &freq
,
639 "profile at this frequency"),
640 OPT_INTEGER('m', "mmap-pages", &mmap_pages
,
641 "number of mmap data pages"),
642 OPT_BOOLEAN('g', "call-graph", &call_graph
,
643 "do call-graph (stack chain/backtrace) recording"),
644 OPT_BOOLEAN('v', "verbose", &verbose
,
645 "be more verbose (show counter open errors, etc)"),
646 OPT_BOOLEAN('s', "stat", &inherit_stat
,
647 "per thread counts"),
648 OPT_BOOLEAN('n', "no-samples", &no_samples
,
653 int cmd_record(int argc
, const char **argv
, const char *prefix
)
657 argc
= parse_options(argc
, argv
, options
, record_usage
, 0);
658 if (!argc
&& target_pid
== -1 && !system_wide
)
659 usage_with_options(record_usage
, options
);
663 attrs
[0].type
= PERF_TYPE_HARDWARE
;
664 attrs
[0].config
= PERF_COUNT_HW_CPU_CYCLES
;
667 for (counter
= 0; counter
< nr_counters
; counter
++) {
668 if (attrs
[counter
].sample_period
)
671 attrs
[counter
].sample_period
= default_interval
;
674 return __cmd_record(argc
, argv
);