builtin-top.c 26 KB

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