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