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