~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

TOMOYO Linux Cross Reference
Linux/tools/perf/builtin-top.c

Version: ~ [ linux-5.8-rc4 ] ~ [ linux-5.7.7 ] ~ [ linux-5.6.19 ] ~ [ linux-5.5.19 ] ~ [ linux-5.4.50 ] ~ [ linux-5.3.18 ] ~ [ linux-5.2.21 ] ~ [ linux-5.1.21 ] ~ [ linux-5.0.21 ] ~ [ linux-4.20.17 ] ~ [ linux-4.19.131 ] ~ [ linux-4.18.20 ] ~ [ linux-4.17.19 ] ~ [ linux-4.16.18 ] ~ [ linux-4.15.18 ] ~ [ linux-4.14.187 ] ~ [ linux-4.13.16 ] ~ [ linux-4.12.14 ] ~ [ linux-4.11.12 ] ~ [ linux-4.10.17 ] ~ [ linux-4.9.229 ] ~ [ linux-4.8.17 ] ~ [ linux-4.7.10 ] ~ [ linux-4.6.7 ] ~ [ linux-4.5.7 ] ~ [ linux-4.4.229 ] ~ [ linux-4.3.6 ] ~ [ linux-4.2.8 ] ~ [ linux-4.1.52 ] ~ [ linux-4.0.9 ] ~ [ linux-3.19.8 ] ~ [ linux-3.18.140 ] ~ [ linux-3.17.8 ] ~ [ linux-3.16.85 ] ~ [ linux-3.15.10 ] ~ [ linux-3.14.79 ] ~ [ linux-3.13.11 ] ~ [ linux-3.12.74 ] ~ [ linux-3.11.10 ] ~ [ linux-3.10.108 ] ~ [ linux-2.6.32.71 ] ~ [ linux-2.6.0 ] ~ [ linux-2.4.37.11 ] ~ [ unix-v6-master ] ~ [ ccs-tools-1.8.5 ] ~ [ policy-sample ] ~
Architecture: ~ [ i386 ] ~ [ alpha ] ~ [ m68k ] ~ [ mips ] ~ [ ppc ] ~ [ sparc ] ~ [ sparc64 ] ~

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

~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

kernel.org | git.kernel.org | LWN.net | Project Home | Wiki (Japanese) | Wiki (English) | SVN repository | Mail admin

Linux® is a registered trademark of Linus Torvalds in the United States and other countries.
TOMOYO® is a registered trademark of NTT DATA CORPORATION.

osdn.jp