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