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