builtin-top.c 28 KB

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