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 long default_interval = 100000;
24 static long event_count[MAX_COUNTERS];
26 static int fd[MAX_NR_CPUS][MAX_COUNTERS];
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;
41 const unsigned int default_count[] = {
57 static unsigned int mmap_read_head(struct mmap_data *md)
59 struct perf_counter_mmap_page *pc = md->base;
69 static struct timeval last_read, this_read;
71 static __u64 bytes_written;
73 static void mmap_read(struct mmap_data *md)
75 unsigned int head = mmap_read_head(md);
76 unsigned int old = md->prev;
77 unsigned char *data = md->base + page_size;
82 gettimeofday(&this_read, NULL);
85 * If we're further behind than half the buffer, there's a chance
86 * the writer will bite our tail and mess up the samples under us.
88 * If we somehow ended up ahead of the head, we got messed up.
90 * In either case, truncate and restart at head.
93 if (diff > md->mask / 2 || diff < 0) {
97 timersub(&this_read, &last_read, &iv);
98 msecs = iv.tv_sec*1000 + iv.tv_usec/1000;
100 fprintf(stderr, "WARNING: failed to keep up with mmap data."
101 " Last read %lu msecs ago.\n", msecs);
104 * head points to a known good entry, start there.
109 last_read = this_read;
116 if ((old & md->mask) + size != (head & md->mask)) {
117 buf = &data[old & md->mask];
118 size = md->mask + 1 - (old & md->mask);
122 int ret = write(output, buf, size);
125 die("failed to write");
130 bytes_written += ret;
134 buf = &data[old & md->mask];
139 int ret = write(output, buf, size);
142 die("failed to write");
147 bytes_written += ret;
153 static volatile int done = 0;
155 static void sig_handler(int sig)
160 static struct pollfd event_array[MAX_NR_CPUS * MAX_COUNTERS];
161 static struct mmap_data mmap_array[MAX_NR_CPUS][MAX_COUNTERS];
167 struct perf_event_header header;
173 char filename[PATH_MAX];
177 struct perf_event_header header;
183 static void pid_synthesize_comm_event(pid_t pid, int full)
185 struct comm_event comm_ev;
186 char filename[PATH_MAX];
192 struct dirent dirent, *next;
194 snprintf(filename, sizeof(filename), "/proc/%d/stat", pid);
196 fd = open(filename, O_RDONLY);
198 fprintf(stderr, "couldn't open %s\n", filename);
201 if (read(fd, bf, sizeof(bf)) < 0) {
202 fprintf(stderr, "couldn't read %s\n", filename);
207 /* 9027 (cat) R 6747 9027 6747 34816 9027 ... */
208 memset(&comm_ev, 0, sizeof(comm_ev));
209 field = strchr(bf, '(');
212 sep = strchr(++field, ')');
216 memcpy(comm_ev.comm, field, size++);
219 comm_ev.header.type = PERF_EVENT_COMM;
220 size = ALIGN(size, sizeof(uint64_t));
221 comm_ev.header.size = sizeof(comm_ev) - (sizeof(comm_ev.comm) - size);
226 ret = write(output, &comm_ev, comm_ev.header.size);
228 perror("failed to write");
234 snprintf(filename, sizeof(filename), "/proc/%d/task", pid);
236 tasks = opendir(filename);
237 while (!readdir_r(tasks, &dirent, &next) && next) {
239 pid = strtol(dirent.d_name, &end, 10);
245 ret = write(output, &comm_ev, comm_ev.header.size);
247 perror("failed to write");
255 fprintf(stderr, "couldn't get COMM and pgid, malformed %s\n",
260 static void pid_synthesize_mmap_samples(pid_t pid)
262 char filename[PATH_MAX];
265 snprintf(filename, sizeof(filename), "/proc/%d/maps", pid);
267 fp = fopen(filename, "r");
269 fprintf(stderr, "couldn't open %s\n", filename);
273 char bf[BUFSIZ], *pbf = bf;
274 struct mmap_event mmap_ev = {
275 .header.type = PERF_EVENT_MMAP,
279 if (fgets(bf, sizeof(bf), fp) == NULL)
282 /* 00400000-0040c000 r-xp 00000000 fd:01 41038 /bin/cat */
283 n = hex2u64(pbf, &mmap_ev.start);
287 n = hex2u64(pbf, &mmap_ev.len);
291 if (*pbf == 'x') { /* vm_exec */
292 char *execname = strrchr(bf, ' ');
294 if (execname == NULL || execname[1] != '/')
298 size = strlen(execname);
299 execname[size - 1] = '\0'; /* Remove \n */
300 memcpy(mmap_ev.filename, execname, size);
301 size = ALIGN(size, sizeof(uint64_t));
302 mmap_ev.len -= mmap_ev.start;
303 mmap_ev.header.size = (sizeof(mmap_ev) -
304 (sizeof(mmap_ev.filename) - size));
308 if (write(output, &mmap_ev, mmap_ev.header.size) < 0) {
309 perror("failed to write");
318 static void synthesize_samples(void)
321 struct dirent dirent, *next;
323 proc = opendir("/proc");
325 while (!readdir_r(proc, &dirent, &next) && next) {
329 pid = strtol(dirent.d_name, &end, 10);
330 if (*end) /* only interested in proper numerical dirents */
333 pid_synthesize_comm_event(pid, 1);
334 pid_synthesize_mmap_samples(pid);
342 static void create_counter(int counter, int cpu, pid_t pid)
344 struct perf_counter_attr attr;
347 memset(&attr, 0, sizeof(attr));
348 attr.config = event_id[counter];
349 attr.sample_period = event_count[counter];
350 attr.sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_TID | PERF_SAMPLE_PERIOD;
354 attr.inherit = (cpu < 0) && inherit;
356 track = 0; /* only the first counter needs these */
358 fd[nr_cpu][counter] = sys_perf_counter_open(&attr, pid, cpu, group_fd, 0);
360 if (fd[nr_cpu][counter] < 0) {
363 error("syscall returned with %d (%s)\n",
364 fd[nr_cpu][counter], strerror(err));
366 printf("Are you root?\n");
369 assert(fd[nr_cpu][counter] >= 0);
370 fcntl(fd[nr_cpu][counter], F_SETFL, O_NONBLOCK);
373 * First counter acts as the group leader:
375 if (group && group_fd == -1)
376 group_fd = fd[nr_cpu][counter];
378 event_array[nr_poll].fd = fd[nr_cpu][counter];
379 event_array[nr_poll].events = POLLIN;
382 mmap_array[nr_cpu][counter].counter = counter;
383 mmap_array[nr_cpu][counter].prev = 0;
384 mmap_array[nr_cpu][counter].mask = mmap_pages*page_size - 1;
385 mmap_array[nr_cpu][counter].base = mmap(NULL, (mmap_pages+1)*page_size,
386 PROT_READ, MAP_SHARED, fd[nr_cpu][counter], 0);
387 if (mmap_array[nr_cpu][counter].base == MAP_FAILED) {
388 error("failed to mmap with %d (%s)\n", errno, strerror(errno));
393 static void open_counters(int cpu, pid_t pid)
398 pid_synthesize_comm_event(pid, 0);
399 pid_synthesize_mmap_samples(pid);
403 for (counter = 0; counter < nr_counters; counter++)
404 create_counter(counter, cpu, pid);
409 static int __cmd_record(int argc, const char **argv)
417 page_size = sysconf(_SC_PAGE_SIZE);
418 nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
419 assert(nr_cpus <= MAX_NR_CPUS);
420 assert(nr_cpus >= 0);
422 if (!stat(output_name, &st) && !force && !append_file) {
423 fprintf(stderr, "Error, output file %s exists, use -A to append or -f to overwrite.\n",
428 flags = O_CREAT|O_RDWR;
434 output = open(output_name, flags, S_IRUSR|S_IWUSR);
436 perror("failed to create output file");
441 open_counters(-1, target_pid != -1 ? target_pid : getpid());
442 } else for (i = 0; i < nr_cpus; i++)
443 open_counters(i, target_pid);
445 signal(SIGCHLD, sig_handler);
446 signal(SIGINT, sig_handler);
448 if (target_pid == -1 && argc) {
451 perror("failed to fork");
454 if (execvp(argv[0], (char **)argv)) {
462 struct sched_param param;
464 param.sched_priority = realtime_prio;
465 if (sched_setscheduler(0, SCHED_FIFO, ¶m)) {
466 printf("Could not set realtime priority.\n");
472 synthesize_samples();
477 for (i = 0; i < nr_cpu; i++) {
478 for (counter = 0; counter < nr_counters; counter++)
479 mmap_read(&mmap_array[i][counter]);
483 ret = poll(event_array, nr_poll, 100);
487 * Approximate RIP event size: 24 bytes.
490 "[ perf record: Captured and wrote %.3f MB %s (~%lld samples) ]\n",
491 (double)bytes_written / 1024.0 / 1024.0,
498 static const char * const record_usage[] = {
499 "perf record [<options>] [<command>]",
500 "perf record [<options>] -- <command> [<options>]",
504 static char events_help_msg[EVENTS_HELP_MAX];
506 static const struct option options[] = {
507 OPT_CALLBACK('e', "event", NULL, "event",
508 events_help_msg, parse_events),
509 OPT_INTEGER('p', "pid", &target_pid,
510 "record events on existing pid"),
511 OPT_INTEGER('r', "realtime", &realtime_prio,
512 "collect data with this RT SCHED_FIFO priority"),
513 OPT_BOOLEAN('a', "all-cpus", &system_wide,
514 "system-wide collection from all CPUs"),
515 OPT_BOOLEAN('A', "append", &append_file,
516 "append to the output file to do incremental profiling"),
517 OPT_BOOLEAN('f', "force", &force,
518 "overwrite existing data file"),
519 OPT_LONG('c', "count", &default_interval,
520 "event period to sample"),
521 OPT_STRING('o', "output", &output_name, "file",
523 OPT_BOOLEAN('i', "inherit", &inherit,
524 "child tasks inherit counters"),
525 OPT_INTEGER('F', "freq", &freq,
526 "profile at this frequency"),
527 OPT_INTEGER('m', "mmap-pages", &mmap_pages,
528 "number of mmap data pages"),
532 int cmd_record(int argc, const char **argv, const char *prefix)
536 create_events_help(events_help_msg);
538 argc = parse_options(argc, argv, options, record_usage, 0);
539 if (!argc && target_pid == -1 && !system_wide)
540 usage_with_options(record_usage, options);
548 default_interval = freq;
551 for (counter = 0; counter < nr_counters; counter++) {
552 if (event_count[counter])
555 event_count[counter] = default_interval;
558 return __cmd_record(argc, argv);