builtin-top.c 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252
  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/session.h"
  28. #include "util/symbol.h"
  29. #include "util/thread.h"
  30. #include "util/thread_map.h"
  31. #include "util/top.h"
  32. #include "util/util.h"
  33. #include <linux/rbtree.h>
  34. #include "util/parse-options.h"
  35. #include "util/parse-events.h"
  36. #include "util/cpumap.h"
  37. #include "util/xyarray.h"
  38. #include "util/sort.h"
  39. #include "util/debug.h"
  40. #include <assert.h>
  41. #include <fcntl.h>
  42. #include <stdio.h>
  43. #include <termios.h>
  44. #include <unistd.h>
  45. #include <inttypes.h>
  46. #include <errno.h>
  47. #include <time.h>
  48. #include <sched.h>
  49. #include <sys/syscall.h>
  50. #include <sys/ioctl.h>
  51. #include <sys/poll.h>
  52. #include <sys/prctl.h>
  53. #include <sys/wait.h>
  54. #include <sys/uio.h>
  55. #include <sys/mman.h>
  56. #include <linux/unistd.h>
  57. #include <linux/types.h>
  58. static struct perf_top top = {
  59. .count_filter = 5,
  60. .delay_secs = 2,
  61. .target_pid = -1,
  62. .target_tid = -1,
  63. .freq = 1000, /* 1 KHz */
  64. };
  65. static bool system_wide = false;
  66. static bool use_tui, use_stdio;
  67. static bool sort_has_symbols;
  68. static bool dont_use_callchains;
  69. static char callchain_default_opt[] = "fractal,0.5,callee";
  70. static int default_interval = 0;
  71. static bool kptr_restrict_warned;
  72. static bool vmlinux_warned;
  73. static bool inherit = false;
  74. static int realtime_prio = 0;
  75. static bool group = false;
  76. static unsigned int mmap_pages = 128;
  77. static bool dump_symtab = false;
  78. static struct winsize winsize;
  79. static const char *sym_filter = NULL;
  80. static int sym_pcnt_filter = 5;
  81. /*
  82. * Source functions
  83. */
  84. void get_term_dimensions(struct winsize *ws)
  85. {
  86. char *s = getenv("LINES");
  87. if (s != NULL) {
  88. ws->ws_row = atoi(s);
  89. s = getenv("COLUMNS");
  90. if (s != NULL) {
  91. ws->ws_col = atoi(s);
  92. if (ws->ws_row && ws->ws_col)
  93. return;
  94. }
  95. }
  96. #ifdef TIOCGWINSZ
  97. if (ioctl(1, TIOCGWINSZ, ws) == 0 &&
  98. ws->ws_row && ws->ws_col)
  99. return;
  100. #endif
  101. ws->ws_row = 25;
  102. ws->ws_col = 80;
  103. }
  104. static void update_print_entries(struct winsize *ws)
  105. {
  106. top.print_entries = ws->ws_row;
  107. if (top.print_entries > 9)
  108. top.print_entries -= 9;
  109. }
  110. static void sig_winch_handler(int sig __used)
  111. {
  112. get_term_dimensions(&winsize);
  113. update_print_entries(&winsize);
  114. }
  115. static int parse_source(struct hist_entry *he)
  116. {
  117. struct symbol *sym;
  118. struct annotation *notes;
  119. struct map *map;
  120. int err = -1;
  121. if (!he || !he->ms.sym)
  122. return -1;
  123. sym = he->ms.sym;
  124. map = he->ms.map;
  125. /*
  126. * We can't annotate with just /proc/kallsyms
  127. */
  128. if (map->dso->symtab_type == SYMTAB__KALLSYMS) {
  129. pr_err("Can't annotate %s: No vmlinux file was found in the "
  130. "path\n", sym->name);
  131. sleep(1);
  132. return -1;
  133. }
  134. notes = symbol__annotation(sym);
  135. if (notes->src != NULL) {
  136. pthread_mutex_lock(&notes->lock);
  137. goto out_assign;
  138. }
  139. pthread_mutex_lock(&notes->lock);
  140. if (symbol__alloc_hist(sym, top.evlist->nr_entries) < 0) {
  141. pthread_mutex_unlock(&notes->lock);
  142. pr_err("Not enough memory for annotating '%s' symbol!\n",
  143. sym->name);
  144. sleep(1);
  145. return err;
  146. }
  147. err = symbol__annotate(sym, map, 0);
  148. if (err == 0) {
  149. out_assign:
  150. top.sym_filter_entry = he;
  151. }
  152. pthread_mutex_unlock(&notes->lock);
  153. return err;
  154. }
  155. static void __zero_source_counters(struct hist_entry *he)
  156. {
  157. struct symbol *sym = he->ms.sym;
  158. symbol__annotate_zero_histograms(sym);
  159. }
  160. static void record_precise_ip(struct hist_entry *he, int counter, u64 ip)
  161. {
  162. struct annotation *notes;
  163. struct symbol *sym;
  164. if (he == NULL || he->ms.sym == NULL ||
  165. (he != top.sym_filter_entry && use_browser != 1))
  166. return;
  167. sym = he->ms.sym;
  168. notes = symbol__annotation(sym);
  169. if (pthread_mutex_trylock(&notes->lock))
  170. return;
  171. if (notes->src == NULL &&
  172. symbol__alloc_hist(sym, top.evlist->nr_entries) < 0) {
  173. pthread_mutex_unlock(&notes->lock);
  174. pr_err("Not enough memory for annotating '%s' symbol!\n",
  175. sym->name);
  176. sleep(1);
  177. return;
  178. }
  179. ip = he->ms.map->map_ip(he->ms.map, ip);
  180. symbol__inc_addr_samples(sym, he->ms.map, counter, ip);
  181. pthread_mutex_unlock(&notes->lock);
  182. }
  183. static void show_details(struct hist_entry *he)
  184. {
  185. struct annotation *notes;
  186. struct symbol *symbol;
  187. int more;
  188. if (!he)
  189. return;
  190. symbol = he->ms.sym;
  191. notes = symbol__annotation(symbol);
  192. pthread_mutex_lock(&notes->lock);
  193. if (notes->src == NULL)
  194. goto out_unlock;
  195. printf("Showing %s for %s\n", event_name(top.sym_evsel), symbol->name);
  196. printf(" Events Pcnt (>=%d%%)\n", sym_pcnt_filter);
  197. more = symbol__annotate_printf(symbol, he->ms.map, top.sym_evsel->idx,
  198. 0, sym_pcnt_filter, top.print_entries, 4);
  199. if (top.zero)
  200. symbol__annotate_zero_histogram(symbol, top.sym_evsel->idx);
  201. else
  202. symbol__annotate_decay_histogram(symbol, top.sym_evsel->idx);
  203. if (more != 0)
  204. printf("%d lines not displayed, maybe increase display entries [e]\n", more);
  205. out_unlock:
  206. pthread_mutex_unlock(&notes->lock);
  207. }
  208. static const char CONSOLE_CLEAR[] = "";
  209. static struct hist_entry *
  210. perf_session__add_hist_entry(struct perf_session *session,
  211. struct addr_location *al,
  212. struct perf_sample *sample,
  213. struct perf_evsel *evsel)
  214. {
  215. struct hist_entry *he;
  216. he = __hists__add_entry(&evsel->hists, al, NULL, sample->period);
  217. if (he == NULL)
  218. return NULL;
  219. session->hists.stats.total_period += sample->period;
  220. hists__inc_nr_events(&evsel->hists, PERF_RECORD_SAMPLE);
  221. return he;
  222. }
  223. static void print_sym_table(void)
  224. {
  225. char bf[160];
  226. int printed = 0;
  227. const int win_width = winsize.ws_col - 1;
  228. puts(CONSOLE_CLEAR);
  229. perf_top__header_snprintf(&top, bf, sizeof(bf));
  230. printf("%s\n", bf);
  231. perf_top__reset_sample_counters(&top);
  232. printf("%-*.*s\n", win_width, win_width, graph_dotted_line);
  233. if (top.total_lost_warned != top.session->hists.stats.total_lost) {
  234. top.total_lost_warned = top.session->hists.stats.total_lost;
  235. color_fprintf(stdout, PERF_COLOR_RED, "WARNING:");
  236. printf(" LOST %" PRIu64 " events, Check IO/CPU overload\n",
  237. top.total_lost_warned);
  238. ++printed;
  239. }
  240. if (top.sym_filter_entry) {
  241. show_details(top.sym_filter_entry);
  242. return;
  243. }
  244. hists__collapse_resort_threaded(&top.sym_evsel->hists);
  245. hists__output_resort_threaded(&top.sym_evsel->hists);
  246. hists__decay_entries_threaded(&top.sym_evsel->hists);
  247. hists__output_recalc_col_len(&top.sym_evsel->hists, winsize.ws_row - 3);
  248. putchar('\n');
  249. hists__fprintf(&top.sym_evsel->hists, NULL, false, false,
  250. 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 prompt_symbol(struct hist_entry **target, const char *msg)
  282. {
  283. char *buf = malloc(0), *p;
  284. struct hist_entry *syme = *target, *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. *target = 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. return;
  311. } else
  312. parse_source(found);
  313. out_free:
  314. free(buf);
  315. }
  316. static void print_mapped_keys(void)
  317. {
  318. char *name = NULL;
  319. if (top.sym_filter_entry) {
  320. struct symbol *sym = top.sym_filter_entry->ms.sym;
  321. name = sym->name;
  322. }
  323. fprintf(stdout, "\nMapped keys:\n");
  324. fprintf(stdout, "\t[d] display refresh delay. \t(%d)\n", top.delay_secs);
  325. fprintf(stdout, "\t[e] display entries (lines). \t(%d)\n", top.print_entries);
  326. if (top.evlist->nr_entries > 1)
  327. fprintf(stdout, "\t[E] active event counter. \t(%s)\n", event_name(top.sym_evsel));
  328. fprintf(stdout, "\t[f] profile display filter (count). \t(%d)\n", top.count_filter);
  329. fprintf(stdout, "\t[F] annotate display filter (percent). \t(%d%%)\n", sym_pcnt_filter);
  330. fprintf(stdout, "\t[s] annotate symbol. \t(%s)\n", name?: "NULL");
  331. fprintf(stdout, "\t[S] stop annotation.\n");
  332. fprintf(stdout,
  333. "\t[K] hide kernel_symbols symbols. \t(%s)\n",
  334. top.hide_kernel_symbols ? "yes" : "no");
  335. fprintf(stdout,
  336. "\t[U] hide user symbols. \t(%s)\n",
  337. top.hide_user_symbols ? "yes" : "no");
  338. fprintf(stdout, "\t[z] toggle sample zeroing. \t(%d)\n", top.zero ? 1 : 0);
  339. fprintf(stdout, "\t[qQ] quit.\n");
  340. }
  341. static int key_mapped(int c)
  342. {
  343. switch (c) {
  344. case 'd':
  345. case 'e':
  346. case 'f':
  347. case 'z':
  348. case 'q':
  349. case 'Q':
  350. case 'K':
  351. case 'U':
  352. case 'F':
  353. case 's':
  354. case 'S':
  355. return 1;
  356. case 'E':
  357. default:
  358. break;
  359. }
  360. return 0;
  361. }
  362. static void handle_keypress(int c)
  363. {
  364. if (!key_mapped(c)) {
  365. struct pollfd stdin_poll = { .fd = 0, .events = POLLIN };
  366. struct termios tc, save;
  367. print_mapped_keys();
  368. fprintf(stdout, "\nEnter selection, or unmapped key to continue: ");
  369. fflush(stdout);
  370. tcgetattr(0, &save);
  371. tc = save;
  372. tc.c_lflag &= ~(ICANON | ECHO);
  373. tc.c_cc[VMIN] = 0;
  374. tc.c_cc[VTIME] = 0;
  375. tcsetattr(0, TCSANOW, &tc);
  376. poll(&stdin_poll, 1, -1);
  377. c = getc(stdin);
  378. tcsetattr(0, TCSAFLUSH, &save);
  379. if (!key_mapped(c))
  380. return;
  381. }
  382. switch (c) {
  383. case 'd':
  384. prompt_integer(&top.delay_secs, "Enter display delay");
  385. if (top.delay_secs < 1)
  386. top.delay_secs = 1;
  387. break;
  388. case 'e':
  389. prompt_integer(&top.print_entries, "Enter display entries (lines)");
  390. if (top.print_entries == 0) {
  391. sig_winch_handler(SIGWINCH);
  392. signal(SIGWINCH, sig_winch_handler);
  393. } else
  394. signal(SIGWINCH, SIG_DFL);
  395. break;
  396. case 'E':
  397. if (top.evlist->nr_entries > 1) {
  398. /* Select 0 as the default event: */
  399. int counter = 0;
  400. fprintf(stderr, "\nAvailable events:");
  401. list_for_each_entry(top.sym_evsel, &top.evlist->entries, node)
  402. fprintf(stderr, "\n\t%d %s", top.sym_evsel->idx, event_name(top.sym_evsel));
  403. prompt_integer(&counter, "Enter details event counter");
  404. if (counter >= top.evlist->nr_entries) {
  405. top.sym_evsel = list_entry(top.evlist->entries.next, struct perf_evsel, node);
  406. fprintf(stderr, "Sorry, no such event, using %s.\n", event_name(top.sym_evsel));
  407. sleep(1);
  408. break;
  409. }
  410. list_for_each_entry(top.sym_evsel, &top.evlist->entries, node)
  411. if (top.sym_evsel->idx == counter)
  412. break;
  413. } else
  414. top.sym_evsel = list_entry(top.evlist->entries.next, struct perf_evsel, node);
  415. break;
  416. case 'f':
  417. prompt_integer(&top.count_filter, "Enter display event count filter");
  418. break;
  419. case 'F':
  420. prompt_percent(&sym_pcnt_filter, "Enter details display event filter (percent)");
  421. break;
  422. case 'K':
  423. top.hide_kernel_symbols = !top.hide_kernel_symbols;
  424. break;
  425. case 'q':
  426. case 'Q':
  427. printf("exiting.\n");
  428. if (dump_symtab)
  429. perf_session__fprintf_dsos(top.session, stderr);
  430. exit(0);
  431. case 's':
  432. prompt_symbol(&top.sym_filter_entry, "Enter details symbol");
  433. break;
  434. case 'S':
  435. if (!top.sym_filter_entry)
  436. break;
  437. else {
  438. struct hist_entry *syme = top.sym_filter_entry;
  439. top.sym_filter_entry = NULL;
  440. __zero_source_counters(syme);
  441. }
  442. break;
  443. case 'U':
  444. top.hide_user_symbols = !top.hide_user_symbols;
  445. break;
  446. case 'z':
  447. top.zero = !top.zero;
  448. break;
  449. default:
  450. break;
  451. }
  452. }
  453. static void perf_top__sort_new_samples(void *arg)
  454. {
  455. struct perf_top *t = arg;
  456. perf_top__reset_sample_counters(t);
  457. if (t->evlist->selected != NULL)
  458. t->sym_evsel = t->evlist->selected;
  459. hists__collapse_resort_threaded(&t->sym_evsel->hists);
  460. hists__output_resort_threaded(&t->sym_evsel->hists);
  461. hists__decay_entries_threaded(&t->sym_evsel->hists);
  462. hists__output_recalc_col_len(&t->sym_evsel->hists, winsize.ws_row - 3);
  463. }
  464. static void *display_thread_tui(void *arg __used)
  465. {
  466. const char *help = "For a higher level overview, try: perf top --sort comm,dso";
  467. perf_top__sort_new_samples(&top);
  468. perf_evlist__tui_browse_hists(top.evlist, help,
  469. perf_top__sort_new_samples,
  470. &top, top.delay_secs);
  471. exit_browser(0);
  472. exit(0);
  473. return NULL;
  474. }
  475. static void *display_thread(void *arg __used)
  476. {
  477. struct pollfd stdin_poll = { .fd = 0, .events = POLLIN };
  478. struct termios tc, save;
  479. int delay_msecs, c;
  480. tcgetattr(0, &save);
  481. tc = save;
  482. tc.c_lflag &= ~(ICANON | ECHO);
  483. tc.c_cc[VMIN] = 0;
  484. tc.c_cc[VTIME] = 0;
  485. pthread__unblock_sigwinch();
  486. repeat:
  487. delay_msecs = top.delay_secs * 1000;
  488. tcsetattr(0, TCSANOW, &tc);
  489. /* trash return*/
  490. getc(stdin);
  491. while (1) {
  492. print_sym_table();
  493. /*
  494. * Either timeout expired or we got an EINTR due to SIGWINCH,
  495. * refresh screen in both cases.
  496. */
  497. switch (poll(&stdin_poll, 1, delay_msecs)) {
  498. case 0:
  499. continue;
  500. case -1:
  501. if (errno == EINTR)
  502. continue;
  503. /* Fall trhu */
  504. default:
  505. goto process_hotkey;
  506. }
  507. }
  508. process_hotkey:
  509. c = getc(stdin);
  510. tcsetattr(0, TCSAFLUSH, &save);
  511. handle_keypress(c);
  512. goto repeat;
  513. return NULL;
  514. }
  515. /* Tag samples to be skipped. */
  516. static const char *skip_symbols[] = {
  517. "default_idle",
  518. "native_safe_halt",
  519. "cpu_idle",
  520. "enter_idle",
  521. "exit_idle",
  522. "mwait_idle",
  523. "mwait_idle_with_hints",
  524. "poll_idle",
  525. "ppc64_runlatch_off",
  526. "pseries_dedicated_idle_sleep",
  527. NULL
  528. };
  529. static int symbol_filter(struct map *map __used, struct symbol *sym)
  530. {
  531. const char *name = sym->name;
  532. int i;
  533. /*
  534. * ppc64 uses function descriptors and appends a '.' to the
  535. * start of every instruction address. Remove it.
  536. */
  537. if (name[0] == '.')
  538. name++;
  539. if (!strcmp(name, "_text") ||
  540. !strcmp(name, "_etext") ||
  541. !strcmp(name, "_sinittext") ||
  542. !strncmp("init_module", name, 11) ||
  543. !strncmp("cleanup_module", name, 14) ||
  544. strstr(name, "_text_start") ||
  545. strstr(name, "_text_end"))
  546. return 1;
  547. for (i = 0; skip_symbols[i]; i++) {
  548. if (!strcmp(skip_symbols[i], name)) {
  549. sym->ignore = true;
  550. break;
  551. }
  552. }
  553. return 0;
  554. }
  555. static void perf_event__process_sample(const union perf_event *event,
  556. struct perf_sample *sample,
  557. struct perf_session *session)
  558. {
  559. struct symbol *parent = NULL;
  560. u64 ip = event->ip.ip;
  561. struct addr_location al;
  562. struct machine *machine;
  563. int err;
  564. u8 origin = event->header.misc & PERF_RECORD_MISC_CPUMODE_MASK;
  565. ++top.samples;
  566. switch (origin) {
  567. case PERF_RECORD_MISC_USER:
  568. ++top.us_samples;
  569. if (top.hide_user_symbols)
  570. return;
  571. machine = perf_session__find_host_machine(session);
  572. break;
  573. case PERF_RECORD_MISC_KERNEL:
  574. ++top.kernel_samples;
  575. if (top.hide_kernel_symbols)
  576. return;
  577. machine = perf_session__find_host_machine(session);
  578. break;
  579. case PERF_RECORD_MISC_GUEST_KERNEL:
  580. ++top.guest_kernel_samples;
  581. machine = perf_session__find_machine(session, event->ip.pid);
  582. break;
  583. case PERF_RECORD_MISC_GUEST_USER:
  584. ++top.guest_us_samples;
  585. /*
  586. * TODO: we don't process guest user from host side
  587. * except simple counting.
  588. */
  589. return;
  590. default:
  591. return;
  592. }
  593. if (!machine && perf_guest) {
  594. pr_err("Can't find guest [%d]'s kernel information\n",
  595. event->ip.pid);
  596. return;
  597. }
  598. if (event->header.misc & PERF_RECORD_MISC_EXACT_IP)
  599. top.exact_samples++;
  600. if (perf_event__preprocess_sample(event, session, &al, sample,
  601. symbol_filter) < 0 ||
  602. al.filtered)
  603. return;
  604. if (!kptr_restrict_warned &&
  605. symbol_conf.kptr_restrict &&
  606. al.cpumode == PERF_RECORD_MISC_KERNEL) {
  607. ui__warning(
  608. "Kernel address maps (/proc/{kallsyms,modules}) are restricted.\n\n"
  609. "Check /proc/sys/kernel/kptr_restrict.\n\n"
  610. "Kernel%s samples will not be resolved.\n",
  611. !RB_EMPTY_ROOT(&al.map->dso->symbols[MAP__FUNCTION]) ?
  612. " modules" : "");
  613. if (use_browser <= 0)
  614. sleep(5);
  615. kptr_restrict_warned = true;
  616. }
  617. if (al.sym == NULL) {
  618. const char *msg = "Kernel samples will not be resolved.\n";
  619. /*
  620. * As we do lazy loading of symtabs we only will know if the
  621. * specified vmlinux file is invalid when we actually have a
  622. * hit in kernel space and then try to load it. So if we get
  623. * here and there are _no_ symbols in the DSO backing the
  624. * kernel map, bail out.
  625. *
  626. * We may never get here, for instance, if we use -K/
  627. * --hide-kernel-symbols, even if the user specifies an
  628. * invalid --vmlinux ;-)
  629. */
  630. if (!kptr_restrict_warned && !vmlinux_warned &&
  631. al.map == machine->vmlinux_maps[MAP__FUNCTION] &&
  632. RB_EMPTY_ROOT(&al.map->dso->symbols[MAP__FUNCTION])) {
  633. if (symbol_conf.vmlinux_name) {
  634. ui__warning("The %s file can't be used.\n%s",
  635. symbol_conf.vmlinux_name, msg);
  636. } else {
  637. ui__warning("A vmlinux file was not found.\n%s",
  638. msg);
  639. }
  640. if (use_browser <= 0)
  641. sleep(5);
  642. vmlinux_warned = true;
  643. }
  644. }
  645. if (al.sym == NULL || !al.sym->ignore) {
  646. struct perf_evsel *evsel;
  647. struct hist_entry *he;
  648. evsel = perf_evlist__id2evsel(top.evlist, sample->id);
  649. assert(evsel != NULL);
  650. if ((sort__has_parent || symbol_conf.use_callchain) &&
  651. sample->callchain) {
  652. err = perf_session__resolve_callchain(session, al.thread,
  653. sample->callchain, &parent);
  654. if (err)
  655. return;
  656. }
  657. he = perf_session__add_hist_entry(session, &al, sample, evsel);
  658. if (he == NULL) {
  659. pr_err("Problem incrementing symbol period, skipping event\n");
  660. return;
  661. }
  662. if (symbol_conf.use_callchain) {
  663. err = callchain_append(he->callchain, &session->callchain_cursor,
  664. sample->period);
  665. if (err)
  666. return;
  667. }
  668. if (sort_has_symbols)
  669. record_precise_ip(he, evsel->idx, ip);
  670. }
  671. return;
  672. }
  673. static void perf_session__mmap_read_idx(struct perf_session *self, int idx)
  674. {
  675. struct perf_sample sample;
  676. union perf_event *event;
  677. int ret;
  678. while ((event = perf_evlist__mmap_read(top.evlist, idx)) != NULL) {
  679. ret = perf_session__parse_sample(self, event, &sample);
  680. if (ret) {
  681. pr_err("Can't parse sample, err = %d\n", ret);
  682. continue;
  683. }
  684. if (event->header.type == PERF_RECORD_SAMPLE)
  685. perf_event__process_sample(event, &sample, self);
  686. else
  687. perf_event__process(event, &sample, self);
  688. }
  689. }
  690. static void perf_session__mmap_read(struct perf_session *self)
  691. {
  692. int i;
  693. for (i = 0; i < top.evlist->nr_mmaps; i++)
  694. perf_session__mmap_read_idx(self, i);
  695. }
  696. static void start_counters(struct perf_evlist *evlist)
  697. {
  698. struct perf_evsel *counter;
  699. list_for_each_entry(counter, &evlist->entries, node) {
  700. struct perf_event_attr *attr = &counter->attr;
  701. attr->sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_TID;
  702. if (top.freq) {
  703. attr->sample_type |= PERF_SAMPLE_PERIOD;
  704. attr->freq = 1;
  705. attr->sample_freq = top.freq;
  706. }
  707. if (evlist->nr_entries > 1) {
  708. attr->sample_type |= PERF_SAMPLE_ID;
  709. attr->read_format |= PERF_FORMAT_ID;
  710. }
  711. if (symbol_conf.use_callchain)
  712. attr->sample_type |= PERF_SAMPLE_CALLCHAIN;
  713. attr->mmap = 1;
  714. attr->comm = 1;
  715. attr->inherit = inherit;
  716. try_again:
  717. if (perf_evsel__open(counter, top.evlist->cpus,
  718. top.evlist->threads, group) < 0) {
  719. int err = errno;
  720. if (err == EPERM || err == EACCES) {
  721. ui__warning_paranoid();
  722. goto out_err;
  723. }
  724. /*
  725. * If it's cycles then fall back to hrtimer
  726. * based cpu-clock-tick sw counter, which
  727. * is always available even if no PMU support:
  728. */
  729. if (attr->type == PERF_TYPE_HARDWARE &&
  730. attr->config == PERF_COUNT_HW_CPU_CYCLES) {
  731. if (verbose)
  732. ui__warning("Cycles event not supported,\n"
  733. "trying to fall back to cpu-clock-ticks\n");
  734. attr->type = PERF_TYPE_SOFTWARE;
  735. attr->config = PERF_COUNT_SW_CPU_CLOCK;
  736. goto try_again;
  737. }
  738. if (err == ENOENT) {
  739. ui__warning("The %s event is not supported.\n",
  740. event_name(counter));
  741. goto out_err;
  742. }
  743. ui__warning("The sys_perf_event_open() syscall "
  744. "returned with %d (%s). /bin/dmesg "
  745. "may provide additional information.\n"
  746. "No CONFIG_PERF_EVENTS=y kernel support "
  747. "configured?\n", err, strerror(err));
  748. goto out_err;
  749. }
  750. }
  751. if (perf_evlist__mmap(evlist, mmap_pages, false) < 0) {
  752. ui__warning("Failed to mmap with %d (%s)\n",
  753. errno, strerror(errno));
  754. goto out_err;
  755. }
  756. return;
  757. out_err:
  758. exit_browser(0);
  759. exit(0);
  760. }
  761. static int setup_sample_type(void)
  762. {
  763. if (!sort_has_symbols) {
  764. if (symbol_conf.use_callchain) {
  765. ui__warning("Selected -g but \"sym\" not present in --sort/-s.");
  766. return -EINVAL;
  767. }
  768. } else if (!dont_use_callchains && callchain_param.mode != CHAIN_NONE) {
  769. if (callchain_register_param(&callchain_param) < 0) {
  770. ui__warning("Can't register callchain params.\n");
  771. return -EINVAL;
  772. }
  773. }
  774. return 0;
  775. }
  776. static int __cmd_top(void)
  777. {
  778. pthread_t thread;
  779. int ret;
  780. /*
  781. * FIXME: perf_session__new should allow passing a O_MMAP, so that all this
  782. * mmap reading, etc is encapsulated in it. Use O_WRONLY for now.
  783. */
  784. top.session = perf_session__new(NULL, O_WRONLY, false, false, NULL);
  785. if (top.session == NULL)
  786. return -ENOMEM;
  787. ret = setup_sample_type();
  788. if (ret)
  789. goto out_delete;
  790. if (top.target_tid != -1)
  791. perf_event__synthesize_thread_map(top.evlist->threads,
  792. perf_event__process, top.session);
  793. else
  794. perf_event__synthesize_threads(perf_event__process, top.session);
  795. start_counters(top.evlist);
  796. top.session->evlist = top.evlist;
  797. perf_session__update_sample_type(top.session);
  798. /* Wait for a minimal set of events before starting the snapshot */
  799. poll(top.evlist->pollfd, top.evlist->nr_fds, 100);
  800. perf_session__mmap_read(top.session);
  801. if (pthread_create(&thread, NULL, (use_browser > 0 ? display_thread_tui :
  802. display_thread), NULL)) {
  803. printf("Could not create display thread.\n");
  804. exit(-1);
  805. }
  806. if (realtime_prio) {
  807. struct sched_param param;
  808. param.sched_priority = realtime_prio;
  809. if (sched_setscheduler(0, SCHED_FIFO, &param)) {
  810. printf("Could not set realtime priority.\n");
  811. exit(-1);
  812. }
  813. }
  814. while (1) {
  815. u64 hits = top.samples;
  816. perf_session__mmap_read(top.session);
  817. if (hits == top.samples)
  818. ret = poll(top.evlist->pollfd, top.evlist->nr_fds, 100);
  819. }
  820. out_delete:
  821. perf_session__delete(top.session);
  822. top.session = NULL;
  823. return 0;
  824. }
  825. static int
  826. parse_callchain_opt(const struct option *opt __used, const char *arg,
  827. int unset)
  828. {
  829. char *tok, *tok2;
  830. char *endptr;
  831. /*
  832. * --no-call-graph
  833. */
  834. if (unset) {
  835. dont_use_callchains = true;
  836. return 0;
  837. }
  838. symbol_conf.use_callchain = true;
  839. if (!arg)
  840. return 0;
  841. tok = strtok((char *)arg, ",");
  842. if (!tok)
  843. return -1;
  844. /* get the output mode */
  845. if (!strncmp(tok, "graph", strlen(arg)))
  846. callchain_param.mode = CHAIN_GRAPH_ABS;
  847. else if (!strncmp(tok, "flat", strlen(arg)))
  848. callchain_param.mode = CHAIN_FLAT;
  849. else if (!strncmp(tok, "fractal", strlen(arg)))
  850. callchain_param.mode = CHAIN_GRAPH_REL;
  851. else if (!strncmp(tok, "none", strlen(arg))) {
  852. callchain_param.mode = CHAIN_NONE;
  853. symbol_conf.use_callchain = false;
  854. return 0;
  855. }
  856. else
  857. return -1;
  858. /* get the min percentage */
  859. tok = strtok(NULL, ",");
  860. if (!tok)
  861. goto setup;
  862. callchain_param.min_percent = strtod(tok, &endptr);
  863. if (tok == endptr)
  864. return -1;
  865. /* get the print limit */
  866. tok2 = strtok(NULL, ",");
  867. if (!tok2)
  868. goto setup;
  869. if (tok2[0] != 'c') {
  870. callchain_param.print_limit = strtod(tok2, &endptr);
  871. tok2 = strtok(NULL, ",");
  872. if (!tok2)
  873. goto setup;
  874. }
  875. /* get the call chain order */
  876. if (!strcmp(tok2, "caller"))
  877. callchain_param.order = ORDER_CALLER;
  878. else if (!strcmp(tok2, "callee"))
  879. callchain_param.order = ORDER_CALLEE;
  880. else
  881. return -1;
  882. setup:
  883. if (callchain_register_param(&callchain_param) < 0) {
  884. fprintf(stderr, "Can't register callchain params\n");
  885. return -1;
  886. }
  887. return 0;
  888. }
  889. static const char * const top_usage[] = {
  890. "perf top [<options>]",
  891. NULL
  892. };
  893. static 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_INTEGER('c', "count", &default_interval,
  898. "event period to sample"),
  899. OPT_INTEGER('p', "pid", &top.target_pid,
  900. "profile events on existing process id"),
  901. OPT_INTEGER('t', "tid", &top.target_tid,
  902. "profile events on existing thread id"),
  903. OPT_BOOLEAN('a', "all-cpus", &system_wide,
  904. "system-wide collection from all CPUs"),
  905. OPT_STRING('C', "cpu", &top.cpu_list, "cpu",
  906. "list of cpus to monitor"),
  907. OPT_STRING('k', "vmlinux", &symbol_conf.vmlinux_name,
  908. "file", "vmlinux pathname"),
  909. OPT_BOOLEAN('K', "hide_kernel_symbols", &top.hide_kernel_symbols,
  910. "hide kernel symbols"),
  911. OPT_UINTEGER('m', "mmap-pages", &mmap_pages, "number of mmap data pages"),
  912. OPT_INTEGER('r', "realtime", &realtime_prio,
  913. "collect data with this RT SCHED_FIFO priority"),
  914. OPT_INTEGER('d', "delay", &top.delay_secs,
  915. "number of seconds to delay between refreshes"),
  916. OPT_BOOLEAN('D', "dump-symtab", &dump_symtab,
  917. "dump the symbol table used for profiling"),
  918. OPT_INTEGER('f', "count-filter", &top.count_filter,
  919. "only display functions with more events than this"),
  920. OPT_BOOLEAN('g', "group", &group,
  921. "put the counters into a counter group"),
  922. OPT_BOOLEAN('i', "inherit", &inherit,
  923. "child tasks inherit counters"),
  924. OPT_STRING(0, "sym-annotate", &sym_filter, "symbol name",
  925. "symbol to annotate"),
  926. OPT_BOOLEAN('z', "zero", &top.zero,
  927. "zero history across updates"),
  928. OPT_INTEGER('F', "freq", &top.freq,
  929. "profile at this frequency"),
  930. OPT_INTEGER('E', "entries", &top.print_entries,
  931. "display this many functions"),
  932. OPT_BOOLEAN('U', "hide_user_symbols", &top.hide_user_symbols,
  933. "hide user symbols"),
  934. OPT_BOOLEAN(0, "tui", &use_tui, "Use the TUI interface"),
  935. OPT_BOOLEAN(0, "stdio", &use_stdio, "Use the stdio interface"),
  936. OPT_INCR('v', "verbose", &verbose,
  937. "be more verbose (show counter open errors, etc)"),
  938. OPT_STRING('s', "sort", &sort_order, "key[,key2...]",
  939. "sort by key(s): pid, comm, dso, symbol, parent"),
  940. OPT_BOOLEAN('n', "show-nr-samples", &symbol_conf.show_nr_samples,
  941. "Show a column with the number of samples"),
  942. OPT_CALLBACK_DEFAULT('G', "call-graph", NULL, "output_type,min_percent, call_order",
  943. "Display callchains using output_type (graph, flat, fractal, or none), min percent threshold and callchain order. "
  944. "Default: fractal,0.5,callee", &parse_callchain_opt,
  945. callchain_default_opt),
  946. OPT_BOOLEAN(0, "show-total-period", &symbol_conf.show_total_period,
  947. "Show a column with the sum of periods"),
  948. OPT_STRING(0, "dsos", &symbol_conf.dso_list_str, "dso[,dso...]",
  949. "only consider symbols in these dsos"),
  950. OPT_STRING(0, "comms", &symbol_conf.comm_list_str, "comm[,comm...]",
  951. "only consider symbols in these comms"),
  952. OPT_STRING(0, "symbols", &symbol_conf.sym_list_str, "symbol[,symbol...]",
  953. "only consider these symbols"),
  954. OPT_BOOLEAN(0, "source", &symbol_conf.annotate_src,
  955. "Interleave source code with assembly code (default)"),
  956. OPT_BOOLEAN(0, "asm-raw", &symbol_conf.annotate_asm_raw,
  957. "Display raw encoding of assembly instructions (default)"),
  958. OPT_STRING('M', "disassembler-style", &disassembler_style, "disassembler style",
  959. "Specify disassembler style (e.g. -M intel for intel syntax)"),
  960. OPT_END()
  961. };
  962. int cmd_top(int argc, const char **argv, const char *prefix __used)
  963. {
  964. struct perf_evsel *pos;
  965. int status = -ENOMEM;
  966. top.evlist = perf_evlist__new(NULL, NULL);
  967. if (top.evlist == NULL)
  968. return -ENOMEM;
  969. symbol_conf.exclude_other = false;
  970. argc = parse_options(argc, argv, options, top_usage, 0);
  971. if (argc)
  972. usage_with_options(top_usage, options);
  973. if (sort_order == default_sort_order)
  974. sort_order = "dso,symbol";
  975. setup_sorting(top_usage, options);
  976. if (use_stdio)
  977. use_browser = 0;
  978. else if (use_tui)
  979. use_browser = 1;
  980. setup_browser(false);
  981. /* CPU and PID are mutually exclusive */
  982. if (top.target_tid > 0 && top.cpu_list) {
  983. printf("WARNING: PID switch overriding CPU\n");
  984. sleep(1);
  985. top.cpu_list = NULL;
  986. }
  987. if (top.target_pid != -1)
  988. top.target_tid = top.target_pid;
  989. if (perf_evlist__create_maps(top.evlist, top.target_pid,
  990. top.target_tid, top.cpu_list) < 0)
  991. usage_with_options(top_usage, options);
  992. if (!top.evlist->nr_entries &&
  993. perf_evlist__add_default(top.evlist) < 0) {
  994. pr_err("Not enough memory for event selector list\n");
  995. return -ENOMEM;
  996. }
  997. if (top.delay_secs < 1)
  998. top.delay_secs = 1;
  999. /*
  1000. * User specified count overrides default frequency.
  1001. */
  1002. if (default_interval)
  1003. top.freq = 0;
  1004. else if (top.freq) {
  1005. default_interval = top.freq;
  1006. } else {
  1007. fprintf(stderr, "frequency and count are zero, aborting\n");
  1008. exit(EXIT_FAILURE);
  1009. }
  1010. list_for_each_entry(pos, &top.evlist->entries, node) {
  1011. if (perf_evsel__alloc_fd(pos, top.evlist->cpus->nr,
  1012. top.evlist->threads->nr) < 0)
  1013. goto out_free_fd;
  1014. /*
  1015. * Fill in the ones not specifically initialized via -c:
  1016. */
  1017. if (pos->attr.sample_period)
  1018. continue;
  1019. pos->attr.sample_period = default_interval;
  1020. }
  1021. if (perf_evlist__alloc_pollfd(top.evlist) < 0 ||
  1022. perf_evlist__alloc_mmap(top.evlist) < 0)
  1023. goto out_free_fd;
  1024. top.sym_evsel = list_entry(top.evlist->entries.next, struct perf_evsel, node);
  1025. symbol_conf.priv_size = sizeof(struct annotation);
  1026. symbol_conf.try_vmlinux_path = (symbol_conf.vmlinux_name == NULL);
  1027. if (symbol__init() < 0)
  1028. return -1;
  1029. sort_entry__setup_elide(&sort_dso, symbol_conf.dso_list, "dso", stdout);
  1030. sort_entry__setup_elide(&sort_comm, symbol_conf.comm_list, "comm", stdout);
  1031. sort_entry__setup_elide(&sort_sym, symbol_conf.sym_list, "symbol", stdout);
  1032. /*
  1033. * Avoid annotation data structures overhead when symbols aren't on the
  1034. * sort list.
  1035. */
  1036. sort_has_symbols = sort_sym.list.next != NULL;
  1037. get_term_dimensions(&winsize);
  1038. if (top.print_entries == 0) {
  1039. update_print_entries(&winsize);
  1040. signal(SIGWINCH, sig_winch_handler);
  1041. }
  1042. status = __cmd_top();
  1043. out_free_fd:
  1044. perf_evlist__delete(top.evlist);
  1045. return status;
  1046. }