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