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 const char *vmlinux_name;
90 unsigned long count[MAX_COUNTERS];
92 struct source_line *next;
95 static char *sym_filter = NULL;
96 struct sym_entry *sym_filter_entry = NULL;
97 static int sym_pcnt_filter = 5;
98 static int sym_counter = 0;
99 static int display_weighted = -1;
105 struct sym_entry_source {
106 struct source_line *source;
107 struct source_line *lines;
108 struct source_line **lines_tail;
109 pthread_mutex_t lock;
113 struct rb_node rb_node;
114 struct list_head node;
115 unsigned long snap_count;
121 struct sym_entry_source *src;
122 unsigned long count[0];
129 static inline struct symbol *sym_entry__symbol(struct sym_entry *self)
131 return ((void *)self) + symbol__priv_size;
134 static void get_term_dimensions(struct winsize *ws)
136 char *s = getenv("LINES");
139 ws->ws_row = atoi(s);
140 s = getenv("COLUMNS");
142 ws->ws_col = atoi(s);
143 if (ws->ws_row && ws->ws_col)
148 if (ioctl(1, TIOCGWINSZ, ws) == 0 &&
149 ws->ws_row && ws->ws_col)
156 static void update_print_entries(struct winsize *ws)
158 print_entries = ws->ws_row;
160 if (print_entries > 9)
164 static void sig_winch_handler(int sig __used)
166 get_term_dimensions(&winsize);
167 update_print_entries(&winsize);
170 static void parse_source(struct sym_entry *syme)
173 struct sym_entry_source *source;
176 char command[PATH_MAX*2];
183 if (syme->src == NULL) {
184 syme->src = calloc(1, sizeof(*source));
185 if (syme->src == NULL)
187 pthread_mutex_init(&syme->src->lock, NULL);
193 pthread_mutex_lock(&source->lock);
197 sym = sym_entry__symbol(syme);
199 path = map->dso->long_name;
201 len = sym->end - sym->start;
204 "objdump --start-address=0x%016Lx "
205 "--stop-address=0x%016Lx -dS %s",
206 map->unmap_ip(map, sym->start),
207 map->unmap_ip(map, sym->end), path);
209 file = popen(command, "r");
213 pthread_mutex_lock(&source->lock);
214 source->lines_tail = &source->lines;
215 while (!feof(file)) {
216 struct source_line *src;
220 src = malloc(sizeof(struct source_line));
222 memset(src, 0, sizeof(struct source_line));
224 if (getline(&src->line, &dummy, file) < 0)
229 c = strchr(src->line, '\n');
234 *source->lines_tail = src;
235 source->lines_tail = &src->next;
237 if (strlen(src->line)>8 && src->line[8] == ':') {
238 src->eip = strtoull(src->line, NULL, 16);
239 src->eip = map->unmap_ip(map, src->eip);
241 if (strlen(src->line)>8 && src->line[16] == ':') {
242 src->eip = strtoull(src->line, NULL, 16);
243 src->eip = map->unmap_ip(map, src->eip);
248 sym_filter_entry = syme;
249 pthread_mutex_unlock(&source->lock);
252 static void __zero_source_counters(struct sym_entry *syme)
255 struct source_line *line;
257 line = syme->src->lines;
259 for (i = 0; i < nr_counters; i++)
265 static void record_precise_ip(struct sym_entry *syme, int counter, u64 ip)
267 struct source_line *line;
269 if (syme != sym_filter_entry)
272 if (pthread_mutex_trylock(&syme->src->lock))
275 if (syme->src == NULL || syme->src->source == NULL)
278 for (line = syme->src->lines; line; line = line->next) {
279 if (line->eip == ip) {
280 line->count[counter]++;
287 pthread_mutex_unlock(&syme->src->lock);
290 static void lookup_sym_source(struct sym_entry *syme)
292 struct symbol *symbol = sym_entry__symbol(syme);
293 struct source_line *line;
294 char pattern[PATH_MAX];
296 sprintf(pattern, "<%s>:", symbol->name);
298 pthread_mutex_lock(&syme->src->lock);
299 for (line = syme->src->lines; line; line = line->next) {
300 if (strstr(line->line, pattern)) {
301 syme->src->source = line;
305 pthread_mutex_unlock(&syme->src->lock);
308 static void show_lines(struct source_line *queue, int count, int total)
311 struct source_line *line;
314 for (i = 0; i < count; i++) {
315 float pcnt = 100.0*(float)line->count[sym_counter]/(float)total;
317 printf("%8li %4.1f%%\t%s\n", line->count[sym_counter], pcnt, line->line);
322 #define TRACE_COUNT 3
324 static void show_details(struct sym_entry *syme)
326 struct symbol *symbol;
327 struct source_line *line;
328 struct source_line *line_queue = NULL;
330 int line_queue_count = 0, total = 0, more = 0;
335 if (!syme->src->source)
336 lookup_sym_source(syme);
338 if (!syme->src->source)
341 symbol = sym_entry__symbol(syme);
342 printf("Showing %s for %s\n", event_name(sym_counter), symbol->name);
343 printf(" Events Pcnt (>=%d%%)\n", sym_pcnt_filter);
345 pthread_mutex_lock(&syme->src->lock);
346 line = syme->src->source;
348 total += line->count[sym_counter];
352 line = syme->src->source;
356 if (!line_queue_count)
360 if (line->count[sym_counter])
361 pcnt = 100.0 * line->count[sym_counter] / (float)total;
362 if (pcnt >= (float)sym_pcnt_filter) {
363 if (displayed <= print_entries)
364 show_lines(line_queue, line_queue_count, total);
366 displayed += line_queue_count;
367 line_queue_count = 0;
369 } else if (line_queue_count > TRACE_COUNT) {
370 line_queue = line_queue->next;
374 line->count[sym_counter] = zero ? 0 : line->count[sym_counter] * 7 / 8;
377 pthread_mutex_unlock(&syme->src->lock);
379 printf("%d lines not displayed, maybe increase display entries [e]\n", more);
383 * Symbols will be added here in event__process_sample and will get out
386 static LIST_HEAD(active_symbols);
387 static pthread_mutex_t active_symbols_lock = PTHREAD_MUTEX_INITIALIZER;
390 * Ordering weight: count-1 * count-2 * ... / count-n
392 static double sym_weight(const struct sym_entry *sym)
394 double weight = sym->snap_count;
397 if (!display_weighted)
400 for (counter = 1; counter < nr_counters-1; counter++)
401 weight *= sym->count[counter];
403 weight /= (sym->count[counter] + 1);
409 static long userspace_samples;
410 static const char CONSOLE_CLEAR[] = "
\e[H
\e[2J";
412 static void __list_insert_active_sym(struct sym_entry *syme)
414 list_add(&syme->node, &active_symbols);
417 static void list_remove_active_sym(struct sym_entry *syme)
419 pthread_mutex_lock(&active_symbols_lock);
420 list_del_init(&syme->node);
421 pthread_mutex_unlock(&active_symbols_lock);
424 static void rb_insert_active_sym(struct rb_root *tree, struct sym_entry *se)
426 struct rb_node **p = &tree->rb_node;
427 struct rb_node *parent = NULL;
428 struct sym_entry *iter;
432 iter = rb_entry(parent, struct sym_entry, rb_node);
434 if (se->weight > iter->weight)
440 rb_link_node(&se->rb_node, parent, p);
441 rb_insert_color(&se->rb_node, tree);
444 static void print_sym_table(void)
447 int counter, snap = !display_weighted ? sym_counter : 0;
448 float samples_per_sec = samples/delay_secs;
449 float ksamples_per_sec = (samples-userspace_samples)/delay_secs;
450 float sum_ksamples = 0.0;
451 struct sym_entry *syme, *n;
452 struct rb_root tmp = RB_ROOT;
454 int sym_width = 0, dso_width = 0;
455 const int win_width = winsize.ws_col - 1;
456 struct dso *unique_dso = NULL, *first_dso = NULL;
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 (first_dso == NULL)
543 unique_dso = first_dso = syme->map->dso;
544 else if (syme->map->dso != first_dso)
547 if (syme->map->dso->long_name_len > dso_width)
548 dso_width = syme->map->dso->long_name_len;
550 if (syme->name_len > sym_width)
551 sym_width = syme->name_len;
557 printf("DSO: %s\n", unique_dso->long_name);
559 int max_dso_width = winsize.ws_col - sym_width - 29;
560 if (dso_width > max_dso_width)
561 dso_width = max_dso_width;
564 if (nr_counters == 1)
565 printf(" samples pcnt");
567 printf(" weight samples pcnt");
571 printf(" %-*.*s", sym_width, sym_width, "function");
575 printf(" %s _______ _____",
576 nr_counters == 1 ? " " : "______");
578 printf(" ________________");
579 printf(" %-*.*s", sym_width, sym_width, graph_line);
581 printf(" %-*.*s", dso_width, dso_width, graph_line);
584 for (nd = rb_first(&tmp); nd; nd = rb_next(nd)) {
588 syme = rb_entry(nd, struct sym_entry, rb_node);
589 sym = sym_entry__symbol(syme);
591 if (++printed > print_entries || (int)syme->snap_count < count_filter)
594 pcnt = 100.0 - (100.0 * ((sum_ksamples - syme->snap_count) /
597 if (nr_counters == 1 || !display_weighted)
598 printf("%20.2f ", syme->weight);
600 printf("%9.1f %10ld ", syme->weight, syme->snap_count);
602 percent_color_fprintf(stdout, "%4.1f%%", pcnt);
604 printf(" %016llx", sym->start);
605 printf(" %-*.*s", sym_width, sym_width, sym->name);
607 printf(" %-*.*s", dso_width, dso_width,
608 dso_width >= syme->map->dso->long_name_len ?
609 syme->map->dso->long_name :
610 syme->map->dso->short_name);
615 static void prompt_integer(int *target, const char *msg)
617 char *buf = malloc(0), *p;
621 fprintf(stdout, "\n%s: ", msg);
622 if (getline(&buf, &dummy, stdin) < 0)
625 p = strchr(buf, '\n');
635 tmp = strtoul(buf, NULL, 10);
641 static void prompt_percent(int *target, const char *msg)
645 prompt_integer(&tmp, msg);
646 if (tmp >= 0 && tmp <= 100)
650 static void prompt_symbol(struct sym_entry **target, const char *msg)
652 char *buf = malloc(0), *p;
653 struct sym_entry *syme = *target, *n, *found = NULL;
656 /* zero counters of active symbol */
658 pthread_mutex_lock(&syme->src->lock);
659 __zero_source_counters(syme);
661 pthread_mutex_unlock(&syme->src->lock);
664 fprintf(stdout, "\n%s: ", msg);
665 if (getline(&buf, &dummy, stdin) < 0)
668 p = strchr(buf, '\n');
672 pthread_mutex_lock(&active_symbols_lock);
673 syme = list_entry(active_symbols.next, struct sym_entry, node);
674 pthread_mutex_unlock(&active_symbols_lock);
676 list_for_each_entry_safe_from(syme, n, &active_symbols, node) {
677 struct symbol *sym = sym_entry__symbol(syme);
679 if (!strcmp(buf, sym->name)) {
686 fprintf(stderr, "Sorry, %s is not active.\n", sym_filter);
696 static void print_mapped_keys(void)
700 if (sym_filter_entry) {
701 struct symbol *sym = sym_entry__symbol(sym_filter_entry);
705 fprintf(stdout, "\nMapped keys:\n");
706 fprintf(stdout, "\t[d] display refresh delay. \t(%d)\n", delay_secs);
707 fprintf(stdout, "\t[e] display entries (lines). \t(%d)\n", print_entries);
710 fprintf(stdout, "\t[E] active event counter. \t(%s)\n", event_name(sym_counter));
712 fprintf(stdout, "\t[f] profile display filter (count). \t(%d)\n", count_filter);
715 fprintf(stdout, "\t[F] annotate display filter (percent). \t(%d%%)\n", sym_pcnt_filter);
716 fprintf(stdout, "\t[s] annotate symbol. \t(%s)\n", name?: "NULL");
717 fprintf(stdout, "\t[S] stop annotation.\n");
721 fprintf(stdout, "\t[w] toggle display weighted/count[E]r. \t(%d)\n", display_weighted ? 1 : 0);
724 "\t[K] hide kernel_symbols symbols. \t(%s)\n",
725 hide_kernel_symbols ? "yes" : "no");
727 "\t[U] hide user symbols. \t(%s)\n",
728 hide_user_symbols ? "yes" : "no");
729 fprintf(stdout, "\t[z] toggle sample zeroing. \t(%d)\n", zero ? 1 : 0);
730 fprintf(stdout, "\t[qQ] quit.\n");
733 static int key_mapped(int c)
747 return nr_counters > 1 ? 1 : 0;
751 return vmlinux_name ? 1 : 0;
759 static void handle_keypress(int c)
761 if (!key_mapped(c)) {
762 struct pollfd stdin_poll = { .fd = 0, .events = POLLIN };
763 struct termios tc, save;
766 fprintf(stdout, "\nEnter selection, or unmapped key to continue: ");
771 tc.c_lflag &= ~(ICANON | ECHO);
774 tcsetattr(0, TCSANOW, &tc);
776 poll(&stdin_poll, 1, -1);
779 tcsetattr(0, TCSAFLUSH, &save);
786 prompt_integer(&delay_secs, "Enter display delay");
791 prompt_integer(&print_entries, "Enter display entries (lines)");
792 if (print_entries == 0) {
793 sig_winch_handler(SIGWINCH);
794 signal(SIGWINCH, sig_winch_handler);
796 signal(SIGWINCH, SIG_DFL);
799 if (nr_counters > 1) {
802 fprintf(stderr, "\nAvailable events:");
803 for (i = 0; i < nr_counters; i++)
804 fprintf(stderr, "\n\t%d %s", i, event_name(i));
806 prompt_integer(&sym_counter, "Enter details event counter");
808 if (sym_counter >= nr_counters) {
809 fprintf(stderr, "Sorry, no such event, using %s.\n", event_name(0));
813 } else sym_counter = 0;
816 prompt_integer(&count_filter, "Enter display event count filter");
819 prompt_percent(&sym_pcnt_filter, "Enter details display event filter (percent)");
822 hide_kernel_symbols = !hide_kernel_symbols;
826 printf("exiting.\n");
828 dsos__fprintf(stderr);
831 prompt_symbol(&sym_filter_entry, "Enter details symbol");
834 if (!sym_filter_entry)
837 struct sym_entry *syme = sym_filter_entry;
839 pthread_mutex_lock(&syme->src->lock);
840 sym_filter_entry = NULL;
841 __zero_source_counters(syme);
842 pthread_mutex_unlock(&syme->src->lock);
846 hide_user_symbols = !hide_user_symbols;
849 display_weighted = ~display_weighted;
859 static void *display_thread(void *arg __used)
861 struct pollfd stdin_poll = { .fd = 0, .events = POLLIN };
862 struct termios tc, save;
867 tc.c_lflag &= ~(ICANON | ECHO);
872 delay_msecs = delay_secs * 1000;
873 tcsetattr(0, TCSANOW, &tc);
879 } while (!poll(&stdin_poll, 1, delay_msecs) == 1);
882 tcsetattr(0, TCSAFLUSH, &save);
890 /* Tag samples to be skipped. */
891 static const char *skip_symbols[] = {
897 "mwait_idle_with_hints",
899 "ppc64_runlatch_off",
900 "pseries_dedicated_idle_sleep",
904 static int symbol_filter(struct map *map, struct symbol *sym)
906 struct sym_entry *syme;
907 const char *name = sym->name;
911 * ppc64 uses function descriptors and appends a '.' to the
912 * start of every instruction address. Remove it.
917 if (!strcmp(name, "_text") ||
918 !strcmp(name, "_etext") ||
919 !strcmp(name, "_sinittext") ||
920 !strncmp("init_module", name, 11) ||
921 !strncmp("cleanup_module", name, 14) ||
922 strstr(name, "_text_start") ||
923 strstr(name, "_text_end"))
926 syme = symbol__priv(sym);
929 if (!sym_filter_entry && sym_filter && !strcmp(name, sym_filter))
930 sym_filter_entry = syme;
932 for (i = 0; skip_symbols[i]; i++) {
933 if (!strcmp(skip_symbols[i], name)) {
940 syme->name_len = strlen(sym->name);
945 static void event__process_sample(const event_t *self, int counter)
947 u64 ip = self->ip.ip;
949 struct sym_entry *syme;
951 u8 origin = self->header.misc & PERF_RECORD_MISC_CPUMODE_MASK;
954 case PERF_RECORD_MISC_USER: {
955 struct thread *thread;
957 if (hide_user_symbols)
960 thread = threads__findnew(self->ip.pid);
964 map = thread__find_map(thread, ip);
966 ip = map->map_ip(map, ip);
967 sym = map__find_symbol(map, ip, symbol_filter);
975 * If this is outside of all known maps,
976 * and is a negative address, try to look it
977 * up in the kernel dso, as it might be a
978 * vsyscall or vdso (which executes in user-mode).
980 if ((long long)ip >= 0)
983 case PERF_RECORD_MISC_KERNEL:
984 if (hide_kernel_symbols)
987 sym = kernel_maps__find_symbol(ip, &map, symbol_filter);
995 syme = symbol__priv(sym);
998 syme->count[counter]++;
999 syme->origin = origin;
1000 record_precise_ip(syme, counter, ip);
1001 pthread_mutex_lock(&active_symbols_lock);
1002 if (list_empty(&syme->node) || !syme->node.next)
1003 __list_insert_active_sym(syme);
1004 pthread_mutex_unlock(&active_symbols_lock);
1010 static void event__process_mmap(event_t *self)
1012 struct thread *thread = threads__findnew(self->mmap.pid);
1014 if (thread != NULL) {
1015 struct map *map = map__new(&self->mmap, NULL, 0);
1017 thread__insert_map(thread, map);
1021 static void event__process_comm(event_t *self)
1023 struct thread *thread = threads__findnew(self->comm.pid);
1026 thread__set_comm(thread, self->comm.comm);
1029 static int event__process(event_t *event)
1031 switch (event->header.type) {
1032 case PERF_RECORD_COMM:
1033 event__process_comm(event);
1035 case PERF_RECORD_MMAP:
1036 event__process_mmap(event);
1052 static unsigned int mmap_read_head(struct mmap_data *md)
1054 struct perf_event_mmap_page *pc = md->base;
1057 head = pc->data_head;
1063 static void mmap_read_counter(struct mmap_data *md)
1065 unsigned int head = mmap_read_head(md);
1066 unsigned int old = md->prev;
1067 unsigned char *data = md->base + page_size;
1071 * If we're further behind than half the buffer, there's a chance
1072 * the writer will bite our tail and mess up the samples under us.
1074 * If we somehow ended up ahead of the head, we got messed up.
1076 * In either case, truncate and restart at head.
1079 if (diff > md->mask / 2 || diff < 0) {
1080 fprintf(stderr, "WARNING: failed to keep up with mmap data.\n");
1083 * head points to a known good entry, start there.
1088 for (; old != head;) {
1089 event_t *event = (event_t *)&data[old & md->mask];
1093 size_t size = event->header.size;
1096 * Event straddles the mmap boundary -- header should always
1097 * be inside due to u64 alignment of output.
1099 if ((old & md->mask) + size != ((old + size) & md->mask)) {
1100 unsigned int offset = old;
1101 unsigned int len = min(sizeof(*event), size), cpy;
1102 void *dst = &event_copy;
1105 cpy = min(md->mask + 1 - (offset & md->mask), len);
1106 memcpy(dst, &data[offset & md->mask], cpy);
1112 event = &event_copy;
1115 if (event->header.type == PERF_RECORD_SAMPLE)
1116 event__process_sample(event, md->counter);
1118 event__process(event);
1125 static struct pollfd event_array[MAX_NR_CPUS * MAX_COUNTERS];
1126 static struct mmap_data mmap_array[MAX_NR_CPUS][MAX_COUNTERS];
1128 static void mmap_read(void)
1132 for (i = 0; i < nr_cpus; i++) {
1133 for (counter = 0; counter < nr_counters; counter++)
1134 mmap_read_counter(&mmap_array[i][counter]);
1141 static void start_counter(int i, int counter)
1143 struct perf_event_attr *attr;
1147 if (target_pid == -1 && profile_cpu == -1)
1150 attr = attrs + counter;
1152 attr->sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_TID;
1155 attr->sample_type |= PERF_SAMPLE_PERIOD;
1157 attr->sample_freq = freq;
1160 attr->inherit = (cpu < 0) && inherit;
1164 fd[i][counter] = sys_perf_event_open(attr, target_pid, cpu, group_fd, 0);
1166 if (fd[i][counter] < 0) {
1169 if (err == EPERM || err == EACCES)
1170 die("No permission - are you root?\n");
1172 * If it's cycles then fall back to hrtimer
1173 * based cpu-clock-tick sw counter, which
1174 * is always available even if no PMU support:
1176 if (attr->type == PERF_TYPE_HARDWARE
1177 && attr->config == PERF_COUNT_HW_CPU_CYCLES) {
1180 warning(" ... trying to fall back to cpu-clock-ticks\n");
1182 attr->type = PERF_TYPE_SOFTWARE;
1183 attr->config = PERF_COUNT_SW_CPU_CLOCK;
1187 error("perfcounter syscall returned with %d (%s)\n",
1188 fd[i][counter], strerror(err));
1189 die("No CONFIG_PERF_EVENTS=y kernel support configured?\n");
1192 assert(fd[i][counter] >= 0);
1193 fcntl(fd[i][counter], F_SETFL, O_NONBLOCK);
1196 * First counter acts as the group leader:
1198 if (group && group_fd == -1)
1199 group_fd = fd[i][counter];
1201 event_array[nr_poll].fd = fd[i][counter];
1202 event_array[nr_poll].events = POLLIN;
1205 mmap_array[i][counter].counter = counter;
1206 mmap_array[i][counter].prev = 0;
1207 mmap_array[i][counter].mask = mmap_pages*page_size - 1;
1208 mmap_array[i][counter].base = mmap(NULL, (mmap_pages+1)*page_size,
1209 PROT_READ, MAP_SHARED, fd[i][counter], 0);
1210 if (mmap_array[i][counter].base == MAP_FAILED)
1211 die("failed to mmap with %d (%s)\n", errno, strerror(errno));
1214 static int __cmd_top(void)
1220 if (target_pid != -1)
1221 event__synthesize_thread(target_pid, event__process);
1223 event__synthesize_threads(event__process);
1225 for (i = 0; i < nr_cpus; i++) {
1227 for (counter = 0; counter < nr_counters; counter++)
1228 start_counter(i, counter);
1231 /* Wait for a minimal set of events before starting the snapshot */
1232 poll(event_array, nr_poll, 100);
1236 if (pthread_create(&thread, NULL, display_thread, NULL)) {
1237 printf("Could not create display thread.\n");
1241 if (realtime_prio) {
1242 struct sched_param param;
1244 param.sched_priority = realtime_prio;
1245 if (sched_setscheduler(0, SCHED_FIFO, ¶m)) {
1246 printf("Could not set realtime priority.\n");
1256 if (hits == samples)
1257 ret = poll(event_array, nr_poll, 100);
1263 static const char * const top_usage[] = {
1264 "perf top [<options>]",
1268 static const struct option options[] = {
1269 OPT_CALLBACK('e', "event", NULL, "event",
1270 "event selector. use 'perf list' to list available events",
1272 OPT_INTEGER('c', "count", &default_interval,
1273 "event period to sample"),
1274 OPT_INTEGER('p', "pid", &target_pid,
1275 "profile events on existing pid"),
1276 OPT_BOOLEAN('a', "all-cpus", &system_wide,
1277 "system-wide collection from all CPUs"),
1278 OPT_INTEGER('C', "CPU", &profile_cpu,
1279 "CPU to profile on"),
1280 OPT_STRING('k', "vmlinux", &vmlinux_name, "file", "vmlinux pathname"),
1281 OPT_BOOLEAN('K', "hide_kernel_symbols", &hide_kernel_symbols,
1282 "hide kernel symbols"),
1283 OPT_INTEGER('m', "mmap-pages", &mmap_pages,
1284 "number of mmap data pages"),
1285 OPT_INTEGER('r', "realtime", &realtime_prio,
1286 "collect data with this RT SCHED_FIFO priority"),
1287 OPT_INTEGER('d', "delay", &delay_secs,
1288 "number of seconds to delay between refreshes"),
1289 OPT_BOOLEAN('D', "dump-symtab", &dump_symtab,
1290 "dump the symbol table used for profiling"),
1291 OPT_INTEGER('f', "count-filter", &count_filter,
1292 "only display functions with more events than this"),
1293 OPT_BOOLEAN('g', "group", &group,
1294 "put the counters into a counter group"),
1295 OPT_BOOLEAN('i', "inherit", &inherit,
1296 "child tasks inherit counters"),
1297 OPT_STRING('s', "sym-annotate", &sym_filter, "symbol name",
1298 "symbol to annotate - requires -k option"),
1299 OPT_BOOLEAN('z', "zero", &zero,
1300 "zero history across updates"),
1301 OPT_INTEGER('F', "freq", &freq,
1302 "profile at this frequency"),
1303 OPT_INTEGER('E', "entries", &print_entries,
1304 "display this many functions"),
1305 OPT_BOOLEAN('U', "hide_user_symbols", &hide_user_symbols,
1306 "hide user symbols"),
1307 OPT_BOOLEAN('v', "verbose", &verbose,
1308 "be more verbose (show counter open errors, etc)"),
1312 int cmd_top(int argc, const char **argv, const char *prefix __used)
1316 page_size = sysconf(_SC_PAGE_SIZE);
1318 argc = parse_options(argc, argv, options, top_usage, 0);
1320 usage_with_options(top_usage, options);
1322 /* CPU and PID are mutually exclusive */
1323 if (target_pid != -1 && profile_cpu != -1) {
1324 printf("WARNING: PID switch overriding CPU\n");
1332 symbol__init(sizeof(struct sym_entry) +
1333 (nr_counters + 1) * sizeof(unsigned long));
1338 err = kernel_maps__init(vmlinux_name, !vmlinux_name, true);
1341 parse_source(sym_filter_entry);
1344 * User specified count overrides default frequency.
1346 if (default_interval)
1349 default_interval = freq;
1351 fprintf(stderr, "frequency and count are zero, aborting\n");
1356 * Fill in the ones not specifically initialized via -c:
1358 for (counter = 0; counter < nr_counters; counter++) {
1359 if (attrs[counter].sample_period)
1362 attrs[counter].sample_period = default_interval;
1365 nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
1366 assert(nr_cpus <= MAX_NR_CPUS);
1367 assert(nr_cpus >= 0);
1369 if (target_pid != -1 || profile_cpu != -1)
1372 get_term_dimensions(&winsize);
1373 if (print_entries == 0) {
1374 update_print_entries(&winsize);
1375 signal(SIGWINCH, sig_winch_handler);