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)
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"
32 #include "util/debug.h"
46 #include <sys/syscall.h>
47 #include <sys/ioctl.h>
49 #include <sys/prctl.h>
54 #include <linux/unistd.h>
55 #include <linux/types.h>
57 static int fd[MAX_NR_CPUS][MAX_COUNTERS];
59 static int system_wide = 0;
61 static int default_interval = 0;
63 static int count_filter = 5;
64 static int print_entries;
66 static int target_pid = -1;
67 static int inherit = 0;
68 static int profile_cpu = -1;
69 static int nr_cpus = 0;
70 static unsigned int realtime_prio = 0;
72 static unsigned int page_size;
73 static unsigned int mmap_pages = 16;
74 static int freq = 1000; /* 1 KHz */
76 static int delay_secs = 2;
78 static int dump_symtab = 0;
80 static bool hide_kernel_symbols = false;
81 static bool hide_user_symbols = false;
82 static struct winsize winsize;
83 static struct symbol_conf symbol_conf;
91 unsigned long count[MAX_COUNTERS];
93 struct source_line *next;
96 static char *sym_filter = NULL;
97 struct sym_entry *sym_filter_entry = NULL;
98 static int sym_pcnt_filter = 5;
99 static int sym_counter = 0;
100 static int display_weighted = -1;
106 struct sym_entry_source {
107 struct source_line *source;
108 struct source_line *lines;
109 struct source_line **lines_tail;
110 pthread_mutex_t lock;
114 struct rb_node rb_node;
115 struct list_head node;
116 unsigned long snap_count;
122 struct sym_entry_source *src;
123 unsigned long count[0];
130 static inline struct symbol *sym_entry__symbol(struct sym_entry *self)
132 return ((void *)self) + symbol_conf.priv_size;
135 static void get_term_dimensions(struct winsize *ws)
137 char *s = getenv("LINES");
140 ws->ws_row = atoi(s);
141 s = getenv("COLUMNS");
143 ws->ws_col = atoi(s);
144 if (ws->ws_row && ws->ws_col)
149 if (ioctl(1, TIOCGWINSZ, ws) == 0 &&
150 ws->ws_row && ws->ws_col)
157 static void update_print_entries(struct winsize *ws)
159 print_entries = ws->ws_row;
161 if (print_entries > 9)
165 static void sig_winch_handler(int sig __used)
167 get_term_dimensions(&winsize);
168 update_print_entries(&winsize);
171 static void parse_source(struct sym_entry *syme)
174 struct sym_entry_source *source;
177 char command[PATH_MAX*2];
184 if (syme->src == NULL) {
185 syme->src = zalloc(sizeof(*source));
186 if (syme->src == NULL)
188 pthread_mutex_init(&syme->src->lock, NULL);
194 pthread_mutex_lock(&source->lock);
198 sym = sym_entry__symbol(syme);
200 path = map->dso->long_name;
202 len = sym->end - sym->start;
205 "objdump --start-address=0x%016Lx "
206 "--stop-address=0x%016Lx -dS %s",
207 map->unmap_ip(map, sym->start),
208 map->unmap_ip(map, sym->end), path);
210 file = popen(command, "r");
214 pthread_mutex_lock(&source->lock);
215 source->lines_tail = &source->lines;
216 while (!feof(file)) {
217 struct source_line *src;
221 src = malloc(sizeof(struct source_line));
223 memset(src, 0, sizeof(struct source_line));
225 if (getline(&src->line, &dummy, file) < 0)
230 c = strchr(src->line, '\n');
235 *source->lines_tail = src;
236 source->lines_tail = &src->next;
238 if (strlen(src->line)>8 && src->line[8] == ':') {
239 src->eip = strtoull(src->line, NULL, 16);
240 src->eip = map->unmap_ip(map, src->eip);
242 if (strlen(src->line)>8 && src->line[16] == ':') {
243 src->eip = strtoull(src->line, NULL, 16);
244 src->eip = map->unmap_ip(map, src->eip);
249 sym_filter_entry = syme;
250 pthread_mutex_unlock(&source->lock);
253 static void __zero_source_counters(struct sym_entry *syme)
256 struct source_line *line;
258 line = syme->src->lines;
260 for (i = 0; i < nr_counters; i++)
266 static void record_precise_ip(struct sym_entry *syme, int counter, u64 ip)
268 struct source_line *line;
270 if (syme != sym_filter_entry)
273 if (pthread_mutex_trylock(&syme->src->lock))
276 if (syme->src == NULL || syme->src->source == NULL)
279 for (line = syme->src->lines; line; line = line->next) {
280 if (line->eip == ip) {
281 line->count[counter]++;
288 pthread_mutex_unlock(&syme->src->lock);
291 static void lookup_sym_source(struct sym_entry *syme)
293 struct symbol *symbol = sym_entry__symbol(syme);
294 struct source_line *line;
295 char pattern[PATH_MAX];
297 sprintf(pattern, "<%s>:", symbol->name);
299 pthread_mutex_lock(&syme->src->lock);
300 for (line = syme->src->lines; line; line = line->next) {
301 if (strstr(line->line, pattern)) {
302 syme->src->source = line;
306 pthread_mutex_unlock(&syme->src->lock);
309 static void show_lines(struct source_line *queue, int count, int total)
312 struct source_line *line;
315 for (i = 0; i < count; i++) {
316 float pcnt = 100.0*(float)line->count[sym_counter]/(float)total;
318 printf("%8li %4.1f%%\t%s\n", line->count[sym_counter], pcnt, line->line);
323 #define TRACE_COUNT 3
325 static void show_details(struct sym_entry *syme)
327 struct symbol *symbol;
328 struct source_line *line;
329 struct source_line *line_queue = NULL;
331 int line_queue_count = 0, total = 0, more = 0;
336 if (!syme->src->source)
337 lookup_sym_source(syme);
339 if (!syme->src->source)
342 symbol = sym_entry__symbol(syme);
343 printf("Showing %s for %s\n", event_name(sym_counter), symbol->name);
344 printf(" Events Pcnt (>=%d%%)\n", sym_pcnt_filter);
346 pthread_mutex_lock(&syme->src->lock);
347 line = syme->src->source;
349 total += line->count[sym_counter];
353 line = syme->src->source;
357 if (!line_queue_count)
361 if (line->count[sym_counter])
362 pcnt = 100.0 * line->count[sym_counter] / (float)total;
363 if (pcnt >= (float)sym_pcnt_filter) {
364 if (displayed <= print_entries)
365 show_lines(line_queue, line_queue_count, total);
367 displayed += line_queue_count;
368 line_queue_count = 0;
370 } else if (line_queue_count > TRACE_COUNT) {
371 line_queue = line_queue->next;
375 line->count[sym_counter] = zero ? 0 : line->count[sym_counter] * 7 / 8;
378 pthread_mutex_unlock(&syme->src->lock);
380 printf("%d lines not displayed, maybe increase display entries [e]\n", more);
384 * Symbols will be added here in event__process_sample and will get out
387 static LIST_HEAD(active_symbols);
388 static pthread_mutex_t active_symbols_lock = PTHREAD_MUTEX_INITIALIZER;
391 * Ordering weight: count-1 * count-2 * ... / count-n
393 static double sym_weight(const struct sym_entry *sym)
395 double weight = sym->snap_count;
398 if (!display_weighted)
401 for (counter = 1; counter < nr_counters-1; counter++)
402 weight *= sym->count[counter];
404 weight /= (sym->count[counter] + 1);
410 static long userspace_samples;
411 static const char CONSOLE_CLEAR[] = "
\e[H
\e[2J";
413 static void __list_insert_active_sym(struct sym_entry *syme)
415 list_add(&syme->node, &active_symbols);
418 static void list_remove_active_sym(struct sym_entry *syme)
420 pthread_mutex_lock(&active_symbols_lock);
421 list_del_init(&syme->node);
422 pthread_mutex_unlock(&active_symbols_lock);
425 static void rb_insert_active_sym(struct rb_root *tree, struct sym_entry *se)
427 struct rb_node **p = &tree->rb_node;
428 struct rb_node *parent = NULL;
429 struct sym_entry *iter;
433 iter = rb_entry(parent, struct sym_entry, rb_node);
435 if (se->weight > iter->weight)
441 rb_link_node(&se->rb_node, parent, p);
442 rb_insert_color(&se->rb_node, tree);
445 static void print_sym_table(void)
448 int counter, snap = !display_weighted ? sym_counter : 0;
449 float samples_per_sec = samples/delay_secs;
450 float ksamples_per_sec = (samples-userspace_samples)/delay_secs;
451 float sum_ksamples = 0.0;
452 struct sym_entry *syme, *n;
453 struct rb_root tmp = RB_ROOT;
455 int sym_width = 0, dso_width = 0, max_dso_width;
456 const int win_width = winsize.ws_col - 1;
458 samples = userspace_samples = 0;
460 /* Sort the active symbols */
461 pthread_mutex_lock(&active_symbols_lock);
462 syme = list_entry(active_symbols.next, struct sym_entry, node);
463 pthread_mutex_unlock(&active_symbols_lock);
465 list_for_each_entry_safe_from(syme, n, &active_symbols, node) {
466 syme->snap_count = syme->count[snap];
467 if (syme->snap_count != 0) {
469 if ((hide_user_symbols &&
470 syme->origin == PERF_RECORD_MISC_USER) ||
471 (hide_kernel_symbols &&
472 syme->origin == PERF_RECORD_MISC_KERNEL)) {
473 list_remove_active_sym(syme);
476 syme->weight = sym_weight(syme);
477 rb_insert_active_sym(&tmp, syme);
478 sum_ksamples += syme->snap_count;
480 for (j = 0; j < nr_counters; j++)
481 syme->count[j] = zero ? 0 : syme->count[j] * 7 / 8;
483 list_remove_active_sym(syme);
488 printf("%-*.*s\n", win_width, win_width, graph_dotted_line);
489 printf( " PerfTop:%8.0f irqs/sec kernel:%4.1f%% [",
491 100.0 - (100.0*((samples_per_sec-ksamples_per_sec)/samples_per_sec)));
493 if (nr_counters == 1 || !display_weighted) {
494 printf("%Ld", (u64)attrs[0].sample_period);
501 if (!display_weighted)
502 printf("%s", event_name(sym_counter));
503 else for (counter = 0; counter < nr_counters; counter++) {
507 printf("%s", event_name(counter));
512 if (target_pid != -1)
513 printf(" (target_pid: %d", target_pid);
517 if (profile_cpu != -1)
518 printf(", cpu: %d)\n", profile_cpu);
520 if (target_pid != -1)
523 printf(", %d CPUs)\n", nr_cpus);
526 printf("%-*.*s\n", win_width, win_width, graph_dotted_line);
528 if (sym_filter_entry) {
529 show_details(sym_filter_entry);
534 * Find the longest symbol name that will be displayed
536 for (nd = rb_first(&tmp); nd; nd = rb_next(nd)) {
537 syme = rb_entry(nd, struct sym_entry, rb_node);
538 if (++printed > print_entries ||
539 (int)syme->snap_count < count_filter)
542 if (syme->map->dso->long_name_len > dso_width)
543 dso_width = syme->map->dso->long_name_len;
545 if (syme->name_len > sym_width)
546 sym_width = syme->name_len;
551 max_dso_width = winsize.ws_col - sym_width - 29;
552 if (dso_width > max_dso_width)
553 dso_width = max_dso_width;
555 if (nr_counters == 1)
556 printf(" samples pcnt");
558 printf(" weight samples pcnt");
562 printf(" %-*.*s DSO\n", sym_width, sym_width, "function");
563 printf(" %s _______ _____",
564 nr_counters == 1 ? " " : "______");
566 printf(" ________________");
567 printf(" %-*.*s", sym_width, sym_width, graph_line);
568 printf(" %-*.*s", dso_width, dso_width, graph_line);
571 for (nd = rb_first(&tmp); nd; nd = rb_next(nd)) {
575 syme = rb_entry(nd, struct sym_entry, rb_node);
576 sym = sym_entry__symbol(syme);
578 if (++printed > print_entries || (int)syme->snap_count < count_filter)
581 pcnt = 100.0 - (100.0 * ((sum_ksamples - syme->snap_count) /
584 if (nr_counters == 1 || !display_weighted)
585 printf("%20.2f ", syme->weight);
587 printf("%9.1f %10ld ", syme->weight, syme->snap_count);
589 percent_color_fprintf(stdout, "%4.1f%%", pcnt);
591 printf(" %016llx", sym->start);
592 printf(" %-*.*s", sym_width, sym_width, sym->name);
593 printf(" %-*.*s\n", dso_width, dso_width,
594 dso_width >= syme->map->dso->long_name_len ?
595 syme->map->dso->long_name :
596 syme->map->dso->short_name);
600 static void prompt_integer(int *target, const char *msg)
602 char *buf = malloc(0), *p;
606 fprintf(stdout, "\n%s: ", msg);
607 if (getline(&buf, &dummy, stdin) < 0)
610 p = strchr(buf, '\n');
620 tmp = strtoul(buf, NULL, 10);
626 static void prompt_percent(int *target, const char *msg)
630 prompt_integer(&tmp, msg);
631 if (tmp >= 0 && tmp <= 100)
635 static void prompt_symbol(struct sym_entry **target, const char *msg)
637 char *buf = malloc(0), *p;
638 struct sym_entry *syme = *target, *n, *found = NULL;
641 /* zero counters of active symbol */
643 pthread_mutex_lock(&syme->src->lock);
644 __zero_source_counters(syme);
646 pthread_mutex_unlock(&syme->src->lock);
649 fprintf(stdout, "\n%s: ", msg);
650 if (getline(&buf, &dummy, stdin) < 0)
653 p = strchr(buf, '\n');
657 pthread_mutex_lock(&active_symbols_lock);
658 syme = list_entry(active_symbols.next, struct sym_entry, node);
659 pthread_mutex_unlock(&active_symbols_lock);
661 list_for_each_entry_safe_from(syme, n, &active_symbols, node) {
662 struct symbol *sym = sym_entry__symbol(syme);
664 if (!strcmp(buf, sym->name)) {
671 fprintf(stderr, "Sorry, %s is not active.\n", sym_filter);
681 static void print_mapped_keys(void)
685 if (sym_filter_entry) {
686 struct symbol *sym = sym_entry__symbol(sym_filter_entry);
690 fprintf(stdout, "\nMapped keys:\n");
691 fprintf(stdout, "\t[d] display refresh delay. \t(%d)\n", delay_secs);
692 fprintf(stdout, "\t[e] display entries (lines). \t(%d)\n", print_entries);
695 fprintf(stdout, "\t[E] active event counter. \t(%s)\n", event_name(sym_counter));
697 fprintf(stdout, "\t[f] profile display filter (count). \t(%d)\n", count_filter);
699 if (symbol_conf.vmlinux_name) {
700 fprintf(stdout, "\t[F] annotate display filter (percent). \t(%d%%)\n", sym_pcnt_filter);
701 fprintf(stdout, "\t[s] annotate symbol. \t(%s)\n", name?: "NULL");
702 fprintf(stdout, "\t[S] stop annotation.\n");
706 fprintf(stdout, "\t[w] toggle display weighted/count[E]r. \t(%d)\n", display_weighted ? 1 : 0);
709 "\t[K] hide kernel_symbols symbols. \t(%s)\n",
710 hide_kernel_symbols ? "yes" : "no");
712 "\t[U] hide user symbols. \t(%s)\n",
713 hide_user_symbols ? "yes" : "no");
714 fprintf(stdout, "\t[z] toggle sample zeroing. \t(%d)\n", zero ? 1 : 0);
715 fprintf(stdout, "\t[qQ] quit.\n");
718 static int key_mapped(int c)
732 return nr_counters > 1 ? 1 : 0;
736 return symbol_conf.vmlinux_name ? 1 : 0;
744 static void handle_keypress(int c)
746 if (!key_mapped(c)) {
747 struct pollfd stdin_poll = { .fd = 0, .events = POLLIN };
748 struct termios tc, save;
751 fprintf(stdout, "\nEnter selection, or unmapped key to continue: ");
756 tc.c_lflag &= ~(ICANON | ECHO);
759 tcsetattr(0, TCSANOW, &tc);
761 poll(&stdin_poll, 1, -1);
764 tcsetattr(0, TCSAFLUSH, &save);
771 prompt_integer(&delay_secs, "Enter display delay");
776 prompt_integer(&print_entries, "Enter display entries (lines)");
777 if (print_entries == 0) {
778 sig_winch_handler(SIGWINCH);
779 signal(SIGWINCH, sig_winch_handler);
781 signal(SIGWINCH, SIG_DFL);
784 if (nr_counters > 1) {
787 fprintf(stderr, "\nAvailable events:");
788 for (i = 0; i < nr_counters; i++)
789 fprintf(stderr, "\n\t%d %s", i, event_name(i));
791 prompt_integer(&sym_counter, "Enter details event counter");
793 if (sym_counter >= nr_counters) {
794 fprintf(stderr, "Sorry, no such event, using %s.\n", event_name(0));
798 } else sym_counter = 0;
801 prompt_integer(&count_filter, "Enter display event count filter");
804 prompt_percent(&sym_pcnt_filter, "Enter details display event filter (percent)");
807 hide_kernel_symbols = !hide_kernel_symbols;
811 printf("exiting.\n");
813 dsos__fprintf(stderr);
816 prompt_symbol(&sym_filter_entry, "Enter details symbol");
819 if (!sym_filter_entry)
822 struct sym_entry *syme = sym_filter_entry;
824 pthread_mutex_lock(&syme->src->lock);
825 sym_filter_entry = NULL;
826 __zero_source_counters(syme);
827 pthread_mutex_unlock(&syme->src->lock);
831 hide_user_symbols = !hide_user_symbols;
834 display_weighted = ~display_weighted;
844 static void *display_thread(void *arg __used)
846 struct pollfd stdin_poll = { .fd = 0, .events = POLLIN };
847 struct termios tc, save;
852 tc.c_lflag &= ~(ICANON | ECHO);
857 delay_msecs = delay_secs * 1000;
858 tcsetattr(0, TCSANOW, &tc);
864 } while (!poll(&stdin_poll, 1, delay_msecs) == 1);
867 tcsetattr(0, TCSAFLUSH, &save);
875 /* Tag samples to be skipped. */
876 static const char *skip_symbols[] = {
882 "mwait_idle_with_hints",
884 "ppc64_runlatch_off",
885 "pseries_dedicated_idle_sleep",
889 static int symbol_filter(struct map *map, struct symbol *sym)
891 struct sym_entry *syme;
892 const char *name = sym->name;
896 * ppc64 uses function descriptors and appends a '.' to the
897 * start of every instruction address. Remove it.
902 if (!strcmp(name, "_text") ||
903 !strcmp(name, "_etext") ||
904 !strcmp(name, "_sinittext") ||
905 !strncmp("init_module", name, 11) ||
906 !strncmp("cleanup_module", name, 14) ||
907 strstr(name, "_text_start") ||
908 strstr(name, "_text_end"))
911 syme = symbol__priv(sym);
914 if (!sym_filter_entry && sym_filter && !strcmp(name, sym_filter))
915 sym_filter_entry = syme;
917 for (i = 0; skip_symbols[i]; i++) {
918 if (!strcmp(skip_symbols[i], name)) {
925 syme->name_len = strlen(sym->name);
930 static void event__process_sample(const event_t *self,
931 struct perf_session *session, int counter)
933 u64 ip = self->ip.ip;
934 struct sym_entry *syme;
935 struct addr_location al;
936 u8 origin = self->header.misc & PERF_RECORD_MISC_CPUMODE_MASK;
939 case PERF_RECORD_MISC_USER:
940 if (hide_user_symbols)
943 case PERF_RECORD_MISC_KERNEL:
944 if (hide_kernel_symbols)
951 if (event__preprocess_sample(self, session, &al, symbol_filter) < 0 ||
955 syme = symbol__priv(al.sym);
957 syme->count[counter]++;
958 syme->origin = origin;
959 record_precise_ip(syme, counter, ip);
960 pthread_mutex_lock(&active_symbols_lock);
961 if (list_empty(&syme->node) || !syme->node.next)
962 __list_insert_active_sym(syme);
963 pthread_mutex_unlock(&active_symbols_lock);
964 if (origin == PERF_RECORD_MISC_USER)
970 static int event__process(event_t *event, struct perf_session *session)
972 switch (event->header.type) {
973 case PERF_RECORD_COMM:
974 event__process_comm(event, session);
976 case PERF_RECORD_MMAP:
977 event__process_mmap(event, session);
993 static unsigned int mmap_read_head(struct mmap_data *md)
995 struct perf_event_mmap_page *pc = md->base;
998 head = pc->data_head;
1004 static void perf_session__mmap_read_counter(struct perf_session *self,
1005 struct mmap_data *md)
1007 unsigned int head = mmap_read_head(md);
1008 unsigned int old = md->prev;
1009 unsigned char *data = md->base + page_size;
1013 * If we're further behind than half the buffer, there's a chance
1014 * the writer will bite our tail and mess up the samples under us.
1016 * If we somehow ended up ahead of the head, we got messed up.
1018 * In either case, truncate and restart at head.
1021 if (diff > md->mask / 2 || diff < 0) {
1022 fprintf(stderr, "WARNING: failed to keep up with mmap data.\n");
1025 * head points to a known good entry, start there.
1030 for (; old != head;) {
1031 event_t *event = (event_t *)&data[old & md->mask];
1035 size_t size = event->header.size;
1038 * Event straddles the mmap boundary -- header should always
1039 * be inside due to u64 alignment of output.
1041 if ((old & md->mask) + size != ((old + size) & md->mask)) {
1042 unsigned int offset = old;
1043 unsigned int len = min(sizeof(*event), size), cpy;
1044 void *dst = &event_copy;
1047 cpy = min(md->mask + 1 - (offset & md->mask), len);
1048 memcpy(dst, &data[offset & md->mask], cpy);
1054 event = &event_copy;
1057 if (event->header.type == PERF_RECORD_SAMPLE)
1058 event__process_sample(event, self, md->counter);
1060 event__process(event, self);
1067 static struct pollfd event_array[MAX_NR_CPUS * MAX_COUNTERS];
1068 static struct mmap_data mmap_array[MAX_NR_CPUS][MAX_COUNTERS];
1070 static void perf_session__mmap_read(struct perf_session *self)
1074 for (i = 0; i < nr_cpus; i++) {
1075 for (counter = 0; counter < nr_counters; counter++)
1076 perf_session__mmap_read_counter(self, &mmap_array[i][counter]);
1083 static void start_counter(int i, int counter)
1085 struct perf_event_attr *attr;
1089 if (target_pid == -1 && profile_cpu == -1)
1092 attr = attrs + counter;
1094 attr->sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_TID;
1097 attr->sample_type |= PERF_SAMPLE_PERIOD;
1099 attr->sample_freq = freq;
1102 attr->inherit = (cpu < 0) && inherit;
1106 fd[i][counter] = sys_perf_event_open(attr, target_pid, cpu, group_fd, 0);
1108 if (fd[i][counter] < 0) {
1111 if (err == EPERM || err == EACCES)
1112 die("No permission - are you root?\n");
1114 * If it's cycles then fall back to hrtimer
1115 * based cpu-clock-tick sw counter, which
1116 * is always available even if no PMU support:
1118 if (attr->type == PERF_TYPE_HARDWARE
1119 && attr->config == PERF_COUNT_HW_CPU_CYCLES) {
1122 warning(" ... trying to fall back to cpu-clock-ticks\n");
1124 attr->type = PERF_TYPE_SOFTWARE;
1125 attr->config = PERF_COUNT_SW_CPU_CLOCK;
1129 error("perfcounter syscall returned with %d (%s)\n",
1130 fd[i][counter], strerror(err));
1131 die("No CONFIG_PERF_EVENTS=y kernel support configured?\n");
1134 assert(fd[i][counter] >= 0);
1135 fcntl(fd[i][counter], F_SETFL, O_NONBLOCK);
1138 * First counter acts as the group leader:
1140 if (group && group_fd == -1)
1141 group_fd = fd[i][counter];
1143 event_array[nr_poll].fd = fd[i][counter];
1144 event_array[nr_poll].events = POLLIN;
1147 mmap_array[i][counter].counter = counter;
1148 mmap_array[i][counter].prev = 0;
1149 mmap_array[i][counter].mask = mmap_pages*page_size - 1;
1150 mmap_array[i][counter].base = mmap(NULL, (mmap_pages+1)*page_size,
1151 PROT_READ, MAP_SHARED, fd[i][counter], 0);
1152 if (mmap_array[i][counter].base == MAP_FAILED)
1153 die("failed to mmap with %d (%s)\n", errno, strerror(errno));
1156 static int __cmd_top(void)
1162 * FIXME: perf_session__new should allow passing a O_MMAP, so that all this
1163 * mmap reading, etc is encapsulated in it. Use O_WRONLY for now.
1165 struct perf_session *session = perf_session__new(NULL, O_WRONLY, false,
1167 if (session == NULL)
1170 if (target_pid != -1)
1171 event__synthesize_thread(target_pid, event__process, session);
1173 event__synthesize_threads(event__process, session);
1175 for (i = 0; i < nr_cpus; i++) {
1177 for (counter = 0; counter < nr_counters; counter++)
1178 start_counter(i, counter);
1181 /* Wait for a minimal set of events before starting the snapshot */
1182 poll(event_array, nr_poll, 100);
1184 perf_session__mmap_read(session);
1186 if (pthread_create(&thread, NULL, display_thread, NULL)) {
1187 printf("Could not create display thread.\n");
1191 if (realtime_prio) {
1192 struct sched_param param;
1194 param.sched_priority = realtime_prio;
1195 if (sched_setscheduler(0, SCHED_FIFO, ¶m)) {
1196 printf("Could not set realtime priority.\n");
1204 perf_session__mmap_read(session);
1206 if (hits == samples)
1207 ret = poll(event_array, nr_poll, 100);
1213 static const char * const top_usage[] = {
1214 "perf top [<options>]",
1218 static const struct option options[] = {
1219 OPT_CALLBACK('e', "event", NULL, "event",
1220 "event selector. use 'perf list' to list available events",
1222 OPT_INTEGER('c', "count", &default_interval,
1223 "event period to sample"),
1224 OPT_INTEGER('p', "pid", &target_pid,
1225 "profile events on existing pid"),
1226 OPT_BOOLEAN('a', "all-cpus", &system_wide,
1227 "system-wide collection from all CPUs"),
1228 OPT_INTEGER('C', "CPU", &profile_cpu,
1229 "CPU to profile on"),
1230 OPT_STRING('k', "vmlinux", &symbol_conf.vmlinux_name,
1231 "file", "vmlinux pathname"),
1232 OPT_BOOLEAN('K', "hide_kernel_symbols", &hide_kernel_symbols,
1233 "hide kernel symbols"),
1234 OPT_INTEGER('m', "mmap-pages", &mmap_pages,
1235 "number of mmap data pages"),
1236 OPT_INTEGER('r', "realtime", &realtime_prio,
1237 "collect data with this RT SCHED_FIFO priority"),
1238 OPT_INTEGER('d', "delay", &delay_secs,
1239 "number of seconds to delay between refreshes"),
1240 OPT_BOOLEAN('D', "dump-symtab", &dump_symtab,
1241 "dump the symbol table used for profiling"),
1242 OPT_INTEGER('f', "count-filter", &count_filter,
1243 "only display functions with more events than this"),
1244 OPT_BOOLEAN('g', "group", &group,
1245 "put the counters into a counter group"),
1246 OPT_BOOLEAN('i', "inherit", &inherit,
1247 "child tasks inherit counters"),
1248 OPT_STRING('s', "sym-annotate", &sym_filter, "symbol name",
1249 "symbol to annotate - requires -k option"),
1250 OPT_BOOLEAN('z', "zero", &zero,
1251 "zero history across updates"),
1252 OPT_INTEGER('F', "freq", &freq,
1253 "profile at this frequency"),
1254 OPT_INTEGER('E', "entries", &print_entries,
1255 "display this many functions"),
1256 OPT_BOOLEAN('U', "hide_user_symbols", &hide_user_symbols,
1257 "hide user symbols"),
1258 OPT_BOOLEAN('v', "verbose", &verbose,
1259 "be more verbose (show counter open errors, etc)"),
1263 int cmd_top(int argc, const char **argv, const char *prefix __used)
1267 page_size = sysconf(_SC_PAGE_SIZE);
1269 argc = parse_options(argc, argv, options, top_usage, 0);
1271 usage_with_options(top_usage, options);
1273 /* CPU and PID are mutually exclusive */
1274 if (target_pid != -1 && profile_cpu != -1) {
1275 printf("WARNING: PID switch overriding CPU\n");
1283 symbol_conf.priv_size = (sizeof(struct sym_entry) +
1284 (nr_counters + 1) * sizeof(unsigned long));
1285 if (symbol_conf.vmlinux_name == NULL)
1286 symbol_conf.try_vmlinux_path = true;
1287 if (symbol__init(&symbol_conf) < 0)
1293 parse_source(sym_filter_entry);
1296 * User specified count overrides default frequency.
1298 if (default_interval)
1301 default_interval = freq;
1303 fprintf(stderr, "frequency and count are zero, aborting\n");
1308 * Fill in the ones not specifically initialized via -c:
1310 for (counter = 0; counter < nr_counters; counter++) {
1311 if (attrs[counter].sample_period)
1314 attrs[counter].sample_period = default_interval;
1317 nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
1318 assert(nr_cpus <= MAX_NR_CPUS);
1319 assert(nr_cpus >= 0);
1321 if (target_pid != -1 || profile_cpu != -1)
1324 get_term_dimensions(&winsize);
1325 if (print_entries == 0) {
1326 update_print_entries(&winsize);
1327 signal(SIGWINCH, sig_winch_handler);