]> bbs.cooldavid.org Git - net-next-2.6.git/blob - tools/perf/builtin-top.c
perf-top: Show the percentage of successfull PEBS-fixups
[net-next-2.6.git] / tools / perf / builtin-top.c
1 /*
2  * builtin-top.c
3  *
4  * Builtin top command: Display a continuously updated profile of
5  * any workload, CPU or specific PID.
6  *
7  * Copyright (C) 2008, Red Hat Inc, Ingo Molnar <mingo@redhat.com>
8  *
9  * Improvements and fixes by:
10  *
11  *   Arjan van de Ven <arjan@linux.intel.com>
12  *   Yanmin Zhang <yanmin.zhang@intel.com>
13  *   Wu Fengguang <fengguang.wu@intel.com>
14  *   Mike Galbraith <efault@gmx.de>
15  *   Paul Mackerras <paulus@samba.org>
16  *
17  * Released under the GPL v2. (and only v2, not any later version)
18  */
19 #include "builtin.h"
20
21 #include "perf.h"
22
23 #include "util/color.h"
24 #include "util/session.h"
25 #include "util/symbol.h"
26 #include "util/thread.h"
27 #include "util/util.h"
28 #include <linux/rbtree.h>
29 #include "util/parse-options.h"
30 #include "util/parse-events.h"
31
32 #include "util/debug.h"
33
34 #include <assert.h>
35 #include <fcntl.h>
36
37 #include <stdio.h>
38 #include <termios.h>
39 #include <unistd.h>
40
41 #include <errno.h>
42 #include <time.h>
43 #include <sched.h>
44 #include <pthread.h>
45
46 #include <sys/syscall.h>
47 #include <sys/ioctl.h>
48 #include <sys/poll.h>
49 #include <sys/prctl.h>
50 #include <sys/wait.h>
51 #include <sys/uio.h>
52 #include <sys/mman.h>
53
54 #include <linux/unistd.h>
55 #include <linux/types.h>
56
57 static int                      fd[MAX_NR_CPUS][MAX_COUNTERS];
58
59 static int                      system_wide                     =      0;
60
61 static int                      default_interval                =      0;
62
63 static int                      count_filter                    =      5;
64 static int                      print_entries;
65
66 static int                      target_pid                      =     -1;
67 static int                      inherit                         =      0;
68 static int                      profile_cpu                     =     -1;
69 static int                      nr_cpus                         =      0;
70 static unsigned int             realtime_prio                   =      0;
71 static int                      group                           =      0;
72 static unsigned int             page_size;
73 static unsigned int             mmap_pages                      =     16;
74 static int                      freq                            =   1000; /* 1 KHz */
75
76 static int                      delay_secs                      =      2;
77 static int                      zero                            =      0;
78 static int                      dump_symtab                     =      0;
79
80 static bool                     hide_kernel_symbols             =  false;
81 static bool                     hide_user_symbols               =  false;
82 static struct winsize           winsize;
83
84 /*
85  * Source
86  */
87
88 struct source_line {
89         u64                     eip;
90         unsigned long           count[MAX_COUNTERS];
91         char                    *line;
92         struct source_line      *next;
93 };
94
95 static char                     *sym_filter                     =   NULL;
96 struct sym_entry                *sym_filter_entry               =   NULL;
97 struct sym_entry                *sym_filter_entry_sched         =   NULL;
98 static int                      sym_pcnt_filter                 =      5;
99 static int                      sym_counter                     =      0;
100 static int                      display_weighted                =     -1;
101
102 /*
103  * Symbols
104  */
105
106 struct sym_entry_source {
107         struct source_line      *source;
108         struct source_line      *lines;
109         struct source_line      **lines_tail;
110         pthread_mutex_t         lock;
111 };
112
113 struct sym_entry {
114         struct rb_node          rb_node;
115         struct list_head        node;
116         unsigned long           snap_count;
117         double                  weight;
118         int                     skip;
119         u16                     name_len;
120         u8                      origin;
121         struct map              *map;
122         struct sym_entry_source *src;
123         unsigned long           count[0];
124 };
125
126 /*
127  * Source functions
128  */
129
130 static inline struct symbol *sym_entry__symbol(struct sym_entry *self)
131 {
132        return ((void *)self) + symbol_conf.priv_size;
133 }
134
135 static void get_term_dimensions(struct winsize *ws)
136 {
137         char *s = getenv("LINES");
138
139         if (s != NULL) {
140                 ws->ws_row = atoi(s);
141                 s = getenv("COLUMNS");
142                 if (s != NULL) {
143                         ws->ws_col = atoi(s);
144                         if (ws->ws_row && ws->ws_col)
145                                 return;
146                 }
147         }
148 #ifdef TIOCGWINSZ
149         if (ioctl(1, TIOCGWINSZ, ws) == 0 &&
150             ws->ws_row && ws->ws_col)
151                 return;
152 #endif
153         ws->ws_row = 25;
154         ws->ws_col = 80;
155 }
156
157 static void update_print_entries(struct winsize *ws)
158 {
159         print_entries = ws->ws_row;
160
161         if (print_entries > 9)
162                 print_entries -= 9;
163 }
164
165 static void sig_winch_handler(int sig __used)
166 {
167         get_term_dimensions(&winsize);
168         update_print_entries(&winsize);
169 }
170
171 static void parse_source(struct sym_entry *syme)
172 {
173         struct symbol *sym;
174         struct sym_entry_source *source;
175         struct map *map;
176         FILE *file;
177         char command[PATH_MAX*2];
178         const char *path;
179         u64 len;
180
181         if (!syme)
182                 return;
183
184         if (syme->src == NULL) {
185                 syme->src = zalloc(sizeof(*source));
186                 if (syme->src == NULL)
187                         return;
188                 pthread_mutex_init(&syme->src->lock, NULL);
189         }
190
191         source = syme->src;
192
193         if (source->lines) {
194                 pthread_mutex_lock(&source->lock);
195                 goto out_assign;
196         }
197
198         sym = sym_entry__symbol(syme);
199         map = syme->map;
200         path = map->dso->long_name;
201
202         len = sym->end - sym->start;
203
204         sprintf(command,
205                 "objdump --start-address=%#0*Lx --stop-address=%#0*Lx -dS %s",
206                 BITS_PER_LONG / 4, map__rip_2objdump(map, sym->start),
207                 BITS_PER_LONG / 4, map__rip_2objdump(map, sym->end), path);
208
209         file = popen(command, "r");
210         if (!file)
211                 return;
212
213         pthread_mutex_lock(&source->lock);
214         source->lines_tail = &source->lines;
215         while (!feof(file)) {
216                 struct source_line *src;
217                 size_t dummy = 0;
218                 char *c, *sep;
219
220                 src = malloc(sizeof(struct source_line));
221                 assert(src != NULL);
222                 memset(src, 0, sizeof(struct source_line));
223
224                 if (getline(&src->line, &dummy, file) < 0)
225                         break;
226                 if (!src->line)
227                         break;
228
229                 c = strchr(src->line, '\n');
230                 if (c)
231                         *c = 0;
232
233                 src->next = NULL;
234                 *source->lines_tail = src;
235                 source->lines_tail = &src->next;
236
237                 src->eip = strtoull(src->line, &sep, 16);
238                 if (*sep == ':')
239                         src->eip = map__objdump_2ip(map, src->eip);
240                 else /* this line has no ip info (e.g. source line) */
241                         src->eip = 0;
242         }
243         pclose(file);
244 out_assign:
245         sym_filter_entry = syme;
246         pthread_mutex_unlock(&source->lock);
247 }
248
249 static void __zero_source_counters(struct sym_entry *syme)
250 {
251         int i;
252         struct source_line *line;
253
254         line = syme->src->lines;
255         while (line) {
256                 for (i = 0; i < nr_counters; i++)
257                         line->count[i] = 0;
258                 line = line->next;
259         }
260 }
261
262 static void record_precise_ip(struct sym_entry *syme, int counter, u64 ip)
263 {
264         struct source_line *line;
265
266         if (syme != sym_filter_entry)
267                 return;
268
269         if (pthread_mutex_trylock(&syme->src->lock))
270                 return;
271
272         if (syme->src == NULL || syme->src->source == NULL)
273                 goto out_unlock;
274
275         for (line = syme->src->lines; line; line = line->next) {
276                 /* skip lines without IP info */
277                 if (line->eip == 0)
278                         continue;
279                 if (line->eip == ip) {
280                         line->count[counter]++;
281                         break;
282                 }
283                 if (line->eip > ip)
284                         break;
285         }
286 out_unlock:
287         pthread_mutex_unlock(&syme->src->lock);
288 }
289
290 #define PATTERN_LEN             (BITS_PER_LONG / 4 + 2)
291
292 static void lookup_sym_source(struct sym_entry *syme)
293 {
294         struct symbol *symbol = sym_entry__symbol(syme);
295         struct source_line *line;
296         char pattern[PATTERN_LEN + 1];
297
298         sprintf(pattern, "%0*Lx <", BITS_PER_LONG / 4,
299                 map__rip_2objdump(syme->map, symbol->start));
300
301         pthread_mutex_lock(&syme->src->lock);
302         for (line = syme->src->lines; line; line = line->next) {
303                 if (memcmp(line->line, pattern, PATTERN_LEN) == 0) {
304                         syme->src->source = line;
305                         break;
306                 }
307         }
308         pthread_mutex_unlock(&syme->src->lock);
309 }
310
311 static void show_lines(struct source_line *queue, int count, int total)
312 {
313         int i;
314         struct source_line *line;
315
316         line = queue;
317         for (i = 0; i < count; i++) {
318                 float pcnt = 100.0*(float)line->count[sym_counter]/(float)total;
319
320                 printf("%8li %4.1f%%\t%s\n", line->count[sym_counter], pcnt, line->line);
321                 line = line->next;
322         }
323 }
324
325 #define TRACE_COUNT     3
326
327 static void show_details(struct sym_entry *syme)
328 {
329         struct symbol *symbol;
330         struct source_line *line;
331         struct source_line *line_queue = NULL;
332         int displayed = 0;
333         int line_queue_count = 0, total = 0, more = 0;
334
335         if (!syme)
336                 return;
337
338         if (!syme->src->source)
339                 lookup_sym_source(syme);
340
341         if (!syme->src->source)
342                 return;
343
344         symbol = sym_entry__symbol(syme);
345         printf("Showing %s for %s\n", event_name(sym_counter), symbol->name);
346         printf("  Events  Pcnt (>=%d%%)\n", sym_pcnt_filter);
347
348         pthread_mutex_lock(&syme->src->lock);
349         line = syme->src->source;
350         while (line) {
351                 total += line->count[sym_counter];
352                 line = line->next;
353         }
354
355         line = syme->src->source;
356         while (line) {
357                 float pcnt = 0.0;
358
359                 if (!line_queue_count)
360                         line_queue = line;
361                 line_queue_count++;
362
363                 if (line->count[sym_counter])
364                         pcnt = 100.0 * line->count[sym_counter] / (float)total;
365                 if (pcnt >= (float)sym_pcnt_filter) {
366                         if (displayed <= print_entries)
367                                 show_lines(line_queue, line_queue_count, total);
368                         else more++;
369                         displayed += line_queue_count;
370                         line_queue_count = 0;
371                         line_queue = NULL;
372                 } else if (line_queue_count > TRACE_COUNT) {
373                         line_queue = line_queue->next;
374                         line_queue_count--;
375                 }
376
377                 line->count[sym_counter] = zero ? 0 : line->count[sym_counter] * 7 / 8;
378                 line = line->next;
379         }
380         pthread_mutex_unlock(&syme->src->lock);
381         if (more)
382                 printf("%d lines not displayed, maybe increase display entries [e]\n", more);
383 }
384
385 /*
386  * Symbols will be added here in event__process_sample and will get out
387  * after decayed.
388  */
389 static LIST_HEAD(active_symbols);
390 static pthread_mutex_t active_symbols_lock = PTHREAD_MUTEX_INITIALIZER;
391
392 /*
393  * Ordering weight: count-1 * count-2 * ... / count-n
394  */
395 static double sym_weight(const struct sym_entry *sym)
396 {
397         double weight = sym->snap_count;
398         int counter;
399
400         if (!display_weighted)
401                 return weight;
402
403         for (counter = 1; counter < nr_counters-1; counter++)
404                 weight *= sym->count[counter];
405
406         weight /= (sym->count[counter] + 1);
407
408         return weight;
409 }
410
411 static long                     samples;
412 static long                     userspace_samples;
413 static long                     exact_samples;
414 static const char               CONSOLE_CLEAR[] = "\e[H\e[2J";
415
416 static void __list_insert_active_sym(struct sym_entry *syme)
417 {
418         list_add(&syme->node, &active_symbols);
419 }
420
421 static void list_remove_active_sym(struct sym_entry *syme)
422 {
423         pthread_mutex_lock(&active_symbols_lock);
424         list_del_init(&syme->node);
425         pthread_mutex_unlock(&active_symbols_lock);
426 }
427
428 static void rb_insert_active_sym(struct rb_root *tree, struct sym_entry *se)
429 {
430         struct rb_node **p = &tree->rb_node;
431         struct rb_node *parent = NULL;
432         struct sym_entry *iter;
433
434         while (*p != NULL) {
435                 parent = *p;
436                 iter = rb_entry(parent, struct sym_entry, rb_node);
437
438                 if (se->weight > iter->weight)
439                         p = &(*p)->rb_left;
440                 else
441                         p = &(*p)->rb_right;
442         }
443
444         rb_link_node(&se->rb_node, parent, p);
445         rb_insert_color(&se->rb_node, tree);
446 }
447
448 static void print_sym_table(void)
449 {
450         int printed = 0, j;
451         int counter, snap = !display_weighted ? sym_counter : 0;
452         float samples_per_sec = samples/delay_secs;
453         float ksamples_per_sec = (samples-userspace_samples)/delay_secs;
454         float esamples_percent = (100.0*exact_samples)/samples;
455         float sum_ksamples = 0.0;
456         struct sym_entry *syme, *n;
457         struct rb_root tmp = RB_ROOT;
458         struct rb_node *nd;
459         int sym_width = 0, dso_width = 0, max_dso_width;
460         const int win_width = winsize.ws_col - 1;
461
462         samples = userspace_samples = exact_samples = 0;
463
464         /* Sort the active symbols */
465         pthread_mutex_lock(&active_symbols_lock);
466         syme = list_entry(active_symbols.next, struct sym_entry, node);
467         pthread_mutex_unlock(&active_symbols_lock);
468
469         list_for_each_entry_safe_from(syme, n, &active_symbols, node) {
470                 syme->snap_count = syme->count[snap];
471                 if (syme->snap_count != 0) {
472
473                         if ((hide_user_symbols &&
474                              syme->origin == PERF_RECORD_MISC_USER) ||
475                             (hide_kernel_symbols &&
476                              syme->origin == PERF_RECORD_MISC_KERNEL)) {
477                                 list_remove_active_sym(syme);
478                                 continue;
479                         }
480                         syme->weight = sym_weight(syme);
481                         rb_insert_active_sym(&tmp, syme);
482                         sum_ksamples += syme->snap_count;
483
484                         for (j = 0; j < nr_counters; j++)
485                                 syme->count[j] = zero ? 0 : syme->count[j] * 7 / 8;
486                 } else
487                         list_remove_active_sym(syme);
488         }
489
490         puts(CONSOLE_CLEAR);
491
492         printf("%-*.*s\n", win_width, win_width, graph_dotted_line);
493         printf( "   PerfTop:%8.0f irqs/sec  kernel:%4.1f%%  exact: %4.1f%% [",
494                 samples_per_sec,
495                 100.0 - (100.0*((samples_per_sec-ksamples_per_sec)/samples_per_sec)),
496                 esamples_percent);
497
498         if (nr_counters == 1 || !display_weighted) {
499                 printf("%Ld", (u64)attrs[0].sample_period);
500                 if (freq)
501                         printf("Hz ");
502                 else
503                         printf(" ");
504         }
505
506         if (!display_weighted)
507                 printf("%s", event_name(sym_counter));
508         else for (counter = 0; counter < nr_counters; counter++) {
509                 if (counter)
510                         printf("/");
511
512                 printf("%s", event_name(counter));
513         }
514
515         printf( "], ");
516
517         if (target_pid != -1)
518                 printf(" (target_pid: %d", target_pid);
519         else
520                 printf(" (all");
521
522         if (profile_cpu != -1)
523                 printf(", cpu: %d)\n", profile_cpu);
524         else {
525                 if (target_pid != -1)
526                         printf(")\n");
527                 else
528                         printf(", %d CPUs)\n", nr_cpus);
529         }
530
531         printf("%-*.*s\n", win_width, win_width, graph_dotted_line);
532
533         if (sym_filter_entry) {
534                 show_details(sym_filter_entry);
535                 return;
536         }
537
538         /*
539          * Find the longest symbol name that will be displayed
540          */
541         for (nd = rb_first(&tmp); nd; nd = rb_next(nd)) {
542                 syme = rb_entry(nd, struct sym_entry, rb_node);
543                 if (++printed > print_entries ||
544                     (int)syme->snap_count < count_filter)
545                         continue;
546
547                 if (syme->map->dso->long_name_len > dso_width)
548                         dso_width = syme->map->dso->long_name_len;
549
550                 if (syme->name_len > sym_width)
551                         sym_width = syme->name_len;
552         }
553
554         printed = 0;
555
556         max_dso_width = winsize.ws_col - sym_width - 29;
557         if (dso_width > max_dso_width)
558                 dso_width = max_dso_width;
559         putchar('\n');
560         if (nr_counters == 1)
561                 printf("             samples  pcnt");
562         else
563                 printf("   weight    samples  pcnt");
564
565         if (verbose)
566                 printf("         RIP       ");
567         printf(" %-*.*s DSO\n", sym_width, sym_width, "function");
568         printf("   %s    _______ _____",
569                nr_counters == 1 ? "      " : "______");
570         if (verbose)
571                 printf(" ________________");
572         printf(" %-*.*s", sym_width, sym_width, graph_line);
573         printf(" %-*.*s", dso_width, dso_width, graph_line);
574         puts("\n");
575
576         for (nd = rb_first(&tmp); nd; nd = rb_next(nd)) {
577                 struct symbol *sym;
578                 double pcnt;
579
580                 syme = rb_entry(nd, struct sym_entry, rb_node);
581                 sym = sym_entry__symbol(syme);
582
583                 if (++printed > print_entries || (int)syme->snap_count < count_filter)
584                         continue;
585
586                 pcnt = 100.0 - (100.0 * ((sum_ksamples - syme->snap_count) /
587                                          sum_ksamples));
588
589                 if (nr_counters == 1 || !display_weighted)
590                         printf("%20.2f ", syme->weight);
591                 else
592                         printf("%9.1f %10ld ", syme->weight, syme->snap_count);
593
594                 percent_color_fprintf(stdout, "%4.1f%%", pcnt);
595                 if (verbose)
596                         printf(" %016llx", sym->start);
597                 printf(" %-*.*s", sym_width, sym_width, sym->name);
598                 printf(" %-*.*s\n", dso_width, dso_width,
599                        dso_width >= syme->map->dso->long_name_len ?
600                                         syme->map->dso->long_name :
601                                         syme->map->dso->short_name);
602         }
603 }
604
605 static void prompt_integer(int *target, const char *msg)
606 {
607         char *buf = malloc(0), *p;
608         size_t dummy = 0;
609         int tmp;
610
611         fprintf(stdout, "\n%s: ", msg);
612         if (getline(&buf, &dummy, stdin) < 0)
613                 return;
614
615         p = strchr(buf, '\n');
616         if (p)
617                 *p = 0;
618
619         p = buf;
620         while(*p) {
621                 if (!isdigit(*p))
622                         goto out_free;
623                 p++;
624         }
625         tmp = strtoul(buf, NULL, 10);
626         *target = tmp;
627 out_free:
628         free(buf);
629 }
630
631 static void prompt_percent(int *target, const char *msg)
632 {
633         int tmp = 0;
634
635         prompt_integer(&tmp, msg);
636         if (tmp >= 0 && tmp <= 100)
637                 *target = tmp;
638 }
639
640 static void prompt_symbol(struct sym_entry **target, const char *msg)
641 {
642         char *buf = malloc(0), *p;
643         struct sym_entry *syme = *target, *n, *found = NULL;
644         size_t dummy = 0;
645
646         /* zero counters of active symbol */
647         if (syme) {
648                 pthread_mutex_lock(&syme->src->lock);
649                 __zero_source_counters(syme);
650                 *target = NULL;
651                 pthread_mutex_unlock(&syme->src->lock);
652         }
653
654         fprintf(stdout, "\n%s: ", msg);
655         if (getline(&buf, &dummy, stdin) < 0)
656                 goto out_free;
657
658         p = strchr(buf, '\n');
659         if (p)
660                 *p = 0;
661
662         pthread_mutex_lock(&active_symbols_lock);
663         syme = list_entry(active_symbols.next, struct sym_entry, node);
664         pthread_mutex_unlock(&active_symbols_lock);
665
666         list_for_each_entry_safe_from(syme, n, &active_symbols, node) {
667                 struct symbol *sym = sym_entry__symbol(syme);
668
669                 if (!strcmp(buf, sym->name)) {
670                         found = syme;
671                         break;
672                 }
673         }
674
675         if (!found) {
676                 fprintf(stderr, "Sorry, %s is not active.\n", buf);
677                 sleep(1);
678                 return;
679         } else
680                 parse_source(found);
681
682 out_free:
683         free(buf);
684 }
685
686 static void print_mapped_keys(void)
687 {
688         char *name = NULL;
689
690         if (sym_filter_entry) {
691                 struct symbol *sym = sym_entry__symbol(sym_filter_entry);
692                 name = sym->name;
693         }
694
695         fprintf(stdout, "\nMapped keys:\n");
696         fprintf(stdout, "\t[d]     display refresh delay.             \t(%d)\n", delay_secs);
697         fprintf(stdout, "\t[e]     display entries (lines).           \t(%d)\n", print_entries);
698
699         if (nr_counters > 1)
700                 fprintf(stdout, "\t[E]     active event counter.              \t(%s)\n", event_name(sym_counter));
701
702         fprintf(stdout, "\t[f]     profile display filter (count).    \t(%d)\n", count_filter);
703
704         fprintf(stdout, "\t[F]     annotate display filter (percent). \t(%d%%)\n", sym_pcnt_filter);
705         fprintf(stdout, "\t[s]     annotate symbol.                   \t(%s)\n", name?: "NULL");
706         fprintf(stdout, "\t[S]     stop annotation.\n");
707
708         if (nr_counters > 1)
709                 fprintf(stdout, "\t[w]     toggle display weighted/count[E]r. \t(%d)\n", display_weighted ? 1 : 0);
710
711         fprintf(stdout,
712                 "\t[K]     hide kernel_symbols symbols.     \t(%s)\n",
713                 hide_kernel_symbols ? "yes" : "no");
714         fprintf(stdout,
715                 "\t[U]     hide user symbols.               \t(%s)\n",
716                 hide_user_symbols ? "yes" : "no");
717         fprintf(stdout, "\t[z]     toggle sample zeroing.             \t(%d)\n", zero ? 1 : 0);
718         fprintf(stdout, "\t[qQ]    quit.\n");
719 }
720
721 static int key_mapped(int c)
722 {
723         switch (c) {
724                 case 'd':
725                 case 'e':
726                 case 'f':
727                 case 'z':
728                 case 'q':
729                 case 'Q':
730                 case 'K':
731                 case 'U':
732                 case 'F':
733                 case 's':
734                 case 'S':
735                         return 1;
736                 case 'E':
737                 case 'w':
738                         return nr_counters > 1 ? 1 : 0;
739                 default:
740                         break;
741         }
742
743         return 0;
744 }
745
746 static void handle_keypress(int c)
747 {
748         if (!key_mapped(c)) {
749                 struct pollfd stdin_poll = { .fd = 0, .events = POLLIN };
750                 struct termios tc, save;
751
752                 print_mapped_keys();
753                 fprintf(stdout, "\nEnter selection, or unmapped key to continue: ");
754                 fflush(stdout);
755
756                 tcgetattr(0, &save);
757                 tc = save;
758                 tc.c_lflag &= ~(ICANON | ECHO);
759                 tc.c_cc[VMIN] = 0;
760                 tc.c_cc[VTIME] = 0;
761                 tcsetattr(0, TCSANOW, &tc);
762
763                 poll(&stdin_poll, 1, -1);
764                 c = getc(stdin);
765
766                 tcsetattr(0, TCSAFLUSH, &save);
767                 if (!key_mapped(c))
768                         return;
769         }
770
771         switch (c) {
772                 case 'd':
773                         prompt_integer(&delay_secs, "Enter display delay");
774                         if (delay_secs < 1)
775                                 delay_secs = 1;
776                         break;
777                 case 'e':
778                         prompt_integer(&print_entries, "Enter display entries (lines)");
779                         if (print_entries == 0) {
780                                 sig_winch_handler(SIGWINCH);
781                                 signal(SIGWINCH, sig_winch_handler);
782                         } else
783                                 signal(SIGWINCH, SIG_DFL);
784                         break;
785                 case 'E':
786                         if (nr_counters > 1) {
787                                 int i;
788
789                                 fprintf(stderr, "\nAvailable events:");
790                                 for (i = 0; i < nr_counters; i++)
791                                         fprintf(stderr, "\n\t%d %s", i, event_name(i));
792
793                                 prompt_integer(&sym_counter, "Enter details event counter");
794
795                                 if (sym_counter >= nr_counters) {
796                                         fprintf(stderr, "Sorry, no such event, using %s.\n", event_name(0));
797                                         sym_counter = 0;
798                                         sleep(1);
799                                 }
800                         } else sym_counter = 0;
801                         break;
802                 case 'f':
803                         prompt_integer(&count_filter, "Enter display event count filter");
804                         break;
805                 case 'F':
806                         prompt_percent(&sym_pcnt_filter, "Enter details display event filter (percent)");
807                         break;
808                 case 'K':
809                         hide_kernel_symbols = !hide_kernel_symbols;
810                         break;
811                 case 'q':
812                 case 'Q':
813                         printf("exiting.\n");
814                         if (dump_symtab)
815                                 dsos__fprintf(stderr);
816                         exit(0);
817                 case 's':
818                         prompt_symbol(&sym_filter_entry, "Enter details symbol");
819                         break;
820                 case 'S':
821                         if (!sym_filter_entry)
822                                 break;
823                         else {
824                                 struct sym_entry *syme = sym_filter_entry;
825
826                                 pthread_mutex_lock(&syme->src->lock);
827                                 sym_filter_entry = NULL;
828                                 __zero_source_counters(syme);
829                                 pthread_mutex_unlock(&syme->src->lock);
830                         }
831                         break;
832                 case 'U':
833                         hide_user_symbols = !hide_user_symbols;
834                         break;
835                 case 'w':
836                         display_weighted = ~display_weighted;
837                         break;
838                 case 'z':
839                         zero = ~zero;
840                         break;
841                 default:
842                         break;
843         }
844 }
845
846 static void *display_thread(void *arg __used)
847 {
848         struct pollfd stdin_poll = { .fd = 0, .events = POLLIN };
849         struct termios tc, save;
850         int delay_msecs, c;
851
852         tcgetattr(0, &save);
853         tc = save;
854         tc.c_lflag &= ~(ICANON | ECHO);
855         tc.c_cc[VMIN] = 0;
856         tc.c_cc[VTIME] = 0;
857
858 repeat:
859         delay_msecs = delay_secs * 1000;
860         tcsetattr(0, TCSANOW, &tc);
861         /* trash return*/
862         getc(stdin);
863
864         do {
865                 print_sym_table();
866         } while (!poll(&stdin_poll, 1, delay_msecs) == 1);
867
868         c = getc(stdin);
869         tcsetattr(0, TCSAFLUSH, &save);
870
871         handle_keypress(c);
872         goto repeat;
873
874         return NULL;
875 }
876
877 /* Tag samples to be skipped. */
878 static const char *skip_symbols[] = {
879         "default_idle",
880         "cpu_idle",
881         "enter_idle",
882         "exit_idle",
883         "mwait_idle",
884         "mwait_idle_with_hints",
885         "poll_idle",
886         "ppc64_runlatch_off",
887         "pseries_dedicated_idle_sleep",
888         NULL
889 };
890
891 static int symbol_filter(struct map *map, struct symbol *sym)
892 {
893         struct sym_entry *syme;
894         const char *name = sym->name;
895         int i;
896
897         /*
898          * ppc64 uses function descriptors and appends a '.' to the
899          * start of every instruction address. Remove it.
900          */
901         if (name[0] == '.')
902                 name++;
903
904         if (!strcmp(name, "_text") ||
905             !strcmp(name, "_etext") ||
906             !strcmp(name, "_sinittext") ||
907             !strncmp("init_module", name, 11) ||
908             !strncmp("cleanup_module", name, 14) ||
909             strstr(name, "_text_start") ||
910             strstr(name, "_text_end"))
911                 return 1;
912
913         syme = symbol__priv(sym);
914         syme->map = map;
915         syme->src = NULL;
916
917         if (!sym_filter_entry && sym_filter && !strcmp(name, sym_filter)) {
918                 /* schedule initial sym_filter_entry setup */
919                 sym_filter_entry_sched = syme;
920                 sym_filter = NULL;
921         }
922
923         for (i = 0; skip_symbols[i]; i++) {
924                 if (!strcmp(skip_symbols[i], name)) {
925                         syme->skip = 1;
926                         break;
927                 }
928         }
929
930         if (!syme->skip)
931                 syme->name_len = strlen(sym->name);
932
933         return 0;
934 }
935
936 static void event__process_sample(const event_t *self,
937                                  struct perf_session *session, int counter)
938 {
939         u64 ip = self->ip.ip;
940         struct sym_entry *syme;
941         struct addr_location al;
942         u8 origin = self->header.misc & PERF_RECORD_MISC_CPUMODE_MASK;
943
944         ++samples;
945
946         switch (origin) {
947         case PERF_RECORD_MISC_USER:
948                 ++userspace_samples;
949                 if (hide_user_symbols)
950                         return;
951                 break;
952         case PERF_RECORD_MISC_KERNEL:
953                 if (hide_kernel_symbols)
954                         return;
955                 break;
956         default:
957                 return;
958         }
959
960         if (self->header.misc & PERF_RECORD_MISC_EXACT)
961                 exact_samples++;
962
963         if (event__preprocess_sample(self, session, &al, symbol_filter) < 0 ||
964             al.filtered)
965                 return;
966
967         if (al.sym == NULL) {
968                 /*
969                  * As we do lazy loading of symtabs we only will know if the
970                  * specified vmlinux file is invalid when we actually have a
971                  * hit in kernel space and then try to load it. So if we get
972                  * here and there are _no_ symbols in the DSO backing the
973                  * kernel map, bail out.
974                  *
975                  * We may never get here, for instance, if we use -K/
976                  * --hide-kernel-symbols, even if the user specifies an
977                  * invalid --vmlinux ;-)
978                  */
979                 if (al.map == session->vmlinux_maps[MAP__FUNCTION] &&
980                     RB_EMPTY_ROOT(&al.map->dso->symbols[MAP__FUNCTION])) {
981                         pr_err("The %s file can't be used\n",
982                                symbol_conf.vmlinux_name);
983                         exit(1);
984                 }
985
986                 return;
987         }
988
989         /* let's see, whether we need to install initial sym_filter_entry */
990         if (sym_filter_entry_sched) {
991                 sym_filter_entry = sym_filter_entry_sched;
992                 sym_filter_entry_sched = NULL;
993                 parse_source(sym_filter_entry);
994         }
995
996         syme = symbol__priv(al.sym);
997         if (!syme->skip) {
998                 syme->count[counter]++;
999                 syme->origin = origin;
1000                 record_precise_ip(syme, counter, ip);
1001                 pthread_mutex_lock(&active_symbols_lock);
1002                 if (list_empty(&syme->node) || !syme->node.next)
1003                         __list_insert_active_sym(syme);
1004                 pthread_mutex_unlock(&active_symbols_lock);
1005         }
1006 }
1007
1008 static int event__process(event_t *event, struct perf_session *session)
1009 {
1010         switch (event->header.type) {
1011         case PERF_RECORD_COMM:
1012                 event__process_comm(event, session);
1013                 break;
1014         case PERF_RECORD_MMAP:
1015                 event__process_mmap(event, session);
1016                 break;
1017         case PERF_RECORD_FORK:
1018         case PERF_RECORD_EXIT:
1019                 event__process_task(event, session);
1020                 break;
1021         default:
1022                 break;
1023         }
1024
1025         return 0;
1026 }
1027
1028 struct mmap_data {
1029         int                     counter;
1030         void                    *base;
1031         int                     mask;
1032         unsigned int            prev;
1033 };
1034
1035 static unsigned int mmap_read_head(struct mmap_data *md)
1036 {
1037         struct perf_event_mmap_page *pc = md->base;
1038         int head;
1039
1040         head = pc->data_head;
1041         rmb();
1042
1043         return head;
1044 }
1045
1046 static void perf_session__mmap_read_counter(struct perf_session *self,
1047                                             struct mmap_data *md)
1048 {
1049         unsigned int head = mmap_read_head(md);
1050         unsigned int old = md->prev;
1051         unsigned char *data = md->base + page_size;
1052         int diff;
1053
1054         /*
1055          * If we're further behind than half the buffer, there's a chance
1056          * the writer will bite our tail and mess up the samples under us.
1057          *
1058          * If we somehow ended up ahead of the head, we got messed up.
1059          *
1060          * In either case, truncate and restart at head.
1061          */
1062         diff = head - old;
1063         if (diff > md->mask / 2 || diff < 0) {
1064                 fprintf(stderr, "WARNING: failed to keep up with mmap data.\n");
1065
1066                 /*
1067                  * head points to a known good entry, start there.
1068                  */
1069                 old = head;
1070         }
1071
1072         for (; old != head;) {
1073                 event_t *event = (event_t *)&data[old & md->mask];
1074
1075                 event_t event_copy;
1076
1077                 size_t size = event->header.size;
1078
1079                 /*
1080                  * Event straddles the mmap boundary -- header should always
1081                  * be inside due to u64 alignment of output.
1082                  */
1083                 if ((old & md->mask) + size != ((old + size) & md->mask)) {
1084                         unsigned int offset = old;
1085                         unsigned int len = min(sizeof(*event), size), cpy;
1086                         void *dst = &event_copy;
1087
1088                         do {
1089                                 cpy = min(md->mask + 1 - (offset & md->mask), len);
1090                                 memcpy(dst, &data[offset & md->mask], cpy);
1091                                 offset += cpy;
1092                                 dst += cpy;
1093                                 len -= cpy;
1094                         } while (len);
1095
1096                         event = &event_copy;
1097                 }
1098
1099                 if (event->header.type == PERF_RECORD_SAMPLE)
1100                         event__process_sample(event, self, md->counter);
1101                 else
1102                         event__process(event, self);
1103                 old += size;
1104         }
1105
1106         md->prev = old;
1107 }
1108
1109 static struct pollfd event_array[MAX_NR_CPUS * MAX_COUNTERS];
1110 static struct mmap_data mmap_array[MAX_NR_CPUS][MAX_COUNTERS];
1111
1112 static void perf_session__mmap_read(struct perf_session *self)
1113 {
1114         int i, counter;
1115
1116         for (i = 0; i < nr_cpus; i++) {
1117                 for (counter = 0; counter < nr_counters; counter++)
1118                         perf_session__mmap_read_counter(self, &mmap_array[i][counter]);
1119         }
1120 }
1121
1122 int nr_poll;
1123 int group_fd;
1124
1125 static void start_counter(int i, int counter)
1126 {
1127         struct perf_event_attr *attr;
1128         int cpu;
1129
1130         cpu = profile_cpu;
1131         if (target_pid == -1 && profile_cpu == -1)
1132                 cpu = i;
1133
1134         attr = attrs + counter;
1135
1136         attr->sample_type       = PERF_SAMPLE_IP | PERF_SAMPLE_TID;
1137
1138         if (freq) {
1139                 attr->sample_type       |= PERF_SAMPLE_PERIOD;
1140                 attr->freq              = 1;
1141                 attr->sample_freq       = freq;
1142         }
1143
1144         attr->inherit           = (cpu < 0) && inherit;
1145         attr->mmap              = 1;
1146
1147 try_again:
1148         fd[i][counter] = sys_perf_event_open(attr, target_pid, cpu, group_fd, 0);
1149
1150         if (fd[i][counter] < 0) {
1151                 int err = errno;
1152
1153                 if (err == EPERM || err == EACCES)
1154                         die("No permission - are you root?\n");
1155                 /*
1156                  * If it's cycles then fall back to hrtimer
1157                  * based cpu-clock-tick sw counter, which
1158                  * is always available even if no PMU support:
1159                  */
1160                 if (attr->type == PERF_TYPE_HARDWARE
1161                         && attr->config == PERF_COUNT_HW_CPU_CYCLES) {
1162
1163                         if (verbose)
1164                                 warning(" ... trying to fall back to cpu-clock-ticks\n");
1165
1166                         attr->type = PERF_TYPE_SOFTWARE;
1167                         attr->config = PERF_COUNT_SW_CPU_CLOCK;
1168                         goto try_again;
1169                 }
1170                 printf("\n");
1171                 error("perfcounter syscall returned with %d (%s)\n",
1172                         fd[i][counter], strerror(err));
1173                 die("No CONFIG_PERF_EVENTS=y kernel support configured?\n");
1174                 exit(-1);
1175         }
1176         assert(fd[i][counter] >= 0);
1177         fcntl(fd[i][counter], F_SETFL, O_NONBLOCK);
1178
1179         /*
1180          * First counter acts as the group leader:
1181          */
1182         if (group && group_fd == -1)
1183                 group_fd = fd[i][counter];
1184
1185         event_array[nr_poll].fd = fd[i][counter];
1186         event_array[nr_poll].events = POLLIN;
1187         nr_poll++;
1188
1189         mmap_array[i][counter].counter = counter;
1190         mmap_array[i][counter].prev = 0;
1191         mmap_array[i][counter].mask = mmap_pages*page_size - 1;
1192         mmap_array[i][counter].base = mmap(NULL, (mmap_pages+1)*page_size,
1193                         PROT_READ, MAP_SHARED, fd[i][counter], 0);
1194         if (mmap_array[i][counter].base == MAP_FAILED)
1195                 die("failed to mmap with %d (%s)\n", errno, strerror(errno));
1196 }
1197
1198 static int __cmd_top(void)
1199 {
1200         pthread_t thread;
1201         int i, counter;
1202         int ret;
1203         /*
1204          * FIXME: perf_session__new should allow passing a O_MMAP, so that all this
1205          * mmap reading, etc is encapsulated in it. Use O_WRONLY for now.
1206          */
1207         struct perf_session *session = perf_session__new(NULL, O_WRONLY, false);
1208         if (session == NULL)
1209                 return -ENOMEM;
1210
1211         if (target_pid != -1)
1212                 event__synthesize_thread(target_pid, event__process, session);
1213         else
1214                 event__synthesize_threads(event__process, session);
1215
1216         for (i = 0; i < nr_cpus; i++) {
1217                 group_fd = -1;
1218                 for (counter = 0; counter < nr_counters; counter++)
1219                         start_counter(i, counter);
1220         }
1221
1222         /* Wait for a minimal set of events before starting the snapshot */
1223         poll(event_array, nr_poll, 100);
1224
1225         perf_session__mmap_read(session);
1226
1227         if (pthread_create(&thread, NULL, display_thread, NULL)) {
1228                 printf("Could not create display thread.\n");
1229                 exit(-1);
1230         }
1231
1232         if (realtime_prio) {
1233                 struct sched_param param;
1234
1235                 param.sched_priority = realtime_prio;
1236                 if (sched_setscheduler(0, SCHED_FIFO, &param)) {
1237                         printf("Could not set realtime priority.\n");
1238                         exit(-1);
1239                 }
1240         }
1241
1242         while (1) {
1243                 int hits = samples;
1244
1245                 perf_session__mmap_read(session);
1246
1247                 if (hits == samples)
1248                         ret = poll(event_array, nr_poll, 100);
1249         }
1250
1251         return 0;
1252 }
1253
1254 static const char * const top_usage[] = {
1255         "perf top [<options>]",
1256         NULL
1257 };
1258
1259 static const struct option options[] = {
1260         OPT_CALLBACK('e', "event", NULL, "event",
1261                      "event selector. use 'perf list' to list available events",
1262                      parse_events),
1263         OPT_INTEGER('c', "count", &default_interval,
1264                     "event period to sample"),
1265         OPT_INTEGER('p', "pid", &target_pid,
1266                     "profile events on existing pid"),
1267         OPT_BOOLEAN('a', "all-cpus", &system_wide,
1268                             "system-wide collection from all CPUs"),
1269         OPT_INTEGER('C', "CPU", &profile_cpu,
1270                     "CPU to profile on"),
1271         OPT_STRING('k', "vmlinux", &symbol_conf.vmlinux_name,
1272                    "file", "vmlinux pathname"),
1273         OPT_BOOLEAN('K', "hide_kernel_symbols", &hide_kernel_symbols,
1274                     "hide kernel symbols"),
1275         OPT_INTEGER('m', "mmap-pages", &mmap_pages,
1276                     "number of mmap data pages"),
1277         OPT_INTEGER('r', "realtime", &realtime_prio,
1278                     "collect data with this RT SCHED_FIFO priority"),
1279         OPT_INTEGER('d', "delay", &delay_secs,
1280                     "number of seconds to delay between refreshes"),
1281         OPT_BOOLEAN('D', "dump-symtab", &dump_symtab,
1282                             "dump the symbol table used for profiling"),
1283         OPT_INTEGER('f', "count-filter", &count_filter,
1284                     "only display functions with more events than this"),
1285         OPT_BOOLEAN('g', "group", &group,
1286                             "put the counters into a counter group"),
1287         OPT_BOOLEAN('i', "inherit", &inherit,
1288                     "child tasks inherit counters"),
1289         OPT_STRING('s', "sym-annotate", &sym_filter, "symbol name",
1290                     "symbol to annotate"),
1291         OPT_BOOLEAN('z', "zero", &zero,
1292                     "zero history across updates"),
1293         OPT_INTEGER('F', "freq", &freq,
1294                     "profile at this frequency"),
1295         OPT_INTEGER('E', "entries", &print_entries,
1296                     "display this many functions"),
1297         OPT_BOOLEAN('U', "hide_user_symbols", &hide_user_symbols,
1298                     "hide user symbols"),
1299         OPT_BOOLEAN('v', "verbose", &verbose,
1300                     "be more verbose (show counter open errors, etc)"),
1301         OPT_END()
1302 };
1303
1304 int cmd_top(int argc, const char **argv, const char *prefix __used)
1305 {
1306         int counter;
1307
1308         page_size = sysconf(_SC_PAGE_SIZE);
1309
1310         argc = parse_options(argc, argv, options, top_usage, 0);
1311         if (argc)
1312                 usage_with_options(top_usage, options);
1313
1314         /* CPU and PID are mutually exclusive */
1315         if (target_pid != -1 && profile_cpu != -1) {
1316                 printf("WARNING: PID switch overriding CPU\n");
1317                 sleep(1);
1318                 profile_cpu = -1;
1319         }
1320
1321         if (!nr_counters)
1322                 nr_counters = 1;
1323
1324         symbol_conf.priv_size = (sizeof(struct sym_entry) +
1325                                  (nr_counters + 1) * sizeof(unsigned long));
1326
1327         symbol_conf.try_vmlinux_path = (symbol_conf.vmlinux_name == NULL);
1328         if (symbol__init() < 0)
1329                 return -1;
1330
1331         if (delay_secs < 1)
1332                 delay_secs = 1;
1333
1334         /*
1335          * User specified count overrides default frequency.
1336          */
1337         if (default_interval)
1338                 freq = 0;
1339         else if (freq) {
1340                 default_interval = freq;
1341         } else {
1342                 fprintf(stderr, "frequency and count are zero, aborting\n");
1343                 exit(EXIT_FAILURE);
1344         }
1345
1346         /*
1347          * Fill in the ones not specifically initialized via -c:
1348          */
1349         for (counter = 0; counter < nr_counters; counter++) {
1350                 if (attrs[counter].sample_period)
1351                         continue;
1352
1353                 attrs[counter].sample_period = default_interval;
1354         }
1355
1356         nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
1357         assert(nr_cpus <= MAX_NR_CPUS);
1358         assert(nr_cpus >= 0);
1359
1360         if (target_pid != -1 || profile_cpu != -1)
1361                 nr_cpus = 1;
1362
1363         get_term_dimensions(&winsize);
1364         if (print_entries == 0) {
1365                 update_print_entries(&winsize);
1366                 signal(SIGWINCH, sig_winch_handler);
1367         }
1368
1369         return __cmd_top();
1370 }