staging: rtl8192u: remove redundant assignment to pointer crypt
[linux/fpc-iii.git] / tools / perf / builtin-top.c
blobb46b3c9f57a02b955b3217a2b59fcfda5da20419
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3 * builtin-top.c
5 * Builtin top command: Display a continuously updated profile of
6 * any workload, CPU or specific PID.
8 * Copyright (C) 2008, Red Hat Inc, Ingo Molnar <mingo@redhat.com>
9 * 2011, Red Hat Inc, Arnaldo Carvalho de Melo <acme@redhat.com>
11 * Improvements and fixes by:
13 * Arjan van de Ven <arjan@linux.intel.com>
14 * Yanmin Zhang <yanmin.zhang@intel.com>
15 * Wu Fengguang <fengguang.wu@intel.com>
16 * Mike Galbraith <efault@gmx.de>
17 * Paul Mackerras <paulus@samba.org>
19 #include "builtin.h"
21 #include "perf.h"
23 #include "util/annotate.h"
24 #include "util/bpf-event.h"
25 #include "util/config.h"
26 #include "util/color.h"
27 #include "util/evlist.h"
28 #include "util/evsel.h"
29 #include "util/event.h"
30 #include "util/machine.h"
31 #include "util/map.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/string2.h"
44 #include "util/term.h"
45 #include "util/intlist.h"
46 #include "util/parse-branch-options.h"
47 #include "arch/common.h"
49 #include "util/debug.h"
50 #include "util/ordered-events.h"
52 #include <assert.h>
53 #include <elf.h>
54 #include <fcntl.h>
56 #include <stdio.h>
57 #include <termios.h>
58 #include <unistd.h>
59 #include <inttypes.h>
61 #include <errno.h>
62 #include <time.h>
63 #include <sched.h>
64 #include <signal.h>
66 #include <sys/syscall.h>
67 #include <sys/ioctl.h>
68 #include <poll.h>
69 #include <sys/prctl.h>
70 #include <sys/wait.h>
71 #include <sys/uio.h>
72 #include <sys/utsname.h>
73 #include <sys/mman.h>
75 #include <linux/stringify.h>
76 #include <linux/time64.h>
77 #include <linux/types.h>
79 #include <linux/ctype.h>
81 static volatile int done;
82 static volatile int resize;
84 #define HEADER_LINE_NR 5
86 static void perf_top__update_print_entries(struct perf_top *top)
88 top->print_entries = top->winsize.ws_row - HEADER_LINE_NR;
91 static void winch_sig(int sig __maybe_unused)
93 resize = 1;
96 static void perf_top__resize(struct perf_top *top)
98 get_term_dimensions(&top->winsize);
99 perf_top__update_print_entries(top);
102 static int perf_top__parse_source(struct perf_top *top, struct hist_entry *he)
104 struct perf_evsel *evsel;
105 struct symbol *sym;
106 struct annotation *notes;
107 struct map *map;
108 int err = -1;
110 if (!he || !he->ms.sym)
111 return -1;
113 evsel = hists_to_evsel(he->hists);
115 sym = he->ms.sym;
116 map = he->ms.map;
119 * We can't annotate with just /proc/kallsyms
121 if (map->dso->symtab_type == DSO_BINARY_TYPE__KALLSYMS &&
122 !dso__is_kcore(map->dso)) {
123 pr_err("Can't annotate %s: No vmlinux file was found in the "
124 "path\n", sym->name);
125 sleep(1);
126 return -1;
129 notes = symbol__annotation(sym);
130 pthread_mutex_lock(&notes->lock);
132 if (!symbol__hists(sym, top->evlist->nr_entries)) {
133 pthread_mutex_unlock(&notes->lock);
134 pr_err("Not enough memory for annotating '%s' symbol!\n",
135 sym->name);
136 sleep(1);
137 return err;
140 err = symbol__annotate(sym, map, evsel, 0, &top->annotation_opts, NULL);
141 if (err == 0) {
142 top->sym_filter_entry = he;
143 } else {
144 char msg[BUFSIZ];
145 symbol__strerror_disassemble(sym, map, err, msg, sizeof(msg));
146 pr_err("Couldn't annotate %s: %s\n", sym->name, msg);
149 pthread_mutex_unlock(&notes->lock);
150 return err;
153 static void __zero_source_counters(struct hist_entry *he)
155 struct symbol *sym = he->ms.sym;
156 symbol__annotate_zero_histograms(sym);
159 static void ui__warn_map_erange(struct map *map, struct symbol *sym, u64 ip)
161 struct utsname uts;
162 int err = uname(&uts);
164 ui__warning("Out of bounds address found:\n\n"
165 "Addr: %" PRIx64 "\n"
166 "DSO: %s %c\n"
167 "Map: %" PRIx64 "-%" PRIx64 "\n"
168 "Symbol: %" PRIx64 "-%" PRIx64 " %c %s\n"
169 "Arch: %s\n"
170 "Kernel: %s\n"
171 "Tools: %s\n\n"
172 "Not all samples will be on the annotation output.\n\n"
173 "Please report to linux-kernel@vger.kernel.org\n",
174 ip, map->dso->long_name, dso__symtab_origin(map->dso),
175 map->start, map->end, sym->start, sym->end,
176 sym->binding == STB_GLOBAL ? 'g' :
177 sym->binding == STB_LOCAL ? 'l' : 'w', sym->name,
178 err ? "[unknown]" : uts.machine,
179 err ? "[unknown]" : uts.release, perf_version_string);
180 if (use_browser <= 0)
181 sleep(5);
183 map->erange_warned = true;
186 static void perf_top__record_precise_ip(struct perf_top *top,
187 struct hist_entry *he,
188 struct perf_sample *sample,
189 struct perf_evsel *evsel, u64 ip)
191 struct annotation *notes;
192 struct symbol *sym = he->ms.sym;
193 int err = 0;
195 if (sym == NULL || (use_browser == 0 &&
196 (top->sym_filter_entry == NULL ||
197 top->sym_filter_entry->ms.sym != sym)))
198 return;
200 notes = symbol__annotation(sym);
202 if (pthread_mutex_trylock(&notes->lock))
203 return;
205 err = hist_entry__inc_addr_samples(he, sample, evsel, ip);
207 pthread_mutex_unlock(&notes->lock);
209 if (unlikely(err)) {
211 * This function is now called with he->hists->lock held.
212 * Release it before going to sleep.
214 pthread_mutex_unlock(&he->hists->lock);
216 if (err == -ERANGE && !he->ms.map->erange_warned)
217 ui__warn_map_erange(he->ms.map, sym, ip);
218 else if (err == -ENOMEM) {
219 pr_err("Not enough memory for annotating '%s' symbol!\n",
220 sym->name);
221 sleep(1);
224 pthread_mutex_lock(&he->hists->lock);
228 static void perf_top__show_details(struct perf_top *top)
230 struct hist_entry *he = top->sym_filter_entry;
231 struct perf_evsel *evsel;
232 struct annotation *notes;
233 struct symbol *symbol;
234 int more;
236 if (!he)
237 return;
239 evsel = hists_to_evsel(he->hists);
241 symbol = he->ms.sym;
242 notes = symbol__annotation(symbol);
244 pthread_mutex_lock(&notes->lock);
246 symbol__calc_percent(symbol, evsel);
248 if (notes->src == NULL)
249 goto out_unlock;
251 printf("Showing %s for %s\n", perf_evsel__name(top->sym_evsel), symbol->name);
252 printf(" Events Pcnt (>=%d%%)\n", top->annotation_opts.min_pcnt);
254 more = symbol__annotate_printf(symbol, he->ms.map, top->sym_evsel, &top->annotation_opts);
256 if (top->evlist->enabled) {
257 if (top->zero)
258 symbol__annotate_zero_histogram(symbol, top->sym_evsel->idx);
259 else
260 symbol__annotate_decay_histogram(symbol, top->sym_evsel->idx);
262 if (more != 0)
263 printf("%d lines not displayed, maybe increase display entries [e]\n", more);
264 out_unlock:
265 pthread_mutex_unlock(&notes->lock);
268 static void perf_top__print_sym_table(struct perf_top *top)
270 char bf[160];
271 int printed = 0;
272 const int win_width = top->winsize.ws_col - 1;
273 struct perf_evsel *evsel = top->sym_evsel;
274 struct hists *hists = evsel__hists(evsel);
276 puts(CONSOLE_CLEAR);
278 perf_top__header_snprintf(top, bf, sizeof(bf));
279 printf("%s\n", bf);
281 printf("%-*.*s\n", win_width, win_width, graph_dotted_line);
283 if (!top->record_opts.overwrite &&
284 (hists->stats.nr_lost_warned !=
285 hists->stats.nr_events[PERF_RECORD_LOST])) {
286 hists->stats.nr_lost_warned =
287 hists->stats.nr_events[PERF_RECORD_LOST];
288 color_fprintf(stdout, PERF_COLOR_RED,
289 "WARNING: LOST %d chunks, Check IO/CPU overload",
290 hists->stats.nr_lost_warned);
291 ++printed;
294 if (top->sym_filter_entry) {
295 perf_top__show_details(top);
296 return;
299 if (top->evlist->enabled) {
300 if (top->zero) {
301 hists__delete_entries(hists);
302 } else {
303 hists__decay_entries(hists, top->hide_user_symbols,
304 top->hide_kernel_symbols);
308 hists__collapse_resort(hists, NULL);
309 perf_evsel__output_resort(evsel, NULL);
311 hists__output_recalc_col_len(hists, top->print_entries - printed);
312 putchar('\n');
313 hists__fprintf(hists, false, top->print_entries - printed, win_width,
314 top->min_percent, stdout, !symbol_conf.use_callchain);
317 static void prompt_integer(int *target, const char *msg)
319 char *buf = malloc(0), *p;
320 size_t dummy = 0;
321 int tmp;
323 fprintf(stdout, "\n%s: ", msg);
324 if (getline(&buf, &dummy, stdin) < 0)
325 return;
327 p = strchr(buf, '\n');
328 if (p)
329 *p = 0;
331 p = buf;
332 while(*p) {
333 if (!isdigit(*p))
334 goto out_free;
335 p++;
337 tmp = strtoul(buf, NULL, 10);
338 *target = tmp;
339 out_free:
340 free(buf);
343 static void prompt_percent(int *target, const char *msg)
345 int tmp = 0;
347 prompt_integer(&tmp, msg);
348 if (tmp >= 0 && tmp <= 100)
349 *target = tmp;
352 static void perf_top__prompt_symbol(struct perf_top *top, const char *msg)
354 char *buf = malloc(0), *p;
355 struct hist_entry *syme = top->sym_filter_entry, *n, *found = NULL;
356 struct hists *hists = evsel__hists(top->sym_evsel);
357 struct rb_node *next;
358 size_t dummy = 0;
360 /* zero counters of active symbol */
361 if (syme) {
362 __zero_source_counters(syme);
363 top->sym_filter_entry = NULL;
366 fprintf(stdout, "\n%s: ", msg);
367 if (getline(&buf, &dummy, stdin) < 0)
368 goto out_free;
370 p = strchr(buf, '\n');
371 if (p)
372 *p = 0;
374 next = rb_first_cached(&hists->entries);
375 while (next) {
376 n = rb_entry(next, struct hist_entry, rb_node);
377 if (n->ms.sym && !strcmp(buf, n->ms.sym->name)) {
378 found = n;
379 break;
381 next = rb_next(&n->rb_node);
384 if (!found) {
385 fprintf(stderr, "Sorry, %s is not active.\n", buf);
386 sleep(1);
387 } else
388 perf_top__parse_source(top, found);
390 out_free:
391 free(buf);
394 static void perf_top__print_mapped_keys(struct perf_top *top)
396 char *name = NULL;
398 if (top->sym_filter_entry) {
399 struct symbol *sym = top->sym_filter_entry->ms.sym;
400 name = sym->name;
403 fprintf(stdout, "\nMapped keys:\n");
404 fprintf(stdout, "\t[d] display refresh delay. \t(%d)\n", top->delay_secs);
405 fprintf(stdout, "\t[e] display entries (lines). \t(%d)\n", top->print_entries);
407 if (top->evlist->nr_entries > 1)
408 fprintf(stdout, "\t[E] active event counter. \t(%s)\n", perf_evsel__name(top->sym_evsel));
410 fprintf(stdout, "\t[f] profile display filter (count). \t(%d)\n", top->count_filter);
412 fprintf(stdout, "\t[F] annotate display filter (percent). \t(%d%%)\n", top->annotation_opts.min_pcnt);
413 fprintf(stdout, "\t[s] annotate symbol. \t(%s)\n", name?: "NULL");
414 fprintf(stdout, "\t[S] stop annotation.\n");
416 fprintf(stdout,
417 "\t[K] hide kernel symbols. \t(%s)\n",
418 top->hide_kernel_symbols ? "yes" : "no");
419 fprintf(stdout,
420 "\t[U] hide user symbols. \t(%s)\n",
421 top->hide_user_symbols ? "yes" : "no");
422 fprintf(stdout, "\t[z] toggle sample zeroing. \t(%d)\n", top->zero ? 1 : 0);
423 fprintf(stdout, "\t[qQ] quit.\n");
426 static int perf_top__key_mapped(struct perf_top *top, int c)
428 switch (c) {
429 case 'd':
430 case 'e':
431 case 'f':
432 case 'z':
433 case 'q':
434 case 'Q':
435 case 'K':
436 case 'U':
437 case 'F':
438 case 's':
439 case 'S':
440 return 1;
441 case 'E':
442 return top->evlist->nr_entries > 1 ? 1 : 0;
443 default:
444 break;
447 return 0;
450 static bool perf_top__handle_keypress(struct perf_top *top, int c)
452 bool ret = true;
454 if (!perf_top__key_mapped(top, c)) {
455 struct pollfd stdin_poll = { .fd = 0, .events = POLLIN };
456 struct termios save;
458 perf_top__print_mapped_keys(top);
459 fprintf(stdout, "\nEnter selection, or unmapped key to continue: ");
460 fflush(stdout);
462 set_term_quiet_input(&save);
464 poll(&stdin_poll, 1, -1);
465 c = getc(stdin);
467 tcsetattr(0, TCSAFLUSH, &save);
468 if (!perf_top__key_mapped(top, c))
469 return ret;
472 switch (c) {
473 case 'd':
474 prompt_integer(&top->delay_secs, "Enter display delay");
475 if (top->delay_secs < 1)
476 top->delay_secs = 1;
477 break;
478 case 'e':
479 prompt_integer(&top->print_entries, "Enter display entries (lines)");
480 if (top->print_entries == 0) {
481 perf_top__resize(top);
482 signal(SIGWINCH, winch_sig);
483 } else {
484 signal(SIGWINCH, SIG_DFL);
486 break;
487 case 'E':
488 if (top->evlist->nr_entries > 1) {
489 /* Select 0 as the default event: */
490 int counter = 0;
492 fprintf(stderr, "\nAvailable events:");
494 evlist__for_each_entry(top->evlist, top->sym_evsel)
495 fprintf(stderr, "\n\t%d %s", top->sym_evsel->idx, perf_evsel__name(top->sym_evsel));
497 prompt_integer(&counter, "Enter details event counter");
499 if (counter >= top->evlist->nr_entries) {
500 top->sym_evsel = perf_evlist__first(top->evlist);
501 fprintf(stderr, "Sorry, no such event, using %s.\n", perf_evsel__name(top->sym_evsel));
502 sleep(1);
503 break;
505 evlist__for_each_entry(top->evlist, top->sym_evsel)
506 if (top->sym_evsel->idx == counter)
507 break;
508 } else
509 top->sym_evsel = perf_evlist__first(top->evlist);
510 break;
511 case 'f':
512 prompt_integer(&top->count_filter, "Enter display event count filter");
513 break;
514 case 'F':
515 prompt_percent(&top->annotation_opts.min_pcnt,
516 "Enter details display event filter (percent)");
517 break;
518 case 'K':
519 top->hide_kernel_symbols = !top->hide_kernel_symbols;
520 break;
521 case 'q':
522 case 'Q':
523 printf("exiting.\n");
524 if (top->dump_symtab)
525 perf_session__fprintf_dsos(top->session, stderr);
526 ret = false;
527 break;
528 case 's':
529 perf_top__prompt_symbol(top, "Enter details symbol");
530 break;
531 case 'S':
532 if (!top->sym_filter_entry)
533 break;
534 else {
535 struct hist_entry *syme = top->sym_filter_entry;
537 top->sym_filter_entry = NULL;
538 __zero_source_counters(syme);
540 break;
541 case 'U':
542 top->hide_user_symbols = !top->hide_user_symbols;
543 break;
544 case 'z':
545 top->zero = !top->zero;
546 break;
547 default:
548 break;
551 return ret;
554 static void perf_top__sort_new_samples(void *arg)
556 struct perf_top *t = arg;
557 struct perf_evsel *evsel = t->sym_evsel;
558 struct hists *hists;
560 if (t->evlist->selected != NULL)
561 t->sym_evsel = t->evlist->selected;
563 hists = evsel__hists(evsel);
565 if (t->evlist->enabled) {
566 if (t->zero) {
567 hists__delete_entries(hists);
568 } else {
569 hists__decay_entries(hists, t->hide_user_symbols,
570 t->hide_kernel_symbols);
574 hists__collapse_resort(hists, NULL);
575 perf_evsel__output_resort(evsel, NULL);
577 if (t->lost || t->drop)
578 pr_warning("Too slow to read ring buffer (change period (-c/-F) or limit CPUs (-C)\n");
581 static void stop_top(void)
583 session_done = 1;
584 done = 1;
587 static void *display_thread_tui(void *arg)
589 struct perf_evsel *pos;
590 struct perf_top *top = arg;
591 const char *help = "For a higher level overview, try: perf top --sort comm,dso";
592 struct hist_browser_timer hbt = {
593 .timer = perf_top__sort_new_samples,
594 .arg = top,
595 .refresh = top->delay_secs,
598 /* In order to read symbols from other namespaces perf to needs to call
599 * setns(2). This isn't permitted if the struct_fs has multiple users.
600 * unshare(2) the fs so that we may continue to setns into namespaces
601 * that we're observing.
603 unshare(CLONE_FS);
605 perf_top__sort_new_samples(top);
608 * Initialize the uid_filter_str, in the future the TUI will allow
609 * Zooming in/out UIDs. For now just use whatever the user passed
610 * via --uid.
612 evlist__for_each_entry(top->evlist, pos) {
613 struct hists *hists = evsel__hists(pos);
614 hists->uid_filter_str = top->record_opts.target.uid_str;
617 perf_evlist__tui_browse_hists(top->evlist, help, &hbt,
618 top->min_percent,
619 &top->session->header.env,
620 !top->record_opts.overwrite,
621 &top->annotation_opts);
623 stop_top();
624 return NULL;
627 static void display_sig(int sig __maybe_unused)
629 stop_top();
632 static void display_setup_sig(void)
634 signal(SIGSEGV, sighandler_dump_stack);
635 signal(SIGFPE, sighandler_dump_stack);
636 signal(SIGINT, display_sig);
637 signal(SIGQUIT, display_sig);
638 signal(SIGTERM, display_sig);
641 static void *display_thread(void *arg)
643 struct pollfd stdin_poll = { .fd = 0, .events = POLLIN };
644 struct termios save;
645 struct perf_top *top = arg;
646 int delay_msecs, c;
648 /* In order to read symbols from other namespaces perf to needs to call
649 * setns(2). This isn't permitted if the struct_fs has multiple users.
650 * unshare(2) the fs so that we may continue to setns into namespaces
651 * that we're observing.
653 unshare(CLONE_FS);
655 display_setup_sig();
656 pthread__unblock_sigwinch();
657 repeat:
658 delay_msecs = top->delay_secs * MSEC_PER_SEC;
659 set_term_quiet_input(&save);
660 /* trash return*/
661 getc(stdin);
663 while (!done) {
664 perf_top__print_sym_table(top);
666 * Either timeout expired or we got an EINTR due to SIGWINCH,
667 * refresh screen in both cases.
669 switch (poll(&stdin_poll, 1, delay_msecs)) {
670 case 0:
671 continue;
672 case -1:
673 if (errno == EINTR)
674 continue;
675 __fallthrough;
676 default:
677 c = getc(stdin);
678 tcsetattr(0, TCSAFLUSH, &save);
680 if (perf_top__handle_keypress(top, c))
681 goto repeat;
682 stop_top();
686 tcsetattr(0, TCSAFLUSH, &save);
687 return NULL;
690 static int hist_iter__top_callback(struct hist_entry_iter *iter,
691 struct addr_location *al, bool single,
692 void *arg)
694 struct perf_top *top = arg;
695 struct hist_entry *he = iter->he;
696 struct perf_evsel *evsel = iter->evsel;
698 if (perf_hpp_list.sym && single)
699 perf_top__record_precise_ip(top, he, iter->sample, evsel, al->addr);
701 hist__account_cycles(iter->sample->branch_stack, al, iter->sample,
702 !(top->record_opts.branch_stack & PERF_SAMPLE_BRANCH_ANY));
703 return 0;
706 static void perf_event__process_sample(struct perf_tool *tool,
707 const union perf_event *event,
708 struct perf_evsel *evsel,
709 struct perf_sample *sample,
710 struct machine *machine)
712 struct perf_top *top = container_of(tool, struct perf_top, tool);
713 struct addr_location al;
714 int err;
716 if (!machine && perf_guest) {
717 static struct intlist *seen;
719 if (!seen)
720 seen = intlist__new(NULL);
722 if (!intlist__has_entry(seen, sample->pid)) {
723 pr_err("Can't find guest [%d]'s kernel information\n",
724 sample->pid);
725 intlist__add(seen, sample->pid);
727 return;
730 if (!machine) {
731 pr_err("%u unprocessable samples recorded.\r",
732 top->session->evlist->stats.nr_unprocessable_samples++);
733 return;
736 if (event->header.misc & PERF_RECORD_MISC_EXACT_IP)
737 top->exact_samples++;
739 if (machine__resolve(machine, &al, sample) < 0)
740 return;
742 if (!machine->kptr_restrict_warned &&
743 symbol_conf.kptr_restrict &&
744 al.cpumode == PERF_RECORD_MISC_KERNEL) {
745 if (!perf_evlist__exclude_kernel(top->session->evlist)) {
746 ui__warning(
747 "Kernel address maps (/proc/{kallsyms,modules}) are restricted.\n\n"
748 "Check /proc/sys/kernel/kptr_restrict.\n\n"
749 "Kernel%s samples will not be resolved.\n",
750 al.map && map__has_symbols(al.map) ?
751 " modules" : "");
752 if (use_browser <= 0)
753 sleep(5);
755 machine->kptr_restrict_warned = true;
758 if (al.sym == NULL && al.map != NULL) {
759 const char *msg = "Kernel samples will not be resolved.\n";
761 * As we do lazy loading of symtabs we only will know if the
762 * specified vmlinux file is invalid when we actually have a
763 * hit in kernel space and then try to load it. So if we get
764 * here and there are _no_ symbols in the DSO backing the
765 * kernel map, bail out.
767 * We may never get here, for instance, if we use -K/
768 * --hide-kernel-symbols, even if the user specifies an
769 * invalid --vmlinux ;-)
771 if (!machine->kptr_restrict_warned && !top->vmlinux_warned &&
772 __map__is_kernel(al.map) && map__has_symbols(al.map)) {
773 if (symbol_conf.vmlinux_name) {
774 char serr[256];
775 dso__strerror_load(al.map->dso, serr, sizeof(serr));
776 ui__warning("The %s file can't be used: %s\n%s",
777 symbol_conf.vmlinux_name, serr, msg);
778 } else {
779 ui__warning("A vmlinux file was not found.\n%s",
780 msg);
783 if (use_browser <= 0)
784 sleep(5);
785 top->vmlinux_warned = true;
789 if (al.sym == NULL || !al.sym->idle) {
790 struct hists *hists = evsel__hists(evsel);
791 struct hist_entry_iter iter = {
792 .evsel = evsel,
793 .sample = sample,
794 .add_entry_cb = hist_iter__top_callback,
797 if (symbol_conf.cumulate_callchain)
798 iter.ops = &hist_iter_cumulative;
799 else
800 iter.ops = &hist_iter_normal;
802 pthread_mutex_lock(&hists->lock);
804 err = hist_entry_iter__add(&iter, &al, top->max_stack, top);
805 if (err < 0)
806 pr_err("Problem incrementing symbol period, skipping event\n");
808 pthread_mutex_unlock(&hists->lock);
811 addr_location__put(&al);
814 static void
815 perf_top__process_lost(struct perf_top *top, union perf_event *event,
816 struct perf_evsel *evsel)
818 struct hists *hists = evsel__hists(evsel);
820 top->lost += event->lost.lost;
821 top->lost_total += event->lost.lost;
822 hists->stats.total_lost += event->lost.lost;
825 static void
826 perf_top__process_lost_samples(struct perf_top *top,
827 union perf_event *event,
828 struct perf_evsel *evsel)
830 struct hists *hists = evsel__hists(evsel);
832 top->lost += event->lost_samples.lost;
833 top->lost_total += event->lost_samples.lost;
834 hists->stats.total_lost_samples += event->lost_samples.lost;
837 static u64 last_timestamp;
839 static void perf_top__mmap_read_idx(struct perf_top *top, int idx)
841 struct record_opts *opts = &top->record_opts;
842 struct perf_evlist *evlist = top->evlist;
843 struct perf_mmap *md;
844 union perf_event *event;
846 md = opts->overwrite ? &evlist->overwrite_mmap[idx] : &evlist->mmap[idx];
847 if (perf_mmap__read_init(md) < 0)
848 return;
850 while ((event = perf_mmap__read_event(md)) != NULL) {
851 int ret;
853 ret = perf_evlist__parse_sample_timestamp(evlist, event, &last_timestamp);
854 if (ret && ret != -1)
855 break;
857 ret = ordered_events__queue(top->qe.in, event, last_timestamp, 0);
858 if (ret)
859 break;
861 perf_mmap__consume(md);
863 if (top->qe.rotate) {
864 pthread_mutex_lock(&top->qe.mutex);
865 top->qe.rotate = false;
866 pthread_cond_signal(&top->qe.cond);
867 pthread_mutex_unlock(&top->qe.mutex);
871 perf_mmap__read_done(md);
874 static void perf_top__mmap_read(struct perf_top *top)
876 bool overwrite = top->record_opts.overwrite;
877 struct perf_evlist *evlist = top->evlist;
878 int i;
880 if (overwrite)
881 perf_evlist__toggle_bkw_mmap(evlist, BKW_MMAP_DATA_PENDING);
883 for (i = 0; i < top->evlist->nr_mmaps; i++)
884 perf_top__mmap_read_idx(top, i);
886 if (overwrite) {
887 perf_evlist__toggle_bkw_mmap(evlist, BKW_MMAP_EMPTY);
888 perf_evlist__toggle_bkw_mmap(evlist, BKW_MMAP_RUNNING);
893 * Check per-event overwrite term.
894 * perf top should support consistent term for all events.
895 * - All events don't have per-event term
896 * E.g. "cpu/cpu-cycles/,cpu/instructions/"
897 * Nothing change, return 0.
898 * - All events have same per-event term
899 * E.g. "cpu/cpu-cycles,no-overwrite/,cpu/instructions,no-overwrite/
900 * Using the per-event setting to replace the opts->overwrite if
901 * they are different, then return 0.
902 * - Events have different per-event term
903 * E.g. "cpu/cpu-cycles,overwrite/,cpu/instructions,no-overwrite/"
904 * Return -1
905 * - Some of the event set per-event term, but some not.
906 * E.g. "cpu/cpu-cycles/,cpu/instructions,no-overwrite/"
907 * Return -1
909 static int perf_top__overwrite_check(struct perf_top *top)
911 struct record_opts *opts = &top->record_opts;
912 struct perf_evlist *evlist = top->evlist;
913 struct perf_evsel_config_term *term;
914 struct list_head *config_terms;
915 struct perf_evsel *evsel;
916 int set, overwrite = -1;
918 evlist__for_each_entry(evlist, evsel) {
919 set = -1;
920 config_terms = &evsel->config_terms;
921 list_for_each_entry(term, config_terms, list) {
922 if (term->type == PERF_EVSEL__CONFIG_TERM_OVERWRITE)
923 set = term->val.overwrite ? 1 : 0;
926 /* no term for current and previous event (likely) */
927 if ((overwrite < 0) && (set < 0))
928 continue;
930 /* has term for both current and previous event, compare */
931 if ((overwrite >= 0) && (set >= 0) && (overwrite != set))
932 return -1;
934 /* no term for current event but has term for previous one */
935 if ((overwrite >= 0) && (set < 0))
936 return -1;
938 /* has term for current event */
939 if ((overwrite < 0) && (set >= 0)) {
940 /* if it's first event, set overwrite */
941 if (evsel == perf_evlist__first(evlist))
942 overwrite = set;
943 else
944 return -1;
948 if ((overwrite >= 0) && (opts->overwrite != overwrite))
949 opts->overwrite = overwrite;
951 return 0;
954 static int perf_top_overwrite_fallback(struct perf_top *top,
955 struct perf_evsel *evsel)
957 struct record_opts *opts = &top->record_opts;
958 struct perf_evlist *evlist = top->evlist;
959 struct perf_evsel *counter;
961 if (!opts->overwrite)
962 return 0;
964 /* only fall back when first event fails */
965 if (evsel != perf_evlist__first(evlist))
966 return 0;
968 evlist__for_each_entry(evlist, counter)
969 counter->attr.write_backward = false;
970 opts->overwrite = false;
971 pr_debug2("fall back to non-overwrite mode\n");
972 return 1;
975 static int perf_top__start_counters(struct perf_top *top)
977 char msg[BUFSIZ];
978 struct perf_evsel *counter;
979 struct perf_evlist *evlist = top->evlist;
980 struct record_opts *opts = &top->record_opts;
982 if (perf_top__overwrite_check(top)) {
983 ui__error("perf top only support consistent per-event "
984 "overwrite setting for all events\n");
985 goto out_err;
988 perf_evlist__config(evlist, opts, &callchain_param);
990 evlist__for_each_entry(evlist, counter) {
991 try_again:
992 if (perf_evsel__open(counter, top->evlist->cpus,
993 top->evlist->threads) < 0) {
996 * Specially handle overwrite fall back.
997 * Because perf top is the only tool which has
998 * overwrite mode by default, support
999 * both overwrite and non-overwrite mode, and
1000 * require consistent mode for all events.
1002 * May move it to generic code with more tools
1003 * have similar attribute.
1005 if (perf_missing_features.write_backward &&
1006 perf_top_overwrite_fallback(top, counter))
1007 goto try_again;
1009 if (perf_evsel__fallback(counter, errno, msg, sizeof(msg))) {
1010 if (verbose > 0)
1011 ui__warning("%s\n", msg);
1012 goto try_again;
1015 perf_evsel__open_strerror(counter, &opts->target,
1016 errno, msg, sizeof(msg));
1017 ui__error("%s\n", msg);
1018 goto out_err;
1022 if (perf_evlist__mmap(evlist, opts->mmap_pages) < 0) {
1023 ui__error("Failed to mmap with %d (%s)\n",
1024 errno, str_error_r(errno, msg, sizeof(msg)));
1025 goto out_err;
1028 return 0;
1030 out_err:
1031 return -1;
1034 static int callchain_param__setup_sample_type(struct callchain_param *callchain)
1036 if (callchain->mode != CHAIN_NONE) {
1037 if (callchain_register_param(callchain) < 0) {
1038 ui__error("Can't register callchain params.\n");
1039 return -EINVAL;
1043 return 0;
1046 static struct ordered_events *rotate_queues(struct perf_top *top)
1048 struct ordered_events *in = top->qe.in;
1050 if (top->qe.in == &top->qe.data[1])
1051 top->qe.in = &top->qe.data[0];
1052 else
1053 top->qe.in = &top->qe.data[1];
1055 return in;
1058 static void *process_thread(void *arg)
1060 struct perf_top *top = arg;
1062 while (!done) {
1063 struct ordered_events *out, *in = top->qe.in;
1065 if (!in->nr_events) {
1066 usleep(100);
1067 continue;
1070 out = rotate_queues(top);
1072 pthread_mutex_lock(&top->qe.mutex);
1073 top->qe.rotate = true;
1074 pthread_cond_wait(&top->qe.cond, &top->qe.mutex);
1075 pthread_mutex_unlock(&top->qe.mutex);
1077 if (ordered_events__flush(out, OE_FLUSH__TOP))
1078 pr_err("failed to process events\n");
1081 return NULL;
1085 * Allow only 'top->delay_secs' seconds behind samples.
1087 static int should_drop(struct ordered_event *qevent, struct perf_top *top)
1089 union perf_event *event = qevent->event;
1090 u64 delay_timestamp;
1092 if (event->header.type != PERF_RECORD_SAMPLE)
1093 return false;
1095 delay_timestamp = qevent->timestamp + top->delay_secs * NSEC_PER_SEC;
1096 return delay_timestamp < last_timestamp;
1099 static int deliver_event(struct ordered_events *qe,
1100 struct ordered_event *qevent)
1102 struct perf_top *top = qe->data;
1103 struct perf_evlist *evlist = top->evlist;
1104 struct perf_session *session = top->session;
1105 union perf_event *event = qevent->event;
1106 struct perf_sample sample;
1107 struct perf_evsel *evsel;
1108 struct machine *machine;
1109 int ret = -1;
1111 if (should_drop(qevent, top)) {
1112 top->drop++;
1113 top->drop_total++;
1114 return 0;
1117 ret = perf_evlist__parse_sample(evlist, event, &sample);
1118 if (ret) {
1119 pr_err("Can't parse sample, err = %d\n", ret);
1120 goto next_event;
1123 evsel = perf_evlist__id2evsel(session->evlist, sample.id);
1124 assert(evsel != NULL);
1126 if (event->header.type == PERF_RECORD_SAMPLE)
1127 ++top->samples;
1129 switch (sample.cpumode) {
1130 case PERF_RECORD_MISC_USER:
1131 ++top->us_samples;
1132 if (top->hide_user_symbols)
1133 goto next_event;
1134 machine = &session->machines.host;
1135 break;
1136 case PERF_RECORD_MISC_KERNEL:
1137 ++top->kernel_samples;
1138 if (top->hide_kernel_symbols)
1139 goto next_event;
1140 machine = &session->machines.host;
1141 break;
1142 case PERF_RECORD_MISC_GUEST_KERNEL:
1143 ++top->guest_kernel_samples;
1144 machine = perf_session__find_machine(session,
1145 sample.pid);
1146 break;
1147 case PERF_RECORD_MISC_GUEST_USER:
1148 ++top->guest_us_samples;
1150 * TODO: we don't process guest user from host side
1151 * except simple counting.
1153 goto next_event;
1154 default:
1155 if (event->header.type == PERF_RECORD_SAMPLE)
1156 goto next_event;
1157 machine = &session->machines.host;
1158 break;
1161 if (event->header.type == PERF_RECORD_SAMPLE) {
1162 perf_event__process_sample(&top->tool, event, evsel,
1163 &sample, machine);
1164 } else if (event->header.type == PERF_RECORD_LOST) {
1165 perf_top__process_lost(top, event, evsel);
1166 } else if (event->header.type == PERF_RECORD_LOST_SAMPLES) {
1167 perf_top__process_lost_samples(top, event, evsel);
1168 } else if (event->header.type < PERF_RECORD_MAX) {
1169 hists__inc_nr_events(evsel__hists(evsel), event->header.type);
1170 machine__process_event(machine, event, &sample);
1171 } else
1172 ++session->evlist->stats.nr_unknown_events;
1174 ret = 0;
1175 next_event:
1176 return ret;
1179 static void init_process_thread(struct perf_top *top)
1181 ordered_events__init(&top->qe.data[0], deliver_event, top);
1182 ordered_events__init(&top->qe.data[1], deliver_event, top);
1183 ordered_events__set_copy_on_queue(&top->qe.data[0], true);
1184 ordered_events__set_copy_on_queue(&top->qe.data[1], true);
1185 top->qe.in = &top->qe.data[0];
1186 pthread_mutex_init(&top->qe.mutex, NULL);
1187 pthread_cond_init(&top->qe.cond, NULL);
1190 static int __cmd_top(struct perf_top *top)
1192 struct record_opts *opts = &top->record_opts;
1193 pthread_t thread, thread_process;
1194 int ret;
1196 if (!top->annotation_opts.objdump_path) {
1197 ret = perf_env__lookup_objdump(&top->session->header.env,
1198 &top->annotation_opts.objdump_path);
1199 if (ret)
1200 return ret;
1203 ret = callchain_param__setup_sample_type(&callchain_param);
1204 if (ret)
1205 return ret;
1207 if (perf_session__register_idle_thread(top->session) < 0)
1208 return ret;
1210 if (top->nr_threads_synthesize > 1)
1211 perf_set_multithreaded();
1213 init_process_thread(top);
1215 if (opts->record_namespaces)
1216 top->tool.namespace_events = true;
1218 ret = perf_event__synthesize_bpf_events(top->session, perf_event__process,
1219 &top->session->machines.host,
1220 &top->record_opts);
1221 if (ret < 0)
1222 pr_debug("Couldn't synthesize BPF events: Pre-existing BPF programs won't have symbols resolved.\n");
1224 machine__synthesize_threads(&top->session->machines.host, &opts->target,
1225 top->evlist->threads, false,
1226 top->nr_threads_synthesize);
1228 if (top->nr_threads_synthesize > 1)
1229 perf_set_singlethreaded();
1231 if (perf_hpp_list.socket) {
1232 ret = perf_env__read_cpu_topology_map(&perf_env);
1233 if (ret < 0) {
1234 char errbuf[BUFSIZ];
1235 const char *err = str_error_r(-ret, errbuf, sizeof(errbuf));
1237 ui__error("Could not read the CPU topology map: %s\n", err);
1238 return ret;
1242 ret = perf_top__start_counters(top);
1243 if (ret)
1244 return ret;
1246 top->session->evlist = top->evlist;
1247 perf_session__set_id_hdr_size(top->session);
1250 * When perf is starting the traced process, all the events (apart from
1251 * group members) have enable_on_exec=1 set, so don't spoil it by
1252 * prematurely enabling them.
1254 * XXX 'top' still doesn't start workloads like record, trace, but should,
1255 * so leave the check here.
1257 if (!target__none(&opts->target))
1258 perf_evlist__enable(top->evlist);
1260 ret = -1;
1261 if (pthread_create(&thread_process, NULL, process_thread, top)) {
1262 ui__error("Could not create process thread.\n");
1263 return ret;
1266 if (pthread_create(&thread, NULL, (use_browser > 0 ? display_thread_tui :
1267 display_thread), top)) {
1268 ui__error("Could not create display thread.\n");
1269 goto out_join_thread;
1272 if (top->realtime_prio) {
1273 struct sched_param param;
1275 param.sched_priority = top->realtime_prio;
1276 if (sched_setscheduler(0, SCHED_FIFO, &param)) {
1277 ui__error("Could not set realtime priority.\n");
1278 goto out_join;
1282 /* Wait for a minimal set of events before starting the snapshot */
1283 perf_evlist__poll(top->evlist, 100);
1285 perf_top__mmap_read(top);
1287 while (!done) {
1288 u64 hits = top->samples;
1290 perf_top__mmap_read(top);
1292 if (opts->overwrite || (hits == top->samples))
1293 ret = perf_evlist__poll(top->evlist, 100);
1295 if (resize) {
1296 perf_top__resize(top);
1297 resize = 0;
1301 ret = 0;
1302 out_join:
1303 pthread_join(thread, NULL);
1304 out_join_thread:
1305 pthread_cond_signal(&top->qe.cond);
1306 pthread_join(thread_process, NULL);
1307 return ret;
1310 static int
1311 callchain_opt(const struct option *opt, const char *arg, int unset)
1313 symbol_conf.use_callchain = true;
1314 return record_callchain_opt(opt, arg, unset);
1317 static int
1318 parse_callchain_opt(const struct option *opt, const char *arg, int unset)
1320 struct callchain_param *callchain = opt->value;
1322 callchain->enabled = !unset;
1323 callchain->record_mode = CALLCHAIN_FP;
1326 * --no-call-graph
1328 if (unset) {
1329 symbol_conf.use_callchain = false;
1330 callchain->record_mode = CALLCHAIN_NONE;
1331 return 0;
1334 return parse_callchain_top_opt(arg);
1337 static int perf_top_config(const char *var, const char *value, void *cb __maybe_unused)
1339 if (!strcmp(var, "top.call-graph")) {
1340 var = "call-graph.record-mode";
1341 return perf_default_config(var, value, cb);
1343 if (!strcmp(var, "top.children")) {
1344 symbol_conf.cumulate_callchain = perf_config_bool(var, value);
1345 return 0;
1348 return 0;
1351 static int
1352 parse_percent_limit(const struct option *opt, const char *arg,
1353 int unset __maybe_unused)
1355 struct perf_top *top = opt->value;
1357 top->min_percent = strtof(arg, NULL);
1358 return 0;
1361 const char top_callchain_help[] = CALLCHAIN_RECORD_HELP CALLCHAIN_REPORT_HELP
1362 "\n\t\t\t\tDefault: fp,graph,0.5,caller,function";
1364 int cmd_top(int argc, const char **argv)
1366 char errbuf[BUFSIZ];
1367 struct perf_top top = {
1368 .count_filter = 5,
1369 .delay_secs = 2,
1370 .record_opts = {
1371 .mmap_pages = UINT_MAX,
1372 .user_freq = UINT_MAX,
1373 .user_interval = ULLONG_MAX,
1374 .freq = 4000, /* 4 KHz */
1375 .target = {
1376 .uses_mmap = true,
1379 * FIXME: This will lose PERF_RECORD_MMAP and other metadata
1380 * when we pause, fix that and reenable. Probably using a
1381 * separate evlist with a dummy event, i.e. a non-overwrite
1382 * ring buffer just for metadata events, while PERF_RECORD_SAMPLE
1383 * stays in overwrite mode. -acme
1384 * */
1385 .overwrite = 0,
1386 .sample_time = true,
1387 .sample_time_set = true,
1389 .max_stack = sysctl__max_stack(),
1390 .annotation_opts = annotation__default_options,
1391 .nr_threads_synthesize = UINT_MAX,
1393 struct record_opts *opts = &top.record_opts;
1394 struct target *target = &opts->target;
1395 const struct option options[] = {
1396 OPT_CALLBACK('e', "event", &top.evlist, "event",
1397 "event selector. use 'perf list' to list available events",
1398 parse_events_option),
1399 OPT_U64('c', "count", &opts->user_interval, "event period to sample"),
1400 OPT_STRING('p', "pid", &target->pid, "pid",
1401 "profile events on existing process id"),
1402 OPT_STRING('t', "tid", &target->tid, "tid",
1403 "profile events on existing thread id"),
1404 OPT_BOOLEAN('a', "all-cpus", &target->system_wide,
1405 "system-wide collection from all CPUs"),
1406 OPT_STRING('C', "cpu", &target->cpu_list, "cpu",
1407 "list of cpus to monitor"),
1408 OPT_STRING('k', "vmlinux", &symbol_conf.vmlinux_name,
1409 "file", "vmlinux pathname"),
1410 OPT_BOOLEAN(0, "ignore-vmlinux", &symbol_conf.ignore_vmlinux,
1411 "don't load vmlinux even if found"),
1412 OPT_STRING(0, "kallsyms", &symbol_conf.kallsyms_name,
1413 "file", "kallsyms pathname"),
1414 OPT_BOOLEAN('K', "hide_kernel_symbols", &top.hide_kernel_symbols,
1415 "hide kernel symbols"),
1416 OPT_CALLBACK('m', "mmap-pages", &opts->mmap_pages, "pages",
1417 "number of mmap data pages",
1418 perf_evlist__parse_mmap_pages),
1419 OPT_INTEGER('r', "realtime", &top.realtime_prio,
1420 "collect data with this RT SCHED_FIFO priority"),
1421 OPT_INTEGER('d', "delay", &top.delay_secs,
1422 "number of seconds to delay between refreshes"),
1423 OPT_BOOLEAN('D', "dump-symtab", &top.dump_symtab,
1424 "dump the symbol table used for profiling"),
1425 OPT_INTEGER('f', "count-filter", &top.count_filter,
1426 "only display functions with more events than this"),
1427 OPT_BOOLEAN(0, "group", &opts->group,
1428 "put the counters into a counter group"),
1429 OPT_BOOLEAN('i', "no-inherit", &opts->no_inherit,
1430 "child tasks do not inherit counters"),
1431 OPT_STRING(0, "sym-annotate", &top.sym_filter, "symbol name",
1432 "symbol to annotate"),
1433 OPT_BOOLEAN('z', "zero", &top.zero, "zero history across updates"),
1434 OPT_CALLBACK('F', "freq", &top.record_opts, "freq or 'max'",
1435 "profile at this frequency",
1436 record__parse_freq),
1437 OPT_INTEGER('E', "entries", &top.print_entries,
1438 "display this many functions"),
1439 OPT_BOOLEAN('U', "hide_user_symbols", &top.hide_user_symbols,
1440 "hide user symbols"),
1441 OPT_BOOLEAN(0, "tui", &top.use_tui, "Use the TUI interface"),
1442 OPT_BOOLEAN(0, "stdio", &top.use_stdio, "Use the stdio interface"),
1443 OPT_INCR('v', "verbose", &verbose,
1444 "be more verbose (show counter open errors, etc)"),
1445 OPT_STRING('s', "sort", &sort_order, "key[,key2...]",
1446 "sort by key(s): pid, comm, dso, symbol, parent, cpu, srcline, ..."
1447 " Please refer the man page for the complete list."),
1448 OPT_STRING(0, "fields", &field_order, "key[,keys...]",
1449 "output field(s): overhead, period, sample plus all of sort keys"),
1450 OPT_BOOLEAN('n', "show-nr-samples", &symbol_conf.show_nr_samples,
1451 "Show a column with the number of samples"),
1452 OPT_CALLBACK_NOOPT('g', NULL, &callchain_param,
1453 NULL, "enables call-graph recording and display",
1454 &callchain_opt),
1455 OPT_CALLBACK(0, "call-graph", &callchain_param,
1456 "record_mode[,record_size],print_type,threshold[,print_limit],order,sort_key[,branch]",
1457 top_callchain_help, &parse_callchain_opt),
1458 OPT_BOOLEAN(0, "children", &symbol_conf.cumulate_callchain,
1459 "Accumulate callchains of children and show total overhead as well"),
1460 OPT_INTEGER(0, "max-stack", &top.max_stack,
1461 "Set the maximum stack depth when parsing the callchain. "
1462 "Default: kernel.perf_event_max_stack or " __stringify(PERF_MAX_STACK_DEPTH)),
1463 OPT_CALLBACK(0, "ignore-callees", NULL, "regex",
1464 "ignore callees of these functions in call graphs",
1465 report_parse_ignore_callees_opt),
1466 OPT_BOOLEAN(0, "show-total-period", &symbol_conf.show_total_period,
1467 "Show a column with the sum of periods"),
1468 OPT_STRING(0, "dsos", &symbol_conf.dso_list_str, "dso[,dso...]",
1469 "only consider symbols in these dsos"),
1470 OPT_STRING(0, "comms", &symbol_conf.comm_list_str, "comm[,comm...]",
1471 "only consider symbols in these comms"),
1472 OPT_STRING(0, "symbols", &symbol_conf.sym_list_str, "symbol[,symbol...]",
1473 "only consider these symbols"),
1474 OPT_BOOLEAN(0, "source", &top.annotation_opts.annotate_src,
1475 "Interleave source code with assembly code (default)"),
1476 OPT_BOOLEAN(0, "asm-raw", &top.annotation_opts.show_asm_raw,
1477 "Display raw encoding of assembly instructions (default)"),
1478 OPT_BOOLEAN(0, "demangle-kernel", &symbol_conf.demangle_kernel,
1479 "Enable kernel symbol demangling"),
1480 OPT_BOOLEAN(0, "no-bpf-event", &top.record_opts.no_bpf_event, "do not record bpf events"),
1481 OPT_STRING(0, "objdump", &top.annotation_opts.objdump_path, "path",
1482 "objdump binary to use for disassembly and annotations"),
1483 OPT_STRING('M', "disassembler-style", &top.annotation_opts.disassembler_style, "disassembler style",
1484 "Specify disassembler style (e.g. -M intel for intel syntax)"),
1485 OPT_STRING('u', "uid", &target->uid_str, "user", "user to profile"),
1486 OPT_CALLBACK(0, "percent-limit", &top, "percent",
1487 "Don't show entries under that percent", parse_percent_limit),
1488 OPT_CALLBACK(0, "percentage", NULL, "relative|absolute",
1489 "How to display percentage of filtered entries", parse_filter_percentage),
1490 OPT_STRING('w', "column-widths", &symbol_conf.col_width_list_str,
1491 "width[,width...]",
1492 "don't try to adjust column width, use these fixed values"),
1493 OPT_UINTEGER(0, "proc-map-timeout", &proc_map_timeout,
1494 "per thread proc mmap processing timeout in ms"),
1495 OPT_CALLBACK_NOOPT('b', "branch-any", &opts->branch_stack,
1496 "branch any", "sample any taken branches",
1497 parse_branch_stack),
1498 OPT_CALLBACK('j', "branch-filter", &opts->branch_stack,
1499 "branch filter mask", "branch stack filter modes",
1500 parse_branch_stack),
1501 OPT_BOOLEAN(0, "raw-trace", &symbol_conf.raw_trace,
1502 "Show raw trace event output (do not use print fmt or plugins)"),
1503 OPT_BOOLEAN(0, "hierarchy", &symbol_conf.report_hierarchy,
1504 "Show entries in a hierarchy"),
1505 OPT_BOOLEAN(0, "overwrite", &top.record_opts.overwrite,
1506 "Use a backward ring buffer, default: no"),
1507 OPT_BOOLEAN(0, "force", &symbol_conf.force, "don't complain, do it"),
1508 OPT_UINTEGER(0, "num-thread-synthesize", &top.nr_threads_synthesize,
1509 "number of thread to run event synthesize"),
1510 OPT_BOOLEAN(0, "namespaces", &opts->record_namespaces,
1511 "Record namespaces events"),
1512 OPT_END()
1514 struct perf_evlist *sb_evlist = NULL;
1515 const char * const top_usage[] = {
1516 "perf top [<options>]",
1517 NULL
1519 int status = hists__init();
1521 if (status < 0)
1522 return status;
1524 top.annotation_opts.min_pcnt = 5;
1525 top.annotation_opts.context = 4;
1527 top.evlist = perf_evlist__new();
1528 if (top.evlist == NULL)
1529 return -ENOMEM;
1531 status = perf_config(perf_top_config, &top);
1532 if (status)
1533 return status;
1535 argc = parse_options(argc, argv, options, top_usage, 0);
1536 if (argc)
1537 usage_with_options(top_usage, options);
1539 if (!top.evlist->nr_entries &&
1540 perf_evlist__add_default(top.evlist) < 0) {
1541 pr_err("Not enough memory for event selector list\n");
1542 goto out_delete_evlist;
1545 if (symbol_conf.report_hierarchy) {
1546 /* disable incompatible options */
1547 symbol_conf.event_group = false;
1548 symbol_conf.cumulate_callchain = false;
1550 if (field_order) {
1551 pr_err("Error: --hierarchy and --fields options cannot be used together\n");
1552 parse_options_usage(top_usage, options, "fields", 0);
1553 parse_options_usage(NULL, options, "hierarchy", 0);
1554 goto out_delete_evlist;
1558 if (opts->branch_stack && callchain_param.enabled)
1559 symbol_conf.show_branchflag_count = true;
1561 sort__mode = SORT_MODE__TOP;
1562 /* display thread wants entries to be collapsed in a different tree */
1563 perf_hpp_list.need_collapse = 1;
1565 if (top.use_stdio)
1566 use_browser = 0;
1567 else if (top.use_tui)
1568 use_browser = 1;
1570 setup_browser(false);
1572 if (setup_sorting(top.evlist) < 0) {
1573 if (sort_order)
1574 parse_options_usage(top_usage, options, "s", 1);
1575 if (field_order)
1576 parse_options_usage(sort_order ? NULL : top_usage,
1577 options, "fields", 0);
1578 goto out_delete_evlist;
1581 status = target__validate(target);
1582 if (status) {
1583 target__strerror(target, status, errbuf, BUFSIZ);
1584 ui__warning("%s\n", errbuf);
1587 status = target__parse_uid(target);
1588 if (status) {
1589 int saved_errno = errno;
1591 target__strerror(target, status, errbuf, BUFSIZ);
1592 ui__error("%s\n", errbuf);
1594 status = -saved_errno;
1595 goto out_delete_evlist;
1598 if (target__none(target))
1599 target->system_wide = true;
1601 if (perf_evlist__create_maps(top.evlist, target) < 0) {
1602 ui__error("Couldn't create thread/CPU maps: %s\n",
1603 errno == ENOENT ? "No such process" : str_error_r(errno, errbuf, sizeof(errbuf)));
1604 goto out_delete_evlist;
1607 if (top.delay_secs < 1)
1608 top.delay_secs = 1;
1610 if (record_opts__config(opts)) {
1611 status = -EINVAL;
1612 goto out_delete_evlist;
1615 top.sym_evsel = perf_evlist__first(top.evlist);
1617 if (!callchain_param.enabled) {
1618 symbol_conf.cumulate_callchain = false;
1619 perf_hpp__cancel_cumulate();
1622 if (symbol_conf.cumulate_callchain && !callchain_param.order_set)
1623 callchain_param.order = ORDER_CALLER;
1625 status = symbol__annotation_init();
1626 if (status < 0)
1627 goto out_delete_evlist;
1629 annotation_config__init();
1631 symbol_conf.try_vmlinux_path = (symbol_conf.vmlinux_name == NULL);
1632 status = symbol__init(NULL);
1633 if (status < 0)
1634 goto out_delete_evlist;
1636 sort__setup_elide(stdout);
1638 get_term_dimensions(&top.winsize);
1639 if (top.print_entries == 0) {
1640 perf_top__update_print_entries(&top);
1641 signal(SIGWINCH, winch_sig);
1644 top.session = perf_session__new(NULL, false, NULL);
1645 if (top.session == NULL) {
1646 status = -1;
1647 goto out_delete_evlist;
1650 if (!top.record_opts.no_bpf_event)
1651 bpf_event__add_sb_event(&sb_evlist, &perf_env);
1653 if (perf_evlist__start_sb_thread(sb_evlist, target)) {
1654 pr_debug("Couldn't start the BPF side band thread:\nBPF programs starting from now on won't be annotatable\n");
1655 opts->no_bpf_event = true;
1658 status = __cmd_top(&top);
1660 if (!opts->no_bpf_event)
1661 perf_evlist__stop_sb_thread(sb_evlist);
1663 out_delete_evlist:
1664 perf_evlist__delete(top.evlist);
1665 perf_session__delete(top.session);
1667 return status;