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