1 // SPDX-License-Identifier: GPL-2.0-only 2 /* 3 * builtin-top.c 4 * 5 * Builtin top command: Display a continuously updated profile of 6 * any workload, CPU or specific PID. 7 * 8 * Copyright (C) 2008, Red Hat Inc, Ingo Molnar <mingo@redhat.com> 9 * 2011, Red Hat Inc, Arnaldo Carvalho de Melo <acme@redhat.com> 10 * 11 * Improvements and fixes by: 12 * 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> 18 */ 19 #include "builtin.h" 20 21 #include "perf.h" 22 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 "util/util.h" 38 #include <linux/rbtree.h> 39 #include <subcmd/parse-options.h> 40 #include "util/parse-events.h" 41 #include "util/cpumap.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" 48 49 #include "util/debug.h" 50 #include "util/ordered-events.h" 51 52 #include <assert.h> 53 #include <elf.h> 54 #include <fcntl.h> 55 56 #include <stdio.h> 57 #include <termios.h> 58 #include <unistd.h> 59 #include <inttypes.h> 60 61 #include <errno.h> 62 #include <time.h> 63 #include <sched.h> 64 #include <signal.h> 65 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> 74 75 #include <linux/stringify.h> 76 #include <linux/time64.h> 77 #include <linux/types.h> 78 79 #include <linux/ctype.h> 80 81 static volatile int done; 82 static volatile int resize; 83 84 #define HEADER_LINE_NR 5 85 86 static void perf_top__update_print_entries(struct perf_top *top) 87 { 88 top->print_entries = top->winsize.ws_row - HEADER_LINE_NR; 89 } 90 91 static void winch_sig(int sig __maybe_unused) 92 { 93 resize = 1; 94 } 95 96 static void perf_top__resize(struct perf_top *top) 97 { 98 get_term_dimensions(&top->winsize); 99 perf_top__update_print_entries(top); 100 } 101 102 static int perf_top__parse_source(struct perf_top *top, struct hist_entry *he) 103 { 104 struct evsel *evsel; 105 struct symbol *sym; 106 struct annotation *notes; 107 struct map *map; 108 int err = -1; 109 110 if (!he || !he->ms.sym) 111 return -1; 112 113 evsel = hists_to_evsel(he->hists); 114 115 sym = he->ms.sym; 116 map = he->ms.map; 117 118 /* 119 * We can't annotate with just /proc/kallsyms 120 */ 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; 127 } 128 129 notes = symbol__annotation(sym); 130 pthread_mutex_lock(¬es->lock); 131 132 if (!symbol__hists(sym, top->evlist->core.nr_entries)) { 133 pthread_mutex_unlock(¬es->lock); 134 pr_err("Not enough memory for annotating '%s' symbol!\n", 135 sym->name); 136 sleep(1); 137 return err; 138 } 139 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); 147 } 148 149 pthread_mutex_unlock(¬es->lock); 150 return err; 151 } 152 153 static void __zero_source_counters(struct hist_entry *he) 154 { 155 struct symbol *sym = he->ms.sym; 156 symbol__annotate_zero_histograms(sym); 157 } 158 159 static void ui__warn_map_erange(struct map *map, struct symbol *sym, u64 ip) 160 { 161 struct utsname uts; 162 int err = uname(&uts); 163 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); 182 183 map->erange_warned = true; 184 } 185 186 static void perf_top__record_precise_ip(struct perf_top *top, 187 struct hist_entry *he, 188 struct perf_sample *sample, 189 struct evsel *evsel, u64 ip) 190 { 191 struct annotation *notes; 192 struct symbol *sym = he->ms.sym; 193 int err = 0; 194 195 if (sym == NULL || (use_browser == 0 && 196 (top->sym_filter_entry == NULL || 197 top->sym_filter_entry->ms.sym != sym))) 198 return; 199 200 notes = symbol__annotation(sym); 201 202 if (pthread_mutex_trylock(¬es->lock)) 203 return; 204 205 err = hist_entry__inc_addr_samples(he, sample, evsel, ip); 206 207 pthread_mutex_unlock(¬es->lock); 208 209 if (unlikely(err)) { 210 /* 211 * This function is now called with he->hists->lock held. 212 * Release it before going to sleep. 213 */ 214 pthread_mutex_unlock(&he->hists->lock); 215 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); 222 } 223 224 pthread_mutex_lock(&he->hists->lock); 225 } 226 } 227 228 static void perf_top__show_details(struct perf_top *top) 229 { 230 struct hist_entry *he = top->sym_filter_entry; 231 struct evsel *evsel; 232 struct annotation *notes; 233 struct symbol *symbol; 234 int more; 235 236 if (!he) 237 return; 238 239 evsel = hists_to_evsel(he->hists); 240 241 symbol = he->ms.sym; 242 notes = symbol__annotation(symbol); 243 244 pthread_mutex_lock(¬es->lock); 245 246 symbol__calc_percent(symbol, evsel); 247 248 if (notes->src == NULL) 249 goto out_unlock; 250 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); 253 254 more = symbol__annotate_printf(symbol, he->ms.map, top->sym_evsel, &top->annotation_opts); 255 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); 261 } 262 if (more != 0) 263 printf("%d lines not displayed, maybe increase display entries [e]\n", more); 264 out_unlock: 265 pthread_mutex_unlock(¬es->lock); 266 } 267 268 static void perf_top__resort_hists(struct perf_top *t) 269 { 270 struct evlist *evlist = t->evlist; 271 struct evsel *pos; 272 273 evlist__for_each_entry(evlist, pos) { 274 struct hists *hists = evsel__hists(pos); 275 276 /* 277 * unlink existing entries so that they can be linked 278 * in a correct order in hists__match() below. 279 */ 280 hists__unlink(hists); 281 282 if (evlist->enabled) { 283 if (t->zero) { 284 hists__delete_entries(hists); 285 } else { 286 hists__decay_entries(hists, t->hide_user_symbols, 287 t->hide_kernel_symbols); 288 } 289 } 290 291 hists__collapse_resort(hists, NULL); 292 293 /* Non-group events are considered as leader */ 294 if (symbol_conf.event_group && 295 !perf_evsel__is_group_leader(pos)) { 296 struct hists *leader_hists = evsel__hists(pos->leader); 297 298 hists__match(leader_hists, hists); 299 hists__link(leader_hists, hists); 300 } 301 } 302 303 evlist__for_each_entry(evlist, pos) { 304 perf_evsel__output_resort(pos, NULL); 305 } 306 } 307 308 static void perf_top__print_sym_table(struct perf_top *top) 309 { 310 char bf[160]; 311 int printed = 0; 312 const int win_width = top->winsize.ws_col - 1; 313 struct evsel *evsel = top->sym_evsel; 314 struct hists *hists = evsel__hists(evsel); 315 316 puts(CONSOLE_CLEAR); 317 318 perf_top__header_snprintf(top, bf, sizeof(bf)); 319 printf("%s\n", bf); 320 321 printf("%-*.*s\n", win_width, win_width, graph_dotted_line); 322 323 if (!top->record_opts.overwrite && 324 (hists->stats.nr_lost_warned != 325 hists->stats.nr_events[PERF_RECORD_LOST])) { 326 hists->stats.nr_lost_warned = 327 hists->stats.nr_events[PERF_RECORD_LOST]; 328 color_fprintf(stdout, PERF_COLOR_RED, 329 "WARNING: LOST %d chunks, Check IO/CPU overload", 330 hists->stats.nr_lost_warned); 331 ++printed; 332 } 333 334 if (top->sym_filter_entry) { 335 perf_top__show_details(top); 336 return; 337 } 338 339 perf_top__resort_hists(top); 340 341 hists__output_recalc_col_len(hists, top->print_entries - printed); 342 putchar('\n'); 343 hists__fprintf(hists, false, top->print_entries - printed, win_width, 344 top->min_percent, stdout, !symbol_conf.use_callchain); 345 } 346 347 static void prompt_integer(int *target, const char *msg) 348 { 349 char *buf = malloc(0), *p; 350 size_t dummy = 0; 351 int tmp; 352 353 fprintf(stdout, "\n%s: ", msg); 354 if (getline(&buf, &dummy, stdin) < 0) 355 return; 356 357 p = strchr(buf, '\n'); 358 if (p) 359 *p = 0; 360 361 p = buf; 362 while(*p) { 363 if (!isdigit(*p)) 364 goto out_free; 365 p++; 366 } 367 tmp = strtoul(buf, NULL, 10); 368 *target = tmp; 369 out_free: 370 free(buf); 371 } 372 373 static void prompt_percent(int *target, const char *msg) 374 { 375 int tmp = 0; 376 377 prompt_integer(&tmp, msg); 378 if (tmp >= 0 && tmp <= 100) 379 *target = tmp; 380 } 381 382 static void perf_top__prompt_symbol(struct perf_top *top, const char *msg) 383 { 384 char *buf = malloc(0), *p; 385 struct hist_entry *syme = top->sym_filter_entry, *n, *found = NULL; 386 struct hists *hists = evsel__hists(top->sym_evsel); 387 struct rb_node *next; 388 size_t dummy = 0; 389 390 /* zero counters of active symbol */ 391 if (syme) { 392 __zero_source_counters(syme); 393 top->sym_filter_entry = NULL; 394 } 395 396 fprintf(stdout, "\n%s: ", msg); 397 if (getline(&buf, &dummy, stdin) < 0) 398 goto out_free; 399 400 p = strchr(buf, '\n'); 401 if (p) 402 *p = 0; 403 404 next = rb_first_cached(&hists->entries); 405 while (next) { 406 n = rb_entry(next, struct hist_entry, rb_node); 407 if (n->ms.sym && !strcmp(buf, n->ms.sym->name)) { 408 found = n; 409 break; 410 } 411 next = rb_next(&n->rb_node); 412 } 413 414 if (!found) { 415 fprintf(stderr, "Sorry, %s is not active.\n", buf); 416 sleep(1); 417 } else 418 perf_top__parse_source(top, found); 419 420 out_free: 421 free(buf); 422 } 423 424 static void perf_top__print_mapped_keys(struct perf_top *top) 425 { 426 char *name = NULL; 427 428 if (top->sym_filter_entry) { 429 struct symbol *sym = top->sym_filter_entry->ms.sym; 430 name = sym->name; 431 } 432 433 fprintf(stdout, "\nMapped keys:\n"); 434 fprintf(stdout, "\t[d] display refresh delay. \t(%d)\n", top->delay_secs); 435 fprintf(stdout, "\t[e] display entries (lines). \t(%d)\n", top->print_entries); 436 437 if (top->evlist->core.nr_entries > 1) 438 fprintf(stdout, "\t[E] active event counter. \t(%s)\n", perf_evsel__name(top->sym_evsel)); 439 440 fprintf(stdout, "\t[f] profile display filter (count). \t(%d)\n", top->count_filter); 441 442 fprintf(stdout, "\t[F] annotate display filter (percent). \t(%d%%)\n", top->annotation_opts.min_pcnt); 443 fprintf(stdout, "\t[s] annotate symbol. \t(%s)\n", name?: "NULL"); 444 fprintf(stdout, "\t[S] stop annotation.\n"); 445 446 fprintf(stdout, 447 "\t[K] hide kernel symbols. \t(%s)\n", 448 top->hide_kernel_symbols ? "yes" : "no"); 449 fprintf(stdout, 450 "\t[U] hide user symbols. \t(%s)\n", 451 top->hide_user_symbols ? "yes" : "no"); 452 fprintf(stdout, "\t[z] toggle sample zeroing. \t(%d)\n", top->zero ? 1 : 0); 453 fprintf(stdout, "\t[qQ] quit.\n"); 454 } 455 456 static int perf_top__key_mapped(struct perf_top *top, int c) 457 { 458 switch (c) { 459 case 'd': 460 case 'e': 461 case 'f': 462 case 'z': 463 case 'q': 464 case 'Q': 465 case 'K': 466 case 'U': 467 case 'F': 468 case 's': 469 case 'S': 470 return 1; 471 case 'E': 472 return top->evlist->core.nr_entries > 1 ? 1 : 0; 473 default: 474 break; 475 } 476 477 return 0; 478 } 479 480 static bool perf_top__handle_keypress(struct perf_top *top, int c) 481 { 482 bool ret = true; 483 484 if (!perf_top__key_mapped(top, c)) { 485 struct pollfd stdin_poll = { .fd = 0, .events = POLLIN }; 486 struct termios save; 487 488 perf_top__print_mapped_keys(top); 489 fprintf(stdout, "\nEnter selection, or unmapped key to continue: "); 490 fflush(stdout); 491 492 set_term_quiet_input(&save); 493 494 poll(&stdin_poll, 1, -1); 495 c = getc(stdin); 496 497 tcsetattr(0, TCSAFLUSH, &save); 498 if (!perf_top__key_mapped(top, c)) 499 return ret; 500 } 501 502 switch (c) { 503 case 'd': 504 prompt_integer(&top->delay_secs, "Enter display delay"); 505 if (top->delay_secs < 1) 506 top->delay_secs = 1; 507 break; 508 case 'e': 509 prompt_integer(&top->print_entries, "Enter display entries (lines)"); 510 if (top->print_entries == 0) { 511 perf_top__resize(top); 512 signal(SIGWINCH, winch_sig); 513 } else { 514 signal(SIGWINCH, SIG_DFL); 515 } 516 break; 517 case 'E': 518 if (top->evlist->core.nr_entries > 1) { 519 /* Select 0 as the default event: */ 520 int counter = 0; 521 522 fprintf(stderr, "\nAvailable events:"); 523 524 evlist__for_each_entry(top->evlist, top->sym_evsel) 525 fprintf(stderr, "\n\t%d %s", top->sym_evsel->idx, perf_evsel__name(top->sym_evsel)); 526 527 prompt_integer(&counter, "Enter details event counter"); 528 529 if (counter >= top->evlist->core.nr_entries) { 530 top->sym_evsel = perf_evlist__first(top->evlist); 531 fprintf(stderr, "Sorry, no such event, using %s.\n", perf_evsel__name(top->sym_evsel)); 532 sleep(1); 533 break; 534 } 535 evlist__for_each_entry(top->evlist, top->sym_evsel) 536 if (top->sym_evsel->idx == counter) 537 break; 538 } else 539 top->sym_evsel = perf_evlist__first(top->evlist); 540 break; 541 case 'f': 542 prompt_integer(&top->count_filter, "Enter display event count filter"); 543 break; 544 case 'F': 545 prompt_percent(&top->annotation_opts.min_pcnt, 546 "Enter details display event filter (percent)"); 547 break; 548 case 'K': 549 top->hide_kernel_symbols = !top->hide_kernel_symbols; 550 break; 551 case 'q': 552 case 'Q': 553 printf("exiting.\n"); 554 if (top->dump_symtab) 555 perf_session__fprintf_dsos(top->session, stderr); 556 ret = false; 557 break; 558 case 's': 559 perf_top__prompt_symbol(top, "Enter details symbol"); 560 break; 561 case 'S': 562 if (!top->sym_filter_entry) 563 break; 564 else { 565 struct hist_entry *syme = top->sym_filter_entry; 566 567 top->sym_filter_entry = NULL; 568 __zero_source_counters(syme); 569 } 570 break; 571 case 'U': 572 top->hide_user_symbols = !top->hide_user_symbols; 573 break; 574 case 'z': 575 top->zero = !top->zero; 576 break; 577 default: 578 break; 579 } 580 581 return ret; 582 } 583 584 static void perf_top__sort_new_samples(void *arg) 585 { 586 struct perf_top *t = arg; 587 588 if (t->evlist->selected != NULL) 589 t->sym_evsel = t->evlist->selected; 590 591 perf_top__resort_hists(t); 592 593 if (t->lost || t->drop) 594 pr_warning("Too slow to read ring buffer (change period (-c/-F) or limit CPUs (-C)\n"); 595 } 596 597 static void stop_top(void) 598 { 599 session_done = 1; 600 done = 1; 601 } 602 603 static void *display_thread_tui(void *arg) 604 { 605 struct evsel *pos; 606 struct perf_top *top = arg; 607 const char *help = "For a higher level overview, try: perf top --sort comm,dso"; 608 struct hist_browser_timer hbt = { 609 .timer = perf_top__sort_new_samples, 610 .arg = top, 611 .refresh = top->delay_secs, 612 }; 613 614 /* In order to read symbols from other namespaces perf to needs to call 615 * setns(2). This isn't permitted if the struct_fs has multiple users. 616 * unshare(2) the fs so that we may continue to setns into namespaces 617 * that we're observing. 618 */ 619 unshare(CLONE_FS); 620 621 prctl(PR_SET_NAME, "perf-top-UI", 0, 0, 0); 622 623 perf_top__sort_new_samples(top); 624 625 /* 626 * Initialize the uid_filter_str, in the future the TUI will allow 627 * Zooming in/out UIDs. For now just use whatever the user passed 628 * via --uid. 629 */ 630 evlist__for_each_entry(top->evlist, pos) { 631 struct hists *hists = evsel__hists(pos); 632 hists->uid_filter_str = top->record_opts.target.uid_str; 633 } 634 635 perf_evlist__tui_browse_hists(top->evlist, help, &hbt, 636 top->min_percent, 637 &top->session->header.env, 638 !top->record_opts.overwrite, 639 &top->annotation_opts); 640 641 stop_top(); 642 return NULL; 643 } 644 645 static void display_sig(int sig __maybe_unused) 646 { 647 stop_top(); 648 } 649 650 static void display_setup_sig(void) 651 { 652 signal(SIGSEGV, sighandler_dump_stack); 653 signal(SIGFPE, sighandler_dump_stack); 654 signal(SIGINT, display_sig); 655 signal(SIGQUIT, display_sig); 656 signal(SIGTERM, display_sig); 657 } 658 659 static void *display_thread(void *arg) 660 { 661 struct pollfd stdin_poll = { .fd = 0, .events = POLLIN }; 662 struct termios save; 663 struct perf_top *top = arg; 664 int delay_msecs, c; 665 666 /* In order to read symbols from other namespaces perf to needs to call 667 * setns(2). This isn't permitted if the struct_fs has multiple users. 668 * unshare(2) the fs so that we may continue to setns into namespaces 669 * that we're observing. 670 */ 671 unshare(CLONE_FS); 672 673 prctl(PR_SET_NAME, "perf-top-UI", 0, 0, 0); 674 675 display_setup_sig(); 676 pthread__unblock_sigwinch(); 677 repeat: 678 delay_msecs = top->delay_secs * MSEC_PER_SEC; 679 set_term_quiet_input(&save); 680 /* trash return*/ 681 getc(stdin); 682 683 while (!done) { 684 perf_top__print_sym_table(top); 685 /* 686 * Either timeout expired or we got an EINTR due to SIGWINCH, 687 * refresh screen in both cases. 688 */ 689 switch (poll(&stdin_poll, 1, delay_msecs)) { 690 case 0: 691 continue; 692 case -1: 693 if (errno == EINTR) 694 continue; 695 __fallthrough; 696 default: 697 c = getc(stdin); 698 tcsetattr(0, TCSAFLUSH, &save); 699 700 if (perf_top__handle_keypress(top, c)) 701 goto repeat; 702 stop_top(); 703 } 704 } 705 706 tcsetattr(0, TCSAFLUSH, &save); 707 return NULL; 708 } 709 710 static int hist_iter__top_callback(struct hist_entry_iter *iter, 711 struct addr_location *al, bool single, 712 void *arg) 713 { 714 struct perf_top *top = arg; 715 struct hist_entry *he = iter->he; 716 struct evsel *evsel = iter->evsel; 717 718 if (perf_hpp_list.sym && single) 719 perf_top__record_precise_ip(top, he, iter->sample, evsel, al->addr); 720 721 hist__account_cycles(iter->sample->branch_stack, al, iter->sample, 722 !(top->record_opts.branch_stack & PERF_SAMPLE_BRANCH_ANY)); 723 return 0; 724 } 725 726 static void perf_event__process_sample(struct perf_tool *tool, 727 const union perf_event *event, 728 struct evsel *evsel, 729 struct perf_sample *sample, 730 struct machine *machine) 731 { 732 struct perf_top *top = container_of(tool, struct perf_top, tool); 733 struct addr_location al; 734 int err; 735 736 if (!machine && perf_guest) { 737 static struct intlist *seen; 738 739 if (!seen) 740 seen = intlist__new(NULL); 741 742 if (!intlist__has_entry(seen, sample->pid)) { 743 pr_err("Can't find guest [%d]'s kernel information\n", 744 sample->pid); 745 intlist__add(seen, sample->pid); 746 } 747 return; 748 } 749 750 if (!machine) { 751 pr_err("%u unprocessable samples recorded.\r", 752 top->session->evlist->stats.nr_unprocessable_samples++); 753 return; 754 } 755 756 if (event->header.misc & PERF_RECORD_MISC_EXACT_IP) 757 top->exact_samples++; 758 759 if (machine__resolve(machine, &al, sample) < 0) 760 return; 761 762 if (!machine->kptr_restrict_warned && 763 symbol_conf.kptr_restrict && 764 al.cpumode == PERF_RECORD_MISC_KERNEL) { 765 if (!perf_evlist__exclude_kernel(top->session->evlist)) { 766 ui__warning( 767 "Kernel address maps (/proc/{kallsyms,modules}) are restricted.\n\n" 768 "Check /proc/sys/kernel/kptr_restrict and /proc/sys/kernel/perf_event_paranoid.\n\n" 769 "Kernel%s samples will not be resolved.\n", 770 al.map && map__has_symbols(al.map) ? 771 " modules" : ""); 772 if (use_browser <= 0) 773 sleep(5); 774 } 775 machine->kptr_restrict_warned = true; 776 } 777 778 if (al.sym == NULL && al.map != NULL) { 779 const char *msg = "Kernel samples will not be resolved.\n"; 780 /* 781 * As we do lazy loading of symtabs we only will know if the 782 * specified vmlinux file is invalid when we actually have a 783 * hit in kernel space and then try to load it. So if we get 784 * here and there are _no_ symbols in the DSO backing the 785 * kernel map, bail out. 786 * 787 * We may never get here, for instance, if we use -K/ 788 * --hide-kernel-symbols, even if the user specifies an 789 * invalid --vmlinux ;-) 790 */ 791 if (!machine->kptr_restrict_warned && !top->vmlinux_warned && 792 __map__is_kernel(al.map) && map__has_symbols(al.map)) { 793 if (symbol_conf.vmlinux_name) { 794 char serr[256]; 795 dso__strerror_load(al.map->dso, serr, sizeof(serr)); 796 ui__warning("The %s file can't be used: %s\n%s", 797 symbol_conf.vmlinux_name, serr, msg); 798 } else { 799 ui__warning("A vmlinux file was not found.\n%s", 800 msg); 801 } 802 803 if (use_browser <= 0) 804 sleep(5); 805 top->vmlinux_warned = true; 806 } 807 } 808 809 if (al.sym == NULL || !al.sym->idle) { 810 struct hists *hists = evsel__hists(evsel); 811 struct hist_entry_iter iter = { 812 .evsel = evsel, 813 .sample = sample, 814 .add_entry_cb = hist_iter__top_callback, 815 }; 816 817 if (symbol_conf.cumulate_callchain) 818 iter.ops = &hist_iter_cumulative; 819 else 820 iter.ops = &hist_iter_normal; 821 822 pthread_mutex_lock(&hists->lock); 823 824 err = hist_entry_iter__add(&iter, &al, top->max_stack, top); 825 if (err < 0) 826 pr_err("Problem incrementing symbol period, skipping event\n"); 827 828 pthread_mutex_unlock(&hists->lock); 829 } 830 831 addr_location__put(&al); 832 } 833 834 static void 835 perf_top__process_lost(struct perf_top *top, union perf_event *event, 836 struct evsel *evsel) 837 { 838 struct hists *hists = evsel__hists(evsel); 839 840 top->lost += event->lost.lost; 841 top->lost_total += event->lost.lost; 842 hists->stats.total_lost += event->lost.lost; 843 } 844 845 static void 846 perf_top__process_lost_samples(struct perf_top *top, 847 union perf_event *event, 848 struct evsel *evsel) 849 { 850 struct hists *hists = evsel__hists(evsel); 851 852 top->lost += event->lost_samples.lost; 853 top->lost_total += event->lost_samples.lost; 854 hists->stats.total_lost_samples += event->lost_samples.lost; 855 } 856 857 static u64 last_timestamp; 858 859 static void perf_top__mmap_read_idx(struct perf_top *top, int idx) 860 { 861 struct record_opts *opts = &top->record_opts; 862 struct evlist *evlist = top->evlist; 863 struct perf_mmap *md; 864 union perf_event *event; 865 866 md = opts->overwrite ? &evlist->overwrite_mmap[idx] : &evlist->mmap[idx]; 867 if (perf_mmap__read_init(md) < 0) 868 return; 869 870 while ((event = perf_mmap__read_event(md)) != NULL) { 871 int ret; 872 873 ret = perf_evlist__parse_sample_timestamp(evlist, event, &last_timestamp); 874 if (ret && ret != -1) 875 break; 876 877 ret = ordered_events__queue(top->qe.in, event, last_timestamp, 0); 878 if (ret) 879 break; 880 881 perf_mmap__consume(md); 882 883 if (top->qe.rotate) { 884 pthread_mutex_lock(&top->qe.mutex); 885 top->qe.rotate = false; 886 pthread_cond_signal(&top->qe.cond); 887 pthread_mutex_unlock(&top->qe.mutex); 888 } 889 } 890 891 perf_mmap__read_done(md); 892 } 893 894 static void perf_top__mmap_read(struct perf_top *top) 895 { 896 bool overwrite = top->record_opts.overwrite; 897 struct evlist *evlist = top->evlist; 898 int i; 899 900 if (overwrite) 901 perf_evlist__toggle_bkw_mmap(evlist, BKW_MMAP_DATA_PENDING); 902 903 for (i = 0; i < top->evlist->nr_mmaps; i++) 904 perf_top__mmap_read_idx(top, i); 905 906 if (overwrite) { 907 perf_evlist__toggle_bkw_mmap(evlist, BKW_MMAP_EMPTY); 908 perf_evlist__toggle_bkw_mmap(evlist, BKW_MMAP_RUNNING); 909 } 910 } 911 912 /* 913 * Check per-event overwrite term. 914 * perf top should support consistent term for all events. 915 * - All events don't have per-event term 916 * E.g. "cpu/cpu-cycles/,cpu/instructions/" 917 * Nothing change, return 0. 918 * - All events have same per-event term 919 * E.g. "cpu/cpu-cycles,no-overwrite/,cpu/instructions,no-overwrite/ 920 * Using the per-event setting to replace the opts->overwrite if 921 * they are different, then return 0. 922 * - Events have different per-event term 923 * E.g. "cpu/cpu-cycles,overwrite/,cpu/instructions,no-overwrite/" 924 * Return -1 925 * - Some of the event set per-event term, but some not. 926 * E.g. "cpu/cpu-cycles/,cpu/instructions,no-overwrite/" 927 * Return -1 928 */ 929 static int perf_top__overwrite_check(struct perf_top *top) 930 { 931 struct record_opts *opts = &top->record_opts; 932 struct evlist *evlist = top->evlist; 933 struct perf_evsel_config_term *term; 934 struct list_head *config_terms; 935 struct evsel *evsel; 936 int set, overwrite = -1; 937 938 evlist__for_each_entry(evlist, evsel) { 939 set = -1; 940 config_terms = &evsel->config_terms; 941 list_for_each_entry(term, config_terms, list) { 942 if (term->type == PERF_EVSEL__CONFIG_TERM_OVERWRITE) 943 set = term->val.overwrite ? 1 : 0; 944 } 945 946 /* no term for current and previous event (likely) */ 947 if ((overwrite < 0) && (set < 0)) 948 continue; 949 950 /* has term for both current and previous event, compare */ 951 if ((overwrite >= 0) && (set >= 0) && (overwrite != set)) 952 return -1; 953 954 /* no term for current event but has term for previous one */ 955 if ((overwrite >= 0) && (set < 0)) 956 return -1; 957 958 /* has term for current event */ 959 if ((overwrite < 0) && (set >= 0)) { 960 /* if it's first event, set overwrite */ 961 if (evsel == perf_evlist__first(evlist)) 962 overwrite = set; 963 else 964 return -1; 965 } 966 } 967 968 if ((overwrite >= 0) && (opts->overwrite != overwrite)) 969 opts->overwrite = overwrite; 970 971 return 0; 972 } 973 974 static int perf_top_overwrite_fallback(struct perf_top *top, 975 struct evsel *evsel) 976 { 977 struct record_opts *opts = &top->record_opts; 978 struct evlist *evlist = top->evlist; 979 struct evsel *counter; 980 981 if (!opts->overwrite) 982 return 0; 983 984 /* only fall back when first event fails */ 985 if (evsel != perf_evlist__first(evlist)) 986 return 0; 987 988 evlist__for_each_entry(evlist, counter) 989 counter->core.attr.write_backward = false; 990 opts->overwrite = false; 991 pr_debug2("fall back to non-overwrite mode\n"); 992 return 1; 993 } 994 995 static int perf_top__start_counters(struct perf_top *top) 996 { 997 char msg[BUFSIZ]; 998 struct evsel *counter; 999 struct evlist *evlist = top->evlist; 1000 struct record_opts *opts = &top->record_opts; 1001 1002 if (perf_top__overwrite_check(top)) { 1003 ui__error("perf top only support consistent per-event " 1004 "overwrite setting for all events\n"); 1005 goto out_err; 1006 } 1007 1008 perf_evlist__config(evlist, opts, &callchain_param); 1009 1010 evlist__for_each_entry(evlist, counter) { 1011 try_again: 1012 if (evsel__open(counter, top->evlist->core.cpus, 1013 top->evlist->core.threads) < 0) { 1014 1015 /* 1016 * Specially handle overwrite fall back. 1017 * Because perf top is the only tool which has 1018 * overwrite mode by default, support 1019 * both overwrite and non-overwrite mode, and 1020 * require consistent mode for all events. 1021 * 1022 * May move it to generic code with more tools 1023 * have similar attribute. 1024 */ 1025 if (perf_missing_features.write_backward && 1026 perf_top_overwrite_fallback(top, counter)) 1027 goto try_again; 1028 1029 if (perf_evsel__fallback(counter, errno, msg, sizeof(msg))) { 1030 if (verbose > 0) 1031 ui__warning("%s\n", msg); 1032 goto try_again; 1033 } 1034 1035 perf_evsel__open_strerror(counter, &opts->target, 1036 errno, msg, sizeof(msg)); 1037 ui__error("%s\n", msg); 1038 goto out_err; 1039 } 1040 } 1041 1042 if (perf_evlist__mmap(evlist, opts->mmap_pages) < 0) { 1043 ui__error("Failed to mmap with %d (%s)\n", 1044 errno, str_error_r(errno, msg, sizeof(msg))); 1045 goto out_err; 1046 } 1047 1048 return 0; 1049 1050 out_err: 1051 return -1; 1052 } 1053 1054 static int callchain_param__setup_sample_type(struct callchain_param *callchain) 1055 { 1056 if (callchain->mode != CHAIN_NONE) { 1057 if (callchain_register_param(callchain) < 0) { 1058 ui__error("Can't register callchain params.\n"); 1059 return -EINVAL; 1060 } 1061 } 1062 1063 return 0; 1064 } 1065 1066 static struct ordered_events *rotate_queues(struct perf_top *top) 1067 { 1068 struct ordered_events *in = top->qe.in; 1069 1070 if (top->qe.in == &top->qe.data[1]) 1071 top->qe.in = &top->qe.data[0]; 1072 else 1073 top->qe.in = &top->qe.data[1]; 1074 1075 return in; 1076 } 1077 1078 static void *process_thread(void *arg) 1079 { 1080 struct perf_top *top = arg; 1081 1082 while (!done) { 1083 struct ordered_events *out, *in = top->qe.in; 1084 1085 if (!in->nr_events) { 1086 usleep(100); 1087 continue; 1088 } 1089 1090 out = rotate_queues(top); 1091 1092 pthread_mutex_lock(&top->qe.mutex); 1093 top->qe.rotate = true; 1094 pthread_cond_wait(&top->qe.cond, &top->qe.mutex); 1095 pthread_mutex_unlock(&top->qe.mutex); 1096 1097 if (ordered_events__flush(out, OE_FLUSH__TOP)) 1098 pr_err("failed to process events\n"); 1099 } 1100 1101 return NULL; 1102 } 1103 1104 /* 1105 * Allow only 'top->delay_secs' seconds behind samples. 1106 */ 1107 static int should_drop(struct ordered_event *qevent, struct perf_top *top) 1108 { 1109 union perf_event *event = qevent->event; 1110 u64 delay_timestamp; 1111 1112 if (event->header.type != PERF_RECORD_SAMPLE) 1113 return false; 1114 1115 delay_timestamp = qevent->timestamp + top->delay_secs * NSEC_PER_SEC; 1116 return delay_timestamp < last_timestamp; 1117 } 1118 1119 static int deliver_event(struct ordered_events *qe, 1120 struct ordered_event *qevent) 1121 { 1122 struct perf_top *top = qe->data; 1123 struct evlist *evlist = top->evlist; 1124 struct perf_session *session = top->session; 1125 union perf_event *event = qevent->event; 1126 struct perf_sample sample; 1127 struct evsel *evsel; 1128 struct machine *machine; 1129 int ret = -1; 1130 1131 if (should_drop(qevent, top)) { 1132 top->drop++; 1133 top->drop_total++; 1134 return 0; 1135 } 1136 1137 ret = perf_evlist__parse_sample(evlist, event, &sample); 1138 if (ret) { 1139 pr_err("Can't parse sample, err = %d\n", ret); 1140 goto next_event; 1141 } 1142 1143 evsel = perf_evlist__id2evsel(session->evlist, sample.id); 1144 assert(evsel != NULL); 1145 1146 if (event->header.type == PERF_RECORD_SAMPLE) { 1147 if (evswitch__discard(&top->evswitch, evsel)) 1148 return 0; 1149 ++top->samples; 1150 } 1151 1152 switch (sample.cpumode) { 1153 case PERF_RECORD_MISC_USER: 1154 ++top->us_samples; 1155 if (top->hide_user_symbols) 1156 goto next_event; 1157 machine = &session->machines.host; 1158 break; 1159 case PERF_RECORD_MISC_KERNEL: 1160 ++top->kernel_samples; 1161 if (top->hide_kernel_symbols) 1162 goto next_event; 1163 machine = &session->machines.host; 1164 break; 1165 case PERF_RECORD_MISC_GUEST_KERNEL: 1166 ++top->guest_kernel_samples; 1167 machine = perf_session__find_machine(session, 1168 sample.pid); 1169 break; 1170 case PERF_RECORD_MISC_GUEST_USER: 1171 ++top->guest_us_samples; 1172 /* 1173 * TODO: we don't process guest user from host side 1174 * except simple counting. 1175 */ 1176 goto next_event; 1177 default: 1178 if (event->header.type == PERF_RECORD_SAMPLE) 1179 goto next_event; 1180 machine = &session->machines.host; 1181 break; 1182 } 1183 1184 if (event->header.type == PERF_RECORD_SAMPLE) { 1185 perf_event__process_sample(&top->tool, event, evsel, 1186 &sample, machine); 1187 } else if (event->header.type == PERF_RECORD_LOST) { 1188 perf_top__process_lost(top, event, evsel); 1189 } else if (event->header.type == PERF_RECORD_LOST_SAMPLES) { 1190 perf_top__process_lost_samples(top, event, evsel); 1191 } else if (event->header.type < PERF_RECORD_MAX) { 1192 hists__inc_nr_events(evsel__hists(evsel), event->header.type); 1193 machine__process_event(machine, event, &sample); 1194 } else 1195 ++session->evlist->stats.nr_unknown_events; 1196 1197 ret = 0; 1198 next_event: 1199 return ret; 1200 } 1201 1202 static void init_process_thread(struct perf_top *top) 1203 { 1204 ordered_events__init(&top->qe.data[0], deliver_event, top); 1205 ordered_events__init(&top->qe.data[1], deliver_event, top); 1206 ordered_events__set_copy_on_queue(&top->qe.data[0], true); 1207 ordered_events__set_copy_on_queue(&top->qe.data[1], true); 1208 top->qe.in = &top->qe.data[0]; 1209 pthread_mutex_init(&top->qe.mutex, NULL); 1210 pthread_cond_init(&top->qe.cond, NULL); 1211 } 1212 1213 static int __cmd_top(struct perf_top *top) 1214 { 1215 struct record_opts *opts = &top->record_opts; 1216 pthread_t thread, thread_process; 1217 int ret; 1218 1219 if (!top->annotation_opts.objdump_path) { 1220 ret = perf_env__lookup_objdump(&top->session->header.env, 1221 &top->annotation_opts.objdump_path); 1222 if (ret) 1223 return ret; 1224 } 1225 1226 ret = callchain_param__setup_sample_type(&callchain_param); 1227 if (ret) 1228 return ret; 1229 1230 if (perf_session__register_idle_thread(top->session) < 0) 1231 return ret; 1232 1233 if (top->nr_threads_synthesize > 1) 1234 perf_set_multithreaded(); 1235 1236 init_process_thread(top); 1237 1238 if (opts->record_namespaces) 1239 top->tool.namespace_events = true; 1240 1241 ret = perf_event__synthesize_bpf_events(top->session, perf_event__process, 1242 &top->session->machines.host, 1243 &top->record_opts); 1244 if (ret < 0) 1245 pr_debug("Couldn't synthesize BPF events: Pre-existing BPF programs won't have symbols resolved.\n"); 1246 1247 machine__synthesize_threads(&top->session->machines.host, &opts->target, 1248 top->evlist->core.threads, false, 1249 top->nr_threads_synthesize); 1250 1251 if (top->nr_threads_synthesize > 1) 1252 perf_set_singlethreaded(); 1253 1254 if (perf_hpp_list.socket) { 1255 ret = perf_env__read_cpu_topology_map(&perf_env); 1256 if (ret < 0) { 1257 char errbuf[BUFSIZ]; 1258 const char *err = str_error_r(-ret, errbuf, sizeof(errbuf)); 1259 1260 ui__error("Could not read the CPU topology map: %s\n", err); 1261 return ret; 1262 } 1263 } 1264 1265 ret = perf_top__start_counters(top); 1266 if (ret) 1267 return ret; 1268 1269 top->session->evlist = top->evlist; 1270 perf_session__set_id_hdr_size(top->session); 1271 1272 /* 1273 * When perf is starting the traced process, all the events (apart from 1274 * group members) have enable_on_exec=1 set, so don't spoil it by 1275 * prematurely enabling them. 1276 * 1277 * XXX 'top' still doesn't start workloads like record, trace, but should, 1278 * so leave the check here. 1279 */ 1280 if (!target__none(&opts->target)) 1281 evlist__enable(top->evlist); 1282 1283 ret = -1; 1284 if (pthread_create(&thread_process, NULL, process_thread, top)) { 1285 ui__error("Could not create process thread.\n"); 1286 return ret; 1287 } 1288 1289 if (pthread_create(&thread, NULL, (use_browser > 0 ? display_thread_tui : 1290 display_thread), top)) { 1291 ui__error("Could not create display thread.\n"); 1292 goto out_join_thread; 1293 } 1294 1295 if (top->realtime_prio) { 1296 struct sched_param param; 1297 1298 param.sched_priority = top->realtime_prio; 1299 if (sched_setscheduler(0, SCHED_FIFO, ¶m)) { 1300 ui__error("Could not set realtime priority.\n"); 1301 goto out_join; 1302 } 1303 } 1304 1305 /* Wait for a minimal set of events before starting the snapshot */ 1306 perf_evlist__poll(top->evlist, 100); 1307 1308 perf_top__mmap_read(top); 1309 1310 while (!done) { 1311 u64 hits = top->samples; 1312 1313 perf_top__mmap_read(top); 1314 1315 if (opts->overwrite || (hits == top->samples)) 1316 ret = perf_evlist__poll(top->evlist, 100); 1317 1318 if (resize) { 1319 perf_top__resize(top); 1320 resize = 0; 1321 } 1322 } 1323 1324 ret = 0; 1325 out_join: 1326 pthread_join(thread, NULL); 1327 out_join_thread: 1328 pthread_cond_signal(&top->qe.cond); 1329 pthread_join(thread_process, NULL); 1330 return ret; 1331 } 1332 1333 static int 1334 callchain_opt(const struct option *opt, const char *arg, int unset) 1335 { 1336 symbol_conf.use_callchain = true; 1337 return record_callchain_opt(opt, arg, unset); 1338 } 1339 1340 static int 1341 parse_callchain_opt(const struct option *opt, const char *arg, int unset) 1342 { 1343 struct callchain_param *callchain = opt->value; 1344 1345 callchain->enabled = !unset; 1346 callchain->record_mode = CALLCHAIN_FP; 1347 1348 /* 1349 * --no-call-graph 1350 */ 1351 if (unset) { 1352 symbol_conf.use_callchain = false; 1353 callchain->record_mode = CALLCHAIN_NONE; 1354 return 0; 1355 } 1356 1357 return parse_callchain_top_opt(arg); 1358 } 1359 1360 static int perf_top_config(const char *var, const char *value, void *cb __maybe_unused) 1361 { 1362 if (!strcmp(var, "top.call-graph")) { 1363 var = "call-graph.record-mode"; 1364 return perf_default_config(var, value, cb); 1365 } 1366 if (!strcmp(var, "top.children")) { 1367 symbol_conf.cumulate_callchain = perf_config_bool(var, value); 1368 return 0; 1369 } 1370 1371 return 0; 1372 } 1373 1374 static int 1375 parse_percent_limit(const struct option *opt, const char *arg, 1376 int unset __maybe_unused) 1377 { 1378 struct perf_top *top = opt->value; 1379 1380 top->min_percent = strtof(arg, NULL); 1381 return 0; 1382 } 1383 1384 const char top_callchain_help[] = CALLCHAIN_RECORD_HELP CALLCHAIN_REPORT_HELP 1385 "\n\t\t\t\tDefault: fp,graph,0.5,caller,function"; 1386 1387 int cmd_top(int argc, const char **argv) 1388 { 1389 char errbuf[BUFSIZ]; 1390 struct perf_top top = { 1391 .count_filter = 5, 1392 .delay_secs = 2, 1393 .record_opts = { 1394 .mmap_pages = UINT_MAX, 1395 .user_freq = UINT_MAX, 1396 .user_interval = ULLONG_MAX, 1397 .freq = 4000, /* 4 KHz */ 1398 .target = { 1399 .uses_mmap = true, 1400 }, 1401 /* 1402 * FIXME: This will lose PERF_RECORD_MMAP and other metadata 1403 * when we pause, fix that and reenable. Probably using a 1404 * separate evlist with a dummy event, i.e. a non-overwrite 1405 * ring buffer just for metadata events, while PERF_RECORD_SAMPLE 1406 * stays in overwrite mode. -acme 1407 * */ 1408 .overwrite = 0, 1409 .sample_time = true, 1410 .sample_time_set = true, 1411 }, 1412 .max_stack = sysctl__max_stack(), 1413 .annotation_opts = annotation__default_options, 1414 .nr_threads_synthesize = UINT_MAX, 1415 }; 1416 struct record_opts *opts = &top.record_opts; 1417 struct target *target = &opts->target; 1418 const struct option options[] = { 1419 OPT_CALLBACK('e', "event", &top.evlist, "event", 1420 "event selector. use 'perf list' to list available events", 1421 parse_events_option), 1422 OPT_U64('c', "count", &opts->user_interval, "event period to sample"), 1423 OPT_STRING('p', "pid", &target->pid, "pid", 1424 "profile events on existing process id"), 1425 OPT_STRING('t', "tid", &target->tid, "tid", 1426 "profile events on existing thread id"), 1427 OPT_BOOLEAN('a', "all-cpus", &target->system_wide, 1428 "system-wide collection from all CPUs"), 1429 OPT_STRING('C', "cpu", &target->cpu_list, "cpu", 1430 "list of cpus to monitor"), 1431 OPT_STRING('k', "vmlinux", &symbol_conf.vmlinux_name, 1432 "file", "vmlinux pathname"), 1433 OPT_BOOLEAN(0, "ignore-vmlinux", &symbol_conf.ignore_vmlinux, 1434 "don't load vmlinux even if found"), 1435 OPT_STRING(0, "kallsyms", &symbol_conf.kallsyms_name, 1436 "file", "kallsyms pathname"), 1437 OPT_BOOLEAN('K', "hide_kernel_symbols", &top.hide_kernel_symbols, 1438 "hide kernel symbols"), 1439 OPT_CALLBACK('m', "mmap-pages", &opts->mmap_pages, "pages", 1440 "number of mmap data pages", 1441 perf_evlist__parse_mmap_pages), 1442 OPT_INTEGER('r', "realtime", &top.realtime_prio, 1443 "collect data with this RT SCHED_FIFO priority"), 1444 OPT_INTEGER('d', "delay", &top.delay_secs, 1445 "number of seconds to delay between refreshes"), 1446 OPT_BOOLEAN('D', "dump-symtab", &top.dump_symtab, 1447 "dump the symbol table used for profiling"), 1448 OPT_INTEGER('f', "count-filter", &top.count_filter, 1449 "only display functions with more events than this"), 1450 OPT_BOOLEAN(0, "group", &opts->group, 1451 "put the counters into a counter group"), 1452 OPT_BOOLEAN('i', "no-inherit", &opts->no_inherit, 1453 "child tasks do not inherit counters"), 1454 OPT_STRING(0, "sym-annotate", &top.sym_filter, "symbol name", 1455 "symbol to annotate"), 1456 OPT_BOOLEAN('z', "zero", &top.zero, "zero history across updates"), 1457 OPT_CALLBACK('F', "freq", &top.record_opts, "freq or 'max'", 1458 "profile at this frequency", 1459 record__parse_freq), 1460 OPT_INTEGER('E', "entries", &top.print_entries, 1461 "display this many functions"), 1462 OPT_BOOLEAN('U', "hide_user_symbols", &top.hide_user_symbols, 1463 "hide user symbols"), 1464 OPT_BOOLEAN(0, "tui", &top.use_tui, "Use the TUI interface"), 1465 OPT_BOOLEAN(0, "stdio", &top.use_stdio, "Use the stdio interface"), 1466 OPT_INCR('v', "verbose", &verbose, 1467 "be more verbose (show counter open errors, etc)"), 1468 OPT_STRING('s', "sort", &sort_order, "key[,key2...]", 1469 "sort by key(s): pid, comm, dso, symbol, parent, cpu, srcline, ..." 1470 " Please refer the man page for the complete list."), 1471 OPT_STRING(0, "fields", &field_order, "key[,keys...]", 1472 "output field(s): overhead, period, sample plus all of sort keys"), 1473 OPT_BOOLEAN('n', "show-nr-samples", &symbol_conf.show_nr_samples, 1474 "Show a column with the number of samples"), 1475 OPT_CALLBACK_NOOPT('g', NULL, &callchain_param, 1476 NULL, "enables call-graph recording and display", 1477 &callchain_opt), 1478 OPT_CALLBACK(0, "call-graph", &callchain_param, 1479 "record_mode[,record_size],print_type,threshold[,print_limit],order,sort_key[,branch]", 1480 top_callchain_help, &parse_callchain_opt), 1481 OPT_BOOLEAN(0, "children", &symbol_conf.cumulate_callchain, 1482 "Accumulate callchains of children and show total overhead as well"), 1483 OPT_INTEGER(0, "max-stack", &top.max_stack, 1484 "Set the maximum stack depth when parsing the callchain. " 1485 "Default: kernel.perf_event_max_stack or " __stringify(PERF_MAX_STACK_DEPTH)), 1486 OPT_CALLBACK(0, "ignore-callees", NULL, "regex", 1487 "ignore callees of these functions in call graphs", 1488 report_parse_ignore_callees_opt), 1489 OPT_BOOLEAN(0, "show-total-period", &symbol_conf.show_total_period, 1490 "Show a column with the sum of periods"), 1491 OPT_STRING(0, "dsos", &symbol_conf.dso_list_str, "dso[,dso...]", 1492 "only consider symbols in these dsos"), 1493 OPT_STRING(0, "comms", &symbol_conf.comm_list_str, "comm[,comm...]", 1494 "only consider symbols in these comms"), 1495 OPT_STRING(0, "symbols", &symbol_conf.sym_list_str, "symbol[,symbol...]", 1496 "only consider these symbols"), 1497 OPT_BOOLEAN(0, "source", &top.annotation_opts.annotate_src, 1498 "Interleave source code with assembly code (default)"), 1499 OPT_BOOLEAN(0, "asm-raw", &top.annotation_opts.show_asm_raw, 1500 "Display raw encoding of assembly instructions (default)"), 1501 OPT_BOOLEAN(0, "demangle-kernel", &symbol_conf.demangle_kernel, 1502 "Enable kernel symbol demangling"), 1503 OPT_BOOLEAN(0, "no-bpf-event", &top.record_opts.no_bpf_event, "do not record bpf events"), 1504 OPT_STRING(0, "objdump", &top.annotation_opts.objdump_path, "path", 1505 "objdump binary to use for disassembly and annotations"), 1506 OPT_STRING('M', "disassembler-style", &top.annotation_opts.disassembler_style, "disassembler style", 1507 "Specify disassembler style (e.g. -M intel for intel syntax)"), 1508 OPT_STRING('u', "uid", &target->uid_str, "user", "user to profile"), 1509 OPT_CALLBACK(0, "percent-limit", &top, "percent", 1510 "Don't show entries under that percent", parse_percent_limit), 1511 OPT_CALLBACK(0, "percentage", NULL, "relative|absolute", 1512 "How to display percentage of filtered entries", parse_filter_percentage), 1513 OPT_STRING('w', "column-widths", &symbol_conf.col_width_list_str, 1514 "width[,width...]", 1515 "don't try to adjust column width, use these fixed values"), 1516 OPT_UINTEGER(0, "proc-map-timeout", &proc_map_timeout, 1517 "per thread proc mmap processing timeout in ms"), 1518 OPT_CALLBACK_NOOPT('b', "branch-any", &opts->branch_stack, 1519 "branch any", "sample any taken branches", 1520 parse_branch_stack), 1521 OPT_CALLBACK('j', "branch-filter", &opts->branch_stack, 1522 "branch filter mask", "branch stack filter modes", 1523 parse_branch_stack), 1524 OPT_BOOLEAN(0, "raw-trace", &symbol_conf.raw_trace, 1525 "Show raw trace event output (do not use print fmt or plugins)"), 1526 OPT_BOOLEAN(0, "hierarchy", &symbol_conf.report_hierarchy, 1527 "Show entries in a hierarchy"), 1528 OPT_BOOLEAN(0, "overwrite", &top.record_opts.overwrite, 1529 "Use a backward ring buffer, default: no"), 1530 OPT_BOOLEAN(0, "force", &symbol_conf.force, "don't complain, do it"), 1531 OPT_UINTEGER(0, "num-thread-synthesize", &top.nr_threads_synthesize, 1532 "number of thread to run event synthesize"), 1533 OPT_BOOLEAN(0, "namespaces", &opts->record_namespaces, 1534 "Record namespaces events"), 1535 OPTS_EVSWITCH(&top.evswitch), 1536 OPT_END() 1537 }; 1538 struct evlist *sb_evlist = NULL; 1539 const char * const top_usage[] = { 1540 "perf top [<options>]", 1541 NULL 1542 }; 1543 int status = hists__init(); 1544 1545 if (status < 0) 1546 return status; 1547 1548 top.annotation_opts.min_pcnt = 5; 1549 top.annotation_opts.context = 4; 1550 1551 top.evlist = evlist__new(); 1552 if (top.evlist == NULL) 1553 return -ENOMEM; 1554 1555 status = perf_config(perf_top_config, &top); 1556 if (status) 1557 return status; 1558 1559 argc = parse_options(argc, argv, options, top_usage, 0); 1560 if (argc) 1561 usage_with_options(top_usage, options); 1562 1563 if (!top.evlist->core.nr_entries && 1564 perf_evlist__add_default(top.evlist) < 0) { 1565 pr_err("Not enough memory for event selector list\n"); 1566 goto out_delete_evlist; 1567 } 1568 1569 status = evswitch__init(&top.evswitch, top.evlist, stderr); 1570 if (status) 1571 goto out_delete_evlist; 1572 1573 if (symbol_conf.report_hierarchy) { 1574 /* disable incompatible options */ 1575 symbol_conf.event_group = false; 1576 symbol_conf.cumulate_callchain = false; 1577 1578 if (field_order) { 1579 pr_err("Error: --hierarchy and --fields options cannot be used together\n"); 1580 parse_options_usage(top_usage, options, "fields", 0); 1581 parse_options_usage(NULL, options, "hierarchy", 0); 1582 goto out_delete_evlist; 1583 } 1584 } 1585 1586 if (opts->branch_stack && callchain_param.enabled) 1587 symbol_conf.show_branchflag_count = true; 1588 1589 sort__mode = SORT_MODE__TOP; 1590 /* display thread wants entries to be collapsed in a different tree */ 1591 perf_hpp_list.need_collapse = 1; 1592 1593 if (top.use_stdio) 1594 use_browser = 0; 1595 else if (top.use_tui) 1596 use_browser = 1; 1597 1598 setup_browser(false); 1599 1600 if (setup_sorting(top.evlist) < 0) { 1601 if (sort_order) 1602 parse_options_usage(top_usage, options, "s", 1); 1603 if (field_order) 1604 parse_options_usage(sort_order ? NULL : top_usage, 1605 options, "fields", 0); 1606 goto out_delete_evlist; 1607 } 1608 1609 status = target__validate(target); 1610 if (status) { 1611 target__strerror(target, status, errbuf, BUFSIZ); 1612 ui__warning("%s\n", errbuf); 1613 } 1614 1615 status = target__parse_uid(target); 1616 if (status) { 1617 int saved_errno = errno; 1618 1619 target__strerror(target, status, errbuf, BUFSIZ); 1620 ui__error("%s\n", errbuf); 1621 1622 status = -saved_errno; 1623 goto out_delete_evlist; 1624 } 1625 1626 if (target__none(target)) 1627 target->system_wide = true; 1628 1629 if (perf_evlist__create_maps(top.evlist, target) < 0) { 1630 ui__error("Couldn't create thread/CPU maps: %s\n", 1631 errno == ENOENT ? "No such process" : str_error_r(errno, errbuf, sizeof(errbuf))); 1632 goto out_delete_evlist; 1633 } 1634 1635 if (top.delay_secs < 1) 1636 top.delay_secs = 1; 1637 1638 if (record_opts__config(opts)) { 1639 status = -EINVAL; 1640 goto out_delete_evlist; 1641 } 1642 1643 top.sym_evsel = perf_evlist__first(top.evlist); 1644 1645 if (!callchain_param.enabled) { 1646 symbol_conf.cumulate_callchain = false; 1647 perf_hpp__cancel_cumulate(); 1648 } 1649 1650 if (symbol_conf.cumulate_callchain && !callchain_param.order_set) 1651 callchain_param.order = ORDER_CALLER; 1652 1653 status = symbol__annotation_init(); 1654 if (status < 0) 1655 goto out_delete_evlist; 1656 1657 annotation_config__init(); 1658 1659 symbol_conf.try_vmlinux_path = (symbol_conf.vmlinux_name == NULL); 1660 status = symbol__init(NULL); 1661 if (status < 0) 1662 goto out_delete_evlist; 1663 1664 sort__setup_elide(stdout); 1665 1666 get_term_dimensions(&top.winsize); 1667 if (top.print_entries == 0) { 1668 perf_top__update_print_entries(&top); 1669 signal(SIGWINCH, winch_sig); 1670 } 1671 1672 top.session = perf_session__new(NULL, false, NULL); 1673 if (top.session == NULL) { 1674 status = -1; 1675 goto out_delete_evlist; 1676 } 1677 1678 if (!top.record_opts.no_bpf_event) 1679 bpf_event__add_sb_event(&sb_evlist, &perf_env); 1680 1681 if (perf_evlist__start_sb_thread(sb_evlist, target)) { 1682 pr_debug("Couldn't start the BPF side band thread:\nBPF programs starting from now on won't be annotatable\n"); 1683 opts->no_bpf_event = true; 1684 } 1685 1686 status = __cmd_top(&top); 1687 1688 if (!opts->no_bpf_event) 1689 perf_evlist__stop_sb_thread(sb_evlist); 1690 1691 out_delete_evlist: 1692 evlist__delete(top.evlist); 1693 perf_session__delete(top.session); 1694 1695 return status; 1696 } 1697