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