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