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