builtin-top.c 26 KB

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