perf record/report: Add call graph / call chain profiling
[safe/jmp/linux-2.6] / tools / perf / builtin-record.c
1 /*
2  * builtin-record.c
3  *
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"
9
10 #include "perf.h"
11
12 #include "util/util.h"
13 #include "util/parse-options.h"
14 #include "util/parse-events.h"
15 #include "util/string.h"
16
17 #include <unistd.h>
18 #include <sched.h>
19
20 #define ALIGN(x, a)             __ALIGN_MASK(x, (typeof(x))(a)-1)
21 #define __ALIGN_MASK(x, mask)   (((x)+(mask))&~(mask))
22
23 static int                      fd[MAX_NR_CPUS][MAX_COUNTERS];
24
25 static long                     default_interval                = 100000;
26
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;
42
43 static long                     samples;
44 static struct timeval           last_read;
45 static struct timeval           this_read;
46
47 static __u64                    bytes_written;
48
49 static struct pollfd            event_array[MAX_NR_CPUS * MAX_COUNTERS];
50
51 static int                      nr_poll;
52 static int                      nr_cpu;
53
54 struct mmap_event {
55         struct perf_event_header        header;
56         __u32                           pid;
57         __u32                           tid;
58         __u64                           start;
59         __u64                           len;
60         __u64                           pgoff;
61         char                            filename[PATH_MAX];
62 };
63
64 struct comm_event {
65         struct perf_event_header        header;
66         __u32                           pid;
67         __u32                           tid;
68         char                            comm[16];
69 };
70
71
72 struct mmap_data {
73         int                     counter;
74         void                    *base;
75         unsigned int            mask;
76         unsigned int            prev;
77 };
78
79 static struct mmap_data         mmap_array[MAX_NR_CPUS][MAX_COUNTERS];
80
81 static unsigned int mmap_read_head(struct mmap_data *md)
82 {
83         struct perf_counter_mmap_page *pc = md->base;
84         int head;
85
86         head = pc->data_head;
87         rmb();
88
89         return head;
90 }
91
92 static void mmap_read(struct mmap_data *md)
93 {
94         unsigned int head = mmap_read_head(md);
95         unsigned int old = md->prev;
96         unsigned char *data = md->base + page_size;
97         unsigned long size;
98         void *buf;
99         int diff;
100
101         gettimeofday(&this_read, NULL);
102
103         /*
104          * If we're further behind than half the buffer, there's a chance
105          * the writer will bite our tail and mess up the samples under us.
106          *
107          * If we somehow ended up ahead of the head, we got messed up.
108          *
109          * In either case, truncate and restart at head.
110          */
111         diff = head - old;
112         if (diff > md->mask / 2 || diff < 0) {
113                 struct timeval iv;
114                 unsigned long msecs;
115
116                 timersub(&this_read, &last_read, &iv);
117                 msecs = iv.tv_sec*1000 + iv.tv_usec/1000;
118
119                 fprintf(stderr, "WARNING: failed to keep up with mmap data."
120                                 "  Last read %lu msecs ago.\n", msecs);
121
122                 /*
123                  * head points to a known good entry, start there.
124                  */
125                 old = head;
126         }
127
128         last_read = this_read;
129
130         if (old != head)
131                 samples++;
132
133         size = head - old;
134
135         if ((old & md->mask) + size != (head & md->mask)) {
136                 buf = &data[old & md->mask];
137                 size = md->mask + 1 - (old & md->mask);
138                 old += size;
139
140                 while (size) {
141                         int ret = write(output, buf, size);
142
143                         if (ret < 0)
144                                 die("failed to write");
145
146                         size -= ret;
147                         buf += ret;
148
149                         bytes_written += ret;
150                 }
151         }
152
153         buf = &data[old & md->mask];
154         size = head - old;
155         old += size;
156
157         while (size) {
158                 int ret = write(output, buf, size);
159
160                 if (ret < 0)
161                         die("failed to write");
162
163                 size -= ret;
164                 buf += ret;
165
166                 bytes_written += ret;
167         }
168
169         md->prev = old;
170 }
171
172 static volatile int done = 0;
173 static volatile int signr = -1;
174
175 static void sig_handler(int sig)
176 {
177         done = 1;
178         signr = sig;
179 }
180
181 static void sig_atexit(void)
182 {
183         if (signr == -1)
184                 return;
185
186         signal(signr, SIG_DFL);
187         kill(getpid(), signr);
188 }
189
190 static void pid_synthesize_comm_event(pid_t pid, int full)
191 {
192         struct comm_event comm_ev;
193         char filename[PATH_MAX];
194         char bf[BUFSIZ];
195         int fd, ret;
196         size_t size;
197         char *field, *sep;
198         DIR *tasks;
199         struct dirent dirent, *next;
200
201         snprintf(filename, sizeof(filename), "/proc/%d/stat", pid);
202
203         fd = open(filename, O_RDONLY);
204         if (fd < 0) {
205                 fprintf(stderr, "couldn't open %s\n", filename);
206                 exit(EXIT_FAILURE);
207         }
208         if (read(fd, bf, sizeof(bf)) < 0) {
209                 fprintf(stderr, "couldn't read %s\n", filename);
210                 exit(EXIT_FAILURE);
211         }
212         close(fd);
213
214         /* 9027 (cat) R 6747 9027 6747 34816 9027 ... */
215         memset(&comm_ev, 0, sizeof(comm_ev));
216         field = strchr(bf, '(');
217         if (field == NULL)
218                 goto out_failure;
219         sep = strchr(++field, ')');
220         if (sep == NULL)
221                 goto out_failure;
222         size = sep - field;
223         memcpy(comm_ev.comm, field, size++);
224
225         comm_ev.pid = pid;
226         comm_ev.header.type = PERF_EVENT_COMM;
227         size = ALIGN(size, sizeof(__u64));
228         comm_ev.header.size = sizeof(comm_ev) - (sizeof(comm_ev.comm) - size);
229
230         if (!full) {
231                 comm_ev.tid = pid;
232
233                 ret = write(output, &comm_ev, comm_ev.header.size);
234                 if (ret < 0) {
235                         perror("failed to write");
236                         exit(-1);
237                 }
238                 return;
239         }
240
241         snprintf(filename, sizeof(filename), "/proc/%d/task", pid);
242
243         tasks = opendir(filename);
244         while (!readdir_r(tasks, &dirent, &next) && next) {
245                 char *end;
246                 pid = strtol(dirent.d_name, &end, 10);
247                 if (*end)
248                         continue;
249
250                 comm_ev.tid = pid;
251
252                 ret = write(output, &comm_ev, comm_ev.header.size);
253                 if (ret < 0) {
254                         perror("failed to write");
255                         exit(-1);
256                 }
257         }
258         closedir(tasks);
259         return;
260
261 out_failure:
262         fprintf(stderr, "couldn't get COMM and pgid, malformed %s\n",
263                 filename);
264         exit(EXIT_FAILURE);
265 }
266
267 static void pid_synthesize_mmap_samples(pid_t pid)
268 {
269         char filename[PATH_MAX];
270         FILE *fp;
271
272         snprintf(filename, sizeof(filename), "/proc/%d/maps", pid);
273
274         fp = fopen(filename, "r");
275         if (fp == NULL) {
276                 fprintf(stderr, "couldn't open %s\n", filename);
277                 exit(EXIT_FAILURE);
278         }
279         while (1) {
280                 char bf[BUFSIZ], *pbf = bf;
281                 struct mmap_event mmap_ev = {
282                         .header.type = PERF_EVENT_MMAP,
283                 };
284                 int n;
285                 size_t size;
286                 if (fgets(bf, sizeof(bf), fp) == NULL)
287                         break;
288
289                 /* 00400000-0040c000 r-xp 00000000 fd:01 41038  /bin/cat */
290                 n = hex2u64(pbf, &mmap_ev.start);
291                 if (n < 0)
292                         continue;
293                 pbf += n + 1;
294                 n = hex2u64(pbf, &mmap_ev.len);
295                 if (n < 0)
296                         continue;
297                 pbf += n + 3;
298                 if (*pbf == 'x') { /* vm_exec */
299                         char *execname = strrchr(bf, ' ');
300
301                         if (execname == NULL || execname[1] != '/')
302                                 continue;
303
304                         execname += 1;
305                         size = strlen(execname);
306                         execname[size - 1] = '\0'; /* Remove \n */
307                         memcpy(mmap_ev.filename, execname, size);
308                         size = ALIGN(size, sizeof(__u64));
309                         mmap_ev.len -= mmap_ev.start;
310                         mmap_ev.header.size = (sizeof(mmap_ev) -
311                                                (sizeof(mmap_ev.filename) - size));
312                         mmap_ev.pid = pid;
313                         mmap_ev.tid = pid;
314
315                         if (write(output, &mmap_ev, mmap_ev.header.size) < 0) {
316                                 perror("failed to write");
317                                 exit(-1);
318                         }
319                 }
320         }
321
322         fclose(fp);
323 }
324
325 static void synthesize_samples(void)
326 {
327         DIR *proc;
328         struct dirent dirent, *next;
329
330         proc = opendir("/proc");
331
332         while (!readdir_r(proc, &dirent, &next) && next) {
333                 char *end;
334                 pid_t pid;
335
336                 pid = strtol(dirent.d_name, &end, 10);
337                 if (*end) /* only interested in proper numerical dirents */
338                         continue;
339
340                 pid_synthesize_comm_event(pid, 1);
341                 pid_synthesize_mmap_samples(pid);
342         }
343
344         closedir(proc);
345 }
346
347 static int group_fd;
348
349 static void create_counter(int counter, int cpu, pid_t pid)
350 {
351         struct perf_counter_attr *attr = attrs + counter;
352         int track = 1;
353
354         attr->sample_type       = PERF_SAMPLE_IP | PERF_SAMPLE_TID;
355
356         if (freq) {
357                 attr->sample_type       |= PERF_SAMPLE_PERIOD;
358                 attr->freq              = 1;
359                 attr->sample_freq       = freq;
360         }
361
362         if (call_graph)
363                 attr->sample_type       |= PERF_SAMPLE_CALLCHAIN;
364
365         attr->mmap              = track;
366         attr->comm              = track;
367         attr->inherit           = (cpu < 0) && inherit;
368         attr->disabled          = 1;
369
370         track = 0; /* only the first counter needs these */
371
372 try_again:
373         fd[nr_cpu][counter] = sys_perf_counter_open(attr, pid, cpu, group_fd, 0);
374
375         if (fd[nr_cpu][counter] < 0) {
376                 int err = errno;
377
378                 if (err == EPERM)
379                         die("Permission error - are you root?\n");
380
381                 /*
382                  * If it's cycles then fall back to hrtimer
383                  * based cpu-clock-tick sw counter, which
384                  * is always available even if no PMU support:
385                  */
386                 if (attr->type == PERF_TYPE_HARDWARE
387                         && attr->config == PERF_COUNT_HW_CPU_CYCLES) {
388
389                         if (verbose)
390                                 warning(" ... trying to fall back to cpu-clock-ticks\n");
391                         attr->type = PERF_TYPE_SOFTWARE;
392                         attr->config = PERF_COUNT_SW_CPU_CLOCK;
393                         goto try_again;
394                 }
395                 printf("\n");
396                 error("perfcounter syscall returned with %d (%s)\n",
397                         fd[nr_cpu][counter], strerror(err));
398                 die("No CONFIG_PERF_COUNTERS=y kernel support configured?\n");
399                 exit(-1);
400         }
401
402         assert(fd[nr_cpu][counter] >= 0);
403         fcntl(fd[nr_cpu][counter], F_SETFL, O_NONBLOCK);
404
405         /*
406          * First counter acts as the group leader:
407          */
408         if (group && group_fd == -1)
409                 group_fd = fd[nr_cpu][counter];
410
411         event_array[nr_poll].fd = fd[nr_cpu][counter];
412         event_array[nr_poll].events = POLLIN;
413         nr_poll++;
414
415         mmap_array[nr_cpu][counter].counter = counter;
416         mmap_array[nr_cpu][counter].prev = 0;
417         mmap_array[nr_cpu][counter].mask = mmap_pages*page_size - 1;
418         mmap_array[nr_cpu][counter].base = mmap(NULL, (mmap_pages+1)*page_size,
419                         PROT_READ, MAP_SHARED, fd[nr_cpu][counter], 0);
420         if (mmap_array[nr_cpu][counter].base == MAP_FAILED) {
421                 error("failed to mmap with %d (%s)\n", errno, strerror(errno));
422                 exit(-1);
423         }
424
425         ioctl(fd[nr_cpu][counter], PERF_COUNTER_IOC_ENABLE);
426 }
427
428 static void open_counters(int cpu, pid_t pid)
429 {
430         int counter;
431
432         if (pid > 0) {
433                 pid_synthesize_comm_event(pid, 0);
434                 pid_synthesize_mmap_samples(pid);
435         }
436
437         group_fd = -1;
438         for (counter = 0; counter < nr_counters; counter++)
439                 create_counter(counter, cpu, pid);
440
441         nr_cpu++;
442 }
443
444 static int __cmd_record(int argc, const char **argv)
445 {
446         int i, counter;
447         struct stat st;
448         pid_t pid;
449         int flags;
450         int ret;
451
452         page_size = sysconf(_SC_PAGE_SIZE);
453         nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
454         assert(nr_cpus <= MAX_NR_CPUS);
455         assert(nr_cpus >= 0);
456
457         if (!stat(output_name, &st) && !force && !append_file) {
458                 fprintf(stderr, "Error, output file %s exists, use -A to append or -f to overwrite.\n",
459                                 output_name);
460                 exit(-1);
461         }
462
463         flags = O_CREAT|O_RDWR;
464         if (append_file)
465                 flags |= O_APPEND;
466         else
467                 flags |= O_TRUNC;
468
469         output = open(output_name, flags, S_IRUSR|S_IWUSR);
470         if (output < 0) {
471                 perror("failed to create output file");
472                 exit(-1);
473         }
474
475         if (!system_wide) {
476                 open_counters(-1, target_pid != -1 ? target_pid : getpid());
477         } else for (i = 0; i < nr_cpus; i++)
478                 open_counters(i, target_pid);
479
480         atexit(sig_atexit);
481         signal(SIGCHLD, sig_handler);
482         signal(SIGINT, sig_handler);
483
484         if (target_pid == -1 && argc) {
485                 pid = fork();
486                 if (pid < 0)
487                         perror("failed to fork");
488
489                 if (!pid) {
490                         if (execvp(argv[0], (char **)argv)) {
491                                 perror(argv[0]);
492                                 exit(-1);
493                         }
494                 }
495         }
496
497         if (realtime_prio) {
498                 struct sched_param param;
499
500                 param.sched_priority = realtime_prio;
501                 if (sched_setscheduler(0, SCHED_FIFO, &param)) {
502                         printf("Could not set realtime priority.\n");
503                         exit(-1);
504                 }
505         }
506
507         if (system_wide)
508                 synthesize_samples();
509
510         while (!done) {
511                 int hits = samples;
512
513                 for (i = 0; i < nr_cpu; i++) {
514                         for (counter = 0; counter < nr_counters; counter++)
515                                 mmap_read(&mmap_array[i][counter]);
516                 }
517
518                 if (hits == samples)
519                         ret = poll(event_array, nr_poll, 100);
520         }
521
522         /*
523          * Approximate RIP event size: 24 bytes.
524          */
525         fprintf(stderr,
526                 "[ perf record: Captured and wrote %.3f MB %s (~%lld samples) ]\n",
527                 (double)bytes_written / 1024.0 / 1024.0,
528                 output_name,
529                 bytes_written / 24);
530
531         return 0;
532 }
533
534 static const char * const record_usage[] = {
535         "perf record [<options>] [<command>]",
536         "perf record [<options>] -- <command> [<options>]",
537         NULL
538 };
539
540 static const struct option options[] = {
541         OPT_CALLBACK('e', "event", NULL, "event",
542                      "event selector. use 'perf list' to list available events",
543                      parse_events),
544         OPT_INTEGER('p', "pid", &target_pid,
545                     "record events on existing pid"),
546         OPT_INTEGER('r', "realtime", &realtime_prio,
547                     "collect data with this RT SCHED_FIFO priority"),
548         OPT_BOOLEAN('a', "all-cpus", &system_wide,
549                             "system-wide collection from all CPUs"),
550         OPT_BOOLEAN('A', "append", &append_file,
551                             "append to the output file to do incremental profiling"),
552         OPT_BOOLEAN('f', "force", &force,
553                         "overwrite existing data file"),
554         OPT_LONG('c', "count", &default_interval,
555                     "event period to sample"),
556         OPT_STRING('o', "output", &output_name, "file",
557                     "output file name"),
558         OPT_BOOLEAN('i', "inherit", &inherit,
559                     "child tasks inherit counters"),
560         OPT_INTEGER('F', "freq", &freq,
561                     "profile at this frequency"),
562         OPT_INTEGER('m', "mmap-pages", &mmap_pages,
563                     "number of mmap data pages"),
564         OPT_BOOLEAN('g', "call-graph", &call_graph,
565                     "do call-graph (stack chain/backtrace) recording"),
566         OPT_BOOLEAN('v', "verbose", &verbose,
567                     "be more verbose (show counter open errors, etc)"),
568         OPT_END()
569 };
570
571 int cmd_record(int argc, const char **argv, const char *prefix)
572 {
573         int counter;
574
575         argc = parse_options(argc, argv, options, record_usage, 0);
576         if (!argc && target_pid == -1 && !system_wide)
577                 usage_with_options(record_usage, options);
578
579         if (!nr_counters) {
580                 nr_counters     = 1;
581                 attrs[0].type   = PERF_TYPE_HARDWARE;
582                 attrs[0].config = PERF_COUNT_HW_CPU_CYCLES;
583         }
584
585         for (counter = 0; counter < nr_counters; counter++) {
586                 if (attrs[counter].sample_period)
587                         continue;
588
589                 attrs[counter].sample_period = default_interval;
590         }
591
592         return __cmd_record(argc, argv);
593 }