blob: 133eb79493211ed5fb318b397da921ac84b0c718 [file] [log] [blame]
rjw1f884582022-01-06 17:20:42 +08001/*
2 * builtin-top.c
3 *
4 * Builtin top command: Display a continuously updated profile of
5 * any workload, CPU or specific PID.
6 *
7 * Copyright (C) 2008, Red Hat Inc, Ingo Molnar <mingo@redhat.com>
8 * 2011, Red Hat Inc, Arnaldo Carvalho de Melo <acme@redhat.com>
9 *
10 * Improvements and fixes by:
11 *
12 * Arjan van de Ven <arjan@linux.intel.com>
13 * Yanmin Zhang <yanmin.zhang@intel.com>
14 * Wu Fengguang <fengguang.wu@intel.com>
15 * Mike Galbraith <efault@gmx.de>
16 * Paul Mackerras <paulus@samba.org>
17 *
18 * Released under the GPL v2. (and only v2, not any later version)
19 */
20#include "builtin.h"
21
22#include "perf.h"
23
24#include "util/annotate.h"
25#include "util/config.h"
26#include "util/color.h"
27#include "util/drv_configs.h"
28#include "util/evlist.h"
29#include "util/evsel.h"
30#include "util/event.h"
31#include "util/machine.h"
32#include "util/session.h"
33#include "util/symbol.h"
34#include "util/thread.h"
35#include "util/thread_map.h"
36#include "util/top.h"
37#include <linux/rbtree.h>
38#include <subcmd/parse-options.h>
39#include "util/parse-events.h"
40#include "util/cpumap.h"
41#include "util/xyarray.h"
42#include "util/sort.h"
43#include "util/term.h"
44#include "util/intlist.h"
45#include "util/parse-branch-options.h"
46#include "arch/common.h"
47
48#include "util/debug.h"
49
50#include <assert.h>
51#include <elf.h>
52#include <fcntl.h>
53
54#include <stdio.h>
55#include <termios.h>
56#include <unistd.h>
57#include <inttypes.h>
58
59#include <errno.h>
60#include <time.h>
61#include <sched.h>
62#include <signal.h>
63
64#include <sys/syscall.h>
65#include <sys/ioctl.h>
66#include <poll.h>
67#include <sys/prctl.h>
68#include <sys/wait.h>
69#include <sys/uio.h>
70#include <sys/utsname.h>
71#include <sys/mman.h>
72
73#include <linux/stringify.h>
74#include <linux/time64.h>
75#include <linux/types.h>
76
77#include "sane_ctype.h"
78
79static volatile int done;
80static volatile int resize;
81
82#define HEADER_LINE_NR 5
83
84static void perf_top__update_print_entries(struct perf_top *top)
85{
86 top->print_entries = top->winsize.ws_row - HEADER_LINE_NR;
87}
88
89static void perf_top__sig_winch(int sig __maybe_unused,
90 siginfo_t *info __maybe_unused, void *arg __maybe_unused)
91{
92 resize = 1;
93}
94
95static void perf_top__resize(struct perf_top *top)
96{
97 get_term_dimensions(&top->winsize);
98 perf_top__update_print_entries(top);
99}
100
101static int perf_top__parse_source(struct perf_top *top, struct hist_entry *he)
102{
103 struct symbol *sym;
104 struct annotation *notes;
105 struct map *map;
106 int err = -1;
107
108 if (!he || !he->ms.sym)
109 return -1;
110
111 sym = he->ms.sym;
112 map = he->ms.map;
113
114 /*
115 * We can't annotate with just /proc/kallsyms
116 */
117 if (map->dso->symtab_type == DSO_BINARY_TYPE__KALLSYMS &&
118 !dso__is_kcore(map->dso)) {
119 pr_err("Can't annotate %s: No vmlinux file was found in the "
120 "path\n", sym->name);
121 sleep(1);
122 return -1;
123 }
124
125 notes = symbol__annotation(sym);
126 if (notes->src != NULL) {
127 pthread_mutex_lock(&notes->lock);
128 goto out_assign;
129 }
130
131 pthread_mutex_lock(&notes->lock);
132
133 if (symbol__alloc_hist(sym) < 0) {
134 pthread_mutex_unlock(&notes->lock);
135 pr_err("Not enough memory for annotating '%s' symbol!\n",
136 sym->name);
137 sleep(1);
138 return err;
139 }
140
141 err = symbol__disassemble(sym, map, NULL, 0, NULL, NULL);
142 if (err == 0) {
143out_assign:
144 top->sym_filter_entry = he;
145 } else {
146 char msg[BUFSIZ];
147 symbol__strerror_disassemble(sym, map, err, msg, sizeof(msg));
148 pr_err("Couldn't annotate %s: %s\n", sym->name, msg);
149 }
150
151 pthread_mutex_unlock(&notes->lock);
152 return err;
153}
154
155static void __zero_source_counters(struct hist_entry *he)
156{
157 struct symbol *sym = he->ms.sym;
158 symbol__annotate_zero_histograms(sym);
159}
160
161static void ui__warn_map_erange(struct map *map, struct symbol *sym, u64 ip)
162{
163 struct utsname uts;
164 int err = uname(&uts);
165
166 ui__warning("Out of bounds address found:\n\n"
167 "Addr: %" PRIx64 "\n"
168 "DSO: %s %c\n"
169 "Map: %" PRIx64 "-%" PRIx64 "\n"
170 "Symbol: %" PRIx64 "-%" PRIx64 " %c %s\n"
171 "Arch: %s\n"
172 "Kernel: %s\n"
173 "Tools: %s\n\n"
174 "Not all samples will be on the annotation output.\n\n"
175 "Please report to linux-kernel@vger.kernel.org\n",
176 ip, map->dso->long_name, dso__symtab_origin(map->dso),
177 map->start, map->end, sym->start, sym->end,
178 sym->binding == STB_GLOBAL ? 'g' :
179 sym->binding == STB_LOCAL ? 'l' : 'w', sym->name,
180 err ? "[unknown]" : uts.machine,
181 err ? "[unknown]" : uts.release, perf_version_string);
182 if (use_browser <= 0)
183 sleep(5);
184
185 map->erange_warned = true;
186}
187
188static void perf_top__record_precise_ip(struct perf_top *top,
189 struct hist_entry *he,
190 struct perf_sample *sample,
191 int counter, u64 ip)
192{
193 struct annotation *notes;
194 struct symbol *sym = he->ms.sym;
195 int err = 0;
196
197 if (sym == NULL || (use_browser == 0 &&
198 (top->sym_filter_entry == NULL ||
199 top->sym_filter_entry->ms.sym != sym)))
200 return;
201
202 notes = symbol__annotation(sym);
203
204 if (pthread_mutex_trylock(&notes->lock))
205 return;
206
207 err = hist_entry__inc_addr_samples(he, sample, counter, ip);
208
209 pthread_mutex_unlock(&notes->lock);
210
211 if (unlikely(err)) {
212 /*
213 * This function is now called with he->hists->lock held.
214 * Release it before going to sleep.
215 */
216 pthread_mutex_unlock(&he->hists->lock);
217
218 if (err == -ERANGE && !he->ms.map->erange_warned)
219 ui__warn_map_erange(he->ms.map, sym, ip);
220 else if (err == -ENOMEM) {
221 pr_err("Not enough memory for annotating '%s' symbol!\n",
222 sym->name);
223 sleep(1);
224 }
225
226 pthread_mutex_lock(&he->hists->lock);
227 }
228}
229
230static void perf_top__show_details(struct perf_top *top)
231{
232 struct hist_entry *he = top->sym_filter_entry;
233 struct annotation *notes;
234 struct symbol *symbol;
235 int more;
236
237 if (!he)
238 return;
239
240 symbol = he->ms.sym;
241 notes = symbol__annotation(symbol);
242
243 pthread_mutex_lock(&notes->lock);
244
245 if (notes->src == NULL)
246 goto out_unlock;
247
248 printf("Showing %s for %s\n", perf_evsel__name(top->sym_evsel), symbol->name);
249 printf(" Events Pcnt (>=%d%%)\n", top->sym_pcnt_filter);
250
251 more = symbol__annotate_printf(symbol, he->ms.map, top->sym_evsel,
252 0, top->sym_pcnt_filter, top->print_entries, 4);
253
254 if (top->evlist->enabled) {
255 if (top->zero)
256 symbol__annotate_zero_histogram(symbol, top->sym_evsel->idx);
257 else
258 symbol__annotate_decay_histogram(symbol, top->sym_evsel->idx);
259 }
260 if (more != 0)
261 printf("%d lines not displayed, maybe increase display entries [e]\n", more);
262out_unlock:
263 pthread_mutex_unlock(&notes->lock);
264}
265
266static void perf_top__print_sym_table(struct perf_top *top)
267{
268 char bf[160];
269 int printed = 0;
270 const int win_width = top->winsize.ws_col - 1;
271 struct perf_evsel *evsel = top->sym_evsel;
272 struct hists *hists = evsel__hists(evsel);
273
274 puts(CONSOLE_CLEAR);
275
276 perf_top__header_snprintf(top, bf, sizeof(bf));
277 printf("%s\n", bf);
278
279 perf_top__reset_sample_counters(top);
280
281 printf("%-*.*s\n", win_width, win_width, graph_dotted_line);
282
283 if (hists->stats.nr_lost_warned !=
284 hists->stats.nr_events[PERF_RECORD_LOST]) {
285 hists->stats.nr_lost_warned =
286 hists->stats.nr_events[PERF_RECORD_LOST];
287 color_fprintf(stdout, PERF_COLOR_RED,
288 "WARNING: LOST %d chunks, Check IO/CPU overload",
289 hists->stats.nr_lost_warned);
290 ++printed;
291 }
292
293 if (top->sym_filter_entry) {
294 perf_top__show_details(top);
295 return;
296 }
297
298 if (top->evlist->enabled) {
299 if (top->zero) {
300 hists__delete_entries(hists);
301 } else {
302 hists__decay_entries(hists, top->hide_user_symbols,
303 top->hide_kernel_symbols);
304 }
305 }
306
307 hists__collapse_resort(hists, NULL);
308 perf_evsel__output_resort(evsel, NULL);
309
310 hists__output_recalc_col_len(hists, top->print_entries - printed);
311 putchar('\n');
312 hists__fprintf(hists, false, top->print_entries - printed, win_width,
313 top->min_percent, stdout, symbol_conf.use_callchain);
314}
315
316static void prompt_integer(int *target, const char *msg)
317{
318 char *buf = malloc(0), *p;
319 size_t dummy = 0;
320 int tmp;
321
322 fprintf(stdout, "\n%s: ", msg);
323 if (getline(&buf, &dummy, stdin) < 0)
324 return;
325
326 p = strchr(buf, '\n');
327 if (p)
328 *p = 0;
329
330 p = buf;
331 while(*p) {
332 if (!isdigit(*p))
333 goto out_free;
334 p++;
335 }
336 tmp = strtoul(buf, NULL, 10);
337 *target = tmp;
338out_free:
339 free(buf);
340}
341
342static void prompt_percent(int *target, const char *msg)
343{
344 int tmp = 0;
345
346 prompt_integer(&tmp, msg);
347 if (tmp >= 0 && tmp <= 100)
348 *target = tmp;
349}
350
351static void perf_top__prompt_symbol(struct perf_top *top, const char *msg)
352{
353 char *buf = malloc(0), *p;
354 struct hist_entry *syme = top->sym_filter_entry, *n, *found = NULL;
355 struct hists *hists = evsel__hists(top->sym_evsel);
356 struct rb_node *next;
357 size_t dummy = 0;
358
359 /* zero counters of active symbol */
360 if (syme) {
361 __zero_source_counters(syme);
362 top->sym_filter_entry = NULL;
363 }
364
365 fprintf(stdout, "\n%s: ", msg);
366 if (getline(&buf, &dummy, stdin) < 0)
367 goto out_free;
368
369 p = strchr(buf, '\n');
370 if (p)
371 *p = 0;
372
373 next = rb_first(&hists->entries);
374 while (next) {
375 n = rb_entry(next, struct hist_entry, rb_node);
376 if (n->ms.sym && !strcmp(buf, n->ms.sym->name)) {
377 found = n;
378 break;
379 }
380 next = rb_next(&n->rb_node);
381 }
382
383 if (!found) {
384 fprintf(stderr, "Sorry, %s is not active.\n", buf);
385 sleep(1);
386 } else
387 perf_top__parse_source(top, found);
388
389out_free:
390 free(buf);
391}
392
393static void perf_top__print_mapped_keys(struct perf_top *top)
394{
395 char *name = NULL;
396
397 if (top->sym_filter_entry) {
398 struct symbol *sym = top->sym_filter_entry->ms.sym;
399 name = sym->name;
400 }
401
402 fprintf(stdout, "\nMapped keys:\n");
403 fprintf(stdout, "\t[d] display refresh delay. \t(%d)\n", top->delay_secs);
404 fprintf(stdout, "\t[e] display entries (lines). \t(%d)\n", top->print_entries);
405
406 if (top->evlist->nr_entries > 1)
407 fprintf(stdout, "\t[E] active event counter. \t(%s)\n", perf_evsel__name(top->sym_evsel));
408
409 fprintf(stdout, "\t[f] profile display filter (count). \t(%d)\n", top->count_filter);
410
411 fprintf(stdout, "\t[F] annotate display filter (percent). \t(%d%%)\n", top->sym_pcnt_filter);
412 fprintf(stdout, "\t[s] annotate symbol. \t(%s)\n", name?: "NULL");
413 fprintf(stdout, "\t[S] stop annotation.\n");
414
415 fprintf(stdout,
416 "\t[K] hide kernel_symbols symbols. \t(%s)\n",
417 top->hide_kernel_symbols ? "yes" : "no");
418 fprintf(stdout,
419 "\t[U] hide user symbols. \t(%s)\n",
420 top->hide_user_symbols ? "yes" : "no");
421 fprintf(stdout, "\t[z] toggle sample zeroing. \t(%d)\n", top->zero ? 1 : 0);
422 fprintf(stdout, "\t[qQ] quit.\n");
423}
424
425static int perf_top__key_mapped(struct perf_top *top, int c)
426{
427 switch (c) {
428 case 'd':
429 case 'e':
430 case 'f':
431 case 'z':
432 case 'q':
433 case 'Q':
434 case 'K':
435 case 'U':
436 case 'F':
437 case 's':
438 case 'S':
439 return 1;
440 case 'E':
441 return top->evlist->nr_entries > 1 ? 1 : 0;
442 default:
443 break;
444 }
445
446 return 0;
447}
448
449static bool perf_top__handle_keypress(struct perf_top *top, int c)
450{
451 bool ret = true;
452
453 if (!perf_top__key_mapped(top, c)) {
454 struct pollfd stdin_poll = { .fd = 0, .events = POLLIN };
455 struct termios save;
456
457 perf_top__print_mapped_keys(top);
458 fprintf(stdout, "\nEnter selection, or unmapped key to continue: ");
459 fflush(stdout);
460
461 set_term_quiet_input(&save);
462
463 poll(&stdin_poll, 1, -1);
464 c = getc(stdin);
465
466 tcsetattr(0, TCSAFLUSH, &save);
467 if (!perf_top__key_mapped(top, c))
468 return ret;
469 }
470
471 switch (c) {
472 case 'd':
473 prompt_integer(&top->delay_secs, "Enter display delay");
474 if (top->delay_secs < 1)
475 top->delay_secs = 1;
476 break;
477 case 'e':
478 prompt_integer(&top->print_entries, "Enter display entries (lines)");
479 if (top->print_entries == 0) {
480 struct sigaction act = {
481 .sa_sigaction = perf_top__sig_winch,
482 .sa_flags = SA_SIGINFO,
483 };
484 perf_top__resize(top);
485 sigaction(SIGWINCH, &act, NULL);
486 } else {
487 signal(SIGWINCH, SIG_DFL);
488 }
489 break;
490 case 'E':
491 if (top->evlist->nr_entries > 1) {
492 /* Select 0 as the default event: */
493 int counter = 0;
494
495 fprintf(stderr, "\nAvailable events:");
496
497 evlist__for_each_entry(top->evlist, top->sym_evsel)
498 fprintf(stderr, "\n\t%d %s", top->sym_evsel->idx, perf_evsel__name(top->sym_evsel));
499
500 prompt_integer(&counter, "Enter details event counter");
501
502 if (counter >= top->evlist->nr_entries) {
503 top->sym_evsel = perf_evlist__first(top->evlist);
504 fprintf(stderr, "Sorry, no such event, using %s.\n", perf_evsel__name(top->sym_evsel));
505 sleep(1);
506 break;
507 }
508 evlist__for_each_entry(top->evlist, top->sym_evsel)
509 if (top->sym_evsel->idx == counter)
510 break;
511 } else
512 top->sym_evsel = perf_evlist__first(top->evlist);
513 break;
514 case 'f':
515 prompt_integer(&top->count_filter, "Enter display event count filter");
516 break;
517 case 'F':
518 prompt_percent(&top->sym_pcnt_filter,
519 "Enter details display event filter (percent)");
520 break;
521 case 'K':
522 top->hide_kernel_symbols = !top->hide_kernel_symbols;
523 break;
524 case 'q':
525 case 'Q':
526 printf("exiting.\n");
527 if (top->dump_symtab)
528 perf_session__fprintf_dsos(top->session, stderr);
529 ret = false;
530 break;
531 case 's':
532 perf_top__prompt_symbol(top, "Enter details symbol");
533 break;
534 case 'S':
535 if (!top->sym_filter_entry)
536 break;
537 else {
538 struct hist_entry *syme = top->sym_filter_entry;
539
540 top->sym_filter_entry = NULL;
541 __zero_source_counters(syme);
542 }
543 break;
544 case 'U':
545 top->hide_user_symbols = !top->hide_user_symbols;
546 break;
547 case 'z':
548 top->zero = !top->zero;
549 break;
550 default:
551 break;
552 }
553
554 return ret;
555}
556
557static void perf_top__sort_new_samples(void *arg)
558{
559 struct perf_top *t = arg;
560 struct perf_evsel *evsel = t->sym_evsel;
561 struct hists *hists;
562
563 perf_top__reset_sample_counters(t);
564
565 if (t->evlist->selected != NULL)
566 t->sym_evsel = t->evlist->selected;
567
568 hists = evsel__hists(evsel);
569
570 if (t->evlist->enabled) {
571 if (t->zero) {
572 hists__delete_entries(hists);
573 } else {
574 hists__decay_entries(hists, t->hide_user_symbols,
575 t->hide_kernel_symbols);
576 }
577 }
578
579 hists__collapse_resort(hists, NULL);
580 perf_evsel__output_resort(evsel, NULL);
581}
582
583static void *display_thread_tui(void *arg)
584{
585 struct perf_evsel *pos;
586 struct perf_top *top = arg;
587 const char *help = "For a higher level overview, try: perf top --sort comm,dso";
588 struct hist_browser_timer hbt = {
589 .timer = perf_top__sort_new_samples,
590 .arg = top,
591 .refresh = top->delay_secs,
592 };
593
594 /* In order to read symbols from other namespaces perf to needs to call
595 * setns(2). This isn't permitted if the struct_fs has multiple users.
596 * unshare(2) the fs so that we may continue to setns into namespaces
597 * that we're observing.
598 */
599 unshare(CLONE_FS);
600
601 perf_top__sort_new_samples(top);
602
603 /*
604 * Initialize the uid_filter_str, in the future the TUI will allow
605 * Zooming in/out UIDs. For now juse use whatever the user passed
606 * via --uid.
607 */
608 evlist__for_each_entry(top->evlist, pos) {
609 struct hists *hists = evsel__hists(pos);
610 hists->uid_filter_str = top->record_opts.target.uid_str;
611 }
612
613 perf_evlist__tui_browse_hists(top->evlist, help, &hbt,
614 top->min_percent,
615 &top->session->header.env);
616
617 done = 1;
618 return NULL;
619}
620
621static void display_sig(int sig __maybe_unused)
622{
623 done = 1;
624}
625
626static void display_setup_sig(void)
627{
628 signal(SIGSEGV, sighandler_dump_stack);
629 signal(SIGFPE, sighandler_dump_stack);
630 signal(SIGINT, display_sig);
631 signal(SIGQUIT, display_sig);
632 signal(SIGTERM, display_sig);
633}
634
635static void *display_thread(void *arg)
636{
637 struct pollfd stdin_poll = { .fd = 0, .events = POLLIN };
638 struct termios save;
639 struct perf_top *top = arg;
640 int delay_msecs, c;
641
642 /* In order to read symbols from other namespaces perf to needs to call
643 * setns(2). This isn't permitted if the struct_fs has multiple users.
644 * unshare(2) the fs so that we may continue to setns into namespaces
645 * that we're observing.
646 */
647 unshare(CLONE_FS);
648
649 display_setup_sig();
650 pthread__unblock_sigwinch();
651repeat:
652 delay_msecs = top->delay_secs * MSEC_PER_SEC;
653 set_term_quiet_input(&save);
654 /* trash return*/
655 getc(stdin);
656
657 while (!done) {
658 perf_top__print_sym_table(top);
659 /*
660 * Either timeout expired or we got an EINTR due to SIGWINCH,
661 * refresh screen in both cases.
662 */
663 switch (poll(&stdin_poll, 1, delay_msecs)) {
664 case 0:
665 continue;
666 case -1:
667 if (errno == EINTR)
668 continue;
669 __fallthrough;
670 default:
671 c = getc(stdin);
672 tcsetattr(0, TCSAFLUSH, &save);
673
674 if (perf_top__handle_keypress(top, c))
675 goto repeat;
676 done = 1;
677 }
678 }
679
680 tcsetattr(0, TCSAFLUSH, &save);
681 return NULL;
682}
683
684static int hist_iter__top_callback(struct hist_entry_iter *iter,
685 struct addr_location *al, bool single,
686 void *arg)
687{
688 struct perf_top *top = arg;
689 struct hist_entry *he = iter->he;
690 struct perf_evsel *evsel = iter->evsel;
691
692 if (perf_hpp_list.sym && single)
693 perf_top__record_precise_ip(top, he, iter->sample, evsel->idx, al->addr);
694
695 hist__account_cycles(iter->sample->branch_stack, al, iter->sample,
696 !(top->record_opts.branch_stack & PERF_SAMPLE_BRANCH_ANY));
697 return 0;
698}
699
700static void perf_event__process_sample(struct perf_tool *tool,
701 const union perf_event *event,
702 struct perf_evsel *evsel,
703 struct perf_sample *sample,
704 struct machine *machine)
705{
706 struct perf_top *top = container_of(tool, struct perf_top, tool);
707 struct addr_location al;
708 int err;
709
710 if (!machine && perf_guest) {
711 static struct intlist *seen;
712
713 if (!seen)
714 seen = intlist__new(NULL);
715
716 if (!intlist__has_entry(seen, sample->pid)) {
717 pr_err("Can't find guest [%d]'s kernel information\n",
718 sample->pid);
719 intlist__add(seen, sample->pid);
720 }
721 return;
722 }
723
724 if (!machine) {
725 pr_err("%u unprocessable samples recorded.\r",
726 top->session->evlist->stats.nr_unprocessable_samples++);
727 return;
728 }
729
730 if (event->header.misc & PERF_RECORD_MISC_EXACT_IP)
731 top->exact_samples++;
732
733 if (machine__resolve(machine, &al, sample) < 0)
734 return;
735
736 if (!machine->kptr_restrict_warned &&
737 symbol_conf.kptr_restrict &&
738 al.cpumode == PERF_RECORD_MISC_KERNEL) {
739 ui__warning(
740"Kernel address maps (/proc/{kallsyms,modules}) are restricted.\n\n"
741"Check /proc/sys/kernel/kptr_restrict.\n\n"
742"Kernel%s samples will not be resolved.\n",
743 al.map && !RB_EMPTY_ROOT(&al.map->dso->symbols[MAP__FUNCTION]) ?
744 " modules" : "");
745 if (use_browser <= 0)
746 sleep(5);
747 machine->kptr_restrict_warned = true;
748 }
749
750 if (al.sym == NULL) {
751 const char *msg = "Kernel samples will not be resolved.\n";
752 /*
753 * As we do lazy loading of symtabs we only will know if the
754 * specified vmlinux file is invalid when we actually have a
755 * hit in kernel space and then try to load it. So if we get
756 * here and there are _no_ symbols in the DSO backing the
757 * kernel map, bail out.
758 *
759 * We may never get here, for instance, if we use -K/
760 * --hide-kernel-symbols, even if the user specifies an
761 * invalid --vmlinux ;-)
762 */
763 if (!machine->kptr_restrict_warned && !top->vmlinux_warned &&
764 al.map == machine->vmlinux_maps[MAP__FUNCTION] &&
765 RB_EMPTY_ROOT(&al.map->dso->symbols[MAP__FUNCTION])) {
766 if (symbol_conf.vmlinux_name) {
767 char serr[256];
768 dso__strerror_load(al.map->dso, serr, sizeof(serr));
769 ui__warning("The %s file can't be used: %s\n%s",
770 symbol_conf.vmlinux_name, serr, msg);
771 } else {
772 ui__warning("A vmlinux file was not found.\n%s",
773 msg);
774 }
775
776 if (use_browser <= 0)
777 sleep(5);
778 top->vmlinux_warned = true;
779 }
780 }
781
782 if (al.sym == NULL || !al.sym->idle) {
783 struct hists *hists = evsel__hists(evsel);
784 struct hist_entry_iter iter = {
785 .evsel = evsel,
786 .sample = sample,
787 .add_entry_cb = hist_iter__top_callback,
788 };
789
790 if (symbol_conf.cumulate_callchain)
791 iter.ops = &hist_iter_cumulative;
792 else
793 iter.ops = &hist_iter_normal;
794
795 pthread_mutex_lock(&hists->lock);
796
797 err = hist_entry_iter__add(&iter, &al, top->max_stack, top);
798 if (err < 0)
799 pr_err("Problem incrementing symbol period, skipping event\n");
800
801 pthread_mutex_unlock(&hists->lock);
802 }
803
804 addr_location__put(&al);
805}
806
807static void perf_top__mmap_read_idx(struct perf_top *top, int idx)
808{
809 struct perf_sample sample;
810 struct perf_evsel *evsel;
811 struct perf_session *session = top->session;
812 union perf_event *event;
813 struct machine *machine;
814 int ret;
815
816 while ((event = perf_evlist__mmap_read(top->evlist, idx)) != NULL) {
817 ret = perf_evlist__parse_sample(top->evlist, event, &sample);
818 if (ret) {
819 pr_err("Can't parse sample, err = %d\n", ret);
820 goto next_event;
821 }
822
823 evsel = perf_evlist__id2evsel(session->evlist, sample.id);
824 assert(evsel != NULL);
825
826 if (event->header.type == PERF_RECORD_SAMPLE)
827 ++top->samples;
828
829 switch (sample.cpumode) {
830 case PERF_RECORD_MISC_USER:
831 ++top->us_samples;
832 if (top->hide_user_symbols)
833 goto next_event;
834 machine = &session->machines.host;
835 break;
836 case PERF_RECORD_MISC_KERNEL:
837 ++top->kernel_samples;
838 if (top->hide_kernel_symbols)
839 goto next_event;
840 machine = &session->machines.host;
841 break;
842 case PERF_RECORD_MISC_GUEST_KERNEL:
843 ++top->guest_kernel_samples;
844 machine = perf_session__find_machine(session,
845 sample.pid);
846 break;
847 case PERF_RECORD_MISC_GUEST_USER:
848 ++top->guest_us_samples;
849 /*
850 * TODO: we don't process guest user from host side
851 * except simple counting.
852 */
853 goto next_event;
854 default:
855 if (event->header.type == PERF_RECORD_SAMPLE)
856 goto next_event;
857 machine = &session->machines.host;
858 break;
859 }
860
861
862 if (event->header.type == PERF_RECORD_SAMPLE) {
863 perf_event__process_sample(&top->tool, event, evsel,
864 &sample, machine);
865 } else if (event->header.type < PERF_RECORD_MAX) {
866 hists__inc_nr_events(evsel__hists(evsel), event->header.type);
867 machine__process_event(machine, event, &sample);
868 } else
869 ++session->evlist->stats.nr_unknown_events;
870next_event:
871 perf_evlist__mmap_consume(top->evlist, idx);
872 }
873}
874
875static void perf_top__mmap_read(struct perf_top *top)
876{
877 int i;
878
879 for (i = 0; i < top->evlist->nr_mmaps; i++)
880 perf_top__mmap_read_idx(top, i);
881}
882
883static int perf_top__start_counters(struct perf_top *top)
884{
885 char msg[BUFSIZ];
886 struct perf_evsel *counter;
887 struct perf_evlist *evlist = top->evlist;
888 struct record_opts *opts = &top->record_opts;
889
890 perf_evlist__config(evlist, opts, &callchain_param);
891
892 evlist__for_each_entry(evlist, counter) {
893try_again:
894 if (perf_evsel__open(counter, top->evlist->cpus,
895 top->evlist->threads) < 0) {
896 if (perf_evsel__fallback(counter, errno, msg, sizeof(msg))) {
897 if (verbose > 0)
898 ui__warning("%s\n", msg);
899 goto try_again;
900 }
901
902 perf_evsel__open_strerror(counter, &opts->target,
903 errno, msg, sizeof(msg));
904 ui__error("%s\n", msg);
905 goto out_err;
906 }
907 }
908
909 if (perf_evlist__mmap(evlist, opts->mmap_pages, false) < 0) {
910 ui__error("Failed to mmap with %d (%s)\n",
911 errno, str_error_r(errno, msg, sizeof(msg)));
912 goto out_err;
913 }
914
915 return 0;
916
917out_err:
918 return -1;
919}
920
921static int callchain_param__setup_sample_type(struct callchain_param *callchain)
922{
923 if (!perf_hpp_list.sym) {
924 if (callchain->enabled) {
925 ui__error("Selected -g but \"sym\" not present in --sort/-s.");
926 return -EINVAL;
927 }
928 } else if (callchain->mode != CHAIN_NONE) {
929 if (callchain_register_param(callchain) < 0) {
930 ui__error("Can't register callchain params.\n");
931 return -EINVAL;
932 }
933 }
934
935 return 0;
936}
937
938static int __cmd_top(struct perf_top *top)
939{
940 char msg[512];
941 struct perf_evsel *pos;
942 struct perf_evsel_config_term *err_term;
943 struct perf_evlist *evlist = top->evlist;
944 struct record_opts *opts = &top->record_opts;
945 pthread_t thread;
946 int ret;
947
948 top->session = perf_session__new(NULL, false, NULL);
949 if (top->session == NULL)
950 return -1;
951
952 if (!objdump_path) {
953 ret = perf_env__lookup_objdump(&top->session->header.env);
954 if (ret)
955 goto out_delete;
956 }
957
958 ret = callchain_param__setup_sample_type(&callchain_param);
959 if (ret)
960 goto out_delete;
961
962 if (perf_session__register_idle_thread(top->session) < 0)
963 goto out_delete;
964
965 machine__synthesize_threads(&top->session->machines.host, &opts->target,
966 top->evlist->threads, false, opts->proc_map_timeout);
967
968 if (perf_hpp_list.socket) {
969 ret = perf_env__read_cpu_topology_map(&perf_env);
970 if (ret < 0)
971 goto out_err_cpu_topo;
972 }
973
974 ret = perf_top__start_counters(top);
975 if (ret)
976 goto out_delete;
977
978 ret = perf_evlist__apply_drv_configs(evlist, &pos, &err_term);
979 if (ret) {
980 pr_err("failed to set config \"%s\" on event %s with %d (%s)\n",
981 err_term->val.drv_cfg, perf_evsel__name(pos), errno,
982 str_error_r(errno, msg, sizeof(msg)));
983 goto out_delete;
984 }
985
986 top->session->evlist = top->evlist;
987 perf_session__set_id_hdr_size(top->session);
988
989 /*
990 * When perf is starting the traced process, all the events (apart from
991 * group members) have enable_on_exec=1 set, so don't spoil it by
992 * prematurely enabling them.
993 *
994 * XXX 'top' still doesn't start workloads like record, trace, but should,
995 * so leave the check here.
996 */
997 if (!target__none(&opts->target))
998 perf_evlist__enable(top->evlist);
999
1000 /* Wait for a minimal set of events before starting the snapshot */
1001 perf_evlist__poll(top->evlist, 100);
1002
1003 perf_top__mmap_read(top);
1004
1005 ret = -1;
1006 if (pthread_create(&thread, NULL, (use_browser > 0 ? display_thread_tui :
1007 display_thread), top)) {
1008 ui__error("Could not create display thread.\n");
1009 goto out_delete;
1010 }
1011
1012 if (top->realtime_prio) {
1013 struct sched_param param;
1014
1015 param.sched_priority = top->realtime_prio;
1016 if (sched_setscheduler(0, SCHED_FIFO, &param)) {
1017 ui__error("Could not set realtime priority.\n");
1018 goto out_join;
1019 }
1020 }
1021
1022 while (!done) {
1023 u64 hits = top->samples;
1024
1025 perf_top__mmap_read(top);
1026
1027 if (hits == top->samples)
1028 ret = perf_evlist__poll(top->evlist, 100);
1029
1030 if (resize) {
1031 perf_top__resize(top);
1032 resize = 0;
1033 }
1034 }
1035
1036 ret = 0;
1037out_join:
1038 pthread_join(thread, NULL);
1039out_delete:
1040 perf_session__delete(top->session);
1041 top->session = NULL;
1042
1043 return ret;
1044
1045out_err_cpu_topo: {
1046 char errbuf[BUFSIZ];
1047 const char *err = str_error_r(-ret, errbuf, sizeof(errbuf));
1048
1049 ui__error("Could not read the CPU topology map: %s\n", err);
1050 goto out_delete;
1051}
1052}
1053
1054static int
1055callchain_opt(const struct option *opt, const char *arg, int unset)
1056{
1057 symbol_conf.use_callchain = true;
1058 return record_callchain_opt(opt, arg, unset);
1059}
1060
1061static int
1062parse_callchain_opt(const struct option *opt, const char *arg, int unset)
1063{
1064 struct callchain_param *callchain = opt->value;
1065
1066 callchain->enabled = !unset;
1067 callchain->record_mode = CALLCHAIN_FP;
1068
1069 /*
1070 * --no-call-graph
1071 */
1072 if (unset) {
1073 symbol_conf.use_callchain = false;
1074 callchain->record_mode = CALLCHAIN_NONE;
1075 return 0;
1076 }
1077
1078 return parse_callchain_top_opt(arg);
1079}
1080
1081static int perf_top_config(const char *var, const char *value, void *cb __maybe_unused)
1082{
1083 if (!strcmp(var, "top.call-graph")) {
1084 var = "call-graph.record-mode";
1085 return perf_default_config(var, value, cb);
1086 }
1087 if (!strcmp(var, "top.children")) {
1088 symbol_conf.cumulate_callchain = perf_config_bool(var, value);
1089 return 0;
1090 }
1091
1092 return 0;
1093}
1094
1095static int
1096parse_percent_limit(const struct option *opt, const char *arg,
1097 int unset __maybe_unused)
1098{
1099 struct perf_top *top = opt->value;
1100
1101 top->min_percent = strtof(arg, NULL);
1102 return 0;
1103}
1104
1105const char top_callchain_help[] = CALLCHAIN_RECORD_HELP CALLCHAIN_REPORT_HELP
1106 "\n\t\t\t\tDefault: fp,graph,0.5,caller,function";
1107
1108int cmd_top(int argc, const char **argv)
1109{
1110 char errbuf[BUFSIZ];
1111 struct perf_top top = {
1112 .count_filter = 5,
1113 .delay_secs = 2,
1114 .record_opts = {
1115 .mmap_pages = UINT_MAX,
1116 .user_freq = UINT_MAX,
1117 .user_interval = ULLONG_MAX,
1118 .freq = 4000, /* 4 KHz */
1119 .target = {
1120 .uses_mmap = true,
1121 },
1122 .proc_map_timeout = 500,
1123 },
1124 .max_stack = sysctl_perf_event_max_stack,
1125 .sym_pcnt_filter = 5,
1126 };
1127 struct record_opts *opts = &top.record_opts;
1128 struct target *target = &opts->target;
1129 const struct option options[] = {
1130 OPT_CALLBACK('e', "event", &top.evlist, "event",
1131 "event selector. use 'perf list' to list available events",
1132 parse_events_option),
1133 OPT_U64('c', "count", &opts->user_interval, "event period to sample"),
1134 OPT_STRING('p', "pid", &target->pid, "pid",
1135 "profile events on existing process id"),
1136 OPT_STRING('t', "tid", &target->tid, "tid",
1137 "profile events on existing thread id"),
1138 OPT_BOOLEAN('a', "all-cpus", &target->system_wide,
1139 "system-wide collection from all CPUs"),
1140 OPT_STRING('C', "cpu", &target->cpu_list, "cpu",
1141 "list of cpus to monitor"),
1142 OPT_STRING('k', "vmlinux", &symbol_conf.vmlinux_name,
1143 "file", "vmlinux pathname"),
1144 OPT_BOOLEAN(0, "ignore-vmlinux", &symbol_conf.ignore_vmlinux,
1145 "don't load vmlinux even if found"),
1146 OPT_BOOLEAN('K', "hide_kernel_symbols", &top.hide_kernel_symbols,
1147 "hide kernel symbols"),
1148 OPT_CALLBACK('m', "mmap-pages", &opts->mmap_pages, "pages",
1149 "number of mmap data pages",
1150 perf_evlist__parse_mmap_pages),
1151 OPT_INTEGER('r', "realtime", &top.realtime_prio,
1152 "collect data with this RT SCHED_FIFO priority"),
1153 OPT_INTEGER('d', "delay", &top.delay_secs,
1154 "number of seconds to delay between refreshes"),
1155 OPT_BOOLEAN('D', "dump-symtab", &top.dump_symtab,
1156 "dump the symbol table used for profiling"),
1157 OPT_INTEGER('f', "count-filter", &top.count_filter,
1158 "only display functions with more events than this"),
1159 OPT_BOOLEAN(0, "group", &opts->group,
1160 "put the counters into a counter group"),
1161 OPT_BOOLEAN('i', "no-inherit", &opts->no_inherit,
1162 "child tasks do not inherit counters"),
1163 OPT_STRING(0, "sym-annotate", &top.sym_filter, "symbol name",
1164 "symbol to annotate"),
1165 OPT_BOOLEAN('z', "zero", &top.zero, "zero history across updates"),
1166 OPT_UINTEGER('F', "freq", &opts->user_freq, "profile at this frequency"),
1167 OPT_INTEGER('E', "entries", &top.print_entries,
1168 "display this many functions"),
1169 OPT_BOOLEAN('U', "hide_user_symbols", &top.hide_user_symbols,
1170 "hide user symbols"),
1171 OPT_BOOLEAN(0, "tui", &top.use_tui, "Use the TUI interface"),
1172 OPT_BOOLEAN(0, "stdio", &top.use_stdio, "Use the stdio interface"),
1173 OPT_INCR('v', "verbose", &verbose,
1174 "be more verbose (show counter open errors, etc)"),
1175 OPT_STRING('s', "sort", &sort_order, "key[,key2...]",
1176 "sort by key(s): pid, comm, dso, symbol, parent, cpu, srcline, ..."
1177 " Please refer the man page for the complete list."),
1178 OPT_STRING(0, "fields", &field_order, "key[,keys...]",
1179 "output field(s): overhead, period, sample plus all of sort keys"),
1180 OPT_BOOLEAN('n', "show-nr-samples", &symbol_conf.show_nr_samples,
1181 "Show a column with the number of samples"),
1182 OPT_CALLBACK_NOOPT('g', NULL, &callchain_param,
1183 NULL, "enables call-graph recording and display",
1184 &callchain_opt),
1185 OPT_CALLBACK(0, "call-graph", &callchain_param,
1186 "record_mode[,record_size],print_type,threshold[,print_limit],order,sort_key[,branch]",
1187 top_callchain_help, &parse_callchain_opt),
1188 OPT_BOOLEAN(0, "children", &symbol_conf.cumulate_callchain,
1189 "Accumulate callchains of children and show total overhead as well"),
1190 OPT_INTEGER(0, "max-stack", &top.max_stack,
1191 "Set the maximum stack depth when parsing the callchain. "
1192 "Default: kernel.perf_event_max_stack or " __stringify(PERF_MAX_STACK_DEPTH)),
1193 OPT_CALLBACK(0, "ignore-callees", NULL, "regex",
1194 "ignore callees of these functions in call graphs",
1195 report_parse_ignore_callees_opt),
1196 OPT_BOOLEAN(0, "show-total-period", &symbol_conf.show_total_period,
1197 "Show a column with the sum of periods"),
1198 OPT_STRING(0, "dsos", &symbol_conf.dso_list_str, "dso[,dso...]",
1199 "only consider symbols in these dsos"),
1200 OPT_STRING(0, "comms", &symbol_conf.comm_list_str, "comm[,comm...]",
1201 "only consider symbols in these comms"),
1202 OPT_STRING(0, "symbols", &symbol_conf.sym_list_str, "symbol[,symbol...]",
1203 "only consider these symbols"),
1204 OPT_BOOLEAN(0, "source", &symbol_conf.annotate_src,
1205 "Interleave source code with assembly code (default)"),
1206 OPT_BOOLEAN(0, "asm-raw", &symbol_conf.annotate_asm_raw,
1207 "Display raw encoding of assembly instructions (default)"),
1208 OPT_BOOLEAN(0, "demangle-kernel", &symbol_conf.demangle_kernel,
1209 "Enable kernel symbol demangling"),
1210 OPT_STRING(0, "objdump", &objdump_path, "path",
1211 "objdump binary to use for disassembly and annotations"),
1212 OPT_STRING('M', "disassembler-style", &disassembler_style, "disassembler style",
1213 "Specify disassembler style (e.g. -M intel for intel syntax)"),
1214 OPT_STRING('u', "uid", &target->uid_str, "user", "user to profile"),
1215 OPT_CALLBACK(0, "percent-limit", &top, "percent",
1216 "Don't show entries under that percent", parse_percent_limit),
1217 OPT_CALLBACK(0, "percentage", NULL, "relative|absolute",
1218 "How to display percentage of filtered entries", parse_filter_percentage),
1219 OPT_STRING('w', "column-widths", &symbol_conf.col_width_list_str,
1220 "width[,width...]",
1221 "don't try to adjust column width, use these fixed values"),
1222 OPT_UINTEGER(0, "proc-map-timeout", &opts->proc_map_timeout,
1223 "per thread proc mmap processing timeout in ms"),
1224 OPT_CALLBACK_NOOPT('b', "branch-any", &opts->branch_stack,
1225 "branch any", "sample any taken branches",
1226 parse_branch_stack),
1227 OPT_CALLBACK('j', "branch-filter", &opts->branch_stack,
1228 "branch filter mask", "branch stack filter modes",
1229 parse_branch_stack),
1230 OPT_BOOLEAN(0, "raw-trace", &symbol_conf.raw_trace,
1231 "Show raw trace event output (do not use print fmt or plugins)"),
1232 OPT_BOOLEAN(0, "hierarchy", &symbol_conf.report_hierarchy,
1233 "Show entries in a hierarchy"),
1234 OPT_BOOLEAN(0, "force", &symbol_conf.force, "don't complain, do it"),
1235 OPT_END()
1236 };
1237 const char * const top_usage[] = {
1238 "perf top [<options>]",
1239 NULL
1240 };
1241 int status = hists__init();
1242
1243 if (status < 0)
1244 return status;
1245
1246 top.evlist = perf_evlist__new();
1247 if (top.evlist == NULL)
1248 return -ENOMEM;
1249
1250 status = perf_config(perf_top_config, &top);
1251 if (status)
1252 return status;
1253
1254 argc = parse_options(argc, argv, options, top_usage, 0);
1255 if (argc)
1256 usage_with_options(top_usage, options);
1257
1258 if (!top.evlist->nr_entries &&
1259 perf_evlist__add_default(top.evlist) < 0) {
1260 pr_err("Not enough memory for event selector list\n");
1261 goto out_delete_evlist;
1262 }
1263
1264 if (symbol_conf.report_hierarchy) {
1265 /* disable incompatible options */
1266 symbol_conf.event_group = false;
1267 symbol_conf.cumulate_callchain = false;
1268
1269 if (field_order) {
1270 pr_err("Error: --hierarchy and --fields options cannot be used together\n");
1271 parse_options_usage(top_usage, options, "fields", 0);
1272 parse_options_usage(NULL, options, "hierarchy", 0);
1273 goto out_delete_evlist;
1274 }
1275 }
1276
1277 sort__mode = SORT_MODE__TOP;
1278 /* display thread wants entries to be collapsed in a different tree */
1279 perf_hpp_list.need_collapse = 1;
1280
1281 if (top.use_stdio)
1282 use_browser = 0;
1283 else if (top.use_tui)
1284 use_browser = 1;
1285
1286 setup_browser(false);
1287
1288 if (setup_sorting(top.evlist) < 0) {
1289 if (sort_order)
1290 parse_options_usage(top_usage, options, "s", 1);
1291 if (field_order)
1292 parse_options_usage(sort_order ? NULL : top_usage,
1293 options, "fields", 0);
1294 goto out_delete_evlist;
1295 }
1296
1297 status = target__validate(target);
1298 if (status) {
1299 target__strerror(target, status, errbuf, BUFSIZ);
1300 ui__warning("%s\n", errbuf);
1301 }
1302
1303 status = target__parse_uid(target);
1304 if (status) {
1305 int saved_errno = errno;
1306
1307 target__strerror(target, status, errbuf, BUFSIZ);
1308 ui__error("%s\n", errbuf);
1309
1310 status = -saved_errno;
1311 goto out_delete_evlist;
1312 }
1313
1314 if (target__none(target))
1315 target->system_wide = true;
1316
1317 if (perf_evlist__create_maps(top.evlist, target) < 0) {
1318 ui__error("Couldn't create thread/CPU maps: %s\n",
1319 errno == ENOENT ? "No such process" : str_error_r(errno, errbuf, sizeof(errbuf)));
1320 goto out_delete_evlist;
1321 }
1322
1323 symbol_conf.nr_events = top.evlist->nr_entries;
1324
1325 if (top.delay_secs < 1)
1326 top.delay_secs = 1;
1327
1328 if (record_opts__config(opts)) {
1329 status = -EINVAL;
1330 goto out_delete_evlist;
1331 }
1332
1333 top.sym_evsel = perf_evlist__first(top.evlist);
1334
1335 if (!callchain_param.enabled) {
1336 symbol_conf.cumulate_callchain = false;
1337 perf_hpp__cancel_cumulate();
1338 }
1339
1340 if (symbol_conf.cumulate_callchain && !callchain_param.order_set)
1341 callchain_param.order = ORDER_CALLER;
1342
1343 status = symbol__annotation_init();
1344 if (status < 0)
1345 goto out_delete_evlist;
1346
1347 symbol_conf.try_vmlinux_path = (symbol_conf.vmlinux_name == NULL);
1348 status = symbol__init(NULL);
1349 if (status < 0)
1350 goto out_delete_evlist;
1351
1352 sort__setup_elide(stdout);
1353
1354 get_term_dimensions(&top.winsize);
1355 if (top.print_entries == 0) {
1356 struct sigaction act = {
1357 .sa_sigaction = perf_top__sig_winch,
1358 .sa_flags = SA_SIGINFO,
1359 };
1360 perf_top__update_print_entries(&top);
1361 sigaction(SIGWINCH, &act, NULL);
1362 }
1363
1364 status = __cmd_top(&top);
1365
1366out_delete_evlist:
1367 perf_evlist__delete(top.evlist);
1368
1369 return status;
1370}