blob: 74021ac90f51d595de2f865377b266ccc2e97417 [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{
377 int i, printed;
378 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;
384 memcpy(tmp, sym_table, sizeof(sym_table[0])*sym_table_count);
385 qsort(tmp, sym_table_count, sizeof(tmp[0]), compare);
386
387 for (i = 0; i < sym_table_count && tmp[i].count[0]; i++)
388 sum_kevents += tmp[i].count[0];
389
390 write(1, CONSOLE_CLEAR, strlen(CONSOLE_CLEAR));
391
392 printf(
393"------------------------------------------------------------------------------\n");
394 printf( " KernelTop:%8.0f irqs/sec kernel:%4.1f%% [%s, ",
395 events_per_sec,
396 100.0 - (100.0*((events_per_sec-kevents_per_sec)/events_per_sec)),
397 nmi ? "NMI" : "IRQ");
398
399 if (nr_counters == 1)
400 printf("%d ", event_count[0]);
401
402 for (counter = 0; counter < nr_counters; counter++) {
403 if (counter)
404 printf("/");
405
406 printf("%s", event_name(counter));
407 }
408
409 printf( "], ");
410
411 if (tid != -1)
412 printf(" (tid: %d", tid);
413 else
414 printf(" (all");
415
416 if (profile_cpu != -1)
417 printf(", cpu: %d)\n", profile_cpu);
418 else {
419 if (tid != -1)
420 printf(")\n");
421 else
422 printf(", %d CPUs)\n", nr_cpus);
423 }
424
425 printf("------------------------------------------------------------------------------\n\n");
426
427 if (nr_counters == 1)
428 printf(" events pcnt");
429 else
430 printf(" weight events pcnt");
431
432 printf(" RIP kernel function\n"
433 " ______ ______ _____ ________________ _______________\n\n"
434 );
435
436 for (i = 0, printed = 0; i < sym_table_count; i++) {
437 float pcnt;
438 int count;
439
440 if (printed <= 18 && tmp[i].count[0] >= count_filter) {
441 pcnt = 100.0 - (100.0*((sum_kevents-tmp[i].count[0])/sum_kevents));
442
443 if (nr_counters == 1)
444 printf("%19.2f - %4.1f%% - %016llx : %s\n",
445 sym_weight(tmp + i),
446 pcnt, tmp[i].addr, tmp[i].sym);
447 else
448 printf("%8.1f %10ld - %4.1f%% - %016llx : %s\n",
449 sym_weight(tmp + i),
450 tmp[i].count[0],
451 pcnt, tmp[i].addr, tmp[i].sym);
452 printed++;
453 }
454 /*
455 * Add decay to the counts:
456 */
457 for (count = 0; count < nr_counters; count++)
458 sym_table[i].count[count] = zero ? 0 : sym_table[i].count[count] * 7 / 8;
459 }
460
461 if (sym_filter_entry)
462 show_details(sym_filter_entry);
463
464 {
465 struct pollfd stdin_poll = { .fd = 0, .events = POLLIN };
466
467 if (poll(&stdin_poll, 1, 0) == 1) {
468 printf("key pressed - exiting.\n");
469 exit(0);
470 }
471 }
472}
473
474static void *display_thread(void *arg)
475{
476 printf("KernelTop refresh period: %d seconds\n", delay_secs);
477
478 while (!sleep(delay_secs))
479 print_sym_table();
480
481 return NULL;
482}
483
484static int read_symbol(FILE *in, struct sym_entry *s)
485{
486 static int filter_match = 0;
487 char *sym, stype;
488 char str[500];
489 int rc, pos;
490
491 rc = fscanf(in, "%llx %c %499s", &s->addr, &stype, str);
492 if (rc == EOF)
493 return -1;
494
495 assert(rc == 3);
496
497 /* skip until end of line: */
498 pos = strlen(str);
499 do {
500 rc = fgetc(in);
501 if (rc == '\n' || rc == EOF || pos >= 499)
502 break;
503 str[pos] = rc;
504 pos++;
505 } while (1);
506 str[pos] = 0;
507
508 sym = str;
509
510 /* Filter out known duplicates and non-text symbols. */
511 if (!strcmp(sym, "_text"))
512 return 1;
513 if (!min_ip && !strcmp(sym, "_stext"))
514 return 1;
515 if (!strcmp(sym, "_etext") || !strcmp(sym, "_sinittext"))
516 return 1;
517 if (stype != 'T' && stype != 't')
518 return 1;
519 if (!strncmp("init_module", sym, 11) || !strncmp("cleanup_module", sym, 14))
520 return 1;
521 if (strstr(sym, "_text_start") || strstr(sym, "_text_end"))
522 return 1;
523
Erdem Aktas82afae62009-05-10 02:13:19 -0400524 s->sym = malloc(strlen(str)+1);
Ingo Molnar07800602009-04-20 15:00:56 +0200525 assert(s->sym);
526
527 strcpy((char *)s->sym, str);
528 s->skip = 0;
529
530 /* Tag events to be skipped. */
531 if (!strcmp("default_idle", s->sym) || !strcmp("cpu_idle", s->sym))
532 s->skip = 1;
533 else if (!strcmp("enter_idle", s->sym) || !strcmp("exit_idle", s->sym))
534 s->skip = 1;
535 else if (!strcmp("mwait_idle", s->sym))
536 s->skip = 1;
537
538 if (filter_match == 1) {
539 filter_end = s->addr;
540 filter_match = -1;
541 if (filter_end - filter_start > 10000) {
542 printf("hm, too large filter symbol <%s> - skipping.\n",
543 sym_filter);
544 printf("symbol filter start: %016lx\n", filter_start);
545 printf(" end: %016lx\n", filter_end);
546 filter_end = filter_start = 0;
547 sym_filter = NULL;
548 sleep(1);
549 }
550 }
551 if (filter_match == 0 && sym_filter && !strcmp(s->sym, sym_filter)) {
552 filter_match = 1;
553 filter_start = s->addr;
554 }
555
556 return 0;
557}
558
Ingo Molnarddcacfa2009-04-20 15:37:32 +0200559static int compare_addr(const void *__sym1, const void *__sym2)
Ingo Molnar07800602009-04-20 15:00:56 +0200560{
561 const struct sym_entry *sym1 = __sym1, *sym2 = __sym2;
562
563 return sym1->addr > sym2->addr;
564}
565
566static void sort_symbol_table(void)
567{
568 int i, dups;
569
570 do {
571 qsort(sym_table, sym_table_count, sizeof(sym_table[0]), compare_addr);
572 for (i = 0, dups = 0; i < sym_table_count; i++) {
573 if (sym_table[i].addr == sym_table[i+1].addr) {
574 sym_table[i+1].addr = -1ll;
575 dups++;
576 }
577 }
578 sym_table_count -= dups;
579 } while(dups);
580}
581
582static void parse_symbols(void)
583{
584 struct sym_entry *last;
585
586 FILE *kallsyms = fopen("/proc/kallsyms", "r");
587
588 if (!kallsyms) {
589 printf("Could not open /proc/kallsyms - no CONFIG_KALLSYMS_ALL=y?\n");
590 exit(-1);
591 }
592
593 while (!feof(kallsyms)) {
594 if (read_symbol(kallsyms, &sym_table[sym_table_count]) == 0) {
595 sym_table_count++;
596 assert(sym_table_count <= MAX_SYMS);
597 }
598 }
599
600 sort_symbol_table();
601 min_ip = sym_table[0].addr;
602 max_ip = sym_table[sym_table_count-1].addr;
603 last = sym_table + sym_table_count++;
604
605 last->addr = -1ll;
606 last->sym = "<end>";
607
608 if (filter_end) {
609 int count;
610 for (count=0; count < sym_table_count; count ++) {
611 if (!strcmp(sym_table[count].sym, sym_filter)) {
612 sym_filter_entry = &sym_table[count];
613 break;
614 }
615 }
616 }
617 if (dump_symtab) {
618 int i;
619
620 for (i = 0; i < sym_table_count; i++)
621 fprintf(stderr, "%llx %s\n",
622 sym_table[i].addr, sym_table[i].sym);
623 }
624}
625
626/*
627 * Source lines
628 */
629
630static void parse_vmlinux(char *filename)
631{
632 FILE *file;
633 char command[PATH_MAX*2];
634 if (!filename)
635 return;
636
637 sprintf(command, "objdump --start-address=0x%016lx --stop-address=0x%016lx -dS %s", filter_start, filter_end, filename);
638
639 file = popen(command, "r");
640 if (!file)
641 return;
642
643 lines_tail = &lines;
644 while (!feof(file)) {
645 struct source_line *src;
646 size_t dummy = 0;
647 char *c;
648
649 src = malloc(sizeof(struct source_line));
650 assert(src != NULL);
651 memset(src, 0, sizeof(struct source_line));
652
653 if (getline(&src->line, &dummy, file) < 0)
654 break;
655 if (!src->line)
656 break;
657
658 c = strchr(src->line, '\n');
659 if (c)
660 *c = 0;
661
662 src->next = NULL;
663 *lines_tail = src;
664 lines_tail = &src->next;
665
666 if (strlen(src->line)>8 && src->line[8] == ':')
667 src->EIP = strtoull(src->line, NULL, 16);
668 if (strlen(src->line)>8 && src->line[16] == ':')
669 src->EIP = strtoull(src->line, NULL, 16);
670 }
671 pclose(file);
672}
673
674static void record_precise_ip(uint64_t ip)
675{
676 struct source_line *line;
677
678 for (line = lines; line; line = line->next) {
679 if (line->EIP == ip)
680 line->count++;
681 if (line->EIP > ip)
682 break;
683 }
684}
685
686static void lookup_sym_in_vmlinux(struct sym_entry *sym)
687{
688 struct source_line *line;
689 char pattern[PATH_MAX];
690 sprintf(pattern, "<%s>:", sym->sym);
691
692 for (line = lines; line; line = line->next) {
693 if (strstr(line->line, pattern)) {
694 sym->source = line;
695 break;
696 }
697 }
698}
699
700static void show_lines(struct source_line *line_queue, int line_queue_count)
701{
702 int i;
703 struct source_line *line;
704
705 line = line_queue;
706 for (i = 0; i < line_queue_count; i++) {
707 printf("%8li\t%s\n", line->count, line->line);
708 line = line->next;
709 }
710}
711
712#define TRACE_COUNT 3
713
714static void show_details(struct sym_entry *sym)
715{
716 struct source_line *line;
717 struct source_line *line_queue = NULL;
718 int displayed = 0;
719 int line_queue_count = 0;
720
721 if (!sym->source)
722 lookup_sym_in_vmlinux(sym);
723 if (!sym->source)
724 return;
725
726 printf("Showing details for %s\n", sym->sym);
727
728 line = sym->source;
729 while (line) {
730 if (displayed && strstr(line->line, ">:"))
731 break;
732
733 if (!line_queue_count)
734 line_queue = line;
735 line_queue_count ++;
736
737 if (line->count >= count_filter) {
738 show_lines(line_queue, line_queue_count);
739 line_queue_count = 0;
740 line_queue = NULL;
741 } else if (line_queue_count > TRACE_COUNT) {
742 line_queue = line_queue->next;
743 line_queue_count --;
744 }
745
746 line->count = 0;
747 displayed++;
748 if (displayed > 300)
749 break;
750 line = line->next;
751 }
752}
753
754/*
755 * Binary search in the histogram table and record the hit:
756 */
757static void record_ip(uint64_t ip, int counter)
758{
759 int left_idx, middle_idx, right_idx, idx;
760 unsigned long left, middle, right;
761
762 record_precise_ip(ip);
763
764 left_idx = 0;
765 right_idx = sym_table_count-1;
766 assert(ip <= max_ip && ip >= min_ip);
767
768 while (left_idx + 1 < right_idx) {
769 middle_idx = (left_idx + right_idx) / 2;
770
771 left = sym_table[ left_idx].addr;
772 middle = sym_table[middle_idx].addr;
773 right = sym_table[ right_idx].addr;
774
775 if (!(left <= middle && middle <= right)) {
776 printf("%016lx...\n%016lx...\n%016lx\n", left, middle, right);
777 printf("%d %d %d\n", left_idx, middle_idx, right_idx);
778 }
779 assert(left <= middle && middle <= right);
780 if (!(left <= ip && ip <= right)) {
781 printf(" left: %016lx\n", left);
782 printf(" ip: %016lx\n", (unsigned long)ip);
783 printf("right: %016lx\n", right);
784 }
785 assert(left <= ip && ip <= right);
786 /*
787 * [ left .... target .... middle .... right ]
788 * => right := middle
789 */
790 if (ip < middle) {
791 right_idx = middle_idx;
792 continue;
793 }
794 /*
795 * [ left .... middle ... target ... right ]
796 * => left := middle
797 */
798 left_idx = middle_idx;
799 }
800
801 idx = left_idx;
802
803 if (!sym_table[idx].skip)
804 sym_table[idx].count[counter]++;
805 else events--;
806}
807
808static void process_event(uint64_t ip, int counter)
809{
810 events++;
811
812 if (ip < min_ip || ip > max_ip) {
813 userspace_events++;
814 return;
815 }
816
817 record_ip(ip, counter);
818}
819
Ingo Molnar6f06ccb2009-04-20 15:22:22 +0200820static void process_options(int argc, char **argv)
Ingo Molnar07800602009-04-20 15:00:56 +0200821{
822 int error = 0, counter;
823
Ingo Molnar07800602009-04-20 15:00:56 +0200824 for (;;) {
825 int option_index = 0;
826 /** Options for getopt */
827 static struct option long_options[] = {
828 {"count", required_argument, NULL, 'c'},
829 {"cpu", required_argument, NULL, 'C'},
830 {"delay", required_argument, NULL, 'd'},
831 {"dump_symtab", no_argument, NULL, 'D'},
832 {"event", required_argument, NULL, 'e'},
833 {"filter", required_argument, NULL, 'f'},
834 {"group", required_argument, NULL, 'g'},
835 {"help", no_argument, NULL, 'h'},
836 {"nmi", required_argument, NULL, 'n'},
837 {"mmap_info", no_argument, NULL, 'M'},
838 {"mmap_pages", required_argument, NULL, 'm'},
839 {"munmap_info", no_argument, NULL, 'U'},
840 {"pid", required_argument, NULL, 'p'},
841 {"realtime", required_argument, NULL, 'r'},
842 {"scale", no_argument, NULL, 'l'},
843 {"symbol", required_argument, NULL, 's'},
844 {"stat", no_argument, NULL, 'S'},
845 {"vmlinux", required_argument, NULL, 'x'},
846 {"zero", no_argument, NULL, 'z'},
Peter Zijlstraf5456a62009-05-15 15:19:29 +0200847 {"freq", required_argument, NULL, 'F'},
Ingo Molnar07800602009-04-20 15:00:56 +0200848 {NULL, 0, NULL, 0 }
849 };
Peter Zijlstraf5456a62009-05-15 15:19:29 +0200850 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 +0200851 long_options, &option_index);
852 if (c == -1)
853 break;
854
855 switch (c) {
856 case 'a': system_wide = 1; break;
857 case 'c': default_interval = atoi(optarg); break;
858 case 'C':
859 /* CPU and PID are mutually exclusive */
860 if (tid != -1) {
861 printf("WARNING: CPU switch overriding PID\n");
862 sleep(1);
863 tid = -1;
864 }
865 profile_cpu = atoi(optarg); break;
866 case 'd': delay_secs = atoi(optarg); break;
867 case 'D': dump_symtab = 1; break;
868
869 case 'e': error = parse_events(optarg); break;
870
871 case 'f': count_filter = atoi(optarg); break;
872 case 'g': group = atoi(optarg); break;
873 case 'h': display_help(); break;
874 case 'l': scale = 1; break;
875 case 'n': nmi = atoi(optarg); break;
876 case 'p':
877 /* CPU and PID are mutually exclusive */
878 if (profile_cpu != -1) {
879 printf("WARNING: PID switch overriding CPU\n");
880 sleep(1);
881 profile_cpu = -1;
882 }
883 tid = atoi(optarg); break;
884 case 'r': realtime_prio = atoi(optarg); break;
885 case 's': sym_filter = strdup(optarg); break;
Ingo Molnar07800602009-04-20 15:00:56 +0200886 case 'x': vmlinux = strdup(optarg); break;
887 case 'z': zero = 1; break;
888 case 'm': mmap_pages = atoi(optarg); break;
889 case 'M': use_mmap = 1; break;
890 case 'U': use_munmap = 1; break;
Peter Zijlstraf5456a62009-05-15 15:19:29 +0200891 case 'F': freq = 1; default_interval = atoi(optarg); break;
Ingo Molnar07800602009-04-20 15:00:56 +0200892 default: error = 1; break;
893 }
894 }
895 if (error)
896 display_help();
897
898 if (!nr_counters) {
Ingo Molnarddcacfa2009-04-20 15:37:32 +0200899 nr_counters = 1;
900 event_id[0] = 0;
Ingo Molnar07800602009-04-20 15:00:56 +0200901 }
902
903 for (counter = 0; counter < nr_counters; counter++) {
904 if (event_count[counter])
905 continue;
906
907 event_count[counter] = default_interval;
908 }
909}
910
911struct mmap_data {
912 int counter;
913 void *base;
914 unsigned int mask;
915 unsigned int prev;
916};
917
918static unsigned int mmap_read_head(struct mmap_data *md)
919{
920 struct perf_counter_mmap_page *pc = md->base;
921 int head;
922
923 head = pc->data_head;
924 rmb();
925
926 return head;
927}
928
929struct timeval last_read, this_read;
930
931static void mmap_read(struct mmap_data *md)
932{
933 unsigned int head = mmap_read_head(md);
934 unsigned int old = md->prev;
935 unsigned char *data = md->base + page_size;
936 int diff;
937
938 gettimeofday(&this_read, NULL);
939
940 /*
941 * If we're further behind than half the buffer, there's a chance
942 * the writer will bite our tail and screw up the events under us.
943 *
944 * If we somehow ended up ahead of the head, we got messed up.
945 *
946 * In either case, truncate and restart at head.
947 */
948 diff = head - old;
949 if (diff > md->mask / 2 || diff < 0) {
950 struct timeval iv;
951 unsigned long msecs;
952
953 timersub(&this_read, &last_read, &iv);
954 msecs = iv.tv_sec*1000 + iv.tv_usec/1000;
955
956 fprintf(stderr, "WARNING: failed to keep up with mmap data."
957 " Last read %lu msecs ago.\n", msecs);
958
959 /*
960 * head points to a known good entry, start there.
961 */
962 old = head;
963 }
964
965 last_read = this_read;
966
967 for (; old != head;) {
968 struct ip_event {
969 struct perf_event_header header;
970 __u64 ip;
971 __u32 pid, tid;
972 };
973 struct mmap_event {
974 struct perf_event_header header;
975 __u32 pid, tid;
976 __u64 start;
977 __u64 len;
978 __u64 pgoff;
979 char filename[PATH_MAX];
980 };
981
982 typedef union event_union {
983 struct perf_event_header header;
984 struct ip_event ip;
985 struct mmap_event mmap;
986 } event_t;
987
988 event_t *event = (event_t *)&data[old & md->mask];
989
990 event_t event_copy;
991
Ingo Molnar6f06ccb2009-04-20 15:22:22 +0200992 size_t size = event->header.size;
Ingo Molnar07800602009-04-20 15:00:56 +0200993
994 /*
995 * Event straddles the mmap boundary -- header should always
996 * be inside due to u64 alignment of output.
997 */
998 if ((old & md->mask) + size != ((old + size) & md->mask)) {
999 unsigned int offset = old;
1000 unsigned int len = min(sizeof(*event), size), cpy;
1001 void *dst = &event_copy;
1002
1003 do {
1004 cpy = min(md->mask + 1 - (offset & md->mask), len);
1005 memcpy(dst, &data[offset & md->mask], cpy);
1006 offset += cpy;
1007 dst += cpy;
1008 len -= cpy;
1009 } while (len);
1010
1011 event = &event_copy;
1012 }
1013
1014 old += size;
1015
1016 if (event->header.misc & PERF_EVENT_MISC_OVERFLOW) {
1017 if (event->header.type & PERF_RECORD_IP)
1018 process_event(event->ip.ip, md->counter);
1019 } else {
1020 switch (event->header.type) {
1021 case PERF_EVENT_MMAP:
1022 case PERF_EVENT_MUNMAP:
1023 printf("%s: %Lu %Lu %Lu %s\n",
1024 event->header.type == PERF_EVENT_MMAP
1025 ? "mmap" : "munmap",
1026 event->mmap.start,
1027 event->mmap.len,
1028 event->mmap.pgoff,
1029 event->mmap.filename);
1030 break;
1031 }
1032 }
1033 }
1034
1035 md->prev = old;
1036}
1037
Mike Galbraithc2990a22009-05-24 08:35:49 +02001038static struct pollfd event_array[MAX_NR_CPUS * MAX_COUNTERS];
1039static struct mmap_data mmap_array[MAX_NR_CPUS][MAX_COUNTERS];
1040
Ingo Molnar6f06ccb2009-04-20 15:22:22 +02001041int cmd_top(int argc, char **argv, const char *prefix)
Ingo Molnar07800602009-04-20 15:00:56 +02001042{
Ingo Molnar07800602009-04-20 15:00:56 +02001043 struct perf_counter_hw_event hw_event;
1044 pthread_t thread;
1045 int i, counter, group_fd, nr_poll = 0;
1046 unsigned int cpu;
1047 int ret;
1048
1049 page_size = sysconf(_SC_PAGE_SIZE);
1050
1051 process_options(argc, argv);
1052
1053 nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
1054 assert(nr_cpus <= MAX_NR_CPUS);
1055 assert(nr_cpus >= 0);
1056
Ingo Molnar07800602009-04-20 15:00:56 +02001057 if (tid != -1 || profile_cpu != -1)
1058 nr_cpus = 1;
1059
1060 parse_symbols();
1061 if (vmlinux && sym_filter_entry)
1062 parse_vmlinux(vmlinux);
1063
1064 for (i = 0; i < nr_cpus; i++) {
1065 group_fd = -1;
1066 for (counter = 0; counter < nr_counters; counter++) {
1067
1068 cpu = profile_cpu;
1069 if (tid == -1 && profile_cpu == -1)
1070 cpu = i;
1071
1072 memset(&hw_event, 0, sizeof(hw_event));
1073 hw_event.config = event_id[counter];
1074 hw_event.irq_period = event_count[counter];
1075 hw_event.record_type = PERF_RECORD_IP | PERF_RECORD_TID;
1076 hw_event.nmi = nmi;
1077 hw_event.mmap = use_mmap;
1078 hw_event.munmap = use_munmap;
Peter Zijlstraf5456a62009-05-15 15:19:29 +02001079 hw_event.freq = freq;
Ingo Molnar07800602009-04-20 15:00:56 +02001080
1081 fd[i][counter] = sys_perf_counter_open(&hw_event, tid, cpu, group_fd, 0);
1082 if (fd[i][counter] < 0) {
1083 int err = errno;
1084 printf("kerneltop error: syscall returned with %d (%s)\n",
1085 fd[i][counter], strerror(err));
1086 if (err == EPERM)
1087 printf("Are you root?\n");
1088 exit(-1);
1089 }
1090 assert(fd[i][counter] >= 0);
1091 fcntl(fd[i][counter], F_SETFL, O_NONBLOCK);
1092
1093 /*
1094 * First counter acts as the group leader:
1095 */
1096 if (group && group_fd == -1)
1097 group_fd = fd[i][counter];
1098
1099 event_array[nr_poll].fd = fd[i][counter];
1100 event_array[nr_poll].events = POLLIN;
1101 nr_poll++;
1102
1103 mmap_array[i][counter].counter = counter;
1104 mmap_array[i][counter].prev = 0;
1105 mmap_array[i][counter].mask = mmap_pages*page_size - 1;
1106 mmap_array[i][counter].base = mmap(NULL, (mmap_pages+1)*page_size,
1107 PROT_READ, MAP_SHARED, fd[i][counter], 0);
1108 if (mmap_array[i][counter].base == MAP_FAILED) {
1109 printf("kerneltop error: failed to mmap with %d (%s)\n",
1110 errno, strerror(errno));
1111 exit(-1);
1112 }
1113 }
1114 }
1115
1116 if (pthread_create(&thread, NULL, display_thread, NULL)) {
1117 printf("Could not create display thread.\n");
1118 exit(-1);
1119 }
1120
1121 if (realtime_prio) {
1122 struct sched_param param;
1123
1124 param.sched_priority = realtime_prio;
1125 if (sched_setscheduler(0, SCHED_FIFO, &param)) {
1126 printf("Could not set realtime priority.\n");
1127 exit(-1);
1128 }
1129 }
1130
1131 while (1) {
1132 int hits = events;
1133
1134 for (i = 0; i < nr_cpus; i++) {
1135 for (counter = 0; counter < nr_counters; counter++)
1136 mmap_read(&mmap_array[i][counter]);
1137 }
1138
1139 if (hits == events)
1140 ret = poll(event_array, nr_poll, 100);
1141 }
1142
1143 return 0;
1144}