builtin-top.c 31 KB

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