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 verbose = 0;
43 static struct timeval last_read;
44 static struct timeval this_read;
46 static __u64 bytes_written;
48 static struct pollfd event_array[MAX_NR_CPUS * MAX_COUNTERS];
54 struct perf_event_header header;
60 char filename[PATH_MAX];
64 struct perf_event_header header;
78 static struct mmap_data mmap_array[MAX_NR_CPUS][MAX_COUNTERS];
80 static unsigned int mmap_read_head(struct mmap_data *md)
82 struct perf_counter_mmap_page *pc = md->base;
91 static void mmap_read(struct mmap_data *md)
93 unsigned int head = mmap_read_head(md);
94 unsigned int old = md->prev;
95 unsigned char *data = md->base + page_size;
100 gettimeofday(&this_read, NULL);
103 * If we're further behind than half the buffer, there's a chance
104 * the writer will bite our tail and mess up the samples under us.
106 * If we somehow ended up ahead of the head, we got messed up.
108 * In either case, truncate and restart at head.
111 if (diff > md->mask / 2 || diff < 0) {
115 timersub(&this_read, &last_read, &iv);
116 msecs = iv.tv_sec*1000 + iv.tv_usec/1000;
118 fprintf(stderr, "WARNING: failed to keep up with mmap data."
119 " Last read %lu msecs ago.\n", msecs);
122 * head points to a known good entry, start there.
127 last_read = this_read;
134 if ((old & md->mask) + size != (head & md->mask)) {
135 buf = &data[old & md->mask];
136 size = md->mask + 1 - (old & md->mask);
140 int ret = write(output, buf, size);
143 die("failed to write");
148 bytes_written += ret;
152 buf = &data[old & md->mask];
157 int ret = write(output, buf, size);
160 die("failed to write");
165 bytes_written += ret;
171 static volatile int done = 0;
173 static void sig_handler(int sig)
178 static void pid_synthesize_comm_event(pid_t pid, int full)
180 struct comm_event comm_ev;
181 char filename[PATH_MAX];
187 struct dirent dirent, *next;
189 snprintf(filename, sizeof(filename), "/proc/%d/stat", pid);
191 fd = open(filename, O_RDONLY);
193 fprintf(stderr, "couldn't open %s\n", filename);
196 if (read(fd, bf, sizeof(bf)) < 0) {
197 fprintf(stderr, "couldn't read %s\n", filename);
202 /* 9027 (cat) R 6747 9027 6747 34816 9027 ... */
203 memset(&comm_ev, 0, sizeof(comm_ev));
204 field = strchr(bf, '(');
207 sep = strchr(++field, ')');
211 memcpy(comm_ev.comm, field, size++);
214 comm_ev.header.type = PERF_EVENT_COMM;
215 size = ALIGN(size, sizeof(uint64_t));
216 comm_ev.header.size = sizeof(comm_ev) - (sizeof(comm_ev.comm) - size);
221 ret = write(output, &comm_ev, comm_ev.header.size);
223 perror("failed to write");
229 snprintf(filename, sizeof(filename), "/proc/%d/task", pid);
231 tasks = opendir(filename);
232 while (!readdir_r(tasks, &dirent, &next) && next) {
234 pid = strtol(dirent.d_name, &end, 10);
240 ret = write(output, &comm_ev, comm_ev.header.size);
242 perror("failed to write");
250 fprintf(stderr, "couldn't get COMM and pgid, malformed %s\n",
255 static void pid_synthesize_mmap_samples(pid_t pid)
257 char filename[PATH_MAX];
260 snprintf(filename, sizeof(filename), "/proc/%d/maps", pid);
262 fp = fopen(filename, "r");
264 fprintf(stderr, "couldn't open %s\n", filename);
268 char bf[BUFSIZ], *pbf = bf;
269 struct mmap_event mmap_ev = {
270 .header.type = PERF_EVENT_MMAP,
274 if (fgets(bf, sizeof(bf), fp) == NULL)
277 /* 00400000-0040c000 r-xp 00000000 fd:01 41038 /bin/cat */
278 n = hex2u64(pbf, &mmap_ev.start);
282 n = hex2u64(pbf, &mmap_ev.len);
286 if (*pbf == 'x') { /* vm_exec */
287 char *execname = strrchr(bf, ' ');
289 if (execname == NULL || execname[1] != '/')
293 size = strlen(execname);
294 execname[size - 1] = '\0'; /* Remove \n */
295 memcpy(mmap_ev.filename, execname, size);
296 size = ALIGN(size, sizeof(uint64_t));
297 mmap_ev.len -= mmap_ev.start;
298 mmap_ev.header.size = (sizeof(mmap_ev) -
299 (sizeof(mmap_ev.filename) - size));
303 if (write(output, &mmap_ev, mmap_ev.header.size) < 0) {
304 perror("failed to write");
313 static void synthesize_samples(void)
316 struct dirent dirent, *next;
318 proc = opendir("/proc");
320 while (!readdir_r(proc, &dirent, &next) && next) {
324 pid = strtol(dirent.d_name, &end, 10);
325 if (*end) /* only interested in proper numerical dirents */
328 pid_synthesize_comm_event(pid, 1);
329 pid_synthesize_mmap_samples(pid);
337 static void create_counter(int counter, int cpu, pid_t pid)
339 struct perf_counter_attr *attr = attrs + counter;
342 attr->sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_TID | PERF_SAMPLE_PERIOD;
345 attr->sample_freq = freq;
349 attr->inherit = (cpu < 0) && inherit;
352 track = 0; /* only the first counter needs these */
355 fd[nr_cpu][counter] = sys_perf_counter_open(attr, pid, cpu, group_fd, 0);
357 if (fd[nr_cpu][counter] < 0) {
361 die("Permission error - are you root?\n");
364 * If it's cycles then fall back to hrtimer
365 * based cpu-clock-tick sw counter, which
366 * is always available even if no PMU support:
368 if (attr->type == PERF_TYPE_HARDWARE
369 && attr->config == PERF_COUNT_CPU_CYCLES) {
372 warning(" ... trying to fall back to cpu-clock-ticks\n");
373 attr->type = PERF_TYPE_SOFTWARE;
374 attr->config = PERF_COUNT_CPU_CLOCK;
378 error("perfcounter syscall returned with %d (%s)\n",
379 fd[nr_cpu][counter], strerror(err));
380 die("No CONFIG_PERF_COUNTERS=y kernel support configured?\n");
384 assert(fd[nr_cpu][counter] >= 0);
385 fcntl(fd[nr_cpu][counter], F_SETFL, O_NONBLOCK);
388 * First counter acts as the group leader:
390 if (group && group_fd == -1)
391 group_fd = fd[nr_cpu][counter];
393 event_array[nr_poll].fd = fd[nr_cpu][counter];
394 event_array[nr_poll].events = POLLIN;
397 mmap_array[nr_cpu][counter].counter = counter;
398 mmap_array[nr_cpu][counter].prev = 0;
399 mmap_array[nr_cpu][counter].mask = mmap_pages*page_size - 1;
400 mmap_array[nr_cpu][counter].base = mmap(NULL, (mmap_pages+1)*page_size,
401 PROT_READ, MAP_SHARED, fd[nr_cpu][counter], 0);
402 if (mmap_array[nr_cpu][counter].base == MAP_FAILED) {
403 error("failed to mmap with %d (%s)\n", errno, strerror(errno));
407 ioctl(fd[nr_cpu][counter], PERF_COUNTER_IOC_ENABLE);
410 static void open_counters(int cpu, pid_t pid)
415 pid_synthesize_comm_event(pid, 0);
416 pid_synthesize_mmap_samples(pid);
420 for (counter = 0; counter < nr_counters; counter++)
421 create_counter(counter, cpu, pid);
426 static int __cmd_record(int argc, const char **argv)
434 page_size = sysconf(_SC_PAGE_SIZE);
435 nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
436 assert(nr_cpus <= MAX_NR_CPUS);
437 assert(nr_cpus >= 0);
439 if (!stat(output_name, &st) && !force && !append_file) {
440 fprintf(stderr, "Error, output file %s exists, use -A to append or -f to overwrite.\n",
445 flags = O_CREAT|O_RDWR;
451 output = open(output_name, flags, S_IRUSR|S_IWUSR);
453 perror("failed to create output file");
458 open_counters(-1, target_pid != -1 ? target_pid : getpid());
459 } else for (i = 0; i < nr_cpus; i++)
460 open_counters(i, target_pid);
462 signal(SIGCHLD, sig_handler);
463 signal(SIGINT, sig_handler);
465 if (target_pid == -1 && argc) {
468 perror("failed to fork");
471 if (execvp(argv[0], (char **)argv)) {
479 struct sched_param param;
481 param.sched_priority = realtime_prio;
482 if (sched_setscheduler(0, SCHED_FIFO, ¶m)) {
483 printf("Could not set realtime priority.\n");
489 synthesize_samples();
494 for (i = 0; i < nr_cpu; i++) {
495 for (counter = 0; counter < nr_counters; counter++)
496 mmap_read(&mmap_array[i][counter]);
500 ret = poll(event_array, nr_poll, 100);
504 * Approximate RIP event size: 24 bytes.
507 "[ perf record: Captured and wrote %.3f MB %s (~%lld samples) ]\n",
508 (double)bytes_written / 1024.0 / 1024.0,
515 static const char * const record_usage[] = {
516 "perf record [<options>] [<command>]",
517 "perf record [<options>] -- <command> [<options>]",
521 static const struct option options[] = {
522 OPT_CALLBACK('e', "event", NULL, "event",
523 "event selector. use 'perf list' to list available events",
525 OPT_INTEGER('p', "pid", &target_pid,
526 "record events on existing pid"),
527 OPT_INTEGER('r', "realtime", &realtime_prio,
528 "collect data with this RT SCHED_FIFO priority"),
529 OPT_BOOLEAN('a', "all-cpus", &system_wide,
530 "system-wide collection from all CPUs"),
531 OPT_BOOLEAN('A', "append", &append_file,
532 "append to the output file to do incremental profiling"),
533 OPT_BOOLEAN('f', "force", &force,
534 "overwrite existing data file"),
535 OPT_LONG('c', "count", &default_interval,
536 "event period to sample"),
537 OPT_STRING('o', "output", &output_name, "file",
539 OPT_BOOLEAN('i', "inherit", &inherit,
540 "child tasks inherit counters"),
541 OPT_INTEGER('F', "freq", &freq,
542 "profile at this frequency"),
543 OPT_INTEGER('m', "mmap-pages", &mmap_pages,
544 "number of mmap data pages"),
545 OPT_BOOLEAN('v', "verbose", &verbose,
546 "be more verbose (show counter open errors, etc)"),
550 int cmd_record(int argc, const char **argv, const char *prefix)
554 argc = parse_options(argc, argv, options, record_usage, 0);
555 if (!argc && target_pid == -1 && !system_wide)
556 usage_with_options(record_usage, options);
561 for (counter = 0; counter < nr_counters; counter++) {
562 if (attrs[counter].sample_period)
565 attrs[counter].sample_period = default_interval;
568 return __cmd_record(argc, argv);