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