builtin-top.c 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264
  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. top.hide_user_symbols,
  248. top.hide_kernel_symbols);
  249. hists__output_recalc_col_len(&top.sym_evsel->hists, winsize.ws_row - 3);
  250. putchar('\n');
  251. hists__fprintf(&top.sym_evsel->hists, NULL, false, false,
  252. winsize.ws_row - 4 - printed, win_width, stdout);
  253. }
  254. static void prompt_integer(int *target, const char *msg)
  255. {
  256. char *buf = malloc(0), *p;
  257. size_t dummy = 0;
  258. int tmp;
  259. fprintf(stdout, "\n%s: ", msg);
  260. if (getline(&buf, &dummy, stdin) < 0)
  261. return;
  262. p = strchr(buf, '\n');
  263. if (p)
  264. *p = 0;
  265. p = buf;
  266. while(*p) {
  267. if (!isdigit(*p))
  268. goto out_free;
  269. p++;
  270. }
  271. tmp = strtoul(buf, NULL, 10);
  272. *target = tmp;
  273. out_free:
  274. free(buf);
  275. }
  276. static void prompt_percent(int *target, const char *msg)
  277. {
  278. int tmp = 0;
  279. prompt_integer(&tmp, msg);
  280. if (tmp >= 0 && tmp <= 100)
  281. *target = tmp;
  282. }
  283. static void prompt_symbol(struct hist_entry **target, const char *msg)
  284. {
  285. char *buf = malloc(0), *p;
  286. struct hist_entry *syme = *target, *n, *found = NULL;
  287. struct rb_node *next;
  288. size_t dummy = 0;
  289. /* zero counters of active symbol */
  290. if (syme) {
  291. __zero_source_counters(syme);
  292. *target = NULL;
  293. }
  294. fprintf(stdout, "\n%s: ", msg);
  295. if (getline(&buf, &dummy, stdin) < 0)
  296. goto out_free;
  297. p = strchr(buf, '\n');
  298. if (p)
  299. *p = 0;
  300. next = rb_first(&top.sym_evsel->hists.entries);
  301. while (next) {
  302. n = rb_entry(next, struct hist_entry, rb_node);
  303. if (n->ms.sym && !strcmp(buf, n->ms.sym->name)) {
  304. found = n;
  305. break;
  306. }
  307. next = rb_next(&n->rb_node);
  308. }
  309. if (!found) {
  310. fprintf(stderr, "Sorry, %s is not active.\n", buf);
  311. sleep(1);
  312. return;
  313. } else
  314. parse_source(found);
  315. out_free:
  316. free(buf);
  317. }
  318. static void print_mapped_keys(void)
  319. {
  320. char *name = NULL;
  321. if (top.sym_filter_entry) {
  322. struct symbol *sym = top.sym_filter_entry->ms.sym;
  323. name = sym->name;
  324. }
  325. fprintf(stdout, "\nMapped keys:\n");
  326. fprintf(stdout, "\t[d] display refresh delay. \t(%d)\n", top.delay_secs);
  327. fprintf(stdout, "\t[e] display entries (lines). \t(%d)\n", top.print_entries);
  328. if (top.evlist->nr_entries > 1)
  329. fprintf(stdout, "\t[E] active event counter. \t(%s)\n", event_name(top.sym_evsel));
  330. fprintf(stdout, "\t[f] profile display filter (count). \t(%d)\n", top.count_filter);
  331. fprintf(stdout, "\t[F] annotate display filter (percent). \t(%d%%)\n", sym_pcnt_filter);
  332. fprintf(stdout, "\t[s] annotate symbol. \t(%s)\n", name?: "NULL");
  333. fprintf(stdout, "\t[S] stop annotation.\n");
  334. fprintf(stdout,
  335. "\t[K] hide kernel_symbols symbols. \t(%s)\n",
  336. top.hide_kernel_symbols ? "yes" : "no");
  337. fprintf(stdout,
  338. "\t[U] hide user symbols. \t(%s)\n",
  339. top.hide_user_symbols ? "yes" : "no");
  340. fprintf(stdout, "\t[z] toggle sample zeroing. \t(%d)\n", top.zero ? 1 : 0);
  341. fprintf(stdout, "\t[qQ] quit.\n");
  342. }
  343. static int key_mapped(int c)
  344. {
  345. switch (c) {
  346. case 'd':
  347. case 'e':
  348. case 'f':
  349. case 'z':
  350. case 'q':
  351. case 'Q':
  352. case 'K':
  353. case 'U':
  354. case 'F':
  355. case 's':
  356. case 'S':
  357. return 1;
  358. case 'E':
  359. return top.evlist->nr_entries > 1 ? 1 : 0;
  360. default:
  361. break;
  362. }
  363. return 0;
  364. }
  365. static void handle_keypress(int c)
  366. {
  367. if (!key_mapped(c)) {
  368. struct pollfd stdin_poll = { .fd = 0, .events = POLLIN };
  369. struct termios tc, save;
  370. print_mapped_keys();
  371. fprintf(stdout, "\nEnter selection, or unmapped key to continue: ");
  372. fflush(stdout);
  373. tcgetattr(0, &save);
  374. tc = save;
  375. tc.c_lflag &= ~(ICANON | ECHO);
  376. tc.c_cc[VMIN] = 0;
  377. tc.c_cc[VTIME] = 0;
  378. tcsetattr(0, TCSANOW, &tc);
  379. poll(&stdin_poll, 1, -1);
  380. c = getc(stdin);
  381. tcsetattr(0, TCSAFLUSH, &save);
  382. if (!key_mapped(c))
  383. return;
  384. }
  385. switch (c) {
  386. case 'd':
  387. prompt_integer(&top.delay_secs, "Enter display delay");
  388. if (top.delay_secs < 1)
  389. top.delay_secs = 1;
  390. break;
  391. case 'e':
  392. prompt_integer(&top.print_entries, "Enter display entries (lines)");
  393. if (top.print_entries == 0) {
  394. sig_winch_handler(SIGWINCH);
  395. signal(SIGWINCH, sig_winch_handler);
  396. } else
  397. signal(SIGWINCH, SIG_DFL);
  398. break;
  399. case 'E':
  400. if (top.evlist->nr_entries > 1) {
  401. /* Select 0 as the default event: */
  402. int counter = 0;
  403. fprintf(stderr, "\nAvailable events:");
  404. list_for_each_entry(top.sym_evsel, &top.evlist->entries, node)
  405. fprintf(stderr, "\n\t%d %s", top.sym_evsel->idx, event_name(top.sym_evsel));
  406. prompt_integer(&counter, "Enter details event counter");
  407. if (counter >= top.evlist->nr_entries) {
  408. top.sym_evsel = list_entry(top.evlist->entries.next, struct perf_evsel, node);
  409. fprintf(stderr, "Sorry, no such event, using %s.\n", event_name(top.sym_evsel));
  410. sleep(1);
  411. break;
  412. }
  413. list_for_each_entry(top.sym_evsel, &top.evlist->entries, node)
  414. if (top.sym_evsel->idx == counter)
  415. break;
  416. } else
  417. top.sym_evsel = list_entry(top.evlist->entries.next, struct perf_evsel, node);
  418. break;
  419. case 'f':
  420. prompt_integer(&top.count_filter, "Enter display event count filter");
  421. break;
  422. case 'F':
  423. prompt_percent(&sym_pcnt_filter, "Enter details display event filter (percent)");
  424. break;
  425. case 'K':
  426. top.hide_kernel_symbols = !top.hide_kernel_symbols;
  427. break;
  428. case 'q':
  429. case 'Q':
  430. printf("exiting.\n");
  431. if (dump_symtab)
  432. perf_session__fprintf_dsos(top.session, stderr);
  433. exit(0);
  434. case 's':
  435. prompt_symbol(&top.sym_filter_entry, "Enter details symbol");
  436. break;
  437. case 'S':
  438. if (!top.sym_filter_entry)
  439. break;
  440. else {
  441. struct hist_entry *syme = top.sym_filter_entry;
  442. top.sym_filter_entry = NULL;
  443. __zero_source_counters(syme);
  444. }
  445. break;
  446. case 'U':
  447. top.hide_user_symbols = !top.hide_user_symbols;
  448. break;
  449. case 'z':
  450. top.zero = !top.zero;
  451. break;
  452. default:
  453. break;
  454. }
  455. }
  456. static void perf_top__sort_new_samples(void *arg)
  457. {
  458. struct perf_top *t = arg;
  459. perf_top__reset_sample_counters(t);
  460. if (t->evlist->selected != NULL)
  461. t->sym_evsel = t->evlist->selected;
  462. hists__collapse_resort_threaded(&t->sym_evsel->hists);
  463. hists__output_resort_threaded(&t->sym_evsel->hists);
  464. hists__decay_entries_threaded(&t->sym_evsel->hists,
  465. top.hide_user_symbols,
  466. top.hide_kernel_symbols);
  467. hists__output_recalc_col_len(&t->sym_evsel->hists, winsize.ws_row - 3);
  468. }
  469. static void *display_thread_tui(void *arg __used)
  470. {
  471. const char *help = "For a higher level overview, try: perf top --sort comm,dso";
  472. perf_top__sort_new_samples(&top);
  473. perf_evlist__tui_browse_hists(top.evlist, help,
  474. perf_top__sort_new_samples,
  475. &top, top.delay_secs);
  476. exit_browser(0);
  477. exit(0);
  478. return NULL;
  479. }
  480. static void *display_thread(void *arg __used)
  481. {
  482. struct pollfd stdin_poll = { .fd = 0, .events = POLLIN };
  483. struct termios tc, save;
  484. int delay_msecs, c;
  485. tcgetattr(0, &save);
  486. tc = save;
  487. tc.c_lflag &= ~(ICANON | ECHO);
  488. tc.c_cc[VMIN] = 0;
  489. tc.c_cc[VTIME] = 0;
  490. pthread__unblock_sigwinch();
  491. repeat:
  492. delay_msecs = top.delay_secs * 1000;
  493. tcsetattr(0, TCSANOW, &tc);
  494. /* trash return*/
  495. getc(stdin);
  496. while (1) {
  497. print_sym_table();
  498. /*
  499. * Either timeout expired or we got an EINTR due to SIGWINCH,
  500. * refresh screen in both cases.
  501. */
  502. switch (poll(&stdin_poll, 1, delay_msecs)) {
  503. case 0:
  504. continue;
  505. case -1:
  506. if (errno == EINTR)
  507. continue;
  508. /* Fall trhu */
  509. default:
  510. goto process_hotkey;
  511. }
  512. }
  513. process_hotkey:
  514. c = getc(stdin);
  515. tcsetattr(0, TCSAFLUSH, &save);
  516. handle_keypress(c);
  517. goto repeat;
  518. return NULL;
  519. }
  520. /* Tag samples to be skipped. */
  521. static const char *skip_symbols[] = {
  522. "default_idle",
  523. "native_safe_halt",
  524. "cpu_idle",
  525. "enter_idle",
  526. "exit_idle",
  527. "mwait_idle",
  528. "mwait_idle_with_hints",
  529. "poll_idle",
  530. "ppc64_runlatch_off",
  531. "pseries_dedicated_idle_sleep",
  532. NULL
  533. };
  534. static int symbol_filter(struct map *map __used, struct symbol *sym)
  535. {
  536. const char *name = sym->name;
  537. int i;
  538. /*
  539. * ppc64 uses function descriptors and appends a '.' to the
  540. * start of every instruction address. Remove it.
  541. */
  542. if (name[0] == '.')
  543. name++;
  544. if (!strcmp(name, "_text") ||
  545. !strcmp(name, "_etext") ||
  546. !strcmp(name, "_sinittext") ||
  547. !strncmp("init_module", name, 11) ||
  548. !strncmp("cleanup_module", name, 14) ||
  549. strstr(name, "_text_start") ||
  550. strstr(name, "_text_end"))
  551. return 1;
  552. for (i = 0; skip_symbols[i]; i++) {
  553. if (!strcmp(skip_symbols[i], name)) {
  554. sym->ignore = true;
  555. break;
  556. }
  557. }
  558. return 0;
  559. }
  560. static void perf_event__process_sample(const union perf_event *event,
  561. struct perf_sample *sample,
  562. struct perf_session *session)
  563. {
  564. struct symbol *parent = NULL;
  565. u64 ip = event->ip.ip;
  566. struct addr_location al;
  567. struct machine *machine;
  568. int err;
  569. u8 origin = event->header.misc & PERF_RECORD_MISC_CPUMODE_MASK;
  570. ++top.samples;
  571. switch (origin) {
  572. case PERF_RECORD_MISC_USER:
  573. ++top.us_samples;
  574. if (top.hide_user_symbols)
  575. return;
  576. machine = perf_session__find_host_machine(session);
  577. break;
  578. case PERF_RECORD_MISC_KERNEL:
  579. ++top.kernel_samples;
  580. if (top.hide_kernel_symbols)
  581. return;
  582. machine = perf_session__find_host_machine(session);
  583. break;
  584. case PERF_RECORD_MISC_GUEST_KERNEL:
  585. ++top.guest_kernel_samples;
  586. machine = perf_session__find_machine(session, event->ip.pid);
  587. break;
  588. case PERF_RECORD_MISC_GUEST_USER:
  589. ++top.guest_us_samples;
  590. /*
  591. * TODO: we don't process guest user from host side
  592. * except simple counting.
  593. */
  594. return;
  595. default:
  596. return;
  597. }
  598. if (!machine && perf_guest) {
  599. pr_err("Can't find guest [%d]'s kernel information\n",
  600. event->ip.pid);
  601. return;
  602. }
  603. if (event->header.misc & PERF_RECORD_MISC_EXACT_IP)
  604. top.exact_samples++;
  605. if (perf_event__preprocess_sample(event, session, &al, sample,
  606. symbol_filter) < 0 ||
  607. al.filtered)
  608. return;
  609. if (!kptr_restrict_warned &&
  610. symbol_conf.kptr_restrict &&
  611. al.cpumode == PERF_RECORD_MISC_KERNEL) {
  612. ui__warning(
  613. "Kernel address maps (/proc/{kallsyms,modules}) are restricted.\n\n"
  614. "Check /proc/sys/kernel/kptr_restrict.\n\n"
  615. "Kernel%s samples will not be resolved.\n",
  616. !RB_EMPTY_ROOT(&al.map->dso->symbols[MAP__FUNCTION]) ?
  617. " modules" : "");
  618. if (use_browser <= 0)
  619. sleep(5);
  620. kptr_restrict_warned = true;
  621. }
  622. if (al.sym == NULL) {
  623. const char *msg = "Kernel samples will not be resolved.\n";
  624. /*
  625. * As we do lazy loading of symtabs we only will know if the
  626. * specified vmlinux file is invalid when we actually have a
  627. * hit in kernel space and then try to load it. So if we get
  628. * here and there are _no_ symbols in the DSO backing the
  629. * kernel map, bail out.
  630. *
  631. * We may never get here, for instance, if we use -K/
  632. * --hide-kernel-symbols, even if the user specifies an
  633. * invalid --vmlinux ;-)
  634. */
  635. if (!kptr_restrict_warned && !vmlinux_warned &&
  636. al.map == machine->vmlinux_maps[MAP__FUNCTION] &&
  637. RB_EMPTY_ROOT(&al.map->dso->symbols[MAP__FUNCTION])) {
  638. if (symbol_conf.vmlinux_name) {
  639. ui__warning("The %s file can't be used.\n%s",
  640. symbol_conf.vmlinux_name, msg);
  641. } else {
  642. ui__warning("A vmlinux file was not found.\n%s",
  643. msg);
  644. }
  645. if (use_browser <= 0)
  646. sleep(5);
  647. vmlinux_warned = true;
  648. }
  649. }
  650. if (al.sym == NULL || !al.sym->ignore) {
  651. struct perf_evsel *evsel;
  652. struct hist_entry *he;
  653. evsel = perf_evlist__id2evsel(top.evlist, sample->id);
  654. assert(evsel != NULL);
  655. if ((sort__has_parent || symbol_conf.use_callchain) &&
  656. sample->callchain) {
  657. err = perf_session__resolve_callchain(session, al.thread,
  658. sample->callchain, &parent);
  659. if (err)
  660. return;
  661. }
  662. he = perf_session__add_hist_entry(session, &al, sample, evsel);
  663. if (he == NULL) {
  664. pr_err("Problem incrementing symbol period, skipping event\n");
  665. return;
  666. }
  667. if (symbol_conf.use_callchain) {
  668. err = callchain_append(he->callchain, &session->callchain_cursor,
  669. sample->period);
  670. if (err)
  671. return;
  672. }
  673. if (sort_has_symbols)
  674. record_precise_ip(he, evsel->idx, ip);
  675. }
  676. return;
  677. }
  678. static void perf_session__mmap_read_idx(struct perf_session *self, int idx)
  679. {
  680. struct perf_sample sample;
  681. union perf_event *event;
  682. int ret;
  683. while ((event = perf_evlist__mmap_read(top.evlist, idx)) != NULL) {
  684. ret = perf_session__parse_sample(self, event, &sample);
  685. if (ret) {
  686. pr_err("Can't parse sample, err = %d\n", ret);
  687. continue;
  688. }
  689. if (event->header.type == PERF_RECORD_SAMPLE)
  690. perf_event__process_sample(event, &sample, self);
  691. else
  692. perf_event__process(event, &sample, self);
  693. }
  694. }
  695. static void perf_session__mmap_read(struct perf_session *self)
  696. {
  697. int i;
  698. for (i = 0; i < top.evlist->nr_mmaps; i++)
  699. perf_session__mmap_read_idx(self, i);
  700. }
  701. static void start_counters(struct perf_evlist *evlist)
  702. {
  703. struct perf_evsel *counter, *first;
  704. first = list_entry(evlist->entries.next, struct perf_evsel, node);
  705. list_for_each_entry(counter, &evlist->entries, node) {
  706. struct perf_event_attr *attr = &counter->attr;
  707. struct xyarray *group_fd = NULL;
  708. if (group && counter != first)
  709. group_fd = first->fd;
  710. attr->sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_TID;
  711. if (top.freq) {
  712. attr->sample_type |= PERF_SAMPLE_PERIOD;
  713. attr->freq = 1;
  714. attr->sample_freq = top.freq;
  715. }
  716. if (evlist->nr_entries > 1) {
  717. attr->sample_type |= PERF_SAMPLE_ID;
  718. attr->read_format |= PERF_FORMAT_ID;
  719. }
  720. if (symbol_conf.use_callchain)
  721. attr->sample_type |= PERF_SAMPLE_CALLCHAIN;
  722. attr->mmap = 1;
  723. attr->comm = 1;
  724. attr->inherit = inherit;
  725. try_again:
  726. if (perf_evsel__open(counter, top.evlist->cpus,
  727. top.evlist->threads, group,
  728. group_fd) < 0) {
  729. int err = errno;
  730. if (err == EPERM || err == EACCES) {
  731. ui__warning_paranoid();
  732. goto out_err;
  733. }
  734. /*
  735. * If it's cycles then fall back to hrtimer
  736. * based cpu-clock-tick sw counter, which
  737. * is always available even if no PMU support:
  738. */
  739. if (attr->type == PERF_TYPE_HARDWARE &&
  740. attr->config == PERF_COUNT_HW_CPU_CYCLES) {
  741. if (verbose)
  742. ui__warning("Cycles event not supported,\n"
  743. "trying to fall back to cpu-clock-ticks\n");
  744. attr->type = PERF_TYPE_SOFTWARE;
  745. attr->config = PERF_COUNT_SW_CPU_CLOCK;
  746. goto try_again;
  747. }
  748. if (err == ENOENT) {
  749. ui__warning("The %s event is not supported.\n",
  750. event_name(counter));
  751. goto out_err;
  752. }
  753. ui__warning("The sys_perf_event_open() syscall "
  754. "returned with %d (%s). /bin/dmesg "
  755. "may provide additional information.\n"
  756. "No CONFIG_PERF_EVENTS=y kernel support "
  757. "configured?\n", err, strerror(err));
  758. goto out_err;
  759. }
  760. }
  761. if (perf_evlist__mmap(evlist, mmap_pages, false) < 0) {
  762. ui__warning("Failed to mmap with %d (%s)\n",
  763. errno, strerror(errno));
  764. goto out_err;
  765. }
  766. return;
  767. out_err:
  768. exit_browser(0);
  769. exit(0);
  770. }
  771. static int setup_sample_type(void)
  772. {
  773. if (!sort_has_symbols) {
  774. if (symbol_conf.use_callchain) {
  775. ui__warning("Selected -g but \"sym\" not present in --sort/-s.");
  776. return -EINVAL;
  777. }
  778. } else if (!dont_use_callchains && callchain_param.mode != CHAIN_NONE) {
  779. if (callchain_register_param(&callchain_param) < 0) {
  780. ui__warning("Can't register callchain params.\n");
  781. return -EINVAL;
  782. }
  783. }
  784. return 0;
  785. }
  786. static int __cmd_top(void)
  787. {
  788. pthread_t thread;
  789. int ret;
  790. /*
  791. * FIXME: perf_session__new should allow passing a O_MMAP, so that all this
  792. * mmap reading, etc is encapsulated in it. Use O_WRONLY for now.
  793. */
  794. top.session = perf_session__new(NULL, O_WRONLY, false, false, NULL);
  795. if (top.session == NULL)
  796. return -ENOMEM;
  797. ret = setup_sample_type();
  798. if (ret)
  799. goto out_delete;
  800. if (top.target_tid != -1)
  801. perf_event__synthesize_thread_map(top.evlist->threads,
  802. perf_event__process, top.session);
  803. else
  804. perf_event__synthesize_threads(perf_event__process, top.session);
  805. start_counters(top.evlist);
  806. top.session->evlist = top.evlist;
  807. perf_session__update_sample_type(top.session);
  808. /* Wait for a minimal set of events before starting the snapshot */
  809. poll(top.evlist->pollfd, top.evlist->nr_fds, 100);
  810. perf_session__mmap_read(top.session);
  811. if (pthread_create(&thread, NULL, (use_browser > 0 ? display_thread_tui :
  812. display_thread), NULL)) {
  813. printf("Could not create display thread.\n");
  814. exit(-1);
  815. }
  816. if (realtime_prio) {
  817. struct sched_param param;
  818. param.sched_priority = realtime_prio;
  819. if (sched_setscheduler(0, SCHED_FIFO, &param)) {
  820. printf("Could not set realtime priority.\n");
  821. exit(-1);
  822. }
  823. }
  824. while (1) {
  825. u64 hits = top.samples;
  826. perf_session__mmap_read(top.session);
  827. if (hits == top.samples)
  828. ret = poll(top.evlist->pollfd, top.evlist->nr_fds, 100);
  829. }
  830. out_delete:
  831. perf_session__delete(top.session);
  832. top.session = NULL;
  833. return 0;
  834. }
  835. static int
  836. parse_callchain_opt(const struct option *opt __used, const char *arg,
  837. int unset)
  838. {
  839. char *tok, *tok2;
  840. char *endptr;
  841. /*
  842. * --no-call-graph
  843. */
  844. if (unset) {
  845. dont_use_callchains = true;
  846. return 0;
  847. }
  848. symbol_conf.use_callchain = true;
  849. if (!arg)
  850. return 0;
  851. tok = strtok((char *)arg, ",");
  852. if (!tok)
  853. return -1;
  854. /* get the output mode */
  855. if (!strncmp(tok, "graph", strlen(arg)))
  856. callchain_param.mode = CHAIN_GRAPH_ABS;
  857. else if (!strncmp(tok, "flat", strlen(arg)))
  858. callchain_param.mode = CHAIN_FLAT;
  859. else if (!strncmp(tok, "fractal", strlen(arg)))
  860. callchain_param.mode = CHAIN_GRAPH_REL;
  861. else if (!strncmp(tok, "none", strlen(arg))) {
  862. callchain_param.mode = CHAIN_NONE;
  863. symbol_conf.use_callchain = false;
  864. return 0;
  865. }
  866. else
  867. return -1;
  868. /* get the min percentage */
  869. tok = strtok(NULL, ",");
  870. if (!tok)
  871. goto setup;
  872. callchain_param.min_percent = strtod(tok, &endptr);
  873. if (tok == endptr)
  874. return -1;
  875. /* get the print limit */
  876. tok2 = strtok(NULL, ",");
  877. if (!tok2)
  878. goto setup;
  879. if (tok2[0] != 'c') {
  880. callchain_param.print_limit = strtod(tok2, &endptr);
  881. tok2 = strtok(NULL, ",");
  882. if (!tok2)
  883. goto setup;
  884. }
  885. /* get the call chain order */
  886. if (!strcmp(tok2, "caller"))
  887. callchain_param.order = ORDER_CALLER;
  888. else if (!strcmp(tok2, "callee"))
  889. callchain_param.order = ORDER_CALLEE;
  890. else
  891. return -1;
  892. setup:
  893. if (callchain_register_param(&callchain_param) < 0) {
  894. fprintf(stderr, "Can't register callchain params\n");
  895. return -1;
  896. }
  897. return 0;
  898. }
  899. static const char * const top_usage[] = {
  900. "perf top [<options>]",
  901. NULL
  902. };
  903. static const struct option options[] = {
  904. OPT_CALLBACK('e', "event", &top.evlist, "event",
  905. "event selector. use 'perf list' to list available events",
  906. parse_events_option),
  907. OPT_INTEGER('c', "count", &default_interval,
  908. "event period to sample"),
  909. OPT_INTEGER('p', "pid", &top.target_pid,
  910. "profile events on existing process id"),
  911. OPT_INTEGER('t', "tid", &top.target_tid,
  912. "profile events on existing thread id"),
  913. OPT_BOOLEAN('a', "all-cpus", &system_wide,
  914. "system-wide collection from all CPUs"),
  915. OPT_STRING('C', "cpu", &top.cpu_list, "cpu",
  916. "list of cpus to monitor"),
  917. OPT_STRING('k', "vmlinux", &symbol_conf.vmlinux_name,
  918. "file", "vmlinux pathname"),
  919. OPT_BOOLEAN('K', "hide_kernel_symbols", &top.hide_kernel_symbols,
  920. "hide kernel symbols"),
  921. OPT_UINTEGER('m', "mmap-pages", &mmap_pages, "number of mmap data pages"),
  922. OPT_INTEGER('r', "realtime", &realtime_prio,
  923. "collect data with this RT SCHED_FIFO priority"),
  924. OPT_INTEGER('d', "delay", &top.delay_secs,
  925. "number of seconds to delay between refreshes"),
  926. OPT_BOOLEAN('D', "dump-symtab", &dump_symtab,
  927. "dump the symbol table used for profiling"),
  928. OPT_INTEGER('f', "count-filter", &top.count_filter,
  929. "only display functions with more events than this"),
  930. OPT_BOOLEAN('g', "group", &group,
  931. "put the counters into a counter group"),
  932. OPT_BOOLEAN('i', "inherit", &inherit,
  933. "child tasks inherit counters"),
  934. OPT_STRING(0, "sym-annotate", &sym_filter, "symbol name",
  935. "symbol to annotate"),
  936. OPT_BOOLEAN('z', "zero", &top.zero,
  937. "zero history across updates"),
  938. OPT_INTEGER('F', "freq", &top.freq,
  939. "profile at this frequency"),
  940. OPT_INTEGER('E', "entries", &top.print_entries,
  941. "display this many functions"),
  942. OPT_BOOLEAN('U', "hide_user_symbols", &top.hide_user_symbols,
  943. "hide user symbols"),
  944. OPT_BOOLEAN(0, "tui", &use_tui, "Use the TUI interface"),
  945. OPT_BOOLEAN(0, "stdio", &use_stdio, "Use the stdio interface"),
  946. OPT_INCR('v', "verbose", &verbose,
  947. "be more verbose (show counter open errors, etc)"),
  948. OPT_STRING('s', "sort", &sort_order, "key[,key2...]",
  949. "sort by key(s): pid, comm, dso, symbol, parent"),
  950. OPT_BOOLEAN('n', "show-nr-samples", &symbol_conf.show_nr_samples,
  951. "Show a column with the number of samples"),
  952. OPT_CALLBACK_DEFAULT('G', "call-graph", NULL, "output_type,min_percent, call_order",
  953. "Display callchains using output_type (graph, flat, fractal, or none), min percent threshold and callchain order. "
  954. "Default: fractal,0.5,callee", &parse_callchain_opt,
  955. callchain_default_opt),
  956. OPT_BOOLEAN(0, "show-total-period", &symbol_conf.show_total_period,
  957. "Show a column with the sum of periods"),
  958. OPT_STRING(0, "dsos", &symbol_conf.dso_list_str, "dso[,dso...]",
  959. "only consider symbols in these dsos"),
  960. OPT_STRING(0, "comms", &symbol_conf.comm_list_str, "comm[,comm...]",
  961. "only consider symbols in these comms"),
  962. OPT_STRING(0, "symbols", &symbol_conf.sym_list_str, "symbol[,symbol...]",
  963. "only consider these symbols"),
  964. OPT_BOOLEAN(0, "source", &symbol_conf.annotate_src,
  965. "Interleave source code with assembly code (default)"),
  966. OPT_BOOLEAN(0, "asm-raw", &symbol_conf.annotate_asm_raw,
  967. "Display raw encoding of assembly instructions (default)"),
  968. OPT_STRING('M', "disassembler-style", &disassembler_style, "disassembler style",
  969. "Specify disassembler style (e.g. -M intel for intel syntax)"),
  970. OPT_END()
  971. };
  972. int cmd_top(int argc, const char **argv, const char *prefix __used)
  973. {
  974. struct perf_evsel *pos;
  975. int status = -ENOMEM;
  976. top.evlist = perf_evlist__new(NULL, NULL);
  977. if (top.evlist == NULL)
  978. return -ENOMEM;
  979. symbol_conf.exclude_other = false;
  980. argc = parse_options(argc, argv, options, top_usage, 0);
  981. if (argc)
  982. usage_with_options(top_usage, options);
  983. if (sort_order == default_sort_order)
  984. sort_order = "dso,symbol";
  985. setup_sorting(top_usage, options);
  986. if (use_stdio)
  987. use_browser = 0;
  988. else if (use_tui)
  989. use_browser = 1;
  990. setup_browser(false);
  991. /* CPU and PID are mutually exclusive */
  992. if (top.target_tid > 0 && top.cpu_list) {
  993. printf("WARNING: PID switch overriding CPU\n");
  994. sleep(1);
  995. top.cpu_list = NULL;
  996. }
  997. if (top.target_pid != -1)
  998. top.target_tid = top.target_pid;
  999. if (perf_evlist__create_maps(top.evlist, top.target_pid,
  1000. top.target_tid, top.cpu_list) < 0)
  1001. usage_with_options(top_usage, options);
  1002. if (!top.evlist->nr_entries &&
  1003. perf_evlist__add_default(top.evlist) < 0) {
  1004. pr_err("Not enough memory for event selector list\n");
  1005. return -ENOMEM;
  1006. }
  1007. if (top.delay_secs < 1)
  1008. top.delay_secs = 1;
  1009. /*
  1010. * User specified count overrides default frequency.
  1011. */
  1012. if (default_interval)
  1013. top.freq = 0;
  1014. else if (top.freq) {
  1015. default_interval = top.freq;
  1016. } else {
  1017. fprintf(stderr, "frequency and count are zero, aborting\n");
  1018. exit(EXIT_FAILURE);
  1019. }
  1020. list_for_each_entry(pos, &top.evlist->entries, node) {
  1021. if (perf_evsel__alloc_fd(pos, top.evlist->cpus->nr,
  1022. top.evlist->threads->nr) < 0)
  1023. goto out_free_fd;
  1024. /*
  1025. * Fill in the ones not specifically initialized via -c:
  1026. */
  1027. if (pos->attr.sample_period)
  1028. continue;
  1029. pos->attr.sample_period = default_interval;
  1030. }
  1031. if (perf_evlist__alloc_pollfd(top.evlist) < 0 ||
  1032. perf_evlist__alloc_mmap(top.evlist) < 0)
  1033. goto out_free_fd;
  1034. top.sym_evsel = list_entry(top.evlist->entries.next, struct perf_evsel, node);
  1035. symbol_conf.priv_size = sizeof(struct annotation);
  1036. symbol_conf.try_vmlinux_path = (symbol_conf.vmlinux_name == NULL);
  1037. if (symbol__init() < 0)
  1038. return -1;
  1039. sort_entry__setup_elide(&sort_dso, symbol_conf.dso_list, "dso", stdout);
  1040. sort_entry__setup_elide(&sort_comm, symbol_conf.comm_list, "comm", stdout);
  1041. sort_entry__setup_elide(&sort_sym, symbol_conf.sym_list, "symbol", stdout);
  1042. /*
  1043. * Avoid annotation data structures overhead when symbols aren't on the
  1044. * sort list.
  1045. */
  1046. sort_has_symbols = sort_sym.list.next != NULL;
  1047. get_term_dimensions(&winsize);
  1048. if (top.print_entries == 0) {
  1049. update_print_entries(&winsize);
  1050. signal(SIGWINCH, sig_winch_handler);
  1051. }
  1052. status = __cmd_top();
  1053. out_free_fd:
  1054. perf_evlist__delete(top.evlist);
  1055. return status;
  1056. }