perf record: Fix filemap pathname parsing in /proc/pid/maps
[linux-2.6/mini2440.git] / tools / perf / builtin-record.c
blob9b899ba1b410816dbf216e73345012e67e0bee09
1 /*
2 * builtin-record.c
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.
7 */
8 #include "builtin.h"
10 #include "perf.h"
12 #include "util/util.h"
13 #include "util/parse-options.h"
14 #include "util/parse-events.h"
15 #include "util/string.h"
17 #include <unistd.h>
18 #include <sched.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;
30 static int freq = 0;
31 static int output;
32 static const char *output_name = "perf.data";
33 static int group = 0;
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;
38 static int force = 0;
39 static int append_file = 0;
40 static int call_graph = 0;
41 static int verbose = 0;
43 static long samples;
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];
51 static int nr_poll;
52 static int nr_cpu;
54 static int file_new = 1;
55 static struct perf_file_header file_header;
57 struct mmap_event {
58 struct perf_event_header header;
59 u32 pid;
60 u32 tid;
61 u64 start;
62 u64 len;
63 u64 pgoff;
64 char filename[PATH_MAX];
67 struct comm_event {
68 struct perf_event_header header;
69 u32 pid;
70 u32 tid;
71 char comm[16];
75 struct mmap_data {
76 int counter;
77 void *base;
78 unsigned int mask;
79 unsigned int prev;
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;
87 long head;
89 head = pc->data_head;
90 rmb();
92 return head;
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.
102 /* mb(); */
103 pc->data_tail = tail;
106 static void write_output(void *buf, size_t size)
108 while (size) {
109 int ret = write(output, buf, size);
111 if (ret < 0)
112 die("failed to write");
114 size -= ret;
115 buf += ret;
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;
126 unsigned long size;
127 void *buf;
128 int diff;
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.
140 diff = head - old;
141 if (diff < 0) {
142 struct timeval iv;
143 unsigned long msecs;
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.
154 old = head;
157 last_read = this_read;
159 if (old != head)
160 samples++;
162 size = head - old;
164 if ((old & md->mask) + size != (head & md->mask)) {
165 buf = &data[old & md->mask];
166 size = md->mask + 1 - (old & md->mask);
167 old += size;
169 write_output(buf, size);
172 buf = &data[old & md->mask];
173 size = head - old;
174 old += size;
176 write_output(buf, size);
178 md->prev = old;
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)
187 done = 1;
188 signr = sig;
191 static void sig_atexit(void)
193 if (signr == -1)
194 return;
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];
204 char bf[BUFSIZ];
205 int fd;
206 size_t size;
207 char *field, *sep;
208 DIR *tasks;
209 struct dirent dirent, *next;
211 snprintf(filename, sizeof(filename), "/proc/%d/stat", pid);
213 fd = open(filename, O_RDONLY);
214 if (fd < 0) {
216 * We raced with a task exiting - just return:
218 if (verbose)
219 fprintf(stderr, "couldn't open %s\n", filename);
220 return;
222 if (read(fd, bf, sizeof(bf)) < 0) {
223 fprintf(stderr, "couldn't read %s\n", filename);
224 exit(EXIT_FAILURE);
226 close(fd);
228 /* 9027 (cat) R 6747 9027 6747 34816 9027 ... */
229 memset(&comm_ev, 0, sizeof(comm_ev));
230 field = strchr(bf, '(');
231 if (field == NULL)
232 goto out_failure;
233 sep = strchr(++field, ')');
234 if (sep == NULL)
235 goto out_failure;
236 size = sep - field;
237 memcpy(comm_ev.comm, field, size++);
239 comm_ev.pid = pid;
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);
244 if (!full) {
245 comm_ev.tid = pid;
247 write_output(&comm_ev, comm_ev.header.size);
248 return;
251 snprintf(filename, sizeof(filename), "/proc/%d/task", pid);
253 tasks = opendir(filename);
254 while (!readdir_r(tasks, &dirent, &next) && next) {
255 char *end;
256 pid = strtol(dirent.d_name, &end, 10);
257 if (*end)
258 continue;
260 comm_ev.tid = pid;
262 write_output(&comm_ev, comm_ev.header.size);
264 closedir(tasks);
265 return;
267 out_failure:
268 fprintf(stderr, "couldn't get COMM and pgid, malformed %s\n",
269 filename);
270 exit(EXIT_FAILURE);
273 static void pid_synthesize_mmap_samples(pid_t pid)
275 char filename[PATH_MAX];
276 FILE *fp;
278 snprintf(filename, sizeof(filename), "/proc/%d/maps", pid);
280 fp = fopen(filename, "r");
281 if (fp == NULL) {
283 * We raced with a task exiting - just return:
285 if (verbose)
286 fprintf(stderr, "couldn't open %s\n", filename);
287 return;
289 while (1) {
290 char bf[BUFSIZ], *pbf = bf;
291 struct mmap_event mmap_ev = {
292 .header.type = PERF_EVENT_MMAP,
294 int n;
295 size_t size;
296 if (fgets(bf, sizeof(bf), fp) == NULL)
297 break;
299 /* 00400000-0040c000 r-xp 00000000 fd:01 41038 /bin/cat */
300 n = hex2u64(pbf, &mmap_ev.start);
301 if (n < 0)
302 continue;
303 pbf += n + 1;
304 n = hex2u64(pbf, &mmap_ev.len);
305 if (n < 0)
306 continue;
307 pbf += n + 3;
308 if (*pbf == 'x') { /* vm_exec */
309 char *execname = strchr(bf, '/');
311 if (execname == NULL)
312 continue;
314 size = strlen(execname);
315 execname[size - 1] = '\0'; /* Remove \n */
316 memcpy(mmap_ev.filename, execname, size);
317 size = ALIGN(size, sizeof(u64));
318 mmap_ev.len -= mmap_ev.start;
319 mmap_ev.header.size = (sizeof(mmap_ev) -
320 (sizeof(mmap_ev.filename) - size));
321 mmap_ev.pid = pid;
322 mmap_ev.tid = pid;
324 write_output(&mmap_ev, mmap_ev.header.size);
328 fclose(fp);
331 static void synthesize_samples(void)
333 DIR *proc;
334 struct dirent dirent, *next;
336 proc = opendir("/proc");
338 while (!readdir_r(proc, &dirent, &next) && next) {
339 char *end;
340 pid_t pid;
342 pid = strtol(dirent.d_name, &end, 10);
343 if (*end) /* only interested in proper numerical dirents */
344 continue;
346 pid_synthesize_comm_event(pid, 1);
347 pid_synthesize_mmap_samples(pid);
350 closedir(proc);
353 static int group_fd;
355 static void create_counter(int counter, int cpu, pid_t pid)
357 struct perf_counter_attr *attr = attrs + counter;
358 int track = 1;
360 attr->sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_TID;
362 if (freq) {
363 attr->sample_type |= PERF_SAMPLE_PERIOD;
364 attr->freq = 1;
365 attr->sample_freq = freq;
368 if (call_graph)
369 attr->sample_type |= PERF_SAMPLE_CALLCHAIN;
371 if (file_new) {
372 file_header.sample_type = attr->sample_type;
373 } else {
374 if (file_header.sample_type != attr->sample_type) {
375 fprintf(stderr, "incompatible append\n");
376 exit(-1);
380 attr->mmap = track;
381 attr->comm = track;
382 attr->inherit = (cpu < 0) && inherit;
383 attr->disabled = 1;
385 track = 0; /* only the first counter needs these */
387 try_again:
388 fd[nr_cpu][counter] = sys_perf_counter_open(attr, pid, cpu, group_fd, 0);
390 if (fd[nr_cpu][counter] < 0) {
391 int err = errno;
393 if (err == EPERM)
394 die("Permission error - are you root?\n");
397 * If it's cycles then fall back to hrtimer
398 * based cpu-clock-tick sw counter, which
399 * is always available even if no PMU support:
401 if (attr->type == PERF_TYPE_HARDWARE
402 && attr->config == PERF_COUNT_HW_CPU_CYCLES) {
404 if (verbose)
405 warning(" ... trying to fall back to cpu-clock-ticks\n");
406 attr->type = PERF_TYPE_SOFTWARE;
407 attr->config = PERF_COUNT_SW_CPU_CLOCK;
408 goto try_again;
410 printf("\n");
411 error("perfcounter syscall returned with %d (%s)\n",
412 fd[nr_cpu][counter], strerror(err));
413 die("No CONFIG_PERF_COUNTERS=y kernel support configured?\n");
414 exit(-1);
417 assert(fd[nr_cpu][counter] >= 0);
418 fcntl(fd[nr_cpu][counter], F_SETFL, O_NONBLOCK);
421 * First counter acts as the group leader:
423 if (group && group_fd == -1)
424 group_fd = fd[nr_cpu][counter];
426 event_array[nr_poll].fd = fd[nr_cpu][counter];
427 event_array[nr_poll].events = POLLIN;
428 nr_poll++;
430 mmap_array[nr_cpu][counter].counter = counter;
431 mmap_array[nr_cpu][counter].prev = 0;
432 mmap_array[nr_cpu][counter].mask = mmap_pages*page_size - 1;
433 mmap_array[nr_cpu][counter].base = mmap(NULL, (mmap_pages+1)*page_size,
434 PROT_READ|PROT_WRITE, MAP_SHARED, fd[nr_cpu][counter], 0);
435 if (mmap_array[nr_cpu][counter].base == MAP_FAILED) {
436 error("failed to mmap with %d (%s)\n", errno, strerror(errno));
437 exit(-1);
440 ioctl(fd[nr_cpu][counter], PERF_COUNTER_IOC_ENABLE);
443 static void open_counters(int cpu, pid_t pid)
445 int counter;
447 if (pid > 0) {
448 pid_synthesize_comm_event(pid, 0);
449 pid_synthesize_mmap_samples(pid);
452 group_fd = -1;
453 for (counter = 0; counter < nr_counters; counter++)
454 create_counter(counter, cpu, pid);
456 nr_cpu++;
459 static void atexit_header(void)
461 file_header.data_size += bytes_written;
463 if (pwrite(output, &file_header, sizeof(file_header), 0) == -1)
464 perror("failed to write on file headers");
467 static int __cmd_record(int argc, const char **argv)
469 int i, counter;
470 struct stat st;
471 pid_t pid;
472 int flags;
473 int ret;
475 page_size = sysconf(_SC_PAGE_SIZE);
476 nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
477 assert(nr_cpus <= MAX_NR_CPUS);
478 assert(nr_cpus >= 0);
480 atexit(sig_atexit);
481 signal(SIGCHLD, sig_handler);
482 signal(SIGINT, sig_handler);
484 if (!stat(output_name, &st) && !force && !append_file) {
485 fprintf(stderr, "Error, output file %s exists, use -A to append or -f to overwrite.\n",
486 output_name);
487 exit(-1);
490 flags = O_CREAT|O_RDWR;
491 if (append_file)
492 file_new = 0;
493 else
494 flags |= O_TRUNC;
496 output = open(output_name, flags, S_IRUSR|S_IWUSR);
497 if (output < 0) {
498 perror("failed to create output file");
499 exit(-1);
502 if (!file_new) {
503 if (read(output, &file_header, sizeof(file_header)) == -1) {
504 perror("failed to read file headers");
505 exit(-1);
508 lseek(output, file_header.data_size, SEEK_CUR);
511 atexit(atexit_header);
513 if (!system_wide) {
514 open_counters(-1, target_pid != -1 ? target_pid : getpid());
515 } else for (i = 0; i < nr_cpus; i++)
516 open_counters(i, target_pid);
518 if (target_pid == -1 && argc) {
519 pid = fork();
520 if (pid < 0)
521 perror("failed to fork");
523 if (!pid) {
524 if (execvp(argv[0], (char **)argv)) {
525 perror(argv[0]);
526 exit(-1);
531 if (realtime_prio) {
532 struct sched_param param;
534 param.sched_priority = realtime_prio;
535 if (sched_setscheduler(0, SCHED_FIFO, &param)) {
536 printf("Could not set realtime priority.\n");
537 exit(-1);
541 if (system_wide)
542 synthesize_samples();
544 while (!done) {
545 int hits = samples;
547 for (i = 0; i < nr_cpu; i++) {
548 for (counter = 0; counter < nr_counters; counter++)
549 mmap_read(&mmap_array[i][counter]);
552 if (hits == samples)
553 ret = poll(event_array, nr_poll, 100);
557 * Approximate RIP event size: 24 bytes.
559 fprintf(stderr,
560 "[ perf record: Captured and wrote %.3f MB %s (~%lld samples) ]\n",
561 (double)bytes_written / 1024.0 / 1024.0,
562 output_name,
563 bytes_written / 24);
565 return 0;
568 static const char * const record_usage[] = {
569 "perf record [<options>] [<command>]",
570 "perf record [<options>] -- <command> [<options>]",
571 NULL
574 static const struct option options[] = {
575 OPT_CALLBACK('e', "event", NULL, "event",
576 "event selector. use 'perf list' to list available events",
577 parse_events),
578 OPT_INTEGER('p', "pid", &target_pid,
579 "record events on existing pid"),
580 OPT_INTEGER('r', "realtime", &realtime_prio,
581 "collect data with this RT SCHED_FIFO priority"),
582 OPT_BOOLEAN('a', "all-cpus", &system_wide,
583 "system-wide collection from all CPUs"),
584 OPT_BOOLEAN('A', "append", &append_file,
585 "append to the output file to do incremental profiling"),
586 OPT_BOOLEAN('f', "force", &force,
587 "overwrite existing data file"),
588 OPT_LONG('c', "count", &default_interval,
589 "event period to sample"),
590 OPT_STRING('o', "output", &output_name, "file",
591 "output file name"),
592 OPT_BOOLEAN('i', "inherit", &inherit,
593 "child tasks inherit counters"),
594 OPT_INTEGER('F', "freq", &freq,
595 "profile at this frequency"),
596 OPT_INTEGER('m', "mmap-pages", &mmap_pages,
597 "number of mmap data pages"),
598 OPT_BOOLEAN('g', "call-graph", &call_graph,
599 "do call-graph (stack chain/backtrace) recording"),
600 OPT_BOOLEAN('v', "verbose", &verbose,
601 "be more verbose (show counter open errors, etc)"),
602 OPT_END()
605 int cmd_record(int argc, const char **argv, const char *prefix)
607 int counter;
609 argc = parse_options(argc, argv, options, record_usage, 0);
610 if (!argc && target_pid == -1 && !system_wide)
611 usage_with_options(record_usage, options);
613 if (!nr_counters) {
614 nr_counters = 1;
615 attrs[0].type = PERF_TYPE_HARDWARE;
616 attrs[0].config = PERF_COUNT_HW_CPU_CYCLES;
619 for (counter = 0; counter < nr_counters; counter++) {
620 if (attrs[counter].sample_period)
621 continue;
623 attrs[counter].sample_period = default_interval;
626 return __cmd_record(argc, argv);