builtin-top.c 31 KB

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