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