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