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