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/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"
31 #include "util/debug.h"
45 #include <sys/syscall.h>
46 #include <sys/ioctl.h>
48 #include <sys/prctl.h>
53 #include <linux/unistd.h>
54 #include <linux/types.h>
56 static int fd[MAX_NR_CPUS][MAX_COUNTERS];
58 static int system_wide = 0;
60 static int default_interval = 0;
62 static int count_filter = 5;
63 static int print_entries;
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;
71 static unsigned int page_size;
72 static unsigned int mmap_pages = 16;
73 static int freq = 1000; /* 1 KHz */
75 static int delay_secs = 2;
77 static int dump_symtab = 0;
79 static bool hide_kernel_symbols = false;
80 static bool hide_user_symbols = false;
81 static struct winsize winsize;
82 static const char *graph_line =
83 "_____________________________________________________________________"
84 "_____________________________________________________________________";
85 static const char *graph_dotted_line =
86 "---------------------------------------------------------------------"
87 "---------------------------------------------------------------------"
88 "---------------------------------------------------------------------";
96 unsigned long count[MAX_COUNTERS];
98 struct source_line *next;
101 static char *sym_filter = NULL;
102 struct sym_entry *sym_filter_entry = NULL;
103 static int sym_pcnt_filter = 5;
104 static int sym_counter = 0;
105 static int display_weighted = -1;
111 struct sym_entry_source {
112 struct source_line *source;
113 struct source_line *lines;
114 struct source_line **lines_tail;
115 pthread_mutex_t lock;
119 struct rb_node rb_node;
120 struct list_head node;
121 unsigned long snap_count;
127 struct sym_entry_source *src;
128 unsigned long count[0];
135 static inline struct symbol *sym_entry__symbol(struct sym_entry *self)
137 return ((void *)self) + symbol__priv_size;
140 static void get_term_dimensions(struct winsize *ws)
142 char *s = getenv("LINES");
145 ws->ws_row = atoi(s);
146 s = getenv("COLUMNS");
148 ws->ws_col = atoi(s);
149 if (ws->ws_row && ws->ws_col)
154 if (ioctl(1, TIOCGWINSZ, ws) == 0 &&
155 ws->ws_row && ws->ws_col)
162 static void update_print_entries(struct winsize *ws)
164 print_entries = ws->ws_row;
166 if (print_entries > 9)
170 static void sig_winch_handler(int sig __used)
172 get_term_dimensions(&winsize);
173 update_print_entries(&winsize);
176 static void parse_source(struct sym_entry *syme)
179 struct sym_entry_source *source;
182 char command[PATH_MAX*2];
189 if (syme->src == NULL) {
190 syme->src = calloc(1, sizeof(*source));
191 if (syme->src == NULL)
193 pthread_mutex_init(&syme->src->lock, NULL);
199 pthread_mutex_lock(&source->lock);
203 sym = sym_entry__symbol(syme);
205 path = map->dso->long_name;
207 len = sym->end - sym->start;
210 "objdump --start-address=0x%016Lx "
211 "--stop-address=0x%016Lx -dS %s",
212 map->unmap_ip(map, sym->start),
213 map->unmap_ip(map, sym->end), path);
215 file = popen(command, "r");
219 pthread_mutex_lock(&source->lock);
220 source->lines_tail = &source->lines;
221 while (!feof(file)) {
222 struct source_line *src;
226 src = malloc(sizeof(struct source_line));
228 memset(src, 0, sizeof(struct source_line));
230 if (getline(&src->line, &dummy, file) < 0)
235 c = strchr(src->line, '\n');
240 *source->lines_tail = src;
241 source->lines_tail = &src->next;
243 if (strlen(src->line)>8 && src->line[8] == ':') {
244 src->eip = strtoull(src->line, NULL, 16);
245 src->eip = map->unmap_ip(map, src->eip);
247 if (strlen(src->line)>8 && src->line[16] == ':') {
248 src->eip = strtoull(src->line, NULL, 16);
249 src->eip = map->unmap_ip(map, src->eip);
254 sym_filter_entry = syme;
255 pthread_mutex_unlock(&source->lock);
258 static void __zero_source_counters(struct sym_entry *syme)
261 struct source_line *line;
263 line = syme->src->lines;
265 for (i = 0; i < nr_counters; i++)
271 static void record_precise_ip(struct sym_entry *syme, int counter, u64 ip)
273 struct source_line *line;
275 if (syme != sym_filter_entry)
278 if (pthread_mutex_trylock(&syme->src->lock))
281 if (syme->src == NULL || syme->src->source == NULL)
284 for (line = syme->src->lines; line; line = line->next) {
285 if (line->eip == ip) {
286 line->count[counter]++;
293 pthread_mutex_unlock(&syme->src->lock);
296 static void lookup_sym_source(struct sym_entry *syme)
298 struct symbol *symbol = sym_entry__symbol(syme);
299 struct source_line *line;
300 char pattern[PATH_MAX];
302 sprintf(pattern, "<%s>:", symbol->name);
304 pthread_mutex_lock(&syme->src->lock);
305 for (line = syme->src->lines; line; line = line->next) {
306 if (strstr(line->line, pattern)) {
307 syme->src->source = line;
311 pthread_mutex_unlock(&syme->src->lock);
314 static void show_lines(struct source_line *queue, int count, int total)
317 struct source_line *line;
320 for (i = 0; i < count; i++) {
321 float pcnt = 100.0*(float)line->count[sym_counter]/(float)total;
323 printf("%8li %4.1f%%\t%s\n", line->count[sym_counter], pcnt, line->line);
328 #define TRACE_COUNT 3
330 static void show_details(struct sym_entry *syme)
332 struct symbol *symbol;
333 struct source_line *line;
334 struct source_line *line_queue = NULL;
336 int line_queue_count = 0, total = 0, more = 0;
341 if (!syme->src->source)
342 lookup_sym_source(syme);
344 if (!syme->src->source)
347 symbol = sym_entry__symbol(syme);
348 printf("Showing %s for %s\n", event_name(sym_counter), symbol->name);
349 printf(" Events Pcnt (>=%d%%)\n", sym_pcnt_filter);
351 pthread_mutex_lock(&syme->src->lock);
352 line = syme->src->source;
354 total += line->count[sym_counter];
358 line = syme->src->source;
362 if (!line_queue_count)
366 if (line->count[sym_counter])
367 pcnt = 100.0 * line->count[sym_counter] / (float)total;
368 if (pcnt >= (float)sym_pcnt_filter) {
369 if (displayed <= print_entries)
370 show_lines(line_queue, line_queue_count, total);
372 displayed += line_queue_count;
373 line_queue_count = 0;
375 } else if (line_queue_count > TRACE_COUNT) {
376 line_queue = line_queue->next;
380 line->count[sym_counter] = zero ? 0 : line->count[sym_counter] * 7 / 8;
383 pthread_mutex_unlock(&syme->src->lock);
385 printf("%d lines not displayed, maybe increase display entries [e]\n", more);
389 * Symbols will be added here in event__process_sample and will get out
392 static LIST_HEAD(active_symbols);
393 static pthread_mutex_t active_symbols_lock = PTHREAD_MUTEX_INITIALIZER;
396 * Ordering weight: count-1 * count-2 * ... / count-n
398 static double sym_weight(const struct sym_entry *sym)
400 double weight = sym->snap_count;
403 if (!display_weighted)
406 for (counter = 1; counter < nr_counters-1; counter++)
407 weight *= sym->count[counter];
409 weight /= (sym->count[counter] + 1);
415 static long userspace_samples;
416 static const char CONSOLE_CLEAR[] = "
\e[H
\e[2J";
418 static void __list_insert_active_sym(struct sym_entry *syme)
420 list_add(&syme->node, &active_symbols);
423 static void list_remove_active_sym(struct sym_entry *syme)
425 pthread_mutex_lock(&active_symbols_lock);
426 list_del_init(&syme->node);
427 pthread_mutex_unlock(&active_symbols_lock);
430 static void rb_insert_active_sym(struct rb_root *tree, struct sym_entry *se)
432 struct rb_node **p = &tree->rb_node;
433 struct rb_node *parent = NULL;
434 struct sym_entry *iter;
438 iter = rb_entry(parent, struct sym_entry, rb_node);
440 if (se->weight > iter->weight)
446 rb_link_node(&se->rb_node, parent, p);
447 rb_insert_color(&se->rb_node, tree);
450 static void print_sym_table(void)
453 int counter, snap = !display_weighted ? sym_counter : 0;
454 float samples_per_sec = samples/delay_secs;
455 float ksamples_per_sec = (samples-userspace_samples)/delay_secs;
456 float sum_ksamples = 0.0;
457 struct sym_entry *syme, *n;
458 struct rb_root tmp = RB_ROOT;
460 int sym_width = 0, dso_width = 0;
461 const int win_width = winsize.ws_col - 1;
462 struct dso *unique_dso = NULL, *first_dso = NULL;
464 samples = userspace_samples = 0;
466 /* Sort the active symbols */
467 pthread_mutex_lock(&active_symbols_lock);
468 syme = list_entry(active_symbols.next, struct sym_entry, node);
469 pthread_mutex_unlock(&active_symbols_lock);
471 list_for_each_entry_safe_from(syme, n, &active_symbols, node) {
472 syme->snap_count = syme->count[snap];
473 if (syme->snap_count != 0) {
475 if ((hide_user_symbols &&
476 syme->origin == PERF_RECORD_MISC_USER) ||
477 (hide_kernel_symbols &&
478 syme->origin == PERF_RECORD_MISC_KERNEL)) {
479 list_remove_active_sym(syme);
482 syme->weight = sym_weight(syme);
483 rb_insert_active_sym(&tmp, syme);
484 sum_ksamples += syme->snap_count;
486 for (j = 0; j < nr_counters; j++)
487 syme->count[j] = zero ? 0 : syme->count[j] * 7 / 8;
489 list_remove_active_sym(syme);
494 printf("%-*.*s\n", win_width, win_width, graph_dotted_line);
495 printf( " PerfTop:%8.0f irqs/sec kernel:%4.1f%% [",
497 100.0 - (100.0*((samples_per_sec-ksamples_per_sec)/samples_per_sec)));
499 if (nr_counters == 1 || !display_weighted) {
500 printf("%Ld", (u64)attrs[0].sample_period);
507 if (!display_weighted)
508 printf("%s", event_name(sym_counter));
509 else for (counter = 0; counter < nr_counters; counter++) {
513 printf("%s", event_name(counter));
518 if (target_pid != -1)
519 printf(" (target_pid: %d", target_pid);
523 if (profile_cpu != -1)
524 printf(", cpu: %d)\n", profile_cpu);
526 if (target_pid != -1)
529 printf(", %d CPUs)\n", nr_cpus);
532 printf("%-*.*s\n", win_width, win_width, graph_dotted_line);
534 if (sym_filter_entry) {
535 show_details(sym_filter_entry);
540 * Find the longest symbol name that will be displayed
542 for (nd = rb_first(&tmp); nd; nd = rb_next(nd)) {
543 syme = rb_entry(nd, struct sym_entry, rb_node);
544 if (++printed > print_entries ||
545 (int)syme->snap_count < count_filter)
548 if (first_dso == NULL)
549 unique_dso = first_dso = syme->map->dso;
550 else if (syme->map->dso != first_dso)
553 if (syme->map->dso->long_name_len > dso_width)
554 dso_width = syme->map->dso->long_name_len;
556 if (syme->name_len > sym_width)
557 sym_width = syme->name_len;
563 printf("DSO: %s\n", unique_dso->long_name);
565 int max_dso_width = winsize.ws_col - sym_width - 29;
566 if (dso_width > max_dso_width)
567 dso_width = max_dso_width;
570 if (nr_counters == 1)
571 printf(" samples pcnt");
573 printf(" weight samples pcnt");
577 printf(" %-*.*s", sym_width, sym_width, "function");
581 printf(" %s _______ _____",
582 nr_counters == 1 ? " " : "______");
584 printf(" ________________");
585 printf(" %-*.*s", sym_width, sym_width, graph_line);
587 printf(" %-*.*s", dso_width, dso_width, graph_line);
590 for (nd = rb_first(&tmp); nd; nd = rb_next(nd)) {
594 syme = rb_entry(nd, struct sym_entry, rb_node);
595 sym = sym_entry__symbol(syme);
597 if (++printed > print_entries || (int)syme->snap_count < count_filter)
600 pcnt = 100.0 - (100.0 * ((sum_ksamples - syme->snap_count) /
603 if (nr_counters == 1 || !display_weighted)
604 printf("%20.2f ", syme->weight);
606 printf("%9.1f %10ld ", syme->weight, syme->snap_count);
608 percent_color_fprintf(stdout, "%4.1f%%", pcnt);
610 printf(" %016llx", sym->start);
611 printf(" %-*.*s", sym_width, sym_width, sym->name);
613 printf(" %-*.*s", dso_width, dso_width,
614 dso_width >= syme->map->dso->long_name_len ?
615 syme->map->dso->long_name :
616 syme->map->dso->short_name);
621 static void prompt_integer(int *target, const char *msg)
623 char *buf = malloc(0), *p;
627 fprintf(stdout, "\n%s: ", msg);
628 if (getline(&buf, &dummy, stdin) < 0)
631 p = strchr(buf, '\n');
641 tmp = strtoul(buf, NULL, 10);
647 static void prompt_percent(int *target, const char *msg)
651 prompt_integer(&tmp, msg);
652 if (tmp >= 0 && tmp <= 100)
656 static void prompt_symbol(struct sym_entry **target, const char *msg)
658 char *buf = malloc(0), *p;
659 struct sym_entry *syme = *target, *n, *found = NULL;
662 /* zero counters of active symbol */
664 pthread_mutex_lock(&syme->src->lock);
665 __zero_source_counters(syme);
667 pthread_mutex_unlock(&syme->src->lock);
670 fprintf(stdout, "\n%s: ", msg);
671 if (getline(&buf, &dummy, stdin) < 0)
674 p = strchr(buf, '\n');
678 pthread_mutex_lock(&active_symbols_lock);
679 syme = list_entry(active_symbols.next, struct sym_entry, node);
680 pthread_mutex_unlock(&active_symbols_lock);
682 list_for_each_entry_safe_from(syme, n, &active_symbols, node) {
683 struct symbol *sym = sym_entry__symbol(syme);
685 if (!strcmp(buf, sym->name)) {
692 fprintf(stderr, "Sorry, %s is not active.\n", sym_filter);
702 static void print_mapped_keys(void)
706 if (sym_filter_entry) {
707 struct symbol *sym = sym_entry__symbol(sym_filter_entry);
711 fprintf(stdout, "\nMapped keys:\n");
712 fprintf(stdout, "\t[d] display refresh delay. \t(%d)\n", delay_secs);
713 fprintf(stdout, "\t[e] display entries (lines). \t(%d)\n", print_entries);
716 fprintf(stdout, "\t[E] active event counter. \t(%s)\n", event_name(sym_counter));
718 fprintf(stdout, "\t[f] profile display filter (count). \t(%d)\n", count_filter);
721 fprintf(stdout, "\t[F] annotate display filter (percent). \t(%d%%)\n", sym_pcnt_filter);
722 fprintf(stdout, "\t[s] annotate symbol. \t(%s)\n", name?: "NULL");
723 fprintf(stdout, "\t[S] stop annotation.\n");
727 fprintf(stdout, "\t[w] toggle display weighted/count[E]r. \t(%d)\n", display_weighted ? 1 : 0);
730 "\t[K] hide kernel_symbols symbols. \t(%s)\n",
731 hide_kernel_symbols ? "yes" : "no");
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)
753 return nr_counters > 1 ? 1 : 0;
757 return vmlinux_name ? 1 : 0;
765 static void handle_keypress(int c)
767 if (!key_mapped(c)) {
768 struct pollfd stdin_poll = { .fd = 0, .events = POLLIN };
769 struct termios tc, save;
772 fprintf(stdout, "\nEnter selection, or unmapped key to continue: ");
777 tc.c_lflag &= ~(ICANON | ECHO);
780 tcsetattr(0, TCSANOW, &tc);
782 poll(&stdin_poll, 1, -1);
785 tcsetattr(0, TCSAFLUSH, &save);
792 prompt_integer(&delay_secs, "Enter display delay");
797 prompt_integer(&print_entries, "Enter display entries (lines)");
798 if (print_entries == 0) {
799 sig_winch_handler(SIGWINCH);
800 signal(SIGWINCH, sig_winch_handler);
802 signal(SIGWINCH, SIG_DFL);
805 if (nr_counters > 1) {
808 fprintf(stderr, "\nAvailable events:");
809 for (i = 0; i < nr_counters; i++)
810 fprintf(stderr, "\n\t%d %s", i, event_name(i));
812 prompt_integer(&sym_counter, "Enter details event counter");
814 if (sym_counter >= nr_counters) {
815 fprintf(stderr, "Sorry, no such event, using %s.\n", event_name(0));
819 } else sym_counter = 0;
822 prompt_integer(&count_filter, "Enter display event count filter");
825 prompt_percent(&sym_pcnt_filter, "Enter details display event filter (percent)");
828 hide_kernel_symbols = !hide_kernel_symbols;
832 printf("exiting.\n");
834 dsos__fprintf(stderr);
837 prompt_symbol(&sym_filter_entry, "Enter details symbol");
840 if (!sym_filter_entry)
843 struct sym_entry *syme = sym_filter_entry;
845 pthread_mutex_lock(&syme->src->lock);
846 sym_filter_entry = NULL;
847 __zero_source_counters(syme);
848 pthread_mutex_unlock(&syme->src->lock);
852 hide_user_symbols = !hide_user_symbols;
855 display_weighted = ~display_weighted;
865 static void *display_thread(void *arg __used)
867 struct pollfd stdin_poll = { .fd = 0, .events = POLLIN };
868 struct termios tc, save;
873 tc.c_lflag &= ~(ICANON | ECHO);
878 delay_msecs = delay_secs * 1000;
879 tcsetattr(0, TCSANOW, &tc);
885 } while (!poll(&stdin_poll, 1, delay_msecs) == 1);
888 tcsetattr(0, TCSAFLUSH, &save);
896 /* Tag samples to be skipped. */
897 static const char *skip_symbols[] = {
903 "mwait_idle_with_hints",
905 "ppc64_runlatch_off",
906 "pseries_dedicated_idle_sleep",
910 static int symbol_filter(struct map *map, struct symbol *sym)
912 struct sym_entry *syme;
913 const char *name = sym->name;
917 * ppc64 uses function descriptors and appends a '.' to the
918 * start of every instruction address. Remove it.
923 if (!strcmp(name, "_text") ||
924 !strcmp(name, "_etext") ||
925 !strcmp(name, "_sinittext") ||
926 !strncmp("init_module", name, 11) ||
927 !strncmp("cleanup_module", name, 14) ||
928 strstr(name, "_text_start") ||
929 strstr(name, "_text_end"))
932 syme = symbol__priv(sym);
935 if (!sym_filter_entry && sym_filter && !strcmp(name, sym_filter))
936 sym_filter_entry = syme;
938 for (i = 0; skip_symbols[i]; i++) {
939 if (!strcmp(skip_symbols[i], name)) {
946 syme->name_len = strlen(sym->name);
951 static void event__process_sample(const event_t *self, int counter)
953 u64 ip = self->ip.ip;
955 struct sym_entry *syme;
957 u8 origin = self->header.misc & PERF_RECORD_MISC_CPUMODE_MASK;
960 case PERF_RECORD_MISC_USER: {
961 struct thread *thread;
963 if (hide_user_symbols)
966 thread = threads__findnew(self->ip.pid);
970 map = thread__find_map(thread, ip);
972 ip = map->map_ip(map, ip);
973 sym = map__find_symbol(map, ip, symbol_filter);
981 * If this is outside of all known maps,
982 * and is a negative address, try to look it
983 * up in the kernel dso, as it might be a
984 * vsyscall or vdso (which executes in user-mode).
986 if ((long long)ip >= 0)
989 case PERF_RECORD_MISC_KERNEL:
990 if (hide_kernel_symbols)
993 sym = kernel_maps__find_symbol(ip, &map, symbol_filter);
1001 syme = symbol__priv(sym);
1004 syme->count[counter]++;
1005 syme->origin = origin;
1006 record_precise_ip(syme, counter, ip);
1007 pthread_mutex_lock(&active_symbols_lock);
1008 if (list_empty(&syme->node) || !syme->node.next)
1009 __list_insert_active_sym(syme);
1010 pthread_mutex_unlock(&active_symbols_lock);
1016 static void event__process_mmap(event_t *self)
1018 struct thread *thread = threads__findnew(self->mmap.pid);
1020 if (thread != NULL) {
1021 struct map *map = map__new(&self->mmap, NULL, 0);
1023 thread__insert_map(thread, map);
1027 static void event__process_comm(event_t *self)
1029 struct thread *thread = threads__findnew(self->comm.pid);
1032 thread__set_comm(thread, self->comm.comm);
1035 static int event__process(event_t *event)
1037 switch (event->header.type) {
1038 case PERF_RECORD_COMM:
1039 event__process_comm(event);
1041 case PERF_RECORD_MMAP:
1042 event__process_mmap(event);
1058 static unsigned int mmap_read_head(struct mmap_data *md)
1060 struct perf_event_mmap_page *pc = md->base;
1063 head = pc->data_head;
1069 static void mmap_read_counter(struct mmap_data *md)
1071 unsigned int head = mmap_read_head(md);
1072 unsigned int old = md->prev;
1073 unsigned char *data = md->base + page_size;
1077 * If we're further behind than half the buffer, there's a chance
1078 * the writer will bite our tail and mess up the samples under us.
1080 * If we somehow ended up ahead of the head, we got messed up.
1082 * In either case, truncate and restart at head.
1085 if (diff > md->mask / 2 || diff < 0) {
1086 fprintf(stderr, "WARNING: failed to keep up with mmap data.\n");
1089 * head points to a known good entry, start there.
1094 for (; old != head;) {
1095 event_t *event = (event_t *)&data[old & md->mask];
1099 size_t size = event->header.size;
1102 * Event straddles the mmap boundary -- header should always
1103 * be inside due to u64 alignment of output.
1105 if ((old & md->mask) + size != ((old + size) & md->mask)) {
1106 unsigned int offset = old;
1107 unsigned int len = min(sizeof(*event), size), cpy;
1108 void *dst = &event_copy;
1111 cpy = min(md->mask + 1 - (offset & md->mask), len);
1112 memcpy(dst, &data[offset & md->mask], cpy);
1118 event = &event_copy;
1121 if (event->header.type == PERF_RECORD_SAMPLE)
1122 event__process_sample(event, md->counter);
1124 event__process(event);
1131 static struct pollfd event_array[MAX_NR_CPUS * MAX_COUNTERS];
1132 static struct mmap_data mmap_array[MAX_NR_CPUS][MAX_COUNTERS];
1134 static void mmap_read(void)
1138 for (i = 0; i < nr_cpus; i++) {
1139 for (counter = 0; counter < nr_counters; counter++)
1140 mmap_read_counter(&mmap_array[i][counter]);
1147 static void start_counter(int i, int counter)
1149 struct perf_event_attr *attr;
1153 if (target_pid == -1 && profile_cpu == -1)
1156 attr = attrs + counter;
1158 attr->sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_TID;
1161 attr->sample_type |= PERF_SAMPLE_PERIOD;
1163 attr->sample_freq = freq;
1166 attr->inherit = (cpu < 0) && inherit;
1170 fd[i][counter] = sys_perf_event_open(attr, target_pid, cpu, group_fd, 0);
1172 if (fd[i][counter] < 0) {
1175 if (err == EPERM || err == EACCES)
1176 die("No permission - are you root?\n");
1178 * If it's cycles then fall back to hrtimer
1179 * based cpu-clock-tick sw counter, which
1180 * is always available even if no PMU support:
1182 if (attr->type == PERF_TYPE_HARDWARE
1183 && attr->config == PERF_COUNT_HW_CPU_CYCLES) {
1186 warning(" ... trying to fall back to cpu-clock-ticks\n");
1188 attr->type = PERF_TYPE_SOFTWARE;
1189 attr->config = PERF_COUNT_SW_CPU_CLOCK;
1193 error("perfcounter syscall returned with %d (%s)\n",
1194 fd[i][counter], strerror(err));
1195 die("No CONFIG_PERF_EVENTS=y kernel support configured?\n");
1198 assert(fd[i][counter] >= 0);
1199 fcntl(fd[i][counter], F_SETFL, O_NONBLOCK);
1202 * First counter acts as the group leader:
1204 if (group && group_fd == -1)
1205 group_fd = fd[i][counter];
1207 event_array[nr_poll].fd = fd[i][counter];
1208 event_array[nr_poll].events = POLLIN;
1211 mmap_array[i][counter].counter = counter;
1212 mmap_array[i][counter].prev = 0;
1213 mmap_array[i][counter].mask = mmap_pages*page_size - 1;
1214 mmap_array[i][counter].base = mmap(NULL, (mmap_pages+1)*page_size,
1215 PROT_READ, MAP_SHARED, fd[i][counter], 0);
1216 if (mmap_array[i][counter].base == MAP_FAILED)
1217 die("failed to mmap with %d (%s)\n", errno, strerror(errno));
1220 static int __cmd_top(void)
1226 if (target_pid != -1)
1227 event__synthesize_thread(target_pid, event__process);
1229 event__synthesize_threads(event__process);
1231 for (i = 0; i < nr_cpus; i++) {
1233 for (counter = 0; counter < nr_counters; counter++)
1234 start_counter(i, counter);
1237 /* Wait for a minimal set of events before starting the snapshot */
1238 poll(event_array, nr_poll, 100);
1242 if (pthread_create(&thread, NULL, display_thread, NULL)) {
1243 printf("Could not create display thread.\n");
1247 if (realtime_prio) {
1248 struct sched_param param;
1250 param.sched_priority = realtime_prio;
1251 if (sched_setscheduler(0, SCHED_FIFO, ¶m)) {
1252 printf("Could not set realtime priority.\n");
1262 if (hits == samples)
1263 ret = poll(event_array, nr_poll, 100);
1269 static const char * const top_usage[] = {
1270 "perf top [<options>]",
1274 static const struct option options[] = {
1275 OPT_CALLBACK('e', "event", NULL, "event",
1276 "event selector. use 'perf list' to list available events",
1278 OPT_INTEGER('c', "count", &default_interval,
1279 "event period to sample"),
1280 OPT_INTEGER('p', "pid", &target_pid,
1281 "profile events on existing pid"),
1282 OPT_BOOLEAN('a', "all-cpus", &system_wide,
1283 "system-wide collection from all CPUs"),
1284 OPT_INTEGER('C', "CPU", &profile_cpu,
1285 "CPU to profile on"),
1286 OPT_STRING('k', "vmlinux", &vmlinux_name, "file", "vmlinux pathname"),
1287 OPT_BOOLEAN('K', "hide_kernel_symbols", &hide_kernel_symbols,
1288 "hide kernel symbols"),
1289 OPT_INTEGER('m', "mmap-pages", &mmap_pages,
1290 "number of mmap data pages"),
1291 OPT_INTEGER('r', "realtime", &realtime_prio,
1292 "collect data with this RT SCHED_FIFO priority"),
1293 OPT_INTEGER('d', "delay", &delay_secs,
1294 "number of seconds to delay between refreshes"),
1295 OPT_BOOLEAN('D', "dump-symtab", &dump_symtab,
1296 "dump the symbol table used for profiling"),
1297 OPT_INTEGER('f', "count-filter", &count_filter,
1298 "only display functions with more events than this"),
1299 OPT_BOOLEAN('g', "group", &group,
1300 "put the counters into a counter group"),
1301 OPT_BOOLEAN('i', "inherit", &inherit,
1302 "child tasks inherit counters"),
1303 OPT_STRING('s', "sym-annotate", &sym_filter, "symbol name",
1304 "symbol to annotate - requires -k option"),
1305 OPT_BOOLEAN('z', "zero", &zero,
1306 "zero history across updates"),
1307 OPT_INTEGER('F', "freq", &freq,
1308 "profile at this frequency"),
1309 OPT_INTEGER('E', "entries", &print_entries,
1310 "display this many functions"),
1311 OPT_BOOLEAN('U', "hide_user_symbols", &hide_user_symbols,
1312 "hide user symbols"),
1313 OPT_BOOLEAN('v', "verbose", &verbose,
1314 "be more verbose (show counter open errors, etc)"),
1318 int cmd_top(int argc, const char **argv, const char *prefix __used)
1322 page_size = sysconf(_SC_PAGE_SIZE);
1324 argc = parse_options(argc, argv, options, top_usage, 0);
1326 usage_with_options(top_usage, options);
1328 /* CPU and PID are mutually exclusive */
1329 if (target_pid != -1 && profile_cpu != -1) {
1330 printf("WARNING: PID switch overriding CPU\n");
1338 symbol__init(sizeof(struct sym_entry) +
1339 (nr_counters + 1) * sizeof(unsigned long));
1344 err = kernel_maps__init(true);
1347 parse_source(sym_filter_entry);
1350 * User specified count overrides default frequency.
1352 if (default_interval)
1355 default_interval = freq;
1357 fprintf(stderr, "frequency and count are zero, aborting\n");
1362 * Fill in the ones not specifically initialized via -c:
1364 for (counter = 0; counter < nr_counters; counter++) {
1365 if (attrs[counter].sample_period)
1368 attrs[counter].sample_period = default_interval;
1371 nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
1372 assert(nr_cpus <= MAX_NR_CPUS);
1373 assert(nr_cpus >= 0);
1375 if (target_pid != -1 || profile_cpu != -1)
1378 get_term_dimensions(&winsize);
1379 if (print_entries == 0) {
1380 update_print_entries(&winsize);
1381 signal(SIGWINCH, sig_winch_handler);