perf symbols: Capture the running kernel buildid too
[safe/jmp/linux-2.6] / 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                         exit(0);
834                 case 's':
835                         prompt_symbol(&sym_filter_entry, "Enter details symbol");
836                         break;
837                 case 'S':
838                         if (!sym_filter_entry)
839                                 break;
840                         else {
841                                 struct sym_entry *syme = sym_filter_entry;
842
843                                 pthread_mutex_lock(&syme->src->lock);
844                                 sym_filter_entry = NULL;
845                                 __zero_source_counters(syme);
846                                 pthread_mutex_unlock(&syme->src->lock);
847                         }
848                         break;
849                 case 'U':
850                         hide_user_symbols = !hide_user_symbols;
851                         break;
852                 case 'w':
853                         display_weighted = ~display_weighted;
854                         break;
855                 case 'z':
856                         zero = ~zero;
857                         break;
858                 default:
859                         break;
860         }
861 }
862
863 static void *display_thread(void *arg __used)
864 {
865         struct pollfd stdin_poll = { .fd = 0, .events = POLLIN };
866         struct termios tc, save;
867         int delay_msecs, c;
868
869         tcgetattr(0, &save);
870         tc = save;
871         tc.c_lflag &= ~(ICANON | ECHO);
872         tc.c_cc[VMIN] = 0;
873         tc.c_cc[VTIME] = 0;
874
875 repeat:
876         delay_msecs = delay_secs * 1000;
877         tcsetattr(0, TCSANOW, &tc);
878         /* trash return*/
879         getc(stdin);
880
881         do {
882                 print_sym_table();
883         } while (!poll(&stdin_poll, 1, delay_msecs) == 1);
884
885         c = getc(stdin);
886         tcsetattr(0, TCSAFLUSH, &save);
887
888         handle_keypress(c);
889         goto repeat;
890
891         return NULL;
892 }
893
894 /* Tag samples to be skipped. */
895 static const char *skip_symbols[] = {
896         "default_idle",
897         "cpu_idle",
898         "enter_idle",
899         "exit_idle",
900         "mwait_idle",
901         "mwait_idle_with_hints",
902         "poll_idle",
903         "ppc64_runlatch_off",
904         "pseries_dedicated_idle_sleep",
905         NULL
906 };
907
908 static int symbol_filter(struct map *map, struct symbol *sym)
909 {
910         struct sym_entry *syme;
911         const char *name = sym->name;
912         int i;
913
914         /*
915          * ppc64 uses function descriptors and appends a '.' to the
916          * start of every instruction address. Remove it.
917          */
918         if (name[0] == '.')
919                 name++;
920
921         if (!strcmp(name, "_text") ||
922             !strcmp(name, "_etext") ||
923             !strcmp(name, "_sinittext") ||
924             !strncmp("init_module", name, 11) ||
925             !strncmp("cleanup_module", name, 14) ||
926             strstr(name, "_text_start") ||
927             strstr(name, "_text_end"))
928                 return 1;
929
930         syme = symbol__priv(sym);
931         syme->map = map;
932         syme->src = NULL;
933         if (!sym_filter_entry && sym_filter && !strcmp(name, sym_filter))
934                 sym_filter_entry = syme;
935
936         for (i = 0; skip_symbols[i]; i++) {
937                 if (!strcmp(skip_symbols[i], name)) {
938                         syme->skip = 1;
939                         break;
940                 }
941         }
942
943         if (!syme->skip)
944                 syme->name_len = strlen(sym->name);
945
946         return 0;
947 }
948
949 static int parse_symbols(void)
950 {
951         struct dso *kernel = dsos__load_kernel();
952
953         if (kernel == NULL)
954                 return -1;
955
956         if (dso__load_kernel_sym(kernel, symbol_filter, 1) <= 0)
957                 return -1;
958
959         if (dump_symtab)
960                 dsos__fprintf(stderr);
961
962         return 0;
963 }
964
965 static void event__process_sample(const event_t *self, int counter)
966 {
967         u64 ip = self->ip.ip;
968         struct map *map;
969         struct sym_entry *syme;
970         struct symbol *sym;
971         u8 origin = self->header.misc & PERF_RECORD_MISC_CPUMODE_MASK;
972
973         switch (origin) {
974         case PERF_RECORD_MISC_USER: {
975                 struct thread *thread;
976
977                 if (hide_user_symbols)
978                         return;
979
980                 thread = threads__findnew(self->ip.pid);
981                 if (thread == NULL)
982                         return;
983
984                 map = thread__find_map(thread, ip);
985                 if (map != NULL) {
986                         ip = map->map_ip(map, ip);
987                         sym = map__find_symbol(map, ip, symbol_filter);
988                         if (sym == NULL)
989                                 return;
990                         userspace_samples++;
991                         break;
992                 }
993         }
994                 /*
995                  * If this is outside of all known maps,
996                  * and is a negative address, try to look it
997                  * up in the kernel dso, as it might be a
998                  * vsyscall or vdso (which executes in user-mode).
999                  */
1000                 if ((long long)ip >= 0)
1001                         return;
1002                 /* Fall thru */
1003         case PERF_RECORD_MISC_KERNEL:
1004                 if (hide_kernel_symbols)
1005                         return;
1006
1007                 sym = kernel_maps__find_symbol(ip, &map);
1008                 if (sym == NULL)
1009                         return;
1010                 break;
1011         default:
1012                 return;
1013         }
1014
1015         syme = symbol__priv(sym);
1016
1017         if (!syme->skip) {
1018                 syme->count[counter]++;
1019                 syme->origin = origin;
1020                 record_precise_ip(syme, counter, ip);
1021                 pthread_mutex_lock(&active_symbols_lock);
1022                 if (list_empty(&syme->node) || !syme->node.next)
1023                         __list_insert_active_sym(syme);
1024                 pthread_mutex_unlock(&active_symbols_lock);
1025                 ++samples;
1026                 return;
1027         }
1028 }
1029
1030 static void event__process_mmap(event_t *self)
1031 {
1032         struct thread *thread = threads__findnew(self->mmap.pid);
1033
1034         if (thread != NULL) {
1035                 struct map *map = map__new(&self->mmap, NULL, 0);
1036                 if (map != NULL)
1037                         thread__insert_map(thread, map);
1038         }
1039 }
1040
1041 static void event__process_comm(event_t *self)
1042 {
1043         struct thread *thread = threads__findnew(self->comm.pid);
1044
1045         if (thread != NULL)
1046                 thread__set_comm(thread, self->comm.comm);
1047 }
1048
1049 static int event__process(event_t *event)
1050 {
1051         switch (event->header.type) {
1052         case PERF_RECORD_COMM:
1053                 event__process_comm(event);
1054                 break;
1055         case PERF_RECORD_MMAP:
1056                 event__process_mmap(event);
1057                 break;
1058         default:
1059                 break;
1060         }
1061
1062         return 0;
1063 }
1064
1065 struct mmap_data {
1066         int                     counter;
1067         void                    *base;
1068         int                     mask;
1069         unsigned int            prev;
1070 };
1071
1072 static unsigned int mmap_read_head(struct mmap_data *md)
1073 {
1074         struct perf_event_mmap_page *pc = md->base;
1075         int head;
1076
1077         head = pc->data_head;
1078         rmb();
1079
1080         return head;
1081 }
1082
1083 static void mmap_read_counter(struct mmap_data *md)
1084 {
1085         unsigned int head = mmap_read_head(md);
1086         unsigned int old = md->prev;
1087         unsigned char *data = md->base + page_size;
1088         int diff;
1089
1090         /*
1091          * If we're further behind than half the buffer, there's a chance
1092          * the writer will bite our tail and mess up the samples under us.
1093          *
1094          * If we somehow ended up ahead of the head, we got messed up.
1095          *
1096          * In either case, truncate and restart at head.
1097          */
1098         diff = head - old;
1099         if (diff > md->mask / 2 || diff < 0) {
1100                 fprintf(stderr, "WARNING: failed to keep up with mmap data.\n");
1101
1102                 /*
1103                  * head points to a known good entry, start there.
1104                  */
1105                 old = head;
1106         }
1107
1108         for (; old != head;) {
1109                 event_t *event = (event_t *)&data[old & md->mask];
1110
1111                 event_t event_copy;
1112
1113                 size_t size = event->header.size;
1114
1115                 /*
1116                  * Event straddles the mmap boundary -- header should always
1117                  * be inside due to u64 alignment of output.
1118                  */
1119                 if ((old & md->mask) + size != ((old + size) & md->mask)) {
1120                         unsigned int offset = old;
1121                         unsigned int len = min(sizeof(*event), size), cpy;
1122                         void *dst = &event_copy;
1123
1124                         do {
1125                                 cpy = min(md->mask + 1 - (offset & md->mask), len);
1126                                 memcpy(dst, &data[offset & md->mask], cpy);
1127                                 offset += cpy;
1128                                 dst += cpy;
1129                                 len -= cpy;
1130                         } while (len);
1131
1132                         event = &event_copy;
1133                 }
1134
1135                 if (event->header.type == PERF_RECORD_SAMPLE)
1136                         event__process_sample(event, md->counter);
1137                 else
1138                         event__process(event);
1139                 old += size;
1140         }
1141
1142         md->prev = old;
1143 }
1144
1145 static struct pollfd event_array[MAX_NR_CPUS * MAX_COUNTERS];
1146 static struct mmap_data mmap_array[MAX_NR_CPUS][MAX_COUNTERS];
1147
1148 static void mmap_read(void)
1149 {
1150         int i, counter;
1151
1152         for (i = 0; i < nr_cpus; i++) {
1153                 for (counter = 0; counter < nr_counters; counter++)
1154                         mmap_read_counter(&mmap_array[i][counter]);
1155         }
1156 }
1157
1158 int nr_poll;
1159 int group_fd;
1160
1161 static void start_counter(int i, int counter)
1162 {
1163         struct perf_event_attr *attr;
1164         int cpu;
1165
1166         cpu = profile_cpu;
1167         if (target_pid == -1 && profile_cpu == -1)
1168                 cpu = i;
1169
1170         attr = attrs + counter;
1171
1172         attr->sample_type       = PERF_SAMPLE_IP | PERF_SAMPLE_TID;
1173
1174         if (freq) {
1175                 attr->sample_type       |= PERF_SAMPLE_PERIOD;
1176                 attr->freq              = 1;
1177                 attr->sample_freq       = freq;
1178         }
1179
1180         attr->inherit           = (cpu < 0) && inherit;
1181         attr->mmap              = 1;
1182
1183 try_again:
1184         fd[i][counter] = sys_perf_event_open(attr, target_pid, cpu, group_fd, 0);
1185
1186         if (fd[i][counter] < 0) {
1187                 int err = errno;
1188
1189                 if (err == EPERM || err == EACCES)
1190                         die("No permission - are you root?\n");
1191                 /*
1192                  * If it's cycles then fall back to hrtimer
1193                  * based cpu-clock-tick sw counter, which
1194                  * is always available even if no PMU support:
1195                  */
1196                 if (attr->type == PERF_TYPE_HARDWARE
1197                         && attr->config == PERF_COUNT_HW_CPU_CYCLES) {
1198
1199                         if (verbose)
1200                                 warning(" ... trying to fall back to cpu-clock-ticks\n");
1201
1202                         attr->type = PERF_TYPE_SOFTWARE;
1203                         attr->config = PERF_COUNT_SW_CPU_CLOCK;
1204                         goto try_again;
1205                 }
1206                 printf("\n");
1207                 error("perfcounter syscall returned with %d (%s)\n",
1208                         fd[i][counter], strerror(err));
1209                 die("No CONFIG_PERF_EVENTS=y kernel support configured?\n");
1210                 exit(-1);
1211         }
1212         assert(fd[i][counter] >= 0);
1213         fcntl(fd[i][counter], F_SETFL, O_NONBLOCK);
1214
1215         /*
1216          * First counter acts as the group leader:
1217          */
1218         if (group && group_fd == -1)
1219                 group_fd = fd[i][counter];
1220
1221         event_array[nr_poll].fd = fd[i][counter];
1222         event_array[nr_poll].events = POLLIN;
1223         nr_poll++;
1224
1225         mmap_array[i][counter].counter = counter;
1226         mmap_array[i][counter].prev = 0;
1227         mmap_array[i][counter].mask = mmap_pages*page_size - 1;
1228         mmap_array[i][counter].base = mmap(NULL, (mmap_pages+1)*page_size,
1229                         PROT_READ, MAP_SHARED, fd[i][counter], 0);
1230         if (mmap_array[i][counter].base == MAP_FAILED)
1231                 die("failed to mmap with %d (%s)\n", errno, strerror(errno));
1232 }
1233
1234 static int __cmd_top(void)
1235 {
1236         pthread_t thread;
1237         int i, counter;
1238         int ret;
1239
1240         if (target_pid != -1)
1241                 event__synthesize_thread(target_pid, event__process);
1242         else
1243                 event__synthesize_threads(event__process);
1244
1245         for (i = 0; i < nr_cpus; i++) {
1246                 group_fd = -1;
1247                 for (counter = 0; counter < nr_counters; counter++)
1248                         start_counter(i, counter);
1249         }
1250
1251         /* Wait for a minimal set of events before starting the snapshot */
1252         poll(event_array, nr_poll, 100);
1253
1254         mmap_read();
1255
1256         if (pthread_create(&thread, NULL, display_thread, NULL)) {
1257                 printf("Could not create display thread.\n");
1258                 exit(-1);
1259         }
1260
1261         if (realtime_prio) {
1262                 struct sched_param param;
1263
1264                 param.sched_priority = realtime_prio;
1265                 if (sched_setscheduler(0, SCHED_FIFO, &param)) {
1266                         printf("Could not set realtime priority.\n");
1267                         exit(-1);
1268                 }
1269         }
1270
1271         while (1) {
1272                 int hits = samples;
1273
1274                 mmap_read();
1275
1276                 if (hits == samples)
1277                         ret = poll(event_array, nr_poll, 100);
1278         }
1279
1280         return 0;
1281 }
1282
1283 static const char * const top_usage[] = {
1284         "perf top [<options>]",
1285         NULL
1286 };
1287
1288 static const struct option options[] = {
1289         OPT_CALLBACK('e', "event", NULL, "event",
1290                      "event selector. use 'perf list' to list available events",
1291                      parse_events),
1292         OPT_INTEGER('c', "count", &default_interval,
1293                     "event period to sample"),
1294         OPT_INTEGER('p', "pid", &target_pid,
1295                     "profile events on existing pid"),
1296         OPT_BOOLEAN('a', "all-cpus", &system_wide,
1297                             "system-wide collection from all CPUs"),
1298         OPT_INTEGER('C', "CPU", &profile_cpu,
1299                     "CPU to profile on"),
1300         OPT_STRING('k', "vmlinux", &vmlinux_name, "file", "vmlinux pathname"),
1301         OPT_BOOLEAN('K', "hide_kernel_symbols", &hide_kernel_symbols,
1302                     "hide kernel symbols"),
1303         OPT_INTEGER('m', "mmap-pages", &mmap_pages,
1304                     "number of mmap data pages"),
1305         OPT_INTEGER('r', "realtime", &realtime_prio,
1306                     "collect data with this RT SCHED_FIFO priority"),
1307         OPT_INTEGER('d', "delay", &delay_secs,
1308                     "number of seconds to delay between refreshes"),
1309         OPT_BOOLEAN('D', "dump-symtab", &dump_symtab,
1310                             "dump the symbol table used for profiling"),
1311         OPT_INTEGER('f', "count-filter", &count_filter,
1312                     "only display functions with more events than this"),
1313         OPT_BOOLEAN('g', "group", &group,
1314                             "put the counters into a counter group"),
1315         OPT_BOOLEAN('i', "inherit", &inherit,
1316                     "child tasks inherit counters"),
1317         OPT_STRING('s', "sym-annotate", &sym_filter, "symbol name",
1318                     "symbol to annotate - requires -k option"),
1319         OPT_BOOLEAN('z', "zero", &zero,
1320                     "zero history across updates"),
1321         OPT_INTEGER('F', "freq", &freq,
1322                     "profile at this frequency"),
1323         OPT_INTEGER('E', "entries", &print_entries,
1324                     "display this many functions"),
1325         OPT_BOOLEAN('U', "hide_user_symbols", &hide_user_symbols,
1326                     "hide user symbols"),
1327         OPT_BOOLEAN('v', "verbose", &verbose,
1328                     "be more verbose (show counter open errors, etc)"),
1329         OPT_END()
1330 };
1331
1332 int cmd_top(int argc, const char **argv, const char *prefix __used)
1333 {
1334         int counter;
1335
1336         page_size = sysconf(_SC_PAGE_SIZE);
1337
1338         argc = parse_options(argc, argv, options, top_usage, 0);
1339         if (argc)
1340                 usage_with_options(top_usage, options);
1341
1342         /* CPU and PID are mutually exclusive */
1343         if (target_pid != -1 && profile_cpu != -1) {
1344                 printf("WARNING: PID switch overriding CPU\n");
1345                 sleep(1);
1346                 profile_cpu = -1;
1347         }
1348
1349         if (!nr_counters)
1350                 nr_counters = 1;
1351
1352         symbol__init(sizeof(struct sym_entry) +
1353                      (nr_counters + 1) * sizeof(unsigned long));
1354
1355         if (delay_secs < 1)
1356                 delay_secs = 1;
1357
1358         parse_symbols();
1359         parse_source(sym_filter_entry);
1360
1361
1362         /*
1363          * User specified count overrides default frequency.
1364          */
1365         if (default_interval)
1366                 freq = 0;
1367         else if (freq) {
1368                 default_interval = freq;
1369         } else {
1370                 fprintf(stderr, "frequency and count are zero, aborting\n");
1371                 exit(EXIT_FAILURE);
1372         }
1373
1374         /*
1375          * Fill in the ones not specifically initialized via -c:
1376          */
1377         for (counter = 0; counter < nr_counters; counter++) {
1378                 if (attrs[counter].sample_period)
1379                         continue;
1380
1381                 attrs[counter].sample_period = default_interval;
1382         }
1383
1384         nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
1385         assert(nr_cpus <= MAX_NR_CPUS);
1386         assert(nr_cpus >= 0);
1387
1388         if (target_pid != -1 || profile_cpu != -1)
1389                 nr_cpus = 1;
1390
1391         get_term_dimensions(&winsize);
1392         if (print_entries == 0) {
1393                 update_print_entries(&winsize);
1394                 signal(SIGWINCH, sig_winch_handler);
1395         }
1396
1397         return __cmd_top();
1398 }