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