2 * kerneltop.c: show top kernel functions - performance counters showcase
6 make -C Documentation/perf_counter/
10 ------------------------------------------------------------------------------
11 KernelTop: 2669 irqs/sec [NMI, cache-misses/cache-refs], (all, cpu: 2)
12 ------------------------------------------------------------------------------
14 weight RIP kernel function
15 ______ ________________ _______________
17 35.20 - ffffffff804ce74b : skb_copy_and_csum_dev
18 33.00 - ffffffff804cb740 : sock_alloc_send_skb
19 31.26 - ffffffff804ce808 : skb_push
20 22.43 - ffffffff80510004 : tcp_established_options
21 19.00 - ffffffff8027d250 : find_get_page
22 15.76 - ffffffff804e4fc9 : eth_type_trans
23 15.20 - ffffffff804d8baa : dst_release
24 14.86 - ffffffff804cf5d8 : skb_release_head_state
25 14.00 - ffffffff802217d5 : read_hpet
26 12.00 - ffffffff804ffb7f : __ip_local_out
27 11.97 - ffffffff804fc0c8 : ip_local_deliver_finish
28 8.54 - ffffffff805001a3 : ip_queue_xmit
32 * Copyright (C) 2008, Red Hat Inc, Ingo Molnar <mingo@redhat.com>
34 * Improvements and fixes by:
36 * Arjan van de Ven <arjan@linux.intel.com>
37 * Yanmin Zhang <yanmin.zhang@intel.com>
38 * Wu Fengguang <fengguang.wu@intel.com>
39 * Mike Galbraith <efault@gmx.de>
40 * Paul Mackerras <paulus@samba.org>
42 * Released under the GPL v2. (and only v2, not any later version)
47 #include "util/util.h"
48 #include "util/util.h"
49 #include "util/parse-options.h"
50 #include "util/parse-events.h"
62 #include <sys/syscall.h>
63 #include <sys/ioctl.h>
65 #include <sys/prctl.h>
70 #include <linux/unistd.h>
71 #include <linux/types.h>
73 static int system_wide = 0;
75 static __u64 default_event_id[MAX_COUNTERS] = {
76 EID(PERF_TYPE_SOFTWARE, PERF_COUNT_TASK_CLOCK),
77 EID(PERF_TYPE_SOFTWARE, PERF_COUNT_CONTEXT_SWITCHES),
78 EID(PERF_TYPE_SOFTWARE, PERF_COUNT_CPU_MIGRATIONS),
79 EID(PERF_TYPE_SOFTWARE, PERF_COUNT_PAGE_FAULTS),
81 EID(PERF_TYPE_HARDWARE, PERF_COUNT_CPU_CYCLES),
82 EID(PERF_TYPE_HARDWARE, PERF_COUNT_INSTRUCTIONS),
83 EID(PERF_TYPE_HARDWARE, PERF_COUNT_CACHE_REFERENCES),
84 EID(PERF_TYPE_HARDWARE, PERF_COUNT_CACHE_MISSES),
86 static int default_interval = 100000;
87 static int event_count[MAX_COUNTERS];
88 static int fd[MAX_NR_CPUS][MAX_COUNTERS];
90 static __u64 count_filter = 100;
92 static int target_pid = -1;
93 static int profile_cpu = -1;
94 static int nr_cpus = 0;
96 static unsigned int realtime_prio = 0;
98 static unsigned int page_size;
99 static unsigned int mmap_pages = 16;
100 static int use_mmap = 0;
101 static int use_munmap = 0;
104 static char *sym_filter;
105 static unsigned long filter_start;
106 static unsigned long filter_end;
108 static int delay_secs = 2;
110 static int dump_symtab;
112 static const unsigned int default_count[] = {
125 static uint64_t min_ip;
126 static uint64_t max_ip = -1ll;
129 unsigned long long addr;
131 unsigned long count[MAX_COUNTERS];
135 #define MAX_SYMS 100000
137 static int sym_table_count;
139 struct sym_entry *sym_filter_entry;
141 static struct sym_entry sym_table[MAX_SYMS];
144 * Ordering weight: count-1 * count-2 * ... / count-n
146 static double sym_weight(const struct sym_entry *sym)
151 weight = sym->count[0];
153 for (counter = 1; counter < nr_counters-1; counter++)
154 weight *= sym->count[counter];
156 weight /= (sym->count[counter] + 1);
161 static int compare(const void *__sym1, const void *__sym2)
163 const struct sym_entry *sym1 = __sym1, *sym2 = __sym2;
165 return sym_weight(sym1) < sym_weight(sym2);
169 static long userspace_events;
170 static const char CONSOLE_CLEAR[] = "
\e[H
\e[2J";
172 static struct sym_entry tmp[MAX_SYMS];
174 static void print_sym_table(void)
176 int i, j, active_count, printed;
178 float events_per_sec = events/delay_secs;
179 float kevents_per_sec = (events-userspace_events)/delay_secs;
180 float sum_kevents = 0.0;
182 events = userspace_events = 0;
184 /* Iterate over symbol table and copy/tally/decay active symbols. */
185 for (i = 0, active_count = 0; i < sym_table_count; i++) {
186 if (sym_table[i].count[0]) {
187 tmp[active_count++] = sym_table[i];
188 sum_kevents += sym_table[i].count[0];
190 for (j = 0; j < nr_counters; j++)
191 sym_table[i].count[j] = zero ? 0 : sym_table[i].count[j] * 7 / 8;
195 qsort(tmp, active_count + 1, sizeof(tmp[0]), compare);
197 write(1, CONSOLE_CLEAR, strlen(CONSOLE_CLEAR));
200 "------------------------------------------------------------------------------\n");
201 printf( " KernelTop:%8.0f irqs/sec kernel:%4.1f%% [%s, ",
203 100.0 - (100.0*((events_per_sec-kevents_per_sec)/events_per_sec)),
204 nmi ? "NMI" : "IRQ");
206 if (nr_counters == 1)
207 printf("%d ", event_count[0]);
209 for (counter = 0; counter < nr_counters; counter++) {
213 printf("%s", event_name(counter));
218 if (target_pid != -1)
219 printf(" (target_pid: %d", target_pid);
223 if (profile_cpu != -1)
224 printf(", cpu: %d)\n", profile_cpu);
226 if (target_pid != -1)
229 printf(", %d CPUs)\n", nr_cpus);
232 printf("------------------------------------------------------------------------------\n\n");
234 if (nr_counters == 1)
235 printf(" events pcnt");
237 printf(" weight events pcnt");
239 printf(" RIP kernel function\n"
240 " ______ ______ _____ ________________ _______________\n\n"
243 for (i = 0, printed = 0; i < active_count; i++) {
246 if (++printed > 18 || tmp[i].count[0] < count_filter)
249 pcnt = 100.0 - (100.0*((sum_kevents-tmp[i].count[0])/sum_kevents));
251 if (nr_counters == 1)
252 printf("%19.2f - %4.1f%% - %016llx : %s\n",
254 pcnt, tmp[i].addr, tmp[i].sym);
256 printf("%8.1f %10ld - %4.1f%% - %016llx : %s\n",
259 pcnt, tmp[i].addr, tmp[i].sym);
263 struct pollfd stdin_poll = { .fd = 0, .events = POLLIN };
265 if (poll(&stdin_poll, 1, 0) == 1) {
266 printf("key pressed - exiting.\n");
272 static void *display_thread(void *arg)
274 printf("KernelTop refresh period: %d seconds\n", delay_secs);
276 while (!sleep(delay_secs))
282 static int read_symbol(FILE *in, struct sym_entry *s)
284 static int filter_match = 0;
289 rc = fscanf(in, "%llx %c %499s", &s->addr, &stype, str);
295 /* skip until end of line: */
299 if (rc == '\n' || rc == EOF || pos >= 499)
308 /* Filter out known duplicates and non-text symbols. */
309 if (!strcmp(sym, "_text"))
311 if (!min_ip && !strcmp(sym, "_stext"))
313 if (!strcmp(sym, "_etext") || !strcmp(sym, "_sinittext"))
315 if (stype != 'T' && stype != 't')
317 if (!strncmp("init_module", sym, 11) || !strncmp("cleanup_module", sym, 14))
319 if (strstr(sym, "_text_start") || strstr(sym, "_text_end"))
322 s->sym = malloc(strlen(str)+1);
325 strcpy((char *)s->sym, str);
328 /* Tag events to be skipped. */
329 if (!strcmp("default_idle", s->sym) || !strcmp("cpu_idle", s->sym))
331 else if (!strcmp("enter_idle", s->sym) || !strcmp("exit_idle", s->sym))
333 else if (!strcmp("mwait_idle", s->sym))
336 if (filter_match == 1) {
337 filter_end = s->addr;
339 if (filter_end - filter_start > 10000) {
340 printf("hm, too large filter symbol <%s> - skipping.\n",
342 printf("symbol filter start: %016lx\n", filter_start);
343 printf(" end: %016lx\n", filter_end);
344 filter_end = filter_start = 0;
349 if (filter_match == 0 && sym_filter && !strcmp(s->sym, sym_filter)) {
351 filter_start = s->addr;
357 static int compare_addr(const void *__sym1, const void *__sym2)
359 const struct sym_entry *sym1 = __sym1, *sym2 = __sym2;
361 return sym1->addr > sym2->addr;
364 static void sort_symbol_table(void)
369 qsort(sym_table, sym_table_count, sizeof(sym_table[0]), compare_addr);
370 for (i = 0, dups = 0; i < sym_table_count; i++) {
371 if (sym_table[i].addr == sym_table[i+1].addr) {
372 sym_table[i+1].addr = -1ll;
376 sym_table_count -= dups;
380 static void parse_symbols(void)
382 struct sym_entry *last;
384 FILE *kallsyms = fopen("/proc/kallsyms", "r");
387 printf("Could not open /proc/kallsyms - no CONFIG_KALLSYMS_ALL=y?\n");
391 while (!feof(kallsyms)) {
392 if (read_symbol(kallsyms, &sym_table[sym_table_count]) == 0) {
394 assert(sym_table_count <= MAX_SYMS);
399 min_ip = sym_table[0].addr;
400 max_ip = sym_table[sym_table_count-1].addr;
401 last = sym_table + sym_table_count++;
408 for (count=0; count < sym_table_count; count ++) {
409 if (!strcmp(sym_table[count].sym, sym_filter)) {
410 sym_filter_entry = &sym_table[count];
418 for (i = 0; i < sym_table_count; i++)
419 fprintf(stderr, "%llx %s\n",
420 sym_table[i].addr, sym_table[i].sym);
424 #define TRACE_COUNT 3
427 * Binary search in the histogram table and record the hit:
429 static void record_ip(uint64_t ip, int counter)
431 int left_idx, middle_idx, right_idx, idx;
432 unsigned long left, middle, right;
435 right_idx = sym_table_count-1;
436 assert(ip <= max_ip && ip >= min_ip);
438 while (left_idx + 1 < right_idx) {
439 middle_idx = (left_idx + right_idx) / 2;
441 left = sym_table[ left_idx].addr;
442 middle = sym_table[middle_idx].addr;
443 right = sym_table[ right_idx].addr;
445 if (!(left <= middle && middle <= right)) {
446 printf("%016lx...\n%016lx...\n%016lx\n", left, middle, right);
447 printf("%d %d %d\n", left_idx, middle_idx, right_idx);
449 assert(left <= middle && middle <= right);
450 if (!(left <= ip && ip <= right)) {
451 printf(" left: %016lx\n", left);
452 printf(" ip: %016lx\n", (unsigned long)ip);
453 printf("right: %016lx\n", right);
455 assert(left <= ip && ip <= right);
457 * [ left .... target .... middle .... right ]
461 right_idx = middle_idx;
465 * [ left .... middle ... target ... right ]
468 left_idx = middle_idx;
473 if (!sym_table[idx].skip)
474 sym_table[idx].count[counter]++;
478 static void process_event(uint64_t ip, int counter)
482 if (ip < min_ip || ip > max_ip) {
487 record_ip(ip, counter);
497 static unsigned int mmap_read_head(struct mmap_data *md)
499 struct perf_counter_mmap_page *pc = md->base;
502 head = pc->data_head;
508 struct timeval last_read, this_read;
510 static void mmap_read(struct mmap_data *md)
512 unsigned int head = mmap_read_head(md);
513 unsigned int old = md->prev;
514 unsigned char *data = md->base + page_size;
517 gettimeofday(&this_read, NULL);
520 * If we're further behind than half the buffer, there's a chance
521 * the writer will bite our tail and screw up the events under us.
523 * If we somehow ended up ahead of the head, we got messed up.
525 * In either case, truncate and restart at head.
528 if (diff > md->mask / 2 || diff < 0) {
532 timersub(&this_read, &last_read, &iv);
533 msecs = iv.tv_sec*1000 + iv.tv_usec/1000;
535 fprintf(stderr, "WARNING: failed to keep up with mmap data."
536 " Last read %lu msecs ago.\n", msecs);
539 * head points to a known good entry, start there.
544 last_read = this_read;
546 for (; old != head;) {
548 struct perf_event_header header;
550 __u32 pid, target_pid;
553 struct perf_event_header header;
554 __u32 pid, target_pid;
558 char filename[PATH_MAX];
561 typedef union event_union {
562 struct perf_event_header header;
564 struct mmap_event mmap;
567 event_t *event = (event_t *)&data[old & md->mask];
571 size_t size = event->header.size;
574 * Event straddles the mmap boundary -- header should always
575 * be inside due to u64 alignment of output.
577 if ((old & md->mask) + size != ((old + size) & md->mask)) {
578 unsigned int offset = old;
579 unsigned int len = min(sizeof(*event), size), cpy;
580 void *dst = &event_copy;
583 cpy = min(md->mask + 1 - (offset & md->mask), len);
584 memcpy(dst, &data[offset & md->mask], cpy);
595 if (event->header.misc & PERF_EVENT_MISC_OVERFLOW) {
596 if (event->header.type & PERF_RECORD_IP)
597 process_event(event->ip.ip, md->counter);
599 switch (event->header.type) {
600 case PERF_EVENT_MMAP:
601 case PERF_EVENT_MUNMAP:
602 printf("%s: %Lu %Lu %Lu %s\n",
603 event->header.type == PERF_EVENT_MMAP
608 event->mmap.filename);
617 static struct pollfd event_array[MAX_NR_CPUS * MAX_COUNTERS];
618 static struct mmap_data mmap_array[MAX_NR_CPUS][MAX_COUNTERS];
620 static int __cmd_top(void)
622 struct perf_counter_hw_event hw_event;
624 int i, counter, group_fd, nr_poll = 0;
628 for (i = 0; i < nr_cpus; i++) {
630 for (counter = 0; counter < nr_counters; counter++) {
633 if (target_pid == -1 && profile_cpu == -1)
636 memset(&hw_event, 0, sizeof(hw_event));
637 hw_event.config = event_id[counter];
638 hw_event.irq_period = event_count[counter];
639 hw_event.record_type = PERF_RECORD_IP | PERF_RECORD_TID;
641 hw_event.mmap = use_mmap;
642 hw_event.munmap = use_munmap;
643 hw_event.freq = freq;
645 fd[i][counter] = sys_perf_counter_open(&hw_event, target_pid, cpu, group_fd, 0);
646 if (fd[i][counter] < 0) {
648 printf("kerneltop error: syscall returned with %d (%s)\n",
649 fd[i][counter], strerror(err));
651 printf("Are you root?\n");
654 assert(fd[i][counter] >= 0);
655 fcntl(fd[i][counter], F_SETFL, O_NONBLOCK);
658 * First counter acts as the group leader:
660 if (group && group_fd == -1)
661 group_fd = fd[i][counter];
663 event_array[nr_poll].fd = fd[i][counter];
664 event_array[nr_poll].events = POLLIN;
667 mmap_array[i][counter].counter = counter;
668 mmap_array[i][counter].prev = 0;
669 mmap_array[i][counter].mask = mmap_pages*page_size - 1;
670 mmap_array[i][counter].base = mmap(NULL, (mmap_pages+1)*page_size,
671 PROT_READ, MAP_SHARED, fd[i][counter], 0);
672 if (mmap_array[i][counter].base == MAP_FAILED) {
673 printf("kerneltop error: failed to mmap with %d (%s)\n",
674 errno, strerror(errno));
680 if (pthread_create(&thread, NULL, display_thread, NULL)) {
681 printf("Could not create display thread.\n");
686 struct sched_param param;
688 param.sched_priority = realtime_prio;
689 if (sched_setscheduler(0, SCHED_FIFO, ¶m)) {
690 printf("Could not set realtime priority.\n");
698 for (i = 0; i < nr_cpus; i++) {
699 for (counter = 0; counter < nr_counters; counter++)
700 mmap_read(&mmap_array[i][counter]);
704 ret = poll(event_array, nr_poll, 100);
710 static const char * const top_usage[] = {
711 "perf top [<options>]",
715 static char events_help_msg[EVENTS_HELP_MAX];
717 static const struct option options[] = {
718 OPT_CALLBACK('e', "event", NULL, "event",
719 events_help_msg, parse_events),
720 OPT_INTEGER('c', "count", &default_interval,
721 "event period to sample"),
722 OPT_INTEGER('p', "pid", &target_pid,
723 "profile events on existing pid"),
724 OPT_BOOLEAN('a', "all-cpus", &system_wide,
725 "system-wide collection from all CPUs"),
726 OPT_INTEGER('C', "CPU", &profile_cpu,
727 "CPU to profile on"),
728 OPT_INTEGER('m', "mmap-pages", &mmap_pages,
729 "number of mmap data pages"),
730 OPT_INTEGER('r', "realtime", &realtime_prio,
731 "collect data with this RT SCHED_FIFO priority"),
732 OPT_INTEGER('d', "delay", &realtime_prio,
733 "number of seconds to delay between refreshes"),
734 OPT_BOOLEAN('D', "dump-symtab", &dump_symtab,
735 "dump the symbol table used for profiling"),
736 OPT_INTEGER('f', "--count-filter", &count_filter,
737 "only display functions with more events than this"),
738 OPT_BOOLEAN('g', "group", &group,
739 "put the counters into a counter group"),
740 OPT_STRING('s', "sym-filter", &sym_filter, "pattern",
741 "only display symbols matchig this pattern"),
742 OPT_BOOLEAN('z', "zero", &group,
743 "zero history across updates"),
744 OPT_BOOLEAN('M', "use-mmap", &use_mmap,
745 "track mmap events"),
746 OPT_BOOLEAN('U', "use-munmap", &use_munmap,
747 "track munmap events"),
748 OPT_INTEGER('F', "--freq", &freq,
749 "profile at this frequency"),
753 int cmd_top(int argc, const char **argv, const char *prefix)
757 page_size = sysconf(_SC_PAGE_SIZE);
759 create_events_help(events_help_msg);
760 memcpy(event_id, default_event_id, sizeof(default_event_id));
762 argc = parse_options(argc, argv, options, top_usage, 0);
764 usage_with_options(top_usage, options);
767 default_interval = freq;
771 /* CPU and PID are mutually exclusive */
772 if (target_pid != -1 && profile_cpu != -1) {
773 printf("WARNING: PID switch overriding CPU\n");
783 for (counter = 0; counter < nr_counters; counter++) {
784 if (event_count[counter])
787 event_count[counter] = default_interval;
790 nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
791 assert(nr_cpus <= MAX_NR_CPUS);
792 assert(nr_cpus >= 0);
794 if (target_pid != -1 || profile_cpu != -1)