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