perf archive: Explain how to use the generated tarball
[linux-2.6/libata-dev.git] / tools / perf / builtin-top.c
blob5f3ac9ff354d6c0f8b5840c0dda840b29ddf7739
1 /*
2 * builtin-top.c
4 * Builtin top command: Display a continuously updated profile of
5 * any workload, CPU or specific PID.
7 * Copyright (C) 2008, Red Hat Inc, Ingo Molnar <mingo@redhat.com>
9 * Improvements and fixes by:
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>
17 * Released under the GPL v2. (and only v2, not any later version)
19 #include "builtin.h"
21 #include "perf.h"
23 #include "util/color.h"
24 #include "util/session.h"
25 #include "util/symbol.h"
26 #include "util/thread.h"
27 #include "util/util.h"
28 #include <linux/rbtree.h>
29 #include "util/parse-options.h"
30 #include "util/parse-events.h"
31 #include "util/cpumap.h"
33 #include "util/debug.h"
35 #include <assert.h>
36 #include <fcntl.h>
38 #include <stdio.h>
39 #include <termios.h>
40 #include <unistd.h>
42 #include <errno.h>
43 #include <time.h>
44 #include <sched.h>
45 #include <pthread.h>
47 #include <sys/syscall.h>
48 #include <sys/ioctl.h>
49 #include <sys/poll.h>
50 #include <sys/prctl.h>
51 #include <sys/wait.h>
52 #include <sys/uio.h>
53 #include <sys/mman.h>
55 #include <linux/unistd.h>
56 #include <linux/types.h>
58 static int *fd[MAX_NR_CPUS][MAX_COUNTERS];
60 static int system_wide = 0;
62 static int default_interval = 0;
64 static int count_filter = 5;
65 static int print_entries;
67 static int target_pid = -1;
68 static int target_tid = -1;
69 static pid_t *all_tids = NULL;
70 static int thread_num = 0;
71 static int inherit = 0;
72 static int profile_cpu = -1;
73 static int nr_cpus = 0;
74 static unsigned int realtime_prio = 0;
75 static int group = 0;
76 static unsigned int page_size;
77 static unsigned int mmap_pages = 16;
78 static int freq = 1000; /* 1 KHz */
80 static int delay_secs = 2;
81 static int zero = 0;
82 static int dump_symtab = 0;
84 static bool hide_kernel_symbols = false;
85 static bool hide_user_symbols = false;
86 static struct winsize winsize;
89 * Source
92 struct source_line {
93 u64 eip;
94 unsigned long count[MAX_COUNTERS];
95 char *line;
96 struct source_line *next;
99 static char *sym_filter = NULL;
100 struct sym_entry *sym_filter_entry = NULL;
101 struct sym_entry *sym_filter_entry_sched = NULL;
102 static int sym_pcnt_filter = 5;
103 static int sym_counter = 0;
104 static int display_weighted = -1;
107 * Symbols
110 struct sym_entry_source {
111 struct source_line *source;
112 struct source_line *lines;
113 struct source_line **lines_tail;
114 pthread_mutex_t lock;
117 struct sym_entry {
118 struct rb_node rb_node;
119 struct list_head node;
120 unsigned long snap_count;
121 double weight;
122 int skip;
123 u16 name_len;
124 u8 origin;
125 struct map *map;
126 struct sym_entry_source *src;
127 unsigned long count[0];
131 * Source functions
134 static inline struct symbol *sym_entry__symbol(struct sym_entry *self)
136 return ((void *)self) + symbol_conf.priv_size;
139 void get_term_dimensions(struct winsize *ws)
141 char *s = getenv("LINES");
143 if (s != NULL) {
144 ws->ws_row = atoi(s);
145 s = getenv("COLUMNS");
146 if (s != NULL) {
147 ws->ws_col = atoi(s);
148 if (ws->ws_row && ws->ws_col)
149 return;
152 #ifdef TIOCGWINSZ
153 if (ioctl(1, TIOCGWINSZ, ws) == 0 &&
154 ws->ws_row && ws->ws_col)
155 return;
156 #endif
157 ws->ws_row = 25;
158 ws->ws_col = 80;
161 static void update_print_entries(struct winsize *ws)
163 print_entries = ws->ws_row;
165 if (print_entries > 9)
166 print_entries -= 9;
169 static void sig_winch_handler(int sig __used)
171 get_term_dimensions(&winsize);
172 update_print_entries(&winsize);
175 static int parse_source(struct sym_entry *syme)
177 struct symbol *sym;
178 struct sym_entry_source *source;
179 struct map *map;
180 FILE *file;
181 char command[PATH_MAX*2];
182 const char *path;
183 u64 len;
185 if (!syme)
186 return -1;
188 sym = sym_entry__symbol(syme);
189 map = syme->map;
192 * We can't annotate with just /proc/kallsyms
194 if (map->dso->origin == DSO__ORIG_KERNEL)
195 return -1;
197 if (syme->src == NULL) {
198 syme->src = zalloc(sizeof(*source));
199 if (syme->src == NULL)
200 return -1;
201 pthread_mutex_init(&syme->src->lock, NULL);
204 source = syme->src;
206 if (source->lines) {
207 pthread_mutex_lock(&source->lock);
208 goto out_assign;
210 path = map->dso->long_name;
212 len = sym->end - sym->start;
214 sprintf(command,
215 "objdump --start-address=%#0*Lx --stop-address=%#0*Lx -dS %s",
216 BITS_PER_LONG / 4, map__rip_2objdump(map, sym->start),
217 BITS_PER_LONG / 4, map__rip_2objdump(map, sym->end), path);
219 file = popen(command, "r");
220 if (!file)
221 return -1;
223 pthread_mutex_lock(&source->lock);
224 source->lines_tail = &source->lines;
225 while (!feof(file)) {
226 struct source_line *src;
227 size_t dummy = 0;
228 char *c, *sep;
230 src = malloc(sizeof(struct source_line));
231 assert(src != NULL);
232 memset(src, 0, sizeof(struct source_line));
234 if (getline(&src->line, &dummy, file) < 0)
235 break;
236 if (!src->line)
237 break;
239 c = strchr(src->line, '\n');
240 if (c)
241 *c = 0;
243 src->next = NULL;
244 *source->lines_tail = src;
245 source->lines_tail = &src->next;
247 src->eip = strtoull(src->line, &sep, 16);
248 if (*sep == ':')
249 src->eip = map__objdump_2ip(map, src->eip);
250 else /* this line has no ip info (e.g. source line) */
251 src->eip = 0;
253 pclose(file);
254 out_assign:
255 sym_filter_entry = syme;
256 pthread_mutex_unlock(&source->lock);
257 return 0;
260 static void __zero_source_counters(struct sym_entry *syme)
262 int i;
263 struct source_line *line;
265 line = syme->src->lines;
266 while (line) {
267 for (i = 0; i < nr_counters; i++)
268 line->count[i] = 0;
269 line = line->next;
273 static void record_precise_ip(struct sym_entry *syme, int counter, u64 ip)
275 struct source_line *line;
277 if (syme != sym_filter_entry)
278 return;
280 if (pthread_mutex_trylock(&syme->src->lock))
281 return;
283 if (syme->src == NULL || syme->src->source == NULL)
284 goto out_unlock;
286 for (line = syme->src->lines; line; line = line->next) {
287 /* skip lines without IP info */
288 if (line->eip == 0)
289 continue;
290 if (line->eip == ip) {
291 line->count[counter]++;
292 break;
294 if (line->eip > ip)
295 break;
297 out_unlock:
298 pthread_mutex_unlock(&syme->src->lock);
301 #define PATTERN_LEN (BITS_PER_LONG / 4 + 2)
303 static void lookup_sym_source(struct sym_entry *syme)
305 struct symbol *symbol = sym_entry__symbol(syme);
306 struct source_line *line;
307 char pattern[PATTERN_LEN + 1];
309 sprintf(pattern, "%0*Lx <", BITS_PER_LONG / 4,
310 map__rip_2objdump(syme->map, symbol->start));
312 pthread_mutex_lock(&syme->src->lock);
313 for (line = syme->src->lines; line; line = line->next) {
314 if (memcmp(line->line, pattern, PATTERN_LEN) == 0) {
315 syme->src->source = line;
316 break;
319 pthread_mutex_unlock(&syme->src->lock);
322 static void show_lines(struct source_line *queue, int count, int total)
324 int i;
325 struct source_line *line;
327 line = queue;
328 for (i = 0; i < count; i++) {
329 float pcnt = 100.0*(float)line->count[sym_counter]/(float)total;
331 printf("%8li %4.1f%%\t%s\n", line->count[sym_counter], pcnt, line->line);
332 line = line->next;
336 #define TRACE_COUNT 3
338 static void show_details(struct sym_entry *syme)
340 struct symbol *symbol;
341 struct source_line *line;
342 struct source_line *line_queue = NULL;
343 int displayed = 0;
344 int line_queue_count = 0, total = 0, more = 0;
346 if (!syme)
347 return;
349 if (!syme->src->source)
350 lookup_sym_source(syme);
352 if (!syme->src->source)
353 return;
355 symbol = sym_entry__symbol(syme);
356 printf("Showing %s for %s\n", event_name(sym_counter), symbol->name);
357 printf(" Events Pcnt (>=%d%%)\n", sym_pcnt_filter);
359 pthread_mutex_lock(&syme->src->lock);
360 line = syme->src->source;
361 while (line) {
362 total += line->count[sym_counter];
363 line = line->next;
366 line = syme->src->source;
367 while (line) {
368 float pcnt = 0.0;
370 if (!line_queue_count)
371 line_queue = line;
372 line_queue_count++;
374 if (line->count[sym_counter])
375 pcnt = 100.0 * line->count[sym_counter] / (float)total;
376 if (pcnt >= (float)sym_pcnt_filter) {
377 if (displayed <= print_entries)
378 show_lines(line_queue, line_queue_count, total);
379 else more++;
380 displayed += line_queue_count;
381 line_queue_count = 0;
382 line_queue = NULL;
383 } else if (line_queue_count > TRACE_COUNT) {
384 line_queue = line_queue->next;
385 line_queue_count--;
388 line->count[sym_counter] = zero ? 0 : line->count[sym_counter] * 7 / 8;
389 line = line->next;
391 pthread_mutex_unlock(&syme->src->lock);
392 if (more)
393 printf("%d lines not displayed, maybe increase display entries [e]\n", more);
397 * Symbols will be added here in event__process_sample and will get out
398 * after decayed.
400 static LIST_HEAD(active_symbols);
401 static pthread_mutex_t active_symbols_lock = PTHREAD_MUTEX_INITIALIZER;
404 * Ordering weight: count-1 * count-2 * ... / count-n
406 static double sym_weight(const struct sym_entry *sym)
408 double weight = sym->snap_count;
409 int counter;
411 if (!display_weighted)
412 return weight;
414 for (counter = 1; counter < nr_counters-1; counter++)
415 weight *= sym->count[counter];
417 weight /= (sym->count[counter] + 1);
419 return weight;
422 static long samples;
423 static long userspace_samples;
424 static long exact_samples;
425 static const char CONSOLE_CLEAR[] = "\e[H\e[2J";
427 static void __list_insert_active_sym(struct sym_entry *syme)
429 list_add(&syme->node, &active_symbols);
432 static void list_remove_active_sym(struct sym_entry *syme)
434 pthread_mutex_lock(&active_symbols_lock);
435 list_del_init(&syme->node);
436 pthread_mutex_unlock(&active_symbols_lock);
439 static void rb_insert_active_sym(struct rb_root *tree, struct sym_entry *se)
441 struct rb_node **p = &tree->rb_node;
442 struct rb_node *parent = NULL;
443 struct sym_entry *iter;
445 while (*p != NULL) {
446 parent = *p;
447 iter = rb_entry(parent, struct sym_entry, rb_node);
449 if (se->weight > iter->weight)
450 p = &(*p)->rb_left;
451 else
452 p = &(*p)->rb_right;
455 rb_link_node(&se->rb_node, parent, p);
456 rb_insert_color(&se->rb_node, tree);
459 static void print_sym_table(void)
461 int printed = 0, j;
462 int counter, snap = !display_weighted ? sym_counter : 0;
463 float samples_per_sec = samples/delay_secs;
464 float ksamples_per_sec = (samples-userspace_samples)/delay_secs;
465 float esamples_percent = (100.0*exact_samples)/samples;
466 float sum_ksamples = 0.0;
467 struct sym_entry *syme, *n;
468 struct rb_root tmp = RB_ROOT;
469 struct rb_node *nd;
470 int sym_width = 0, dso_width = 0, dso_short_width = 0;
471 const int win_width = winsize.ws_col - 1;
473 samples = userspace_samples = exact_samples = 0;
475 /* Sort the active symbols */
476 pthread_mutex_lock(&active_symbols_lock);
477 syme = list_entry(active_symbols.next, struct sym_entry, node);
478 pthread_mutex_unlock(&active_symbols_lock);
480 list_for_each_entry_safe_from(syme, n, &active_symbols, node) {
481 syme->snap_count = syme->count[snap];
482 if (syme->snap_count != 0) {
484 if ((hide_user_symbols &&
485 syme->origin == PERF_RECORD_MISC_USER) ||
486 (hide_kernel_symbols &&
487 syme->origin == PERF_RECORD_MISC_KERNEL)) {
488 list_remove_active_sym(syme);
489 continue;
491 syme->weight = sym_weight(syme);
492 rb_insert_active_sym(&tmp, syme);
493 sum_ksamples += syme->snap_count;
495 for (j = 0; j < nr_counters; j++)
496 syme->count[j] = zero ? 0 : syme->count[j] * 7 / 8;
497 } else
498 list_remove_active_sym(syme);
501 puts(CONSOLE_CLEAR);
503 printf("%-*.*s\n", win_width, win_width, graph_dotted_line);
504 printf( " PerfTop:%8.0f irqs/sec kernel:%4.1f%% exact: %4.1f%% [",
505 samples_per_sec,
506 100.0 - (100.0*((samples_per_sec-ksamples_per_sec)/samples_per_sec)),
507 esamples_percent);
509 if (nr_counters == 1 || !display_weighted) {
510 printf("%Ld", (u64)attrs[0].sample_period);
511 if (freq)
512 printf("Hz ");
513 else
514 printf(" ");
517 if (!display_weighted)
518 printf("%s", event_name(sym_counter));
519 else for (counter = 0; counter < nr_counters; counter++) {
520 if (counter)
521 printf("/");
523 printf("%s", event_name(counter));
526 printf( "], ");
528 if (target_pid != -1)
529 printf(" (target_pid: %d", target_pid);
530 else if (target_tid != -1)
531 printf(" (target_tid: %d", target_tid);
532 else
533 printf(" (all");
535 if (profile_cpu != -1)
536 printf(", cpu: %d)\n", profile_cpu);
537 else {
538 if (target_tid != -1)
539 printf(")\n");
540 else
541 printf(", %d CPUs)\n", nr_cpus);
544 printf("%-*.*s\n", win_width, win_width, graph_dotted_line);
546 if (sym_filter_entry) {
547 show_details(sym_filter_entry);
548 return;
552 * Find the longest symbol name that will be displayed
554 for (nd = rb_first(&tmp); nd; nd = rb_next(nd)) {
555 syme = rb_entry(nd, struct sym_entry, rb_node);
556 if (++printed > print_entries ||
557 (int)syme->snap_count < count_filter)
558 continue;
560 if (syme->map->dso->long_name_len > dso_width)
561 dso_width = syme->map->dso->long_name_len;
563 if (syme->map->dso->short_name_len > dso_short_width)
564 dso_short_width = syme->map->dso->short_name_len;
566 if (syme->name_len > sym_width)
567 sym_width = syme->name_len;
570 printed = 0;
572 if (sym_width + dso_width > winsize.ws_col - 29) {
573 dso_width = dso_short_width;
574 if (sym_width + dso_width > winsize.ws_col - 29)
575 sym_width = winsize.ws_col - dso_width - 29;
577 putchar('\n');
578 if (nr_counters == 1)
579 printf(" samples pcnt");
580 else
581 printf(" weight samples pcnt");
583 if (verbose)
584 printf(" RIP ");
585 printf(" %-*.*s DSO\n", sym_width, sym_width, "function");
586 printf(" %s _______ _____",
587 nr_counters == 1 ? " " : "______");
588 if (verbose)
589 printf(" ________________");
590 printf(" %-*.*s", sym_width, sym_width, graph_line);
591 printf(" %-*.*s", dso_width, dso_width, graph_line);
592 puts("\n");
594 for (nd = rb_first(&tmp); nd; nd = rb_next(nd)) {
595 struct symbol *sym;
596 double pcnt;
598 syme = rb_entry(nd, struct sym_entry, rb_node);
599 sym = sym_entry__symbol(syme);
601 if (++printed > print_entries || (int)syme->snap_count < count_filter)
602 continue;
604 pcnt = 100.0 - (100.0 * ((sum_ksamples - syme->snap_count) /
605 sum_ksamples));
607 if (nr_counters == 1 || !display_weighted)
608 printf("%20.2f ", syme->weight);
609 else
610 printf("%9.1f %10ld ", syme->weight, syme->snap_count);
612 percent_color_fprintf(stdout, "%4.1f%%", pcnt);
613 if (verbose)
614 printf(" %016llx", sym->start);
615 printf(" %-*.*s", sym_width, sym_width, sym->name);
616 printf(" %-*.*s\n", dso_width, dso_width,
617 dso_width >= syme->map->dso->long_name_len ?
618 syme->map->dso->long_name :
619 syme->map->dso->short_name);
623 static void prompt_integer(int *target, const char *msg)
625 char *buf = malloc(0), *p;
626 size_t dummy = 0;
627 int tmp;
629 fprintf(stdout, "\n%s: ", msg);
630 if (getline(&buf, &dummy, stdin) < 0)
631 return;
633 p = strchr(buf, '\n');
634 if (p)
635 *p = 0;
637 p = buf;
638 while(*p) {
639 if (!isdigit(*p))
640 goto out_free;
641 p++;
643 tmp = strtoul(buf, NULL, 10);
644 *target = tmp;
645 out_free:
646 free(buf);
649 static void prompt_percent(int *target, const char *msg)
651 int tmp = 0;
653 prompt_integer(&tmp, msg);
654 if (tmp >= 0 && tmp <= 100)
655 *target = tmp;
658 static void prompt_symbol(struct sym_entry **target, const char *msg)
660 char *buf = malloc(0), *p;
661 struct sym_entry *syme = *target, *n, *found = NULL;
662 size_t dummy = 0;
664 /* zero counters of active symbol */
665 if (syme) {
666 pthread_mutex_lock(&syme->src->lock);
667 __zero_source_counters(syme);
668 *target = NULL;
669 pthread_mutex_unlock(&syme->src->lock);
672 fprintf(stdout, "\n%s: ", msg);
673 if (getline(&buf, &dummy, stdin) < 0)
674 goto out_free;
676 p = strchr(buf, '\n');
677 if (p)
678 *p = 0;
680 pthread_mutex_lock(&active_symbols_lock);
681 syme = list_entry(active_symbols.next, struct sym_entry, node);
682 pthread_mutex_unlock(&active_symbols_lock);
684 list_for_each_entry_safe_from(syme, n, &active_symbols, node) {
685 struct symbol *sym = sym_entry__symbol(syme);
687 if (!strcmp(buf, sym->name)) {
688 found = syme;
689 break;
693 if (!found) {
694 fprintf(stderr, "Sorry, %s is not active.\n", buf);
695 sleep(1);
696 return;
697 } else
698 parse_source(found);
700 out_free:
701 free(buf);
704 static void print_mapped_keys(void)
706 char *name = NULL;
708 if (sym_filter_entry) {
709 struct symbol *sym = sym_entry__symbol(sym_filter_entry);
710 name = sym->name;
713 fprintf(stdout, "\nMapped keys:\n");
714 fprintf(stdout, "\t[d] display refresh delay. \t(%d)\n", delay_secs);
715 fprintf(stdout, "\t[e] display entries (lines). \t(%d)\n", print_entries);
717 if (nr_counters > 1)
718 fprintf(stdout, "\t[E] active event counter. \t(%s)\n", event_name(sym_counter));
720 fprintf(stdout, "\t[f] profile display filter (count). \t(%d)\n", count_filter);
722 fprintf(stdout, "\t[F] annotate display filter (percent). \t(%d%%)\n", sym_pcnt_filter);
723 fprintf(stdout, "\t[s] annotate symbol. \t(%s)\n", name?: "NULL");
724 fprintf(stdout, "\t[S] stop annotation.\n");
726 if (nr_counters > 1)
727 fprintf(stdout, "\t[w] toggle display weighted/count[E]r. \t(%d)\n", display_weighted ? 1 : 0);
729 fprintf(stdout,
730 "\t[K] hide kernel_symbols symbols. \t(%s)\n",
731 hide_kernel_symbols ? "yes" : "no");
732 fprintf(stdout,
733 "\t[U] hide user symbols. \t(%s)\n",
734 hide_user_symbols ? "yes" : "no");
735 fprintf(stdout, "\t[z] toggle sample zeroing. \t(%d)\n", zero ? 1 : 0);
736 fprintf(stdout, "\t[qQ] quit.\n");
739 static int key_mapped(int c)
741 switch (c) {
742 case 'd':
743 case 'e':
744 case 'f':
745 case 'z':
746 case 'q':
747 case 'Q':
748 case 'K':
749 case 'U':
750 case 'F':
751 case 's':
752 case 'S':
753 return 1;
754 case 'E':
755 case 'w':
756 return nr_counters > 1 ? 1 : 0;
757 default:
758 break;
761 return 0;
764 static void handle_keypress(int c)
766 if (!key_mapped(c)) {
767 struct pollfd stdin_poll = { .fd = 0, .events = POLLIN };
768 struct termios tc, save;
770 print_mapped_keys();
771 fprintf(stdout, "\nEnter selection, or unmapped key to continue: ");
772 fflush(stdout);
774 tcgetattr(0, &save);
775 tc = save;
776 tc.c_lflag &= ~(ICANON | ECHO);
777 tc.c_cc[VMIN] = 0;
778 tc.c_cc[VTIME] = 0;
779 tcsetattr(0, TCSANOW, &tc);
781 poll(&stdin_poll, 1, -1);
782 c = getc(stdin);
784 tcsetattr(0, TCSAFLUSH, &save);
785 if (!key_mapped(c))
786 return;
789 switch (c) {
790 case 'd':
791 prompt_integer(&delay_secs, "Enter display delay");
792 if (delay_secs < 1)
793 delay_secs = 1;
794 break;
795 case 'e':
796 prompt_integer(&print_entries, "Enter display entries (lines)");
797 if (print_entries == 0) {
798 sig_winch_handler(SIGWINCH);
799 signal(SIGWINCH, sig_winch_handler);
800 } else
801 signal(SIGWINCH, SIG_DFL);
802 break;
803 case 'E':
804 if (nr_counters > 1) {
805 int i;
807 fprintf(stderr, "\nAvailable events:");
808 for (i = 0; i < nr_counters; i++)
809 fprintf(stderr, "\n\t%d %s", i, event_name(i));
811 prompt_integer(&sym_counter, "Enter details event counter");
813 if (sym_counter >= nr_counters) {
814 fprintf(stderr, "Sorry, no such event, using %s.\n", event_name(0));
815 sym_counter = 0;
816 sleep(1);
818 } else sym_counter = 0;
819 break;
820 case 'f':
821 prompt_integer(&count_filter, "Enter display event count filter");
822 break;
823 case 'F':
824 prompt_percent(&sym_pcnt_filter, "Enter details display event filter (percent)");
825 break;
826 case 'K':
827 hide_kernel_symbols = !hide_kernel_symbols;
828 break;
829 case 'q':
830 case 'Q':
831 printf("exiting.\n");
832 if (dump_symtab)
833 dsos__fprintf(stderr);
834 exit(0);
835 case 's':
836 prompt_symbol(&sym_filter_entry, "Enter details symbol");
837 break;
838 case 'S':
839 if (!sym_filter_entry)
840 break;
841 else {
842 struct sym_entry *syme = sym_filter_entry;
844 pthread_mutex_lock(&syme->src->lock);
845 sym_filter_entry = NULL;
846 __zero_source_counters(syme);
847 pthread_mutex_unlock(&syme->src->lock);
849 break;
850 case 'U':
851 hide_user_symbols = !hide_user_symbols;
852 break;
853 case 'w':
854 display_weighted = ~display_weighted;
855 break;
856 case 'z':
857 zero = ~zero;
858 break;
859 default:
860 break;
864 static void *display_thread(void *arg __used)
866 struct pollfd stdin_poll = { .fd = 0, .events = POLLIN };
867 struct termios tc, save;
868 int delay_msecs, c;
870 tcgetattr(0, &save);
871 tc = save;
872 tc.c_lflag &= ~(ICANON | ECHO);
873 tc.c_cc[VMIN] = 0;
874 tc.c_cc[VTIME] = 0;
876 repeat:
877 delay_msecs = delay_secs * 1000;
878 tcsetattr(0, TCSANOW, &tc);
879 /* trash return*/
880 getc(stdin);
882 do {
883 print_sym_table();
884 } while (!poll(&stdin_poll, 1, delay_msecs) == 1);
886 c = getc(stdin);
887 tcsetattr(0, TCSAFLUSH, &save);
889 handle_keypress(c);
890 goto repeat;
892 return NULL;
895 /* Tag samples to be skipped. */
896 static const char *skip_symbols[] = {
897 "default_idle",
898 "cpu_idle",
899 "enter_idle",
900 "exit_idle",
901 "mwait_idle",
902 "mwait_idle_with_hints",
903 "poll_idle",
904 "ppc64_runlatch_off",
905 "pseries_dedicated_idle_sleep",
906 NULL
909 static int symbol_filter(struct map *map, struct symbol *sym)
911 struct sym_entry *syme;
912 const char *name = sym->name;
913 int i;
916 * ppc64 uses function descriptors and appends a '.' to the
917 * start of every instruction address. Remove it.
919 if (name[0] == '.')
920 name++;
922 if (!strcmp(name, "_text") ||
923 !strcmp(name, "_etext") ||
924 !strcmp(name, "_sinittext") ||
925 !strncmp("init_module", name, 11) ||
926 !strncmp("cleanup_module", name, 14) ||
927 strstr(name, "_text_start") ||
928 strstr(name, "_text_end"))
929 return 1;
931 syme = symbol__priv(sym);
932 syme->map = map;
933 syme->src = NULL;
935 if (!sym_filter_entry && sym_filter && !strcmp(name, sym_filter)) {
936 /* schedule initial sym_filter_entry setup */
937 sym_filter_entry_sched = syme;
938 sym_filter = NULL;
941 for (i = 0; skip_symbols[i]; i++) {
942 if (!strcmp(skip_symbols[i], name)) {
943 syme->skip = 1;
944 break;
948 if (!syme->skip)
949 syme->name_len = strlen(sym->name);
951 return 0;
954 static void event__process_sample(const event_t *self,
955 struct perf_session *session, int counter)
957 u64 ip = self->ip.ip;
958 struct sym_entry *syme;
959 struct addr_location al;
960 u8 origin = self->header.misc & PERF_RECORD_MISC_CPUMODE_MASK;
962 ++samples;
964 switch (origin) {
965 case PERF_RECORD_MISC_USER:
966 ++userspace_samples;
967 if (hide_user_symbols)
968 return;
969 break;
970 case PERF_RECORD_MISC_KERNEL:
971 if (hide_kernel_symbols)
972 return;
973 break;
974 default:
975 return;
978 if (self->header.misc & PERF_RECORD_MISC_EXACT)
979 exact_samples++;
981 if (event__preprocess_sample(self, session, &al, symbol_filter) < 0 ||
982 al.filtered)
983 return;
985 if (al.sym == NULL) {
987 * As we do lazy loading of symtabs we only will know if the
988 * specified vmlinux file is invalid when we actually have a
989 * hit in kernel space and then try to load it. So if we get
990 * here and there are _no_ symbols in the DSO backing the
991 * kernel map, bail out.
993 * We may never get here, for instance, if we use -K/
994 * --hide-kernel-symbols, even if the user specifies an
995 * invalid --vmlinux ;-)
997 if (al.map == session->vmlinux_maps[MAP__FUNCTION] &&
998 RB_EMPTY_ROOT(&al.map->dso->symbols[MAP__FUNCTION])) {
999 pr_err("The %s file can't be used\n",
1000 symbol_conf.vmlinux_name);
1001 exit(1);
1004 return;
1007 /* let's see, whether we need to install initial sym_filter_entry */
1008 if (sym_filter_entry_sched) {
1009 sym_filter_entry = sym_filter_entry_sched;
1010 sym_filter_entry_sched = NULL;
1011 if (parse_source(sym_filter_entry) < 0) {
1012 struct symbol *sym = sym_entry__symbol(sym_filter_entry);
1014 pr_err("Can't annotate %s", sym->name);
1015 if (sym_filter_entry->map->dso->origin == DSO__ORIG_KERNEL) {
1016 pr_err(": No vmlinux file was found in the path:\n");
1017 vmlinux_path__fprintf(stderr);
1018 } else
1019 pr_err(".\n");
1020 exit(1);
1024 syme = symbol__priv(al.sym);
1025 if (!syme->skip) {
1026 syme->count[counter]++;
1027 syme->origin = origin;
1028 record_precise_ip(syme, counter, ip);
1029 pthread_mutex_lock(&active_symbols_lock);
1030 if (list_empty(&syme->node) || !syme->node.next)
1031 __list_insert_active_sym(syme);
1032 pthread_mutex_unlock(&active_symbols_lock);
1036 static int event__process(event_t *event, struct perf_session *session)
1038 switch (event->header.type) {
1039 case PERF_RECORD_COMM:
1040 event__process_comm(event, session);
1041 break;
1042 case PERF_RECORD_MMAP:
1043 event__process_mmap(event, session);
1044 break;
1045 case PERF_RECORD_FORK:
1046 case PERF_RECORD_EXIT:
1047 event__process_task(event, session);
1048 break;
1049 default:
1050 break;
1053 return 0;
1056 struct mmap_data {
1057 int counter;
1058 void *base;
1059 int mask;
1060 unsigned int prev;
1063 static unsigned int mmap_read_head(struct mmap_data *md)
1065 struct perf_event_mmap_page *pc = md->base;
1066 int head;
1068 head = pc->data_head;
1069 rmb();
1071 return head;
1074 static void perf_session__mmap_read_counter(struct perf_session *self,
1075 struct mmap_data *md)
1077 unsigned int head = mmap_read_head(md);
1078 unsigned int old = md->prev;
1079 unsigned char *data = md->base + page_size;
1080 int diff;
1083 * If we're further behind than half the buffer, there's a chance
1084 * the writer will bite our tail and mess up the samples under us.
1086 * If we somehow ended up ahead of the head, we got messed up.
1088 * In either case, truncate and restart at head.
1090 diff = head - old;
1091 if (diff > md->mask / 2 || diff < 0) {
1092 fprintf(stderr, "WARNING: failed to keep up with mmap data.\n");
1095 * head points to a known good entry, start there.
1097 old = head;
1100 for (; old != head;) {
1101 event_t *event = (event_t *)&data[old & md->mask];
1103 event_t event_copy;
1105 size_t size = event->header.size;
1108 * Event straddles the mmap boundary -- header should always
1109 * be inside due to u64 alignment of output.
1111 if ((old & md->mask) + size != ((old + size) & md->mask)) {
1112 unsigned int offset = old;
1113 unsigned int len = min(sizeof(*event), size), cpy;
1114 void *dst = &event_copy;
1116 do {
1117 cpy = min(md->mask + 1 - (offset & md->mask), len);
1118 memcpy(dst, &data[offset & md->mask], cpy);
1119 offset += cpy;
1120 dst += cpy;
1121 len -= cpy;
1122 } while (len);
1124 event = &event_copy;
1127 if (event->header.type == PERF_RECORD_SAMPLE)
1128 event__process_sample(event, self, md->counter);
1129 else
1130 event__process(event, self);
1131 old += size;
1134 md->prev = old;
1137 static struct pollfd *event_array;
1138 static struct mmap_data *mmap_array[MAX_NR_CPUS][MAX_COUNTERS];
1140 static void perf_session__mmap_read(struct perf_session *self)
1142 int i, counter, thread_index;
1144 for (i = 0; i < nr_cpus; i++) {
1145 for (counter = 0; counter < nr_counters; counter++)
1146 for (thread_index = 0;
1147 thread_index < thread_num;
1148 thread_index++) {
1149 perf_session__mmap_read_counter(self,
1150 &mmap_array[i][counter][thread_index]);
1155 int nr_poll;
1156 int group_fd;
1158 static void start_counter(int i, int counter)
1160 struct perf_event_attr *attr;
1161 int cpu;
1162 int thread_index;
1164 cpu = profile_cpu;
1165 if (target_tid == -1 && profile_cpu == -1)
1166 cpu = cpumap[i];
1168 attr = attrs + counter;
1170 attr->sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_TID;
1172 if (freq) {
1173 attr->sample_type |= PERF_SAMPLE_PERIOD;
1174 attr->freq = 1;
1175 attr->sample_freq = freq;
1178 attr->inherit = (cpu < 0) && inherit;
1179 attr->mmap = 1;
1181 for (thread_index = 0; thread_index < thread_num; thread_index++) {
1182 try_again:
1183 fd[i][counter][thread_index] = sys_perf_event_open(attr,
1184 all_tids[thread_index], cpu, group_fd, 0);
1186 if (fd[i][counter][thread_index] < 0) {
1187 int err = errno;
1189 if (err == EPERM || err == EACCES)
1190 die("No permission - are you root?\n");
1192 * If it's cycles then fall back to hrtimer
1193 * based cpu-clock-tick sw counter, which
1194 * is always available even if no PMU support:
1196 if (attr->type == PERF_TYPE_HARDWARE
1197 && attr->config == PERF_COUNT_HW_CPU_CYCLES) {
1199 if (verbose)
1200 warning(" ... trying to fall back to cpu-clock-ticks\n");
1202 attr->type = PERF_TYPE_SOFTWARE;
1203 attr->config = PERF_COUNT_SW_CPU_CLOCK;
1204 goto try_again;
1206 printf("\n");
1207 error("perfcounter syscall returned with %d (%s)\n",
1208 fd[i][counter][thread_index], strerror(err));
1209 die("No CONFIG_PERF_EVENTS=y kernel support configured?\n");
1210 exit(-1);
1212 assert(fd[i][counter][thread_index] >= 0);
1213 fcntl(fd[i][counter][thread_index], F_SETFL, O_NONBLOCK);
1216 * First counter acts as the group leader:
1218 if (group && group_fd == -1)
1219 group_fd = fd[i][counter][thread_index];
1221 event_array[nr_poll].fd = fd[i][counter][thread_index];
1222 event_array[nr_poll].events = POLLIN;
1223 nr_poll++;
1225 mmap_array[i][counter][thread_index].counter = counter;
1226 mmap_array[i][counter][thread_index].prev = 0;
1227 mmap_array[i][counter][thread_index].mask = mmap_pages*page_size - 1;
1228 mmap_array[i][counter][thread_index].base = mmap(NULL, (mmap_pages+1)*page_size,
1229 PROT_READ, MAP_SHARED, fd[i][counter][thread_index], 0);
1230 if (mmap_array[i][counter][thread_index].base == MAP_FAILED)
1231 die("failed to mmap with %d (%s)\n", errno, strerror(errno));
1235 static int __cmd_top(void)
1237 pthread_t thread;
1238 int i, counter;
1239 int ret;
1241 * FIXME: perf_session__new should allow passing a O_MMAP, so that all this
1242 * mmap reading, etc is encapsulated in it. Use O_WRONLY for now.
1244 struct perf_session *session = perf_session__new(NULL, O_WRONLY, false);
1245 if (session == NULL)
1246 return -ENOMEM;
1248 if (target_tid != -1)
1249 event__synthesize_thread(target_tid, event__process, session);
1250 else
1251 event__synthesize_threads(event__process, session);
1253 for (i = 0; i < nr_cpus; i++) {
1254 group_fd = -1;
1255 for (counter = 0; counter < nr_counters; counter++)
1256 start_counter(i, counter);
1259 /* Wait for a minimal set of events before starting the snapshot */
1260 poll(&event_array[0], nr_poll, 100);
1262 perf_session__mmap_read(session);
1264 if (pthread_create(&thread, NULL, display_thread, NULL)) {
1265 printf("Could not create display thread.\n");
1266 exit(-1);
1269 if (realtime_prio) {
1270 struct sched_param param;
1272 param.sched_priority = realtime_prio;
1273 if (sched_setscheduler(0, SCHED_FIFO, &param)) {
1274 printf("Could not set realtime priority.\n");
1275 exit(-1);
1279 while (1) {
1280 int hits = samples;
1282 perf_session__mmap_read(session);
1284 if (hits == samples)
1285 ret = poll(event_array, nr_poll, 100);
1288 return 0;
1291 static const char * const top_usage[] = {
1292 "perf top [<options>]",
1293 NULL
1296 static const struct option options[] = {
1297 OPT_CALLBACK('e', "event", NULL, "event",
1298 "event selector. use 'perf list' to list available events",
1299 parse_events),
1300 OPT_INTEGER('c', "count", &default_interval,
1301 "event period to sample"),
1302 OPT_INTEGER('p', "pid", &target_pid,
1303 "profile events on existing process id"),
1304 OPT_INTEGER('t', "tid", &target_tid,
1305 "profile events on existing thread id"),
1306 OPT_BOOLEAN('a', "all-cpus", &system_wide,
1307 "system-wide collection from all CPUs"),
1308 OPT_INTEGER('C', "CPU", &profile_cpu,
1309 "CPU to profile on"),
1310 OPT_STRING('k', "vmlinux", &symbol_conf.vmlinux_name,
1311 "file", "vmlinux pathname"),
1312 OPT_BOOLEAN('K', "hide_kernel_symbols", &hide_kernel_symbols,
1313 "hide kernel symbols"),
1314 OPT_INTEGER('m', "mmap-pages", &mmap_pages,
1315 "number of mmap data pages"),
1316 OPT_INTEGER('r', "realtime", &realtime_prio,
1317 "collect data with this RT SCHED_FIFO priority"),
1318 OPT_INTEGER('d', "delay", &delay_secs,
1319 "number of seconds to delay between refreshes"),
1320 OPT_BOOLEAN('D', "dump-symtab", &dump_symtab,
1321 "dump the symbol table used for profiling"),
1322 OPT_INTEGER('f', "count-filter", &count_filter,
1323 "only display functions with more events than this"),
1324 OPT_BOOLEAN('g', "group", &group,
1325 "put the counters into a counter group"),
1326 OPT_BOOLEAN('i', "inherit", &inherit,
1327 "child tasks inherit counters"),
1328 OPT_STRING('s', "sym-annotate", &sym_filter, "symbol name",
1329 "symbol to annotate"),
1330 OPT_BOOLEAN('z', "zero", &zero,
1331 "zero history across updates"),
1332 OPT_INTEGER('F', "freq", &freq,
1333 "profile at this frequency"),
1334 OPT_INTEGER('E', "entries", &print_entries,
1335 "display this many functions"),
1336 OPT_BOOLEAN('U', "hide_user_symbols", &hide_user_symbols,
1337 "hide user symbols"),
1338 OPT_BOOLEAN('v', "verbose", &verbose,
1339 "be more verbose (show counter open errors, etc)"),
1340 OPT_END()
1343 int cmd_top(int argc, const char **argv, const char *prefix __used)
1345 int counter;
1346 int i,j;
1348 page_size = sysconf(_SC_PAGE_SIZE);
1350 argc = parse_options(argc, argv, options, top_usage, 0);
1351 if (argc)
1352 usage_with_options(top_usage, options);
1354 if (target_pid != -1) {
1355 target_tid = target_pid;
1356 thread_num = find_all_tid(target_pid, &all_tids);
1357 if (thread_num <= 0) {
1358 fprintf(stderr, "Can't find all threads of pid %d\n",
1359 target_pid);
1360 usage_with_options(top_usage, options);
1362 } else {
1363 all_tids=malloc(sizeof(pid_t));
1364 if (!all_tids)
1365 return -ENOMEM;
1367 all_tids[0] = target_tid;
1368 thread_num = 1;
1371 for (i = 0; i < MAX_NR_CPUS; i++) {
1372 for (j = 0; j < MAX_COUNTERS; j++) {
1373 fd[i][j] = malloc(sizeof(int)*thread_num);
1374 mmap_array[i][j] = malloc(
1375 sizeof(struct mmap_data)*thread_num);
1376 if (!fd[i][j] || !mmap_array[i][j])
1377 return -ENOMEM;
1380 event_array = malloc(
1381 sizeof(struct pollfd)*MAX_NR_CPUS*MAX_COUNTERS*thread_num);
1382 if (!event_array)
1383 return -ENOMEM;
1385 /* CPU and PID are mutually exclusive */
1386 if (target_tid > 0 && profile_cpu != -1) {
1387 printf("WARNING: PID switch overriding CPU\n");
1388 sleep(1);
1389 profile_cpu = -1;
1392 if (!nr_counters)
1393 nr_counters = 1;
1395 symbol_conf.priv_size = (sizeof(struct sym_entry) +
1396 (nr_counters + 1) * sizeof(unsigned long));
1398 symbol_conf.try_vmlinux_path = (symbol_conf.vmlinux_name == NULL);
1399 if (symbol__init() < 0)
1400 return -1;
1402 if (delay_secs < 1)
1403 delay_secs = 1;
1406 * User specified count overrides default frequency.
1408 if (default_interval)
1409 freq = 0;
1410 else if (freq) {
1411 default_interval = freq;
1412 } else {
1413 fprintf(stderr, "frequency and count are zero, aborting\n");
1414 exit(EXIT_FAILURE);
1418 * Fill in the ones not specifically initialized via -c:
1420 for (counter = 0; counter < nr_counters; counter++) {
1421 if (attrs[counter].sample_period)
1422 continue;
1424 attrs[counter].sample_period = default_interval;
1427 if (target_tid != -1 || profile_cpu != -1)
1428 nr_cpus = 1;
1429 else
1430 nr_cpus = read_cpu_map();
1432 get_term_dimensions(&winsize);
1433 if (print_entries == 0) {
1434 update_print_entries(&winsize);
1435 signal(SIGWINCH, sig_winch_handler);
1438 return __cmd_top();