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