builtin-top.c 27 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111
  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. *
  9. * Improvements and fixes by:
  10. *
  11. * Arjan van de Ven <arjan@linux.intel.com>
  12. * Yanmin Zhang <yanmin.zhang@intel.com>
  13. * Wu Fengguang <fengguang.wu@intel.com>
  14. * Mike Galbraith <efault@gmx.de>
  15. * Paul Mackerras <paulus@samba.org>
  16. *
  17. * Released under the GPL v2. (and only v2, not any later version)
  18. */
  19. #include "builtin.h"
  20. #include "perf.h"
  21. #include "util/annotate.h"
  22. #include "util/cache.h"
  23. #include "util/color.h"
  24. #include "util/evlist.h"
  25. #include "util/evsel.h"
  26. #include "util/session.h"
  27. #include "util/symbol.h"
  28. #include "util/thread.h"
  29. #include "util/thread_map.h"
  30. #include "util/top.h"
  31. #include "util/util.h"
  32. #include <linux/rbtree.h>
  33. #include "util/parse-options.h"
  34. #include "util/parse-events.h"
  35. #include "util/cpumap.h"
  36. #include "util/xyarray.h"
  37. #include "util/debug.h"
  38. #include <assert.h>
  39. #include <fcntl.h>
  40. #include <stdio.h>
  41. #include <termios.h>
  42. #include <unistd.h>
  43. #include <inttypes.h>
  44. #include <errno.h>
  45. #include <time.h>
  46. #include <sched.h>
  47. #include <sys/syscall.h>
  48. #include <sys/ioctl.h>
  49. #include <sys/poll.h>
  50. #include <sys/prctl.h>
  51. #include <sys/wait.h>
  52. #include <sys/uio.h>
  53. #include <sys/mman.h>
  54. #include <linux/unistd.h>
  55. #include <linux/types.h>
  56. #define FD(e, x, y) (*(int *)xyarray__entry(e->fd, x, y))
  57. static struct perf_top top = {
  58. .count_filter = 5,
  59. .delay_secs = 2,
  60. .display_weighted = -1,
  61. .target_pid = -1,
  62. .target_tid = -1,
  63. .active_symbols = LIST_HEAD_INIT(top.active_symbols),
  64. .active_symbols_lock = PTHREAD_MUTEX_INITIALIZER,
  65. .active_symbols_cond = PTHREAD_COND_INITIALIZER,
  66. .freq = 1000, /* 1 KHz */
  67. };
  68. static bool system_wide = false;
  69. static bool use_tui, use_stdio;
  70. static int default_interval = 0;
  71. static bool inherit = false;
  72. static int realtime_prio = 0;
  73. static bool group = false;
  74. static unsigned int page_size;
  75. static unsigned int mmap_pages = 128;
  76. static bool dump_symtab = false;
  77. static struct winsize winsize;
  78. static const char *sym_filter = NULL;
  79. struct sym_entry *sym_filter_entry_sched = 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 sym_entry *syme)
  116. {
  117. struct symbol *sym;
  118. struct annotation *notes;
  119. struct map *map;
  120. int err = -1;
  121. if (!syme)
  122. return -1;
  123. sym = sym_entry__symbol(syme);
  124. map = syme->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, syme->map, 0);
  148. if (err == 0) {
  149. out_assign:
  150. top.sym_filter_entry = syme;
  151. }
  152. pthread_mutex_unlock(&notes->lock);
  153. return err;
  154. }
  155. static void __zero_source_counters(struct sym_entry *syme)
  156. {
  157. struct symbol *sym = sym_entry__symbol(syme);
  158. symbol__annotate_zero_histograms(sym);
  159. }
  160. static void record_precise_ip(struct sym_entry *syme, int counter, u64 ip)
  161. {
  162. struct annotation *notes;
  163. struct symbol *sym;
  164. if (syme != top.sym_filter_entry)
  165. return;
  166. sym = sym_entry__symbol(syme);
  167. notes = symbol__annotation(sym);
  168. if (pthread_mutex_trylock(&notes->lock))
  169. return;
  170. ip = syme->map->map_ip(syme->map, ip);
  171. symbol__inc_addr_samples(sym, syme->map, counter, ip);
  172. pthread_mutex_unlock(&notes->lock);
  173. }
  174. static void show_details(struct sym_entry *syme)
  175. {
  176. struct annotation *notes;
  177. struct symbol *symbol;
  178. int more;
  179. if (!syme)
  180. return;
  181. symbol = sym_entry__symbol(syme);
  182. notes = symbol__annotation(symbol);
  183. pthread_mutex_lock(&notes->lock);
  184. if (notes->src == NULL)
  185. goto out_unlock;
  186. printf("Showing %s for %s\n", event_name(top.sym_evsel), symbol->name);
  187. printf(" Events Pcnt (>=%d%%)\n", sym_pcnt_filter);
  188. more = symbol__annotate_printf(symbol, syme->map, top.sym_evsel->idx,
  189. 0, sym_pcnt_filter, top.print_entries, 4);
  190. if (top.zero)
  191. symbol__annotate_zero_histogram(symbol, top.sym_evsel->idx);
  192. else
  193. symbol__annotate_decay_histogram(symbol, top.sym_evsel->idx);
  194. if (more != 0)
  195. printf("%d lines not displayed, maybe increase display entries [e]\n", more);
  196. out_unlock:
  197. pthread_mutex_unlock(&notes->lock);
  198. }
  199. static const char CONSOLE_CLEAR[] = "";
  200. static void __list_insert_active_sym(struct sym_entry *syme)
  201. {
  202. list_add(&syme->node, &top.active_symbols);
  203. }
  204. static void print_sym_table(struct perf_session *session)
  205. {
  206. char bf[160];
  207. int printed = 0;
  208. struct rb_node *nd;
  209. struct sym_entry *syme;
  210. struct rb_root tmp = RB_ROOT;
  211. const int win_width = winsize.ws_col - 1;
  212. int sym_width, dso_width, dso_short_width;
  213. float sum_ksamples = perf_top__decay_samples(&top, &tmp);
  214. puts(CONSOLE_CLEAR);
  215. perf_top__header_snprintf(&top, bf, sizeof(bf));
  216. printf("%s\n", bf);
  217. perf_top__reset_sample_counters(&top);
  218. printf("%-*.*s\n", win_width, win_width, graph_dotted_line);
  219. if (session->hists.stats.total_lost != 0) {
  220. color_fprintf(stdout, PERF_COLOR_RED, "WARNING:");
  221. printf(" LOST %" PRIu64 " events, Check IO/CPU overload\n",
  222. session->hists.stats.total_lost);
  223. }
  224. if (top.sym_filter_entry) {
  225. show_details(top.sym_filter_entry);
  226. return;
  227. }
  228. perf_top__find_widths(&top, &tmp, &dso_width, &dso_short_width,
  229. &sym_width);
  230. if (sym_width + dso_width > winsize.ws_col - 29) {
  231. dso_width = dso_short_width;
  232. if (sym_width + dso_width > winsize.ws_col - 29)
  233. sym_width = winsize.ws_col - dso_width - 29;
  234. }
  235. putchar('\n');
  236. if (top.evlist->nr_entries == 1)
  237. printf(" samples pcnt");
  238. else
  239. printf(" weight samples pcnt");
  240. if (verbose)
  241. printf(" RIP ");
  242. printf(" %-*.*s DSO\n", sym_width, sym_width, "function");
  243. printf(" %s _______ _____",
  244. top.evlist->nr_entries == 1 ? " " : "______");
  245. if (verbose)
  246. printf(" ________________");
  247. printf(" %-*.*s", sym_width, sym_width, graph_line);
  248. printf(" %-*.*s", dso_width, dso_width, graph_line);
  249. puts("\n");
  250. for (nd = rb_first(&tmp); nd; nd = rb_next(nd)) {
  251. struct symbol *sym;
  252. double pcnt;
  253. syme = rb_entry(nd, struct sym_entry, rb_node);
  254. sym = sym_entry__symbol(syme);
  255. if (++printed > top.print_entries ||
  256. (int)syme->snap_count < top.count_filter)
  257. continue;
  258. pcnt = 100.0 - (100.0 * ((sum_ksamples - syme->snap_count) /
  259. sum_ksamples));
  260. if (top.evlist->nr_entries == 1 || !top.display_weighted)
  261. printf("%20.2f ", syme->weight);
  262. else
  263. printf("%9.1f %10ld ", syme->weight, syme->snap_count);
  264. percent_color_fprintf(stdout, "%4.1f%%", pcnt);
  265. if (verbose)
  266. printf(" %016" PRIx64, sym->start);
  267. printf(" %-*.*s", sym_width, sym_width, sym->name);
  268. printf(" %-*.*s\n", dso_width, dso_width,
  269. dso_width >= syme->map->dso->long_name_len ?
  270. syme->map->dso->long_name :
  271. syme->map->dso->short_name);
  272. }
  273. }
  274. static void prompt_integer(int *target, const char *msg)
  275. {
  276. char *buf = malloc(0), *p;
  277. size_t dummy = 0;
  278. int tmp;
  279. fprintf(stdout, "\n%s: ", msg);
  280. if (getline(&buf, &dummy, stdin) < 0)
  281. return;
  282. p = strchr(buf, '\n');
  283. if (p)
  284. *p = 0;
  285. p = buf;
  286. while(*p) {
  287. if (!isdigit(*p))
  288. goto out_free;
  289. p++;
  290. }
  291. tmp = strtoul(buf, NULL, 10);
  292. *target = tmp;
  293. out_free:
  294. free(buf);
  295. }
  296. static void prompt_percent(int *target, const char *msg)
  297. {
  298. int tmp = 0;
  299. prompt_integer(&tmp, msg);
  300. if (tmp >= 0 && tmp <= 100)
  301. *target = tmp;
  302. }
  303. static void prompt_symbol(struct sym_entry **target, const char *msg)
  304. {
  305. char *buf = malloc(0), *p;
  306. struct sym_entry *syme = *target, *n, *found = NULL;
  307. size_t dummy = 0;
  308. /* zero counters of active symbol */
  309. if (syme) {
  310. __zero_source_counters(syme);
  311. *target = NULL;
  312. }
  313. fprintf(stdout, "\n%s: ", msg);
  314. if (getline(&buf, &dummy, stdin) < 0)
  315. goto out_free;
  316. p = strchr(buf, '\n');
  317. if (p)
  318. *p = 0;
  319. pthread_mutex_lock(&top.active_symbols_lock);
  320. syme = list_entry(top.active_symbols.next, struct sym_entry, node);
  321. pthread_mutex_unlock(&top.active_symbols_lock);
  322. list_for_each_entry_safe_from(syme, n, &top.active_symbols, node) {
  323. struct symbol *sym = sym_entry__symbol(syme);
  324. if (!strcmp(buf, sym->name)) {
  325. found = syme;
  326. break;
  327. }
  328. }
  329. if (!found) {
  330. fprintf(stderr, "Sorry, %s is not active.\n", buf);
  331. sleep(1);
  332. return;
  333. } else
  334. parse_source(found);
  335. out_free:
  336. free(buf);
  337. }
  338. static void print_mapped_keys(void)
  339. {
  340. char *name = NULL;
  341. if (top.sym_filter_entry) {
  342. struct symbol *sym = sym_entry__symbol(top.sym_filter_entry);
  343. name = sym->name;
  344. }
  345. fprintf(stdout, "\nMapped keys:\n");
  346. fprintf(stdout, "\t[d] display refresh delay. \t(%d)\n", top.delay_secs);
  347. fprintf(stdout, "\t[e] display entries (lines). \t(%d)\n", top.print_entries);
  348. if (top.evlist->nr_entries > 1)
  349. fprintf(stdout, "\t[E] active event counter. \t(%s)\n", event_name(top.sym_evsel));
  350. fprintf(stdout, "\t[f] profile display filter (count). \t(%d)\n", top.count_filter);
  351. fprintf(stdout, "\t[F] annotate display filter (percent). \t(%d%%)\n", sym_pcnt_filter);
  352. fprintf(stdout, "\t[s] annotate symbol. \t(%s)\n", name?: "NULL");
  353. fprintf(stdout, "\t[S] stop annotation.\n");
  354. if (top.evlist->nr_entries > 1)
  355. fprintf(stdout, "\t[w] toggle display weighted/count[E]r. \t(%d)\n", top.display_weighted ? 1 : 0);
  356. fprintf(stdout,
  357. "\t[K] hide kernel_symbols symbols. \t(%s)\n",
  358. top.hide_kernel_symbols ? "yes" : "no");
  359. fprintf(stdout,
  360. "\t[U] hide user symbols. \t(%s)\n",
  361. top.hide_user_symbols ? "yes" : "no");
  362. fprintf(stdout, "\t[z] toggle sample zeroing. \t(%d)\n", top.zero ? 1 : 0);
  363. fprintf(stdout, "\t[qQ] quit.\n");
  364. }
  365. static int key_mapped(int c)
  366. {
  367. switch (c) {
  368. case 'd':
  369. case 'e':
  370. case 'f':
  371. case 'z':
  372. case 'q':
  373. case 'Q':
  374. case 'K':
  375. case 'U':
  376. case 'F':
  377. case 's':
  378. case 'S':
  379. return 1;
  380. case 'E':
  381. case 'w':
  382. return top.evlist->nr_entries > 1 ? 1 : 0;
  383. default:
  384. break;
  385. }
  386. return 0;
  387. }
  388. static void handle_keypress(struct perf_session *session, int c)
  389. {
  390. if (!key_mapped(c)) {
  391. struct pollfd stdin_poll = { .fd = 0, .events = POLLIN };
  392. struct termios tc, save;
  393. print_mapped_keys();
  394. fprintf(stdout, "\nEnter selection, or unmapped key to continue: ");
  395. fflush(stdout);
  396. tcgetattr(0, &save);
  397. tc = save;
  398. tc.c_lflag &= ~(ICANON | ECHO);
  399. tc.c_cc[VMIN] = 0;
  400. tc.c_cc[VTIME] = 0;
  401. tcsetattr(0, TCSANOW, &tc);
  402. poll(&stdin_poll, 1, -1);
  403. c = getc(stdin);
  404. tcsetattr(0, TCSAFLUSH, &save);
  405. if (!key_mapped(c))
  406. return;
  407. }
  408. switch (c) {
  409. case 'd':
  410. prompt_integer(&top.delay_secs, "Enter display delay");
  411. if (top.delay_secs < 1)
  412. top.delay_secs = 1;
  413. break;
  414. case 'e':
  415. prompt_integer(&top.print_entries, "Enter display entries (lines)");
  416. if (top.print_entries == 0) {
  417. sig_winch_handler(SIGWINCH);
  418. signal(SIGWINCH, sig_winch_handler);
  419. } else
  420. signal(SIGWINCH, SIG_DFL);
  421. break;
  422. case 'E':
  423. if (top.evlist->nr_entries > 1) {
  424. /* Select 0 as the default event: */
  425. int counter = 0;
  426. fprintf(stderr, "\nAvailable events:");
  427. list_for_each_entry(top.sym_evsel, &top.evlist->entries, node)
  428. fprintf(stderr, "\n\t%d %s", top.sym_evsel->idx, event_name(top.sym_evsel));
  429. prompt_integer(&counter, "Enter details event counter");
  430. if (counter >= top.evlist->nr_entries) {
  431. top.sym_evsel = list_entry(top.evlist->entries.next, struct perf_evsel, node);
  432. fprintf(stderr, "Sorry, no such event, using %s.\n", event_name(top.sym_evsel));
  433. sleep(1);
  434. break;
  435. }
  436. list_for_each_entry(top.sym_evsel, &top.evlist->entries, node)
  437. if (top.sym_evsel->idx == counter)
  438. break;
  439. } else
  440. top.sym_evsel = list_entry(top.evlist->entries.next, struct perf_evsel, node);
  441. break;
  442. case 'f':
  443. prompt_integer(&top.count_filter, "Enter display event count filter");
  444. break;
  445. case 'F':
  446. prompt_percent(&sym_pcnt_filter, "Enter details display event filter (percent)");
  447. break;
  448. case 'K':
  449. top.hide_kernel_symbols = !top.hide_kernel_symbols;
  450. break;
  451. case 'q':
  452. case 'Q':
  453. printf("exiting.\n");
  454. if (dump_symtab)
  455. perf_session__fprintf_dsos(session, stderr);
  456. exit(0);
  457. case 's':
  458. prompt_symbol(&top.sym_filter_entry, "Enter details symbol");
  459. break;
  460. case 'S':
  461. if (!top.sym_filter_entry)
  462. break;
  463. else {
  464. struct sym_entry *syme = top.sym_filter_entry;
  465. top.sym_filter_entry = NULL;
  466. __zero_source_counters(syme);
  467. }
  468. break;
  469. case 'U':
  470. top.hide_user_symbols = !top.hide_user_symbols;
  471. break;
  472. case 'w':
  473. top.display_weighted = ~top.display_weighted;
  474. break;
  475. case 'z':
  476. top.zero = !top.zero;
  477. break;
  478. default:
  479. break;
  480. }
  481. }
  482. static void *display_thread_tui(void *arg __used)
  483. {
  484. int err = 0;
  485. pthread_mutex_lock(&top.active_symbols_lock);
  486. while (list_empty(&top.active_symbols)) {
  487. err = pthread_cond_wait(&top.active_symbols_cond,
  488. &top.active_symbols_lock);
  489. if (err)
  490. break;
  491. }
  492. pthread_mutex_unlock(&top.active_symbols_lock);
  493. if (!err)
  494. perf_top__tui_browser(&top);
  495. exit_browser(0);
  496. exit(0);
  497. return NULL;
  498. }
  499. static void *display_thread(void *arg __used)
  500. {
  501. struct pollfd stdin_poll = { .fd = 0, .events = POLLIN };
  502. struct termios tc, save;
  503. int delay_msecs, c;
  504. struct perf_session *session = (struct perf_session *) arg;
  505. tcgetattr(0, &save);
  506. tc = save;
  507. tc.c_lflag &= ~(ICANON | ECHO);
  508. tc.c_cc[VMIN] = 0;
  509. tc.c_cc[VTIME] = 0;
  510. repeat:
  511. delay_msecs = top.delay_secs * 1000;
  512. tcsetattr(0, TCSANOW, &tc);
  513. /* trash return*/
  514. getc(stdin);
  515. do {
  516. print_sym_table(session);
  517. } while (!poll(&stdin_poll, 1, delay_msecs) == 1);
  518. c = getc(stdin);
  519. tcsetattr(0, TCSAFLUSH, &save);
  520. handle_keypress(session, c);
  521. goto repeat;
  522. return NULL;
  523. }
  524. /* Tag samples to be skipped. */
  525. static const char *skip_symbols[] = {
  526. "default_idle",
  527. "native_safe_halt",
  528. "cpu_idle",
  529. "enter_idle",
  530. "exit_idle",
  531. "mwait_idle",
  532. "mwait_idle_with_hints",
  533. "poll_idle",
  534. "ppc64_runlatch_off",
  535. "pseries_dedicated_idle_sleep",
  536. NULL
  537. };
  538. static int symbol_filter(struct map *map, struct symbol *sym)
  539. {
  540. struct sym_entry *syme;
  541. const char *name = sym->name;
  542. int i;
  543. /*
  544. * ppc64 uses function descriptors and appends a '.' to the
  545. * start of every instruction address. Remove it.
  546. */
  547. if (name[0] == '.')
  548. name++;
  549. if (!strcmp(name, "_text") ||
  550. !strcmp(name, "_etext") ||
  551. !strcmp(name, "_sinittext") ||
  552. !strncmp("init_module", name, 11) ||
  553. !strncmp("cleanup_module", name, 14) ||
  554. strstr(name, "_text_start") ||
  555. strstr(name, "_text_end"))
  556. return 1;
  557. syme = symbol__priv(sym);
  558. syme->map = map;
  559. symbol__annotate_init(map, sym);
  560. if (!top.sym_filter_entry && sym_filter && !strcmp(name, sym_filter)) {
  561. /* schedule initial sym_filter_entry setup */
  562. sym_filter_entry_sched = syme;
  563. sym_filter = NULL;
  564. }
  565. for (i = 0; skip_symbols[i]; i++) {
  566. if (!strcmp(skip_symbols[i], name)) {
  567. sym->ignore = true;
  568. break;
  569. }
  570. }
  571. return 0;
  572. }
  573. static void perf_event__process_sample(const union perf_event *event,
  574. struct perf_sample *sample,
  575. struct perf_session *session)
  576. {
  577. u64 ip = event->ip.ip;
  578. struct sym_entry *syme;
  579. struct addr_location al;
  580. struct machine *machine;
  581. u8 origin = event->header.misc & PERF_RECORD_MISC_CPUMODE_MASK;
  582. ++top.samples;
  583. switch (origin) {
  584. case PERF_RECORD_MISC_USER:
  585. ++top.us_samples;
  586. if (top.hide_user_symbols)
  587. return;
  588. machine = perf_session__find_host_machine(session);
  589. break;
  590. case PERF_RECORD_MISC_KERNEL:
  591. ++top.kernel_samples;
  592. if (top.hide_kernel_symbols)
  593. return;
  594. machine = perf_session__find_host_machine(session);
  595. break;
  596. case PERF_RECORD_MISC_GUEST_KERNEL:
  597. ++top.guest_kernel_samples;
  598. machine = perf_session__find_machine(session, event->ip.pid);
  599. break;
  600. case PERF_RECORD_MISC_GUEST_USER:
  601. ++top.guest_us_samples;
  602. /*
  603. * TODO: we don't process guest user from host side
  604. * except simple counting.
  605. */
  606. return;
  607. default:
  608. return;
  609. }
  610. if (!machine && perf_guest) {
  611. pr_err("Can't find guest [%d]'s kernel information\n",
  612. event->ip.pid);
  613. return;
  614. }
  615. if (event->header.misc & PERF_RECORD_MISC_EXACT_IP)
  616. top.exact_samples++;
  617. if (perf_event__preprocess_sample(event, session, &al, sample,
  618. symbol_filter) < 0 ||
  619. al.filtered)
  620. return;
  621. if (al.sym == NULL) {
  622. /*
  623. * As we do lazy loading of symtabs we only will know if the
  624. * specified vmlinux file is invalid when we actually have a
  625. * hit in kernel space and then try to load it. So if we get
  626. * here and there are _no_ symbols in the DSO backing the
  627. * kernel map, bail out.
  628. *
  629. * We may never get here, for instance, if we use -K/
  630. * --hide-kernel-symbols, even if the user specifies an
  631. * invalid --vmlinux ;-)
  632. */
  633. if (al.map == machine->vmlinux_maps[MAP__FUNCTION] &&
  634. RB_EMPTY_ROOT(&al.map->dso->symbols[MAP__FUNCTION])) {
  635. ui__warning("The %s file can't be used\n",
  636. symbol_conf.vmlinux_name);
  637. exit_browser(0);
  638. exit(1);
  639. }
  640. return;
  641. }
  642. /* let's see, whether we need to install initial sym_filter_entry */
  643. if (sym_filter_entry_sched) {
  644. top.sym_filter_entry = sym_filter_entry_sched;
  645. sym_filter_entry_sched = NULL;
  646. if (parse_source(top.sym_filter_entry) < 0) {
  647. struct symbol *sym = sym_entry__symbol(top.sym_filter_entry);
  648. pr_err("Can't annotate %s", sym->name);
  649. if (top.sym_filter_entry->map->dso->symtab_type == SYMTAB__KALLSYMS) {
  650. pr_err(": No vmlinux file was found in the path:\n");
  651. machine__fprintf_vmlinux_path(machine, stderr);
  652. } else
  653. pr_err(".\n");
  654. exit(1);
  655. }
  656. }
  657. syme = symbol__priv(al.sym);
  658. if (!al.sym->ignore) {
  659. struct perf_evsel *evsel;
  660. evsel = perf_evlist__id2evsel(top.evlist, sample->id);
  661. assert(evsel != NULL);
  662. syme->count[evsel->idx]++;
  663. record_precise_ip(syme, evsel->idx, ip);
  664. pthread_mutex_lock(&top.active_symbols_lock);
  665. if (list_empty(&syme->node) || !syme->node.next) {
  666. static bool first = true;
  667. __list_insert_active_sym(syme);
  668. if (first) {
  669. pthread_cond_broadcast(&top.active_symbols_cond);
  670. first = false;
  671. }
  672. }
  673. pthread_mutex_unlock(&top.active_symbols_lock);
  674. }
  675. }
  676. static void perf_session__mmap_read_cpu(struct perf_session *self, int cpu)
  677. {
  678. struct perf_sample sample;
  679. union perf_event *event;
  680. while ((event = perf_evlist__read_on_cpu(top.evlist, cpu)) != NULL) {
  681. perf_session__parse_sample(self, event, &sample);
  682. if (event->header.type == PERF_RECORD_SAMPLE)
  683. perf_event__process_sample(event, &sample, self);
  684. else
  685. perf_event__process(event, &sample, self);
  686. }
  687. }
  688. static void perf_session__mmap_read(struct perf_session *self)
  689. {
  690. int i;
  691. for (i = 0; i < top.evlist->cpus->nr; i++)
  692. perf_session__mmap_read_cpu(self, i);
  693. }
  694. static void start_counters(struct perf_evlist *evlist)
  695. {
  696. struct perf_evsel *counter;
  697. list_for_each_entry(counter, &evlist->entries, node) {
  698. struct perf_event_attr *attr = &counter->attr;
  699. attr->sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_TID;
  700. if (top.freq) {
  701. attr->sample_type |= PERF_SAMPLE_PERIOD;
  702. attr->freq = 1;
  703. attr->sample_freq = top.freq;
  704. }
  705. if (evlist->nr_entries > 1) {
  706. attr->sample_type |= PERF_SAMPLE_ID;
  707. attr->read_format |= PERF_FORMAT_ID;
  708. }
  709. attr->mmap = 1;
  710. attr->inherit = inherit;
  711. try_again:
  712. if (perf_evsel__open(counter, top.evlist->cpus,
  713. top.evlist->threads, group) < 0) {
  714. int err = errno;
  715. if (err == EPERM || err == EACCES) {
  716. ui__warning_paranoid();
  717. goto out_err;
  718. }
  719. /*
  720. * If it's cycles then fall back to hrtimer
  721. * based cpu-clock-tick sw counter, which
  722. * is always available even if no PMU support:
  723. */
  724. if (attr->type == PERF_TYPE_HARDWARE &&
  725. attr->config == PERF_COUNT_HW_CPU_CYCLES) {
  726. if (verbose)
  727. ui__warning("Cycles event not supported,\n"
  728. "trying to fall back to cpu-clock-ticks\n");
  729. attr->type = PERF_TYPE_SOFTWARE;
  730. attr->config = PERF_COUNT_SW_CPU_CLOCK;
  731. goto try_again;
  732. }
  733. if (err == ENOENT) {
  734. ui__warning("The %s event is not supported.\n",
  735. event_name(counter));
  736. goto out_err;
  737. }
  738. ui__warning("The sys_perf_event_open() syscall "
  739. "returned with %d (%s). /bin/dmesg "
  740. "may provide additional information.\n"
  741. "No CONFIG_PERF_EVENTS=y kernel support "
  742. "configured?\n", err, strerror(err));
  743. goto out_err;
  744. }
  745. }
  746. if (perf_evlist__mmap(evlist, mmap_pages, false) < 0) {
  747. ui__warning("Failed to mmap with %d (%s)\n",
  748. errno, strerror(errno));
  749. goto out_err;
  750. }
  751. return;
  752. out_err:
  753. exit_browser(0);
  754. exit(0);
  755. }
  756. static int __cmd_top(void)
  757. {
  758. pthread_t thread;
  759. int ret __used;
  760. /*
  761. * FIXME: perf_session__new should allow passing a O_MMAP, so that all this
  762. * mmap reading, etc is encapsulated in it. Use O_WRONLY for now.
  763. */
  764. struct perf_session *session = perf_session__new(NULL, O_WRONLY, false, false, NULL);
  765. if (session == NULL)
  766. return -ENOMEM;
  767. if (top.target_tid != -1)
  768. perf_event__synthesize_thread_map(top.evlist->threads,
  769. perf_event__process, session);
  770. else
  771. perf_event__synthesize_threads(perf_event__process, session);
  772. start_counters(top.evlist);
  773. session->evlist = top.evlist;
  774. perf_session__update_sample_type(session);
  775. /* Wait for a minimal set of events before starting the snapshot */
  776. poll(top.evlist->pollfd, top.evlist->nr_fds, 100);
  777. perf_session__mmap_read(session);
  778. if (pthread_create(&thread, NULL, (use_browser > 0 ? display_thread_tui :
  779. display_thread), session)) {
  780. printf("Could not create display thread.\n");
  781. exit(-1);
  782. }
  783. if (realtime_prio) {
  784. struct sched_param param;
  785. param.sched_priority = realtime_prio;
  786. if (sched_setscheduler(0, SCHED_FIFO, &param)) {
  787. printf("Could not set realtime priority.\n");
  788. exit(-1);
  789. }
  790. }
  791. while (1) {
  792. u64 hits = top.samples;
  793. perf_session__mmap_read(session);
  794. if (hits == top.samples)
  795. ret = poll(top.evlist->pollfd, top.evlist->nr_fds, 100);
  796. }
  797. return 0;
  798. }
  799. static const char * const top_usage[] = {
  800. "perf top [<options>]",
  801. NULL
  802. };
  803. static const struct option options[] = {
  804. OPT_CALLBACK('e', "event", &top.evlist, "event",
  805. "event selector. use 'perf list' to list available events",
  806. parse_events),
  807. OPT_INTEGER('c', "count", &default_interval,
  808. "event period to sample"),
  809. OPT_INTEGER('p', "pid", &top.target_pid,
  810. "profile events on existing process id"),
  811. OPT_INTEGER('t', "tid", &top.target_tid,
  812. "profile events on existing thread id"),
  813. OPT_BOOLEAN('a', "all-cpus", &system_wide,
  814. "system-wide collection from all CPUs"),
  815. OPT_STRING('C', "cpu", &top.cpu_list, "cpu",
  816. "list of cpus to monitor"),
  817. OPT_STRING('k', "vmlinux", &symbol_conf.vmlinux_name,
  818. "file", "vmlinux pathname"),
  819. OPT_BOOLEAN('K', "hide_kernel_symbols", &top.hide_kernel_symbols,
  820. "hide kernel symbols"),
  821. OPT_UINTEGER('m', "mmap-pages", &mmap_pages, "number of mmap data pages"),
  822. OPT_INTEGER('r', "realtime", &realtime_prio,
  823. "collect data with this RT SCHED_FIFO priority"),
  824. OPT_INTEGER('d', "delay", &top.delay_secs,
  825. "number of seconds to delay between refreshes"),
  826. OPT_BOOLEAN('D', "dump-symtab", &dump_symtab,
  827. "dump the symbol table used for profiling"),
  828. OPT_INTEGER('f', "count-filter", &top.count_filter,
  829. "only display functions with more events than this"),
  830. OPT_BOOLEAN('g', "group", &group,
  831. "put the counters into a counter group"),
  832. OPT_BOOLEAN('i', "inherit", &inherit,
  833. "child tasks inherit counters"),
  834. OPT_STRING('s', "sym-annotate", &sym_filter, "symbol name",
  835. "symbol to annotate"),
  836. OPT_BOOLEAN('z', "zero", &top.zero,
  837. "zero history across updates"),
  838. OPT_INTEGER('F', "freq", &top.freq,
  839. "profile at this frequency"),
  840. OPT_INTEGER('E', "entries", &top.print_entries,
  841. "display this many functions"),
  842. OPT_BOOLEAN('U', "hide_user_symbols", &top.hide_user_symbols,
  843. "hide user symbols"),
  844. OPT_BOOLEAN(0, "tui", &use_tui, "Use the TUI interface"),
  845. OPT_BOOLEAN(0, "stdio", &use_stdio, "Use the stdio interface"),
  846. OPT_INCR('v', "verbose", &verbose,
  847. "be more verbose (show counter open errors, etc)"),
  848. OPT_END()
  849. };
  850. int cmd_top(int argc, const char **argv, const char *prefix __used)
  851. {
  852. struct perf_evsel *pos;
  853. int status = -ENOMEM;
  854. top.evlist = perf_evlist__new(NULL, NULL);
  855. if (top.evlist == NULL)
  856. return -ENOMEM;
  857. page_size = sysconf(_SC_PAGE_SIZE);
  858. argc = parse_options(argc, argv, options, top_usage, 0);
  859. if (argc)
  860. usage_with_options(top_usage, options);
  861. /*
  862. * XXX For now start disabled, only using TUI if explicitely asked for.
  863. * Change that when handle_keys equivalent gets written, live annotation
  864. * done, etc.
  865. */
  866. use_browser = 0;
  867. if (use_stdio)
  868. use_browser = 0;
  869. else if (use_tui)
  870. use_browser = 1;
  871. setup_browser(false);
  872. /* CPU and PID are mutually exclusive */
  873. if (top.target_tid > 0 && top.cpu_list) {
  874. printf("WARNING: PID switch overriding CPU\n");
  875. sleep(1);
  876. top.cpu_list = NULL;
  877. }
  878. if (top.target_pid != -1)
  879. top.target_tid = top.target_pid;
  880. if (perf_evlist__create_maps(top.evlist, top.target_pid,
  881. top.target_tid, top.cpu_list) < 0)
  882. usage_with_options(top_usage, options);
  883. if (!top.evlist->nr_entries &&
  884. perf_evlist__add_default(top.evlist) < 0) {
  885. pr_err("Not enough memory for event selector list\n");
  886. return -ENOMEM;
  887. }
  888. if (top.delay_secs < 1)
  889. top.delay_secs = 1;
  890. /*
  891. * User specified count overrides default frequency.
  892. */
  893. if (default_interval)
  894. top.freq = 0;
  895. else if (top.freq) {
  896. default_interval = top.freq;
  897. } else {
  898. fprintf(stderr, "frequency and count are zero, aborting\n");
  899. exit(EXIT_FAILURE);
  900. }
  901. list_for_each_entry(pos, &top.evlist->entries, node) {
  902. if (perf_evsel__alloc_fd(pos, top.evlist->cpus->nr,
  903. top.evlist->threads->nr) < 0)
  904. goto out_free_fd;
  905. /*
  906. * Fill in the ones not specifically initialized via -c:
  907. */
  908. if (pos->attr.sample_period)
  909. continue;
  910. pos->attr.sample_period = default_interval;
  911. }
  912. if (perf_evlist__alloc_pollfd(top.evlist) < 0 ||
  913. perf_evlist__alloc_mmap(top.evlist) < 0)
  914. goto out_free_fd;
  915. top.sym_evsel = list_entry(top.evlist->entries.next, struct perf_evsel, node);
  916. symbol_conf.priv_size = (sizeof(struct sym_entry) + sizeof(struct annotation) +
  917. (top.evlist->nr_entries + 1) * sizeof(unsigned long));
  918. symbol_conf.try_vmlinux_path = (symbol_conf.vmlinux_name == NULL);
  919. if (symbol__init() < 0)
  920. return -1;
  921. get_term_dimensions(&winsize);
  922. if (top.print_entries == 0) {
  923. update_print_entries(&winsize);
  924. signal(SIGWINCH, sig_winch_handler);
  925. }
  926. status = __cmd_top();
  927. out_free_fd:
  928. perf_evlist__delete(top.evlist);
  929. return status;
  930. }