blob: 4bed265926dd2df379682a11aeb867a1b056144d [file] [log] [blame]
Ingo Molnar07800602009-04-20 15:00:56 +02001/*
2 * kerneltop.c: show top kernel functions - performance counters showcase
3
4 Build with:
5
Robert Richter38105f02009-04-29 12:47:26 +02006 make -C Documentation/perf_counter/
Ingo Molnar07800602009-04-20 15:00:56 +02007
8 Sample output:
9
10------------------------------------------------------------------------------
11 KernelTop: 2669 irqs/sec [NMI, cache-misses/cache-refs], (all, cpu: 2)
12------------------------------------------------------------------------------
13
14 weight RIP kernel function
15 ______ ________________ _______________
16
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
29 */
30
Ingo Molnar07800602009-04-20 15:00:56 +020031 /*
32 * Copyright (C) 2008, Red Hat Inc, Ingo Molnar <mingo@redhat.com>
33 *
34 * Improvements and fixes by:
35 *
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>
41 *
42 * Released under the GPL v2. (and only v2, not any later version)
43 */
44
Peter Zijlstra1a482f32009-05-23 18:28:58 +020045#include "perf.h"
Ingo Molnar148be2c2009-04-27 08:02:14 +020046#include "util/util.h"
Ingo Molnar07800602009-04-20 15:00:56 +020047
Ingo Molnar07800602009-04-20 15:00:56 +020048#include <getopt.h>
49#include <assert.h>
50#include <fcntl.h>
51#include <stdio.h>
52#include <errno.h>
Ingo Molnar07800602009-04-20 15:00:56 +020053#include <time.h>
54#include <sched.h>
55#include <pthread.h>
56
57#include <sys/syscall.h>
58#include <sys/ioctl.h>
59#include <sys/poll.h>
60#include <sys/prctl.h>
61#include <sys/wait.h>
62#include <sys/uio.h>
63#include <sys/mman.h>
64
65#include <linux/unistd.h>
66#include <linux/types.h>
67
Ingo Molnar07800602009-04-20 15:00:56 +020068static int system_wide = 0;
69
70static int nr_counters = 0;
71static __u64 event_id[MAX_COUNTERS] = {
72 EID(PERF_TYPE_SOFTWARE, PERF_COUNT_TASK_CLOCK),
73 EID(PERF_TYPE_SOFTWARE, PERF_COUNT_CONTEXT_SWITCHES),
74 EID(PERF_TYPE_SOFTWARE, PERF_COUNT_CPU_MIGRATIONS),
75 EID(PERF_TYPE_SOFTWARE, PERF_COUNT_PAGE_FAULTS),
76
77 EID(PERF_TYPE_HARDWARE, PERF_COUNT_CPU_CYCLES),
78 EID(PERF_TYPE_HARDWARE, PERF_COUNT_INSTRUCTIONS),
79 EID(PERF_TYPE_HARDWARE, PERF_COUNT_CACHE_REFERENCES),
80 EID(PERF_TYPE_HARDWARE, PERF_COUNT_CACHE_MISSES),
81};
82static int default_interval = 100000;
83static int event_count[MAX_COUNTERS];
84static int fd[MAX_NR_CPUS][MAX_COUNTERS];
85
86static __u64 count_filter = 100;
87
88static int tid = -1;
89static int profile_cpu = -1;
90static int nr_cpus = 0;
91static int nmi = 1;
92static unsigned int realtime_prio = 0;
93static int group = 0;
94static unsigned int page_size;
95static unsigned int mmap_pages = 16;
96static int use_mmap = 0;
97static int use_munmap = 0;
Peter Zijlstraf5456a62009-05-15 15:19:29 +020098static int freq = 0;
Ingo Molnar07800602009-04-20 15:00:56 +020099
100static char *vmlinux;
101
102static char *sym_filter;
103static unsigned long filter_start;
104static unsigned long filter_end;
105
106static int delay_secs = 2;
107static int zero;
108static int dump_symtab;
109
110static int scale;
111
112struct source_line {
113 uint64_t EIP;
114 unsigned long count;
115 char *line;
116 struct source_line *next;
117};
118
119static struct source_line *lines;
120static struct source_line **lines_tail;
121
Ingo Molnarddcacfa2009-04-20 15:37:32 +0200122static const unsigned int default_count[] = {
Ingo Molnar07800602009-04-20 15:00:56 +0200123 1000000,
124 1000000,
125 10000,
126 10000,
127 1000000,
128 10000,
129};
130
131static char *hw_event_names[] = {
132 "CPU cycles",
133 "instructions",
134 "cache references",
135 "cache misses",
136 "branches",
137 "branch misses",
138 "bus cycles",
139};
140
141static char *sw_event_names[] = {
142 "cpu clock ticks",
143 "task clock ticks",
144 "pagefaults",
145 "context switches",
146 "CPU migrations",
147 "minor faults",
148 "major faults",
149};
150
151struct event_symbol {
152 __u64 event;
153 char *symbol;
154};
155
156static struct event_symbol event_symbols[] = {
157 {EID(PERF_TYPE_HARDWARE, PERF_COUNT_CPU_CYCLES), "cpu-cycles", },
158 {EID(PERF_TYPE_HARDWARE, PERF_COUNT_CPU_CYCLES), "cycles", },
159 {EID(PERF_TYPE_HARDWARE, PERF_COUNT_INSTRUCTIONS), "instructions", },
160 {EID(PERF_TYPE_HARDWARE, PERF_COUNT_CACHE_REFERENCES), "cache-references", },
161 {EID(PERF_TYPE_HARDWARE, PERF_COUNT_CACHE_MISSES), "cache-misses", },
162 {EID(PERF_TYPE_HARDWARE, PERF_COUNT_BRANCH_INSTRUCTIONS), "branch-instructions", },
163 {EID(PERF_TYPE_HARDWARE, PERF_COUNT_BRANCH_INSTRUCTIONS), "branches", },
164 {EID(PERF_TYPE_HARDWARE, PERF_COUNT_BRANCH_MISSES), "branch-misses", },
165 {EID(PERF_TYPE_HARDWARE, PERF_COUNT_BUS_CYCLES), "bus-cycles", },
166
167 {EID(PERF_TYPE_SOFTWARE, PERF_COUNT_CPU_CLOCK), "cpu-clock", },
168 {EID(PERF_TYPE_SOFTWARE, PERF_COUNT_TASK_CLOCK), "task-clock", },
169 {EID(PERF_TYPE_SOFTWARE, PERF_COUNT_PAGE_FAULTS), "page-faults", },
170 {EID(PERF_TYPE_SOFTWARE, PERF_COUNT_PAGE_FAULTS), "faults", },
171 {EID(PERF_TYPE_SOFTWARE, PERF_COUNT_PAGE_FAULTS_MIN), "minor-faults", },
172 {EID(PERF_TYPE_SOFTWARE, PERF_COUNT_PAGE_FAULTS_MAJ), "major-faults", },
173 {EID(PERF_TYPE_SOFTWARE, PERF_COUNT_CONTEXT_SWITCHES), "context-switches", },
174 {EID(PERF_TYPE_SOFTWARE, PERF_COUNT_CONTEXT_SWITCHES), "cs", },
175 {EID(PERF_TYPE_SOFTWARE, PERF_COUNT_CPU_MIGRATIONS), "cpu-migrations", },
176 {EID(PERF_TYPE_SOFTWARE, PERF_COUNT_CPU_MIGRATIONS), "migrations", },
177};
178
179#define __PERF_COUNTER_FIELD(config, name) \
180 ((config & PERF_COUNTER_##name##_MASK) >> PERF_COUNTER_##name##_SHIFT)
181
182#define PERF_COUNTER_RAW(config) __PERF_COUNTER_FIELD(config, RAW)
183#define PERF_COUNTER_CONFIG(config) __PERF_COUNTER_FIELD(config, CONFIG)
184#define PERF_COUNTER_TYPE(config) __PERF_COUNTER_FIELD(config, TYPE)
185#define PERF_COUNTER_ID(config) __PERF_COUNTER_FIELD(config, EVENT)
186
187static void display_events_help(void)
188{
189 unsigned int i;
190 __u64 e;
191
192 printf(
193 " -e EVENT --event=EVENT # symbolic-name abbreviations");
194
195 for (i = 0; i < ARRAY_SIZE(event_symbols); i++) {
196 int type, id;
197
198 e = event_symbols[i].event;
199 type = PERF_COUNTER_TYPE(e);
200 id = PERF_COUNTER_ID(e);
201
202 printf("\n %d:%d: %-20s",
203 type, id, event_symbols[i].symbol);
204 }
205
206 printf("\n"
207 " rNNN: raw PMU events (eventsel+umask)\n\n");
208}
209
Ingo Molnar07800602009-04-20 15:00:56 +0200210static void display_help(void)
211{
Ingo Molnar07800602009-04-20 15:00:56 +0200212 printf(
213 "Usage: kerneltop [<options>]\n"
214 " Or: kerneltop -S [<options>] COMMAND [ARGS]\n\n"
215 "KernelTop Options (up to %d event types can be specified at once):\n\n",
216 MAX_COUNTERS);
217
218 display_events_help();
219
220 printf(
Ingo Molnar07800602009-04-20 15:00:56 +0200221 " -c CNT --count=CNT # event period to sample\n\n"
222 " -C CPU --cpu=CPU # CPU (-1 for all) [default: -1]\n"
223 " -p PID --pid=PID # PID of sampled task (-1 for all) [default: -1]\n\n"
224 " -l # show scale factor for RR events\n"
225 " -d delay --delay=<seconds> # sampling/display delay [default: 2]\n"
226 " -f CNT --filter=CNT # min-event-count filter [default: 100]\n\n"
227 " -r prio --realtime=<prio> # event acquisition runs with SCHED_FIFO policy\n"
228 " -s symbol --symbol=<symbol> # function to be showed annotated one-shot\n"
229 " -x path --vmlinux=<path> # the vmlinux binary, required for -s use\n"
230 " -z --zero # zero counts after display\n"
231 " -D --dump_symtab # dump symbol table to stderr on startup\n"
232 " -m pages --mmap_pages=<pages> # number of mmap data pages\n"
233 " -M --mmap_info # print mmap info stream\n"
234 " -U --munmap_info # print munmap info stream\n"
235 );
236
237 exit(0);
238}
239
240static char *event_name(int ctr)
241{
242 __u64 config = event_id[ctr];
243 int type = PERF_COUNTER_TYPE(config);
244 int id = PERF_COUNTER_ID(config);
245 static char buf[32];
246
247 if (PERF_COUNTER_RAW(config)) {
248 sprintf(buf, "raw 0x%llx", PERF_COUNTER_CONFIG(config));
249 return buf;
250 }
251
252 switch (type) {
253 case PERF_TYPE_HARDWARE:
254 if (id < PERF_HW_EVENTS_MAX)
255 return hw_event_names[id];
256 return "unknown-hardware";
257
258 case PERF_TYPE_SOFTWARE:
259 if (id < PERF_SW_EVENTS_MAX)
260 return sw_event_names[id];
261 return "unknown-software";
262
263 default:
264 break;
265 }
266
267 return "unknown";
268}
269
270/*
271 * Each event can have multiple symbolic names.
272 * Symbolic names are (almost) exactly matched.
273 */
274static __u64 match_event_symbols(char *str)
275{
276 __u64 config, id;
277 int type;
278 unsigned int i;
279
280 if (sscanf(str, "r%llx", &config) == 1)
281 return config | PERF_COUNTER_RAW_MASK;
282
283 if (sscanf(str, "%d:%llu", &type, &id) == 2)
284 return EID(type, id);
285
286 for (i = 0; i < ARRAY_SIZE(event_symbols); i++) {
287 if (!strncmp(str, event_symbols[i].symbol,
288 strlen(event_symbols[i].symbol)))
289 return event_symbols[i].event;
290 }
291
292 return ~0ULL;
293}
294
295static int parse_events(char *str)
296{
297 __u64 config;
298
299again:
300 if (nr_counters == MAX_COUNTERS)
301 return -1;
302
303 config = match_event_symbols(str);
304 if (config == ~0ULL)
305 return -1;
306
307 event_id[nr_counters] = config;
308 nr_counters++;
309
310 str = strstr(str, ",");
311 if (str) {
312 str++;
313 goto again;
314 }
315
316 return 0;
317}
318
Ingo Molnar07800602009-04-20 15:00:56 +0200319/*
320 * Symbols
321 */
322
323static uint64_t min_ip;
324static uint64_t max_ip = -1ll;
325
326struct sym_entry {
327 unsigned long long addr;
328 char *sym;
329 unsigned long count[MAX_COUNTERS];
330 int skip;
331 struct source_line *source;
332};
333
334#define MAX_SYMS 100000
335
336static int sym_table_count;
337
338struct sym_entry *sym_filter_entry;
339
340static struct sym_entry sym_table[MAX_SYMS];
341
342static void show_details(struct sym_entry *sym);
343
344/*
345 * Ordering weight: count-1 * count-2 * ... / count-n
346 */
347static double sym_weight(const struct sym_entry *sym)
348{
349 double weight;
350 int counter;
351
352 weight = sym->count[0];
353
354 for (counter = 1; counter < nr_counters-1; counter++)
355 weight *= sym->count[counter];
356
357 weight /= (sym->count[counter] + 1);
358
359 return weight;
360}
361
362static int compare(const void *__sym1, const void *__sym2)
363{
364 const struct sym_entry *sym1 = __sym1, *sym2 = __sym2;
365
366 return sym_weight(sym1) < sym_weight(sym2);
367}
368
369static long events;
370static long userspace_events;
371static const char CONSOLE_CLEAR[] = "";
372
373static struct sym_entry tmp[MAX_SYMS];
374
375static void print_sym_table(void)
376{
Mike Galbraithd94b9432009-05-25 09:57:56 +0200377 int i, j, active_count, printed;
Ingo Molnar07800602009-04-20 15:00:56 +0200378 int counter;
379 float events_per_sec = events/delay_secs;
380 float kevents_per_sec = (events-userspace_events)/delay_secs;
381 float sum_kevents = 0.0;
382
383 events = userspace_events = 0;
Ingo Molnar07800602009-04-20 15:00:56 +0200384
Mike Galbraithd94b9432009-05-25 09:57:56 +0200385 /* Iterate over symbol table and copy/tally/decay active symbols. */
386 for (i = 0, active_count = 0; i < sym_table_count; i++) {
387 if (sym_table[i].count[0]) {
388 tmp[active_count++] = sym_table[i];
389 sum_kevents += sym_table[i].count[0];
390
391 for (j = 0; j < nr_counters; j++)
392 sym_table[i].count[j] = zero ? 0 : sym_table[i].count[j] * 7 / 8;
393 }
394 }
395
396 qsort(tmp, active_count + 1, sizeof(tmp[0]), compare);
Ingo Molnar07800602009-04-20 15:00:56 +0200397
398 write(1, CONSOLE_CLEAR, strlen(CONSOLE_CLEAR));
399
400 printf(
401"------------------------------------------------------------------------------\n");
402 printf( " KernelTop:%8.0f irqs/sec kernel:%4.1f%% [%s, ",
403 events_per_sec,
404 100.0 - (100.0*((events_per_sec-kevents_per_sec)/events_per_sec)),
405 nmi ? "NMI" : "IRQ");
406
407 if (nr_counters == 1)
408 printf("%d ", event_count[0]);
409
410 for (counter = 0; counter < nr_counters; counter++) {
411 if (counter)
412 printf("/");
413
414 printf("%s", event_name(counter));
415 }
416
417 printf( "], ");
418
419 if (tid != -1)
420 printf(" (tid: %d", tid);
421 else
422 printf(" (all");
423
424 if (profile_cpu != -1)
425 printf(", cpu: %d)\n", profile_cpu);
426 else {
427 if (tid != -1)
428 printf(")\n");
429 else
430 printf(", %d CPUs)\n", nr_cpus);
431 }
432
433 printf("------------------------------------------------------------------------------\n\n");
434
435 if (nr_counters == 1)
436 printf(" events pcnt");
437 else
438 printf(" weight events pcnt");
439
440 printf(" RIP kernel function\n"
441 " ______ ______ _____ ________________ _______________\n\n"
442 );
443
Mike Galbraithd94b9432009-05-25 09:57:56 +0200444 for (i = 0, printed = 0; i < active_count; i++) {
Ingo Molnar07800602009-04-20 15:00:56 +0200445 float pcnt;
Ingo Molnar07800602009-04-20 15:00:56 +0200446
Mike Galbraithd94b9432009-05-25 09:57:56 +0200447 if (++printed > 18 || tmp[i].count[0] < count_filter)
448 break;
Ingo Molnar07800602009-04-20 15:00:56 +0200449
Mike Galbraithd94b9432009-05-25 09:57:56 +0200450 pcnt = 100.0 - (100.0*((sum_kevents-tmp[i].count[0])/sum_kevents));
451
452 if (nr_counters == 1)
453 printf("%19.2f - %4.1f%% - %016llx : %s\n",
454 sym_weight(tmp + i),
455 pcnt, tmp[i].addr, tmp[i].sym);
456 else
457 printf("%8.1f %10ld - %4.1f%% - %016llx : %s\n",
458 sym_weight(tmp + i),
459 tmp[i].count[0],
460 pcnt, tmp[i].addr, tmp[i].sym);
Ingo Molnar07800602009-04-20 15:00:56 +0200461 }
462
463 if (sym_filter_entry)
464 show_details(sym_filter_entry);
465
466 {
467 struct pollfd stdin_poll = { .fd = 0, .events = POLLIN };
468
469 if (poll(&stdin_poll, 1, 0) == 1) {
470 printf("key pressed - exiting.\n");
471 exit(0);
472 }
473 }
474}
475
476static void *display_thread(void *arg)
477{
478 printf("KernelTop refresh period: %d seconds\n", delay_secs);
479
480 while (!sleep(delay_secs))
481 print_sym_table();
482
483 return NULL;
484}
485
486static int read_symbol(FILE *in, struct sym_entry *s)
487{
488 static int filter_match = 0;
489 char *sym, stype;
490 char str[500];
491 int rc, pos;
492
493 rc = fscanf(in, "%llx %c %499s", &s->addr, &stype, str);
494 if (rc == EOF)
495 return -1;
496
497 assert(rc == 3);
498
499 /* skip until end of line: */
500 pos = strlen(str);
501 do {
502 rc = fgetc(in);
503 if (rc == '\n' || rc == EOF || pos >= 499)
504 break;
505 str[pos] = rc;
506 pos++;
507 } while (1);
508 str[pos] = 0;
509
510 sym = str;
511
512 /* Filter out known duplicates and non-text symbols. */
513 if (!strcmp(sym, "_text"))
514 return 1;
515 if (!min_ip && !strcmp(sym, "_stext"))
516 return 1;
517 if (!strcmp(sym, "_etext") || !strcmp(sym, "_sinittext"))
518 return 1;
519 if (stype != 'T' && stype != 't')
520 return 1;
521 if (!strncmp("init_module", sym, 11) || !strncmp("cleanup_module", sym, 14))
522 return 1;
523 if (strstr(sym, "_text_start") || strstr(sym, "_text_end"))
524 return 1;
525
Erdem Aktas82afae62009-05-10 02:13:19 -0400526 s->sym = malloc(strlen(str)+1);
Ingo Molnar07800602009-04-20 15:00:56 +0200527 assert(s->sym);
528
529 strcpy((char *)s->sym, str);
530 s->skip = 0;
531
532 /* Tag events to be skipped. */
533 if (!strcmp("default_idle", s->sym) || !strcmp("cpu_idle", s->sym))
534 s->skip = 1;
535 else if (!strcmp("enter_idle", s->sym) || !strcmp("exit_idle", s->sym))
536 s->skip = 1;
537 else if (!strcmp("mwait_idle", s->sym))
538 s->skip = 1;
539
540 if (filter_match == 1) {
541 filter_end = s->addr;
542 filter_match = -1;
543 if (filter_end - filter_start > 10000) {
544 printf("hm, too large filter symbol <%s> - skipping.\n",
545 sym_filter);
546 printf("symbol filter start: %016lx\n", filter_start);
547 printf(" end: %016lx\n", filter_end);
548 filter_end = filter_start = 0;
549 sym_filter = NULL;
550 sleep(1);
551 }
552 }
553 if (filter_match == 0 && sym_filter && !strcmp(s->sym, sym_filter)) {
554 filter_match = 1;
555 filter_start = s->addr;
556 }
557
558 return 0;
559}
560
Ingo Molnarddcacfa2009-04-20 15:37:32 +0200561static int compare_addr(const void *__sym1, const void *__sym2)
Ingo Molnar07800602009-04-20 15:00:56 +0200562{
563 const struct sym_entry *sym1 = __sym1, *sym2 = __sym2;
564
565 return sym1->addr > sym2->addr;
566}
567
568static void sort_symbol_table(void)
569{
570 int i, dups;
571
572 do {
573 qsort(sym_table, sym_table_count, sizeof(sym_table[0]), compare_addr);
574 for (i = 0, dups = 0; i < sym_table_count; i++) {
575 if (sym_table[i].addr == sym_table[i+1].addr) {
576 sym_table[i+1].addr = -1ll;
577 dups++;
578 }
579 }
580 sym_table_count -= dups;
581 } while(dups);
582}
583
584static void parse_symbols(void)
585{
586 struct sym_entry *last;
587
588 FILE *kallsyms = fopen("/proc/kallsyms", "r");
589
590 if (!kallsyms) {
591 printf("Could not open /proc/kallsyms - no CONFIG_KALLSYMS_ALL=y?\n");
592 exit(-1);
593 }
594
595 while (!feof(kallsyms)) {
596 if (read_symbol(kallsyms, &sym_table[sym_table_count]) == 0) {
597 sym_table_count++;
598 assert(sym_table_count <= MAX_SYMS);
599 }
600 }
601
602 sort_symbol_table();
603 min_ip = sym_table[0].addr;
604 max_ip = sym_table[sym_table_count-1].addr;
605 last = sym_table + sym_table_count++;
606
607 last->addr = -1ll;
608 last->sym = "<end>";
609
610 if (filter_end) {
611 int count;
612 for (count=0; count < sym_table_count; count ++) {
613 if (!strcmp(sym_table[count].sym, sym_filter)) {
614 sym_filter_entry = &sym_table[count];
615 break;
616 }
617 }
618 }
619 if (dump_symtab) {
620 int i;
621
622 for (i = 0; i < sym_table_count; i++)
623 fprintf(stderr, "%llx %s\n",
624 sym_table[i].addr, sym_table[i].sym);
625 }
626}
627
628/*
629 * Source lines
630 */
631
632static void parse_vmlinux(char *filename)
633{
634 FILE *file;
635 char command[PATH_MAX*2];
636 if (!filename)
637 return;
638
639 sprintf(command, "objdump --start-address=0x%016lx --stop-address=0x%016lx -dS %s", filter_start, filter_end, filename);
640
641 file = popen(command, "r");
642 if (!file)
643 return;
644
645 lines_tail = &lines;
646 while (!feof(file)) {
647 struct source_line *src;
648 size_t dummy = 0;
649 char *c;
650
651 src = malloc(sizeof(struct source_line));
652 assert(src != NULL);
653 memset(src, 0, sizeof(struct source_line));
654
655 if (getline(&src->line, &dummy, file) < 0)
656 break;
657 if (!src->line)
658 break;
659
660 c = strchr(src->line, '\n');
661 if (c)
662 *c = 0;
663
664 src->next = NULL;
665 *lines_tail = src;
666 lines_tail = &src->next;
667
668 if (strlen(src->line)>8 && src->line[8] == ':')
669 src->EIP = strtoull(src->line, NULL, 16);
670 if (strlen(src->line)>8 && src->line[16] == ':')
671 src->EIP = strtoull(src->line, NULL, 16);
672 }
673 pclose(file);
674}
675
676static void record_precise_ip(uint64_t ip)
677{
678 struct source_line *line;
679
680 for (line = lines; line; line = line->next) {
681 if (line->EIP == ip)
682 line->count++;
683 if (line->EIP > ip)
684 break;
685 }
686}
687
688static void lookup_sym_in_vmlinux(struct sym_entry *sym)
689{
690 struct source_line *line;
691 char pattern[PATH_MAX];
692 sprintf(pattern, "<%s>:", sym->sym);
693
694 for (line = lines; line; line = line->next) {
695 if (strstr(line->line, pattern)) {
696 sym->source = line;
697 break;
698 }
699 }
700}
701
702static void show_lines(struct source_line *line_queue, int line_queue_count)
703{
704 int i;
705 struct source_line *line;
706
707 line = line_queue;
708 for (i = 0; i < line_queue_count; i++) {
709 printf("%8li\t%s\n", line->count, line->line);
710 line = line->next;
711 }
712}
713
714#define TRACE_COUNT 3
715
716static void show_details(struct sym_entry *sym)
717{
718 struct source_line *line;
719 struct source_line *line_queue = NULL;
720 int displayed = 0;
721 int line_queue_count = 0;
722
723 if (!sym->source)
724 lookup_sym_in_vmlinux(sym);
725 if (!sym->source)
726 return;
727
728 printf("Showing details for %s\n", sym->sym);
729
730 line = sym->source;
731 while (line) {
732 if (displayed && strstr(line->line, ">:"))
733 break;
734
735 if (!line_queue_count)
736 line_queue = line;
737 line_queue_count ++;
738
739 if (line->count >= count_filter) {
740 show_lines(line_queue, line_queue_count);
741 line_queue_count = 0;
742 line_queue = NULL;
743 } else if (line_queue_count > TRACE_COUNT) {
744 line_queue = line_queue->next;
745 line_queue_count --;
746 }
747
748 line->count = 0;
749 displayed++;
750 if (displayed > 300)
751 break;
752 line = line->next;
753 }
754}
755
756/*
757 * Binary search in the histogram table and record the hit:
758 */
759static void record_ip(uint64_t ip, int counter)
760{
761 int left_idx, middle_idx, right_idx, idx;
762 unsigned long left, middle, right;
763
764 record_precise_ip(ip);
765
766 left_idx = 0;
767 right_idx = sym_table_count-1;
768 assert(ip <= max_ip && ip >= min_ip);
769
770 while (left_idx + 1 < right_idx) {
771 middle_idx = (left_idx + right_idx) / 2;
772
773 left = sym_table[ left_idx].addr;
774 middle = sym_table[middle_idx].addr;
775 right = sym_table[ right_idx].addr;
776
777 if (!(left <= middle && middle <= right)) {
778 printf("%016lx...\n%016lx...\n%016lx\n", left, middle, right);
779 printf("%d %d %d\n", left_idx, middle_idx, right_idx);
780 }
781 assert(left <= middle && middle <= right);
782 if (!(left <= ip && ip <= right)) {
783 printf(" left: %016lx\n", left);
784 printf(" ip: %016lx\n", (unsigned long)ip);
785 printf("right: %016lx\n", right);
786 }
787 assert(left <= ip && ip <= right);
788 /*
789 * [ left .... target .... middle .... right ]
790 * => right := middle
791 */
792 if (ip < middle) {
793 right_idx = middle_idx;
794 continue;
795 }
796 /*
797 * [ left .... middle ... target ... right ]
798 * => left := middle
799 */
800 left_idx = middle_idx;
801 }
802
803 idx = left_idx;
804
805 if (!sym_table[idx].skip)
806 sym_table[idx].count[counter]++;
807 else events--;
808}
809
810static void process_event(uint64_t ip, int counter)
811{
812 events++;
813
814 if (ip < min_ip || ip > max_ip) {
815 userspace_events++;
816 return;
817 }
818
819 record_ip(ip, counter);
820}
821
Ingo Molnar6f06ccb2009-04-20 15:22:22 +0200822static void process_options(int argc, char **argv)
Ingo Molnar07800602009-04-20 15:00:56 +0200823{
824 int error = 0, counter;
825
Ingo Molnar07800602009-04-20 15:00:56 +0200826 for (;;) {
827 int option_index = 0;
828 /** Options for getopt */
829 static struct option long_options[] = {
830 {"count", required_argument, NULL, 'c'},
831 {"cpu", required_argument, NULL, 'C'},
832 {"delay", required_argument, NULL, 'd'},
833 {"dump_symtab", no_argument, NULL, 'D'},
834 {"event", required_argument, NULL, 'e'},
835 {"filter", required_argument, NULL, 'f'},
836 {"group", required_argument, NULL, 'g'},
837 {"help", no_argument, NULL, 'h'},
838 {"nmi", required_argument, NULL, 'n'},
839 {"mmap_info", no_argument, NULL, 'M'},
840 {"mmap_pages", required_argument, NULL, 'm'},
841 {"munmap_info", no_argument, NULL, 'U'},
842 {"pid", required_argument, NULL, 'p'},
843 {"realtime", required_argument, NULL, 'r'},
844 {"scale", no_argument, NULL, 'l'},
845 {"symbol", required_argument, NULL, 's'},
846 {"stat", no_argument, NULL, 'S'},
847 {"vmlinux", required_argument, NULL, 'x'},
848 {"zero", no_argument, NULL, 'z'},
Peter Zijlstraf5456a62009-05-15 15:19:29 +0200849 {"freq", required_argument, NULL, 'F'},
Ingo Molnar07800602009-04-20 15:00:56 +0200850 {NULL, 0, NULL, 0 }
851 };
Peter Zijlstraf5456a62009-05-15 15:19:29 +0200852 int c = getopt_long(argc, argv, "+:ac:C:d:De:f:g:hln:m:p:r:s:Sx:zMUF:",
Ingo Molnar07800602009-04-20 15:00:56 +0200853 long_options, &option_index);
854 if (c == -1)
855 break;
856
857 switch (c) {
858 case 'a': system_wide = 1; break;
859 case 'c': default_interval = atoi(optarg); break;
860 case 'C':
861 /* CPU and PID are mutually exclusive */
862 if (tid != -1) {
863 printf("WARNING: CPU switch overriding PID\n");
864 sleep(1);
865 tid = -1;
866 }
867 profile_cpu = atoi(optarg); break;
868 case 'd': delay_secs = atoi(optarg); break;
869 case 'D': dump_symtab = 1; break;
870
871 case 'e': error = parse_events(optarg); break;
872
873 case 'f': count_filter = atoi(optarg); break;
874 case 'g': group = atoi(optarg); break;
875 case 'h': display_help(); break;
876 case 'l': scale = 1; break;
877 case 'n': nmi = atoi(optarg); break;
878 case 'p':
879 /* CPU and PID are mutually exclusive */
880 if (profile_cpu != -1) {
881 printf("WARNING: PID switch overriding CPU\n");
882 sleep(1);
883 profile_cpu = -1;
884 }
885 tid = atoi(optarg); break;
886 case 'r': realtime_prio = atoi(optarg); break;
887 case 's': sym_filter = strdup(optarg); break;
Ingo Molnar07800602009-04-20 15:00:56 +0200888 case 'x': vmlinux = strdup(optarg); break;
889 case 'z': zero = 1; break;
890 case 'm': mmap_pages = atoi(optarg); break;
891 case 'M': use_mmap = 1; break;
892 case 'U': use_munmap = 1; break;
Peter Zijlstraf5456a62009-05-15 15:19:29 +0200893 case 'F': freq = 1; default_interval = atoi(optarg); break;
Ingo Molnar07800602009-04-20 15:00:56 +0200894 default: error = 1; break;
895 }
896 }
897 if (error)
898 display_help();
899
900 if (!nr_counters) {
Ingo Molnarddcacfa2009-04-20 15:37:32 +0200901 nr_counters = 1;
902 event_id[0] = 0;
Ingo Molnar07800602009-04-20 15:00:56 +0200903 }
904
905 for (counter = 0; counter < nr_counters; counter++) {
906 if (event_count[counter])
907 continue;
908
909 event_count[counter] = default_interval;
910 }
911}
912
913struct mmap_data {
914 int counter;
915 void *base;
916 unsigned int mask;
917 unsigned int prev;
918};
919
920static unsigned int mmap_read_head(struct mmap_data *md)
921{
922 struct perf_counter_mmap_page *pc = md->base;
923 int head;
924
925 head = pc->data_head;
926 rmb();
927
928 return head;
929}
930
931struct timeval last_read, this_read;
932
933static void mmap_read(struct mmap_data *md)
934{
935 unsigned int head = mmap_read_head(md);
936 unsigned int old = md->prev;
937 unsigned char *data = md->base + page_size;
938 int diff;
939
940 gettimeofday(&this_read, NULL);
941
942 /*
943 * If we're further behind than half the buffer, there's a chance
944 * the writer will bite our tail and screw up the events under us.
945 *
946 * If we somehow ended up ahead of the head, we got messed up.
947 *
948 * In either case, truncate and restart at head.
949 */
950 diff = head - old;
951 if (diff > md->mask / 2 || diff < 0) {
952 struct timeval iv;
953 unsigned long msecs;
954
955 timersub(&this_read, &last_read, &iv);
956 msecs = iv.tv_sec*1000 + iv.tv_usec/1000;
957
958 fprintf(stderr, "WARNING: failed to keep up with mmap data."
959 " Last read %lu msecs ago.\n", msecs);
960
961 /*
962 * head points to a known good entry, start there.
963 */
964 old = head;
965 }
966
967 last_read = this_read;
968
969 for (; old != head;) {
970 struct ip_event {
971 struct perf_event_header header;
972 __u64 ip;
973 __u32 pid, tid;
974 };
975 struct mmap_event {
976 struct perf_event_header header;
977 __u32 pid, tid;
978 __u64 start;
979 __u64 len;
980 __u64 pgoff;
981 char filename[PATH_MAX];
982 };
983
984 typedef union event_union {
985 struct perf_event_header header;
986 struct ip_event ip;
987 struct mmap_event mmap;
988 } event_t;
989
990 event_t *event = (event_t *)&data[old & md->mask];
991
992 event_t event_copy;
993
Ingo Molnar6f06ccb2009-04-20 15:22:22 +0200994 size_t size = event->header.size;
Ingo Molnar07800602009-04-20 15:00:56 +0200995
996 /*
997 * Event straddles the mmap boundary -- header should always
998 * be inside due to u64 alignment of output.
999 */
1000 if ((old & md->mask) + size != ((old + size) & md->mask)) {
1001 unsigned int offset = old;
1002 unsigned int len = min(sizeof(*event), size), cpy;
1003 void *dst = &event_copy;
1004
1005 do {
1006 cpy = min(md->mask + 1 - (offset & md->mask), len);
1007 memcpy(dst, &data[offset & md->mask], cpy);
1008 offset += cpy;
1009 dst += cpy;
1010 len -= cpy;
1011 } while (len);
1012
1013 event = &event_copy;
1014 }
1015
1016 old += size;
1017
1018 if (event->header.misc & PERF_EVENT_MISC_OVERFLOW) {
1019 if (event->header.type & PERF_RECORD_IP)
1020 process_event(event->ip.ip, md->counter);
1021 } else {
1022 switch (event->header.type) {
1023 case PERF_EVENT_MMAP:
1024 case PERF_EVENT_MUNMAP:
1025 printf("%s: %Lu %Lu %Lu %s\n",
1026 event->header.type == PERF_EVENT_MMAP
1027 ? "mmap" : "munmap",
1028 event->mmap.start,
1029 event->mmap.len,
1030 event->mmap.pgoff,
1031 event->mmap.filename);
1032 break;
1033 }
1034 }
1035 }
1036
1037 md->prev = old;
1038}
1039
Mike Galbraithc2990a22009-05-24 08:35:49 +02001040static struct pollfd event_array[MAX_NR_CPUS * MAX_COUNTERS];
1041static struct mmap_data mmap_array[MAX_NR_CPUS][MAX_COUNTERS];
1042
Ingo Molnar6f06ccb2009-04-20 15:22:22 +02001043int cmd_top(int argc, char **argv, const char *prefix)
Ingo Molnar07800602009-04-20 15:00:56 +02001044{
Ingo Molnar07800602009-04-20 15:00:56 +02001045 struct perf_counter_hw_event hw_event;
1046 pthread_t thread;
1047 int i, counter, group_fd, nr_poll = 0;
1048 unsigned int cpu;
1049 int ret;
1050
1051 page_size = sysconf(_SC_PAGE_SIZE);
1052
1053 process_options(argc, argv);
1054
1055 nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
1056 assert(nr_cpus <= MAX_NR_CPUS);
1057 assert(nr_cpus >= 0);
1058
Ingo Molnar07800602009-04-20 15:00:56 +02001059 if (tid != -1 || profile_cpu != -1)
1060 nr_cpus = 1;
1061
1062 parse_symbols();
1063 if (vmlinux && sym_filter_entry)
1064 parse_vmlinux(vmlinux);
1065
1066 for (i = 0; i < nr_cpus; i++) {
1067 group_fd = -1;
1068 for (counter = 0; counter < nr_counters; counter++) {
1069
1070 cpu = profile_cpu;
1071 if (tid == -1 && profile_cpu == -1)
1072 cpu = i;
1073
1074 memset(&hw_event, 0, sizeof(hw_event));
1075 hw_event.config = event_id[counter];
1076 hw_event.irq_period = event_count[counter];
1077 hw_event.record_type = PERF_RECORD_IP | PERF_RECORD_TID;
1078 hw_event.nmi = nmi;
1079 hw_event.mmap = use_mmap;
1080 hw_event.munmap = use_munmap;
Peter Zijlstraf5456a62009-05-15 15:19:29 +02001081 hw_event.freq = freq;
Ingo Molnar07800602009-04-20 15:00:56 +02001082
1083 fd[i][counter] = sys_perf_counter_open(&hw_event, tid, cpu, group_fd, 0);
1084 if (fd[i][counter] < 0) {
1085 int err = errno;
1086 printf("kerneltop error: syscall returned with %d (%s)\n",
1087 fd[i][counter], strerror(err));
1088 if (err == EPERM)
1089 printf("Are you root?\n");
1090 exit(-1);
1091 }
1092 assert(fd[i][counter] >= 0);
1093 fcntl(fd[i][counter], F_SETFL, O_NONBLOCK);
1094
1095 /*
1096 * First counter acts as the group leader:
1097 */
1098 if (group && group_fd == -1)
1099 group_fd = fd[i][counter];
1100
1101 event_array[nr_poll].fd = fd[i][counter];
1102 event_array[nr_poll].events = POLLIN;
1103 nr_poll++;
1104
1105 mmap_array[i][counter].counter = counter;
1106 mmap_array[i][counter].prev = 0;
1107 mmap_array[i][counter].mask = mmap_pages*page_size - 1;
1108 mmap_array[i][counter].base = mmap(NULL, (mmap_pages+1)*page_size,
1109 PROT_READ, MAP_SHARED, fd[i][counter], 0);
1110 if (mmap_array[i][counter].base == MAP_FAILED) {
1111 printf("kerneltop error: failed to mmap with %d (%s)\n",
1112 errno, strerror(errno));
1113 exit(-1);
1114 }
1115 }
1116 }
1117
1118 if (pthread_create(&thread, NULL, display_thread, NULL)) {
1119 printf("Could not create display thread.\n");
1120 exit(-1);
1121 }
1122
1123 if (realtime_prio) {
1124 struct sched_param param;
1125
1126 param.sched_priority = realtime_prio;
1127 if (sched_setscheduler(0, SCHED_FIFO, &param)) {
1128 printf("Could not set realtime priority.\n");
1129 exit(-1);
1130 }
1131 }
1132
1133 while (1) {
1134 int hits = events;
1135
1136 for (i = 0; i < nr_cpus; i++) {
1137 for (counter = 0; counter < nr_counters; counter++)
1138 mmap_read(&mmap_array[i][counter]);
1139 }
1140
1141 if (hits == events)
1142 ret = poll(event_array, nr_poll, 100);
1143 }
1144
1145 return 0;
1146}