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;
46 static struct timeval last_read
;
47 static struct timeval this_read
;
49 static u64 bytes_written
;
51 static struct pollfd event_array
[MAX_NR_CPUS
* MAX_COUNTERS
];
56 static int file_new
= 1;
58 struct perf_header
*header
;
61 struct perf_event_header header
;
67 char filename
[PATH_MAX
];
71 struct perf_event_header header
;
85 static struct mmap_data mmap_array
[MAX_NR_CPUS
][MAX_COUNTERS
];
87 static unsigned long mmap_read_head(struct mmap_data
*md
)
89 struct perf_counter_mmap_page
*pc
= md
->base
;
98 static void mmap_write_tail(struct mmap_data
*md
, unsigned long tail
)
100 struct perf_counter_mmap_page
*pc
= md
->base
;
103 * ensure all reads are done before we write the tail out.
106 pc
->data_tail
= tail
;
109 static void write_output(void *buf
, size_t size
)
112 int ret
= write(output
, buf
, size
);
115 die("failed to write");
120 bytes_written
+= ret
;
124 static void mmap_read(struct mmap_data
*md
)
126 unsigned int head
= mmap_read_head(md
);
127 unsigned int old
= md
->prev
;
128 unsigned char *data
= md
->base
+ page_size
;
133 gettimeofday(&this_read
, NULL
);
136 * If we're further behind than half the buffer, there's a chance
137 * the writer will bite our tail and mess up the samples under us.
139 * If we somehow ended up ahead of the head, we got messed up.
141 * In either case, truncate and restart at head.
148 timersub(&this_read
, &last_read
, &iv
);
149 msecs
= iv
.tv_sec
*1000 + iv
.tv_usec
/1000;
151 fprintf(stderr
, "WARNING: failed to keep up with mmap data."
152 " Last read %lu msecs ago.\n", msecs
);
155 * head points to a known good entry, start there.
160 last_read
= this_read
;
167 if ((old
& md
->mask
) + size
!= (head
& md
->mask
)) {
168 buf
= &data
[old
& md
->mask
];
169 size
= md
->mask
+ 1 - (old
& md
->mask
);
172 write_output(buf
, size
);
175 buf
= &data
[old
& md
->mask
];
179 write_output(buf
, size
);
182 mmap_write_tail(md
, old
);
185 static volatile int done
= 0;
186 static volatile int signr
= -1;
188 static void sig_handler(int sig
)
194 static void sig_atexit(void)
199 signal(signr
, SIG_DFL
);
200 kill(getpid(), signr
);
203 static void pid_synthesize_comm_event(pid_t pid
, int full
)
205 struct comm_event comm_ev
;
206 char filename
[PATH_MAX
];
212 struct dirent dirent
, *next
;
214 snprintf(filename
, sizeof(filename
), "/proc/%d/stat", pid
);
216 fd
= open(filename
, O_RDONLY
);
219 * We raced with a task exiting - just return:
222 fprintf(stderr
, "couldn't open %s\n", filename
);
225 if (read(fd
, bf
, sizeof(bf
)) < 0) {
226 fprintf(stderr
, "couldn't read %s\n", filename
);
231 /* 9027 (cat) R 6747 9027 6747 34816 9027 ... */
232 memset(&comm_ev
, 0, sizeof(comm_ev
));
233 field
= strchr(bf
, '(');
236 sep
= strchr(++field
, ')');
240 memcpy(comm_ev
.comm
, field
, size
++);
243 comm_ev
.header
.type
= PERF_EVENT_COMM
;
244 size
= ALIGN(size
, sizeof(u64
));
245 comm_ev
.header
.size
= sizeof(comm_ev
) - (sizeof(comm_ev
.comm
) - size
);
250 write_output(&comm_ev
, comm_ev
.header
.size
);
254 snprintf(filename
, sizeof(filename
), "/proc/%d/task", pid
);
256 tasks
= opendir(filename
);
257 while (!readdir_r(tasks
, &dirent
, &next
) && next
) {
259 pid
= strtol(dirent
.d_name
, &end
, 10);
265 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
)
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_EVENT_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
, '/');
314 if (execname
== NULL
)
317 size
= strlen(execname
);
318 execname
[size
- 1] = '\0'; /* Remove \n */
319 memcpy(mmap_ev
.filename
, execname
, size
);
320 size
= ALIGN(size
, sizeof(u64
));
321 mmap_ev
.len
-= mmap_ev
.start
;
322 mmap_ev
.header
.size
= (sizeof(mmap_ev
) -
323 (sizeof(mmap_ev
.filename
) - size
));
327 write_output(&mmap_ev
, mmap_ev
.header
.size
);
334 static void synthesize_all(void)
337 struct dirent dirent
, *next
;
339 proc
= opendir("/proc");
341 while (!readdir_r(proc
, &dirent
, &next
) && next
) {
345 pid
= strtol(dirent
.d_name
, &end
, 10);
346 if (*end
) /* only interested in proper numerical dirents */
349 pid_synthesize_comm_event(pid
, 1);
350 pid_synthesize_mmap_samples(pid
);
358 static struct perf_header_attr
*get_header_attr(struct perf_counter_attr
*a
, int nr
)
360 struct perf_header_attr
*h_attr
;
362 if (nr
< header
->attrs
) {
363 h_attr
= header
->attr
[nr
];
365 h_attr
= perf_header_attr__new(a
);
366 perf_header__add_attr(header
, h_attr
);
372 static void create_counter(int counter
, int cpu
, pid_t pid
)
374 struct perf_counter_attr
*attr
= attrs
+ counter
;
375 struct perf_header_attr
*h_attr
;
376 int track
= !counter
; /* only the first counter needs these */
384 attr
->read_format
= PERF_FORMAT_TOTAL_TIME_ENABLED
|
385 PERF_FORMAT_TOTAL_TIME_RUNNING
|
388 attr
->sample_type
= PERF_SAMPLE_IP
| PERF_SAMPLE_TID
;
391 attr
->sample_type
|= PERF_SAMPLE_PERIOD
;
393 attr
->sample_freq
= freq
;
397 attr
->sample_type
|= PERF_SAMPLE_CALLCHAIN
;
401 attr
->inherit
= (cpu
< 0) && inherit
;
405 fd
[nr_cpu
][counter
] = sys_perf_counter_open(attr
, pid
, cpu
, group_fd
, 0);
407 if (fd
[nr_cpu
][counter
] < 0) {
411 die("Permission error - are you root?\n");
414 * If it's cycles then fall back to hrtimer
415 * based cpu-clock-tick sw counter, which
416 * is always available even if no PMU support:
418 if (attr
->type
== PERF_TYPE_HARDWARE
419 && attr
->config
== PERF_COUNT_HW_CPU_CYCLES
) {
422 warning(" ... trying to fall back to cpu-clock-ticks\n");
423 attr
->type
= PERF_TYPE_SOFTWARE
;
424 attr
->config
= PERF_COUNT_SW_CPU_CLOCK
;
428 error("perfcounter syscall returned with %d (%s)\n",
429 fd
[nr_cpu
][counter
], strerror(err
));
430 die("No CONFIG_PERF_COUNTERS=y kernel support configured?\n");
434 h_attr
= get_header_attr(attr
, counter
);
437 if (memcmp(&h_attr
->attr
, attr
, sizeof(*attr
))) {
438 fprintf(stderr
, "incompatible append\n");
443 read(fd
[nr_cpu
][counter
], &read_data
, sizeof(read_data
));
445 perf_header_attr__add_id(h_attr
, read_data
.id
);
447 assert(fd
[nr_cpu
][counter
] >= 0);
448 fcntl(fd
[nr_cpu
][counter
], F_SETFL
, O_NONBLOCK
);
451 * First counter acts as the group leader:
453 if (group
&& group_fd
== -1)
454 group_fd
= fd
[nr_cpu
][counter
];
456 event_array
[nr_poll
].fd
= fd
[nr_cpu
][counter
];
457 event_array
[nr_poll
].events
= POLLIN
;
460 mmap_array
[nr_cpu
][counter
].counter
= counter
;
461 mmap_array
[nr_cpu
][counter
].prev
= 0;
462 mmap_array
[nr_cpu
][counter
].mask
= mmap_pages
*page_size
- 1;
463 mmap_array
[nr_cpu
][counter
].base
= mmap(NULL
, (mmap_pages
+1)*page_size
,
464 PROT_READ
|PROT_WRITE
, MAP_SHARED
, fd
[nr_cpu
][counter
], 0);
465 if (mmap_array
[nr_cpu
][counter
].base
== MAP_FAILED
) {
466 error("failed to mmap with %d (%s)\n", errno
, strerror(errno
));
470 ioctl(fd
[nr_cpu
][counter
], PERF_COUNTER_IOC_ENABLE
);
473 static void open_counters(int cpu
, pid_t pid
)
478 for (counter
= 0; counter
< nr_counters
; counter
++)
479 create_counter(counter
, cpu
, pid
);
484 static void atexit_header(void)
486 header
->data_size
+= bytes_written
;
488 perf_header__write(header
, output
);
491 static int __cmd_record(int argc
, const char **argv
)
499 page_size
= sysconf(_SC_PAGE_SIZE
);
500 nr_cpus
= sysconf(_SC_NPROCESSORS_ONLN
);
501 assert(nr_cpus
<= MAX_NR_CPUS
);
502 assert(nr_cpus
>= 0);
505 signal(SIGCHLD
, sig_handler
);
506 signal(SIGINT
, sig_handler
);
508 if (!stat(output_name
, &st
) && !force
&& !append_file
) {
509 fprintf(stderr
, "Error, output file %s exists, use -A to append or -f to overwrite.\n",
514 flags
= O_CREAT
|O_RDWR
;
520 output
= open(output_name
, flags
, S_IRUSR
|S_IWUSR
);
522 perror("failed to create output file");
527 header
= perf_header__read(output
);
529 header
= perf_header__new();
531 atexit(atexit_header
);
538 open_counters(-1, pid
);
539 } else for (i
= 0; i
< nr_cpus
; i
++)
540 open_counters(i
, target_pid
);
543 perf_header__write(header
, output
);
546 pid_synthesize_comm_event(pid
, 0);
547 pid_synthesize_mmap_samples(pid
);
551 if (target_pid
== -1 && argc
) {
554 perror("failed to fork");
557 if (execvp(argv
[0], (char **)argv
)) {
565 struct sched_param param
;
567 param
.sched_priority
= realtime_prio
;
568 if (sched_setscheduler(0, SCHED_FIFO
, ¶m
)) {
569 printf("Could not set realtime priority.\n");
577 for (i
= 0; i
< nr_cpu
; i
++) {
578 for (counter
= 0; counter
< nr_counters
; counter
++)
579 mmap_read(&mmap_array
[i
][counter
]);
583 ret
= poll(event_array
, nr_poll
, 100);
587 * Approximate RIP event size: 24 bytes.
590 "[ perf record: Captured and wrote %.3f MB %s (~%lld samples) ]\n",
591 (double)bytes_written
/ 1024.0 / 1024.0,
598 static const char * const record_usage
[] = {
599 "perf record [<options>] [<command>]",
600 "perf record [<options>] -- <command> [<options>]",
604 static const struct option options
[] = {
605 OPT_CALLBACK('e', "event", NULL
, "event",
606 "event selector. use 'perf list' to list available events",
608 OPT_INTEGER('p', "pid", &target_pid
,
609 "record events on existing pid"),
610 OPT_INTEGER('r', "realtime", &realtime_prio
,
611 "collect data with this RT SCHED_FIFO priority"),
612 OPT_BOOLEAN('a', "all-cpus", &system_wide
,
613 "system-wide collection from all CPUs"),
614 OPT_BOOLEAN('A', "append", &append_file
,
615 "append to the output file to do incremental profiling"),
616 OPT_BOOLEAN('f', "force", &force
,
617 "overwrite existing data file"),
618 OPT_LONG('c', "count", &default_interval
,
619 "event period to sample"),
620 OPT_STRING('o', "output", &output_name
, "file",
622 OPT_BOOLEAN('i', "inherit", &inherit
,
623 "child tasks inherit counters"),
624 OPT_INTEGER('F', "freq", &freq
,
625 "profile at this frequency"),
626 OPT_INTEGER('m', "mmap-pages", &mmap_pages
,
627 "number of mmap data pages"),
628 OPT_BOOLEAN('g', "call-graph", &call_graph
,
629 "do call-graph (stack chain/backtrace) recording"),
630 OPT_BOOLEAN('v', "verbose", &verbose
,
631 "be more verbose (show counter open errors, etc)"),
635 int cmd_record(int argc
, const char **argv
, const char *prefix
)
639 argc
= parse_options(argc
, argv
, options
, record_usage
, 0);
640 if (!argc
&& target_pid
== -1 && !system_wide
)
641 usage_with_options(record_usage
, options
);
645 attrs
[0].type
= PERF_TYPE_HARDWARE
;
646 attrs
[0].config
= PERF_COUNT_HW_CPU_CYCLES
;
649 for (counter
= 0; counter
< nr_counters
; counter
++) {
650 if (attrs
[counter
].sample_period
)
653 attrs
[counter
].sample_period
= default_interval
;
656 return __cmd_record(argc
, argv
);