perf record: Intercept all events
[pandora-kernel.git] / 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 "util/header.h"
18 #include "util/event.h"
19 #include "util/debug.h"
20 #include "util/session.h"
21 #include "util/symbol.h"
22
23 #include <unistd.h>
24 #include <sched.h>
25
26 static int                      fd[MAX_NR_CPUS][MAX_COUNTERS];
27
28 static long                     default_interval                =      0;
29
30 static int                      nr_cpus                         =      0;
31 static unsigned int             page_size;
32 static unsigned int             mmap_pages                      =    128;
33 static int                      freq                            =   1000;
34 static int                      output;
35 static const char               *output_name                    = "perf.data";
36 static int                      group                           =      0;
37 static unsigned int             realtime_prio                   =      0;
38 static int                      raw_samples                     =      0;
39 static int                      system_wide                     =      0;
40 static int                      profile_cpu                     =     -1;
41 static pid_t                    target_pid                      =     -1;
42 static pid_t                    child_pid                       =     -1;
43 static int                      inherit                         =      1;
44 static int                      force                           =      0;
45 static int                      append_file                     =      0;
46 static int                      call_graph                      =      0;
47 static int                      inherit_stat                    =      0;
48 static int                      no_samples                      =      0;
49 static int                      sample_address                  =      0;
50 static int                      multiplex                       =      0;
51 static int                      multiplex_fd                    =     -1;
52
53 static long                     samples                         =      0;
54 static struct timeval           last_read;
55 static struct timeval           this_read;
56
57 static u64                      bytes_written                   =      0;
58
59 static struct pollfd            event_array[MAX_NR_CPUS * MAX_COUNTERS];
60
61 static int                      nr_poll                         =      0;
62 static int                      nr_cpu                          =      0;
63
64 static int                      file_new                        =      1;
65
66 static struct perf_session      *session;
67
68 struct mmap_data {
69         int                     counter;
70         void                    *base;
71         unsigned int            mask;
72         unsigned int            prev;
73 };
74
75 static struct mmap_data         mmap_array[MAX_NR_CPUS][MAX_COUNTERS];
76
77 static unsigned long mmap_read_head(struct mmap_data *md)
78 {
79         struct perf_event_mmap_page *pc = md->base;
80         long head;
81
82         head = pc->data_head;
83         rmb();
84
85         return head;
86 }
87
88 static void mmap_write_tail(struct mmap_data *md, unsigned long tail)
89 {
90         struct perf_event_mmap_page *pc = md->base;
91
92         /*
93          * ensure all reads are done before we write the tail out.
94          */
95         /* mb(); */
96         pc->data_tail = tail;
97 }
98
99 static void write_output(void *buf, size_t size)
100 {
101         while (size) {
102                 int ret = write(output, buf, size);
103
104                 if (ret < 0)
105                         die("failed to write");
106
107                 size -= ret;
108                 buf += ret;
109
110                 bytes_written += ret;
111         }
112 }
113
114 static void write_event(event_t *buf, size_t size)
115 {
116         size_t processed_size = buf->header.size;
117         event_t *ev = buf;
118
119         do {
120                 /*
121                 * Add it to the list of DSOs, so that when we finish this
122                  * record session we can pick the available build-ids.
123                  */
124                 if (ev->header.type == PERF_RECORD_MMAP) {
125                         struct list_head *head = &dsos__user;
126                         if (ev->header.misc == 1)
127                                 head = &dsos__kernel;
128                         __dsos__findnew(head, ev->mmap.filename);
129                 }
130
131                 ev = ((void *)ev) + ev->header.size;
132                 processed_size += ev->header.size;
133         } while (processed_size < size);
134
135         write_output(buf, size);
136 }
137
138 static int process_synthesized_event(event_t *event,
139                                      struct perf_session *self __used)
140 {
141         write_event(event, event->header.size);
142         return 0;
143 }
144
145 static void mmap_read(struct mmap_data *md)
146 {
147         unsigned int head = mmap_read_head(md);
148         unsigned int old = md->prev;
149         unsigned char *data = md->base + page_size;
150         unsigned long size;
151         void *buf;
152         int diff;
153
154         gettimeofday(&this_read, NULL);
155
156         /*
157          * If we're further behind than half the buffer, there's a chance
158          * the writer will bite our tail and mess up the samples under us.
159          *
160          * If we somehow ended up ahead of the head, we got messed up.
161          *
162          * In either case, truncate and restart at head.
163          */
164         diff = head - old;
165         if (diff < 0) {
166                 struct timeval iv;
167                 unsigned long msecs;
168
169                 timersub(&this_read, &last_read, &iv);
170                 msecs = iv.tv_sec*1000 + iv.tv_usec/1000;
171
172                 fprintf(stderr, "WARNING: failed to keep up with mmap data."
173                                 "  Last read %lu msecs ago.\n", msecs);
174
175                 /*
176                  * head points to a known good entry, start there.
177                  */
178                 old = head;
179         }
180
181         last_read = this_read;
182
183         if (old != head)
184                 samples++;
185
186         size = head - old;
187
188         if ((old & md->mask) + size != (head & md->mask)) {
189                 buf = &data[old & md->mask];
190                 size = md->mask + 1 - (old & md->mask);
191                 old += size;
192
193                 write_event(buf, size);
194         }
195
196         buf = &data[old & md->mask];
197         size = head - old;
198         old += size;
199
200         write_event(buf, size);
201
202         md->prev = old;
203         mmap_write_tail(md, old);
204 }
205
206 static volatile int done = 0;
207 static volatile int signr = -1;
208
209 static void sig_handler(int sig)
210 {
211         done = 1;
212         signr = sig;
213 }
214
215 static void sig_atexit(void)
216 {
217         if (child_pid != -1)
218                 kill(child_pid, SIGTERM);
219
220         if (signr == -1)
221                 return;
222
223         signal(signr, SIG_DFL);
224         kill(getpid(), signr);
225 }
226
227 static int group_fd;
228
229 static struct perf_header_attr *get_header_attr(struct perf_event_attr *a, int nr)
230 {
231         struct perf_header_attr *h_attr;
232
233         if (nr < session->header.attrs) {
234                 h_attr = session->header.attr[nr];
235         } else {
236                 h_attr = perf_header_attr__new(a);
237                 if (h_attr != NULL)
238                         if (perf_header__add_attr(&session->header, h_attr) < 0) {
239                                 perf_header_attr__delete(h_attr);
240                                 h_attr = NULL;
241                         }
242         }
243
244         return h_attr;
245 }
246
247 static void create_counter(int counter, int cpu, pid_t pid)
248 {
249         char *filter = filters[counter];
250         struct perf_event_attr *attr = attrs + counter;
251         struct perf_header_attr *h_attr;
252         int track = !counter; /* only the first counter needs these */
253         int ret;
254         struct {
255                 u64 count;
256                 u64 time_enabled;
257                 u64 time_running;
258                 u64 id;
259         } read_data;
260
261         attr->read_format       = PERF_FORMAT_TOTAL_TIME_ENABLED |
262                                   PERF_FORMAT_TOTAL_TIME_RUNNING |
263                                   PERF_FORMAT_ID;
264
265         attr->sample_type       |= PERF_SAMPLE_IP | PERF_SAMPLE_TID;
266
267         if (freq) {
268                 attr->sample_type       |= PERF_SAMPLE_PERIOD;
269                 attr->freq              = 1;
270                 attr->sample_freq       = freq;
271         }
272
273         if (no_samples)
274                 attr->sample_freq = 0;
275
276         if (inherit_stat)
277                 attr->inherit_stat = 1;
278
279         if (sample_address)
280                 attr->sample_type       |= PERF_SAMPLE_ADDR;
281
282         if (call_graph)
283                 attr->sample_type       |= PERF_SAMPLE_CALLCHAIN;
284
285         if (raw_samples) {
286                 attr->sample_type       |= PERF_SAMPLE_TIME;
287                 attr->sample_type       |= PERF_SAMPLE_RAW;
288                 attr->sample_type       |= PERF_SAMPLE_CPU;
289         }
290
291         attr->mmap              = track;
292         attr->comm              = track;
293         attr->inherit           = inherit;
294         attr->disabled          = 1;
295
296 try_again:
297         fd[nr_cpu][counter] = sys_perf_event_open(attr, pid, cpu, group_fd, 0);
298
299         if (fd[nr_cpu][counter] < 0) {
300                 int err = errno;
301
302                 if (err == EPERM || err == EACCES)
303                         die("Permission error - are you root?\n");
304                 else if (err ==  ENODEV && profile_cpu != -1)
305                         die("No such device - did you specify an out-of-range profile CPU?\n");
306
307                 /*
308                  * If it's cycles then fall back to hrtimer
309                  * based cpu-clock-tick sw counter, which
310                  * is always available even if no PMU support:
311                  */
312                 if (attr->type == PERF_TYPE_HARDWARE
313                         && attr->config == PERF_COUNT_HW_CPU_CYCLES) {
314
315                         if (verbose)
316                                 warning(" ... trying to fall back to cpu-clock-ticks\n");
317                         attr->type = PERF_TYPE_SOFTWARE;
318                         attr->config = PERF_COUNT_SW_CPU_CLOCK;
319                         goto try_again;
320                 }
321                 printf("\n");
322                 error("perfcounter syscall returned with %d (%s)\n",
323                         fd[nr_cpu][counter], strerror(err));
324
325 #if defined(__i386__) || defined(__x86_64__)
326                 if (attr->type == PERF_TYPE_HARDWARE && err == EOPNOTSUPP)
327                         die("No hardware sampling interrupt available. No APIC? If so then you can boot the kernel with the \"lapic\" boot parameter to force-enable it.\n");
328 #endif
329
330                 die("No CONFIG_PERF_EVENTS=y kernel support configured?\n");
331                 exit(-1);
332         }
333
334         h_attr = get_header_attr(attr, counter);
335         if (h_attr == NULL)
336                 die("nomem\n");
337
338         if (!file_new) {
339                 if (memcmp(&h_attr->attr, attr, sizeof(*attr))) {
340                         fprintf(stderr, "incompatible append\n");
341                         exit(-1);
342                 }
343         }
344
345         if (read(fd[nr_cpu][counter], &read_data, sizeof(read_data)) == -1) {
346                 perror("Unable to read perf file descriptor\n");
347                 exit(-1);
348         }
349
350         if (perf_header_attr__add_id(h_attr, read_data.id) < 0) {
351                 pr_warning("Not enough memory to add id\n");
352                 exit(-1);
353         }
354
355         assert(fd[nr_cpu][counter] >= 0);
356         fcntl(fd[nr_cpu][counter], F_SETFL, O_NONBLOCK);
357
358         /*
359          * First counter acts as the group leader:
360          */
361         if (group && group_fd == -1)
362                 group_fd = fd[nr_cpu][counter];
363         if (multiplex && multiplex_fd == -1)
364                 multiplex_fd = fd[nr_cpu][counter];
365
366         if (multiplex && fd[nr_cpu][counter] != multiplex_fd) {
367
368                 ret = ioctl(fd[nr_cpu][counter], PERF_EVENT_IOC_SET_OUTPUT, multiplex_fd);
369                 assert(ret != -1);
370         } else {
371                 event_array[nr_poll].fd = fd[nr_cpu][counter];
372                 event_array[nr_poll].events = POLLIN;
373                 nr_poll++;
374
375                 mmap_array[nr_cpu][counter].counter = counter;
376                 mmap_array[nr_cpu][counter].prev = 0;
377                 mmap_array[nr_cpu][counter].mask = mmap_pages*page_size - 1;
378                 mmap_array[nr_cpu][counter].base = mmap(NULL, (mmap_pages+1)*page_size,
379                                 PROT_READ|PROT_WRITE, MAP_SHARED, fd[nr_cpu][counter], 0);
380                 if (mmap_array[nr_cpu][counter].base == MAP_FAILED) {
381                         error("failed to mmap with %d (%s)\n", errno, strerror(errno));
382                         exit(-1);
383                 }
384         }
385
386         if (filter != NULL) {
387                 ret = ioctl(fd[nr_cpu][counter],
388                             PERF_EVENT_IOC_SET_FILTER, filter);
389                 if (ret) {
390                         error("failed to set filter with %d (%s)\n", errno,
391                               strerror(errno));
392                         exit(-1);
393                 }
394         }
395
396         ioctl(fd[nr_cpu][counter], PERF_EVENT_IOC_ENABLE);
397 }
398
399 static void open_counters(int cpu, pid_t pid)
400 {
401         int counter;
402
403         group_fd = -1;
404         for (counter = 0; counter < nr_counters; counter++)
405                 create_counter(counter, cpu, pid);
406
407         nr_cpu++;
408 }
409
410 static void atexit_header(void)
411 {
412         session->header.data_size += bytes_written;
413
414         perf_header__write(&session->header, output, true);
415 }
416
417 static int __cmd_record(int argc, const char **argv)
418 {
419         int i, counter;
420         struct stat st;
421         pid_t pid = 0;
422         int flags;
423         int err;
424         unsigned long waking = 0;
425         int child_ready_pipe[2], go_pipe[2];
426         const bool forks = target_pid == -1 && argc > 0;
427         char buf;
428
429         page_size = sysconf(_SC_PAGE_SIZE);
430         nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
431         assert(nr_cpus <= MAX_NR_CPUS);
432         assert(nr_cpus >= 0);
433
434         atexit(sig_atexit);
435         signal(SIGCHLD, sig_handler);
436         signal(SIGINT, sig_handler);
437
438         if (forks && (pipe(child_ready_pipe) < 0 || pipe(go_pipe) < 0)) {
439                 perror("failed to create pipes");
440                 exit(-1);
441         }
442
443         if (!stat(output_name, &st) && st.st_size) {
444                 if (!force) {
445                         if (!append_file) {
446                                 pr_err("Error, output file %s exists, use -A "
447                                        "to append or -f to overwrite.\n",
448                                        output_name);
449                                 exit(-1);
450                         }
451                 } else {
452                         char oldname[PATH_MAX];
453                         snprintf(oldname, sizeof(oldname), "%s.old",
454                                  output_name);
455                         unlink(oldname);
456                         rename(output_name, oldname);
457                 }
458         } else {
459                 append_file = 0;
460         }
461
462         flags = O_CREAT|O_RDWR;
463         if (append_file)
464                 file_new = 0;
465         else
466                 flags |= O_TRUNC;
467
468         output = open(output_name, flags, S_IRUSR|S_IWUSR);
469         if (output < 0) {
470                 perror("failed to create output file");
471                 exit(-1);
472         }
473
474         session = perf_session__new(output_name, O_WRONLY, force);
475         if (session == NULL) {
476                 pr_err("Not enough memory for reading perf file header\n");
477                 return -1;
478         }
479
480         if (perf_session__create_kernel_maps(session) < 0) {
481                 pr_err("Problems creating kernel maps\n");
482                 return -1;
483         }
484
485         if (!file_new) {
486                 err = perf_header__read(&session->header, output);
487                 if (err < 0)
488                         return err;
489         }
490
491         if (raw_samples) {
492                 perf_header__set_feat(&session->header, HEADER_TRACE_INFO);
493         } else {
494                 for (i = 0; i < nr_counters; i++) {
495                         if (attrs[i].sample_type & PERF_SAMPLE_RAW) {
496                                 perf_header__set_feat(&session->header, HEADER_TRACE_INFO);
497                                 break;
498                         }
499                 }
500         }
501
502         atexit(atexit_header);
503
504         if (forks) {
505                 pid = fork();
506                 if (pid < 0) {
507                         perror("failed to fork");
508                         exit(-1);
509                 }
510
511                 if (!pid) {
512                         close(child_ready_pipe[0]);
513                         close(go_pipe[1]);
514                         fcntl(go_pipe[0], F_SETFD, FD_CLOEXEC);
515
516                         /*
517                          * Do a dummy execvp to get the PLT entry resolved,
518                          * so we avoid the resolver overhead on the real
519                          * execvp call.
520                          */
521                         execvp("", (char **)argv);
522
523                         /*
524                          * Tell the parent we're ready to go
525                          */
526                         close(child_ready_pipe[1]);
527
528                         /*
529                          * Wait until the parent tells us to go.
530                          */
531                         if (read(go_pipe[0], &buf, 1) == -1)
532                                 perror("unable to read pipe");
533
534                         execvp(argv[0], (char **)argv);
535
536                         perror(argv[0]);
537                         exit(-1);
538                 }
539
540                 child_pid = pid;
541
542                 if (!system_wide)
543                         target_pid = pid;
544
545                 close(child_ready_pipe[1]);
546                 close(go_pipe[0]);
547                 /*
548                  * wait for child to settle
549                  */
550                 if (read(child_ready_pipe[0], &buf, 1) == -1) {
551                         perror("unable to read pipe");
552                         exit(-1);
553                 }
554                 close(child_ready_pipe[0]);
555         }
556
557
558         if ((!system_wide && !inherit) || profile_cpu != -1) {
559                 open_counters(profile_cpu, target_pid);
560         } else {
561                 for (i = 0; i < nr_cpus; i++)
562                         open_counters(i, target_pid);
563         }
564
565         if (file_new) {
566                 err = perf_header__write(&session->header, output, false);
567                 if (err < 0)
568                         return err;
569         }
570
571         err = event__synthesize_kernel_mmap(process_synthesized_event,
572                                             session, "_text");
573         if (err < 0) {
574                 pr_err("Couldn't record kernel reference relocation symbol.\n");
575                 return err;
576         }
577
578         err = event__synthesize_modules(process_synthesized_event, session);
579         if (err < 0) {
580                 pr_err("Couldn't record kernel reference relocation symbol.\n");
581                 return err;
582         }
583
584         if (!system_wide && profile_cpu == -1)
585                 event__synthesize_thread(pid, process_synthesized_event,
586                                          session);
587         else
588                 event__synthesize_threads(process_synthesized_event, session);
589
590         if (realtime_prio) {
591                 struct sched_param param;
592
593                 param.sched_priority = realtime_prio;
594                 if (sched_setscheduler(0, SCHED_FIFO, &param)) {
595                         pr_err("Could not set realtime priority.\n");
596                         exit(-1);
597                 }
598         }
599
600         /*
601          * Let the child rip
602          */
603         if (forks)
604                 close(go_pipe[1]);
605
606         for (;;) {
607                 int hits = samples;
608
609                 for (i = 0; i < nr_cpu; i++) {
610                         for (counter = 0; counter < nr_counters; counter++) {
611                                 if (mmap_array[i][counter].base)
612                                         mmap_read(&mmap_array[i][counter]);
613                         }
614                 }
615
616                 if (hits == samples) {
617                         if (done)
618                                 break;
619                         err = poll(event_array, nr_poll, -1);
620                         waking++;
621                 }
622
623                 if (done) {
624                         for (i = 0; i < nr_cpu; i++) {
625                                 for (counter = 0; counter < nr_counters; counter++)
626                                         ioctl(fd[i][counter], PERF_EVENT_IOC_DISABLE);
627                         }
628                 }
629         }
630
631         fprintf(stderr, "[ perf record: Woken up %ld times to write data ]\n", waking);
632
633         /*
634          * Approximate RIP event size: 24 bytes.
635          */
636         fprintf(stderr,
637                 "[ perf record: Captured and wrote %.3f MB %s (~%lld samples) ]\n",
638                 (double)bytes_written / 1024.0 / 1024.0,
639                 output_name,
640                 bytes_written / 24);
641
642         return 0;
643 }
644
645 static const char * const record_usage[] = {
646         "perf record [<options>] [<command>]",
647         "perf record [<options>] -- <command> [<options>]",
648         NULL
649 };
650
651 static const struct option options[] = {
652         OPT_CALLBACK('e', "event", NULL, "event",
653                      "event selector. use 'perf list' to list available events",
654                      parse_events),
655         OPT_CALLBACK(0, "filter", NULL, "filter",
656                      "event filter", parse_filter),
657         OPT_INTEGER('p', "pid", &target_pid,
658                     "record events on existing pid"),
659         OPT_INTEGER('r', "realtime", &realtime_prio,
660                     "collect data with this RT SCHED_FIFO priority"),
661         OPT_BOOLEAN('R', "raw-samples", &raw_samples,
662                     "collect raw sample records from all opened counters"),
663         OPT_BOOLEAN('a', "all-cpus", &system_wide,
664                             "system-wide collection from all CPUs"),
665         OPT_BOOLEAN('A', "append", &append_file,
666                             "append to the output file to do incremental profiling"),
667         OPT_INTEGER('C', "profile_cpu", &profile_cpu,
668                             "CPU to profile on"),
669         OPT_BOOLEAN('f', "force", &force,
670                         "overwrite existing data file"),
671         OPT_LONG('c', "count", &default_interval,
672                     "event period to sample"),
673         OPT_STRING('o', "output", &output_name, "file",
674                     "output file name"),
675         OPT_BOOLEAN('i', "inherit", &inherit,
676                     "child tasks inherit counters"),
677         OPT_INTEGER('F', "freq", &freq,
678                     "profile at this frequency"),
679         OPT_INTEGER('m', "mmap-pages", &mmap_pages,
680                     "number of mmap data pages"),
681         OPT_BOOLEAN('g', "call-graph", &call_graph,
682                     "do call-graph (stack chain/backtrace) recording"),
683         OPT_BOOLEAN('v', "verbose", &verbose,
684                     "be more verbose (show counter open errors, etc)"),
685         OPT_BOOLEAN('s', "stat", &inherit_stat,
686                     "per thread counts"),
687         OPT_BOOLEAN('d', "data", &sample_address,
688                     "Sample addresses"),
689         OPT_BOOLEAN('n', "no-samples", &no_samples,
690                     "don't sample"),
691         OPT_BOOLEAN('M', "multiplex", &multiplex,
692                     "multiplex counter output in a single channel"),
693         OPT_END()
694 };
695
696 int cmd_record(int argc, const char **argv, const char *prefix __used)
697 {
698         int counter;
699
700         argc = parse_options(argc, argv, options, record_usage,
701                             PARSE_OPT_STOP_AT_NON_OPTION);
702         if (!argc && target_pid == -1 && !system_wide && profile_cpu == -1)
703                 usage_with_options(record_usage, options);
704
705         symbol__init();
706
707         if (!nr_counters) {
708                 nr_counters     = 1;
709                 attrs[0].type   = PERF_TYPE_HARDWARE;
710                 attrs[0].config = PERF_COUNT_HW_CPU_CYCLES;
711         }
712
713         /*
714          * User specified count overrides default frequency.
715          */
716         if (default_interval)
717                 freq = 0;
718         else if (freq) {
719                 default_interval = freq;
720         } else {
721                 fprintf(stderr, "frequency and count are zero, aborting\n");
722                 exit(EXIT_FAILURE);
723         }
724
725         for (counter = 0; counter < nr_counters; counter++) {
726                 if (attrs[counter].sample_period)
727                         continue;
728
729                 attrs[counter].sample_period = default_interval;
730         }
731
732         return __cmd_record(argc, argv);
733 }