builtin-top.c 32 KB

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