builtin-top.c 26 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076
  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. ui__warning("The %s file can't be used\n",
  623. symbol_conf.vmlinux_name);
  624. exit_browser(0);
  625. exit(1);
  626. }
  627. return;
  628. }
  629. /* let's see, whether we need to install initial sym_filter_entry */
  630. if (sym_filter_entry_sched) {
  631. top.sym_filter_entry = sym_filter_entry_sched;
  632. sym_filter_entry_sched = NULL;
  633. if (parse_source(top.sym_filter_entry) < 0) {
  634. struct symbol *sym = sym_entry__symbol(top.sym_filter_entry);
  635. pr_err("Can't annotate %s", sym->name);
  636. if (top.sym_filter_entry->map->dso->origin == DSO__ORIG_KERNEL) {
  637. pr_err(": No vmlinux file was found in the path:\n");
  638. machine__fprintf_vmlinux_path(machine, stderr);
  639. } else
  640. pr_err(".\n");
  641. exit(1);
  642. }
  643. }
  644. syme = symbol__priv(al.sym);
  645. if (!syme->skip) {
  646. struct perf_evsel *evsel;
  647. syme->origin = origin;
  648. evsel = perf_evlist__id2evsel(top.evlist, sample->id);
  649. assert(evsel != NULL);
  650. syme->count[evsel->idx]++;
  651. record_precise_ip(syme, evsel->idx, ip);
  652. pthread_mutex_lock(&top.active_symbols_lock);
  653. if (list_empty(&syme->node) || !syme->node.next)
  654. __list_insert_active_sym(syme);
  655. pthread_mutex_unlock(&top.active_symbols_lock);
  656. }
  657. }
  658. static void perf_session__mmap_read_cpu(struct perf_session *self, int cpu)
  659. {
  660. struct perf_sample sample;
  661. union perf_event *event;
  662. while ((event = perf_evlist__read_on_cpu(top.evlist, cpu)) != NULL) {
  663. perf_session__parse_sample(self, event, &sample);
  664. if (event->header.type == PERF_RECORD_SAMPLE)
  665. perf_event__process_sample(event, &sample, self);
  666. else
  667. perf_event__process(event, &sample, self);
  668. }
  669. }
  670. static void perf_session__mmap_read(struct perf_session *self)
  671. {
  672. int i;
  673. for (i = 0; i < top.evlist->cpus->nr; i++)
  674. perf_session__mmap_read_cpu(self, i);
  675. }
  676. static void start_counters(struct perf_evlist *evlist)
  677. {
  678. struct perf_evsel *counter;
  679. list_for_each_entry(counter, &evlist->entries, node) {
  680. struct perf_event_attr *attr = &counter->attr;
  681. attr->sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_TID;
  682. if (top.freq) {
  683. attr->sample_type |= PERF_SAMPLE_PERIOD;
  684. attr->freq = 1;
  685. attr->sample_freq = top.freq;
  686. }
  687. if (evlist->nr_entries > 1) {
  688. attr->sample_type |= PERF_SAMPLE_ID;
  689. attr->read_format |= PERF_FORMAT_ID;
  690. }
  691. attr->mmap = 1;
  692. try_again:
  693. if (perf_evsel__open(counter, top.evlist->cpus,
  694. top.evlist->threads, group, inherit) < 0) {
  695. int err = errno;
  696. if (err == EPERM || err == EACCES)
  697. die("Permission error - are you root?\n"
  698. "\t Consider tweaking"
  699. " /proc/sys/kernel/perf_event_paranoid.\n");
  700. /*
  701. * If it's cycles then fall back to hrtimer
  702. * based cpu-clock-tick sw counter, which
  703. * is always available even if no PMU support:
  704. */
  705. if (attr->type == PERF_TYPE_HARDWARE &&
  706. attr->config == PERF_COUNT_HW_CPU_CYCLES) {
  707. if (verbose)
  708. warning(" ... trying to fall back to cpu-clock-ticks\n");
  709. attr->type = PERF_TYPE_SOFTWARE;
  710. attr->config = PERF_COUNT_SW_CPU_CLOCK;
  711. goto try_again;
  712. }
  713. printf("\n");
  714. error("sys_perf_event_open() syscall returned with %d "
  715. "(%s). /bin/dmesg may provide additional information.\n",
  716. err, strerror(err));
  717. die("No CONFIG_PERF_EVENTS=y kernel support configured?\n");
  718. exit(-1);
  719. }
  720. }
  721. if (perf_evlist__mmap(evlist, mmap_pages, false) < 0)
  722. die("failed to mmap with %d (%s)\n", errno, strerror(errno));
  723. }
  724. static int __cmd_top(void)
  725. {
  726. pthread_t thread;
  727. struct perf_evsel *first;
  728. int ret __used;
  729. /*
  730. * FIXME: perf_session__new should allow passing a O_MMAP, so that all this
  731. * mmap reading, etc is encapsulated in it. Use O_WRONLY for now.
  732. */
  733. struct perf_session *session = perf_session__new(NULL, O_WRONLY, false, false, NULL);
  734. if (session == NULL)
  735. return -ENOMEM;
  736. if (top.target_tid != -1)
  737. perf_event__synthesize_thread_map(top.evlist->threads,
  738. perf_event__process, session);
  739. else
  740. perf_event__synthesize_threads(perf_event__process, session);
  741. start_counters(top.evlist);
  742. first = list_entry(top.evlist->entries.next, struct perf_evsel, node);
  743. perf_session__set_sample_type(session, first->attr.sample_type);
  744. /* Wait for a minimal set of events before starting the snapshot */
  745. poll(top.evlist->pollfd, top.evlist->nr_fds, 100);
  746. perf_session__mmap_read(session);
  747. if (pthread_create(&thread, NULL, (use_browser > 0 ? display_thread_tui :
  748. display_thread), session)) {
  749. printf("Could not create display thread.\n");
  750. exit(-1);
  751. }
  752. if (realtime_prio) {
  753. struct sched_param param;
  754. param.sched_priority = realtime_prio;
  755. if (sched_setscheduler(0, SCHED_FIFO, &param)) {
  756. printf("Could not set realtime priority.\n");
  757. exit(-1);
  758. }
  759. }
  760. while (1) {
  761. u64 hits = top.samples;
  762. perf_session__mmap_read(session);
  763. if (hits == top.samples)
  764. ret = poll(top.evlist->pollfd, top.evlist->nr_fds, 100);
  765. }
  766. return 0;
  767. }
  768. static const char * const top_usage[] = {
  769. "perf top [<options>]",
  770. NULL
  771. };
  772. static const struct option options[] = {
  773. OPT_CALLBACK('e', "event", &top.evlist, "event",
  774. "event selector. use 'perf list' to list available events",
  775. parse_events),
  776. OPT_INTEGER('c', "count", &default_interval,
  777. "event period to sample"),
  778. OPT_INTEGER('p', "pid", &top.target_pid,
  779. "profile events on existing process id"),
  780. OPT_INTEGER('t', "tid", &top.target_tid,
  781. "profile events on existing thread id"),
  782. OPT_BOOLEAN('a', "all-cpus", &system_wide,
  783. "system-wide collection from all CPUs"),
  784. OPT_STRING('C', "cpu", &top.cpu_list, "cpu",
  785. "list of cpus to monitor"),
  786. OPT_STRING('k', "vmlinux", &symbol_conf.vmlinux_name,
  787. "file", "vmlinux pathname"),
  788. OPT_BOOLEAN('K', "hide_kernel_symbols", &top.hide_kernel_symbols,
  789. "hide kernel symbols"),
  790. OPT_UINTEGER('m', "mmap-pages", &mmap_pages, "number of mmap data pages"),
  791. OPT_INTEGER('r', "realtime", &realtime_prio,
  792. "collect data with this RT SCHED_FIFO priority"),
  793. OPT_INTEGER('d', "delay", &top.delay_secs,
  794. "number of seconds to delay between refreshes"),
  795. OPT_BOOLEAN('D', "dump-symtab", &dump_symtab,
  796. "dump the symbol table used for profiling"),
  797. OPT_INTEGER('f', "count-filter", &top.count_filter,
  798. "only display functions with more events than this"),
  799. OPT_BOOLEAN('g', "group", &group,
  800. "put the counters into a counter group"),
  801. OPT_BOOLEAN('i', "inherit", &inherit,
  802. "child tasks inherit counters"),
  803. OPT_STRING('s', "sym-annotate", &sym_filter, "symbol name",
  804. "symbol to annotate"),
  805. OPT_BOOLEAN('z', "zero", &top.zero,
  806. "zero history across updates"),
  807. OPT_INTEGER('F', "freq", &top.freq,
  808. "profile at this frequency"),
  809. OPT_INTEGER('E', "entries", &top.print_entries,
  810. "display this many functions"),
  811. OPT_BOOLEAN('U', "hide_user_symbols", &top.hide_user_symbols,
  812. "hide user symbols"),
  813. OPT_BOOLEAN(0, "tui", &use_tui, "Use the TUI interface"),
  814. OPT_BOOLEAN(0, "stdio", &use_stdio, "Use the stdio interface"),
  815. OPT_INCR('v', "verbose", &verbose,
  816. "be more verbose (show counter open errors, etc)"),
  817. OPT_END()
  818. };
  819. int cmd_top(int argc, const char **argv, const char *prefix __used)
  820. {
  821. struct perf_evsel *pos;
  822. int status = -ENOMEM;
  823. top.evlist = perf_evlist__new(NULL, NULL);
  824. if (top.evlist == NULL)
  825. return -ENOMEM;
  826. page_size = sysconf(_SC_PAGE_SIZE);
  827. argc = parse_options(argc, argv, options, top_usage, 0);
  828. if (argc)
  829. usage_with_options(top_usage, options);
  830. /*
  831. * XXX For now start disabled, only using TUI if explicitely asked for.
  832. * Change that when handle_keys equivalent gets written, live annotation
  833. * done, etc.
  834. */
  835. use_browser = 0;
  836. if (use_stdio)
  837. use_browser = 0;
  838. else if (use_tui)
  839. use_browser = 1;
  840. setup_browser(false);
  841. /* CPU and PID are mutually exclusive */
  842. if (top.target_tid > 0 && top.cpu_list) {
  843. printf("WARNING: PID switch overriding CPU\n");
  844. sleep(1);
  845. top.cpu_list = NULL;
  846. }
  847. if (top.target_pid != -1)
  848. top.target_tid = top.target_pid;
  849. if (perf_evlist__create_maps(top.evlist, top.target_pid,
  850. top.target_tid, top.cpu_list) < 0)
  851. usage_with_options(top_usage, options);
  852. if (!top.evlist->nr_entries &&
  853. perf_evlist__add_default(top.evlist) < 0) {
  854. pr_err("Not enough memory for event selector list\n");
  855. return -ENOMEM;
  856. }
  857. if (top.delay_secs < 1)
  858. top.delay_secs = 1;
  859. /*
  860. * User specified count overrides default frequency.
  861. */
  862. if (default_interval)
  863. top.freq = 0;
  864. else if (top.freq) {
  865. default_interval = top.freq;
  866. } else {
  867. fprintf(stderr, "frequency and count are zero, aborting\n");
  868. exit(EXIT_FAILURE);
  869. }
  870. list_for_each_entry(pos, &top.evlist->entries, node) {
  871. if (perf_evsel__alloc_fd(pos, top.evlist->cpus->nr,
  872. top.evlist->threads->nr) < 0)
  873. goto out_free_fd;
  874. /*
  875. * Fill in the ones not specifically initialized via -c:
  876. */
  877. if (pos->attr.sample_period)
  878. continue;
  879. pos->attr.sample_period = default_interval;
  880. }
  881. if (perf_evlist__alloc_pollfd(top.evlist) < 0 ||
  882. perf_evlist__alloc_mmap(top.evlist) < 0)
  883. goto out_free_fd;
  884. top.sym_evsel = list_entry(top.evlist->entries.next, struct perf_evsel, node);
  885. symbol_conf.priv_size = (sizeof(struct sym_entry) + sizeof(struct annotation) +
  886. (top.evlist->nr_entries + 1) * sizeof(unsigned long));
  887. symbol_conf.try_vmlinux_path = (symbol_conf.vmlinux_name == NULL);
  888. if (symbol__init() < 0)
  889. return -1;
  890. get_term_dimensions(&winsize);
  891. if (top.print_entries == 0) {
  892. update_print_entries(&winsize);
  893. signal(SIGWINCH, sig_winch_handler);
  894. }
  895. status = __cmd_top();
  896. out_free_fd:
  897. perf_evlist__delete(top.evlist);
  898. return status;
  899. }