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
];
54 static int file_new
= 1;
55 static struct perf_file_header file_header
;
58 struct perf_event_header header
;
64 char filename
[PATH_MAX
];
68 struct perf_event_header header
;
82 static struct mmap_data mmap_array
[MAX_NR_CPUS
][MAX_COUNTERS
];
84 static unsigned long mmap_read_head(struct mmap_data
*md
)
86 struct perf_counter_mmap_page
*pc
= md
->base
;
95 static void mmap_write_tail(struct mmap_data
*md
, unsigned long tail
)
97 struct perf_counter_mmap_page
*pc
= md
->base
;
100 * ensure all reads are done before we write the tail out.
103 pc
->data_tail
= tail
;
106 static void write_output(void *buf
, size_t size
)
109 int ret
= write(output
, buf
, size
);
112 die("failed to write");
117 bytes_written
+= ret
;
121 static void mmap_read(struct mmap_data
*md
)
123 unsigned int head
= mmap_read_head(md
);
124 unsigned int old
= md
->prev
;
125 unsigned char *data
= md
->base
+ page_size
;
130 gettimeofday(&this_read
, NULL
);
133 * If we're further behind than half the buffer, there's a chance
134 * the writer will bite our tail and mess up the samples under us.
136 * If we somehow ended up ahead of the head, we got messed up.
138 * In either case, truncate and restart at head.
145 timersub(&this_read
, &last_read
, &iv
);
146 msecs
= iv
.tv_sec
*1000 + iv
.tv_usec
/1000;
148 fprintf(stderr
, "WARNING: failed to keep up with mmap data."
149 " Last read %lu msecs ago.\n", msecs
);
152 * head points to a known good entry, start there.
157 last_read
= this_read
;
164 if ((old
& md
->mask
) + size
!= (head
& md
->mask
)) {
165 buf
= &data
[old
& md
->mask
];
166 size
= md
->mask
+ 1 - (old
& md
->mask
);
169 write_output(buf
, size
);
172 buf
= &data
[old
& md
->mask
];
176 write_output(buf
, size
);
179 mmap_write_tail(md
, old
);
182 static volatile int done
= 0;
183 static volatile int signr
= -1;
185 static void sig_handler(int sig
)
191 static void sig_atexit(void)
196 signal(signr
, SIG_DFL
);
197 kill(getpid(), signr
);
200 static void pid_synthesize_comm_event(pid_t pid
, int full
)
202 struct comm_event comm_ev
;
203 char filename
[PATH_MAX
];
209 struct dirent dirent
, *next
;
211 snprintf(filename
, sizeof(filename
), "/proc/%d/stat", pid
);
213 fd
= open(filename
, O_RDONLY
);
216 * We raced with a task exiting - just return:
219 fprintf(stderr
, "couldn't open %s\n", filename
);
222 if (read(fd
, bf
, sizeof(bf
)) < 0) {
223 fprintf(stderr
, "couldn't read %s\n", filename
);
228 /* 9027 (cat) R 6747 9027 6747 34816 9027 ... */
229 memset(&comm_ev
, 0, sizeof(comm_ev
));
230 field
= strchr(bf
, '(');
233 sep
= strchr(++field
, ')');
237 memcpy(comm_ev
.comm
, field
, size
++);
240 comm_ev
.header
.type
= PERF_EVENT_COMM
;
241 size
= ALIGN(size
, sizeof(u64
));
242 comm_ev
.header
.size
= sizeof(comm_ev
) - (sizeof(comm_ev
.comm
) - size
);
247 write_output(&comm_ev
, comm_ev
.header
.size
);
251 snprintf(filename
, sizeof(filename
), "/proc/%d/task", pid
);
253 tasks
= opendir(filename
);
254 while (!readdir_r(tasks
, &dirent
, &next
) && next
) {
256 pid
= strtol(dirent
.d_name
, &end
, 10);
262 write_output(&comm_ev
, comm_ev
.header
.size
);
268 fprintf(stderr
, "couldn't get COMM and pgid, malformed %s\n",
273 static void pid_synthesize_mmap_samples(pid_t pid
)
275 char filename
[PATH_MAX
];
278 snprintf(filename
, sizeof(filename
), "/proc/%d/maps", pid
);
280 fp
= fopen(filename
, "r");
283 * We raced with a task exiting - just return:
286 fprintf(stderr
, "couldn't open %s\n", filename
);
290 char bf
[BUFSIZ
], *pbf
= bf
;
291 struct mmap_event mmap_ev
= {
292 .header
.type
= PERF_EVENT_MMAP
,
296 if (fgets(bf
, sizeof(bf
), fp
) == NULL
)
299 /* 00400000-0040c000 r-xp 00000000 fd:01 41038 /bin/cat */
300 n
= hex2u64(pbf
, &mmap_ev
.start
);
304 n
= hex2u64(pbf
, &mmap_ev
.len
);
308 if (*pbf
== 'x') { /* vm_exec */
309 char *execname
= strrchr(bf
, ' ');
311 if (execname
== NULL
|| execname
[1] != '/')
315 size
= strlen(execname
);
316 execname
[size
- 1] = '\0'; /* Remove \n */
317 memcpy(mmap_ev
.filename
, execname
, size
);
318 size
= ALIGN(size
, sizeof(u64
));
319 mmap_ev
.len
-= mmap_ev
.start
;
320 mmap_ev
.header
.size
= (sizeof(mmap_ev
) -
321 (sizeof(mmap_ev
.filename
) - size
));
325 write_output(&mmap_ev
, mmap_ev
.header
.size
);
332 static void synthesize_samples(void)
335 struct dirent dirent
, *next
;
337 proc
= opendir("/proc");
339 while (!readdir_r(proc
, &dirent
, &next
) && next
) {
343 pid
= strtol(dirent
.d_name
, &end
, 10);
344 if (*end
) /* only interested in proper numerical dirents */
347 pid_synthesize_comm_event(pid
, 1);
348 pid_synthesize_mmap_samples(pid
);
356 static void create_counter(int counter
, int cpu
, pid_t pid
)
358 struct perf_counter_attr
*attr
= attrs
+ counter
;
361 attr
->sample_type
= PERF_SAMPLE_IP
| PERF_SAMPLE_TID
;
364 attr
->sample_type
|= PERF_SAMPLE_PERIOD
;
366 attr
->sample_freq
= freq
;
370 attr
->sample_type
|= PERF_SAMPLE_CALLCHAIN
;
373 file_header
.sample_type
= attr
->sample_type
;
375 if (file_header
.sample_type
!= attr
->sample_type
) {
376 fprintf(stderr
, "incompatible append\n");
383 attr
->inherit
= (cpu
< 0) && inherit
;
386 track
= 0; /* only the first counter needs these */
389 fd
[nr_cpu
][counter
] = sys_perf_counter_open(attr
, pid
, cpu
, group_fd
, 0);
391 if (fd
[nr_cpu
][counter
] < 0) {
395 die("Permission error - are you root?\n");
398 * If it's cycles then fall back to hrtimer
399 * based cpu-clock-tick sw counter, which
400 * is always available even if no PMU support:
402 if (attr
->type
== PERF_TYPE_HARDWARE
403 && attr
->config
== PERF_COUNT_HW_CPU_CYCLES
) {
406 warning(" ... trying to fall back to cpu-clock-ticks\n");
407 attr
->type
= PERF_TYPE_SOFTWARE
;
408 attr
->config
= PERF_COUNT_SW_CPU_CLOCK
;
412 error("perfcounter syscall returned with %d (%s)\n",
413 fd
[nr_cpu
][counter
], strerror(err
));
414 die("No CONFIG_PERF_COUNTERS=y kernel support configured?\n");
418 assert(fd
[nr_cpu
][counter
] >= 0);
419 fcntl(fd
[nr_cpu
][counter
], F_SETFL
, O_NONBLOCK
);
422 * First counter acts as the group leader:
424 if (group
&& group_fd
== -1)
425 group_fd
= fd
[nr_cpu
][counter
];
427 event_array
[nr_poll
].fd
= fd
[nr_cpu
][counter
];
428 event_array
[nr_poll
].events
= POLLIN
;
431 mmap_array
[nr_cpu
][counter
].counter
= counter
;
432 mmap_array
[nr_cpu
][counter
].prev
= 0;
433 mmap_array
[nr_cpu
][counter
].mask
= mmap_pages
*page_size
- 1;
434 mmap_array
[nr_cpu
][counter
].base
= mmap(NULL
, (mmap_pages
+1)*page_size
,
435 PROT_READ
|PROT_WRITE
, MAP_SHARED
, fd
[nr_cpu
][counter
], 0);
436 if (mmap_array
[nr_cpu
][counter
].base
== MAP_FAILED
) {
437 error("failed to mmap with %d (%s)\n", errno
, strerror(errno
));
441 ioctl(fd
[nr_cpu
][counter
], PERF_COUNTER_IOC_ENABLE
);
444 static void open_counters(int cpu
, pid_t pid
)
449 pid_synthesize_comm_event(pid
, 0);
450 pid_synthesize_mmap_samples(pid
);
454 for (counter
= 0; counter
< nr_counters
; counter
++)
455 create_counter(counter
, cpu
, pid
);
460 static void atexit_header(void)
462 file_header
.data_size
+= bytes_written
;
464 if (pwrite(output
, &file_header
, sizeof(file_header
), 0) == -1)
465 perror("failed to write on file headers");
468 static int __cmd_record(int argc
, const char **argv
)
476 page_size
= sysconf(_SC_PAGE_SIZE
);
477 nr_cpus
= sysconf(_SC_NPROCESSORS_ONLN
);
478 assert(nr_cpus
<= MAX_NR_CPUS
);
479 assert(nr_cpus
>= 0);
482 signal(SIGCHLD
, sig_handler
);
483 signal(SIGINT
, sig_handler
);
485 if (!stat(output_name
, &st
) && !force
&& !append_file
) {
486 fprintf(stderr
, "Error, output file %s exists, use -A to append or -f to overwrite.\n",
491 flags
= O_CREAT
|O_RDWR
;
497 output
= open(output_name
, flags
, S_IRUSR
|S_IWUSR
);
499 perror("failed to create output file");
504 if (read(output
, &file_header
, sizeof(file_header
)) == -1) {
505 perror("failed to read file headers");
509 lseek(output
, file_header
.data_size
, SEEK_CUR
);
512 atexit(atexit_header
);
515 open_counters(-1, target_pid
!= -1 ? target_pid
: getpid());
516 } else for (i
= 0; i
< nr_cpus
; i
++)
517 open_counters(i
, target_pid
);
519 if (target_pid
== -1 && argc
) {
522 perror("failed to fork");
525 if (execvp(argv
[0], (char **)argv
)) {
533 struct sched_param param
;
535 param
.sched_priority
= realtime_prio
;
536 if (sched_setscheduler(0, SCHED_FIFO
, ¶m
)) {
537 printf("Could not set realtime priority.\n");
543 synthesize_samples();
548 for (i
= 0; i
< nr_cpu
; i
++) {
549 for (counter
= 0; counter
< nr_counters
; counter
++)
550 mmap_read(&mmap_array
[i
][counter
]);
554 ret
= poll(event_array
, nr_poll
, 100);
558 * Approximate RIP event size: 24 bytes.
561 "[ perf record: Captured and wrote %.3f MB %s (~%lld samples) ]\n",
562 (double)bytes_written
/ 1024.0 / 1024.0,
569 static const char * const record_usage
[] = {
570 "perf record [<options>] [<command>]",
571 "perf record [<options>] -- <command> [<options>]",
575 static const struct option options
[] = {
576 OPT_CALLBACK('e', "event", NULL
, "event",
577 "event selector. use 'perf list' to list available events",
579 OPT_INTEGER('p', "pid", &target_pid
,
580 "record events on existing pid"),
581 OPT_INTEGER('r', "realtime", &realtime_prio
,
582 "collect data with this RT SCHED_FIFO priority"),
583 OPT_BOOLEAN('a', "all-cpus", &system_wide
,
584 "system-wide collection from all CPUs"),
585 OPT_BOOLEAN('A', "append", &append_file
,
586 "append to the output file to do incremental profiling"),
587 OPT_BOOLEAN('f', "force", &force
,
588 "overwrite existing data file"),
589 OPT_LONG('c', "count", &default_interval
,
590 "event period to sample"),
591 OPT_STRING('o', "output", &output_name
, "file",
593 OPT_BOOLEAN('i', "inherit", &inherit
,
594 "child tasks inherit counters"),
595 OPT_INTEGER('F', "freq", &freq
,
596 "profile at this frequency"),
597 OPT_INTEGER('m', "mmap-pages", &mmap_pages
,
598 "number of mmap data pages"),
599 OPT_BOOLEAN('g', "call-graph", &call_graph
,
600 "do call-graph (stack chain/backtrace) recording"),
601 OPT_BOOLEAN('v', "verbose", &verbose
,
602 "be more verbose (show counter open errors, etc)"),
606 int cmd_record(int argc
, const char **argv
, const char *prefix
)
610 argc
= parse_options(argc
, argv
, options
, record_usage
, 0);
611 if (!argc
&& target_pid
== -1 && !system_wide
)
612 usage_with_options(record_usage
, options
);
616 attrs
[0].type
= PERF_TYPE_HARDWARE
;
617 attrs
[0].config
= PERF_COUNT_HW_CPU_CYCLES
;
620 for (counter
= 0; counter
< nr_counters
; counter
++) {
621 if (attrs
[counter
].sample_period
)
624 attrs
[counter
].sample_period
= default_interval
;
627 return __cmd_record(argc
, argv
);