builtin-top.c 33 KB

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