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