builtin-top.c 27 KB

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