builtin-top.c 32 KB

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