builtin-top.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092
  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->origin == DSO__ORIG_KERNEL) {
  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. fprintf(stderr, "\nAvailable events:");
  425. list_for_each_entry(top.sym_evsel, &top.evlist->entries, node)
  426. fprintf(stderr, "\n\t%d %s", top.sym_evsel->idx, event_name(top.sym_evsel));
  427. prompt_integer(&top.sym_counter, "Enter details event counter");
  428. if (top.sym_counter >= top.evlist->nr_entries) {
  429. top.sym_evsel = list_entry(top.evlist->entries.next, struct perf_evsel, node);
  430. top.sym_counter = 0;
  431. fprintf(stderr, "Sorry, no such event, using %s.\n", event_name(top.sym_evsel));
  432. sleep(1);
  433. break;
  434. }
  435. list_for_each_entry(top.sym_evsel, &top.evlist->entries, node)
  436. if (top.sym_evsel->idx == top.sym_counter)
  437. break;
  438. } else top.sym_counter = 0;
  439. break;
  440. case 'f':
  441. prompt_integer(&top.count_filter, "Enter display event count filter");
  442. break;
  443. case 'F':
  444. prompt_percent(&sym_pcnt_filter, "Enter details display event filter (percent)");
  445. break;
  446. case 'K':
  447. top.hide_kernel_symbols = !top.hide_kernel_symbols;
  448. break;
  449. case 'q':
  450. case 'Q':
  451. printf("exiting.\n");
  452. if (dump_symtab)
  453. perf_session__fprintf_dsos(session, stderr);
  454. exit(0);
  455. case 's':
  456. prompt_symbol(&top.sym_filter_entry, "Enter details symbol");
  457. break;
  458. case 'S':
  459. if (!top.sym_filter_entry)
  460. break;
  461. else {
  462. struct sym_entry *syme = top.sym_filter_entry;
  463. top.sym_filter_entry = NULL;
  464. __zero_source_counters(syme);
  465. }
  466. break;
  467. case 'U':
  468. top.hide_user_symbols = !top.hide_user_symbols;
  469. break;
  470. case 'w':
  471. top.display_weighted = ~top.display_weighted;
  472. break;
  473. case 'z':
  474. top.zero = !top.zero;
  475. break;
  476. default:
  477. break;
  478. }
  479. }
  480. static void *display_thread_tui(void *arg __used)
  481. {
  482. int err = 0;
  483. pthread_mutex_lock(&top.active_symbols_lock);
  484. while (list_empty(&top.active_symbols)) {
  485. err = pthread_cond_wait(&top.active_symbols_cond,
  486. &top.active_symbols_lock);
  487. if (err)
  488. break;
  489. }
  490. pthread_mutex_unlock(&top.active_symbols_lock);
  491. if (!err)
  492. perf_top__tui_browser(&top);
  493. exit_browser(0);
  494. exit(0);
  495. return NULL;
  496. }
  497. static void *display_thread(void *arg __used)
  498. {
  499. struct pollfd stdin_poll = { .fd = 0, .events = POLLIN };
  500. struct termios tc, save;
  501. int delay_msecs, c;
  502. struct perf_session *session = (struct perf_session *) arg;
  503. tcgetattr(0, &save);
  504. tc = save;
  505. tc.c_lflag &= ~(ICANON | ECHO);
  506. tc.c_cc[VMIN] = 0;
  507. tc.c_cc[VTIME] = 0;
  508. repeat:
  509. delay_msecs = top.delay_secs * 1000;
  510. tcsetattr(0, TCSANOW, &tc);
  511. /* trash return*/
  512. getc(stdin);
  513. do {
  514. print_sym_table(session);
  515. } while (!poll(&stdin_poll, 1, delay_msecs) == 1);
  516. c = getc(stdin);
  517. tcsetattr(0, TCSAFLUSH, &save);
  518. handle_keypress(session, c);
  519. goto repeat;
  520. return NULL;
  521. }
  522. /* Tag samples to be skipped. */
  523. static const char *skip_symbols[] = {
  524. "default_idle",
  525. "native_safe_halt",
  526. "cpu_idle",
  527. "enter_idle",
  528. "exit_idle",
  529. "mwait_idle",
  530. "mwait_idle_with_hints",
  531. "poll_idle",
  532. "ppc64_runlatch_off",
  533. "pseries_dedicated_idle_sleep",
  534. NULL
  535. };
  536. static int symbol_filter(struct map *map, struct symbol *sym)
  537. {
  538. struct sym_entry *syme;
  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. syme = symbol__priv(sym);
  556. syme->map = map;
  557. symbol__annotate_init(map, sym);
  558. if (!top.sym_filter_entry && sym_filter && !strcmp(name, sym_filter)) {
  559. /* schedule initial sym_filter_entry setup */
  560. sym_filter_entry_sched = syme;
  561. sym_filter = NULL;
  562. }
  563. for (i = 0; skip_symbols[i]; i++) {
  564. if (!strcmp(skip_symbols[i], name)) {
  565. syme->skip = 1;
  566. break;
  567. }
  568. }
  569. return 0;
  570. }
  571. static void perf_event__process_sample(const union perf_event *event,
  572. struct perf_sample *sample,
  573. struct perf_session *session)
  574. {
  575. u64 ip = event->ip.ip;
  576. struct sym_entry *syme;
  577. struct addr_location al;
  578. struct machine *machine;
  579. u8 origin = event->header.misc & PERF_RECORD_MISC_CPUMODE_MASK;
  580. ++top.samples;
  581. switch (origin) {
  582. case PERF_RECORD_MISC_USER:
  583. ++top.us_samples;
  584. if (top.hide_user_symbols)
  585. return;
  586. machine = perf_session__find_host_machine(session);
  587. break;
  588. case PERF_RECORD_MISC_KERNEL:
  589. ++top.kernel_samples;
  590. if (top.hide_kernel_symbols)
  591. return;
  592. machine = perf_session__find_host_machine(session);
  593. break;
  594. case PERF_RECORD_MISC_GUEST_KERNEL:
  595. ++top.guest_kernel_samples;
  596. machine = perf_session__find_machine(session, event->ip.pid);
  597. break;
  598. case PERF_RECORD_MISC_GUEST_USER:
  599. ++top.guest_us_samples;
  600. /*
  601. * TODO: we don't process guest user from host side
  602. * except simple counting.
  603. */
  604. return;
  605. default:
  606. return;
  607. }
  608. if (!machine && perf_guest) {
  609. pr_err("Can't find guest [%d]'s kernel information\n",
  610. event->ip.pid);
  611. return;
  612. }
  613. if (event->header.misc & PERF_RECORD_MISC_EXACT_IP)
  614. top.exact_samples++;
  615. if (perf_event__preprocess_sample(event, session, &al, sample,
  616. symbol_filter) < 0 ||
  617. al.filtered)
  618. return;
  619. if (al.sym == NULL) {
  620. /*
  621. * As we do lazy loading of symtabs we only will know if the
  622. * specified vmlinux file is invalid when we actually have a
  623. * hit in kernel space and then try to load it. So if we get
  624. * here and there are _no_ symbols in the DSO backing the
  625. * kernel map, bail out.
  626. *
  627. * We may never get here, for instance, if we use -K/
  628. * --hide-kernel-symbols, even if the user specifies an
  629. * invalid --vmlinux ;-)
  630. */
  631. if (al.map == machine->vmlinux_maps[MAP__FUNCTION] &&
  632. RB_EMPTY_ROOT(&al.map->dso->symbols[MAP__FUNCTION])) {
  633. ui__warning("The %s file can't be used\n",
  634. symbol_conf.vmlinux_name);
  635. exit_browser(0);
  636. exit(1);
  637. }
  638. return;
  639. }
  640. /* let's see, whether we need to install initial sym_filter_entry */
  641. if (sym_filter_entry_sched) {
  642. top.sym_filter_entry = sym_filter_entry_sched;
  643. sym_filter_entry_sched = NULL;
  644. if (parse_source(top.sym_filter_entry) < 0) {
  645. struct symbol *sym = sym_entry__symbol(top.sym_filter_entry);
  646. pr_err("Can't annotate %s", sym->name);
  647. if (top.sym_filter_entry->map->dso->origin == DSO__ORIG_KERNEL) {
  648. pr_err(": No vmlinux file was found in the path:\n");
  649. machine__fprintf_vmlinux_path(machine, stderr);
  650. } else
  651. pr_err(".\n");
  652. exit(1);
  653. }
  654. }
  655. syme = symbol__priv(al.sym);
  656. if (!syme->skip) {
  657. struct perf_evsel *evsel;
  658. syme->origin = origin;
  659. evsel = perf_evlist__id2evsel(top.evlist, sample->id);
  660. assert(evsel != NULL);
  661. syme->count[evsel->idx]++;
  662. record_precise_ip(syme, evsel->idx, ip);
  663. pthread_mutex_lock(&top.active_symbols_lock);
  664. if (list_empty(&syme->node) || !syme->node.next) {
  665. static bool first = true;
  666. __list_insert_active_sym(syme);
  667. if (first) {
  668. pthread_cond_broadcast(&top.active_symbols_cond);
  669. first = false;
  670. }
  671. }
  672. pthread_mutex_unlock(&top.active_symbols_lock);
  673. }
  674. }
  675. static void perf_session__mmap_read_cpu(struct perf_session *self, int cpu)
  676. {
  677. struct perf_sample sample;
  678. union perf_event *event;
  679. while ((event = perf_evlist__read_on_cpu(top.evlist, cpu)) != NULL) {
  680. perf_session__parse_sample(self, event, &sample);
  681. if (event->header.type == PERF_RECORD_SAMPLE)
  682. perf_event__process_sample(event, &sample, self);
  683. else
  684. perf_event__process(event, &sample, self);
  685. }
  686. }
  687. static void perf_session__mmap_read(struct perf_session *self)
  688. {
  689. int i;
  690. for (i = 0; i < top.evlist->cpus->nr; i++)
  691. perf_session__mmap_read_cpu(self, i);
  692. }
  693. static void start_counters(struct perf_evlist *evlist)
  694. {
  695. struct perf_evsel *counter;
  696. list_for_each_entry(counter, &evlist->entries, node) {
  697. struct perf_event_attr *attr = &counter->attr;
  698. attr->sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_TID;
  699. if (top.freq) {
  700. attr->sample_type |= PERF_SAMPLE_PERIOD;
  701. attr->freq = 1;
  702. attr->sample_freq = top.freq;
  703. }
  704. if (evlist->nr_entries > 1) {
  705. attr->sample_type |= PERF_SAMPLE_ID;
  706. attr->read_format |= PERF_FORMAT_ID;
  707. }
  708. attr->mmap = 1;
  709. try_again:
  710. if (perf_evsel__open(counter, top.evlist->cpus,
  711. top.evlist->threads, group, inherit) < 0) {
  712. int err = errno;
  713. if (err == EPERM || err == EACCES)
  714. die("Permission error - are you root?\n"
  715. "\t Consider tweaking"
  716. " /proc/sys/kernel/perf_event_paranoid.\n");
  717. /*
  718. * If it's cycles then fall back to hrtimer
  719. * based cpu-clock-tick sw counter, which
  720. * is always available even if no PMU support:
  721. */
  722. if (attr->type == PERF_TYPE_HARDWARE &&
  723. attr->config == PERF_COUNT_HW_CPU_CYCLES) {
  724. if (verbose)
  725. warning(" ... trying to fall back to cpu-clock-ticks\n");
  726. attr->type = PERF_TYPE_SOFTWARE;
  727. attr->config = PERF_COUNT_SW_CPU_CLOCK;
  728. goto try_again;
  729. }
  730. printf("\n");
  731. error("sys_perf_event_open() syscall returned with %d "
  732. "(%s). /bin/dmesg may provide additional information.\n",
  733. err, strerror(err));
  734. die("No CONFIG_PERF_EVENTS=y kernel support configured?\n");
  735. exit(-1);
  736. }
  737. }
  738. if (perf_evlist__mmap(evlist, mmap_pages, false) < 0)
  739. die("failed to mmap with %d (%s)\n", errno, strerror(errno));
  740. }
  741. static int __cmd_top(void)
  742. {
  743. pthread_t thread;
  744. int ret __used;
  745. /*
  746. * FIXME: perf_session__new should allow passing a O_MMAP, so that all this
  747. * mmap reading, etc is encapsulated in it. Use O_WRONLY for now.
  748. */
  749. struct perf_session *session = perf_session__new(NULL, O_WRONLY, false, false, NULL);
  750. if (session == NULL)
  751. return -ENOMEM;
  752. if (top.target_tid != -1)
  753. perf_event__synthesize_thread_map(top.evlist->threads,
  754. perf_event__process, session);
  755. else
  756. perf_event__synthesize_threads(perf_event__process, session);
  757. start_counters(top.evlist);
  758. session->evlist = top.evlist;
  759. perf_session__update_sample_type(session);
  760. /* Wait for a minimal set of events before starting the snapshot */
  761. poll(top.evlist->pollfd, top.evlist->nr_fds, 100);
  762. perf_session__mmap_read(session);
  763. if (pthread_create(&thread, NULL, (use_browser > 0 ? display_thread_tui :
  764. display_thread), session)) {
  765. printf("Could not create display thread.\n");
  766. exit(-1);
  767. }
  768. if (realtime_prio) {
  769. struct sched_param param;
  770. param.sched_priority = realtime_prio;
  771. if (sched_setscheduler(0, SCHED_FIFO, &param)) {
  772. printf("Could not set realtime priority.\n");
  773. exit(-1);
  774. }
  775. }
  776. while (1) {
  777. u64 hits = top.samples;
  778. perf_session__mmap_read(session);
  779. if (hits == top.samples)
  780. ret = poll(top.evlist->pollfd, top.evlist->nr_fds, 100);
  781. }
  782. return 0;
  783. }
  784. static const char * const top_usage[] = {
  785. "perf top [<options>]",
  786. NULL
  787. };
  788. static const struct option options[] = {
  789. OPT_CALLBACK('e', "event", &top.evlist, "event",
  790. "event selector. use 'perf list' to list available events",
  791. parse_events),
  792. OPT_INTEGER('c', "count", &default_interval,
  793. "event period to sample"),
  794. OPT_INTEGER('p', "pid", &top.target_pid,
  795. "profile events on existing process id"),
  796. OPT_INTEGER('t', "tid", &top.target_tid,
  797. "profile events on existing thread id"),
  798. OPT_BOOLEAN('a', "all-cpus", &system_wide,
  799. "system-wide collection from all CPUs"),
  800. OPT_STRING('C', "cpu", &top.cpu_list, "cpu",
  801. "list of cpus to monitor"),
  802. OPT_STRING('k', "vmlinux", &symbol_conf.vmlinux_name,
  803. "file", "vmlinux pathname"),
  804. OPT_BOOLEAN('K', "hide_kernel_symbols", &top.hide_kernel_symbols,
  805. "hide kernel symbols"),
  806. OPT_UINTEGER('m', "mmap-pages", &mmap_pages, "number of mmap data pages"),
  807. OPT_INTEGER('r', "realtime", &realtime_prio,
  808. "collect data with this RT SCHED_FIFO priority"),
  809. OPT_INTEGER('d', "delay", &top.delay_secs,
  810. "number of seconds to delay between refreshes"),
  811. OPT_BOOLEAN('D', "dump-symtab", &dump_symtab,
  812. "dump the symbol table used for profiling"),
  813. OPT_INTEGER('f', "count-filter", &top.count_filter,
  814. "only display functions with more events than this"),
  815. OPT_BOOLEAN('g', "group", &group,
  816. "put the counters into a counter group"),
  817. OPT_BOOLEAN('i', "inherit", &inherit,
  818. "child tasks inherit counters"),
  819. OPT_STRING('s', "sym-annotate", &sym_filter, "symbol name",
  820. "symbol to annotate"),
  821. OPT_BOOLEAN('z', "zero", &top.zero,
  822. "zero history across updates"),
  823. OPT_INTEGER('F', "freq", &top.freq,
  824. "profile at this frequency"),
  825. OPT_INTEGER('E', "entries", &top.print_entries,
  826. "display this many functions"),
  827. OPT_BOOLEAN('U', "hide_user_symbols", &top.hide_user_symbols,
  828. "hide user symbols"),
  829. OPT_BOOLEAN(0, "tui", &use_tui, "Use the TUI interface"),
  830. OPT_BOOLEAN(0, "stdio", &use_stdio, "Use the stdio interface"),
  831. OPT_INCR('v', "verbose", &verbose,
  832. "be more verbose (show counter open errors, etc)"),
  833. OPT_END()
  834. };
  835. int cmd_top(int argc, const char **argv, const char *prefix __used)
  836. {
  837. struct perf_evsel *pos;
  838. int status = -ENOMEM;
  839. top.evlist = perf_evlist__new(NULL, NULL);
  840. if (top.evlist == NULL)
  841. return -ENOMEM;
  842. page_size = sysconf(_SC_PAGE_SIZE);
  843. argc = parse_options(argc, argv, options, top_usage, 0);
  844. if (argc)
  845. usage_with_options(top_usage, options);
  846. /*
  847. * XXX For now start disabled, only using TUI if explicitely asked for.
  848. * Change that when handle_keys equivalent gets written, live annotation
  849. * done, etc.
  850. */
  851. use_browser = 0;
  852. if (use_stdio)
  853. use_browser = 0;
  854. else if (use_tui)
  855. use_browser = 1;
  856. setup_browser(false);
  857. /* CPU and PID are mutually exclusive */
  858. if (top.target_tid > 0 && top.cpu_list) {
  859. printf("WARNING: PID switch overriding CPU\n");
  860. sleep(1);
  861. top.cpu_list = NULL;
  862. }
  863. if (top.target_pid != -1)
  864. top.target_tid = top.target_pid;
  865. if (perf_evlist__create_maps(top.evlist, top.target_pid,
  866. top.target_tid, top.cpu_list) < 0)
  867. usage_with_options(top_usage, options);
  868. if (!top.evlist->nr_entries &&
  869. perf_evlist__add_default(top.evlist) < 0) {
  870. pr_err("Not enough memory for event selector list\n");
  871. return -ENOMEM;
  872. }
  873. if (top.delay_secs < 1)
  874. top.delay_secs = 1;
  875. /*
  876. * User specified count overrides default frequency.
  877. */
  878. if (default_interval)
  879. top.freq = 0;
  880. else if (top.freq) {
  881. default_interval = top.freq;
  882. } else {
  883. fprintf(stderr, "frequency and count are zero, aborting\n");
  884. exit(EXIT_FAILURE);
  885. }
  886. list_for_each_entry(pos, &top.evlist->entries, node) {
  887. if (perf_evsel__alloc_fd(pos, top.evlist->cpus->nr,
  888. top.evlist->threads->nr) < 0)
  889. goto out_free_fd;
  890. /*
  891. * Fill in the ones not specifically initialized via -c:
  892. */
  893. if (pos->attr.sample_period)
  894. continue;
  895. pos->attr.sample_period = default_interval;
  896. }
  897. if (perf_evlist__alloc_pollfd(top.evlist) < 0 ||
  898. perf_evlist__alloc_mmap(top.evlist) < 0)
  899. goto out_free_fd;
  900. top.sym_evsel = list_entry(top.evlist->entries.next, struct perf_evsel, node);
  901. symbol_conf.priv_size = (sizeof(struct sym_entry) + sizeof(struct annotation) +
  902. (top.evlist->nr_entries + 1) * sizeof(unsigned long));
  903. symbol_conf.try_vmlinux_path = (symbol_conf.vmlinux_name == NULL);
  904. if (symbol__init() < 0)
  905. return -1;
  906. get_term_dimensions(&winsize);
  907. if (top.print_entries == 0) {
  908. update_print_entries(&winsize);
  909. signal(SIGWINCH, sig_winch_handler);
  910. }
  911. status = __cmd_top();
  912. out_free_fd:
  913. perf_evlist__delete(top.evlist);
  914. return status;
  915. }