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");
835 prompt_symbol(&sym_filter_entry, "Enter details symbol");
838 if (!sym_filter_entry)
841 struct sym_entry *syme = sym_filter_entry;
843 pthread_mutex_lock(&syme->src->lock);
844 sym_filter_entry = NULL;
845 __zero_source_counters(syme);
846 pthread_mutex_unlock(&syme->src->lock);
850 hide_user_symbols = !hide_user_symbols;
853 display_weighted = ~display_weighted;
863 static void *display_thread(void *arg __used)
865 struct pollfd stdin_poll = { .fd = 0, .events = POLLIN };
866 struct termios tc, save;
871 tc.c_lflag &= ~(ICANON | ECHO);
876 delay_msecs = delay_secs * 1000;
877 tcsetattr(0, TCSANOW, &tc);
883 } while (!poll(&stdin_poll, 1, delay_msecs) == 1);
886 tcsetattr(0, TCSAFLUSH, &save);
894 /* Tag samples to be skipped. */
895 static const char *skip_symbols[] = {
901 "mwait_idle_with_hints",
903 "ppc64_runlatch_off",
904 "pseries_dedicated_idle_sleep",
908 static int symbol_filter(struct map *map, struct symbol *sym)
910 struct sym_entry *syme;
911 const char *name = sym->name;
915 * ppc64 uses function descriptors and appends a '.' to the
916 * start of every instruction address. Remove it.
921 if (!strcmp(name, "_text") ||
922 !strcmp(name, "_etext") ||
923 !strcmp(name, "_sinittext") ||
924 !strncmp("init_module", name, 11) ||
925 !strncmp("cleanup_module", name, 14) ||
926 strstr(name, "_text_start") ||
927 strstr(name, "_text_end"))
930 syme = symbol__priv(sym);
933 if (!sym_filter_entry && sym_filter && !strcmp(name, sym_filter))
934 sym_filter_entry = syme;
936 for (i = 0; skip_symbols[i]; i++) {
937 if (!strcmp(skip_symbols[i], name)) {
944 syme->name_len = strlen(sym->name);
949 static int parse_symbols(void)
951 struct dso *kernel = dsos__load_kernel();
956 if (dso__load_kernel_sym(kernel, symbol_filter, 1) <= 0)
960 dsos__fprintf(stderr);
965 static void event__process_sample(const event_t *self, int counter)
967 u64 ip = self->ip.ip;
969 struct sym_entry *syme;
971 u8 origin = self->header.misc & PERF_RECORD_MISC_CPUMODE_MASK;
974 case PERF_RECORD_MISC_USER: {
975 struct thread *thread;
977 if (hide_user_symbols)
980 thread = threads__findnew(self->ip.pid);
984 map = thread__find_map(thread, ip);
986 ip = map->map_ip(map, ip);
987 sym = map__find_symbol(map, ip, symbol_filter);
995 * If this is outside of all known maps,
996 * and is a negative address, try to look it
997 * up in the kernel dso, as it might be a
998 * vsyscall or vdso (which executes in user-mode).
1000 if ((long long)ip >= 0)
1003 case PERF_RECORD_MISC_KERNEL:
1004 if (hide_kernel_symbols)
1007 sym = kernel_maps__find_symbol(ip, &map);
1015 syme = symbol__priv(sym);
1018 syme->count[counter]++;
1019 syme->origin = origin;
1020 record_precise_ip(syme, counter, ip);
1021 pthread_mutex_lock(&active_symbols_lock);
1022 if (list_empty(&syme->node) || !syme->node.next)
1023 __list_insert_active_sym(syme);
1024 pthread_mutex_unlock(&active_symbols_lock);
1030 static void event__process_mmap(event_t *self)
1032 struct thread *thread = threads__findnew(self->mmap.pid);
1034 if (thread != NULL) {
1035 struct map *map = map__new(&self->mmap, NULL, 0);
1037 thread__insert_map(thread, map);
1041 static void event__process_comm(event_t *self)
1043 struct thread *thread = threads__findnew(self->comm.pid);
1046 thread__set_comm(thread, self->comm.comm);
1049 static int event__process(event_t *event)
1051 switch (event->header.type) {
1052 case PERF_RECORD_COMM:
1053 event__process_comm(event);
1055 case PERF_RECORD_MMAP:
1056 event__process_mmap(event);
1072 static unsigned int mmap_read_head(struct mmap_data *md)
1074 struct perf_event_mmap_page *pc = md->base;
1077 head = pc->data_head;
1083 static void mmap_read_counter(struct mmap_data *md)
1085 unsigned int head = mmap_read_head(md);
1086 unsigned int old = md->prev;
1087 unsigned char *data = md->base + page_size;
1091 * If we're further behind than half the buffer, there's a chance
1092 * the writer will bite our tail and mess up the samples under us.
1094 * If we somehow ended up ahead of the head, we got messed up.
1096 * In either case, truncate and restart at head.
1099 if (diff > md->mask / 2 || diff < 0) {
1100 fprintf(stderr, "WARNING: failed to keep up with mmap data.\n");
1103 * head points to a known good entry, start there.
1108 for (; old != head;) {
1109 event_t *event = (event_t *)&data[old & md->mask];
1113 size_t size = event->header.size;
1116 * Event straddles the mmap boundary -- header should always
1117 * be inside due to u64 alignment of output.
1119 if ((old & md->mask) + size != ((old + size) & md->mask)) {
1120 unsigned int offset = old;
1121 unsigned int len = min(sizeof(*event), size), cpy;
1122 void *dst = &event_copy;
1125 cpy = min(md->mask + 1 - (offset & md->mask), len);
1126 memcpy(dst, &data[offset & md->mask], cpy);
1132 event = &event_copy;
1135 if (event->header.type == PERF_RECORD_SAMPLE)
1136 event__process_sample(event, md->counter);
1138 event__process(event);
1145 static struct pollfd event_array[MAX_NR_CPUS * MAX_COUNTERS];
1146 static struct mmap_data mmap_array[MAX_NR_CPUS][MAX_COUNTERS];
1148 static void mmap_read(void)
1152 for (i = 0; i < nr_cpus; i++) {
1153 for (counter = 0; counter < nr_counters; counter++)
1154 mmap_read_counter(&mmap_array[i][counter]);
1161 static void start_counter(int i, int counter)
1163 struct perf_event_attr *attr;
1167 if (target_pid == -1 && profile_cpu == -1)
1170 attr = attrs + counter;
1172 attr->sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_TID;
1175 attr->sample_type |= PERF_SAMPLE_PERIOD;
1177 attr->sample_freq = freq;
1180 attr->inherit = (cpu < 0) && inherit;
1184 fd[i][counter] = sys_perf_event_open(attr, target_pid, cpu, group_fd, 0);
1186 if (fd[i][counter] < 0) {
1189 if (err == EPERM || err == EACCES)
1190 die("No permission - are you root?\n");
1192 * If it's cycles then fall back to hrtimer
1193 * based cpu-clock-tick sw counter, which
1194 * is always available even if no PMU support:
1196 if (attr->type == PERF_TYPE_HARDWARE
1197 && attr->config == PERF_COUNT_HW_CPU_CYCLES) {
1200 warning(" ... trying to fall back to cpu-clock-ticks\n");
1202 attr->type = PERF_TYPE_SOFTWARE;
1203 attr->config = PERF_COUNT_SW_CPU_CLOCK;
1207 error("perfcounter syscall returned with %d (%s)\n",
1208 fd[i][counter], strerror(err));
1209 die("No CONFIG_PERF_EVENTS=y kernel support configured?\n");
1212 assert(fd[i][counter] >= 0);
1213 fcntl(fd[i][counter], F_SETFL, O_NONBLOCK);
1216 * First counter acts as the group leader:
1218 if (group && group_fd == -1)
1219 group_fd = fd[i][counter];
1221 event_array[nr_poll].fd = fd[i][counter];
1222 event_array[nr_poll].events = POLLIN;
1225 mmap_array[i][counter].counter = counter;
1226 mmap_array[i][counter].prev = 0;
1227 mmap_array[i][counter].mask = mmap_pages*page_size - 1;
1228 mmap_array[i][counter].base = mmap(NULL, (mmap_pages+1)*page_size,
1229 PROT_READ, MAP_SHARED, fd[i][counter], 0);
1230 if (mmap_array[i][counter].base == MAP_FAILED)
1231 die("failed to mmap with %d (%s)\n", errno, strerror(errno));
1234 static int __cmd_top(void)
1240 if (target_pid != -1)
1241 event__synthesize_thread(target_pid, event__process);
1243 event__synthesize_threads(event__process);
1245 for (i = 0; i < nr_cpus; i++) {
1247 for (counter = 0; counter < nr_counters; counter++)
1248 start_counter(i, counter);
1251 /* Wait for a minimal set of events before starting the snapshot */
1252 poll(event_array, nr_poll, 100);
1256 if (pthread_create(&thread, NULL, display_thread, NULL)) {
1257 printf("Could not create display thread.\n");
1261 if (realtime_prio) {
1262 struct sched_param param;
1264 param.sched_priority = realtime_prio;
1265 if (sched_setscheduler(0, SCHED_FIFO, ¶m)) {
1266 printf("Could not set realtime priority.\n");
1276 if (hits == samples)
1277 ret = poll(event_array, nr_poll, 100);
1283 static const char * const top_usage[] = {
1284 "perf top [<options>]",
1288 static const struct option options[] = {
1289 OPT_CALLBACK('e', "event", NULL, "event",
1290 "event selector. use 'perf list' to list available events",
1292 OPT_INTEGER('c', "count", &default_interval,
1293 "event period to sample"),
1294 OPT_INTEGER('p', "pid", &target_pid,
1295 "profile events on existing pid"),
1296 OPT_BOOLEAN('a', "all-cpus", &system_wide,
1297 "system-wide collection from all CPUs"),
1298 OPT_INTEGER('C', "CPU", &profile_cpu,
1299 "CPU to profile on"),
1300 OPT_STRING('k', "vmlinux", &vmlinux_name, "file", "vmlinux pathname"),
1301 OPT_BOOLEAN('K', "hide_kernel_symbols", &hide_kernel_symbols,
1302 "hide kernel symbols"),
1303 OPT_INTEGER('m', "mmap-pages", &mmap_pages,
1304 "number of mmap data pages"),
1305 OPT_INTEGER('r', "realtime", &realtime_prio,
1306 "collect data with this RT SCHED_FIFO priority"),
1307 OPT_INTEGER('d', "delay", &delay_secs,
1308 "number of seconds to delay between refreshes"),
1309 OPT_BOOLEAN('D', "dump-symtab", &dump_symtab,
1310 "dump the symbol table used for profiling"),
1311 OPT_INTEGER('f', "count-filter", &count_filter,
1312 "only display functions with more events than this"),
1313 OPT_BOOLEAN('g', "group", &group,
1314 "put the counters into a counter group"),
1315 OPT_BOOLEAN('i', "inherit", &inherit,
1316 "child tasks inherit counters"),
1317 OPT_STRING('s', "sym-annotate", &sym_filter, "symbol name",
1318 "symbol to annotate - requires -k option"),
1319 OPT_BOOLEAN('z', "zero", &zero,
1320 "zero history across updates"),
1321 OPT_INTEGER('F', "freq", &freq,
1322 "profile at this frequency"),
1323 OPT_INTEGER('E', "entries", &print_entries,
1324 "display this many functions"),
1325 OPT_BOOLEAN('U', "hide_user_symbols", &hide_user_symbols,
1326 "hide user symbols"),
1327 OPT_BOOLEAN('v', "verbose", &verbose,
1328 "be more verbose (show counter open errors, etc)"),
1332 int cmd_top(int argc, const char **argv, const char *prefix __used)
1336 page_size = sysconf(_SC_PAGE_SIZE);
1338 argc = parse_options(argc, argv, options, top_usage, 0);
1340 usage_with_options(top_usage, options);
1342 /* CPU and PID are mutually exclusive */
1343 if (target_pid != -1 && profile_cpu != -1) {
1344 printf("WARNING: PID switch overriding CPU\n");
1352 symbol__init(sizeof(struct sym_entry) +
1353 (nr_counters + 1) * sizeof(unsigned long));
1359 parse_source(sym_filter_entry);
1363 * User specified count overrides default frequency.
1365 if (default_interval)
1368 default_interval = freq;
1370 fprintf(stderr, "frequency and count are zero, aborting\n");
1375 * Fill in the ones not specifically initialized via -c:
1377 for (counter = 0; counter < nr_counters; counter++) {
1378 if (attrs[counter].sample_period)
1381 attrs[counter].sample_period = default_interval;
1384 nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
1385 assert(nr_cpus <= MAX_NR_CPUS);
1386 assert(nr_cpus >= 0);
1388 if (target_pid != -1 || profile_cpu != -1)
1391 get_term_dimensions(&winsize);
1392 if (print_entries == 0) {
1393 update_print_entries(&winsize);
1394 signal(SIGWINCH, sig_winch_handler);