perf session: Create kernel maps in the constructor
[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         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 (!file_new) {
481                 err = perf_header__read(&session->header, output);
482                 if (err < 0)
483                         return err;
484         }
485
486         if (raw_samples) {
487                 perf_header__set_feat(&session->header, HEADER_TRACE_INFO);
488         } else {
489                 for (i = 0; i < nr_counters; i++) {
490                         if (attrs[i].sample_type & PERF_SAMPLE_RAW) {
491                                 perf_header__set_feat(&session->header, HEADER_TRACE_INFO);
492                                 break;
493                         }
494                 }
495         }
496
497         atexit(atexit_header);
498
499         if (forks) {
500                 pid = fork();
501                 if (pid < 0) {
502                         perror("failed to fork");
503                         exit(-1);
504                 }
505
506                 if (!pid) {
507                         close(child_ready_pipe[0]);
508                         close(go_pipe[1]);
509                         fcntl(go_pipe[0], F_SETFD, FD_CLOEXEC);
510
511                         /*
512                          * Do a dummy execvp to get the PLT entry resolved,
513                          * so we avoid the resolver overhead on the real
514                          * execvp call.
515                          */
516                         execvp("", (char **)argv);
517
518                         /*
519                          * Tell the parent we're ready to go
520                          */
521                         close(child_ready_pipe[1]);
522
523                         /*
524                          * Wait until the parent tells us to go.
525                          */
526                         if (read(go_pipe[0], &buf, 1) == -1)
527                                 perror("unable to read pipe");
528
529                         execvp(argv[0], (char **)argv);
530
531                         perror(argv[0]);
532                         exit(-1);
533                 }
534
535                 child_pid = pid;
536
537                 if (!system_wide)
538                         target_pid = pid;
539
540                 close(child_ready_pipe[1]);
541                 close(go_pipe[0]);
542                 /*
543                  * wait for child to settle
544                  */
545                 if (read(child_ready_pipe[0], &buf, 1) == -1) {
546                         perror("unable to read pipe");
547                         exit(-1);
548                 }
549                 close(child_ready_pipe[0]);
550         }
551
552
553         if ((!system_wide && !inherit) || profile_cpu != -1) {
554                 open_counters(profile_cpu, target_pid);
555         } else {
556                 for (i = 0; i < nr_cpus; i++)
557                         open_counters(i, target_pid);
558         }
559
560         if (file_new) {
561                 err = perf_header__write(&session->header, output, false);
562                 if (err < 0)
563                         return err;
564         }
565
566         err = event__synthesize_kernel_mmap(process_synthesized_event,
567                                             session, "_text");
568         if (err < 0) {
569                 pr_err("Couldn't record kernel reference relocation symbol.\n");
570                 return err;
571         }
572
573         err = event__synthesize_modules(process_synthesized_event, session);
574         if (err < 0) {
575                 pr_err("Couldn't record kernel reference relocation symbol.\n");
576                 return err;
577         }
578
579         if (!system_wide && profile_cpu == -1)
580                 event__synthesize_thread(pid, process_synthesized_event,
581                                          session);
582         else
583                 event__synthesize_threads(process_synthesized_event, session);
584
585         if (realtime_prio) {
586                 struct sched_param param;
587
588                 param.sched_priority = realtime_prio;
589                 if (sched_setscheduler(0, SCHED_FIFO, &param)) {
590                         pr_err("Could not set realtime priority.\n");
591                         exit(-1);
592                 }
593         }
594
595         /*
596          * Let the child rip
597          */
598         if (forks)
599                 close(go_pipe[1]);
600
601         for (;;) {
602                 int hits = samples;
603
604                 for (i = 0; i < nr_cpu; i++) {
605                         for (counter = 0; counter < nr_counters; counter++) {
606                                 if (mmap_array[i][counter].base)
607                                         mmap_read(&mmap_array[i][counter]);
608                         }
609                 }
610
611                 if (hits == samples) {
612                         if (done)
613                                 break;
614                         err = poll(event_array, nr_poll, -1);
615                         waking++;
616                 }
617
618                 if (done) {
619                         for (i = 0; i < nr_cpu; i++) {
620                                 for (counter = 0; counter < nr_counters; counter++)
621                                         ioctl(fd[i][counter], PERF_EVENT_IOC_DISABLE);
622                         }
623                 }
624         }
625
626         fprintf(stderr, "[ perf record: Woken up %ld times to write data ]\n", waking);
627
628         /*
629          * Approximate RIP event size: 24 bytes.
630          */
631         fprintf(stderr,
632                 "[ perf record: Captured and wrote %.3f MB %s (~%lld samples) ]\n",
633                 (double)bytes_written / 1024.0 / 1024.0,
634                 output_name,
635                 bytes_written / 24);
636
637         return 0;
638 }
639
640 static const char * const record_usage[] = {
641         "perf record [<options>] [<command>]",
642         "perf record [<options>] -- <command> [<options>]",
643         NULL
644 };
645
646 static const struct option options[] = {
647         OPT_CALLBACK('e', "event", NULL, "event",
648                      "event selector. use 'perf list' to list available events",
649                      parse_events),
650         OPT_CALLBACK(0, "filter", NULL, "filter",
651                      "event filter", parse_filter),
652         OPT_INTEGER('p', "pid", &target_pid,
653                     "record events on existing pid"),
654         OPT_INTEGER('r', "realtime", &realtime_prio,
655                     "collect data with this RT SCHED_FIFO priority"),
656         OPT_BOOLEAN('R', "raw-samples", &raw_samples,
657                     "collect raw sample records from all opened counters"),
658         OPT_BOOLEAN('a', "all-cpus", &system_wide,
659                             "system-wide collection from all CPUs"),
660         OPT_BOOLEAN('A', "append", &append_file,
661                             "append to the output file to do incremental profiling"),
662         OPT_INTEGER('C', "profile_cpu", &profile_cpu,
663                             "CPU to profile on"),
664         OPT_BOOLEAN('f', "force", &force,
665                         "overwrite existing data file"),
666         OPT_LONG('c', "count", &default_interval,
667                     "event period to sample"),
668         OPT_STRING('o', "output", &output_name, "file",
669                     "output file name"),
670         OPT_BOOLEAN('i', "inherit", &inherit,
671                     "child tasks inherit counters"),
672         OPT_INTEGER('F', "freq", &freq,
673                     "profile at this frequency"),
674         OPT_INTEGER('m', "mmap-pages", &mmap_pages,
675                     "number of mmap data pages"),
676         OPT_BOOLEAN('g', "call-graph", &call_graph,
677                     "do call-graph (stack chain/backtrace) recording"),
678         OPT_BOOLEAN('v', "verbose", &verbose,
679                     "be more verbose (show counter open errors, etc)"),
680         OPT_BOOLEAN('s', "stat", &inherit_stat,
681                     "per thread counts"),
682         OPT_BOOLEAN('d', "data", &sample_address,
683                     "Sample addresses"),
684         OPT_BOOLEAN('n', "no-samples", &no_samples,
685                     "don't sample"),
686         OPT_BOOLEAN('M', "multiplex", &multiplex,
687                     "multiplex counter output in a single channel"),
688         OPT_END()
689 };
690
691 int cmd_record(int argc, const char **argv, const char *prefix __used)
692 {
693         int counter;
694
695         argc = parse_options(argc, argv, options, record_usage,
696                             PARSE_OPT_STOP_AT_NON_OPTION);
697         if (!argc && target_pid == -1 && !system_wide && profile_cpu == -1)
698                 usage_with_options(record_usage, options);
699
700         symbol__init();
701
702         if (!nr_counters) {
703                 nr_counters     = 1;
704                 attrs[0].type   = PERF_TYPE_HARDWARE;
705                 attrs[0].config = PERF_COUNT_HW_CPU_CYCLES;
706         }
707
708         /*
709          * User specified count overrides default frequency.
710          */
711         if (default_interval)
712                 freq = 0;
713         else if (freq) {
714                 default_interval = freq;
715         } else {
716                 fprintf(stderr, "frequency and count are zero, aborting\n");
717                 exit(EXIT_FAILURE);
718         }
719
720         for (counter = 0; counter < nr_counters; counter++) {
721                 if (attrs[counter].sample_period)
722                         continue;
723
724                 attrs[counter].sample_period = default_interval;
725         }
726
727         return __cmd_record(argc, argv);
728 }